xref: /openbmc/linux/fs/btrfs/ctree.c (revision d16c702fe4f274bd77b47d3ab737eadcf24e0b93)
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,
2014d75f8a9SDavid Sterba 			&disk_key, level, buf->start, 0);
2025d4f98a2SYan Zheng 	if (IS_ERR(cow))
203be20aa9dSChris Mason 		return PTR_ERR(cow);
204be20aa9dSChris Mason 
20558e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
206be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
207be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2085d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2095d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2105d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2115d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2125d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2135d4f98a2SYan Zheng 	else
214be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
215be20aa9dSChris Mason 
216de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2172b82032cSYan Zheng 
218be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2195d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
220e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2215d4f98a2SYan Zheng 	else
222e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
2234aec2b52SChris Mason 
224be20aa9dSChris Mason 	if (ret)
225be20aa9dSChris Mason 		return ret;
226be20aa9dSChris Mason 
227be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
228be20aa9dSChris Mason 	*cow_ret = cow;
229be20aa9dSChris Mason 	return 0;
230be20aa9dSChris Mason }
231be20aa9dSChris Mason 
232bd989ba3SJan Schmidt enum mod_log_op {
233bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
234bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
235bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
236bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
237bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
238bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
239bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
240bd989ba3SJan Schmidt };
241bd989ba3SJan Schmidt 
242bd989ba3SJan Schmidt struct tree_mod_root {
243bd989ba3SJan Schmidt 	u64 logical;
244bd989ba3SJan Schmidt 	u8 level;
245bd989ba3SJan Schmidt };
246bd989ba3SJan Schmidt 
247bd989ba3SJan Schmidt struct tree_mod_elem {
248bd989ba3SJan Schmidt 	struct rb_node node;
249298cfd36SChandan Rajendra 	u64 logical;
250097b8a7cSJan Schmidt 	u64 seq;
251bd989ba3SJan Schmidt 	enum mod_log_op op;
252bd989ba3SJan Schmidt 
253bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
254bd989ba3SJan Schmidt 	int slot;
255bd989ba3SJan Schmidt 
256bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
257bd989ba3SJan Schmidt 	u64 generation;
258bd989ba3SJan Schmidt 
259bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
260bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
261bd989ba3SJan Schmidt 	u64 blockptr;
262bd989ba3SJan Schmidt 
263bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
264b6dfa35bSDavid Sterba 	struct {
265b6dfa35bSDavid Sterba 		int dst_slot;
266b6dfa35bSDavid Sterba 		int nr_items;
267b6dfa35bSDavid Sterba 	} move;
268bd989ba3SJan Schmidt 
269bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
270bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
271bd989ba3SJan Schmidt };
272bd989ba3SJan Schmidt 
273097b8a7cSJan Schmidt /*
274fcebe456SJosef Bacik  * Pull a new tree mod seq number for our operation.
275fc36ed7eSJan Schmidt  */
276fcebe456SJosef Bacik static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
277fc36ed7eSJan Schmidt {
278fc36ed7eSJan Schmidt 	return atomic64_inc_return(&fs_info->tree_mod_seq);
279fc36ed7eSJan Schmidt }
280fc36ed7eSJan Schmidt 
281fc36ed7eSJan Schmidt /*
282097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
283097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
284097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
285097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
286097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
287097b8a7cSJan Schmidt  * blocker was added.
288097b8a7cSJan Schmidt  */
289097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
290bd989ba3SJan Schmidt 			   struct seq_list *elem)
291bd989ba3SJan Schmidt {
292b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
293097b8a7cSJan Schmidt 	if (!elem->seq) {
294fcebe456SJosef Bacik 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
295097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
296097b8a7cSJan Schmidt 	}
297b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
298097b8a7cSJan Schmidt 
299fcebe456SJosef Bacik 	return elem->seq;
300bd989ba3SJan Schmidt }
301bd989ba3SJan Schmidt 
302bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
303bd989ba3SJan Schmidt 			    struct seq_list *elem)
304bd989ba3SJan Schmidt {
305bd989ba3SJan Schmidt 	struct rb_root *tm_root;
306bd989ba3SJan Schmidt 	struct rb_node *node;
307bd989ba3SJan Schmidt 	struct rb_node *next;
308bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
309bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
310bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
311bd989ba3SJan Schmidt 
312bd989ba3SJan Schmidt 	if (!seq_putting)
313bd989ba3SJan Schmidt 		return;
314bd989ba3SJan Schmidt 
3157227ff4dSFilipe Manana 	write_lock(&fs_info->tree_mod_log_lock);
316bd989ba3SJan Schmidt 	list_del(&elem->list);
317097b8a7cSJan Schmidt 	elem->seq = 0;
318bd989ba3SJan Schmidt 
31942836cf4SFilipe Manana 	if (!list_empty(&fs_info->tree_mod_seq_list)) {
32042836cf4SFilipe Manana 		struct seq_list *first;
32142836cf4SFilipe Manana 
32242836cf4SFilipe Manana 		first = list_first_entry(&fs_info->tree_mod_seq_list,
32342836cf4SFilipe Manana 					 struct seq_list, list);
32442836cf4SFilipe Manana 		if (seq_putting > first->seq) {
325bd989ba3SJan Schmidt 			/*
32642836cf4SFilipe Manana 			 * Blocker with lower sequence number exists, we
32742836cf4SFilipe Manana 			 * cannot remove anything from the log.
328bd989ba3SJan Schmidt 			 */
3297227ff4dSFilipe Manana 			write_unlock(&fs_info->tree_mod_log_lock);
330097b8a7cSJan Schmidt 			return;
331bd989ba3SJan Schmidt 		}
33242836cf4SFilipe Manana 		min_seq = first->seq;
333bd989ba3SJan Schmidt 	}
334097b8a7cSJan Schmidt 
335097b8a7cSJan Schmidt 	/*
336bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
337bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
338bd989ba3SJan Schmidt 	 */
339bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
340bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
341bd989ba3SJan Schmidt 		next = rb_next(node);
3426b4df8b6SGeliang Tang 		tm = rb_entry(node, struct tree_mod_elem, node);
3436609fee8SFilipe Manana 		if (tm->seq >= min_seq)
344bd989ba3SJan Schmidt 			continue;
345bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
346bd989ba3SJan Schmidt 		kfree(tm);
347bd989ba3SJan Schmidt 	}
348b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
349bd989ba3SJan Schmidt }
350bd989ba3SJan Schmidt 
351bd989ba3SJan Schmidt /*
352bd989ba3SJan Schmidt  * key order of the log:
353298cfd36SChandan Rajendra  *       node/leaf start address -> sequence
354bd989ba3SJan Schmidt  *
355298cfd36SChandan Rajendra  * The 'start address' is the logical address of the *new* root node
356298cfd36SChandan Rajendra  * for root replace operations, or the logical address of the affected
357298cfd36SChandan Rajendra  * block for all other operations.
358bd989ba3SJan Schmidt  */
359bd989ba3SJan Schmidt static noinline int
360bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
361bd989ba3SJan Schmidt {
362bd989ba3SJan Schmidt 	struct rb_root *tm_root;
363bd989ba3SJan Schmidt 	struct rb_node **new;
364bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
365bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
366bd989ba3SJan Schmidt 
36773e82fe4SDavid Sterba 	lockdep_assert_held_write(&fs_info->tree_mod_log_lock);
36873e82fe4SDavid Sterba 
369fcebe456SJosef Bacik 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
370bd989ba3SJan Schmidt 
371bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
372bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
373bd989ba3SJan Schmidt 	while (*new) {
3746b4df8b6SGeliang Tang 		cur = rb_entry(*new, struct tree_mod_elem, node);
375bd989ba3SJan Schmidt 		parent = *new;
376298cfd36SChandan Rajendra 		if (cur->logical < tm->logical)
377bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
378298cfd36SChandan Rajendra 		else if (cur->logical > tm->logical)
379bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
380097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
381bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
382097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
383bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
3845de865eeSFilipe David Borba Manana 		else
3855de865eeSFilipe David Borba Manana 			return -EEXIST;
386bd989ba3SJan Schmidt 	}
387bd989ba3SJan Schmidt 
388bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
389bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
3905de865eeSFilipe David Borba Manana 	return 0;
391bd989ba3SJan Schmidt }
392bd989ba3SJan Schmidt 
393097b8a7cSJan Schmidt /*
394097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
395097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
396097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
397b1a09f1eSDavid Sterba  * write unlock fs_info::tree_mod_log_lock.
398097b8a7cSJan Schmidt  */
399e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
400e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
401e9b7fd4dSJan Schmidt 	smp_mb();
402e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
403e9b7fd4dSJan Schmidt 		return 1;
404097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
405e9b7fd4dSJan Schmidt 		return 1;
4065de865eeSFilipe David Borba Manana 
407b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
4085de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list)) {
409b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
4105de865eeSFilipe David Borba Manana 		return 1;
4115de865eeSFilipe David Borba Manana 	}
4125de865eeSFilipe David Borba Manana 
413e9b7fd4dSJan Schmidt 	return 0;
414e9b7fd4dSJan Schmidt }
415e9b7fd4dSJan Schmidt 
4165de865eeSFilipe David Borba Manana /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
4175de865eeSFilipe David Borba Manana static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
4185de865eeSFilipe David Borba Manana 				    struct extent_buffer *eb)
4195de865eeSFilipe David Borba Manana {
4205de865eeSFilipe David Borba Manana 	smp_mb();
4215de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list))
4225de865eeSFilipe David Borba Manana 		return 0;
4235de865eeSFilipe David Borba Manana 	if (eb && btrfs_header_level(eb) == 0)
4245de865eeSFilipe David Borba Manana 		return 0;
4255de865eeSFilipe David Borba Manana 
4265de865eeSFilipe David Borba Manana 	return 1;
4275de865eeSFilipe David Borba Manana }
4285de865eeSFilipe David Borba Manana 
4295de865eeSFilipe David Borba Manana static struct tree_mod_elem *
4305de865eeSFilipe David Borba Manana alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
431bd989ba3SJan Schmidt 		    enum mod_log_op op, gfp_t flags)
432bd989ba3SJan Schmidt {
433097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
434bd989ba3SJan Schmidt 
435c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
436c8cc6341SJosef Bacik 	if (!tm)
4375de865eeSFilipe David Borba Manana 		return NULL;
438bd989ba3SJan Schmidt 
439298cfd36SChandan Rajendra 	tm->logical = eb->start;
440bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
441bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
442bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
443bd989ba3SJan Schmidt 	}
444bd989ba3SJan Schmidt 	tm->op = op;
445bd989ba3SJan Schmidt 	tm->slot = slot;
446bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
4475de865eeSFilipe David Borba Manana 	RB_CLEAR_NODE(&tm->node);
448bd989ba3SJan Schmidt 
4495de865eeSFilipe David Borba Manana 	return tm;
450097b8a7cSJan Schmidt }
451097b8a7cSJan Schmidt 
452e09c2efeSDavid Sterba static noinline int tree_mod_log_insert_key(struct extent_buffer *eb, int slot,
453097b8a7cSJan Schmidt 		enum mod_log_op op, gfp_t flags)
454097b8a7cSJan Schmidt {
4555de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm;
4565de865eeSFilipe David Borba Manana 	int ret;
4575de865eeSFilipe David Borba Manana 
458e09c2efeSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
459097b8a7cSJan Schmidt 		return 0;
460097b8a7cSJan Schmidt 
4615de865eeSFilipe David Borba Manana 	tm = alloc_tree_mod_elem(eb, slot, op, flags);
4625de865eeSFilipe David Borba Manana 	if (!tm)
4635de865eeSFilipe David Borba Manana 		return -ENOMEM;
4645de865eeSFilipe David Borba Manana 
465e09c2efeSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb)) {
4665de865eeSFilipe David Borba Manana 		kfree(tm);
4675de865eeSFilipe David Borba Manana 		return 0;
4685de865eeSFilipe David Borba Manana 	}
4695de865eeSFilipe David Borba Manana 
470e09c2efeSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
471b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
4725de865eeSFilipe David Borba Manana 	if (ret)
4735de865eeSFilipe David Borba Manana 		kfree(tm);
4745de865eeSFilipe David Borba Manana 
4755de865eeSFilipe David Borba Manana 	return ret;
476097b8a7cSJan Schmidt }
477097b8a7cSJan Schmidt 
4786074d45fSDavid Sterba static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
4796074d45fSDavid Sterba 		int dst_slot, int src_slot, int nr_items)
480bd989ba3SJan Schmidt {
4815de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
4825de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
4835de865eeSFilipe David Borba Manana 	int ret = 0;
484bd989ba3SJan Schmidt 	int i;
4855de865eeSFilipe David Borba Manana 	int locked = 0;
486bd989ba3SJan Schmidt 
4876074d45fSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
488f395694cSJan Schmidt 		return 0;
489bd989ba3SJan Schmidt 
490176ef8f5SDavid Sterba 	tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
4915de865eeSFilipe David Borba Manana 	if (!tm_list)
4925de865eeSFilipe David Borba Manana 		return -ENOMEM;
493bd989ba3SJan Schmidt 
494176ef8f5SDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
4955de865eeSFilipe David Borba Manana 	if (!tm) {
4965de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
4975de865eeSFilipe David Borba Manana 		goto free_tms;
4985de865eeSFilipe David Borba Manana 	}
499f395694cSJan Schmidt 
500298cfd36SChandan Rajendra 	tm->logical = eb->start;
501bd989ba3SJan Schmidt 	tm->slot = src_slot;
502bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
503bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
504bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
505bd989ba3SJan Schmidt 
5065de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5075de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
508176ef8f5SDavid Sterba 		    MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
5095de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
5105de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
5115de865eeSFilipe David Borba Manana 			goto free_tms;
5125de865eeSFilipe David Borba Manana 		}
513bd989ba3SJan Schmidt 	}
514bd989ba3SJan Schmidt 
5156074d45fSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
5165de865eeSFilipe David Borba Manana 		goto free_tms;
5175de865eeSFilipe David Borba Manana 	locked = 1;
5185de865eeSFilipe David Borba Manana 
5195de865eeSFilipe David Borba Manana 	/*
5205de865eeSFilipe David Borba Manana 	 * When we override something during the move, we log these removals.
5215de865eeSFilipe David Borba Manana 	 * This can only happen when we move towards the beginning of the
5225de865eeSFilipe David Borba Manana 	 * buffer, i.e. dst_slot < src_slot.
5235de865eeSFilipe David Borba Manana 	 */
5245de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5256074d45fSDavid Sterba 		ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
5265de865eeSFilipe David Borba Manana 		if (ret)
5275de865eeSFilipe David Borba Manana 			goto free_tms;
5285de865eeSFilipe David Borba Manana 	}
5295de865eeSFilipe David Borba Manana 
5306074d45fSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
5315de865eeSFilipe David Borba Manana 	if (ret)
5325de865eeSFilipe David Borba Manana 		goto free_tms;
533b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
5345de865eeSFilipe David Borba Manana 	kfree(tm_list);
5355de865eeSFilipe David Borba Manana 
5365de865eeSFilipe David Borba Manana 	return 0;
5375de865eeSFilipe David Borba Manana free_tms:
5385de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
5395de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
5406074d45fSDavid Sterba 			rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
5415de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
5425de865eeSFilipe David Borba Manana 	}
5435de865eeSFilipe David Borba Manana 	if (locked)
544b1a09f1eSDavid Sterba 		write_unlock(&eb->fs_info->tree_mod_log_lock);
5455de865eeSFilipe David Borba Manana 	kfree(tm_list);
5465de865eeSFilipe David Borba Manana 	kfree(tm);
5475de865eeSFilipe David Borba Manana 
5485de865eeSFilipe David Borba Manana 	return ret;
5495de865eeSFilipe David Borba Manana }
5505de865eeSFilipe David Borba Manana 
5515de865eeSFilipe David Borba Manana static inline int
5525de865eeSFilipe David Borba Manana __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
5535de865eeSFilipe David Borba Manana 		       struct tree_mod_elem **tm_list,
5545de865eeSFilipe David Borba Manana 		       int nritems)
555097b8a7cSJan Schmidt {
5565de865eeSFilipe David Borba Manana 	int i, j;
557097b8a7cSJan Schmidt 	int ret;
558097b8a7cSJan Schmidt 
559097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
5605de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list[i]);
5615de865eeSFilipe David Borba Manana 		if (ret) {
5625de865eeSFilipe David Borba Manana 			for (j = nritems - 1; j > i; j--)
5635de865eeSFilipe David Borba Manana 				rb_erase(&tm_list[j]->node,
5645de865eeSFilipe David Borba Manana 					 &fs_info->tree_mod_log);
5655de865eeSFilipe David Borba Manana 			return ret;
566097b8a7cSJan Schmidt 		}
567097b8a7cSJan Schmidt 	}
568097b8a7cSJan Schmidt 
5695de865eeSFilipe David Borba Manana 	return 0;
5705de865eeSFilipe David Borba Manana }
5715de865eeSFilipe David Borba Manana 
57295b757c1SDavid Sterba static noinline int tree_mod_log_insert_root(struct extent_buffer *old_root,
57395b757c1SDavid Sterba 			 struct extent_buffer *new_root, int log_removal)
574bd989ba3SJan Schmidt {
57595b757c1SDavid Sterba 	struct btrfs_fs_info *fs_info = old_root->fs_info;
5765de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
5775de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
5785de865eeSFilipe David Borba Manana 	int nritems = 0;
5795de865eeSFilipe David Borba Manana 	int ret = 0;
5805de865eeSFilipe David Borba Manana 	int i;
581bd989ba3SJan Schmidt 
5825de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
583097b8a7cSJan Schmidt 		return 0;
584097b8a7cSJan Schmidt 
5855de865eeSFilipe David Borba Manana 	if (log_removal && btrfs_header_level(old_root) > 0) {
5865de865eeSFilipe David Borba Manana 		nritems = btrfs_header_nritems(old_root);
58731e818feSDavid Sterba 		tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
588bcc8e07fSDavid Sterba 				  GFP_NOFS);
5895de865eeSFilipe David Borba Manana 		if (!tm_list) {
5905de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
5915de865eeSFilipe David Borba Manana 			goto free_tms;
5925de865eeSFilipe David Borba Manana 		}
5935de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++) {
5945de865eeSFilipe David Borba Manana 			tm_list[i] = alloc_tree_mod_elem(old_root, i,
595bcc8e07fSDavid Sterba 			    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
5965de865eeSFilipe David Borba Manana 			if (!tm_list[i]) {
5975de865eeSFilipe David Borba Manana 				ret = -ENOMEM;
5985de865eeSFilipe David Borba Manana 				goto free_tms;
5995de865eeSFilipe David Borba Manana 			}
6005de865eeSFilipe David Borba Manana 		}
6015de865eeSFilipe David Borba Manana 	}
602d9abbf1cSJan Schmidt 
603bcc8e07fSDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
6045de865eeSFilipe David Borba Manana 	if (!tm) {
6055de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
6065de865eeSFilipe David Borba Manana 		goto free_tms;
6075de865eeSFilipe David Borba Manana 	}
608bd989ba3SJan Schmidt 
609298cfd36SChandan Rajendra 	tm->logical = new_root->start;
610bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
611bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
612bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
613bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
614bd989ba3SJan Schmidt 
6155de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
6165de865eeSFilipe David Borba Manana 		goto free_tms;
6175de865eeSFilipe David Borba Manana 
6185de865eeSFilipe David Borba Manana 	if (tm_list)
6195de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
6205de865eeSFilipe David Borba Manana 	if (!ret)
6215de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm);
6225de865eeSFilipe David Borba Manana 
623b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
6245de865eeSFilipe David Borba Manana 	if (ret)
6255de865eeSFilipe David Borba Manana 		goto free_tms;
6265de865eeSFilipe David Borba Manana 	kfree(tm_list);
6275de865eeSFilipe David Borba Manana 
6285de865eeSFilipe David Borba Manana 	return ret;
6295de865eeSFilipe David Borba Manana 
6305de865eeSFilipe David Borba Manana free_tms:
6315de865eeSFilipe David Borba Manana 	if (tm_list) {
6325de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++)
6335de865eeSFilipe David Borba Manana 			kfree(tm_list[i]);
6345de865eeSFilipe David Borba Manana 		kfree(tm_list);
6355de865eeSFilipe David Borba Manana 	}
6365de865eeSFilipe David Borba Manana 	kfree(tm);
6375de865eeSFilipe David Borba Manana 
6385de865eeSFilipe David Borba Manana 	return ret;
639bd989ba3SJan Schmidt }
640bd989ba3SJan Schmidt 
641bd989ba3SJan Schmidt static struct tree_mod_elem *
642bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
643bd989ba3SJan Schmidt 		      int smallest)
644bd989ba3SJan Schmidt {
645bd989ba3SJan Schmidt 	struct rb_root *tm_root;
646bd989ba3SJan Schmidt 	struct rb_node *node;
647bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
648bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
649bd989ba3SJan Schmidt 
650b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
651bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
652bd989ba3SJan Schmidt 	node = tm_root->rb_node;
653bd989ba3SJan Schmidt 	while (node) {
6546b4df8b6SGeliang Tang 		cur = rb_entry(node, struct tree_mod_elem, node);
655298cfd36SChandan Rajendra 		if (cur->logical < start) {
656bd989ba3SJan Schmidt 			node = node->rb_left;
657298cfd36SChandan Rajendra 		} else if (cur->logical > start) {
658bd989ba3SJan Schmidt 			node = node->rb_right;
659097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
660bd989ba3SJan Schmidt 			node = node->rb_left;
661bd989ba3SJan Schmidt 		} else if (!smallest) {
662bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
663bd989ba3SJan Schmidt 			if (found)
664097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
665bd989ba3SJan Schmidt 			found = cur;
666bd989ba3SJan Schmidt 			node = node->rb_left;
667097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
668bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
669bd989ba3SJan Schmidt 			if (found)
670097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
671bd989ba3SJan Schmidt 			found = cur;
672bd989ba3SJan Schmidt 			node = node->rb_right;
673bd989ba3SJan Schmidt 		} else {
674bd989ba3SJan Schmidt 			found = cur;
675bd989ba3SJan Schmidt 			break;
676bd989ba3SJan Schmidt 		}
677bd989ba3SJan Schmidt 	}
678b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
679bd989ba3SJan Schmidt 
680bd989ba3SJan Schmidt 	return found;
681bd989ba3SJan Schmidt }
682bd989ba3SJan Schmidt 
683bd989ba3SJan Schmidt /*
684bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
685bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
686bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
687bd989ba3SJan Schmidt  */
688bd989ba3SJan Schmidt static struct tree_mod_elem *
689bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
690bd989ba3SJan Schmidt 			   u64 min_seq)
691bd989ba3SJan Schmidt {
692bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
693bd989ba3SJan Schmidt }
694bd989ba3SJan Schmidt 
695bd989ba3SJan Schmidt /*
696bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
697bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
698bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
699bd989ba3SJan Schmidt  */
700bd989ba3SJan Schmidt static struct tree_mod_elem *
701bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
702bd989ba3SJan Schmidt {
703bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
704bd989ba3SJan Schmidt }
705bd989ba3SJan Schmidt 
706ed874f0dSDavid Sterba static noinline int tree_mod_log_eb_copy(struct extent_buffer *dst,
707bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
70890f8d62eSJan Schmidt 		     unsigned long src_offset, int nr_items)
709bd989ba3SJan Schmidt {
710ed874f0dSDavid Sterba 	struct btrfs_fs_info *fs_info = dst->fs_info;
7115de865eeSFilipe David Borba Manana 	int ret = 0;
7125de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
7135de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list_add, **tm_list_rem;
714bd989ba3SJan Schmidt 	int i;
7155de865eeSFilipe David Borba Manana 	int locked = 0;
716bd989ba3SJan Schmidt 
7175de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
7185de865eeSFilipe David Borba Manana 		return 0;
719bd989ba3SJan Schmidt 
720c8cc6341SJosef Bacik 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
7215de865eeSFilipe David Borba Manana 		return 0;
7225de865eeSFilipe David Borba Manana 
72331e818feSDavid Sterba 	tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
7245de865eeSFilipe David Borba Manana 			  GFP_NOFS);
7255de865eeSFilipe David Borba Manana 	if (!tm_list)
7265de865eeSFilipe David Borba Manana 		return -ENOMEM;
7275de865eeSFilipe David Borba Manana 
7285de865eeSFilipe David Borba Manana 	tm_list_add = tm_list;
7295de865eeSFilipe David Borba Manana 	tm_list_rem = tm_list + nr_items;
7305de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
7315de865eeSFilipe David Borba Manana 		tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
7325de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE, GFP_NOFS);
7335de865eeSFilipe David Borba Manana 		if (!tm_list_rem[i]) {
7345de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7355de865eeSFilipe David Borba Manana 			goto free_tms;
7365de865eeSFilipe David Borba Manana 		}
7375de865eeSFilipe David Borba Manana 
7385de865eeSFilipe David Borba Manana 		tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
7395de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_ADD, GFP_NOFS);
7405de865eeSFilipe David Borba Manana 		if (!tm_list_add[i]) {
7415de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7425de865eeSFilipe David Borba Manana 			goto free_tms;
7435de865eeSFilipe David Borba Manana 		}
7445de865eeSFilipe David Borba Manana 	}
7455de865eeSFilipe David Borba Manana 
7465de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
7475de865eeSFilipe David Borba Manana 		goto free_tms;
7485de865eeSFilipe David Borba Manana 	locked = 1;
749bd989ba3SJan Schmidt 
750bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
7515de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
7525de865eeSFilipe David Borba Manana 		if (ret)
7535de865eeSFilipe David Borba Manana 			goto free_tms;
7545de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
7555de865eeSFilipe David Borba Manana 		if (ret)
7565de865eeSFilipe David Borba Manana 			goto free_tms;
757bd989ba3SJan Schmidt 	}
7585de865eeSFilipe David Borba Manana 
759b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
7605de865eeSFilipe David Borba Manana 	kfree(tm_list);
7615de865eeSFilipe David Borba Manana 
7625de865eeSFilipe David Borba Manana 	return 0;
7635de865eeSFilipe David Borba Manana 
7645de865eeSFilipe David Borba Manana free_tms:
7655de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items * 2; i++) {
7665de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
7675de865eeSFilipe David Borba Manana 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
7685de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
7695de865eeSFilipe David Borba Manana 	}
7705de865eeSFilipe David Borba Manana 	if (locked)
771b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
7725de865eeSFilipe David Borba Manana 	kfree(tm_list);
7735de865eeSFilipe David Borba Manana 
7745de865eeSFilipe David Borba Manana 	return ret;
775bd989ba3SJan Schmidt }
776bd989ba3SJan Schmidt 
777db7279a2SDavid Sterba static noinline int tree_mod_log_free_eb(struct extent_buffer *eb)
778bd989ba3SJan Schmidt {
7795de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
7805de865eeSFilipe David Borba Manana 	int nritems = 0;
7815de865eeSFilipe David Borba Manana 	int i;
7825de865eeSFilipe David Borba Manana 	int ret = 0;
7835de865eeSFilipe David Borba Manana 
7845de865eeSFilipe David Borba Manana 	if (btrfs_header_level(eb) == 0)
7855de865eeSFilipe David Borba Manana 		return 0;
7865de865eeSFilipe David Borba Manana 
787db7279a2SDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, NULL))
7885de865eeSFilipe David Borba Manana 		return 0;
7895de865eeSFilipe David Borba Manana 
7905de865eeSFilipe David Borba Manana 	nritems = btrfs_header_nritems(eb);
79131e818feSDavid Sterba 	tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
7925de865eeSFilipe David Borba Manana 	if (!tm_list)
7935de865eeSFilipe David Borba Manana 		return -ENOMEM;
7945de865eeSFilipe David Borba Manana 
7955de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++) {
7965de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i,
7975de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
7985de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
7995de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8005de865eeSFilipe David Borba Manana 			goto free_tms;
8015de865eeSFilipe David Borba Manana 		}
8025de865eeSFilipe David Borba Manana 	}
8035de865eeSFilipe David Borba Manana 
804db7279a2SDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
8055de865eeSFilipe David Borba Manana 		goto free_tms;
8065de865eeSFilipe David Borba Manana 
807db7279a2SDavid Sterba 	ret = __tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
808b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
8095de865eeSFilipe David Borba Manana 	if (ret)
8105de865eeSFilipe David Borba Manana 		goto free_tms;
8115de865eeSFilipe David Borba Manana 	kfree(tm_list);
8125de865eeSFilipe David Borba Manana 
8135de865eeSFilipe David Borba Manana 	return 0;
8145de865eeSFilipe David Borba Manana 
8155de865eeSFilipe David Borba Manana free_tms:
8165de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++)
8175de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8185de865eeSFilipe David Borba Manana 	kfree(tm_list);
8195de865eeSFilipe David Borba Manana 
8205de865eeSFilipe David Borba Manana 	return ret;
821bd989ba3SJan Schmidt }
822bd989ba3SJan Schmidt 
823d352ac68SChris Mason /*
8245d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
8255d4f98a2SYan Zheng  */
8265d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
8275d4f98a2SYan Zheng 			      struct extent_buffer *buf)
8285d4f98a2SYan Zheng {
8295d4f98a2SYan Zheng 	/*
83092a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
83192a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
83292a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
8335d4f98a2SYan Zheng 	 */
83492a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
8355d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
8365d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
8375d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
8385d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
8395d4f98a2SYan Zheng 		return 1;
840a79865c6SNikolay Borisov 
8415d4f98a2SYan Zheng 	return 0;
8425d4f98a2SYan Zheng }
8435d4f98a2SYan Zheng 
8445d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
8455d4f98a2SYan Zheng 				       struct btrfs_root *root,
8465d4f98a2SYan Zheng 				       struct extent_buffer *buf,
847f0486c68SYan, Zheng 				       struct extent_buffer *cow,
848f0486c68SYan, Zheng 				       int *last_ref)
8495d4f98a2SYan Zheng {
8500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8515d4f98a2SYan Zheng 	u64 refs;
8525d4f98a2SYan Zheng 	u64 owner;
8535d4f98a2SYan Zheng 	u64 flags;
8545d4f98a2SYan Zheng 	u64 new_flags = 0;
8555d4f98a2SYan Zheng 	int ret;
8565d4f98a2SYan Zheng 
8575d4f98a2SYan Zheng 	/*
8585d4f98a2SYan Zheng 	 * Backrefs update rules:
8595d4f98a2SYan Zheng 	 *
8605d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
8615d4f98a2SYan Zheng 	 * allocated by tree relocation.
8625d4f98a2SYan Zheng 	 *
8635d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
8645d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
8655d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8665d4f98a2SYan Zheng 	 *
8675d4f98a2SYan Zheng 	 * If a tree block is been relocating
8685d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
8695d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8705d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
8715d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
8725d4f98a2SYan Zheng 	 */
8735d4f98a2SYan Zheng 
8745d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
8752ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
8763173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
8773173a18fSJosef Bacik 					       &refs, &flags);
878be1a5564SMark Fasheh 		if (ret)
879be1a5564SMark Fasheh 			return ret;
880e5df9573SMark Fasheh 		if (refs == 0) {
881e5df9573SMark Fasheh 			ret = -EROFS;
8820b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
883e5df9573SMark Fasheh 			return ret;
884e5df9573SMark Fasheh 		}
8855d4f98a2SYan Zheng 	} else {
8865d4f98a2SYan Zheng 		refs = 1;
8875d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8885d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
8895d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8905d4f98a2SYan Zheng 		else
8915d4f98a2SYan Zheng 			flags = 0;
8925d4f98a2SYan Zheng 	}
8935d4f98a2SYan Zheng 
8945d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
8955d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
8965d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8975d4f98a2SYan Zheng 
8985d4f98a2SYan Zheng 	if (refs > 1) {
8995d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
9005d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
9015d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
902e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
903692826b2SJeff Mahoney 			if (ret)
904692826b2SJeff Mahoney 				return ret;
9055d4f98a2SYan Zheng 
9065d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9075d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
908e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
909692826b2SJeff Mahoney 				if (ret)
910692826b2SJeff Mahoney 					return ret;
911e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
912692826b2SJeff Mahoney 				if (ret)
913692826b2SJeff Mahoney 					return ret;
9145d4f98a2SYan Zheng 			}
9155d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
9165d4f98a2SYan Zheng 		} else {
9175d4f98a2SYan Zheng 
9185d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9195d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
920e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9215d4f98a2SYan Zheng 			else
922e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
923692826b2SJeff Mahoney 			if (ret)
924692826b2SJeff Mahoney 				return ret;
9255d4f98a2SYan Zheng 		}
9265d4f98a2SYan Zheng 		if (new_flags != 0) {
927b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
928b1c79e09SJosef Bacik 
92942c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
930b1c79e09SJosef Bacik 							  new_flags, level, 0);
931be1a5564SMark Fasheh 			if (ret)
932be1a5564SMark Fasheh 				return ret;
9335d4f98a2SYan Zheng 		}
9345d4f98a2SYan Zheng 	} else {
9355d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
9365d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9375d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
938e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9395d4f98a2SYan Zheng 			else
940e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
941692826b2SJeff Mahoney 			if (ret)
942692826b2SJeff Mahoney 				return ret;
943e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
944692826b2SJeff Mahoney 			if (ret)
945692826b2SJeff Mahoney 				return ret;
9465d4f98a2SYan Zheng 		}
9476a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
948f0486c68SYan, Zheng 		*last_ref = 1;
9495d4f98a2SYan Zheng 	}
9505d4f98a2SYan Zheng 	return 0;
9515d4f98a2SYan Zheng }
9525d4f98a2SYan Zheng 
953a6279470SFilipe Manana static struct extent_buffer *alloc_tree_block_no_bg_flush(
954a6279470SFilipe Manana 					  struct btrfs_trans_handle *trans,
955a6279470SFilipe Manana 					  struct btrfs_root *root,
956a6279470SFilipe Manana 					  u64 parent_start,
957a6279470SFilipe Manana 					  const struct btrfs_disk_key *disk_key,
958a6279470SFilipe Manana 					  int level,
959a6279470SFilipe Manana 					  u64 hint,
960a6279470SFilipe Manana 					  u64 empty_size)
961a6279470SFilipe Manana {
962a6279470SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
963a6279470SFilipe Manana 	struct extent_buffer *ret;
964a6279470SFilipe Manana 
965a6279470SFilipe Manana 	/*
966a6279470SFilipe Manana 	 * If we are COWing a node/leaf from the extent, chunk, device or free
967a6279470SFilipe Manana 	 * space trees, make sure that we do not finish block group creation of
968a6279470SFilipe Manana 	 * pending block groups. We do this to avoid a deadlock.
969a6279470SFilipe Manana 	 * COWing can result in allocation of a new chunk, and flushing pending
970a6279470SFilipe Manana 	 * block groups (btrfs_create_pending_block_groups()) can be triggered
971a6279470SFilipe Manana 	 * when finishing allocation of a new chunk. Creation of a pending block
972a6279470SFilipe Manana 	 * group modifies the extent, chunk, device and free space trees,
973a6279470SFilipe Manana 	 * therefore we could deadlock with ourselves since we are holding a
974a6279470SFilipe Manana 	 * lock on an extent buffer that btrfs_create_pending_block_groups() may
975a6279470SFilipe Manana 	 * try to COW later.
976a6279470SFilipe Manana 	 * For similar reasons, we also need to delay flushing pending block
977a6279470SFilipe Manana 	 * groups when splitting a leaf or node, from one of those trees, since
978a6279470SFilipe Manana 	 * we are holding a write lock on it and its parent or when inserting a
979a6279470SFilipe Manana 	 * new root node for one of those trees.
980a6279470SFilipe Manana 	 */
981a6279470SFilipe Manana 	if (root == fs_info->extent_root ||
982a6279470SFilipe Manana 	    root == fs_info->chunk_root ||
983a6279470SFilipe Manana 	    root == fs_info->dev_root ||
984a6279470SFilipe Manana 	    root == fs_info->free_space_root)
985a6279470SFilipe Manana 		trans->can_flush_pending_bgs = false;
986a6279470SFilipe Manana 
987a6279470SFilipe Manana 	ret = btrfs_alloc_tree_block(trans, root, parent_start,
988a6279470SFilipe Manana 				     root->root_key.objectid, disk_key, level,
989a6279470SFilipe Manana 				     hint, empty_size);
990a6279470SFilipe Manana 	trans->can_flush_pending_bgs = true;
991a6279470SFilipe Manana 
992a6279470SFilipe Manana 	return ret;
993a6279470SFilipe Manana }
994a6279470SFilipe Manana 
9955d4f98a2SYan Zheng /*
996d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
997d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
998d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
999d397712bSChris Mason  * dirty again.
1000d352ac68SChris Mason  *
1001d352ac68SChris Mason  * search_start -- an allocation hint for the new block
1002d352ac68SChris Mason  *
1003d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1004d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
1005d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
1006d352ac68SChris Mason  */
1007d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
10085f39d397SChris Mason 			     struct btrfs_root *root,
10095f39d397SChris Mason 			     struct extent_buffer *buf,
10105f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
10115f39d397SChris Mason 			     struct extent_buffer **cow_ret,
10129fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
10136702ed49SChris Mason {
10140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10155d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
10165f39d397SChris Mason 	struct extent_buffer *cow;
1017be1a5564SMark Fasheh 	int level, ret;
1018f0486c68SYan, Zheng 	int last_ref = 0;
1019925baeddSChris Mason 	int unlock_orig = 0;
10200f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
10216702ed49SChris Mason 
1022925baeddSChris Mason 	if (*cow_ret == buf)
1023925baeddSChris Mason 		unlock_orig = 1;
1024925baeddSChris Mason 
1025b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
1026925baeddSChris Mason 
102792a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
10280b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
102992a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
103027cdeb70SMiao Xie 		trans->transid != root->last_trans);
10315f39d397SChris Mason 
10327bb86316SChris Mason 	level = btrfs_header_level(buf);
103331840ae1SZheng Yan 
10345d4f98a2SYan Zheng 	if (level == 0)
10355d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
10365d4f98a2SYan Zheng 	else
10375d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
10385d4f98a2SYan Zheng 
10390f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
10405d4f98a2SYan Zheng 		parent_start = parent->start;
10415d4f98a2SYan Zheng 
1042a6279470SFilipe Manana 	cow = alloc_tree_block_no_bg_flush(trans, root, parent_start, &disk_key,
1043a6279470SFilipe Manana 					   level, search_start, empty_size);
10446702ed49SChris Mason 	if (IS_ERR(cow))
10456702ed49SChris Mason 		return PTR_ERR(cow);
10466702ed49SChris Mason 
1047b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
1048b4ce94deSChris Mason 
104958e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
1050db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
10515f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
10525d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
10535d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
10545d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
10555d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10565d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
10575d4f98a2SYan Zheng 	else
10585f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
10596702ed49SChris Mason 
1060de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
10612b82032cSYan Zheng 
1062be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1063b68dc2a9SMark Fasheh 	if (ret) {
106466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1065b68dc2a9SMark Fasheh 		return ret;
1066b68dc2a9SMark Fasheh 	}
10671a40e23bSZheng Yan 
106892a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
106983d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
107093314e3bSZhaolei 		if (ret) {
107166642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
107283d4cfd4SJosef Bacik 			return ret;
107383d4cfd4SJosef Bacik 		}
107493314e3bSZhaolei 	}
10753fd0a558SYan, Zheng 
10766702ed49SChris Mason 	if (buf == root->node) {
1077925baeddSChris Mason 		WARN_ON(parent && parent != buf);
10785d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
10795d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
10805d4f98a2SYan Zheng 			parent_start = buf->start;
1081925baeddSChris Mason 
108267439dadSDavid Sterba 		atomic_inc(&cow->refs);
1083d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, cow, 1);
1084d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1085240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1086925baeddSChris Mason 
1087f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
10885581a51aSJan Schmidt 				      last_ref);
10895f39d397SChris Mason 		free_extent_buffer(buf);
10900b86a832SChris Mason 		add_root_to_dirty_list(root);
10916702ed49SChris Mason 	} else {
10925d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1093e09c2efeSDavid Sterba 		tree_mod_log_insert_key(parent, parent_slot,
1094c8cc6341SJosef Bacik 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
10955f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1096db94535dSChris Mason 					cow->start);
109774493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
109874493f7aSChris Mason 					      trans->transid);
10996702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
11005de865eeSFilipe David Borba Manana 		if (last_ref) {
1101db7279a2SDavid Sterba 			ret = tree_mod_log_free_eb(buf);
11025de865eeSFilipe David Borba Manana 			if (ret) {
110366642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
11045de865eeSFilipe David Borba Manana 				return ret;
11055de865eeSFilipe David Borba Manana 			}
11065de865eeSFilipe David Borba Manana 		}
1107f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11085581a51aSJan Schmidt 				      last_ref);
11096702ed49SChris Mason 	}
1110925baeddSChris Mason 	if (unlock_orig)
1111925baeddSChris Mason 		btrfs_tree_unlock(buf);
11123083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
11136702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
11146702ed49SChris Mason 	*cow_ret = cow;
11156702ed49SChris Mason 	return 0;
11166702ed49SChris Mason }
11176702ed49SChris Mason 
11185d9e75c4SJan Schmidt /*
11195d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
11205d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
11215d9e75c4SJan Schmidt  */
1122bcd24dabSDavid Sterba static struct tree_mod_elem *__tree_mod_log_oldest_root(
112330b0463aSJan Schmidt 		struct extent_buffer *eb_root, u64 time_seq)
11245d9e75c4SJan Schmidt {
11255d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11265d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
112730b0463aSJan Schmidt 	u64 root_logical = eb_root->start;
11285d9e75c4SJan Schmidt 	int looped = 0;
11295d9e75c4SJan Schmidt 
11305d9e75c4SJan Schmidt 	if (!time_seq)
113135a3621bSStefan Behrens 		return NULL;
11325d9e75c4SJan Schmidt 
11335d9e75c4SJan Schmidt 	/*
1134298cfd36SChandan Rajendra 	 * the very last operation that's logged for a root is the
1135298cfd36SChandan Rajendra 	 * replacement operation (if it is replaced at all). this has
1136298cfd36SChandan Rajendra 	 * the logical address of the *new* root, making it the very
1137298cfd36SChandan Rajendra 	 * first operation that's logged for this root.
11385d9e75c4SJan Schmidt 	 */
11395d9e75c4SJan Schmidt 	while (1) {
1140bcd24dabSDavid Sterba 		tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
11415d9e75c4SJan Schmidt 						time_seq);
11425d9e75c4SJan Schmidt 		if (!looped && !tm)
114335a3621bSStefan Behrens 			return NULL;
11445d9e75c4SJan Schmidt 		/*
114528da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
114628da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
114728da9fb4SJan Schmidt 		 * level 0.
11485d9e75c4SJan Schmidt 		 */
114928da9fb4SJan Schmidt 		if (!tm)
115028da9fb4SJan Schmidt 			break;
11515d9e75c4SJan Schmidt 
115228da9fb4SJan Schmidt 		/*
115328da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
115428da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
115528da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
115628da9fb4SJan Schmidt 		 */
11575d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
11585d9e75c4SJan Schmidt 			break;
11595d9e75c4SJan Schmidt 
11605d9e75c4SJan Schmidt 		found = tm;
11615d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
11625d9e75c4SJan Schmidt 		looped = 1;
11635d9e75c4SJan Schmidt 	}
11645d9e75c4SJan Schmidt 
1165a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1166a95236d9SJan Schmidt 	if (!found)
1167a95236d9SJan Schmidt 		found = tm;
1168a95236d9SJan Schmidt 
11695d9e75c4SJan Schmidt 	return found;
11705d9e75c4SJan Schmidt }
11715d9e75c4SJan Schmidt 
11725d9e75c4SJan Schmidt /*
11735d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
117401327610SNicholas D Steeves  * previous operations will be rewound (until we reach something older than
11755d9e75c4SJan Schmidt  * time_seq).
11765d9e75c4SJan Schmidt  */
11775d9e75c4SJan Schmidt static void
1178f1ca7e98SJosef Bacik __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1179f1ca7e98SJosef Bacik 		      u64 time_seq, struct tree_mod_elem *first_tm)
11805d9e75c4SJan Schmidt {
11815d9e75c4SJan Schmidt 	u32 n;
11825d9e75c4SJan Schmidt 	struct rb_node *next;
11835d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
11845d9e75c4SJan Schmidt 	unsigned long o_dst;
11855d9e75c4SJan Schmidt 	unsigned long o_src;
11865d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
11875d9e75c4SJan Schmidt 
11885d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1189b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
1190097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
11915d9e75c4SJan Schmidt 		/*
11925d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
11935d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
11945d9e75c4SJan Schmidt 		 * opposite of each operation here.
11955d9e75c4SJan Schmidt 		 */
11965d9e75c4SJan Schmidt 		switch (tm->op) {
11975d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
11985d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
1199c730ae0cSMarcos Paulo de Souza 			fallthrough;
120095c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
12014c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
12025d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12035d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12045d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12055d9e75c4SJan Schmidt 						      tm->generation);
12064c3e6969SChris Mason 			n++;
12075d9e75c4SJan Schmidt 			break;
12085d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
12095d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
12105d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12115d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12125d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12135d9e75c4SJan Schmidt 						      tm->generation);
12145d9e75c4SJan Schmidt 			break;
12155d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
121619956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
12175d9e75c4SJan Schmidt 			n--;
12185d9e75c4SJan Schmidt 			break;
12195d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1220c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1221c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1222c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
12235d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
12245d9e75c4SJan Schmidt 			break;
12255d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
12265d9e75c4SJan Schmidt 			/*
12275d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
12285d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
12295d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
12305d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
12315d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
12325d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
12335d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
12345d9e75c4SJan Schmidt 			 */
12355d9e75c4SJan Schmidt 			break;
12365d9e75c4SJan Schmidt 		}
12375d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
12385d9e75c4SJan Schmidt 		if (!next)
12395d9e75c4SJan Schmidt 			break;
12406b4df8b6SGeliang Tang 		tm = rb_entry(next, struct tree_mod_elem, node);
1241298cfd36SChandan Rajendra 		if (tm->logical != first_tm->logical)
12425d9e75c4SJan Schmidt 			break;
12435d9e75c4SJan Schmidt 	}
1244b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
12455d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
12465d9e75c4SJan Schmidt }
12475d9e75c4SJan Schmidt 
124847fb091fSJan Schmidt /*
124901327610SNicholas D Steeves  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
125047fb091fSJan Schmidt  * is returned. If rewind operations happen, a fresh buffer is returned. The
125147fb091fSJan Schmidt  * returned buffer is always read-locked. If the returned buffer is not the
125247fb091fSJan Schmidt  * input buffer, the lock on the input buffer is released and the input buffer
125347fb091fSJan Schmidt  * is freed (its refcount is decremented).
125447fb091fSJan Schmidt  */
12555d9e75c4SJan Schmidt static struct extent_buffer *
12569ec72677SJosef Bacik tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
12579ec72677SJosef Bacik 		    struct extent_buffer *eb, u64 time_seq)
12585d9e75c4SJan Schmidt {
12595d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
12605d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
12615d9e75c4SJan Schmidt 
12625d9e75c4SJan Schmidt 	if (!time_seq)
12635d9e75c4SJan Schmidt 		return eb;
12645d9e75c4SJan Schmidt 
12655d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
12665d9e75c4SJan Schmidt 		return eb;
12675d9e75c4SJan Schmidt 
12685d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
12695d9e75c4SJan Schmidt 	if (!tm)
12705d9e75c4SJan Schmidt 		return eb;
12715d9e75c4SJan Schmidt 
12729ec72677SJosef Bacik 	btrfs_set_path_blocking(path);
1273300aa896SDavid Sterba 	btrfs_set_lock_blocking_read(eb);
12749ec72677SJosef Bacik 
12755d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
12765d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
1277da17066cSJeff Mahoney 		eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1278db7f3436SJosef Bacik 		if (!eb_rewin) {
12799ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1280db7f3436SJosef Bacik 			free_extent_buffer(eb);
1281db7f3436SJosef Bacik 			return NULL;
1282db7f3436SJosef Bacik 		}
12835d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
12845d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
12855d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
12865d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1287c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
12885d9e75c4SJan Schmidt 	} else {
12895d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
1290db7f3436SJosef Bacik 		if (!eb_rewin) {
12919ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1292db7f3436SJosef Bacik 			free_extent_buffer(eb);
1293db7f3436SJosef Bacik 			return NULL;
1294db7f3436SJosef Bacik 		}
12955d9e75c4SJan Schmidt 	}
12965d9e75c4SJan Schmidt 
12979ec72677SJosef Bacik 	btrfs_tree_read_unlock_blocking(eb);
12985d9e75c4SJan Schmidt 	free_extent_buffer(eb);
12995d9e75c4SJan Schmidt 
1300d3beaa25SJosef Bacik 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb_rewin),
1301d3beaa25SJosef Bacik 				       eb_rewin, btrfs_header_level(eb_rewin));
130247fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1303f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
130457911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
1305da17066cSJeff Mahoney 		BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13065d9e75c4SJan Schmidt 
13075d9e75c4SJan Schmidt 	return eb_rewin;
13085d9e75c4SJan Schmidt }
13095d9e75c4SJan Schmidt 
13108ba97a15SJan Schmidt /*
13118ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
13128ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
13138ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
13148ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
13158ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
13168ba97a15SJan Schmidt  */
13175d9e75c4SJan Schmidt static inline struct extent_buffer *
13185d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
13195d9e75c4SJan Schmidt {
13200b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13215d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
132230b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
132330b0463aSJan Schmidt 	struct extent_buffer *eb_root;
1324efad8a85SFilipe Manana 	u64 eb_root_owner = 0;
13257bfdcf7fSLiu Bo 	struct extent_buffer *old;
1326a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
13274325edd0SChris Mason 	u64 old_generation = 0;
1328a95236d9SJan Schmidt 	u64 logical;
1329581c1760SQu Wenruo 	int level;
13305d9e75c4SJan Schmidt 
133130b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
1332bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
13335d9e75c4SJan Schmidt 	if (!tm)
133430b0463aSJan Schmidt 		return eb_root;
13355d9e75c4SJan Schmidt 
1336a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
13375d9e75c4SJan Schmidt 		old_root = &tm->old_root;
13385d9e75c4SJan Schmidt 		old_generation = tm->generation;
1339a95236d9SJan Schmidt 		logical = old_root->logical;
1340581c1760SQu Wenruo 		level = old_root->level;
1341a95236d9SJan Schmidt 	} else {
134230b0463aSJan Schmidt 		logical = eb_root->start;
1343581c1760SQu Wenruo 		level = btrfs_header_level(eb_root);
1344a95236d9SJan Schmidt 	}
13455d9e75c4SJan Schmidt 
13460b246afaSJeff Mahoney 	tm = tree_mod_log_search(fs_info, logical, time_seq);
1347834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
134830b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
134930b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1350581c1760SQu Wenruo 		old = read_tree_block(fs_info, logical, 0, level, NULL);
135164c043deSLiu Bo 		if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
135264c043deSLiu Bo 			if (!IS_ERR(old))
1353416bc658SJosef Bacik 				free_extent_buffer(old);
13540b246afaSJeff Mahoney 			btrfs_warn(fs_info,
13550b246afaSJeff Mahoney 				   "failed to read tree block %llu from get_old_root",
13560b246afaSJeff Mahoney 				   logical);
1357834328a8SJan Schmidt 		} else {
13587bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
13597bfdcf7fSLiu Bo 			free_extent_buffer(old);
1360834328a8SJan Schmidt 		}
1361834328a8SJan Schmidt 	} else if (old_root) {
1362efad8a85SFilipe Manana 		eb_root_owner = btrfs_header_owner(eb_root);
136330b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
136430b0463aSJan Schmidt 		free_extent_buffer(eb_root);
13650b246afaSJeff Mahoney 		eb = alloc_dummy_extent_buffer(fs_info, logical);
1366834328a8SJan Schmidt 	} else {
1367300aa896SDavid Sterba 		btrfs_set_lock_blocking_read(eb_root);
136830b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
13699ec72677SJosef Bacik 		btrfs_tree_read_unlock_blocking(eb_root);
137030b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1371834328a8SJan Schmidt 	}
1372834328a8SJan Schmidt 
13738ba97a15SJan Schmidt 	if (!eb)
13748ba97a15SJan Schmidt 		return NULL;
1375a95236d9SJan Schmidt 	if (old_root) {
13765d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
13775d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1378efad8a85SFilipe Manana 		btrfs_set_header_owner(eb, eb_root_owner);
13795d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
13805d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1381a95236d9SJan Schmidt 	}
1382d3beaa25SJosef Bacik 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb), eb,
1383d3beaa25SJosef Bacik 				       btrfs_header_level(eb));
1384d3beaa25SJosef Bacik 	btrfs_tree_read_lock(eb);
138528da9fb4SJan Schmidt 	if (tm)
13860b246afaSJeff Mahoney 		__tree_mod_log_rewind(fs_info, eb, time_seq, tm);
138728da9fb4SJan Schmidt 	else
138828da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
13890b246afaSJeff Mahoney 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13905d9e75c4SJan Schmidt 
13915d9e75c4SJan Schmidt 	return eb;
13925d9e75c4SJan Schmidt }
13935d9e75c4SJan Schmidt 
13945b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
13955b6602e7SJan Schmidt {
13965b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
13975b6602e7SJan Schmidt 	int level;
139830b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
13995b6602e7SJan Schmidt 
1400bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
14015b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
14025b6602e7SJan Schmidt 		level = tm->old_root.level;
14035b6602e7SJan Schmidt 	} else {
140430b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
14055b6602e7SJan Schmidt 	}
140630b0463aSJan Schmidt 	free_extent_buffer(eb_root);
14075b6602e7SJan Schmidt 
14085b6602e7SJan Schmidt 	return level;
14095b6602e7SJan Schmidt }
14105b6602e7SJan Schmidt 
14115d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
14125d4f98a2SYan Zheng 				   struct btrfs_root *root,
14135d4f98a2SYan Zheng 				   struct extent_buffer *buf)
14145d4f98a2SYan Zheng {
1415f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
1416faa2dbf0SJosef Bacik 		return 0;
1417fccb84c9SDavid Sterba 
1418d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
1419d1980131SDavid Sterba 	smp_mb__before_atomic();
1420f1ebcc74SLiu Bo 
1421f1ebcc74SLiu Bo 	/*
1422f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1423f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1424f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1425f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1426f1ebcc74SLiu Bo 	 *
1427f1ebcc74SLiu Bo 	 * What is forced COW:
142801327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
142952042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
1430f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1431f1ebcc74SLiu Bo 	 */
14325d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
14335d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
14345d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1435f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
143627cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
14375d4f98a2SYan Zheng 		return 0;
14385d4f98a2SYan Zheng 	return 1;
14395d4f98a2SYan Zheng }
14405d4f98a2SYan Zheng 
1441d352ac68SChris Mason /*
1442d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
144301327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
1444d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1445d352ac68SChris Mason  */
1446d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
14475f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
14485f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
14499fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
145002217ed2SChris Mason {
14510b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14526702ed49SChris Mason 	u64 search_start;
1453f510cfecSChris Mason 	int ret;
1454dc17ff8fSChris Mason 
145583354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
145683354f07SJosef Bacik 		btrfs_err(fs_info,
145783354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
145883354f07SJosef Bacik 
14590b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
146031b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1461c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
14620b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
146331b1a2bdSJulia Lawall 
14640b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
146531b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
14660b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
1467dc17ff8fSChris Mason 
14685d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
146964c12921SJeff Mahoney 		trans->dirty = true;
147002217ed2SChris Mason 		*cow_ret = buf;
147102217ed2SChris Mason 		return 0;
147202217ed2SChris Mason 	}
1473c487685dSChris Mason 
1474ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
1475b4ce94deSChris Mason 
1476b4ce94deSChris Mason 	if (parent)
14778bead258SDavid Sterba 		btrfs_set_lock_blocking_write(parent);
14788bead258SDavid Sterba 	btrfs_set_lock_blocking_write(buf);
1479b4ce94deSChris Mason 
1480f616f5cdSQu Wenruo 	/*
1481f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
1482f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
1483f616f5cdSQu Wenruo 	 *
1484f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
1485f616f5cdSQu Wenruo 	 */
1486f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
1487f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
14889fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
14891abe9b8aSliubo 
14901abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
14911abe9b8aSliubo 
1492f510cfecSChris Mason 	return ret;
14932c90e5d6SChris Mason }
14946702ed49SChris Mason 
1495d352ac68SChris Mason /*
1496d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1497d352ac68SChris Mason  * node are actually close by
1498d352ac68SChris Mason  */
14996b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
15006702ed49SChris Mason {
15016b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
15026702ed49SChris Mason 		return 1;
15036b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
15046702ed49SChris Mason 		return 1;
150502217ed2SChris Mason 	return 0;
150602217ed2SChris Mason }
150702217ed2SChris Mason 
1508ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
1509ce6ef5abSDavid Sterba 
1510ce6ef5abSDavid Sterba /*
1511ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
1512ce6ef5abSDavid Sterba  * we can avoid the conversion.
1513ce6ef5abSDavid Sterba  */
1514ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
1515ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
1516ce6ef5abSDavid Sterba {
1517ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
1518ce6ef5abSDavid Sterba 
1519ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
1520ce6ef5abSDavid Sterba }
1521ce6ef5abSDavid Sterba 
1522ce6ef5abSDavid Sterba #else
1523ce6ef5abSDavid Sterba 
1524081e9573SChris Mason /*
1525081e9573SChris Mason  * compare two keys in a memcmp fashion
1526081e9573SChris Mason  */
1527310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
1528310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
1529081e9573SChris Mason {
1530081e9573SChris Mason 	struct btrfs_key k1;
1531081e9573SChris Mason 
1532081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1533081e9573SChris Mason 
153420736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1535081e9573SChris Mason }
1536ce6ef5abSDavid Sterba #endif
1537081e9573SChris Mason 
1538f3465ca4SJosef Bacik /*
1539f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1540f3465ca4SJosef Bacik  */
1541e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1542f3465ca4SJosef Bacik {
1543f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1544f3465ca4SJosef Bacik 		return 1;
1545f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1546f3465ca4SJosef Bacik 		return -1;
1547f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1548f3465ca4SJosef Bacik 		return 1;
1549f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1550f3465ca4SJosef Bacik 		return -1;
1551f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1552f3465ca4SJosef Bacik 		return 1;
1553f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1554f3465ca4SJosef Bacik 		return -1;
1555f3465ca4SJosef Bacik 	return 0;
1556f3465ca4SJosef Bacik }
1557081e9573SChris Mason 
1558d352ac68SChris Mason /*
1559d352ac68SChris Mason  * this is used by the defrag code to go through all the
1560d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1561d352ac68SChris Mason  * disk order is close to key order
1562d352ac68SChris Mason  */
15636702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
15645f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1565de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1566a6b6e75eSChris Mason 		       struct btrfs_key *progress)
15676702ed49SChris Mason {
15680b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15696b80053dSChris Mason 	struct extent_buffer *cur;
15706702ed49SChris Mason 	u64 blocknr;
1571ca7a79adSChris Mason 	u64 gen;
1572e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1573e9d0b13bSChris Mason 	u64 last_block = 0;
15746702ed49SChris Mason 	u64 other;
15756702ed49SChris Mason 	u32 parent_nritems;
15766702ed49SChris Mason 	int end_slot;
15776702ed49SChris Mason 	int i;
15786702ed49SChris Mason 	int err = 0;
1579f2183bdeSChris Mason 	int parent_level;
15806b80053dSChris Mason 	int uptodate;
15816b80053dSChris Mason 	u32 blocksize;
1582081e9573SChris Mason 	int progress_passed = 0;
1583081e9573SChris Mason 	struct btrfs_disk_key disk_key;
15846702ed49SChris Mason 
15855708b959SChris Mason 	parent_level = btrfs_header_level(parent);
15865708b959SChris Mason 
15870b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
15880b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
158986479a04SChris Mason 
15906b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
15910b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
15925dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
15936702ed49SChris Mason 
15945dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
15956702ed49SChris Mason 		return 0;
15966702ed49SChris Mason 
15978bead258SDavid Sterba 	btrfs_set_lock_blocking_write(parent);
1598b4ce94deSChris Mason 
15995dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
1600581c1760SQu Wenruo 		struct btrfs_key first_key;
16016702ed49SChris Mason 		int close = 1;
1602a6b6e75eSChris Mason 
1603081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1604081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1605081e9573SChris Mason 			continue;
1606081e9573SChris Mason 
1607081e9573SChris Mason 		progress_passed = 1;
16086b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1609ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1610581c1760SQu Wenruo 		btrfs_node_key_to_cpu(parent, &first_key, i);
1611e9d0b13bSChris Mason 		if (last_block == 0)
1612e9d0b13bSChris Mason 			last_block = blocknr;
16135708b959SChris Mason 
16146702ed49SChris Mason 		if (i > 0) {
16156b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
16166b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16176702ed49SChris Mason 		}
16185dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
16196b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
16206b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16216702ed49SChris Mason 		}
1622e9d0b13bSChris Mason 		if (close) {
1623e9d0b13bSChris Mason 			last_block = blocknr;
16246702ed49SChris Mason 			continue;
1625e9d0b13bSChris Mason 		}
16266702ed49SChris Mason 
16270b246afaSJeff Mahoney 		cur = find_extent_buffer(fs_info, blocknr);
16286b80053dSChris Mason 		if (cur)
1629b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
16306b80053dSChris Mason 		else
16316b80053dSChris Mason 			uptodate = 0;
16325708b959SChris Mason 		if (!cur || !uptodate) {
16336b80053dSChris Mason 			if (!cur) {
1634581c1760SQu Wenruo 				cur = read_tree_block(fs_info, blocknr, gen,
1635581c1760SQu Wenruo 						      parent_level - 1,
1636581c1760SQu Wenruo 						      &first_key);
163764c043deSLiu Bo 				if (IS_ERR(cur)) {
163864c043deSLiu Bo 					return PTR_ERR(cur);
163964c043deSLiu Bo 				} else if (!extent_buffer_uptodate(cur)) {
1640416bc658SJosef Bacik 					free_extent_buffer(cur);
164197d9a8a4STsutomu Itoh 					return -EIO;
1642416bc658SJosef Bacik 				}
16436b80053dSChris Mason 			} else if (!uptodate) {
1644581c1760SQu Wenruo 				err = btrfs_read_buffer(cur, gen,
1645581c1760SQu Wenruo 						parent_level - 1,&first_key);
1646018642a1STsutomu Itoh 				if (err) {
1647018642a1STsutomu Itoh 					free_extent_buffer(cur);
1648018642a1STsutomu Itoh 					return err;
1649018642a1STsutomu Itoh 				}
16506702ed49SChris Mason 			}
1651f2183bdeSChris Mason 		}
1652e9d0b13bSChris Mason 		if (search_start == 0)
16536b80053dSChris Mason 			search_start = last_block;
1654e9d0b13bSChris Mason 
1655e7a84565SChris Mason 		btrfs_tree_lock(cur);
16568bead258SDavid Sterba 		btrfs_set_lock_blocking_write(cur);
16576b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1658e7a84565SChris Mason 					&cur, search_start,
16596b80053dSChris Mason 					min(16 * blocksize,
16609fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1661252c38f0SYan 		if (err) {
1662e7a84565SChris Mason 			btrfs_tree_unlock(cur);
16636b80053dSChris Mason 			free_extent_buffer(cur);
16646702ed49SChris Mason 			break;
1665252c38f0SYan 		}
1666e7a84565SChris Mason 		search_start = cur->start;
1667e7a84565SChris Mason 		last_block = cur->start;
1668f2183bdeSChris Mason 		*last_ret = search_start;
1669e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1670e7a84565SChris Mason 		free_extent_buffer(cur);
16716702ed49SChris Mason 	}
16726702ed49SChris Mason 	return err;
16736702ed49SChris Mason }
16746702ed49SChris Mason 
167574123bd7SChris Mason /*
16765f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
16775f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
16785f39d397SChris Mason  *
167974123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
168074123bd7SChris Mason  * the place where you would insert key if it is not found in
168174123bd7SChris Mason  * the array.
168274123bd7SChris Mason  *
168374123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
168474123bd7SChris Mason  */
1685e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1686310712b2SOmar Sandoval 				       unsigned long p, int item_size,
1687310712b2SOmar Sandoval 				       const struct btrfs_key *key,
1688be0e5c09SChris Mason 				       int max, int *slot)
1689be0e5c09SChris Mason {
1690be0e5c09SChris Mason 	int low = 0;
1691be0e5c09SChris Mason 	int high = max;
1692be0e5c09SChris Mason 	int ret;
16935cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
1694be0e5c09SChris Mason 
16955e24e9afSLiu Bo 	if (low > high) {
16965e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
16975e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
16985e24e9afSLiu Bo 			  __func__, low, high, eb->start,
16995e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
17005e24e9afSLiu Bo 		return -EINVAL;
17015e24e9afSLiu Bo 	}
17025e24e9afSLiu Bo 
1703be0e5c09SChris Mason 	while (low < high) {
17045cd17f34SDavid Sterba 		unsigned long oip;
17055cd17f34SDavid Sterba 		unsigned long offset;
17065cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
17075cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
17085cd17f34SDavid Sterba 		int mid;
17095cd17f34SDavid Sterba 
1710be0e5c09SChris Mason 		mid = (low + high) / 2;
17115f39d397SChris Mason 		offset = p + mid * item_size;
17125cd17f34SDavid Sterba 		oip = offset_in_page(offset);
17135f39d397SChris Mason 
17145cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
17155cd17f34SDavid Sterba 			const unsigned long idx = offset >> PAGE_SHIFT;
17165cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
1717934d375bSChris Mason 
17185cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
17195cd17f34SDavid Sterba 		} else {
17205cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
17215f39d397SChris Mason 			tmp = &unaligned;
1722479965d6SChris Mason 		}
1723479965d6SChris Mason 
1724be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1725be0e5c09SChris Mason 
1726be0e5c09SChris Mason 		if (ret < 0)
1727be0e5c09SChris Mason 			low = mid + 1;
1728be0e5c09SChris Mason 		else if (ret > 0)
1729be0e5c09SChris Mason 			high = mid;
1730be0e5c09SChris Mason 		else {
1731be0e5c09SChris Mason 			*slot = mid;
1732be0e5c09SChris Mason 			return 0;
1733be0e5c09SChris Mason 		}
1734be0e5c09SChris Mason 	}
1735be0e5c09SChris Mason 	*slot = low;
1736be0e5c09SChris Mason 	return 1;
1737be0e5c09SChris Mason }
1738be0e5c09SChris Mason 
173997571fd0SChris Mason /*
174097571fd0SChris Mason  * simple bin_search frontend that does the right thing for
174197571fd0SChris Mason  * leaves vs nodes
174297571fd0SChris Mason  */
1743a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
1744e3b83361SQu Wenruo 		     int *slot)
1745be0e5c09SChris Mason {
1746e3b83361SQu Wenruo 	if (btrfs_header_level(eb) == 0)
17475f39d397SChris Mason 		return generic_bin_search(eb,
17485f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
17490783fcfcSChris Mason 					  sizeof(struct btrfs_item),
17505f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17517518a238SChris Mason 					  slot);
1752f775738fSWang Sheng-Hui 	else
17535f39d397SChris Mason 		return generic_bin_search(eb,
17545f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1755123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
17565f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17577518a238SChris Mason 					  slot);
1758be0e5c09SChris Mason }
1759be0e5c09SChris Mason 
1760f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1761f0486c68SYan, Zheng {
1762f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1763f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1764f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1765f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1766f0486c68SYan, Zheng }
1767f0486c68SYan, Zheng 
1768f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1769f0486c68SYan, Zheng {
1770f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1771f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1772f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1773f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1774f0486c68SYan, Zheng }
1775f0486c68SYan, Zheng 
1776d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1777d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1778d352ac68SChris Mason  */
17794b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
17804b231ae4SDavid Sterba 					   int slot)
1781bb803951SChris Mason {
1782ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1783416bc658SJosef Bacik 	struct extent_buffer *eb;
1784581c1760SQu Wenruo 	struct btrfs_key first_key;
1785416bc658SJosef Bacik 
1786fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
1787fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
1788ca7a79adSChris Mason 
1789ca7a79adSChris Mason 	BUG_ON(level == 0);
1790ca7a79adSChris Mason 
1791581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
1792d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1793581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
1794581c1760SQu Wenruo 			     level - 1, &first_key);
1795fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1796416bc658SJosef Bacik 		free_extent_buffer(eb);
1797fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
1798416bc658SJosef Bacik 	}
1799416bc658SJosef Bacik 
1800416bc658SJosef Bacik 	return eb;
1801bb803951SChris Mason }
1802bb803951SChris Mason 
1803d352ac68SChris Mason /*
1804d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1805d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1806d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1807d352ac68SChris Mason  */
1808e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
180998ed5174SChris Mason 			 struct btrfs_root *root,
181098ed5174SChris Mason 			 struct btrfs_path *path, int level)
1811bb803951SChris Mason {
18120b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
18135f39d397SChris Mason 	struct extent_buffer *right = NULL;
18145f39d397SChris Mason 	struct extent_buffer *mid;
18155f39d397SChris Mason 	struct extent_buffer *left = NULL;
18165f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1817bb803951SChris Mason 	int ret = 0;
1818bb803951SChris Mason 	int wret;
1819bb803951SChris Mason 	int pslot;
1820bb803951SChris Mason 	int orig_slot = path->slots[level];
182179f95c82SChris Mason 	u64 orig_ptr;
1822bb803951SChris Mason 
182398e6b1ebSLiu Bo 	ASSERT(level > 0);
1824bb803951SChris Mason 
18255f39d397SChris Mason 	mid = path->nodes[level];
1826b4ce94deSChris Mason 
1827bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1828bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
18297bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
18307bb86316SChris Mason 
18311d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
183279f95c82SChris Mason 
1833a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18345f39d397SChris Mason 		parent = path->nodes[level + 1];
1835bb803951SChris Mason 		pslot = path->slots[level + 1];
1836a05a9bb1SLi Zefan 	}
1837bb803951SChris Mason 
183840689478SChris Mason 	/*
183940689478SChris Mason 	 * deal with the case where there is only one pointer in the root
184040689478SChris Mason 	 * by promoting the node below to a root
184140689478SChris Mason 	 */
18425f39d397SChris Mason 	if (!parent) {
18435f39d397SChris Mason 		struct extent_buffer *child;
1844bb803951SChris Mason 
18455f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1846bb803951SChris Mason 			return 0;
1847bb803951SChris Mason 
1848bb803951SChris Mason 		/* promote the child to a root */
18494b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1850fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1851fb770ae4SLiu Bo 			ret = PTR_ERR(child);
18520b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1853305a26afSMark Fasheh 			goto enospc;
1854305a26afSMark Fasheh 		}
1855305a26afSMark Fasheh 
1856925baeddSChris Mason 		btrfs_tree_lock(child);
18578bead258SDavid Sterba 		btrfs_set_lock_blocking_write(child);
18589fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1859f0486c68SYan, Zheng 		if (ret) {
1860f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1861f0486c68SYan, Zheng 			free_extent_buffer(child);
1862f0486c68SYan, Zheng 			goto enospc;
1863f0486c68SYan, Zheng 		}
18642f375ab9SYan 
1865d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, child, 1);
1866d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1867240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1868925baeddSChris Mason 
18690b86a832SChris Mason 		add_root_to_dirty_list(root);
1870925baeddSChris Mason 		btrfs_tree_unlock(child);
1871b4ce94deSChris Mason 
1872925baeddSChris Mason 		path->locks[level] = 0;
1873bb803951SChris Mason 		path->nodes[level] = NULL;
18746a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1875925baeddSChris Mason 		btrfs_tree_unlock(mid);
1876bb803951SChris Mason 		/* once for the path */
18775f39d397SChris Mason 		free_extent_buffer(mid);
1878f0486c68SYan, Zheng 
1879f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
18805581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1881bb803951SChris Mason 		/* once for the root ptr */
18823083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1883f0486c68SYan, Zheng 		return 0;
1884bb803951SChris Mason 	}
18855f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
18860b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1887bb803951SChris Mason 		return 0;
1888bb803951SChris Mason 
18894b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1890fb770ae4SLiu Bo 	if (IS_ERR(left))
1891fb770ae4SLiu Bo 		left = NULL;
1892fb770ae4SLiu Bo 
18935f39d397SChris Mason 	if (left) {
1894925baeddSChris Mason 		btrfs_tree_lock(left);
18958bead258SDavid Sterba 		btrfs_set_lock_blocking_write(left);
18965f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
18979fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
189854aa1f4dSChris Mason 		if (wret) {
189954aa1f4dSChris Mason 			ret = wret;
190054aa1f4dSChris Mason 			goto enospc;
190154aa1f4dSChris Mason 		}
19022cc58cf2SChris Mason 	}
1903fb770ae4SLiu Bo 
19044b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1905fb770ae4SLiu Bo 	if (IS_ERR(right))
1906fb770ae4SLiu Bo 		right = NULL;
1907fb770ae4SLiu Bo 
19085f39d397SChris Mason 	if (right) {
1909925baeddSChris Mason 		btrfs_tree_lock(right);
19108bead258SDavid Sterba 		btrfs_set_lock_blocking_write(right);
19115f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
19129fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
19132cc58cf2SChris Mason 		if (wret) {
19142cc58cf2SChris Mason 			ret = wret;
19152cc58cf2SChris Mason 			goto enospc;
19162cc58cf2SChris Mason 		}
19172cc58cf2SChris Mason 	}
19182cc58cf2SChris Mason 
19192cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
19205f39d397SChris Mason 	if (left) {
19215f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1922d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
192379f95c82SChris Mason 		if (wret < 0)
192479f95c82SChris Mason 			ret = wret;
1925bb803951SChris Mason 	}
192679f95c82SChris Mason 
192779f95c82SChris Mason 	/*
192879f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
192979f95c82SChris Mason 	 */
19305f39d397SChris Mason 	if (right) {
1931d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
193254aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
193379f95c82SChris Mason 			ret = wret;
19345f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
19356a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1936925baeddSChris Mason 			btrfs_tree_unlock(right);
1937afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1938f0486c68SYan, Zheng 			root_sub_used(root, right->len);
19395581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
19403083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1941f0486c68SYan, Zheng 			right = NULL;
1942bb803951SChris Mason 		} else {
19435f39d397SChris Mason 			struct btrfs_disk_key right_key;
19445f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
19450e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
19460e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
19470e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
19485f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
19495f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1950bb803951SChris Mason 		}
1951bb803951SChris Mason 	}
19525f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
195379f95c82SChris Mason 		/*
195479f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
195579f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
195679f95c82SChris Mason 		 * could try to delete the only pointer in this node.
195779f95c82SChris Mason 		 * So, pull some keys from the left.
195879f95c82SChris Mason 		 * There has to be a left pointer at this point because
195979f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
196079f95c82SChris Mason 		 * right
196179f95c82SChris Mason 		 */
1962305a26afSMark Fasheh 		if (!left) {
1963305a26afSMark Fasheh 			ret = -EROFS;
19640b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1965305a26afSMark Fasheh 			goto enospc;
1966305a26afSMark Fasheh 		}
196755d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
196854aa1f4dSChris Mason 		if (wret < 0) {
196979f95c82SChris Mason 			ret = wret;
197054aa1f4dSChris Mason 			goto enospc;
197154aa1f4dSChris Mason 		}
1972bce4eae9SChris Mason 		if (wret == 1) {
1973d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1974bce4eae9SChris Mason 			if (wret < 0)
1975bce4eae9SChris Mason 				ret = wret;
1976bce4eae9SChris Mason 		}
197779f95c82SChris Mason 		BUG_ON(wret == 1);
197879f95c82SChris Mason 	}
19795f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
19806a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1981925baeddSChris Mason 		btrfs_tree_unlock(mid);
1982afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1983f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
19845581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
19853083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1986f0486c68SYan, Zheng 		mid = NULL;
198779f95c82SChris Mason 	} else {
198879f95c82SChris Mason 		/* update the parent key to reflect our changes */
19895f39d397SChris Mason 		struct btrfs_disk_key mid_key;
19905f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
19910e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, pslot,
19920e82bcfeSDavid Sterba 				MOD_LOG_KEY_REPLACE, GFP_NOFS);
19930e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
19945f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
19955f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
199679f95c82SChris Mason 	}
1997bb803951SChris Mason 
199879f95c82SChris Mason 	/* update the path */
19995f39d397SChris Mason 	if (left) {
20005f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
200167439dadSDavid Sterba 			atomic_inc(&left->refs);
2002925baeddSChris Mason 			/* left was locked after cow */
20035f39d397SChris Mason 			path->nodes[level] = left;
2004bb803951SChris Mason 			path->slots[level + 1] -= 1;
2005bb803951SChris Mason 			path->slots[level] = orig_slot;
2006925baeddSChris Mason 			if (mid) {
2007925baeddSChris Mason 				btrfs_tree_unlock(mid);
20085f39d397SChris Mason 				free_extent_buffer(mid);
2009925baeddSChris Mason 			}
2010bb803951SChris Mason 		} else {
20115f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
2012bb803951SChris Mason 			path->slots[level] = orig_slot;
2013bb803951SChris Mason 		}
2014bb803951SChris Mason 	}
201579f95c82SChris Mason 	/* double check we haven't messed things up */
2016e20d96d6SChris Mason 	if (orig_ptr !=
20175f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
201879f95c82SChris Mason 		BUG();
201954aa1f4dSChris Mason enospc:
2020925baeddSChris Mason 	if (right) {
2021925baeddSChris Mason 		btrfs_tree_unlock(right);
20225f39d397SChris Mason 		free_extent_buffer(right);
2023925baeddSChris Mason 	}
2024925baeddSChris Mason 	if (left) {
2025925baeddSChris Mason 		if (path->nodes[level] != left)
2026925baeddSChris Mason 			btrfs_tree_unlock(left);
20275f39d397SChris Mason 		free_extent_buffer(left);
2028925baeddSChris Mason 	}
2029bb803951SChris Mason 	return ret;
2030bb803951SChris Mason }
2031bb803951SChris Mason 
2032d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
2033d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
2034d352ac68SChris Mason  * have to be pessimistic.
2035d352ac68SChris Mason  */
2036d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2037e66f709bSChris Mason 					  struct btrfs_root *root,
2038e66f709bSChris Mason 					  struct btrfs_path *path, int level)
2039e66f709bSChris Mason {
20400b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
20415f39d397SChris Mason 	struct extent_buffer *right = NULL;
20425f39d397SChris Mason 	struct extent_buffer *mid;
20435f39d397SChris Mason 	struct extent_buffer *left = NULL;
20445f39d397SChris Mason 	struct extent_buffer *parent = NULL;
2045e66f709bSChris Mason 	int ret = 0;
2046e66f709bSChris Mason 	int wret;
2047e66f709bSChris Mason 	int pslot;
2048e66f709bSChris Mason 	int orig_slot = path->slots[level];
2049e66f709bSChris Mason 
2050e66f709bSChris Mason 	if (level == 0)
2051e66f709bSChris Mason 		return 1;
2052e66f709bSChris Mason 
20535f39d397SChris Mason 	mid = path->nodes[level];
20547bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
2055e66f709bSChris Mason 
2056a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
20575f39d397SChris Mason 		parent = path->nodes[level + 1];
2058e66f709bSChris Mason 		pslot = path->slots[level + 1];
2059a05a9bb1SLi Zefan 	}
2060e66f709bSChris Mason 
20615f39d397SChris Mason 	if (!parent)
2062e66f709bSChris Mason 		return 1;
2063e66f709bSChris Mason 
20644b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
2065fb770ae4SLiu Bo 	if (IS_ERR(left))
2066fb770ae4SLiu Bo 		left = NULL;
2067e66f709bSChris Mason 
2068e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
20695f39d397SChris Mason 	if (left) {
2070e66f709bSChris Mason 		u32 left_nr;
2071925baeddSChris Mason 
2072925baeddSChris Mason 		btrfs_tree_lock(left);
20738bead258SDavid Sterba 		btrfs_set_lock_blocking_write(left);
2074b4ce94deSChris Mason 
20755f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
20760b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
207733ade1f8SChris Mason 			wret = 1;
207833ade1f8SChris Mason 		} else {
20795f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
20809fa8cfe7SChris Mason 					      pslot - 1, &left);
208154aa1f4dSChris Mason 			if (ret)
208254aa1f4dSChris Mason 				wret = 1;
208354aa1f4dSChris Mason 			else {
2084d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
208554aa1f4dSChris Mason 			}
208633ade1f8SChris Mason 		}
2087e66f709bSChris Mason 		if (wret < 0)
2088e66f709bSChris Mason 			ret = wret;
2089e66f709bSChris Mason 		if (wret == 0) {
20905f39d397SChris Mason 			struct btrfs_disk_key disk_key;
2091e66f709bSChris Mason 			orig_slot += left_nr;
20925f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
20930e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot,
20940e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
20950e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
20965f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
20975f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
20985f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
20995f39d397SChris Mason 				path->nodes[level] = left;
2100e66f709bSChris Mason 				path->slots[level + 1] -= 1;
2101e66f709bSChris Mason 				path->slots[level] = orig_slot;
2102925baeddSChris Mason 				btrfs_tree_unlock(mid);
21035f39d397SChris Mason 				free_extent_buffer(mid);
2104e66f709bSChris Mason 			} else {
2105e66f709bSChris Mason 				orig_slot -=
21065f39d397SChris Mason 					btrfs_header_nritems(left);
2107e66f709bSChris Mason 				path->slots[level] = orig_slot;
2108925baeddSChris Mason 				btrfs_tree_unlock(left);
21095f39d397SChris Mason 				free_extent_buffer(left);
2110e66f709bSChris Mason 			}
2111e66f709bSChris Mason 			return 0;
2112e66f709bSChris Mason 		}
2113925baeddSChris Mason 		btrfs_tree_unlock(left);
21145f39d397SChris Mason 		free_extent_buffer(left);
2115e66f709bSChris Mason 	}
21164b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
2117fb770ae4SLiu Bo 	if (IS_ERR(right))
2118fb770ae4SLiu Bo 		right = NULL;
2119e66f709bSChris Mason 
2120e66f709bSChris Mason 	/*
2121e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2122e66f709bSChris Mason 	 */
21235f39d397SChris Mason 	if (right) {
212433ade1f8SChris Mason 		u32 right_nr;
2125b4ce94deSChris Mason 
2126925baeddSChris Mason 		btrfs_tree_lock(right);
21278bead258SDavid Sterba 		btrfs_set_lock_blocking_write(right);
2128b4ce94deSChris Mason 
21295f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
21300b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
213133ade1f8SChris Mason 			wret = 1;
213233ade1f8SChris Mason 		} else {
21335f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
21345f39d397SChris Mason 					      parent, pslot + 1,
21359fa8cfe7SChris Mason 					      &right);
213654aa1f4dSChris Mason 			if (ret)
213754aa1f4dSChris Mason 				wret = 1;
213854aa1f4dSChris Mason 			else {
213955d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
214033ade1f8SChris Mason 			}
214154aa1f4dSChris Mason 		}
2142e66f709bSChris Mason 		if (wret < 0)
2143e66f709bSChris Mason 			ret = wret;
2144e66f709bSChris Mason 		if (wret == 0) {
21455f39d397SChris Mason 			struct btrfs_disk_key disk_key;
21465f39d397SChris Mason 
21475f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
21480e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
21490e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21500e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21515f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
21525f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21535f39d397SChris Mason 
21545f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
21555f39d397SChris Mason 				path->nodes[level] = right;
2156e66f709bSChris Mason 				path->slots[level + 1] += 1;
2157e66f709bSChris Mason 				path->slots[level] = orig_slot -
21585f39d397SChris Mason 					btrfs_header_nritems(mid);
2159925baeddSChris Mason 				btrfs_tree_unlock(mid);
21605f39d397SChris Mason 				free_extent_buffer(mid);
2161e66f709bSChris Mason 			} else {
2162925baeddSChris Mason 				btrfs_tree_unlock(right);
21635f39d397SChris Mason 				free_extent_buffer(right);
2164e66f709bSChris Mason 			}
2165e66f709bSChris Mason 			return 0;
2166e66f709bSChris Mason 		}
2167925baeddSChris Mason 		btrfs_tree_unlock(right);
21685f39d397SChris Mason 		free_extent_buffer(right);
2169e66f709bSChris Mason 	}
2170e66f709bSChris Mason 	return 1;
2171e66f709bSChris Mason }
2172e66f709bSChris Mason 
217374123bd7SChris Mason /*
2174d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2175d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
21763c69faecSChris Mason  */
21772ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
2178e02119d5SChris Mason 			     struct btrfs_path *path,
217901f46658SChris Mason 			     int level, int slot, u64 objectid)
21803c69faecSChris Mason {
21815f39d397SChris Mason 	struct extent_buffer *node;
218201f46658SChris Mason 	struct btrfs_disk_key disk_key;
21833c69faecSChris Mason 	u32 nritems;
21843c69faecSChris Mason 	u64 search;
2185a7175319SChris Mason 	u64 target;
21866b80053dSChris Mason 	u64 nread = 0;
21875f39d397SChris Mason 	struct extent_buffer *eb;
21886b80053dSChris Mason 	u32 nr;
21896b80053dSChris Mason 	u32 blocksize;
21906b80053dSChris Mason 	u32 nscan = 0;
2191db94535dSChris Mason 
2192a6b6e75eSChris Mason 	if (level != 1)
21933c69faecSChris Mason 		return;
21943c69faecSChris Mason 
21956702ed49SChris Mason 	if (!path->nodes[level])
21966702ed49SChris Mason 		return;
21976702ed49SChris Mason 
21985f39d397SChris Mason 	node = path->nodes[level];
2199925baeddSChris Mason 
22003c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
22010b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
22020b246afaSJeff Mahoney 	eb = find_extent_buffer(fs_info, search);
22035f39d397SChris Mason 	if (eb) {
22045f39d397SChris Mason 		free_extent_buffer(eb);
22053c69faecSChris Mason 		return;
22063c69faecSChris Mason 	}
22073c69faecSChris Mason 
2208a7175319SChris Mason 	target = search;
22096b80053dSChris Mason 
22105f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
22116b80053dSChris Mason 	nr = slot;
221225b8b936SJosef Bacik 
22133c69faecSChris Mason 	while (1) {
2214e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
22156b80053dSChris Mason 			if (nr == 0)
22163c69faecSChris Mason 				break;
22176b80053dSChris Mason 			nr--;
2218e4058b54SDavid Sterba 		} else if (path->reada == READA_FORWARD) {
22196b80053dSChris Mason 			nr++;
22206b80053dSChris Mason 			if (nr >= nritems)
22216b80053dSChris Mason 				break;
22223c69faecSChris Mason 		}
2223e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
222401f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
222501f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
222601f46658SChris Mason 				break;
222701f46658SChris Mason 		}
22286b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2229a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2230a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
22312ff7e61eSJeff Mahoney 			readahead_tree_block(fs_info, search);
22326b80053dSChris Mason 			nread += blocksize;
22333c69faecSChris Mason 		}
22346b80053dSChris Mason 		nscan++;
2235a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
22366b80053dSChris Mason 			break;
22373c69faecSChris Mason 	}
22383c69faecSChris Mason }
2239925baeddSChris Mason 
22402ff7e61eSJeff Mahoney static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2241b4ce94deSChris Mason 				       struct btrfs_path *path, int level)
2242b4ce94deSChris Mason {
2243b4ce94deSChris Mason 	int slot;
2244b4ce94deSChris Mason 	int nritems;
2245b4ce94deSChris Mason 	struct extent_buffer *parent;
2246b4ce94deSChris Mason 	struct extent_buffer *eb;
2247b4ce94deSChris Mason 	u64 gen;
2248b4ce94deSChris Mason 	u64 block1 = 0;
2249b4ce94deSChris Mason 	u64 block2 = 0;
2250b4ce94deSChris Mason 
22518c594ea8SChris Mason 	parent = path->nodes[level + 1];
2252b4ce94deSChris Mason 	if (!parent)
22530b08851fSJosef Bacik 		return;
2254b4ce94deSChris Mason 
2255b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
22568c594ea8SChris Mason 	slot = path->slots[level + 1];
2257b4ce94deSChris Mason 
2258b4ce94deSChris Mason 	if (slot > 0) {
2259b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2260b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
22610b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block1);
2262b9fab919SChris Mason 		/*
2263b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2264b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2265b9fab919SChris Mason 		 * forever
2266b9fab919SChris Mason 		 */
2267b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2268b4ce94deSChris Mason 			block1 = 0;
2269b4ce94deSChris Mason 		free_extent_buffer(eb);
2270b4ce94deSChris Mason 	}
22718c594ea8SChris Mason 	if (slot + 1 < nritems) {
2272b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2273b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
22740b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block2);
2275b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2276b4ce94deSChris Mason 			block2 = 0;
2277b4ce94deSChris Mason 		free_extent_buffer(eb);
2278b4ce94deSChris Mason 	}
22798c594ea8SChris Mason 
2280b4ce94deSChris Mason 	if (block1)
22812ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block1);
2282b4ce94deSChris Mason 	if (block2)
22832ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block2);
2284b4ce94deSChris Mason }
2285b4ce94deSChris Mason 
2286b4ce94deSChris Mason 
2287b4ce94deSChris Mason /*
2288d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2289d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2290d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2291d397712bSChris Mason  * tree.
2292d352ac68SChris Mason  *
2293d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2294d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2295d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2296d352ac68SChris Mason  *
2297d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2298d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2299d352ac68SChris Mason  */
2300e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2301f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2302f7c79f30SChris Mason 			       int *write_lock_level)
2303925baeddSChris Mason {
2304925baeddSChris Mason 	int i;
2305925baeddSChris Mason 	int skip_level = level;
2306051e1b9fSChris Mason 	int no_skips = 0;
2307925baeddSChris Mason 	struct extent_buffer *t;
2308925baeddSChris Mason 
2309925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2310925baeddSChris Mason 		if (!path->nodes[i])
2311925baeddSChris Mason 			break;
2312925baeddSChris Mason 		if (!path->locks[i])
2313925baeddSChris Mason 			break;
2314051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2315925baeddSChris Mason 			skip_level = i + 1;
2316925baeddSChris Mason 			continue;
2317925baeddSChris Mason 		}
2318051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2319925baeddSChris Mason 			u32 nritems;
2320925baeddSChris Mason 			t = path->nodes[i];
2321925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2322051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2323925baeddSChris Mason 				skip_level = i + 1;
2324925baeddSChris Mason 				continue;
2325925baeddSChris Mason 			}
2326925baeddSChris Mason 		}
2327051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2328051e1b9fSChris Mason 			no_skips = 1;
2329051e1b9fSChris Mason 
2330925baeddSChris Mason 		t = path->nodes[i];
2331d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
2332bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2333925baeddSChris Mason 			path->locks[i] = 0;
2334f7c79f30SChris Mason 			if (write_lock_level &&
2335f7c79f30SChris Mason 			    i > min_write_lock_level &&
2336f7c79f30SChris Mason 			    i <= *write_lock_level) {
2337f7c79f30SChris Mason 				*write_lock_level = i - 1;
2338f7c79f30SChris Mason 			}
2339925baeddSChris Mason 		}
2340925baeddSChris Mason 	}
2341925baeddSChris Mason }
2342925baeddSChris Mason 
23433c69faecSChris Mason /*
2344c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2345c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2346c8c42864SChris Mason  * we return zero and the path is unchanged.
2347c8c42864SChris Mason  *
2348c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2349c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2350c8c42864SChris Mason  */
2351c8c42864SChris Mason static int
2352d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2353c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
2354cda79c54SDavid Sterba 		      const struct btrfs_key *key)
2355c8c42864SChris Mason {
23560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2357c8c42864SChris Mason 	u64 blocknr;
2358c8c42864SChris Mason 	u64 gen;
2359c8c42864SChris Mason 	struct extent_buffer *tmp;
2360581c1760SQu Wenruo 	struct btrfs_key first_key;
236176a05b35SChris Mason 	int ret;
2362581c1760SQu Wenruo 	int parent_level;
2363c8c42864SChris Mason 
2364213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
2365213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
2366213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
2367213ff4b7SNikolay Borisov 	btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
2368c8c42864SChris Mason 
23690b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
2370cb44921aSChris Mason 	if (tmp) {
2371b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2372b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2373448de471SQu Wenruo 			/*
2374448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
2375448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
2376448de471SQu Wenruo 			 * parents (shared tree blocks).
2377448de471SQu Wenruo 			 */
2378e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
2379448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
2380448de471SQu Wenruo 				free_extent_buffer(tmp);
2381448de471SQu Wenruo 				return -EUCLEAN;
2382448de471SQu Wenruo 			}
2383c8c42864SChris Mason 			*eb_ret = tmp;
2384c8c42864SChris Mason 			return 0;
2385c8c42864SChris Mason 		}
2386bdf7c00eSJosef Bacik 
2387cb44921aSChris Mason 		/* the pages were up to date, but we failed
2388cb44921aSChris Mason 		 * the generation number check.  Do a full
2389cb44921aSChris Mason 		 * read for the generation number that is correct.
2390cb44921aSChris Mason 		 * We must do this without dropping locks so
2391cb44921aSChris Mason 		 * we can trust our generation number
2392cb44921aSChris Mason 		 */
2393bd681513SChris Mason 		btrfs_set_path_blocking(p);
2394bd681513SChris Mason 
2395b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2396581c1760SQu Wenruo 		ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
2397bdf7c00eSJosef Bacik 		if (!ret) {
2398cb44921aSChris Mason 			*eb_ret = tmp;
2399cb44921aSChris Mason 			return 0;
2400cb44921aSChris Mason 		}
2401cb44921aSChris Mason 		free_extent_buffer(tmp);
2402b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2403cb44921aSChris Mason 		return -EIO;
2404cb44921aSChris Mason 	}
2405c8c42864SChris Mason 
2406c8c42864SChris Mason 	/*
2407c8c42864SChris Mason 	 * reduce lock contention at high levels
2408c8c42864SChris Mason 	 * of the btree by dropping locks before
240976a05b35SChris Mason 	 * we read.  Don't release the lock on the current
241076a05b35SChris Mason 	 * level because we need to walk this node to figure
241176a05b35SChris Mason 	 * out which blocks to read.
2412c8c42864SChris Mason 	 */
24138c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
24148c594ea8SChris Mason 	btrfs_set_path_blocking(p);
24158c594ea8SChris Mason 
2416e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
24172ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
2418c8c42864SChris Mason 
241976a05b35SChris Mason 	ret = -EAGAIN;
242002a3307aSLiu Bo 	tmp = read_tree_block(fs_info, blocknr, gen, parent_level - 1,
2421581c1760SQu Wenruo 			      &first_key);
242264c043deSLiu Bo 	if (!IS_ERR(tmp)) {
242376a05b35SChris Mason 		/*
242476a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
242576a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
242676a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
242776a05b35SChris Mason 		 * on our EAGAINs.
242876a05b35SChris Mason 		 */
2429e6a1d6fdSLiu Bo 		if (!extent_buffer_uptodate(tmp))
243076a05b35SChris Mason 			ret = -EIO;
2431c8c42864SChris Mason 		free_extent_buffer(tmp);
2432c871b0f2SLiu Bo 	} else {
2433c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
243476a05b35SChris Mason 	}
243502a3307aSLiu Bo 
243602a3307aSLiu Bo 	btrfs_release_path(p);
243776a05b35SChris Mason 	return ret;
2438c8c42864SChris Mason }
2439c8c42864SChris Mason 
2440c8c42864SChris Mason /*
2441c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2442c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2443c8c42864SChris Mason  * the ins_len.
2444c8c42864SChris Mason  *
2445c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2446c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2447c8c42864SChris Mason  * start over
2448c8c42864SChris Mason  */
2449c8c42864SChris Mason static int
2450c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2451c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2452bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2453bd681513SChris Mason 		       int *write_lock_level)
2454c8c42864SChris Mason {
24550b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2456c8c42864SChris Mason 	int ret;
24570b246afaSJeff Mahoney 
2458c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
24590b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2460c8c42864SChris Mason 		int sret;
2461c8c42864SChris Mason 
2462bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2463bd681513SChris Mason 			*write_lock_level = level + 1;
2464bd681513SChris Mason 			btrfs_release_path(p);
2465bd681513SChris Mason 			goto again;
2466bd681513SChris Mason 		}
2467bd681513SChris Mason 
2468c8c42864SChris Mason 		btrfs_set_path_blocking(p);
24692ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2470c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2471c8c42864SChris Mason 
2472c8c42864SChris Mason 		BUG_ON(sret > 0);
2473c8c42864SChris Mason 		if (sret) {
2474c8c42864SChris Mason 			ret = sret;
2475c8c42864SChris Mason 			goto done;
2476c8c42864SChris Mason 		}
2477c8c42864SChris Mason 		b = p->nodes[level];
2478c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
24790b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2480c8c42864SChris Mason 		int sret;
2481c8c42864SChris Mason 
2482bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2483bd681513SChris Mason 			*write_lock_level = level + 1;
2484bd681513SChris Mason 			btrfs_release_path(p);
2485bd681513SChris Mason 			goto again;
2486bd681513SChris Mason 		}
2487bd681513SChris Mason 
2488c8c42864SChris Mason 		btrfs_set_path_blocking(p);
24892ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2490c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2491c8c42864SChris Mason 
2492c8c42864SChris Mason 		if (sret) {
2493c8c42864SChris Mason 			ret = sret;
2494c8c42864SChris Mason 			goto done;
2495c8c42864SChris Mason 		}
2496c8c42864SChris Mason 		b = p->nodes[level];
2497c8c42864SChris Mason 		if (!b) {
2498b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2499c8c42864SChris Mason 			goto again;
2500c8c42864SChris Mason 		}
2501c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2502c8c42864SChris Mason 	}
2503c8c42864SChris Mason 	return 0;
2504c8c42864SChris Mason 
2505c8c42864SChris Mason again:
2506c8c42864SChris Mason 	ret = -EAGAIN;
2507c8c42864SChris Mason done:
2508c8c42864SChris Mason 	return ret;
2509c8c42864SChris Mason }
2510c8c42864SChris Mason 
2511381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2512e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
2513e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
2514e33d5c3dSKelley Nielsen {
2515e33d5c3dSKelley Nielsen 	int ret;
2516e33d5c3dSKelley Nielsen 	struct btrfs_key key;
2517e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
2518381cf658SDavid Sterba 
2519381cf658SDavid Sterba 	ASSERT(path);
25201d4c08e0SDavid Sterba 	ASSERT(found_key);
2521e33d5c3dSKelley Nielsen 
2522e33d5c3dSKelley Nielsen 	key.type = key_type;
2523e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
2524e33d5c3dSKelley Nielsen 	key.offset = ioff;
2525e33d5c3dSKelley Nielsen 
2526e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
25271d4c08e0SDavid Sterba 	if (ret < 0)
2528e33d5c3dSKelley Nielsen 		return ret;
2529e33d5c3dSKelley Nielsen 
2530e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
2531e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2532e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
2533e33d5c3dSKelley Nielsen 		if (ret)
2534e33d5c3dSKelley Nielsen 			return ret;
2535e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
2536e33d5c3dSKelley Nielsen 	}
2537e33d5c3dSKelley Nielsen 
2538e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2539e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
2540e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
2541e33d5c3dSKelley Nielsen 		return 1;
2542e33d5c3dSKelley Nielsen 
2543e33d5c3dSKelley Nielsen 	return 0;
2544e33d5c3dSKelley Nielsen }
2545e33d5c3dSKelley Nielsen 
25461fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
25471fc28d8eSLiu Bo 							struct btrfs_path *p,
25481fc28d8eSLiu Bo 							int write_lock_level)
25491fc28d8eSLiu Bo {
25501fc28d8eSLiu Bo 	struct btrfs_fs_info *fs_info = root->fs_info;
25511fc28d8eSLiu Bo 	struct extent_buffer *b;
25521fc28d8eSLiu Bo 	int root_lock;
25531fc28d8eSLiu Bo 	int level = 0;
25541fc28d8eSLiu Bo 
25551fc28d8eSLiu Bo 	/* We try very hard to do read locks on the root */
25561fc28d8eSLiu Bo 	root_lock = BTRFS_READ_LOCK;
25571fc28d8eSLiu Bo 
25581fc28d8eSLiu Bo 	if (p->search_commit_root) {
2559be6821f8SFilipe Manana 		/*
2560be6821f8SFilipe Manana 		 * The commit roots are read only so we always do read locks,
2561be6821f8SFilipe Manana 		 * and we always must hold the commit_root_sem when doing
2562be6821f8SFilipe Manana 		 * searches on them, the only exception is send where we don't
2563be6821f8SFilipe Manana 		 * want to block transaction commits for a long time, so
2564be6821f8SFilipe Manana 		 * we need to clone the commit root in order to avoid races
2565be6821f8SFilipe Manana 		 * with transaction commits that create a snapshot of one of
2566be6821f8SFilipe Manana 		 * the roots used by a send operation.
2567be6821f8SFilipe Manana 		 */
2568be6821f8SFilipe Manana 		if (p->need_commit_sem) {
25691fc28d8eSLiu Bo 			down_read(&fs_info->commit_root_sem);
2570be6821f8SFilipe Manana 			b = btrfs_clone_extent_buffer(root->commit_root);
2571be6821f8SFilipe Manana 			up_read(&fs_info->commit_root_sem);
2572be6821f8SFilipe Manana 			if (!b)
2573be6821f8SFilipe Manana 				return ERR_PTR(-ENOMEM);
2574be6821f8SFilipe Manana 
2575be6821f8SFilipe Manana 		} else {
25761fc28d8eSLiu Bo 			b = root->commit_root;
257767439dadSDavid Sterba 			atomic_inc(&b->refs);
2578be6821f8SFilipe Manana 		}
25791fc28d8eSLiu Bo 		level = btrfs_header_level(b);
2580f9ddfd05SLiu Bo 		/*
2581f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
2582f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
2583f9ddfd05SLiu Bo 		 */
2584f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
25851fc28d8eSLiu Bo 
25861fc28d8eSLiu Bo 		goto out;
25871fc28d8eSLiu Bo 	}
25881fc28d8eSLiu Bo 
25891fc28d8eSLiu Bo 	if (p->skip_locking) {
25901fc28d8eSLiu Bo 		b = btrfs_root_node(root);
25911fc28d8eSLiu Bo 		level = btrfs_header_level(b);
25921fc28d8eSLiu Bo 		goto out;
25931fc28d8eSLiu Bo 	}
25941fc28d8eSLiu Bo 
25951fc28d8eSLiu Bo 	/*
2596662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
2597662c653bSLiu Bo 	 * lock.
2598662c653bSLiu Bo 	 */
2599662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
2600662c653bSLiu Bo 		/*
2601662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
2602662c653bSLiu Bo 		 * have it read locked
26031fc28d8eSLiu Bo 		 */
26041fc28d8eSLiu Bo 		b = btrfs_read_lock_root_node(root);
26051fc28d8eSLiu Bo 		level = btrfs_header_level(b);
26061fc28d8eSLiu Bo 		if (level > write_lock_level)
26071fc28d8eSLiu Bo 			goto out;
26081fc28d8eSLiu Bo 
2609662c653bSLiu Bo 		/* Whoops, must trade for write lock */
26101fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
26111fc28d8eSLiu Bo 		free_extent_buffer(b);
2612662c653bSLiu Bo 	}
2613662c653bSLiu Bo 
26141fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
26151fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
26161fc28d8eSLiu Bo 
26171fc28d8eSLiu Bo 	/* The level might have changed, check again */
26181fc28d8eSLiu Bo 	level = btrfs_header_level(b);
26191fc28d8eSLiu Bo 
26201fc28d8eSLiu Bo out:
26211fc28d8eSLiu Bo 	p->nodes[level] = b;
26221fc28d8eSLiu Bo 	if (!p->skip_locking)
26231fc28d8eSLiu Bo 		p->locks[level] = root_lock;
26241fc28d8eSLiu Bo 	/*
26251fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
26261fc28d8eSLiu Bo 	 */
26271fc28d8eSLiu Bo 	return b;
26281fc28d8eSLiu Bo }
26291fc28d8eSLiu Bo 
26301fc28d8eSLiu Bo 
2631c8c42864SChris Mason /*
26324271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
26334271eceaSNikolay Borisov  * modifications to preserve tree invariants.
263474123bd7SChris Mason  *
26354271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
26364271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
26374271eceaSNikolay Borisov  * @root:	The root node of the tree
26384271eceaSNikolay Borisov  * @key:	The key we are looking for
26394271eceaSNikolay Borisov  * @ins_len:	Indicates purpose of search, for inserts it is 1, for
26404271eceaSNikolay Borisov  *		deletions it's -1. 0 for plain searches
26414271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
26424271eceaSNikolay Borisov  *		when modifying the tree.
264397571fd0SChris Mason  *
26444271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
26454271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
26464271eceaSNikolay Borisov  *
26474271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
26484271eceaSNikolay Borisov  * of the path (level 0)
26494271eceaSNikolay Borisov  *
26504271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
26514271eceaSNikolay Borisov  * points to the slot where it should be inserted
26524271eceaSNikolay Borisov  *
26534271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
26544271eceaSNikolay Borisov  * is returned
265574123bd7SChris Mason  */
2656310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2657310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2658310712b2SOmar Sandoval 		      int ins_len, int cow)
2659be0e5c09SChris Mason {
26605f39d397SChris Mason 	struct extent_buffer *b;
2661be0e5c09SChris Mason 	int slot;
2662be0e5c09SChris Mason 	int ret;
266333c66f43SYan Zheng 	int err;
2664be0e5c09SChris Mason 	int level;
2665925baeddSChris Mason 	int lowest_unlock = 1;
2666bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2667bd681513SChris Mason 	int write_lock_level = 0;
26689f3a7427SChris Mason 	u8 lowest_level = 0;
2669f7c79f30SChris Mason 	int min_write_lock_level;
2670d7396f07SFilipe David Borba Manana 	int prev_cmp;
26719f3a7427SChris Mason 
26726702ed49SChris Mason 	lowest_level = p->lowest_level;
2673323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
267422b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2675eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
267625179201SJosef Bacik 
2677bd681513SChris Mason 	if (ins_len < 0) {
2678925baeddSChris Mason 		lowest_unlock = 2;
267965b51a00SChris Mason 
2680bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2681bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2682bd681513SChris Mason 		 * for those levels as well
2683bd681513SChris Mason 		 */
2684bd681513SChris Mason 		write_lock_level = 2;
2685bd681513SChris Mason 	} else if (ins_len > 0) {
2686bd681513SChris Mason 		/*
2687bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2688bd681513SChris Mason 		 * level 1 so we can update keys
2689bd681513SChris Mason 		 */
2690bd681513SChris Mason 		write_lock_level = 1;
2691bd681513SChris Mason 	}
2692bd681513SChris Mason 
2693bd681513SChris Mason 	if (!cow)
2694bd681513SChris Mason 		write_lock_level = -1;
2695bd681513SChris Mason 
269609a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2697bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2698bd681513SChris Mason 
2699f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2700f7c79f30SChris Mason 
2701bb803951SChris Mason again:
2702d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
27031fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2704be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2705be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2706be6821f8SFilipe Manana 		goto done;
2707be6821f8SFilipe Manana 	}
2708925baeddSChris Mason 
2709eb60ceacSChris Mason 	while (b) {
2710f624d976SQu Wenruo 		int dec = 0;
2711f624d976SQu Wenruo 
27125f39d397SChris Mason 		level = btrfs_header_level(b);
271365b51a00SChris Mason 
271402217ed2SChris Mason 		if (cow) {
27159ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
27169ea2c7c9SNikolay Borisov 
2717c8c42864SChris Mason 			/*
2718c8c42864SChris Mason 			 * if we don't really need to cow this block
2719c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2720c8c42864SChris Mason 			 * so we test it here
2721c8c42864SChris Mason 			 */
272264c12921SJeff Mahoney 			if (!should_cow_block(trans, root, b)) {
272364c12921SJeff Mahoney 				trans->dirty = true;
272465b51a00SChris Mason 				goto cow_done;
272564c12921SJeff Mahoney 			}
27265d4f98a2SYan Zheng 
2727bd681513SChris Mason 			/*
2728bd681513SChris Mason 			 * must have write locks on this node and the
2729bd681513SChris Mason 			 * parent
2730bd681513SChris Mason 			 */
27315124e00eSJosef Bacik 			if (level > write_lock_level ||
27325124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
27335124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
27345124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2735bd681513SChris Mason 				write_lock_level = level + 1;
2736bd681513SChris Mason 				btrfs_release_path(p);
2737bd681513SChris Mason 				goto again;
2738bd681513SChris Mason 			}
2739bd681513SChris Mason 
2740160f4089SFilipe Manana 			btrfs_set_path_blocking(p);
27419ea2c7c9SNikolay Borisov 			if (last_level)
27429ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
27439ea2c7c9SNikolay Borisov 						      &b);
27449ea2c7c9SNikolay Borisov 			else
274533c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2746e20d96d6SChris Mason 						      p->nodes[level + 1],
27479fa8cfe7SChris Mason 						      p->slots[level + 1], &b);
274833c66f43SYan Zheng 			if (err) {
274933c66f43SYan Zheng 				ret = err;
275065b51a00SChris Mason 				goto done;
275154aa1f4dSChris Mason 			}
275202217ed2SChris Mason 		}
275365b51a00SChris Mason cow_done:
2754eb60ceacSChris Mason 		p->nodes[level] = b;
275552398340SLiu Bo 		/*
275652398340SLiu Bo 		 * Leave path with blocking locks to avoid massive
275752398340SLiu Bo 		 * lock context switch, this is made on purpose.
275852398340SLiu Bo 		 */
2759b4ce94deSChris Mason 
2760b4ce94deSChris Mason 		/*
2761b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2762b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2763b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2764b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2765b4ce94deSChris Mason 		 *
2766eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2767eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2768eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2769eb653de1SFilipe David Borba Manana 		 * we're operating on.
2770b4ce94deSChris Mason 		 */
2771eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2772eb653de1SFilipe David Borba Manana 			int u = level + 1;
2773eb653de1SFilipe David Borba Manana 
2774eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2775eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2776eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2777eb653de1SFilipe David Borba Manana 			}
2778eb653de1SFilipe David Borba Manana 		}
2779b4ce94deSChris Mason 
2780995e9a16SNikolay Borisov 		/*
2781995e9a16SNikolay Borisov 		 * If btrfs_bin_search returns an exact match (prev_cmp == 0)
2782995e9a16SNikolay Borisov 		 * we can safely assume the target key will always be in slot 0
2783995e9a16SNikolay Borisov 		 * on lower levels due to the invariants BTRFS' btree provides,
2784995e9a16SNikolay Borisov 		 * namely that a btrfs_key_ptr entry always points to the
2785995e9a16SNikolay Borisov 		 * lowest key in the child node, thus we can skip searching
2786995e9a16SNikolay Borisov 		 * lower levels
2787995e9a16SNikolay Borisov 		 */
2788995e9a16SNikolay Borisov 		if (prev_cmp == 0) {
2789995e9a16SNikolay Borisov 			slot = 0;
2790995e9a16SNikolay Borisov 			ret = 0;
2791995e9a16SNikolay Borisov 		} else {
2792995e9a16SNikolay Borisov 			ret = btrfs_bin_search(b, key, &slot);
2793995e9a16SNikolay Borisov 			prev_cmp = ret;
2794415b35a5SLiu Bo 			if (ret < 0)
2795415b35a5SLiu Bo 				goto done;
2796995e9a16SNikolay Borisov 		}
2797b4ce94deSChris Mason 
2798f624d976SQu Wenruo 		if (level == 0) {
2799be0e5c09SChris Mason 			p->slots[level] = slot;
280087b29b20SYan Zheng 			if (ins_len > 0 &&
2801e902baacSDavid Sterba 			    btrfs_leaf_free_space(b) < ins_len) {
2802bd681513SChris Mason 				if (write_lock_level < 1) {
2803bd681513SChris Mason 					write_lock_level = 1;
2804bd681513SChris Mason 					btrfs_release_path(p);
2805bd681513SChris Mason 					goto again;
2806bd681513SChris Mason 				}
2807bd681513SChris Mason 
2808b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
280933c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2810cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2811b4ce94deSChris Mason 
281233c66f43SYan Zheng 				BUG_ON(err > 0);
281333c66f43SYan Zheng 				if (err) {
281433c66f43SYan Zheng 					ret = err;
281565b51a00SChris Mason 					goto done;
281665b51a00SChris Mason 				}
28175c680ed6SChris Mason 			}
2818459931ecSChris Mason 			if (!p->search_for_split)
2819f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
28204b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
282165b51a00SChris Mason 			goto done;
282265b51a00SChris Mason 		}
2823f624d976SQu Wenruo 		if (ret && slot > 0) {
2824f624d976SQu Wenruo 			dec = 1;
2825f624d976SQu Wenruo 			slot--;
2826f624d976SQu Wenruo 		}
2827f624d976SQu Wenruo 		p->slots[level] = slot;
2828f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2829f624d976SQu Wenruo 					     &write_lock_level);
2830f624d976SQu Wenruo 		if (err == -EAGAIN)
2831f624d976SQu Wenruo 			goto again;
2832f624d976SQu Wenruo 		if (err) {
2833f624d976SQu Wenruo 			ret = err;
2834f624d976SQu Wenruo 			goto done;
2835f624d976SQu Wenruo 		}
2836f624d976SQu Wenruo 		b = p->nodes[level];
2837f624d976SQu Wenruo 		slot = p->slots[level];
2838f624d976SQu Wenruo 
2839f624d976SQu Wenruo 		/*
2840f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2841f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2842f624d976SQu Wenruo 		 * the parent
2843f624d976SQu Wenruo 		 */
2844f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2845f624d976SQu Wenruo 			write_lock_level = level + 1;
2846f624d976SQu Wenruo 			btrfs_release_path(p);
2847f624d976SQu Wenruo 			goto again;
2848f624d976SQu Wenruo 		}
2849f624d976SQu Wenruo 
2850f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2851f624d976SQu Wenruo 			  &write_lock_level);
2852f624d976SQu Wenruo 
2853f624d976SQu Wenruo 		if (level == lowest_level) {
2854f624d976SQu Wenruo 			if (dec)
2855f624d976SQu Wenruo 				p->slots[level]++;
2856f624d976SQu Wenruo 			goto done;
2857f624d976SQu Wenruo 		}
2858f624d976SQu Wenruo 
2859f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2860f624d976SQu Wenruo 		if (err == -EAGAIN)
2861f624d976SQu Wenruo 			goto again;
2862f624d976SQu Wenruo 		if (err) {
2863f624d976SQu Wenruo 			ret = err;
2864f624d976SQu Wenruo 			goto done;
2865f624d976SQu Wenruo 		}
2866f624d976SQu Wenruo 
2867f624d976SQu Wenruo 		if (!p->skip_locking) {
2868f624d976SQu Wenruo 			level = btrfs_header_level(b);
2869f624d976SQu Wenruo 			if (level <= write_lock_level) {
2870f624d976SQu Wenruo 				if (!btrfs_try_tree_write_lock(b)) {
2871f624d976SQu Wenruo 					btrfs_set_path_blocking(p);
2872f624d976SQu Wenruo 					btrfs_tree_lock(b);
2873f624d976SQu Wenruo 				}
2874f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2875f624d976SQu Wenruo 			} else {
2876f624d976SQu Wenruo 				if (!btrfs_tree_read_lock_atomic(b)) {
2877f624d976SQu Wenruo 					btrfs_set_path_blocking(p);
2878f624d976SQu Wenruo 					btrfs_tree_read_lock(b);
2879f624d976SQu Wenruo 				}
2880f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2881f624d976SQu Wenruo 			}
2882f624d976SQu Wenruo 			p->nodes[level] = b;
2883f624d976SQu Wenruo 		}
288465b51a00SChris Mason 	}
288565b51a00SChris Mason 	ret = 1;
288665b51a00SChris Mason done:
2887b4ce94deSChris Mason 	/*
2888b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2889b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2890b4ce94deSChris Mason 	 */
2891b9473439SChris Mason 	if (!p->leave_spinning)
2892b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
28935f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2894b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2895be0e5c09SChris Mason 	return ret;
2896be0e5c09SChris Mason }
2897be0e5c09SChris Mason 
289874123bd7SChris Mason /*
28995d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
29005d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
29015d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
29025d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
29035d9e75c4SJan Schmidt  *
29045d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
29055d9e75c4SJan Schmidt  *
29065d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
29075d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
29085d9e75c4SJan Schmidt  */
2909310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
29105d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
29115d9e75c4SJan Schmidt {
29120b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29135d9e75c4SJan Schmidt 	struct extent_buffer *b;
29145d9e75c4SJan Schmidt 	int slot;
29155d9e75c4SJan Schmidt 	int ret;
29165d9e75c4SJan Schmidt 	int err;
29175d9e75c4SJan Schmidt 	int level;
29185d9e75c4SJan Schmidt 	int lowest_unlock = 1;
29195d9e75c4SJan Schmidt 	u8 lowest_level = 0;
29205d9e75c4SJan Schmidt 
29215d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
29225d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
29235d9e75c4SJan Schmidt 
29245d9e75c4SJan Schmidt 	if (p->search_commit_root) {
29255d9e75c4SJan Schmidt 		BUG_ON(time_seq);
29265d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
29275d9e75c4SJan Schmidt 	}
29285d9e75c4SJan Schmidt 
29295d9e75c4SJan Schmidt again:
29305d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
2931315bed43SNikolay Borisov 	if (!b) {
2932315bed43SNikolay Borisov 		ret = -EIO;
2933315bed43SNikolay Borisov 		goto done;
2934315bed43SNikolay Borisov 	}
29355d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
29365d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
29375d9e75c4SJan Schmidt 
29385d9e75c4SJan Schmidt 	while (b) {
2939abe9339dSQu Wenruo 		int dec = 0;
2940abe9339dSQu Wenruo 
29415d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
29425d9e75c4SJan Schmidt 		p->nodes[level] = b;
29435d9e75c4SJan Schmidt 
29445d9e75c4SJan Schmidt 		/*
29455d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
29465d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
29475d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
29485d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
29495d9e75c4SJan Schmidt 		 */
29505d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
29515d9e75c4SJan Schmidt 
2952995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
2953cbca7d59SFilipe Manana 		if (ret < 0)
2954cbca7d59SFilipe Manana 			goto done;
29555d9e75c4SJan Schmidt 
2956abe9339dSQu Wenruo 		if (level == 0) {
2957abe9339dSQu Wenruo 			p->slots[level] = slot;
2958abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2959abe9339dSQu Wenruo 			goto done;
2960abe9339dSQu Wenruo 		}
2961abe9339dSQu Wenruo 
29625d9e75c4SJan Schmidt 		if (ret && slot > 0) {
29635d9e75c4SJan Schmidt 			dec = 1;
2964abe9339dSQu Wenruo 			slot--;
29655d9e75c4SJan Schmidt 		}
29665d9e75c4SJan Schmidt 		p->slots[level] = slot;
29675d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
29685d9e75c4SJan Schmidt 
29695d9e75c4SJan Schmidt 		if (level == lowest_level) {
29705d9e75c4SJan Schmidt 			if (dec)
29715d9e75c4SJan Schmidt 				p->slots[level]++;
29725d9e75c4SJan Schmidt 			goto done;
29735d9e75c4SJan Schmidt 		}
29745d9e75c4SJan Schmidt 
2975abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
29765d9e75c4SJan Schmidt 		if (err == -EAGAIN)
29775d9e75c4SJan Schmidt 			goto again;
29785d9e75c4SJan Schmidt 		if (err) {
29795d9e75c4SJan Schmidt 			ret = err;
29805d9e75c4SJan Schmidt 			goto done;
29815d9e75c4SJan Schmidt 		}
29825d9e75c4SJan Schmidt 
29835d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
298465e99c43SNikolay Borisov 		if (!btrfs_tree_read_lock_atomic(b)) {
29855d9e75c4SJan Schmidt 			btrfs_set_path_blocking(p);
29865d9e75c4SJan Schmidt 			btrfs_tree_read_lock(b);
29875d9e75c4SJan Schmidt 		}
29880b246afaSJeff Mahoney 		b = tree_mod_log_rewind(fs_info, p, b, time_seq);
2989db7f3436SJosef Bacik 		if (!b) {
2990db7f3436SJosef Bacik 			ret = -ENOMEM;
2991db7f3436SJosef Bacik 			goto done;
2992db7f3436SJosef Bacik 		}
29935d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
29945d9e75c4SJan Schmidt 		p->nodes[level] = b;
29955d9e75c4SJan Schmidt 	}
29965d9e75c4SJan Schmidt 	ret = 1;
29975d9e75c4SJan Schmidt done:
29985d9e75c4SJan Schmidt 	if (!p->leave_spinning)
29995d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
30005d9e75c4SJan Schmidt 	if (ret < 0)
30015d9e75c4SJan Schmidt 		btrfs_release_path(p);
30025d9e75c4SJan Schmidt 
30035d9e75c4SJan Schmidt 	return ret;
30045d9e75c4SJan Schmidt }
30055d9e75c4SJan Schmidt 
30065d9e75c4SJan Schmidt /*
30072f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
30082f38b3e1SArne Jansen  * instead the next or previous item should be returned.
30092f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
30102f38b3e1SArne Jansen  * otherwise.
30112f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
30122f38b3e1SArne Jansen  * return the next lower instead.
30132f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
30142f38b3e1SArne Jansen  * return the next higher instead.
30152f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
30162f38b3e1SArne Jansen  * < 0 on error
30172f38b3e1SArne Jansen  */
30182f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
3019310712b2SOmar Sandoval 			       const struct btrfs_key *key,
3020310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
3021310712b2SOmar Sandoval 			       int return_any)
30222f38b3e1SArne Jansen {
30232f38b3e1SArne Jansen 	int ret;
30242f38b3e1SArne Jansen 	struct extent_buffer *leaf;
30252f38b3e1SArne Jansen 
30262f38b3e1SArne Jansen again:
30272f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
30282f38b3e1SArne Jansen 	if (ret <= 0)
30292f38b3e1SArne Jansen 		return ret;
30302f38b3e1SArne Jansen 	/*
30312f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
30322f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
30332f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
30342f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
30352f38b3e1SArne Jansen 	 * item.
30362f38b3e1SArne Jansen 	 */
30372f38b3e1SArne Jansen 	leaf = p->nodes[0];
30382f38b3e1SArne Jansen 
30392f38b3e1SArne Jansen 	if (find_higher) {
30402f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
30412f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
30422f38b3e1SArne Jansen 			if (ret <= 0)
30432f38b3e1SArne Jansen 				return ret;
30442f38b3e1SArne Jansen 			if (!return_any)
30452f38b3e1SArne Jansen 				return 1;
30462f38b3e1SArne Jansen 			/*
30472f38b3e1SArne Jansen 			 * no higher item found, return the next
30482f38b3e1SArne Jansen 			 * lower instead
30492f38b3e1SArne Jansen 			 */
30502f38b3e1SArne Jansen 			return_any = 0;
30512f38b3e1SArne Jansen 			find_higher = 0;
30522f38b3e1SArne Jansen 			btrfs_release_path(p);
30532f38b3e1SArne Jansen 			goto again;
30542f38b3e1SArne Jansen 		}
30552f38b3e1SArne Jansen 	} else {
30562f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
30572f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
3058e6793769SArne Jansen 			if (ret < 0)
30592f38b3e1SArne Jansen 				return ret;
3060e6793769SArne Jansen 			if (!ret) {
306123c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
306223c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
306323c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
3064e6793769SArne Jansen 				return 0;
3065e6793769SArne Jansen 			}
30662f38b3e1SArne Jansen 			if (!return_any)
30672f38b3e1SArne Jansen 				return 1;
30682f38b3e1SArne Jansen 			/*
30692f38b3e1SArne Jansen 			 * no lower item found, return the next
30702f38b3e1SArne Jansen 			 * higher instead
30712f38b3e1SArne Jansen 			 */
30722f38b3e1SArne Jansen 			return_any = 0;
30732f38b3e1SArne Jansen 			find_higher = 1;
30742f38b3e1SArne Jansen 			btrfs_release_path(p);
30752f38b3e1SArne Jansen 			goto again;
3076e6793769SArne Jansen 		} else {
30772f38b3e1SArne Jansen 			--p->slots[0];
30782f38b3e1SArne Jansen 		}
30792f38b3e1SArne Jansen 	}
30802f38b3e1SArne Jansen 	return 0;
30812f38b3e1SArne Jansen }
30822f38b3e1SArne Jansen 
30832f38b3e1SArne Jansen /*
308474123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
308574123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
308674123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
308774123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
308874123bd7SChris Mason  * higher levels
3089aa5d6bedSChris Mason  *
309074123bd7SChris Mason  */
3091b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
30925f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
3093be0e5c09SChris Mason {
3094be0e5c09SChris Mason 	int i;
30955f39d397SChris Mason 	struct extent_buffer *t;
30960e82bcfeSDavid Sterba 	int ret;
30975f39d397SChris Mason 
3098234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3099be0e5c09SChris Mason 		int tslot = path->slots[i];
31000e82bcfeSDavid Sterba 
3101eb60ceacSChris Mason 		if (!path->nodes[i])
3102be0e5c09SChris Mason 			break;
31035f39d397SChris Mason 		t = path->nodes[i];
31040e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
31050e82bcfeSDavid Sterba 				GFP_ATOMIC);
31060e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
31075f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
3108d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
3109be0e5c09SChris Mason 		if (tslot != 0)
3110be0e5c09SChris Mason 			break;
3111be0e5c09SChris Mason 	}
3112be0e5c09SChris Mason }
3113be0e5c09SChris Mason 
311474123bd7SChris Mason /*
311531840ae1SZheng Yan  * update item key.
311631840ae1SZheng Yan  *
311731840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
311831840ae1SZheng Yan  * that the new key won't break the order
311931840ae1SZheng Yan  */
3120b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3121b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
3122310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
312331840ae1SZheng Yan {
312431840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
312531840ae1SZheng Yan 	struct extent_buffer *eb;
312631840ae1SZheng Yan 	int slot;
312731840ae1SZheng Yan 
312831840ae1SZheng Yan 	eb = path->nodes[0];
312931840ae1SZheng Yan 	slot = path->slots[0];
313031840ae1SZheng Yan 	if (slot > 0) {
313131840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
31327c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
31337c15d410SQu Wenruo 			btrfs_crit(fs_info,
31347c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
31357c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
31367c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
31377c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
31387c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
31397c15d410SQu Wenruo 				   new_key->offset);
31407c15d410SQu Wenruo 			btrfs_print_leaf(eb);
31417c15d410SQu Wenruo 			BUG();
31427c15d410SQu Wenruo 		}
314331840ae1SZheng Yan 	}
314431840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
314531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
31467c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
31477c15d410SQu Wenruo 			btrfs_crit(fs_info,
31487c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
31497c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
31507c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
31517c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
31527c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
31537c15d410SQu Wenruo 				   new_key->offset);
31547c15d410SQu Wenruo 			btrfs_print_leaf(eb);
31557c15d410SQu Wenruo 			BUG();
31567c15d410SQu Wenruo 		}
315731840ae1SZheng Yan 	}
315831840ae1SZheng Yan 
315931840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
316031840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
316131840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
316231840ae1SZheng Yan 	if (slot == 0)
3163b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
316431840ae1SZheng Yan }
316531840ae1SZheng Yan 
316631840ae1SZheng Yan /*
3167*d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
3168*d16c702fSQu Wenruo  *
3169*d16c702fSQu Wenruo  * Return true if something is wrong.
3170*d16c702fSQu Wenruo  * Return false if everything is fine.
3171*d16c702fSQu Wenruo  *
3172*d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
3173*d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
3174*d16c702fSQu Wenruo  *
3175*d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
3176*d16c702fSQu Wenruo  * --------------------------------------------------------------
3177*d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
3178*d16c702fSQu Wenruo  *
3179*d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
3180*d16c702fSQu Wenruo  * key in leaf @right is 7.
3181*d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
3182*d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
3183*d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
3184*d16c702fSQu Wenruo  * key of @right.
3185*d16c702fSQu Wenruo  */
3186*d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
3187*d16c702fSQu Wenruo 			       struct extent_buffer *right)
3188*d16c702fSQu Wenruo {
3189*d16c702fSQu Wenruo 	struct btrfs_key left_last;
3190*d16c702fSQu Wenruo 	struct btrfs_key right_first;
3191*d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
3192*d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
3193*d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
3194*d16c702fSQu Wenruo 
3195*d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
3196*d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
3197*d16c702fSQu Wenruo 		return false;
3198*d16c702fSQu Wenruo 
3199*d16c702fSQu Wenruo 	if (level) {
3200*d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
3201*d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
3202*d16c702fSQu Wenruo 	} else {
3203*d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
3204*d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
3205*d16c702fSQu Wenruo 	}
3206*d16c702fSQu Wenruo 
3207*d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
3208*d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
3209*d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
3210*d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
3211*d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
3212*d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
3213*d16c702fSQu Wenruo 		return true;
3214*d16c702fSQu Wenruo 	}
3215*d16c702fSQu Wenruo 	return false;
3216*d16c702fSQu Wenruo }
3217*d16c702fSQu Wenruo 
3218*d16c702fSQu Wenruo /*
321974123bd7SChris Mason  * try to push data from one node into the next node left in the
322079f95c82SChris Mason  * tree.
3221aa5d6bedSChris Mason  *
3222aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3223aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
322474123bd7SChris Mason  */
322598ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
32262ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
3227971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
3228be0e5c09SChris Mason {
3229d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3230be0e5c09SChris Mason 	int push_items = 0;
3231bb803951SChris Mason 	int src_nritems;
3232bb803951SChris Mason 	int dst_nritems;
3233aa5d6bedSChris Mason 	int ret = 0;
3234be0e5c09SChris Mason 
32355f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32365f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
32370b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
32387bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32397bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
324054aa1f4dSChris Mason 
3241bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
3242971a1f66SChris Mason 		return 1;
3243971a1f66SChris Mason 
3244d397712bSChris Mason 	if (push_items <= 0)
3245be0e5c09SChris Mason 		return 1;
3246be0e5c09SChris Mason 
3247bce4eae9SChris Mason 	if (empty) {
3248971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
3249bce4eae9SChris Mason 		if (push_items < src_nritems) {
3250bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
3251bce4eae9SChris Mason 			 * we aren't going to empty it
3252bce4eae9SChris Mason 			 */
3253bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
3254bce4eae9SChris Mason 				if (push_items <= 8)
3255bce4eae9SChris Mason 					return 1;
3256bce4eae9SChris Mason 				push_items -= 8;
3257bce4eae9SChris Mason 			}
3258bce4eae9SChris Mason 		}
3259bce4eae9SChris Mason 	} else
3260bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
326179f95c82SChris Mason 
3262*d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
3263*d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
3264*d16c702fSQu Wenruo 		ret = -EUCLEAN;
3265*d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
3266*d16c702fSQu Wenruo 		return ret;
3267*d16c702fSQu Wenruo 	}
3268ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
32695de865eeSFilipe David Borba Manana 	if (ret) {
327066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32715de865eeSFilipe David Borba Manana 		return ret;
32725de865eeSFilipe David Borba Manana 	}
32735f39d397SChris Mason 	copy_extent_buffer(dst, src,
32745f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
32755f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3276123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
32775f39d397SChris Mason 
3278bb803951SChris Mason 	if (push_items < src_nritems) {
327957911b8bSJan Schmidt 		/*
3280bf1d3425SDavid Sterba 		 * Don't call tree_mod_log_insert_move here, key removal was
3281bf1d3425SDavid Sterba 		 * already fully logged by tree_mod_log_eb_copy above.
328257911b8bSJan Schmidt 		 */
32835f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
32845f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3285e2fa7227SChris Mason 				      (src_nritems - push_items) *
3286123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3287bb803951SChris Mason 	}
32885f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
32895f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
32905f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
32915f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
329231840ae1SZheng Yan 
3293bb803951SChris Mason 	return ret;
3294be0e5c09SChris Mason }
3295be0e5c09SChris Mason 
329697571fd0SChris Mason /*
329779f95c82SChris Mason  * try to push data from one node into the next node right in the
329879f95c82SChris Mason  * tree.
329979f95c82SChris Mason  *
330079f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
330179f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
330279f95c82SChris Mason  *
330379f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
330479f95c82SChris Mason  */
33055f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
33065f39d397SChris Mason 			      struct extent_buffer *dst,
33075f39d397SChris Mason 			      struct extent_buffer *src)
330879f95c82SChris Mason {
330955d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
331079f95c82SChris Mason 	int push_items = 0;
331179f95c82SChris Mason 	int max_push;
331279f95c82SChris Mason 	int src_nritems;
331379f95c82SChris Mason 	int dst_nritems;
331479f95c82SChris Mason 	int ret = 0;
331579f95c82SChris Mason 
33167bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
33177bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
33187bb86316SChris Mason 
33195f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
33205f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
33210b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3322d397712bSChris Mason 	if (push_items <= 0)
332379f95c82SChris Mason 		return 1;
3324bce4eae9SChris Mason 
3325d397712bSChris Mason 	if (src_nritems < 4)
3326bce4eae9SChris Mason 		return 1;
332779f95c82SChris Mason 
332879f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
332979f95c82SChris Mason 	/* don't try to empty the node */
3330d397712bSChris Mason 	if (max_push >= src_nritems)
333179f95c82SChris Mason 		return 1;
3332252c38f0SYan 
333379f95c82SChris Mason 	if (max_push < push_items)
333479f95c82SChris Mason 		push_items = max_push;
333579f95c82SChris Mason 
3336*d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
3337*d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
3338*d16c702fSQu Wenruo 		ret = -EUCLEAN;
3339*d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
3340*d16c702fSQu Wenruo 		return ret;
3341*d16c702fSQu Wenruo 	}
3342bf1d3425SDavid Sterba 	ret = tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
3343bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
33445f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
33455f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
33465f39d397SChris Mason 				      (dst_nritems) *
33475f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3348d6025579SChris Mason 
3349ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
3350ed874f0dSDavid Sterba 				   push_items);
33515de865eeSFilipe David Borba Manana 	if (ret) {
335266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
33535de865eeSFilipe David Borba Manana 		return ret;
33545de865eeSFilipe David Borba Manana 	}
33555f39d397SChris Mason 	copy_extent_buffer(dst, src,
33565f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
33575f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3358123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
335979f95c82SChris Mason 
33605f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
33615f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
336279f95c82SChris Mason 
33635f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
33645f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
336531840ae1SZheng Yan 
336679f95c82SChris Mason 	return ret;
336779f95c82SChris Mason }
336879f95c82SChris Mason 
336979f95c82SChris Mason /*
337097571fd0SChris Mason  * helper function to insert a new root level in the tree.
337197571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
337297571fd0SChris Mason  * point to the existing root
3373aa5d6bedSChris Mason  *
3374aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
337597571fd0SChris Mason  */
3376d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
33775f39d397SChris Mason 			   struct btrfs_root *root,
3378fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
337974123bd7SChris Mason {
33800b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
33817bb86316SChris Mason 	u64 lower_gen;
33825f39d397SChris Mason 	struct extent_buffer *lower;
33835f39d397SChris Mason 	struct extent_buffer *c;
3384925baeddSChris Mason 	struct extent_buffer *old;
33855f39d397SChris Mason 	struct btrfs_disk_key lower_key;
3386d9d19a01SDavid Sterba 	int ret;
33875c680ed6SChris Mason 
33885c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
33895c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
33905c680ed6SChris Mason 
33917bb86316SChris Mason 	lower = path->nodes[level-1];
33927bb86316SChris Mason 	if (level == 1)
33937bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
33947bb86316SChris Mason 	else
33957bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
33967bb86316SChris Mason 
3397a6279470SFilipe Manana 	c = alloc_tree_block_no_bg_flush(trans, root, 0, &lower_key, level,
3398a6279470SFilipe Manana 					 root->node->start, 0);
33995f39d397SChris Mason 	if (IS_ERR(c))
34005f39d397SChris Mason 		return PTR_ERR(c);
3401925baeddSChris Mason 
34020b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3403f0486c68SYan, Zheng 
34045f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
34055f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3406db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
34077bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
340831840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
34097bb86316SChris Mason 
34107bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
34115f39d397SChris Mason 
34125f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3413d5719762SChris Mason 
3414925baeddSChris Mason 	old = root->node;
3415d9d19a01SDavid Sterba 	ret = tree_mod_log_insert_root(root->node, c, 0);
3416d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
3417240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3418925baeddSChris Mason 
3419925baeddSChris Mason 	/* the super has an extra ref to root->node */
3420925baeddSChris Mason 	free_extent_buffer(old);
3421925baeddSChris Mason 
34220b86a832SChris Mason 	add_root_to_dirty_list(root);
342367439dadSDavid Sterba 	atomic_inc(&c->refs);
34245f39d397SChris Mason 	path->nodes[level] = c;
342595449a16Schandan 	path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
342674123bd7SChris Mason 	path->slots[level] = 0;
342774123bd7SChris Mason 	return 0;
342874123bd7SChris Mason }
34295c680ed6SChris Mason 
34305c680ed6SChris Mason /*
34315c680ed6SChris Mason  * worker function to insert a single pointer in a node.
34325c680ed6SChris Mason  * the node should have enough room for the pointer already
343397571fd0SChris Mason  *
34345c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
34355c680ed6SChris Mason  * blocknr is the block the key points to.
34365c680ed6SChris Mason  */
3437143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
34386ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
3439143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3440c3e06965SJan Schmidt 		       int slot, int level)
34415c680ed6SChris Mason {
34425f39d397SChris Mason 	struct extent_buffer *lower;
34435c680ed6SChris Mason 	int nritems;
3444f3ea38daSJan Schmidt 	int ret;
34455c680ed6SChris Mason 
34465c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3447f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
34485f39d397SChris Mason 	lower = path->nodes[level];
34495f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3450c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
34516ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
345274123bd7SChris Mason 	if (slot != nritems) {
3453bf1d3425SDavid Sterba 		if (level) {
3454bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(lower, slot + 1, slot,
3455a446a979SDavid Sterba 					nritems - slot);
3456bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
3457bf1d3425SDavid Sterba 		}
34585f39d397SChris Mason 		memmove_extent_buffer(lower,
34595f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
34605f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3461123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
346274123bd7SChris Mason 	}
3463c3e06965SJan Schmidt 	if (level) {
3464e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3465e09c2efeSDavid Sterba 				GFP_NOFS);
3466f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3467f3ea38daSJan Schmidt 	}
34685f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3469db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
347074493f7aSChris Mason 	WARN_ON(trans->transid == 0);
347174493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
34725f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
34735f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
347474123bd7SChris Mason }
347574123bd7SChris Mason 
347697571fd0SChris Mason /*
347797571fd0SChris Mason  * split the node at the specified level in path in two.
347897571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
347997571fd0SChris Mason  *
348097571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
348197571fd0SChris Mason  * left and right, if either one works, it returns right away.
3482aa5d6bedSChris Mason  *
3483aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
348497571fd0SChris Mason  */
3485e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3486e02119d5SChris Mason 			       struct btrfs_root *root,
3487e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3488be0e5c09SChris Mason {
34890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
34905f39d397SChris Mason 	struct extent_buffer *c;
34915f39d397SChris Mason 	struct extent_buffer *split;
34925f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3493be0e5c09SChris Mason 	int mid;
34945c680ed6SChris Mason 	int ret;
34957518a238SChris Mason 	u32 c_nritems;
3496be0e5c09SChris Mason 
34975f39d397SChris Mason 	c = path->nodes[level];
34987bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
34995f39d397SChris Mason 	if (c == root->node) {
3500d9abbf1cSJan Schmidt 		/*
350190f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
350290f8d62eSJan Schmidt 		 *
3503fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
350490f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
350590f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
350690f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
350790f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
350890f8d62eSJan Schmidt 		 * other tree_mod_log users.
3509d9abbf1cSJan Schmidt 		 */
3510fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
35115c680ed6SChris Mason 		if (ret)
35125c680ed6SChris Mason 			return ret;
3513b3612421SChris Mason 	} else {
3514e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
35155f39d397SChris Mason 		c = path->nodes[level];
35165f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
35170b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3518e66f709bSChris Mason 			return 0;
351954aa1f4dSChris Mason 		if (ret < 0)
352054aa1f4dSChris Mason 			return ret;
35215c680ed6SChris Mason 	}
3522e66f709bSChris Mason 
35235f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
35245d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
35255d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
35267bb86316SChris Mason 
3527a6279470SFilipe Manana 	split = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, level,
3528a6279470SFilipe Manana 					     c->start, 0);
35295f39d397SChris Mason 	if (IS_ERR(split))
35305f39d397SChris Mason 		return PTR_ERR(split);
353154aa1f4dSChris Mason 
35320b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3533bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
35345f39d397SChris Mason 
3535ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
35365de865eeSFilipe David Borba Manana 	if (ret) {
353766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
35385de865eeSFilipe David Borba Manana 		return ret;
35395de865eeSFilipe David Borba Manana 	}
35405f39d397SChris Mason 	copy_extent_buffer(split, c,
35415f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
35425f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3543123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
35445f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
35455f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3546aa5d6bedSChris Mason 	ret = 0;
3547aa5d6bedSChris Mason 
35485f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
35495f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
35505f39d397SChris Mason 
35516ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
3552c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3553aa5d6bedSChris Mason 
35545de08d7dSChris Mason 	if (path->slots[level] >= mid) {
35555c680ed6SChris Mason 		path->slots[level] -= mid;
3556925baeddSChris Mason 		btrfs_tree_unlock(c);
35575f39d397SChris Mason 		free_extent_buffer(c);
35585f39d397SChris Mason 		path->nodes[level] = split;
35595c680ed6SChris Mason 		path->slots[level + 1] += 1;
3560eb60ceacSChris Mason 	} else {
3561925baeddSChris Mason 		btrfs_tree_unlock(split);
35625f39d397SChris Mason 		free_extent_buffer(split);
3563be0e5c09SChris Mason 	}
3564aa5d6bedSChris Mason 	return ret;
3565be0e5c09SChris Mason }
3566be0e5c09SChris Mason 
356774123bd7SChris Mason /*
356874123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
356974123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
357074123bd7SChris Mason  * space used both by the item structs and the item data
357174123bd7SChris Mason  */
35725f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3573be0e5c09SChris Mason {
357441be1f3bSJosef Bacik 	struct btrfs_item *start_item;
357541be1f3bSJosef Bacik 	struct btrfs_item *end_item;
3576be0e5c09SChris Mason 	int data_len;
35775f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3578d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3579be0e5c09SChris Mason 
3580be0e5c09SChris Mason 	if (!nr)
3581be0e5c09SChris Mason 		return 0;
3582dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
3583dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
3584a31356b9SDavid Sterba 	data_len = btrfs_item_offset(l, start_item) +
3585a31356b9SDavid Sterba 		   btrfs_item_size(l, start_item);
3586a31356b9SDavid Sterba 	data_len = data_len - btrfs_item_offset(l, end_item);
35870783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3588d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3589be0e5c09SChris Mason 	return data_len;
3590be0e5c09SChris Mason }
3591be0e5c09SChris Mason 
359274123bd7SChris Mason /*
3593d4dbff95SChris Mason  * The space between the end of the leaf items and
3594d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3595d4dbff95SChris Mason  * the leaf has left for both items and data
3596d4dbff95SChris Mason  */
3597e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
3598d4dbff95SChris Mason {
3599e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
36005f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
36015f39d397SChris Mason 	int ret;
36020b246afaSJeff Mahoney 
36030b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
36045f39d397SChris Mason 	if (ret < 0) {
36050b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3606efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3607da17066cSJeff Mahoney 			   ret,
36080b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
36095f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
36105f39d397SChris Mason 	}
36115f39d397SChris Mason 	return ret;
3612d4dbff95SChris Mason }
3613d4dbff95SChris Mason 
361499d8f83cSChris Mason /*
361599d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
361699d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
361799d8f83cSChris Mason  */
3618f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
361944871b1bSChris Mason 				      int data_size, int empty,
362044871b1bSChris Mason 				      struct extent_buffer *right,
362199d8f83cSChris Mason 				      int free_space, u32 left_nritems,
362299d8f83cSChris Mason 				      u32 min_slot)
362300ec4c51SChris Mason {
3624f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
36255f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
362644871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3627cfed81a0SChris Mason 	struct btrfs_map_token token;
36285f39d397SChris Mason 	struct btrfs_disk_key disk_key;
362900ec4c51SChris Mason 	int slot;
363034a38218SChris Mason 	u32 i;
363100ec4c51SChris Mason 	int push_space = 0;
363200ec4c51SChris Mason 	int push_items = 0;
36330783fcfcSChris Mason 	struct btrfs_item *item;
363434a38218SChris Mason 	u32 nr;
36357518a238SChris Mason 	u32 right_nritems;
36365f39d397SChris Mason 	u32 data_end;
3637db94535dSChris Mason 	u32 this_item_size;
363800ec4c51SChris Mason 
363934a38218SChris Mason 	if (empty)
364034a38218SChris Mason 		nr = 0;
364134a38218SChris Mason 	else
364299d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
364334a38218SChris Mason 
364431840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
364587b29b20SYan Zheng 		push_space += data_size;
364631840ae1SZheng Yan 
364744871b1bSChris Mason 	slot = path->slots[1];
364834a38218SChris Mason 	i = left_nritems - 1;
364934a38218SChris Mason 	while (i >= nr) {
3650dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3651db94535dSChris Mason 
365231840ae1SZheng Yan 		if (!empty && push_items > 0) {
365331840ae1SZheng Yan 			if (path->slots[0] > i)
365431840ae1SZheng Yan 				break;
365531840ae1SZheng Yan 			if (path->slots[0] == i) {
3656e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3657e902baacSDavid Sterba 
365831840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
365931840ae1SZheng Yan 					break;
366031840ae1SZheng Yan 			}
366131840ae1SZheng Yan 		}
366231840ae1SZheng Yan 
366300ec4c51SChris Mason 		if (path->slots[0] == i)
366487b29b20SYan Zheng 			push_space += data_size;
3665db94535dSChris Mason 
3666db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3667db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
366800ec4c51SChris Mason 			break;
366931840ae1SZheng Yan 
367000ec4c51SChris Mason 		push_items++;
3671db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
367234a38218SChris Mason 		if (i == 0)
367334a38218SChris Mason 			break;
367434a38218SChris Mason 		i--;
3675db94535dSChris Mason 	}
36765f39d397SChris Mason 
3677925baeddSChris Mason 	if (push_items == 0)
3678925baeddSChris Mason 		goto out_unlock;
36795f39d397SChris Mason 
36806c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
36815f39d397SChris Mason 
368200ec4c51SChris Mason 	/* push left to right */
36835f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
368434a38218SChris Mason 
36855f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
36868f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
36875f39d397SChris Mason 
368800ec4c51SChris Mason 	/* make room in the right data area */
36898f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
36905f39d397SChris Mason 	memmove_extent_buffer(right,
36913d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
36923d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
36930b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
36945f39d397SChris Mason 
369500ec4c51SChris Mason 	/* copy from the left data area */
36963d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
36970b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
36988f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3699d6025579SChris Mason 		     push_space);
37005f39d397SChris Mason 
37015f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
37025f39d397SChris Mason 			      btrfs_item_nr_offset(0),
37030783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
37045f39d397SChris Mason 
370500ec4c51SChris Mason 	/* copy the items from left to right */
37065f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
37075f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
37080783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
370900ec4c51SChris Mason 
371000ec4c51SChris Mason 	/* update the item pointers */
3711c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
37127518a238SChris Mason 	right_nritems += push_items;
37135f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
37140b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
37157518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
3716dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3717cc4c13d5SDavid Sterba 		push_space -= btrfs_token_item_size(&token, item);
3718cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, push_space);
3719db94535dSChris Mason 	}
3720db94535dSChris Mason 
37217518a238SChris Mason 	left_nritems -= push_items;
37225f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
372300ec4c51SChris Mason 
372434a38218SChris Mason 	if (left_nritems)
37255f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3726f0486c68SYan, Zheng 	else
37276a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3728f0486c68SYan, Zheng 
37295f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3730a429e513SChris Mason 
37315f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
37325f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3733d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
373402217ed2SChris Mason 
373500ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
37367518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
37377518a238SChris Mason 		path->slots[0] -= left_nritems;
3738925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
37396a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3740925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
37415f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
37425f39d397SChris Mason 		path->nodes[0] = right;
374300ec4c51SChris Mason 		path->slots[1] += 1;
374400ec4c51SChris Mason 	} else {
3745925baeddSChris Mason 		btrfs_tree_unlock(right);
37465f39d397SChris Mason 		free_extent_buffer(right);
374700ec4c51SChris Mason 	}
374800ec4c51SChris Mason 	return 0;
3749925baeddSChris Mason 
3750925baeddSChris Mason out_unlock:
3751925baeddSChris Mason 	btrfs_tree_unlock(right);
3752925baeddSChris Mason 	free_extent_buffer(right);
3753925baeddSChris Mason 	return 1;
375400ec4c51SChris Mason }
3755925baeddSChris Mason 
375600ec4c51SChris Mason /*
375744871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
375874123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
375944871b1bSChris Mason  *
376044871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
376144871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
376299d8f83cSChris Mason  *
376399d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
376499d8f83cSChris Mason  * push any slot lower than min_slot
376574123bd7SChris Mason  */
376644871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
376799d8f83cSChris Mason 			   *root, struct btrfs_path *path,
376899d8f83cSChris Mason 			   int min_data_size, int data_size,
376999d8f83cSChris Mason 			   int empty, u32 min_slot)
3770be0e5c09SChris Mason {
377144871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
377244871b1bSChris Mason 	struct extent_buffer *right;
377344871b1bSChris Mason 	struct extent_buffer *upper;
377444871b1bSChris Mason 	int slot;
377544871b1bSChris Mason 	int free_space;
377644871b1bSChris Mason 	u32 left_nritems;
377744871b1bSChris Mason 	int ret;
377844871b1bSChris Mason 
377944871b1bSChris Mason 	if (!path->nodes[1])
378044871b1bSChris Mason 		return 1;
378144871b1bSChris Mason 
378244871b1bSChris Mason 	slot = path->slots[1];
378344871b1bSChris Mason 	upper = path->nodes[1];
378444871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
378544871b1bSChris Mason 		return 1;
378644871b1bSChris Mason 
378744871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
378844871b1bSChris Mason 
37894b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3790fb770ae4SLiu Bo 	/*
3791fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3792fb770ae4SLiu Bo 	 * no big deal, just return.
3793fb770ae4SLiu Bo 	 */
3794fb770ae4SLiu Bo 	if (IS_ERR(right))
379591ca338dSTsutomu Itoh 		return 1;
379691ca338dSTsutomu Itoh 
379744871b1bSChris Mason 	btrfs_tree_lock(right);
37988bead258SDavid Sterba 	btrfs_set_lock_blocking_write(right);
379944871b1bSChris Mason 
3800e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
380144871b1bSChris Mason 	if (free_space < data_size)
380244871b1bSChris Mason 		goto out_unlock;
380344871b1bSChris Mason 
380444871b1bSChris Mason 	/* cow and double check */
380544871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
380644871b1bSChris Mason 			      slot + 1, &right);
380744871b1bSChris Mason 	if (ret)
380844871b1bSChris Mason 		goto out_unlock;
380944871b1bSChris Mason 
3810e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
381144871b1bSChris Mason 	if (free_space < data_size)
381244871b1bSChris Mason 		goto out_unlock;
381344871b1bSChris Mason 
381444871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
381544871b1bSChris Mason 	if (left_nritems == 0)
381644871b1bSChris Mason 		goto out_unlock;
381744871b1bSChris Mason 
3818*d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3819*d16c702fSQu Wenruo 		ret = -EUCLEAN;
3820*d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3821*d16c702fSQu Wenruo 		free_extent_buffer(right);
3822*d16c702fSQu Wenruo 		return ret;
3823*d16c702fSQu Wenruo 	}
38242ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
38252ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
38262ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
38272ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
382852042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
38292ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
38302ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
38312ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
38322ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
38332ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
38342ef1fed2SFilipe David Borba Manana 		return 0;
38352ef1fed2SFilipe David Borba Manana 	}
38362ef1fed2SFilipe David Borba Manana 
3837f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
383899d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
383944871b1bSChris Mason out_unlock:
384044871b1bSChris Mason 	btrfs_tree_unlock(right);
384144871b1bSChris Mason 	free_extent_buffer(right);
384244871b1bSChris Mason 	return 1;
384344871b1bSChris Mason }
384444871b1bSChris Mason 
384544871b1bSChris Mason /*
384644871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
384744871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
384899d8f83cSChris Mason  *
384999d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
385099d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
385199d8f83cSChris Mason  * items
385244871b1bSChris Mason  */
38538087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
385444871b1bSChris Mason 				     int empty, struct extent_buffer *left,
385599d8f83cSChris Mason 				     int free_space, u32 right_nritems,
385699d8f83cSChris Mason 				     u32 max_slot)
385744871b1bSChris Mason {
38588087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
38595f39d397SChris Mason 	struct btrfs_disk_key disk_key;
38605f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3861be0e5c09SChris Mason 	int i;
3862be0e5c09SChris Mason 	int push_space = 0;
3863be0e5c09SChris Mason 	int push_items = 0;
38640783fcfcSChris Mason 	struct btrfs_item *item;
38657518a238SChris Mason 	u32 old_left_nritems;
386634a38218SChris Mason 	u32 nr;
3867aa5d6bedSChris Mason 	int ret = 0;
3868db94535dSChris Mason 	u32 this_item_size;
3869db94535dSChris Mason 	u32 old_left_item_size;
3870cfed81a0SChris Mason 	struct btrfs_map_token token;
3871cfed81a0SChris Mason 
387234a38218SChris Mason 	if (empty)
387399d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
387434a38218SChris Mason 	else
387599d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
387634a38218SChris Mason 
387734a38218SChris Mason 	for (i = 0; i < nr; i++) {
3878dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3879db94535dSChris Mason 
388031840ae1SZheng Yan 		if (!empty && push_items > 0) {
388131840ae1SZheng Yan 			if (path->slots[0] < i)
388231840ae1SZheng Yan 				break;
388331840ae1SZheng Yan 			if (path->slots[0] == i) {
3884e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3885e902baacSDavid Sterba 
388631840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
388731840ae1SZheng Yan 					break;
388831840ae1SZheng Yan 			}
388931840ae1SZheng Yan 		}
389031840ae1SZheng Yan 
3891be0e5c09SChris Mason 		if (path->slots[0] == i)
389287b29b20SYan Zheng 			push_space += data_size;
3893db94535dSChris Mason 
3894db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3895db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3896be0e5c09SChris Mason 			break;
3897db94535dSChris Mason 
3898be0e5c09SChris Mason 		push_items++;
3899db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3900be0e5c09SChris Mason 	}
3901db94535dSChris Mason 
3902be0e5c09SChris Mason 	if (push_items == 0) {
3903925baeddSChris Mason 		ret = 1;
3904925baeddSChris Mason 		goto out;
3905be0e5c09SChris Mason 	}
3906fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
39075f39d397SChris Mason 
3908be0e5c09SChris Mason 	/* push data from right to left */
39095f39d397SChris Mason 	copy_extent_buffer(left, right,
39105f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
39115f39d397SChris Mason 			   btrfs_item_nr_offset(0),
39125f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
39135f39d397SChris Mason 
39140b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
39155f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
39165f39d397SChris Mason 
39173d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
39188f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
39193d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
39205f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3921be0e5c09SChris Mason 		     push_space);
39225f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
392387b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3924eb60ceacSChris Mason 
3925c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
3926db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3927be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
39285f39d397SChris Mason 		u32 ioff;
3929db94535dSChris Mason 
3930dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3931db94535dSChris Mason 
3932cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
3933cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item,
3934cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3935be0e5c09SChris Mason 	}
39365f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3937be0e5c09SChris Mason 
3938be0e5c09SChris Mason 	/* fixup right node */
393931b1a2bdSJulia Lawall 	if (push_items > right_nritems)
394031b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3941d397712bSChris Mason 		       right_nritems);
394234a38218SChris Mason 
394334a38218SChris Mason 	if (push_items < right_nritems) {
39445f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
39458f881e8cSDavid Sterba 						  leaf_data_end(right);
39463d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
39470b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
39483d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
39498f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
39505f39d397SChris Mason 
39515f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
39525f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
39535f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
39540783fcfcSChris Mason 			     sizeof(struct btrfs_item));
395534a38218SChris Mason 	}
3956c82f823cSDavid Sterba 
3957c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3958eef1c494SYan 	right_nritems -= push_items;
3959eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
39600b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
39615f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
3962dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3963db94535dSChris Mason 
3964cc4c13d5SDavid Sterba 		push_space = push_space - btrfs_token_item_size(&token, item);
3965cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, push_space);
3966db94535dSChris Mason 	}
3967eb60ceacSChris Mason 
39685f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
396934a38218SChris Mason 	if (right_nritems)
39705f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3971f0486c68SYan, Zheng 	else
39726a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3973098f59c2SChris Mason 
39745f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3975b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3976be0e5c09SChris Mason 
3977be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3978be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3979be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3980925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
39815f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
39825f39d397SChris Mason 		path->nodes[0] = left;
3983be0e5c09SChris Mason 		path->slots[1] -= 1;
3984be0e5c09SChris Mason 	} else {
3985925baeddSChris Mason 		btrfs_tree_unlock(left);
39865f39d397SChris Mason 		free_extent_buffer(left);
3987be0e5c09SChris Mason 		path->slots[0] -= push_items;
3988be0e5c09SChris Mason 	}
3989eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3990aa5d6bedSChris Mason 	return ret;
3991925baeddSChris Mason out:
3992925baeddSChris Mason 	btrfs_tree_unlock(left);
3993925baeddSChris Mason 	free_extent_buffer(left);
3994925baeddSChris Mason 	return ret;
3995be0e5c09SChris Mason }
3996be0e5c09SChris Mason 
399774123bd7SChris Mason /*
399844871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
399944871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
400099d8f83cSChris Mason  *
400199d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
400299d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
400399d8f83cSChris Mason  * items
400444871b1bSChris Mason  */
400544871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
400699d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
400799d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
400844871b1bSChris Mason {
400944871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
401044871b1bSChris Mason 	struct extent_buffer *left;
401144871b1bSChris Mason 	int slot;
401244871b1bSChris Mason 	int free_space;
401344871b1bSChris Mason 	u32 right_nritems;
401444871b1bSChris Mason 	int ret = 0;
401544871b1bSChris Mason 
401644871b1bSChris Mason 	slot = path->slots[1];
401744871b1bSChris Mason 	if (slot == 0)
401844871b1bSChris Mason 		return 1;
401944871b1bSChris Mason 	if (!path->nodes[1])
402044871b1bSChris Mason 		return 1;
402144871b1bSChris Mason 
402244871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
402344871b1bSChris Mason 	if (right_nritems == 0)
402444871b1bSChris Mason 		return 1;
402544871b1bSChris Mason 
402644871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
402744871b1bSChris Mason 
40284b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
4029fb770ae4SLiu Bo 	/*
4030fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
4031fb770ae4SLiu Bo 	 * no big deal, just return.
4032fb770ae4SLiu Bo 	 */
4033fb770ae4SLiu Bo 	if (IS_ERR(left))
403491ca338dSTsutomu Itoh 		return 1;
403591ca338dSTsutomu Itoh 
403644871b1bSChris Mason 	btrfs_tree_lock(left);
40378bead258SDavid Sterba 	btrfs_set_lock_blocking_write(left);
403844871b1bSChris Mason 
4039e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
404044871b1bSChris Mason 	if (free_space < data_size) {
404144871b1bSChris Mason 		ret = 1;
404244871b1bSChris Mason 		goto out;
404344871b1bSChris Mason 	}
404444871b1bSChris Mason 
404544871b1bSChris Mason 	/* cow and double check */
404644871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
404744871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
404844871b1bSChris Mason 	if (ret) {
404944871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
405079787eaaSJeff Mahoney 		if (ret == -ENOSPC)
405144871b1bSChris Mason 			ret = 1;
405244871b1bSChris Mason 		goto out;
405344871b1bSChris Mason 	}
405444871b1bSChris Mason 
4055e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
405644871b1bSChris Mason 	if (free_space < data_size) {
405744871b1bSChris Mason 		ret = 1;
405844871b1bSChris Mason 		goto out;
405944871b1bSChris Mason 	}
406044871b1bSChris Mason 
4061*d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
4062*d16c702fSQu Wenruo 		ret = -EUCLEAN;
4063*d16c702fSQu Wenruo 		goto out;
4064*d16c702fSQu Wenruo 	}
40658087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
406699d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
406799d8f83cSChris Mason 			       max_slot);
406844871b1bSChris Mason out:
406944871b1bSChris Mason 	btrfs_tree_unlock(left);
407044871b1bSChris Mason 	free_extent_buffer(left);
407144871b1bSChris Mason 	return ret;
407244871b1bSChris Mason }
407344871b1bSChris Mason 
407444871b1bSChris Mason /*
407574123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
407674123bd7SChris Mason  * available for the resulting leaf level of the path.
407774123bd7SChris Mason  */
4078143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
407944871b1bSChris Mason 				    struct btrfs_path *path,
408044871b1bSChris Mason 				    struct extent_buffer *l,
408144871b1bSChris Mason 				    struct extent_buffer *right,
408244871b1bSChris Mason 				    int slot, int mid, int nritems)
4083be0e5c09SChris Mason {
408494f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
4085be0e5c09SChris Mason 	int data_copy_size;
4086be0e5c09SChris Mason 	int rt_data_off;
4087be0e5c09SChris Mason 	int i;
4088d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
4089cfed81a0SChris Mason 	struct btrfs_map_token token;
4090cfed81a0SChris Mason 
40915f39d397SChris Mason 	nritems = nritems - mid;
40925f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
40938f881e8cSDavid Sterba 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
40945f39d397SChris Mason 
40955f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
40965f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
40975f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
40985f39d397SChris Mason 
40995f39d397SChris Mason 	copy_extent_buffer(right, l,
41003d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
41013d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
41028f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
410374123bd7SChris Mason 
41040b246afaSJeff Mahoney 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
41055f39d397SChris Mason 
4106c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
41075f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
4108dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
4109db94535dSChris Mason 		u32 ioff;
4110db94535dSChris Mason 
4111cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
4112cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff + rt_data_off);
41130783fcfcSChris Mason 	}
411474123bd7SChris Mason 
41155f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
41165f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
41176ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
41185f39d397SChris Mason 
41195f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
41205f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
4121eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
41225f39d397SChris Mason 
4123be0e5c09SChris Mason 	if (mid <= slot) {
4124925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
41255f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
41265f39d397SChris Mason 		path->nodes[0] = right;
4127be0e5c09SChris Mason 		path->slots[0] -= mid;
4128be0e5c09SChris Mason 		path->slots[1] += 1;
4129925baeddSChris Mason 	} else {
4130925baeddSChris Mason 		btrfs_tree_unlock(right);
41315f39d397SChris Mason 		free_extent_buffer(right);
4132925baeddSChris Mason 	}
41335f39d397SChris Mason 
4134eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
413544871b1bSChris Mason }
413644871b1bSChris Mason 
413744871b1bSChris Mason /*
413899d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
413999d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
414099d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
414199d8f83cSChris Mason  *          A                 B                 C
414299d8f83cSChris Mason  *
414399d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
414499d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
414599d8f83cSChris Mason  * completely.
414699d8f83cSChris Mason  */
414799d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
414899d8f83cSChris Mason 					  struct btrfs_root *root,
414999d8f83cSChris Mason 					  struct btrfs_path *path,
415099d8f83cSChris Mason 					  int data_size)
415199d8f83cSChris Mason {
415299d8f83cSChris Mason 	int ret;
415399d8f83cSChris Mason 	int progress = 0;
415499d8f83cSChris Mason 	int slot;
415599d8f83cSChris Mason 	u32 nritems;
41565a4267caSFilipe David Borba Manana 	int space_needed = data_size;
415799d8f83cSChris Mason 
415899d8f83cSChris Mason 	slot = path->slots[0];
41595a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
4160e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
416199d8f83cSChris Mason 
416299d8f83cSChris Mason 	/*
416399d8f83cSChris Mason 	 * try to push all the items after our slot into the
416499d8f83cSChris Mason 	 * right leaf
416599d8f83cSChris Mason 	 */
41665a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
416799d8f83cSChris Mason 	if (ret < 0)
416899d8f83cSChris Mason 		return ret;
416999d8f83cSChris Mason 
417099d8f83cSChris Mason 	if (ret == 0)
417199d8f83cSChris Mason 		progress++;
417299d8f83cSChris Mason 
417399d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
417499d8f83cSChris Mason 	/*
417599d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
417699d8f83cSChris Mason 	 * we've done so we're done
417799d8f83cSChris Mason 	 */
417899d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
417999d8f83cSChris Mason 		return 0;
418099d8f83cSChris Mason 
4181e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
418299d8f83cSChris Mason 		return 0;
418399d8f83cSChris Mason 
418499d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
418599d8f83cSChris Mason 	slot = path->slots[0];
4186263d3995SFilipe Manana 	space_needed = data_size;
4187263d3995SFilipe Manana 	if (slot > 0)
4188e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
41895a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
419099d8f83cSChris Mason 	if (ret < 0)
419199d8f83cSChris Mason 		return ret;
419299d8f83cSChris Mason 
419399d8f83cSChris Mason 	if (ret == 0)
419499d8f83cSChris Mason 		progress++;
419599d8f83cSChris Mason 
419699d8f83cSChris Mason 	if (progress)
419799d8f83cSChris Mason 		return 0;
419899d8f83cSChris Mason 	return 1;
419999d8f83cSChris Mason }
420099d8f83cSChris Mason 
420199d8f83cSChris Mason /*
420244871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
420344871b1bSChris Mason  * available for the resulting leaf level of the path.
420444871b1bSChris Mason  *
420544871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
420644871b1bSChris Mason  */
420744871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
420844871b1bSChris Mason 			       struct btrfs_root *root,
4209310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
421044871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
421144871b1bSChris Mason 			       int extend)
421244871b1bSChris Mason {
42135d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
421444871b1bSChris Mason 	struct extent_buffer *l;
421544871b1bSChris Mason 	u32 nritems;
421644871b1bSChris Mason 	int mid;
421744871b1bSChris Mason 	int slot;
421844871b1bSChris Mason 	struct extent_buffer *right;
4219b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
422044871b1bSChris Mason 	int ret = 0;
422144871b1bSChris Mason 	int wret;
42225d4f98a2SYan Zheng 	int split;
422344871b1bSChris Mason 	int num_doubles = 0;
422499d8f83cSChris Mason 	int tried_avoid_double = 0;
422544871b1bSChris Mason 
4226a5719521SYan, Zheng 	l = path->nodes[0];
4227a5719521SYan, Zheng 	slot = path->slots[0];
4228a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
42290b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4230a5719521SYan, Zheng 		return -EOVERFLOW;
4231a5719521SYan, Zheng 
423244871b1bSChris Mason 	/* first try to make some room by pushing left and right */
423333157e05SLiu Bo 	if (data_size && path->nodes[1]) {
42345a4267caSFilipe David Borba Manana 		int space_needed = data_size;
42355a4267caSFilipe David Borba Manana 
42365a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
4237e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
42385a4267caSFilipe David Borba Manana 
42395a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
42405a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
424144871b1bSChris Mason 		if (wret < 0)
424244871b1bSChris Mason 			return wret;
424344871b1bSChris Mason 		if (wret) {
4244263d3995SFilipe Manana 			space_needed = data_size;
4245263d3995SFilipe Manana 			if (slot > 0)
4246e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
42475a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
42485a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
424944871b1bSChris Mason 			if (wret < 0)
425044871b1bSChris Mason 				return wret;
425144871b1bSChris Mason 		}
425244871b1bSChris Mason 		l = path->nodes[0];
425344871b1bSChris Mason 
425444871b1bSChris Mason 		/* did the pushes work? */
4255e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
425644871b1bSChris Mason 			return 0;
425744871b1bSChris Mason 	}
425844871b1bSChris Mason 
425944871b1bSChris Mason 	if (!path->nodes[1]) {
4260fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
426144871b1bSChris Mason 		if (ret)
426244871b1bSChris Mason 			return ret;
426344871b1bSChris Mason 	}
426444871b1bSChris Mason again:
42655d4f98a2SYan Zheng 	split = 1;
426644871b1bSChris Mason 	l = path->nodes[0];
426744871b1bSChris Mason 	slot = path->slots[0];
426844871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
426944871b1bSChris Mason 	mid = (nritems + 1) / 2;
427044871b1bSChris Mason 
42715d4f98a2SYan Zheng 	if (mid <= slot) {
42725d4f98a2SYan Zheng 		if (nritems == 1 ||
42735d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
42740b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42755d4f98a2SYan Zheng 			if (slot >= nritems) {
42765d4f98a2SYan Zheng 				split = 0;
42775d4f98a2SYan Zheng 			} else {
42785d4f98a2SYan Zheng 				mid = slot;
42795d4f98a2SYan Zheng 				if (mid != nritems &&
42805d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42810b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
428299d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
428399d8f83cSChris Mason 						goto push_for_double;
42845d4f98a2SYan Zheng 					split = 2;
42855d4f98a2SYan Zheng 				}
42865d4f98a2SYan Zheng 			}
42875d4f98a2SYan Zheng 		}
42885d4f98a2SYan Zheng 	} else {
42895d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
42900b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42915d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
42925d4f98a2SYan Zheng 				split = 0;
42935d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
42945d4f98a2SYan Zheng 				mid = 1;
42955d4f98a2SYan Zheng 			} else {
42965d4f98a2SYan Zheng 				mid = slot;
42975d4f98a2SYan Zheng 				if (mid != nritems &&
42985d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42990b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
430099d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
430199d8f83cSChris Mason 						goto push_for_double;
43025d4f98a2SYan Zheng 					split = 2;
43035d4f98a2SYan Zheng 				}
43045d4f98a2SYan Zheng 			}
43055d4f98a2SYan Zheng 		}
43065d4f98a2SYan Zheng 	}
43075d4f98a2SYan Zheng 
43085d4f98a2SYan Zheng 	if (split == 0)
43095d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
43105d4f98a2SYan Zheng 	else
43115d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
43125d4f98a2SYan Zheng 
4313a6279470SFilipe Manana 	right = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, 0,
4314a6279470SFilipe Manana 					     l->start, 0);
4315f0486c68SYan, Zheng 	if (IS_ERR(right))
431644871b1bSChris Mason 		return PTR_ERR(right);
4317f0486c68SYan, Zheng 
43180b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
431944871b1bSChris Mason 
43205d4f98a2SYan Zheng 	if (split == 0) {
432144871b1bSChris Mason 		if (mid <= slot) {
432244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
43236ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
43242ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
432544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
432644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
432744871b1bSChris Mason 			path->nodes[0] = right;
432844871b1bSChris Mason 			path->slots[0] = 0;
432944871b1bSChris Mason 			path->slots[1] += 1;
433044871b1bSChris Mason 		} else {
433144871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
43326ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
43332ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
433444871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
433544871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
433644871b1bSChris Mason 			path->nodes[0] = right;
433744871b1bSChris Mason 			path->slots[0] = 0;
4338143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4339b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
43405d4f98a2SYan Zheng 		}
4341196e0249SLiu Bo 		/*
4342196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
4343196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4344196e0249SLiu Bo 		 * the content of ins_len to 'right'.
4345196e0249SLiu Bo 		 */
434644871b1bSChris Mason 		return ret;
434744871b1bSChris Mason 	}
434844871b1bSChris Mason 
434994f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
435044871b1bSChris Mason 
43515d4f98a2SYan Zheng 	if (split == 2) {
4352cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4353cc0c5538SChris Mason 		num_doubles++;
4354cc0c5538SChris Mason 		goto again;
43553326d1b0SChris Mason 	}
435644871b1bSChris Mason 
4357143bede5SJeff Mahoney 	return 0;
435899d8f83cSChris Mason 
435999d8f83cSChris Mason push_for_double:
436099d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
436199d8f83cSChris Mason 	tried_avoid_double = 1;
4362e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
436399d8f83cSChris Mason 		return 0;
436499d8f83cSChris Mason 	goto again;
4365be0e5c09SChris Mason }
4366be0e5c09SChris Mason 
4367ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4368ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4369ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4370ad48fd75SYan, Zheng {
4371ad48fd75SYan, Zheng 	struct btrfs_key key;
4372ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4373ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4374ad48fd75SYan, Zheng 	u64 extent_len = 0;
4375ad48fd75SYan, Zheng 	u32 item_size;
4376ad48fd75SYan, Zheng 	int ret;
4377ad48fd75SYan, Zheng 
4378ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4379ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4380ad48fd75SYan, Zheng 
4381ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4382ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4383ad48fd75SYan, Zheng 
4384e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
4385ad48fd75SYan, Zheng 		return 0;
4386ad48fd75SYan, Zheng 
4387ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4388ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4389ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4390ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4391ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4392ad48fd75SYan, Zheng 	}
4393b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4394ad48fd75SYan, Zheng 
4395ad48fd75SYan, Zheng 	path->keep_locks = 1;
4396ad48fd75SYan, Zheng 	path->search_for_split = 1;
4397ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4398ad48fd75SYan, Zheng 	path->search_for_split = 0;
4399a8df6fe6SFilipe Manana 	if (ret > 0)
4400a8df6fe6SFilipe Manana 		ret = -EAGAIN;
4401ad48fd75SYan, Zheng 	if (ret < 0)
4402ad48fd75SYan, Zheng 		goto err;
4403ad48fd75SYan, Zheng 
4404ad48fd75SYan, Zheng 	ret = -EAGAIN;
4405ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4406a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
4407a8df6fe6SFilipe Manana 	if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4408ad48fd75SYan, Zheng 		goto err;
4409ad48fd75SYan, Zheng 
4410109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4411e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
4412109f6aefSChris Mason 		goto err;
4413109f6aefSChris Mason 
4414ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4415ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4416ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4417ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4418ad48fd75SYan, Zheng 			goto err;
4419ad48fd75SYan, Zheng 	}
4420ad48fd75SYan, Zheng 
4421ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4422ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4423f0486c68SYan, Zheng 	if (ret)
4424f0486c68SYan, Zheng 		goto err;
4425ad48fd75SYan, Zheng 
4426ad48fd75SYan, Zheng 	path->keep_locks = 0;
4427ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4428ad48fd75SYan, Zheng 	return 0;
4429ad48fd75SYan, Zheng err:
4430ad48fd75SYan, Zheng 	path->keep_locks = 0;
4431ad48fd75SYan, Zheng 	return ret;
4432ad48fd75SYan, Zheng }
4433ad48fd75SYan, Zheng 
443425263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
4435310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
4436459931ecSChris Mason 			       unsigned long split_offset)
4437459931ecSChris Mason {
4438459931ecSChris Mason 	struct extent_buffer *leaf;
4439459931ecSChris Mason 	struct btrfs_item *item;
4440459931ecSChris Mason 	struct btrfs_item *new_item;
4441459931ecSChris Mason 	int slot;
4442ad48fd75SYan, Zheng 	char *buf;
4443459931ecSChris Mason 	u32 nritems;
4444ad48fd75SYan, Zheng 	u32 item_size;
4445459931ecSChris Mason 	u32 orig_offset;
4446459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4447459931ecSChris Mason 
4448459931ecSChris Mason 	leaf = path->nodes[0];
4449e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
4450b9473439SChris Mason 
4451b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4452b4ce94deSChris Mason 
4453dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
4454459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4455459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4456459931ecSChris Mason 
4457459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4458ad48fd75SYan, Zheng 	if (!buf)
4459ad48fd75SYan, Zheng 		return -ENOMEM;
4460ad48fd75SYan, Zheng 
4461459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4462459931ecSChris Mason 			    path->slots[0]), item_size);
4463ad48fd75SYan, Zheng 
4464459931ecSChris Mason 	slot = path->slots[0] + 1;
4465459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4466459931ecSChris Mason 	if (slot != nritems) {
4467459931ecSChris Mason 		/* shift the items */
4468459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4469459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4470459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4471459931ecSChris Mason 	}
4472459931ecSChris Mason 
4473459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4474459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4475459931ecSChris Mason 
4476dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
4477459931ecSChris Mason 
4478459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4479459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4480459931ecSChris Mason 
4481459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4482459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4483459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4484459931ecSChris Mason 
4485459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4486459931ecSChris Mason 
4487459931ecSChris Mason 	/* write the data for the start of the original item */
4488459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4489459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4490459931ecSChris Mason 			    split_offset);
4491459931ecSChris Mason 
4492459931ecSChris Mason 	/* write the data for the new item */
4493459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4494459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4495459931ecSChris Mason 			    item_size - split_offset);
4496459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4497459931ecSChris Mason 
4498e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
4499459931ecSChris Mason 	kfree(buf);
4500ad48fd75SYan, Zheng 	return 0;
4501ad48fd75SYan, Zheng }
4502ad48fd75SYan, Zheng 
4503ad48fd75SYan, Zheng /*
4504ad48fd75SYan, Zheng  * This function splits a single item into two items,
4505ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4506ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4507ad48fd75SYan, Zheng  *
4508ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4509ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4510ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4511ad48fd75SYan, Zheng  *
4512ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4513ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4514ad48fd75SYan, Zheng  *
4515ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4516ad48fd75SYan, Zheng  * leaf the entire time.
4517ad48fd75SYan, Zheng  */
4518ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4519ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4520ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4521310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
4522ad48fd75SYan, Zheng 		     unsigned long split_offset)
4523ad48fd75SYan, Zheng {
4524ad48fd75SYan, Zheng 	int ret;
4525ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4526ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4527ad48fd75SYan, Zheng 	if (ret)
4528459931ecSChris Mason 		return ret;
4529ad48fd75SYan, Zheng 
453025263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
4531ad48fd75SYan, Zheng 	return ret;
4532ad48fd75SYan, Zheng }
4533ad48fd75SYan, Zheng 
4534ad48fd75SYan, Zheng /*
4535ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4536ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4537ad48fd75SYan, Zheng  * is contiguous with the original item.
4538ad48fd75SYan, Zheng  *
4539ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4540ad48fd75SYan, Zheng  * leaf the entire time.
4541ad48fd75SYan, Zheng  */
4542ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4543ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4544ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4545310712b2SOmar Sandoval 			 const struct btrfs_key *new_key)
4546ad48fd75SYan, Zheng {
4547ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4548ad48fd75SYan, Zheng 	int ret;
4549ad48fd75SYan, Zheng 	u32 item_size;
4550ad48fd75SYan, Zheng 
4551ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4552ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4553ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4554ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4555ad48fd75SYan, Zheng 	if (ret)
4556ad48fd75SYan, Zheng 		return ret;
4557ad48fd75SYan, Zheng 
4558ad48fd75SYan, Zheng 	path->slots[0]++;
4559afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, new_key, &item_size,
4560ad48fd75SYan, Zheng 			       item_size, item_size +
4561ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4562ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4563ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4564ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4565ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4566ad48fd75SYan, Zheng 			     item_size);
4567ad48fd75SYan, Zheng 	return 0;
4568459931ecSChris Mason }
4569459931ecSChris Mason 
4570459931ecSChris Mason /*
4571d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4572d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4573d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4574d352ac68SChris Mason  * the front.
4575d352ac68SChris Mason  */
457678ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
4577b18c6685SChris Mason {
4578b18c6685SChris Mason 	int slot;
45795f39d397SChris Mason 	struct extent_buffer *leaf;
45805f39d397SChris Mason 	struct btrfs_item *item;
4581b18c6685SChris Mason 	u32 nritems;
4582b18c6685SChris Mason 	unsigned int data_end;
4583b18c6685SChris Mason 	unsigned int old_data_start;
4584b18c6685SChris Mason 	unsigned int old_size;
4585b18c6685SChris Mason 	unsigned int size_diff;
4586b18c6685SChris Mason 	int i;
4587cfed81a0SChris Mason 	struct btrfs_map_token token;
4588cfed81a0SChris Mason 
45895f39d397SChris Mason 	leaf = path->nodes[0];
4590179e29e4SChris Mason 	slot = path->slots[0];
4591179e29e4SChris Mason 
4592179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4593179e29e4SChris Mason 	if (old_size == new_size)
4594143bede5SJeff Mahoney 		return;
4595b18c6685SChris Mason 
45965f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
45978f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4598b18c6685SChris Mason 
45995f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4600179e29e4SChris Mason 
4601b18c6685SChris Mason 	size_diff = old_size - new_size;
4602b18c6685SChris Mason 
4603b18c6685SChris Mason 	BUG_ON(slot < 0);
4604b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4605b18c6685SChris Mason 
4606b18c6685SChris Mason 	/*
4607b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4608b18c6685SChris Mason 	 */
4609b18c6685SChris Mason 	/* first correct the data pointers */
4610c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4611b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
46125f39d397SChris Mason 		u32 ioff;
4613dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4614db94535dSChris Mason 
4615cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
4616cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff + size_diff);
4617b18c6685SChris Mason 	}
4618db94535dSChris Mason 
4619b18c6685SChris Mason 	/* shift the data */
4620179e29e4SChris Mason 	if (from_end) {
46213d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46223d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4623b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4624179e29e4SChris Mason 	} else {
4625179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4626179e29e4SChris Mason 		u64 offset;
4627179e29e4SChris Mason 
4628179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4629179e29e4SChris Mason 
4630179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4631179e29e4SChris Mason 			unsigned long ptr;
4632179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4633179e29e4SChris Mason 
4634179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4635179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4636179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4637179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4638179e29e4SChris Mason 
4639179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4640179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4641179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4642179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4643179e29e4SChris Mason 				      (unsigned long)fi,
46447ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4645179e29e4SChris Mason 			}
4646179e29e4SChris Mason 		}
4647179e29e4SChris Mason 
46483d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46493d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4650179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4651179e29e4SChris Mason 
4652179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4653179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4654179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4655179e29e4SChris Mason 		if (slot == 0)
4656b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4657179e29e4SChris Mason 	}
46585f39d397SChris Mason 
4659dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46605f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
46615f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4662b18c6685SChris Mason 
4663e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4664a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4665b18c6685SChris Mason 		BUG();
46665f39d397SChris Mason 	}
4667b18c6685SChris Mason }
4668b18c6685SChris Mason 
4669d352ac68SChris Mason /*
46708f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4671d352ac68SChris Mason  */
4672c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
46736567e837SChris Mason {
46746567e837SChris Mason 	int slot;
46755f39d397SChris Mason 	struct extent_buffer *leaf;
46765f39d397SChris Mason 	struct btrfs_item *item;
46776567e837SChris Mason 	u32 nritems;
46786567e837SChris Mason 	unsigned int data_end;
46796567e837SChris Mason 	unsigned int old_data;
46806567e837SChris Mason 	unsigned int old_size;
46816567e837SChris Mason 	int i;
4682cfed81a0SChris Mason 	struct btrfs_map_token token;
4683cfed81a0SChris Mason 
46845f39d397SChris Mason 	leaf = path->nodes[0];
46856567e837SChris Mason 
46865f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46878f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
46886567e837SChris Mason 
4689e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4690a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46916567e837SChris Mason 		BUG();
46925f39d397SChris Mason 	}
46936567e837SChris Mason 	slot = path->slots[0];
46945f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
46956567e837SChris Mason 
46966567e837SChris Mason 	BUG_ON(slot < 0);
46973326d1b0SChris Mason 	if (slot >= nritems) {
4698a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4699c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4700d397712bSChris Mason 			   slot, nritems);
4701290342f6SArnd Bergmann 		BUG();
47023326d1b0SChris Mason 	}
47036567e837SChris Mason 
47046567e837SChris Mason 	/*
47056567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
47066567e837SChris Mason 	 */
47076567e837SChris Mason 	/* first correct the data pointers */
4708c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
47096567e837SChris Mason 	for (i = slot; i < nritems; i++) {
47105f39d397SChris Mason 		u32 ioff;
4711dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4712db94535dSChris Mason 
4713cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
4714cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff - data_size);
47156567e837SChris Mason 	}
47165f39d397SChris Mason 
47176567e837SChris Mason 	/* shift the data */
47183d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
47193d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
47206567e837SChris Mason 		      data_end, old_data - data_end);
47215f39d397SChris Mason 
47226567e837SChris Mason 	data_end = old_data;
47235f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4724dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
47255f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
47265f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
47276567e837SChris Mason 
4728e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4729a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47306567e837SChris Mason 		BUG();
47315f39d397SChris Mason 	}
47326567e837SChris Mason }
47336567e837SChris Mason 
473474123bd7SChris Mason /*
473544871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
473644871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
473744871b1bSChris Mason  * that doesn't call btrfs_search_slot
473874123bd7SChris Mason  */
4739afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4740310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
474144871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4742be0e5c09SChris Mason {
47430b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
47445f39d397SChris Mason 	struct btrfs_item *item;
47459c58309dSChris Mason 	int i;
47467518a238SChris Mason 	u32 nritems;
4747be0e5c09SChris Mason 	unsigned int data_end;
4748e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
474944871b1bSChris Mason 	struct extent_buffer *leaf;
475044871b1bSChris Mason 	int slot;
4751cfed81a0SChris Mason 	struct btrfs_map_token token;
4752cfed81a0SChris Mason 
475324cdc847SFilipe Manana 	if (path->slots[0] == 0) {
475424cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4755b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
475624cdc847SFilipe Manana 	}
475724cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
475824cdc847SFilipe Manana 
47595f39d397SChris Mason 	leaf = path->nodes[0];
476044871b1bSChris Mason 	slot = path->slots[0];
476174123bd7SChris Mason 
47625f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
47638f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4764eb60ceacSChris Mason 
4765e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4766a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47670b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4768e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4769be0e5c09SChris Mason 		BUG();
4770d4dbff95SChris Mason 	}
47715f39d397SChris Mason 
4772c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4773be0e5c09SChris Mason 	if (slot != nritems) {
47745f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4775be0e5c09SChris Mason 
47765f39d397SChris Mason 		if (old_data < data_end) {
4777a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
47780b246afaSJeff Mahoney 			btrfs_crit(fs_info, "slot %d old_data %d data_end %d",
47795f39d397SChris Mason 				   slot, old_data, data_end);
4780290342f6SArnd Bergmann 			BUG();
47815f39d397SChris Mason 		}
4782be0e5c09SChris Mason 		/*
4783be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4784be0e5c09SChris Mason 		 */
4785be0e5c09SChris Mason 		/* first correct the data pointers */
47860783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
47875f39d397SChris Mason 			u32 ioff;
4788db94535dSChris Mason 
4789dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4790cc4c13d5SDavid Sterba 			ioff = btrfs_token_item_offset(&token, item);
4791cc4c13d5SDavid Sterba 			btrfs_set_token_item_offset(&token, item,
4792cc4c13d5SDavid Sterba 						    ioff - total_data);
47930783fcfcSChris Mason 		}
4794be0e5c09SChris Mason 		/* shift the items */
47959c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
47965f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
47970783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4798be0e5c09SChris Mason 
4799be0e5c09SChris Mason 		/* shift the data */
48003d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
48013d9ec8c4SNikolay Borisov 			      data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
4802be0e5c09SChris Mason 			      data_end, old_data - data_end);
4803be0e5c09SChris Mason 		data_end = old_data;
4804be0e5c09SChris Mason 	}
48055f39d397SChris Mason 
480662e2749eSChris Mason 	/* setup the item for the new data */
48079c58309dSChris Mason 	for (i = 0; i < nr; i++) {
48089c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
48099c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4810dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
4811cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, data_end - data_size[i]);
48129c58309dSChris Mason 		data_end -= data_size[i];
4813cc4c13d5SDavid Sterba 		btrfs_set_token_item_size(&token, item, data_size[i]);
48149c58309dSChris Mason 	}
481544871b1bSChris Mason 
48169c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4817b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4818aa5d6bedSChris Mason 
4819e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4820a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4821be0e5c09SChris Mason 		BUG();
48225f39d397SChris Mason 	}
482344871b1bSChris Mason }
482444871b1bSChris Mason 
482544871b1bSChris Mason /*
482644871b1bSChris Mason  * Given a key and some data, insert items into the tree.
482744871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
482844871b1bSChris Mason  */
482944871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
483044871b1bSChris Mason 			    struct btrfs_root *root,
483144871b1bSChris Mason 			    struct btrfs_path *path,
4832310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
483344871b1bSChris Mason 			    int nr)
483444871b1bSChris Mason {
483544871b1bSChris Mason 	int ret = 0;
483644871b1bSChris Mason 	int slot;
483744871b1bSChris Mason 	int i;
483844871b1bSChris Mason 	u32 total_size = 0;
483944871b1bSChris Mason 	u32 total_data = 0;
484044871b1bSChris Mason 
484144871b1bSChris Mason 	for (i = 0; i < nr; i++)
484244871b1bSChris Mason 		total_data += data_size[i];
484344871b1bSChris Mason 
484444871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
484544871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
484644871b1bSChris Mason 	if (ret == 0)
484744871b1bSChris Mason 		return -EEXIST;
484844871b1bSChris Mason 	if (ret < 0)
4849143bede5SJeff Mahoney 		return ret;
485044871b1bSChris Mason 
485144871b1bSChris Mason 	slot = path->slots[0];
485244871b1bSChris Mason 	BUG_ON(slot < 0);
485344871b1bSChris Mason 
4854afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, cpu_key, data_size,
485544871b1bSChris Mason 			       total_data, total_size, nr);
4856143bede5SJeff Mahoney 	return 0;
485762e2749eSChris Mason }
485862e2749eSChris Mason 
485962e2749eSChris Mason /*
486062e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
486162e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
486262e2749eSChris Mason  */
4863310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4864310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4865310712b2SOmar Sandoval 		      u32 data_size)
486662e2749eSChris Mason {
486762e2749eSChris Mason 	int ret = 0;
48682c90e5d6SChris Mason 	struct btrfs_path *path;
48695f39d397SChris Mason 	struct extent_buffer *leaf;
48705f39d397SChris Mason 	unsigned long ptr;
487162e2749eSChris Mason 
48722c90e5d6SChris Mason 	path = btrfs_alloc_path();
4873db5b493aSTsutomu Itoh 	if (!path)
4874db5b493aSTsutomu Itoh 		return -ENOMEM;
48752c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
487662e2749eSChris Mason 	if (!ret) {
48775f39d397SChris Mason 		leaf = path->nodes[0];
48785f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
48795f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
48805f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
488162e2749eSChris Mason 	}
48822c90e5d6SChris Mason 	btrfs_free_path(path);
4883aa5d6bedSChris Mason 	return ret;
4884be0e5c09SChris Mason }
4885be0e5c09SChris Mason 
488674123bd7SChris Mason /*
48875de08d7dSChris Mason  * delete the pointer from a given node.
488874123bd7SChris Mason  *
4889d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4890d352ac68SChris Mason  * empty a node.
489174123bd7SChris Mason  */
4892afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4893afe5fea7STsutomu Itoh 		    int level, int slot)
4894be0e5c09SChris Mason {
48955f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
48967518a238SChris Mason 	u32 nritems;
4897f3ea38daSJan Schmidt 	int ret;
4898be0e5c09SChris Mason 
48995f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4900be0e5c09SChris Mason 	if (slot != nritems - 1) {
4901bf1d3425SDavid Sterba 		if (level) {
4902bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(parent, slot, slot + 1,
4903a446a979SDavid Sterba 					nritems - slot - 1);
4904bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4905bf1d3425SDavid Sterba 		}
49065f39d397SChris Mason 		memmove_extent_buffer(parent,
49075f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
49085f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4909d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4910d6025579SChris Mason 			      (nritems - slot - 1));
491157ba86c0SChris Mason 	} else if (level) {
4912e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4913e09c2efeSDavid Sterba 				GFP_NOFS);
491457ba86c0SChris Mason 		BUG_ON(ret < 0);
4915be0e5c09SChris Mason 	}
4916f3ea38daSJan Schmidt 
49177518a238SChris Mason 	nritems--;
49185f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
49197518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
49205f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4921eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
49225f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4923bb803951SChris Mason 	} else if (slot == 0) {
49245f39d397SChris Mason 		struct btrfs_disk_key disk_key;
49255f39d397SChris Mason 
49265f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4927b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4928be0e5c09SChris Mason 	}
4929d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4930be0e5c09SChris Mason }
4931be0e5c09SChris Mason 
493274123bd7SChris Mason /*
4933323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
49345d4f98a2SYan Zheng  * path->nodes[1].
4935323ac95bSChris Mason  *
4936323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4937323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4938323ac95bSChris Mason  *
4939323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4940323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4941323ac95bSChris Mason  */
4942143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4943323ac95bSChris Mason 				    struct btrfs_root *root,
49445d4f98a2SYan Zheng 				    struct btrfs_path *path,
49455d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4946323ac95bSChris Mason {
49475d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4948afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4949323ac95bSChris Mason 
49504d081c41SChris Mason 	/*
49514d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
49524d081c41SChris Mason 	 * aren't holding any locks when we call it
49534d081c41SChris Mason 	 */
49544d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
49554d081c41SChris Mason 
4956f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4957f0486c68SYan, Zheng 
495867439dadSDavid Sterba 	atomic_inc(&leaf->refs);
49595581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
49603083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4961323ac95bSChris Mason }
4962323ac95bSChris Mason /*
496374123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
496474123bd7SChris Mason  * the leaf, remove it from the tree
496574123bd7SChris Mason  */
496685e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
496785e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4968be0e5c09SChris Mason {
49690b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
49705f39d397SChris Mason 	struct extent_buffer *leaf;
49715f39d397SChris Mason 	struct btrfs_item *item;
4972ce0eac2aSAlexandru Moise 	u32 last_off;
4973ce0eac2aSAlexandru Moise 	u32 dsize = 0;
4974aa5d6bedSChris Mason 	int ret = 0;
4975aa5d6bedSChris Mason 	int wret;
497685e21bacSChris Mason 	int i;
49777518a238SChris Mason 	u32 nritems;
4978be0e5c09SChris Mason 
49795f39d397SChris Mason 	leaf = path->nodes[0];
498085e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
498185e21bacSChris Mason 
498285e21bacSChris Mason 	for (i = 0; i < nr; i++)
498385e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
498485e21bacSChris Mason 
49855f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4986be0e5c09SChris Mason 
498785e21bacSChris Mason 	if (slot + nr != nritems) {
49888f881e8cSDavid Sterba 		int data_end = leaf_data_end(leaf);
4989c82f823cSDavid Sterba 		struct btrfs_map_token token;
49905f39d397SChris Mason 
49913d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4992d6025579SChris Mason 			      data_end + dsize,
49933d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
499485e21bacSChris Mason 			      last_off - data_end);
49955f39d397SChris Mason 
4996c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
499785e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
49985f39d397SChris Mason 			u32 ioff;
4999db94535dSChris Mason 
5000dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
5001cc4c13d5SDavid Sterba 			ioff = btrfs_token_item_offset(&token, item);
5002cc4c13d5SDavid Sterba 			btrfs_set_token_item_offset(&token, item, ioff + dsize);
50030783fcfcSChris Mason 		}
5004db94535dSChris Mason 
50055f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
500685e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
50070783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
500885e21bacSChris Mason 			      (nritems - slot - nr));
5009be0e5c09SChris Mason 	}
501085e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
501185e21bacSChris Mason 	nritems -= nr;
50125f39d397SChris Mason 
501374123bd7SChris Mason 	/* delete the leaf if we've emptied it */
50147518a238SChris Mason 	if (nritems == 0) {
50155f39d397SChris Mason 		if (leaf == root->node) {
50165f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
50179a8dd150SChris Mason 		} else {
5018f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
50196a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
5020143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
50219a8dd150SChris Mason 		}
5022be0e5c09SChris Mason 	} else {
50237518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
5024aa5d6bedSChris Mason 		if (slot == 0) {
50255f39d397SChris Mason 			struct btrfs_disk_key disk_key;
50265f39d397SChris Mason 
50275f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
5028b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
5029aa5d6bedSChris Mason 		}
5030aa5d6bedSChris Mason 
503174123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
50320b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
5033be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
5034be0e5c09SChris Mason 			 * make sure the path still points to our leaf
5035be0e5c09SChris Mason 			 * for possible call to del_ptr below
5036be0e5c09SChris Mason 			 */
50374920c9acSChris Mason 			slot = path->slots[1];
503867439dadSDavid Sterba 			atomic_inc(&leaf->refs);
50395f39d397SChris Mason 
5040b9473439SChris Mason 			btrfs_set_path_blocking(path);
504199d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
504299d8f83cSChris Mason 					      1, (u32)-1);
504354aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
5044aa5d6bedSChris Mason 				ret = wret;
50455f39d397SChris Mason 
50465f39d397SChris Mason 			if (path->nodes[0] == leaf &&
50475f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
504899d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
504999d8f83cSChris Mason 						       1, 1, 0);
505054aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
5051aa5d6bedSChris Mason 					ret = wret;
5052aa5d6bedSChris Mason 			}
50535f39d397SChris Mason 
50545f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
5055323ac95bSChris Mason 				path->slots[1] = slot;
5056143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
50575f39d397SChris Mason 				free_extent_buffer(leaf);
5058143bede5SJeff Mahoney 				ret = 0;
50595de08d7dSChris Mason 			} else {
5060925baeddSChris Mason 				/* if we're still in the path, make sure
5061925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
5062925baeddSChris Mason 				 * push_leaf functions must have already
5063925baeddSChris Mason 				 * dirtied this buffer
5064925baeddSChris Mason 				 */
5065925baeddSChris Mason 				if (path->nodes[0] == leaf)
50665f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
50675f39d397SChris Mason 				free_extent_buffer(leaf);
5068be0e5c09SChris Mason 			}
5069d5719762SChris Mason 		} else {
50705f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
5071be0e5c09SChris Mason 		}
50729a8dd150SChris Mason 	}
5073aa5d6bedSChris Mason 	return ret;
50749a8dd150SChris Mason }
50759a8dd150SChris Mason 
507697571fd0SChris Mason /*
5077925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
50787bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
50797bb86316SChris Mason  * returns < 0 on io errors.
5080d352ac68SChris Mason  *
5081d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
5082d352ac68SChris Mason  * time you call it.
50837bb86316SChris Mason  */
508416e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
50857bb86316SChris Mason {
5086925baeddSChris Mason 	struct btrfs_key key;
5087925baeddSChris Mason 	struct btrfs_disk_key found_key;
5088925baeddSChris Mason 	int ret;
50897bb86316SChris Mason 
5090925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5091925baeddSChris Mason 
5092e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
5093925baeddSChris Mason 		key.offset--;
5094e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
5095925baeddSChris Mason 		key.type--;
5096e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5097e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
5098925baeddSChris Mason 		key.objectid--;
5099e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
5100e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5101e8b0d724SFilipe David Borba Manana 	} else {
51027bb86316SChris Mason 		return 1;
5103e8b0d724SFilipe David Borba Manana 	}
51047bb86316SChris Mason 
5105b3b4aa74SDavid Sterba 	btrfs_release_path(path);
5106925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5107925baeddSChris Mason 	if (ret < 0)
5108925baeddSChris Mason 		return ret;
5109925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
5110925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
5111337c6f68SFilipe Manana 	/*
5112337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
5113337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
5114337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
5115337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
5116337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
5117337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
5118337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
5119337c6f68SFilipe Manana 	 * the previous key we computed above.
5120337c6f68SFilipe Manana 	 */
5121337c6f68SFilipe Manana 	if (ret <= 0)
51227bb86316SChris Mason 		return 0;
5123925baeddSChris Mason 	return 1;
51247bb86316SChris Mason }
51257bb86316SChris Mason 
51263f157a2fSChris Mason /*
51273f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
5128de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
5129de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
51303f157a2fSChris Mason  *
51313f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
51323f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
51333f157a2fSChris Mason  * key and get a writable path.
51343f157a2fSChris Mason  *
51353f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
51363f157a2fSChris Mason  * of the tree.
51373f157a2fSChris Mason  *
5138d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
5139d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
5140d352ac68SChris Mason  * skipped over (without reading them).
5141d352ac68SChris Mason  *
51423f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
51433f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
51443f157a2fSChris Mason  */
51453f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5146de78b51aSEric Sandeen 			 struct btrfs_path *path,
51473f157a2fSChris Mason 			 u64 min_trans)
51483f157a2fSChris Mason {
51493f157a2fSChris Mason 	struct extent_buffer *cur;
51503f157a2fSChris Mason 	struct btrfs_key found_key;
51513f157a2fSChris Mason 	int slot;
51529652480bSYan 	int sret;
51533f157a2fSChris Mason 	u32 nritems;
51543f157a2fSChris Mason 	int level;
51553f157a2fSChris Mason 	int ret = 1;
5156f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
51573f157a2fSChris Mason 
5158f98de9b9SFilipe Manana 	path->keep_locks = 1;
51593f157a2fSChris Mason again:
5160bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
51613f157a2fSChris Mason 	level = btrfs_header_level(cur);
5162e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
51633f157a2fSChris Mason 	path->nodes[level] = cur;
5164bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
51653f157a2fSChris Mason 
51663f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
51673f157a2fSChris Mason 		ret = 1;
51683f157a2fSChris Mason 		goto out;
51693f157a2fSChris Mason 	}
51703f157a2fSChris Mason 	while (1) {
51713f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
51723f157a2fSChris Mason 		level = btrfs_header_level(cur);
5173e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
5174cbca7d59SFilipe Manana 		if (sret < 0) {
5175cbca7d59SFilipe Manana 			ret = sret;
5176cbca7d59SFilipe Manana 			goto out;
5177cbca7d59SFilipe Manana 		}
51783f157a2fSChris Mason 
5179323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
5180323ac95bSChris Mason 		if (level == path->lowest_level) {
5181e02119d5SChris Mason 			if (slot >= nritems)
5182e02119d5SChris Mason 				goto find_next_key;
51833f157a2fSChris Mason 			ret = 0;
51843f157a2fSChris Mason 			path->slots[level] = slot;
51853f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
51863f157a2fSChris Mason 			goto out;
51873f157a2fSChris Mason 		}
51889652480bSYan 		if (sret && slot > 0)
51899652480bSYan 			slot--;
51903f157a2fSChris Mason 		/*
5191de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
5192260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
51933f157a2fSChris Mason 		 */
51943f157a2fSChris Mason 		while (slot < nritems) {
51953f157a2fSChris Mason 			u64 gen;
5196e02119d5SChris Mason 
51973f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
51983f157a2fSChris Mason 			if (gen < min_trans) {
51993f157a2fSChris Mason 				slot++;
52003f157a2fSChris Mason 				continue;
52013f157a2fSChris Mason 			}
52023f157a2fSChris Mason 			break;
52033f157a2fSChris Mason 		}
5204e02119d5SChris Mason find_next_key:
52053f157a2fSChris Mason 		/*
52063f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
52073f157a2fSChris Mason 		 * and find another one
52083f157a2fSChris Mason 		 */
52093f157a2fSChris Mason 		if (slot >= nritems) {
5210e02119d5SChris Mason 			path->slots[level] = slot;
5211b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
5212e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
5213de78b51aSEric Sandeen 						  min_trans);
5214e02119d5SChris Mason 			if (sret == 0) {
5215b3b4aa74SDavid Sterba 				btrfs_release_path(path);
52163f157a2fSChris Mason 				goto again;
52173f157a2fSChris Mason 			} else {
52183f157a2fSChris Mason 				goto out;
52193f157a2fSChris Mason 			}
52203f157a2fSChris Mason 		}
52213f157a2fSChris Mason 		/* save our key for returning back */
52223f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
52233f157a2fSChris Mason 		path->slots[level] = slot;
52243f157a2fSChris Mason 		if (level == path->lowest_level) {
52253f157a2fSChris Mason 			ret = 0;
52263f157a2fSChris Mason 			goto out;
52273f157a2fSChris Mason 		}
5228b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
52294b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
5230fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
5231fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
5232fb770ae4SLiu Bo 			goto out;
5233fb770ae4SLiu Bo 		}
52343f157a2fSChris Mason 
5235bd681513SChris Mason 		btrfs_tree_read_lock(cur);
5236b4ce94deSChris Mason 
5237bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
52383f157a2fSChris Mason 		path->nodes[level - 1] = cur;
5239f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
52403f157a2fSChris Mason 	}
52413f157a2fSChris Mason out:
5242f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
5243f98de9b9SFilipe Manana 	if (ret == 0) {
5244f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
5245b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
5246f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
5247f98de9b9SFilipe Manana 	}
52483f157a2fSChris Mason 	return ret;
52493f157a2fSChris Mason }
52503f157a2fSChris Mason 
52513f157a2fSChris Mason /*
52523f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
52533f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5254de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
52553f157a2fSChris Mason  *
52563f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
52573f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
52583f157a2fSChris Mason  *
52593f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
52603f157a2fSChris Mason  * calling this function.
52613f157a2fSChris Mason  */
5262e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5263de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5264e7a84565SChris Mason {
5265e7a84565SChris Mason 	int slot;
5266e7a84565SChris Mason 	struct extent_buffer *c;
5267e7a84565SChris Mason 
52686a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
5269e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5270e7a84565SChris Mason 		if (!path->nodes[level])
5271e7a84565SChris Mason 			return 1;
5272e7a84565SChris Mason 
5273e7a84565SChris Mason 		slot = path->slots[level] + 1;
5274e7a84565SChris Mason 		c = path->nodes[level];
52753f157a2fSChris Mason next:
5276e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
527733c66f43SYan Zheng 			int ret;
527833c66f43SYan Zheng 			int orig_lowest;
527933c66f43SYan Zheng 			struct btrfs_key cur_key;
528033c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
528133c66f43SYan Zheng 			    !path->nodes[level + 1])
5282e7a84565SChris Mason 				return 1;
528333c66f43SYan Zheng 
52846a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
528533c66f43SYan Zheng 				level++;
5286e7a84565SChris Mason 				continue;
5287e7a84565SChris Mason 			}
528833c66f43SYan Zheng 
528933c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
529033c66f43SYan Zheng 			if (level == 0)
529133c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
529233c66f43SYan Zheng 			else
529333c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
529433c66f43SYan Zheng 
529533c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5296b3b4aa74SDavid Sterba 			btrfs_release_path(path);
529733c66f43SYan Zheng 			path->lowest_level = level;
529833c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
529933c66f43SYan Zheng 						0, 0);
530033c66f43SYan Zheng 			path->lowest_level = orig_lowest;
530133c66f43SYan Zheng 			if (ret < 0)
530233c66f43SYan Zheng 				return ret;
530333c66f43SYan Zheng 
530433c66f43SYan Zheng 			c = path->nodes[level];
530533c66f43SYan Zheng 			slot = path->slots[level];
530633c66f43SYan Zheng 			if (ret == 0)
530733c66f43SYan Zheng 				slot++;
530833c66f43SYan Zheng 			goto next;
530933c66f43SYan Zheng 		}
531033c66f43SYan Zheng 
5311e7a84565SChris Mason 		if (level == 0)
5312e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
53133f157a2fSChris Mason 		else {
53143f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
53153f157a2fSChris Mason 
53163f157a2fSChris Mason 			if (gen < min_trans) {
53173f157a2fSChris Mason 				slot++;
53183f157a2fSChris Mason 				goto next;
53193f157a2fSChris Mason 			}
5320e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
53213f157a2fSChris Mason 		}
5322e7a84565SChris Mason 		return 0;
5323e7a84565SChris Mason 	}
5324e7a84565SChris Mason 	return 1;
5325e7a84565SChris Mason }
5326e7a84565SChris Mason 
53277bb86316SChris Mason /*
5328925baeddSChris Mason  * search the tree again to find a leaf with greater keys
53290f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
53300f70abe2SChris Mason  * returns < 0 on io errors.
533197571fd0SChris Mason  */
5332234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5333d97e63b6SChris Mason {
53343d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
53353d7806ecSJan Schmidt }
53363d7806ecSJan Schmidt 
53373d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
53383d7806ecSJan Schmidt 			u64 time_seq)
53393d7806ecSJan Schmidt {
5340d97e63b6SChris Mason 	int slot;
53418e73f275SChris Mason 	int level;
53425f39d397SChris Mason 	struct extent_buffer *c;
53438e73f275SChris Mason 	struct extent_buffer *next;
5344925baeddSChris Mason 	struct btrfs_key key;
5345925baeddSChris Mason 	u32 nritems;
5346925baeddSChris Mason 	int ret;
53478e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5348bd681513SChris Mason 	int next_rw_lock = 0;
5349925baeddSChris Mason 
5350925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5351d397712bSChris Mason 	if (nritems == 0)
5352925baeddSChris Mason 		return 1;
5353925baeddSChris Mason 
53548e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
53558e73f275SChris Mason again:
53568e73f275SChris Mason 	level = 1;
53578e73f275SChris Mason 	next = NULL;
5358bd681513SChris Mason 	next_rw_lock = 0;
5359b3b4aa74SDavid Sterba 	btrfs_release_path(path);
53608e73f275SChris Mason 
5361a2135011SChris Mason 	path->keep_locks = 1;
53628e73f275SChris Mason 	path->leave_spinning = 1;
53638e73f275SChris Mason 
53643d7806ecSJan Schmidt 	if (time_seq)
53653d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
53663d7806ecSJan Schmidt 	else
5367925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5368925baeddSChris Mason 	path->keep_locks = 0;
5369925baeddSChris Mason 
5370925baeddSChris Mason 	if (ret < 0)
5371925baeddSChris Mason 		return ret;
5372925baeddSChris Mason 
5373a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5374168fd7d2SChris Mason 	/*
5375168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5376168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5377168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5378168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5379168fd7d2SChris Mason 	 */
5380a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5381e457afecSYan Zheng 		if (ret == 0)
5382168fd7d2SChris Mason 			path->slots[0]++;
53838e73f275SChris Mason 		ret = 0;
5384925baeddSChris Mason 		goto done;
5385925baeddSChris Mason 	}
53860b43e04fSLiu Bo 	/*
53870b43e04fSLiu Bo 	 * So the above check misses one case:
53880b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
53890b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
53900b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
53910b43e04fSLiu Bo 	 *
53920b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
53930b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
53940b43e04fSLiu Bo 	 *
53950b43e04fSLiu Bo 	 * And a bit more explanation about this check,
53960b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
53970b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
53980b43e04fSLiu Bo 	 * bigger one.
53990b43e04fSLiu Bo 	 */
54000b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
54010b43e04fSLiu Bo 		ret = 0;
54020b43e04fSLiu Bo 		goto done;
54030b43e04fSLiu Bo 	}
5404d97e63b6SChris Mason 
5405234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
54068e73f275SChris Mason 		if (!path->nodes[level]) {
54078e73f275SChris Mason 			ret = 1;
54088e73f275SChris Mason 			goto done;
54098e73f275SChris Mason 		}
54105f39d397SChris Mason 
5411d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5412d97e63b6SChris Mason 		c = path->nodes[level];
54135f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5414d97e63b6SChris Mason 			level++;
54158e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
54168e73f275SChris Mason 				ret = 1;
54178e73f275SChris Mason 				goto done;
54188e73f275SChris Mason 			}
5419d97e63b6SChris Mason 			continue;
5420d97e63b6SChris Mason 		}
54215f39d397SChris Mason 
5422925baeddSChris Mason 		if (next) {
5423bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
54245f39d397SChris Mason 			free_extent_buffer(next);
5425925baeddSChris Mason 		}
54265f39d397SChris Mason 
54278e73f275SChris Mason 		next = c;
5428bd681513SChris Mason 		next_rw_lock = path->locks[level];
5429d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5430cda79c54SDavid Sterba 					    slot, &key);
54318e73f275SChris Mason 		if (ret == -EAGAIN)
54328e73f275SChris Mason 			goto again;
54335f39d397SChris Mason 
543476a05b35SChris Mason 		if (ret < 0) {
5435b3b4aa74SDavid Sterba 			btrfs_release_path(path);
543676a05b35SChris Mason 			goto done;
543776a05b35SChris Mason 		}
543876a05b35SChris Mason 
54395cd57b2cSChris Mason 		if (!path->skip_locking) {
5440bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5441d42244a0SJan Schmidt 			if (!ret && time_seq) {
5442d42244a0SJan Schmidt 				/*
5443d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5444d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5445d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5446d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5447d42244a0SJan Schmidt 				 * on our lock and cycle.
5448d42244a0SJan Schmidt 				 */
5449cf538830SJan Schmidt 				free_extent_buffer(next);
5450d42244a0SJan Schmidt 				btrfs_release_path(path);
5451d42244a0SJan Schmidt 				cond_resched();
5452d42244a0SJan Schmidt 				goto again;
5453d42244a0SJan Schmidt 			}
54548e73f275SChris Mason 			if (!ret) {
54558e73f275SChris Mason 				btrfs_set_path_blocking(path);
5456bd681513SChris Mason 				btrfs_tree_read_lock(next);
54578e73f275SChris Mason 			}
5458bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5459bd681513SChris Mason 		}
5460d97e63b6SChris Mason 		break;
5461d97e63b6SChris Mason 	}
5462d97e63b6SChris Mason 	path->slots[level] = slot;
5463d97e63b6SChris Mason 	while (1) {
5464d97e63b6SChris Mason 		level--;
5465d97e63b6SChris Mason 		c = path->nodes[level];
5466925baeddSChris Mason 		if (path->locks[level])
5467bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
54688e73f275SChris Mason 
54695f39d397SChris Mason 		free_extent_buffer(c);
5470d97e63b6SChris Mason 		path->nodes[level] = next;
5471d97e63b6SChris Mason 		path->slots[level] = 0;
5472a74a4b97SChris Mason 		if (!path->skip_locking)
5473bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5474d97e63b6SChris Mason 		if (!level)
5475d97e63b6SChris Mason 			break;
5476b4ce94deSChris Mason 
5477d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5478cda79c54SDavid Sterba 					    0, &key);
54798e73f275SChris Mason 		if (ret == -EAGAIN)
54808e73f275SChris Mason 			goto again;
54818e73f275SChris Mason 
548276a05b35SChris Mason 		if (ret < 0) {
5483b3b4aa74SDavid Sterba 			btrfs_release_path(path);
548476a05b35SChris Mason 			goto done;
548576a05b35SChris Mason 		}
548676a05b35SChris Mason 
54875cd57b2cSChris Mason 		if (!path->skip_locking) {
5488bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
54898e73f275SChris Mason 			if (!ret) {
54908e73f275SChris Mason 				btrfs_set_path_blocking(path);
5491bd681513SChris Mason 				btrfs_tree_read_lock(next);
54928e73f275SChris Mason 			}
5493bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5494bd681513SChris Mason 		}
5495d97e63b6SChris Mason 	}
54968e73f275SChris Mason 	ret = 0;
5497925baeddSChris Mason done:
5498f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
54998e73f275SChris Mason 	path->leave_spinning = old_spinning;
55008e73f275SChris Mason 	if (!old_spinning)
55018e73f275SChris Mason 		btrfs_set_path_blocking(path);
55028e73f275SChris Mason 
55038e73f275SChris Mason 	return ret;
5504d97e63b6SChris Mason }
55050b86a832SChris Mason 
55063f157a2fSChris Mason /*
55073f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
55083f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
55093f157a2fSChris Mason  *
55103f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
55113f157a2fSChris Mason  */
55120b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
55130b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
55140b86a832SChris Mason 			int type)
55150b86a832SChris Mason {
55160b86a832SChris Mason 	struct btrfs_key found_key;
55170b86a832SChris Mason 	struct extent_buffer *leaf;
5518e02119d5SChris Mason 	u32 nritems;
55190b86a832SChris Mason 	int ret;
55200b86a832SChris Mason 
55210b86a832SChris Mason 	while (1) {
55220b86a832SChris Mason 		if (path->slots[0] == 0) {
5523b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
55240b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
55250b86a832SChris Mason 			if (ret != 0)
55260b86a832SChris Mason 				return ret;
55270b86a832SChris Mason 		} else {
55280b86a832SChris Mason 			path->slots[0]--;
55290b86a832SChris Mason 		}
55300b86a832SChris Mason 		leaf = path->nodes[0];
5531e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5532e02119d5SChris Mason 		if (nritems == 0)
5533e02119d5SChris Mason 			return 1;
5534e02119d5SChris Mason 		if (path->slots[0] == nritems)
5535e02119d5SChris Mason 			path->slots[0]--;
5536e02119d5SChris Mason 
55370b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5538e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5539e02119d5SChris Mason 			break;
55400a4eefbbSYan Zheng 		if (found_key.type == type)
55410a4eefbbSYan Zheng 			return 0;
5542e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5543e02119d5SChris Mason 		    found_key.type < type)
5544e02119d5SChris Mason 			break;
55450b86a832SChris Mason 	}
55460b86a832SChris Mason 	return 1;
55470b86a832SChris Mason }
5548ade2e0b3SWang Shilong 
5549ade2e0b3SWang Shilong /*
5550ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5551ade2e0b3SWang Shilong  * min objecitd.
5552ade2e0b3SWang Shilong  *
5553ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5554ade2e0b3SWang Shilong  */
5555ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5556ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5557ade2e0b3SWang Shilong {
5558ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5559ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5560ade2e0b3SWang Shilong 	u32 nritems;
5561ade2e0b3SWang Shilong 	int ret;
5562ade2e0b3SWang Shilong 
5563ade2e0b3SWang Shilong 	while (1) {
5564ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5565ade2e0b3SWang Shilong 			btrfs_set_path_blocking(path);
5566ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5567ade2e0b3SWang Shilong 			if (ret != 0)
5568ade2e0b3SWang Shilong 				return ret;
5569ade2e0b3SWang Shilong 		} else {
5570ade2e0b3SWang Shilong 			path->slots[0]--;
5571ade2e0b3SWang Shilong 		}
5572ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5573ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5574ade2e0b3SWang Shilong 		if (nritems == 0)
5575ade2e0b3SWang Shilong 			return 1;
5576ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5577ade2e0b3SWang Shilong 			path->slots[0]--;
5578ade2e0b3SWang Shilong 
5579ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5580ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5581ade2e0b3SWang Shilong 			break;
5582ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5583ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5584ade2e0b3SWang Shilong 			return 0;
5585ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5586ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5587ade2e0b3SWang Shilong 			break;
5588ade2e0b3SWang Shilong 	}
5589ade2e0b3SWang Shilong 	return 1;
5590ade2e0b3SWang Shilong }
5591