xref: /openbmc/linux/fs/btrfs/ctree.c (revision f624d976081d371b3dea65935501d8d9f142d5df)
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;
35af024ed2SJohannes Thumshirn } btrfs_csums[] = {
36af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
37af024ed2SJohannes Thumshirn };
38af024ed2SJohannes Thumshirn 
39af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
40af024ed2SJohannes Thumshirn {
41af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
42af024ed2SJohannes Thumshirn 	/*
43af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
44af024ed2SJohannes Thumshirn 	 */
45af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
46af024ed2SJohannes Thumshirn }
47af024ed2SJohannes Thumshirn 
48af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
49af024ed2SJohannes Thumshirn {
50af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
51af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
52af024ed2SJohannes Thumshirn }
53af024ed2SJohannes Thumshirn 
542c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
552c90e5d6SChris Mason {
56e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
572c90e5d6SChris Mason }
582c90e5d6SChris Mason 
59b4ce94deSChris Mason /*
60b4ce94deSChris Mason  * set all locked nodes in the path to blocking locks.  This should
61b4ce94deSChris Mason  * be done before scheduling
62b4ce94deSChris Mason  */
63b4ce94deSChris Mason noinline void btrfs_set_path_blocking(struct btrfs_path *p)
64b4ce94deSChris Mason {
65b4ce94deSChris Mason 	int i;
66b4ce94deSChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
67bd681513SChris Mason 		if (!p->nodes[i] || !p->locks[i])
68bd681513SChris Mason 			continue;
69766ece54SDavid Sterba 		/*
70766ece54SDavid Sterba 		 * If we currently have a spinning reader or writer lock this
71766ece54SDavid Sterba 		 * will bump the count of blocking holders and drop the
72766ece54SDavid Sterba 		 * spinlock.
73766ece54SDavid Sterba 		 */
74766ece54SDavid Sterba 		if (p->locks[i] == BTRFS_READ_LOCK) {
75766ece54SDavid Sterba 			btrfs_set_lock_blocking_read(p->nodes[i]);
76bd681513SChris Mason 			p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
77766ece54SDavid Sterba 		} else if (p->locks[i] == BTRFS_WRITE_LOCK) {
78766ece54SDavid Sterba 			btrfs_set_lock_blocking_write(p->nodes[i]);
79bd681513SChris Mason 			p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
80b4ce94deSChris Mason 		}
81b4ce94deSChris Mason 	}
82766ece54SDavid Sterba }
83b4ce94deSChris Mason 
84d352ac68SChris Mason /* this also releases the path */
852c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
862c90e5d6SChris Mason {
87ff175d57SJesper Juhl 	if (!p)
88ff175d57SJesper Juhl 		return;
89b3b4aa74SDavid Sterba 	btrfs_release_path(p);
902c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
912c90e5d6SChris Mason }
922c90e5d6SChris Mason 
93d352ac68SChris Mason /*
94d352ac68SChris Mason  * path release drops references on the extent buffers in the path
95d352ac68SChris Mason  * and it drops any locks held by this path
96d352ac68SChris Mason  *
97d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
98d352ac68SChris Mason  */
99b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
100eb60ceacSChris Mason {
101eb60ceacSChris Mason 	int i;
102a2135011SChris Mason 
103234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1043f157a2fSChris Mason 		p->slots[i] = 0;
105eb60ceacSChris Mason 		if (!p->nodes[i])
106925baeddSChris Mason 			continue;
107925baeddSChris Mason 		if (p->locks[i]) {
108bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
109925baeddSChris Mason 			p->locks[i] = 0;
110925baeddSChris Mason 		}
1115f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1123f157a2fSChris Mason 		p->nodes[i] = NULL;
113eb60ceacSChris Mason 	}
114eb60ceacSChris Mason }
115eb60ceacSChris Mason 
116d352ac68SChris Mason /*
117d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
118d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
119d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
120d352ac68SChris Mason  * looping required.
121d352ac68SChris Mason  *
122d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
123d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
124d352ac68SChris Mason  * at any time because there are no locks held.
125d352ac68SChris Mason  */
126925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
127925baeddSChris Mason {
128925baeddSChris Mason 	struct extent_buffer *eb;
129240f62c8SChris Mason 
1303083ee2eSJosef Bacik 	while (1) {
131240f62c8SChris Mason 		rcu_read_lock();
132240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1333083ee2eSJosef Bacik 
1343083ee2eSJosef Bacik 		/*
1353083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
13601327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1373083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1383083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1393083ee2eSJosef Bacik 		 */
1403083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
141240f62c8SChris Mason 			rcu_read_unlock();
1423083ee2eSJosef Bacik 			break;
1433083ee2eSJosef Bacik 		}
1443083ee2eSJosef Bacik 		rcu_read_unlock();
1453083ee2eSJosef Bacik 		synchronize_rcu();
1463083ee2eSJosef Bacik 	}
147925baeddSChris Mason 	return eb;
148925baeddSChris Mason }
149925baeddSChris Mason 
150d352ac68SChris Mason /* loop around taking references on and locking the root node of the
151d352ac68SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
152d352ac68SChris Mason  * is returned, with a reference held.
153d352ac68SChris Mason  */
154925baeddSChris Mason struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
155925baeddSChris Mason {
156925baeddSChris Mason 	struct extent_buffer *eb;
157925baeddSChris Mason 
158925baeddSChris Mason 	while (1) {
159925baeddSChris Mason 		eb = btrfs_root_node(root);
160925baeddSChris Mason 		btrfs_tree_lock(eb);
161240f62c8SChris Mason 		if (eb == root->node)
162925baeddSChris Mason 			break;
163925baeddSChris Mason 		btrfs_tree_unlock(eb);
164925baeddSChris Mason 		free_extent_buffer(eb);
165925baeddSChris Mason 	}
166925baeddSChris Mason 	return eb;
167925baeddSChris Mason }
168925baeddSChris Mason 
169bd681513SChris Mason /* loop around taking references on and locking the root node of the
170bd681513SChris Mason  * tree until you end up with a lock on the root.  A locked buffer
171bd681513SChris Mason  * is returned, with a reference held.
172bd681513SChris Mason  */
17384f7d8e6SJosef Bacik struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
174bd681513SChris Mason {
175bd681513SChris Mason 	struct extent_buffer *eb;
176bd681513SChris Mason 
177bd681513SChris Mason 	while (1) {
178bd681513SChris Mason 		eb = btrfs_root_node(root);
179bd681513SChris Mason 		btrfs_tree_read_lock(eb);
180bd681513SChris Mason 		if (eb == root->node)
181bd681513SChris Mason 			break;
182bd681513SChris Mason 		btrfs_tree_read_unlock(eb);
183bd681513SChris Mason 		free_extent_buffer(eb);
184bd681513SChris Mason 	}
185bd681513SChris Mason 	return eb;
186bd681513SChris Mason }
187bd681513SChris Mason 
188d352ac68SChris Mason /* cowonly root (everything not a reference counted cow subvolume), just get
189d352ac68SChris Mason  * put onto a simple dirty list.  transaction.c walks this to make sure they
190d352ac68SChris Mason  * get properly updated on disk.
191d352ac68SChris Mason  */
1920b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1930b86a832SChris Mason {
1940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1950b246afaSJeff Mahoney 
196e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
197e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
198e7070be1SJosef Bacik 		return;
199e7070be1SJosef Bacik 
2000b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
201e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
202e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
2034fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
204e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
2050b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
206e7070be1SJosef Bacik 		else
207e7070be1SJosef Bacik 			list_move(&root->dirty_list,
2080b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
2090b86a832SChris Mason 	}
2100b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2110b86a832SChris Mason }
2120b86a832SChris Mason 
213d352ac68SChris Mason /*
214d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
215d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
216d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
217d352ac68SChris Mason  */
218be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
219be20aa9dSChris Mason 		      struct btrfs_root *root,
220be20aa9dSChris Mason 		      struct extent_buffer *buf,
221be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
222be20aa9dSChris Mason {
2230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
224be20aa9dSChris Mason 	struct extent_buffer *cow;
225be20aa9dSChris Mason 	int ret = 0;
226be20aa9dSChris Mason 	int level;
2275d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
228be20aa9dSChris Mason 
22927cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
2300b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
23127cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
23227cdeb70SMiao Xie 		trans->transid != root->last_trans);
233be20aa9dSChris Mason 
234be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2355d4f98a2SYan Zheng 	if (level == 0)
2365d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2375d4f98a2SYan Zheng 	else
2385d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
23931840ae1SZheng Yan 
2404d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
2414d75f8a9SDavid Sterba 			&disk_key, level, buf->start, 0);
2425d4f98a2SYan Zheng 	if (IS_ERR(cow))
243be20aa9dSChris Mason 		return PTR_ERR(cow);
244be20aa9dSChris Mason 
24558e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
246be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
247be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2485d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2495d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2505d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2515d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2525d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2535d4f98a2SYan Zheng 	else
254be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
255be20aa9dSChris Mason 
256de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2572b82032cSYan Zheng 
258be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2595d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
260e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2615d4f98a2SYan Zheng 	else
262e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
2634aec2b52SChris Mason 
264be20aa9dSChris Mason 	if (ret)
265be20aa9dSChris Mason 		return ret;
266be20aa9dSChris Mason 
267be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
268be20aa9dSChris Mason 	*cow_ret = cow;
269be20aa9dSChris Mason 	return 0;
270be20aa9dSChris Mason }
271be20aa9dSChris Mason 
272bd989ba3SJan Schmidt enum mod_log_op {
273bd989ba3SJan Schmidt 	MOD_LOG_KEY_REPLACE,
274bd989ba3SJan Schmidt 	MOD_LOG_KEY_ADD,
275bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE,
276bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_FREEING,
277bd989ba3SJan Schmidt 	MOD_LOG_KEY_REMOVE_WHILE_MOVING,
278bd989ba3SJan Schmidt 	MOD_LOG_MOVE_KEYS,
279bd989ba3SJan Schmidt 	MOD_LOG_ROOT_REPLACE,
280bd989ba3SJan Schmidt };
281bd989ba3SJan Schmidt 
282bd989ba3SJan Schmidt struct tree_mod_root {
283bd989ba3SJan Schmidt 	u64 logical;
284bd989ba3SJan Schmidt 	u8 level;
285bd989ba3SJan Schmidt };
286bd989ba3SJan Schmidt 
287bd989ba3SJan Schmidt struct tree_mod_elem {
288bd989ba3SJan Schmidt 	struct rb_node node;
289298cfd36SChandan Rajendra 	u64 logical;
290097b8a7cSJan Schmidt 	u64 seq;
291bd989ba3SJan Schmidt 	enum mod_log_op op;
292bd989ba3SJan Schmidt 
293bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
294bd989ba3SJan Schmidt 	int slot;
295bd989ba3SJan Schmidt 
296bd989ba3SJan Schmidt 	/* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
297bd989ba3SJan Schmidt 	u64 generation;
298bd989ba3SJan Schmidt 
299bd989ba3SJan Schmidt 	/* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
300bd989ba3SJan Schmidt 	struct btrfs_disk_key key;
301bd989ba3SJan Schmidt 	u64 blockptr;
302bd989ba3SJan Schmidt 
303bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_MOVE_KEYS */
304b6dfa35bSDavid Sterba 	struct {
305b6dfa35bSDavid Sterba 		int dst_slot;
306b6dfa35bSDavid Sterba 		int nr_items;
307b6dfa35bSDavid Sterba 	} move;
308bd989ba3SJan Schmidt 
309bd989ba3SJan Schmidt 	/* this is used for op == MOD_LOG_ROOT_REPLACE */
310bd989ba3SJan Schmidt 	struct tree_mod_root old_root;
311bd989ba3SJan Schmidt };
312bd989ba3SJan Schmidt 
313097b8a7cSJan Schmidt /*
314fcebe456SJosef Bacik  * Pull a new tree mod seq number for our operation.
315fc36ed7eSJan Schmidt  */
316fcebe456SJosef Bacik static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
317fc36ed7eSJan Schmidt {
318fc36ed7eSJan Schmidt 	return atomic64_inc_return(&fs_info->tree_mod_seq);
319fc36ed7eSJan Schmidt }
320fc36ed7eSJan Schmidt 
321fc36ed7eSJan Schmidt /*
322097b8a7cSJan Schmidt  * This adds a new blocker to the tree mod log's blocker list if the @elem
323097b8a7cSJan Schmidt  * passed does not already have a sequence number set. So when a caller expects
324097b8a7cSJan Schmidt  * to record tree modifications, it should ensure to set elem->seq to zero
325097b8a7cSJan Schmidt  * before calling btrfs_get_tree_mod_seq.
326097b8a7cSJan Schmidt  * Returns a fresh, unused tree log modification sequence number, even if no new
327097b8a7cSJan Schmidt  * blocker was added.
328097b8a7cSJan Schmidt  */
329097b8a7cSJan Schmidt u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
330bd989ba3SJan Schmidt 			   struct seq_list *elem)
331bd989ba3SJan Schmidt {
332b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
333bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
334097b8a7cSJan Schmidt 	if (!elem->seq) {
335fcebe456SJosef Bacik 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
336097b8a7cSJan Schmidt 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
337097b8a7cSJan Schmidt 	}
338bd989ba3SJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
339b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
340097b8a7cSJan Schmidt 
341fcebe456SJosef Bacik 	return elem->seq;
342bd989ba3SJan Schmidt }
343bd989ba3SJan Schmidt 
344bd989ba3SJan Schmidt void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
345bd989ba3SJan Schmidt 			    struct seq_list *elem)
346bd989ba3SJan Schmidt {
347bd989ba3SJan Schmidt 	struct rb_root *tm_root;
348bd989ba3SJan Schmidt 	struct rb_node *node;
349bd989ba3SJan Schmidt 	struct rb_node *next;
350bd989ba3SJan Schmidt 	struct seq_list *cur_elem;
351bd989ba3SJan Schmidt 	struct tree_mod_elem *tm;
352bd989ba3SJan Schmidt 	u64 min_seq = (u64)-1;
353bd989ba3SJan Schmidt 	u64 seq_putting = elem->seq;
354bd989ba3SJan Schmidt 
355bd989ba3SJan Schmidt 	if (!seq_putting)
356bd989ba3SJan Schmidt 		return;
357bd989ba3SJan Schmidt 
358bd989ba3SJan Schmidt 	spin_lock(&fs_info->tree_mod_seq_lock);
359bd989ba3SJan Schmidt 	list_del(&elem->list);
360097b8a7cSJan Schmidt 	elem->seq = 0;
361bd989ba3SJan Schmidt 
362bd989ba3SJan Schmidt 	list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
363097b8a7cSJan Schmidt 		if (cur_elem->seq < min_seq) {
364bd989ba3SJan Schmidt 			if (seq_putting > cur_elem->seq) {
365bd989ba3SJan Schmidt 				/*
366bd989ba3SJan Schmidt 				 * blocker with lower sequence number exists, we
367bd989ba3SJan Schmidt 				 * cannot remove anything from the log
368bd989ba3SJan Schmidt 				 */
369097b8a7cSJan Schmidt 				spin_unlock(&fs_info->tree_mod_seq_lock);
370097b8a7cSJan Schmidt 				return;
371bd989ba3SJan Schmidt 			}
372bd989ba3SJan Schmidt 			min_seq = cur_elem->seq;
373bd989ba3SJan Schmidt 		}
374bd989ba3SJan Schmidt 	}
375097b8a7cSJan Schmidt 	spin_unlock(&fs_info->tree_mod_seq_lock);
376097b8a7cSJan Schmidt 
377097b8a7cSJan Schmidt 	/*
378bd989ba3SJan Schmidt 	 * anything that's lower than the lowest existing (read: blocked)
379bd989ba3SJan Schmidt 	 * sequence number can be removed from the tree.
380bd989ba3SJan Schmidt 	 */
381b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
382bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
383bd989ba3SJan Schmidt 	for (node = rb_first(tm_root); node; node = next) {
384bd989ba3SJan Schmidt 		next = rb_next(node);
3856b4df8b6SGeliang Tang 		tm = rb_entry(node, struct tree_mod_elem, node);
386097b8a7cSJan Schmidt 		if (tm->seq > min_seq)
387bd989ba3SJan Schmidt 			continue;
388bd989ba3SJan Schmidt 		rb_erase(node, tm_root);
389bd989ba3SJan Schmidt 		kfree(tm);
390bd989ba3SJan Schmidt 	}
391b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
392bd989ba3SJan Schmidt }
393bd989ba3SJan Schmidt 
394bd989ba3SJan Schmidt /*
395bd989ba3SJan Schmidt  * key order of the log:
396298cfd36SChandan Rajendra  *       node/leaf start address -> sequence
397bd989ba3SJan Schmidt  *
398298cfd36SChandan Rajendra  * The 'start address' is the logical address of the *new* root node
399298cfd36SChandan Rajendra  * for root replace operations, or the logical address of the affected
400298cfd36SChandan Rajendra  * block for all other operations.
401bd989ba3SJan Schmidt  */
402bd989ba3SJan Schmidt static noinline int
403bd989ba3SJan Schmidt __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
404bd989ba3SJan Schmidt {
405bd989ba3SJan Schmidt 	struct rb_root *tm_root;
406bd989ba3SJan Schmidt 	struct rb_node **new;
407bd989ba3SJan Schmidt 	struct rb_node *parent = NULL;
408bd989ba3SJan Schmidt 	struct tree_mod_elem *cur;
409bd989ba3SJan Schmidt 
41073e82fe4SDavid Sterba 	lockdep_assert_held_write(&fs_info->tree_mod_log_lock);
41173e82fe4SDavid Sterba 
412fcebe456SJosef Bacik 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
413bd989ba3SJan Schmidt 
414bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
415bd989ba3SJan Schmidt 	new = &tm_root->rb_node;
416bd989ba3SJan Schmidt 	while (*new) {
4176b4df8b6SGeliang Tang 		cur = rb_entry(*new, struct tree_mod_elem, node);
418bd989ba3SJan Schmidt 		parent = *new;
419298cfd36SChandan Rajendra 		if (cur->logical < tm->logical)
420bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
421298cfd36SChandan Rajendra 		else if (cur->logical > tm->logical)
422bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
423097b8a7cSJan Schmidt 		else if (cur->seq < tm->seq)
424bd989ba3SJan Schmidt 			new = &((*new)->rb_left);
425097b8a7cSJan Schmidt 		else if (cur->seq > tm->seq)
426bd989ba3SJan Schmidt 			new = &((*new)->rb_right);
4275de865eeSFilipe David Borba Manana 		else
4285de865eeSFilipe David Borba Manana 			return -EEXIST;
429bd989ba3SJan Schmidt 	}
430bd989ba3SJan Schmidt 
431bd989ba3SJan Schmidt 	rb_link_node(&tm->node, parent, new);
432bd989ba3SJan Schmidt 	rb_insert_color(&tm->node, tm_root);
4335de865eeSFilipe David Borba Manana 	return 0;
434bd989ba3SJan Schmidt }
435bd989ba3SJan Schmidt 
436097b8a7cSJan Schmidt /*
437097b8a7cSJan Schmidt  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
438097b8a7cSJan Schmidt  * returns zero with the tree_mod_log_lock acquired. The caller must hold
439097b8a7cSJan Schmidt  * this until all tree mod log insertions are recorded in the rb tree and then
440b1a09f1eSDavid Sterba  * write unlock fs_info::tree_mod_log_lock.
441097b8a7cSJan Schmidt  */
442e9b7fd4dSJan Schmidt static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
443e9b7fd4dSJan Schmidt 				    struct extent_buffer *eb) {
444e9b7fd4dSJan Schmidt 	smp_mb();
445e9b7fd4dSJan Schmidt 	if (list_empty(&(fs_info)->tree_mod_seq_list))
446e9b7fd4dSJan Schmidt 		return 1;
447097b8a7cSJan Schmidt 	if (eb && btrfs_header_level(eb) == 0)
448e9b7fd4dSJan Schmidt 		return 1;
4495de865eeSFilipe David Borba Manana 
450b1a09f1eSDavid Sterba 	write_lock(&fs_info->tree_mod_log_lock);
4515de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list)) {
452b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
4535de865eeSFilipe David Borba Manana 		return 1;
4545de865eeSFilipe David Borba Manana 	}
4555de865eeSFilipe David Borba Manana 
456e9b7fd4dSJan Schmidt 	return 0;
457e9b7fd4dSJan Schmidt }
458e9b7fd4dSJan Schmidt 
4595de865eeSFilipe David Borba Manana /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
4605de865eeSFilipe David Borba Manana static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
4615de865eeSFilipe David Borba Manana 				    struct extent_buffer *eb)
4625de865eeSFilipe David Borba Manana {
4635de865eeSFilipe David Borba Manana 	smp_mb();
4645de865eeSFilipe David Borba Manana 	if (list_empty(&(fs_info)->tree_mod_seq_list))
4655de865eeSFilipe David Borba Manana 		return 0;
4665de865eeSFilipe David Borba Manana 	if (eb && btrfs_header_level(eb) == 0)
4675de865eeSFilipe David Borba Manana 		return 0;
4685de865eeSFilipe David Borba Manana 
4695de865eeSFilipe David Borba Manana 	return 1;
4705de865eeSFilipe David Borba Manana }
4715de865eeSFilipe David Borba Manana 
4725de865eeSFilipe David Borba Manana static struct tree_mod_elem *
4735de865eeSFilipe David Borba Manana alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
474bd989ba3SJan Schmidt 		    enum mod_log_op op, gfp_t flags)
475bd989ba3SJan Schmidt {
476097b8a7cSJan Schmidt 	struct tree_mod_elem *tm;
477bd989ba3SJan Schmidt 
478c8cc6341SJosef Bacik 	tm = kzalloc(sizeof(*tm), flags);
479c8cc6341SJosef Bacik 	if (!tm)
4805de865eeSFilipe David Borba Manana 		return NULL;
481bd989ba3SJan Schmidt 
482298cfd36SChandan Rajendra 	tm->logical = eb->start;
483bd989ba3SJan Schmidt 	if (op != MOD_LOG_KEY_ADD) {
484bd989ba3SJan Schmidt 		btrfs_node_key(eb, &tm->key, slot);
485bd989ba3SJan Schmidt 		tm->blockptr = btrfs_node_blockptr(eb, slot);
486bd989ba3SJan Schmidt 	}
487bd989ba3SJan Schmidt 	tm->op = op;
488bd989ba3SJan Schmidt 	tm->slot = slot;
489bd989ba3SJan Schmidt 	tm->generation = btrfs_node_ptr_generation(eb, slot);
4905de865eeSFilipe David Borba Manana 	RB_CLEAR_NODE(&tm->node);
491bd989ba3SJan Schmidt 
4925de865eeSFilipe David Borba Manana 	return tm;
493097b8a7cSJan Schmidt }
494097b8a7cSJan Schmidt 
495e09c2efeSDavid Sterba static noinline int tree_mod_log_insert_key(struct extent_buffer *eb, int slot,
496097b8a7cSJan Schmidt 		enum mod_log_op op, gfp_t flags)
497097b8a7cSJan Schmidt {
4985de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm;
4995de865eeSFilipe David Borba Manana 	int ret;
5005de865eeSFilipe David Borba Manana 
501e09c2efeSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
502097b8a7cSJan Schmidt 		return 0;
503097b8a7cSJan Schmidt 
5045de865eeSFilipe David Borba Manana 	tm = alloc_tree_mod_elem(eb, slot, op, flags);
5055de865eeSFilipe David Borba Manana 	if (!tm)
5065de865eeSFilipe David Borba Manana 		return -ENOMEM;
5075de865eeSFilipe David Borba Manana 
508e09c2efeSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb)) {
5095de865eeSFilipe David Borba Manana 		kfree(tm);
5105de865eeSFilipe David Borba Manana 		return 0;
5115de865eeSFilipe David Borba Manana 	}
5125de865eeSFilipe David Borba Manana 
513e09c2efeSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
514b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
5155de865eeSFilipe David Borba Manana 	if (ret)
5165de865eeSFilipe David Borba Manana 		kfree(tm);
5175de865eeSFilipe David Borba Manana 
5185de865eeSFilipe David Borba Manana 	return ret;
519097b8a7cSJan Schmidt }
520097b8a7cSJan Schmidt 
5216074d45fSDavid Sterba static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
5226074d45fSDavid Sterba 		int dst_slot, int src_slot, int nr_items)
523bd989ba3SJan Schmidt {
5245de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
5255de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
5265de865eeSFilipe David Borba Manana 	int ret = 0;
527bd989ba3SJan Schmidt 	int i;
5285de865eeSFilipe David Borba Manana 	int locked = 0;
529bd989ba3SJan Schmidt 
5306074d45fSDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, eb))
531f395694cSJan Schmidt 		return 0;
532bd989ba3SJan Schmidt 
533176ef8f5SDavid Sterba 	tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
5345de865eeSFilipe David Borba Manana 	if (!tm_list)
5355de865eeSFilipe David Borba Manana 		return -ENOMEM;
536bd989ba3SJan Schmidt 
537176ef8f5SDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
5385de865eeSFilipe David Borba Manana 	if (!tm) {
5395de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
5405de865eeSFilipe David Borba Manana 		goto free_tms;
5415de865eeSFilipe David Borba Manana 	}
542f395694cSJan Schmidt 
543298cfd36SChandan Rajendra 	tm->logical = eb->start;
544bd989ba3SJan Schmidt 	tm->slot = src_slot;
545bd989ba3SJan Schmidt 	tm->move.dst_slot = dst_slot;
546bd989ba3SJan Schmidt 	tm->move.nr_items = nr_items;
547bd989ba3SJan Schmidt 	tm->op = MOD_LOG_MOVE_KEYS;
548bd989ba3SJan Schmidt 
5495de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5505de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
551176ef8f5SDavid Sterba 		    MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
5525de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
5535de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
5545de865eeSFilipe David Borba Manana 			goto free_tms;
5555de865eeSFilipe David Borba Manana 		}
556bd989ba3SJan Schmidt 	}
557bd989ba3SJan Schmidt 
5586074d45fSDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
5595de865eeSFilipe David Borba Manana 		goto free_tms;
5605de865eeSFilipe David Borba Manana 	locked = 1;
5615de865eeSFilipe David Borba Manana 
5625de865eeSFilipe David Borba Manana 	/*
5635de865eeSFilipe David Borba Manana 	 * When we override something during the move, we log these removals.
5645de865eeSFilipe David Borba Manana 	 * This can only happen when we move towards the beginning of the
5655de865eeSFilipe David Borba Manana 	 * buffer, i.e. dst_slot < src_slot.
5665de865eeSFilipe David Borba Manana 	 */
5675de865eeSFilipe David Borba Manana 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
5686074d45fSDavid Sterba 		ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
5695de865eeSFilipe David Borba Manana 		if (ret)
5705de865eeSFilipe David Borba Manana 			goto free_tms;
5715de865eeSFilipe David Borba Manana 	}
5725de865eeSFilipe David Borba Manana 
5736074d45fSDavid Sterba 	ret = __tree_mod_log_insert(eb->fs_info, tm);
5745de865eeSFilipe David Borba Manana 	if (ret)
5755de865eeSFilipe David Borba Manana 		goto free_tms;
576b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
5775de865eeSFilipe David Borba Manana 	kfree(tm_list);
5785de865eeSFilipe David Borba Manana 
5795de865eeSFilipe David Borba Manana 	return 0;
5805de865eeSFilipe David Borba Manana free_tms:
5815de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
5825de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
5836074d45fSDavid Sterba 			rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
5845de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
5855de865eeSFilipe David Borba Manana 	}
5865de865eeSFilipe David Borba Manana 	if (locked)
587b1a09f1eSDavid Sterba 		write_unlock(&eb->fs_info->tree_mod_log_lock);
5885de865eeSFilipe David Borba Manana 	kfree(tm_list);
5895de865eeSFilipe David Borba Manana 	kfree(tm);
5905de865eeSFilipe David Borba Manana 
5915de865eeSFilipe David Borba Manana 	return ret;
5925de865eeSFilipe David Borba Manana }
5935de865eeSFilipe David Borba Manana 
5945de865eeSFilipe David Borba Manana static inline int
5955de865eeSFilipe David Borba Manana __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
5965de865eeSFilipe David Borba Manana 		       struct tree_mod_elem **tm_list,
5975de865eeSFilipe David Borba Manana 		       int nritems)
598097b8a7cSJan Schmidt {
5995de865eeSFilipe David Borba Manana 	int i, j;
600097b8a7cSJan Schmidt 	int ret;
601097b8a7cSJan Schmidt 
602097b8a7cSJan Schmidt 	for (i = nritems - 1; i >= 0; i--) {
6035de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list[i]);
6045de865eeSFilipe David Borba Manana 		if (ret) {
6055de865eeSFilipe David Borba Manana 			for (j = nritems - 1; j > i; j--)
6065de865eeSFilipe David Borba Manana 				rb_erase(&tm_list[j]->node,
6075de865eeSFilipe David Borba Manana 					 &fs_info->tree_mod_log);
6085de865eeSFilipe David Borba Manana 			return ret;
609097b8a7cSJan Schmidt 		}
610097b8a7cSJan Schmidt 	}
611097b8a7cSJan Schmidt 
6125de865eeSFilipe David Borba Manana 	return 0;
6135de865eeSFilipe David Borba Manana }
6145de865eeSFilipe David Borba Manana 
61595b757c1SDavid Sterba static noinline int tree_mod_log_insert_root(struct extent_buffer *old_root,
61695b757c1SDavid Sterba 			 struct extent_buffer *new_root, int log_removal)
617bd989ba3SJan Schmidt {
61895b757c1SDavid Sterba 	struct btrfs_fs_info *fs_info = old_root->fs_info;
6195de865eeSFilipe David Borba Manana 	struct tree_mod_elem *tm = NULL;
6205de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
6215de865eeSFilipe David Borba Manana 	int nritems = 0;
6225de865eeSFilipe David Borba Manana 	int ret = 0;
6235de865eeSFilipe David Borba Manana 	int i;
624bd989ba3SJan Schmidt 
6255de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
626097b8a7cSJan Schmidt 		return 0;
627097b8a7cSJan Schmidt 
6285de865eeSFilipe David Borba Manana 	if (log_removal && btrfs_header_level(old_root) > 0) {
6295de865eeSFilipe David Borba Manana 		nritems = btrfs_header_nritems(old_root);
63031e818feSDavid Sterba 		tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
631bcc8e07fSDavid Sterba 				  GFP_NOFS);
6325de865eeSFilipe David Borba Manana 		if (!tm_list) {
6335de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
6345de865eeSFilipe David Borba Manana 			goto free_tms;
6355de865eeSFilipe David Borba Manana 		}
6365de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++) {
6375de865eeSFilipe David Borba Manana 			tm_list[i] = alloc_tree_mod_elem(old_root, i,
638bcc8e07fSDavid Sterba 			    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
6395de865eeSFilipe David Borba Manana 			if (!tm_list[i]) {
6405de865eeSFilipe David Borba Manana 				ret = -ENOMEM;
6415de865eeSFilipe David Borba Manana 				goto free_tms;
6425de865eeSFilipe David Borba Manana 			}
6435de865eeSFilipe David Borba Manana 		}
6445de865eeSFilipe David Borba Manana 	}
645d9abbf1cSJan Schmidt 
646bcc8e07fSDavid Sterba 	tm = kzalloc(sizeof(*tm), GFP_NOFS);
6475de865eeSFilipe David Borba Manana 	if (!tm) {
6485de865eeSFilipe David Borba Manana 		ret = -ENOMEM;
6495de865eeSFilipe David Borba Manana 		goto free_tms;
6505de865eeSFilipe David Borba Manana 	}
651bd989ba3SJan Schmidt 
652298cfd36SChandan Rajendra 	tm->logical = new_root->start;
653bd989ba3SJan Schmidt 	tm->old_root.logical = old_root->start;
654bd989ba3SJan Schmidt 	tm->old_root.level = btrfs_header_level(old_root);
655bd989ba3SJan Schmidt 	tm->generation = btrfs_header_generation(old_root);
656bd989ba3SJan Schmidt 	tm->op = MOD_LOG_ROOT_REPLACE;
657bd989ba3SJan Schmidt 
6585de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
6595de865eeSFilipe David Borba Manana 		goto free_tms;
6605de865eeSFilipe David Borba Manana 
6615de865eeSFilipe David Borba Manana 	if (tm_list)
6625de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
6635de865eeSFilipe David Borba Manana 	if (!ret)
6645de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm);
6655de865eeSFilipe David Borba Manana 
666b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
6675de865eeSFilipe David Borba Manana 	if (ret)
6685de865eeSFilipe David Borba Manana 		goto free_tms;
6695de865eeSFilipe David Borba Manana 	kfree(tm_list);
6705de865eeSFilipe David Borba Manana 
6715de865eeSFilipe David Borba Manana 	return ret;
6725de865eeSFilipe David Borba Manana 
6735de865eeSFilipe David Borba Manana free_tms:
6745de865eeSFilipe David Borba Manana 	if (tm_list) {
6755de865eeSFilipe David Borba Manana 		for (i = 0; i < nritems; i++)
6765de865eeSFilipe David Borba Manana 			kfree(tm_list[i]);
6775de865eeSFilipe David Borba Manana 		kfree(tm_list);
6785de865eeSFilipe David Borba Manana 	}
6795de865eeSFilipe David Borba Manana 	kfree(tm);
6805de865eeSFilipe David Borba Manana 
6815de865eeSFilipe David Borba Manana 	return ret;
682bd989ba3SJan Schmidt }
683bd989ba3SJan Schmidt 
684bd989ba3SJan Schmidt static struct tree_mod_elem *
685bd989ba3SJan Schmidt __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
686bd989ba3SJan Schmidt 		      int smallest)
687bd989ba3SJan Schmidt {
688bd989ba3SJan Schmidt 	struct rb_root *tm_root;
689bd989ba3SJan Schmidt 	struct rb_node *node;
690bd989ba3SJan Schmidt 	struct tree_mod_elem *cur = NULL;
691bd989ba3SJan Schmidt 	struct tree_mod_elem *found = NULL;
692bd989ba3SJan Schmidt 
693b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
694bd989ba3SJan Schmidt 	tm_root = &fs_info->tree_mod_log;
695bd989ba3SJan Schmidt 	node = tm_root->rb_node;
696bd989ba3SJan Schmidt 	while (node) {
6976b4df8b6SGeliang Tang 		cur = rb_entry(node, struct tree_mod_elem, node);
698298cfd36SChandan Rajendra 		if (cur->logical < start) {
699bd989ba3SJan Schmidt 			node = node->rb_left;
700298cfd36SChandan Rajendra 		} else if (cur->logical > start) {
701bd989ba3SJan Schmidt 			node = node->rb_right;
702097b8a7cSJan Schmidt 		} else if (cur->seq < min_seq) {
703bd989ba3SJan Schmidt 			node = node->rb_left;
704bd989ba3SJan Schmidt 		} else if (!smallest) {
705bd989ba3SJan Schmidt 			/* we want the node with the highest seq */
706bd989ba3SJan Schmidt 			if (found)
707097b8a7cSJan Schmidt 				BUG_ON(found->seq > cur->seq);
708bd989ba3SJan Schmidt 			found = cur;
709bd989ba3SJan Schmidt 			node = node->rb_left;
710097b8a7cSJan Schmidt 		} else if (cur->seq > min_seq) {
711bd989ba3SJan Schmidt 			/* we want the node with the smallest seq */
712bd989ba3SJan Schmidt 			if (found)
713097b8a7cSJan Schmidt 				BUG_ON(found->seq < cur->seq);
714bd989ba3SJan Schmidt 			found = cur;
715bd989ba3SJan Schmidt 			node = node->rb_right;
716bd989ba3SJan Schmidt 		} else {
717bd989ba3SJan Schmidt 			found = cur;
718bd989ba3SJan Schmidt 			break;
719bd989ba3SJan Schmidt 		}
720bd989ba3SJan Schmidt 	}
721b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
722bd989ba3SJan Schmidt 
723bd989ba3SJan Schmidt 	return found;
724bd989ba3SJan Schmidt }
725bd989ba3SJan Schmidt 
726bd989ba3SJan Schmidt /*
727bd989ba3SJan Schmidt  * this returns the element from the log with the smallest time sequence
728bd989ba3SJan Schmidt  * value that's in the log (the oldest log item). any element with a time
729bd989ba3SJan Schmidt  * sequence lower than min_seq will be ignored.
730bd989ba3SJan Schmidt  */
731bd989ba3SJan Schmidt static struct tree_mod_elem *
732bd989ba3SJan Schmidt tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
733bd989ba3SJan Schmidt 			   u64 min_seq)
734bd989ba3SJan Schmidt {
735bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 1);
736bd989ba3SJan Schmidt }
737bd989ba3SJan Schmidt 
738bd989ba3SJan Schmidt /*
739bd989ba3SJan Schmidt  * this returns the element from the log with the largest time sequence
740bd989ba3SJan Schmidt  * value that's in the log (the most recent log item). any element with
741bd989ba3SJan Schmidt  * a time sequence lower than min_seq will be ignored.
742bd989ba3SJan Schmidt  */
743bd989ba3SJan Schmidt static struct tree_mod_elem *
744bd989ba3SJan Schmidt tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
745bd989ba3SJan Schmidt {
746bd989ba3SJan Schmidt 	return __tree_mod_log_search(fs_info, start, min_seq, 0);
747bd989ba3SJan Schmidt }
748bd989ba3SJan Schmidt 
749ed874f0dSDavid Sterba static noinline int tree_mod_log_eb_copy(struct extent_buffer *dst,
750bd989ba3SJan Schmidt 		     struct extent_buffer *src, unsigned long dst_offset,
75190f8d62eSJan Schmidt 		     unsigned long src_offset, int nr_items)
752bd989ba3SJan Schmidt {
753ed874f0dSDavid Sterba 	struct btrfs_fs_info *fs_info = dst->fs_info;
7545de865eeSFilipe David Borba Manana 	int ret = 0;
7555de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
7565de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list_add, **tm_list_rem;
757bd989ba3SJan Schmidt 	int i;
7585de865eeSFilipe David Borba Manana 	int locked = 0;
759bd989ba3SJan Schmidt 
7605de865eeSFilipe David Borba Manana 	if (!tree_mod_need_log(fs_info, NULL))
7615de865eeSFilipe David Borba Manana 		return 0;
762bd989ba3SJan Schmidt 
763c8cc6341SJosef Bacik 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
7645de865eeSFilipe David Borba Manana 		return 0;
7655de865eeSFilipe David Borba Manana 
76631e818feSDavid Sterba 	tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
7675de865eeSFilipe David Borba Manana 			  GFP_NOFS);
7685de865eeSFilipe David Borba Manana 	if (!tm_list)
7695de865eeSFilipe David Borba Manana 		return -ENOMEM;
7705de865eeSFilipe David Borba Manana 
7715de865eeSFilipe David Borba Manana 	tm_list_add = tm_list;
7725de865eeSFilipe David Borba Manana 	tm_list_rem = tm_list + nr_items;
7735de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items; i++) {
7745de865eeSFilipe David Borba Manana 		tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
7755de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE, GFP_NOFS);
7765de865eeSFilipe David Borba Manana 		if (!tm_list_rem[i]) {
7775de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7785de865eeSFilipe David Borba Manana 			goto free_tms;
7795de865eeSFilipe David Borba Manana 		}
7805de865eeSFilipe David Borba Manana 
7815de865eeSFilipe David Borba Manana 		tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
7825de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_ADD, GFP_NOFS);
7835de865eeSFilipe David Borba Manana 		if (!tm_list_add[i]) {
7845de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
7855de865eeSFilipe David Borba Manana 			goto free_tms;
7865de865eeSFilipe David Borba Manana 		}
7875de865eeSFilipe David Borba Manana 	}
7885de865eeSFilipe David Borba Manana 
7895de865eeSFilipe David Borba Manana 	if (tree_mod_dont_log(fs_info, NULL))
7905de865eeSFilipe David Borba Manana 		goto free_tms;
7915de865eeSFilipe David Borba Manana 	locked = 1;
792bd989ba3SJan Schmidt 
793bd989ba3SJan Schmidt 	for (i = 0; i < nr_items; i++) {
7945de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
7955de865eeSFilipe David Borba Manana 		if (ret)
7965de865eeSFilipe David Borba Manana 			goto free_tms;
7975de865eeSFilipe David Borba Manana 		ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
7985de865eeSFilipe David Borba Manana 		if (ret)
7995de865eeSFilipe David Borba Manana 			goto free_tms;
800bd989ba3SJan Schmidt 	}
8015de865eeSFilipe David Borba Manana 
802b1a09f1eSDavid Sterba 	write_unlock(&fs_info->tree_mod_log_lock);
8035de865eeSFilipe David Borba Manana 	kfree(tm_list);
8045de865eeSFilipe David Borba Manana 
8055de865eeSFilipe David Borba Manana 	return 0;
8065de865eeSFilipe David Borba Manana 
8075de865eeSFilipe David Borba Manana free_tms:
8085de865eeSFilipe David Borba Manana 	for (i = 0; i < nr_items * 2; i++) {
8095de865eeSFilipe David Borba Manana 		if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
8105de865eeSFilipe David Borba Manana 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
8115de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8125de865eeSFilipe David Borba Manana 	}
8135de865eeSFilipe David Borba Manana 	if (locked)
814b1a09f1eSDavid Sterba 		write_unlock(&fs_info->tree_mod_log_lock);
8155de865eeSFilipe David Borba Manana 	kfree(tm_list);
8165de865eeSFilipe David Borba Manana 
8175de865eeSFilipe David Borba Manana 	return ret;
818bd989ba3SJan Schmidt }
819bd989ba3SJan Schmidt 
820db7279a2SDavid Sterba static noinline int tree_mod_log_free_eb(struct extent_buffer *eb)
821bd989ba3SJan Schmidt {
8225de865eeSFilipe David Borba Manana 	struct tree_mod_elem **tm_list = NULL;
8235de865eeSFilipe David Borba Manana 	int nritems = 0;
8245de865eeSFilipe David Borba Manana 	int i;
8255de865eeSFilipe David Borba Manana 	int ret = 0;
8265de865eeSFilipe David Borba Manana 
8275de865eeSFilipe David Borba Manana 	if (btrfs_header_level(eb) == 0)
8285de865eeSFilipe David Borba Manana 		return 0;
8295de865eeSFilipe David Borba Manana 
830db7279a2SDavid Sterba 	if (!tree_mod_need_log(eb->fs_info, NULL))
8315de865eeSFilipe David Borba Manana 		return 0;
8325de865eeSFilipe David Borba Manana 
8335de865eeSFilipe David Borba Manana 	nritems = btrfs_header_nritems(eb);
83431e818feSDavid Sterba 	tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
8355de865eeSFilipe David Borba Manana 	if (!tm_list)
8365de865eeSFilipe David Borba Manana 		return -ENOMEM;
8375de865eeSFilipe David Borba Manana 
8385de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++) {
8395de865eeSFilipe David Borba Manana 		tm_list[i] = alloc_tree_mod_elem(eb, i,
8405de865eeSFilipe David Borba Manana 		    MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
8415de865eeSFilipe David Borba Manana 		if (!tm_list[i]) {
8425de865eeSFilipe David Borba Manana 			ret = -ENOMEM;
8435de865eeSFilipe David Borba Manana 			goto free_tms;
8445de865eeSFilipe David Borba Manana 		}
8455de865eeSFilipe David Borba Manana 	}
8465de865eeSFilipe David Borba Manana 
847db7279a2SDavid Sterba 	if (tree_mod_dont_log(eb->fs_info, eb))
8485de865eeSFilipe David Borba Manana 		goto free_tms;
8495de865eeSFilipe David Borba Manana 
850db7279a2SDavid Sterba 	ret = __tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
851b1a09f1eSDavid Sterba 	write_unlock(&eb->fs_info->tree_mod_log_lock);
8525de865eeSFilipe David Borba Manana 	if (ret)
8535de865eeSFilipe David Borba Manana 		goto free_tms;
8545de865eeSFilipe David Borba Manana 	kfree(tm_list);
8555de865eeSFilipe David Borba Manana 
8565de865eeSFilipe David Borba Manana 	return 0;
8575de865eeSFilipe David Borba Manana 
8585de865eeSFilipe David Borba Manana free_tms:
8595de865eeSFilipe David Borba Manana 	for (i = 0; i < nritems; i++)
8605de865eeSFilipe David Borba Manana 		kfree(tm_list[i]);
8615de865eeSFilipe David Borba Manana 	kfree(tm_list);
8625de865eeSFilipe David Borba Manana 
8635de865eeSFilipe David Borba Manana 	return ret;
864bd989ba3SJan Schmidt }
865bd989ba3SJan Schmidt 
866d352ac68SChris Mason /*
8675d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
8685d4f98a2SYan Zheng  */
8695d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
8705d4f98a2SYan Zheng 			      struct extent_buffer *buf)
8715d4f98a2SYan Zheng {
8725d4f98a2SYan Zheng 	/*
87301327610SNicholas D Steeves 	 * Tree blocks not in reference counted trees and tree roots
8745d4f98a2SYan Zheng 	 * are never shared. If a block was allocated after the last
8755d4f98a2SYan Zheng 	 * snapshot and the block was not allocated by tree relocation,
8765d4f98a2SYan Zheng 	 * we know the block is not shared.
8775d4f98a2SYan Zheng 	 */
87827cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
8795d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
8805d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
8815d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
8825d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
8835d4f98a2SYan Zheng 		return 1;
884a79865c6SNikolay Borisov 
8855d4f98a2SYan Zheng 	return 0;
8865d4f98a2SYan Zheng }
8875d4f98a2SYan Zheng 
8885d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
8895d4f98a2SYan Zheng 				       struct btrfs_root *root,
8905d4f98a2SYan Zheng 				       struct extent_buffer *buf,
891f0486c68SYan, Zheng 				       struct extent_buffer *cow,
892f0486c68SYan, Zheng 				       int *last_ref)
8935d4f98a2SYan Zheng {
8940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8955d4f98a2SYan Zheng 	u64 refs;
8965d4f98a2SYan Zheng 	u64 owner;
8975d4f98a2SYan Zheng 	u64 flags;
8985d4f98a2SYan Zheng 	u64 new_flags = 0;
8995d4f98a2SYan Zheng 	int ret;
9005d4f98a2SYan Zheng 
9015d4f98a2SYan Zheng 	/*
9025d4f98a2SYan Zheng 	 * Backrefs update rules:
9035d4f98a2SYan Zheng 	 *
9045d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
9055d4f98a2SYan Zheng 	 * allocated by tree relocation.
9065d4f98a2SYan Zheng 	 *
9075d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
9085d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
9095d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
9105d4f98a2SYan Zheng 	 *
9115d4f98a2SYan Zheng 	 * If a tree block is been relocating
9125d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
9135d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
9145d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
9155d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
9165d4f98a2SYan Zheng 	 */
9175d4f98a2SYan Zheng 
9185d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
9192ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
9203173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
9213173a18fSJosef Bacik 					       &refs, &flags);
922be1a5564SMark Fasheh 		if (ret)
923be1a5564SMark Fasheh 			return ret;
924e5df9573SMark Fasheh 		if (refs == 0) {
925e5df9573SMark Fasheh 			ret = -EROFS;
9260b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
927e5df9573SMark Fasheh 			return ret;
928e5df9573SMark Fasheh 		}
9295d4f98a2SYan Zheng 	} else {
9305d4f98a2SYan Zheng 		refs = 1;
9315d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
9325d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
9335d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9345d4f98a2SYan Zheng 		else
9355d4f98a2SYan Zheng 			flags = 0;
9365d4f98a2SYan Zheng 	}
9375d4f98a2SYan Zheng 
9385d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
9395d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
9405d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
9415d4f98a2SYan Zheng 
9425d4f98a2SYan Zheng 	if (refs > 1) {
9435d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
9445d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
9455d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
946e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
947692826b2SJeff Mahoney 			if (ret)
948692826b2SJeff Mahoney 				return ret;
9495d4f98a2SYan Zheng 
9505d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9515d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
952e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
953692826b2SJeff Mahoney 				if (ret)
954692826b2SJeff Mahoney 					return ret;
955e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
956692826b2SJeff Mahoney 				if (ret)
957692826b2SJeff Mahoney 					return ret;
9585d4f98a2SYan Zheng 			}
9595d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
9605d4f98a2SYan Zheng 		} else {
9615d4f98a2SYan Zheng 
9625d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9635d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
964e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9655d4f98a2SYan Zheng 			else
966e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
967692826b2SJeff Mahoney 			if (ret)
968692826b2SJeff Mahoney 				return ret;
9695d4f98a2SYan Zheng 		}
9705d4f98a2SYan Zheng 		if (new_flags != 0) {
971b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
972b1c79e09SJosef Bacik 
973f5c8daa5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans,
9745d4f98a2SYan Zheng 							  buf->start,
9755d4f98a2SYan Zheng 							  buf->len,
976b1c79e09SJosef Bacik 							  new_flags, level, 0);
977be1a5564SMark Fasheh 			if (ret)
978be1a5564SMark Fasheh 				return ret;
9795d4f98a2SYan Zheng 		}
9805d4f98a2SYan Zheng 	} else {
9815d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
9825d4f98a2SYan Zheng 			if (root->root_key.objectid ==
9835d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
984e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
9855d4f98a2SYan Zheng 			else
986e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
987692826b2SJeff Mahoney 			if (ret)
988692826b2SJeff Mahoney 				return ret;
989e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
990692826b2SJeff Mahoney 			if (ret)
991692826b2SJeff Mahoney 				return ret;
9925d4f98a2SYan Zheng 		}
9936a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
994f0486c68SYan, Zheng 		*last_ref = 1;
9955d4f98a2SYan Zheng 	}
9965d4f98a2SYan Zheng 	return 0;
9975d4f98a2SYan Zheng }
9985d4f98a2SYan Zheng 
999a6279470SFilipe Manana static struct extent_buffer *alloc_tree_block_no_bg_flush(
1000a6279470SFilipe Manana 					  struct btrfs_trans_handle *trans,
1001a6279470SFilipe Manana 					  struct btrfs_root *root,
1002a6279470SFilipe Manana 					  u64 parent_start,
1003a6279470SFilipe Manana 					  const struct btrfs_disk_key *disk_key,
1004a6279470SFilipe Manana 					  int level,
1005a6279470SFilipe Manana 					  u64 hint,
1006a6279470SFilipe Manana 					  u64 empty_size)
1007a6279470SFilipe Manana {
1008a6279470SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
1009a6279470SFilipe Manana 	struct extent_buffer *ret;
1010a6279470SFilipe Manana 
1011a6279470SFilipe Manana 	/*
1012a6279470SFilipe Manana 	 * If we are COWing a node/leaf from the extent, chunk, device or free
1013a6279470SFilipe Manana 	 * space trees, make sure that we do not finish block group creation of
1014a6279470SFilipe Manana 	 * pending block groups. We do this to avoid a deadlock.
1015a6279470SFilipe Manana 	 * COWing can result in allocation of a new chunk, and flushing pending
1016a6279470SFilipe Manana 	 * block groups (btrfs_create_pending_block_groups()) can be triggered
1017a6279470SFilipe Manana 	 * when finishing allocation of a new chunk. Creation of a pending block
1018a6279470SFilipe Manana 	 * group modifies the extent, chunk, device and free space trees,
1019a6279470SFilipe Manana 	 * therefore we could deadlock with ourselves since we are holding a
1020a6279470SFilipe Manana 	 * lock on an extent buffer that btrfs_create_pending_block_groups() may
1021a6279470SFilipe Manana 	 * try to COW later.
1022a6279470SFilipe Manana 	 * For similar reasons, we also need to delay flushing pending block
1023a6279470SFilipe Manana 	 * groups when splitting a leaf or node, from one of those trees, since
1024a6279470SFilipe Manana 	 * we are holding a write lock on it and its parent or when inserting a
1025a6279470SFilipe Manana 	 * new root node for one of those trees.
1026a6279470SFilipe Manana 	 */
1027a6279470SFilipe Manana 	if (root == fs_info->extent_root ||
1028a6279470SFilipe Manana 	    root == fs_info->chunk_root ||
1029a6279470SFilipe Manana 	    root == fs_info->dev_root ||
1030a6279470SFilipe Manana 	    root == fs_info->free_space_root)
1031a6279470SFilipe Manana 		trans->can_flush_pending_bgs = false;
1032a6279470SFilipe Manana 
1033a6279470SFilipe Manana 	ret = btrfs_alloc_tree_block(trans, root, parent_start,
1034a6279470SFilipe Manana 				     root->root_key.objectid, disk_key, level,
1035a6279470SFilipe Manana 				     hint, empty_size);
1036a6279470SFilipe Manana 	trans->can_flush_pending_bgs = true;
1037a6279470SFilipe Manana 
1038a6279470SFilipe Manana 	return ret;
1039a6279470SFilipe Manana }
1040a6279470SFilipe Manana 
10415d4f98a2SYan Zheng /*
1042d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
1043d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1044d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
1045d397712bSChris Mason  * dirty again.
1046d352ac68SChris Mason  *
1047d352ac68SChris Mason  * search_start -- an allocation hint for the new block
1048d352ac68SChris Mason  *
1049d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1050d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
1051d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
1052d352ac68SChris Mason  */
1053d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
10545f39d397SChris Mason 			     struct btrfs_root *root,
10555f39d397SChris Mason 			     struct extent_buffer *buf,
10565f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
10575f39d397SChris Mason 			     struct extent_buffer **cow_ret,
10589fa8cfe7SChris Mason 			     u64 search_start, u64 empty_size)
10596702ed49SChris Mason {
10600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10615d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
10625f39d397SChris Mason 	struct extent_buffer *cow;
1063be1a5564SMark Fasheh 	int level, ret;
1064f0486c68SYan, Zheng 	int last_ref = 0;
1065925baeddSChris Mason 	int unlock_orig = 0;
10660f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
10676702ed49SChris Mason 
1068925baeddSChris Mason 	if (*cow_ret == buf)
1069925baeddSChris Mason 		unlock_orig = 1;
1070925baeddSChris Mason 
1071b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
1072925baeddSChris Mason 
107327cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
10740b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
107527cdeb70SMiao Xie 	WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
107627cdeb70SMiao Xie 		trans->transid != root->last_trans);
10775f39d397SChris Mason 
10787bb86316SChris Mason 	level = btrfs_header_level(buf);
107931840ae1SZheng Yan 
10805d4f98a2SYan Zheng 	if (level == 0)
10815d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
10825d4f98a2SYan Zheng 	else
10835d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
10845d4f98a2SYan Zheng 
10850f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
10865d4f98a2SYan Zheng 		parent_start = parent->start;
10875d4f98a2SYan Zheng 
1088a6279470SFilipe Manana 	cow = alloc_tree_block_no_bg_flush(trans, root, parent_start, &disk_key,
1089a6279470SFilipe Manana 					   level, search_start, empty_size);
10906702ed49SChris Mason 	if (IS_ERR(cow))
10916702ed49SChris Mason 		return PTR_ERR(cow);
10926702ed49SChris Mason 
1093b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
1094b4ce94deSChris Mason 
109558e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
1096db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
10975f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
10985d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
10995d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
11005d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
11015d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
11025d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
11035d4f98a2SYan Zheng 	else
11045f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
11056702ed49SChris Mason 
1106de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
11072b82032cSYan Zheng 
1108be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1109b68dc2a9SMark Fasheh 	if (ret) {
111066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
1111b68dc2a9SMark Fasheh 		return ret;
1112b68dc2a9SMark Fasheh 	}
11131a40e23bSZheng Yan 
111427cdeb70SMiao Xie 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
111583d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
111693314e3bSZhaolei 		if (ret) {
111766642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
111883d4cfd4SJosef Bacik 			return ret;
111983d4cfd4SJosef Bacik 		}
112093314e3bSZhaolei 	}
11213fd0a558SYan, Zheng 
11226702ed49SChris Mason 	if (buf == root->node) {
1123925baeddSChris Mason 		WARN_ON(parent && parent != buf);
11245d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
11255d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
11265d4f98a2SYan Zheng 			parent_start = buf->start;
1127925baeddSChris Mason 
11285f39d397SChris Mason 		extent_buffer_get(cow);
1129d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, cow, 1);
1130d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1131240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
1132925baeddSChris Mason 
1133f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11345581a51aSJan Schmidt 				      last_ref);
11355f39d397SChris Mason 		free_extent_buffer(buf);
11360b86a832SChris Mason 		add_root_to_dirty_list(root);
11376702ed49SChris Mason 	} else {
11385d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
1139e09c2efeSDavid Sterba 		tree_mod_log_insert_key(parent, parent_slot,
1140c8cc6341SJosef Bacik 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
11415f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
1142db94535dSChris Mason 					cow->start);
114374493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
114474493f7aSChris Mason 					      trans->transid);
11456702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
11465de865eeSFilipe David Borba Manana 		if (last_ref) {
1147db7279a2SDavid Sterba 			ret = tree_mod_log_free_eb(buf);
11485de865eeSFilipe David Borba Manana 			if (ret) {
114966642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
11505de865eeSFilipe David Borba Manana 				return ret;
11515de865eeSFilipe David Borba Manana 			}
11525de865eeSFilipe David Borba Manana 		}
1153f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
11545581a51aSJan Schmidt 				      last_ref);
11556702ed49SChris Mason 	}
1156925baeddSChris Mason 	if (unlock_orig)
1157925baeddSChris Mason 		btrfs_tree_unlock(buf);
11583083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
11596702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
11606702ed49SChris Mason 	*cow_ret = cow;
11616702ed49SChris Mason 	return 0;
11626702ed49SChris Mason }
11636702ed49SChris Mason 
11645d9e75c4SJan Schmidt /*
11655d9e75c4SJan Schmidt  * returns the logical address of the oldest predecessor of the given root.
11665d9e75c4SJan Schmidt  * entries older than time_seq are ignored.
11675d9e75c4SJan Schmidt  */
1168bcd24dabSDavid Sterba static struct tree_mod_elem *__tree_mod_log_oldest_root(
116930b0463aSJan Schmidt 		struct extent_buffer *eb_root, u64 time_seq)
11705d9e75c4SJan Schmidt {
11715d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
11725d9e75c4SJan Schmidt 	struct tree_mod_elem *found = NULL;
117330b0463aSJan Schmidt 	u64 root_logical = eb_root->start;
11745d9e75c4SJan Schmidt 	int looped = 0;
11755d9e75c4SJan Schmidt 
11765d9e75c4SJan Schmidt 	if (!time_seq)
117735a3621bSStefan Behrens 		return NULL;
11785d9e75c4SJan Schmidt 
11795d9e75c4SJan Schmidt 	/*
1180298cfd36SChandan Rajendra 	 * the very last operation that's logged for a root is the
1181298cfd36SChandan Rajendra 	 * replacement operation (if it is replaced at all). this has
1182298cfd36SChandan Rajendra 	 * the logical address of the *new* root, making it the very
1183298cfd36SChandan Rajendra 	 * first operation that's logged for this root.
11845d9e75c4SJan Schmidt 	 */
11855d9e75c4SJan Schmidt 	while (1) {
1186bcd24dabSDavid Sterba 		tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
11875d9e75c4SJan Schmidt 						time_seq);
11885d9e75c4SJan Schmidt 		if (!looped && !tm)
118935a3621bSStefan Behrens 			return NULL;
11905d9e75c4SJan Schmidt 		/*
119128da9fb4SJan Schmidt 		 * if there are no tree operation for the oldest root, we simply
119228da9fb4SJan Schmidt 		 * return it. this should only happen if that (old) root is at
119328da9fb4SJan Schmidt 		 * level 0.
11945d9e75c4SJan Schmidt 		 */
119528da9fb4SJan Schmidt 		if (!tm)
119628da9fb4SJan Schmidt 			break;
11975d9e75c4SJan Schmidt 
119828da9fb4SJan Schmidt 		/*
119928da9fb4SJan Schmidt 		 * if there's an operation that's not a root replacement, we
120028da9fb4SJan Schmidt 		 * found the oldest version of our root. normally, we'll find a
120128da9fb4SJan Schmidt 		 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
120228da9fb4SJan Schmidt 		 */
12035d9e75c4SJan Schmidt 		if (tm->op != MOD_LOG_ROOT_REPLACE)
12045d9e75c4SJan Schmidt 			break;
12055d9e75c4SJan Schmidt 
12065d9e75c4SJan Schmidt 		found = tm;
12075d9e75c4SJan Schmidt 		root_logical = tm->old_root.logical;
12085d9e75c4SJan Schmidt 		looped = 1;
12095d9e75c4SJan Schmidt 	}
12105d9e75c4SJan Schmidt 
1211a95236d9SJan Schmidt 	/* if there's no old root to return, return what we found instead */
1212a95236d9SJan Schmidt 	if (!found)
1213a95236d9SJan Schmidt 		found = tm;
1214a95236d9SJan Schmidt 
12155d9e75c4SJan Schmidt 	return found;
12165d9e75c4SJan Schmidt }
12175d9e75c4SJan Schmidt 
12185d9e75c4SJan Schmidt /*
12195d9e75c4SJan Schmidt  * tm is a pointer to the first operation to rewind within eb. then, all
122001327610SNicholas D Steeves  * previous operations will be rewound (until we reach something older than
12215d9e75c4SJan Schmidt  * time_seq).
12225d9e75c4SJan Schmidt  */
12235d9e75c4SJan Schmidt static void
1224f1ca7e98SJosef Bacik __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1225f1ca7e98SJosef Bacik 		      u64 time_seq, struct tree_mod_elem *first_tm)
12265d9e75c4SJan Schmidt {
12275d9e75c4SJan Schmidt 	u32 n;
12285d9e75c4SJan Schmidt 	struct rb_node *next;
12295d9e75c4SJan Schmidt 	struct tree_mod_elem *tm = first_tm;
12305d9e75c4SJan Schmidt 	unsigned long o_dst;
12315d9e75c4SJan Schmidt 	unsigned long o_src;
12325d9e75c4SJan Schmidt 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
12335d9e75c4SJan Schmidt 
12345d9e75c4SJan Schmidt 	n = btrfs_header_nritems(eb);
1235b1a09f1eSDavid Sterba 	read_lock(&fs_info->tree_mod_log_lock);
1236097b8a7cSJan Schmidt 	while (tm && tm->seq >= time_seq) {
12375d9e75c4SJan Schmidt 		/*
12385d9e75c4SJan Schmidt 		 * all the operations are recorded with the operator used for
12395d9e75c4SJan Schmidt 		 * the modification. as we're going backwards, we do the
12405d9e75c4SJan Schmidt 		 * opposite of each operation here.
12415d9e75c4SJan Schmidt 		 */
12425d9e75c4SJan Schmidt 		switch (tm->op) {
12435d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
12445d9e75c4SJan Schmidt 			BUG_ON(tm->slot < n);
12451c697d4aSEric Sandeen 			/* Fallthrough */
124695c80bb1SLiu Bo 		case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
12474c3e6969SChris Mason 		case MOD_LOG_KEY_REMOVE:
12485d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12495d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12505d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12515d9e75c4SJan Schmidt 						      tm->generation);
12524c3e6969SChris Mason 			n++;
12535d9e75c4SJan Schmidt 			break;
12545d9e75c4SJan Schmidt 		case MOD_LOG_KEY_REPLACE:
12555d9e75c4SJan Schmidt 			BUG_ON(tm->slot >= n);
12565d9e75c4SJan Schmidt 			btrfs_set_node_key(eb, &tm->key, tm->slot);
12575d9e75c4SJan Schmidt 			btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
12585d9e75c4SJan Schmidt 			btrfs_set_node_ptr_generation(eb, tm->slot,
12595d9e75c4SJan Schmidt 						      tm->generation);
12605d9e75c4SJan Schmidt 			break;
12615d9e75c4SJan Schmidt 		case MOD_LOG_KEY_ADD:
126219956c7eSJan Schmidt 			/* if a move operation is needed it's in the log */
12635d9e75c4SJan Schmidt 			n--;
12645d9e75c4SJan Schmidt 			break;
12655d9e75c4SJan Schmidt 		case MOD_LOG_MOVE_KEYS:
1266c3193108SJan Schmidt 			o_dst = btrfs_node_key_ptr_offset(tm->slot);
1267c3193108SJan Schmidt 			o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1268c3193108SJan Schmidt 			memmove_extent_buffer(eb, o_dst, o_src,
12695d9e75c4SJan Schmidt 					      tm->move.nr_items * p_size);
12705d9e75c4SJan Schmidt 			break;
12715d9e75c4SJan Schmidt 		case MOD_LOG_ROOT_REPLACE:
12725d9e75c4SJan Schmidt 			/*
12735d9e75c4SJan Schmidt 			 * this operation is special. for roots, this must be
12745d9e75c4SJan Schmidt 			 * handled explicitly before rewinding.
12755d9e75c4SJan Schmidt 			 * for non-roots, this operation may exist if the node
12765d9e75c4SJan Schmidt 			 * was a root: root A -> child B; then A gets empty and
12775d9e75c4SJan Schmidt 			 * B is promoted to the new root. in the mod log, we'll
12785d9e75c4SJan Schmidt 			 * have a root-replace operation for B, a tree block
12795d9e75c4SJan Schmidt 			 * that is no root. we simply ignore that operation.
12805d9e75c4SJan Schmidt 			 */
12815d9e75c4SJan Schmidt 			break;
12825d9e75c4SJan Schmidt 		}
12835d9e75c4SJan Schmidt 		next = rb_next(&tm->node);
12845d9e75c4SJan Schmidt 		if (!next)
12855d9e75c4SJan Schmidt 			break;
12866b4df8b6SGeliang Tang 		tm = rb_entry(next, struct tree_mod_elem, node);
1287298cfd36SChandan Rajendra 		if (tm->logical != first_tm->logical)
12885d9e75c4SJan Schmidt 			break;
12895d9e75c4SJan Schmidt 	}
1290b1a09f1eSDavid Sterba 	read_unlock(&fs_info->tree_mod_log_lock);
12915d9e75c4SJan Schmidt 	btrfs_set_header_nritems(eb, n);
12925d9e75c4SJan Schmidt }
12935d9e75c4SJan Schmidt 
129447fb091fSJan Schmidt /*
129501327610SNicholas D Steeves  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
129647fb091fSJan Schmidt  * is returned. If rewind operations happen, a fresh buffer is returned. The
129747fb091fSJan Schmidt  * returned buffer is always read-locked. If the returned buffer is not the
129847fb091fSJan Schmidt  * input buffer, the lock on the input buffer is released and the input buffer
129947fb091fSJan Schmidt  * is freed (its refcount is decremented).
130047fb091fSJan Schmidt  */
13015d9e75c4SJan Schmidt static struct extent_buffer *
13029ec72677SJosef Bacik tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
13039ec72677SJosef Bacik 		    struct extent_buffer *eb, u64 time_seq)
13045d9e75c4SJan Schmidt {
13055d9e75c4SJan Schmidt 	struct extent_buffer *eb_rewin;
13065d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
13075d9e75c4SJan Schmidt 
13085d9e75c4SJan Schmidt 	if (!time_seq)
13095d9e75c4SJan Schmidt 		return eb;
13105d9e75c4SJan Schmidt 
13115d9e75c4SJan Schmidt 	if (btrfs_header_level(eb) == 0)
13125d9e75c4SJan Schmidt 		return eb;
13135d9e75c4SJan Schmidt 
13145d9e75c4SJan Schmidt 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
13155d9e75c4SJan Schmidt 	if (!tm)
13165d9e75c4SJan Schmidt 		return eb;
13175d9e75c4SJan Schmidt 
13189ec72677SJosef Bacik 	btrfs_set_path_blocking(path);
1319300aa896SDavid Sterba 	btrfs_set_lock_blocking_read(eb);
13209ec72677SJosef Bacik 
13215d9e75c4SJan Schmidt 	if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
13225d9e75c4SJan Schmidt 		BUG_ON(tm->slot != 0);
1323da17066cSJeff Mahoney 		eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1324db7f3436SJosef Bacik 		if (!eb_rewin) {
13259ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1326db7f3436SJosef Bacik 			free_extent_buffer(eb);
1327db7f3436SJosef Bacik 			return NULL;
1328db7f3436SJosef Bacik 		}
13295d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb_rewin, eb->start);
13305d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb_rewin,
13315d9e75c4SJan Schmidt 					     btrfs_header_backref_rev(eb));
13325d9e75c4SJan Schmidt 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1333c3193108SJan Schmidt 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
13345d9e75c4SJan Schmidt 	} else {
13355d9e75c4SJan Schmidt 		eb_rewin = btrfs_clone_extent_buffer(eb);
1336db7f3436SJosef Bacik 		if (!eb_rewin) {
13379ec72677SJosef Bacik 			btrfs_tree_read_unlock_blocking(eb);
1338db7f3436SJosef Bacik 			free_extent_buffer(eb);
1339db7f3436SJosef Bacik 			return NULL;
1340db7f3436SJosef Bacik 		}
13415d9e75c4SJan Schmidt 	}
13425d9e75c4SJan Schmidt 
13439ec72677SJosef Bacik 	btrfs_tree_read_unlock_blocking(eb);
13445d9e75c4SJan Schmidt 	free_extent_buffer(eb);
13455d9e75c4SJan Schmidt 
134647fb091fSJan Schmidt 	btrfs_tree_read_lock(eb_rewin);
1347f1ca7e98SJosef Bacik 	__tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
134857911b8bSJan Schmidt 	WARN_ON(btrfs_header_nritems(eb_rewin) >
1349da17066cSJeff Mahoney 		BTRFS_NODEPTRS_PER_BLOCK(fs_info));
13505d9e75c4SJan Schmidt 
13515d9e75c4SJan Schmidt 	return eb_rewin;
13525d9e75c4SJan Schmidt }
13535d9e75c4SJan Schmidt 
13548ba97a15SJan Schmidt /*
13558ba97a15SJan Schmidt  * get_old_root() rewinds the state of @root's root node to the given @time_seq
13568ba97a15SJan Schmidt  * value. If there are no changes, the current root->root_node is returned. If
13578ba97a15SJan Schmidt  * anything changed in between, there's a fresh buffer allocated on which the
13588ba97a15SJan Schmidt  * rewind operations are done. In any case, the returned buffer is read locked.
13598ba97a15SJan Schmidt  * Returns NULL on error (with no locks held).
13608ba97a15SJan Schmidt  */
13615d9e75c4SJan Schmidt static inline struct extent_buffer *
13625d9e75c4SJan Schmidt get_old_root(struct btrfs_root *root, u64 time_seq)
13635d9e75c4SJan Schmidt {
13640b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13655d9e75c4SJan Schmidt 	struct tree_mod_elem *tm;
136630b0463aSJan Schmidt 	struct extent_buffer *eb = NULL;
136730b0463aSJan Schmidt 	struct extent_buffer *eb_root;
1368efad8a85SFilipe Manana 	u64 eb_root_owner = 0;
13697bfdcf7fSLiu Bo 	struct extent_buffer *old;
1370a95236d9SJan Schmidt 	struct tree_mod_root *old_root = NULL;
13714325edd0SChris Mason 	u64 old_generation = 0;
1372a95236d9SJan Schmidt 	u64 logical;
1373581c1760SQu Wenruo 	int level;
13745d9e75c4SJan Schmidt 
137530b0463aSJan Schmidt 	eb_root = btrfs_read_lock_root_node(root);
1376bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
13775d9e75c4SJan Schmidt 	if (!tm)
137830b0463aSJan Schmidt 		return eb_root;
13795d9e75c4SJan Schmidt 
1380a95236d9SJan Schmidt 	if (tm->op == MOD_LOG_ROOT_REPLACE) {
13815d9e75c4SJan Schmidt 		old_root = &tm->old_root;
13825d9e75c4SJan Schmidt 		old_generation = tm->generation;
1383a95236d9SJan Schmidt 		logical = old_root->logical;
1384581c1760SQu Wenruo 		level = old_root->level;
1385a95236d9SJan Schmidt 	} else {
138630b0463aSJan Schmidt 		logical = eb_root->start;
1387581c1760SQu Wenruo 		level = btrfs_header_level(eb_root);
1388a95236d9SJan Schmidt 	}
13895d9e75c4SJan Schmidt 
13900b246afaSJeff Mahoney 	tm = tree_mod_log_search(fs_info, logical, time_seq);
1391834328a8SJan Schmidt 	if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
139230b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
139330b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1394581c1760SQu Wenruo 		old = read_tree_block(fs_info, logical, 0, level, NULL);
139564c043deSLiu Bo 		if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
139664c043deSLiu Bo 			if (!IS_ERR(old))
1397416bc658SJosef Bacik 				free_extent_buffer(old);
13980b246afaSJeff Mahoney 			btrfs_warn(fs_info,
13990b246afaSJeff Mahoney 				   "failed to read tree block %llu from get_old_root",
14000b246afaSJeff Mahoney 				   logical);
1401834328a8SJan Schmidt 		} else {
14027bfdcf7fSLiu Bo 			eb = btrfs_clone_extent_buffer(old);
14037bfdcf7fSLiu Bo 			free_extent_buffer(old);
1404834328a8SJan Schmidt 		}
1405834328a8SJan Schmidt 	} else if (old_root) {
1406efad8a85SFilipe Manana 		eb_root_owner = btrfs_header_owner(eb_root);
140730b0463aSJan Schmidt 		btrfs_tree_read_unlock(eb_root);
140830b0463aSJan Schmidt 		free_extent_buffer(eb_root);
14090b246afaSJeff Mahoney 		eb = alloc_dummy_extent_buffer(fs_info, logical);
1410834328a8SJan Schmidt 	} else {
1411300aa896SDavid Sterba 		btrfs_set_lock_blocking_read(eb_root);
141230b0463aSJan Schmidt 		eb = btrfs_clone_extent_buffer(eb_root);
14139ec72677SJosef Bacik 		btrfs_tree_read_unlock_blocking(eb_root);
141430b0463aSJan Schmidt 		free_extent_buffer(eb_root);
1415834328a8SJan Schmidt 	}
1416834328a8SJan Schmidt 
14178ba97a15SJan Schmidt 	if (!eb)
14188ba97a15SJan Schmidt 		return NULL;
14198ba97a15SJan Schmidt 	btrfs_tree_read_lock(eb);
1420a95236d9SJan Schmidt 	if (old_root) {
14215d9e75c4SJan Schmidt 		btrfs_set_header_bytenr(eb, eb->start);
14225d9e75c4SJan Schmidt 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1423efad8a85SFilipe Manana 		btrfs_set_header_owner(eb, eb_root_owner);
14245d9e75c4SJan Schmidt 		btrfs_set_header_level(eb, old_root->level);
14255d9e75c4SJan Schmidt 		btrfs_set_header_generation(eb, old_generation);
1426a95236d9SJan Schmidt 	}
142728da9fb4SJan Schmidt 	if (tm)
14280b246afaSJeff Mahoney 		__tree_mod_log_rewind(fs_info, eb, time_seq, tm);
142928da9fb4SJan Schmidt 	else
143028da9fb4SJan Schmidt 		WARN_ON(btrfs_header_level(eb) != 0);
14310b246afaSJeff Mahoney 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
14325d9e75c4SJan Schmidt 
14335d9e75c4SJan Schmidt 	return eb;
14345d9e75c4SJan Schmidt }
14355d9e75c4SJan Schmidt 
14365b6602e7SJan Schmidt int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
14375b6602e7SJan Schmidt {
14385b6602e7SJan Schmidt 	struct tree_mod_elem *tm;
14395b6602e7SJan Schmidt 	int level;
144030b0463aSJan Schmidt 	struct extent_buffer *eb_root = btrfs_root_node(root);
14415b6602e7SJan Schmidt 
1442bcd24dabSDavid Sterba 	tm = __tree_mod_log_oldest_root(eb_root, time_seq);
14435b6602e7SJan Schmidt 	if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
14445b6602e7SJan Schmidt 		level = tm->old_root.level;
14455b6602e7SJan Schmidt 	} else {
144630b0463aSJan Schmidt 		level = btrfs_header_level(eb_root);
14475b6602e7SJan Schmidt 	}
144830b0463aSJan Schmidt 	free_extent_buffer(eb_root);
14495b6602e7SJan Schmidt 
14505b6602e7SJan Schmidt 	return level;
14515b6602e7SJan Schmidt }
14525b6602e7SJan Schmidt 
14535d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
14545d4f98a2SYan Zheng 				   struct btrfs_root *root,
14555d4f98a2SYan Zheng 				   struct extent_buffer *buf)
14565d4f98a2SYan Zheng {
1457f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
1458faa2dbf0SJosef Bacik 		return 0;
1459fccb84c9SDavid Sterba 
1460d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
1461d1980131SDavid Sterba 	smp_mb__before_atomic();
1462f1ebcc74SLiu Bo 
1463f1ebcc74SLiu Bo 	/*
1464f1ebcc74SLiu Bo 	 * We do not need to cow a block if
1465f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
1466f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
1467f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
1468f1ebcc74SLiu Bo 	 *
1469f1ebcc74SLiu Bo 	 * What is forced COW:
147001327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
147152042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
1472f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
1473f1ebcc74SLiu Bo 	 */
14745d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
14755d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
14765d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1477f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
147827cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
14795d4f98a2SYan Zheng 		return 0;
14805d4f98a2SYan Zheng 	return 1;
14815d4f98a2SYan Zheng }
14825d4f98a2SYan Zheng 
1483d352ac68SChris Mason /*
1484d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
148501327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
1486d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
1487d352ac68SChris Mason  */
1488d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
14895f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
14905f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
14919fa8cfe7SChris Mason 		    struct extent_buffer **cow_ret)
149202217ed2SChris Mason {
14930b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14946702ed49SChris Mason 	u64 search_start;
1495f510cfecSChris Mason 	int ret;
1496dc17ff8fSChris Mason 
149783354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
149883354f07SJosef Bacik 		btrfs_err(fs_info,
149983354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
150083354f07SJosef Bacik 
15010b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
150231b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
1503c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
15040b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
150531b1a2bdSJulia Lawall 
15060b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
150731b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
15080b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
1509dc17ff8fSChris Mason 
15105d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
151164c12921SJeff Mahoney 		trans->dirty = true;
151202217ed2SChris Mason 		*cow_ret = buf;
151302217ed2SChris Mason 		return 0;
151402217ed2SChris Mason 	}
1515c487685dSChris Mason 
1516ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
1517b4ce94deSChris Mason 
1518b4ce94deSChris Mason 	if (parent)
15198bead258SDavid Sterba 		btrfs_set_lock_blocking_write(parent);
15208bead258SDavid Sterba 	btrfs_set_lock_blocking_write(buf);
1521b4ce94deSChris Mason 
1522f616f5cdSQu Wenruo 	/*
1523f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
1524f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
1525f616f5cdSQu Wenruo 	 *
1526f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
1527f616f5cdSQu Wenruo 	 */
1528f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
1529f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
15309fa8cfe7SChris Mason 				 parent_slot, cow_ret, search_start, 0);
15311abe9b8aSliubo 
15321abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
15331abe9b8aSliubo 
1534f510cfecSChris Mason 	return ret;
15352c90e5d6SChris Mason }
15366702ed49SChris Mason 
1537d352ac68SChris Mason /*
1538d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
1539d352ac68SChris Mason  * node are actually close by
1540d352ac68SChris Mason  */
15416b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
15426702ed49SChris Mason {
15436b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
15446702ed49SChris Mason 		return 1;
15456b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
15466702ed49SChris Mason 		return 1;
154702217ed2SChris Mason 	return 0;
154802217ed2SChris Mason }
154902217ed2SChris Mason 
1550081e9573SChris Mason /*
1551081e9573SChris Mason  * compare two keys in a memcmp fashion
1552081e9573SChris Mason  */
1553310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
1554310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
1555081e9573SChris Mason {
1556081e9573SChris Mason 	struct btrfs_key k1;
1557081e9573SChris Mason 
1558081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
1559081e9573SChris Mason 
156020736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
1561081e9573SChris Mason }
1562081e9573SChris Mason 
1563f3465ca4SJosef Bacik /*
1564f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
1565f3465ca4SJosef Bacik  */
1566310712b2SOmar Sandoval int btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1567f3465ca4SJosef Bacik {
1568f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
1569f3465ca4SJosef Bacik 		return 1;
1570f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
1571f3465ca4SJosef Bacik 		return -1;
1572f3465ca4SJosef Bacik 	if (k1->type > k2->type)
1573f3465ca4SJosef Bacik 		return 1;
1574f3465ca4SJosef Bacik 	if (k1->type < k2->type)
1575f3465ca4SJosef Bacik 		return -1;
1576f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
1577f3465ca4SJosef Bacik 		return 1;
1578f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
1579f3465ca4SJosef Bacik 		return -1;
1580f3465ca4SJosef Bacik 	return 0;
1581f3465ca4SJosef Bacik }
1582081e9573SChris Mason 
1583d352ac68SChris Mason /*
1584d352ac68SChris Mason  * this is used by the defrag code to go through all the
1585d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
1586d352ac68SChris Mason  * disk order is close to key order
1587d352ac68SChris Mason  */
15886702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
15895f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
1590de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
1591a6b6e75eSChris Mason 		       struct btrfs_key *progress)
15926702ed49SChris Mason {
15930b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15946b80053dSChris Mason 	struct extent_buffer *cur;
15956702ed49SChris Mason 	u64 blocknr;
1596ca7a79adSChris Mason 	u64 gen;
1597e9d0b13bSChris Mason 	u64 search_start = *last_ret;
1598e9d0b13bSChris Mason 	u64 last_block = 0;
15996702ed49SChris Mason 	u64 other;
16006702ed49SChris Mason 	u32 parent_nritems;
16016702ed49SChris Mason 	int end_slot;
16026702ed49SChris Mason 	int i;
16036702ed49SChris Mason 	int err = 0;
1604f2183bdeSChris Mason 	int parent_level;
16056b80053dSChris Mason 	int uptodate;
16066b80053dSChris Mason 	u32 blocksize;
1607081e9573SChris Mason 	int progress_passed = 0;
1608081e9573SChris Mason 	struct btrfs_disk_key disk_key;
16096702ed49SChris Mason 
16105708b959SChris Mason 	parent_level = btrfs_header_level(parent);
16115708b959SChris Mason 
16120b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
16130b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
161486479a04SChris Mason 
16156b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
16160b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
16175dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
16186702ed49SChris Mason 
16195dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
16206702ed49SChris Mason 		return 0;
16216702ed49SChris Mason 
16228bead258SDavid Sterba 	btrfs_set_lock_blocking_write(parent);
1623b4ce94deSChris Mason 
16245dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
1625581c1760SQu Wenruo 		struct btrfs_key first_key;
16266702ed49SChris Mason 		int close = 1;
1627a6b6e75eSChris Mason 
1628081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
1629081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1630081e9573SChris Mason 			continue;
1631081e9573SChris Mason 
1632081e9573SChris Mason 		progress_passed = 1;
16336b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
1634ca7a79adSChris Mason 		gen = btrfs_node_ptr_generation(parent, i);
1635581c1760SQu Wenruo 		btrfs_node_key_to_cpu(parent, &first_key, i);
1636e9d0b13bSChris Mason 		if (last_block == 0)
1637e9d0b13bSChris Mason 			last_block = blocknr;
16385708b959SChris Mason 
16396702ed49SChris Mason 		if (i > 0) {
16406b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
16416b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16426702ed49SChris Mason 		}
16435dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
16446b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
16456b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
16466702ed49SChris Mason 		}
1647e9d0b13bSChris Mason 		if (close) {
1648e9d0b13bSChris Mason 			last_block = blocknr;
16496702ed49SChris Mason 			continue;
1650e9d0b13bSChris Mason 		}
16516702ed49SChris Mason 
16520b246afaSJeff Mahoney 		cur = find_extent_buffer(fs_info, blocknr);
16536b80053dSChris Mason 		if (cur)
1654b9fab919SChris Mason 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
16556b80053dSChris Mason 		else
16566b80053dSChris Mason 			uptodate = 0;
16575708b959SChris Mason 		if (!cur || !uptodate) {
16586b80053dSChris Mason 			if (!cur) {
1659581c1760SQu Wenruo 				cur = read_tree_block(fs_info, blocknr, gen,
1660581c1760SQu Wenruo 						      parent_level - 1,
1661581c1760SQu Wenruo 						      &first_key);
166264c043deSLiu Bo 				if (IS_ERR(cur)) {
166364c043deSLiu Bo 					return PTR_ERR(cur);
166464c043deSLiu Bo 				} else if (!extent_buffer_uptodate(cur)) {
1665416bc658SJosef Bacik 					free_extent_buffer(cur);
166697d9a8a4STsutomu Itoh 					return -EIO;
1667416bc658SJosef Bacik 				}
16686b80053dSChris Mason 			} else if (!uptodate) {
1669581c1760SQu Wenruo 				err = btrfs_read_buffer(cur, gen,
1670581c1760SQu Wenruo 						parent_level - 1,&first_key);
1671018642a1STsutomu Itoh 				if (err) {
1672018642a1STsutomu Itoh 					free_extent_buffer(cur);
1673018642a1STsutomu Itoh 					return err;
1674018642a1STsutomu Itoh 				}
16756702ed49SChris Mason 			}
1676f2183bdeSChris Mason 		}
1677e9d0b13bSChris Mason 		if (search_start == 0)
16786b80053dSChris Mason 			search_start = last_block;
1679e9d0b13bSChris Mason 
1680e7a84565SChris Mason 		btrfs_tree_lock(cur);
16818bead258SDavid Sterba 		btrfs_set_lock_blocking_write(cur);
16826b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
1683e7a84565SChris Mason 					&cur, search_start,
16846b80053dSChris Mason 					min(16 * blocksize,
16859fa8cfe7SChris Mason 					    (end_slot - i) * blocksize));
1686252c38f0SYan 		if (err) {
1687e7a84565SChris Mason 			btrfs_tree_unlock(cur);
16886b80053dSChris Mason 			free_extent_buffer(cur);
16896702ed49SChris Mason 			break;
1690252c38f0SYan 		}
1691e7a84565SChris Mason 		search_start = cur->start;
1692e7a84565SChris Mason 		last_block = cur->start;
1693f2183bdeSChris Mason 		*last_ret = search_start;
1694e7a84565SChris Mason 		btrfs_tree_unlock(cur);
1695e7a84565SChris Mason 		free_extent_buffer(cur);
16966702ed49SChris Mason 	}
16976702ed49SChris Mason 	return err;
16986702ed49SChris Mason }
16996702ed49SChris Mason 
170074123bd7SChris Mason /*
17015f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
17025f39d397SChris Mason  * and they are item_size apart.  There are 'max' items in p.
17035f39d397SChris Mason  *
170474123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
170574123bd7SChris Mason  * the place where you would insert key if it is not found in
170674123bd7SChris Mason  * the array.
170774123bd7SChris Mason  *
170874123bd7SChris Mason  * slot may point to max if the key is bigger than all of the keys
170974123bd7SChris Mason  */
1710e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
1711310712b2SOmar Sandoval 				       unsigned long p, int item_size,
1712310712b2SOmar Sandoval 				       const struct btrfs_key *key,
1713be0e5c09SChris Mason 				       int max, int *slot)
1714be0e5c09SChris Mason {
1715be0e5c09SChris Mason 	int low = 0;
1716be0e5c09SChris Mason 	int high = max;
1717be0e5c09SChris Mason 	int mid;
1718be0e5c09SChris Mason 	int ret;
1719479965d6SChris Mason 	struct btrfs_disk_key *tmp = NULL;
17205f39d397SChris Mason 	struct btrfs_disk_key unaligned;
17215f39d397SChris Mason 	unsigned long offset;
17225f39d397SChris Mason 	char *kaddr = NULL;
17235f39d397SChris Mason 	unsigned long map_start = 0;
17245f39d397SChris Mason 	unsigned long map_len = 0;
1725479965d6SChris Mason 	int err;
1726be0e5c09SChris Mason 
17275e24e9afSLiu Bo 	if (low > high) {
17285e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
17295e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
17305e24e9afSLiu Bo 			  __func__, low, high, eb->start,
17315e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
17325e24e9afSLiu Bo 		return -EINVAL;
17335e24e9afSLiu Bo 	}
17345e24e9afSLiu Bo 
1735be0e5c09SChris Mason 	while (low < high) {
1736be0e5c09SChris Mason 		mid = (low + high) / 2;
17375f39d397SChris Mason 		offset = p + mid * item_size;
17385f39d397SChris Mason 
1739a6591715SChris Mason 		if (!kaddr || offset < map_start ||
17405f39d397SChris Mason 		    (offset + sizeof(struct btrfs_disk_key)) >
17415f39d397SChris Mason 		    map_start + map_len) {
1742934d375bSChris Mason 
1743934d375bSChris Mason 			err = map_private_extent_buffer(eb, offset,
1744479965d6SChris Mason 						sizeof(struct btrfs_disk_key),
1745a6591715SChris Mason 						&kaddr, &map_start, &map_len);
17465f39d397SChris Mason 
1747479965d6SChris Mason 			if (!err) {
1748479965d6SChris Mason 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
1749479965d6SChris Mason 							map_start);
1750415b35a5SLiu Bo 			} else if (err == 1) {
17515f39d397SChris Mason 				read_extent_buffer(eb, &unaligned,
17525f39d397SChris Mason 						   offset, sizeof(unaligned));
17535f39d397SChris Mason 				tmp = &unaligned;
1754415b35a5SLiu Bo 			} else {
1755415b35a5SLiu Bo 				return err;
1756479965d6SChris Mason 			}
1757479965d6SChris Mason 
17585f39d397SChris Mason 		} else {
17595f39d397SChris Mason 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
17605f39d397SChris Mason 							map_start);
17615f39d397SChris Mason 		}
1762be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
1763be0e5c09SChris Mason 
1764be0e5c09SChris Mason 		if (ret < 0)
1765be0e5c09SChris Mason 			low = mid + 1;
1766be0e5c09SChris Mason 		else if (ret > 0)
1767be0e5c09SChris Mason 			high = mid;
1768be0e5c09SChris Mason 		else {
1769be0e5c09SChris Mason 			*slot = mid;
1770be0e5c09SChris Mason 			return 0;
1771be0e5c09SChris Mason 		}
1772be0e5c09SChris Mason 	}
1773be0e5c09SChris Mason 	*slot = low;
1774be0e5c09SChris Mason 	return 1;
1775be0e5c09SChris Mason }
1776be0e5c09SChris Mason 
177797571fd0SChris Mason /*
177897571fd0SChris Mason  * simple bin_search frontend that does the right thing for
177997571fd0SChris Mason  * leaves vs nodes
178097571fd0SChris Mason  */
1781a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
17825f39d397SChris Mason 		     int level, int *slot)
1783be0e5c09SChris Mason {
1784f775738fSWang Sheng-Hui 	if (level == 0)
17855f39d397SChris Mason 		return generic_bin_search(eb,
17865f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
17870783fcfcSChris Mason 					  sizeof(struct btrfs_item),
17885f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17897518a238SChris Mason 					  slot);
1790f775738fSWang Sheng-Hui 	else
17915f39d397SChris Mason 		return generic_bin_search(eb,
17925f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
1793123abc88SChris Mason 					  sizeof(struct btrfs_key_ptr),
17945f39d397SChris Mason 					  key, btrfs_header_nritems(eb),
17957518a238SChris Mason 					  slot);
1796be0e5c09SChris Mason }
1797be0e5c09SChris Mason 
1798f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1799f0486c68SYan, Zheng {
1800f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1801f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1802f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1803f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1804f0486c68SYan, Zheng }
1805f0486c68SYan, Zheng 
1806f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1807f0486c68SYan, Zheng {
1808f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1809f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1810f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1811f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1812f0486c68SYan, Zheng }
1813f0486c68SYan, Zheng 
1814d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1815d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1816d352ac68SChris Mason  */
18174b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
18184b231ae4SDavid Sterba 					   int slot)
1819bb803951SChris Mason {
1820ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1821416bc658SJosef Bacik 	struct extent_buffer *eb;
1822581c1760SQu Wenruo 	struct btrfs_key first_key;
1823416bc658SJosef Bacik 
1824fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
1825fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
1826ca7a79adSChris Mason 
1827ca7a79adSChris Mason 	BUG_ON(level == 0);
1828ca7a79adSChris Mason 
1829581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
1830d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1831581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
1832581c1760SQu Wenruo 			     level - 1, &first_key);
1833fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1834416bc658SJosef Bacik 		free_extent_buffer(eb);
1835fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
1836416bc658SJosef Bacik 	}
1837416bc658SJosef Bacik 
1838416bc658SJosef Bacik 	return eb;
1839bb803951SChris Mason }
1840bb803951SChris Mason 
1841d352ac68SChris Mason /*
1842d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1843d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1844d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1845d352ac68SChris Mason  */
1846e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
184798ed5174SChris Mason 			 struct btrfs_root *root,
184898ed5174SChris Mason 			 struct btrfs_path *path, int level)
1849bb803951SChris Mason {
18500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
18515f39d397SChris Mason 	struct extent_buffer *right = NULL;
18525f39d397SChris Mason 	struct extent_buffer *mid;
18535f39d397SChris Mason 	struct extent_buffer *left = NULL;
18545f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1855bb803951SChris Mason 	int ret = 0;
1856bb803951SChris Mason 	int wret;
1857bb803951SChris Mason 	int pslot;
1858bb803951SChris Mason 	int orig_slot = path->slots[level];
185979f95c82SChris Mason 	u64 orig_ptr;
1860bb803951SChris Mason 
186198e6b1ebSLiu Bo 	ASSERT(level > 0);
1862bb803951SChris Mason 
18635f39d397SChris Mason 	mid = path->nodes[level];
1864b4ce94deSChris Mason 
1865bd681513SChris Mason 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1866bd681513SChris Mason 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
18677bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
18687bb86316SChris Mason 
18691d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
187079f95c82SChris Mason 
1871a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
18725f39d397SChris Mason 		parent = path->nodes[level + 1];
1873bb803951SChris Mason 		pslot = path->slots[level + 1];
1874a05a9bb1SLi Zefan 	}
1875bb803951SChris Mason 
187640689478SChris Mason 	/*
187740689478SChris Mason 	 * deal with the case where there is only one pointer in the root
187840689478SChris Mason 	 * by promoting the node below to a root
187940689478SChris Mason 	 */
18805f39d397SChris Mason 	if (!parent) {
18815f39d397SChris Mason 		struct extent_buffer *child;
1882bb803951SChris Mason 
18835f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1884bb803951SChris Mason 			return 0;
1885bb803951SChris Mason 
1886bb803951SChris Mason 		/* promote the child to a root */
18874b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1888fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1889fb770ae4SLiu Bo 			ret = PTR_ERR(child);
18900b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1891305a26afSMark Fasheh 			goto enospc;
1892305a26afSMark Fasheh 		}
1893305a26afSMark Fasheh 
1894925baeddSChris Mason 		btrfs_tree_lock(child);
18958bead258SDavid Sterba 		btrfs_set_lock_blocking_write(child);
18969fa8cfe7SChris Mason 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1897f0486c68SYan, Zheng 		if (ret) {
1898f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1899f0486c68SYan, Zheng 			free_extent_buffer(child);
1900f0486c68SYan, Zheng 			goto enospc;
1901f0486c68SYan, Zheng 		}
19022f375ab9SYan 
1903d9d19a01SDavid Sterba 		ret = tree_mod_log_insert_root(root->node, child, 1);
1904d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1905240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1906925baeddSChris Mason 
19070b86a832SChris Mason 		add_root_to_dirty_list(root);
1908925baeddSChris Mason 		btrfs_tree_unlock(child);
1909b4ce94deSChris Mason 
1910925baeddSChris Mason 		path->locks[level] = 0;
1911bb803951SChris Mason 		path->nodes[level] = NULL;
19126a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1913925baeddSChris Mason 		btrfs_tree_unlock(mid);
1914bb803951SChris Mason 		/* once for the path */
19155f39d397SChris Mason 		free_extent_buffer(mid);
1916f0486c68SYan, Zheng 
1917f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
19185581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
1919bb803951SChris Mason 		/* once for the root ptr */
19203083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1921f0486c68SYan, Zheng 		return 0;
1922bb803951SChris Mason 	}
19235f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
19240b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1925bb803951SChris Mason 		return 0;
1926bb803951SChris Mason 
19274b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1928fb770ae4SLiu Bo 	if (IS_ERR(left))
1929fb770ae4SLiu Bo 		left = NULL;
1930fb770ae4SLiu Bo 
19315f39d397SChris Mason 	if (left) {
1932925baeddSChris Mason 		btrfs_tree_lock(left);
19338bead258SDavid Sterba 		btrfs_set_lock_blocking_write(left);
19345f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
19359fa8cfe7SChris Mason 				       parent, pslot - 1, &left);
193654aa1f4dSChris Mason 		if (wret) {
193754aa1f4dSChris Mason 			ret = wret;
193854aa1f4dSChris Mason 			goto enospc;
193954aa1f4dSChris Mason 		}
19402cc58cf2SChris Mason 	}
1941fb770ae4SLiu Bo 
19424b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1943fb770ae4SLiu Bo 	if (IS_ERR(right))
1944fb770ae4SLiu Bo 		right = NULL;
1945fb770ae4SLiu Bo 
19465f39d397SChris Mason 	if (right) {
1947925baeddSChris Mason 		btrfs_tree_lock(right);
19488bead258SDavid Sterba 		btrfs_set_lock_blocking_write(right);
19495f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
19509fa8cfe7SChris Mason 				       parent, pslot + 1, &right);
19512cc58cf2SChris Mason 		if (wret) {
19522cc58cf2SChris Mason 			ret = wret;
19532cc58cf2SChris Mason 			goto enospc;
19542cc58cf2SChris Mason 		}
19552cc58cf2SChris Mason 	}
19562cc58cf2SChris Mason 
19572cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
19585f39d397SChris Mason 	if (left) {
19595f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1960d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
196179f95c82SChris Mason 		if (wret < 0)
196279f95c82SChris Mason 			ret = wret;
1963bb803951SChris Mason 	}
196479f95c82SChris Mason 
196579f95c82SChris Mason 	/*
196679f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
196779f95c82SChris Mason 	 */
19685f39d397SChris Mason 	if (right) {
1969d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
197054aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
197179f95c82SChris Mason 			ret = wret;
19725f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
19736a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1974925baeddSChris Mason 			btrfs_tree_unlock(right);
1975afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1976f0486c68SYan, Zheng 			root_sub_used(root, right->len);
19775581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
19783083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1979f0486c68SYan, Zheng 			right = NULL;
1980bb803951SChris Mason 		} else {
19815f39d397SChris Mason 			struct btrfs_disk_key right_key;
19825f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
19830e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
19840e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
19850e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
19865f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
19875f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1988bb803951SChris Mason 		}
1989bb803951SChris Mason 	}
19905f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
199179f95c82SChris Mason 		/*
199279f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
199379f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
199479f95c82SChris Mason 		 * could try to delete the only pointer in this node.
199579f95c82SChris Mason 		 * So, pull some keys from the left.
199679f95c82SChris Mason 		 * There has to be a left pointer at this point because
199779f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
199879f95c82SChris Mason 		 * right
199979f95c82SChris Mason 		 */
2000305a26afSMark Fasheh 		if (!left) {
2001305a26afSMark Fasheh 			ret = -EROFS;
20020b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
2003305a26afSMark Fasheh 			goto enospc;
2004305a26afSMark Fasheh 		}
200555d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
200654aa1f4dSChris Mason 		if (wret < 0) {
200779f95c82SChris Mason 			ret = wret;
200854aa1f4dSChris Mason 			goto enospc;
200954aa1f4dSChris Mason 		}
2010bce4eae9SChris Mason 		if (wret == 1) {
2011d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
2012bce4eae9SChris Mason 			if (wret < 0)
2013bce4eae9SChris Mason 				ret = wret;
2014bce4eae9SChris Mason 		}
201579f95c82SChris Mason 		BUG_ON(wret == 1);
201679f95c82SChris Mason 	}
20175f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
20186a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
2019925baeddSChris Mason 		btrfs_tree_unlock(mid);
2020afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
2021f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
20225581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
20233083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
2024f0486c68SYan, Zheng 		mid = NULL;
202579f95c82SChris Mason 	} else {
202679f95c82SChris Mason 		/* update the parent key to reflect our changes */
20275f39d397SChris Mason 		struct btrfs_disk_key mid_key;
20285f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
20290e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, pslot,
20300e82bcfeSDavid Sterba 				MOD_LOG_KEY_REPLACE, GFP_NOFS);
20310e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
20325f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
20335f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
203479f95c82SChris Mason 	}
2035bb803951SChris Mason 
203679f95c82SChris Mason 	/* update the path */
20375f39d397SChris Mason 	if (left) {
20385f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
20395f39d397SChris Mason 			extent_buffer_get(left);
2040925baeddSChris Mason 			/* left was locked after cow */
20415f39d397SChris Mason 			path->nodes[level] = left;
2042bb803951SChris Mason 			path->slots[level + 1] -= 1;
2043bb803951SChris Mason 			path->slots[level] = orig_slot;
2044925baeddSChris Mason 			if (mid) {
2045925baeddSChris Mason 				btrfs_tree_unlock(mid);
20465f39d397SChris Mason 				free_extent_buffer(mid);
2047925baeddSChris Mason 			}
2048bb803951SChris Mason 		} else {
20495f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
2050bb803951SChris Mason 			path->slots[level] = orig_slot;
2051bb803951SChris Mason 		}
2052bb803951SChris Mason 	}
205379f95c82SChris Mason 	/* double check we haven't messed things up */
2054e20d96d6SChris Mason 	if (orig_ptr !=
20555f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
205679f95c82SChris Mason 		BUG();
205754aa1f4dSChris Mason enospc:
2058925baeddSChris Mason 	if (right) {
2059925baeddSChris Mason 		btrfs_tree_unlock(right);
20605f39d397SChris Mason 		free_extent_buffer(right);
2061925baeddSChris Mason 	}
2062925baeddSChris Mason 	if (left) {
2063925baeddSChris Mason 		if (path->nodes[level] != left)
2064925baeddSChris Mason 			btrfs_tree_unlock(left);
20655f39d397SChris Mason 		free_extent_buffer(left);
2066925baeddSChris Mason 	}
2067bb803951SChris Mason 	return ret;
2068bb803951SChris Mason }
2069bb803951SChris Mason 
2070d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
2071d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
2072d352ac68SChris Mason  * have to be pessimistic.
2073d352ac68SChris Mason  */
2074d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2075e66f709bSChris Mason 					  struct btrfs_root *root,
2076e66f709bSChris Mason 					  struct btrfs_path *path, int level)
2077e66f709bSChris Mason {
20780b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
20795f39d397SChris Mason 	struct extent_buffer *right = NULL;
20805f39d397SChris Mason 	struct extent_buffer *mid;
20815f39d397SChris Mason 	struct extent_buffer *left = NULL;
20825f39d397SChris Mason 	struct extent_buffer *parent = NULL;
2083e66f709bSChris Mason 	int ret = 0;
2084e66f709bSChris Mason 	int wret;
2085e66f709bSChris Mason 	int pslot;
2086e66f709bSChris Mason 	int orig_slot = path->slots[level];
2087e66f709bSChris Mason 
2088e66f709bSChris Mason 	if (level == 0)
2089e66f709bSChris Mason 		return 1;
2090e66f709bSChris Mason 
20915f39d397SChris Mason 	mid = path->nodes[level];
20927bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
2093e66f709bSChris Mason 
2094a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
20955f39d397SChris Mason 		parent = path->nodes[level + 1];
2096e66f709bSChris Mason 		pslot = path->slots[level + 1];
2097a05a9bb1SLi Zefan 	}
2098e66f709bSChris Mason 
20995f39d397SChris Mason 	if (!parent)
2100e66f709bSChris Mason 		return 1;
2101e66f709bSChris Mason 
21024b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
2103fb770ae4SLiu Bo 	if (IS_ERR(left))
2104fb770ae4SLiu Bo 		left = NULL;
2105e66f709bSChris Mason 
2106e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
21075f39d397SChris Mason 	if (left) {
2108e66f709bSChris Mason 		u32 left_nr;
2109925baeddSChris Mason 
2110925baeddSChris Mason 		btrfs_tree_lock(left);
21118bead258SDavid Sterba 		btrfs_set_lock_blocking_write(left);
2112b4ce94deSChris Mason 
21135f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
21140b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
211533ade1f8SChris Mason 			wret = 1;
211633ade1f8SChris Mason 		} else {
21175f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
21189fa8cfe7SChris Mason 					      pslot - 1, &left);
211954aa1f4dSChris Mason 			if (ret)
212054aa1f4dSChris Mason 				wret = 1;
212154aa1f4dSChris Mason 			else {
2122d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
212354aa1f4dSChris Mason 			}
212433ade1f8SChris Mason 		}
2125e66f709bSChris Mason 		if (wret < 0)
2126e66f709bSChris Mason 			ret = wret;
2127e66f709bSChris Mason 		if (wret == 0) {
21285f39d397SChris Mason 			struct btrfs_disk_key disk_key;
2129e66f709bSChris Mason 			orig_slot += left_nr;
21305f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
21310e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot,
21320e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21330e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21345f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
21355f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21365f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
21375f39d397SChris Mason 				path->nodes[level] = left;
2138e66f709bSChris Mason 				path->slots[level + 1] -= 1;
2139e66f709bSChris Mason 				path->slots[level] = orig_slot;
2140925baeddSChris Mason 				btrfs_tree_unlock(mid);
21415f39d397SChris Mason 				free_extent_buffer(mid);
2142e66f709bSChris Mason 			} else {
2143e66f709bSChris Mason 				orig_slot -=
21445f39d397SChris Mason 					btrfs_header_nritems(left);
2145e66f709bSChris Mason 				path->slots[level] = orig_slot;
2146925baeddSChris Mason 				btrfs_tree_unlock(left);
21475f39d397SChris Mason 				free_extent_buffer(left);
2148e66f709bSChris Mason 			}
2149e66f709bSChris Mason 			return 0;
2150e66f709bSChris Mason 		}
2151925baeddSChris Mason 		btrfs_tree_unlock(left);
21525f39d397SChris Mason 		free_extent_buffer(left);
2153e66f709bSChris Mason 	}
21544b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
2155fb770ae4SLiu Bo 	if (IS_ERR(right))
2156fb770ae4SLiu Bo 		right = NULL;
2157e66f709bSChris Mason 
2158e66f709bSChris Mason 	/*
2159e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
2160e66f709bSChris Mason 	 */
21615f39d397SChris Mason 	if (right) {
216233ade1f8SChris Mason 		u32 right_nr;
2163b4ce94deSChris Mason 
2164925baeddSChris Mason 		btrfs_tree_lock(right);
21658bead258SDavid Sterba 		btrfs_set_lock_blocking_write(right);
2166b4ce94deSChris Mason 
21675f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
21680b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
216933ade1f8SChris Mason 			wret = 1;
217033ade1f8SChris Mason 		} else {
21715f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
21725f39d397SChris Mason 					      parent, pslot + 1,
21739fa8cfe7SChris Mason 					      &right);
217454aa1f4dSChris Mason 			if (ret)
217554aa1f4dSChris Mason 				wret = 1;
217654aa1f4dSChris Mason 			else {
217755d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
217833ade1f8SChris Mason 			}
217954aa1f4dSChris Mason 		}
2180e66f709bSChris Mason 		if (wret < 0)
2181e66f709bSChris Mason 			ret = wret;
2182e66f709bSChris Mason 		if (wret == 0) {
21835f39d397SChris Mason 			struct btrfs_disk_key disk_key;
21845f39d397SChris Mason 
21855f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
21860e82bcfeSDavid Sterba 			ret = tree_mod_log_insert_key(parent, pslot + 1,
21870e82bcfeSDavid Sterba 					MOD_LOG_KEY_REPLACE, GFP_NOFS);
21880e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
21895f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
21905f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
21915f39d397SChris Mason 
21925f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
21935f39d397SChris Mason 				path->nodes[level] = right;
2194e66f709bSChris Mason 				path->slots[level + 1] += 1;
2195e66f709bSChris Mason 				path->slots[level] = orig_slot -
21965f39d397SChris Mason 					btrfs_header_nritems(mid);
2197925baeddSChris Mason 				btrfs_tree_unlock(mid);
21985f39d397SChris Mason 				free_extent_buffer(mid);
2199e66f709bSChris Mason 			} else {
2200925baeddSChris Mason 				btrfs_tree_unlock(right);
22015f39d397SChris Mason 				free_extent_buffer(right);
2202e66f709bSChris Mason 			}
2203e66f709bSChris Mason 			return 0;
2204e66f709bSChris Mason 		}
2205925baeddSChris Mason 		btrfs_tree_unlock(right);
22065f39d397SChris Mason 		free_extent_buffer(right);
2207e66f709bSChris Mason 	}
2208e66f709bSChris Mason 	return 1;
2209e66f709bSChris Mason }
2210e66f709bSChris Mason 
221174123bd7SChris Mason /*
2212d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
2213d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
22143c69faecSChris Mason  */
22152ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
2216e02119d5SChris Mason 			     struct btrfs_path *path,
221701f46658SChris Mason 			     int level, int slot, u64 objectid)
22183c69faecSChris Mason {
22195f39d397SChris Mason 	struct extent_buffer *node;
222001f46658SChris Mason 	struct btrfs_disk_key disk_key;
22213c69faecSChris Mason 	u32 nritems;
22223c69faecSChris Mason 	u64 search;
2223a7175319SChris Mason 	u64 target;
22246b80053dSChris Mason 	u64 nread = 0;
22255f39d397SChris Mason 	struct extent_buffer *eb;
22266b80053dSChris Mason 	u32 nr;
22276b80053dSChris Mason 	u32 blocksize;
22286b80053dSChris Mason 	u32 nscan = 0;
2229db94535dSChris Mason 
2230a6b6e75eSChris Mason 	if (level != 1)
22313c69faecSChris Mason 		return;
22323c69faecSChris Mason 
22336702ed49SChris Mason 	if (!path->nodes[level])
22346702ed49SChris Mason 		return;
22356702ed49SChris Mason 
22365f39d397SChris Mason 	node = path->nodes[level];
2237925baeddSChris Mason 
22383c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
22390b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
22400b246afaSJeff Mahoney 	eb = find_extent_buffer(fs_info, search);
22415f39d397SChris Mason 	if (eb) {
22425f39d397SChris Mason 		free_extent_buffer(eb);
22433c69faecSChris Mason 		return;
22443c69faecSChris Mason 	}
22453c69faecSChris Mason 
2246a7175319SChris Mason 	target = search;
22476b80053dSChris Mason 
22485f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
22496b80053dSChris Mason 	nr = slot;
225025b8b936SJosef Bacik 
22513c69faecSChris Mason 	while (1) {
2252e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
22536b80053dSChris Mason 			if (nr == 0)
22543c69faecSChris Mason 				break;
22556b80053dSChris Mason 			nr--;
2256e4058b54SDavid Sterba 		} else if (path->reada == READA_FORWARD) {
22576b80053dSChris Mason 			nr++;
22586b80053dSChris Mason 			if (nr >= nritems)
22596b80053dSChris Mason 				break;
22603c69faecSChris Mason 		}
2261e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
226201f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
226301f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
226401f46658SChris Mason 				break;
226501f46658SChris Mason 		}
22666b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
2267a7175319SChris Mason 		if ((search <= target && target - search <= 65536) ||
2268a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
22692ff7e61eSJeff Mahoney 			readahead_tree_block(fs_info, search);
22706b80053dSChris Mason 			nread += blocksize;
22713c69faecSChris Mason 		}
22726b80053dSChris Mason 		nscan++;
2273a7175319SChris Mason 		if ((nread > 65536 || nscan > 32))
22746b80053dSChris Mason 			break;
22753c69faecSChris Mason 	}
22763c69faecSChris Mason }
2277925baeddSChris Mason 
22782ff7e61eSJeff Mahoney static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2279b4ce94deSChris Mason 				       struct btrfs_path *path, int level)
2280b4ce94deSChris Mason {
2281b4ce94deSChris Mason 	int slot;
2282b4ce94deSChris Mason 	int nritems;
2283b4ce94deSChris Mason 	struct extent_buffer *parent;
2284b4ce94deSChris Mason 	struct extent_buffer *eb;
2285b4ce94deSChris Mason 	u64 gen;
2286b4ce94deSChris Mason 	u64 block1 = 0;
2287b4ce94deSChris Mason 	u64 block2 = 0;
2288b4ce94deSChris Mason 
22898c594ea8SChris Mason 	parent = path->nodes[level + 1];
2290b4ce94deSChris Mason 	if (!parent)
22910b08851fSJosef Bacik 		return;
2292b4ce94deSChris Mason 
2293b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
22948c594ea8SChris Mason 	slot = path->slots[level + 1];
2295b4ce94deSChris Mason 
2296b4ce94deSChris Mason 	if (slot > 0) {
2297b4ce94deSChris Mason 		block1 = btrfs_node_blockptr(parent, slot - 1);
2298b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot - 1);
22990b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block1);
2300b9fab919SChris Mason 		/*
2301b9fab919SChris Mason 		 * if we get -eagain from btrfs_buffer_uptodate, we
2302b9fab919SChris Mason 		 * don't want to return eagain here.  That will loop
2303b9fab919SChris Mason 		 * forever
2304b9fab919SChris Mason 		 */
2305b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2306b4ce94deSChris Mason 			block1 = 0;
2307b4ce94deSChris Mason 		free_extent_buffer(eb);
2308b4ce94deSChris Mason 	}
23098c594ea8SChris Mason 	if (slot + 1 < nritems) {
2310b4ce94deSChris Mason 		block2 = btrfs_node_blockptr(parent, slot + 1);
2311b4ce94deSChris Mason 		gen = btrfs_node_ptr_generation(parent, slot + 1);
23120b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, block2);
2313b9fab919SChris Mason 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2314b4ce94deSChris Mason 			block2 = 0;
2315b4ce94deSChris Mason 		free_extent_buffer(eb);
2316b4ce94deSChris Mason 	}
23178c594ea8SChris Mason 
2318b4ce94deSChris Mason 	if (block1)
23192ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block1);
2320b4ce94deSChris Mason 	if (block2)
23212ff7e61eSJeff Mahoney 		readahead_tree_block(fs_info, block2);
2322b4ce94deSChris Mason }
2323b4ce94deSChris Mason 
2324b4ce94deSChris Mason 
2325b4ce94deSChris Mason /*
2326d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
2327d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
2328d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
2329d397712bSChris Mason  * tree.
2330d352ac68SChris Mason  *
2331d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
2332d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
2333d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
2334d352ac68SChris Mason  *
2335d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2336d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
2337d352ac68SChris Mason  */
2338e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
2339f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
2340f7c79f30SChris Mason 			       int *write_lock_level)
2341925baeddSChris Mason {
2342925baeddSChris Mason 	int i;
2343925baeddSChris Mason 	int skip_level = level;
2344051e1b9fSChris Mason 	int no_skips = 0;
2345925baeddSChris Mason 	struct extent_buffer *t;
2346925baeddSChris Mason 
2347925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2348925baeddSChris Mason 		if (!path->nodes[i])
2349925baeddSChris Mason 			break;
2350925baeddSChris Mason 		if (!path->locks[i])
2351925baeddSChris Mason 			break;
2352051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
2353925baeddSChris Mason 			skip_level = i + 1;
2354925baeddSChris Mason 			continue;
2355925baeddSChris Mason 		}
2356051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
2357925baeddSChris Mason 			u32 nritems;
2358925baeddSChris Mason 			t = path->nodes[i];
2359925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
2360051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
2361925baeddSChris Mason 				skip_level = i + 1;
2362925baeddSChris Mason 				continue;
2363925baeddSChris Mason 			}
2364925baeddSChris Mason 		}
2365051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
2366051e1b9fSChris Mason 			no_skips = 1;
2367051e1b9fSChris Mason 
2368925baeddSChris Mason 		t = path->nodes[i];
2369d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
2370bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
2371925baeddSChris Mason 			path->locks[i] = 0;
2372f7c79f30SChris Mason 			if (write_lock_level &&
2373f7c79f30SChris Mason 			    i > min_write_lock_level &&
2374f7c79f30SChris Mason 			    i <= *write_lock_level) {
2375f7c79f30SChris Mason 				*write_lock_level = i - 1;
2376f7c79f30SChris Mason 			}
2377925baeddSChris Mason 		}
2378925baeddSChris Mason 	}
2379925baeddSChris Mason }
2380925baeddSChris Mason 
23813c69faecSChris Mason /*
2382b4ce94deSChris Mason  * This releases any locks held in the path starting at level and
2383b4ce94deSChris Mason  * going all the way up to the root.
2384b4ce94deSChris Mason  *
2385b4ce94deSChris Mason  * btrfs_search_slot will keep the lock held on higher nodes in a few
2386b4ce94deSChris Mason  * corner cases, such as COW of the block at slot zero in the node.  This
2387b4ce94deSChris Mason  * ignores those rules, and it should only be called when there are no
2388b4ce94deSChris Mason  * more updates to be done higher up in the tree.
2389b4ce94deSChris Mason  */
2390b4ce94deSChris Mason noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2391b4ce94deSChris Mason {
2392b4ce94deSChris Mason 	int i;
2393b4ce94deSChris Mason 
239409a2a8f9SJosef Bacik 	if (path->keep_locks)
2395b4ce94deSChris Mason 		return;
2396b4ce94deSChris Mason 
2397b4ce94deSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2398b4ce94deSChris Mason 		if (!path->nodes[i])
239912f4daccSChris Mason 			continue;
2400b4ce94deSChris Mason 		if (!path->locks[i])
240112f4daccSChris Mason 			continue;
2402bd681513SChris Mason 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2403b4ce94deSChris Mason 		path->locks[i] = 0;
2404b4ce94deSChris Mason 	}
2405b4ce94deSChris Mason }
2406b4ce94deSChris Mason 
2407b4ce94deSChris Mason /*
2408c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
2409c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
2410c8c42864SChris Mason  * we return zero and the path is unchanged.
2411c8c42864SChris Mason  *
2412c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
2413c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
2414c8c42864SChris Mason  */
2415c8c42864SChris Mason static int
2416d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2417c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
2418cda79c54SDavid Sterba 		      const struct btrfs_key *key)
2419c8c42864SChris Mason {
24200b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2421c8c42864SChris Mason 	u64 blocknr;
2422c8c42864SChris Mason 	u64 gen;
2423c8c42864SChris Mason 	struct extent_buffer *b = *eb_ret;
2424c8c42864SChris Mason 	struct extent_buffer *tmp;
2425581c1760SQu Wenruo 	struct btrfs_key first_key;
242676a05b35SChris Mason 	int ret;
2427581c1760SQu Wenruo 	int parent_level;
2428c8c42864SChris Mason 
2429c8c42864SChris Mason 	blocknr = btrfs_node_blockptr(b, slot);
2430c8c42864SChris Mason 	gen = btrfs_node_ptr_generation(b, slot);
2431581c1760SQu Wenruo 	parent_level = btrfs_header_level(b);
2432581c1760SQu Wenruo 	btrfs_node_key_to_cpu(b, &first_key, slot);
2433c8c42864SChris Mason 
24340b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
2435cb44921aSChris Mason 	if (tmp) {
2436b9fab919SChris Mason 		/* first we do an atomic uptodate check */
2437b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2438448de471SQu Wenruo 			/*
2439448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
2440448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
2441448de471SQu Wenruo 			 * parents (shared tree blocks).
2442448de471SQu Wenruo 			 */
2443e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
2444448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
2445448de471SQu Wenruo 				free_extent_buffer(tmp);
2446448de471SQu Wenruo 				return -EUCLEAN;
2447448de471SQu Wenruo 			}
2448c8c42864SChris Mason 			*eb_ret = tmp;
2449c8c42864SChris Mason 			return 0;
2450c8c42864SChris Mason 		}
2451bdf7c00eSJosef Bacik 
2452cb44921aSChris Mason 		/* the pages were up to date, but we failed
2453cb44921aSChris Mason 		 * the generation number check.  Do a full
2454cb44921aSChris Mason 		 * read for the generation number that is correct.
2455cb44921aSChris Mason 		 * We must do this without dropping locks so
2456cb44921aSChris Mason 		 * we can trust our generation number
2457cb44921aSChris Mason 		 */
2458bd681513SChris Mason 		btrfs_set_path_blocking(p);
2459bd681513SChris Mason 
2460b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
2461581c1760SQu Wenruo 		ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
2462bdf7c00eSJosef Bacik 		if (!ret) {
2463cb44921aSChris Mason 			*eb_ret = tmp;
2464cb44921aSChris Mason 			return 0;
2465cb44921aSChris Mason 		}
2466cb44921aSChris Mason 		free_extent_buffer(tmp);
2467b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2468cb44921aSChris Mason 		return -EIO;
2469cb44921aSChris Mason 	}
2470c8c42864SChris Mason 
2471c8c42864SChris Mason 	/*
2472c8c42864SChris Mason 	 * reduce lock contention at high levels
2473c8c42864SChris Mason 	 * of the btree by dropping locks before
247476a05b35SChris Mason 	 * we read.  Don't release the lock on the current
247576a05b35SChris Mason 	 * level because we need to walk this node to figure
247676a05b35SChris Mason 	 * out which blocks to read.
2477c8c42864SChris Mason 	 */
24788c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
24798c594ea8SChris Mason 	btrfs_set_path_blocking(p);
24808c594ea8SChris Mason 
2481e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
24822ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
2483c8c42864SChris Mason 
248476a05b35SChris Mason 	ret = -EAGAIN;
248502a3307aSLiu Bo 	tmp = read_tree_block(fs_info, blocknr, gen, parent_level - 1,
2486581c1760SQu Wenruo 			      &first_key);
248764c043deSLiu Bo 	if (!IS_ERR(tmp)) {
248876a05b35SChris Mason 		/*
248976a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
249076a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
249176a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
249276a05b35SChris Mason 		 * on our EAGAINs.
249376a05b35SChris Mason 		 */
2494e6a1d6fdSLiu Bo 		if (!extent_buffer_uptodate(tmp))
249576a05b35SChris Mason 			ret = -EIO;
2496c8c42864SChris Mason 		free_extent_buffer(tmp);
2497c871b0f2SLiu Bo 	} else {
2498c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
249976a05b35SChris Mason 	}
250002a3307aSLiu Bo 
250102a3307aSLiu Bo 	btrfs_release_path(p);
250276a05b35SChris Mason 	return ret;
2503c8c42864SChris Mason }
2504c8c42864SChris Mason 
2505c8c42864SChris Mason /*
2506c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
2507c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
2508c8c42864SChris Mason  * the ins_len.
2509c8c42864SChris Mason  *
2510c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
2511c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2512c8c42864SChris Mason  * start over
2513c8c42864SChris Mason  */
2514c8c42864SChris Mason static int
2515c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
2516c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
2517bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
2518bd681513SChris Mason 		       int *write_lock_level)
2519c8c42864SChris Mason {
25200b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2521c8c42864SChris Mason 	int ret;
25220b246afaSJeff Mahoney 
2523c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
25240b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2525c8c42864SChris Mason 		int sret;
2526c8c42864SChris Mason 
2527bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2528bd681513SChris Mason 			*write_lock_level = level + 1;
2529bd681513SChris Mason 			btrfs_release_path(p);
2530bd681513SChris Mason 			goto again;
2531bd681513SChris Mason 		}
2532bd681513SChris Mason 
2533c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25342ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2535c8c42864SChris Mason 		sret = split_node(trans, root, p, level);
2536c8c42864SChris Mason 
2537c8c42864SChris Mason 		BUG_ON(sret > 0);
2538c8c42864SChris Mason 		if (sret) {
2539c8c42864SChris Mason 			ret = sret;
2540c8c42864SChris Mason 			goto done;
2541c8c42864SChris Mason 		}
2542c8c42864SChris Mason 		b = p->nodes[level];
2543c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
25440b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2545c8c42864SChris Mason 		int sret;
2546c8c42864SChris Mason 
2547bd681513SChris Mason 		if (*write_lock_level < level + 1) {
2548bd681513SChris Mason 			*write_lock_level = level + 1;
2549bd681513SChris Mason 			btrfs_release_path(p);
2550bd681513SChris Mason 			goto again;
2551bd681513SChris Mason 		}
2552bd681513SChris Mason 
2553c8c42864SChris Mason 		btrfs_set_path_blocking(p);
25542ff7e61eSJeff Mahoney 		reada_for_balance(fs_info, p, level);
2555c8c42864SChris Mason 		sret = balance_level(trans, root, p, level);
2556c8c42864SChris Mason 
2557c8c42864SChris Mason 		if (sret) {
2558c8c42864SChris Mason 			ret = sret;
2559c8c42864SChris Mason 			goto done;
2560c8c42864SChris Mason 		}
2561c8c42864SChris Mason 		b = p->nodes[level];
2562c8c42864SChris Mason 		if (!b) {
2563b3b4aa74SDavid Sterba 			btrfs_release_path(p);
2564c8c42864SChris Mason 			goto again;
2565c8c42864SChris Mason 		}
2566c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
2567c8c42864SChris Mason 	}
2568c8c42864SChris Mason 	return 0;
2569c8c42864SChris Mason 
2570c8c42864SChris Mason again:
2571c8c42864SChris Mason 	ret = -EAGAIN;
2572c8c42864SChris Mason done:
2573c8c42864SChris Mason 	return ret;
2574c8c42864SChris Mason }
2575c8c42864SChris Mason 
2576310712b2SOmar Sandoval static int key_search(struct extent_buffer *b, const struct btrfs_key *key,
2577d7396f07SFilipe David Borba Manana 		      int level, int *prev_cmp, int *slot)
2578d7396f07SFilipe David Borba Manana {
2579d7396f07SFilipe David Borba Manana 	if (*prev_cmp != 0) {
2580a74b35ecSNikolay Borisov 		*prev_cmp = btrfs_bin_search(b, key, level, slot);
2581d7396f07SFilipe David Borba Manana 		return *prev_cmp;
2582d7396f07SFilipe David Borba Manana 	}
2583d7396f07SFilipe David Borba Manana 
2584d7396f07SFilipe David Borba Manana 	*slot = 0;
2585d7396f07SFilipe David Borba Manana 
2586d7396f07SFilipe David Borba Manana 	return 0;
2587d7396f07SFilipe David Borba Manana }
2588d7396f07SFilipe David Borba Manana 
2589381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2590e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
2591e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
2592e33d5c3dSKelley Nielsen {
2593e33d5c3dSKelley Nielsen 	int ret;
2594e33d5c3dSKelley Nielsen 	struct btrfs_key key;
2595e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
2596381cf658SDavid Sterba 
2597381cf658SDavid Sterba 	ASSERT(path);
25981d4c08e0SDavid Sterba 	ASSERT(found_key);
2599e33d5c3dSKelley Nielsen 
2600e33d5c3dSKelley Nielsen 	key.type = key_type;
2601e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
2602e33d5c3dSKelley Nielsen 	key.offset = ioff;
2603e33d5c3dSKelley Nielsen 
2604e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
26051d4c08e0SDavid Sterba 	if (ret < 0)
2606e33d5c3dSKelley Nielsen 		return ret;
2607e33d5c3dSKelley Nielsen 
2608e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
2609e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2610e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
2611e33d5c3dSKelley Nielsen 		if (ret)
2612e33d5c3dSKelley Nielsen 			return ret;
2613e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
2614e33d5c3dSKelley Nielsen 	}
2615e33d5c3dSKelley Nielsen 
2616e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2617e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
2618e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
2619e33d5c3dSKelley Nielsen 		return 1;
2620e33d5c3dSKelley Nielsen 
2621e33d5c3dSKelley Nielsen 	return 0;
2622e33d5c3dSKelley Nielsen }
2623e33d5c3dSKelley Nielsen 
26241fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
26251fc28d8eSLiu Bo 							struct btrfs_path *p,
26261fc28d8eSLiu Bo 							int write_lock_level)
26271fc28d8eSLiu Bo {
26281fc28d8eSLiu Bo 	struct btrfs_fs_info *fs_info = root->fs_info;
26291fc28d8eSLiu Bo 	struct extent_buffer *b;
26301fc28d8eSLiu Bo 	int root_lock;
26311fc28d8eSLiu Bo 	int level = 0;
26321fc28d8eSLiu Bo 
26331fc28d8eSLiu Bo 	/* We try very hard to do read locks on the root */
26341fc28d8eSLiu Bo 	root_lock = BTRFS_READ_LOCK;
26351fc28d8eSLiu Bo 
26361fc28d8eSLiu Bo 	if (p->search_commit_root) {
2637be6821f8SFilipe Manana 		/*
2638be6821f8SFilipe Manana 		 * The commit roots are read only so we always do read locks,
2639be6821f8SFilipe Manana 		 * and we always must hold the commit_root_sem when doing
2640be6821f8SFilipe Manana 		 * searches on them, the only exception is send where we don't
2641be6821f8SFilipe Manana 		 * want to block transaction commits for a long time, so
2642be6821f8SFilipe Manana 		 * we need to clone the commit root in order to avoid races
2643be6821f8SFilipe Manana 		 * with transaction commits that create a snapshot of one of
2644be6821f8SFilipe Manana 		 * the roots used by a send operation.
2645be6821f8SFilipe Manana 		 */
2646be6821f8SFilipe Manana 		if (p->need_commit_sem) {
26471fc28d8eSLiu Bo 			down_read(&fs_info->commit_root_sem);
2648be6821f8SFilipe Manana 			b = btrfs_clone_extent_buffer(root->commit_root);
2649be6821f8SFilipe Manana 			up_read(&fs_info->commit_root_sem);
2650be6821f8SFilipe Manana 			if (!b)
2651be6821f8SFilipe Manana 				return ERR_PTR(-ENOMEM);
2652be6821f8SFilipe Manana 
2653be6821f8SFilipe Manana 		} else {
26541fc28d8eSLiu Bo 			b = root->commit_root;
26551fc28d8eSLiu Bo 			extent_buffer_get(b);
2656be6821f8SFilipe Manana 		}
26571fc28d8eSLiu Bo 		level = btrfs_header_level(b);
2658f9ddfd05SLiu Bo 		/*
2659f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
2660f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
2661f9ddfd05SLiu Bo 		 */
2662f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
26631fc28d8eSLiu Bo 
26641fc28d8eSLiu Bo 		goto out;
26651fc28d8eSLiu Bo 	}
26661fc28d8eSLiu Bo 
26671fc28d8eSLiu Bo 	if (p->skip_locking) {
26681fc28d8eSLiu Bo 		b = btrfs_root_node(root);
26691fc28d8eSLiu Bo 		level = btrfs_header_level(b);
26701fc28d8eSLiu Bo 		goto out;
26711fc28d8eSLiu Bo 	}
26721fc28d8eSLiu Bo 
26731fc28d8eSLiu Bo 	/*
2674662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
2675662c653bSLiu Bo 	 * lock.
2676662c653bSLiu Bo 	 */
2677662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
2678662c653bSLiu Bo 		/*
2679662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
2680662c653bSLiu Bo 		 * have it read locked
26811fc28d8eSLiu Bo 		 */
26821fc28d8eSLiu Bo 		b = btrfs_read_lock_root_node(root);
26831fc28d8eSLiu Bo 		level = btrfs_header_level(b);
26841fc28d8eSLiu Bo 		if (level > write_lock_level)
26851fc28d8eSLiu Bo 			goto out;
26861fc28d8eSLiu Bo 
2687662c653bSLiu Bo 		/* Whoops, must trade for write lock */
26881fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
26891fc28d8eSLiu Bo 		free_extent_buffer(b);
2690662c653bSLiu Bo 	}
2691662c653bSLiu Bo 
26921fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
26931fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
26941fc28d8eSLiu Bo 
26951fc28d8eSLiu Bo 	/* The level might have changed, check again */
26961fc28d8eSLiu Bo 	level = btrfs_header_level(b);
26971fc28d8eSLiu Bo 
26981fc28d8eSLiu Bo out:
26991fc28d8eSLiu Bo 	p->nodes[level] = b;
27001fc28d8eSLiu Bo 	if (!p->skip_locking)
27011fc28d8eSLiu Bo 		p->locks[level] = root_lock;
27021fc28d8eSLiu Bo 	/*
27031fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
27041fc28d8eSLiu Bo 	 */
27051fc28d8eSLiu Bo 	return b;
27061fc28d8eSLiu Bo }
27071fc28d8eSLiu Bo 
27081fc28d8eSLiu Bo 
2709c8c42864SChris Mason /*
27104271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
27114271eceaSNikolay Borisov  * modifications to preserve tree invariants.
271274123bd7SChris Mason  *
27134271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
27144271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
27154271eceaSNikolay Borisov  * @root:	The root node of the tree
27164271eceaSNikolay Borisov  * @key:	The key we are looking for
27174271eceaSNikolay Borisov  * @ins_len:	Indicates purpose of search, for inserts it is 1, for
27184271eceaSNikolay Borisov  *		deletions it's -1. 0 for plain searches
27194271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
27204271eceaSNikolay Borisov  *		when modifying the tree.
272197571fd0SChris Mason  *
27224271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
27234271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
27244271eceaSNikolay Borisov  *
27254271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
27264271eceaSNikolay Borisov  * of the path (level 0)
27274271eceaSNikolay Borisov  *
27284271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
27294271eceaSNikolay Borisov  * points to the slot where it should be inserted
27304271eceaSNikolay Borisov  *
27314271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
27324271eceaSNikolay Borisov  * is returned
273374123bd7SChris Mason  */
2734310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2735310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2736310712b2SOmar Sandoval 		      int ins_len, int cow)
2737be0e5c09SChris Mason {
27385f39d397SChris Mason 	struct extent_buffer *b;
2739be0e5c09SChris Mason 	int slot;
2740be0e5c09SChris Mason 	int ret;
274133c66f43SYan Zheng 	int err;
2742be0e5c09SChris Mason 	int level;
2743925baeddSChris Mason 	int lowest_unlock = 1;
2744bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2745bd681513SChris Mason 	int write_lock_level = 0;
27469f3a7427SChris Mason 	u8 lowest_level = 0;
2747f7c79f30SChris Mason 	int min_write_lock_level;
2748d7396f07SFilipe David Borba Manana 	int prev_cmp;
27499f3a7427SChris Mason 
27506702ed49SChris Mason 	lowest_level = p->lowest_level;
2751323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
275222b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2753eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
275425179201SJosef Bacik 
2755bd681513SChris Mason 	if (ins_len < 0) {
2756925baeddSChris Mason 		lowest_unlock = 2;
275765b51a00SChris Mason 
2758bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2759bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2760bd681513SChris Mason 		 * for those levels as well
2761bd681513SChris Mason 		 */
2762bd681513SChris Mason 		write_lock_level = 2;
2763bd681513SChris Mason 	} else if (ins_len > 0) {
2764bd681513SChris Mason 		/*
2765bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2766bd681513SChris Mason 		 * level 1 so we can update keys
2767bd681513SChris Mason 		 */
2768bd681513SChris Mason 		write_lock_level = 1;
2769bd681513SChris Mason 	}
2770bd681513SChris Mason 
2771bd681513SChris Mason 	if (!cow)
2772bd681513SChris Mason 		write_lock_level = -1;
2773bd681513SChris Mason 
277409a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2775bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2776bd681513SChris Mason 
2777f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2778f7c79f30SChris Mason 
2779bb803951SChris Mason again:
2780d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
27811fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2782be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2783be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2784be6821f8SFilipe Manana 		goto done;
2785be6821f8SFilipe Manana 	}
2786925baeddSChris Mason 
2787eb60ceacSChris Mason 	while (b) {
2788*f624d976SQu Wenruo 		int dec = 0;
2789*f624d976SQu Wenruo 
27905f39d397SChris Mason 		level = btrfs_header_level(b);
279165b51a00SChris Mason 
279265b51a00SChris Mason 		/*
279365b51a00SChris Mason 		 * setup the path here so we can release it under lock
279465b51a00SChris Mason 		 * contention with the cow code
279565b51a00SChris Mason 		 */
279602217ed2SChris Mason 		if (cow) {
27979ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
27989ea2c7c9SNikolay Borisov 
2799c8c42864SChris Mason 			/*
2800c8c42864SChris Mason 			 * if we don't really need to cow this block
2801c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2802c8c42864SChris Mason 			 * so we test it here
2803c8c42864SChris Mason 			 */
280464c12921SJeff Mahoney 			if (!should_cow_block(trans, root, b)) {
280564c12921SJeff Mahoney 				trans->dirty = true;
280665b51a00SChris Mason 				goto cow_done;
280764c12921SJeff Mahoney 			}
28085d4f98a2SYan Zheng 
2809bd681513SChris Mason 			/*
2810bd681513SChris Mason 			 * must have write locks on this node and the
2811bd681513SChris Mason 			 * parent
2812bd681513SChris Mason 			 */
28135124e00eSJosef Bacik 			if (level > write_lock_level ||
28145124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
28155124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
28165124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2817bd681513SChris Mason 				write_lock_level = level + 1;
2818bd681513SChris Mason 				btrfs_release_path(p);
2819bd681513SChris Mason 				goto again;
2820bd681513SChris Mason 			}
2821bd681513SChris Mason 
2822160f4089SFilipe Manana 			btrfs_set_path_blocking(p);
28239ea2c7c9SNikolay Borisov 			if (last_level)
28249ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
28259ea2c7c9SNikolay Borisov 						      &b);
28269ea2c7c9SNikolay Borisov 			else
282733c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2828e20d96d6SChris Mason 						      p->nodes[level + 1],
28299fa8cfe7SChris Mason 						      p->slots[level + 1], &b);
283033c66f43SYan Zheng 			if (err) {
283133c66f43SYan Zheng 				ret = err;
283265b51a00SChris Mason 				goto done;
283354aa1f4dSChris Mason 			}
283402217ed2SChris Mason 		}
283565b51a00SChris Mason cow_done:
2836eb60ceacSChris Mason 		p->nodes[level] = b;
283752398340SLiu Bo 		/*
283852398340SLiu Bo 		 * Leave path with blocking locks to avoid massive
283952398340SLiu Bo 		 * lock context switch, this is made on purpose.
284052398340SLiu Bo 		 */
2841b4ce94deSChris Mason 
2842b4ce94deSChris Mason 		/*
2843b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2844b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2845b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2846b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2847b4ce94deSChris Mason 		 *
2848eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2849eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2850eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2851eb653de1SFilipe David Borba Manana 		 * we're operating on.
2852b4ce94deSChris Mason 		 */
2853eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2854eb653de1SFilipe David Borba Manana 			int u = level + 1;
2855eb653de1SFilipe David Borba Manana 
2856eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2857eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2858eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2859eb653de1SFilipe David Borba Manana 			}
2860eb653de1SFilipe David Borba Manana 		}
2861b4ce94deSChris Mason 
2862d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
2863415b35a5SLiu Bo 		if (ret < 0)
2864415b35a5SLiu Bo 			goto done;
2865b4ce94deSChris Mason 
2866*f624d976SQu Wenruo 		if (level == 0) {
2867be0e5c09SChris Mason 			p->slots[level] = slot;
286887b29b20SYan Zheng 			if (ins_len > 0 &&
2869e902baacSDavid Sterba 			    btrfs_leaf_free_space(b) < ins_len) {
2870bd681513SChris Mason 				if (write_lock_level < 1) {
2871bd681513SChris Mason 					write_lock_level = 1;
2872bd681513SChris Mason 					btrfs_release_path(p);
2873bd681513SChris Mason 					goto again;
2874bd681513SChris Mason 				}
2875bd681513SChris Mason 
2876b4ce94deSChris Mason 				btrfs_set_path_blocking(p);
287733c66f43SYan Zheng 				err = split_leaf(trans, root, key,
2878cc0c5538SChris Mason 						 p, ins_len, ret == 0);
2879b4ce94deSChris Mason 
288033c66f43SYan Zheng 				BUG_ON(err > 0);
288133c66f43SYan Zheng 				if (err) {
288233c66f43SYan Zheng 					ret = err;
288365b51a00SChris Mason 					goto done;
288465b51a00SChris Mason 				}
28855c680ed6SChris Mason 			}
2886459931ecSChris Mason 			if (!p->search_for_split)
2887f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
28884b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
288965b51a00SChris Mason 			goto done;
289065b51a00SChris Mason 		}
2891*f624d976SQu Wenruo 		if (ret && slot > 0) {
2892*f624d976SQu Wenruo 			dec = 1;
2893*f624d976SQu Wenruo 			slot--;
2894*f624d976SQu Wenruo 		}
2895*f624d976SQu Wenruo 		p->slots[level] = slot;
2896*f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2897*f624d976SQu Wenruo 					     &write_lock_level);
2898*f624d976SQu Wenruo 		if (err == -EAGAIN)
2899*f624d976SQu Wenruo 			goto again;
2900*f624d976SQu Wenruo 		if (err) {
2901*f624d976SQu Wenruo 			ret = err;
2902*f624d976SQu Wenruo 			goto done;
2903*f624d976SQu Wenruo 		}
2904*f624d976SQu Wenruo 		b = p->nodes[level];
2905*f624d976SQu Wenruo 		slot = p->slots[level];
2906*f624d976SQu Wenruo 
2907*f624d976SQu Wenruo 		/*
2908*f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2909*f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2910*f624d976SQu Wenruo 		 * the parent
2911*f624d976SQu Wenruo 		 */
2912*f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2913*f624d976SQu Wenruo 			write_lock_level = level + 1;
2914*f624d976SQu Wenruo 			btrfs_release_path(p);
2915*f624d976SQu Wenruo 			goto again;
2916*f624d976SQu Wenruo 		}
2917*f624d976SQu Wenruo 
2918*f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2919*f624d976SQu Wenruo 			  &write_lock_level);
2920*f624d976SQu Wenruo 
2921*f624d976SQu Wenruo 		if (level == lowest_level) {
2922*f624d976SQu Wenruo 			if (dec)
2923*f624d976SQu Wenruo 				p->slots[level]++;
2924*f624d976SQu Wenruo 			goto done;
2925*f624d976SQu Wenruo 		}
2926*f624d976SQu Wenruo 
2927*f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2928*f624d976SQu Wenruo 		if (err == -EAGAIN)
2929*f624d976SQu Wenruo 			goto again;
2930*f624d976SQu Wenruo 		if (err) {
2931*f624d976SQu Wenruo 			ret = err;
2932*f624d976SQu Wenruo 			goto done;
2933*f624d976SQu Wenruo 		}
2934*f624d976SQu Wenruo 
2935*f624d976SQu Wenruo 		if (!p->skip_locking) {
2936*f624d976SQu Wenruo 			level = btrfs_header_level(b);
2937*f624d976SQu Wenruo 			if (level <= write_lock_level) {
2938*f624d976SQu Wenruo 				if (!btrfs_try_tree_write_lock(b)) {
2939*f624d976SQu Wenruo 					btrfs_set_path_blocking(p);
2940*f624d976SQu Wenruo 					btrfs_tree_lock(b);
2941*f624d976SQu Wenruo 				}
2942*f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2943*f624d976SQu Wenruo 			} else {
2944*f624d976SQu Wenruo 				if (!btrfs_tree_read_lock_atomic(b)) {
2945*f624d976SQu Wenruo 					btrfs_set_path_blocking(p);
2946*f624d976SQu Wenruo 					btrfs_tree_read_lock(b);
2947*f624d976SQu Wenruo 				}
2948*f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2949*f624d976SQu Wenruo 			}
2950*f624d976SQu Wenruo 			p->nodes[level] = b;
2951*f624d976SQu Wenruo 		}
295265b51a00SChris Mason 	}
295365b51a00SChris Mason 	ret = 1;
295465b51a00SChris Mason done:
2955b4ce94deSChris Mason 	/*
2956b4ce94deSChris Mason 	 * we don't really know what they plan on doing with the path
2957b4ce94deSChris Mason 	 * from here on, so for now just mark it as blocking
2958b4ce94deSChris Mason 	 */
2959b9473439SChris Mason 	if (!p->leave_spinning)
2960b4ce94deSChris Mason 		btrfs_set_path_blocking(p);
29615f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2962b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2963be0e5c09SChris Mason 	return ret;
2964be0e5c09SChris Mason }
2965be0e5c09SChris Mason 
296674123bd7SChris Mason /*
29675d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
29685d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
29695d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
29705d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
29715d9e75c4SJan Schmidt  *
29725d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
29735d9e75c4SJan Schmidt  *
29745d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
29755d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
29765d9e75c4SJan Schmidt  */
2977310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
29785d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
29795d9e75c4SJan Schmidt {
29800b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29815d9e75c4SJan Schmidt 	struct extent_buffer *b;
29825d9e75c4SJan Schmidt 	int slot;
29835d9e75c4SJan Schmidt 	int ret;
29845d9e75c4SJan Schmidt 	int err;
29855d9e75c4SJan Schmidt 	int level;
29865d9e75c4SJan Schmidt 	int lowest_unlock = 1;
29875d9e75c4SJan Schmidt 	u8 lowest_level = 0;
2988d4b4087cSJosef Bacik 	int prev_cmp = -1;
29895d9e75c4SJan Schmidt 
29905d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
29915d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
29925d9e75c4SJan Schmidt 
29935d9e75c4SJan Schmidt 	if (p->search_commit_root) {
29945d9e75c4SJan Schmidt 		BUG_ON(time_seq);
29955d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
29965d9e75c4SJan Schmidt 	}
29975d9e75c4SJan Schmidt 
29985d9e75c4SJan Schmidt again:
29995d9e75c4SJan Schmidt 	b = get_old_root(root, time_seq);
3000315bed43SNikolay Borisov 	if (!b) {
3001315bed43SNikolay Borisov 		ret = -EIO;
3002315bed43SNikolay Borisov 		goto done;
3003315bed43SNikolay Borisov 	}
30045d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
30055d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
30065d9e75c4SJan Schmidt 
30075d9e75c4SJan Schmidt 	while (b) {
30085d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
30095d9e75c4SJan Schmidt 		p->nodes[level] = b;
30105d9e75c4SJan Schmidt 
30115d9e75c4SJan Schmidt 		/*
30125d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
30135d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
30145d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
30155d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
30165d9e75c4SJan Schmidt 		 */
30175d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
30185d9e75c4SJan Schmidt 
3019d4b4087cSJosef Bacik 		/*
302001327610SNicholas D Steeves 		 * Since we can unwind ebs we want to do a real search every
3021d4b4087cSJosef Bacik 		 * time.
3022d4b4087cSJosef Bacik 		 */
3023d4b4087cSJosef Bacik 		prev_cmp = -1;
3024d7396f07SFilipe David Borba Manana 		ret = key_search(b, key, level, &prev_cmp, &slot);
3025cbca7d59SFilipe Manana 		if (ret < 0)
3026cbca7d59SFilipe Manana 			goto done;
30275d9e75c4SJan Schmidt 
30285d9e75c4SJan Schmidt 		if (level != 0) {
30295d9e75c4SJan Schmidt 			int dec = 0;
30305d9e75c4SJan Schmidt 			if (ret && slot > 0) {
30315d9e75c4SJan Schmidt 				dec = 1;
30325d9e75c4SJan Schmidt 				slot -= 1;
30335d9e75c4SJan Schmidt 			}
30345d9e75c4SJan Schmidt 			p->slots[level] = slot;
30355d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
30365d9e75c4SJan Schmidt 
30375d9e75c4SJan Schmidt 			if (level == lowest_level) {
30385d9e75c4SJan Schmidt 				if (dec)
30395d9e75c4SJan Schmidt 					p->slots[level]++;
30405d9e75c4SJan Schmidt 				goto done;
30415d9e75c4SJan Schmidt 			}
30425d9e75c4SJan Schmidt 
3043d07b8528SLiu Bo 			err = read_block_for_search(root, p, &b, level,
3044cda79c54SDavid Sterba 						    slot, key);
30455d9e75c4SJan Schmidt 			if (err == -EAGAIN)
30465d9e75c4SJan Schmidt 				goto again;
30475d9e75c4SJan Schmidt 			if (err) {
30485d9e75c4SJan Schmidt 				ret = err;
30495d9e75c4SJan Schmidt 				goto done;
30505d9e75c4SJan Schmidt 			}
30515d9e75c4SJan Schmidt 
30525d9e75c4SJan Schmidt 			level = btrfs_header_level(b);
305365e99c43SNikolay Borisov 			if (!btrfs_tree_read_lock_atomic(b)) {
30545d9e75c4SJan Schmidt 				btrfs_set_path_blocking(p);
30555d9e75c4SJan Schmidt 				btrfs_tree_read_lock(b);
30565d9e75c4SJan Schmidt 			}
30570b246afaSJeff Mahoney 			b = tree_mod_log_rewind(fs_info, p, b, time_seq);
3058db7f3436SJosef Bacik 			if (!b) {
3059db7f3436SJosef Bacik 				ret = -ENOMEM;
3060db7f3436SJosef Bacik 				goto done;
3061db7f3436SJosef Bacik 			}
30625d9e75c4SJan Schmidt 			p->locks[level] = BTRFS_READ_LOCK;
30635d9e75c4SJan Schmidt 			p->nodes[level] = b;
30645d9e75c4SJan Schmidt 		} else {
30655d9e75c4SJan Schmidt 			p->slots[level] = slot;
30665d9e75c4SJan Schmidt 			unlock_up(p, level, lowest_unlock, 0, NULL);
30675d9e75c4SJan Schmidt 			goto done;
30685d9e75c4SJan Schmidt 		}
30695d9e75c4SJan Schmidt 	}
30705d9e75c4SJan Schmidt 	ret = 1;
30715d9e75c4SJan Schmidt done:
30725d9e75c4SJan Schmidt 	if (!p->leave_spinning)
30735d9e75c4SJan Schmidt 		btrfs_set_path_blocking(p);
30745d9e75c4SJan Schmidt 	if (ret < 0)
30755d9e75c4SJan Schmidt 		btrfs_release_path(p);
30765d9e75c4SJan Schmidt 
30775d9e75c4SJan Schmidt 	return ret;
30785d9e75c4SJan Schmidt }
30795d9e75c4SJan Schmidt 
30805d9e75c4SJan Schmidt /*
30812f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
30822f38b3e1SArne Jansen  * instead the next or previous item should be returned.
30832f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
30842f38b3e1SArne Jansen  * otherwise.
30852f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
30862f38b3e1SArne Jansen  * return the next lower instead.
30872f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
30882f38b3e1SArne Jansen  * return the next higher instead.
30892f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
30902f38b3e1SArne Jansen  * < 0 on error
30912f38b3e1SArne Jansen  */
30922f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
3093310712b2SOmar Sandoval 			       const struct btrfs_key *key,
3094310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
3095310712b2SOmar Sandoval 			       int return_any)
30962f38b3e1SArne Jansen {
30972f38b3e1SArne Jansen 	int ret;
30982f38b3e1SArne Jansen 	struct extent_buffer *leaf;
30992f38b3e1SArne Jansen 
31002f38b3e1SArne Jansen again:
31012f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
31022f38b3e1SArne Jansen 	if (ret <= 0)
31032f38b3e1SArne Jansen 		return ret;
31042f38b3e1SArne Jansen 	/*
31052f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
31062f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
31072f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
31082f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
31092f38b3e1SArne Jansen 	 * item.
31102f38b3e1SArne Jansen 	 */
31112f38b3e1SArne Jansen 	leaf = p->nodes[0];
31122f38b3e1SArne Jansen 
31132f38b3e1SArne Jansen 	if (find_higher) {
31142f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
31152f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
31162f38b3e1SArne Jansen 			if (ret <= 0)
31172f38b3e1SArne Jansen 				return ret;
31182f38b3e1SArne Jansen 			if (!return_any)
31192f38b3e1SArne Jansen 				return 1;
31202f38b3e1SArne Jansen 			/*
31212f38b3e1SArne Jansen 			 * no higher item found, return the next
31222f38b3e1SArne Jansen 			 * lower instead
31232f38b3e1SArne Jansen 			 */
31242f38b3e1SArne Jansen 			return_any = 0;
31252f38b3e1SArne Jansen 			find_higher = 0;
31262f38b3e1SArne Jansen 			btrfs_release_path(p);
31272f38b3e1SArne Jansen 			goto again;
31282f38b3e1SArne Jansen 		}
31292f38b3e1SArne Jansen 	} else {
31302f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
31312f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
3132e6793769SArne Jansen 			if (ret < 0)
31332f38b3e1SArne Jansen 				return ret;
3134e6793769SArne Jansen 			if (!ret) {
313523c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
313623c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
313723c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
3138e6793769SArne Jansen 				return 0;
3139e6793769SArne Jansen 			}
31402f38b3e1SArne Jansen 			if (!return_any)
31412f38b3e1SArne Jansen 				return 1;
31422f38b3e1SArne Jansen 			/*
31432f38b3e1SArne Jansen 			 * no lower item found, return the next
31442f38b3e1SArne Jansen 			 * higher instead
31452f38b3e1SArne Jansen 			 */
31462f38b3e1SArne Jansen 			return_any = 0;
31472f38b3e1SArne Jansen 			find_higher = 1;
31482f38b3e1SArne Jansen 			btrfs_release_path(p);
31492f38b3e1SArne Jansen 			goto again;
3150e6793769SArne Jansen 		} else {
31512f38b3e1SArne Jansen 			--p->slots[0];
31522f38b3e1SArne Jansen 		}
31532f38b3e1SArne Jansen 	}
31542f38b3e1SArne Jansen 	return 0;
31552f38b3e1SArne Jansen }
31562f38b3e1SArne Jansen 
31572f38b3e1SArne Jansen /*
315874123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
315974123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
316074123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
316174123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
316274123bd7SChris Mason  * higher levels
3163aa5d6bedSChris Mason  *
316474123bd7SChris Mason  */
3165b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
31665f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
3167be0e5c09SChris Mason {
3168be0e5c09SChris Mason 	int i;
31695f39d397SChris Mason 	struct extent_buffer *t;
31700e82bcfeSDavid Sterba 	int ret;
31715f39d397SChris Mason 
3172234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
3173be0e5c09SChris Mason 		int tslot = path->slots[i];
31740e82bcfeSDavid Sterba 
3175eb60ceacSChris Mason 		if (!path->nodes[i])
3176be0e5c09SChris Mason 			break;
31775f39d397SChris Mason 		t = path->nodes[i];
31780e82bcfeSDavid Sterba 		ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
31790e82bcfeSDavid Sterba 				GFP_ATOMIC);
31800e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
31815f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
3182d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
3183be0e5c09SChris Mason 		if (tslot != 0)
3184be0e5c09SChris Mason 			break;
3185be0e5c09SChris Mason 	}
3186be0e5c09SChris Mason }
3187be0e5c09SChris Mason 
318874123bd7SChris Mason /*
318931840ae1SZheng Yan  * update item key.
319031840ae1SZheng Yan  *
319131840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
319231840ae1SZheng Yan  * that the new key won't break the order
319331840ae1SZheng Yan  */
3194b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3195b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
3196310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
319731840ae1SZheng Yan {
319831840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
319931840ae1SZheng Yan 	struct extent_buffer *eb;
320031840ae1SZheng Yan 	int slot;
320131840ae1SZheng Yan 
320231840ae1SZheng Yan 	eb = path->nodes[0];
320331840ae1SZheng Yan 	slot = path->slots[0];
320431840ae1SZheng Yan 	if (slot > 0) {
320531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
32067c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
32077c15d410SQu Wenruo 			btrfs_crit(fs_info,
32087c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
32097c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
32107c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
32117c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
32127c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
32137c15d410SQu Wenruo 				   new_key->offset);
32147c15d410SQu Wenruo 			btrfs_print_leaf(eb);
32157c15d410SQu Wenruo 			BUG();
32167c15d410SQu Wenruo 		}
321731840ae1SZheng Yan 	}
321831840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
321931840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
32207c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
32217c15d410SQu Wenruo 			btrfs_crit(fs_info,
32227c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
32237c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
32247c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
32257c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
32267c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
32277c15d410SQu Wenruo 				   new_key->offset);
32287c15d410SQu Wenruo 			btrfs_print_leaf(eb);
32297c15d410SQu Wenruo 			BUG();
32307c15d410SQu Wenruo 		}
323131840ae1SZheng Yan 	}
323231840ae1SZheng Yan 
323331840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
323431840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
323531840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
323631840ae1SZheng Yan 	if (slot == 0)
3237b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
323831840ae1SZheng Yan }
323931840ae1SZheng Yan 
324031840ae1SZheng Yan /*
324174123bd7SChris Mason  * try to push data from one node into the next node left in the
324279f95c82SChris Mason  * tree.
3243aa5d6bedSChris Mason  *
3244aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3245aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
324674123bd7SChris Mason  */
324798ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
32482ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
3249971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
3250be0e5c09SChris Mason {
3251d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3252be0e5c09SChris Mason 	int push_items = 0;
3253bb803951SChris Mason 	int src_nritems;
3254bb803951SChris Mason 	int dst_nritems;
3255aa5d6bedSChris Mason 	int ret = 0;
3256be0e5c09SChris Mason 
32575f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
32585f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
32590b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
32607bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
32617bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
326254aa1f4dSChris Mason 
3263bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
3264971a1f66SChris Mason 		return 1;
3265971a1f66SChris Mason 
3266d397712bSChris Mason 	if (push_items <= 0)
3267be0e5c09SChris Mason 		return 1;
3268be0e5c09SChris Mason 
3269bce4eae9SChris Mason 	if (empty) {
3270971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
3271bce4eae9SChris Mason 		if (push_items < src_nritems) {
3272bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
3273bce4eae9SChris Mason 			 * we aren't going to empty it
3274bce4eae9SChris Mason 			 */
3275bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
3276bce4eae9SChris Mason 				if (push_items <= 8)
3277bce4eae9SChris Mason 					return 1;
3278bce4eae9SChris Mason 				push_items -= 8;
3279bce4eae9SChris Mason 			}
3280bce4eae9SChris Mason 		}
3281bce4eae9SChris Mason 	} else
3282bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
328379f95c82SChris Mason 
3284ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
32855de865eeSFilipe David Borba Manana 	if (ret) {
328666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
32875de865eeSFilipe David Borba Manana 		return ret;
32885de865eeSFilipe David Borba Manana 	}
32895f39d397SChris Mason 	copy_extent_buffer(dst, src,
32905f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
32915f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
3292123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
32935f39d397SChris Mason 
3294bb803951SChris Mason 	if (push_items < src_nritems) {
329557911b8bSJan Schmidt 		/*
3296bf1d3425SDavid Sterba 		 * Don't call tree_mod_log_insert_move here, key removal was
3297bf1d3425SDavid Sterba 		 * already fully logged by tree_mod_log_eb_copy above.
329857911b8bSJan Schmidt 		 */
32995f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
33005f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
3301e2fa7227SChris Mason 				      (src_nritems - push_items) *
3302123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
3303bb803951SChris Mason 	}
33045f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
33055f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
33065f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
33075f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
330831840ae1SZheng Yan 
3309bb803951SChris Mason 	return ret;
3310be0e5c09SChris Mason }
3311be0e5c09SChris Mason 
331297571fd0SChris Mason /*
331379f95c82SChris Mason  * try to push data from one node into the next node right in the
331479f95c82SChris Mason  * tree.
331579f95c82SChris Mason  *
331679f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
331779f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
331879f95c82SChris Mason  *
331979f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
332079f95c82SChris Mason  */
33215f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
33225f39d397SChris Mason 			      struct extent_buffer *dst,
33235f39d397SChris Mason 			      struct extent_buffer *src)
332479f95c82SChris Mason {
332555d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
332679f95c82SChris Mason 	int push_items = 0;
332779f95c82SChris Mason 	int max_push;
332879f95c82SChris Mason 	int src_nritems;
332979f95c82SChris Mason 	int dst_nritems;
333079f95c82SChris Mason 	int ret = 0;
333179f95c82SChris Mason 
33327bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
33337bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
33347bb86316SChris Mason 
33355f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
33365f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
33370b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
3338d397712bSChris Mason 	if (push_items <= 0)
333979f95c82SChris Mason 		return 1;
3340bce4eae9SChris Mason 
3341d397712bSChris Mason 	if (src_nritems < 4)
3342bce4eae9SChris Mason 		return 1;
334379f95c82SChris Mason 
334479f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
334579f95c82SChris Mason 	/* don't try to empty the node */
3346d397712bSChris Mason 	if (max_push >= src_nritems)
334779f95c82SChris Mason 		return 1;
3348252c38f0SYan 
334979f95c82SChris Mason 	if (max_push < push_items)
335079f95c82SChris Mason 		push_items = max_push;
335179f95c82SChris Mason 
3352bf1d3425SDavid Sterba 	ret = tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
3353bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
33545f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
33555f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
33565f39d397SChris Mason 				      (dst_nritems) *
33575f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
3358d6025579SChris Mason 
3359ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
3360ed874f0dSDavid Sterba 				   push_items);
33615de865eeSFilipe David Borba Manana 	if (ret) {
336266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
33635de865eeSFilipe David Borba Manana 		return ret;
33645de865eeSFilipe David Borba Manana 	}
33655f39d397SChris Mason 	copy_extent_buffer(dst, src,
33665f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
33675f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
3368123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
336979f95c82SChris Mason 
33705f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
33715f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
337279f95c82SChris Mason 
33735f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
33745f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
337531840ae1SZheng Yan 
337679f95c82SChris Mason 	return ret;
337779f95c82SChris Mason }
337879f95c82SChris Mason 
337979f95c82SChris Mason /*
338097571fd0SChris Mason  * helper function to insert a new root level in the tree.
338197571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
338297571fd0SChris Mason  * point to the existing root
3383aa5d6bedSChris Mason  *
3384aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
338597571fd0SChris Mason  */
3386d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
33875f39d397SChris Mason 			   struct btrfs_root *root,
3388fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
338974123bd7SChris Mason {
33900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
33917bb86316SChris Mason 	u64 lower_gen;
33925f39d397SChris Mason 	struct extent_buffer *lower;
33935f39d397SChris Mason 	struct extent_buffer *c;
3394925baeddSChris Mason 	struct extent_buffer *old;
33955f39d397SChris Mason 	struct btrfs_disk_key lower_key;
3396d9d19a01SDavid Sterba 	int ret;
33975c680ed6SChris Mason 
33985c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
33995c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
34005c680ed6SChris Mason 
34017bb86316SChris Mason 	lower = path->nodes[level-1];
34027bb86316SChris Mason 	if (level == 1)
34037bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
34047bb86316SChris Mason 	else
34057bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
34067bb86316SChris Mason 
3407a6279470SFilipe Manana 	c = alloc_tree_block_no_bg_flush(trans, root, 0, &lower_key, level,
3408a6279470SFilipe Manana 					 root->node->start, 0);
34095f39d397SChris Mason 	if (IS_ERR(c))
34105f39d397SChris Mason 		return PTR_ERR(c);
3411925baeddSChris Mason 
34120b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3413f0486c68SYan, Zheng 
34145f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
34155f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3416db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
34177bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
341831840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
34197bb86316SChris Mason 
34207bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
34215f39d397SChris Mason 
34225f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3423d5719762SChris Mason 
3424925baeddSChris Mason 	old = root->node;
3425d9d19a01SDavid Sterba 	ret = tree_mod_log_insert_root(root->node, c, 0);
3426d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
3427240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3428925baeddSChris Mason 
3429925baeddSChris Mason 	/* the super has an extra ref to root->node */
3430925baeddSChris Mason 	free_extent_buffer(old);
3431925baeddSChris Mason 
34320b86a832SChris Mason 	add_root_to_dirty_list(root);
34335f39d397SChris Mason 	extent_buffer_get(c);
34345f39d397SChris Mason 	path->nodes[level] = c;
343595449a16Schandan 	path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
343674123bd7SChris Mason 	path->slots[level] = 0;
343774123bd7SChris Mason 	return 0;
343874123bd7SChris Mason }
34395c680ed6SChris Mason 
34405c680ed6SChris Mason /*
34415c680ed6SChris Mason  * worker function to insert a single pointer in a node.
34425c680ed6SChris Mason  * the node should have enough room for the pointer already
344397571fd0SChris Mason  *
34445c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
34455c680ed6SChris Mason  * blocknr is the block the key points to.
34465c680ed6SChris Mason  */
3447143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
34486ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
3449143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
3450c3e06965SJan Schmidt 		       int slot, int level)
34515c680ed6SChris Mason {
34525f39d397SChris Mason 	struct extent_buffer *lower;
34535c680ed6SChris Mason 	int nritems;
3454f3ea38daSJan Schmidt 	int ret;
34555c680ed6SChris Mason 
34565c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
3457f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
34585f39d397SChris Mason 	lower = path->nodes[level];
34595f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3460c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
34616ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
346274123bd7SChris Mason 	if (slot != nritems) {
3463bf1d3425SDavid Sterba 		if (level) {
3464bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(lower, slot + 1, slot,
3465a446a979SDavid Sterba 					nritems - slot);
3466bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
3467bf1d3425SDavid Sterba 		}
34685f39d397SChris Mason 		memmove_extent_buffer(lower,
34695f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
34705f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
3471123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
347274123bd7SChris Mason 	}
3473c3e06965SJan Schmidt 	if (level) {
3474e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3475e09c2efeSDavid Sterba 				GFP_NOFS);
3476f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3477f3ea38daSJan Schmidt 	}
34785f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3479db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
348074493f7aSChris Mason 	WARN_ON(trans->transid == 0);
348174493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
34825f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
34835f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
348474123bd7SChris Mason }
348574123bd7SChris Mason 
348697571fd0SChris Mason /*
348797571fd0SChris Mason  * split the node at the specified level in path in two.
348897571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
348997571fd0SChris Mason  *
349097571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
349197571fd0SChris Mason  * left and right, if either one works, it returns right away.
3492aa5d6bedSChris Mason  *
3493aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
349497571fd0SChris Mason  */
3495e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3496e02119d5SChris Mason 			       struct btrfs_root *root,
3497e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3498be0e5c09SChris Mason {
34990b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
35005f39d397SChris Mason 	struct extent_buffer *c;
35015f39d397SChris Mason 	struct extent_buffer *split;
35025f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3503be0e5c09SChris Mason 	int mid;
35045c680ed6SChris Mason 	int ret;
35057518a238SChris Mason 	u32 c_nritems;
3506be0e5c09SChris Mason 
35075f39d397SChris Mason 	c = path->nodes[level];
35087bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
35095f39d397SChris Mason 	if (c == root->node) {
3510d9abbf1cSJan Schmidt 		/*
351190f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
351290f8d62eSJan Schmidt 		 *
3513fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
351490f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
351590f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
351690f8d62eSJan Schmidt 		 * elements below with tree_mod_log_eb_copy. We're holding a
351790f8d62eSJan Schmidt 		 * tree lock on the buffer, which is why we cannot race with
351890f8d62eSJan Schmidt 		 * other tree_mod_log users.
3519d9abbf1cSJan Schmidt 		 */
3520fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
35215c680ed6SChris Mason 		if (ret)
35225c680ed6SChris Mason 			return ret;
3523b3612421SChris Mason 	} else {
3524e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
35255f39d397SChris Mason 		c = path->nodes[level];
35265f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
35270b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3528e66f709bSChris Mason 			return 0;
352954aa1f4dSChris Mason 		if (ret < 0)
353054aa1f4dSChris Mason 			return ret;
35315c680ed6SChris Mason 	}
3532e66f709bSChris Mason 
35335f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
35345d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
35355d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
35367bb86316SChris Mason 
3537a6279470SFilipe Manana 	split = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, level,
3538a6279470SFilipe Manana 					     c->start, 0);
35395f39d397SChris Mason 	if (IS_ERR(split))
35405f39d397SChris Mason 		return PTR_ERR(split);
354154aa1f4dSChris Mason 
35420b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3543bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
35445f39d397SChris Mason 
3545ed874f0dSDavid Sterba 	ret = tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
35465de865eeSFilipe David Borba Manana 	if (ret) {
354766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
35485de865eeSFilipe David Borba Manana 		return ret;
35495de865eeSFilipe David Borba Manana 	}
35505f39d397SChris Mason 	copy_extent_buffer(split, c,
35515f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
35525f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
3553123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
35545f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
35555f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3556aa5d6bedSChris Mason 	ret = 0;
3557aa5d6bedSChris Mason 
35585f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
35595f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
35605f39d397SChris Mason 
35616ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
3562c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3563aa5d6bedSChris Mason 
35645de08d7dSChris Mason 	if (path->slots[level] >= mid) {
35655c680ed6SChris Mason 		path->slots[level] -= mid;
3566925baeddSChris Mason 		btrfs_tree_unlock(c);
35675f39d397SChris Mason 		free_extent_buffer(c);
35685f39d397SChris Mason 		path->nodes[level] = split;
35695c680ed6SChris Mason 		path->slots[level + 1] += 1;
3570eb60ceacSChris Mason 	} else {
3571925baeddSChris Mason 		btrfs_tree_unlock(split);
35725f39d397SChris Mason 		free_extent_buffer(split);
3573be0e5c09SChris Mason 	}
3574aa5d6bedSChris Mason 	return ret;
3575be0e5c09SChris Mason }
3576be0e5c09SChris Mason 
357774123bd7SChris Mason /*
357874123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
357974123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
358074123bd7SChris Mason  * space used both by the item structs and the item data
358174123bd7SChris Mason  */
35825f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3583be0e5c09SChris Mason {
358441be1f3bSJosef Bacik 	struct btrfs_item *start_item;
358541be1f3bSJosef Bacik 	struct btrfs_item *end_item;
358641be1f3bSJosef Bacik 	struct btrfs_map_token token;
3587be0e5c09SChris Mason 	int data_len;
35885f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3589d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3590be0e5c09SChris Mason 
3591be0e5c09SChris Mason 	if (!nr)
3592be0e5c09SChris Mason 		return 0;
3593c82f823cSDavid Sterba 	btrfs_init_map_token(&token, l);
3594dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
3595dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
359641be1f3bSJosef Bacik 	data_len = btrfs_token_item_offset(l, start_item, &token) +
359741be1f3bSJosef Bacik 		btrfs_token_item_size(l, start_item, &token);
359841be1f3bSJosef Bacik 	data_len = data_len - btrfs_token_item_offset(l, end_item, &token);
35990783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3600d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3601be0e5c09SChris Mason 	return data_len;
3602be0e5c09SChris Mason }
3603be0e5c09SChris Mason 
360474123bd7SChris Mason /*
3605d4dbff95SChris Mason  * The space between the end of the leaf items and
3606d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3607d4dbff95SChris Mason  * the leaf has left for both items and data
3608d4dbff95SChris Mason  */
3609e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
3610d4dbff95SChris Mason {
3611e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
36125f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
36135f39d397SChris Mason 	int ret;
36140b246afaSJeff Mahoney 
36150b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
36165f39d397SChris Mason 	if (ret < 0) {
36170b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3618efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3619da17066cSJeff Mahoney 			   ret,
36200b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
36215f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
36225f39d397SChris Mason 	}
36235f39d397SChris Mason 	return ret;
3624d4dbff95SChris Mason }
3625d4dbff95SChris Mason 
362699d8f83cSChris Mason /*
362799d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
362899d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
362999d8f83cSChris Mason  */
3630f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
363144871b1bSChris Mason 				      int data_size, int empty,
363244871b1bSChris Mason 				      struct extent_buffer *right,
363399d8f83cSChris Mason 				      int free_space, u32 left_nritems,
363499d8f83cSChris Mason 				      u32 min_slot)
363500ec4c51SChris Mason {
3636f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
36375f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
363844871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3639cfed81a0SChris Mason 	struct btrfs_map_token token;
36405f39d397SChris Mason 	struct btrfs_disk_key disk_key;
364100ec4c51SChris Mason 	int slot;
364234a38218SChris Mason 	u32 i;
364300ec4c51SChris Mason 	int push_space = 0;
364400ec4c51SChris Mason 	int push_items = 0;
36450783fcfcSChris Mason 	struct btrfs_item *item;
364634a38218SChris Mason 	u32 nr;
36477518a238SChris Mason 	u32 right_nritems;
36485f39d397SChris Mason 	u32 data_end;
3649db94535dSChris Mason 	u32 this_item_size;
365000ec4c51SChris Mason 
365134a38218SChris Mason 	if (empty)
365234a38218SChris Mason 		nr = 0;
365334a38218SChris Mason 	else
365499d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
365534a38218SChris Mason 
365631840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
365787b29b20SYan Zheng 		push_space += data_size;
365831840ae1SZheng Yan 
365944871b1bSChris Mason 	slot = path->slots[1];
366034a38218SChris Mason 	i = left_nritems - 1;
366134a38218SChris Mason 	while (i >= nr) {
3662dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3663db94535dSChris Mason 
366431840ae1SZheng Yan 		if (!empty && push_items > 0) {
366531840ae1SZheng Yan 			if (path->slots[0] > i)
366631840ae1SZheng Yan 				break;
366731840ae1SZheng Yan 			if (path->slots[0] == i) {
3668e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3669e902baacSDavid Sterba 
367031840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
367131840ae1SZheng Yan 					break;
367231840ae1SZheng Yan 			}
367331840ae1SZheng Yan 		}
367431840ae1SZheng Yan 
367500ec4c51SChris Mason 		if (path->slots[0] == i)
367687b29b20SYan Zheng 			push_space += data_size;
3677db94535dSChris Mason 
3678db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
3679db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
368000ec4c51SChris Mason 			break;
368131840ae1SZheng Yan 
368200ec4c51SChris Mason 		push_items++;
3683db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
368434a38218SChris Mason 		if (i == 0)
368534a38218SChris Mason 			break;
368634a38218SChris Mason 		i--;
3687db94535dSChris Mason 	}
36885f39d397SChris Mason 
3689925baeddSChris Mason 	if (push_items == 0)
3690925baeddSChris Mason 		goto out_unlock;
36915f39d397SChris Mason 
36926c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
36935f39d397SChris Mason 
369400ec4c51SChris Mason 	/* push left to right */
36955f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
369634a38218SChris Mason 
36975f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
36988f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
36995f39d397SChris Mason 
370000ec4c51SChris Mason 	/* make room in the right data area */
37018f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
37025f39d397SChris Mason 	memmove_extent_buffer(right,
37033d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
37043d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
37050b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
37065f39d397SChris Mason 
370700ec4c51SChris Mason 	/* copy from the left data area */
37083d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
37090b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
37108f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3711d6025579SChris Mason 		     push_space);
37125f39d397SChris Mason 
37135f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
37145f39d397SChris Mason 			      btrfs_item_nr_offset(0),
37150783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
37165f39d397SChris Mason 
371700ec4c51SChris Mason 	/* copy the items from left to right */
37185f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
37195f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
37200783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
372100ec4c51SChris Mason 
372200ec4c51SChris Mason 	/* update the item pointers */
3723c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
37247518a238SChris Mason 	right_nritems += push_items;
37255f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
37260b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
37277518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
3728dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3729cfed81a0SChris Mason 		push_space -= btrfs_token_item_size(right, item, &token);
3730cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3731db94535dSChris Mason 	}
3732db94535dSChris Mason 
37337518a238SChris Mason 	left_nritems -= push_items;
37345f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
373500ec4c51SChris Mason 
373634a38218SChris Mason 	if (left_nritems)
37375f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3738f0486c68SYan, Zheng 	else
37396a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3740f0486c68SYan, Zheng 
37415f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3742a429e513SChris Mason 
37435f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
37445f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3745d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
374602217ed2SChris Mason 
374700ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
37487518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
37497518a238SChris Mason 		path->slots[0] -= left_nritems;
3750925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
37516a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3752925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
37535f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
37545f39d397SChris Mason 		path->nodes[0] = right;
375500ec4c51SChris Mason 		path->slots[1] += 1;
375600ec4c51SChris Mason 	} else {
3757925baeddSChris Mason 		btrfs_tree_unlock(right);
37585f39d397SChris Mason 		free_extent_buffer(right);
375900ec4c51SChris Mason 	}
376000ec4c51SChris Mason 	return 0;
3761925baeddSChris Mason 
3762925baeddSChris Mason out_unlock:
3763925baeddSChris Mason 	btrfs_tree_unlock(right);
3764925baeddSChris Mason 	free_extent_buffer(right);
3765925baeddSChris Mason 	return 1;
376600ec4c51SChris Mason }
3767925baeddSChris Mason 
376800ec4c51SChris Mason /*
376944871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
377074123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
377144871b1bSChris Mason  *
377244871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
377344871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
377499d8f83cSChris Mason  *
377599d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
377699d8f83cSChris Mason  * push any slot lower than min_slot
377774123bd7SChris Mason  */
377844871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
377999d8f83cSChris Mason 			   *root, struct btrfs_path *path,
378099d8f83cSChris Mason 			   int min_data_size, int data_size,
378199d8f83cSChris Mason 			   int empty, u32 min_slot)
3782be0e5c09SChris Mason {
378344871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
378444871b1bSChris Mason 	struct extent_buffer *right;
378544871b1bSChris Mason 	struct extent_buffer *upper;
378644871b1bSChris Mason 	int slot;
378744871b1bSChris Mason 	int free_space;
378844871b1bSChris Mason 	u32 left_nritems;
378944871b1bSChris Mason 	int ret;
379044871b1bSChris Mason 
379144871b1bSChris Mason 	if (!path->nodes[1])
379244871b1bSChris Mason 		return 1;
379344871b1bSChris Mason 
379444871b1bSChris Mason 	slot = path->slots[1];
379544871b1bSChris Mason 	upper = path->nodes[1];
379644871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
379744871b1bSChris Mason 		return 1;
379844871b1bSChris Mason 
379944871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
380044871b1bSChris Mason 
38014b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3802fb770ae4SLiu Bo 	/*
3803fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3804fb770ae4SLiu Bo 	 * no big deal, just return.
3805fb770ae4SLiu Bo 	 */
3806fb770ae4SLiu Bo 	if (IS_ERR(right))
380791ca338dSTsutomu Itoh 		return 1;
380891ca338dSTsutomu Itoh 
380944871b1bSChris Mason 	btrfs_tree_lock(right);
38108bead258SDavid Sterba 	btrfs_set_lock_blocking_write(right);
381144871b1bSChris Mason 
3812e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
381344871b1bSChris Mason 	if (free_space < data_size)
381444871b1bSChris Mason 		goto out_unlock;
381544871b1bSChris Mason 
381644871b1bSChris Mason 	/* cow and double check */
381744871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
381844871b1bSChris Mason 			      slot + 1, &right);
381944871b1bSChris Mason 	if (ret)
382044871b1bSChris Mason 		goto out_unlock;
382144871b1bSChris Mason 
3822e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
382344871b1bSChris Mason 	if (free_space < data_size)
382444871b1bSChris Mason 		goto out_unlock;
382544871b1bSChris Mason 
382644871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
382744871b1bSChris Mason 	if (left_nritems == 0)
382844871b1bSChris Mason 		goto out_unlock;
382944871b1bSChris Mason 
38302ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
38312ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
38322ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
38332ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
383452042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
38352ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
38362ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
38372ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
38382ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
38392ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
38402ef1fed2SFilipe David Borba Manana 		return 0;
38412ef1fed2SFilipe David Borba Manana 	}
38422ef1fed2SFilipe David Borba Manana 
3843f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
384499d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
384544871b1bSChris Mason out_unlock:
384644871b1bSChris Mason 	btrfs_tree_unlock(right);
384744871b1bSChris Mason 	free_extent_buffer(right);
384844871b1bSChris Mason 	return 1;
384944871b1bSChris Mason }
385044871b1bSChris Mason 
385144871b1bSChris Mason /*
385244871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
385344871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
385499d8f83cSChris Mason  *
385599d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
385699d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
385799d8f83cSChris Mason  * items
385844871b1bSChris Mason  */
38598087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
386044871b1bSChris Mason 				     int empty, struct extent_buffer *left,
386199d8f83cSChris Mason 				     int free_space, u32 right_nritems,
386299d8f83cSChris Mason 				     u32 max_slot)
386344871b1bSChris Mason {
38648087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
38655f39d397SChris Mason 	struct btrfs_disk_key disk_key;
38665f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3867be0e5c09SChris Mason 	int i;
3868be0e5c09SChris Mason 	int push_space = 0;
3869be0e5c09SChris Mason 	int push_items = 0;
38700783fcfcSChris Mason 	struct btrfs_item *item;
38717518a238SChris Mason 	u32 old_left_nritems;
387234a38218SChris Mason 	u32 nr;
3873aa5d6bedSChris Mason 	int ret = 0;
3874db94535dSChris Mason 	u32 this_item_size;
3875db94535dSChris Mason 	u32 old_left_item_size;
3876cfed81a0SChris Mason 	struct btrfs_map_token token;
3877cfed81a0SChris Mason 
387834a38218SChris Mason 	if (empty)
387999d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
388034a38218SChris Mason 	else
388199d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
388234a38218SChris Mason 
388334a38218SChris Mason 	for (i = 0; i < nr; i++) {
3884dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3885db94535dSChris Mason 
388631840ae1SZheng Yan 		if (!empty && push_items > 0) {
388731840ae1SZheng Yan 			if (path->slots[0] < i)
388831840ae1SZheng Yan 				break;
388931840ae1SZheng Yan 			if (path->slots[0] == i) {
3890e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3891e902baacSDavid Sterba 
389231840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
389331840ae1SZheng Yan 					break;
389431840ae1SZheng Yan 			}
389531840ae1SZheng Yan 		}
389631840ae1SZheng Yan 
3897be0e5c09SChris Mason 		if (path->slots[0] == i)
389887b29b20SYan Zheng 			push_space += data_size;
3899db94535dSChris Mason 
3900db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
3901db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
3902be0e5c09SChris Mason 			break;
3903db94535dSChris Mason 
3904be0e5c09SChris Mason 		push_items++;
3905db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
3906be0e5c09SChris Mason 	}
3907db94535dSChris Mason 
3908be0e5c09SChris Mason 	if (push_items == 0) {
3909925baeddSChris Mason 		ret = 1;
3910925baeddSChris Mason 		goto out;
3911be0e5c09SChris Mason 	}
3912fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
39135f39d397SChris Mason 
3914be0e5c09SChris Mason 	/* push data from right to left */
39155f39d397SChris Mason 	copy_extent_buffer(left, right,
39165f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
39175f39d397SChris Mason 			   btrfs_item_nr_offset(0),
39185f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
39195f39d397SChris Mason 
39200b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
39215f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
39225f39d397SChris Mason 
39233d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
39248f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
39253d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
39265f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
3927be0e5c09SChris Mason 		     push_space);
39285f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
392987b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3930eb60ceacSChris Mason 
3931c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
3932db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
3933be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
39345f39d397SChris Mason 		u32 ioff;
3935db94535dSChris Mason 
3936dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3937db94535dSChris Mason 
3938cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(left, item, &token);
3939cfed81a0SChris Mason 		btrfs_set_token_item_offset(left, item,
39400b246afaSJeff Mahoney 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size),
3941cfed81a0SChris Mason 		      &token);
3942be0e5c09SChris Mason 	}
39435f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3944be0e5c09SChris Mason 
3945be0e5c09SChris Mason 	/* fixup right node */
394631b1a2bdSJulia Lawall 	if (push_items > right_nritems)
394731b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3948d397712bSChris Mason 		       right_nritems);
394934a38218SChris Mason 
395034a38218SChris Mason 	if (push_items < right_nritems) {
39515f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
39528f881e8cSDavid Sterba 						  leaf_data_end(right);
39533d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
39540b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
39553d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
39568f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
39575f39d397SChris Mason 
39585f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
39595f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
39605f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
39610783fcfcSChris Mason 			     sizeof(struct btrfs_item));
396234a38218SChris Mason 	}
3963c82f823cSDavid Sterba 
3964c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3965eef1c494SYan 	right_nritems -= push_items;
3966eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
39670b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
39685f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
3969dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3970db94535dSChris Mason 
3971cfed81a0SChris Mason 		push_space = push_space - btrfs_token_item_size(right,
3972cfed81a0SChris Mason 								item, &token);
3973cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item, push_space, &token);
3974db94535dSChris Mason 	}
3975eb60ceacSChris Mason 
39765f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
397734a38218SChris Mason 	if (right_nritems)
39785f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3979f0486c68SYan, Zheng 	else
39806a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3981098f59c2SChris Mason 
39825f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3983b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3984be0e5c09SChris Mason 
3985be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3986be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3987be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3988925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
39895f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
39905f39d397SChris Mason 		path->nodes[0] = left;
3991be0e5c09SChris Mason 		path->slots[1] -= 1;
3992be0e5c09SChris Mason 	} else {
3993925baeddSChris Mason 		btrfs_tree_unlock(left);
39945f39d397SChris Mason 		free_extent_buffer(left);
3995be0e5c09SChris Mason 		path->slots[0] -= push_items;
3996be0e5c09SChris Mason 	}
3997eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3998aa5d6bedSChris Mason 	return ret;
3999925baeddSChris Mason out:
4000925baeddSChris Mason 	btrfs_tree_unlock(left);
4001925baeddSChris Mason 	free_extent_buffer(left);
4002925baeddSChris Mason 	return ret;
4003be0e5c09SChris Mason }
4004be0e5c09SChris Mason 
400574123bd7SChris Mason /*
400644871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
400744871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
400899d8f83cSChris Mason  *
400999d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
401099d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
401199d8f83cSChris Mason  * items
401244871b1bSChris Mason  */
401344871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
401499d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
401599d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
401644871b1bSChris Mason {
401744871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
401844871b1bSChris Mason 	struct extent_buffer *left;
401944871b1bSChris Mason 	int slot;
402044871b1bSChris Mason 	int free_space;
402144871b1bSChris Mason 	u32 right_nritems;
402244871b1bSChris Mason 	int ret = 0;
402344871b1bSChris Mason 
402444871b1bSChris Mason 	slot = path->slots[1];
402544871b1bSChris Mason 	if (slot == 0)
402644871b1bSChris Mason 		return 1;
402744871b1bSChris Mason 	if (!path->nodes[1])
402844871b1bSChris Mason 		return 1;
402944871b1bSChris Mason 
403044871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
403144871b1bSChris Mason 	if (right_nritems == 0)
403244871b1bSChris Mason 		return 1;
403344871b1bSChris Mason 
403444871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
403544871b1bSChris Mason 
40364b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
4037fb770ae4SLiu Bo 	/*
4038fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
4039fb770ae4SLiu Bo 	 * no big deal, just return.
4040fb770ae4SLiu Bo 	 */
4041fb770ae4SLiu Bo 	if (IS_ERR(left))
404291ca338dSTsutomu Itoh 		return 1;
404391ca338dSTsutomu Itoh 
404444871b1bSChris Mason 	btrfs_tree_lock(left);
40458bead258SDavid Sterba 	btrfs_set_lock_blocking_write(left);
404644871b1bSChris Mason 
4047e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
404844871b1bSChris Mason 	if (free_space < data_size) {
404944871b1bSChris Mason 		ret = 1;
405044871b1bSChris Mason 		goto out;
405144871b1bSChris Mason 	}
405244871b1bSChris Mason 
405344871b1bSChris Mason 	/* cow and double check */
405444871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
405544871b1bSChris Mason 			      path->nodes[1], slot - 1, &left);
405644871b1bSChris Mason 	if (ret) {
405744871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
405879787eaaSJeff Mahoney 		if (ret == -ENOSPC)
405944871b1bSChris Mason 			ret = 1;
406044871b1bSChris Mason 		goto out;
406144871b1bSChris Mason 	}
406244871b1bSChris Mason 
4063e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
406444871b1bSChris Mason 	if (free_space < data_size) {
406544871b1bSChris Mason 		ret = 1;
406644871b1bSChris Mason 		goto out;
406744871b1bSChris Mason 	}
406844871b1bSChris Mason 
40698087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
407099d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
407199d8f83cSChris Mason 			       max_slot);
407244871b1bSChris Mason out:
407344871b1bSChris Mason 	btrfs_tree_unlock(left);
407444871b1bSChris Mason 	free_extent_buffer(left);
407544871b1bSChris Mason 	return ret;
407644871b1bSChris Mason }
407744871b1bSChris Mason 
407844871b1bSChris Mason /*
407974123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
408074123bd7SChris Mason  * available for the resulting leaf level of the path.
408174123bd7SChris Mason  */
4082143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
408344871b1bSChris Mason 				    struct btrfs_path *path,
408444871b1bSChris Mason 				    struct extent_buffer *l,
408544871b1bSChris Mason 				    struct extent_buffer *right,
408644871b1bSChris Mason 				    int slot, int mid, int nritems)
4087be0e5c09SChris Mason {
408894f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
4089be0e5c09SChris Mason 	int data_copy_size;
4090be0e5c09SChris Mason 	int rt_data_off;
4091be0e5c09SChris Mason 	int i;
4092d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
4093cfed81a0SChris Mason 	struct btrfs_map_token token;
4094cfed81a0SChris Mason 
40955f39d397SChris Mason 	nritems = nritems - mid;
40965f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
40978f881e8cSDavid Sterba 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
40985f39d397SChris Mason 
40995f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
41005f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
41015f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
41025f39d397SChris Mason 
41035f39d397SChris Mason 	copy_extent_buffer(right, l,
41043d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
41053d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
41068f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
410774123bd7SChris Mason 
41080b246afaSJeff Mahoney 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
41095f39d397SChris Mason 
4110c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
41115f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
4112dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
4113db94535dSChris Mason 		u32 ioff;
4114db94535dSChris Mason 
4115cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(right, item, &token);
4116cfed81a0SChris Mason 		btrfs_set_token_item_offset(right, item,
4117cfed81a0SChris Mason 					    ioff + rt_data_off, &token);
41180783fcfcSChris Mason 	}
411974123bd7SChris Mason 
41205f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
41215f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
41226ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
41235f39d397SChris Mason 
41245f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
41255f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
4126eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
41275f39d397SChris Mason 
4128be0e5c09SChris Mason 	if (mid <= slot) {
4129925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
41305f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
41315f39d397SChris Mason 		path->nodes[0] = right;
4132be0e5c09SChris Mason 		path->slots[0] -= mid;
4133be0e5c09SChris Mason 		path->slots[1] += 1;
4134925baeddSChris Mason 	} else {
4135925baeddSChris Mason 		btrfs_tree_unlock(right);
41365f39d397SChris Mason 		free_extent_buffer(right);
4137925baeddSChris Mason 	}
41385f39d397SChris Mason 
4139eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
414044871b1bSChris Mason }
414144871b1bSChris Mason 
414244871b1bSChris Mason /*
414399d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
414499d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
414599d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
414699d8f83cSChris Mason  *          A                 B                 C
414799d8f83cSChris Mason  *
414899d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
414999d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
415099d8f83cSChris Mason  * completely.
415199d8f83cSChris Mason  */
415299d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
415399d8f83cSChris Mason 					  struct btrfs_root *root,
415499d8f83cSChris Mason 					  struct btrfs_path *path,
415599d8f83cSChris Mason 					  int data_size)
415699d8f83cSChris Mason {
415799d8f83cSChris Mason 	int ret;
415899d8f83cSChris Mason 	int progress = 0;
415999d8f83cSChris Mason 	int slot;
416099d8f83cSChris Mason 	u32 nritems;
41615a4267caSFilipe David Borba Manana 	int space_needed = data_size;
416299d8f83cSChris Mason 
416399d8f83cSChris Mason 	slot = path->slots[0];
41645a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
4165e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
416699d8f83cSChris Mason 
416799d8f83cSChris Mason 	/*
416899d8f83cSChris Mason 	 * try to push all the items after our slot into the
416999d8f83cSChris Mason 	 * right leaf
417099d8f83cSChris Mason 	 */
41715a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
417299d8f83cSChris Mason 	if (ret < 0)
417399d8f83cSChris Mason 		return ret;
417499d8f83cSChris Mason 
417599d8f83cSChris Mason 	if (ret == 0)
417699d8f83cSChris Mason 		progress++;
417799d8f83cSChris Mason 
417899d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
417999d8f83cSChris Mason 	/*
418099d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
418199d8f83cSChris Mason 	 * we've done so we're done
418299d8f83cSChris Mason 	 */
418399d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
418499d8f83cSChris Mason 		return 0;
418599d8f83cSChris Mason 
4186e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
418799d8f83cSChris Mason 		return 0;
418899d8f83cSChris Mason 
418999d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
419099d8f83cSChris Mason 	slot = path->slots[0];
4191263d3995SFilipe Manana 	space_needed = data_size;
4192263d3995SFilipe Manana 	if (slot > 0)
4193e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
41945a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
419599d8f83cSChris Mason 	if (ret < 0)
419699d8f83cSChris Mason 		return ret;
419799d8f83cSChris Mason 
419899d8f83cSChris Mason 	if (ret == 0)
419999d8f83cSChris Mason 		progress++;
420099d8f83cSChris Mason 
420199d8f83cSChris Mason 	if (progress)
420299d8f83cSChris Mason 		return 0;
420399d8f83cSChris Mason 	return 1;
420499d8f83cSChris Mason }
420599d8f83cSChris Mason 
420699d8f83cSChris Mason /*
420744871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
420844871b1bSChris Mason  * available for the resulting leaf level of the path.
420944871b1bSChris Mason  *
421044871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
421144871b1bSChris Mason  */
421244871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
421344871b1bSChris Mason 			       struct btrfs_root *root,
4214310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
421544871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
421644871b1bSChris Mason 			       int extend)
421744871b1bSChris Mason {
42185d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
421944871b1bSChris Mason 	struct extent_buffer *l;
422044871b1bSChris Mason 	u32 nritems;
422144871b1bSChris Mason 	int mid;
422244871b1bSChris Mason 	int slot;
422344871b1bSChris Mason 	struct extent_buffer *right;
4224b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
422544871b1bSChris Mason 	int ret = 0;
422644871b1bSChris Mason 	int wret;
42275d4f98a2SYan Zheng 	int split;
422844871b1bSChris Mason 	int num_doubles = 0;
422999d8f83cSChris Mason 	int tried_avoid_double = 0;
423044871b1bSChris Mason 
4231a5719521SYan, Zheng 	l = path->nodes[0];
4232a5719521SYan, Zheng 	slot = path->slots[0];
4233a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
42340b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
4235a5719521SYan, Zheng 		return -EOVERFLOW;
4236a5719521SYan, Zheng 
423744871b1bSChris Mason 	/* first try to make some room by pushing left and right */
423833157e05SLiu Bo 	if (data_size && path->nodes[1]) {
42395a4267caSFilipe David Borba Manana 		int space_needed = data_size;
42405a4267caSFilipe David Borba Manana 
42415a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
4242e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
42435a4267caSFilipe David Borba Manana 
42445a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
42455a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
424644871b1bSChris Mason 		if (wret < 0)
424744871b1bSChris Mason 			return wret;
424844871b1bSChris Mason 		if (wret) {
4249263d3995SFilipe Manana 			space_needed = data_size;
4250263d3995SFilipe Manana 			if (slot > 0)
4251e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
42525a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
42535a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
425444871b1bSChris Mason 			if (wret < 0)
425544871b1bSChris Mason 				return wret;
425644871b1bSChris Mason 		}
425744871b1bSChris Mason 		l = path->nodes[0];
425844871b1bSChris Mason 
425944871b1bSChris Mason 		/* did the pushes work? */
4260e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
426144871b1bSChris Mason 			return 0;
426244871b1bSChris Mason 	}
426344871b1bSChris Mason 
426444871b1bSChris Mason 	if (!path->nodes[1]) {
4265fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
426644871b1bSChris Mason 		if (ret)
426744871b1bSChris Mason 			return ret;
426844871b1bSChris Mason 	}
426944871b1bSChris Mason again:
42705d4f98a2SYan Zheng 	split = 1;
427144871b1bSChris Mason 	l = path->nodes[0];
427244871b1bSChris Mason 	slot = path->slots[0];
427344871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
427444871b1bSChris Mason 	mid = (nritems + 1) / 2;
427544871b1bSChris Mason 
42765d4f98a2SYan Zheng 	if (mid <= slot) {
42775d4f98a2SYan Zheng 		if (nritems == 1 ||
42785d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
42790b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42805d4f98a2SYan Zheng 			if (slot >= nritems) {
42815d4f98a2SYan Zheng 				split = 0;
42825d4f98a2SYan Zheng 			} else {
42835d4f98a2SYan Zheng 				mid = slot;
42845d4f98a2SYan Zheng 				if (mid != nritems &&
42855d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
42860b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
428799d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
428899d8f83cSChris Mason 						goto push_for_double;
42895d4f98a2SYan Zheng 					split = 2;
42905d4f98a2SYan Zheng 				}
42915d4f98a2SYan Zheng 			}
42925d4f98a2SYan Zheng 		}
42935d4f98a2SYan Zheng 	} else {
42945d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
42950b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
42965d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
42975d4f98a2SYan Zheng 				split = 0;
42985d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
42995d4f98a2SYan Zheng 				mid = 1;
43005d4f98a2SYan Zheng 			} else {
43015d4f98a2SYan Zheng 				mid = slot;
43025d4f98a2SYan Zheng 				if (mid != nritems &&
43035d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
43040b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
430599d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
430699d8f83cSChris Mason 						goto push_for_double;
43075d4f98a2SYan Zheng 					split = 2;
43085d4f98a2SYan Zheng 				}
43095d4f98a2SYan Zheng 			}
43105d4f98a2SYan Zheng 		}
43115d4f98a2SYan Zheng 	}
43125d4f98a2SYan Zheng 
43135d4f98a2SYan Zheng 	if (split == 0)
43145d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
43155d4f98a2SYan Zheng 	else
43165d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
43175d4f98a2SYan Zheng 
4318a6279470SFilipe Manana 	right = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, 0,
4319a6279470SFilipe Manana 					     l->start, 0);
4320f0486c68SYan, Zheng 	if (IS_ERR(right))
432144871b1bSChris Mason 		return PTR_ERR(right);
4322f0486c68SYan, Zheng 
43230b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
432444871b1bSChris Mason 
43255d4f98a2SYan Zheng 	if (split == 0) {
432644871b1bSChris Mason 		if (mid <= slot) {
432744871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
43286ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
43292ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
433044871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
433144871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
433244871b1bSChris Mason 			path->nodes[0] = right;
433344871b1bSChris Mason 			path->slots[0] = 0;
433444871b1bSChris Mason 			path->slots[1] += 1;
433544871b1bSChris Mason 		} else {
433644871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
43376ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
43382ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
433944871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
434044871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
434144871b1bSChris Mason 			path->nodes[0] = right;
434244871b1bSChris Mason 			path->slots[0] = 0;
4343143bede5SJeff Mahoney 			if (path->slots[1] == 0)
4344b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
43455d4f98a2SYan Zheng 		}
4346196e0249SLiu Bo 		/*
4347196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
4348196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4349196e0249SLiu Bo 		 * the content of ins_len to 'right'.
4350196e0249SLiu Bo 		 */
435144871b1bSChris Mason 		return ret;
435244871b1bSChris Mason 	}
435344871b1bSChris Mason 
435494f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
435544871b1bSChris Mason 
43565d4f98a2SYan Zheng 	if (split == 2) {
4357cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
4358cc0c5538SChris Mason 		num_doubles++;
4359cc0c5538SChris Mason 		goto again;
43603326d1b0SChris Mason 	}
436144871b1bSChris Mason 
4362143bede5SJeff Mahoney 	return 0;
436399d8f83cSChris Mason 
436499d8f83cSChris Mason push_for_double:
436599d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
436699d8f83cSChris Mason 	tried_avoid_double = 1;
4367e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
436899d8f83cSChris Mason 		return 0;
436999d8f83cSChris Mason 	goto again;
4370be0e5c09SChris Mason }
4371be0e5c09SChris Mason 
4372ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4373ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4374ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4375ad48fd75SYan, Zheng {
4376ad48fd75SYan, Zheng 	struct btrfs_key key;
4377ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4378ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4379ad48fd75SYan, Zheng 	u64 extent_len = 0;
4380ad48fd75SYan, Zheng 	u32 item_size;
4381ad48fd75SYan, Zheng 	int ret;
4382ad48fd75SYan, Zheng 
4383ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4384ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4385ad48fd75SYan, Zheng 
4386ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4387ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4388ad48fd75SYan, Zheng 
4389e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
4390ad48fd75SYan, Zheng 		return 0;
4391ad48fd75SYan, Zheng 
4392ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4393ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4394ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4395ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4396ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4397ad48fd75SYan, Zheng 	}
4398b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4399ad48fd75SYan, Zheng 
4400ad48fd75SYan, Zheng 	path->keep_locks = 1;
4401ad48fd75SYan, Zheng 	path->search_for_split = 1;
4402ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4403ad48fd75SYan, Zheng 	path->search_for_split = 0;
4404a8df6fe6SFilipe Manana 	if (ret > 0)
4405a8df6fe6SFilipe Manana 		ret = -EAGAIN;
4406ad48fd75SYan, Zheng 	if (ret < 0)
4407ad48fd75SYan, Zheng 		goto err;
4408ad48fd75SYan, Zheng 
4409ad48fd75SYan, Zheng 	ret = -EAGAIN;
4410ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4411a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
4412a8df6fe6SFilipe Manana 	if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4413ad48fd75SYan, Zheng 		goto err;
4414ad48fd75SYan, Zheng 
4415109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4416e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
4417109f6aefSChris Mason 		goto err;
4418109f6aefSChris Mason 
4419ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4420ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4421ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4422ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4423ad48fd75SYan, Zheng 			goto err;
4424ad48fd75SYan, Zheng 	}
4425ad48fd75SYan, Zheng 
4426ad48fd75SYan, Zheng 	btrfs_set_path_blocking(path);
4427ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4428f0486c68SYan, Zheng 	if (ret)
4429f0486c68SYan, Zheng 		goto err;
4430ad48fd75SYan, Zheng 
4431ad48fd75SYan, Zheng 	path->keep_locks = 0;
4432ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4433ad48fd75SYan, Zheng 	return 0;
4434ad48fd75SYan, Zheng err:
4435ad48fd75SYan, Zheng 	path->keep_locks = 0;
4436ad48fd75SYan, Zheng 	return ret;
4437ad48fd75SYan, Zheng }
4438ad48fd75SYan, Zheng 
443925263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
4440310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
4441459931ecSChris Mason 			       unsigned long split_offset)
4442459931ecSChris Mason {
4443459931ecSChris Mason 	struct extent_buffer *leaf;
4444459931ecSChris Mason 	struct btrfs_item *item;
4445459931ecSChris Mason 	struct btrfs_item *new_item;
4446459931ecSChris Mason 	int slot;
4447ad48fd75SYan, Zheng 	char *buf;
4448459931ecSChris Mason 	u32 nritems;
4449ad48fd75SYan, Zheng 	u32 item_size;
4450459931ecSChris Mason 	u32 orig_offset;
4451459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4452459931ecSChris Mason 
4453459931ecSChris Mason 	leaf = path->nodes[0];
4454e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
4455b9473439SChris Mason 
4456b4ce94deSChris Mason 	btrfs_set_path_blocking(path);
4457b4ce94deSChris Mason 
4458dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
4459459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
4460459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
4461459931ecSChris Mason 
4462459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4463ad48fd75SYan, Zheng 	if (!buf)
4464ad48fd75SYan, Zheng 		return -ENOMEM;
4465ad48fd75SYan, Zheng 
4466459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4467459931ecSChris Mason 			    path->slots[0]), item_size);
4468ad48fd75SYan, Zheng 
4469459931ecSChris Mason 	slot = path->slots[0] + 1;
4470459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4471459931ecSChris Mason 	if (slot != nritems) {
4472459931ecSChris Mason 		/* shift the items */
4473459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
4474459931ecSChris Mason 				btrfs_item_nr_offset(slot),
4475459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
4476459931ecSChris Mason 	}
4477459931ecSChris Mason 
4478459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4479459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4480459931ecSChris Mason 
4481dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
4482459931ecSChris Mason 
4483459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
4484459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4485459931ecSChris Mason 
4486459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
4487459931ecSChris Mason 			      orig_offset + item_size - split_offset);
4488459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
4489459931ecSChris Mason 
4490459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4491459931ecSChris Mason 
4492459931ecSChris Mason 	/* write the data for the start of the original item */
4493459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4494459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4495459931ecSChris Mason 			    split_offset);
4496459931ecSChris Mason 
4497459931ecSChris Mason 	/* write the data for the new item */
4498459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4499459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4500459931ecSChris Mason 			    item_size - split_offset);
4501459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4502459931ecSChris Mason 
4503e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
4504459931ecSChris Mason 	kfree(buf);
4505ad48fd75SYan, Zheng 	return 0;
4506ad48fd75SYan, Zheng }
4507ad48fd75SYan, Zheng 
4508ad48fd75SYan, Zheng /*
4509ad48fd75SYan, Zheng  * This function splits a single item into two items,
4510ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4511ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4512ad48fd75SYan, Zheng  *
4513ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4514ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4515ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4516ad48fd75SYan, Zheng  *
4517ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4518ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4519ad48fd75SYan, Zheng  *
4520ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4521ad48fd75SYan, Zheng  * leaf the entire time.
4522ad48fd75SYan, Zheng  */
4523ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4524ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4525ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4526310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
4527ad48fd75SYan, Zheng 		     unsigned long split_offset)
4528ad48fd75SYan, Zheng {
4529ad48fd75SYan, Zheng 	int ret;
4530ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4531ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4532ad48fd75SYan, Zheng 	if (ret)
4533459931ecSChris Mason 		return ret;
4534ad48fd75SYan, Zheng 
453525263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
4536ad48fd75SYan, Zheng 	return ret;
4537ad48fd75SYan, Zheng }
4538ad48fd75SYan, Zheng 
4539ad48fd75SYan, Zheng /*
4540ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
4541ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
4542ad48fd75SYan, Zheng  * is contiguous with the original item.
4543ad48fd75SYan, Zheng  *
4544ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
4545ad48fd75SYan, Zheng  * leaf the entire time.
4546ad48fd75SYan, Zheng  */
4547ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4548ad48fd75SYan, Zheng 			 struct btrfs_root *root,
4549ad48fd75SYan, Zheng 			 struct btrfs_path *path,
4550310712b2SOmar Sandoval 			 const struct btrfs_key *new_key)
4551ad48fd75SYan, Zheng {
4552ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4553ad48fd75SYan, Zheng 	int ret;
4554ad48fd75SYan, Zheng 	u32 item_size;
4555ad48fd75SYan, Zheng 
4556ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4557ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4558ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4559ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
4560ad48fd75SYan, Zheng 	if (ret)
4561ad48fd75SYan, Zheng 		return ret;
4562ad48fd75SYan, Zheng 
4563ad48fd75SYan, Zheng 	path->slots[0]++;
4564afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, new_key, &item_size,
4565ad48fd75SYan, Zheng 			       item_size, item_size +
4566ad48fd75SYan, Zheng 			       sizeof(struct btrfs_item), 1);
4567ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4568ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
4569ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4570ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4571ad48fd75SYan, Zheng 			     item_size);
4572ad48fd75SYan, Zheng 	return 0;
4573459931ecSChris Mason }
4574459931ecSChris Mason 
4575459931ecSChris Mason /*
4576d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4577d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4578d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4579d352ac68SChris Mason  * the front.
4580d352ac68SChris Mason  */
458178ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
4582b18c6685SChris Mason {
4583b18c6685SChris Mason 	int slot;
45845f39d397SChris Mason 	struct extent_buffer *leaf;
45855f39d397SChris Mason 	struct btrfs_item *item;
4586b18c6685SChris Mason 	u32 nritems;
4587b18c6685SChris Mason 	unsigned int data_end;
4588b18c6685SChris Mason 	unsigned int old_data_start;
4589b18c6685SChris Mason 	unsigned int old_size;
4590b18c6685SChris Mason 	unsigned int size_diff;
4591b18c6685SChris Mason 	int i;
4592cfed81a0SChris Mason 	struct btrfs_map_token token;
4593cfed81a0SChris Mason 
45945f39d397SChris Mason 	leaf = path->nodes[0];
4595179e29e4SChris Mason 	slot = path->slots[0];
4596179e29e4SChris Mason 
4597179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4598179e29e4SChris Mason 	if (old_size == new_size)
4599143bede5SJeff Mahoney 		return;
4600b18c6685SChris Mason 
46015f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46028f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4603b18c6685SChris Mason 
46045f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
4605179e29e4SChris Mason 
4606b18c6685SChris Mason 	size_diff = old_size - new_size;
4607b18c6685SChris Mason 
4608b18c6685SChris Mason 	BUG_ON(slot < 0);
4609b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4610b18c6685SChris Mason 
4611b18c6685SChris Mason 	/*
4612b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4613b18c6685SChris Mason 	 */
4614b18c6685SChris Mason 	/* first correct the data pointers */
4615c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4616b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
46175f39d397SChris Mason 		u32 ioff;
4618dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4619db94535dSChris Mason 
4620cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4621cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4622cfed81a0SChris Mason 					    ioff + size_diff, &token);
4623b18c6685SChris Mason 	}
4624db94535dSChris Mason 
4625b18c6685SChris Mason 	/* shift the data */
4626179e29e4SChris Mason 	if (from_end) {
46273d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46283d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4629b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
4630179e29e4SChris Mason 	} else {
4631179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4632179e29e4SChris Mason 		u64 offset;
4633179e29e4SChris Mason 
4634179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4635179e29e4SChris Mason 
4636179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4637179e29e4SChris Mason 			unsigned long ptr;
4638179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4639179e29e4SChris Mason 
4640179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4641179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4642179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4643179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4644179e29e4SChris Mason 
4645179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4646179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4647179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4648179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4649179e29e4SChris Mason 				      (unsigned long)fi,
46507ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4651179e29e4SChris Mason 			}
4652179e29e4SChris Mason 		}
4653179e29e4SChris Mason 
46543d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
46553d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
4656179e29e4SChris Mason 			      data_end, old_data_start - data_end);
4657179e29e4SChris Mason 
4658179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4659179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4660179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4661179e29e4SChris Mason 		if (slot == 0)
4662b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4663179e29e4SChris Mason 	}
46645f39d397SChris Mason 
4665dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
46665f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
46675f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4668b18c6685SChris Mason 
4669e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4670a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4671b18c6685SChris Mason 		BUG();
46725f39d397SChris Mason 	}
4673b18c6685SChris Mason }
4674b18c6685SChris Mason 
4675d352ac68SChris Mason /*
46768f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4677d352ac68SChris Mason  */
4678c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
46796567e837SChris Mason {
46806567e837SChris Mason 	int slot;
46815f39d397SChris Mason 	struct extent_buffer *leaf;
46825f39d397SChris Mason 	struct btrfs_item *item;
46836567e837SChris Mason 	u32 nritems;
46846567e837SChris Mason 	unsigned int data_end;
46856567e837SChris Mason 	unsigned int old_data;
46866567e837SChris Mason 	unsigned int old_size;
46876567e837SChris Mason 	int i;
4688cfed81a0SChris Mason 	struct btrfs_map_token token;
4689cfed81a0SChris Mason 
46905f39d397SChris Mason 	leaf = path->nodes[0];
46916567e837SChris Mason 
46925f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
46938f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
46946567e837SChris Mason 
4695e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4696a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
46976567e837SChris Mason 		BUG();
46985f39d397SChris Mason 	}
46996567e837SChris Mason 	slot = path->slots[0];
47005f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
47016567e837SChris Mason 
47026567e837SChris Mason 	BUG_ON(slot < 0);
47033326d1b0SChris Mason 	if (slot >= nritems) {
4704a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4705c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4706d397712bSChris Mason 			   slot, nritems);
4707290342f6SArnd Bergmann 		BUG();
47083326d1b0SChris Mason 	}
47096567e837SChris Mason 
47106567e837SChris Mason 	/*
47116567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
47126567e837SChris Mason 	 */
47136567e837SChris Mason 	/* first correct the data pointers */
4714c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
47156567e837SChris Mason 	for (i = slot; i < nritems; i++) {
47165f39d397SChris Mason 		u32 ioff;
4717dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
4718db94535dSChris Mason 
4719cfed81a0SChris Mason 		ioff = btrfs_token_item_offset(leaf, item, &token);
4720cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4721cfed81a0SChris Mason 					    ioff - data_size, &token);
47226567e837SChris Mason 	}
47235f39d397SChris Mason 
47246567e837SChris Mason 	/* shift the data */
47253d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
47263d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
47276567e837SChris Mason 		      data_end, old_data - data_end);
47285f39d397SChris Mason 
47296567e837SChris Mason 	data_end = old_data;
47305f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
4731dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
47325f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
47335f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
47346567e837SChris Mason 
4735e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4736a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47376567e837SChris Mason 		BUG();
47385f39d397SChris Mason 	}
47396567e837SChris Mason }
47406567e837SChris Mason 
474174123bd7SChris Mason /*
474244871b1bSChris Mason  * this is a helper for btrfs_insert_empty_items, the main goal here is
474344871b1bSChris Mason  * to save stack depth by doing the bulk of the work in a function
474444871b1bSChris Mason  * that doesn't call btrfs_search_slot
474574123bd7SChris Mason  */
4746afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4747310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
474844871b1bSChris Mason 			    u32 total_data, u32 total_size, int nr)
4749be0e5c09SChris Mason {
47500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
47515f39d397SChris Mason 	struct btrfs_item *item;
47529c58309dSChris Mason 	int i;
47537518a238SChris Mason 	u32 nritems;
4754be0e5c09SChris Mason 	unsigned int data_end;
4755e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
475644871b1bSChris Mason 	struct extent_buffer *leaf;
475744871b1bSChris Mason 	int slot;
4758cfed81a0SChris Mason 	struct btrfs_map_token token;
4759cfed81a0SChris Mason 
476024cdc847SFilipe Manana 	if (path->slots[0] == 0) {
476124cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
4762b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
476324cdc847SFilipe Manana 	}
476424cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
476524cdc847SFilipe Manana 
47665f39d397SChris Mason 	leaf = path->nodes[0];
476744871b1bSChris Mason 	slot = path->slots[0];
476874123bd7SChris Mason 
47695f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
47708f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4771eb60ceacSChris Mason 
4772e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4773a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
47740b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4775e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4776be0e5c09SChris Mason 		BUG();
4777d4dbff95SChris Mason 	}
47785f39d397SChris Mason 
4779c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4780be0e5c09SChris Mason 	if (slot != nritems) {
47815f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
4782be0e5c09SChris Mason 
47835f39d397SChris Mason 		if (old_data < data_end) {
4784a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
47850b246afaSJeff Mahoney 			btrfs_crit(fs_info, "slot %d old_data %d data_end %d",
47865f39d397SChris Mason 				   slot, old_data, data_end);
4787290342f6SArnd Bergmann 			BUG();
47885f39d397SChris Mason 		}
4789be0e5c09SChris Mason 		/*
4790be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4791be0e5c09SChris Mason 		 */
4792be0e5c09SChris Mason 		/* first correct the data pointers */
47930783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
47945f39d397SChris Mason 			u32 ioff;
4795db94535dSChris Mason 
4796dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4797cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
4798cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
4799cfed81a0SChris Mason 						    ioff - total_data, &token);
48000783fcfcSChris Mason 		}
4801be0e5c09SChris Mason 		/* shift the items */
48029c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
48035f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
48040783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4805be0e5c09SChris Mason 
4806be0e5c09SChris Mason 		/* shift the data */
48073d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
48083d9ec8c4SNikolay Borisov 			      data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
4809be0e5c09SChris Mason 			      data_end, old_data - data_end);
4810be0e5c09SChris Mason 		data_end = old_data;
4811be0e5c09SChris Mason 	}
48125f39d397SChris Mason 
481362e2749eSChris Mason 	/* setup the item for the new data */
48149c58309dSChris Mason 	for (i = 0; i < nr; i++) {
48159c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
48169c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4817dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
4818cfed81a0SChris Mason 		btrfs_set_token_item_offset(leaf, item,
4819cfed81a0SChris Mason 					    data_end - data_size[i], &token);
48209c58309dSChris Mason 		data_end -= data_size[i];
4821cfed81a0SChris Mason 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
48229c58309dSChris Mason 	}
482344871b1bSChris Mason 
48249c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
4825b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4826aa5d6bedSChris Mason 
4827e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4828a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4829be0e5c09SChris Mason 		BUG();
48305f39d397SChris Mason 	}
483144871b1bSChris Mason }
483244871b1bSChris Mason 
483344871b1bSChris Mason /*
483444871b1bSChris Mason  * Given a key and some data, insert items into the tree.
483544871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
483644871b1bSChris Mason  */
483744871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
483844871b1bSChris Mason 			    struct btrfs_root *root,
483944871b1bSChris Mason 			    struct btrfs_path *path,
4840310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
484144871b1bSChris Mason 			    int nr)
484244871b1bSChris Mason {
484344871b1bSChris Mason 	int ret = 0;
484444871b1bSChris Mason 	int slot;
484544871b1bSChris Mason 	int i;
484644871b1bSChris Mason 	u32 total_size = 0;
484744871b1bSChris Mason 	u32 total_data = 0;
484844871b1bSChris Mason 
484944871b1bSChris Mason 	for (i = 0; i < nr; i++)
485044871b1bSChris Mason 		total_data += data_size[i];
485144871b1bSChris Mason 
485244871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
485344871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
485444871b1bSChris Mason 	if (ret == 0)
485544871b1bSChris Mason 		return -EEXIST;
485644871b1bSChris Mason 	if (ret < 0)
4857143bede5SJeff Mahoney 		return ret;
485844871b1bSChris Mason 
485944871b1bSChris Mason 	slot = path->slots[0];
486044871b1bSChris Mason 	BUG_ON(slot < 0);
486144871b1bSChris Mason 
4862afe5fea7STsutomu Itoh 	setup_items_for_insert(root, path, cpu_key, data_size,
486344871b1bSChris Mason 			       total_data, total_size, nr);
4864143bede5SJeff Mahoney 	return 0;
486562e2749eSChris Mason }
486662e2749eSChris Mason 
486762e2749eSChris Mason /*
486862e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
486962e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
487062e2749eSChris Mason  */
4871310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4872310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4873310712b2SOmar Sandoval 		      u32 data_size)
487462e2749eSChris Mason {
487562e2749eSChris Mason 	int ret = 0;
48762c90e5d6SChris Mason 	struct btrfs_path *path;
48775f39d397SChris Mason 	struct extent_buffer *leaf;
48785f39d397SChris Mason 	unsigned long ptr;
487962e2749eSChris Mason 
48802c90e5d6SChris Mason 	path = btrfs_alloc_path();
4881db5b493aSTsutomu Itoh 	if (!path)
4882db5b493aSTsutomu Itoh 		return -ENOMEM;
48832c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
488462e2749eSChris Mason 	if (!ret) {
48855f39d397SChris Mason 		leaf = path->nodes[0];
48865f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
48875f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
48885f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
488962e2749eSChris Mason 	}
48902c90e5d6SChris Mason 	btrfs_free_path(path);
4891aa5d6bedSChris Mason 	return ret;
4892be0e5c09SChris Mason }
4893be0e5c09SChris Mason 
489474123bd7SChris Mason /*
48955de08d7dSChris Mason  * delete the pointer from a given node.
489674123bd7SChris Mason  *
4897d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4898d352ac68SChris Mason  * empty a node.
489974123bd7SChris Mason  */
4900afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4901afe5fea7STsutomu Itoh 		    int level, int slot)
4902be0e5c09SChris Mason {
49035f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
49047518a238SChris Mason 	u32 nritems;
4905f3ea38daSJan Schmidt 	int ret;
4906be0e5c09SChris Mason 
49075f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4908be0e5c09SChris Mason 	if (slot != nritems - 1) {
4909bf1d3425SDavid Sterba 		if (level) {
4910bf1d3425SDavid Sterba 			ret = tree_mod_log_insert_move(parent, slot, slot + 1,
4911a446a979SDavid Sterba 					nritems - slot - 1);
4912bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4913bf1d3425SDavid Sterba 		}
49145f39d397SChris Mason 		memmove_extent_buffer(parent,
49155f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
49165f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4917d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4918d6025579SChris Mason 			      (nritems - slot - 1));
491957ba86c0SChris Mason 	} else if (level) {
4920e09c2efeSDavid Sterba 		ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4921e09c2efeSDavid Sterba 				GFP_NOFS);
492257ba86c0SChris Mason 		BUG_ON(ret < 0);
4923be0e5c09SChris Mason 	}
4924f3ea38daSJan Schmidt 
49257518a238SChris Mason 	nritems--;
49265f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
49277518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
49285f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4929eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
49305f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4931bb803951SChris Mason 	} else if (slot == 0) {
49325f39d397SChris Mason 		struct btrfs_disk_key disk_key;
49335f39d397SChris Mason 
49345f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4935b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4936be0e5c09SChris Mason 	}
4937d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4938be0e5c09SChris Mason }
4939be0e5c09SChris Mason 
494074123bd7SChris Mason /*
4941323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
49425d4f98a2SYan Zheng  * path->nodes[1].
4943323ac95bSChris Mason  *
4944323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4945323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4946323ac95bSChris Mason  *
4947323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4948323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4949323ac95bSChris Mason  */
4950143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4951323ac95bSChris Mason 				    struct btrfs_root *root,
49525d4f98a2SYan Zheng 				    struct btrfs_path *path,
49535d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4954323ac95bSChris Mason {
49555d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4956afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4957323ac95bSChris Mason 
49584d081c41SChris Mason 	/*
49594d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
49604d081c41SChris Mason 	 * aren't holding any locks when we call it
49614d081c41SChris Mason 	 */
49624d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
49634d081c41SChris Mason 
4964f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4965f0486c68SYan, Zheng 
49663083ee2eSJosef Bacik 	extent_buffer_get(leaf);
49675581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
49683083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4969323ac95bSChris Mason }
4970323ac95bSChris Mason /*
497174123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
497274123bd7SChris Mason  * the leaf, remove it from the tree
497374123bd7SChris Mason  */
497485e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
497585e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4976be0e5c09SChris Mason {
49770b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
49785f39d397SChris Mason 	struct extent_buffer *leaf;
49795f39d397SChris Mason 	struct btrfs_item *item;
4980ce0eac2aSAlexandru Moise 	u32 last_off;
4981ce0eac2aSAlexandru Moise 	u32 dsize = 0;
4982aa5d6bedSChris Mason 	int ret = 0;
4983aa5d6bedSChris Mason 	int wret;
498485e21bacSChris Mason 	int i;
49857518a238SChris Mason 	u32 nritems;
4986be0e5c09SChris Mason 
49875f39d397SChris Mason 	leaf = path->nodes[0];
498885e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
498985e21bacSChris Mason 
499085e21bacSChris Mason 	for (i = 0; i < nr; i++)
499185e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
499285e21bacSChris Mason 
49935f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4994be0e5c09SChris Mason 
499585e21bacSChris Mason 	if (slot + nr != nritems) {
49968f881e8cSDavid Sterba 		int data_end = leaf_data_end(leaf);
4997c82f823cSDavid Sterba 		struct btrfs_map_token token;
49985f39d397SChris Mason 
49993d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
5000d6025579SChris Mason 			      data_end + dsize,
50013d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
500285e21bacSChris Mason 			      last_off - data_end);
50035f39d397SChris Mason 
5004c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
500585e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
50065f39d397SChris Mason 			u32 ioff;
5007db94535dSChris Mason 
5008dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
5009cfed81a0SChris Mason 			ioff = btrfs_token_item_offset(leaf, item, &token);
5010cfed81a0SChris Mason 			btrfs_set_token_item_offset(leaf, item,
5011cfed81a0SChris Mason 						    ioff + dsize, &token);
50120783fcfcSChris Mason 		}
5013db94535dSChris Mason 
50145f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
501585e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
50160783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
501785e21bacSChris Mason 			      (nritems - slot - nr));
5018be0e5c09SChris Mason 	}
501985e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
502085e21bacSChris Mason 	nritems -= nr;
50215f39d397SChris Mason 
502274123bd7SChris Mason 	/* delete the leaf if we've emptied it */
50237518a238SChris Mason 	if (nritems == 0) {
50245f39d397SChris Mason 		if (leaf == root->node) {
50255f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
50269a8dd150SChris Mason 		} else {
5027f0486c68SYan, Zheng 			btrfs_set_path_blocking(path);
50286a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
5029143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
50309a8dd150SChris Mason 		}
5031be0e5c09SChris Mason 	} else {
50327518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
5033aa5d6bedSChris Mason 		if (slot == 0) {
50345f39d397SChris Mason 			struct btrfs_disk_key disk_key;
50355f39d397SChris Mason 
50365f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
5037b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
5038aa5d6bedSChris Mason 		}
5039aa5d6bedSChris Mason 
504074123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
50410b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
5042be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
5043be0e5c09SChris Mason 			 * make sure the path still points to our leaf
5044be0e5c09SChris Mason 			 * for possible call to del_ptr below
5045be0e5c09SChris Mason 			 */
50464920c9acSChris Mason 			slot = path->slots[1];
50475f39d397SChris Mason 			extent_buffer_get(leaf);
50485f39d397SChris Mason 
5049b9473439SChris Mason 			btrfs_set_path_blocking(path);
505099d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
505199d8f83cSChris Mason 					      1, (u32)-1);
505254aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
5053aa5d6bedSChris Mason 				ret = wret;
50545f39d397SChris Mason 
50555f39d397SChris Mason 			if (path->nodes[0] == leaf &&
50565f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
505799d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
505899d8f83cSChris Mason 						       1, 1, 0);
505954aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
5060aa5d6bedSChris Mason 					ret = wret;
5061aa5d6bedSChris Mason 			}
50625f39d397SChris Mason 
50635f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
5064323ac95bSChris Mason 				path->slots[1] = slot;
5065143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
50665f39d397SChris Mason 				free_extent_buffer(leaf);
5067143bede5SJeff Mahoney 				ret = 0;
50685de08d7dSChris Mason 			} else {
5069925baeddSChris Mason 				/* if we're still in the path, make sure
5070925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
5071925baeddSChris Mason 				 * push_leaf functions must have already
5072925baeddSChris Mason 				 * dirtied this buffer
5073925baeddSChris Mason 				 */
5074925baeddSChris Mason 				if (path->nodes[0] == leaf)
50755f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
50765f39d397SChris Mason 				free_extent_buffer(leaf);
5077be0e5c09SChris Mason 			}
5078d5719762SChris Mason 		} else {
50795f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
5080be0e5c09SChris Mason 		}
50819a8dd150SChris Mason 	}
5082aa5d6bedSChris Mason 	return ret;
50839a8dd150SChris Mason }
50849a8dd150SChris Mason 
508597571fd0SChris Mason /*
5086925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
50877bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
50887bb86316SChris Mason  * returns < 0 on io errors.
5089d352ac68SChris Mason  *
5090d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
5091d352ac68SChris Mason  * time you call it.
50927bb86316SChris Mason  */
509316e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
50947bb86316SChris Mason {
5095925baeddSChris Mason 	struct btrfs_key key;
5096925baeddSChris Mason 	struct btrfs_disk_key found_key;
5097925baeddSChris Mason 	int ret;
50987bb86316SChris Mason 
5099925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
5100925baeddSChris Mason 
5101e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
5102925baeddSChris Mason 		key.offset--;
5103e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
5104925baeddSChris Mason 		key.type--;
5105e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5106e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
5107925baeddSChris Mason 		key.objectid--;
5108e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
5109e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
5110e8b0d724SFilipe David Borba Manana 	} else {
51117bb86316SChris Mason 		return 1;
5112e8b0d724SFilipe David Borba Manana 	}
51137bb86316SChris Mason 
5114b3b4aa74SDavid Sterba 	btrfs_release_path(path);
5115925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5116925baeddSChris Mason 	if (ret < 0)
5117925baeddSChris Mason 		return ret;
5118925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
5119925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
5120337c6f68SFilipe Manana 	/*
5121337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
5122337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
5123337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
5124337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
5125337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
5126337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
5127337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
5128337c6f68SFilipe Manana 	 * the previous key we computed above.
5129337c6f68SFilipe Manana 	 */
5130337c6f68SFilipe Manana 	if (ret <= 0)
51317bb86316SChris Mason 		return 0;
5132925baeddSChris Mason 	return 1;
51337bb86316SChris Mason }
51347bb86316SChris Mason 
51353f157a2fSChris Mason /*
51363f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
5137de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
5138de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
51393f157a2fSChris Mason  *
51403f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
51413f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
51423f157a2fSChris Mason  * key and get a writable path.
51433f157a2fSChris Mason  *
51443f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
51453f157a2fSChris Mason  * of the tree.
51463f157a2fSChris Mason  *
5147d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
5148d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
5149d352ac68SChris Mason  * skipped over (without reading them).
5150d352ac68SChris Mason  *
51513f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
51523f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
51533f157a2fSChris Mason  */
51543f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
5155de78b51aSEric Sandeen 			 struct btrfs_path *path,
51563f157a2fSChris Mason 			 u64 min_trans)
51573f157a2fSChris Mason {
51583f157a2fSChris Mason 	struct extent_buffer *cur;
51593f157a2fSChris Mason 	struct btrfs_key found_key;
51603f157a2fSChris Mason 	int slot;
51619652480bSYan 	int sret;
51623f157a2fSChris Mason 	u32 nritems;
51633f157a2fSChris Mason 	int level;
51643f157a2fSChris Mason 	int ret = 1;
5165f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
51663f157a2fSChris Mason 
5167f98de9b9SFilipe Manana 	path->keep_locks = 1;
51683f157a2fSChris Mason again:
5169bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
51703f157a2fSChris Mason 	level = btrfs_header_level(cur);
5171e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
51723f157a2fSChris Mason 	path->nodes[level] = cur;
5173bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
51743f157a2fSChris Mason 
51753f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
51763f157a2fSChris Mason 		ret = 1;
51773f157a2fSChris Mason 		goto out;
51783f157a2fSChris Mason 	}
51793f157a2fSChris Mason 	while (1) {
51803f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
51813f157a2fSChris Mason 		level = btrfs_header_level(cur);
5182a74b35ecSNikolay Borisov 		sret = btrfs_bin_search(cur, min_key, level, &slot);
5183cbca7d59SFilipe Manana 		if (sret < 0) {
5184cbca7d59SFilipe Manana 			ret = sret;
5185cbca7d59SFilipe Manana 			goto out;
5186cbca7d59SFilipe Manana 		}
51873f157a2fSChris Mason 
5188323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
5189323ac95bSChris Mason 		if (level == path->lowest_level) {
5190e02119d5SChris Mason 			if (slot >= nritems)
5191e02119d5SChris Mason 				goto find_next_key;
51923f157a2fSChris Mason 			ret = 0;
51933f157a2fSChris Mason 			path->slots[level] = slot;
51943f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
51953f157a2fSChris Mason 			goto out;
51963f157a2fSChris Mason 		}
51979652480bSYan 		if (sret && slot > 0)
51989652480bSYan 			slot--;
51993f157a2fSChris Mason 		/*
5200de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
5201de78b51aSEric Sandeen 		 * If it is too old, old, skip to the next one.
52023f157a2fSChris Mason 		 */
52033f157a2fSChris Mason 		while (slot < nritems) {
52043f157a2fSChris Mason 			u64 gen;
5205e02119d5SChris Mason 
52063f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
52073f157a2fSChris Mason 			if (gen < min_trans) {
52083f157a2fSChris Mason 				slot++;
52093f157a2fSChris Mason 				continue;
52103f157a2fSChris Mason 			}
52113f157a2fSChris Mason 			break;
52123f157a2fSChris Mason 		}
5213e02119d5SChris Mason find_next_key:
52143f157a2fSChris Mason 		/*
52153f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
52163f157a2fSChris Mason 		 * and find another one
52173f157a2fSChris Mason 		 */
52183f157a2fSChris Mason 		if (slot >= nritems) {
5219e02119d5SChris Mason 			path->slots[level] = slot;
5220b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
5221e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
5222de78b51aSEric Sandeen 						  min_trans);
5223e02119d5SChris Mason 			if (sret == 0) {
5224b3b4aa74SDavid Sterba 				btrfs_release_path(path);
52253f157a2fSChris Mason 				goto again;
52263f157a2fSChris Mason 			} else {
52273f157a2fSChris Mason 				goto out;
52283f157a2fSChris Mason 			}
52293f157a2fSChris Mason 		}
52303f157a2fSChris Mason 		/* save our key for returning back */
52313f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
52323f157a2fSChris Mason 		path->slots[level] = slot;
52333f157a2fSChris Mason 		if (level == path->lowest_level) {
52343f157a2fSChris Mason 			ret = 0;
52353f157a2fSChris Mason 			goto out;
52363f157a2fSChris Mason 		}
5237b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
52384b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
5239fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
5240fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
5241fb770ae4SLiu Bo 			goto out;
5242fb770ae4SLiu Bo 		}
52433f157a2fSChris Mason 
5244bd681513SChris Mason 		btrfs_tree_read_lock(cur);
5245b4ce94deSChris Mason 
5246bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
52473f157a2fSChris Mason 		path->nodes[level - 1] = cur;
5248f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
52493f157a2fSChris Mason 	}
52503f157a2fSChris Mason out:
5251f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
5252f98de9b9SFilipe Manana 	if (ret == 0) {
5253f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
5254b4ce94deSChris Mason 		btrfs_set_path_blocking(path);
5255f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
5256f98de9b9SFilipe Manana 	}
52573f157a2fSChris Mason 	return ret;
52583f157a2fSChris Mason }
52593f157a2fSChris Mason 
52603f157a2fSChris Mason /*
52613f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
52623f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
5263de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
52643f157a2fSChris Mason  *
52653f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
52663f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
52673f157a2fSChris Mason  *
52683f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
52693f157a2fSChris Mason  * calling this function.
52703f157a2fSChris Mason  */
5271e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
5272de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
5273e7a84565SChris Mason {
5274e7a84565SChris Mason 	int slot;
5275e7a84565SChris Mason 	struct extent_buffer *c;
5276e7a84565SChris Mason 
52776a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
5278e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
5279e7a84565SChris Mason 		if (!path->nodes[level])
5280e7a84565SChris Mason 			return 1;
5281e7a84565SChris Mason 
5282e7a84565SChris Mason 		slot = path->slots[level] + 1;
5283e7a84565SChris Mason 		c = path->nodes[level];
52843f157a2fSChris Mason next:
5285e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
528633c66f43SYan Zheng 			int ret;
528733c66f43SYan Zheng 			int orig_lowest;
528833c66f43SYan Zheng 			struct btrfs_key cur_key;
528933c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
529033c66f43SYan Zheng 			    !path->nodes[level + 1])
5291e7a84565SChris Mason 				return 1;
529233c66f43SYan Zheng 
52936a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
529433c66f43SYan Zheng 				level++;
5295e7a84565SChris Mason 				continue;
5296e7a84565SChris Mason 			}
529733c66f43SYan Zheng 
529833c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
529933c66f43SYan Zheng 			if (level == 0)
530033c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
530133c66f43SYan Zheng 			else
530233c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
530333c66f43SYan Zheng 
530433c66f43SYan Zheng 			orig_lowest = path->lowest_level;
5305b3b4aa74SDavid Sterba 			btrfs_release_path(path);
530633c66f43SYan Zheng 			path->lowest_level = level;
530733c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
530833c66f43SYan Zheng 						0, 0);
530933c66f43SYan Zheng 			path->lowest_level = orig_lowest;
531033c66f43SYan Zheng 			if (ret < 0)
531133c66f43SYan Zheng 				return ret;
531233c66f43SYan Zheng 
531333c66f43SYan Zheng 			c = path->nodes[level];
531433c66f43SYan Zheng 			slot = path->slots[level];
531533c66f43SYan Zheng 			if (ret == 0)
531633c66f43SYan Zheng 				slot++;
531733c66f43SYan Zheng 			goto next;
531833c66f43SYan Zheng 		}
531933c66f43SYan Zheng 
5320e7a84565SChris Mason 		if (level == 0)
5321e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
53223f157a2fSChris Mason 		else {
53233f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
53243f157a2fSChris Mason 
53253f157a2fSChris Mason 			if (gen < min_trans) {
53263f157a2fSChris Mason 				slot++;
53273f157a2fSChris Mason 				goto next;
53283f157a2fSChris Mason 			}
5329e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
53303f157a2fSChris Mason 		}
5331e7a84565SChris Mason 		return 0;
5332e7a84565SChris Mason 	}
5333e7a84565SChris Mason 	return 1;
5334e7a84565SChris Mason }
5335e7a84565SChris Mason 
53367bb86316SChris Mason /*
5337925baeddSChris Mason  * search the tree again to find a leaf with greater keys
53380f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
53390f70abe2SChris Mason  * returns < 0 on io errors.
534097571fd0SChris Mason  */
5341234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
5342d97e63b6SChris Mason {
53433d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
53443d7806ecSJan Schmidt }
53453d7806ecSJan Schmidt 
53463d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
53473d7806ecSJan Schmidt 			u64 time_seq)
53483d7806ecSJan Schmidt {
5349d97e63b6SChris Mason 	int slot;
53508e73f275SChris Mason 	int level;
53515f39d397SChris Mason 	struct extent_buffer *c;
53528e73f275SChris Mason 	struct extent_buffer *next;
5353925baeddSChris Mason 	struct btrfs_key key;
5354925baeddSChris Mason 	u32 nritems;
5355925baeddSChris Mason 	int ret;
53568e73f275SChris Mason 	int old_spinning = path->leave_spinning;
5357bd681513SChris Mason 	int next_rw_lock = 0;
5358925baeddSChris Mason 
5359925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5360d397712bSChris Mason 	if (nritems == 0)
5361925baeddSChris Mason 		return 1;
5362925baeddSChris Mason 
53638e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
53648e73f275SChris Mason again:
53658e73f275SChris Mason 	level = 1;
53668e73f275SChris Mason 	next = NULL;
5367bd681513SChris Mason 	next_rw_lock = 0;
5368b3b4aa74SDavid Sterba 	btrfs_release_path(path);
53698e73f275SChris Mason 
5370a2135011SChris Mason 	path->keep_locks = 1;
53718e73f275SChris Mason 	path->leave_spinning = 1;
53728e73f275SChris Mason 
53733d7806ecSJan Schmidt 	if (time_seq)
53743d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
53753d7806ecSJan Schmidt 	else
5376925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5377925baeddSChris Mason 	path->keep_locks = 0;
5378925baeddSChris Mason 
5379925baeddSChris Mason 	if (ret < 0)
5380925baeddSChris Mason 		return ret;
5381925baeddSChris Mason 
5382a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5383168fd7d2SChris Mason 	/*
5384168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5385168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5386168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5387168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5388168fd7d2SChris Mason 	 */
5389a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5390e457afecSYan Zheng 		if (ret == 0)
5391168fd7d2SChris Mason 			path->slots[0]++;
53928e73f275SChris Mason 		ret = 0;
5393925baeddSChris Mason 		goto done;
5394925baeddSChris Mason 	}
53950b43e04fSLiu Bo 	/*
53960b43e04fSLiu Bo 	 * So the above check misses one case:
53970b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
53980b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
53990b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
54000b43e04fSLiu Bo 	 *
54010b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
54020b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
54030b43e04fSLiu Bo 	 *
54040b43e04fSLiu Bo 	 * And a bit more explanation about this check,
54050b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
54060b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
54070b43e04fSLiu Bo 	 * bigger one.
54080b43e04fSLiu Bo 	 */
54090b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
54100b43e04fSLiu Bo 		ret = 0;
54110b43e04fSLiu Bo 		goto done;
54120b43e04fSLiu Bo 	}
5413d97e63b6SChris Mason 
5414234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
54158e73f275SChris Mason 		if (!path->nodes[level]) {
54168e73f275SChris Mason 			ret = 1;
54178e73f275SChris Mason 			goto done;
54188e73f275SChris Mason 		}
54195f39d397SChris Mason 
5420d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5421d97e63b6SChris Mason 		c = path->nodes[level];
54225f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5423d97e63b6SChris Mason 			level++;
54248e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
54258e73f275SChris Mason 				ret = 1;
54268e73f275SChris Mason 				goto done;
54278e73f275SChris Mason 			}
5428d97e63b6SChris Mason 			continue;
5429d97e63b6SChris Mason 		}
54305f39d397SChris Mason 
5431925baeddSChris Mason 		if (next) {
5432bd681513SChris Mason 			btrfs_tree_unlock_rw(next, next_rw_lock);
54335f39d397SChris Mason 			free_extent_buffer(next);
5434925baeddSChris Mason 		}
54355f39d397SChris Mason 
54368e73f275SChris Mason 		next = c;
5437bd681513SChris Mason 		next_rw_lock = path->locks[level];
5438d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5439cda79c54SDavid Sterba 					    slot, &key);
54408e73f275SChris Mason 		if (ret == -EAGAIN)
54418e73f275SChris Mason 			goto again;
54425f39d397SChris Mason 
544376a05b35SChris Mason 		if (ret < 0) {
5444b3b4aa74SDavid Sterba 			btrfs_release_path(path);
544576a05b35SChris Mason 			goto done;
544676a05b35SChris Mason 		}
544776a05b35SChris Mason 
54485cd57b2cSChris Mason 		if (!path->skip_locking) {
5449bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5450d42244a0SJan Schmidt 			if (!ret && time_seq) {
5451d42244a0SJan Schmidt 				/*
5452d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5453d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5454d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5455d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5456d42244a0SJan Schmidt 				 * on our lock and cycle.
5457d42244a0SJan Schmidt 				 */
5458cf538830SJan Schmidt 				free_extent_buffer(next);
5459d42244a0SJan Schmidt 				btrfs_release_path(path);
5460d42244a0SJan Schmidt 				cond_resched();
5461d42244a0SJan Schmidt 				goto again;
5462d42244a0SJan Schmidt 			}
54638e73f275SChris Mason 			if (!ret) {
54648e73f275SChris Mason 				btrfs_set_path_blocking(path);
5465bd681513SChris Mason 				btrfs_tree_read_lock(next);
54668e73f275SChris Mason 			}
5467bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5468bd681513SChris Mason 		}
5469d97e63b6SChris Mason 		break;
5470d97e63b6SChris Mason 	}
5471d97e63b6SChris Mason 	path->slots[level] = slot;
5472d97e63b6SChris Mason 	while (1) {
5473d97e63b6SChris Mason 		level--;
5474d97e63b6SChris Mason 		c = path->nodes[level];
5475925baeddSChris Mason 		if (path->locks[level])
5476bd681513SChris Mason 			btrfs_tree_unlock_rw(c, path->locks[level]);
54778e73f275SChris Mason 
54785f39d397SChris Mason 		free_extent_buffer(c);
5479d97e63b6SChris Mason 		path->nodes[level] = next;
5480d97e63b6SChris Mason 		path->slots[level] = 0;
5481a74a4b97SChris Mason 		if (!path->skip_locking)
5482bd681513SChris Mason 			path->locks[level] = next_rw_lock;
5483d97e63b6SChris Mason 		if (!level)
5484d97e63b6SChris Mason 			break;
5485b4ce94deSChris Mason 
5486d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5487cda79c54SDavid Sterba 					    0, &key);
54888e73f275SChris Mason 		if (ret == -EAGAIN)
54898e73f275SChris Mason 			goto again;
54908e73f275SChris Mason 
549176a05b35SChris Mason 		if (ret < 0) {
5492b3b4aa74SDavid Sterba 			btrfs_release_path(path);
549376a05b35SChris Mason 			goto done;
549476a05b35SChris Mason 		}
549576a05b35SChris Mason 
54965cd57b2cSChris Mason 		if (!path->skip_locking) {
5497bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
54988e73f275SChris Mason 			if (!ret) {
54998e73f275SChris Mason 				btrfs_set_path_blocking(path);
5500bd681513SChris Mason 				btrfs_tree_read_lock(next);
55018e73f275SChris Mason 			}
5502bd681513SChris Mason 			next_rw_lock = BTRFS_READ_LOCK;
5503bd681513SChris Mason 		}
5504d97e63b6SChris Mason 	}
55058e73f275SChris Mason 	ret = 0;
5506925baeddSChris Mason done:
5507f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
55088e73f275SChris Mason 	path->leave_spinning = old_spinning;
55098e73f275SChris Mason 	if (!old_spinning)
55108e73f275SChris Mason 		btrfs_set_path_blocking(path);
55118e73f275SChris Mason 
55128e73f275SChris Mason 	return ret;
5513d97e63b6SChris Mason }
55140b86a832SChris Mason 
55153f157a2fSChris Mason /*
55163f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
55173f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
55183f157a2fSChris Mason  *
55193f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
55203f157a2fSChris Mason  */
55210b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
55220b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
55230b86a832SChris Mason 			int type)
55240b86a832SChris Mason {
55250b86a832SChris Mason 	struct btrfs_key found_key;
55260b86a832SChris Mason 	struct extent_buffer *leaf;
5527e02119d5SChris Mason 	u32 nritems;
55280b86a832SChris Mason 	int ret;
55290b86a832SChris Mason 
55300b86a832SChris Mason 	while (1) {
55310b86a832SChris Mason 		if (path->slots[0] == 0) {
5532b4ce94deSChris Mason 			btrfs_set_path_blocking(path);
55330b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
55340b86a832SChris Mason 			if (ret != 0)
55350b86a832SChris Mason 				return ret;
55360b86a832SChris Mason 		} else {
55370b86a832SChris Mason 			path->slots[0]--;
55380b86a832SChris Mason 		}
55390b86a832SChris Mason 		leaf = path->nodes[0];
5540e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5541e02119d5SChris Mason 		if (nritems == 0)
5542e02119d5SChris Mason 			return 1;
5543e02119d5SChris Mason 		if (path->slots[0] == nritems)
5544e02119d5SChris Mason 			path->slots[0]--;
5545e02119d5SChris Mason 
55460b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5547e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5548e02119d5SChris Mason 			break;
55490a4eefbbSYan Zheng 		if (found_key.type == type)
55500a4eefbbSYan Zheng 			return 0;
5551e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5552e02119d5SChris Mason 		    found_key.type < type)
5553e02119d5SChris Mason 			break;
55540b86a832SChris Mason 	}
55550b86a832SChris Mason 	return 1;
55560b86a832SChris Mason }
5557ade2e0b3SWang Shilong 
5558ade2e0b3SWang Shilong /*
5559ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5560ade2e0b3SWang Shilong  * min objecitd.
5561ade2e0b3SWang Shilong  *
5562ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5563ade2e0b3SWang Shilong  */
5564ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5565ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5566ade2e0b3SWang Shilong {
5567ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5568ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5569ade2e0b3SWang Shilong 	u32 nritems;
5570ade2e0b3SWang Shilong 	int ret;
5571ade2e0b3SWang Shilong 
5572ade2e0b3SWang Shilong 	while (1) {
5573ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5574ade2e0b3SWang Shilong 			btrfs_set_path_blocking(path);
5575ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5576ade2e0b3SWang Shilong 			if (ret != 0)
5577ade2e0b3SWang Shilong 				return ret;
5578ade2e0b3SWang Shilong 		} else {
5579ade2e0b3SWang Shilong 			path->slots[0]--;
5580ade2e0b3SWang Shilong 		}
5581ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5582ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5583ade2e0b3SWang Shilong 		if (nritems == 0)
5584ade2e0b3SWang Shilong 			return 1;
5585ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5586ade2e0b3SWang Shilong 			path->slots[0]--;
5587ade2e0b3SWang Shilong 
5588ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5589ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5590ade2e0b3SWang Shilong 			break;
5591ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5592ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5593ade2e0b3SWang Shilong 			return 0;
5594ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5595ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5596ade2e0b3SWang Shilong 			break;
5597ade2e0b3SWang Shilong 	}
5598ade2e0b3SWang Shilong 	return 1;
5599ade2e0b3SWang Shilong }
5600