xref: /openbmc/linux/fs/btrfs/ctree.c (revision 42c9d0b524cf9af180dcb788a938cdc4c678e8cb)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
3d352ac68SChris Mason  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
6a6b6e75eSChris Mason #include <linux/sched.h>
75a0e3ad6STejun Heo #include <linux/slab.h>
8bd989ba3SJan Schmidt #include <linux/rbtree.h>
9adf02123SDavid Sterba #include <linux/mm.h>
10eb60ceacSChris Mason #include "ctree.h"
11eb60ceacSChris Mason #include "disk-io.h"
127f5c1516SChris Mason #include "transaction.h"
135f39d397SChris Mason #include "print-tree.h"
14925baeddSChris Mason #include "locking.h"
15de37aa51SNikolay Borisov #include "volumes.h"
16f616f5cdSQu Wenruo #include "qgroup.h"
179a8dd150SChris Mason 
18e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
19e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
20310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
21310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
22310712b2SOmar Sandoval 		      int data_size, int extend);
235f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
242ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
25971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
265f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
275f39d397SChris Mason 			      struct extent_buffer *dst_buf,
285f39d397SChris Mason 			      struct extent_buffer *src_buf);
29afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
30afe5fea7STsutomu Itoh 		    int level, int slot);
31d97e63b6SChris Mason 
32af024ed2SJohannes Thumshirn static const struct btrfs_csums {
33af024ed2SJohannes Thumshirn 	u16		size;
34af024ed2SJohannes Thumshirn 	const char	*name;
35b4e967beSDavid Sterba 	const char	*driver;
36af024ed2SJohannes Thumshirn } btrfs_csums[] = {
37af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
383951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
393831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
40352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
41352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
42af024ed2SJohannes Thumshirn };
43af024ed2SJohannes Thumshirn 
44af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
45af024ed2SJohannes Thumshirn {
46af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
47af024ed2SJohannes Thumshirn 	/*
48af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
49af024ed2SJohannes Thumshirn 	 */
50af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
51af024ed2SJohannes Thumshirn }
52af024ed2SJohannes Thumshirn 
53af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
54af024ed2SJohannes Thumshirn {
55af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
56af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
57af024ed2SJohannes Thumshirn }
58af024ed2SJohannes Thumshirn 
59b4e967beSDavid Sterba /*
60b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
61b4e967beSDavid Sterba  * name
62b4e967beSDavid Sterba  */
63b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
64b4e967beSDavid Sterba {
65b4e967beSDavid Sterba 	/* csum type is validated at mount time */
66b4e967beSDavid Sterba 	return btrfs_csums[csum_type].driver ?:
67b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
68b4e967beSDavid Sterba }
69b4e967beSDavid Sterba 
70f7cea56cSDavid Sterba size_t __const btrfs_get_num_csums(void)
71f7cea56cSDavid Sterba {
72f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
73f7cea56cSDavid Sterba }
74f7cea56cSDavid Sterba 
752c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
762c90e5d6SChris Mason {
77e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
782c90e5d6SChris Mason }
792c90e5d6SChris Mason 
80d352ac68SChris Mason /* this also releases the path */
812c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
822c90e5d6SChris Mason {
83ff175d57SJesper Juhl 	if (!p)
84ff175d57SJesper Juhl 		return;
85b3b4aa74SDavid Sterba 	btrfs_release_path(p);
862c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
872c90e5d6SChris Mason }
882c90e5d6SChris Mason 
89d352ac68SChris Mason /*
90d352ac68SChris Mason  * path release drops references on the extent buffers in the path
91d352ac68SChris Mason  * and it drops any locks held by this path
92d352ac68SChris Mason  *
93d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
94d352ac68SChris Mason  */
95b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
96eb60ceacSChris Mason {
97eb60ceacSChris Mason 	int i;
98a2135011SChris Mason 
99234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1003f157a2fSChris Mason 		p->slots[i] = 0;
101eb60ceacSChris Mason 		if (!p->nodes[i])
102925baeddSChris Mason 			continue;
103925baeddSChris Mason 		if (p->locks[i]) {
104bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
105925baeddSChris Mason 			p->locks[i] = 0;
106925baeddSChris Mason 		}
1075f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1083f157a2fSChris Mason 		p->nodes[i] = NULL;
109eb60ceacSChris Mason 	}
110eb60ceacSChris Mason }
111eb60ceacSChris Mason 
112d352ac68SChris Mason /*
113d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
114d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
115d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
116d352ac68SChris Mason  * looping required.
117d352ac68SChris Mason  *
118d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
119d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
120d352ac68SChris Mason  * at any time because there are no locks held.
121d352ac68SChris Mason  */
122925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
123925baeddSChris Mason {
124925baeddSChris Mason 	struct extent_buffer *eb;
125240f62c8SChris Mason 
1263083ee2eSJosef Bacik 	while (1) {
127240f62c8SChris Mason 		rcu_read_lock();
128240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1293083ee2eSJosef Bacik 
1303083ee2eSJosef Bacik 		/*
1313083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
13201327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1333083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1343083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1353083ee2eSJosef Bacik 		 */
1363083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
137240f62c8SChris Mason 			rcu_read_unlock();
1383083ee2eSJosef Bacik 			break;
1393083ee2eSJosef Bacik 		}
1403083ee2eSJosef Bacik 		rcu_read_unlock();
1413083ee2eSJosef Bacik 		synchronize_rcu();
1423083ee2eSJosef Bacik 	}
143925baeddSChris Mason 	return eb;
144925baeddSChris Mason }
145925baeddSChris Mason 
146d352ac68SChris Mason /* cowonly root (everything not a reference counted cow subvolume), just get
147d352ac68SChris Mason  * put onto a simple dirty list.  transaction.c walks this to make sure they
148d352ac68SChris Mason  * get properly updated on disk.
149d352ac68SChris Mason  */
1500b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1510b86a832SChris Mason {
1520b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1530b246afaSJeff Mahoney 
154e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
155e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
156e7070be1SJosef Bacik 		return;
157e7070be1SJosef Bacik 
1580b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
159e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
160e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
1614fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
162e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
1630b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
164e7070be1SJosef Bacik 		else
165e7070be1SJosef Bacik 			list_move(&root->dirty_list,
1660b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
1670b86a832SChris Mason 	}
1680b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1690b86a832SChris Mason }
1700b86a832SChris Mason 
171d352ac68SChris Mason /*
172d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
173d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
174d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
175d352ac68SChris Mason  */
176be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
177be20aa9dSChris Mason 		      struct btrfs_root *root,
178be20aa9dSChris Mason 		      struct extent_buffer *buf,
179be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
180be20aa9dSChris Mason {
1810b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
182be20aa9dSChris Mason 	struct extent_buffer *cow;
183be20aa9dSChris Mason 	int ret = 0;
184be20aa9dSChris Mason 	int level;
1855d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
186be20aa9dSChris Mason 
18727cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1880b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
18927cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
19027cdeb70SMiao Xie 		trans->transid != root->last_trans);
191be20aa9dSChris Mason 
192be20aa9dSChris Mason 	level = btrfs_header_level(buf);
1935d4f98a2SYan Zheng 	if (level == 0)
1945d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
1955d4f98a2SYan Zheng 	else
1965d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
19731840ae1SZheng Yan 
1984d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
1994d75f8a9SDavid Sterba 			&disk_key, level, buf->start, 0);
2005d4f98a2SYan Zheng 	if (IS_ERR(cow))
201be20aa9dSChris Mason 		return PTR_ERR(cow);
202be20aa9dSChris Mason 
20358e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
204be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
205be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2065d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2075d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2085d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2095d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2105d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2115d4f98a2SYan Zheng 	else
212be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
213be20aa9dSChris Mason 
214de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2152b82032cSYan Zheng 
216be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2175d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
218e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2195d4f98a2SYan Zheng 	else
220e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
2214aec2b52SChris Mason 
222be20aa9dSChris Mason 	if (ret)
223be20aa9dSChris Mason 		return ret;
224be20aa9dSChris Mason 
225be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
226be20aa9dSChris Mason 	*cow_ret = cow;
227be20aa9dSChris Mason 	return 0;
228be20aa9dSChris Mason }
229be20aa9dSChris Mason 
230bd989ba3SJan Schmidt enum mod_log_op {
231bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
232bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
233bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
234bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
235bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
236bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
237bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
238bd989ba3SJan Schmidt };
239bd989ba3SJan Schmidt 
240bd989ba3SJan Schmidt struct tree_mod_root {
241bd989ba3SJan Schmidt 	u64 logical;
242bd989ba3SJan Schmidt 	u8 level;
243bd989ba3SJan Schmidt };
244bd989ba3SJan Schmidt 
245bd989ba3SJan Schmidt struct tree_mod_elem {
246bd989ba3SJan Schmidt 	struct rb_node node;
247298cfd36SChandan Rajendra 	u64 logical;
248097b8a7cSJan Schmidt 	u64 seq;
249bd989ba3SJan Schmidt 	enum mod_log_op op;
250bd989ba3SJan Schmidt 
251bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
252bd989ba3SJan Schmidt 	int slot;
253bd989ba3SJan Schmidt 
254bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
255bd989ba3SJan Schmidt 	u64 generation;
256bd989ba3SJan Schmidt 
257bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
258bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
259bd989ba3SJan Schmidt 	u64 blockptr;
260bd989ba3SJan Schmidt 
261bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
262b6dfa35bSDavid Sterba 	struct {
263b6dfa35bSDavid Sterba 		int dst_slot;
264b6dfa35bSDavid Sterba 		int nr_items;
265b6dfa35bSDavid Sterba 	} move;
266bd989ba3SJan Schmidt 
267bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
268bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
269bd989ba3SJan Schmidt };
270bd989ba3SJan Schmidt 
271097b8a7cSJan Schmidt /*
272fcebe456SJosef Bacik  * Pull a new tree mod seq number for our operation.
273fc36ed7eSJan Schmidt  */
274fcebe456SJosef Bacik static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
275fc36ed7eSJan Schmidt {
276fc36ed7eSJan Schmidt 	return atomic64_inc_return(&fs_info->tree_mod_seq);
277fc36ed7eSJan Schmidt }
278fc36ed7eSJan Schmidt 
279fc36ed7eSJan Schmidt /*
280097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
281097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
282097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
283097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
284097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
285097b8a7cSJan Schmidt  * blocker was added.
286097b8a7cSJan Schmidt  */
287097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
288bd989ba3SJan Schmidt 			   struct seq_list *elem)
289bd989ba3SJan Schmidt {
290b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
291097b8a7cSJan Schmidt 	if (!elem->seq) {
292fcebe456SJosef Bacik 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
293097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
294097b8a7cSJan Schmidt 	}
295b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
296097b8a7cSJan Schmidt 
297fcebe456SJosef Bacik 	return elem->seq;
298bd989ba3SJan Schmidt }
299bd989ba3SJan Schmidt 
300bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
301bd989ba3SJan Schmidt 			    struct seq_list *elem)
302bd989ba3SJan Schmidt {
303bd989ba3SJan Schmidt 	struct rb_root *tm_root;
304bd989ba3SJan Schmidt 	struct rb_node *node;
305bd989ba3SJan Schmidt 	struct rb_node *next;
306bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
307bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
308bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
309bd989ba3SJan Schmidt 
310bd989ba3SJan Schmidt 	if (!seq_putting)
311bd989ba3SJan Schmidt 		return;
312bd989ba3SJan Schmidt 
3137227ff4dSFilipe Manana 	write_lock(&fs_info->tree_mod_log_lock);
314bd989ba3SJan Schmidt 	list_del(&elem->list);
315097b8a7cSJan Schmidt 	elem->seq = 0;
316bd989ba3SJan Schmidt 
31742836cf4SFilipe Manana 	if (!list_empty(&fs_info->tree_mod_seq_list)) {
31842836cf4SFilipe Manana 		struct seq_list *first;
31942836cf4SFilipe Manana 
32042836cf4SFilipe Manana 		first = list_first_entry(&fs_info->tree_mod_seq_list,
32142836cf4SFilipe Manana 					 struct seq_list, list);
32242836cf4SFilipe Manana 		if (seq_putting > first->seq) {
323bd989ba3SJan Schmidt 			/*
32442836cf4SFilipe Manana 			 * Blocker with lower sequence number exists, we
32542836cf4SFilipe Manana 			 * cannot remove anything from the log.
326bd989ba3SJan Schmidt 			 */
3277227ff4dSFilipe Manana 			write_unlock(&fs_info->tree_mod_log_lock);
328097b8a7cSJan Schmidt 			return;
329bd989ba3SJan Schmidt 		}
33042836cf4SFilipe Manana 		min_seq = first->seq;
331bd989ba3SJan Schmidt 	}
332097b8a7cSJan Schmidt 
333097b8a7cSJan Schmidt 	/*
334bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
335bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
336bd989ba3SJan Schmidt 	 */
337bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
338bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
339bd989ba3SJan Schmidt 		next = rb_next(node);
3406b4df8b6SGeliang Tang 		tm = rb_entry(node, struct tree_mod_elem, node);
3416609fee8SFilipe Manana 		if (tm->seq >= min_seq)
342bd989ba3SJan Schmidt 			continue;
343bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
344bd989ba3SJan Schmidt 		kfree(tm);
345bd989ba3SJan Schmidt 	}
346b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
347bd989ba3SJan Schmidt }
348bd989ba3SJan Schmidt 
349bd989ba3SJan Schmidt /*
350bd989ba3SJan Schmidt  * key order of the log:
351298cfd36SChandan Rajendra  *       node/leaf start address -> sequence
352bd989ba3SJan Schmidt  *
353298cfd36SChandan Rajendra  * The 'start address' is the logical address of the *new* root node
354298cfd36SChandan Rajendra  * for root replace operations, or the logical address of the affected
355298cfd36SChandan Rajendra  * block for all other operations.
356bd989ba3SJan Schmidt  */
357bd989ba3SJan Schmidt static noinline int
358bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
359bd989ba3SJan Schmidt {
360bd989ba3SJan Schmidt 	struct rb_root *tm_root;
361bd989ba3SJan Schmidt 	struct rb_node **new;
362bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
363bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
364bd989ba3SJan Schmidt 
36573e82fe4SDavid Sterba 	lockdep_assert_held_write(&fs_info->tree_mod_log_lock);
36673e82fe4SDavid Sterba 
367fcebe456SJosef Bacik 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
368bd989ba3SJan Schmidt 
369bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
370bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
371bd989ba3SJan Schmidt 	while (*new) {
3726b4df8b6SGeliang Tang 		cur = rb_entry(*new, struct tree_mod_elem, node);
373bd989ba3SJan Schmidt 		parent = *new;
374298cfd36SChandan Rajendra 		if (cur->logical < tm->logical)
375bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
376298cfd36SChandan Rajendra 		else if (cur->logical > tm->logical)
377bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
378097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
379bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
380097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
381bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
3825de865eeSFilipe David Borba Manana 		else
3835de865eeSFilipe David Borba Manana 			return -EEXIST;
384bd989ba3SJan Schmidt 	}
385bd989ba3SJan Schmidt 
386bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
387bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
3885de865eeSFilipe David Borba Manana 	return 0;
389bd989ba3SJan Schmidt }
390bd989ba3SJan Schmidt 
391097b8a7cSJan Schmidt /*
392097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
393097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
394097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
395b1a09f1eSDavid Sterba  * write unlock fs_info::tree_mod_log_lock.
396097b8a7cSJan Schmidt  */
397e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
398e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
399e9b7fd4dSJan Schmidt 	smp_mb();
400e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
401e9b7fd4dSJan Schmidt 		return 1;
402097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
403e9b7fd4dSJan Schmidt 		return 1;
4045de865eeSFilipe David Borba Manana 
405b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
4065de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list)) {
407b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
4085de865eeSFilipe David Borba Manana 		return 1;
4095de865eeSFilipe David Borba Manana 	}
4105de865eeSFilipe David Borba Manana 
411e9b7fd4dSJan Schmidt 	return 0;
412e9b7fd4dSJan Schmidt }
413e9b7fd4dSJan Schmidt 
4145de865eeSFilipe David Borba Manana /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
4155de865eeSFilipe David Borba Manana static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
4165de865eeSFilipe David Borba Manana 				    struct extent_buffer *eb)
4175de865eeSFilipe David Borba Manana {
4185de865eeSFilipe David Borba Manana 	smp_mb();
4195de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list))
4205de865eeSFilipe David Borba Manana 		return 0;
4215de865eeSFilipe David Borba Manana 	if (eb && btrfs_header_level(eb) == 0)
4225de865eeSFilipe David Borba Manana 		return 0;
4235de865eeSFilipe David Borba Manana 
4245de865eeSFilipe David Borba Manana 	return 1;
4255de865eeSFilipe David Borba Manana }
4265de865eeSFilipe David Borba Manana 
4275de865eeSFilipe David Borba Manana static struct tree_mod_elem *
4285de865eeSFilipe David Borba Manana alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
429bd989ba3SJan Schmidt 		    enum mod_log_op op, gfp_t flags)
430bd989ba3SJan Schmidt {
431097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
432bd989ba3SJan Schmidt 
433c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
434c8cc6341SJosef Bacik 	if (!tm)
4355de865eeSFilipe David Borba Manana 		return NULL;
436bd989ba3SJan Schmidt 
437298cfd36SChandan Rajendra 	tm->logical = eb->start;
438bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
439bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
440bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
441bd989ba3SJan Schmidt 	}
442bd989ba3SJan Schmidt 	tm->op = op;
443bd989ba3SJan Schmidt 	tm->slot = slot;
444bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
4455de865eeSFilipe David Borba Manana 	RB_CLEAR_NODE(&tm->node);
446bd989ba3SJan Schmidt 
4475de865eeSFilipe David Borba Manana 	return tm;
448097b8a7cSJan Schmidt }
449097b8a7cSJan Schmidt 
450e09c2efeSDavid Sterba static noinline int tree_mod_log_insert_key(struct extent_buffer *eb, int slot,
451097b8a7cSJan Schmidt 		enum mod_log_op op, gfp_t flags)
452097b8a7cSJan Schmidt {
4535de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm;
4545de865eeSFilipe David Borba Manana 	int ret;
4555de865eeSFilipe David Borba Manana 
456e09c2efeSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
457097b8a7cSJan Schmidt 		return 0;
458097b8a7cSJan Schmidt 
4595de865eeSFilipe David Borba Manana 	tm = alloc_tree_mod_elem(eb, slot, op, flags);
4605de865eeSFilipe David Borba Manana 	if (!tm)
4615de865eeSFilipe David Borba Manana 		return -ENOMEM;
4625de865eeSFilipe David Borba Manana 
463e09c2efeSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb)) {
4645de865eeSFilipe David Borba Manana 		kfree(tm);
4655de865eeSFilipe David Borba Manana 		return 0;
4665de865eeSFilipe David Borba Manana 	}
4675de865eeSFilipe David Borba Manana 
468e09c2efeSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
469b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
4705de865eeSFilipe David Borba Manana 	if (ret)
4715de865eeSFilipe David Borba Manana 		kfree(tm);
4725de865eeSFilipe David Borba Manana 
4735de865eeSFilipe David Borba Manana 	return ret;
474097b8a7cSJan Schmidt }
475097b8a7cSJan Schmidt 
4766074d45fSDavid Sterba static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
4776074d45fSDavid Sterba 		int dst_slot, int src_slot, int nr_items)
478bd989ba3SJan Schmidt {
4795de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
4805de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
4815de865eeSFilipe David Borba Manana 	int ret = 0;
482bd989ba3SJan Schmidt 	int i;
4835de865eeSFilipe David Borba Manana 	int locked = 0;
484bd989ba3SJan Schmidt 
4856074d45fSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
486f395694cSJan Schmidt 		return 0;
487bd989ba3SJan Schmidt 
488176ef8f5SDavid Sterba 	tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
4895de865eeSFilipe David Borba Manana 	if (!tm_list)
4905de865eeSFilipe David Borba Manana 		return -ENOMEM;
491bd989ba3SJan Schmidt 
492176ef8f5SDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
4935de865eeSFilipe David Borba Manana 	if (!tm) {
4945de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
4955de865eeSFilipe David Borba Manana 		goto free_tms;
4965de865eeSFilipe David Borba Manana 	}
497f395694cSJan Schmidt 
498298cfd36SChandan Rajendra 	tm->logical = eb->start;
499bd989ba3SJan Schmidt 	tm->slot = src_slot;
500bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
501bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
502bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
503bd989ba3SJan Schmidt 
5045de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5055de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
506176ef8f5SDavid Sterba 		    MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
5075de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
5085de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
5095de865eeSFilipe David Borba Manana 			goto free_tms;
5105de865eeSFilipe David Borba Manana 		}
511bd989ba3SJan Schmidt 	}
512bd989ba3SJan Schmidt 
5136074d45fSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
5145de865eeSFilipe David Borba Manana 		goto free_tms;
5155de865eeSFilipe David Borba Manana 	locked = 1;
5165de865eeSFilipe David Borba Manana 
5175de865eeSFilipe David Borba Manana 	/*
5185de865eeSFilipe David Borba Manana 	 * When we override something during the move, we log these removals.
5195de865eeSFilipe David Borba Manana 	 * This can only happen when we move towards the beginning of the
5205de865eeSFilipe David Borba Manana 	 * buffer, i.e. dst_slot < src_slot.
5215de865eeSFilipe David Borba Manana 	 */
5225de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5236074d45fSDavid Sterba 		ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
5245de865eeSFilipe David Borba Manana 		if (ret)
5255de865eeSFilipe David Borba Manana 			goto free_tms;
5265de865eeSFilipe David Borba Manana 	}
5275de865eeSFilipe David Borba Manana 
5286074d45fSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
5295de865eeSFilipe David Borba Manana 	if (ret)
5305de865eeSFilipe David Borba Manana 		goto free_tms;
531b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
5325de865eeSFilipe David Borba Manana 	kfree(tm_list);
5335de865eeSFilipe David Borba Manana 
5345de865eeSFilipe David Borba Manana 	return 0;
5355de865eeSFilipe David Borba Manana free_tms:
5365de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
5375de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
5386074d45fSDavid Sterba 			rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
5395de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
5405de865eeSFilipe David Borba Manana 	}
5415de865eeSFilipe David Borba Manana 	if (locked)
542b1a09f1eSDavid Sterba 		write_unlock(&eb->fs_info->tree_mod_log_lock);
5435de865eeSFilipe David Borba Manana 	kfree(tm_list);
5445de865eeSFilipe David Borba Manana 	kfree(tm);
5455de865eeSFilipe David Borba Manana 
5465de865eeSFilipe David Borba Manana 	return ret;
5475de865eeSFilipe David Borba Manana }
5485de865eeSFilipe David Borba Manana 
5495de865eeSFilipe David Borba Manana static inline int
5505de865eeSFilipe David Borba Manana __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
5515de865eeSFilipe David Borba Manana 		       struct tree_mod_elem **tm_list,
5525de865eeSFilipe David Borba Manana 		       int nritems)
553097b8a7cSJan Schmidt {
5545de865eeSFilipe David Borba Manana 	int i, j;
555097b8a7cSJan Schmidt 	int ret;
556097b8a7cSJan Schmidt 
557097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
5585de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list[i]);
5595de865eeSFilipe David Borba Manana 		if (ret) {
5605de865eeSFilipe David Borba Manana 			for (j = nritems - 1; j > i; j--)
5615de865eeSFilipe David Borba Manana 				rb_erase(&tm_list[j]->node,
5625de865eeSFilipe David Borba Manana 					 &fs_info->tree_mod_log);
5635de865eeSFilipe David Borba Manana 			return ret;
564097b8a7cSJan Schmidt 		}
565097b8a7cSJan Schmidt 	}
566097b8a7cSJan Schmidt 
5675de865eeSFilipe David Borba Manana 	return 0;
5685de865eeSFilipe David Borba Manana }
5695de865eeSFilipe David Borba Manana 
57095b757c1SDavid Sterba static noinline int tree_mod_log_insert_root(struct extent_buffer *old_root,
57195b757c1SDavid Sterba 			 struct extent_buffer *new_root, int log_removal)
572bd989ba3SJan Schmidt {
57395b757c1SDavid Sterba 	struct btrfs_fs_info *fs_info = old_root->fs_info;
5745de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
5755de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
5765de865eeSFilipe David Borba Manana 	int nritems = 0;
5775de865eeSFilipe David Borba Manana 	int ret = 0;
5785de865eeSFilipe David Borba Manana 	int i;
579bd989ba3SJan Schmidt 
5805de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
581097b8a7cSJan Schmidt 		return 0;
582097b8a7cSJan Schmidt 
5835de865eeSFilipe David Borba Manana 	if (log_removal && btrfs_header_level(old_root) > 0) {
5845de865eeSFilipe David Borba Manana 		nritems = btrfs_header_nritems(old_root);
58531e818feSDavid Sterba 		tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
586bcc8e07fSDavid Sterba 				  GFP_NOFS);
5875de865eeSFilipe David Borba Manana 		if (!tm_list) {
5885de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
5895de865eeSFilipe David Borba Manana 			goto free_tms;
5905de865eeSFilipe David Borba Manana 		}
5915de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++) {
5925de865eeSFilipe David Borba Manana 			tm_list[i] = alloc_tree_mod_elem(old_root, i,
593bcc8e07fSDavid Sterba 			    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
5945de865eeSFilipe David Borba Manana 			if (!tm_list[i]) {
5955de865eeSFilipe David Borba Manana 				ret = -ENOMEM;
5965de865eeSFilipe David Borba Manana 				goto free_tms;
5975de865eeSFilipe David Borba Manana 			}
5985de865eeSFilipe David Borba Manana 		}
5995de865eeSFilipe David Borba Manana 	}
600d9abbf1cSJan Schmidt 
601bcc8e07fSDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
6025de865eeSFilipe David Borba Manana 	if (!tm) {
6035de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
6045de865eeSFilipe David Borba Manana 		goto free_tms;
6055de865eeSFilipe David Borba Manana 	}
606bd989ba3SJan Schmidt 
607298cfd36SChandan Rajendra 	tm->logical = new_root->start;
608bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
609bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
610bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
611bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
612bd989ba3SJan Schmidt 
6135de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
6145de865eeSFilipe David Borba Manana 		goto free_tms;
6155de865eeSFilipe David Borba Manana 
6165de865eeSFilipe David Borba Manana 	if (tm_list)
6175de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
6185de865eeSFilipe David Borba Manana 	if (!ret)
6195de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm);
6205de865eeSFilipe David Borba Manana 
621b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
6225de865eeSFilipe David Borba Manana 	if (ret)
6235de865eeSFilipe David Borba Manana 		goto free_tms;
6245de865eeSFilipe David Borba Manana 	kfree(tm_list);
6255de865eeSFilipe David Borba Manana 
6265de865eeSFilipe David Borba Manana 	return ret;
6275de865eeSFilipe David Borba Manana 
6285de865eeSFilipe David Borba Manana free_tms:
6295de865eeSFilipe David Borba Manana 	if (tm_list) {
6305de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++)
6315de865eeSFilipe David Borba Manana 			kfree(tm_list[i]);
6325de865eeSFilipe David Borba Manana 		kfree(tm_list);
6335de865eeSFilipe David Borba Manana 	}
6345de865eeSFilipe David Borba Manana 	kfree(tm);
6355de865eeSFilipe David Borba Manana 
6365de865eeSFilipe David Borba Manana 	return ret;
637bd989ba3SJan Schmidt }
638bd989ba3SJan Schmidt 
639bd989ba3SJan Schmidt static struct tree_mod_elem *
640bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
641bd989ba3SJan Schmidt 		      int smallest)
642bd989ba3SJan Schmidt {
643bd989ba3SJan Schmidt 	struct rb_root *tm_root;
644bd989ba3SJan Schmidt 	struct rb_node *node;
645bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
646bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
647bd989ba3SJan Schmidt 
648b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
649bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
650bd989ba3SJan Schmidt 	node = tm_root->rb_node;
651bd989ba3SJan Schmidt 	while (node) {
6526b4df8b6SGeliang Tang 		cur = rb_entry(node, struct tree_mod_elem, node);
653298cfd36SChandan Rajendra 		if (cur->logical < start) {
654bd989ba3SJan Schmidt 			node = node->rb_left;
655298cfd36SChandan Rajendra 		} else if (cur->logical > start) {
656bd989ba3SJan Schmidt 			node = node->rb_right;
657097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
658bd989ba3SJan Schmidt 			node = node->rb_left;
659bd989ba3SJan Schmidt 		} else if (!smallest) {
660bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
661bd989ba3SJan Schmidt 			if (found)
662097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
663bd989ba3SJan Schmidt 			found = cur;
664bd989ba3SJan Schmidt 			node = node->rb_left;
665097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
666bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
667bd989ba3SJan Schmidt 			if (found)
668097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
669bd989ba3SJan Schmidt 			found = cur;
670bd989ba3SJan Schmidt 			node = node->rb_right;
671bd989ba3SJan Schmidt 		} else {
672bd989ba3SJan Schmidt 			found = cur;
673bd989ba3SJan Schmidt 			break;
674bd989ba3SJan Schmidt 		}
675bd989ba3SJan Schmidt 	}
676b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
677bd989ba3SJan Schmidt 
678bd989ba3SJan Schmidt 	return found;
679bd989ba3SJan Schmidt }
680bd989ba3SJan Schmidt 
681bd989ba3SJan Schmidt /*
682bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
683bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
684bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
685bd989ba3SJan Schmidt  */
686bd989ba3SJan Schmidt static struct tree_mod_elem *
687bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
688bd989ba3SJan Schmidt 			   u64 min_seq)
689bd989ba3SJan Schmidt {
690bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
691bd989ba3SJan Schmidt }
692bd989ba3SJan Schmidt 
693bd989ba3SJan Schmidt /*
694bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
695bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
696bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
697bd989ba3SJan Schmidt  */
698bd989ba3SJan Schmidt static struct tree_mod_elem *
699bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
700bd989ba3SJan Schmidt {
701bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
702bd989ba3SJan Schmidt }
703bd989ba3SJan Schmidt 
704ed874f0dSDavid Sterba static noinline int tree_mod_log_eb_copy(struct extent_buffer *dst,
705bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
70690f8d62eSJan Schmidt 		     unsigned long src_offset, int nr_items)
707bd989ba3SJan Schmidt {
708ed874f0dSDavid Sterba 	struct btrfs_fs_info *fs_info = dst->fs_info;
7095de865eeSFilipe David Borba Manana 	int ret = 0;
7105de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
7115de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list_add, **tm_list_rem;
712bd989ba3SJan Schmidt 	int i;
7135de865eeSFilipe David Borba Manana 	int locked = 0;
714bd989ba3SJan Schmidt 
7155de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
7165de865eeSFilipe David Borba Manana 		return 0;
717bd989ba3SJan Schmidt 
718c8cc6341SJosef Bacik 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
7195de865eeSFilipe David Borba Manana 		return 0;
7205de865eeSFilipe David Borba Manana 
72131e818feSDavid Sterba 	tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
7225de865eeSFilipe David Borba Manana 			  GFP_NOFS);
7235de865eeSFilipe David Borba Manana 	if (!tm_list)
7245de865eeSFilipe David Borba Manana 		return -ENOMEM;
7255de865eeSFilipe David Borba Manana 
7265de865eeSFilipe David Borba Manana 	tm_list_add = tm_list;
7275de865eeSFilipe David Borba Manana 	tm_list_rem = tm_list + nr_items;
7285de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
7295de865eeSFilipe David Borba Manana 		tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
7305de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE, GFP_NOFS);
7315de865eeSFilipe David Borba Manana 		if (!tm_list_rem[i]) {
7325de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7335de865eeSFilipe David Borba Manana 			goto free_tms;
7345de865eeSFilipe David Borba Manana 		}
7355de865eeSFilipe David Borba Manana 
7365de865eeSFilipe David Borba Manana 		tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
7375de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_ADD, GFP_NOFS);
7385de865eeSFilipe David Borba Manana 		if (!tm_list_add[i]) {
7395de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7405de865eeSFilipe David Borba Manana 			goto free_tms;
7415de865eeSFilipe David Borba Manana 		}
7425de865eeSFilipe David Borba Manana 	}
7435de865eeSFilipe David Borba Manana 
7445de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
7455de865eeSFilipe David Borba Manana 		goto free_tms;
7465de865eeSFilipe David Borba Manana 	locked = 1;
747bd989ba3SJan Schmidt 
748bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
7495de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
7505de865eeSFilipe David Borba Manana 		if (ret)
7515de865eeSFilipe David Borba Manana 			goto free_tms;
7525de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
7535de865eeSFilipe David Borba Manana 		if (ret)
7545de865eeSFilipe David Borba Manana 			goto free_tms;
755bd989ba3SJan Schmidt 	}
7565de865eeSFilipe David Borba Manana 
757b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
7585de865eeSFilipe David Borba Manana 	kfree(tm_list);
7595de865eeSFilipe David Borba Manana 
7605de865eeSFilipe David Borba Manana 	return 0;
7615de865eeSFilipe David Borba Manana 
7625de865eeSFilipe David Borba Manana free_tms:
7635de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items * 2; i++) {
7645de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
7655de865eeSFilipe David Borba Manana 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
7665de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
7675de865eeSFilipe David Borba Manana 	}
7685de865eeSFilipe David Borba Manana 	if (locked)
769b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
7705de865eeSFilipe David Borba Manana 	kfree(tm_list);
7715de865eeSFilipe David Borba Manana 
7725de865eeSFilipe David Borba Manana 	return ret;
773bd989ba3SJan Schmidt }
774bd989ba3SJan Schmidt 
775db7279a2SDavid Sterba static noinline int tree_mod_log_free_eb(struct extent_buffer *eb)
776bd989ba3SJan Schmidt {
7775de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
7785de865eeSFilipe David Borba Manana 	int nritems = 0;
7795de865eeSFilipe David Borba Manana 	int i;
7805de865eeSFilipe David Borba Manana 	int ret = 0;
7815de865eeSFilipe David Borba Manana 
7825de865eeSFilipe David Borba Manana 	if (btrfs_header_level(eb) == 0)
7835de865eeSFilipe David Borba Manana 		return 0;
7845de865eeSFilipe David Borba Manana 
785db7279a2SDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, NULL))
7865de865eeSFilipe David Borba Manana 		return 0;
7875de865eeSFilipe David Borba Manana 
7885de865eeSFilipe David Borba Manana 	nritems = btrfs_header_nritems(eb);
78931e818feSDavid Sterba 	tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
7905de865eeSFilipe David Borba Manana 	if (!tm_list)
7915de865eeSFilipe David Borba Manana 		return -ENOMEM;
7925de865eeSFilipe David Borba Manana 
7935de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++) {
7945de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i,
7955de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
7965de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
7975de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7985de865eeSFilipe David Borba Manana 			goto free_tms;
7995de865eeSFilipe David Borba Manana 		}
8005de865eeSFilipe David Borba Manana 	}
8015de865eeSFilipe David Borba Manana 
802db7279a2SDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
8035de865eeSFilipe David Borba Manana 		goto free_tms;
8045de865eeSFilipe David Borba Manana 
805db7279a2SDavid Sterba 	ret = __tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
806b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
8075de865eeSFilipe David Borba Manana 	if (ret)
8085de865eeSFilipe David Borba Manana 		goto free_tms;
8095de865eeSFilipe David Borba Manana 	kfree(tm_list);
8105de865eeSFilipe David Borba Manana 
8115de865eeSFilipe David Borba Manana 	return 0;
8125de865eeSFilipe David Borba Manana 
8135de865eeSFilipe David Borba Manana free_tms:
8145de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++)
8155de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8165de865eeSFilipe David Borba Manana 	kfree(tm_list);
8175de865eeSFilipe David Borba Manana 
8185de865eeSFilipe David Borba Manana 	return ret;
819bd989ba3SJan Schmidt }
820bd989ba3SJan Schmidt 
821d352ac68SChris Mason /*
8225d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
8235d4f98a2SYan Zheng  */
8245d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
8255d4f98a2SYan Zheng 			      struct extent_buffer *buf)
8265d4f98a2SYan Zheng {
8275d4f98a2SYan Zheng 	/*
82801327610SNicholas D Steeves 	 * Tree blocks not in reference counted trees and tree roots
8295d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
8305d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
8315d4f98a2SYan Zheng 	 * we know the block is not shared.
8325d4f98a2SYan Zheng 	 */
83327cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
8345d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
8355d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
8365d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
8375d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
8385d4f98a2SYan Zheng 		return 1;
839a79865c6SNikolay Borisov 
8405d4f98a2SYan Zheng 	return 0;
8415d4f98a2SYan Zheng }
8425d4f98a2SYan Zheng 
8435d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
8445d4f98a2SYan Zheng 				       struct btrfs_root *root,
8455d4f98a2SYan Zheng 				       struct extent_buffer *buf,
846f0486c68SYan, Zheng 				       struct extent_buffer *cow,
847f0486c68SYan, Zheng 				       int *last_ref)
8485d4f98a2SYan Zheng {
8490b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8505d4f98a2SYan Zheng 	u64 refs;
8515d4f98a2SYan Zheng 	u64 owner;
8525d4f98a2SYan Zheng 	u64 flags;
8535d4f98a2SYan Zheng 	u64 new_flags = 0;
8545d4f98a2SYan Zheng 	int ret;
8555d4f98a2SYan Zheng 
8565d4f98a2SYan Zheng 	/*
8575d4f98a2SYan Zheng 	 * Backrefs update rules:
8585d4f98a2SYan Zheng 	 *
8595d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
8605d4f98a2SYan Zheng 	 * allocated by tree relocation.
8615d4f98a2SYan Zheng 	 *
8625d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
8635d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
8645d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8655d4f98a2SYan Zheng 	 *
8665d4f98a2SYan Zheng 	 * If a tree block is been relocating
8675d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
8685d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
8695d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
8705d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
8715d4f98a2SYan Zheng 	 */
8725d4f98a2SYan Zheng 
8735d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
8742ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
8753173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
8763173a18fSJosef Bacik 					       &refs, &flags);
877be1a5564SMark Fasheh 		if (ret)
878be1a5564SMark Fasheh 			return ret;
879e5df9573SMark Fasheh 		if (refs == 0) {
880e5df9573SMark Fasheh 			ret = -EROFS;
8810b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
882e5df9573SMark Fasheh 			return ret;
883e5df9573SMark Fasheh 		}
8845d4f98a2SYan Zheng 	} else {
8855d4f98a2SYan Zheng 		refs = 1;
8865d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8875d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
8885d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8895d4f98a2SYan Zheng 		else
8905d4f98a2SYan Zheng 			flags = 0;
8915d4f98a2SYan Zheng 	}
8925d4f98a2SYan Zheng 
8935d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
8945d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
8955d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8965d4f98a2SYan Zheng 
8975d4f98a2SYan Zheng 	if (refs > 1) {
8985d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
8995d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
9005d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
901e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
902692826b2SJeff Mahoney 			if (ret)
903692826b2SJeff Mahoney 				return ret;
9045d4f98a2SYan Zheng 
9055d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9065d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
907e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
908692826b2SJeff Mahoney 				if (ret)
909692826b2SJeff Mahoney 					return ret;
910e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
911692826b2SJeff Mahoney 				if (ret)
912692826b2SJeff Mahoney 					return ret;
9135d4f98a2SYan Zheng 			}
9145d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
9155d4f98a2SYan Zheng 		} else {
9165d4f98a2SYan Zheng 
9175d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9185d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
919e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9205d4f98a2SYan Zheng 			else
921e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
922692826b2SJeff Mahoney 			if (ret)
923692826b2SJeff Mahoney 				return ret;
9245d4f98a2SYan Zheng 		}
9255d4f98a2SYan Zheng 		if (new_flags != 0) {
926b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
927b1c79e09SJosef Bacik 
928*42c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
929b1c79e09SJosef Bacik 							  new_flags, level, 0);
930be1a5564SMark Fasheh 			if (ret)
931be1a5564SMark Fasheh 				return ret;
9325d4f98a2SYan Zheng 		}
9335d4f98a2SYan Zheng 	} else {
9345d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
9355d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9365d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
937e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9385d4f98a2SYan Zheng 			else
939e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
940692826b2SJeff Mahoney 			if (ret)
941692826b2SJeff Mahoney 				return ret;
942e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
943692826b2SJeff Mahoney 			if (ret)
944692826b2SJeff Mahoney 				return ret;
9455d4f98a2SYan Zheng 		}
9466a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
947f0486c68SYan, Zheng 		*last_ref = 1;
9485d4f98a2SYan Zheng 	}
9495d4f98a2SYan Zheng 	return 0;
9505d4f98a2SYan Zheng }
9515d4f98a2SYan Zheng 
952a6279470SFilipe Manana static struct extent_buffer *alloc_tree_block_no_bg_flush(
953a6279470SFilipe Manana 					  struct btrfs_trans_handle *trans,
954a6279470SFilipe Manana 					  struct btrfs_root *root,
955a6279470SFilipe Manana 					  u64 parent_start,
956a6279470SFilipe Manana 					  const struct btrfs_disk_key *disk_key,
957a6279470SFilipe Manana 					  int level,
958a6279470SFilipe Manana 					  u64 hint,
959a6279470SFilipe Manana 					  u64 empty_size)
960a6279470SFilipe Manana {
961a6279470SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
962a6279470SFilipe Manana 	struct extent_buffer *ret;
963a6279470SFilipe Manana 
964a6279470SFilipe Manana 	/*
965a6279470SFilipe Manana 	 * If we are COWing a node/leaf from the extent, chunk, device or free
966a6279470SFilipe Manana 	 * space trees, make sure that we do not finish block group creation of
967a6279470SFilipe Manana 	 * pending block groups. We do this to avoid a deadlock.
968a6279470SFilipe Manana 	 * COWing can result in allocation of a new chunk, and flushing pending
969a6279470SFilipe Manana 	 * block groups (btrfs_create_pending_block_groups()) can be triggered
970a6279470SFilipe Manana 	 * when finishing allocation of a new chunk. Creation of a pending block
971a6279470SFilipe Manana 	 * group modifies the extent, chunk, device and free space trees,
972a6279470SFilipe Manana 	 * therefore we could deadlock with ourselves since we are holding a
973a6279470SFilipe Manana 	 * lock on an extent buffer that btrfs_create_pending_block_groups() may
974a6279470SFilipe Manana 	 * try to COW later.
975a6279470SFilipe Manana 	 * For similar reasons, we also need to delay flushing pending block
976a6279470SFilipe Manana 	 * groups when splitting a leaf or node, from one of those trees, since
977a6279470SFilipe Manana 	 * we are holding a write lock on it and its parent or when inserting a
978a6279470SFilipe Manana 	 * new root node for one of those trees.
979a6279470SFilipe Manana 	 */
980a6279470SFilipe Manana 	if (root == fs_info->extent_root ||
981a6279470SFilipe Manana 	    root == fs_info->chunk_root ||
982a6279470SFilipe Manana 	    root == fs_info->dev_root ||
983a6279470SFilipe Manana 	    root == fs_info->free_space_root)
984a6279470SFilipe Manana 		trans->can_flush_pending_bgs = false;
985a6279470SFilipe Manana 
986a6279470SFilipe Manana 	ret = btrfs_alloc_tree_block(trans, root, parent_start,
987a6279470SFilipe Manana 				     root->root_key.objectid, disk_key, level,
988a6279470SFilipe Manana 				     hint, empty_size);
989a6279470SFilipe Manana 	trans->can_flush_pending_bgs = true;
990a6279470SFilipe Manana 
991a6279470SFilipe Manana 	return ret;
992a6279470SFilipe Manana }
993a6279470SFilipe Manana 
9945d4f98a2SYan Zheng /*
995d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
996d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
997d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
998d397712bSChris Mason  * dirty again.
999d352ac68SChris Mason  *
1000d352ac68SChris Mason  * search_start -- an allocation hint for the new block
1001d352ac68SChris Mason  *
1002d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1003d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
1004d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
1005d352ac68SChris Mason  */
1006d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
10075f39d397SChris Mason 			     struct btrfs_root *root,
10085f39d397SChris Mason 			     struct extent_buffer *buf,
10095f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
10105f39d397SChris Mason 			     struct extent_buffer **cow_ret,
10119fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
10126702ed49SChris Mason {
10130b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10145d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
10155f39d397SChris Mason 	struct extent_buffer *cow;
1016be1a5564SMark Fasheh 	int level, ret;
1017f0486c68SYan, Zheng 	int last_ref = 0;
1018925baeddSChris Mason 	int unlock_orig = 0;
10190f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
10206702ed49SChris Mason 
1021925baeddSChris Mason 	if (*cow_ret == buf)
1022925baeddSChris Mason 		unlock_orig = 1;
1023925baeddSChris Mason 
1024b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
1025925baeddSChris Mason 
102627cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
10270b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
102827cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
102927cdeb70SMiao Xie 		trans->transid != root->last_trans);
10305f39d397SChris Mason 
10317bb86316SChris Mason 	level = btrfs_header_level(buf);
103231840ae1SZheng Yan 
10335d4f98a2SYan Zheng 	if (level == 0)
10345d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
10355d4f98a2SYan Zheng 	else
10365d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
10375d4f98a2SYan Zheng 
10380f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
10395d4f98a2SYan Zheng 		parent_start = parent->start;
10405d4f98a2SYan Zheng 
1041a6279470SFilipe Manana 	cow = alloc_tree_block_no_bg_flush(trans, root, parent_start, &disk_key,
1042a6279470SFilipe Manana 					   level, search_start, empty_size);
10436702ed49SChris Mason 	if (IS_ERR(cow))
10446702ed49SChris Mason 		return PTR_ERR(cow);
10456702ed49SChris Mason 
1046b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
1047b4ce94deSChris Mason 
104858e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
1049db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
10505f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
10515d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
10525d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
10535d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
10545d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10555d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
10565d4f98a2SYan Zheng 	else
10575f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
10586702ed49SChris Mason 
1059de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
10602b82032cSYan Zheng 
1061be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1062b68dc2a9SMark Fasheh 	if (ret) {
106366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1064b68dc2a9SMark Fasheh 		return ret;
1065b68dc2a9SMark Fasheh 	}
10661a40e23bSZheng Yan 
106727cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
106883d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
106993314e3bSZhaolei 		if (ret) {
107066642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
107183d4cfd4SJosef Bacik 			return ret;
107283d4cfd4SJosef Bacik 		}
107393314e3bSZhaolei 	}
10743fd0a558SYan, Zheng 
10756702ed49SChris Mason 	if (buf == root->node) {
1076925baeddSChris Mason 		WARN_ON(parent && parent != buf);
10775d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
10785d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
10795d4f98a2SYan Zheng 			parent_start = buf->start;
1080925baeddSChris Mason 
108167439dadSDavid Sterba 		atomic_inc(&cow->refs);
1082d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, cow, 1);
1083d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1084240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1085925baeddSChris Mason 
1086f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
10875581a51aSJan Schmidt 				      last_ref);
10885f39d397SChris Mason 		free_extent_buffer(buf);
10890b86a832SChris Mason 		add_root_to_dirty_list(root);
10906702ed49SChris Mason 	} else {
10915d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1092e09c2efeSDavid Sterba 		tree_mod_log_insert_key(parent, parent_slot,
1093c8cc6341SJosef Bacik 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
10945f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1095db94535dSChris Mason 					cow->start);
109674493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
109774493f7aSChris Mason 					      trans->transid);
10986702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
10995de865eeSFilipe David Borba Manana 		if (last_ref) {
1100db7279a2SDavid Sterba 			ret = tree_mod_log_free_eb(buf);
11015de865eeSFilipe David Borba Manana 			if (ret) {
110266642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
11035de865eeSFilipe David Borba Manana 				return ret;
11045de865eeSFilipe David Borba Manana 			}
11055de865eeSFilipe David Borba Manana 		}
1106f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11075581a51aSJan Schmidt 				      last_ref);
11086702ed49SChris Mason 	}
1109925baeddSChris Mason 	if (unlock_orig)
1110925baeddSChris Mason 		btrfs_tree_unlock(buf);
11113083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
11126702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
11136702ed49SChris Mason 	*cow_ret = cow;
11146702ed49SChris Mason 	return 0;
11156702ed49SChris Mason }
11166702ed49SChris Mason 
11175d9e75c4SJan Schmidt /*
11185d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
11195d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
11205d9e75c4SJan Schmidt  */
1121bcd24dabSDavid Sterba static struct tree_mod_elem *__tree_mod_log_oldest_root(
112230b0463aSJan Schmidt 		struct extent_buffer *eb_root, u64 time_seq)
11235d9e75c4SJan Schmidt {
11245d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11255d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
112630b0463aSJan Schmidt 	u64 root_logical = eb_root->start;
11275d9e75c4SJan Schmidt 	int looped = 0;
11285d9e75c4SJan Schmidt 
11295d9e75c4SJan Schmidt 	if (!time_seq)
113035a3621bSStefan Behrens 		return NULL;
11315d9e75c4SJan Schmidt 
11325d9e75c4SJan Schmidt 	/*
1133298cfd36SChandan Rajendra 	 * the very last operation that's logged for a root is the
1134298cfd36SChandan Rajendra 	 * replacement operation (if it is replaced at all). this has
1135298cfd36SChandan Rajendra 	 * the logical address of the *new* root, making it the very
1136298cfd36SChandan Rajendra 	 * first operation that's logged for this root.
11375d9e75c4SJan Schmidt 	 */
11385d9e75c4SJan Schmidt 	while (1) {
1139bcd24dabSDavid Sterba 		tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
11405d9e75c4SJan Schmidt 						time_seq);
11415d9e75c4SJan Schmidt 		if (!looped && !tm)
114235a3621bSStefan Behrens 			return NULL;
11435d9e75c4SJan Schmidt 		/*
114428da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
114528da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
114628da9fb4SJan Schmidt 		 * level 0.
11475d9e75c4SJan Schmidt 		 */
114828da9fb4SJan Schmidt 		if (!tm)
114928da9fb4SJan Schmidt 			break;
11505d9e75c4SJan Schmidt 
115128da9fb4SJan Schmidt 		/*
115228da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
115328da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
115428da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
115528da9fb4SJan Schmidt 		 */
11565d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
11575d9e75c4SJan Schmidt 			break;
11585d9e75c4SJan Schmidt 
11595d9e75c4SJan Schmidt 		found = tm;
11605d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
11615d9e75c4SJan Schmidt 		looped = 1;
11625d9e75c4SJan Schmidt 	}
11635d9e75c4SJan Schmidt 
1164a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1165a95236d9SJan Schmidt 	if (!found)
1166a95236d9SJan Schmidt 		found = tm;
1167a95236d9SJan Schmidt 
11685d9e75c4SJan Schmidt 	return found;
11695d9e75c4SJan Schmidt }
11705d9e75c4SJan Schmidt 
11715d9e75c4SJan Schmidt /*
11725d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
117301327610SNicholas D Steeves  * previous operations will be rewound (until we reach something older than
11745d9e75c4SJan Schmidt  * time_seq).
11755d9e75c4SJan Schmidt  */
11765d9e75c4SJan Schmidt static void
1177f1ca7e98SJosef Bacik __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1178f1ca7e98SJosef Bacik 		      u64 time_seq, struct tree_mod_elem *first_tm)
11795d9e75c4SJan Schmidt {
11805d9e75c4SJan Schmidt 	u32 n;
11815d9e75c4SJan Schmidt 	struct rb_node *next;
11825d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
11835d9e75c4SJan Schmidt 	unsigned long o_dst;
11845d9e75c4SJan Schmidt 	unsigned long o_src;
11855d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
11865d9e75c4SJan Schmidt 
11875d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1188b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
1189097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
11905d9e75c4SJan Schmidt 		/*
11915d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
11925d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
11935d9e75c4SJan Schmidt 		 * opposite of each operation here.
11945d9e75c4SJan Schmidt 		 */
11955d9e75c4SJan Schmidt 		switch (tm->op) {
11965d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
11975d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
11981c697d4aSEric Sandeen 			/* Fallthrough */
119995c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
12004c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
12015d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12025d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12035d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12045d9e75c4SJan Schmidt 						      tm->generation);
12054c3e6969SChris Mason 			n++;
12065d9e75c4SJan Schmidt 			break;
12075d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
12085d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
12095d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12105d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12115d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12125d9e75c4SJan Schmidt 						      tm->generation);
12135d9e75c4SJan Schmidt 			break;
12145d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
121519956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
12165d9e75c4SJan Schmidt 			n--;
12175d9e75c4SJan Schmidt 			break;
12185d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1219c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1220c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1221c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
12225d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
12235d9e75c4SJan Schmidt 			break;
12245d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
12255d9e75c4SJan Schmidt 			/*
12265d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
12275d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
12285d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
12295d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
12305d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
12315d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
12325d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
12335d9e75c4SJan Schmidt 			 */
12345d9e75c4SJan Schmidt 			break;
12355d9e75c4SJan Schmidt 		}
12365d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
12375d9e75c4SJan Schmidt 		if (!next)
12385d9e75c4SJan Schmidt 			break;
12396b4df8b6SGeliang Tang 		tm = rb_entry(next, struct tree_mod_elem, node);
1240298cfd36SChandan Rajendra 		if (tm->logical != first_tm->logical)
12415d9e75c4SJan Schmidt 			break;
12425d9e75c4SJan Schmidt 	}
1243b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
12445d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
12455d9e75c4SJan Schmidt }
12465d9e75c4SJan Schmidt 
124747fb091fSJan Schmidt /*
124801327610SNicholas D Steeves  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
124947fb091fSJan Schmidt  * is returned. If rewind operations happen, a fresh buffer is returned. The
125047fb091fSJan Schmidt  * returned buffer is always read-locked. If the returned buffer is not the
125147fb091fSJan Schmidt  * input buffer, the lock on the input buffer is released and the input buffer
125247fb091fSJan Schmidt  * is freed (its refcount is decremented).
125347fb091fSJan Schmidt  */
12545d9e75c4SJan Schmidt static struct extent_buffer *
12559ec72677SJosef Bacik tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
12569ec72677SJosef Bacik 		    struct extent_buffer *eb, u64 time_seq)
12575d9e75c4SJan Schmidt {
12585d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
12595d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
12605d9e75c4SJan Schmidt 
12615d9e75c4SJan Schmidt 	if (!time_seq)
12625d9e75c4SJan Schmidt 		return eb;
12635d9e75c4SJan Schmidt 
12645d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
12655d9e75c4SJan Schmidt 		return eb;
12665d9e75c4SJan Schmidt 
12675d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
12685d9e75c4SJan Schmidt 	if (!tm)
12695d9e75c4SJan Schmidt 		return eb;
12705d9e75c4SJan Schmidt 
12719ec72677SJosef Bacik 	btrfs_set_path_blocking(path);
1272300aa896SDavid Sterba 	btrfs_set_lock_blocking_read(eb);
12739ec72677SJosef Bacik 
12745d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
12755d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
1276da17066cSJeff Mahoney 		eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1277db7f3436SJosef Bacik 		if (!eb_rewin) {
12789ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1279db7f3436SJosef Bacik 			free_extent_buffer(eb);
1280db7f3436SJosef Bacik 			return NULL;
1281db7f3436SJosef Bacik 		}
12825d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
12835d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
12845d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
12855d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1286c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
12875d9e75c4SJan Schmidt 	} else {
12885d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
1289db7f3436SJosef Bacik 		if (!eb_rewin) {
12909ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1291db7f3436SJosef Bacik 			free_extent_buffer(eb);
1292db7f3436SJosef Bacik 			return NULL;
1293db7f3436SJosef Bacik 		}
12945d9e75c4SJan Schmidt 	}
12955d9e75c4SJan Schmidt 
12969ec72677SJosef Bacik 	btrfs_tree_read_unlock_blocking(eb);
12975d9e75c4SJan Schmidt 	free_extent_buffer(eb);
12985d9e75c4SJan Schmidt 
129947fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1300f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
130157911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
1302da17066cSJeff Mahoney 		BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13035d9e75c4SJan Schmidt 
13045d9e75c4SJan Schmidt 	return eb_rewin;
13055d9e75c4SJan Schmidt }
13065d9e75c4SJan Schmidt 
13078ba97a15SJan Schmidt /*
13088ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
13098ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
13108ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
13118ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
13128ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
13138ba97a15SJan Schmidt  */
13145d9e75c4SJan Schmidt static inline struct extent_buffer *
13155d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
13165d9e75c4SJan Schmidt {
13170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13185d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
131930b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
132030b0463aSJan Schmidt 	struct extent_buffer *eb_root;
1321efad8a85SFilipe Manana 	u64 eb_root_owner = 0;
13227bfdcf7fSLiu Bo 	struct extent_buffer *old;
1323a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
13244325edd0SChris Mason 	u64 old_generation = 0;
1325a95236d9SJan Schmidt 	u64 logical;
1326581c1760SQu Wenruo 	int level;
13275d9e75c4SJan Schmidt 
132830b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
1329bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
13305d9e75c4SJan Schmidt 	if (!tm)
133130b0463aSJan Schmidt 		return eb_root;
13325d9e75c4SJan Schmidt 
1333a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
13345d9e75c4SJan Schmidt 		old_root = &tm->old_root;
13355d9e75c4SJan Schmidt 		old_generation = tm->generation;
1336a95236d9SJan Schmidt 		logical = old_root->logical;
1337581c1760SQu Wenruo 		level = old_root->level;
1338a95236d9SJan Schmidt 	} else {
133930b0463aSJan Schmidt 		logical = eb_root->start;
1340581c1760SQu Wenruo 		level = btrfs_header_level(eb_root);
1341a95236d9SJan Schmidt 	}
13425d9e75c4SJan Schmidt 
13430b246afaSJeff Mahoney 	tm = tree_mod_log_search(fs_info, logical, time_seq);
1344834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
134530b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
134630b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1347581c1760SQu Wenruo 		old = read_tree_block(fs_info, logical, 0, level, NULL);
134864c043deSLiu Bo 		if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
134964c043deSLiu Bo 			if (!IS_ERR(old))
1350416bc658SJosef Bacik 				free_extent_buffer(old);
13510b246afaSJeff Mahoney 			btrfs_warn(fs_info,
13520b246afaSJeff Mahoney 				   "failed to read tree block %llu from get_old_root",
13530b246afaSJeff Mahoney 				   logical);
1354834328a8SJan Schmidt 		} else {
13557bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
13567bfdcf7fSLiu Bo 			free_extent_buffer(old);
1357834328a8SJan Schmidt 		}
1358834328a8SJan Schmidt 	} else if (old_root) {
1359efad8a85SFilipe Manana 		eb_root_owner = btrfs_header_owner(eb_root);
136030b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
136130b0463aSJan Schmidt 		free_extent_buffer(eb_root);
13620b246afaSJeff Mahoney 		eb = alloc_dummy_extent_buffer(fs_info, logical);
1363834328a8SJan Schmidt 	} else {
1364300aa896SDavid Sterba 		btrfs_set_lock_blocking_read(eb_root);
136530b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
13669ec72677SJosef Bacik 		btrfs_tree_read_unlock_blocking(eb_root);
136730b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1368834328a8SJan Schmidt 	}
1369834328a8SJan Schmidt 
13708ba97a15SJan Schmidt 	if (!eb)
13718ba97a15SJan Schmidt 		return NULL;
13728ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1373a95236d9SJan Schmidt 	if (old_root) {
13745d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
13755d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1376efad8a85SFilipe Manana 		btrfs_set_header_owner(eb, eb_root_owner);
13775d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
13785d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1379a95236d9SJan Schmidt 	}
138028da9fb4SJan Schmidt 	if (tm)
13810b246afaSJeff Mahoney 		__tree_mod_log_rewind(fs_info, eb, time_seq, tm);
138228da9fb4SJan Schmidt 	else
138328da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
13840b246afaSJeff Mahoney 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13855d9e75c4SJan Schmidt 
13865d9e75c4SJan Schmidt 	return eb;
13875d9e75c4SJan Schmidt }
13885d9e75c4SJan Schmidt 
13895b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
13905b6602e7SJan Schmidt {
13915b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
13925b6602e7SJan Schmidt 	int level;
139330b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
13945b6602e7SJan Schmidt 
1395bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
13965b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
13975b6602e7SJan Schmidt 		level = tm->old_root.level;
13985b6602e7SJan Schmidt 	} else {
139930b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
14005b6602e7SJan Schmidt 	}
140130b0463aSJan Schmidt 	free_extent_buffer(eb_root);
14025b6602e7SJan Schmidt 
14035b6602e7SJan Schmidt 	return level;
14045b6602e7SJan Schmidt }
14055b6602e7SJan Schmidt 
14065d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
14075d4f98a2SYan Zheng 				   struct btrfs_root *root,
14085d4f98a2SYan Zheng 				   struct extent_buffer *buf)
14095d4f98a2SYan Zheng {
1410f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
1411faa2dbf0SJosef Bacik 		return 0;
1412fccb84c9SDavid Sterba 
1413d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
1414d1980131SDavid Sterba 	smp_mb__before_atomic();
1415f1ebcc74SLiu Bo 
1416f1ebcc74SLiu Bo 	/*
1417f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1418f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1419f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1420f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1421f1ebcc74SLiu Bo 	 *
1422f1ebcc74SLiu Bo 	 * What is forced COW:
142301327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
142452042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
1425f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1426f1ebcc74SLiu Bo 	 */
14275d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
14285d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
14295d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1430f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
143127cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
14325d4f98a2SYan Zheng 		return 0;
14335d4f98a2SYan Zheng 	return 1;
14345d4f98a2SYan Zheng }
14355d4f98a2SYan Zheng 
1436d352ac68SChris Mason /*
1437d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
143801327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
1439d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1440d352ac68SChris Mason  */
1441d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
14425f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
14435f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
14449fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
144502217ed2SChris Mason {
14460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14476702ed49SChris Mason 	u64 search_start;
1448f510cfecSChris Mason 	int ret;
1449dc17ff8fSChris Mason 
145083354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
145183354f07SJosef Bacik 		btrfs_err(fs_info,
145283354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
145383354f07SJosef Bacik 
14540b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
145531b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1456c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
14570b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
145831b1a2bdSJulia Lawall 
14590b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
146031b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
14610b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
1462dc17ff8fSChris Mason 
14635d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
146464c12921SJeff Mahoney 		trans->dirty = true;
146502217ed2SChris Mason 		*cow_ret = buf;
146602217ed2SChris Mason 		return 0;
146702217ed2SChris Mason 	}
1468c487685dSChris Mason 
1469ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
1470b4ce94deSChris Mason 
1471b4ce94deSChris Mason 	if (parent)
14728bead258SDavid Sterba 		btrfs_set_lock_blocking_write(parent);
14738bead258SDavid Sterba 	btrfs_set_lock_blocking_write(buf);
1474b4ce94deSChris Mason 
1475f616f5cdSQu Wenruo 	/*
1476f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
1477f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
1478f616f5cdSQu Wenruo 	 *
1479f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
1480f616f5cdSQu Wenruo 	 */
1481f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
1482f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
14839fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
14841abe9b8aSliubo 
14851abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
14861abe9b8aSliubo 
1487f510cfecSChris Mason 	return ret;
14882c90e5d6SChris Mason }
14896702ed49SChris Mason 
1490d352ac68SChris Mason /*
1491d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1492d352ac68SChris Mason  * node are actually close by
1493d352ac68SChris Mason  */
14946b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
14956702ed49SChris Mason {
14966b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
14976702ed49SChris Mason 		return 1;
14986b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
14996702ed49SChris Mason 		return 1;
150002217ed2SChris Mason 	return 0;
150102217ed2SChris Mason }
150202217ed2SChris Mason 
1503081e9573SChris Mason /*
1504081e9573SChris Mason  * compare two keys in a memcmp fashion
1505081e9573SChris Mason  */
1506310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
1507310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
1508081e9573SChris Mason {
1509081e9573SChris Mason 	struct btrfs_key k1;
1510081e9573SChris Mason 
1511081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1512081e9573SChris Mason 
151320736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1514081e9573SChris Mason }
1515081e9573SChris Mason 
1516f3465ca4SJosef Bacik /*
1517f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1518f3465ca4SJosef Bacik  */
1519e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1520f3465ca4SJosef Bacik {
1521f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1522f3465ca4SJosef Bacik 		return 1;
1523f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1524f3465ca4SJosef Bacik 		return -1;
1525f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1526f3465ca4SJosef Bacik 		return 1;
1527f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1528f3465ca4SJosef Bacik 		return -1;
1529f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1530f3465ca4SJosef Bacik 		return 1;
1531f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1532f3465ca4SJosef Bacik 		return -1;
1533f3465ca4SJosef Bacik 	return 0;
1534f3465ca4SJosef Bacik }
1535081e9573SChris Mason 
1536d352ac68SChris Mason /*
1537d352ac68SChris Mason  * this is used by the defrag code to go through all the
1538d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1539d352ac68SChris Mason  * disk order is close to key order
1540d352ac68SChris Mason  */
15416702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
15425f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1543de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1544a6b6e75eSChris Mason 		       struct btrfs_key *progress)
15456702ed49SChris Mason {
15460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15476b80053dSChris Mason 	struct extent_buffer *cur;
15486702ed49SChris Mason 	u64 blocknr;
1549ca7a79adSChris Mason 	u64 gen;
1550e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1551e9d0b13bSChris Mason 	u64 last_block = 0;
15526702ed49SChris Mason 	u64 other;
15536702ed49SChris Mason 	u32 parent_nritems;
15546702ed49SChris Mason 	int end_slot;
15556702ed49SChris Mason 	int i;
15566702ed49SChris Mason 	int err = 0;
1557f2183bdeSChris Mason 	int parent_level;
15586b80053dSChris Mason 	int uptodate;
15596b80053dSChris Mason 	u32 blocksize;
1560081e9573SChris Mason 	int progress_passed = 0;
1561081e9573SChris Mason 	struct btrfs_disk_key disk_key;
15626702ed49SChris Mason 
15635708b959SChris Mason 	parent_level = btrfs_header_level(parent);
15645708b959SChris Mason 
15650b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
15660b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
156786479a04SChris Mason 
15686b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
15690b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
15705dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
15716702ed49SChris Mason 
15725dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
15736702ed49SChris Mason 		return 0;
15746702ed49SChris Mason 
15758bead258SDavid Sterba 	btrfs_set_lock_blocking_write(parent);
1576b4ce94deSChris Mason 
15775dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
1578581c1760SQu Wenruo 		struct btrfs_key first_key;
15796702ed49SChris Mason 		int close = 1;
1580a6b6e75eSChris Mason 
1581081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1582081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1583081e9573SChris Mason 			continue;
1584081e9573SChris Mason 
1585081e9573SChris Mason 		progress_passed = 1;
15866b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1587ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1588581c1760SQu Wenruo 		btrfs_node_key_to_cpu(parent, &first_key, i);
1589e9d0b13bSChris Mason 		if (last_block == 0)
1590e9d0b13bSChris Mason 			last_block = blocknr;
15915708b959SChris Mason 
15926702ed49SChris Mason 		if (i > 0) {
15936b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
15946b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
15956702ed49SChris Mason 		}
15965dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
15976b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
15986b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
15996702ed49SChris Mason 		}
1600e9d0b13bSChris Mason 		if (close) {
1601e9d0b13bSChris Mason 			last_block = blocknr;
16026702ed49SChris Mason 			continue;
1603e9d0b13bSChris Mason 		}
16046702ed49SChris Mason 
16050b246afaSJeff Mahoney 		cur = find_extent_buffer(fs_info, blocknr);
16066b80053dSChris Mason 		if (cur)
1607b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
16086b80053dSChris Mason 		else
16096b80053dSChris Mason 			uptodate = 0;
16105708b959SChris Mason 		if (!cur || !uptodate) {
16116b80053dSChris Mason 			if (!cur) {
1612581c1760SQu Wenruo 				cur = read_tree_block(fs_info, blocknr, gen,
1613581c1760SQu Wenruo 						      parent_level - 1,
1614581c1760SQu Wenruo 						      &first_key);
161564c043deSLiu Bo 				if (IS_ERR(cur)) {
161664c043deSLiu Bo 					return PTR_ERR(cur);
161764c043deSLiu Bo 				} else if (!extent_buffer_uptodate(cur)) {
1618416bc658SJosef Bacik 					free_extent_buffer(cur);
161997d9a8a4STsutomu Itoh 					return -EIO;
1620416bc658SJosef Bacik 				}
16216b80053dSChris Mason 			} else if (!uptodate) {
1622581c1760SQu Wenruo 				err = btrfs_read_buffer(cur, gen,
1623581c1760SQu Wenruo 						parent_level - 1,&first_key);
1624018642a1STsutomu Itoh 				if (err) {
1625018642a1STsutomu Itoh 					free_extent_buffer(cur);
1626018642a1STsutomu Itoh 					return err;
1627018642a1STsutomu Itoh 				}
16286702ed49SChris Mason 			}
1629f2183bdeSChris Mason 		}
1630e9d0b13bSChris Mason 		if (search_start == 0)
16316b80053dSChris Mason 			search_start = last_block;
1632e9d0b13bSChris Mason 
1633e7a84565SChris Mason 		btrfs_tree_lock(cur);
16348bead258SDavid Sterba 		btrfs_set_lock_blocking_write(cur);
16356b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1636e7a84565SChris Mason 					&cur, search_start,
16376b80053dSChris Mason 					min(16 * blocksize,
16389fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1639252c38f0SYan 		if (err) {
1640e7a84565SChris Mason 			btrfs_tree_unlock(cur);
16416b80053dSChris Mason 			free_extent_buffer(cur);
16426702ed49SChris Mason 			break;
1643252c38f0SYan 		}
1644e7a84565SChris Mason 		search_start = cur->start;
1645e7a84565SChris Mason 		last_block = cur->start;
1646f2183bdeSChris Mason 		*last_ret = search_start;
1647e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1648e7a84565SChris Mason 		free_extent_buffer(cur);
16496702ed49SChris Mason 	}
16506702ed49SChris Mason 	return err;
16516702ed49SChris Mason }
16526702ed49SChris Mason 
165374123bd7SChris Mason /*
16545f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
16555f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
16565f39d397SChris Mason  *
165774123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
165874123bd7SChris Mason  * the place where you would insert key if it is not found in
165974123bd7SChris Mason  * the array.
166074123bd7SChris Mason  *
166174123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
166274123bd7SChris Mason  */
1663e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1664310712b2SOmar Sandoval 				       unsigned long p, int item_size,
1665310712b2SOmar Sandoval 				       const struct btrfs_key *key,
1666be0e5c09SChris Mason 				       int max, int *slot)
1667be0e5c09SChris Mason {
1668be0e5c09SChris Mason 	int low = 0;
1669be0e5c09SChris Mason 	int high = max;
1670be0e5c09SChris Mason 	int mid;
1671be0e5c09SChris Mason 	int ret;
1672479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
16735f39d397SChris Mason 	struct btrfs_disk_key unaligned;
16745f39d397SChris Mason 	unsigned long offset;
16755f39d397SChris Mason 	char *kaddr = NULL;
16765f39d397SChris Mason 	unsigned long map_start = 0;
16775f39d397SChris Mason 	unsigned long map_len = 0;
1678479965d6SChris Mason 	int err;
1679be0e5c09SChris Mason 
16805e24e9afSLiu Bo 	if (low > high) {
16815e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
16825e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
16835e24e9afSLiu Bo 			  __func__, low, high, eb->start,
16845e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
16855e24e9afSLiu Bo 		return -EINVAL;
16865e24e9afSLiu Bo 	}
16875e24e9afSLiu Bo 
1688be0e5c09SChris Mason 	while (low < high) {
1689be0e5c09SChris Mason 		mid = (low + high) / 2;
16905f39d397SChris Mason 		offset = p + mid * item_size;
16915f39d397SChris Mason 
1692a6591715SChris Mason 		if (!kaddr || offset < map_start ||
16935f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
16945f39d397SChris Mason 		    map_start + map_len) {
1695934d375bSChris Mason 
1696934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1697479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1698a6591715SChris Mason 						&kaddr, &map_start, &map_len);
16995f39d397SChris Mason 
1700479965d6SChris Mason 			if (!err) {
1701479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1702479965d6SChris Mason 							map_start);
1703415b35a5SLiu Bo 			} else if (err == 1) {
17045f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
17055f39d397SChris Mason 						   offset, sizeof(unaligned));
17065f39d397SChris Mason 				tmp = &unaligned;
1707415b35a5SLiu Bo 			} else {
1708415b35a5SLiu Bo 				return err;
1709479965d6SChris Mason 			}
1710479965d6SChris Mason 
17115f39d397SChris Mason 		} else {
17125f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
17135f39d397SChris Mason 							map_start);
17145f39d397SChris Mason 		}
1715be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1716be0e5c09SChris Mason 
1717be0e5c09SChris Mason 		if (ret < 0)
1718be0e5c09SChris Mason 			low = mid + 1;
1719be0e5c09SChris Mason 		else if (ret > 0)
1720be0e5c09SChris Mason 			high = mid;
1721be0e5c09SChris Mason 		else {
1722be0e5c09SChris Mason 			*slot = mid;
1723be0e5c09SChris Mason 			return 0;
1724be0e5c09SChris Mason 		}
1725be0e5c09SChris Mason 	}
1726be0e5c09SChris Mason 	*slot = low;
1727be0e5c09SChris Mason 	return 1;
1728be0e5c09SChris Mason }
1729be0e5c09SChris Mason 
173097571fd0SChris Mason /*
173197571fd0SChris Mason  * simple bin_search frontend that does the right thing for
173297571fd0SChris Mason  * leaves vs nodes
173397571fd0SChris Mason  */
1734a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
17355f39d397SChris Mason 		     int level, int *slot)
1736be0e5c09SChris Mason {
1737f775738fSWang Sheng-Hui 	if (level == 0)
17385f39d397SChris Mason 		return generic_bin_search(eb,
17395f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
17400783fcfcSChris Mason 					  sizeof(struct btrfs_item),
17415f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17427518a238SChris Mason 					  slot);
1743f775738fSWang Sheng-Hui 	else
17445f39d397SChris Mason 		return generic_bin_search(eb,
17455f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1746123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
17475f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17487518a238SChris Mason 					  slot);
1749be0e5c09SChris Mason }
1750be0e5c09SChris Mason 
1751f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1752f0486c68SYan, Zheng {
1753f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1754f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1755f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1756f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1757f0486c68SYan, Zheng }
1758f0486c68SYan, Zheng 
1759f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1760f0486c68SYan, Zheng {
1761f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1762f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1763f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1764f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1765f0486c68SYan, Zheng }
1766f0486c68SYan, Zheng 
1767d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1768d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1769d352ac68SChris Mason  */
17704b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
17714b231ae4SDavid Sterba 					   int slot)
1772bb803951SChris Mason {
1773ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1774416bc658SJosef Bacik 	struct extent_buffer *eb;
1775581c1760SQu Wenruo 	struct btrfs_key first_key;
1776416bc658SJosef Bacik 
1777fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
1778fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
1779ca7a79adSChris Mason 
1780ca7a79adSChris Mason 	BUG_ON(level == 0);
1781ca7a79adSChris Mason 
1782581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
1783d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1784581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
1785581c1760SQu Wenruo 			     level - 1, &first_key);
1786fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1787416bc658SJosef Bacik 		free_extent_buffer(eb);
1788fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
1789416bc658SJosef Bacik 	}
1790416bc658SJosef Bacik 
1791416bc658SJosef Bacik 	return eb;
1792bb803951SChris Mason }
1793bb803951SChris Mason 
1794d352ac68SChris Mason /*
1795d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1796d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1797d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1798d352ac68SChris Mason  */
1799e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
180098ed5174SChris Mason 			 struct btrfs_root *root,
180198ed5174SChris Mason 			 struct btrfs_path *path, int level)
1802bb803951SChris Mason {
18030b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
18045f39d397SChris Mason 	struct extent_buffer *right = NULL;
18055f39d397SChris Mason 	struct extent_buffer *mid;
18065f39d397SChris Mason 	struct extent_buffer *left = NULL;
18075f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1808bb803951SChris Mason 	int ret = 0;
1809bb803951SChris Mason 	int wret;
1810bb803951SChris Mason 	int pslot;
1811bb803951SChris Mason 	int orig_slot = path->slots[level];
181279f95c82SChris Mason 	u64 orig_ptr;
1813bb803951SChris Mason 
181498e6b1ebSLiu Bo 	ASSERT(level > 0);
1815bb803951SChris Mason 
18165f39d397SChris Mason 	mid = path->nodes[level];
1817b4ce94deSChris Mason 
1818bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1819bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
18207bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
18217bb86316SChris Mason 
18221d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
182379f95c82SChris Mason 
1824a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18255f39d397SChris Mason 		parent = path->nodes[level + 1];
1826bb803951SChris Mason 		pslot = path->slots[level + 1];
1827a05a9bb1SLi Zefan 	}
1828bb803951SChris Mason 
182940689478SChris Mason 	/*
183040689478SChris Mason 	 * deal with the case where there is only one pointer in the root
183140689478SChris Mason 	 * by promoting the node below to a root
183240689478SChris Mason 	 */
18335f39d397SChris Mason 	if (!parent) {
18345f39d397SChris Mason 		struct extent_buffer *child;
1835bb803951SChris Mason 
18365f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1837bb803951SChris Mason 			return 0;
1838bb803951SChris Mason 
1839bb803951SChris Mason 		/* promote the child to a root */
18404b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1841fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1842fb770ae4SLiu Bo 			ret = PTR_ERR(child);
18430b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1844305a26afSMark Fasheh 			goto enospc;
1845305a26afSMark Fasheh 		}
1846305a26afSMark Fasheh 
1847925baeddSChris Mason 		btrfs_tree_lock(child);
18488bead258SDavid Sterba 		btrfs_set_lock_blocking_write(child);
18499fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1850f0486c68SYan, Zheng 		if (ret) {
1851f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1852f0486c68SYan, Zheng 			free_extent_buffer(child);
1853f0486c68SYan, Zheng 			goto enospc;
1854f0486c68SYan, Zheng 		}
18552f375ab9SYan 
1856d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, child, 1);
1857d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1858240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1859925baeddSChris Mason 
18600b86a832SChris Mason 		add_root_to_dirty_list(root);
1861925baeddSChris Mason 		btrfs_tree_unlock(child);
1862b4ce94deSChris Mason 
1863925baeddSChris Mason 		path->locks[level] = 0;
1864bb803951SChris Mason 		path->nodes[level] = NULL;
18656a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1866925baeddSChris Mason 		btrfs_tree_unlock(mid);
1867bb803951SChris Mason 		/* once for the path */
18685f39d397SChris Mason 		free_extent_buffer(mid);
1869f0486c68SYan, Zheng 
1870f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
18715581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1872bb803951SChris Mason 		/* once for the root ptr */
18733083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1874f0486c68SYan, Zheng 		return 0;
1875bb803951SChris Mason 	}
18765f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
18770b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1878bb803951SChris Mason 		return 0;
1879bb803951SChris Mason 
18804b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1881fb770ae4SLiu Bo 	if (IS_ERR(left))
1882fb770ae4SLiu Bo 		left = NULL;
1883fb770ae4SLiu Bo 
18845f39d397SChris Mason 	if (left) {
1885925baeddSChris Mason 		btrfs_tree_lock(left);
18868bead258SDavid Sterba 		btrfs_set_lock_blocking_write(left);
18875f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
18889fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
188954aa1f4dSChris Mason 		if (wret) {
189054aa1f4dSChris Mason 			ret = wret;
189154aa1f4dSChris Mason 			goto enospc;
189254aa1f4dSChris Mason 		}
18932cc58cf2SChris Mason 	}
1894fb770ae4SLiu Bo 
18954b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1896fb770ae4SLiu Bo 	if (IS_ERR(right))
1897fb770ae4SLiu Bo 		right = NULL;
1898fb770ae4SLiu Bo 
18995f39d397SChris Mason 	if (right) {
1900925baeddSChris Mason 		btrfs_tree_lock(right);
19018bead258SDavid Sterba 		btrfs_set_lock_blocking_write(right);
19025f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
19039fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
19042cc58cf2SChris Mason 		if (wret) {
19052cc58cf2SChris Mason 			ret = wret;
19062cc58cf2SChris Mason 			goto enospc;
19072cc58cf2SChris Mason 		}
19082cc58cf2SChris Mason 	}
19092cc58cf2SChris Mason 
19102cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
19115f39d397SChris Mason 	if (left) {
19125f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1913d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
191479f95c82SChris Mason 		if (wret < 0)
191579f95c82SChris Mason 			ret = wret;
1916bb803951SChris Mason 	}
191779f95c82SChris Mason 
191879f95c82SChris Mason 	/*
191979f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
192079f95c82SChris Mason 	 */
19215f39d397SChris Mason 	if (right) {
1922d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
192354aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
192479f95c82SChris Mason 			ret = wret;
19255f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
19266a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1927925baeddSChris Mason 			btrfs_tree_unlock(right);
1928afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1929f0486c68SYan, Zheng 			root_sub_used(root, right->len);
19305581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
19313083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1932f0486c68SYan, Zheng 			right = NULL;
1933bb803951SChris Mason 		} else {
19345f39d397SChris Mason 			struct btrfs_disk_key right_key;
19355f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
19360e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
19370e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
19380e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
19395f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
19405f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1941bb803951SChris Mason 		}
1942bb803951SChris Mason 	}
19435f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
194479f95c82SChris Mason 		/*
194579f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
194679f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
194779f95c82SChris Mason 		 * could try to delete the only pointer in this node.
194879f95c82SChris Mason 		 * So, pull some keys from the left.
194979f95c82SChris Mason 		 * There has to be a left pointer at this point because
195079f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
195179f95c82SChris Mason 		 * right
195279f95c82SChris Mason 		 */
1953305a26afSMark Fasheh 		if (!left) {
1954305a26afSMark Fasheh 			ret = -EROFS;
19550b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1956305a26afSMark Fasheh 			goto enospc;
1957305a26afSMark Fasheh 		}
195855d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
195954aa1f4dSChris Mason 		if (wret < 0) {
196079f95c82SChris Mason 			ret = wret;
196154aa1f4dSChris Mason 			goto enospc;
196254aa1f4dSChris Mason 		}
1963bce4eae9SChris Mason 		if (wret == 1) {
1964d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1965bce4eae9SChris Mason 			if (wret < 0)
1966bce4eae9SChris Mason 				ret = wret;
1967bce4eae9SChris Mason 		}
196879f95c82SChris Mason 		BUG_ON(wret == 1);
196979f95c82SChris Mason 	}
19705f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
19716a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1972925baeddSChris Mason 		btrfs_tree_unlock(mid);
1973afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1974f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
19755581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
19763083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1977f0486c68SYan, Zheng 		mid = NULL;
197879f95c82SChris Mason 	} else {
197979f95c82SChris Mason 		/* update the parent key to reflect our changes */
19805f39d397SChris Mason 		struct btrfs_disk_key mid_key;
19815f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
19820e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, pslot,
19830e82bcfeSDavid Sterba 				MOD_LOG_KEY_REPLACE, GFP_NOFS);
19840e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
19855f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
19865f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
198779f95c82SChris Mason 	}
1988bb803951SChris Mason 
198979f95c82SChris Mason 	/* update the path */
19905f39d397SChris Mason 	if (left) {
19915f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
199267439dadSDavid Sterba 			atomic_inc(&left->refs);
1993925baeddSChris Mason 			/* left was locked after cow */
19945f39d397SChris Mason 			path->nodes[level] = left;
1995bb803951SChris Mason 			path->slots[level + 1] -= 1;
1996bb803951SChris Mason 			path->slots[level] = orig_slot;
1997925baeddSChris Mason 			if (mid) {
1998925baeddSChris Mason 				btrfs_tree_unlock(mid);
19995f39d397SChris Mason 				free_extent_buffer(mid);
2000925baeddSChris Mason 			}
2001bb803951SChris Mason 		} else {
20025f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
2003bb803951SChris Mason 			path->slots[level] = orig_slot;
2004bb803951SChris Mason 		}
2005bb803951SChris Mason 	}
200679f95c82SChris Mason 	/* double check we haven't messed things up */
2007e20d96d6SChris Mason 	if (orig_ptr !=
20085f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
200979f95c82SChris Mason 		BUG();
201054aa1f4dSChris Mason enospc:
2011925baeddSChris Mason 	if (right) {
2012925baeddSChris Mason 		btrfs_tree_unlock(right);
20135f39d397SChris Mason 		free_extent_buffer(right);
2014925baeddSChris Mason 	}
2015925baeddSChris Mason 	if (left) {
2016925baeddSChris Mason 		if (path->nodes[level] != left)
2017925baeddSChris Mason 			btrfs_tree_unlock(left);
20185f39d397SChris Mason 		free_extent_buffer(left);
2019925baeddSChris Mason 	}
2020bb803951SChris Mason 	return ret;
2021bb803951SChris Mason }
2022bb803951SChris Mason 
2023d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
2024d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
2025d352ac68SChris Mason  * have to be pessimistic.
2026d352ac68SChris Mason  */
2027d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2028e66f709bSChris Mason 					  struct btrfs_root *root,
2029e66f709bSChris Mason 					  struct btrfs_path *path, int level)
2030e66f709bSChris Mason {
20310b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
20325f39d397SChris Mason 	struct extent_buffer *right = NULL;
20335f39d397SChris Mason 	struct extent_buffer *mid;
20345f39d397SChris Mason 	struct extent_buffer *left = NULL;
20355f39d397SChris Mason 	struct extent_buffer *parent = NULL;
2036e66f709bSChris Mason 	int ret = 0;
2037e66f709bSChris Mason 	int wret;
2038e66f709bSChris Mason 	int pslot;
2039e66f709bSChris Mason 	int orig_slot = path->slots[level];
2040e66f709bSChris Mason 
2041e66f709bSChris Mason 	if (level == 0)
2042e66f709bSChris Mason 		return 1;
2043e66f709bSChris Mason 
20445f39d397SChris Mason 	mid = path->nodes[level];
20457bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
2046e66f709bSChris Mason 
2047a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
20485f39d397SChris Mason 		parent = path->nodes[level + 1];
2049e66f709bSChris Mason 		pslot = path->slots[level + 1];
2050a05a9bb1SLi Zefan 	}
2051e66f709bSChris Mason 
20525f39d397SChris Mason 	if (!parent)
2053e66f709bSChris Mason 		return 1;
2054e66f709bSChris Mason 
20554b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
2056fb770ae4SLiu Bo 	if (IS_ERR(left))
2057fb770ae4SLiu Bo 		left = NULL;
2058e66f709bSChris Mason 
2059e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
20605f39d397SChris Mason 	if (left) {
2061e66f709bSChris Mason 		u32 left_nr;
2062925baeddSChris Mason 
2063925baeddSChris Mason 		btrfs_tree_lock(left);
20648bead258SDavid Sterba 		btrfs_set_lock_blocking_write(left);
2065b4ce94deSChris Mason 
20665f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
20670b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
206833ade1f8SChris Mason 			wret = 1;
206933ade1f8SChris Mason 		} else {
20705f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
20719fa8cfe7SChris Mason 					      pslot - 1, &left);
207254aa1f4dSChris Mason 			if (ret)
207354aa1f4dSChris Mason 				wret = 1;
207454aa1f4dSChris Mason 			else {
2075d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
207654aa1f4dSChris Mason 			}
207733ade1f8SChris Mason 		}
2078e66f709bSChris Mason 		if (wret < 0)
2079e66f709bSChris Mason 			ret = wret;
2080e66f709bSChris Mason 		if (wret == 0) {
20815f39d397SChris Mason 			struct btrfs_disk_key disk_key;
2082e66f709bSChris Mason 			orig_slot += left_nr;
20835f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
20840e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot,
20850e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
20860e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
20875f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
20885f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
20895f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
20905f39d397SChris Mason 				path->nodes[level] = left;
2091e66f709bSChris Mason 				path->slots[level + 1] -= 1;
2092e66f709bSChris Mason 				path->slots[level] = orig_slot;
2093925baeddSChris Mason 				btrfs_tree_unlock(mid);
20945f39d397SChris Mason 				free_extent_buffer(mid);
2095e66f709bSChris Mason 			} else {
2096e66f709bSChris Mason 				orig_slot -=
20975f39d397SChris Mason 					btrfs_header_nritems(left);
2098e66f709bSChris Mason 				path->slots[level] = orig_slot;
2099925baeddSChris Mason 				btrfs_tree_unlock(left);
21005f39d397SChris Mason 				free_extent_buffer(left);
2101e66f709bSChris Mason 			}
2102e66f709bSChris Mason 			return 0;
2103e66f709bSChris Mason 		}
2104925baeddSChris Mason 		btrfs_tree_unlock(left);
21055f39d397SChris Mason 		free_extent_buffer(left);
2106e66f709bSChris Mason 	}
21074b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
2108fb770ae4SLiu Bo 	if (IS_ERR(right))
2109fb770ae4SLiu Bo 		right = NULL;
2110e66f709bSChris Mason 
2111e66f709bSChris Mason 	/*
2112e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2113e66f709bSChris Mason 	 */
21145f39d397SChris Mason 	if (right) {
211533ade1f8SChris Mason 		u32 right_nr;
2116b4ce94deSChris Mason 
2117925baeddSChris Mason 		btrfs_tree_lock(right);
21188bead258SDavid Sterba 		btrfs_set_lock_blocking_write(right);
2119b4ce94deSChris Mason 
21205f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
21210b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
212233ade1f8SChris Mason 			wret = 1;
212333ade1f8SChris Mason 		} else {
21245f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
21255f39d397SChris Mason 					      parent, pslot + 1,
21269fa8cfe7SChris Mason 					      &right);
212754aa1f4dSChris Mason 			if (ret)
212854aa1f4dSChris Mason 				wret = 1;
212954aa1f4dSChris Mason 			else {
213055d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
213133ade1f8SChris Mason 			}
213254aa1f4dSChris Mason 		}
2133e66f709bSChris Mason 		if (wret < 0)
2134e66f709bSChris Mason 			ret = wret;
2135e66f709bSChris Mason 		if (wret == 0) {
21365f39d397SChris Mason 			struct btrfs_disk_key disk_key;
21375f39d397SChris Mason 
21385f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
21390e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
21400e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21410e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21425f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
21435f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21445f39d397SChris Mason 
21455f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
21465f39d397SChris Mason 				path->nodes[level] = right;
2147e66f709bSChris Mason 				path->slots[level + 1] += 1;
2148e66f709bSChris Mason 				path->slots[level] = orig_slot -
21495f39d397SChris Mason 					btrfs_header_nritems(mid);
2150925baeddSChris Mason 				btrfs_tree_unlock(mid);
21515f39d397SChris Mason 				free_extent_buffer(mid);
2152e66f709bSChris Mason 			} else {
2153925baeddSChris Mason 				btrfs_tree_unlock(right);
21545f39d397SChris Mason 				free_extent_buffer(right);
2155e66f709bSChris Mason 			}
2156e66f709bSChris Mason 			return 0;
2157e66f709bSChris Mason 		}
2158925baeddSChris Mason 		btrfs_tree_unlock(right);
21595f39d397SChris Mason 		free_extent_buffer(right);
2160e66f709bSChris Mason 	}
2161e66f709bSChris Mason 	return 1;
2162e66f709bSChris Mason }
2163e66f709bSChris Mason 
216474123bd7SChris Mason /*
2165d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2166d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
21673c69faecSChris Mason  */
21682ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
2169e02119d5SChris Mason 			     struct btrfs_path *path,
217001f46658SChris Mason 			     int level, int slot, u64 objectid)
21713c69faecSChris Mason {
21725f39d397SChris Mason 	struct extent_buffer *node;
217301f46658SChris Mason 	struct btrfs_disk_key disk_key;
21743c69faecSChris Mason 	u32 nritems;
21753c69faecSChris Mason 	u64 search;
2176a7175319SChris Mason 	u64 target;
21776b80053dSChris Mason 	u64 nread = 0;
21785f39d397SChris Mason 	struct extent_buffer *eb;
21796b80053dSChris Mason 	u32 nr;
21806b80053dSChris Mason 	u32 blocksize;
21816b80053dSChris Mason 	u32 nscan = 0;
2182db94535dSChris Mason 
2183a6b6e75eSChris Mason 	if (level != 1)
21843c69faecSChris Mason 		return;
21853c69faecSChris Mason 
21866702ed49SChris Mason 	if (!path->nodes[level])
21876702ed49SChris Mason 		return;
21886702ed49SChris Mason 
21895f39d397SChris Mason 	node = path->nodes[level];
2190925baeddSChris Mason 
21913c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
21920b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
21930b246afaSJeff Mahoney 	eb = find_extent_buffer(fs_info, search);
21945f39d397SChris Mason 	if (eb) {
21955f39d397SChris Mason 		free_extent_buffer(eb);
21963c69faecSChris Mason 		return;
21973c69faecSChris Mason 	}
21983c69faecSChris Mason 
2199a7175319SChris Mason 	target = search;
22006b80053dSChris Mason 
22015f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
22026b80053dSChris Mason 	nr = slot;
220325b8b936SJosef Bacik 
22043c69faecSChris Mason 	while (1) {
2205e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
22066b80053dSChris Mason 			if (nr == 0)
22073c69faecSChris Mason 				break;
22086b80053dSChris Mason 			nr--;
2209e4058b54SDavid Sterba 		} else if (path->reada == READA_FORWARD) {
22106b80053dSChris Mason 			nr++;
22116b80053dSChris Mason 			if (nr >= nritems)
22126b80053dSChris Mason 				break;
22133c69faecSChris Mason 		}
2214e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
221501f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
221601f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
221701f46658SChris Mason 				break;
221801f46658SChris Mason 		}
22196b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2220a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2221a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
22222ff7e61eSJeff Mahoney 			readahead_tree_block(fs_info, search);
22236b80053dSChris Mason 			nread += blocksize;
22243c69faecSChris Mason 		}
22256b80053dSChris Mason 		nscan++;
2226a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
22276b80053dSChris Mason 			break;
22283c69faecSChris Mason 	}
22293c69faecSChris Mason }
2230925baeddSChris Mason 
22312ff7e61eSJeff Mahoney static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2232b4ce94deSChris Mason 				       struct btrfs_path *path, int level)
2233b4ce94deSChris Mason {
2234b4ce94deSChris Mason 	int slot;
2235b4ce94deSChris Mason 	int nritems;
2236b4ce94deSChris Mason 	struct extent_buffer *parent;
2237b4ce94deSChris Mason 	struct extent_buffer *eb;
2238b4ce94deSChris Mason 	u64 gen;
2239b4ce94deSChris Mason 	u64 block1 = 0;
2240b4ce94deSChris Mason 	u64 block2 = 0;
2241b4ce94deSChris Mason 
22428c594ea8SChris Mason 	parent = path->nodes[level + 1];
2243b4ce94deSChris Mason 	if (!parent)
22440b08851fSJosef Bacik 		return;
2245b4ce94deSChris Mason 
2246b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
22478c594ea8SChris Mason 	slot = path->slots[level + 1];
2248b4ce94deSChris Mason 
2249b4ce94deSChris Mason 	if (slot > 0) {
2250b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2251b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
22520b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block1);
2253b9fab919SChris Mason 		/*
2254b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2255b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2256b9fab919SChris Mason 		 * forever
2257b9fab919SChris Mason 		 */
2258b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2259b4ce94deSChris Mason 			block1 = 0;
2260b4ce94deSChris Mason 		free_extent_buffer(eb);
2261b4ce94deSChris Mason 	}
22628c594ea8SChris Mason 	if (slot + 1 < nritems) {
2263b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2264b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
22650b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block2);
2266b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2267b4ce94deSChris Mason 			block2 = 0;
2268b4ce94deSChris Mason 		free_extent_buffer(eb);
2269b4ce94deSChris Mason 	}
22708c594ea8SChris Mason 
2271b4ce94deSChris Mason 	if (block1)
22722ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block1);
2273b4ce94deSChris Mason 	if (block2)
22742ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block2);
2275b4ce94deSChris Mason }
2276b4ce94deSChris Mason 
2277b4ce94deSChris Mason 
2278b4ce94deSChris Mason /*
2279d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2280d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2281d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2282d397712bSChris Mason  * tree.
2283d352ac68SChris Mason  *
2284d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2285d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2286d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2287d352ac68SChris Mason  *
2288d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2289d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2290d352ac68SChris Mason  */
2291e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2292f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2293f7c79f30SChris Mason 			       int *write_lock_level)
2294925baeddSChris Mason {
2295925baeddSChris Mason 	int i;
2296925baeddSChris Mason 	int skip_level = level;
2297051e1b9fSChris Mason 	int no_skips = 0;
2298925baeddSChris Mason 	struct extent_buffer *t;
2299925baeddSChris Mason 
2300925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2301925baeddSChris Mason 		if (!path->nodes[i])
2302925baeddSChris Mason 			break;
2303925baeddSChris Mason 		if (!path->locks[i])
2304925baeddSChris Mason 			break;
2305051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2306925baeddSChris Mason 			skip_level = i + 1;
2307925baeddSChris Mason 			continue;
2308925baeddSChris Mason 		}
2309051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2310925baeddSChris Mason 			u32 nritems;
2311925baeddSChris Mason 			t = path->nodes[i];
2312925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2313051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2314925baeddSChris Mason 				skip_level = i + 1;
2315925baeddSChris Mason 				continue;
2316925baeddSChris Mason 			}
2317925baeddSChris Mason 		}
2318051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2319051e1b9fSChris Mason 			no_skips = 1;
2320051e1b9fSChris Mason 
2321925baeddSChris Mason 		t = path->nodes[i];
2322d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
2323bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2324925baeddSChris Mason 			path->locks[i] = 0;
2325f7c79f30SChris Mason 			if (write_lock_level &&
2326f7c79f30SChris Mason 			    i > min_write_lock_level &&
2327f7c79f30SChris Mason 			    i <= *write_lock_level) {
2328f7c79f30SChris Mason 				*write_lock_level = i - 1;
2329f7c79f30SChris Mason 			}
2330925baeddSChris Mason 		}
2331925baeddSChris Mason 	}
2332925baeddSChris Mason }
2333925baeddSChris Mason 
23343c69faecSChris Mason /*
2335c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2336c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2337c8c42864SChris Mason  * we return zero and the path is unchanged.
2338c8c42864SChris Mason  *
2339c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2340c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2341c8c42864SChris Mason  */
2342c8c42864SChris Mason static int
2343d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2344c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
2345cda79c54SDavid Sterba 		      const struct btrfs_key *key)
2346c8c42864SChris Mason {
23470b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2348c8c42864SChris Mason 	u64 blocknr;
2349c8c42864SChris Mason 	u64 gen;
2350c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2351c8c42864SChris Mason 	struct extent_buffer *tmp;
2352581c1760SQu Wenruo 	struct btrfs_key first_key;
235376a05b35SChris Mason 	int ret;
2354581c1760SQu Wenruo 	int parent_level;
2355c8c42864SChris Mason 
2356c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2357c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2358581c1760SQu Wenruo 	parent_level = btrfs_header_level(b);
2359581c1760SQu Wenruo 	btrfs_node_key_to_cpu(b, &first_key, slot);
2360c8c42864SChris Mason 
23610b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
2362cb44921aSChris Mason 	if (tmp) {
2363b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2364b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2365448de471SQu Wenruo 			/*
2366448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
2367448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
2368448de471SQu Wenruo 			 * parents (shared tree blocks).
2369448de471SQu Wenruo 			 */
2370e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
2371448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
2372448de471SQu Wenruo 				free_extent_buffer(tmp);
2373448de471SQu Wenruo 				return -EUCLEAN;
2374448de471SQu Wenruo 			}
2375c8c42864SChris Mason 			*eb_ret = tmp;
2376c8c42864SChris Mason 			return 0;
2377c8c42864SChris Mason 		}
2378bdf7c00eSJosef Bacik 
2379cb44921aSChris Mason 		/* the pages were up to date, but we failed
2380cb44921aSChris Mason 		 * the generation number check.  Do a full
2381cb44921aSChris Mason 		 * read for the generation number that is correct.
2382cb44921aSChris Mason 		 * We must do this without dropping locks so
2383cb44921aSChris Mason 		 * we can trust our generation number
2384cb44921aSChris Mason 		 */
2385bd681513SChris Mason 		btrfs_set_path_blocking(p);
2386bd681513SChris Mason 
2387b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2388581c1760SQu Wenruo 		ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
2389bdf7c00eSJosef Bacik 		if (!ret) {
2390cb44921aSChris Mason 			*eb_ret = tmp;
2391cb44921aSChris Mason 			return 0;
2392cb44921aSChris Mason 		}
2393cb44921aSChris Mason 		free_extent_buffer(tmp);
2394b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2395cb44921aSChris Mason 		return -EIO;
2396cb44921aSChris Mason 	}
2397c8c42864SChris Mason 
2398c8c42864SChris Mason 	/*
2399c8c42864SChris Mason 	 * reduce lock contention at high levels
2400c8c42864SChris Mason 	 * of the btree by dropping locks before
240176a05b35SChris Mason 	 * we read.  Don't release the lock on the current
240276a05b35SChris Mason 	 * level because we need to walk this node to figure
240376a05b35SChris Mason 	 * out which blocks to read.
2404c8c42864SChris Mason 	 */
24058c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
24068c594ea8SChris Mason 	btrfs_set_path_blocking(p);
24078c594ea8SChris Mason 
2408e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
24092ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
2410c8c42864SChris Mason 
241176a05b35SChris Mason 	ret = -EAGAIN;
241202a3307aSLiu Bo 	tmp = read_tree_block(fs_info, blocknr, gen, parent_level - 1,
2413581c1760SQu Wenruo 			      &first_key);
241464c043deSLiu Bo 	if (!IS_ERR(tmp)) {
241576a05b35SChris Mason 		/*
241676a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
241776a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
241876a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
241976a05b35SChris Mason 		 * on our EAGAINs.
242076a05b35SChris Mason 		 */
2421e6a1d6fdSLiu Bo 		if (!extent_buffer_uptodate(tmp))
242276a05b35SChris Mason 			ret = -EIO;
2423c8c42864SChris Mason 		free_extent_buffer(tmp);
2424c871b0f2SLiu Bo 	} else {
2425c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
242676a05b35SChris Mason 	}
242702a3307aSLiu Bo 
242802a3307aSLiu Bo 	btrfs_release_path(p);
242976a05b35SChris Mason 	return ret;
2430c8c42864SChris Mason }
2431c8c42864SChris Mason 
2432c8c42864SChris Mason /*
2433c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2434c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2435c8c42864SChris Mason  * the ins_len.
2436c8c42864SChris Mason  *
2437c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2438c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2439c8c42864SChris Mason  * start over
2440c8c42864SChris Mason  */
2441c8c42864SChris Mason static int
2442c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2443c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2444bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2445bd681513SChris Mason 		       int *write_lock_level)
2446c8c42864SChris Mason {
24470b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2448c8c42864SChris Mason 	int ret;
24490b246afaSJeff Mahoney 
2450c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
24510b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2452c8c42864SChris Mason 		int sret;
2453c8c42864SChris Mason 
2454bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2455bd681513SChris Mason 			*write_lock_level = level + 1;
2456bd681513SChris Mason 			btrfs_release_path(p);
2457bd681513SChris Mason 			goto again;
2458bd681513SChris Mason 		}
2459bd681513SChris Mason 
2460c8c42864SChris Mason 		btrfs_set_path_blocking(p);
24612ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2462c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2463c8c42864SChris Mason 
2464c8c42864SChris Mason 		BUG_ON(sret > 0);
2465c8c42864SChris Mason 		if (sret) {
2466c8c42864SChris Mason 			ret = sret;
2467c8c42864SChris Mason 			goto done;
2468c8c42864SChris Mason 		}
2469c8c42864SChris Mason 		b = p->nodes[level];
2470c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
24710b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2472c8c42864SChris Mason 		int sret;
2473c8c42864SChris Mason 
2474bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2475bd681513SChris Mason 			*write_lock_level = level + 1;
2476bd681513SChris Mason 			btrfs_release_path(p);
2477bd681513SChris Mason 			goto again;
2478bd681513SChris Mason 		}
2479bd681513SChris Mason 
2480c8c42864SChris Mason 		btrfs_set_path_blocking(p);
24812ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2482c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2483c8c42864SChris Mason 
2484c8c42864SChris Mason 		if (sret) {
2485c8c42864SChris Mason 			ret = sret;
2486c8c42864SChris Mason 			goto done;
2487c8c42864SChris Mason 		}
2488c8c42864SChris Mason 		b = p->nodes[level];
2489c8c42864SChris Mason 		if (!b) {
2490b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2491c8c42864SChris Mason 			goto again;
2492c8c42864SChris Mason 		}
2493c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2494c8c42864SChris Mason 	}
2495c8c42864SChris Mason 	return 0;
2496c8c42864SChris Mason 
2497c8c42864SChris Mason again:
2498c8c42864SChris Mason 	ret = -EAGAIN;
2499c8c42864SChris Mason done:
2500c8c42864SChris Mason 	return ret;
2501c8c42864SChris Mason }
2502c8c42864SChris Mason 
2503310712b2SOmar Sandoval static int key_search(struct extent_buffer *b, const struct btrfs_key *key,
2504d7396f07SFilipe David Borba Manana 		      int level, int *prev_cmp, int *slot)
2505d7396f07SFilipe David Borba Manana {
2506d7396f07SFilipe David Borba Manana 	if (*prev_cmp != 0) {
2507a74b35ecSNikolay Borisov 		*prev_cmp = btrfs_bin_search(b, key, level, slot);
2508d7396f07SFilipe David Borba Manana 		return *prev_cmp;
2509d7396f07SFilipe David Borba Manana 	}
2510d7396f07SFilipe David Borba Manana 
2511d7396f07SFilipe David Borba Manana 	*slot = 0;
2512d7396f07SFilipe David Borba Manana 
2513d7396f07SFilipe David Borba Manana 	return 0;
2514d7396f07SFilipe David Borba Manana }
2515d7396f07SFilipe David Borba Manana 
2516381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2517e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
2518e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
2519e33d5c3dSKelley Nielsen {
2520e33d5c3dSKelley Nielsen 	int ret;
2521e33d5c3dSKelley Nielsen 	struct btrfs_key key;
2522e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
2523381cf658SDavid Sterba 
2524381cf658SDavid Sterba 	ASSERT(path);
25251d4c08e0SDavid Sterba 	ASSERT(found_key);
2526e33d5c3dSKelley Nielsen 
2527e33d5c3dSKelley Nielsen 	key.type = key_type;
2528e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
2529e33d5c3dSKelley Nielsen 	key.offset = ioff;
2530e33d5c3dSKelley Nielsen 
2531e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
25321d4c08e0SDavid Sterba 	if (ret < 0)
2533e33d5c3dSKelley Nielsen 		return ret;
2534e33d5c3dSKelley Nielsen 
2535e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
2536e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2537e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
2538e33d5c3dSKelley Nielsen 		if (ret)
2539e33d5c3dSKelley Nielsen 			return ret;
2540e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
2541e33d5c3dSKelley Nielsen 	}
2542e33d5c3dSKelley Nielsen 
2543e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2544e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
2545e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
2546e33d5c3dSKelley Nielsen 		return 1;
2547e33d5c3dSKelley Nielsen 
2548e33d5c3dSKelley Nielsen 	return 0;
2549e33d5c3dSKelley Nielsen }
2550e33d5c3dSKelley Nielsen 
25511fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
25521fc28d8eSLiu Bo 							struct btrfs_path *p,
25531fc28d8eSLiu Bo 							int write_lock_level)
25541fc28d8eSLiu Bo {
25551fc28d8eSLiu Bo 	struct btrfs_fs_info *fs_info = root->fs_info;
25561fc28d8eSLiu Bo 	struct extent_buffer *b;
25571fc28d8eSLiu Bo 	int root_lock;
25581fc28d8eSLiu Bo 	int level = 0;
25591fc28d8eSLiu Bo 
25601fc28d8eSLiu Bo 	/* We try very hard to do read locks on the root */
25611fc28d8eSLiu Bo 	root_lock = BTRFS_READ_LOCK;
25621fc28d8eSLiu Bo 
25631fc28d8eSLiu Bo 	if (p->search_commit_root) {
2564be6821f8SFilipe Manana 		/*
2565be6821f8SFilipe Manana 		 * The commit roots are read only so we always do read locks,
2566be6821f8SFilipe Manana 		 * and we always must hold the commit_root_sem when doing
2567be6821f8SFilipe Manana 		 * searches on them, the only exception is send where we don't
2568be6821f8SFilipe Manana 		 * want to block transaction commits for a long time, so
2569be6821f8SFilipe Manana 		 * we need to clone the commit root in order to avoid races
2570be6821f8SFilipe Manana 		 * with transaction commits that create a snapshot of one of
2571be6821f8SFilipe Manana 		 * the roots used by a send operation.
2572be6821f8SFilipe Manana 		 */
2573be6821f8SFilipe Manana 		if (p->need_commit_sem) {
25741fc28d8eSLiu Bo 			down_read(&fs_info->commit_root_sem);
2575be6821f8SFilipe Manana 			b = btrfs_clone_extent_buffer(root->commit_root);
2576be6821f8SFilipe Manana 			up_read(&fs_info->commit_root_sem);
2577be6821f8SFilipe Manana 			if (!b)
2578be6821f8SFilipe Manana 				return ERR_PTR(-ENOMEM);
2579be6821f8SFilipe Manana 
2580be6821f8SFilipe Manana 		} else {
25811fc28d8eSLiu Bo 			b = root->commit_root;
258267439dadSDavid Sterba 			atomic_inc(&b->refs);
2583be6821f8SFilipe Manana 		}
25841fc28d8eSLiu Bo 		level = btrfs_header_level(b);
2585f9ddfd05SLiu Bo 		/*
2586f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
2587f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
2588f9ddfd05SLiu Bo 		 */
2589f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
25901fc28d8eSLiu Bo 
25911fc28d8eSLiu Bo 		goto out;
25921fc28d8eSLiu Bo 	}
25931fc28d8eSLiu Bo 
25941fc28d8eSLiu Bo 	if (p->skip_locking) {
25951fc28d8eSLiu Bo 		b = btrfs_root_node(root);
25961fc28d8eSLiu Bo 		level = btrfs_header_level(b);
25971fc28d8eSLiu Bo 		goto out;
25981fc28d8eSLiu Bo 	}
25991fc28d8eSLiu Bo 
26001fc28d8eSLiu Bo 	/*
2601662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
2602662c653bSLiu Bo 	 * lock.
2603662c653bSLiu Bo 	 */
2604662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
2605662c653bSLiu Bo 		/*
2606662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
2607662c653bSLiu Bo 		 * have it read locked
26081fc28d8eSLiu Bo 		 */
26091fc28d8eSLiu Bo 		b = btrfs_read_lock_root_node(root);
26101fc28d8eSLiu Bo 		level = btrfs_header_level(b);
26111fc28d8eSLiu Bo 		if (level > write_lock_level)
26121fc28d8eSLiu Bo 			goto out;
26131fc28d8eSLiu Bo 
2614662c653bSLiu Bo 		/* Whoops, must trade for write lock */
26151fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
26161fc28d8eSLiu Bo 		free_extent_buffer(b);
2617662c653bSLiu Bo 	}
2618662c653bSLiu Bo 
26191fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
26201fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
26211fc28d8eSLiu Bo 
26221fc28d8eSLiu Bo 	/* The level might have changed, check again */
26231fc28d8eSLiu Bo 	level = btrfs_header_level(b);
26241fc28d8eSLiu Bo 
26251fc28d8eSLiu Bo out:
26261fc28d8eSLiu Bo 	p->nodes[level] = b;
26271fc28d8eSLiu Bo 	if (!p->skip_locking)
26281fc28d8eSLiu Bo 		p->locks[level] = root_lock;
26291fc28d8eSLiu Bo 	/*
26301fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
26311fc28d8eSLiu Bo 	 */
26321fc28d8eSLiu Bo 	return b;
26331fc28d8eSLiu Bo }
26341fc28d8eSLiu Bo 
26351fc28d8eSLiu Bo 
2636c8c42864SChris Mason /*
26374271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
26384271eceaSNikolay Borisov  * modifications to preserve tree invariants.
263974123bd7SChris Mason  *
26404271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
26414271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
26424271eceaSNikolay Borisov  * @root:	The root node of the tree
26434271eceaSNikolay Borisov  * @key:	The key we are looking for
26444271eceaSNikolay Borisov  * @ins_len:	Indicates purpose of search, for inserts it is 1, for
26454271eceaSNikolay Borisov  *		deletions it's -1. 0 for plain searches
26464271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
26474271eceaSNikolay Borisov  *		when modifying the tree.
264897571fd0SChris Mason  *
26494271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
26504271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
26514271eceaSNikolay Borisov  *
26524271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
26534271eceaSNikolay Borisov  * of the path (level 0)
26544271eceaSNikolay Borisov  *
26554271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
26564271eceaSNikolay Borisov  * points to the slot where it should be inserted
26574271eceaSNikolay Borisov  *
26584271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
26594271eceaSNikolay Borisov  * is returned
266074123bd7SChris Mason  */
2661310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2662310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2663310712b2SOmar Sandoval 		      int ins_len, int cow)
2664be0e5c09SChris Mason {
26655f39d397SChris Mason 	struct extent_buffer *b;
2666be0e5c09SChris Mason 	int slot;
2667be0e5c09SChris Mason 	int ret;
266833c66f43SYan Zheng 	int err;
2669be0e5c09SChris Mason 	int level;
2670925baeddSChris Mason 	int lowest_unlock = 1;
2671bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2672bd681513SChris Mason 	int write_lock_level = 0;
26739f3a7427SChris Mason 	u8 lowest_level = 0;
2674f7c79f30SChris Mason 	int min_write_lock_level;
2675d7396f07SFilipe David Borba Manana 	int prev_cmp;
26769f3a7427SChris Mason 
26776702ed49SChris Mason 	lowest_level = p->lowest_level;
2678323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
267922b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2680eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
268125179201SJosef Bacik 
2682bd681513SChris Mason 	if (ins_len < 0) {
2683925baeddSChris Mason 		lowest_unlock = 2;
268465b51a00SChris Mason 
2685bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2686bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2687bd681513SChris Mason 		 * for those levels as well
2688bd681513SChris Mason 		 */
2689bd681513SChris Mason 		write_lock_level = 2;
2690bd681513SChris Mason 	} else if (ins_len > 0) {
2691bd681513SChris Mason 		/*
2692bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2693bd681513SChris Mason 		 * level 1 so we can update keys
2694bd681513SChris Mason 		 */
2695bd681513SChris Mason 		write_lock_level = 1;
2696bd681513SChris Mason 	}
2697bd681513SChris Mason 
2698bd681513SChris Mason 	if (!cow)
2699bd681513SChris Mason 		write_lock_level = -1;
2700bd681513SChris Mason 
270109a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2702bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2703bd681513SChris Mason 
2704f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2705f7c79f30SChris Mason 
2706bb803951SChris Mason again:
2707d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
27081fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2709be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2710be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2711be6821f8SFilipe Manana 		goto done;
2712be6821f8SFilipe Manana 	}
2713925baeddSChris Mason 
2714eb60ceacSChris Mason 	while (b) {
2715f624d976SQu Wenruo 		int dec = 0;
2716f624d976SQu Wenruo 
27175f39d397SChris Mason 		level = btrfs_header_level(b);
271865b51a00SChris Mason 
271902217ed2SChris Mason 		if (cow) {
27209ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
27219ea2c7c9SNikolay Borisov 
2722c8c42864SChris Mason 			/*
2723c8c42864SChris Mason 			 * if we don't really need to cow this block
2724c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2725c8c42864SChris Mason 			 * so we test it here
2726c8c42864SChris Mason 			 */
272764c12921SJeff Mahoney 			if (!should_cow_block(trans, root, b)) {
272864c12921SJeff Mahoney 				trans->dirty = true;
272965b51a00SChris Mason 				goto cow_done;
273064c12921SJeff Mahoney 			}
27315d4f98a2SYan Zheng 
2732bd681513SChris Mason 			/*
2733bd681513SChris Mason 			 * must have write locks on this node and the
2734bd681513SChris Mason 			 * parent
2735bd681513SChris Mason 			 */
27365124e00eSJosef Bacik 			if (level > write_lock_level ||
27375124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
27385124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
27395124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2740bd681513SChris Mason 				write_lock_level = level + 1;
2741bd681513SChris Mason 				btrfs_release_path(p);
2742bd681513SChris Mason 				goto again;
2743bd681513SChris Mason 			}
2744bd681513SChris Mason 
2745160f4089SFilipe Manana 			btrfs_set_path_blocking(p);
27469ea2c7c9SNikolay Borisov 			if (last_level)
27479ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
27489ea2c7c9SNikolay Borisov 						      &b);
27499ea2c7c9SNikolay Borisov 			else
275033c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2751e20d96d6SChris Mason 						      p->nodes[level + 1],
27529fa8cfe7SChris Mason 						      p->slots[level + 1], &b);
275333c66f43SYan Zheng 			if (err) {
275433c66f43SYan Zheng 				ret = err;
275565b51a00SChris Mason 				goto done;
275654aa1f4dSChris Mason 			}
275702217ed2SChris Mason 		}
275865b51a00SChris Mason cow_done:
2759eb60ceacSChris Mason 		p->nodes[level] = b;
276052398340SLiu Bo 		/*
276152398340SLiu Bo 		 * Leave path with blocking locks to avoid massive
276252398340SLiu Bo 		 * lock context switch, this is made on purpose.
276352398340SLiu Bo 		 */
2764b4ce94deSChris Mason 
2765b4ce94deSChris Mason 		/*
2766b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2767b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2768b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2769b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2770b4ce94deSChris Mason 		 *
2771eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2772eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2773eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2774eb653de1SFilipe David Borba Manana 		 * we're operating on.
2775b4ce94deSChris Mason 		 */
2776eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2777eb653de1SFilipe David Borba Manana 			int u = level + 1;
2778eb653de1SFilipe David Borba Manana 
2779eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2780eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2781eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2782eb653de1SFilipe David Borba Manana 			}
2783eb653de1SFilipe David Borba Manana 		}
2784b4ce94deSChris Mason 
2785d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
2786415b35a5SLiu Bo 		if (ret < 0)
2787415b35a5SLiu Bo 			goto done;
2788b4ce94deSChris Mason 
2789f624d976SQu Wenruo 		if (level == 0) {
2790be0e5c09SChris Mason 			p->slots[level] = slot;
279187b29b20SYan Zheng 			if (ins_len > 0 &&
2792e902baacSDavid Sterba 			    btrfs_leaf_free_space(b) < ins_len) {
2793bd681513SChris Mason 				if (write_lock_level < 1) {
2794bd681513SChris Mason 					write_lock_level = 1;
2795bd681513SChris Mason 					btrfs_release_path(p);
2796bd681513SChris Mason 					goto again;
2797bd681513SChris Mason 				}
2798bd681513SChris Mason 
2799b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
280033c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2801cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2802b4ce94deSChris Mason 
280333c66f43SYan Zheng 				BUG_ON(err > 0);
280433c66f43SYan Zheng 				if (err) {
280533c66f43SYan Zheng 					ret = err;
280665b51a00SChris Mason 					goto done;
280765b51a00SChris Mason 				}
28085c680ed6SChris Mason 			}
2809459931ecSChris Mason 			if (!p->search_for_split)
2810f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
28114b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
281265b51a00SChris Mason 			goto done;
281365b51a00SChris Mason 		}
2814f624d976SQu Wenruo 		if (ret && slot > 0) {
2815f624d976SQu Wenruo 			dec = 1;
2816f624d976SQu Wenruo 			slot--;
2817f624d976SQu Wenruo 		}
2818f624d976SQu Wenruo 		p->slots[level] = slot;
2819f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2820f624d976SQu Wenruo 					     &write_lock_level);
2821f624d976SQu Wenruo 		if (err == -EAGAIN)
2822f624d976SQu Wenruo 			goto again;
2823f624d976SQu Wenruo 		if (err) {
2824f624d976SQu Wenruo 			ret = err;
2825f624d976SQu Wenruo 			goto done;
2826f624d976SQu Wenruo 		}
2827f624d976SQu Wenruo 		b = p->nodes[level];
2828f624d976SQu Wenruo 		slot = p->slots[level];
2829f624d976SQu Wenruo 
2830f624d976SQu Wenruo 		/*
2831f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2832f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2833f624d976SQu Wenruo 		 * the parent
2834f624d976SQu Wenruo 		 */
2835f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2836f624d976SQu Wenruo 			write_lock_level = level + 1;
2837f624d976SQu Wenruo 			btrfs_release_path(p);
2838f624d976SQu Wenruo 			goto again;
2839f624d976SQu Wenruo 		}
2840f624d976SQu Wenruo 
2841f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2842f624d976SQu Wenruo 			  &write_lock_level);
2843f624d976SQu Wenruo 
2844f624d976SQu Wenruo 		if (level == lowest_level) {
2845f624d976SQu Wenruo 			if (dec)
2846f624d976SQu Wenruo 				p->slots[level]++;
2847f624d976SQu Wenruo 			goto done;
2848f624d976SQu Wenruo 		}
2849f624d976SQu Wenruo 
2850f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2851f624d976SQu Wenruo 		if (err == -EAGAIN)
2852f624d976SQu Wenruo 			goto again;
2853f624d976SQu Wenruo 		if (err) {
2854f624d976SQu Wenruo 			ret = err;
2855f624d976SQu Wenruo 			goto done;
2856f624d976SQu Wenruo 		}
2857f624d976SQu Wenruo 
2858f624d976SQu Wenruo 		if (!p->skip_locking) {
2859f624d976SQu Wenruo 			level = btrfs_header_level(b);
2860f624d976SQu Wenruo 			if (level <= write_lock_level) {
2861f624d976SQu Wenruo 				if (!btrfs_try_tree_write_lock(b)) {
2862f624d976SQu Wenruo 					btrfs_set_path_blocking(p);
2863f624d976SQu Wenruo 					btrfs_tree_lock(b);
2864f624d976SQu Wenruo 				}
2865f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2866f624d976SQu Wenruo 			} else {
2867f624d976SQu Wenruo 				if (!btrfs_tree_read_lock_atomic(b)) {
2868f624d976SQu Wenruo 					btrfs_set_path_blocking(p);
2869f624d976SQu Wenruo 					btrfs_tree_read_lock(b);
2870f624d976SQu Wenruo 				}
2871f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2872f624d976SQu Wenruo 			}
2873f624d976SQu Wenruo 			p->nodes[level] = b;
2874f624d976SQu Wenruo 		}
287565b51a00SChris Mason 	}
287665b51a00SChris Mason 	ret = 1;
287765b51a00SChris Mason done:
2878b4ce94deSChris Mason 	/*
2879b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2880b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2881b4ce94deSChris Mason 	 */
2882b9473439SChris Mason 	if (!p->leave_spinning)
2883b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
28845f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2885b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2886be0e5c09SChris Mason 	return ret;
2887be0e5c09SChris Mason }
2888be0e5c09SChris Mason 
288974123bd7SChris Mason /*
28905d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
28915d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
28925d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
28935d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
28945d9e75c4SJan Schmidt  *
28955d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
28965d9e75c4SJan Schmidt  *
28975d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
28985d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
28995d9e75c4SJan Schmidt  */
2900310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
29015d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
29025d9e75c4SJan Schmidt {
29030b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29045d9e75c4SJan Schmidt 	struct extent_buffer *b;
29055d9e75c4SJan Schmidt 	int slot;
29065d9e75c4SJan Schmidt 	int ret;
29075d9e75c4SJan Schmidt 	int err;
29085d9e75c4SJan Schmidt 	int level;
29095d9e75c4SJan Schmidt 	int lowest_unlock = 1;
29105d9e75c4SJan Schmidt 	u8 lowest_level = 0;
2911d4b4087cSJosef Bacik 	int prev_cmp = -1;
29125d9e75c4SJan Schmidt 
29135d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
29145d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
29155d9e75c4SJan Schmidt 
29165d9e75c4SJan Schmidt 	if (p->search_commit_root) {
29175d9e75c4SJan Schmidt 		BUG_ON(time_seq);
29185d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
29195d9e75c4SJan Schmidt 	}
29205d9e75c4SJan Schmidt 
29215d9e75c4SJan Schmidt again:
29225d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
2923315bed43SNikolay Borisov 	if (!b) {
2924315bed43SNikolay Borisov 		ret = -EIO;
2925315bed43SNikolay Borisov 		goto done;
2926315bed43SNikolay Borisov 	}
29275d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
29285d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
29295d9e75c4SJan Schmidt 
29305d9e75c4SJan Schmidt 	while (b) {
2931abe9339dSQu Wenruo 		int dec = 0;
2932abe9339dSQu Wenruo 
29335d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
29345d9e75c4SJan Schmidt 		p->nodes[level] = b;
29355d9e75c4SJan Schmidt 
29365d9e75c4SJan Schmidt 		/*
29375d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
29385d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
29395d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
29405d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
29415d9e75c4SJan Schmidt 		 */
29425d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
29435d9e75c4SJan Schmidt 
2944d4b4087cSJosef Bacik 		/*
294501327610SNicholas D Steeves 		 * Since we can unwind ebs we want to do a real search every
2946d4b4087cSJosef Bacik 		 * time.
2947d4b4087cSJosef Bacik 		 */
2948d4b4087cSJosef Bacik 		prev_cmp = -1;
2949d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
2950cbca7d59SFilipe Manana 		if (ret < 0)
2951cbca7d59SFilipe Manana 			goto done;
29525d9e75c4SJan Schmidt 
2953abe9339dSQu Wenruo 		if (level == 0) {
2954abe9339dSQu Wenruo 			p->slots[level] = slot;
2955abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2956abe9339dSQu Wenruo 			goto done;
2957abe9339dSQu Wenruo 		}
2958abe9339dSQu Wenruo 
29595d9e75c4SJan Schmidt 		if (ret && slot > 0) {
29605d9e75c4SJan Schmidt 			dec = 1;
2961abe9339dSQu Wenruo 			slot--;
29625d9e75c4SJan Schmidt 		}
29635d9e75c4SJan Schmidt 		p->slots[level] = slot;
29645d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
29655d9e75c4SJan Schmidt 
29665d9e75c4SJan Schmidt 		if (level == lowest_level) {
29675d9e75c4SJan Schmidt 			if (dec)
29685d9e75c4SJan Schmidt 				p->slots[level]++;
29695d9e75c4SJan Schmidt 			goto done;
29705d9e75c4SJan Schmidt 		}
29715d9e75c4SJan Schmidt 
2972abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
29735d9e75c4SJan Schmidt 		if (err == -EAGAIN)
29745d9e75c4SJan Schmidt 			goto again;
29755d9e75c4SJan Schmidt 		if (err) {
29765d9e75c4SJan Schmidt 			ret = err;
29775d9e75c4SJan Schmidt 			goto done;
29785d9e75c4SJan Schmidt 		}
29795d9e75c4SJan Schmidt 
29805d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
298165e99c43SNikolay Borisov 		if (!btrfs_tree_read_lock_atomic(b)) {
29825d9e75c4SJan Schmidt 			btrfs_set_path_blocking(p);
29835d9e75c4SJan Schmidt 			btrfs_tree_read_lock(b);
29845d9e75c4SJan Schmidt 		}
29850b246afaSJeff Mahoney 		b = tree_mod_log_rewind(fs_info, p, b, time_seq);
2986db7f3436SJosef Bacik 		if (!b) {
2987db7f3436SJosef Bacik 			ret = -ENOMEM;
2988db7f3436SJosef Bacik 			goto done;
2989db7f3436SJosef Bacik 		}
29905d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
29915d9e75c4SJan Schmidt 		p->nodes[level] = b;
29925d9e75c4SJan Schmidt 	}
29935d9e75c4SJan Schmidt 	ret = 1;
29945d9e75c4SJan Schmidt done:
29955d9e75c4SJan Schmidt 	if (!p->leave_spinning)
29965d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
29975d9e75c4SJan Schmidt 	if (ret < 0)
29985d9e75c4SJan Schmidt 		btrfs_release_path(p);
29995d9e75c4SJan Schmidt 
30005d9e75c4SJan Schmidt 	return ret;
30015d9e75c4SJan Schmidt }
30025d9e75c4SJan Schmidt 
30035d9e75c4SJan Schmidt /*
30042f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
30052f38b3e1SArne Jansen  * instead the next or previous item should be returned.
30062f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
30072f38b3e1SArne Jansen  * otherwise.
30082f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
30092f38b3e1SArne Jansen  * return the next lower instead.
30102f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
30112f38b3e1SArne Jansen  * return the next higher instead.
30122f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
30132f38b3e1SArne Jansen  * < 0 on error
30142f38b3e1SArne Jansen  */
30152f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
3016310712b2SOmar Sandoval 			       const struct btrfs_key *key,
3017310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
3018310712b2SOmar Sandoval 			       int return_any)
30192f38b3e1SArne Jansen {
30202f38b3e1SArne Jansen 	int ret;
30212f38b3e1SArne Jansen 	struct extent_buffer *leaf;
30222f38b3e1SArne Jansen 
30232f38b3e1SArne Jansen again:
30242f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
30252f38b3e1SArne Jansen 	if (ret <= 0)
30262f38b3e1SArne Jansen 		return ret;
30272f38b3e1SArne Jansen 	/*
30282f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
30292f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
30302f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
30312f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
30322f38b3e1SArne Jansen 	 * item.
30332f38b3e1SArne Jansen 	 */
30342f38b3e1SArne Jansen 	leaf = p->nodes[0];
30352f38b3e1SArne Jansen 
30362f38b3e1SArne Jansen 	if (find_higher) {
30372f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
30382f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
30392f38b3e1SArne Jansen 			if (ret <= 0)
30402f38b3e1SArne Jansen 				return ret;
30412f38b3e1SArne Jansen 			if (!return_any)
30422f38b3e1SArne Jansen 				return 1;
30432f38b3e1SArne Jansen 			/*
30442f38b3e1SArne Jansen 			 * no higher item found, return the next
30452f38b3e1SArne Jansen 			 * lower instead
30462f38b3e1SArne Jansen 			 */
30472f38b3e1SArne Jansen 			return_any = 0;
30482f38b3e1SArne Jansen 			find_higher = 0;
30492f38b3e1SArne Jansen 			btrfs_release_path(p);
30502f38b3e1SArne Jansen 			goto again;
30512f38b3e1SArne Jansen 		}
30522f38b3e1SArne Jansen 	} else {
30532f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
30542f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
3055e6793769SArne Jansen 			if (ret < 0)
30562f38b3e1SArne Jansen 				return ret;
3057e6793769SArne Jansen 			if (!ret) {
305823c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
305923c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
306023c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
3061e6793769SArne Jansen 				return 0;
3062e6793769SArne Jansen 			}
30632f38b3e1SArne Jansen 			if (!return_any)
30642f38b3e1SArne Jansen 				return 1;
30652f38b3e1SArne Jansen 			/*
30662f38b3e1SArne Jansen 			 * no lower item found, return the next
30672f38b3e1SArne Jansen 			 * higher instead
30682f38b3e1SArne Jansen 			 */
30692f38b3e1SArne Jansen 			return_any = 0;
30702f38b3e1SArne Jansen 			find_higher = 1;
30712f38b3e1SArne Jansen 			btrfs_release_path(p);
30722f38b3e1SArne Jansen 			goto again;
3073e6793769SArne Jansen 		} else {
30742f38b3e1SArne Jansen 			--p->slots[0];
30752f38b3e1SArne Jansen 		}
30762f38b3e1SArne Jansen 	}
30772f38b3e1SArne Jansen 	return 0;
30782f38b3e1SArne Jansen }
30792f38b3e1SArne Jansen 
30802f38b3e1SArne Jansen /*
308174123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
308274123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
308374123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
308474123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
308574123bd7SChris Mason  * higher levels
3086aa5d6bedSChris Mason  *
308774123bd7SChris Mason  */
3088b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
30895f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
3090be0e5c09SChris Mason {
3091be0e5c09SChris Mason 	int i;
30925f39d397SChris Mason 	struct extent_buffer *t;
30930e82bcfeSDavid Sterba 	int ret;
30945f39d397SChris Mason 
3095234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3096be0e5c09SChris Mason 		int tslot = path->slots[i];
30970e82bcfeSDavid Sterba 
3098eb60ceacSChris Mason 		if (!path->nodes[i])
3099be0e5c09SChris Mason 			break;
31005f39d397SChris Mason 		t = path->nodes[i];
31010e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
31020e82bcfeSDavid Sterba 				GFP_ATOMIC);
31030e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
31045f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
3105d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
3106be0e5c09SChris Mason 		if (tslot != 0)
3107be0e5c09SChris Mason 			break;
3108be0e5c09SChris Mason 	}
3109be0e5c09SChris Mason }
3110be0e5c09SChris Mason 
311174123bd7SChris Mason /*
311231840ae1SZheng Yan  * update item key.
311331840ae1SZheng Yan  *
311431840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
311531840ae1SZheng Yan  * that the new key won't break the order
311631840ae1SZheng Yan  */
3117b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3118b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
3119310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
312031840ae1SZheng Yan {
312131840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
312231840ae1SZheng Yan 	struct extent_buffer *eb;
312331840ae1SZheng Yan 	int slot;
312431840ae1SZheng Yan 
312531840ae1SZheng Yan 	eb = path->nodes[0];
312631840ae1SZheng Yan 	slot = path->slots[0];
312731840ae1SZheng Yan 	if (slot > 0) {
312831840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
31297c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
31307c15d410SQu Wenruo 			btrfs_crit(fs_info,
31317c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
31327c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
31337c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
31347c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
31357c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
31367c15d410SQu Wenruo 				   new_key->offset);
31377c15d410SQu Wenruo 			btrfs_print_leaf(eb);
31387c15d410SQu Wenruo 			BUG();
31397c15d410SQu Wenruo 		}
314031840ae1SZheng Yan 	}
314131840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
314231840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
31437c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
31447c15d410SQu Wenruo 			btrfs_crit(fs_info,
31457c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
31467c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
31477c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
31487c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
31497c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
31507c15d410SQu Wenruo 				   new_key->offset);
31517c15d410SQu Wenruo 			btrfs_print_leaf(eb);
31527c15d410SQu Wenruo 			BUG();
31537c15d410SQu Wenruo 		}
315431840ae1SZheng Yan 	}
315531840ae1SZheng Yan 
315631840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
315731840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
315831840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
315931840ae1SZheng Yan 	if (slot == 0)
3160b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
316131840ae1SZheng Yan }
316231840ae1SZheng Yan 
316331840ae1SZheng Yan /*
316474123bd7SChris Mason  * try to push data from one node into the next node left in the
316579f95c82SChris Mason  * tree.
3166aa5d6bedSChris Mason  *
3167aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3168aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
316974123bd7SChris Mason  */
317098ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
31712ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
3172971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
3173be0e5c09SChris Mason {
3174d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3175be0e5c09SChris Mason 	int push_items = 0;
3176bb803951SChris Mason 	int src_nritems;
3177bb803951SChris Mason 	int dst_nritems;
3178aa5d6bedSChris Mason 	int ret = 0;
3179be0e5c09SChris Mason 
31805f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
31815f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
31820b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
31837bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
31847bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
318554aa1f4dSChris Mason 
3186bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
3187971a1f66SChris Mason 		return 1;
3188971a1f66SChris Mason 
3189d397712bSChris Mason 	if (push_items <= 0)
3190be0e5c09SChris Mason 		return 1;
3191be0e5c09SChris Mason 
3192bce4eae9SChris Mason 	if (empty) {
3193971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
3194bce4eae9SChris Mason 		if (push_items < src_nritems) {
3195bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
3196bce4eae9SChris Mason 			 * we aren't going to empty it
3197bce4eae9SChris Mason 			 */
3198bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
3199bce4eae9SChris Mason 				if (push_items <= 8)
3200bce4eae9SChris Mason 					return 1;
3201bce4eae9SChris Mason 				push_items -= 8;
3202bce4eae9SChris Mason 			}
3203bce4eae9SChris Mason 		}
3204bce4eae9SChris Mason 	} else
3205bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
320679f95c82SChris Mason 
3207ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
32085de865eeSFilipe David Borba Manana 	if (ret) {
320966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32105de865eeSFilipe David Borba Manana 		return ret;
32115de865eeSFilipe David Borba Manana 	}
32125f39d397SChris Mason 	copy_extent_buffer(dst, src,
32135f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
32145f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3215123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
32165f39d397SChris Mason 
3217bb803951SChris Mason 	if (push_items < src_nritems) {
321857911b8bSJan Schmidt 		/*
3219bf1d3425SDavid Sterba 		 * Don't call tree_mod_log_insert_move here, key removal was
3220bf1d3425SDavid Sterba 		 * already fully logged by tree_mod_log_eb_copy above.
322157911b8bSJan Schmidt 		 */
32225f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
32235f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3224e2fa7227SChris Mason 				      (src_nritems - push_items) *
3225123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3226bb803951SChris Mason 	}
32275f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
32285f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
32295f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
32305f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
323131840ae1SZheng Yan 
3232bb803951SChris Mason 	return ret;
3233be0e5c09SChris Mason }
3234be0e5c09SChris Mason 
323597571fd0SChris Mason /*
323679f95c82SChris Mason  * try to push data from one node into the next node right in the
323779f95c82SChris Mason  * tree.
323879f95c82SChris Mason  *
323979f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
324079f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
324179f95c82SChris Mason  *
324279f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
324379f95c82SChris Mason  */
32445f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
32455f39d397SChris Mason 			      struct extent_buffer *dst,
32465f39d397SChris Mason 			      struct extent_buffer *src)
324779f95c82SChris Mason {
324855d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
324979f95c82SChris Mason 	int push_items = 0;
325079f95c82SChris Mason 	int max_push;
325179f95c82SChris Mason 	int src_nritems;
325279f95c82SChris Mason 	int dst_nritems;
325379f95c82SChris Mason 	int ret = 0;
325479f95c82SChris Mason 
32557bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32567bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
32577bb86316SChris Mason 
32585f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32595f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
32600b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3261d397712bSChris Mason 	if (push_items <= 0)
326279f95c82SChris Mason 		return 1;
3263bce4eae9SChris Mason 
3264d397712bSChris Mason 	if (src_nritems < 4)
3265bce4eae9SChris Mason 		return 1;
326679f95c82SChris Mason 
326779f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
326879f95c82SChris Mason 	/* don't try to empty the node */
3269d397712bSChris Mason 	if (max_push >= src_nritems)
327079f95c82SChris Mason 		return 1;
3271252c38f0SYan 
327279f95c82SChris Mason 	if (max_push < push_items)
327379f95c82SChris Mason 		push_items = max_push;
327479f95c82SChris Mason 
3275bf1d3425SDavid Sterba 	ret = tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
3276bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
32775f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
32785f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
32795f39d397SChris Mason 				      (dst_nritems) *
32805f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3281d6025579SChris Mason 
3282ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
3283ed874f0dSDavid Sterba 				   push_items);
32845de865eeSFilipe David Borba Manana 	if (ret) {
328566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32865de865eeSFilipe David Borba Manana 		return ret;
32875de865eeSFilipe David Borba Manana 	}
32885f39d397SChris Mason 	copy_extent_buffer(dst, src,
32895f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
32905f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3291123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
329279f95c82SChris Mason 
32935f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
32945f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
329579f95c82SChris Mason 
32965f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
32975f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
329831840ae1SZheng Yan 
329979f95c82SChris Mason 	return ret;
330079f95c82SChris Mason }
330179f95c82SChris Mason 
330279f95c82SChris Mason /*
330397571fd0SChris Mason  * helper function to insert a new root level in the tree.
330497571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
330597571fd0SChris Mason  * point to the existing root
3306aa5d6bedSChris Mason  *
3307aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
330897571fd0SChris Mason  */
3309d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
33105f39d397SChris Mason 			   struct btrfs_root *root,
3311fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
331274123bd7SChris Mason {
33130b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
33147bb86316SChris Mason 	u64 lower_gen;
33155f39d397SChris Mason 	struct extent_buffer *lower;
33165f39d397SChris Mason 	struct extent_buffer *c;
3317925baeddSChris Mason 	struct extent_buffer *old;
33185f39d397SChris Mason 	struct btrfs_disk_key lower_key;
3319d9d19a01SDavid Sterba 	int ret;
33205c680ed6SChris Mason 
33215c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
33225c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
33235c680ed6SChris Mason 
33247bb86316SChris Mason 	lower = path->nodes[level-1];
33257bb86316SChris Mason 	if (level == 1)
33267bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
33277bb86316SChris Mason 	else
33287bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
33297bb86316SChris Mason 
3330a6279470SFilipe Manana 	c = alloc_tree_block_no_bg_flush(trans, root, 0, &lower_key, level,
3331a6279470SFilipe Manana 					 root->node->start, 0);
33325f39d397SChris Mason 	if (IS_ERR(c))
33335f39d397SChris Mason 		return PTR_ERR(c);
3334925baeddSChris Mason 
33350b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3336f0486c68SYan, Zheng 
33375f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
33385f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3339db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
33407bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
334131840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
33427bb86316SChris Mason 
33437bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
33445f39d397SChris Mason 
33455f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3346d5719762SChris Mason 
3347925baeddSChris Mason 	old = root->node;
3348d9d19a01SDavid Sterba 	ret = tree_mod_log_insert_root(root->node, c, 0);
3349d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
3350240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3351925baeddSChris Mason 
3352925baeddSChris Mason 	/* the super has an extra ref to root->node */
3353925baeddSChris Mason 	free_extent_buffer(old);
3354925baeddSChris Mason 
33550b86a832SChris Mason 	add_root_to_dirty_list(root);
335667439dadSDavid Sterba 	atomic_inc(&c->refs);
33575f39d397SChris Mason 	path->nodes[level] = c;
335895449a16Schandan 	path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
335974123bd7SChris Mason 	path->slots[level] = 0;
336074123bd7SChris Mason 	return 0;
336174123bd7SChris Mason }
33625c680ed6SChris Mason 
33635c680ed6SChris Mason /*
33645c680ed6SChris Mason  * worker function to insert a single pointer in a node.
33655c680ed6SChris Mason  * the node should have enough room for the pointer already
336697571fd0SChris Mason  *
33675c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
33685c680ed6SChris Mason  * blocknr is the block the key points to.
33695c680ed6SChris Mason  */
3370143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
33716ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
3372143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3373c3e06965SJan Schmidt 		       int slot, int level)
33745c680ed6SChris Mason {
33755f39d397SChris Mason 	struct extent_buffer *lower;
33765c680ed6SChris Mason 	int nritems;
3377f3ea38daSJan Schmidt 	int ret;
33785c680ed6SChris Mason 
33795c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3380f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
33815f39d397SChris Mason 	lower = path->nodes[level];
33825f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3383c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
33846ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
338574123bd7SChris Mason 	if (slot != nritems) {
3386bf1d3425SDavid Sterba 		if (level) {
3387bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(lower, slot + 1, slot,
3388a446a979SDavid Sterba 					nritems - slot);
3389bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
3390bf1d3425SDavid Sterba 		}
33915f39d397SChris Mason 		memmove_extent_buffer(lower,
33925f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
33935f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3394123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
339574123bd7SChris Mason 	}
3396c3e06965SJan Schmidt 	if (level) {
3397e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3398e09c2efeSDavid Sterba 				GFP_NOFS);
3399f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3400f3ea38daSJan Schmidt 	}
34015f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3402db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
340374493f7aSChris Mason 	WARN_ON(trans->transid == 0);
340474493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
34055f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
34065f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
340774123bd7SChris Mason }
340874123bd7SChris Mason 
340997571fd0SChris Mason /*
341097571fd0SChris Mason  * split the node at the specified level in path in two.
341197571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
341297571fd0SChris Mason  *
341397571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
341497571fd0SChris Mason  * left and right, if either one works, it returns right away.
3415aa5d6bedSChris Mason  *
3416aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
341797571fd0SChris Mason  */
3418e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3419e02119d5SChris Mason 			       struct btrfs_root *root,
3420e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3421be0e5c09SChris Mason {
34220b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
34235f39d397SChris Mason 	struct extent_buffer *c;
34245f39d397SChris Mason 	struct extent_buffer *split;
34255f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3426be0e5c09SChris Mason 	int mid;
34275c680ed6SChris Mason 	int ret;
34287518a238SChris Mason 	u32 c_nritems;
3429be0e5c09SChris Mason 
34305f39d397SChris Mason 	c = path->nodes[level];
34317bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
34325f39d397SChris Mason 	if (c == root->node) {
3433d9abbf1cSJan Schmidt 		/*
343490f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
343590f8d62eSJan Schmidt 		 *
3436fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
343790f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
343890f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
343990f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
344090f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
344190f8d62eSJan Schmidt 		 * other tree_mod_log users.
3442d9abbf1cSJan Schmidt 		 */
3443fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
34445c680ed6SChris Mason 		if (ret)
34455c680ed6SChris Mason 			return ret;
3446b3612421SChris Mason 	} else {
3447e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
34485f39d397SChris Mason 		c = path->nodes[level];
34495f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
34500b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3451e66f709bSChris Mason 			return 0;
345254aa1f4dSChris Mason 		if (ret < 0)
345354aa1f4dSChris Mason 			return ret;
34545c680ed6SChris Mason 	}
3455e66f709bSChris Mason 
34565f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
34575d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
34585d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
34597bb86316SChris Mason 
3460a6279470SFilipe Manana 	split = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, level,
3461a6279470SFilipe Manana 					     c->start, 0);
34625f39d397SChris Mason 	if (IS_ERR(split))
34635f39d397SChris Mason 		return PTR_ERR(split);
346454aa1f4dSChris Mason 
34650b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3466bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
34675f39d397SChris Mason 
3468ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
34695de865eeSFilipe David Borba Manana 	if (ret) {
347066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
34715de865eeSFilipe David Borba Manana 		return ret;
34725de865eeSFilipe David Borba Manana 	}
34735f39d397SChris Mason 	copy_extent_buffer(split, c,
34745f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
34755f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3476123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
34775f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
34785f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3479aa5d6bedSChris Mason 	ret = 0;
3480aa5d6bedSChris Mason 
34815f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
34825f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
34835f39d397SChris Mason 
34846ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
3485c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3486aa5d6bedSChris Mason 
34875de08d7dSChris Mason 	if (path->slots[level] >= mid) {
34885c680ed6SChris Mason 		path->slots[level] -= mid;
3489925baeddSChris Mason 		btrfs_tree_unlock(c);
34905f39d397SChris Mason 		free_extent_buffer(c);
34915f39d397SChris Mason 		path->nodes[level] = split;
34925c680ed6SChris Mason 		path->slots[level + 1] += 1;
3493eb60ceacSChris Mason 	} else {
3494925baeddSChris Mason 		btrfs_tree_unlock(split);
34955f39d397SChris Mason 		free_extent_buffer(split);
3496be0e5c09SChris Mason 	}
3497aa5d6bedSChris Mason 	return ret;
3498be0e5c09SChris Mason }
3499be0e5c09SChris Mason 
350074123bd7SChris Mason /*
350174123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
350274123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
350374123bd7SChris Mason  * space used both by the item structs and the item data
350474123bd7SChris Mason  */
35055f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3506be0e5c09SChris Mason {
350741be1f3bSJosef Bacik 	struct btrfs_item *start_item;
350841be1f3bSJosef Bacik 	struct btrfs_item *end_item;
350941be1f3bSJosef Bacik 	struct btrfs_map_token token;
3510be0e5c09SChris Mason 	int data_len;
35115f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3512d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3513be0e5c09SChris Mason 
3514be0e5c09SChris Mason 	if (!nr)
3515be0e5c09SChris Mason 		return 0;
3516c82f823cSDavid Sterba 	btrfs_init_map_token(&token, l);
3517dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
3518dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
351941be1f3bSJosef Bacik 	data_len = btrfs_token_item_offset(l, start_item, &token) +
352041be1f3bSJosef Bacik 		btrfs_token_item_size(l, start_item, &token);
352141be1f3bSJosef Bacik 	data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
35220783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3523d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3524be0e5c09SChris Mason 	return data_len;
3525be0e5c09SChris Mason }
3526be0e5c09SChris Mason 
352774123bd7SChris Mason /*
3528d4dbff95SChris Mason  * The space between the end of the leaf items and
3529d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3530d4dbff95SChris Mason  * the leaf has left for both items and data
3531d4dbff95SChris Mason  */
3532e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
3533d4dbff95SChris Mason {
3534e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
35355f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
35365f39d397SChris Mason 	int ret;
35370b246afaSJeff Mahoney 
35380b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
35395f39d397SChris Mason 	if (ret < 0) {
35400b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3541efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3542da17066cSJeff Mahoney 			   ret,
35430b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
35445f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
35455f39d397SChris Mason 	}
35465f39d397SChris Mason 	return ret;
3547d4dbff95SChris Mason }
3548d4dbff95SChris Mason 
354999d8f83cSChris Mason /*
355099d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
355199d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
355299d8f83cSChris Mason  */
3553f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
355444871b1bSChris Mason 				      int data_size, int empty,
355544871b1bSChris Mason 				      struct extent_buffer *right,
355699d8f83cSChris Mason 				      int free_space, u32 left_nritems,
355799d8f83cSChris Mason 				      u32 min_slot)
355800ec4c51SChris Mason {
3559f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
35605f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
356144871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3562cfed81a0SChris Mason 	struct btrfs_map_token token;
35635f39d397SChris Mason 	struct btrfs_disk_key disk_key;
356400ec4c51SChris Mason 	int slot;
356534a38218SChris Mason 	u32 i;
356600ec4c51SChris Mason 	int push_space = 0;
356700ec4c51SChris Mason 	int push_items = 0;
35680783fcfcSChris Mason 	struct btrfs_item *item;
356934a38218SChris Mason 	u32 nr;
35707518a238SChris Mason 	u32 right_nritems;
35715f39d397SChris Mason 	u32 data_end;
3572db94535dSChris Mason 	u32 this_item_size;
357300ec4c51SChris Mason 
357434a38218SChris Mason 	if (empty)
357534a38218SChris Mason 		nr = 0;
357634a38218SChris Mason 	else
357799d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
357834a38218SChris Mason 
357931840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
358087b29b20SYan Zheng 		push_space += data_size;
358131840ae1SZheng Yan 
358244871b1bSChris Mason 	slot = path->slots[1];
358334a38218SChris Mason 	i = left_nritems - 1;
358434a38218SChris Mason 	while (i >= nr) {
3585dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3586db94535dSChris Mason 
358731840ae1SZheng Yan 		if (!empty && push_items > 0) {
358831840ae1SZheng Yan 			if (path->slots[0] > i)
358931840ae1SZheng Yan 				break;
359031840ae1SZheng Yan 			if (path->slots[0] == i) {
3591e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3592e902baacSDavid Sterba 
359331840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
359431840ae1SZheng Yan 					break;
359531840ae1SZheng Yan 			}
359631840ae1SZheng Yan 		}
359731840ae1SZheng Yan 
359800ec4c51SChris Mason 		if (path->slots[0] == i)
359987b29b20SYan Zheng 			push_space += data_size;
3600db94535dSChris Mason 
3601db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3602db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
360300ec4c51SChris Mason 			break;
360431840ae1SZheng Yan 
360500ec4c51SChris Mason 		push_items++;
3606db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
360734a38218SChris Mason 		if (i == 0)
360834a38218SChris Mason 			break;
360934a38218SChris Mason 		i--;
3610db94535dSChris Mason 	}
36115f39d397SChris Mason 
3612925baeddSChris Mason 	if (push_items == 0)
3613925baeddSChris Mason 		goto out_unlock;
36145f39d397SChris Mason 
36156c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
36165f39d397SChris Mason 
361700ec4c51SChris Mason 	/* push left to right */
36185f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
361934a38218SChris Mason 
36205f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
36218f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
36225f39d397SChris Mason 
362300ec4c51SChris Mason 	/* make room in the right data area */
36248f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
36255f39d397SChris Mason 	memmove_extent_buffer(right,
36263d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
36273d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
36280b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
36295f39d397SChris Mason 
363000ec4c51SChris Mason 	/* copy from the left data area */
36313d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
36320b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
36338f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3634d6025579SChris Mason 		     push_space);
36355f39d397SChris Mason 
36365f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
36375f39d397SChris Mason 			      btrfs_item_nr_offset(0),
36380783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
36395f39d397SChris Mason 
364000ec4c51SChris Mason 	/* copy the items from left to right */
36415f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
36425f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
36430783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
364400ec4c51SChris Mason 
364500ec4c51SChris Mason 	/* update the item pointers */
3646c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
36477518a238SChris Mason 	right_nritems += push_items;
36485f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
36490b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
36507518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
3651dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3652cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3653cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3654db94535dSChris Mason 	}
3655db94535dSChris Mason 
36567518a238SChris Mason 	left_nritems -= push_items;
36575f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
365800ec4c51SChris Mason 
365934a38218SChris Mason 	if (left_nritems)
36605f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3661f0486c68SYan, Zheng 	else
36626a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3663f0486c68SYan, Zheng 
36645f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3665a429e513SChris Mason 
36665f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
36675f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3668d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
366902217ed2SChris Mason 
367000ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
36717518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
36727518a238SChris Mason 		path->slots[0] -= left_nritems;
3673925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
36746a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3675925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
36765f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
36775f39d397SChris Mason 		path->nodes[0] = right;
367800ec4c51SChris Mason 		path->slots[1] += 1;
367900ec4c51SChris Mason 	} else {
3680925baeddSChris Mason 		btrfs_tree_unlock(right);
36815f39d397SChris Mason 		free_extent_buffer(right);
368200ec4c51SChris Mason 	}
368300ec4c51SChris Mason 	return 0;
3684925baeddSChris Mason 
3685925baeddSChris Mason out_unlock:
3686925baeddSChris Mason 	btrfs_tree_unlock(right);
3687925baeddSChris Mason 	free_extent_buffer(right);
3688925baeddSChris Mason 	return 1;
368900ec4c51SChris Mason }
3690925baeddSChris Mason 
369100ec4c51SChris Mason /*
369244871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
369374123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
369444871b1bSChris Mason  *
369544871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
369644871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
369799d8f83cSChris Mason  *
369899d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
369999d8f83cSChris Mason  * push any slot lower than min_slot
370074123bd7SChris Mason  */
370144871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
370299d8f83cSChris Mason 			   *root, struct btrfs_path *path,
370399d8f83cSChris Mason 			   int min_data_size, int data_size,
370499d8f83cSChris Mason 			   int empty, u32 min_slot)
3705be0e5c09SChris Mason {
370644871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
370744871b1bSChris Mason 	struct extent_buffer *right;
370844871b1bSChris Mason 	struct extent_buffer *upper;
370944871b1bSChris Mason 	int slot;
371044871b1bSChris Mason 	int free_space;
371144871b1bSChris Mason 	u32 left_nritems;
371244871b1bSChris Mason 	int ret;
371344871b1bSChris Mason 
371444871b1bSChris Mason 	if (!path->nodes[1])
371544871b1bSChris Mason 		return 1;
371644871b1bSChris Mason 
371744871b1bSChris Mason 	slot = path->slots[1];
371844871b1bSChris Mason 	upper = path->nodes[1];
371944871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
372044871b1bSChris Mason 		return 1;
372144871b1bSChris Mason 
372244871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
372344871b1bSChris Mason 
37244b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3725fb770ae4SLiu Bo 	/*
3726fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3727fb770ae4SLiu Bo 	 * no big deal, just return.
3728fb770ae4SLiu Bo 	 */
3729fb770ae4SLiu Bo 	if (IS_ERR(right))
373091ca338dSTsutomu Itoh 		return 1;
373191ca338dSTsutomu Itoh 
373244871b1bSChris Mason 	btrfs_tree_lock(right);
37338bead258SDavid Sterba 	btrfs_set_lock_blocking_write(right);
373444871b1bSChris Mason 
3735e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
373644871b1bSChris Mason 	if (free_space < data_size)
373744871b1bSChris Mason 		goto out_unlock;
373844871b1bSChris Mason 
373944871b1bSChris Mason 	/* cow and double check */
374044871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
374144871b1bSChris Mason 			      slot + 1, &right);
374244871b1bSChris Mason 	if (ret)
374344871b1bSChris Mason 		goto out_unlock;
374444871b1bSChris Mason 
3745e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
374644871b1bSChris Mason 	if (free_space < data_size)
374744871b1bSChris Mason 		goto out_unlock;
374844871b1bSChris Mason 
374944871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
375044871b1bSChris Mason 	if (left_nritems == 0)
375144871b1bSChris Mason 		goto out_unlock;
375244871b1bSChris Mason 
37532ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
37542ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
37552ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
37562ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
375752042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
37582ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
37592ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
37602ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
37612ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
37622ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
37632ef1fed2SFilipe David Borba Manana 		return 0;
37642ef1fed2SFilipe David Borba Manana 	}
37652ef1fed2SFilipe David Borba Manana 
3766f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
376799d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
376844871b1bSChris Mason out_unlock:
376944871b1bSChris Mason 	btrfs_tree_unlock(right);
377044871b1bSChris Mason 	free_extent_buffer(right);
377144871b1bSChris Mason 	return 1;
377244871b1bSChris Mason }
377344871b1bSChris Mason 
377444871b1bSChris Mason /*
377544871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
377644871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
377799d8f83cSChris Mason  *
377899d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
377999d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
378099d8f83cSChris Mason  * items
378144871b1bSChris Mason  */
37828087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
378344871b1bSChris Mason 				     int empty, struct extent_buffer *left,
378499d8f83cSChris Mason 				     int free_space, u32 right_nritems,
378599d8f83cSChris Mason 				     u32 max_slot)
378644871b1bSChris Mason {
37878087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
37885f39d397SChris Mason 	struct btrfs_disk_key disk_key;
37895f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3790be0e5c09SChris Mason 	int i;
3791be0e5c09SChris Mason 	int push_space = 0;
3792be0e5c09SChris Mason 	int push_items = 0;
37930783fcfcSChris Mason 	struct btrfs_item *item;
37947518a238SChris Mason 	u32 old_left_nritems;
379534a38218SChris Mason 	u32 nr;
3796aa5d6bedSChris Mason 	int ret = 0;
3797db94535dSChris Mason 	u32 this_item_size;
3798db94535dSChris Mason 	u32 old_left_item_size;
3799cfed81a0SChris Mason 	struct btrfs_map_token token;
3800cfed81a0SChris Mason 
380134a38218SChris Mason 	if (empty)
380299d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
380334a38218SChris Mason 	else
380499d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
380534a38218SChris Mason 
380634a38218SChris Mason 	for (i = 0; i < nr; i++) {
3807dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3808db94535dSChris Mason 
380931840ae1SZheng Yan 		if (!empty && push_items > 0) {
381031840ae1SZheng Yan 			if (path->slots[0] < i)
381131840ae1SZheng Yan 				break;
381231840ae1SZheng Yan 			if (path->slots[0] == i) {
3813e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3814e902baacSDavid Sterba 
381531840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
381631840ae1SZheng Yan 					break;
381731840ae1SZheng Yan 			}
381831840ae1SZheng Yan 		}
381931840ae1SZheng Yan 
3820be0e5c09SChris Mason 		if (path->slots[0] == i)
382187b29b20SYan Zheng 			push_space += data_size;
3822db94535dSChris Mason 
3823db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3824db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3825be0e5c09SChris Mason 			break;
3826db94535dSChris Mason 
3827be0e5c09SChris Mason 		push_items++;
3828db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3829be0e5c09SChris Mason 	}
3830db94535dSChris Mason 
3831be0e5c09SChris Mason 	if (push_items == 0) {
3832925baeddSChris Mason 		ret = 1;
3833925baeddSChris Mason 		goto out;
3834be0e5c09SChris Mason 	}
3835fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
38365f39d397SChris Mason 
3837be0e5c09SChris Mason 	/* push data from right to left */
38385f39d397SChris Mason 	copy_extent_buffer(left, right,
38395f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
38405f39d397SChris Mason 			   btrfs_item_nr_offset(0),
38415f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
38425f39d397SChris Mason 
38430b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
38445f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
38455f39d397SChris Mason 
38463d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
38478f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
38483d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
38495f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3850be0e5c09SChris Mason 		     push_space);
38515f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
385287b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3853eb60ceacSChris Mason 
3854c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
3855db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3856be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
38575f39d397SChris Mason 		u32 ioff;
3858db94535dSChris Mason 
3859dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3860db94535dSChris Mason 
3861cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3862cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
38630b246afaSJeff Mahoney 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size),
3864cfed81a0SChris Mason 		      &token);
3865be0e5c09SChris Mason 	}
38665f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3867be0e5c09SChris Mason 
3868be0e5c09SChris Mason 	/* fixup right node */
386931b1a2bdSJulia Lawall 	if (push_items > right_nritems)
387031b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3871d397712bSChris Mason 		       right_nritems);
387234a38218SChris Mason 
387334a38218SChris Mason 	if (push_items < right_nritems) {
38745f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
38758f881e8cSDavid Sterba 						  leaf_data_end(right);
38763d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
38770b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
38783d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
38798f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
38805f39d397SChris Mason 
38815f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
38825f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
38835f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
38840783fcfcSChris Mason 			     sizeof(struct btrfs_item));
388534a38218SChris Mason 	}
3886c82f823cSDavid Sterba 
3887c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3888eef1c494SYan 	right_nritems -= push_items;
3889eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
38900b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
38915f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
3892dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3893db94535dSChris Mason 
3894cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3895cfed81a0SChris Mason 								item, &token);
3896cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3897db94535dSChris Mason 	}
3898eb60ceacSChris Mason 
38995f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
390034a38218SChris Mason 	if (right_nritems)
39015f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3902f0486c68SYan, Zheng 	else
39036a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3904098f59c2SChris Mason 
39055f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3906b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3907be0e5c09SChris Mason 
3908be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3909be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3910be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3911925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
39125f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
39135f39d397SChris Mason 		path->nodes[0] = left;
3914be0e5c09SChris Mason 		path->slots[1] -= 1;
3915be0e5c09SChris Mason 	} else {
3916925baeddSChris Mason 		btrfs_tree_unlock(left);
39175f39d397SChris Mason 		free_extent_buffer(left);
3918be0e5c09SChris Mason 		path->slots[0] -= push_items;
3919be0e5c09SChris Mason 	}
3920eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3921aa5d6bedSChris Mason 	return ret;
3922925baeddSChris Mason out:
3923925baeddSChris Mason 	btrfs_tree_unlock(left);
3924925baeddSChris Mason 	free_extent_buffer(left);
3925925baeddSChris Mason 	return ret;
3926be0e5c09SChris Mason }
3927be0e5c09SChris Mason 
392874123bd7SChris Mason /*
392944871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
393044871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
393199d8f83cSChris Mason  *
393299d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
393399d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
393499d8f83cSChris Mason  * items
393544871b1bSChris Mason  */
393644871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
393799d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
393899d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
393944871b1bSChris Mason {
394044871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
394144871b1bSChris Mason 	struct extent_buffer *left;
394244871b1bSChris Mason 	int slot;
394344871b1bSChris Mason 	int free_space;
394444871b1bSChris Mason 	u32 right_nritems;
394544871b1bSChris Mason 	int ret = 0;
394644871b1bSChris Mason 
394744871b1bSChris Mason 	slot = path->slots[1];
394844871b1bSChris Mason 	if (slot == 0)
394944871b1bSChris Mason 		return 1;
395044871b1bSChris Mason 	if (!path->nodes[1])
395144871b1bSChris Mason 		return 1;
395244871b1bSChris Mason 
395344871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
395444871b1bSChris Mason 	if (right_nritems == 0)
395544871b1bSChris Mason 		return 1;
395644871b1bSChris Mason 
395744871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
395844871b1bSChris Mason 
39594b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3960fb770ae4SLiu Bo 	/*
3961fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3962fb770ae4SLiu Bo 	 * no big deal, just return.
3963fb770ae4SLiu Bo 	 */
3964fb770ae4SLiu Bo 	if (IS_ERR(left))
396591ca338dSTsutomu Itoh 		return 1;
396691ca338dSTsutomu Itoh 
396744871b1bSChris Mason 	btrfs_tree_lock(left);
39688bead258SDavid Sterba 	btrfs_set_lock_blocking_write(left);
396944871b1bSChris Mason 
3970e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
397144871b1bSChris Mason 	if (free_space < data_size) {
397244871b1bSChris Mason 		ret = 1;
397344871b1bSChris Mason 		goto out;
397444871b1bSChris Mason 	}
397544871b1bSChris Mason 
397644871b1bSChris Mason 	/* cow and double check */
397744871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
397844871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
397944871b1bSChris Mason 	if (ret) {
398044871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
398179787eaaSJeff Mahoney 		if (ret == -ENOSPC)
398244871b1bSChris Mason 			ret = 1;
398344871b1bSChris Mason 		goto out;
398444871b1bSChris Mason 	}
398544871b1bSChris Mason 
3986e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
398744871b1bSChris Mason 	if (free_space < data_size) {
398844871b1bSChris Mason 		ret = 1;
398944871b1bSChris Mason 		goto out;
399044871b1bSChris Mason 	}
399144871b1bSChris Mason 
39928087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
399399d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
399499d8f83cSChris Mason 			       max_slot);
399544871b1bSChris Mason out:
399644871b1bSChris Mason 	btrfs_tree_unlock(left);
399744871b1bSChris Mason 	free_extent_buffer(left);
399844871b1bSChris Mason 	return ret;
399944871b1bSChris Mason }
400044871b1bSChris Mason 
400144871b1bSChris Mason /*
400274123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
400374123bd7SChris Mason  * available for the resulting leaf level of the path.
400474123bd7SChris Mason  */
4005143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
400644871b1bSChris Mason 				    struct btrfs_path *path,
400744871b1bSChris Mason 				    struct extent_buffer *l,
400844871b1bSChris Mason 				    struct extent_buffer *right,
400944871b1bSChris Mason 				    int slot, int mid, int nritems)
4010be0e5c09SChris Mason {
401194f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
4012be0e5c09SChris Mason 	int data_copy_size;
4013be0e5c09SChris Mason 	int rt_data_off;
4014be0e5c09SChris Mason 	int i;
4015d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
4016cfed81a0SChris Mason 	struct btrfs_map_token token;
4017cfed81a0SChris Mason 
40185f39d397SChris Mason 	nritems = nritems - mid;
40195f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
40208f881e8cSDavid Sterba 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
40215f39d397SChris Mason 
40225f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
40235f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
40245f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
40255f39d397SChris Mason 
40265f39d397SChris Mason 	copy_extent_buffer(right, l,
40273d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
40283d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
40298f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
403074123bd7SChris Mason 
40310b246afaSJeff Mahoney 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
40325f39d397SChris Mason 
4033c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
40345f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
4035dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
4036db94535dSChris Mason 		u32 ioff;
4037db94535dSChris Mason 
4038cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
4039cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
4040cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
40410783fcfcSChris Mason 	}
404274123bd7SChris Mason 
40435f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
40445f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
40456ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
40465f39d397SChris Mason 
40475f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
40485f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
4049eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
40505f39d397SChris Mason 
4051be0e5c09SChris Mason 	if (mid <= slot) {
4052925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
40535f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
40545f39d397SChris Mason 		path->nodes[0] = right;
4055be0e5c09SChris Mason 		path->slots[0] -= mid;
4056be0e5c09SChris Mason 		path->slots[1] += 1;
4057925baeddSChris Mason 	} else {
4058925baeddSChris Mason 		btrfs_tree_unlock(right);
40595f39d397SChris Mason 		free_extent_buffer(right);
4060925baeddSChris Mason 	}
40615f39d397SChris Mason 
4062eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
406344871b1bSChris Mason }
406444871b1bSChris Mason 
406544871b1bSChris Mason /*
406699d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
406799d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
406899d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
406999d8f83cSChris Mason  *          A                 B                 C
407099d8f83cSChris Mason  *
407199d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
407299d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
407399d8f83cSChris Mason  * completely.
407499d8f83cSChris Mason  */
407599d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
407699d8f83cSChris Mason 					  struct btrfs_root *root,
407799d8f83cSChris Mason 					  struct btrfs_path *path,
407899d8f83cSChris Mason 					  int data_size)
407999d8f83cSChris Mason {
408099d8f83cSChris Mason 	int ret;
408199d8f83cSChris Mason 	int progress = 0;
408299d8f83cSChris Mason 	int slot;
408399d8f83cSChris Mason 	u32 nritems;
40845a4267caSFilipe David Borba Manana 	int space_needed = data_size;
408599d8f83cSChris Mason 
408699d8f83cSChris Mason 	slot = path->slots[0];
40875a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
4088e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
408999d8f83cSChris Mason 
409099d8f83cSChris Mason 	/*
409199d8f83cSChris Mason 	 * try to push all the items after our slot into the
409299d8f83cSChris Mason 	 * right leaf
409399d8f83cSChris Mason 	 */
40945a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
409599d8f83cSChris Mason 	if (ret < 0)
409699d8f83cSChris Mason 		return ret;
409799d8f83cSChris Mason 
409899d8f83cSChris Mason 	if (ret == 0)
409999d8f83cSChris Mason 		progress++;
410099d8f83cSChris Mason 
410199d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
410299d8f83cSChris Mason 	/*
410399d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
410499d8f83cSChris Mason 	 * we've done so we're done
410599d8f83cSChris Mason 	 */
410699d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
410799d8f83cSChris Mason 		return 0;
410899d8f83cSChris Mason 
4109e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
411099d8f83cSChris Mason 		return 0;
411199d8f83cSChris Mason 
411299d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
411399d8f83cSChris Mason 	slot = path->slots[0];
4114263d3995SFilipe Manana 	space_needed = data_size;
4115263d3995SFilipe Manana 	if (slot > 0)
4116e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
41175a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
411899d8f83cSChris Mason 	if (ret < 0)
411999d8f83cSChris Mason 		return ret;
412099d8f83cSChris Mason 
412199d8f83cSChris Mason 	if (ret == 0)
412299d8f83cSChris Mason 		progress++;
412399d8f83cSChris Mason 
412499d8f83cSChris Mason 	if (progress)
412599d8f83cSChris Mason 		return 0;
412699d8f83cSChris Mason 	return 1;
412799d8f83cSChris Mason }
412899d8f83cSChris Mason 
412999d8f83cSChris Mason /*
413044871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
413144871b1bSChris Mason  * available for the resulting leaf level of the path.
413244871b1bSChris Mason  *
413344871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
413444871b1bSChris Mason  */
413544871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
413644871b1bSChris Mason 			       struct btrfs_root *root,
4137310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
413844871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
413944871b1bSChris Mason 			       int extend)
414044871b1bSChris Mason {
41415d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
414244871b1bSChris Mason 	struct extent_buffer *l;
414344871b1bSChris Mason 	u32 nritems;
414444871b1bSChris Mason 	int mid;
414544871b1bSChris Mason 	int slot;
414644871b1bSChris Mason 	struct extent_buffer *right;
4147b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
414844871b1bSChris Mason 	int ret = 0;
414944871b1bSChris Mason 	int wret;
41505d4f98a2SYan Zheng 	int split;
415144871b1bSChris Mason 	int num_doubles = 0;
415299d8f83cSChris Mason 	int tried_avoid_double = 0;
415344871b1bSChris Mason 
4154a5719521SYan, Zheng 	l = path->nodes[0];
4155a5719521SYan, Zheng 	slot = path->slots[0];
4156a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
41570b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4158a5719521SYan, Zheng 		return -EOVERFLOW;
4159a5719521SYan, Zheng 
416044871b1bSChris Mason 	/* first try to make some room by pushing left and right */
416133157e05SLiu Bo 	if (data_size && path->nodes[1]) {
41625a4267caSFilipe David Borba Manana 		int space_needed = data_size;
41635a4267caSFilipe David Borba Manana 
41645a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
4165e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
41665a4267caSFilipe David Borba Manana 
41675a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
41685a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
416944871b1bSChris Mason 		if (wret < 0)
417044871b1bSChris Mason 			return wret;
417144871b1bSChris Mason 		if (wret) {
4172263d3995SFilipe Manana 			space_needed = data_size;
4173263d3995SFilipe Manana 			if (slot > 0)
4174e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
41755a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
41765a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
417744871b1bSChris Mason 			if (wret < 0)
417844871b1bSChris Mason 				return wret;
417944871b1bSChris Mason 		}
418044871b1bSChris Mason 		l = path->nodes[0];
418144871b1bSChris Mason 
418244871b1bSChris Mason 		/* did the pushes work? */
4183e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
418444871b1bSChris Mason 			return 0;
418544871b1bSChris Mason 	}
418644871b1bSChris Mason 
418744871b1bSChris Mason 	if (!path->nodes[1]) {
4188fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
418944871b1bSChris Mason 		if (ret)
419044871b1bSChris Mason 			return ret;
419144871b1bSChris Mason 	}
419244871b1bSChris Mason again:
41935d4f98a2SYan Zheng 	split = 1;
419444871b1bSChris Mason 	l = path->nodes[0];
419544871b1bSChris Mason 	slot = path->slots[0];
419644871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
419744871b1bSChris Mason 	mid = (nritems + 1) / 2;
419844871b1bSChris Mason 
41995d4f98a2SYan Zheng 	if (mid <= slot) {
42005d4f98a2SYan Zheng 		if (nritems == 1 ||
42015d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
42020b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42035d4f98a2SYan Zheng 			if (slot >= nritems) {
42045d4f98a2SYan Zheng 				split = 0;
42055d4f98a2SYan Zheng 			} else {
42065d4f98a2SYan Zheng 				mid = slot;
42075d4f98a2SYan Zheng 				if (mid != nritems &&
42085d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42090b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
421099d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
421199d8f83cSChris Mason 						goto push_for_double;
42125d4f98a2SYan Zheng 					split = 2;
42135d4f98a2SYan Zheng 				}
42145d4f98a2SYan Zheng 			}
42155d4f98a2SYan Zheng 		}
42165d4f98a2SYan Zheng 	} else {
42175d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
42180b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42195d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
42205d4f98a2SYan Zheng 				split = 0;
42215d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
42225d4f98a2SYan Zheng 				mid = 1;
42235d4f98a2SYan Zheng 			} else {
42245d4f98a2SYan Zheng 				mid = slot;
42255d4f98a2SYan Zheng 				if (mid != nritems &&
42265d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42270b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
422899d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
422999d8f83cSChris Mason 						goto push_for_double;
42305d4f98a2SYan Zheng 					split = 2;
42315d4f98a2SYan Zheng 				}
42325d4f98a2SYan Zheng 			}
42335d4f98a2SYan Zheng 		}
42345d4f98a2SYan Zheng 	}
42355d4f98a2SYan Zheng 
42365d4f98a2SYan Zheng 	if (split == 0)
42375d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
42385d4f98a2SYan Zheng 	else
42395d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
42405d4f98a2SYan Zheng 
4241a6279470SFilipe Manana 	right = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, 0,
4242a6279470SFilipe Manana 					     l->start, 0);
4243f0486c68SYan, Zheng 	if (IS_ERR(right))
424444871b1bSChris Mason 		return PTR_ERR(right);
4245f0486c68SYan, Zheng 
42460b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
424744871b1bSChris Mason 
42485d4f98a2SYan Zheng 	if (split == 0) {
424944871b1bSChris Mason 		if (mid <= slot) {
425044871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
42516ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
42522ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
425344871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
425444871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
425544871b1bSChris Mason 			path->nodes[0] = right;
425644871b1bSChris Mason 			path->slots[0] = 0;
425744871b1bSChris Mason 			path->slots[1] += 1;
425844871b1bSChris Mason 		} else {
425944871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
42606ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
42612ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
426244871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
426344871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
426444871b1bSChris Mason 			path->nodes[0] = right;
426544871b1bSChris Mason 			path->slots[0] = 0;
4266143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4267b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
42685d4f98a2SYan Zheng 		}
4269196e0249SLiu Bo 		/*
4270196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
4271196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4272196e0249SLiu Bo 		 * the content of ins_len to 'right'.
4273196e0249SLiu Bo 		 */
427444871b1bSChris Mason 		return ret;
427544871b1bSChris Mason 	}
427644871b1bSChris Mason 
427794f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
427844871b1bSChris Mason 
42795d4f98a2SYan Zheng 	if (split == 2) {
4280cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4281cc0c5538SChris Mason 		num_doubles++;
4282cc0c5538SChris Mason 		goto again;
42833326d1b0SChris Mason 	}
428444871b1bSChris Mason 
4285143bede5SJeff Mahoney 	return 0;
428699d8f83cSChris Mason 
428799d8f83cSChris Mason push_for_double:
428899d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
428999d8f83cSChris Mason 	tried_avoid_double = 1;
4290e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
429199d8f83cSChris Mason 		return 0;
429299d8f83cSChris Mason 	goto again;
4293be0e5c09SChris Mason }
4294be0e5c09SChris Mason 
4295ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4296ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4297ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4298ad48fd75SYan, Zheng {
4299ad48fd75SYan, Zheng 	struct btrfs_key key;
4300ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4301ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4302ad48fd75SYan, Zheng 	u64 extent_len = 0;
4303ad48fd75SYan, Zheng 	u32 item_size;
4304ad48fd75SYan, Zheng 	int ret;
4305ad48fd75SYan, Zheng 
4306ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4307ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4308ad48fd75SYan, Zheng 
4309ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4310ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4311ad48fd75SYan, Zheng 
4312e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
4313ad48fd75SYan, Zheng 		return 0;
4314ad48fd75SYan, Zheng 
4315ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4316ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4317ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4318ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4319ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4320ad48fd75SYan, Zheng 	}
4321b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4322ad48fd75SYan, Zheng 
4323ad48fd75SYan, Zheng 	path->keep_locks = 1;
4324ad48fd75SYan, Zheng 	path->search_for_split = 1;
4325ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4326ad48fd75SYan, Zheng 	path->search_for_split = 0;
4327a8df6fe6SFilipe Manana 	if (ret > 0)
4328a8df6fe6SFilipe Manana 		ret = -EAGAIN;
4329ad48fd75SYan, Zheng 	if (ret < 0)
4330ad48fd75SYan, Zheng 		goto err;
4331ad48fd75SYan, Zheng 
4332ad48fd75SYan, Zheng 	ret = -EAGAIN;
4333ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4334a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
4335a8df6fe6SFilipe Manana 	if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4336ad48fd75SYan, Zheng 		goto err;
4337ad48fd75SYan, Zheng 
4338109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4339e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
4340109f6aefSChris Mason 		goto err;
4341109f6aefSChris Mason 
4342ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4343ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4344ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4345ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4346ad48fd75SYan, Zheng 			goto err;
4347ad48fd75SYan, Zheng 	}
4348ad48fd75SYan, Zheng 
4349ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4350ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4351f0486c68SYan, Zheng 	if (ret)
4352f0486c68SYan, Zheng 		goto err;
4353ad48fd75SYan, Zheng 
4354ad48fd75SYan, Zheng 	path->keep_locks = 0;
4355ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4356ad48fd75SYan, Zheng 	return 0;
4357ad48fd75SYan, Zheng err:
4358ad48fd75SYan, Zheng 	path->keep_locks = 0;
4359ad48fd75SYan, Zheng 	return ret;
4360ad48fd75SYan, Zheng }
4361ad48fd75SYan, Zheng 
436225263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
4363310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
4364459931ecSChris Mason 			       unsigned long split_offset)
4365459931ecSChris Mason {
4366459931ecSChris Mason 	struct extent_buffer *leaf;
4367459931ecSChris Mason 	struct btrfs_item *item;
4368459931ecSChris Mason 	struct btrfs_item *new_item;
4369459931ecSChris Mason 	int slot;
4370ad48fd75SYan, Zheng 	char *buf;
4371459931ecSChris Mason 	u32 nritems;
4372ad48fd75SYan, Zheng 	u32 item_size;
4373459931ecSChris Mason 	u32 orig_offset;
4374459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4375459931ecSChris Mason 
4376459931ecSChris Mason 	leaf = path->nodes[0];
4377e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
4378b9473439SChris Mason 
4379b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4380b4ce94deSChris Mason 
4381dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
4382459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4383459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4384459931ecSChris Mason 
4385459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4386ad48fd75SYan, Zheng 	if (!buf)
4387ad48fd75SYan, Zheng 		return -ENOMEM;
4388ad48fd75SYan, Zheng 
4389459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4390459931ecSChris Mason 			    path->slots[0]), item_size);
4391ad48fd75SYan, Zheng 
4392459931ecSChris Mason 	slot = path->slots[0] + 1;
4393459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4394459931ecSChris Mason 	if (slot != nritems) {
4395459931ecSChris Mason 		/* shift the items */
4396459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4397459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4398459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4399459931ecSChris Mason 	}
4400459931ecSChris Mason 
4401459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4402459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4403459931ecSChris Mason 
4404dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
4405459931ecSChris Mason 
4406459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4407459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4408459931ecSChris Mason 
4409459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4410459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4411459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4412459931ecSChris Mason 
4413459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4414459931ecSChris Mason 
4415459931ecSChris Mason 	/* write the data for the start of the original item */
4416459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4417459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4418459931ecSChris Mason 			    split_offset);
4419459931ecSChris Mason 
4420459931ecSChris Mason 	/* write the data for the new item */
4421459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4422459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4423459931ecSChris Mason 			    item_size - split_offset);
4424459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4425459931ecSChris Mason 
4426e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
4427459931ecSChris Mason 	kfree(buf);
4428ad48fd75SYan, Zheng 	return 0;
4429ad48fd75SYan, Zheng }
4430ad48fd75SYan, Zheng 
4431ad48fd75SYan, Zheng /*
4432ad48fd75SYan, Zheng  * This function splits a single item into two items,
4433ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4434ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4435ad48fd75SYan, Zheng  *
4436ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4437ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4438ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4439ad48fd75SYan, Zheng  *
4440ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4441ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4442ad48fd75SYan, Zheng  *
4443ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4444ad48fd75SYan, Zheng  * leaf the entire time.
4445ad48fd75SYan, Zheng  */
4446ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4447ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4448ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4449310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
4450ad48fd75SYan, Zheng 		     unsigned long split_offset)
4451ad48fd75SYan, Zheng {
4452ad48fd75SYan, Zheng 	int ret;
4453ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4454ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4455ad48fd75SYan, Zheng 	if (ret)
4456459931ecSChris Mason 		return ret;
4457ad48fd75SYan, Zheng 
445825263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
4459ad48fd75SYan, Zheng 	return ret;
4460ad48fd75SYan, Zheng }
4461ad48fd75SYan, Zheng 
4462ad48fd75SYan, Zheng /*
4463ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4464ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4465ad48fd75SYan, Zheng  * is contiguous with the original item.
4466ad48fd75SYan, Zheng  *
4467ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4468ad48fd75SYan, Zheng  * leaf the entire time.
4469ad48fd75SYan, Zheng  */
4470ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4471ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4472ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4473310712b2SOmar Sandoval 			 const struct btrfs_key *new_key)
4474ad48fd75SYan, Zheng {
4475ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4476ad48fd75SYan, Zheng 	int ret;
4477ad48fd75SYan, Zheng 	u32 item_size;
4478ad48fd75SYan, Zheng 
4479ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4480ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4481ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4482ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4483ad48fd75SYan, Zheng 	if (ret)
4484ad48fd75SYan, Zheng 		return ret;
4485ad48fd75SYan, Zheng 
4486ad48fd75SYan, Zheng 	path->slots[0]++;
4487afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, new_key, &item_size,
4488ad48fd75SYan, Zheng 			       item_size, item_size +
4489ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4490ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4491ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4492ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4493ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4494ad48fd75SYan, Zheng 			     item_size);
4495ad48fd75SYan, Zheng 	return 0;
4496459931ecSChris Mason }
4497459931ecSChris Mason 
4498459931ecSChris Mason /*
4499d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4500d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4501d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4502d352ac68SChris Mason  * the front.
4503d352ac68SChris Mason  */
450478ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
4505b18c6685SChris Mason {
4506b18c6685SChris Mason 	int slot;
45075f39d397SChris Mason 	struct extent_buffer *leaf;
45085f39d397SChris Mason 	struct btrfs_item *item;
4509b18c6685SChris Mason 	u32 nritems;
4510b18c6685SChris Mason 	unsigned int data_end;
4511b18c6685SChris Mason 	unsigned int old_data_start;
4512b18c6685SChris Mason 	unsigned int old_size;
4513b18c6685SChris Mason 	unsigned int size_diff;
4514b18c6685SChris Mason 	int i;
4515cfed81a0SChris Mason 	struct btrfs_map_token token;
4516cfed81a0SChris Mason 
45175f39d397SChris Mason 	leaf = path->nodes[0];
4518179e29e4SChris Mason 	slot = path->slots[0];
4519179e29e4SChris Mason 
4520179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4521179e29e4SChris Mason 	if (old_size == new_size)
4522143bede5SJeff Mahoney 		return;
4523b18c6685SChris Mason 
45245f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
45258f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4526b18c6685SChris Mason 
45275f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4528179e29e4SChris Mason 
4529b18c6685SChris Mason 	size_diff = old_size - new_size;
4530b18c6685SChris Mason 
4531b18c6685SChris Mason 	BUG_ON(slot < 0);
4532b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4533b18c6685SChris Mason 
4534b18c6685SChris Mason 	/*
4535b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4536b18c6685SChris Mason 	 */
4537b18c6685SChris Mason 	/* first correct the data pointers */
4538c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4539b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
45405f39d397SChris Mason 		u32 ioff;
4541dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4542db94535dSChris Mason 
4543cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4544cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4545cfed81a0SChris Mason 					    ioff + size_diff, &token);
4546b18c6685SChris Mason 	}
4547db94535dSChris Mason 
4548b18c6685SChris Mason 	/* shift the data */
4549179e29e4SChris Mason 	if (from_end) {
45503d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
45513d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4552b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4553179e29e4SChris Mason 	} else {
4554179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4555179e29e4SChris Mason 		u64 offset;
4556179e29e4SChris Mason 
4557179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4558179e29e4SChris Mason 
4559179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4560179e29e4SChris Mason 			unsigned long ptr;
4561179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4562179e29e4SChris Mason 
4563179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4564179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4565179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4566179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4567179e29e4SChris Mason 
4568179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4569179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4570179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4571179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4572179e29e4SChris Mason 				      (unsigned long)fi,
45737ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4574179e29e4SChris Mason 			}
4575179e29e4SChris Mason 		}
4576179e29e4SChris Mason 
45773d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
45783d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4579179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4580179e29e4SChris Mason 
4581179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4582179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4583179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4584179e29e4SChris Mason 		if (slot == 0)
4585b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4586179e29e4SChris Mason 	}
45875f39d397SChris Mason 
4588dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
45895f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
45905f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4591b18c6685SChris Mason 
4592e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4593a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4594b18c6685SChris Mason 		BUG();
45955f39d397SChris Mason 	}
4596b18c6685SChris Mason }
4597b18c6685SChris Mason 
4598d352ac68SChris Mason /*
45998f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4600d352ac68SChris Mason  */
4601c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
46026567e837SChris Mason {
46036567e837SChris Mason 	int slot;
46045f39d397SChris Mason 	struct extent_buffer *leaf;
46055f39d397SChris Mason 	struct btrfs_item *item;
46066567e837SChris Mason 	u32 nritems;
46076567e837SChris Mason 	unsigned int data_end;
46086567e837SChris Mason 	unsigned int old_data;
46096567e837SChris Mason 	unsigned int old_size;
46106567e837SChris Mason 	int i;
4611cfed81a0SChris Mason 	struct btrfs_map_token token;
4612cfed81a0SChris Mason 
46135f39d397SChris Mason 	leaf = path->nodes[0];
46146567e837SChris Mason 
46155f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46168f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
46176567e837SChris Mason 
4618e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4619a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46206567e837SChris Mason 		BUG();
46215f39d397SChris Mason 	}
46226567e837SChris Mason 	slot = path->slots[0];
46235f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
46246567e837SChris Mason 
46256567e837SChris Mason 	BUG_ON(slot < 0);
46263326d1b0SChris Mason 	if (slot >= nritems) {
4627a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4628c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4629d397712bSChris Mason 			   slot, nritems);
4630290342f6SArnd Bergmann 		BUG();
46313326d1b0SChris Mason 	}
46326567e837SChris Mason 
46336567e837SChris Mason 	/*
46346567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
46356567e837SChris Mason 	 */
46366567e837SChris Mason 	/* first correct the data pointers */
4637c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
46386567e837SChris Mason 	for (i = slot; i < nritems; i++) {
46395f39d397SChris Mason 		u32 ioff;
4640dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4641db94535dSChris Mason 
4642cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4643cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4644cfed81a0SChris Mason 					    ioff - data_size, &token);
46456567e837SChris Mason 	}
46465f39d397SChris Mason 
46476567e837SChris Mason 	/* shift the data */
46483d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46493d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
46506567e837SChris Mason 		      data_end, old_data - data_end);
46515f39d397SChris Mason 
46526567e837SChris Mason 	data_end = old_data;
46535f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4654dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46555f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
46565f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
46576567e837SChris Mason 
4658e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4659a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46606567e837SChris Mason 		BUG();
46615f39d397SChris Mason 	}
46626567e837SChris Mason }
46636567e837SChris Mason 
466474123bd7SChris Mason /*
466544871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
466644871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
466744871b1bSChris Mason  * that doesn't call btrfs_search_slot
466874123bd7SChris Mason  */
4669afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4670310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
467144871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4672be0e5c09SChris Mason {
46730b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
46745f39d397SChris Mason 	struct btrfs_item *item;
46759c58309dSChris Mason 	int i;
46767518a238SChris Mason 	u32 nritems;
4677be0e5c09SChris Mason 	unsigned int data_end;
4678e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
467944871b1bSChris Mason 	struct extent_buffer *leaf;
468044871b1bSChris Mason 	int slot;
4681cfed81a0SChris Mason 	struct btrfs_map_token token;
4682cfed81a0SChris Mason 
468324cdc847SFilipe Manana 	if (path->slots[0] == 0) {
468424cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4685b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
468624cdc847SFilipe Manana 	}
468724cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
468824cdc847SFilipe Manana 
46895f39d397SChris Mason 	leaf = path->nodes[0];
469044871b1bSChris Mason 	slot = path->slots[0];
469174123bd7SChris Mason 
46925f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46938f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4694eb60ceacSChris Mason 
4695e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4696a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46970b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4698e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4699be0e5c09SChris Mason 		BUG();
4700d4dbff95SChris Mason 	}
47015f39d397SChris Mason 
4702c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4703be0e5c09SChris Mason 	if (slot != nritems) {
47045f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4705be0e5c09SChris Mason 
47065f39d397SChris Mason 		if (old_data < data_end) {
4707a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
47080b246afaSJeff Mahoney 			btrfs_crit(fs_info, "slot %d old_data %d data_end %d",
47095f39d397SChris Mason 				   slot, old_data, data_end);
4710290342f6SArnd Bergmann 			BUG();
47115f39d397SChris Mason 		}
4712be0e5c09SChris Mason 		/*
4713be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4714be0e5c09SChris Mason 		 */
4715be0e5c09SChris Mason 		/* first correct the data pointers */
47160783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
47175f39d397SChris Mason 			u32 ioff;
4718db94535dSChris Mason 
4719dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4720cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4721cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4722cfed81a0SChris Mason 						    ioff - total_data, &token);
47230783fcfcSChris Mason 		}
4724be0e5c09SChris Mason 		/* shift the items */
47259c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
47265f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
47270783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4728be0e5c09SChris Mason 
4729be0e5c09SChris Mason 		/* shift the data */
47303d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
47313d9ec8c4SNikolay Borisov 			      data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
4732be0e5c09SChris Mason 			      data_end, old_data - data_end);
4733be0e5c09SChris Mason 		data_end = old_data;
4734be0e5c09SChris Mason 	}
47355f39d397SChris Mason 
473662e2749eSChris Mason 	/* setup the item for the new data */
47379c58309dSChris Mason 	for (i = 0; i < nr; i++) {
47389c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
47399c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4740dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
4741cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4742cfed81a0SChris Mason 					    data_end - data_size[i], &token);
47439c58309dSChris Mason 		data_end -= data_size[i];
4744cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
47459c58309dSChris Mason 	}
474644871b1bSChris Mason 
47479c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4748b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4749aa5d6bedSChris Mason 
4750e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4751a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4752be0e5c09SChris Mason 		BUG();
47535f39d397SChris Mason 	}
475444871b1bSChris Mason }
475544871b1bSChris Mason 
475644871b1bSChris Mason /*
475744871b1bSChris Mason  * Given a key and some data, insert items into the tree.
475844871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
475944871b1bSChris Mason  */
476044871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
476144871b1bSChris Mason 			    struct btrfs_root *root,
476244871b1bSChris Mason 			    struct btrfs_path *path,
4763310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
476444871b1bSChris Mason 			    int nr)
476544871b1bSChris Mason {
476644871b1bSChris Mason 	int ret = 0;
476744871b1bSChris Mason 	int slot;
476844871b1bSChris Mason 	int i;
476944871b1bSChris Mason 	u32 total_size = 0;
477044871b1bSChris Mason 	u32 total_data = 0;
477144871b1bSChris Mason 
477244871b1bSChris Mason 	for (i = 0; i < nr; i++)
477344871b1bSChris Mason 		total_data += data_size[i];
477444871b1bSChris Mason 
477544871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
477644871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
477744871b1bSChris Mason 	if (ret == 0)
477844871b1bSChris Mason 		return -EEXIST;
477944871b1bSChris Mason 	if (ret < 0)
4780143bede5SJeff Mahoney 		return ret;
478144871b1bSChris Mason 
478244871b1bSChris Mason 	slot = path->slots[0];
478344871b1bSChris Mason 	BUG_ON(slot < 0);
478444871b1bSChris Mason 
4785afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, cpu_key, data_size,
478644871b1bSChris Mason 			       total_data, total_size, nr);
4787143bede5SJeff Mahoney 	return 0;
478862e2749eSChris Mason }
478962e2749eSChris Mason 
479062e2749eSChris Mason /*
479162e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
479262e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
479362e2749eSChris Mason  */
4794310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4795310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4796310712b2SOmar Sandoval 		      u32 data_size)
479762e2749eSChris Mason {
479862e2749eSChris Mason 	int ret = 0;
47992c90e5d6SChris Mason 	struct btrfs_path *path;
48005f39d397SChris Mason 	struct extent_buffer *leaf;
48015f39d397SChris Mason 	unsigned long ptr;
480262e2749eSChris Mason 
48032c90e5d6SChris Mason 	path = btrfs_alloc_path();
4804db5b493aSTsutomu Itoh 	if (!path)
4805db5b493aSTsutomu Itoh 		return -ENOMEM;
48062c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
480762e2749eSChris Mason 	if (!ret) {
48085f39d397SChris Mason 		leaf = path->nodes[0];
48095f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
48105f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
48115f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
481262e2749eSChris Mason 	}
48132c90e5d6SChris Mason 	btrfs_free_path(path);
4814aa5d6bedSChris Mason 	return ret;
4815be0e5c09SChris Mason }
4816be0e5c09SChris Mason 
481774123bd7SChris Mason /*
48185de08d7dSChris Mason  * delete the pointer from a given node.
481974123bd7SChris Mason  *
4820d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4821d352ac68SChris Mason  * empty a node.
482274123bd7SChris Mason  */
4823afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4824afe5fea7STsutomu Itoh 		    int level, int slot)
4825be0e5c09SChris Mason {
48265f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
48277518a238SChris Mason 	u32 nritems;
4828f3ea38daSJan Schmidt 	int ret;
4829be0e5c09SChris Mason 
48305f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4831be0e5c09SChris Mason 	if (slot != nritems - 1) {
4832bf1d3425SDavid Sterba 		if (level) {
4833bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(parent, slot, slot + 1,
4834a446a979SDavid Sterba 					nritems - slot - 1);
4835bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4836bf1d3425SDavid Sterba 		}
48375f39d397SChris Mason 		memmove_extent_buffer(parent,
48385f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
48395f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4840d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4841d6025579SChris Mason 			      (nritems - slot - 1));
484257ba86c0SChris Mason 	} else if (level) {
4843e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4844e09c2efeSDavid Sterba 				GFP_NOFS);
484557ba86c0SChris Mason 		BUG_ON(ret < 0);
4846be0e5c09SChris Mason 	}
4847f3ea38daSJan Schmidt 
48487518a238SChris Mason 	nritems--;
48495f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
48507518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
48515f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4852eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
48535f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4854bb803951SChris Mason 	} else if (slot == 0) {
48555f39d397SChris Mason 		struct btrfs_disk_key disk_key;
48565f39d397SChris Mason 
48575f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4858b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4859be0e5c09SChris Mason 	}
4860d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4861be0e5c09SChris Mason }
4862be0e5c09SChris Mason 
486374123bd7SChris Mason /*
4864323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
48655d4f98a2SYan Zheng  * path->nodes[1].
4866323ac95bSChris Mason  *
4867323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4868323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4869323ac95bSChris Mason  *
4870323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4871323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4872323ac95bSChris Mason  */
4873143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4874323ac95bSChris Mason 				    struct btrfs_root *root,
48755d4f98a2SYan Zheng 				    struct btrfs_path *path,
48765d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4877323ac95bSChris Mason {
48785d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4879afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4880323ac95bSChris Mason 
48814d081c41SChris Mason 	/*
48824d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
48834d081c41SChris Mason 	 * aren't holding any locks when we call it
48844d081c41SChris Mason 	 */
48854d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
48864d081c41SChris Mason 
4887f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4888f0486c68SYan, Zheng 
488967439dadSDavid Sterba 	atomic_inc(&leaf->refs);
48905581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
48913083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4892323ac95bSChris Mason }
4893323ac95bSChris Mason /*
489474123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
489574123bd7SChris Mason  * the leaf, remove it from the tree
489674123bd7SChris Mason  */
489785e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
489885e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4899be0e5c09SChris Mason {
49000b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
49015f39d397SChris Mason 	struct extent_buffer *leaf;
49025f39d397SChris Mason 	struct btrfs_item *item;
4903ce0eac2aSAlexandru Moise 	u32 last_off;
4904ce0eac2aSAlexandru Moise 	u32 dsize = 0;
4905aa5d6bedSChris Mason 	int ret = 0;
4906aa5d6bedSChris Mason 	int wret;
490785e21bacSChris Mason 	int i;
49087518a238SChris Mason 	u32 nritems;
4909be0e5c09SChris Mason 
49105f39d397SChris Mason 	leaf = path->nodes[0];
491185e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
491285e21bacSChris Mason 
491385e21bacSChris Mason 	for (i = 0; i < nr; i++)
491485e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
491585e21bacSChris Mason 
49165f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4917be0e5c09SChris Mason 
491885e21bacSChris Mason 	if (slot + nr != nritems) {
49198f881e8cSDavid Sterba 		int data_end = leaf_data_end(leaf);
4920c82f823cSDavid Sterba 		struct btrfs_map_token token;
49215f39d397SChris Mason 
49223d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4923d6025579SChris Mason 			      data_end + dsize,
49243d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
492585e21bacSChris Mason 			      last_off - data_end);
49265f39d397SChris Mason 
4927c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
492885e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
49295f39d397SChris Mason 			u32 ioff;
4930db94535dSChris Mason 
4931dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4932cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4933cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4934cfed81a0SChris Mason 						    ioff + dsize, &token);
49350783fcfcSChris Mason 		}
4936db94535dSChris Mason 
49375f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
493885e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
49390783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
494085e21bacSChris Mason 			      (nritems - slot - nr));
4941be0e5c09SChris Mason 	}
494285e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
494385e21bacSChris Mason 	nritems -= nr;
49445f39d397SChris Mason 
494574123bd7SChris Mason 	/* delete the leaf if we've emptied it */
49467518a238SChris Mason 	if (nritems == 0) {
49475f39d397SChris Mason 		if (leaf == root->node) {
49485f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
49499a8dd150SChris Mason 		} else {
4950f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
49516a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4952143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
49539a8dd150SChris Mason 		}
4954be0e5c09SChris Mason 	} else {
49557518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4956aa5d6bedSChris Mason 		if (slot == 0) {
49575f39d397SChris Mason 			struct btrfs_disk_key disk_key;
49585f39d397SChris Mason 
49595f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4960b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4961aa5d6bedSChris Mason 		}
4962aa5d6bedSChris Mason 
496374123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
49640b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
4965be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4966be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4967be0e5c09SChris Mason 			 * for possible call to del_ptr below
4968be0e5c09SChris Mason 			 */
49694920c9acSChris Mason 			slot = path->slots[1];
497067439dadSDavid Sterba 			atomic_inc(&leaf->refs);
49715f39d397SChris Mason 
4972b9473439SChris Mason 			btrfs_set_path_blocking(path);
497399d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
497499d8f83cSChris Mason 					      1, (u32)-1);
497554aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4976aa5d6bedSChris Mason 				ret = wret;
49775f39d397SChris Mason 
49785f39d397SChris Mason 			if (path->nodes[0] == leaf &&
49795f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
498099d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
498199d8f83cSChris Mason 						       1, 1, 0);
498254aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4983aa5d6bedSChris Mason 					ret = wret;
4984aa5d6bedSChris Mason 			}
49855f39d397SChris Mason 
49865f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4987323ac95bSChris Mason 				path->slots[1] = slot;
4988143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
49895f39d397SChris Mason 				free_extent_buffer(leaf);
4990143bede5SJeff Mahoney 				ret = 0;
49915de08d7dSChris Mason 			} else {
4992925baeddSChris Mason 				/* if we're still in the path, make sure
4993925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4994925baeddSChris Mason 				 * push_leaf functions must have already
4995925baeddSChris Mason 				 * dirtied this buffer
4996925baeddSChris Mason 				 */
4997925baeddSChris Mason 				if (path->nodes[0] == leaf)
49985f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
49995f39d397SChris Mason 				free_extent_buffer(leaf);
5000be0e5c09SChris Mason 			}
5001d5719762SChris Mason 		} else {
50025f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
5003be0e5c09SChris Mason 		}
50049a8dd150SChris Mason 	}
5005aa5d6bedSChris Mason 	return ret;
50069a8dd150SChris Mason }
50079a8dd150SChris Mason 
500897571fd0SChris Mason /*
5009925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
50107bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
50117bb86316SChris Mason  * returns < 0 on io errors.
5012d352ac68SChris Mason  *
5013d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
5014d352ac68SChris Mason  * time you call it.
50157bb86316SChris Mason  */
501616e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
50177bb86316SChris Mason {
5018925baeddSChris Mason 	struct btrfs_key key;
5019925baeddSChris Mason 	struct btrfs_disk_key found_key;
5020925baeddSChris Mason 	int ret;
50217bb86316SChris Mason 
5022925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5023925baeddSChris Mason 
5024e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
5025925baeddSChris Mason 		key.offset--;
5026e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
5027925baeddSChris Mason 		key.type--;
5028e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5029e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
5030925baeddSChris Mason 		key.objectid--;
5031e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
5032e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5033e8b0d724SFilipe David Borba Manana 	} else {
50347bb86316SChris Mason 		return 1;
5035e8b0d724SFilipe David Borba Manana 	}
50367bb86316SChris Mason 
5037b3b4aa74SDavid Sterba 	btrfs_release_path(path);
5038925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5039925baeddSChris Mason 	if (ret < 0)
5040925baeddSChris Mason 		return ret;
5041925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
5042925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
5043337c6f68SFilipe Manana 	/*
5044337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
5045337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
5046337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
5047337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
5048337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
5049337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
5050337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
5051337c6f68SFilipe Manana 	 * the previous key we computed above.
5052337c6f68SFilipe Manana 	 */
5053337c6f68SFilipe Manana 	if (ret <= 0)
50547bb86316SChris Mason 		return 0;
5055925baeddSChris Mason 	return 1;
50567bb86316SChris Mason }
50577bb86316SChris Mason 
50583f157a2fSChris Mason /*
50593f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
5060de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
5061de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
50623f157a2fSChris Mason  *
50633f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
50643f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
50653f157a2fSChris Mason  * key and get a writable path.
50663f157a2fSChris Mason  *
50673f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
50683f157a2fSChris Mason  * of the tree.
50693f157a2fSChris Mason  *
5070d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
5071d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
5072d352ac68SChris Mason  * skipped over (without reading them).
5073d352ac68SChris Mason  *
50743f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
50753f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
50763f157a2fSChris Mason  */
50773f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5078de78b51aSEric Sandeen 			 struct btrfs_path *path,
50793f157a2fSChris Mason 			 u64 min_trans)
50803f157a2fSChris Mason {
50813f157a2fSChris Mason 	struct extent_buffer *cur;
50823f157a2fSChris Mason 	struct btrfs_key found_key;
50833f157a2fSChris Mason 	int slot;
50849652480bSYan 	int sret;
50853f157a2fSChris Mason 	u32 nritems;
50863f157a2fSChris Mason 	int level;
50873f157a2fSChris Mason 	int ret = 1;
5088f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
50893f157a2fSChris Mason 
5090f98de9b9SFilipe Manana 	path->keep_locks = 1;
50913f157a2fSChris Mason again:
5092bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
50933f157a2fSChris Mason 	level = btrfs_header_level(cur);
5094e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
50953f157a2fSChris Mason 	path->nodes[level] = cur;
5096bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
50973f157a2fSChris Mason 
50983f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
50993f157a2fSChris Mason 		ret = 1;
51003f157a2fSChris Mason 		goto out;
51013f157a2fSChris Mason 	}
51023f157a2fSChris Mason 	while (1) {
51033f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
51043f157a2fSChris Mason 		level = btrfs_header_level(cur);
5105a74b35ecSNikolay Borisov 		sret = btrfs_bin_search(cur, min_key, level, &slot);
5106cbca7d59SFilipe Manana 		if (sret < 0) {
5107cbca7d59SFilipe Manana 			ret = sret;
5108cbca7d59SFilipe Manana 			goto out;
5109cbca7d59SFilipe Manana 		}
51103f157a2fSChris Mason 
5111323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
5112323ac95bSChris Mason 		if (level == path->lowest_level) {
5113e02119d5SChris Mason 			if (slot >= nritems)
5114e02119d5SChris Mason 				goto find_next_key;
51153f157a2fSChris Mason 			ret = 0;
51163f157a2fSChris Mason 			path->slots[level] = slot;
51173f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
51183f157a2fSChris Mason 			goto out;
51193f157a2fSChris Mason 		}
51209652480bSYan 		if (sret && slot > 0)
51219652480bSYan 			slot--;
51223f157a2fSChris Mason 		/*
5123de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
5124de78b51aSEric Sandeen 		 * If it is too old, old, skip to the next one.
51253f157a2fSChris Mason 		 */
51263f157a2fSChris Mason 		while (slot < nritems) {
51273f157a2fSChris Mason 			u64 gen;
5128e02119d5SChris Mason 
51293f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
51303f157a2fSChris Mason 			if (gen < min_trans) {
51313f157a2fSChris Mason 				slot++;
51323f157a2fSChris Mason 				continue;
51333f157a2fSChris Mason 			}
51343f157a2fSChris Mason 			break;
51353f157a2fSChris Mason 		}
5136e02119d5SChris Mason find_next_key:
51373f157a2fSChris Mason 		/*
51383f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
51393f157a2fSChris Mason 		 * and find another one
51403f157a2fSChris Mason 		 */
51413f157a2fSChris Mason 		if (slot >= nritems) {
5142e02119d5SChris Mason 			path->slots[level] = slot;
5143b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
5144e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
5145de78b51aSEric Sandeen 						  min_trans);
5146e02119d5SChris Mason 			if (sret == 0) {
5147b3b4aa74SDavid Sterba 				btrfs_release_path(path);
51483f157a2fSChris Mason 				goto again;
51493f157a2fSChris Mason 			} else {
51503f157a2fSChris Mason 				goto out;
51513f157a2fSChris Mason 			}
51523f157a2fSChris Mason 		}
51533f157a2fSChris Mason 		/* save our key for returning back */
51543f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
51553f157a2fSChris Mason 		path->slots[level] = slot;
51563f157a2fSChris Mason 		if (level == path->lowest_level) {
51573f157a2fSChris Mason 			ret = 0;
51583f157a2fSChris Mason 			goto out;
51593f157a2fSChris Mason 		}
5160b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
51614b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
5162fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
5163fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
5164fb770ae4SLiu Bo 			goto out;
5165fb770ae4SLiu Bo 		}
51663f157a2fSChris Mason 
5167bd681513SChris Mason 		btrfs_tree_read_lock(cur);
5168b4ce94deSChris Mason 
5169bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
51703f157a2fSChris Mason 		path->nodes[level - 1] = cur;
5171f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
51723f157a2fSChris Mason 	}
51733f157a2fSChris Mason out:
5174f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
5175f98de9b9SFilipe Manana 	if (ret == 0) {
5176f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
5177b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
5178f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
5179f98de9b9SFilipe Manana 	}
51803f157a2fSChris Mason 	return ret;
51813f157a2fSChris Mason }
51823f157a2fSChris Mason 
51833f157a2fSChris Mason /*
51843f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
51853f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5186de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
51873f157a2fSChris Mason  *
51883f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
51893f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
51903f157a2fSChris Mason  *
51913f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
51923f157a2fSChris Mason  * calling this function.
51933f157a2fSChris Mason  */
5194e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5195de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5196e7a84565SChris Mason {
5197e7a84565SChris Mason 	int slot;
5198e7a84565SChris Mason 	struct extent_buffer *c;
5199e7a84565SChris Mason 
52006a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
5201e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5202e7a84565SChris Mason 		if (!path->nodes[level])
5203e7a84565SChris Mason 			return 1;
5204e7a84565SChris Mason 
5205e7a84565SChris Mason 		slot = path->slots[level] + 1;
5206e7a84565SChris Mason 		c = path->nodes[level];
52073f157a2fSChris Mason next:
5208e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
520933c66f43SYan Zheng 			int ret;
521033c66f43SYan Zheng 			int orig_lowest;
521133c66f43SYan Zheng 			struct btrfs_key cur_key;
521233c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
521333c66f43SYan Zheng 			    !path->nodes[level + 1])
5214e7a84565SChris Mason 				return 1;
521533c66f43SYan Zheng 
52166a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
521733c66f43SYan Zheng 				level++;
5218e7a84565SChris Mason 				continue;
5219e7a84565SChris Mason 			}
522033c66f43SYan Zheng 
522133c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
522233c66f43SYan Zheng 			if (level == 0)
522333c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
522433c66f43SYan Zheng 			else
522533c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
522633c66f43SYan Zheng 
522733c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5228b3b4aa74SDavid Sterba 			btrfs_release_path(path);
522933c66f43SYan Zheng 			path->lowest_level = level;
523033c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
523133c66f43SYan Zheng 						0, 0);
523233c66f43SYan Zheng 			path->lowest_level = orig_lowest;
523333c66f43SYan Zheng 			if (ret < 0)
523433c66f43SYan Zheng 				return ret;
523533c66f43SYan Zheng 
523633c66f43SYan Zheng 			c = path->nodes[level];
523733c66f43SYan Zheng 			slot = path->slots[level];
523833c66f43SYan Zheng 			if (ret == 0)
523933c66f43SYan Zheng 				slot++;
524033c66f43SYan Zheng 			goto next;
524133c66f43SYan Zheng 		}
524233c66f43SYan Zheng 
5243e7a84565SChris Mason 		if (level == 0)
5244e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
52453f157a2fSChris Mason 		else {
52463f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
52473f157a2fSChris Mason 
52483f157a2fSChris Mason 			if (gen < min_trans) {
52493f157a2fSChris Mason 				slot++;
52503f157a2fSChris Mason 				goto next;
52513f157a2fSChris Mason 			}
5252e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
52533f157a2fSChris Mason 		}
5254e7a84565SChris Mason 		return 0;
5255e7a84565SChris Mason 	}
5256e7a84565SChris Mason 	return 1;
5257e7a84565SChris Mason }
5258e7a84565SChris Mason 
52597bb86316SChris Mason /*
5260925baeddSChris Mason  * search the tree again to find a leaf with greater keys
52610f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
52620f70abe2SChris Mason  * returns < 0 on io errors.
526397571fd0SChris Mason  */
5264234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5265d97e63b6SChris Mason {
52663d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
52673d7806ecSJan Schmidt }
52683d7806ecSJan Schmidt 
52693d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
52703d7806ecSJan Schmidt 			u64 time_seq)
52713d7806ecSJan Schmidt {
5272d97e63b6SChris Mason 	int slot;
52738e73f275SChris Mason 	int level;
52745f39d397SChris Mason 	struct extent_buffer *c;
52758e73f275SChris Mason 	struct extent_buffer *next;
5276925baeddSChris Mason 	struct btrfs_key key;
5277925baeddSChris Mason 	u32 nritems;
5278925baeddSChris Mason 	int ret;
52798e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5280bd681513SChris Mason 	int next_rw_lock = 0;
5281925baeddSChris Mason 
5282925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5283d397712bSChris Mason 	if (nritems == 0)
5284925baeddSChris Mason 		return 1;
5285925baeddSChris Mason 
52868e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
52878e73f275SChris Mason again:
52888e73f275SChris Mason 	level = 1;
52898e73f275SChris Mason 	next = NULL;
5290bd681513SChris Mason 	next_rw_lock = 0;
5291b3b4aa74SDavid Sterba 	btrfs_release_path(path);
52928e73f275SChris Mason 
5293a2135011SChris Mason 	path->keep_locks = 1;
52948e73f275SChris Mason 	path->leave_spinning = 1;
52958e73f275SChris Mason 
52963d7806ecSJan Schmidt 	if (time_seq)
52973d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
52983d7806ecSJan Schmidt 	else
5299925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5300925baeddSChris Mason 	path->keep_locks = 0;
5301925baeddSChris Mason 
5302925baeddSChris Mason 	if (ret < 0)
5303925baeddSChris Mason 		return ret;
5304925baeddSChris Mason 
5305a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5306168fd7d2SChris Mason 	/*
5307168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5308168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5309168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5310168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5311168fd7d2SChris Mason 	 */
5312a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5313e457afecSYan Zheng 		if (ret == 0)
5314168fd7d2SChris Mason 			path->slots[0]++;
53158e73f275SChris Mason 		ret = 0;
5316925baeddSChris Mason 		goto done;
5317925baeddSChris Mason 	}
53180b43e04fSLiu Bo 	/*
53190b43e04fSLiu Bo 	 * So the above check misses one case:
53200b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
53210b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
53220b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
53230b43e04fSLiu Bo 	 *
53240b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
53250b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
53260b43e04fSLiu Bo 	 *
53270b43e04fSLiu Bo 	 * And a bit more explanation about this check,
53280b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
53290b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
53300b43e04fSLiu Bo 	 * bigger one.
53310b43e04fSLiu Bo 	 */
53320b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
53330b43e04fSLiu Bo 		ret = 0;
53340b43e04fSLiu Bo 		goto done;
53350b43e04fSLiu Bo 	}
5336d97e63b6SChris Mason 
5337234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
53388e73f275SChris Mason 		if (!path->nodes[level]) {
53398e73f275SChris Mason 			ret = 1;
53408e73f275SChris Mason 			goto done;
53418e73f275SChris Mason 		}
53425f39d397SChris Mason 
5343d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5344d97e63b6SChris Mason 		c = path->nodes[level];
53455f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5346d97e63b6SChris Mason 			level++;
53478e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
53488e73f275SChris Mason 				ret = 1;
53498e73f275SChris Mason 				goto done;
53508e73f275SChris Mason 			}
5351d97e63b6SChris Mason 			continue;
5352d97e63b6SChris Mason 		}
53535f39d397SChris Mason 
5354925baeddSChris Mason 		if (next) {
5355bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
53565f39d397SChris Mason 			free_extent_buffer(next);
5357925baeddSChris Mason 		}
53585f39d397SChris Mason 
53598e73f275SChris Mason 		next = c;
5360bd681513SChris Mason 		next_rw_lock = path->locks[level];
5361d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5362cda79c54SDavid Sterba 					    slot, &key);
53638e73f275SChris Mason 		if (ret == -EAGAIN)
53648e73f275SChris Mason 			goto again;
53655f39d397SChris Mason 
536676a05b35SChris Mason 		if (ret < 0) {
5367b3b4aa74SDavid Sterba 			btrfs_release_path(path);
536876a05b35SChris Mason 			goto done;
536976a05b35SChris Mason 		}
537076a05b35SChris Mason 
53715cd57b2cSChris Mason 		if (!path->skip_locking) {
5372bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5373d42244a0SJan Schmidt 			if (!ret && time_seq) {
5374d42244a0SJan Schmidt 				/*
5375d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5376d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5377d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5378d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5379d42244a0SJan Schmidt 				 * on our lock and cycle.
5380d42244a0SJan Schmidt 				 */
5381cf538830SJan Schmidt 				free_extent_buffer(next);
5382d42244a0SJan Schmidt 				btrfs_release_path(path);
5383d42244a0SJan Schmidt 				cond_resched();
5384d42244a0SJan Schmidt 				goto again;
5385d42244a0SJan Schmidt 			}
53868e73f275SChris Mason 			if (!ret) {
53878e73f275SChris Mason 				btrfs_set_path_blocking(path);
5388bd681513SChris Mason 				btrfs_tree_read_lock(next);
53898e73f275SChris Mason 			}
5390bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5391bd681513SChris Mason 		}
5392d97e63b6SChris Mason 		break;
5393d97e63b6SChris Mason 	}
5394d97e63b6SChris Mason 	path->slots[level] = slot;
5395d97e63b6SChris Mason 	while (1) {
5396d97e63b6SChris Mason 		level--;
5397d97e63b6SChris Mason 		c = path->nodes[level];
5398925baeddSChris Mason 		if (path->locks[level])
5399bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
54008e73f275SChris Mason 
54015f39d397SChris Mason 		free_extent_buffer(c);
5402d97e63b6SChris Mason 		path->nodes[level] = next;
5403d97e63b6SChris Mason 		path->slots[level] = 0;
5404a74a4b97SChris Mason 		if (!path->skip_locking)
5405bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5406d97e63b6SChris Mason 		if (!level)
5407d97e63b6SChris Mason 			break;
5408b4ce94deSChris Mason 
5409d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5410cda79c54SDavid Sterba 					    0, &key);
54118e73f275SChris Mason 		if (ret == -EAGAIN)
54128e73f275SChris Mason 			goto again;
54138e73f275SChris Mason 
541476a05b35SChris Mason 		if (ret < 0) {
5415b3b4aa74SDavid Sterba 			btrfs_release_path(path);
541676a05b35SChris Mason 			goto done;
541776a05b35SChris Mason 		}
541876a05b35SChris Mason 
54195cd57b2cSChris Mason 		if (!path->skip_locking) {
5420bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
54218e73f275SChris Mason 			if (!ret) {
54228e73f275SChris Mason 				btrfs_set_path_blocking(path);
5423bd681513SChris Mason 				btrfs_tree_read_lock(next);
54248e73f275SChris Mason 			}
5425bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5426bd681513SChris Mason 		}
5427d97e63b6SChris Mason 	}
54288e73f275SChris Mason 	ret = 0;
5429925baeddSChris Mason done:
5430f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
54318e73f275SChris Mason 	path->leave_spinning = old_spinning;
54328e73f275SChris Mason 	if (!old_spinning)
54338e73f275SChris Mason 		btrfs_set_path_blocking(path);
54348e73f275SChris Mason 
54358e73f275SChris Mason 	return ret;
5436d97e63b6SChris Mason }
54370b86a832SChris Mason 
54383f157a2fSChris Mason /*
54393f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
54403f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
54413f157a2fSChris Mason  *
54423f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
54433f157a2fSChris Mason  */
54440b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
54450b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
54460b86a832SChris Mason 			int type)
54470b86a832SChris Mason {
54480b86a832SChris Mason 	struct btrfs_key found_key;
54490b86a832SChris Mason 	struct extent_buffer *leaf;
5450e02119d5SChris Mason 	u32 nritems;
54510b86a832SChris Mason 	int ret;
54520b86a832SChris Mason 
54530b86a832SChris Mason 	while (1) {
54540b86a832SChris Mason 		if (path->slots[0] == 0) {
5455b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
54560b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
54570b86a832SChris Mason 			if (ret != 0)
54580b86a832SChris Mason 				return ret;
54590b86a832SChris Mason 		} else {
54600b86a832SChris Mason 			path->slots[0]--;
54610b86a832SChris Mason 		}
54620b86a832SChris Mason 		leaf = path->nodes[0];
5463e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5464e02119d5SChris Mason 		if (nritems == 0)
5465e02119d5SChris Mason 			return 1;
5466e02119d5SChris Mason 		if (path->slots[0] == nritems)
5467e02119d5SChris Mason 			path->slots[0]--;
5468e02119d5SChris Mason 
54690b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5470e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5471e02119d5SChris Mason 			break;
54720a4eefbbSYan Zheng 		if (found_key.type == type)
54730a4eefbbSYan Zheng 			return 0;
5474e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5475e02119d5SChris Mason 		    found_key.type < type)
5476e02119d5SChris Mason 			break;
54770b86a832SChris Mason 	}
54780b86a832SChris Mason 	return 1;
54790b86a832SChris Mason }
5480ade2e0b3SWang Shilong 
5481ade2e0b3SWang Shilong /*
5482ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5483ade2e0b3SWang Shilong  * min objecitd.
5484ade2e0b3SWang Shilong  *
5485ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5486ade2e0b3SWang Shilong  */
5487ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5488ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5489ade2e0b3SWang Shilong {
5490ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5491ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5492ade2e0b3SWang Shilong 	u32 nritems;
5493ade2e0b3SWang Shilong 	int ret;
5494ade2e0b3SWang Shilong 
5495ade2e0b3SWang Shilong 	while (1) {
5496ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5497ade2e0b3SWang Shilong 			btrfs_set_path_blocking(path);
5498ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5499ade2e0b3SWang Shilong 			if (ret != 0)
5500ade2e0b3SWang Shilong 				return ret;
5501ade2e0b3SWang Shilong 		} else {
5502ade2e0b3SWang Shilong 			path->slots[0]--;
5503ade2e0b3SWang Shilong 		}
5504ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5505ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5506ade2e0b3SWang Shilong 		if (nritems == 0)
5507ade2e0b3SWang Shilong 			return 1;
5508ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5509ade2e0b3SWang Shilong 			path->slots[0]--;
5510ade2e0b3SWang Shilong 
5511ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5512ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5513ade2e0b3SWang Shilong 			break;
5514ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5515ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5516ade2e0b3SWang Shilong 			return 0;
5517ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5518ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5519ade2e0b3SWang Shilong 			break;
5520ade2e0b3SWang Shilong 	}
5521ade2e0b3SWang Shilong 	return 1;
5522ade2e0b3SWang Shilong }
5523