xref: /openbmc/linux/fs/btrfs/ctree.c (revision e36f94914021e58ee88a8856c7fdf35adf9c7ee1)
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>
10e41d12f5SChristoph Hellwig #include <linux/error-injection.h>
119b569ea0SJosef Bacik #include "messages.h"
12eb60ceacSChris Mason #include "ctree.h"
13eb60ceacSChris Mason #include "disk-io.h"
147f5c1516SChris Mason #include "transaction.h"
155f39d397SChris Mason #include "print-tree.h"
16925baeddSChris Mason #include "locking.h"
17de37aa51SNikolay Borisov #include "volumes.h"
18f616f5cdSQu Wenruo #include "qgroup.h"
19f3a84ccdSFilipe Manana #include "tree-mod-log.h"
2088c602abSQu Wenruo #include "tree-checker.h"
21ec8eb376SJosef Bacik #include "fs.h"
22ad1ac501SJosef Bacik #include "accessors.h"
23a0231804SJosef Bacik #include "extent-tree.h"
2467707479SJosef Bacik #include "relocation.h"
256bfd0ffaSJosef Bacik #include "file-item.h"
269a8dd150SChris Mason 
27226463d7SJosef Bacik static struct kmem_cache *btrfs_path_cachep;
28226463d7SJosef Bacik 
29e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
30e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
31310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
32310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
33310712b2SOmar Sandoval 		      int data_size, int extend);
345f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
352ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
36971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
375f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
385f39d397SChris Mason 			      struct extent_buffer *dst_buf,
395f39d397SChris Mason 			      struct extent_buffer *src_buf);
40d97e63b6SChris Mason 
41af024ed2SJohannes Thumshirn static const struct btrfs_csums {
42af024ed2SJohannes Thumshirn 	u16		size;
4359a0fcdbSDavid Sterba 	const char	name[10];
4459a0fcdbSDavid Sterba 	const char	driver[12];
45af024ed2SJohannes Thumshirn } btrfs_csums[] = {
46af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
473951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
483831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
49352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
50352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
51af024ed2SJohannes Thumshirn };
52af024ed2SJohannes Thumshirn 
533a3178c7SJosef Bacik /*
543a3178c7SJosef Bacik  * The leaf data grows from end-to-front in the node.  this returns the address
553a3178c7SJosef Bacik  * of the start of the last item, which is the stop of the leaf data stack.
563a3178c7SJosef Bacik  */
573a3178c7SJosef Bacik static unsigned int leaf_data_end(const struct extent_buffer *leaf)
583a3178c7SJosef Bacik {
593a3178c7SJosef Bacik 	u32 nr = btrfs_header_nritems(leaf);
603a3178c7SJosef Bacik 
613a3178c7SJosef Bacik 	if (nr == 0)
623a3178c7SJosef Bacik 		return BTRFS_LEAF_DATA_SIZE(leaf->fs_info);
633a3178c7SJosef Bacik 	return btrfs_item_offset(leaf, nr - 1);
643a3178c7SJosef Bacik }
653a3178c7SJosef Bacik 
66637e3b48SJosef Bacik /*
67637e3b48SJosef Bacik  * Move data in a @leaf (using memmove, safe for overlapping ranges).
68637e3b48SJosef Bacik  *
69637e3b48SJosef Bacik  * @leaf:	leaf that we're doing a memmove on
70637e3b48SJosef Bacik  * @dst_offset:	item data offset we're moving to
71637e3b48SJosef Bacik  * @src_offset:	item data offset were' moving from
72637e3b48SJosef Bacik  * @len:	length of the data we're moving
73637e3b48SJosef Bacik  *
74637e3b48SJosef Bacik  * Wrapper around memmove_extent_buffer() that takes into account the header on
75637e3b48SJosef Bacik  * the leaf.  The btrfs_item offset's start directly after the header, so we
76637e3b48SJosef Bacik  * have to adjust any offsets to account for the header in the leaf.  This
77637e3b48SJosef Bacik  * handles that math to simplify the callers.
78637e3b48SJosef Bacik  */
79637e3b48SJosef Bacik static inline void memmove_leaf_data(const struct extent_buffer *leaf,
80637e3b48SJosef Bacik 				     unsigned long dst_offset,
81637e3b48SJosef Bacik 				     unsigned long src_offset,
82637e3b48SJosef Bacik 				     unsigned long len)
83637e3b48SJosef Bacik {
848009adf3SJosef Bacik 	memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, 0) + dst_offset,
858009adf3SJosef Bacik 			      btrfs_item_nr_offset(leaf, 0) + src_offset, len);
86637e3b48SJosef Bacik }
87637e3b48SJosef Bacik 
88637e3b48SJosef Bacik /*
89637e3b48SJosef Bacik  * Copy item data from @src into @dst at the given @offset.
90637e3b48SJosef Bacik  *
91637e3b48SJosef Bacik  * @dst:	destination leaf that we're copying into
92637e3b48SJosef Bacik  * @src:	source leaf that we're copying from
93637e3b48SJosef Bacik  * @dst_offset:	item data offset we're copying to
94637e3b48SJosef Bacik  * @src_offset:	item data offset were' copying from
95637e3b48SJosef Bacik  * @len:	length of the data we're copying
96637e3b48SJosef Bacik  *
97637e3b48SJosef Bacik  * Wrapper around copy_extent_buffer() that takes into account the header on
98637e3b48SJosef Bacik  * the leaf.  The btrfs_item offset's start directly after the header, so we
99637e3b48SJosef Bacik  * have to adjust any offsets to account for the header in the leaf.  This
100637e3b48SJosef Bacik  * handles that math to simplify the callers.
101637e3b48SJosef Bacik  */
102637e3b48SJosef Bacik static inline void copy_leaf_data(const struct extent_buffer *dst,
103637e3b48SJosef Bacik 				  const struct extent_buffer *src,
104637e3b48SJosef Bacik 				  unsigned long dst_offset,
105637e3b48SJosef Bacik 				  unsigned long src_offset, unsigned long len)
106637e3b48SJosef Bacik {
1078009adf3SJosef Bacik 	copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, 0) + dst_offset,
1088009adf3SJosef Bacik 			   btrfs_item_nr_offset(src, 0) + src_offset, len);
109637e3b48SJosef Bacik }
110637e3b48SJosef Bacik 
111637e3b48SJosef Bacik /*
112637e3b48SJosef Bacik  * Move items in a @leaf (using memmove).
113637e3b48SJosef Bacik  *
114637e3b48SJosef Bacik  * @dst:	destination leaf for the items
115637e3b48SJosef Bacik  * @dst_item:	the item nr we're copying into
116637e3b48SJosef Bacik  * @src_item:	the item nr we're copying from
117637e3b48SJosef Bacik  * @nr_items:	the number of items to copy
118637e3b48SJosef Bacik  *
119637e3b48SJosef Bacik  * Wrapper around memmove_extent_buffer() that does the math to get the
120637e3b48SJosef Bacik  * appropriate offsets into the leaf from the item numbers.
121637e3b48SJosef Bacik  */
122637e3b48SJosef Bacik static inline void memmove_leaf_items(const struct extent_buffer *leaf,
123637e3b48SJosef Bacik 				      int dst_item, int src_item, int nr_items)
124637e3b48SJosef Bacik {
125637e3b48SJosef Bacik 	memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, dst_item),
126637e3b48SJosef Bacik 			      btrfs_item_nr_offset(leaf, src_item),
127637e3b48SJosef Bacik 			      nr_items * sizeof(struct btrfs_item));
128637e3b48SJosef Bacik }
129637e3b48SJosef Bacik 
130637e3b48SJosef Bacik /*
131637e3b48SJosef Bacik  * Copy items from @src into @dst at the given @offset.
132637e3b48SJosef Bacik  *
133637e3b48SJosef Bacik  * @dst:	destination leaf for the items
134637e3b48SJosef Bacik  * @src:	source leaf for the items
135637e3b48SJosef Bacik  * @dst_item:	the item nr we're copying into
136637e3b48SJosef Bacik  * @src_item:	the item nr we're copying from
137637e3b48SJosef Bacik  * @nr_items:	the number of items to copy
138637e3b48SJosef Bacik  *
139637e3b48SJosef Bacik  * Wrapper around copy_extent_buffer() that does the math to get the
140637e3b48SJosef Bacik  * appropriate offsets into the leaf from the item numbers.
141637e3b48SJosef Bacik  */
142637e3b48SJosef Bacik static inline void copy_leaf_items(const struct extent_buffer *dst,
143637e3b48SJosef Bacik 				   const struct extent_buffer *src,
144637e3b48SJosef Bacik 				   int dst_item, int src_item, int nr_items)
145637e3b48SJosef Bacik {
146637e3b48SJosef Bacik 	copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, dst_item),
147637e3b48SJosef Bacik 			      btrfs_item_nr_offset(src, src_item),
148637e3b48SJosef Bacik 			      nr_items * sizeof(struct btrfs_item));
149637e3b48SJosef Bacik }
150637e3b48SJosef Bacik 
151b3cbfb0dSJosef Bacik /* This exists for btrfs-progs usages. */
152b3cbfb0dSJosef Bacik u16 btrfs_csum_type_size(u16 type)
153b3cbfb0dSJosef Bacik {
154b3cbfb0dSJosef Bacik 	return btrfs_csums[type].size;
155b3cbfb0dSJosef Bacik }
156b3cbfb0dSJosef Bacik 
157af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
158af024ed2SJohannes Thumshirn {
159af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
160af024ed2SJohannes Thumshirn 	/*
161af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
162af024ed2SJohannes Thumshirn 	 */
163b3cbfb0dSJosef Bacik 	return btrfs_csum_type_size(t);
164af024ed2SJohannes Thumshirn }
165af024ed2SJohannes Thumshirn 
166af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
167af024ed2SJohannes Thumshirn {
168af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
169af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
170af024ed2SJohannes Thumshirn }
171af024ed2SJohannes Thumshirn 
172b4e967beSDavid Sterba /*
173b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
174b4e967beSDavid Sterba  * name
175b4e967beSDavid Sterba  */
176b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
177b4e967beSDavid Sterba {
178b4e967beSDavid Sterba 	/* csum type is validated at mount time */
17959a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
18059a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
181b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
182b4e967beSDavid Sterba }
183b4e967beSDavid Sterba 
184604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
185f7cea56cSDavid Sterba {
186f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
187f7cea56cSDavid Sterba }
188f7cea56cSDavid Sterba 
1892c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
1902c90e5d6SChris Mason {
191a4c853afSChenXiaoSong 	might_sleep();
192a4c853afSChenXiaoSong 
193e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
1942c90e5d6SChris Mason }
1952c90e5d6SChris Mason 
196d352ac68SChris Mason /* this also releases the path */
1972c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1982c90e5d6SChris Mason {
199ff175d57SJesper Juhl 	if (!p)
200ff175d57SJesper Juhl 		return;
201b3b4aa74SDavid Sterba 	btrfs_release_path(p);
2022c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
2032c90e5d6SChris Mason }
2042c90e5d6SChris Mason 
205d352ac68SChris Mason /*
206d352ac68SChris Mason  * path release drops references on the extent buffers in the path
207d352ac68SChris Mason  * and it drops any locks held by this path
208d352ac68SChris Mason  *
209d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
210d352ac68SChris Mason  */
211b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
212eb60ceacSChris Mason {
213eb60ceacSChris Mason 	int i;
214a2135011SChris Mason 
215234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
2163f157a2fSChris Mason 		p->slots[i] = 0;
217eb60ceacSChris Mason 		if (!p->nodes[i])
218925baeddSChris Mason 			continue;
219925baeddSChris Mason 		if (p->locks[i]) {
220bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
221925baeddSChris Mason 			p->locks[i] = 0;
222925baeddSChris Mason 		}
2235f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
2243f157a2fSChris Mason 		p->nodes[i] = NULL;
225eb60ceacSChris Mason 	}
226eb60ceacSChris Mason }
227eb60ceacSChris Mason 
228d352ac68SChris Mason /*
2298bb808c6SDavid Sterba  * We want the transaction abort to print stack trace only for errors where the
2308bb808c6SDavid Sterba  * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
2318bb808c6SDavid Sterba  * caused by external factors.
2328bb808c6SDavid Sterba  */
2338bb808c6SDavid Sterba bool __cold abort_should_print_stack(int errno)
2348bb808c6SDavid Sterba {
2358bb808c6SDavid Sterba 	switch (errno) {
2368bb808c6SDavid Sterba 	case -EIO:
2378bb808c6SDavid Sterba 	case -EROFS:
2388bb808c6SDavid Sterba 	case -ENOMEM:
2398bb808c6SDavid Sterba 		return false;
2408bb808c6SDavid Sterba 	}
2418bb808c6SDavid Sterba 	return true;
2428bb808c6SDavid Sterba }
2438bb808c6SDavid Sterba 
2448bb808c6SDavid Sterba /*
245d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
246d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
247d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
248d352ac68SChris Mason  * looping required.
249d352ac68SChris Mason  *
250d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
251d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
252d352ac68SChris Mason  * at any time because there are no locks held.
253d352ac68SChris Mason  */
254925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
255925baeddSChris Mason {
256925baeddSChris Mason 	struct extent_buffer *eb;
257240f62c8SChris Mason 
2583083ee2eSJosef Bacik 	while (1) {
259240f62c8SChris Mason 		rcu_read_lock();
260240f62c8SChris Mason 		eb = rcu_dereference(root->node);
2613083ee2eSJosef Bacik 
2623083ee2eSJosef Bacik 		/*
2633083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
26401327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
2653083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
2663083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
2673083ee2eSJosef Bacik 		 */
2683083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
269240f62c8SChris Mason 			rcu_read_unlock();
2703083ee2eSJosef Bacik 			break;
2713083ee2eSJosef Bacik 		}
2723083ee2eSJosef Bacik 		rcu_read_unlock();
2733083ee2eSJosef Bacik 		synchronize_rcu();
2743083ee2eSJosef Bacik 	}
275925baeddSChris Mason 	return eb;
276925baeddSChris Mason }
277925baeddSChris Mason 
27892a7cc42SQu Wenruo /*
27992a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
28092a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
28192a7cc42SQu Wenruo  * sure they get properly updated on disk.
282d352ac68SChris Mason  */
2830b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
2840b86a832SChris Mason {
2850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2860b246afaSJeff Mahoney 
287e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
288e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
289e7070be1SJosef Bacik 		return;
290e7070be1SJosef Bacik 
2910b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
292e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
293e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
2944fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
295e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
2960b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
297e7070be1SJosef Bacik 		else
298e7070be1SJosef Bacik 			list_move(&root->dirty_list,
2990b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
3000b86a832SChris Mason 	}
3010b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
3020b86a832SChris Mason }
3030b86a832SChris Mason 
304d352ac68SChris Mason /*
305d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
306d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
307d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
308d352ac68SChris Mason  */
309be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
310be20aa9dSChris Mason 		      struct btrfs_root *root,
311be20aa9dSChris Mason 		      struct extent_buffer *buf,
312be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
313be20aa9dSChris Mason {
3140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
315be20aa9dSChris Mason 	struct extent_buffer *cow;
316be20aa9dSChris Mason 	int ret = 0;
317be20aa9dSChris Mason 	int level;
3185d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
319be20aa9dSChris Mason 
32092a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
3210b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
32292a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
32327cdeb70SMiao Xie 		trans->transid != root->last_trans);
324be20aa9dSChris Mason 
325be20aa9dSChris Mason 	level = btrfs_header_level(buf);
3265d4f98a2SYan Zheng 	if (level == 0)
3275d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
3285d4f98a2SYan Zheng 	else
3295d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
33031840ae1SZheng Yan 
3314d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
332cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
333cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
3345d4f98a2SYan Zheng 	if (IS_ERR(cow))
335be20aa9dSChris Mason 		return PTR_ERR(cow);
336be20aa9dSChris Mason 
33758e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
338be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
339be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
3405d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
3415d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
3425d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
3435d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
3445d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
3455d4f98a2SYan Zheng 	else
346be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
347be20aa9dSChris Mason 
348de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
3492b82032cSYan Zheng 
350be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
3515d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
352e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
3535d4f98a2SYan Zheng 	else
354e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
355867ed321SJosef Bacik 	if (ret) {
35672c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
35772c9925fSFilipe Manana 		free_extent_buffer(cow);
358867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
359be20aa9dSChris Mason 		return ret;
360867ed321SJosef Bacik 	}
361be20aa9dSChris Mason 
362be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
363be20aa9dSChris Mason 	*cow_ret = cow;
364be20aa9dSChris Mason 	return 0;
365be20aa9dSChris Mason }
366be20aa9dSChris Mason 
367d352ac68SChris Mason /*
3685d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
3695d4f98a2SYan Zheng  */
3705d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
3715d4f98a2SYan Zheng 			      struct extent_buffer *buf)
3725d4f98a2SYan Zheng {
3735d4f98a2SYan Zheng 	/*
37492a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
37592a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
37692a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
3775d4f98a2SYan Zheng 	 */
37892a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
3795d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
3805d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
3815d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
3825d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
3835d4f98a2SYan Zheng 		return 1;
384a79865c6SNikolay Borisov 
3855d4f98a2SYan Zheng 	return 0;
3865d4f98a2SYan Zheng }
3875d4f98a2SYan Zheng 
3885d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
3895d4f98a2SYan Zheng 				       struct btrfs_root *root,
3905d4f98a2SYan Zheng 				       struct extent_buffer *buf,
391f0486c68SYan, Zheng 				       struct extent_buffer *cow,
392f0486c68SYan, Zheng 				       int *last_ref)
3935d4f98a2SYan Zheng {
3940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3955d4f98a2SYan Zheng 	u64 refs;
3965d4f98a2SYan Zheng 	u64 owner;
3975d4f98a2SYan Zheng 	u64 flags;
3985d4f98a2SYan Zheng 	u64 new_flags = 0;
3995d4f98a2SYan Zheng 	int ret;
4005d4f98a2SYan Zheng 
4015d4f98a2SYan Zheng 	/*
4025d4f98a2SYan Zheng 	 * Backrefs update rules:
4035d4f98a2SYan Zheng 	 *
4045d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
4055d4f98a2SYan Zheng 	 * allocated by tree relocation.
4065d4f98a2SYan Zheng 	 *
4075d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
4085d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
4095d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
4105d4f98a2SYan Zheng 	 *
4115d4f98a2SYan Zheng 	 * If a tree block is been relocating
4125d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
4135d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
4145d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
4155d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
4165d4f98a2SYan Zheng 	 */
4175d4f98a2SYan Zheng 
4185d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
4192ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
4203173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
4213173a18fSJosef Bacik 					       &refs, &flags);
422be1a5564SMark Fasheh 		if (ret)
423be1a5564SMark Fasheh 			return ret;
424eced687eSFilipe Manana 		if (unlikely(refs == 0)) {
425eced687eSFilipe Manana 			btrfs_crit(fs_info,
426eced687eSFilipe Manana 		"found 0 references for tree block at bytenr %llu level %d root %llu",
427eced687eSFilipe Manana 				   buf->start, btrfs_header_level(buf),
428eced687eSFilipe Manana 				   btrfs_root_id(root));
429eced687eSFilipe Manana 			ret = -EUCLEAN;
430eced687eSFilipe Manana 			btrfs_abort_transaction(trans, ret);
431e5df9573SMark Fasheh 			return ret;
432e5df9573SMark Fasheh 		}
4335d4f98a2SYan Zheng 	} else {
4345d4f98a2SYan Zheng 		refs = 1;
4355d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4365d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4375d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
4385d4f98a2SYan Zheng 		else
4395d4f98a2SYan Zheng 			flags = 0;
4405d4f98a2SYan Zheng 	}
4415d4f98a2SYan Zheng 
4425d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
4435d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
4445d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
4455d4f98a2SYan Zheng 
4465d4f98a2SYan Zheng 	if (refs > 1) {
4475d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
4485d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
4495d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
450e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
451692826b2SJeff Mahoney 			if (ret)
452692826b2SJeff Mahoney 				return ret;
4535d4f98a2SYan Zheng 
4545d4f98a2SYan Zheng 			if (root->root_key.objectid ==
4555d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
456e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
457692826b2SJeff Mahoney 				if (ret)
458692826b2SJeff Mahoney 					return ret;
459e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
460692826b2SJeff Mahoney 				if (ret)
461692826b2SJeff Mahoney 					return ret;
4625d4f98a2SYan Zheng 			}
4635d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4645d4f98a2SYan Zheng 		} else {
4655d4f98a2SYan Zheng 
4665d4f98a2SYan Zheng 			if (root->root_key.objectid ==
4675d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
468e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
4695d4f98a2SYan Zheng 			else
470e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
471692826b2SJeff Mahoney 			if (ret)
472692826b2SJeff Mahoney 				return ret;
4735d4f98a2SYan Zheng 		}
4745d4f98a2SYan Zheng 		if (new_flags != 0) {
4754aec05faSJosef Bacik 			ret = btrfs_set_disk_extent_flags(trans, buf, new_flags);
476be1a5564SMark Fasheh 			if (ret)
477be1a5564SMark Fasheh 				return ret;
4785d4f98a2SYan Zheng 		}
4795d4f98a2SYan Zheng 	} else {
4805d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
4815d4f98a2SYan Zheng 			if (root->root_key.objectid ==
4825d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
483e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
4845d4f98a2SYan Zheng 			else
485e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
486692826b2SJeff Mahoney 			if (ret)
487692826b2SJeff Mahoney 				return ret;
488e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
489692826b2SJeff Mahoney 			if (ret)
490692826b2SJeff Mahoney 				return ret;
4915d4f98a2SYan Zheng 		}
492190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, buf);
493f0486c68SYan, Zheng 		*last_ref = 1;
4945d4f98a2SYan Zheng 	}
4955d4f98a2SYan Zheng 	return 0;
4965d4f98a2SYan Zheng }
4975d4f98a2SYan Zheng 
4985d4f98a2SYan Zheng /*
499d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
500d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
501d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
502d397712bSChris Mason  * dirty again.
503d352ac68SChris Mason  *
504d352ac68SChris Mason  * search_start -- an allocation hint for the new block
505d352ac68SChris Mason  *
506d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
507d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
508d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
509d352ac68SChris Mason  */
510d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
5115f39d397SChris Mason 			     struct btrfs_root *root,
5125f39d397SChris Mason 			     struct extent_buffer *buf,
5135f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
5145f39d397SChris Mason 			     struct extent_buffer **cow_ret,
5159631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
5169631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
5176702ed49SChris Mason {
5180b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5195d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
5205f39d397SChris Mason 	struct extent_buffer *cow;
521be1a5564SMark Fasheh 	int level, ret;
522f0486c68SYan, Zheng 	int last_ref = 0;
523925baeddSChris Mason 	int unlock_orig = 0;
5240f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
5256702ed49SChris Mason 
526925baeddSChris Mason 	if (*cow_ret == buf)
527925baeddSChris Mason 		unlock_orig = 1;
528925baeddSChris Mason 
52949d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
530925baeddSChris Mason 
53192a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
5320b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
53392a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
53427cdeb70SMiao Xie 		trans->transid != root->last_trans);
5355f39d397SChris Mason 
5367bb86316SChris Mason 	level = btrfs_header_level(buf);
53731840ae1SZheng Yan 
5385d4f98a2SYan Zheng 	if (level == 0)
5395d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
5405d4f98a2SYan Zheng 	else
5415d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
5425d4f98a2SYan Zheng 
5430f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
5445d4f98a2SYan Zheng 		parent_start = parent->start;
5455d4f98a2SYan Zheng 
54679bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
54779bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
54879bd3712SFilipe Manana 				     search_start, empty_size, nest);
5496702ed49SChris Mason 	if (IS_ERR(cow))
5506702ed49SChris Mason 		return PTR_ERR(cow);
5516702ed49SChris Mason 
552b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
553b4ce94deSChris Mason 
55458e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
555db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
5565f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
5575d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
5585d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
5595d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
5605d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
5615d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
5625d4f98a2SYan Zheng 	else
5635f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
5646702ed49SChris Mason 
565de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
5662b82032cSYan Zheng 
567be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
568b68dc2a9SMark Fasheh 	if (ret) {
569572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
570572c83acSJosef Bacik 		free_extent_buffer(cow);
57166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
572b68dc2a9SMark Fasheh 		return ret;
573b68dc2a9SMark Fasheh 	}
5741a40e23bSZheng Yan 
57592a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
57683d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
57793314e3bSZhaolei 		if (ret) {
578572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
579572c83acSJosef Bacik 			free_extent_buffer(cow);
58066642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
58183d4cfd4SJosef Bacik 			return ret;
58283d4cfd4SJosef Bacik 		}
58393314e3bSZhaolei 	}
5843fd0a558SYan, Zheng 
5856702ed49SChris Mason 	if (buf == root->node) {
586925baeddSChris Mason 		WARN_ON(parent && parent != buf);
5875d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
5885d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
5895d4f98a2SYan Zheng 			parent_start = buf->start;
590925baeddSChris Mason 
591406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
59240b0a749SFilipe Manana 		if (ret < 0) {
59340b0a749SFilipe Manana 			btrfs_tree_unlock(cow);
59440b0a749SFilipe Manana 			free_extent_buffer(cow);
59540b0a749SFilipe Manana 			btrfs_abort_transaction(trans, ret);
59640b0a749SFilipe Manana 			return ret;
59740b0a749SFilipe Manana 		}
59840b0a749SFilipe Manana 		atomic_inc(&cow->refs);
599240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
600925baeddSChris Mason 
6017a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
6027a163608SFilipe Manana 				      parent_start, last_ref);
6035f39d397SChris Mason 		free_extent_buffer(buf);
6040b86a832SChris Mason 		add_root_to_dirty_list(root);
6056702ed49SChris Mason 	} else {
6065d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
607d09c5152SFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, parent_slot,
60833cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
609d09c5152SFilipe Manana 		if (ret) {
610d09c5152SFilipe Manana 			btrfs_tree_unlock(cow);
611d09c5152SFilipe Manana 			free_extent_buffer(cow);
612d09c5152SFilipe Manana 			btrfs_abort_transaction(trans, ret);
613d09c5152SFilipe Manana 			return ret;
614d09c5152SFilipe Manana 		}
6155f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
616db94535dSChris Mason 					cow->start);
61774493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
61874493f7aSChris Mason 					      trans->transid);
6196702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
6205de865eeSFilipe David Borba Manana 		if (last_ref) {
621f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
6225de865eeSFilipe David Borba Manana 			if (ret) {
623572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
624572c83acSJosef Bacik 				free_extent_buffer(cow);
62566642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
6265de865eeSFilipe David Borba Manana 				return ret;
6275de865eeSFilipe David Borba Manana 			}
6285de865eeSFilipe David Borba Manana 		}
6297a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
6307a163608SFilipe Manana 				      parent_start, last_ref);
6316702ed49SChris Mason 	}
632925baeddSChris Mason 	if (unlock_orig)
633925baeddSChris Mason 		btrfs_tree_unlock(buf);
6343083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
6356702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
6366702ed49SChris Mason 	*cow_ret = cow;
6376702ed49SChris Mason 	return 0;
6386702ed49SChris Mason }
6396702ed49SChris Mason 
6405d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
6415d4f98a2SYan Zheng 				   struct btrfs_root *root,
6425d4f98a2SYan Zheng 				   struct extent_buffer *buf)
6435d4f98a2SYan Zheng {
644f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
645faa2dbf0SJosef Bacik 		return 0;
646fccb84c9SDavid Sterba 
647d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
648d1980131SDavid Sterba 	smp_mb__before_atomic();
649f1ebcc74SLiu Bo 
650f1ebcc74SLiu Bo 	/*
651f1ebcc74SLiu Bo 	 * We do not need to cow a block if
652f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
653f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
654f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
655f1ebcc74SLiu Bo 	 *
656f1ebcc74SLiu Bo 	 * What is forced COW:
65701327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
65852042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
659f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
660f1ebcc74SLiu Bo 	 */
6615d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
6625d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
6635d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
664f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
66527cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
6665d4f98a2SYan Zheng 		return 0;
6675d4f98a2SYan Zheng 	return 1;
6685d4f98a2SYan Zheng }
6695d4f98a2SYan Zheng 
670d352ac68SChris Mason /*
671d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
67201327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
673d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
674d352ac68SChris Mason  */
675d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
6765f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
6775f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
6789631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
6799631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
68002217ed2SChris Mason {
6810b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6826702ed49SChris Mason 	u64 search_start;
683f510cfecSChris Mason 	int ret;
684dc17ff8fSChris Mason 
685a2caab29SFilipe Manana 	if (unlikely(test_bit(BTRFS_ROOT_DELETING, &root->state))) {
686a2caab29SFilipe Manana 		btrfs_abort_transaction(trans, -EUCLEAN);
687a2caab29SFilipe Manana 		btrfs_crit(fs_info,
688a2caab29SFilipe Manana 		   "attempt to COW block %llu on root %llu that is being deleted",
689a2caab29SFilipe Manana 			   buf->start, btrfs_root_id(root));
690a2caab29SFilipe Manana 		return -EUCLEAN;
691a2caab29SFilipe Manana 	}
69283354f07SJosef Bacik 
69348774f3bSFilipe Manana 	/*
69448774f3bSFilipe Manana 	 * COWing must happen through a running transaction, which always
69548774f3bSFilipe Manana 	 * matches the current fs generation (it's a transaction with a state
69648774f3bSFilipe Manana 	 * less than TRANS_STATE_UNBLOCKED). If it doesn't, then turn the fs
69748774f3bSFilipe Manana 	 * into error state to prevent the commit of any transaction.
69848774f3bSFilipe Manana 	 */
69948774f3bSFilipe Manana 	if (unlikely(trans->transaction != fs_info->running_transaction ||
70048774f3bSFilipe Manana 		     trans->transid != fs_info->generation)) {
70148774f3bSFilipe Manana 		btrfs_abort_transaction(trans, -EUCLEAN);
70248774f3bSFilipe Manana 		btrfs_crit(fs_info,
70348774f3bSFilipe Manana "unexpected transaction when attempting to COW block %llu on root %llu, transaction %llu running transaction %llu fs generation %llu",
70448774f3bSFilipe Manana 			   buf->start, btrfs_root_id(root), trans->transid,
70548774f3bSFilipe Manana 			   fs_info->running_transaction->transid,
70648774f3bSFilipe Manana 			   fs_info->generation);
70748774f3bSFilipe Manana 		return -EUCLEAN;
70848774f3bSFilipe Manana 	}
709dc17ff8fSChris Mason 
7105d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
71102217ed2SChris Mason 		*cow_ret = buf;
71202217ed2SChris Mason 		return 0;
71302217ed2SChris Mason 	}
714c487685dSChris Mason 
715ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
716b4ce94deSChris Mason 
717f616f5cdSQu Wenruo 	/*
718f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
719f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
720f616f5cdSQu Wenruo 	 *
721f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
722f616f5cdSQu Wenruo 	 */
723f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
724f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
7259631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
7261abe9b8aSliubo 
7271abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
7281abe9b8aSliubo 
729f510cfecSChris Mason 	return ret;
7302c90e5d6SChris Mason }
731f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
7326702ed49SChris Mason 
733d352ac68SChris Mason /*
734d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
735d352ac68SChris Mason  * node are actually close by
736d352ac68SChris Mason  */
7376b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
7386702ed49SChris Mason {
7396b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
7406702ed49SChris Mason 		return 1;
7416b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
7426702ed49SChris Mason 		return 1;
74302217ed2SChris Mason 	return 0;
74402217ed2SChris Mason }
74502217ed2SChris Mason 
746ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
747ce6ef5abSDavid Sterba 
748ce6ef5abSDavid Sterba /*
749ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
750ce6ef5abSDavid Sterba  * we can avoid the conversion.
751ce6ef5abSDavid Sterba  */
752ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
753ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
754ce6ef5abSDavid Sterba {
755ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
756ce6ef5abSDavid Sterba 
757ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
758ce6ef5abSDavid Sterba }
759ce6ef5abSDavid Sterba 
760ce6ef5abSDavid Sterba #else
761ce6ef5abSDavid Sterba 
762081e9573SChris Mason /*
763081e9573SChris Mason  * compare two keys in a memcmp fashion
764081e9573SChris Mason  */
765310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
766310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
767081e9573SChris Mason {
768081e9573SChris Mason 	struct btrfs_key k1;
769081e9573SChris Mason 
770081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
771081e9573SChris Mason 
77220736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
773081e9573SChris Mason }
774ce6ef5abSDavid Sterba #endif
775081e9573SChris Mason 
776f3465ca4SJosef Bacik /*
777f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
778f3465ca4SJosef Bacik  */
779e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
780f3465ca4SJosef Bacik {
781f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
782f3465ca4SJosef Bacik 		return 1;
783f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
784f3465ca4SJosef Bacik 		return -1;
785f3465ca4SJosef Bacik 	if (k1->type > k2->type)
786f3465ca4SJosef Bacik 		return 1;
787f3465ca4SJosef Bacik 	if (k1->type < k2->type)
788f3465ca4SJosef Bacik 		return -1;
789f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
790f3465ca4SJosef Bacik 		return 1;
791f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
792f3465ca4SJosef Bacik 		return -1;
793f3465ca4SJosef Bacik 	return 0;
794f3465ca4SJosef Bacik }
795081e9573SChris Mason 
796d352ac68SChris Mason /*
797d352ac68SChris Mason  * this is used by the defrag code to go through all the
798d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
799d352ac68SChris Mason  * disk order is close to key order
800d352ac68SChris Mason  */
8016702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
8025f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
803de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
804a6b6e75eSChris Mason 		       struct btrfs_key *progress)
8056702ed49SChris Mason {
8060b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8076b80053dSChris Mason 	struct extent_buffer *cur;
8086702ed49SChris Mason 	u64 blocknr;
809e9d0b13bSChris Mason 	u64 search_start = *last_ret;
810e9d0b13bSChris Mason 	u64 last_block = 0;
8116702ed49SChris Mason 	u64 other;
8126702ed49SChris Mason 	u32 parent_nritems;
8136702ed49SChris Mason 	int end_slot;
8146702ed49SChris Mason 	int i;
8156702ed49SChris Mason 	int err = 0;
8166b80053dSChris Mason 	u32 blocksize;
817081e9573SChris Mason 	int progress_passed = 0;
818081e9573SChris Mason 	struct btrfs_disk_key disk_key;
8196702ed49SChris Mason 
820*e36f9491SFilipe Manana 	/*
821*e36f9491SFilipe Manana 	 * COWing must happen through a running transaction, which always
822*e36f9491SFilipe Manana 	 * matches the current fs generation (it's a transaction with a state
823*e36f9491SFilipe Manana 	 * less than TRANS_STATE_UNBLOCKED). If it doesn't, then turn the fs
824*e36f9491SFilipe Manana 	 * into error state to prevent the commit of any transaction.
825*e36f9491SFilipe Manana 	 */
826*e36f9491SFilipe Manana 	if (unlikely(trans->transaction != fs_info->running_transaction ||
827*e36f9491SFilipe Manana 		     trans->transid != fs_info->generation)) {
828*e36f9491SFilipe Manana 		btrfs_abort_transaction(trans, -EUCLEAN);
829*e36f9491SFilipe Manana 		btrfs_crit(fs_info,
830*e36f9491SFilipe Manana "unexpected transaction when attempting to reallocate parent %llu for root %llu, transaction %llu running transaction %llu fs generation %llu",
831*e36f9491SFilipe Manana 			   parent->start, btrfs_root_id(root), trans->transid,
832*e36f9491SFilipe Manana 			   fs_info->running_transaction->transid,
833*e36f9491SFilipe Manana 			   fs_info->generation);
834*e36f9491SFilipe Manana 		return -EUCLEAN;
835*e36f9491SFilipe Manana 	}
83686479a04SChris Mason 
8376b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
8380b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
8395dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
8406702ed49SChris Mason 
8415dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
8426702ed49SChris Mason 		return 0;
8436702ed49SChris Mason 
8445dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
8456702ed49SChris Mason 		int close = 1;
846a6b6e75eSChris Mason 
847081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
848081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
849081e9573SChris Mason 			continue;
850081e9573SChris Mason 
851081e9573SChris Mason 		progress_passed = 1;
8526b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
853e9d0b13bSChris Mason 		if (last_block == 0)
854e9d0b13bSChris Mason 			last_block = blocknr;
8555708b959SChris Mason 
8566702ed49SChris Mason 		if (i > 0) {
8576b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
8586b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
8596702ed49SChris Mason 		}
8605dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
8616b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
8626b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
8636702ed49SChris Mason 		}
864e9d0b13bSChris Mason 		if (close) {
865e9d0b13bSChris Mason 			last_block = blocknr;
8666702ed49SChris Mason 			continue;
867e9d0b13bSChris Mason 		}
8686702ed49SChris Mason 
869206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
870206983b7SJosef Bacik 		if (IS_ERR(cur))
87164c043deSLiu Bo 			return PTR_ERR(cur);
872e9d0b13bSChris Mason 		if (search_start == 0)
8736b80053dSChris Mason 			search_start = last_block;
874e9d0b13bSChris Mason 
875e7a84565SChris Mason 		btrfs_tree_lock(cur);
8766b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
877e7a84565SChris Mason 					&cur, search_start,
8786b80053dSChris Mason 					min(16 * blocksize,
8799631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
8809631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
881252c38f0SYan 		if (err) {
882e7a84565SChris Mason 			btrfs_tree_unlock(cur);
8836b80053dSChris Mason 			free_extent_buffer(cur);
8846702ed49SChris Mason 			break;
885252c38f0SYan 		}
886e7a84565SChris Mason 		search_start = cur->start;
887e7a84565SChris Mason 		last_block = cur->start;
888f2183bdeSChris Mason 		*last_ret = search_start;
889e7a84565SChris Mason 		btrfs_tree_unlock(cur);
890e7a84565SChris Mason 		free_extent_buffer(cur);
8916702ed49SChris Mason 	}
8926702ed49SChris Mason 	return err;
8936702ed49SChris Mason }
8946702ed49SChris Mason 
89574123bd7SChris Mason /*
896fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
8975f39d397SChris Mason  *
898a724f313SFilipe Manana  * The lower boundary for the search is specified by the slot number @first_slot.
899fdf8d595SAnand Jain  * Use a value of 0 to search over the whole extent buffer. Works for both
900fdf8d595SAnand Jain  * leaves and nodes.
90174123bd7SChris Mason  *
902fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
903fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
904fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
905fb81212cSFilipe Manana  *
906fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
907fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
90874123bd7SChris Mason  */
909fdf8d595SAnand Jain int btrfs_bin_search(struct extent_buffer *eb, int first_slot,
91067d5e289SMarcos Paulo de Souza 		     const struct btrfs_key *key, int *slot)
911be0e5c09SChris Mason {
912fb81212cSFilipe Manana 	unsigned long p;
913fb81212cSFilipe Manana 	int item_size;
914a724f313SFilipe Manana 	/*
915a724f313SFilipe Manana 	 * Use unsigned types for the low and high slots, so that we get a more
916a724f313SFilipe Manana 	 * efficient division in the search loop below.
917a724f313SFilipe Manana 	 */
918a724f313SFilipe Manana 	u32 low = first_slot;
919a724f313SFilipe Manana 	u32 high = btrfs_header_nritems(eb);
920be0e5c09SChris Mason 	int ret;
9215cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
922be0e5c09SChris Mason 
923a724f313SFilipe Manana 	if (unlikely(low > high)) {
9245e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
925a724f313SFilipe Manana 		 "%s: low (%u) > high (%u) eb %llu owner %llu level %d",
9265e24e9afSLiu Bo 			  __func__, low, high, eb->start,
9275e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
9285e24e9afSLiu Bo 		return -EINVAL;
9295e24e9afSLiu Bo 	}
9305e24e9afSLiu Bo 
931fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
932fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
933fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
934fb81212cSFilipe Manana 	} else {
935fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
936fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
937fb81212cSFilipe Manana 	}
938fb81212cSFilipe Manana 
939be0e5c09SChris Mason 	while (low < high) {
9405cd17f34SDavid Sterba 		unsigned long oip;
9415cd17f34SDavid Sterba 		unsigned long offset;
9425cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
9435cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
9445cd17f34SDavid Sterba 		int mid;
9455cd17f34SDavid Sterba 
946be0e5c09SChris Mason 		mid = (low + high) / 2;
9475f39d397SChris Mason 		offset = p + mid * item_size;
9485cd17f34SDavid Sterba 		oip = offset_in_page(offset);
9495f39d397SChris Mason 
9505cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
951884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
9525cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
953934d375bSChris Mason 
954884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
9555cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
9565cd17f34SDavid Sterba 		} else {
9575cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
9585f39d397SChris Mason 			tmp = &unaligned;
959479965d6SChris Mason 		}
960479965d6SChris Mason 
961be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
962be0e5c09SChris Mason 
963be0e5c09SChris Mason 		if (ret < 0)
964be0e5c09SChris Mason 			low = mid + 1;
965be0e5c09SChris Mason 		else if (ret > 0)
966be0e5c09SChris Mason 			high = mid;
967be0e5c09SChris Mason 		else {
968be0e5c09SChris Mason 			*slot = mid;
969be0e5c09SChris Mason 			return 0;
970be0e5c09SChris Mason 		}
971be0e5c09SChris Mason 	}
972be0e5c09SChris Mason 	*slot = low;
973be0e5c09SChris Mason 	return 1;
974be0e5c09SChris Mason }
975be0e5c09SChris Mason 
976f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
977f0486c68SYan, Zheng {
978f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
979f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
980f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
981f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
982f0486c68SYan, Zheng }
983f0486c68SYan, Zheng 
984f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
985f0486c68SYan, Zheng {
986f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
987f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
988f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
989f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
990f0486c68SYan, Zheng }
991f0486c68SYan, Zheng 
992d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
993d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
994d352ac68SChris Mason  */
9954b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
9964b231ae4SDavid Sterba 					   int slot)
997bb803951SChris Mason {
998ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
999789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1000416bc658SJosef Bacik 	struct extent_buffer *eb;
1001416bc658SJosef Bacik 
1002fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
1003fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
1004ca7a79adSChris Mason 
1005d4694728SJosef Bacik 	ASSERT(level);
1006ca7a79adSChris Mason 
1007789d6a3aSQu Wenruo 	check.level = level - 1;
1008789d6a3aSQu Wenruo 	check.transid = btrfs_node_ptr_generation(parent, slot);
1009789d6a3aSQu Wenruo 	check.owner_root = btrfs_header_owner(parent);
1010789d6a3aSQu Wenruo 	check.has_first_key = true;
1011789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(parent, &check.first_key, slot);
1012789d6a3aSQu Wenruo 
1013d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1014789d6a3aSQu Wenruo 			     &check);
10154eb150d6SQu Wenruo 	if (IS_ERR(eb))
10164eb150d6SQu Wenruo 		return eb;
10174eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
1018416bc658SJosef Bacik 		free_extent_buffer(eb);
10194eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
1020416bc658SJosef Bacik 	}
1021416bc658SJosef Bacik 
1022416bc658SJosef Bacik 	return eb;
1023bb803951SChris Mason }
1024bb803951SChris Mason 
1025d352ac68SChris Mason /*
1026d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1027d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1028d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1029d352ac68SChris Mason  */
1030e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
103198ed5174SChris Mason 			 struct btrfs_root *root,
103298ed5174SChris Mason 			 struct btrfs_path *path, int level)
1033bb803951SChris Mason {
10340b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10355f39d397SChris Mason 	struct extent_buffer *right = NULL;
10365f39d397SChris Mason 	struct extent_buffer *mid;
10375f39d397SChris Mason 	struct extent_buffer *left = NULL;
10385f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1039bb803951SChris Mason 	int ret = 0;
1040bb803951SChris Mason 	int wret;
1041bb803951SChris Mason 	int pslot;
1042bb803951SChris Mason 	int orig_slot = path->slots[level];
104379f95c82SChris Mason 	u64 orig_ptr;
1044bb803951SChris Mason 
104598e6b1ebSLiu Bo 	ASSERT(level > 0);
1046bb803951SChris Mason 
10475f39d397SChris Mason 	mid = path->nodes[level];
1048b4ce94deSChris Mason 
1049ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
10507bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
10517bb86316SChris Mason 
10521d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
105379f95c82SChris Mason 
1054a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
10555f39d397SChris Mason 		parent = path->nodes[level + 1];
1056bb803951SChris Mason 		pslot = path->slots[level + 1];
1057a05a9bb1SLi Zefan 	}
1058bb803951SChris Mason 
105940689478SChris Mason 	/*
106040689478SChris Mason 	 * deal with the case where there is only one pointer in the root
106140689478SChris Mason 	 * by promoting the node below to a root
106240689478SChris Mason 	 */
10635f39d397SChris Mason 	if (!parent) {
10645f39d397SChris Mason 		struct extent_buffer *child;
1065bb803951SChris Mason 
10665f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1067bb803951SChris Mason 			return 0;
1068bb803951SChris Mason 
1069bb803951SChris Mason 		/* promote the child to a root */
10704b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1071fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1072fb770ae4SLiu Bo 			ret = PTR_ERR(child);
1073daefe4d4SFilipe Manana 			goto out;
1074305a26afSMark Fasheh 		}
1075305a26afSMark Fasheh 
1076925baeddSChris Mason 		btrfs_tree_lock(child);
10779631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
10789631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
1079f0486c68SYan, Zheng 		if (ret) {
1080f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1081f0486c68SYan, Zheng 			free_extent_buffer(child);
1082daefe4d4SFilipe Manana 			goto out;
1083f0486c68SYan, Zheng 		}
10842f375ab9SYan 
1085406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
108639020d8aSFilipe Manana 		if (ret < 0) {
108739020d8aSFilipe Manana 			btrfs_tree_unlock(child);
108839020d8aSFilipe Manana 			free_extent_buffer(child);
108939020d8aSFilipe Manana 			btrfs_abort_transaction(trans, ret);
1090daefe4d4SFilipe Manana 			goto out;
109139020d8aSFilipe Manana 		}
1092240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1093925baeddSChris Mason 
10940b86a832SChris Mason 		add_root_to_dirty_list(root);
1095925baeddSChris Mason 		btrfs_tree_unlock(child);
1096b4ce94deSChris Mason 
1097925baeddSChris Mason 		path->locks[level] = 0;
1098bb803951SChris Mason 		path->nodes[level] = NULL;
1099190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, mid);
1100925baeddSChris Mason 		btrfs_tree_unlock(mid);
1101bb803951SChris Mason 		/* once for the path */
11025f39d397SChris Mason 		free_extent_buffer(mid);
1103f0486c68SYan, Zheng 
1104f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
11057a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1106bb803951SChris Mason 		/* once for the root ptr */
11073083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1108f0486c68SYan, Zheng 		return 0;
1109bb803951SChris Mason 	}
11105f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
11110b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1112bb803951SChris Mason 		return 0;
1113bb803951SChris Mason 
11149cf14029SJosef Bacik 	if (pslot) {
11154b231ae4SDavid Sterba 		left = btrfs_read_node_slot(parent, pslot - 1);
11169cf14029SJosef Bacik 		if (IS_ERR(left)) {
11179cf14029SJosef Bacik 			ret = PTR_ERR(left);
1118fb770ae4SLiu Bo 			left = NULL;
1119daefe4d4SFilipe Manana 			goto out;
11209cf14029SJosef Bacik 		}
1121fb770ae4SLiu Bo 
1122bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
11235f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
11249631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
1125bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
112654aa1f4dSChris Mason 		if (wret) {
112754aa1f4dSChris Mason 			ret = wret;
1128daefe4d4SFilipe Manana 			goto out;
112954aa1f4dSChris Mason 		}
11302cc58cf2SChris Mason 	}
1131fb770ae4SLiu Bo 
11329cf14029SJosef Bacik 	if (pslot + 1 < btrfs_header_nritems(parent)) {
11334b231ae4SDavid Sterba 		right = btrfs_read_node_slot(parent, pslot + 1);
11349cf14029SJosef Bacik 		if (IS_ERR(right)) {
11359cf14029SJosef Bacik 			ret = PTR_ERR(right);
1136fb770ae4SLiu Bo 			right = NULL;
1137daefe4d4SFilipe Manana 			goto out;
11389cf14029SJosef Bacik 		}
1139fb770ae4SLiu Bo 
1140bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
11415f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
11429631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
1143bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
11442cc58cf2SChris Mason 		if (wret) {
11452cc58cf2SChris Mason 			ret = wret;
1146daefe4d4SFilipe Manana 			goto out;
11472cc58cf2SChris Mason 		}
11482cc58cf2SChris Mason 	}
11492cc58cf2SChris Mason 
11502cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
11515f39d397SChris Mason 	if (left) {
11525f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1153d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
115479f95c82SChris Mason 		if (wret < 0)
115579f95c82SChris Mason 			ret = wret;
1156bb803951SChris Mason 	}
115779f95c82SChris Mason 
115879f95c82SChris Mason 	/*
115979f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
116079f95c82SChris Mason 	 */
11615f39d397SChris Mason 	if (right) {
1162d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
116354aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
116479f95c82SChris Mason 			ret = wret;
11655f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
1166190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, right);
1167925baeddSChris Mason 			btrfs_tree_unlock(right);
1168751a2761SFilipe Manana 			ret = btrfs_del_ptr(trans, root, path, level + 1, pslot + 1);
1169751a2761SFilipe Manana 			if (ret < 0) {
1170751a2761SFilipe Manana 				free_extent_buffer_stale(right);
1171751a2761SFilipe Manana 				right = NULL;
1172751a2761SFilipe Manana 				goto out;
1173751a2761SFilipe Manana 			}
1174f0486c68SYan, Zheng 			root_sub_used(root, right->len);
11757a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
11767a163608SFilipe Manana 					      0, 1);
11773083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1178f0486c68SYan, Zheng 			right = NULL;
1179bb803951SChris Mason 		} else {
11805f39d397SChris Mason 			struct btrfs_disk_key right_key;
11815f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1182f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
118333cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
118439020d8aSFilipe Manana 			if (ret < 0) {
118539020d8aSFilipe Manana 				btrfs_abort_transaction(trans, ret);
1186daefe4d4SFilipe Manana 				goto out;
118739020d8aSFilipe Manana 			}
11885f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
11895f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1190bb803951SChris Mason 		}
1191bb803951SChris Mason 	}
11925f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
119379f95c82SChris Mason 		/*
119479f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
119579f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
119679f95c82SChris Mason 		 * could try to delete the only pointer in this node.
119779f95c82SChris Mason 		 * So, pull some keys from the left.
119879f95c82SChris Mason 		 * There has to be a left pointer at this point because
119979f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
120079f95c82SChris Mason 		 * right
120179f95c82SChris Mason 		 */
1202725026edSFilipe Manana 		if (unlikely(!left)) {
1203725026edSFilipe Manana 			btrfs_crit(fs_info,
1204725026edSFilipe Manana "missing left child when middle child only has 1 item, parent bytenr %llu level %d mid bytenr %llu root %llu",
1205725026edSFilipe Manana 				   parent->start, btrfs_header_level(parent),
1206725026edSFilipe Manana 				   mid->start, btrfs_root_id(root));
1207725026edSFilipe Manana 			ret = -EUCLEAN;
1208725026edSFilipe Manana 			btrfs_abort_transaction(trans, ret);
1209daefe4d4SFilipe Manana 			goto out;
1210305a26afSMark Fasheh 		}
121155d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
121254aa1f4dSChris Mason 		if (wret < 0) {
121379f95c82SChris Mason 			ret = wret;
1214daefe4d4SFilipe Manana 			goto out;
121554aa1f4dSChris Mason 		}
1216bce4eae9SChris Mason 		if (wret == 1) {
1217d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1218bce4eae9SChris Mason 			if (wret < 0)
1219bce4eae9SChris Mason 				ret = wret;
1220bce4eae9SChris Mason 		}
122179f95c82SChris Mason 		BUG_ON(wret == 1);
122279f95c82SChris Mason 	}
12235f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
1224190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, mid);
1225925baeddSChris Mason 		btrfs_tree_unlock(mid);
1226751a2761SFilipe Manana 		ret = btrfs_del_ptr(trans, root, path, level + 1, pslot);
1227751a2761SFilipe Manana 		if (ret < 0) {
1228751a2761SFilipe Manana 			free_extent_buffer_stale(mid);
1229751a2761SFilipe Manana 			mid = NULL;
1230751a2761SFilipe Manana 			goto out;
1231751a2761SFilipe Manana 		}
1232f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
12337a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
12343083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1235f0486c68SYan, Zheng 		mid = NULL;
123679f95c82SChris Mason 	} else {
123779f95c82SChris Mason 		/* update the parent key to reflect our changes */
12385f39d397SChris Mason 		struct btrfs_disk_key mid_key;
12395f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1240f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
124133cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
124239020d8aSFilipe Manana 		if (ret < 0) {
124339020d8aSFilipe Manana 			btrfs_abort_transaction(trans, ret);
1244daefe4d4SFilipe Manana 			goto out;
124539020d8aSFilipe Manana 		}
12465f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
12475f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
124879f95c82SChris Mason 	}
1249bb803951SChris Mason 
125079f95c82SChris Mason 	/* update the path */
12515f39d397SChris Mason 	if (left) {
12525f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
125367439dadSDavid Sterba 			atomic_inc(&left->refs);
1254925baeddSChris Mason 			/* left was locked after cow */
12555f39d397SChris Mason 			path->nodes[level] = left;
1256bb803951SChris Mason 			path->slots[level + 1] -= 1;
1257bb803951SChris Mason 			path->slots[level] = orig_slot;
1258925baeddSChris Mason 			if (mid) {
1259925baeddSChris Mason 				btrfs_tree_unlock(mid);
12605f39d397SChris Mason 				free_extent_buffer(mid);
1261925baeddSChris Mason 			}
1262bb803951SChris Mason 		} else {
12635f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1264bb803951SChris Mason 			path->slots[level] = orig_slot;
1265bb803951SChris Mason 		}
1266bb803951SChris Mason 	}
126779f95c82SChris Mason 	/* double check we haven't messed things up */
1268e20d96d6SChris Mason 	if (orig_ptr !=
12695f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
127079f95c82SChris Mason 		BUG();
1271daefe4d4SFilipe Manana out:
1272925baeddSChris Mason 	if (right) {
1273925baeddSChris Mason 		btrfs_tree_unlock(right);
12745f39d397SChris Mason 		free_extent_buffer(right);
1275925baeddSChris Mason 	}
1276925baeddSChris Mason 	if (left) {
1277925baeddSChris Mason 		if (path->nodes[level] != left)
1278925baeddSChris Mason 			btrfs_tree_unlock(left);
12795f39d397SChris Mason 		free_extent_buffer(left);
1280925baeddSChris Mason 	}
1281bb803951SChris Mason 	return ret;
1282bb803951SChris Mason }
1283bb803951SChris Mason 
1284d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1285d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1286d352ac68SChris Mason  * have to be pessimistic.
1287d352ac68SChris Mason  */
1288d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1289e66f709bSChris Mason 					  struct btrfs_root *root,
1290e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1291e66f709bSChris Mason {
12920b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12935f39d397SChris Mason 	struct extent_buffer *right = NULL;
12945f39d397SChris Mason 	struct extent_buffer *mid;
12955f39d397SChris Mason 	struct extent_buffer *left = NULL;
12965f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1297e66f709bSChris Mason 	int ret = 0;
1298e66f709bSChris Mason 	int wret;
1299e66f709bSChris Mason 	int pslot;
1300e66f709bSChris Mason 	int orig_slot = path->slots[level];
1301e66f709bSChris Mason 
1302e66f709bSChris Mason 	if (level == 0)
1303e66f709bSChris Mason 		return 1;
1304e66f709bSChris Mason 
13055f39d397SChris Mason 	mid = path->nodes[level];
13067bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1307e66f709bSChris Mason 
1308a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
13095f39d397SChris Mason 		parent = path->nodes[level + 1];
1310e66f709bSChris Mason 		pslot = path->slots[level + 1];
1311a05a9bb1SLi Zefan 	}
1312e66f709bSChris Mason 
13135f39d397SChris Mason 	if (!parent)
1314e66f709bSChris Mason 		return 1;
1315e66f709bSChris Mason 
13169cf14029SJosef Bacik 	/* first, try to make some room in the middle buffer */
13179cf14029SJosef Bacik 	if (pslot) {
13189cf14029SJosef Bacik 		u32 left_nr;
13199cf14029SJosef Bacik 
13204b231ae4SDavid Sterba 		left = btrfs_read_node_slot(parent, pslot - 1);
1321fb770ae4SLiu Bo 		if (IS_ERR(left))
13229cf14029SJosef Bacik 			return PTR_ERR(left);
1323925baeddSChris Mason 
1324bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1325b4ce94deSChris Mason 
13265f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
13270b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
132833ade1f8SChris Mason 			wret = 1;
132933ade1f8SChris Mason 		} else {
13305f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
13319631e4ccSJosef Bacik 					      pslot - 1, &left,
1332bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
133354aa1f4dSChris Mason 			if (ret)
133454aa1f4dSChris Mason 				wret = 1;
133554aa1f4dSChris Mason 			else {
1336d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
133754aa1f4dSChris Mason 			}
133833ade1f8SChris Mason 		}
1339e66f709bSChris Mason 		if (wret < 0)
1340e66f709bSChris Mason 			ret = wret;
1341e66f709bSChris Mason 		if (wret == 0) {
13425f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1343e66f709bSChris Mason 			orig_slot += left_nr;
13445f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1345f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
134633cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
134711d6ae03SFilipe Manana 			if (ret < 0) {
134811d6ae03SFilipe Manana 				btrfs_tree_unlock(left);
134911d6ae03SFilipe Manana 				free_extent_buffer(left);
135011d6ae03SFilipe Manana 				btrfs_abort_transaction(trans, ret);
135111d6ae03SFilipe Manana 				return ret;
135211d6ae03SFilipe Manana 			}
13535f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
13545f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
13555f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
13565f39d397SChris Mason 				path->nodes[level] = left;
1357e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1358e66f709bSChris Mason 				path->slots[level] = orig_slot;
1359925baeddSChris Mason 				btrfs_tree_unlock(mid);
13605f39d397SChris Mason 				free_extent_buffer(mid);
1361e66f709bSChris Mason 			} else {
1362e66f709bSChris Mason 				orig_slot -=
13635f39d397SChris Mason 					btrfs_header_nritems(left);
1364e66f709bSChris Mason 				path->slots[level] = orig_slot;
1365925baeddSChris Mason 				btrfs_tree_unlock(left);
13665f39d397SChris Mason 				free_extent_buffer(left);
1367e66f709bSChris Mason 			}
1368e66f709bSChris Mason 			return 0;
1369e66f709bSChris Mason 		}
1370925baeddSChris Mason 		btrfs_tree_unlock(left);
13715f39d397SChris Mason 		free_extent_buffer(left);
1372e66f709bSChris Mason 	}
1373e66f709bSChris Mason 
1374e66f709bSChris Mason 	/*
1375e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1376e66f709bSChris Mason 	 */
13779cf14029SJosef Bacik 	if (pslot + 1 < btrfs_header_nritems(parent)) {
137833ade1f8SChris Mason 		u32 right_nr;
1379b4ce94deSChris Mason 
13809cf14029SJosef Bacik 		right = btrfs_read_node_slot(parent, pslot + 1);
13819cf14029SJosef Bacik 		if (IS_ERR(right))
13829cf14029SJosef Bacik 			return PTR_ERR(right);
13839cf14029SJosef Bacik 
1384bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1385b4ce94deSChris Mason 
13865f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
13870b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
138833ade1f8SChris Mason 			wret = 1;
138933ade1f8SChris Mason 		} else {
13905f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
13915f39d397SChris Mason 					      parent, pslot + 1,
1392bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
139354aa1f4dSChris Mason 			if (ret)
139454aa1f4dSChris Mason 				wret = 1;
139554aa1f4dSChris Mason 			else {
139655d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
139733ade1f8SChris Mason 			}
139854aa1f4dSChris Mason 		}
1399e66f709bSChris Mason 		if (wret < 0)
1400e66f709bSChris Mason 			ret = wret;
1401e66f709bSChris Mason 		if (wret == 0) {
14025f39d397SChris Mason 			struct btrfs_disk_key disk_key;
14035f39d397SChris Mason 
14045f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1405f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
140633cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
140711d6ae03SFilipe Manana 			if (ret < 0) {
140811d6ae03SFilipe Manana 				btrfs_tree_unlock(right);
140911d6ae03SFilipe Manana 				free_extent_buffer(right);
141011d6ae03SFilipe Manana 				btrfs_abort_transaction(trans, ret);
141111d6ae03SFilipe Manana 				return ret;
141211d6ae03SFilipe Manana 			}
14135f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
14145f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
14155f39d397SChris Mason 
14165f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
14175f39d397SChris Mason 				path->nodes[level] = right;
1418e66f709bSChris Mason 				path->slots[level + 1] += 1;
1419e66f709bSChris Mason 				path->slots[level] = orig_slot -
14205f39d397SChris Mason 					btrfs_header_nritems(mid);
1421925baeddSChris Mason 				btrfs_tree_unlock(mid);
14225f39d397SChris Mason 				free_extent_buffer(mid);
1423e66f709bSChris Mason 			} else {
1424925baeddSChris Mason 				btrfs_tree_unlock(right);
14255f39d397SChris Mason 				free_extent_buffer(right);
1426e66f709bSChris Mason 			}
1427e66f709bSChris Mason 			return 0;
1428e66f709bSChris Mason 		}
1429925baeddSChris Mason 		btrfs_tree_unlock(right);
14305f39d397SChris Mason 		free_extent_buffer(right);
1431e66f709bSChris Mason 	}
1432e66f709bSChris Mason 	return 1;
1433e66f709bSChris Mason }
1434e66f709bSChris Mason 
143574123bd7SChris Mason /*
1436d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1437d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
14383c69faecSChris Mason  */
14392ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1440e02119d5SChris Mason 			     struct btrfs_path *path,
144101f46658SChris Mason 			     int level, int slot, u64 objectid)
14423c69faecSChris Mason {
14435f39d397SChris Mason 	struct extent_buffer *node;
144401f46658SChris Mason 	struct btrfs_disk_key disk_key;
14453c69faecSChris Mason 	u32 nritems;
14463c69faecSChris Mason 	u64 search;
1447a7175319SChris Mason 	u64 target;
14486b80053dSChris Mason 	u64 nread = 0;
1449ace75066SFilipe Manana 	u64 nread_max;
14506b80053dSChris Mason 	u32 nr;
14516b80053dSChris Mason 	u32 blocksize;
14526b80053dSChris Mason 	u32 nscan = 0;
1453db94535dSChris Mason 
1454ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
14553c69faecSChris Mason 		return;
14563c69faecSChris Mason 
14576702ed49SChris Mason 	if (!path->nodes[level])
14586702ed49SChris Mason 		return;
14596702ed49SChris Mason 
14605f39d397SChris Mason 	node = path->nodes[level];
1461925baeddSChris Mason 
1462ace75066SFilipe Manana 	/*
1463ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1464ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1465ace75066SFilipe Manana 	 * much IO at once (possibly random).
1466ace75066SFilipe Manana 	 */
1467ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1468ace75066SFilipe Manana 		if (level > 1)
1469ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1470ace75066SFilipe Manana 		else
1471ace75066SFilipe Manana 			nread_max = SZ_128K;
1472ace75066SFilipe Manana 	} else {
1473ace75066SFilipe Manana 		nread_max = SZ_64K;
1474ace75066SFilipe Manana 	}
1475ace75066SFilipe Manana 
14763c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
14770b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1478069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1479069a2e37SFilipe Manana 		struct extent_buffer *eb;
1480069a2e37SFilipe Manana 
14810b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
14825f39d397SChris Mason 		if (eb) {
14835f39d397SChris Mason 			free_extent_buffer(eb);
14843c69faecSChris Mason 			return;
14853c69faecSChris Mason 		}
1486069a2e37SFilipe Manana 	}
14873c69faecSChris Mason 
1488a7175319SChris Mason 	target = search;
14896b80053dSChris Mason 
14905f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
14916b80053dSChris Mason 	nr = slot;
149225b8b936SJosef Bacik 
14933c69faecSChris Mason 	while (1) {
1494e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
14956b80053dSChris Mason 			if (nr == 0)
14963c69faecSChris Mason 				break;
14976b80053dSChris Mason 			nr--;
1498ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1499ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
15006b80053dSChris Mason 			nr++;
15016b80053dSChris Mason 			if (nr >= nritems)
15026b80053dSChris Mason 				break;
15033c69faecSChris Mason 		}
1504e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
150501f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
150601f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
150701f46658SChris Mason 				break;
150801f46658SChris Mason 		}
15096b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1510ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1511ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1512a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1513bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
15146b80053dSChris Mason 			nread += blocksize;
15153c69faecSChris Mason 		}
15166b80053dSChris Mason 		nscan++;
1517ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
15186b80053dSChris Mason 			break;
15193c69faecSChris Mason 	}
15203c69faecSChris Mason }
1521925baeddSChris Mason 
1522bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1523b4ce94deSChris Mason {
1524bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1525b4ce94deSChris Mason 	int slot;
1526b4ce94deSChris Mason 	int nritems;
1527b4ce94deSChris Mason 
15288c594ea8SChris Mason 	parent = path->nodes[level + 1];
1529b4ce94deSChris Mason 	if (!parent)
15300b08851fSJosef Bacik 		return;
1531b4ce94deSChris Mason 
1532b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
15338c594ea8SChris Mason 	slot = path->slots[level + 1];
1534b4ce94deSChris Mason 
1535bfb484d9SJosef Bacik 	if (slot > 0)
1536bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1537bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1538bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1539b4ce94deSChris Mason }
1540b4ce94deSChris Mason 
1541b4ce94deSChris Mason 
1542b4ce94deSChris Mason /*
1543d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1544d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1545d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1546d397712bSChris Mason  * tree.
1547d352ac68SChris Mason  *
1548d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1549d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1550d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1551d352ac68SChris Mason  *
1552d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1553d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1554d352ac68SChris Mason  */
1555e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1556f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1557f7c79f30SChris Mason 			       int *write_lock_level)
1558925baeddSChris Mason {
1559925baeddSChris Mason 	int i;
1560925baeddSChris Mason 	int skip_level = level;
1561c1227996SNikolay Borisov 	bool check_skip = true;
1562925baeddSChris Mason 
1563925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1564925baeddSChris Mason 		if (!path->nodes[i])
1565925baeddSChris Mason 			break;
1566925baeddSChris Mason 		if (!path->locks[i])
1567925baeddSChris Mason 			break;
1568c1227996SNikolay Borisov 
1569c1227996SNikolay Borisov 		if (check_skip) {
1570c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1571925baeddSChris Mason 				skip_level = i + 1;
1572925baeddSChris Mason 				continue;
1573925baeddSChris Mason 			}
1574c1227996SNikolay Borisov 
1575c1227996SNikolay Borisov 			if (path->keep_locks) {
1576925baeddSChris Mason 				u32 nritems;
1577c1227996SNikolay Borisov 
1578c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1579051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1580925baeddSChris Mason 					skip_level = i + 1;
1581925baeddSChris Mason 					continue;
1582925baeddSChris Mason 				}
1583925baeddSChris Mason 			}
1584c1227996SNikolay Borisov 		}
1585051e1b9fSChris Mason 
1586d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1587c1227996SNikolay Borisov 			check_skip = false;
1588c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1589925baeddSChris Mason 			path->locks[i] = 0;
1590f7c79f30SChris Mason 			if (write_lock_level &&
1591f7c79f30SChris Mason 			    i > min_write_lock_level &&
1592f7c79f30SChris Mason 			    i <= *write_lock_level) {
1593f7c79f30SChris Mason 				*write_lock_level = i - 1;
1594f7c79f30SChris Mason 			}
1595925baeddSChris Mason 		}
1596925baeddSChris Mason 	}
1597925baeddSChris Mason }
1598925baeddSChris Mason 
15993c69faecSChris Mason /*
1600376a21d7SFilipe Manana  * Helper function for btrfs_search_slot() and other functions that do a search
1601376a21d7SFilipe Manana  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1602376a21d7SFilipe Manana  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1603376a21d7SFilipe Manana  * its pages from disk.
1604c8c42864SChris Mason  *
1605376a21d7SFilipe Manana  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1606376a21d7SFilipe Manana  * whole btree search, starting again from the current root node.
1607c8c42864SChris Mason  */
1608c8c42864SChris Mason static int
1609d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1610c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1611cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1612c8c42864SChris Mason {
16130b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1614789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1615c8c42864SChris Mason 	u64 blocknr;
1616c8c42864SChris Mason 	u64 gen;
1617c8c42864SChris Mason 	struct extent_buffer *tmp;
161876a05b35SChris Mason 	int ret;
1619581c1760SQu Wenruo 	int parent_level;
1620b246666eSFilipe Manana 	bool unlock_up;
1621c8c42864SChris Mason 
1622b246666eSFilipe Manana 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1623213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1624213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1625213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1626789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(*eb_ret, &check.first_key, slot);
1627789d6a3aSQu Wenruo 	check.has_first_key = true;
1628789d6a3aSQu Wenruo 	check.level = parent_level - 1;
1629789d6a3aSQu Wenruo 	check.transid = gen;
1630789d6a3aSQu Wenruo 	check.owner_root = root->root_key.objectid;
1631c8c42864SChris Mason 
1632b246666eSFilipe Manana 	/*
1633b246666eSFilipe Manana 	 * If we need to read an extent buffer from disk and we are holding locks
1634b246666eSFilipe Manana 	 * on upper level nodes, we unlock all the upper nodes before reading the
1635b246666eSFilipe Manana 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1636b246666eSFilipe Manana 	 * restart the search. We don't release the lock on the current level
1637b246666eSFilipe Manana 	 * because we need to walk this node to figure out which blocks to read.
1638b246666eSFilipe Manana 	 */
16390b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1640cb44921aSChris Mason 	if (tmp) {
1641ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1642ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1643ace75066SFilipe Manana 
1644b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1645b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1646448de471SQu Wenruo 			/*
1647448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1648448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1649448de471SQu Wenruo 			 * parents (shared tree blocks).
1650448de471SQu Wenruo 			 */
1651e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1652789d6a3aSQu Wenruo 					parent_level - 1, &check.first_key, gen)) {
1653448de471SQu Wenruo 				free_extent_buffer(tmp);
1654448de471SQu Wenruo 				return -EUCLEAN;
1655448de471SQu Wenruo 			}
1656c8c42864SChris Mason 			*eb_ret = tmp;
1657c8c42864SChris Mason 			return 0;
1658c8c42864SChris Mason 		}
1659bdf7c00eSJosef Bacik 
1660857bc13fSJosef Bacik 		if (p->nowait) {
1661857bc13fSJosef Bacik 			free_extent_buffer(tmp);
1662857bc13fSJosef Bacik 			return -EAGAIN;
1663857bc13fSJosef Bacik 		}
1664857bc13fSJosef Bacik 
1665b246666eSFilipe Manana 		if (unlock_up)
1666b246666eSFilipe Manana 			btrfs_unlock_up_safe(p, level + 1);
1667b246666eSFilipe Manana 
1668b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
1669789d6a3aSQu Wenruo 		ret = btrfs_read_extent_buffer(tmp, &check);
16709a4ffa1bSQu Wenruo 		if (ret) {
1671cb44921aSChris Mason 			free_extent_buffer(tmp);
1672b3b4aa74SDavid Sterba 			btrfs_release_path(p);
1673cb44921aSChris Mason 			return -EIO;
1674cb44921aSChris Mason 		}
167588c602abSQu Wenruo 		if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
167688c602abSQu Wenruo 			free_extent_buffer(tmp);
167788c602abSQu Wenruo 			btrfs_release_path(p);
167888c602abSQu Wenruo 			return -EUCLEAN;
167988c602abSQu Wenruo 		}
1680b246666eSFilipe Manana 
1681b246666eSFilipe Manana 		if (unlock_up)
1682b246666eSFilipe Manana 			ret = -EAGAIN;
1683b246666eSFilipe Manana 
1684b246666eSFilipe Manana 		goto out;
1685857bc13fSJosef Bacik 	} else if (p->nowait) {
1686857bc13fSJosef Bacik 		return -EAGAIN;
16879a4ffa1bSQu Wenruo 	}
1688c8c42864SChris Mason 
1689b246666eSFilipe Manana 	if (unlock_up) {
16908c594ea8SChris Mason 		btrfs_unlock_up_safe(p, level + 1);
16914bb59055SFilipe Manana 		ret = -EAGAIN;
16924bb59055SFilipe Manana 	} else {
16934bb59055SFilipe Manana 		ret = 0;
16944bb59055SFilipe Manana 	}
16958c594ea8SChris Mason 
1696e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
16972ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1698c8c42864SChris Mason 
1699789d6a3aSQu Wenruo 	tmp = read_tree_block(fs_info, blocknr, &check);
17004eb150d6SQu Wenruo 	if (IS_ERR(tmp)) {
17014eb150d6SQu Wenruo 		btrfs_release_path(p);
17024eb150d6SQu Wenruo 		return PTR_ERR(tmp);
17034eb150d6SQu Wenruo 	}
170476a05b35SChris Mason 	/*
170576a05b35SChris Mason 	 * If the read above didn't mark this buffer up to date,
170676a05b35SChris Mason 	 * it will never end up being up to date.  Set ret to EIO now
170776a05b35SChris Mason 	 * and give up so that our caller doesn't loop forever
170876a05b35SChris Mason 	 * on our EAGAINs.
170976a05b35SChris Mason 	 */
1710e6a1d6fdSLiu Bo 	if (!extent_buffer_uptodate(tmp))
171176a05b35SChris Mason 		ret = -EIO;
171202a3307aSLiu Bo 
1713b246666eSFilipe Manana out:
17144bb59055SFilipe Manana 	if (ret == 0) {
17154bb59055SFilipe Manana 		*eb_ret = tmp;
17164bb59055SFilipe Manana 	} else {
17174bb59055SFilipe Manana 		free_extent_buffer(tmp);
171802a3307aSLiu Bo 		btrfs_release_path(p);
17194bb59055SFilipe Manana 	}
17204bb59055SFilipe Manana 
172176a05b35SChris Mason 	return ret;
1722c8c42864SChris Mason }
1723c8c42864SChris Mason 
1724c8c42864SChris Mason /*
1725c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1726c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1727c8c42864SChris Mason  * the ins_len.
1728c8c42864SChris Mason  *
1729c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1730c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1731c8c42864SChris Mason  * start over
1732c8c42864SChris Mason  */
1733c8c42864SChris Mason static int
1734c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1735c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1736bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1737bd681513SChris Mason 		       int *write_lock_level)
1738c8c42864SChris Mason {
17390b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
174095b982deSNikolay Borisov 	int ret = 0;
17410b246afaSJeff Mahoney 
1742c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
17430b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1744c8c42864SChris Mason 
1745bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1746bd681513SChris Mason 			*write_lock_level = level + 1;
1747bd681513SChris Mason 			btrfs_release_path(p);
174895b982deSNikolay Borisov 			return -EAGAIN;
1749bd681513SChris Mason 		}
1750bd681513SChris Mason 
1751bfb484d9SJosef Bacik 		reada_for_balance(p, level);
175295b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1753c8c42864SChris Mason 
1754c8c42864SChris Mason 		b = p->nodes[level];
1755c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
17560b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1757c8c42864SChris Mason 
1758bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1759bd681513SChris Mason 			*write_lock_level = level + 1;
1760bd681513SChris Mason 			btrfs_release_path(p);
176195b982deSNikolay Borisov 			return -EAGAIN;
1762bd681513SChris Mason 		}
1763bd681513SChris Mason 
1764bfb484d9SJosef Bacik 		reada_for_balance(p, level);
176595b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
176695b982deSNikolay Borisov 		if (ret)
176795b982deSNikolay Borisov 			return ret;
1768c8c42864SChris Mason 
1769c8c42864SChris Mason 		b = p->nodes[level];
1770c8c42864SChris Mason 		if (!b) {
1771b3b4aa74SDavid Sterba 			btrfs_release_path(p);
177295b982deSNikolay Borisov 			return -EAGAIN;
1773c8c42864SChris Mason 		}
1774c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1775c8c42864SChris Mason 	}
1776c8c42864SChris Mason 	return ret;
1777c8c42864SChris Mason }
1778c8c42864SChris Mason 
1779381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1780e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1781e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1782e33d5c3dSKelley Nielsen {
1783e33d5c3dSKelley Nielsen 	int ret;
1784e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1785e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1786381cf658SDavid Sterba 
1787381cf658SDavid Sterba 	ASSERT(path);
17881d4c08e0SDavid Sterba 	ASSERT(found_key);
1789e33d5c3dSKelley Nielsen 
1790e33d5c3dSKelley Nielsen 	key.type = key_type;
1791e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1792e33d5c3dSKelley Nielsen 	key.offset = ioff;
1793e33d5c3dSKelley Nielsen 
1794e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
17951d4c08e0SDavid Sterba 	if (ret < 0)
1796e33d5c3dSKelley Nielsen 		return ret;
1797e33d5c3dSKelley Nielsen 
1798e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1799e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1800e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1801e33d5c3dSKelley Nielsen 		if (ret)
1802e33d5c3dSKelley Nielsen 			return ret;
1803e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1804e33d5c3dSKelley Nielsen 	}
1805e33d5c3dSKelley Nielsen 
1806e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1807e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1808e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1809e33d5c3dSKelley Nielsen 		return 1;
1810e33d5c3dSKelley Nielsen 
1811e33d5c3dSKelley Nielsen 	return 0;
1812e33d5c3dSKelley Nielsen }
1813e33d5c3dSKelley Nielsen 
18141fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
18151fc28d8eSLiu Bo 							struct btrfs_path *p,
18161fc28d8eSLiu Bo 							int write_lock_level)
18171fc28d8eSLiu Bo {
18181fc28d8eSLiu Bo 	struct extent_buffer *b;
1819120de408SJosef Bacik 	int root_lock = 0;
18201fc28d8eSLiu Bo 	int level = 0;
18211fc28d8eSLiu Bo 
18221fc28d8eSLiu Bo 	if (p->search_commit_root) {
18231fc28d8eSLiu Bo 		b = root->commit_root;
182467439dadSDavid Sterba 		atomic_inc(&b->refs);
18251fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1826f9ddfd05SLiu Bo 		/*
1827f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1828f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1829f9ddfd05SLiu Bo 		 */
1830f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
18311fc28d8eSLiu Bo 
18321fc28d8eSLiu Bo 		goto out;
18331fc28d8eSLiu Bo 	}
18341fc28d8eSLiu Bo 
18351fc28d8eSLiu Bo 	if (p->skip_locking) {
18361fc28d8eSLiu Bo 		b = btrfs_root_node(root);
18371fc28d8eSLiu Bo 		level = btrfs_header_level(b);
18381fc28d8eSLiu Bo 		goto out;
18391fc28d8eSLiu Bo 	}
18401fc28d8eSLiu Bo 
1841120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1842120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1843120de408SJosef Bacik 
18441fc28d8eSLiu Bo 	/*
1845662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1846662c653bSLiu Bo 	 * lock.
1847662c653bSLiu Bo 	 */
1848662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1849662c653bSLiu Bo 		/*
1850662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1851662c653bSLiu Bo 		 * have it read locked
18521fc28d8eSLiu Bo 		 */
1853857bc13fSJosef Bacik 		if (p->nowait) {
1854857bc13fSJosef Bacik 			b = btrfs_try_read_lock_root_node(root);
1855857bc13fSJosef Bacik 			if (IS_ERR(b))
1856857bc13fSJosef Bacik 				return b;
1857857bc13fSJosef Bacik 		} else {
18581bb96598SJosef Bacik 			b = btrfs_read_lock_root_node(root);
1859857bc13fSJosef Bacik 		}
18601fc28d8eSLiu Bo 		level = btrfs_header_level(b);
18611fc28d8eSLiu Bo 		if (level > write_lock_level)
18621fc28d8eSLiu Bo 			goto out;
18631fc28d8eSLiu Bo 
1864662c653bSLiu Bo 		/* Whoops, must trade for write lock */
18651fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
18661fc28d8eSLiu Bo 		free_extent_buffer(b);
1867662c653bSLiu Bo 	}
1868662c653bSLiu Bo 
18691fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
18701fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
18711fc28d8eSLiu Bo 
18721fc28d8eSLiu Bo 	/* The level might have changed, check again */
18731fc28d8eSLiu Bo 	level = btrfs_header_level(b);
18741fc28d8eSLiu Bo 
18751fc28d8eSLiu Bo out:
1876120de408SJosef Bacik 	/*
1877120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1878120de408SJosef Bacik 	 * longer valid, return an error in this case.
1879120de408SJosef Bacik 	 */
1880120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1881120de408SJosef Bacik 		if (root_lock)
1882120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1883120de408SJosef Bacik 		free_extent_buffer(b);
1884120de408SJosef Bacik 		return ERR_PTR(-EIO);
1885120de408SJosef Bacik 	}
1886120de408SJosef Bacik 
18871fc28d8eSLiu Bo 	p->nodes[level] = b;
18881fc28d8eSLiu Bo 	if (!p->skip_locking)
18891fc28d8eSLiu Bo 		p->locks[level] = root_lock;
18901fc28d8eSLiu Bo 	/*
18911fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
18921fc28d8eSLiu Bo 	 */
18931fc28d8eSLiu Bo 	return b;
18941fc28d8eSLiu Bo }
18951fc28d8eSLiu Bo 
1896d96b3424SFilipe Manana /*
1897d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1898d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1899d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1900d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1901d96b3424SFilipe Manana  * reallocated in the next transaction.
1902d96b3424SFilipe Manana  *
1903d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1904d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1905d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1906d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1907d96b3424SFilipe Manana  */
1908d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1909d96b3424SFilipe Manana {
1910d96b3424SFilipe Manana 	const int i = path->lowest_level;
1911d96b3424SFilipe Manana 	const int slot = path->slots[i];
1912d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1913d96b3424SFilipe Manana 	struct extent_buffer *clone;
1914d96b3424SFilipe Manana 
1915d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1916d96b3424SFilipe Manana 
1917d96b3424SFilipe Manana 	if (!lowest)
1918d96b3424SFilipe Manana 		return 0;
1919d96b3424SFilipe Manana 
1920d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1921d96b3424SFilipe Manana 
1922d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1923d96b3424SFilipe Manana 	if (!clone)
1924d96b3424SFilipe Manana 		return -ENOMEM;
1925d96b3424SFilipe Manana 
1926d96b3424SFilipe Manana 	btrfs_release_path(path);
1927d96b3424SFilipe Manana 	path->nodes[i] = clone;
1928d96b3424SFilipe Manana 	path->slots[i] = slot;
1929d96b3424SFilipe Manana 
1930d96b3424SFilipe Manana 	return 0;
1931d96b3424SFilipe Manana }
19321fc28d8eSLiu Bo 
1933e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1934e2e58d0fSFilipe Manana 				      int search_low_slot,
1935e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1936e2e58d0fSFilipe Manana 				      int prev_cmp,
1937e2e58d0fSFilipe Manana 				      int *slot)
1938e2e58d0fSFilipe Manana {
1939e2e58d0fSFilipe Manana 	/*
1940e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1941e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1942e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1943e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1944e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1945e2e58d0fSFilipe Manana 	 */
1946e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1947e2e58d0fSFilipe Manana 		*slot = 0;
1948e2e58d0fSFilipe Manana 		return 0;
1949e2e58d0fSFilipe Manana 	}
1950e2e58d0fSFilipe Manana 
1951fdf8d595SAnand Jain 	return btrfs_bin_search(eb, search_low_slot, key, slot);
1952e2e58d0fSFilipe Manana }
1953e2e58d0fSFilipe Manana 
1954109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1955109324cfSFilipe Manana 		       struct btrfs_root *root,
1956109324cfSFilipe Manana 		       const struct btrfs_key *key,
1957109324cfSFilipe Manana 		       struct btrfs_path *path,
1958109324cfSFilipe Manana 		       int ins_len,
1959109324cfSFilipe Manana 		       int prev_cmp)
1960109324cfSFilipe Manana {
1961109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
1962109324cfSFilipe Manana 	int leaf_free_space = -1;
1963109324cfSFilipe Manana 	int search_low_slot = 0;
1964109324cfSFilipe Manana 	int ret;
1965109324cfSFilipe Manana 	bool do_bin_search = true;
1966109324cfSFilipe Manana 
1967109324cfSFilipe Manana 	/*
1968109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
1969109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
1970109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
1971109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1972109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
1973109324cfSFilipe Manana 	 */
1974109324cfSFilipe Manana 	if (ins_len > 0) {
1975109324cfSFilipe Manana 		/*
1976109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
1977109324cfSFilipe Manana 		 * will not change until then.
1978109324cfSFilipe Manana 		 */
1979109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
1980109324cfSFilipe Manana 
1981109324cfSFilipe Manana 		/*
1982109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
1983109324cfSFilipe Manana 		 * the root of the tree.
1984109324cfSFilipe Manana 		 */
1985109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
1986109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
1987109324cfSFilipe Manana 
1988109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
1989109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
1990109324cfSFilipe Manana 
1991109324cfSFilipe Manana 			/*
1992109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
1993109324cfSFilipe Manana 			 * taking into account that the first key is very likely
1994109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
1995109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
1996109324cfSFilipe Manana 			 * the header's level field.
1997109324cfSFilipe Manana 			 */
1998109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
1999109324cfSFilipe Manana 			if (ret < 0) {
2000109324cfSFilipe Manana 				/*
2001109324cfSFilipe Manana 				 * The first key is smaller than the key we want
2002109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
2003109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
2004109324cfSFilipe Manana 				 *
2005109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
2006109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
2007109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
2008109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
2009109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
2010109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
2011109324cfSFilipe Manana 				 */
2012109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
2013109324cfSFilipe Manana 				search_low_slot = 1;
2014109324cfSFilipe Manana 			} else {
2015109324cfSFilipe Manana 				/*
2016109324cfSFilipe Manana 				 * The first key is >= then the key we want to
2017109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
2018109324cfSFilipe Manana 				 * the target key will be at slot 0.
2019109324cfSFilipe Manana 				 *
2020109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
2021109324cfSFilipe Manana 				 * less than the first key, because we will need
2022109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
2023109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
2024109324cfSFilipe Manana 				 * If the key matches the first key, then we can
2025109324cfSFilipe Manana 				 * unlock all the upper nodes, using
2026109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
2027109324cfSFilipe Manana 				 * as stated above.
2028109324cfSFilipe Manana 				 */
2029109324cfSFilipe Manana 				if (ret == 0)
2030109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
2031109324cfSFilipe Manana 				/*
2032109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
2033109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
2034109324cfSFilipe Manana 				 * to adjust it.
2035109324cfSFilipe Manana 				 */
2036109324cfSFilipe Manana 				do_bin_search = false;
2037109324cfSFilipe Manana 				path->slots[0] = 0;
2038109324cfSFilipe Manana 			}
2039109324cfSFilipe Manana 		}
2040109324cfSFilipe Manana 	}
2041109324cfSFilipe Manana 
2042109324cfSFilipe Manana 	if (do_bin_search) {
2043109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
2044109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
2045109324cfSFilipe Manana 		if (ret < 0)
2046109324cfSFilipe Manana 			return ret;
2047109324cfSFilipe Manana 	}
2048109324cfSFilipe Manana 
2049109324cfSFilipe Manana 	if (ins_len > 0) {
2050109324cfSFilipe Manana 		/*
2051109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
2052109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
2053109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
2054109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
2055109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
2056109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
2057109324cfSFilipe Manana 		 * check will be correct.
2058109324cfSFilipe Manana 		 */
2059109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
2060109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
2061109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
2062109324cfSFilipe Manana 		}
2063109324cfSFilipe Manana 
2064109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
2065109324cfSFilipe Manana 
2066109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
2067109324cfSFilipe Manana 			int err;
2068109324cfSFilipe Manana 
2069109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
2070109324cfSFilipe Manana 					 (ret == 0));
2071bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
2072bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
2073bb8e9a60SFilipe Manana 				err = -EUCLEAN;
2074109324cfSFilipe Manana 			if (err)
2075109324cfSFilipe Manana 				ret = err;
2076109324cfSFilipe Manana 		}
2077109324cfSFilipe Manana 	}
2078109324cfSFilipe Manana 
2079109324cfSFilipe Manana 	return ret;
2080109324cfSFilipe Manana }
2081109324cfSFilipe Manana 
2082c8c42864SChris Mason /*
20834271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
20844271eceaSNikolay Borisov  * modifications to preserve tree invariants.
208574123bd7SChris Mason  *
20864271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
20874271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
20884271eceaSNikolay Borisov  * @root:	The root node of the tree
20894271eceaSNikolay Borisov  * @key:	The key we are looking for
20909a664971Sethanwu  * @ins_len:	Indicates purpose of search:
20919a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
20929a664971Sethanwu  *              <0  for deletions
20939a664971Sethanwu  *               0  for plain searches, not modifying the tree
20949a664971Sethanwu  *
20959a664971Sethanwu  *              (*) If size of item inserted doesn't include
20969a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
20979a664971Sethanwu  *              be set.
20984271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
20994271eceaSNikolay Borisov  *		when modifying the tree.
210097571fd0SChris Mason  *
21014271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
21024271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
21034271eceaSNikolay Borisov  *
21044271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
21054271eceaSNikolay Borisov  * of the path (level 0)
21064271eceaSNikolay Borisov  *
21074271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
21084271eceaSNikolay Borisov  * points to the slot where it should be inserted
21094271eceaSNikolay Borisov  *
21104271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
21114271eceaSNikolay Borisov  * is returned
211274123bd7SChris Mason  */
2113310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2114310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2115310712b2SOmar Sandoval 		      int ins_len, int cow)
2116be0e5c09SChris Mason {
2117d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
21185f39d397SChris Mason 	struct extent_buffer *b;
2119be0e5c09SChris Mason 	int slot;
2120be0e5c09SChris Mason 	int ret;
212133c66f43SYan Zheng 	int err;
2122be0e5c09SChris Mason 	int level;
2123925baeddSChris Mason 	int lowest_unlock = 1;
2124bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2125bd681513SChris Mason 	int write_lock_level = 0;
21269f3a7427SChris Mason 	u8 lowest_level = 0;
2127f7c79f30SChris Mason 	int min_write_lock_level;
2128d7396f07SFilipe David Borba Manana 	int prev_cmp;
21299f3a7427SChris Mason 
2130a4c853afSChenXiaoSong 	might_sleep();
2131a4c853afSChenXiaoSong 
21326702ed49SChris Mason 	lowest_level = p->lowest_level;
2133323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
213422b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2135eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
213625179201SJosef Bacik 
2137857bc13fSJosef Bacik 	/*
2138857bc13fSJosef Bacik 	 * For now only allow nowait for read only operations.  There's no
2139857bc13fSJosef Bacik 	 * strict reason why we can't, we just only need it for reads so it's
2140857bc13fSJosef Bacik 	 * only implemented for reads.
2141857bc13fSJosef Bacik 	 */
2142857bc13fSJosef Bacik 	ASSERT(!p->nowait || !cow);
2143857bc13fSJosef Bacik 
2144bd681513SChris Mason 	if (ins_len < 0) {
2145925baeddSChris Mason 		lowest_unlock = 2;
214665b51a00SChris Mason 
2147bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2148bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2149bd681513SChris Mason 		 * for those levels as well
2150bd681513SChris Mason 		 */
2151bd681513SChris Mason 		write_lock_level = 2;
2152bd681513SChris Mason 	} else if (ins_len > 0) {
2153bd681513SChris Mason 		/*
2154bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2155bd681513SChris Mason 		 * level 1 so we can update keys
2156bd681513SChris Mason 		 */
2157bd681513SChris Mason 		write_lock_level = 1;
2158bd681513SChris Mason 	}
2159bd681513SChris Mason 
2160bd681513SChris Mason 	if (!cow)
2161bd681513SChris Mason 		write_lock_level = -1;
2162bd681513SChris Mason 
216309a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2164bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2165bd681513SChris Mason 
2166f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2167f7c79f30SChris Mason 
2168d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2169d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
2170857bc13fSJosef Bacik 		if (p->nowait) {
2171857bc13fSJosef Bacik 			if (!down_read_trylock(&fs_info->commit_root_sem))
2172857bc13fSJosef Bacik 				return -EAGAIN;
2173857bc13fSJosef Bacik 		} else {
2174d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
2175d96b3424SFilipe Manana 		}
2176857bc13fSJosef Bacik 	}
2177d96b3424SFilipe Manana 
2178bb803951SChris Mason again:
2179d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
21801fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2181be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2182be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2183be6821f8SFilipe Manana 		goto done;
2184be6821f8SFilipe Manana 	}
2185925baeddSChris Mason 
2186eb60ceacSChris Mason 	while (b) {
2187f624d976SQu Wenruo 		int dec = 0;
2188f624d976SQu Wenruo 
21895f39d397SChris Mason 		level = btrfs_header_level(b);
219065b51a00SChris Mason 
219102217ed2SChris Mason 		if (cow) {
21929ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
21939ea2c7c9SNikolay Borisov 
2194c8c42864SChris Mason 			/*
2195c8c42864SChris Mason 			 * if we don't really need to cow this block
2196c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2197c8c42864SChris Mason 			 * so we test it here
2198c8c42864SChris Mason 			 */
21995963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
220065b51a00SChris Mason 				goto cow_done;
22015d4f98a2SYan Zheng 
2202bd681513SChris Mason 			/*
2203bd681513SChris Mason 			 * must have write locks on this node and the
2204bd681513SChris Mason 			 * parent
2205bd681513SChris Mason 			 */
22065124e00eSJosef Bacik 			if (level > write_lock_level ||
22075124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
22085124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
22095124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2210bd681513SChris Mason 				write_lock_level = level + 1;
2211bd681513SChris Mason 				btrfs_release_path(p);
2212bd681513SChris Mason 				goto again;
2213bd681513SChris Mason 			}
2214bd681513SChris Mason 
22159ea2c7c9SNikolay Borisov 			if (last_level)
22169ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
22179631e4ccSJosef Bacik 						      &b,
22189631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
22199ea2c7c9SNikolay Borisov 			else
222033c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2221e20d96d6SChris Mason 						      p->nodes[level + 1],
22229631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
22239631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
222433c66f43SYan Zheng 			if (err) {
222533c66f43SYan Zheng 				ret = err;
222665b51a00SChris Mason 				goto done;
222754aa1f4dSChris Mason 			}
222802217ed2SChris Mason 		}
222965b51a00SChris Mason cow_done:
2230eb60ceacSChris Mason 		p->nodes[level] = b;
2231b4ce94deSChris Mason 
2232b4ce94deSChris Mason 		/*
2233b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2234b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2235b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2236b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2237b4ce94deSChris Mason 		 *
2238eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2239eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2240eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2241eb653de1SFilipe David Borba Manana 		 * we're operating on.
2242b4ce94deSChris Mason 		 */
2243eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2244eb653de1SFilipe David Borba Manana 			int u = level + 1;
2245eb653de1SFilipe David Borba Manana 
2246eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2247eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2248eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2249eb653de1SFilipe David Borba Manana 			}
2250eb653de1SFilipe David Borba Manana 		}
2251b4ce94deSChris Mason 
2252e2e58d0fSFilipe Manana 		if (level == 0) {
2253109324cfSFilipe Manana 			if (ins_len > 0)
2254e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
2255bd681513SChris Mason 
2256109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2257459931ecSChris Mason 			if (!p->search_for_split)
2258f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
22594b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
226065b51a00SChris Mason 			goto done;
226165b51a00SChris Mason 		}
2262e2e58d0fSFilipe Manana 
2263e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2264e2e58d0fSFilipe Manana 		if (ret < 0)
2265e2e58d0fSFilipe Manana 			goto done;
2266e2e58d0fSFilipe Manana 		prev_cmp = ret;
2267e2e58d0fSFilipe Manana 
2268f624d976SQu Wenruo 		if (ret && slot > 0) {
2269f624d976SQu Wenruo 			dec = 1;
2270f624d976SQu Wenruo 			slot--;
2271f624d976SQu Wenruo 		}
2272f624d976SQu Wenruo 		p->slots[level] = slot;
2273f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2274f624d976SQu Wenruo 					     &write_lock_level);
2275f624d976SQu Wenruo 		if (err == -EAGAIN)
2276f624d976SQu Wenruo 			goto again;
2277f624d976SQu Wenruo 		if (err) {
2278f624d976SQu Wenruo 			ret = err;
2279f624d976SQu Wenruo 			goto done;
2280f624d976SQu Wenruo 		}
2281f624d976SQu Wenruo 		b = p->nodes[level];
2282f624d976SQu Wenruo 		slot = p->slots[level];
2283f624d976SQu Wenruo 
2284f624d976SQu Wenruo 		/*
2285f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2286f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2287f624d976SQu Wenruo 		 * the parent
2288f624d976SQu Wenruo 		 */
2289f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2290f624d976SQu Wenruo 			write_lock_level = level + 1;
2291f624d976SQu Wenruo 			btrfs_release_path(p);
2292f624d976SQu Wenruo 			goto again;
2293f624d976SQu Wenruo 		}
2294f624d976SQu Wenruo 
2295f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2296f624d976SQu Wenruo 			  &write_lock_level);
2297f624d976SQu Wenruo 
2298f624d976SQu Wenruo 		if (level == lowest_level) {
2299f624d976SQu Wenruo 			if (dec)
2300f624d976SQu Wenruo 				p->slots[level]++;
2301f624d976SQu Wenruo 			goto done;
2302f624d976SQu Wenruo 		}
2303f624d976SQu Wenruo 
2304f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2305f624d976SQu Wenruo 		if (err == -EAGAIN)
2306f624d976SQu Wenruo 			goto again;
2307f624d976SQu Wenruo 		if (err) {
2308f624d976SQu Wenruo 			ret = err;
2309f624d976SQu Wenruo 			goto done;
2310f624d976SQu Wenruo 		}
2311f624d976SQu Wenruo 
2312f624d976SQu Wenruo 		if (!p->skip_locking) {
2313f624d976SQu Wenruo 			level = btrfs_header_level(b);
2314b40130b2SJosef Bacik 
2315b40130b2SJosef Bacik 			btrfs_maybe_reset_lockdep_class(root, b);
2316b40130b2SJosef Bacik 
2317f624d976SQu Wenruo 			if (level <= write_lock_level) {
2318f624d976SQu Wenruo 				btrfs_tree_lock(b);
2319f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2320f624d976SQu Wenruo 			} else {
2321857bc13fSJosef Bacik 				if (p->nowait) {
2322857bc13fSJosef Bacik 					if (!btrfs_try_tree_read_lock(b)) {
2323857bc13fSJosef Bacik 						free_extent_buffer(b);
2324857bc13fSJosef Bacik 						ret = -EAGAIN;
2325857bc13fSJosef Bacik 						goto done;
2326857bc13fSJosef Bacik 					}
2327857bc13fSJosef Bacik 				} else {
2328fe596ca3SJosef Bacik 					btrfs_tree_read_lock(b);
2329857bc13fSJosef Bacik 				}
2330f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2331f624d976SQu Wenruo 			}
2332f624d976SQu Wenruo 			p->nodes[level] = b;
2333f624d976SQu Wenruo 		}
233465b51a00SChris Mason 	}
233565b51a00SChris Mason 	ret = 1;
233665b51a00SChris Mason done:
23375f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2338b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2339d96b3424SFilipe Manana 
2340d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2341d96b3424SFilipe Manana 		int ret2;
2342d96b3424SFilipe Manana 
2343d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2344d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2345d96b3424SFilipe Manana 		if (ret2)
2346d96b3424SFilipe Manana 			ret = ret2;
2347d96b3424SFilipe Manana 	}
2348d96b3424SFilipe Manana 
2349be0e5c09SChris Mason 	return ret;
2350be0e5c09SChris Mason }
2351f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2352be0e5c09SChris Mason 
235374123bd7SChris Mason /*
23545d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
23555d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
23565d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
23575d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
23585d9e75c4SJan Schmidt  *
23595d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
23605d9e75c4SJan Schmidt  *
23615d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
23625d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
23635d9e75c4SJan Schmidt  */
2364310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
23655d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
23665d9e75c4SJan Schmidt {
23670b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
23685d9e75c4SJan Schmidt 	struct extent_buffer *b;
23695d9e75c4SJan Schmidt 	int slot;
23705d9e75c4SJan Schmidt 	int ret;
23715d9e75c4SJan Schmidt 	int err;
23725d9e75c4SJan Schmidt 	int level;
23735d9e75c4SJan Schmidt 	int lowest_unlock = 1;
23745d9e75c4SJan Schmidt 	u8 lowest_level = 0;
23755d9e75c4SJan Schmidt 
23765d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
23775d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
2378c922b016SStefan Roesch 	ASSERT(!p->nowait);
23795d9e75c4SJan Schmidt 
23805d9e75c4SJan Schmidt 	if (p->search_commit_root) {
23815d9e75c4SJan Schmidt 		BUG_ON(time_seq);
23825d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
23835d9e75c4SJan Schmidt 	}
23845d9e75c4SJan Schmidt 
23855d9e75c4SJan Schmidt again:
2386f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2387315bed43SNikolay Borisov 	if (!b) {
2388315bed43SNikolay Borisov 		ret = -EIO;
2389315bed43SNikolay Borisov 		goto done;
2390315bed43SNikolay Borisov 	}
23915d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
23925d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
23935d9e75c4SJan Schmidt 
23945d9e75c4SJan Schmidt 	while (b) {
2395abe9339dSQu Wenruo 		int dec = 0;
2396abe9339dSQu Wenruo 
23975d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
23985d9e75c4SJan Schmidt 		p->nodes[level] = b;
23995d9e75c4SJan Schmidt 
24005d9e75c4SJan Schmidt 		/*
24015d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
24025d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
24035d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
24045d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
24055d9e75c4SJan Schmidt 		 */
24065d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
24075d9e75c4SJan Schmidt 
2408fdf8d595SAnand Jain 		ret = btrfs_bin_search(b, 0, key, &slot);
2409cbca7d59SFilipe Manana 		if (ret < 0)
2410cbca7d59SFilipe Manana 			goto done;
24115d9e75c4SJan Schmidt 
2412abe9339dSQu Wenruo 		if (level == 0) {
2413abe9339dSQu Wenruo 			p->slots[level] = slot;
2414abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2415abe9339dSQu Wenruo 			goto done;
2416abe9339dSQu Wenruo 		}
2417abe9339dSQu Wenruo 
24185d9e75c4SJan Schmidt 		if (ret && slot > 0) {
24195d9e75c4SJan Schmidt 			dec = 1;
2420abe9339dSQu Wenruo 			slot--;
24215d9e75c4SJan Schmidt 		}
24225d9e75c4SJan Schmidt 		p->slots[level] = slot;
24235d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
24245d9e75c4SJan Schmidt 
24255d9e75c4SJan Schmidt 		if (level == lowest_level) {
24265d9e75c4SJan Schmidt 			if (dec)
24275d9e75c4SJan Schmidt 				p->slots[level]++;
24285d9e75c4SJan Schmidt 			goto done;
24295d9e75c4SJan Schmidt 		}
24305d9e75c4SJan Schmidt 
2431abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
24325d9e75c4SJan Schmidt 		if (err == -EAGAIN)
24335d9e75c4SJan Schmidt 			goto again;
24345d9e75c4SJan Schmidt 		if (err) {
24355d9e75c4SJan Schmidt 			ret = err;
24365d9e75c4SJan Schmidt 			goto done;
24375d9e75c4SJan Schmidt 		}
24385d9e75c4SJan Schmidt 
24395d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
24405d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2441f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2442db7f3436SJosef Bacik 		if (!b) {
2443db7f3436SJosef Bacik 			ret = -ENOMEM;
2444db7f3436SJosef Bacik 			goto done;
2445db7f3436SJosef Bacik 		}
24465d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
24475d9e75c4SJan Schmidt 		p->nodes[level] = b;
24485d9e75c4SJan Schmidt 	}
24495d9e75c4SJan Schmidt 	ret = 1;
24505d9e75c4SJan Schmidt done:
24515d9e75c4SJan Schmidt 	if (ret < 0)
24525d9e75c4SJan Schmidt 		btrfs_release_path(p);
24535d9e75c4SJan Schmidt 
24545d9e75c4SJan Schmidt 	return ret;
24555d9e75c4SJan Schmidt }
24565d9e75c4SJan Schmidt 
24575d9e75c4SJan Schmidt /*
2458f469c8bdSFilipe Manana  * Search the tree again to find a leaf with smaller keys.
2459f469c8bdSFilipe Manana  * Returns 0 if it found something.
2460f469c8bdSFilipe Manana  * Returns 1 if there are no smaller keys.
2461f469c8bdSFilipe Manana  * Returns < 0 on error.
2462f469c8bdSFilipe Manana  *
2463f469c8bdSFilipe Manana  * This may release the path, and so you may lose any locks held at the
2464f469c8bdSFilipe Manana  * time you call it.
2465f469c8bdSFilipe Manana  */
2466f469c8bdSFilipe Manana static int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
2467f469c8bdSFilipe Manana {
2468f469c8bdSFilipe Manana 	struct btrfs_key key;
2469f469c8bdSFilipe Manana 	struct btrfs_key orig_key;
2470f469c8bdSFilipe Manana 	struct btrfs_disk_key found_key;
2471f469c8bdSFilipe Manana 	int ret;
2472f469c8bdSFilipe Manana 
2473f469c8bdSFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
2474f469c8bdSFilipe Manana 	orig_key = key;
2475f469c8bdSFilipe Manana 
2476f469c8bdSFilipe Manana 	if (key.offset > 0) {
2477f469c8bdSFilipe Manana 		key.offset--;
2478f469c8bdSFilipe Manana 	} else if (key.type > 0) {
2479f469c8bdSFilipe Manana 		key.type--;
2480f469c8bdSFilipe Manana 		key.offset = (u64)-1;
2481f469c8bdSFilipe Manana 	} else if (key.objectid > 0) {
2482f469c8bdSFilipe Manana 		key.objectid--;
2483f469c8bdSFilipe Manana 		key.type = (u8)-1;
2484f469c8bdSFilipe Manana 		key.offset = (u64)-1;
2485f469c8bdSFilipe Manana 	} else {
2486f469c8bdSFilipe Manana 		return 1;
2487f469c8bdSFilipe Manana 	}
2488f469c8bdSFilipe Manana 
2489f469c8bdSFilipe Manana 	btrfs_release_path(path);
2490f469c8bdSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2491f469c8bdSFilipe Manana 	if (ret <= 0)
2492f469c8bdSFilipe Manana 		return ret;
2493f469c8bdSFilipe Manana 
2494f469c8bdSFilipe Manana 	/*
2495f469c8bdSFilipe Manana 	 * Previous key not found. Even if we were at slot 0 of the leaf we had
2496f469c8bdSFilipe Manana 	 * before releasing the path and calling btrfs_search_slot(), we now may
2497f469c8bdSFilipe Manana 	 * be in a slot pointing to the same original key - this can happen if
2498f469c8bdSFilipe Manana 	 * after we released the path, one of more items were moved from a
2499f469c8bdSFilipe Manana 	 * sibling leaf into the front of the leaf we had due to an insertion
2500f469c8bdSFilipe Manana 	 * (see push_leaf_right()).
2501f469c8bdSFilipe Manana 	 * If we hit this case and our slot is > 0 and just decrement the slot
2502f469c8bdSFilipe Manana 	 * so that the caller does not process the same key again, which may or
2503f469c8bdSFilipe Manana 	 * may not break the caller, depending on its logic.
2504f469c8bdSFilipe Manana 	 */
2505f469c8bdSFilipe Manana 	if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
2506f469c8bdSFilipe Manana 		btrfs_item_key(path->nodes[0], &found_key, path->slots[0]);
2507f469c8bdSFilipe Manana 		ret = comp_keys(&found_key, &orig_key);
2508f469c8bdSFilipe Manana 		if (ret == 0) {
2509f469c8bdSFilipe Manana 			if (path->slots[0] > 0) {
2510f469c8bdSFilipe Manana 				path->slots[0]--;
2511f469c8bdSFilipe Manana 				return 0;
2512f469c8bdSFilipe Manana 			}
2513f469c8bdSFilipe Manana 			/*
2514f469c8bdSFilipe Manana 			 * At slot 0, same key as before, it means orig_key is
2515f469c8bdSFilipe Manana 			 * the lowest, leftmost, key in the tree. We're done.
2516f469c8bdSFilipe Manana 			 */
2517f469c8bdSFilipe Manana 			return 1;
2518f469c8bdSFilipe Manana 		}
2519f469c8bdSFilipe Manana 	}
2520f469c8bdSFilipe Manana 
2521f469c8bdSFilipe Manana 	btrfs_item_key(path->nodes[0], &found_key, 0);
2522f469c8bdSFilipe Manana 	ret = comp_keys(&found_key, &key);
2523f469c8bdSFilipe Manana 	/*
2524f469c8bdSFilipe Manana 	 * We might have had an item with the previous key in the tree right
2525f469c8bdSFilipe Manana 	 * before we released our path. And after we released our path, that
2526f469c8bdSFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
2527f469c8bdSFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
2528f469c8bdSFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
2529f469c8bdSFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
2530f469c8bdSFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
2531f469c8bdSFilipe Manana 	 * the previous key we computed above.
2532f469c8bdSFilipe Manana 	 */
2533f469c8bdSFilipe Manana 	if (ret <= 0)
2534f469c8bdSFilipe Manana 		return 0;
2535f469c8bdSFilipe Manana 	return 1;
2536f469c8bdSFilipe Manana }
2537f469c8bdSFilipe Manana 
2538f469c8bdSFilipe Manana /*
25392f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
25402f38b3e1SArne Jansen  * instead the next or previous item should be returned.
25412f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
25422f38b3e1SArne Jansen  * otherwise.
25432f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
25442f38b3e1SArne Jansen  * return the next lower instead.
25452f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
25462f38b3e1SArne Jansen  * return the next higher instead.
25472f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
25482f38b3e1SArne Jansen  * < 0 on error
25492f38b3e1SArne Jansen  */
25502f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2551310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2552310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2553310712b2SOmar Sandoval 			       int return_any)
25542f38b3e1SArne Jansen {
25552f38b3e1SArne Jansen 	int ret;
25562f38b3e1SArne Jansen 	struct extent_buffer *leaf;
25572f38b3e1SArne Jansen 
25582f38b3e1SArne Jansen again:
25592f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
25602f38b3e1SArne Jansen 	if (ret <= 0)
25612f38b3e1SArne Jansen 		return ret;
25622f38b3e1SArne Jansen 	/*
25632f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
25642f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
25652f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
25662f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
25672f38b3e1SArne Jansen 	 * item.
25682f38b3e1SArne Jansen 	 */
25692f38b3e1SArne Jansen 	leaf = p->nodes[0];
25702f38b3e1SArne Jansen 
25712f38b3e1SArne Jansen 	if (find_higher) {
25722f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
25732f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
25742f38b3e1SArne Jansen 			if (ret <= 0)
25752f38b3e1SArne Jansen 				return ret;
25762f38b3e1SArne Jansen 			if (!return_any)
25772f38b3e1SArne Jansen 				return 1;
25782f38b3e1SArne Jansen 			/*
25792f38b3e1SArne Jansen 			 * no higher item found, return the next
25802f38b3e1SArne Jansen 			 * lower instead
25812f38b3e1SArne Jansen 			 */
25822f38b3e1SArne Jansen 			return_any = 0;
25832f38b3e1SArne Jansen 			find_higher = 0;
25842f38b3e1SArne Jansen 			btrfs_release_path(p);
25852f38b3e1SArne Jansen 			goto again;
25862f38b3e1SArne Jansen 		}
25872f38b3e1SArne Jansen 	} else {
25882f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
25892f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2590e6793769SArne Jansen 			if (ret < 0)
25912f38b3e1SArne Jansen 				return ret;
2592e6793769SArne Jansen 			if (!ret) {
259323c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
259423c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
259523c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2596e6793769SArne Jansen 				return 0;
2597e6793769SArne Jansen 			}
25982f38b3e1SArne Jansen 			if (!return_any)
25992f38b3e1SArne Jansen 				return 1;
26002f38b3e1SArne Jansen 			/*
26012f38b3e1SArne Jansen 			 * no lower item found, return the next
26022f38b3e1SArne Jansen 			 * higher instead
26032f38b3e1SArne Jansen 			 */
26042f38b3e1SArne Jansen 			return_any = 0;
26052f38b3e1SArne Jansen 			find_higher = 1;
26062f38b3e1SArne Jansen 			btrfs_release_path(p);
26072f38b3e1SArne Jansen 			goto again;
2608e6793769SArne Jansen 		} else {
26092f38b3e1SArne Jansen 			--p->slots[0];
26102f38b3e1SArne Jansen 		}
26112f38b3e1SArne Jansen 	}
26122f38b3e1SArne Jansen 	return 0;
26132f38b3e1SArne Jansen }
26142f38b3e1SArne Jansen 
26152f38b3e1SArne Jansen /*
26160ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
26170ff40a91SMarcos Paulo de Souza  * was not found.
26180ff40a91SMarcos Paulo de Souza  *
26190ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
26200ff40a91SMarcos Paulo de Souza  */
26210ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
26220ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
26230ff40a91SMarcos Paulo de Souza {
26240ff40a91SMarcos Paulo de Souza 	int ret;
26250ff40a91SMarcos Paulo de Souza 
26260ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
26270ff40a91SMarcos Paulo de Souza 	if (ret > 0)
26280ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
26290ff40a91SMarcos Paulo de Souza 
26300ff40a91SMarcos Paulo de Souza 	if (ret == 0)
26310ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
26320ff40a91SMarcos Paulo de Souza 
26330ff40a91SMarcos Paulo de Souza 	return ret;
26340ff40a91SMarcos Paulo de Souza }
26350ff40a91SMarcos Paulo de Souza 
263643dd529aSDavid Sterba /*
263762142be3SGabriel Niebler  * Search for a valid slot for the given path.
263862142be3SGabriel Niebler  *
263962142be3SGabriel Niebler  * @root:	The root node of the tree.
264062142be3SGabriel Niebler  * @key:	Will contain a valid item if found.
264162142be3SGabriel Niebler  * @path:	The starting point to validate the slot.
264262142be3SGabriel Niebler  *
264362142be3SGabriel Niebler  * Return: 0  if the item is valid
264462142be3SGabriel Niebler  *         1  if not found
264562142be3SGabriel Niebler  *         <0 if error.
264662142be3SGabriel Niebler  */
264762142be3SGabriel Niebler int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
264862142be3SGabriel Niebler 			      struct btrfs_path *path)
264962142be3SGabriel Niebler {
2650524f14bbSFilipe Manana 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
265162142be3SGabriel Niebler 		int ret;
265262142be3SGabriel Niebler 
265362142be3SGabriel Niebler 		ret = btrfs_next_leaf(root, path);
265462142be3SGabriel Niebler 		if (ret)
265562142be3SGabriel Niebler 			return ret;
265662142be3SGabriel Niebler 	}
2657524f14bbSFilipe Manana 
2658524f14bbSFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
265962142be3SGabriel Niebler 	return 0;
266062142be3SGabriel Niebler }
266162142be3SGabriel Niebler 
26620ff40a91SMarcos Paulo de Souza /*
266374123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
266474123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
266574123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
266674123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
266774123bd7SChris Mason  * higher levels
2668aa5d6bedSChris Mason  *
266974123bd7SChris Mason  */
2670b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
26715f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2672be0e5c09SChris Mason {
2673be0e5c09SChris Mason 	int i;
26745f39d397SChris Mason 	struct extent_buffer *t;
26750e82bcfeSDavid Sterba 	int ret;
26765f39d397SChris Mason 
2677234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2678be0e5c09SChris Mason 		int tslot = path->slots[i];
26790e82bcfeSDavid Sterba 
2680eb60ceacSChris Mason 		if (!path->nodes[i])
2681be0e5c09SChris Mason 			break;
26825f39d397SChris Mason 		t = path->nodes[i];
2683f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
268433cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
26850e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
26865f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2687d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2688be0e5c09SChris Mason 		if (tslot != 0)
2689be0e5c09SChris Mason 			break;
2690be0e5c09SChris Mason 	}
2691be0e5c09SChris Mason }
2692be0e5c09SChris Mason 
269374123bd7SChris Mason /*
269431840ae1SZheng Yan  * update item key.
269531840ae1SZheng Yan  *
269631840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
269731840ae1SZheng Yan  * that the new key won't break the order
269831840ae1SZheng Yan  */
2699b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2700b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2701310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
270231840ae1SZheng Yan {
270331840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
270431840ae1SZheng Yan 	struct extent_buffer *eb;
270531840ae1SZheng Yan 	int slot;
270631840ae1SZheng Yan 
270731840ae1SZheng Yan 	eb = path->nodes[0];
270831840ae1SZheng Yan 	slot = path->slots[0];
270931840ae1SZheng Yan 	if (slot > 0) {
271031840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
27117c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
2712eee3b811SQu Wenruo 			btrfs_print_leaf(eb);
27137c15d410SQu Wenruo 			btrfs_crit(fs_info,
27147c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
27157c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
27167c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
27177c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
27187c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
27197c15d410SQu Wenruo 				   new_key->offset);
27207c15d410SQu Wenruo 			BUG();
27217c15d410SQu Wenruo 		}
272231840ae1SZheng Yan 	}
272331840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
272431840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
27257c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
2726eee3b811SQu Wenruo 			btrfs_print_leaf(eb);
27277c15d410SQu Wenruo 			btrfs_crit(fs_info,
27287c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
27297c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
27307c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
27317c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
27327c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
27337c15d410SQu Wenruo 				   new_key->offset);
27347c15d410SQu Wenruo 			BUG();
27357c15d410SQu Wenruo 		}
273631840ae1SZheng Yan 	}
273731840ae1SZheng Yan 
273831840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
273931840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
274031840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
274131840ae1SZheng Yan 	if (slot == 0)
2742b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
274331840ae1SZheng Yan }
274431840ae1SZheng Yan 
274531840ae1SZheng Yan /*
2746d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2747d16c702fSQu Wenruo  *
2748d16c702fSQu Wenruo  * Return true if something is wrong.
2749d16c702fSQu Wenruo  * Return false if everything is fine.
2750d16c702fSQu Wenruo  *
2751d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2752d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2753d16c702fSQu Wenruo  *
2754d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2755d16c702fSQu Wenruo  * --------------------------------------------------------------
2756d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2757d16c702fSQu Wenruo  *
2758d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2759d16c702fSQu Wenruo  * key in leaf @right is 7.
2760d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2761d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2762d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2763d16c702fSQu Wenruo  * key of @right.
2764d16c702fSQu Wenruo  */
2765d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2766d16c702fSQu Wenruo 			       struct extent_buffer *right)
2767d16c702fSQu Wenruo {
2768d16c702fSQu Wenruo 	struct btrfs_key left_last;
2769d16c702fSQu Wenruo 	struct btrfs_key right_first;
2770d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2771d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2772d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2773d16c702fSQu Wenruo 
2774d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2775d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2776d16c702fSQu Wenruo 		return false;
2777d16c702fSQu Wenruo 
2778d16c702fSQu Wenruo 	if (level) {
2779d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2780d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2781d16c702fSQu Wenruo 	} else {
2782d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2783d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2784d16c702fSQu Wenruo 	}
2785d16c702fSQu Wenruo 
278688ad95b0SFilipe Manana 	if (unlikely(btrfs_comp_cpu_keys(&left_last, &right_first) >= 0)) {
2787a2cea677SFilipe Manana 		btrfs_crit(left->fs_info, "left extent buffer:");
2788a2cea677SFilipe Manana 		btrfs_print_tree(left, false);
2789a2cea677SFilipe Manana 		btrfs_crit(left->fs_info, "right extent buffer:");
2790a2cea677SFilipe Manana 		btrfs_print_tree(right, false);
2791d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2792d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2793d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2794d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2795d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2796d16c702fSQu Wenruo 		return true;
2797d16c702fSQu Wenruo 	}
2798d16c702fSQu Wenruo 	return false;
2799d16c702fSQu Wenruo }
2800d16c702fSQu Wenruo 
2801d16c702fSQu Wenruo /*
280274123bd7SChris Mason  * try to push data from one node into the next node left in the
280379f95c82SChris Mason  * tree.
2804aa5d6bedSChris Mason  *
2805aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2806aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
280774123bd7SChris Mason  */
280898ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
28092ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2810971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2811be0e5c09SChris Mason {
2812d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2813be0e5c09SChris Mason 	int push_items = 0;
2814bb803951SChris Mason 	int src_nritems;
2815bb803951SChris Mason 	int dst_nritems;
2816aa5d6bedSChris Mason 	int ret = 0;
2817be0e5c09SChris Mason 
28185f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28195f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
28200b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
28217bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28227bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
282354aa1f4dSChris Mason 
2824bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2825971a1f66SChris Mason 		return 1;
2826971a1f66SChris Mason 
2827d397712bSChris Mason 	if (push_items <= 0)
2828be0e5c09SChris Mason 		return 1;
2829be0e5c09SChris Mason 
2830bce4eae9SChris Mason 	if (empty) {
2831971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2832bce4eae9SChris Mason 		if (push_items < src_nritems) {
2833bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2834bce4eae9SChris Mason 			 * we aren't going to empty it
2835bce4eae9SChris Mason 			 */
2836bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2837bce4eae9SChris Mason 				if (push_items <= 8)
2838bce4eae9SChris Mason 					return 1;
2839bce4eae9SChris Mason 				push_items -= 8;
2840bce4eae9SChris Mason 			}
2841bce4eae9SChris Mason 		}
2842bce4eae9SChris Mason 	} else
2843bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
284479f95c82SChris Mason 
2845d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2846d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2847d16c702fSQu Wenruo 		ret = -EUCLEAN;
2848d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2849d16c702fSQu Wenruo 		return ret;
2850d16c702fSQu Wenruo 	}
2851f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
28525de865eeSFilipe David Borba Manana 	if (ret) {
285366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
28545de865eeSFilipe David Borba Manana 		return ret;
28555de865eeSFilipe David Borba Manana 	}
28565f39d397SChris Mason 	copy_extent_buffer(dst, src,
2857e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, dst_nritems),
2858e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, 0),
2859123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
28605f39d397SChris Mason 
2861bb803951SChris Mason 	if (push_items < src_nritems) {
286257911b8bSJan Schmidt 		/*
28635cead542SBoris Burkov 		 * btrfs_tree_mod_log_eb_copy handles logging the move, so we
28645cead542SBoris Burkov 		 * don't need to do an explicit tree mod log operation for it.
286557911b8bSJan Schmidt 		 */
2866e23efd8eSJosef Bacik 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(src, 0),
2867e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(src, push_items),
2868e2fa7227SChris Mason 				      (src_nritems - push_items) *
2869123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2870bb803951SChris Mason 	}
28715f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
28725f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
28735f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
28745f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
287531840ae1SZheng Yan 
2876bb803951SChris Mason 	return ret;
2877be0e5c09SChris Mason }
2878be0e5c09SChris Mason 
287997571fd0SChris Mason /*
288079f95c82SChris Mason  * try to push data from one node into the next node right in the
288179f95c82SChris Mason  * tree.
288279f95c82SChris Mason  *
288379f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
288479f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
288579f95c82SChris Mason  *
288679f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
288779f95c82SChris Mason  */
28885f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
28895f39d397SChris Mason 			      struct extent_buffer *dst,
28905f39d397SChris Mason 			      struct extent_buffer *src)
289179f95c82SChris Mason {
289255d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
289379f95c82SChris Mason 	int push_items = 0;
289479f95c82SChris Mason 	int max_push;
289579f95c82SChris Mason 	int src_nritems;
289679f95c82SChris Mason 	int dst_nritems;
289779f95c82SChris Mason 	int ret = 0;
289879f95c82SChris Mason 
28997bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
29007bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
29017bb86316SChris Mason 
29025f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
29035f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
29040b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2905d397712bSChris Mason 	if (push_items <= 0)
290679f95c82SChris Mason 		return 1;
2907bce4eae9SChris Mason 
2908d397712bSChris Mason 	if (src_nritems < 4)
2909bce4eae9SChris Mason 		return 1;
291079f95c82SChris Mason 
291179f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
291279f95c82SChris Mason 	/* don't try to empty the node */
2913d397712bSChris Mason 	if (max_push >= src_nritems)
291479f95c82SChris Mason 		return 1;
2915252c38f0SYan 
291679f95c82SChris Mason 	if (max_push < push_items)
291779f95c82SChris Mason 		push_items = max_push;
291879f95c82SChris Mason 
2919d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2920d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2921d16c702fSQu Wenruo 		ret = -EUCLEAN;
2922d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2923d16c702fSQu Wenruo 		return ret;
2924d16c702fSQu Wenruo 	}
29255cead542SBoris Burkov 
29265cead542SBoris Burkov 	/*
29275cead542SBoris Burkov 	 * btrfs_tree_mod_log_eb_copy handles logging the move, so we don't
29285cead542SBoris Burkov 	 * need to do an explicit tree mod log operation for it.
29295cead542SBoris Burkov 	 */
2930e23efd8eSJosef Bacik 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(dst, push_items),
2931e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(dst, 0),
29325f39d397SChris Mason 				      (dst_nritems) *
29335f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2934d6025579SChris Mason 
2935f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2936ed874f0dSDavid Sterba 					 push_items);
29375de865eeSFilipe David Borba Manana 	if (ret) {
293866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
29395de865eeSFilipe David Borba Manana 		return ret;
29405de865eeSFilipe David Borba Manana 	}
29415f39d397SChris Mason 	copy_extent_buffer(dst, src,
2942e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, 0),
2943e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, src_nritems - push_items),
2944123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
294579f95c82SChris Mason 
29465f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
29475f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
294879f95c82SChris Mason 
29495f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
29505f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
295131840ae1SZheng Yan 
295279f95c82SChris Mason 	return ret;
295379f95c82SChris Mason }
295479f95c82SChris Mason 
295579f95c82SChris Mason /*
295697571fd0SChris Mason  * helper function to insert a new root level in the tree.
295797571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
295897571fd0SChris Mason  * point to the existing root
2959aa5d6bedSChris Mason  *
2960aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
296197571fd0SChris Mason  */
2962d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
29635f39d397SChris Mason 			   struct btrfs_root *root,
2964fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
296574123bd7SChris Mason {
29660b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29677bb86316SChris Mason 	u64 lower_gen;
29685f39d397SChris Mason 	struct extent_buffer *lower;
29695f39d397SChris Mason 	struct extent_buffer *c;
2970925baeddSChris Mason 	struct extent_buffer *old;
29715f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2972d9d19a01SDavid Sterba 	int ret;
29735c680ed6SChris Mason 
29745c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
29755c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
29765c680ed6SChris Mason 
29777bb86316SChris Mason 	lower = path->nodes[level-1];
29787bb86316SChris Mason 	if (level == 1)
29797bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
29807bb86316SChris Mason 	else
29817bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
29827bb86316SChris Mason 
298379bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
298479bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2985cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
29865f39d397SChris Mason 	if (IS_ERR(c))
29875f39d397SChris Mason 		return PTR_ERR(c);
2988925baeddSChris Mason 
29890b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2990f0486c68SYan, Zheng 
29915f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
29925f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2993db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
29947bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
299531840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
29967bb86316SChris Mason 
29977bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
29985f39d397SChris Mason 
29995f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
3000d5719762SChris Mason 
3001925baeddSChris Mason 	old = root->node;
3002406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
3003f61aa7baSFilipe Manana 	if (ret < 0) {
3004f61aa7baSFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), c, 0, 1);
3005f61aa7baSFilipe Manana 		btrfs_tree_unlock(c);
3006f61aa7baSFilipe Manana 		free_extent_buffer(c);
3007f61aa7baSFilipe Manana 		return ret;
3008f61aa7baSFilipe Manana 	}
3009240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3010925baeddSChris Mason 
3011925baeddSChris Mason 	/* the super has an extra ref to root->node */
3012925baeddSChris Mason 	free_extent_buffer(old);
3013925baeddSChris Mason 
30140b86a832SChris Mason 	add_root_to_dirty_list(root);
301567439dadSDavid Sterba 	atomic_inc(&c->refs);
30165f39d397SChris Mason 	path->nodes[level] = c;
3017ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
301874123bd7SChris Mason 	path->slots[level] = 0;
301974123bd7SChris Mason 	return 0;
302074123bd7SChris Mason }
30215c680ed6SChris Mason 
30225c680ed6SChris Mason /*
30235c680ed6SChris Mason  * worker function to insert a single pointer in a node.
30245c680ed6SChris Mason  * the node should have enough room for the pointer already
302597571fd0SChris Mason  *
30265c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
30275c680ed6SChris Mason  * blocknr is the block the key points to.
30285c680ed6SChris Mason  */
302950b5d1fcSFilipe Manana static int insert_ptr(struct btrfs_trans_handle *trans,
30306ad3cf6dSDavid Sterba 		      struct btrfs_path *path,
3031143bede5SJeff Mahoney 		      struct btrfs_disk_key *key, u64 bytenr,
3032c3e06965SJan Schmidt 		      int slot, int level)
30335c680ed6SChris Mason {
30345f39d397SChris Mason 	struct extent_buffer *lower;
30355c680ed6SChris Mason 	int nritems;
3036f3ea38daSJan Schmidt 	int ret;
30375c680ed6SChris Mason 
30385c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
303949d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
30405f39d397SChris Mason 	lower = path->nodes[level];
30415f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3042c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
30436ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
304474123bd7SChris Mason 	if (slot != nritems) {
3045bf1d3425SDavid Sterba 		if (level) {
3046f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
3047f3a84ccdSFilipe Manana 					slot, nritems - slot);
304850b5d1fcSFilipe Manana 			if (ret < 0) {
304950b5d1fcSFilipe Manana 				btrfs_abort_transaction(trans, ret);
305050b5d1fcSFilipe Manana 				return ret;
305150b5d1fcSFilipe Manana 			}
3052bf1d3425SDavid Sterba 		}
30535f39d397SChris Mason 		memmove_extent_buffer(lower,
3054e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot + 1),
3055e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot),
3056123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
305774123bd7SChris Mason 	}
3058c3e06965SJan Schmidt 	if (level) {
3059f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
306033cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_ADD);
306150b5d1fcSFilipe Manana 		if (ret < 0) {
306250b5d1fcSFilipe Manana 			btrfs_abort_transaction(trans, ret);
306350b5d1fcSFilipe Manana 			return ret;
306450b5d1fcSFilipe Manana 		}
3065f3ea38daSJan Schmidt 	}
30665f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3067db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
306874493f7aSChris Mason 	WARN_ON(trans->transid == 0);
306974493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
30705f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
30715f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
307250b5d1fcSFilipe Manana 
307350b5d1fcSFilipe Manana 	return 0;
307474123bd7SChris Mason }
307574123bd7SChris Mason 
307697571fd0SChris Mason /*
307797571fd0SChris Mason  * split the node at the specified level in path in two.
307897571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
307997571fd0SChris Mason  *
308097571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
308197571fd0SChris Mason  * left and right, if either one works, it returns right away.
3082aa5d6bedSChris Mason  *
3083aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
308497571fd0SChris Mason  */
3085e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3086e02119d5SChris Mason 			       struct btrfs_root *root,
3087e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3088be0e5c09SChris Mason {
30890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
30905f39d397SChris Mason 	struct extent_buffer *c;
30915f39d397SChris Mason 	struct extent_buffer *split;
30925f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3093be0e5c09SChris Mason 	int mid;
30945c680ed6SChris Mason 	int ret;
30957518a238SChris Mason 	u32 c_nritems;
3096be0e5c09SChris Mason 
30975f39d397SChris Mason 	c = path->nodes[level];
30987bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
30995f39d397SChris Mason 	if (c == root->node) {
3100d9abbf1cSJan Schmidt 		/*
310190f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
310290f8d62eSJan Schmidt 		 *
3103fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
310490f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
310590f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
3106f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
3107f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
3108f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
3109d9abbf1cSJan Schmidt 		 */
3110fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
31115c680ed6SChris Mason 		if (ret)
31125c680ed6SChris Mason 			return ret;
3113b3612421SChris Mason 	} else {
3114e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
31155f39d397SChris Mason 		c = path->nodes[level];
31165f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
31170b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3118e66f709bSChris Mason 			return 0;
311954aa1f4dSChris Mason 		if (ret < 0)
312054aa1f4dSChris Mason 			return ret;
31215c680ed6SChris Mason 	}
3122e66f709bSChris Mason 
31235f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
31245d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
31255d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
31267bb86316SChris Mason 
312779bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
312879bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
312979bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
31305f39d397SChris Mason 	if (IS_ERR(split))
31315f39d397SChris Mason 		return PTR_ERR(split);
313254aa1f4dSChris Mason 
31330b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3134bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
31355f39d397SChris Mason 
3136f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
31375de865eeSFilipe David Borba Manana 	if (ret) {
3138ede600e4SFilipe Manana 		btrfs_tree_unlock(split);
3139ede600e4SFilipe Manana 		free_extent_buffer(split);
314066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
31415de865eeSFilipe David Borba Manana 		return ret;
31425de865eeSFilipe David Borba Manana 	}
31435f39d397SChris Mason 	copy_extent_buffer(split, c,
3144e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(split, 0),
3145e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(c, mid),
3146123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
31475f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
31485f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3149aa5d6bedSChris Mason 
31505f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
31515f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
31525f39d397SChris Mason 
315350b5d1fcSFilipe Manana 	ret = insert_ptr(trans, path, &disk_key, split->start,
3154c3e06965SJan Schmidt 			 path->slots[level + 1] + 1, level + 1);
315550b5d1fcSFilipe Manana 	if (ret < 0) {
315650b5d1fcSFilipe Manana 		btrfs_tree_unlock(split);
315750b5d1fcSFilipe Manana 		free_extent_buffer(split);
315850b5d1fcSFilipe Manana 		return ret;
315950b5d1fcSFilipe Manana 	}
3160aa5d6bedSChris Mason 
31615de08d7dSChris Mason 	if (path->slots[level] >= mid) {
31625c680ed6SChris Mason 		path->slots[level] -= mid;
3163925baeddSChris Mason 		btrfs_tree_unlock(c);
31645f39d397SChris Mason 		free_extent_buffer(c);
31655f39d397SChris Mason 		path->nodes[level] = split;
31665c680ed6SChris Mason 		path->slots[level + 1] += 1;
3167eb60ceacSChris Mason 	} else {
3168925baeddSChris Mason 		btrfs_tree_unlock(split);
31695f39d397SChris Mason 		free_extent_buffer(split);
3170be0e5c09SChris Mason 	}
3171d5286a92SNikolay Borisov 	return 0;
3172be0e5c09SChris Mason }
3173be0e5c09SChris Mason 
317474123bd7SChris Mason /*
317574123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
317674123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
317774123bd7SChris Mason  * space used both by the item structs and the item data
317874123bd7SChris Mason  */
31796c75a589SQu Wenruo static int leaf_space_used(const struct extent_buffer *l, int start, int nr)
3180be0e5c09SChris Mason {
3181be0e5c09SChris Mason 	int data_len;
31825f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3183d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3184be0e5c09SChris Mason 
3185be0e5c09SChris Mason 	if (!nr)
3186be0e5c09SChris Mason 		return 0;
31873212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
31883212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
31890783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3190d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3191be0e5c09SChris Mason 	return data_len;
3192be0e5c09SChris Mason }
3193be0e5c09SChris Mason 
319474123bd7SChris Mason /*
3195d4dbff95SChris Mason  * The space between the end of the leaf items and
3196d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3197d4dbff95SChris Mason  * the leaf has left for both items and data
3198d4dbff95SChris Mason  */
31996c75a589SQu Wenruo int btrfs_leaf_free_space(const struct extent_buffer *leaf)
3200d4dbff95SChris Mason {
3201e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
32025f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
32035f39d397SChris Mason 	int ret;
32040b246afaSJeff Mahoney 
32050b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
32065f39d397SChris Mason 	if (ret < 0) {
32070b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3208efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3209da17066cSJeff Mahoney 			   ret,
32100b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
32115f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
32125f39d397SChris Mason 	}
32135f39d397SChris Mason 	return ret;
3214d4dbff95SChris Mason }
3215d4dbff95SChris Mason 
321699d8f83cSChris Mason /*
321799d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
321899d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
321999d8f83cSChris Mason  */
3220ed25dab3SJosef Bacik static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
3221ed25dab3SJosef Bacik 				      struct btrfs_path *path,
322244871b1bSChris Mason 				      int data_size, int empty,
322344871b1bSChris Mason 				      struct extent_buffer *right,
322499d8f83cSChris Mason 				      int free_space, u32 left_nritems,
322599d8f83cSChris Mason 				      u32 min_slot)
322600ec4c51SChris Mason {
3227f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
32285f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
322944871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3230cfed81a0SChris Mason 	struct btrfs_map_token token;
32315f39d397SChris Mason 	struct btrfs_disk_key disk_key;
323200ec4c51SChris Mason 	int slot;
323334a38218SChris Mason 	u32 i;
323400ec4c51SChris Mason 	int push_space = 0;
323500ec4c51SChris Mason 	int push_items = 0;
323634a38218SChris Mason 	u32 nr;
32377518a238SChris Mason 	u32 right_nritems;
32385f39d397SChris Mason 	u32 data_end;
3239db94535dSChris Mason 	u32 this_item_size;
324000ec4c51SChris Mason 
324134a38218SChris Mason 	if (empty)
324234a38218SChris Mason 		nr = 0;
324334a38218SChris Mason 	else
324499d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
324534a38218SChris Mason 
324631840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
324787b29b20SYan Zheng 		push_space += data_size;
324831840ae1SZheng Yan 
324944871b1bSChris Mason 	slot = path->slots[1];
325034a38218SChris Mason 	i = left_nritems - 1;
325134a38218SChris Mason 	while (i >= nr) {
325231840ae1SZheng Yan 		if (!empty && push_items > 0) {
325331840ae1SZheng Yan 			if (path->slots[0] > i)
325431840ae1SZheng Yan 				break;
325531840ae1SZheng Yan 			if (path->slots[0] == i) {
3256e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3257e902baacSDavid Sterba 
325831840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
325931840ae1SZheng Yan 					break;
326031840ae1SZheng Yan 			}
326131840ae1SZheng Yan 		}
326231840ae1SZheng Yan 
326300ec4c51SChris Mason 		if (path->slots[0] == i)
326487b29b20SYan Zheng 			push_space += data_size;
3265db94535dSChris Mason 
32663212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
326774794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
326874794207SJosef Bacik 		    push_space > free_space)
326900ec4c51SChris Mason 			break;
327031840ae1SZheng Yan 
327100ec4c51SChris Mason 		push_items++;
327274794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
327334a38218SChris Mason 		if (i == 0)
327434a38218SChris Mason 			break;
327534a38218SChris Mason 		i--;
3276db94535dSChris Mason 	}
32775f39d397SChris Mason 
3278925baeddSChris Mason 	if (push_items == 0)
3279925baeddSChris Mason 		goto out_unlock;
32805f39d397SChris Mason 
32816c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
32825f39d397SChris Mason 
328300ec4c51SChris Mason 	/* push left to right */
32845f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
328534a38218SChris Mason 
3286dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
32878f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
32885f39d397SChris Mason 
328900ec4c51SChris Mason 	/* make room in the right data area */
32908f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
3291637e3b48SJosef Bacik 	memmove_leaf_data(right, data_end - push_space, data_end,
32920b246afaSJeff Mahoney 			  BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
32935f39d397SChris Mason 
329400ec4c51SChris Mason 	/* copy from the left data area */
3295637e3b48SJosef Bacik 	copy_leaf_data(right, left, BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3296637e3b48SJosef Bacik 		       leaf_data_end(left), push_space);
32975f39d397SChris Mason 
3298637e3b48SJosef Bacik 	memmove_leaf_items(right, push_items, 0, right_nritems);
32995f39d397SChris Mason 
330000ec4c51SChris Mason 	/* copy the items from left to right */
3301637e3b48SJosef Bacik 	copy_leaf_items(right, left, 0, left_nritems - push_items, push_items);
330200ec4c51SChris Mason 
330300ec4c51SChris Mason 	/* update the item pointers */
3304c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
33057518a238SChris Mason 	right_nritems += push_items;
33065f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
33070b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
33087518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
33093212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
33103212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3311db94535dSChris Mason 	}
3312db94535dSChris Mason 
33137518a238SChris Mason 	left_nritems -= push_items;
33145f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
331500ec4c51SChris Mason 
331634a38218SChris Mason 	if (left_nritems)
33175f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3318f0486c68SYan, Zheng 	else
3319190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, left);
3320f0486c68SYan, Zheng 
33215f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3322a429e513SChris Mason 
33235f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
33245f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3325d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
332602217ed2SChris Mason 
332700ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
33287518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
33297518a238SChris Mason 		path->slots[0] -= left_nritems;
3330925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3331190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, path->nodes[0]);
3332925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
33335f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
33345f39d397SChris Mason 		path->nodes[0] = right;
333500ec4c51SChris Mason 		path->slots[1] += 1;
333600ec4c51SChris Mason 	} else {
3337925baeddSChris Mason 		btrfs_tree_unlock(right);
33385f39d397SChris Mason 		free_extent_buffer(right);
333900ec4c51SChris Mason 	}
334000ec4c51SChris Mason 	return 0;
3341925baeddSChris Mason 
3342925baeddSChris Mason out_unlock:
3343925baeddSChris Mason 	btrfs_tree_unlock(right);
3344925baeddSChris Mason 	free_extent_buffer(right);
3345925baeddSChris Mason 	return 1;
334600ec4c51SChris Mason }
3347925baeddSChris Mason 
334800ec4c51SChris Mason /*
334944871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
335074123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
335144871b1bSChris Mason  *
335244871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
335344871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
335499d8f83cSChris Mason  *
335599d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
335699d8f83cSChris Mason  * push any slot lower than min_slot
335774123bd7SChris Mason  */
335844871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
335999d8f83cSChris Mason 			   *root, struct btrfs_path *path,
336099d8f83cSChris Mason 			   int min_data_size, int data_size,
336199d8f83cSChris Mason 			   int empty, u32 min_slot)
3362be0e5c09SChris Mason {
336344871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
336444871b1bSChris Mason 	struct extent_buffer *right;
336544871b1bSChris Mason 	struct extent_buffer *upper;
336644871b1bSChris Mason 	int slot;
336744871b1bSChris Mason 	int free_space;
336844871b1bSChris Mason 	u32 left_nritems;
336944871b1bSChris Mason 	int ret;
337044871b1bSChris Mason 
337144871b1bSChris Mason 	if (!path->nodes[1])
337244871b1bSChris Mason 		return 1;
337344871b1bSChris Mason 
337444871b1bSChris Mason 	slot = path->slots[1];
337544871b1bSChris Mason 	upper = path->nodes[1];
337644871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
337744871b1bSChris Mason 		return 1;
337844871b1bSChris Mason 
337949d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
338044871b1bSChris Mason 
33814b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3382fb770ae4SLiu Bo 	if (IS_ERR(right))
33839cf14029SJosef Bacik 		return PTR_ERR(right);
338491ca338dSTsutomu Itoh 
3385bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
338644871b1bSChris Mason 
3387e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
338844871b1bSChris Mason 	if (free_space < data_size)
338944871b1bSChris Mason 		goto out_unlock;
339044871b1bSChris Mason 
339144871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3392bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
339344871b1bSChris Mason 	if (ret)
339444871b1bSChris Mason 		goto out_unlock;
339544871b1bSChris Mason 
339644871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
339744871b1bSChris Mason 	if (left_nritems == 0)
339844871b1bSChris Mason 		goto out_unlock;
339944871b1bSChris Mason 
3400d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3401d16c702fSQu Wenruo 		ret = -EUCLEAN;
34029ae5afd0SFilipe Manana 		btrfs_abort_transaction(trans, ret);
3403d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3404d16c702fSQu Wenruo 		free_extent_buffer(right);
3405d16c702fSQu Wenruo 		return ret;
3406d16c702fSQu Wenruo 	}
34072ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
34082ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
34092ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
34102ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
341152042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
34122ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
34132ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
34142ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
34152ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
34162ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
34172ef1fed2SFilipe David Borba Manana 		return 0;
34182ef1fed2SFilipe David Borba Manana 	}
34192ef1fed2SFilipe David Borba Manana 
3420ed25dab3SJosef Bacik 	return __push_leaf_right(trans, path, min_data_size, empty, right,
3421ed25dab3SJosef Bacik 				 free_space, left_nritems, min_slot);
342244871b1bSChris Mason out_unlock:
342344871b1bSChris Mason 	btrfs_tree_unlock(right);
342444871b1bSChris Mason 	free_extent_buffer(right);
342544871b1bSChris Mason 	return 1;
342644871b1bSChris Mason }
342744871b1bSChris Mason 
342844871b1bSChris Mason /*
342944871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
343044871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
343199d8f83cSChris Mason  *
343299d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
343399d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
343499d8f83cSChris Mason  * items
343544871b1bSChris Mason  */
3436ed25dab3SJosef Bacik static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
3437ed25dab3SJosef Bacik 				     struct btrfs_path *path, int data_size,
343844871b1bSChris Mason 				     int empty, struct extent_buffer *left,
343999d8f83cSChris Mason 				     int free_space, u32 right_nritems,
344099d8f83cSChris Mason 				     u32 max_slot)
344144871b1bSChris Mason {
34428087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
34435f39d397SChris Mason 	struct btrfs_disk_key disk_key;
34445f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3445be0e5c09SChris Mason 	int i;
3446be0e5c09SChris Mason 	int push_space = 0;
3447be0e5c09SChris Mason 	int push_items = 0;
34487518a238SChris Mason 	u32 old_left_nritems;
344934a38218SChris Mason 	u32 nr;
3450aa5d6bedSChris Mason 	int ret = 0;
3451db94535dSChris Mason 	u32 this_item_size;
3452db94535dSChris Mason 	u32 old_left_item_size;
3453cfed81a0SChris Mason 	struct btrfs_map_token token;
3454cfed81a0SChris Mason 
345534a38218SChris Mason 	if (empty)
345699d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
345734a38218SChris Mason 	else
345899d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
345934a38218SChris Mason 
346034a38218SChris Mason 	for (i = 0; i < nr; i++) {
346131840ae1SZheng Yan 		if (!empty && push_items > 0) {
346231840ae1SZheng Yan 			if (path->slots[0] < i)
346331840ae1SZheng Yan 				break;
346431840ae1SZheng Yan 			if (path->slots[0] == i) {
3465e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3466e902baacSDavid Sterba 
346731840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
346831840ae1SZheng Yan 					break;
346931840ae1SZheng Yan 			}
347031840ae1SZheng Yan 		}
347131840ae1SZheng Yan 
3472be0e5c09SChris Mason 		if (path->slots[0] == i)
347387b29b20SYan Zheng 			push_space += data_size;
3474db94535dSChris Mason 
34753212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
347674794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
347774794207SJosef Bacik 		    free_space)
3478be0e5c09SChris Mason 			break;
3479db94535dSChris Mason 
3480be0e5c09SChris Mason 		push_items++;
348174794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3482be0e5c09SChris Mason 	}
3483db94535dSChris Mason 
3484be0e5c09SChris Mason 	if (push_items == 0) {
3485925baeddSChris Mason 		ret = 1;
3486925baeddSChris Mason 		goto out;
3487be0e5c09SChris Mason 	}
3488fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
34895f39d397SChris Mason 
3490be0e5c09SChris Mason 	/* push data from right to left */
3491637e3b48SJosef Bacik 	copy_leaf_items(left, right, btrfs_header_nritems(left), 0, push_items);
34925f39d397SChris Mason 
34930b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
34943212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
34955f39d397SChris Mason 
3496637e3b48SJosef Bacik 	copy_leaf_data(left, right, leaf_data_end(left) - push_space,
3497637e3b48SJosef Bacik 		       btrfs_item_offset(right, push_items - 1), push_space);
34985f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
349987b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3500eb60ceacSChris Mason 
3501c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
35023212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3503be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
35045f39d397SChris Mason 		u32 ioff;
3505db94535dSChris Mason 
35063212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
35073212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3508cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3509be0e5c09SChris Mason 	}
35105f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3511be0e5c09SChris Mason 
3512be0e5c09SChris Mason 	/* fixup right node */
351331b1a2bdSJulia Lawall 	if (push_items > right_nritems)
351431b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3515d397712bSChris Mason 		       right_nritems);
351634a38218SChris Mason 
351734a38218SChris Mason 	if (push_items < right_nritems) {
35183212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
35198f881e8cSDavid Sterba 						  leaf_data_end(right);
3520637e3b48SJosef Bacik 		memmove_leaf_data(right,
35210b246afaSJeff Mahoney 				  BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
35228f881e8cSDavid Sterba 				  leaf_data_end(right), push_space);
35235f39d397SChris Mason 
3524637e3b48SJosef Bacik 		memmove_leaf_items(right, 0, push_items,
3525637e3b48SJosef Bacik 				   btrfs_header_nritems(right) - push_items);
352634a38218SChris Mason 	}
3527c82f823cSDavid Sterba 
3528c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3529eef1c494SYan 	right_nritems -= push_items;
3530eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
35310b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
35325f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
35333212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
35343212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3535db94535dSChris Mason 	}
3536eb60ceacSChris Mason 
35375f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
353834a38218SChris Mason 	if (right_nritems)
35395f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3540f0486c68SYan, Zheng 	else
3541190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, right);
3542098f59c2SChris Mason 
35435f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3544b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3545be0e5c09SChris Mason 
3546be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3547be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3548be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3549925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
35505f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
35515f39d397SChris Mason 		path->nodes[0] = left;
3552be0e5c09SChris Mason 		path->slots[1] -= 1;
3553be0e5c09SChris Mason 	} else {
3554925baeddSChris Mason 		btrfs_tree_unlock(left);
35555f39d397SChris Mason 		free_extent_buffer(left);
3556be0e5c09SChris Mason 		path->slots[0] -= push_items;
3557be0e5c09SChris Mason 	}
3558eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3559aa5d6bedSChris Mason 	return ret;
3560925baeddSChris Mason out:
3561925baeddSChris Mason 	btrfs_tree_unlock(left);
3562925baeddSChris Mason 	free_extent_buffer(left);
3563925baeddSChris Mason 	return ret;
3564be0e5c09SChris Mason }
3565be0e5c09SChris Mason 
356674123bd7SChris Mason /*
356744871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
356844871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
356999d8f83cSChris Mason  *
357099d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
357199d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
357299d8f83cSChris Mason  * items
357344871b1bSChris Mason  */
357444871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
357599d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
357699d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
357744871b1bSChris Mason {
357844871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
357944871b1bSChris Mason 	struct extent_buffer *left;
358044871b1bSChris Mason 	int slot;
358144871b1bSChris Mason 	int free_space;
358244871b1bSChris Mason 	u32 right_nritems;
358344871b1bSChris Mason 	int ret = 0;
358444871b1bSChris Mason 
358544871b1bSChris Mason 	slot = path->slots[1];
358644871b1bSChris Mason 	if (slot == 0)
358744871b1bSChris Mason 		return 1;
358844871b1bSChris Mason 	if (!path->nodes[1])
358944871b1bSChris Mason 		return 1;
359044871b1bSChris Mason 
359144871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
359244871b1bSChris Mason 	if (right_nritems == 0)
359344871b1bSChris Mason 		return 1;
359444871b1bSChris Mason 
359549d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
359644871b1bSChris Mason 
35974b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3598fb770ae4SLiu Bo 	if (IS_ERR(left))
35999cf14029SJosef Bacik 		return PTR_ERR(left);
360091ca338dSTsutomu Itoh 
3601bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
360244871b1bSChris Mason 
3603e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
360444871b1bSChris Mason 	if (free_space < data_size) {
360544871b1bSChris Mason 		ret = 1;
360644871b1bSChris Mason 		goto out;
360744871b1bSChris Mason 	}
360844871b1bSChris Mason 
360944871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
36109631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3611bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
361244871b1bSChris Mason 	if (ret) {
361344871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
361479787eaaSJeff Mahoney 		if (ret == -ENOSPC)
361544871b1bSChris Mason 			ret = 1;
361644871b1bSChris Mason 		goto out;
361744871b1bSChris Mason 	}
361844871b1bSChris Mason 
3619d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3620d16c702fSQu Wenruo 		ret = -EUCLEAN;
36219ae5afd0SFilipe Manana 		btrfs_abort_transaction(trans, ret);
3622d16c702fSQu Wenruo 		goto out;
3623d16c702fSQu Wenruo 	}
3624ed25dab3SJosef Bacik 	return __push_leaf_left(trans, path, min_data_size, empty, left,
3625ed25dab3SJosef Bacik 				free_space, right_nritems, max_slot);
362644871b1bSChris Mason out:
362744871b1bSChris Mason 	btrfs_tree_unlock(left);
362844871b1bSChris Mason 	free_extent_buffer(left);
362944871b1bSChris Mason 	return ret;
363044871b1bSChris Mason }
363144871b1bSChris Mason 
363244871b1bSChris Mason /*
363374123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
363474123bd7SChris Mason  * available for the resulting leaf level of the path.
363574123bd7SChris Mason  */
363650b5d1fcSFilipe Manana static noinline int copy_for_split(struct btrfs_trans_handle *trans,
363744871b1bSChris Mason 				   struct btrfs_path *path,
363844871b1bSChris Mason 				   struct extent_buffer *l,
363944871b1bSChris Mason 				   struct extent_buffer *right,
364044871b1bSChris Mason 				   int slot, int mid, int nritems)
3641be0e5c09SChris Mason {
364294f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3643be0e5c09SChris Mason 	int data_copy_size;
3644be0e5c09SChris Mason 	int rt_data_off;
3645be0e5c09SChris Mason 	int i;
364650b5d1fcSFilipe Manana 	int ret;
3647d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3648cfed81a0SChris Mason 	struct btrfs_map_token token;
3649cfed81a0SChris Mason 
36505f39d397SChris Mason 	nritems = nritems - mid;
36515f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3652dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
36535f39d397SChris Mason 
3654637e3b48SJosef Bacik 	copy_leaf_items(right, l, 0, mid, nritems);
36555f39d397SChris Mason 
3656637e3b48SJosef Bacik 	copy_leaf_data(right, l, BTRFS_LEAF_DATA_SIZE(fs_info) - data_copy_size,
36578f881e8cSDavid Sterba 		       leaf_data_end(l), data_copy_size);
365874123bd7SChris Mason 
3659dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
36605f39d397SChris Mason 
3661c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
36625f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3663db94535dSChris Mason 		u32 ioff;
3664db94535dSChris Mason 
36653212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
36663212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
36670783fcfcSChris Mason 	}
366874123bd7SChris Mason 
36695f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
36705f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
367150b5d1fcSFilipe Manana 	ret = insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
367250b5d1fcSFilipe Manana 	if (ret < 0)
367350b5d1fcSFilipe Manana 		return ret;
36745f39d397SChris Mason 
36755f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
36765f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3677eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
36785f39d397SChris Mason 
3679be0e5c09SChris Mason 	if (mid <= slot) {
3680925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
36815f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
36825f39d397SChris Mason 		path->nodes[0] = right;
3683be0e5c09SChris Mason 		path->slots[0] -= mid;
3684be0e5c09SChris Mason 		path->slots[1] += 1;
3685925baeddSChris Mason 	} else {
3686925baeddSChris Mason 		btrfs_tree_unlock(right);
36875f39d397SChris Mason 		free_extent_buffer(right);
3688925baeddSChris Mason 	}
36895f39d397SChris Mason 
3690eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
369150b5d1fcSFilipe Manana 
369250b5d1fcSFilipe Manana 	return 0;
369344871b1bSChris Mason }
369444871b1bSChris Mason 
369544871b1bSChris Mason /*
369699d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
369799d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
369899d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
369999d8f83cSChris Mason  *          A                 B                 C
370099d8f83cSChris Mason  *
370199d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
370299d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
370399d8f83cSChris Mason  * completely.
370499d8f83cSChris Mason  */
370599d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
370699d8f83cSChris Mason 					  struct btrfs_root *root,
370799d8f83cSChris Mason 					  struct btrfs_path *path,
370899d8f83cSChris Mason 					  int data_size)
370999d8f83cSChris Mason {
371099d8f83cSChris Mason 	int ret;
371199d8f83cSChris Mason 	int progress = 0;
371299d8f83cSChris Mason 	int slot;
371399d8f83cSChris Mason 	u32 nritems;
37145a4267caSFilipe David Borba Manana 	int space_needed = data_size;
371599d8f83cSChris Mason 
371699d8f83cSChris Mason 	slot = path->slots[0];
37175a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3718e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
371999d8f83cSChris Mason 
372099d8f83cSChris Mason 	/*
372199d8f83cSChris Mason 	 * try to push all the items after our slot into the
372299d8f83cSChris Mason 	 * right leaf
372399d8f83cSChris Mason 	 */
37245a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
372599d8f83cSChris Mason 	if (ret < 0)
372699d8f83cSChris Mason 		return ret;
372799d8f83cSChris Mason 
372899d8f83cSChris Mason 	if (ret == 0)
372999d8f83cSChris Mason 		progress++;
373099d8f83cSChris Mason 
373199d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
373299d8f83cSChris Mason 	/*
373399d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
373499d8f83cSChris Mason 	 * we've done so we're done
373599d8f83cSChris Mason 	 */
373699d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
373799d8f83cSChris Mason 		return 0;
373899d8f83cSChris Mason 
3739e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
374099d8f83cSChris Mason 		return 0;
374199d8f83cSChris Mason 
374299d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
374399d8f83cSChris Mason 	slot = path->slots[0];
3744263d3995SFilipe Manana 	space_needed = data_size;
3745263d3995SFilipe Manana 	if (slot > 0)
3746e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
37475a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
374899d8f83cSChris Mason 	if (ret < 0)
374999d8f83cSChris Mason 		return ret;
375099d8f83cSChris Mason 
375199d8f83cSChris Mason 	if (ret == 0)
375299d8f83cSChris Mason 		progress++;
375399d8f83cSChris Mason 
375499d8f83cSChris Mason 	if (progress)
375599d8f83cSChris Mason 		return 0;
375699d8f83cSChris Mason 	return 1;
375799d8f83cSChris Mason }
375899d8f83cSChris Mason 
375999d8f83cSChris Mason /*
376044871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
376144871b1bSChris Mason  * available for the resulting leaf level of the path.
376244871b1bSChris Mason  *
376344871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
376444871b1bSChris Mason  */
376544871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
376644871b1bSChris Mason 			       struct btrfs_root *root,
3767310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
376844871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
376944871b1bSChris Mason 			       int extend)
377044871b1bSChris Mason {
37715d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
377244871b1bSChris Mason 	struct extent_buffer *l;
377344871b1bSChris Mason 	u32 nritems;
377444871b1bSChris Mason 	int mid;
377544871b1bSChris Mason 	int slot;
377644871b1bSChris Mason 	struct extent_buffer *right;
3777b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
377844871b1bSChris Mason 	int ret = 0;
377944871b1bSChris Mason 	int wret;
37805d4f98a2SYan Zheng 	int split;
378144871b1bSChris Mason 	int num_doubles = 0;
378299d8f83cSChris Mason 	int tried_avoid_double = 0;
378344871b1bSChris Mason 
3784a5719521SYan, Zheng 	l = path->nodes[0];
3785a5719521SYan, Zheng 	slot = path->slots[0];
37863212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
37870b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3788a5719521SYan, Zheng 		return -EOVERFLOW;
3789a5719521SYan, Zheng 
379044871b1bSChris Mason 	/* first try to make some room by pushing left and right */
379133157e05SLiu Bo 	if (data_size && path->nodes[1]) {
37925a4267caSFilipe David Borba Manana 		int space_needed = data_size;
37935a4267caSFilipe David Borba Manana 
37945a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3795e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
37965a4267caSFilipe David Borba Manana 
37975a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
37985a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
379944871b1bSChris Mason 		if (wret < 0)
380044871b1bSChris Mason 			return wret;
380144871b1bSChris Mason 		if (wret) {
3802263d3995SFilipe Manana 			space_needed = data_size;
3803263d3995SFilipe Manana 			if (slot > 0)
3804e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
38055a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
38065a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
380744871b1bSChris Mason 			if (wret < 0)
380844871b1bSChris Mason 				return wret;
380944871b1bSChris Mason 		}
381044871b1bSChris Mason 		l = path->nodes[0];
381144871b1bSChris Mason 
381244871b1bSChris Mason 		/* did the pushes work? */
3813e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
381444871b1bSChris Mason 			return 0;
381544871b1bSChris Mason 	}
381644871b1bSChris Mason 
381744871b1bSChris Mason 	if (!path->nodes[1]) {
3818fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
381944871b1bSChris Mason 		if (ret)
382044871b1bSChris Mason 			return ret;
382144871b1bSChris Mason 	}
382244871b1bSChris Mason again:
38235d4f98a2SYan Zheng 	split = 1;
382444871b1bSChris Mason 	l = path->nodes[0];
382544871b1bSChris Mason 	slot = path->slots[0];
382644871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
382744871b1bSChris Mason 	mid = (nritems + 1) / 2;
382844871b1bSChris Mason 
38295d4f98a2SYan Zheng 	if (mid <= slot) {
38305d4f98a2SYan Zheng 		if (nritems == 1 ||
38315d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
38320b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
38335d4f98a2SYan Zheng 			if (slot >= nritems) {
38345d4f98a2SYan Zheng 				split = 0;
38355d4f98a2SYan Zheng 			} else {
38365d4f98a2SYan Zheng 				mid = slot;
38375d4f98a2SYan Zheng 				if (mid != nritems &&
38385d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
38390b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
384099d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
384199d8f83cSChris Mason 						goto push_for_double;
38425d4f98a2SYan Zheng 					split = 2;
38435d4f98a2SYan Zheng 				}
38445d4f98a2SYan Zheng 			}
38455d4f98a2SYan Zheng 		}
38465d4f98a2SYan Zheng 	} else {
38475d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
38480b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
38495d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
38505d4f98a2SYan Zheng 				split = 0;
38515d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
38525d4f98a2SYan Zheng 				mid = 1;
38535d4f98a2SYan Zheng 			} else {
38545d4f98a2SYan Zheng 				mid = slot;
38555d4f98a2SYan Zheng 				if (mid != nritems &&
38565d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
38570b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
385899d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
385999d8f83cSChris Mason 						goto push_for_double;
38605d4f98a2SYan Zheng 					split = 2;
38615d4f98a2SYan Zheng 				}
38625d4f98a2SYan Zheng 			}
38635d4f98a2SYan Zheng 		}
38645d4f98a2SYan Zheng 	}
38655d4f98a2SYan Zheng 
38665d4f98a2SYan Zheng 	if (split == 0)
38675d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
38685d4f98a2SYan Zheng 	else
38695d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
38705d4f98a2SYan Zheng 
3871ca9d473aSJosef Bacik 	/*
3872ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3873ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3874ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3875ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3876ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3877ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3878ca9d473aSJosef Bacik 	 */
387979bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
388079bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
388179bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3882ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3883f0486c68SYan, Zheng 	if (IS_ERR(right))
388444871b1bSChris Mason 		return PTR_ERR(right);
3885f0486c68SYan, Zheng 
38860b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
388744871b1bSChris Mason 
38885d4f98a2SYan Zheng 	if (split == 0) {
388944871b1bSChris Mason 		if (mid <= slot) {
389044871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
389150b5d1fcSFilipe Manana 			ret = insert_ptr(trans, path, &disk_key,
38922ff7e61eSJeff Mahoney 					 right->start, path->slots[1] + 1, 1);
389350b5d1fcSFilipe Manana 			if (ret < 0) {
389450b5d1fcSFilipe Manana 				btrfs_tree_unlock(right);
389550b5d1fcSFilipe Manana 				free_extent_buffer(right);
389650b5d1fcSFilipe Manana 				return ret;
389750b5d1fcSFilipe Manana 			}
389844871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
389944871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
390044871b1bSChris Mason 			path->nodes[0] = right;
390144871b1bSChris Mason 			path->slots[0] = 0;
390244871b1bSChris Mason 			path->slots[1] += 1;
390344871b1bSChris Mason 		} else {
390444871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
390550b5d1fcSFilipe Manana 			ret = insert_ptr(trans, path, &disk_key,
39062ff7e61eSJeff Mahoney 					 right->start, path->slots[1], 1);
390750b5d1fcSFilipe Manana 			if (ret < 0) {
390850b5d1fcSFilipe Manana 				btrfs_tree_unlock(right);
390950b5d1fcSFilipe Manana 				free_extent_buffer(right);
391050b5d1fcSFilipe Manana 				return ret;
391150b5d1fcSFilipe Manana 			}
391244871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
391344871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
391444871b1bSChris Mason 			path->nodes[0] = right;
391544871b1bSChris Mason 			path->slots[0] = 0;
3916143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3917b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
39185d4f98a2SYan Zheng 		}
3919196e0249SLiu Bo 		/*
3920196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3921196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3922196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3923196e0249SLiu Bo 		 */
392444871b1bSChris Mason 		return ret;
392544871b1bSChris Mason 	}
392644871b1bSChris Mason 
392750b5d1fcSFilipe Manana 	ret = copy_for_split(trans, path, l, right, slot, mid, nritems);
392850b5d1fcSFilipe Manana 	if (ret < 0) {
392950b5d1fcSFilipe Manana 		btrfs_tree_unlock(right);
393050b5d1fcSFilipe Manana 		free_extent_buffer(right);
393150b5d1fcSFilipe Manana 		return ret;
393250b5d1fcSFilipe Manana 	}
393344871b1bSChris Mason 
39345d4f98a2SYan Zheng 	if (split == 2) {
3935cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3936cc0c5538SChris Mason 		num_doubles++;
3937cc0c5538SChris Mason 		goto again;
39383326d1b0SChris Mason 	}
393944871b1bSChris Mason 
3940143bede5SJeff Mahoney 	return 0;
394199d8f83cSChris Mason 
394299d8f83cSChris Mason push_for_double:
394399d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
394499d8f83cSChris Mason 	tried_avoid_double = 1;
3945e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
394699d8f83cSChris Mason 		return 0;
394799d8f83cSChris Mason 	goto again;
3948be0e5c09SChris Mason }
3949be0e5c09SChris Mason 
3950ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3951ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3952ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3953ad48fd75SYan, Zheng {
3954ad48fd75SYan, Zheng 	struct btrfs_key key;
3955ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3956ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3957ad48fd75SYan, Zheng 	u64 extent_len = 0;
3958ad48fd75SYan, Zheng 	u32 item_size;
3959ad48fd75SYan, Zheng 	int ret;
3960ad48fd75SYan, Zheng 
3961ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3962ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3963ad48fd75SYan, Zheng 
3964ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3965ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3966ad48fd75SYan, Zheng 
3967e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3968ad48fd75SYan, Zheng 		return 0;
3969ad48fd75SYan, Zheng 
39703212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3971ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3972ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3973ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3974ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3975ad48fd75SYan, Zheng 	}
3976b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3977ad48fd75SYan, Zheng 
3978ad48fd75SYan, Zheng 	path->keep_locks = 1;
3979ad48fd75SYan, Zheng 	path->search_for_split = 1;
3980ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3981ad48fd75SYan, Zheng 	path->search_for_split = 0;
3982a8df6fe6SFilipe Manana 	if (ret > 0)
3983a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3984ad48fd75SYan, Zheng 	if (ret < 0)
3985ad48fd75SYan, Zheng 		goto err;
3986ad48fd75SYan, Zheng 
3987ad48fd75SYan, Zheng 	ret = -EAGAIN;
3988ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3989a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
39903212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3991ad48fd75SYan, Zheng 		goto err;
3992ad48fd75SYan, Zheng 
3993109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3994e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3995109f6aefSChris Mason 		goto err;
3996109f6aefSChris Mason 
3997ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3998ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3999ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4000ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4001ad48fd75SYan, Zheng 			goto err;
4002ad48fd75SYan, Zheng 	}
4003ad48fd75SYan, Zheng 
4004ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4005f0486c68SYan, Zheng 	if (ret)
4006f0486c68SYan, Zheng 		goto err;
4007ad48fd75SYan, Zheng 
4008ad48fd75SYan, Zheng 	path->keep_locks = 0;
4009ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4010ad48fd75SYan, Zheng 	return 0;
4011ad48fd75SYan, Zheng err:
4012ad48fd75SYan, Zheng 	path->keep_locks = 0;
4013ad48fd75SYan, Zheng 	return ret;
4014ad48fd75SYan, Zheng }
4015ad48fd75SYan, Zheng 
401625263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
4017310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
4018459931ecSChris Mason 			       unsigned long split_offset)
4019459931ecSChris Mason {
4020459931ecSChris Mason 	struct extent_buffer *leaf;
4021c91666b1SJosef Bacik 	int orig_slot, slot;
4022ad48fd75SYan, Zheng 	char *buf;
4023459931ecSChris Mason 	u32 nritems;
4024ad48fd75SYan, Zheng 	u32 item_size;
4025459931ecSChris Mason 	u32 orig_offset;
4026459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4027459931ecSChris Mason 
4028459931ecSChris Mason 	leaf = path->nodes[0];
40297569141eSFilipe Manana 	/*
40307569141eSFilipe Manana 	 * Shouldn't happen because the caller must have previously called
40317569141eSFilipe Manana 	 * setup_leaf_for_split() to make room for the new item in the leaf.
40327569141eSFilipe Manana 	 */
40337569141eSFilipe Manana 	if (WARN_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item)))
40347569141eSFilipe Manana 		return -ENOSPC;
4035b9473439SChris Mason 
4036c91666b1SJosef Bacik 	orig_slot = path->slots[0];
40373212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
40383212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4039459931ecSChris Mason 
4040459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4041ad48fd75SYan, Zheng 	if (!buf)
4042ad48fd75SYan, Zheng 		return -ENOMEM;
4043ad48fd75SYan, Zheng 
4044459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4045459931ecSChris Mason 			    path->slots[0]), item_size);
4046ad48fd75SYan, Zheng 
4047459931ecSChris Mason 	slot = path->slots[0] + 1;
4048459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4049459931ecSChris Mason 	if (slot != nritems) {
4050459931ecSChris Mason 		/* shift the items */
4051637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot + 1, slot, nritems - slot);
4052459931ecSChris Mason 	}
4053459931ecSChris Mason 
4054459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4055459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4056459931ecSChris Mason 
40573212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
40583212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
4059459931ecSChris Mason 
40603212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
4061459931ecSChris Mason 				 orig_offset + item_size - split_offset);
40623212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
4063459931ecSChris Mason 
4064459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4065459931ecSChris Mason 
4066459931ecSChris Mason 	/* write the data for the start of the original item */
4067459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4068459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4069459931ecSChris Mason 			    split_offset);
4070459931ecSChris Mason 
4071459931ecSChris Mason 	/* write the data for the new item */
4072459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4073459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4074459931ecSChris Mason 			    item_size - split_offset);
4075459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
4076459931ecSChris Mason 
4077e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
4078459931ecSChris Mason 	kfree(buf);
4079ad48fd75SYan, Zheng 	return 0;
4080ad48fd75SYan, Zheng }
4081ad48fd75SYan, Zheng 
4082ad48fd75SYan, Zheng /*
4083ad48fd75SYan, Zheng  * This function splits a single item into two items,
4084ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4085ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4086ad48fd75SYan, Zheng  *
4087ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4088ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4089ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4090ad48fd75SYan, Zheng  *
4091ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4092ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4093ad48fd75SYan, Zheng  *
4094ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4095ad48fd75SYan, Zheng  * leaf the entire time.
4096ad48fd75SYan, Zheng  */
4097ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4098ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4099ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4100310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
4101ad48fd75SYan, Zheng 		     unsigned long split_offset)
4102ad48fd75SYan, Zheng {
4103ad48fd75SYan, Zheng 	int ret;
4104ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4105ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4106ad48fd75SYan, Zheng 	if (ret)
4107459931ecSChris Mason 		return ret;
4108ad48fd75SYan, Zheng 
410925263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
4110ad48fd75SYan, Zheng 	return ret;
4111ad48fd75SYan, Zheng }
4112ad48fd75SYan, Zheng 
4113ad48fd75SYan, Zheng /*
4114d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4115d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4116d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4117d352ac68SChris Mason  * the front.
4118d352ac68SChris Mason  */
411978ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
4120b18c6685SChris Mason {
4121b18c6685SChris Mason 	int slot;
41225f39d397SChris Mason 	struct extent_buffer *leaf;
4123b18c6685SChris Mason 	u32 nritems;
4124b18c6685SChris Mason 	unsigned int data_end;
4125b18c6685SChris Mason 	unsigned int old_data_start;
4126b18c6685SChris Mason 	unsigned int old_size;
4127b18c6685SChris Mason 	unsigned int size_diff;
4128b18c6685SChris Mason 	int i;
4129cfed81a0SChris Mason 	struct btrfs_map_token token;
4130cfed81a0SChris Mason 
41315f39d397SChris Mason 	leaf = path->nodes[0];
4132179e29e4SChris Mason 	slot = path->slots[0];
4133179e29e4SChris Mason 
41343212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
4135179e29e4SChris Mason 	if (old_size == new_size)
4136143bede5SJeff Mahoney 		return;
4137b18c6685SChris Mason 
41385f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
41398f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4140b18c6685SChris Mason 
41413212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
4142179e29e4SChris Mason 
4143b18c6685SChris Mason 	size_diff = old_size - new_size;
4144b18c6685SChris Mason 
4145b18c6685SChris Mason 	BUG_ON(slot < 0);
4146b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4147b18c6685SChris Mason 
4148b18c6685SChris Mason 	/*
4149b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4150b18c6685SChris Mason 	 */
4151b18c6685SChris Mason 	/* first correct the data pointers */
4152c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4153b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
41545f39d397SChris Mason 		u32 ioff;
4155db94535dSChris Mason 
41563212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
41573212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
4158b18c6685SChris Mason 	}
4159db94535dSChris Mason 
4160b18c6685SChris Mason 	/* shift the data */
4161179e29e4SChris Mason 	if (from_end) {
4162637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
4163637e3b48SJosef Bacik 				  old_data_start + new_size - data_end);
4164179e29e4SChris Mason 	} else {
4165179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4166179e29e4SChris Mason 		u64 offset;
4167179e29e4SChris Mason 
4168179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4169179e29e4SChris Mason 
4170179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4171179e29e4SChris Mason 			unsigned long ptr;
4172179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4173179e29e4SChris Mason 
4174179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4175179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4176179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4177179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4178179e29e4SChris Mason 
4179179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4180179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4181179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4182179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4183179e29e4SChris Mason 				      (unsigned long)fi,
41847ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4185179e29e4SChris Mason 			}
4186179e29e4SChris Mason 		}
4187179e29e4SChris Mason 
4188637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
4189637e3b48SJosef Bacik 				  old_data_start - data_end);
4190179e29e4SChris Mason 
4191179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4192179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4193179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4194179e29e4SChris Mason 		if (slot == 0)
4195b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4196179e29e4SChris Mason 	}
41975f39d397SChris Mason 
41983212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
41995f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4200b18c6685SChris Mason 
4201e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4202a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4203b18c6685SChris Mason 		BUG();
42045f39d397SChris Mason 	}
4205b18c6685SChris Mason }
4206b18c6685SChris Mason 
4207d352ac68SChris Mason /*
42088f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4209d352ac68SChris Mason  */
4210c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
42116567e837SChris Mason {
42126567e837SChris Mason 	int slot;
42135f39d397SChris Mason 	struct extent_buffer *leaf;
42146567e837SChris Mason 	u32 nritems;
42156567e837SChris Mason 	unsigned int data_end;
42166567e837SChris Mason 	unsigned int old_data;
42176567e837SChris Mason 	unsigned int old_size;
42186567e837SChris Mason 	int i;
4219cfed81a0SChris Mason 	struct btrfs_map_token token;
4220cfed81a0SChris Mason 
42215f39d397SChris Mason 	leaf = path->nodes[0];
42226567e837SChris Mason 
42235f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
42248f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
42256567e837SChris Mason 
4226e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4227a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
42286567e837SChris Mason 		BUG();
42295f39d397SChris Mason 	}
42306567e837SChris Mason 	slot = path->slots[0];
4231dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
42326567e837SChris Mason 
42336567e837SChris Mason 	BUG_ON(slot < 0);
42343326d1b0SChris Mason 	if (slot >= nritems) {
4235a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4236c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4237d397712bSChris Mason 			   slot, nritems);
4238290342f6SArnd Bergmann 		BUG();
42393326d1b0SChris Mason 	}
42406567e837SChris Mason 
42416567e837SChris Mason 	/*
42426567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
42436567e837SChris Mason 	 */
42446567e837SChris Mason 	/* first correct the data pointers */
4245c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
42466567e837SChris Mason 	for (i = slot; i < nritems; i++) {
42475f39d397SChris Mason 		u32 ioff;
4248db94535dSChris Mason 
42493212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
42503212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
42516567e837SChris Mason 	}
42525f39d397SChris Mason 
42536567e837SChris Mason 	/* shift the data */
4254637e3b48SJosef Bacik 	memmove_leaf_data(leaf, data_end - data_size, data_end,
4255637e3b48SJosef Bacik 			  old_data - data_end);
42565f39d397SChris Mason 
42576567e837SChris Mason 	data_end = old_data;
42583212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
42593212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
42605f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
42616567e837SChris Mason 
4262e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4263a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
42646567e837SChris Mason 		BUG();
42655f39d397SChris Mason 	}
42666567e837SChris Mason }
42676567e837SChris Mason 
426843dd529aSDavid Sterba /*
426943dd529aSDavid Sterba  * Make space in the node before inserting one or more items.
4270da9ffb24SNikolay Borisov  *
4271da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
4272da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
4273b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
427443dd529aSDavid Sterba  *
427543dd529aSDavid Sterba  * Main purpose is to save stack depth by doing the bulk of the work in a
427643dd529aSDavid Sterba  * function that doesn't call btrfs_search_slot
427774123bd7SChris Mason  */
4278f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4279b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
4280be0e5c09SChris Mason {
42810b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
42829c58309dSChris Mason 	int i;
42837518a238SChris Mason 	u32 nritems;
4284be0e5c09SChris Mason 	unsigned int data_end;
4285e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
428644871b1bSChris Mason 	struct extent_buffer *leaf;
428744871b1bSChris Mason 	int slot;
4288cfed81a0SChris Mason 	struct btrfs_map_token token;
4289fc0d82e1SNikolay Borisov 	u32 total_size;
4290fc0d82e1SNikolay Borisov 
4291b7ef5f3aSFilipe Manana 	/*
4292b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
4293b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
4294b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
4295b7ef5f3aSFilipe Manana 	 */
429624cdc847SFilipe Manana 	if (path->slots[0] == 0) {
4297b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4298b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
429924cdc847SFilipe Manana 	}
430024cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
430124cdc847SFilipe Manana 
43025f39d397SChris Mason 	leaf = path->nodes[0];
430344871b1bSChris Mason 	slot = path->slots[0];
430474123bd7SChris Mason 
43055f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
43068f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4307b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4308eb60ceacSChris Mason 
4309e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4310a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
43110b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4312e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4313be0e5c09SChris Mason 		BUG();
4314d4dbff95SChris Mason 	}
43155f39d397SChris Mason 
4316c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4317be0e5c09SChris Mason 	if (slot != nritems) {
4318dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4319be0e5c09SChris Mason 
43205f39d397SChris Mason 		if (old_data < data_end) {
4321a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
43227269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
43237269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
43245f39d397SChris Mason 				   slot, old_data, data_end);
4325290342f6SArnd Bergmann 			BUG();
43265f39d397SChris Mason 		}
4327be0e5c09SChris Mason 		/*
4328be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4329be0e5c09SChris Mason 		 */
4330be0e5c09SChris Mason 		/* first correct the data pointers */
43310783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
43325f39d397SChris Mason 			u32 ioff;
4333db94535dSChris Mason 
43343212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
43353212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
4336b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
43370783fcfcSChris Mason 		}
4338be0e5c09SChris Mason 		/* shift the items */
4339637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot + batch->nr, slot, nritems - slot);
4340be0e5c09SChris Mason 
4341be0e5c09SChris Mason 		/* shift the data */
4342637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end - batch->total_data_size,
4343637e3b48SJosef Bacik 				  data_end, old_data - data_end);
4344be0e5c09SChris Mason 		data_end = old_data;
4345be0e5c09SChris Mason 	}
43465f39d397SChris Mason 
434762e2749eSChris Mason 	/* setup the item for the new data */
4348b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
4349b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
43509c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4351b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
43523212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
43533212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
43549c58309dSChris Mason 	}
435544871b1bSChris Mason 
4356b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4357b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4358aa5d6bedSChris Mason 
4359e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4360a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4361be0e5c09SChris Mason 		BUG();
43625f39d397SChris Mason 	}
436344871b1bSChris Mason }
436444871b1bSChris Mason 
436544871b1bSChris Mason /*
4366f0641656SFilipe Manana  * Insert a new item into a leaf.
4367f0641656SFilipe Manana  *
4368f0641656SFilipe Manana  * @root:      The root of the btree.
4369f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
4370f0641656SFilipe Manana  * @key:       The key of the new item.
4371f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
4372f0641656SFilipe Manana  */
4373f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
4374f0641656SFilipe Manana 				 struct btrfs_path *path,
4375f0641656SFilipe Manana 				 const struct btrfs_key *key,
4376f0641656SFilipe Manana 				 u32 data_size)
4377f0641656SFilipe Manana {
4378f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4379f0641656SFilipe Manana 
4380f0641656SFilipe Manana 	batch.keys = key;
4381f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4382f0641656SFilipe Manana 	batch.total_data_size = data_size;
4383f0641656SFilipe Manana 	batch.nr = 1;
4384f0641656SFilipe Manana 
4385f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
4386f0641656SFilipe Manana }
4387f0641656SFilipe Manana 
4388f0641656SFilipe Manana /*
438944871b1bSChris Mason  * Given a key and some data, insert items into the tree.
439044871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
439144871b1bSChris Mason  */
439244871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
439344871b1bSChris Mason 			    struct btrfs_root *root,
439444871b1bSChris Mason 			    struct btrfs_path *path,
4395b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
439644871b1bSChris Mason {
439744871b1bSChris Mason 	int ret = 0;
439844871b1bSChris Mason 	int slot;
4399b7ef5f3aSFilipe Manana 	u32 total_size;
440044871b1bSChris Mason 
4401b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4402b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
440344871b1bSChris Mason 	if (ret == 0)
440444871b1bSChris Mason 		return -EEXIST;
440544871b1bSChris Mason 	if (ret < 0)
4406143bede5SJeff Mahoney 		return ret;
440744871b1bSChris Mason 
440844871b1bSChris Mason 	slot = path->slots[0];
440944871b1bSChris Mason 	BUG_ON(slot < 0);
441044871b1bSChris Mason 
4411b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4412143bede5SJeff Mahoney 	return 0;
441362e2749eSChris Mason }
441462e2749eSChris Mason 
441562e2749eSChris Mason /*
441662e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
441762e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
441862e2749eSChris Mason  */
4419310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4420310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4421310712b2SOmar Sandoval 		      u32 data_size)
442262e2749eSChris Mason {
442362e2749eSChris Mason 	int ret = 0;
44242c90e5d6SChris Mason 	struct btrfs_path *path;
44255f39d397SChris Mason 	struct extent_buffer *leaf;
44265f39d397SChris Mason 	unsigned long ptr;
442762e2749eSChris Mason 
44282c90e5d6SChris Mason 	path = btrfs_alloc_path();
4429db5b493aSTsutomu Itoh 	if (!path)
4430db5b493aSTsutomu Itoh 		return -ENOMEM;
44312c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
443262e2749eSChris Mason 	if (!ret) {
44335f39d397SChris Mason 		leaf = path->nodes[0];
44345f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
44355f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
44365f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
443762e2749eSChris Mason 	}
44382c90e5d6SChris Mason 	btrfs_free_path(path);
4439aa5d6bedSChris Mason 	return ret;
4440be0e5c09SChris Mason }
4441be0e5c09SChris Mason 
444274123bd7SChris Mason /*
4443f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4444f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4445f0641656SFilipe Manana  * contiguous with the original item.
4446f0641656SFilipe Manana  *
4447f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4448f0641656SFilipe Manana  * the entire time.
4449f0641656SFilipe Manana  */
4450f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4451f0641656SFilipe Manana 			 struct btrfs_root *root,
4452f0641656SFilipe Manana 			 struct btrfs_path *path,
4453f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4454f0641656SFilipe Manana {
4455f0641656SFilipe Manana 	struct extent_buffer *leaf;
4456f0641656SFilipe Manana 	int ret;
4457f0641656SFilipe Manana 	u32 item_size;
4458f0641656SFilipe Manana 
4459f0641656SFilipe Manana 	leaf = path->nodes[0];
44603212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4461f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4462f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4463f0641656SFilipe Manana 	if (ret)
4464f0641656SFilipe Manana 		return ret;
4465f0641656SFilipe Manana 
4466f0641656SFilipe Manana 	path->slots[0]++;
4467f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4468f0641656SFilipe Manana 	leaf = path->nodes[0];
4469f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4470f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4471f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4472f0641656SFilipe Manana 			     item_size);
4473f0641656SFilipe Manana 	return 0;
4474f0641656SFilipe Manana }
4475f0641656SFilipe Manana 
4476f0641656SFilipe Manana /*
44775de08d7dSChris Mason  * delete the pointer from a given node.
447874123bd7SChris Mason  *
4479d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4480d352ac68SChris Mason  * empty a node.
4481016f9d0bSJosef Bacik  *
4482016f9d0bSJosef Bacik  * This is exported for use inside btrfs-progs, don't un-export it.
448374123bd7SChris Mason  */
4484751a2761SFilipe Manana int btrfs_del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4485751a2761SFilipe Manana 		  struct btrfs_path *path, int level, int slot)
4486be0e5c09SChris Mason {
44875f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
44887518a238SChris Mason 	u32 nritems;
4489f3ea38daSJan Schmidt 	int ret;
4490be0e5c09SChris Mason 
44915f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4492be0e5c09SChris Mason 	if (slot != nritems - 1) {
4493bf1d3425SDavid Sterba 		if (level) {
4494f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4495f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4496751a2761SFilipe Manana 			if (ret < 0) {
4497751a2761SFilipe Manana 				btrfs_abort_transaction(trans, ret);
4498751a2761SFilipe Manana 				return ret;
4499751a2761SFilipe Manana 			}
4500bf1d3425SDavid Sterba 		}
45015f39d397SChris Mason 		memmove_extent_buffer(parent,
4502e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot),
4503e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot + 1),
4504d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4505d6025579SChris Mason 			      (nritems - slot - 1));
450657ba86c0SChris Mason 	} else if (level) {
4507f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
450833cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REMOVE);
4509751a2761SFilipe Manana 		if (ret < 0) {
4510751a2761SFilipe Manana 			btrfs_abort_transaction(trans, ret);
4511751a2761SFilipe Manana 			return ret;
4512751a2761SFilipe Manana 		}
4513be0e5c09SChris Mason 	}
4514f3ea38daSJan Schmidt 
45157518a238SChris Mason 	nritems--;
45165f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
45177518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
45185f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4519eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
45205f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4521bb803951SChris Mason 	} else if (slot == 0) {
45225f39d397SChris Mason 		struct btrfs_disk_key disk_key;
45235f39d397SChris Mason 
45245f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4525b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4526be0e5c09SChris Mason 	}
4527d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4528751a2761SFilipe Manana 	return 0;
4529be0e5c09SChris Mason }
4530be0e5c09SChris Mason 
453174123bd7SChris Mason /*
4532323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
45335d4f98a2SYan Zheng  * path->nodes[1].
4534323ac95bSChris Mason  *
4535323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4536323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4537323ac95bSChris Mason  *
4538323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4539323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4540323ac95bSChris Mason  */
4541751a2761SFilipe Manana static noinline int btrfs_del_leaf(struct btrfs_trans_handle *trans,
4542323ac95bSChris Mason 				   struct btrfs_root *root,
45435d4f98a2SYan Zheng 				   struct btrfs_path *path,
45445d4f98a2SYan Zheng 				   struct extent_buffer *leaf)
4545323ac95bSChris Mason {
4546751a2761SFilipe Manana 	int ret;
4547751a2761SFilipe Manana 
45485d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4549751a2761SFilipe Manana 	ret = btrfs_del_ptr(trans, root, path, 1, path->slots[1]);
4550751a2761SFilipe Manana 	if (ret < 0)
4551751a2761SFilipe Manana 		return ret;
4552323ac95bSChris Mason 
45534d081c41SChris Mason 	/*
45544d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
45554d081c41SChris Mason 	 * aren't holding any locks when we call it
45564d081c41SChris Mason 	 */
45574d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
45584d081c41SChris Mason 
4559f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4560f0486c68SYan, Zheng 
456167439dadSDavid Sterba 	atomic_inc(&leaf->refs);
45627a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
45633083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4564751a2761SFilipe Manana 	return 0;
4565323ac95bSChris Mason }
4566323ac95bSChris Mason /*
456774123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
456874123bd7SChris Mason  * the leaf, remove it from the tree
456974123bd7SChris Mason  */
457085e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
457185e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4572be0e5c09SChris Mason {
45730b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
45745f39d397SChris Mason 	struct extent_buffer *leaf;
4575aa5d6bedSChris Mason 	int ret = 0;
4576aa5d6bedSChris Mason 	int wret;
45777518a238SChris Mason 	u32 nritems;
4578be0e5c09SChris Mason 
45795f39d397SChris Mason 	leaf = path->nodes[0];
45805f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4581be0e5c09SChris Mason 
458285e21bacSChris Mason 	if (slot + nr != nritems) {
45830cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
45840cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4585c82f823cSDavid Sterba 		struct btrfs_map_token token;
45860cae23b6SFilipe Manana 		u32 dsize = 0;
45870cae23b6SFilipe Manana 		int i;
45880cae23b6SFilipe Manana 
45890cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
45900cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
45915f39d397SChris Mason 
4592637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + dsize, data_end,
459385e21bacSChris Mason 				  last_off - data_end);
45945f39d397SChris Mason 
4595c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
459685e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
45975f39d397SChris Mason 			u32 ioff;
4598db94535dSChris Mason 
45993212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
46003212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
46010783fcfcSChris Mason 		}
4602db94535dSChris Mason 
4603637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot, slot + nr, nritems - slot - nr);
4604be0e5c09SChris Mason 	}
460585e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
460685e21bacSChris Mason 	nritems -= nr;
46075f39d397SChris Mason 
460874123bd7SChris Mason 	/* delete the leaf if we've emptied it */
46097518a238SChris Mason 	if (nritems == 0) {
46105f39d397SChris Mason 		if (leaf == root->node) {
46115f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
46129a8dd150SChris Mason 		} else {
4613190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, leaf);
4614751a2761SFilipe Manana 			ret = btrfs_del_leaf(trans, root, path, leaf);
4615751a2761SFilipe Manana 			if (ret < 0)
4616751a2761SFilipe Manana 				return ret;
46179a8dd150SChris Mason 		}
4618be0e5c09SChris Mason 	} else {
46197518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4620aa5d6bedSChris Mason 		if (slot == 0) {
46215f39d397SChris Mason 			struct btrfs_disk_key disk_key;
46225f39d397SChris Mason 
46235f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4624b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4625aa5d6bedSChris Mason 		}
4626aa5d6bedSChris Mason 
46277c4063d1SFilipe Manana 		/*
46287c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
46297c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
46307c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
46317c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
46327c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
46337c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
46347c4063d1SFilipe Manana 		 */
46350b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
46367c4063d1SFilipe Manana 			u32 min_push_space;
46377c4063d1SFilipe Manana 
4638be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4639be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4640016f9d0bSJosef Bacik 			 * for possible call to btrfs_del_ptr below
4641be0e5c09SChris Mason 			 */
46424920c9acSChris Mason 			slot = path->slots[1];
464367439dadSDavid Sterba 			atomic_inc(&leaf->refs);
46447c4063d1SFilipe Manana 			/*
46457c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
46467c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
46477c4063d1SFilipe Manana 			 */
46487c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
46497c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
46507c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
46517c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
465254aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4653aa5d6bedSChris Mason 				ret = wret;
46545f39d397SChris Mason 
46555f39d397SChris Mason 			if (path->nodes[0] == leaf &&
46565f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
46577c4063d1SFilipe Manana 				/*
46587c4063d1SFilipe Manana 				 * If we were not able to push all items from our
46597c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
46607c4063d1SFilipe Manana 				 * either push all the remaining items to the
46617c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
46627c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
46637c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
46647c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
46657c4063d1SFilipe Manana 				 * or nearly full.
46667c4063d1SFilipe Manana 				 */
46677c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
46687c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
46697c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
46707c4063d1SFilipe Manana 						       min_push_space, 1, 0);
467154aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4672aa5d6bedSChris Mason 					ret = wret;
4673aa5d6bedSChris Mason 			}
46745f39d397SChris Mason 
46755f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4676323ac95bSChris Mason 				path->slots[1] = slot;
4677751a2761SFilipe Manana 				ret = btrfs_del_leaf(trans, root, path, leaf);
4678751a2761SFilipe Manana 				if (ret < 0)
4679751a2761SFilipe Manana 					return ret;
46805f39d397SChris Mason 				free_extent_buffer(leaf);
4681143bede5SJeff Mahoney 				ret = 0;
46825de08d7dSChris Mason 			} else {
4683925baeddSChris Mason 				/* if we're still in the path, make sure
4684925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4685925baeddSChris Mason 				 * push_leaf functions must have already
4686925baeddSChris Mason 				 * dirtied this buffer
4687925baeddSChris Mason 				 */
4688925baeddSChris Mason 				if (path->nodes[0] == leaf)
46895f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
46905f39d397SChris Mason 				free_extent_buffer(leaf);
4691be0e5c09SChris Mason 			}
4692d5719762SChris Mason 		} else {
46935f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4694be0e5c09SChris Mason 		}
46959a8dd150SChris Mason 	}
4696aa5d6bedSChris Mason 	return ret;
46979a8dd150SChris Mason }
46989a8dd150SChris Mason 
469997571fd0SChris Mason /*
47003f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4701de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4702de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
47033f157a2fSChris Mason  *
47043f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
47053f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
47063f157a2fSChris Mason  * key and get a writable path.
47073f157a2fSChris Mason  *
47083f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
47093f157a2fSChris Mason  * of the tree.
47103f157a2fSChris Mason  *
4711d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4712d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4713d352ac68SChris Mason  * skipped over (without reading them).
4714d352ac68SChris Mason  *
47153f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
47163f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
47173f157a2fSChris Mason  */
47183f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4719de78b51aSEric Sandeen 			 struct btrfs_path *path,
47203f157a2fSChris Mason 			 u64 min_trans)
47213f157a2fSChris Mason {
47223f157a2fSChris Mason 	struct extent_buffer *cur;
47233f157a2fSChris Mason 	struct btrfs_key found_key;
47243f157a2fSChris Mason 	int slot;
47259652480bSYan 	int sret;
47263f157a2fSChris Mason 	u32 nritems;
47273f157a2fSChris Mason 	int level;
47283f157a2fSChris Mason 	int ret = 1;
4729f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
47303f157a2fSChris Mason 
4731c922b016SStefan Roesch 	ASSERT(!path->nowait);
4732f98de9b9SFilipe Manana 	path->keep_locks = 1;
47333f157a2fSChris Mason again:
4734bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
47353f157a2fSChris Mason 	level = btrfs_header_level(cur);
4736e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
47373f157a2fSChris Mason 	path->nodes[level] = cur;
4738bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
47393f157a2fSChris Mason 
47403f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
47413f157a2fSChris Mason 		ret = 1;
47423f157a2fSChris Mason 		goto out;
47433f157a2fSChris Mason 	}
47443f157a2fSChris Mason 	while (1) {
47453f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
47463f157a2fSChris Mason 		level = btrfs_header_level(cur);
4747fdf8d595SAnand Jain 		sret = btrfs_bin_search(cur, 0, min_key, &slot);
4748cbca7d59SFilipe Manana 		if (sret < 0) {
4749cbca7d59SFilipe Manana 			ret = sret;
4750cbca7d59SFilipe Manana 			goto out;
4751cbca7d59SFilipe Manana 		}
47523f157a2fSChris Mason 
4753323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4754323ac95bSChris Mason 		if (level == path->lowest_level) {
4755e02119d5SChris Mason 			if (slot >= nritems)
4756e02119d5SChris Mason 				goto find_next_key;
47573f157a2fSChris Mason 			ret = 0;
47583f157a2fSChris Mason 			path->slots[level] = slot;
47593f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
47603f157a2fSChris Mason 			goto out;
47613f157a2fSChris Mason 		}
47629652480bSYan 		if (sret && slot > 0)
47639652480bSYan 			slot--;
47643f157a2fSChris Mason 		/*
4765de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4766260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
47673f157a2fSChris Mason 		 */
47683f157a2fSChris Mason 		while (slot < nritems) {
47693f157a2fSChris Mason 			u64 gen;
4770e02119d5SChris Mason 
47713f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
47723f157a2fSChris Mason 			if (gen < min_trans) {
47733f157a2fSChris Mason 				slot++;
47743f157a2fSChris Mason 				continue;
47753f157a2fSChris Mason 			}
47763f157a2fSChris Mason 			break;
47773f157a2fSChris Mason 		}
4778e02119d5SChris Mason find_next_key:
47793f157a2fSChris Mason 		/*
47803f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
47813f157a2fSChris Mason 		 * and find another one
47823f157a2fSChris Mason 		 */
47833f157a2fSChris Mason 		if (slot >= nritems) {
4784e02119d5SChris Mason 			path->slots[level] = slot;
4785e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4786de78b51aSEric Sandeen 						  min_trans);
4787e02119d5SChris Mason 			if (sret == 0) {
4788b3b4aa74SDavid Sterba 				btrfs_release_path(path);
47893f157a2fSChris Mason 				goto again;
47903f157a2fSChris Mason 			} else {
47913f157a2fSChris Mason 				goto out;
47923f157a2fSChris Mason 			}
47933f157a2fSChris Mason 		}
47943f157a2fSChris Mason 		/* save our key for returning back */
47953f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
47963f157a2fSChris Mason 		path->slots[level] = slot;
47973f157a2fSChris Mason 		if (level == path->lowest_level) {
47983f157a2fSChris Mason 			ret = 0;
47993f157a2fSChris Mason 			goto out;
48003f157a2fSChris Mason 		}
48014b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4802fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4803fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4804fb770ae4SLiu Bo 			goto out;
4805fb770ae4SLiu Bo 		}
48063f157a2fSChris Mason 
4807bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4808b4ce94deSChris Mason 
4809bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
48103f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4811f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
48123f157a2fSChris Mason 	}
48133f157a2fSChris Mason out:
4814f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4815f98de9b9SFilipe Manana 	if (ret == 0) {
4816f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4817f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4818f98de9b9SFilipe Manana 	}
48193f157a2fSChris Mason 	return ret;
48203f157a2fSChris Mason }
48213f157a2fSChris Mason 
48223f157a2fSChris Mason /*
48233f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
48243f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4825de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
48263f157a2fSChris Mason  *
48273f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
48283f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
48293f157a2fSChris Mason  *
48303f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
48313f157a2fSChris Mason  * calling this function.
48323f157a2fSChris Mason  */
4833e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4834de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4835e7a84565SChris Mason {
4836e7a84565SChris Mason 	int slot;
4837e7a84565SChris Mason 	struct extent_buffer *c;
4838e7a84565SChris Mason 
48396a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4840e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4841e7a84565SChris Mason 		if (!path->nodes[level])
4842e7a84565SChris Mason 			return 1;
4843e7a84565SChris Mason 
4844e7a84565SChris Mason 		slot = path->slots[level] + 1;
4845e7a84565SChris Mason 		c = path->nodes[level];
48463f157a2fSChris Mason next:
4847e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
484833c66f43SYan Zheng 			int ret;
484933c66f43SYan Zheng 			int orig_lowest;
485033c66f43SYan Zheng 			struct btrfs_key cur_key;
485133c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
485233c66f43SYan Zheng 			    !path->nodes[level + 1])
4853e7a84565SChris Mason 				return 1;
485433c66f43SYan Zheng 
48556a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
485633c66f43SYan Zheng 				level++;
4857e7a84565SChris Mason 				continue;
4858e7a84565SChris Mason 			}
485933c66f43SYan Zheng 
486033c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
486133c66f43SYan Zheng 			if (level == 0)
486233c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
486333c66f43SYan Zheng 			else
486433c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
486533c66f43SYan Zheng 
486633c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4867b3b4aa74SDavid Sterba 			btrfs_release_path(path);
486833c66f43SYan Zheng 			path->lowest_level = level;
486933c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
487033c66f43SYan Zheng 						0, 0);
487133c66f43SYan Zheng 			path->lowest_level = orig_lowest;
487233c66f43SYan Zheng 			if (ret < 0)
487333c66f43SYan Zheng 				return ret;
487433c66f43SYan Zheng 
487533c66f43SYan Zheng 			c = path->nodes[level];
487633c66f43SYan Zheng 			slot = path->slots[level];
487733c66f43SYan Zheng 			if (ret == 0)
487833c66f43SYan Zheng 				slot++;
487933c66f43SYan Zheng 			goto next;
488033c66f43SYan Zheng 		}
488133c66f43SYan Zheng 
4882e7a84565SChris Mason 		if (level == 0)
4883e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
48843f157a2fSChris Mason 		else {
48853f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
48863f157a2fSChris Mason 
48873f157a2fSChris Mason 			if (gen < min_trans) {
48883f157a2fSChris Mason 				slot++;
48893f157a2fSChris Mason 				goto next;
48903f157a2fSChris Mason 			}
4891e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
48923f157a2fSChris Mason 		}
4893e7a84565SChris Mason 		return 0;
4894e7a84565SChris Mason 	}
4895e7a84565SChris Mason 	return 1;
4896e7a84565SChris Mason }
4897e7a84565SChris Mason 
48983d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
48993d7806ecSJan Schmidt 			u64 time_seq)
49003d7806ecSJan Schmidt {
4901d97e63b6SChris Mason 	int slot;
49028e73f275SChris Mason 	int level;
49035f39d397SChris Mason 	struct extent_buffer *c;
49048e73f275SChris Mason 	struct extent_buffer *next;
4905d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4906925baeddSChris Mason 	struct btrfs_key key;
4907d96b3424SFilipe Manana 	bool need_commit_sem = false;
4908925baeddSChris Mason 	u32 nritems;
4909925baeddSChris Mason 	int ret;
49100e46318dSJosef Bacik 	int i;
4911925baeddSChris Mason 
4912bdcdd86cSFilipe Manana 	/*
4913bdcdd86cSFilipe Manana 	 * The nowait semantics are used only for write paths, where we don't
4914bdcdd86cSFilipe Manana 	 * use the tree mod log and sequence numbers.
4915bdcdd86cSFilipe Manana 	 */
4916bdcdd86cSFilipe Manana 	if (time_seq)
4917c922b016SStefan Roesch 		ASSERT(!path->nowait);
4918c922b016SStefan Roesch 
4919925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4920d397712bSChris Mason 	if (nritems == 0)
4921925baeddSChris Mason 		return 1;
4922925baeddSChris Mason 
49238e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
49248e73f275SChris Mason again:
49258e73f275SChris Mason 	level = 1;
49268e73f275SChris Mason 	next = NULL;
4927b3b4aa74SDavid Sterba 	btrfs_release_path(path);
49288e73f275SChris Mason 
4929a2135011SChris Mason 	path->keep_locks = 1;
49308e73f275SChris Mason 
4931d96b3424SFilipe Manana 	if (time_seq) {
49323d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4933d96b3424SFilipe Manana 	} else {
4934d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4935d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4936d96b3424SFilipe Manana 			need_commit_sem = true;
4937bdcdd86cSFilipe Manana 			if (path->nowait) {
4938bdcdd86cSFilipe Manana 				if (!down_read_trylock(&fs_info->commit_root_sem)) {
4939bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4940bdcdd86cSFilipe Manana 					goto done;
4941bdcdd86cSFilipe Manana 				}
4942bdcdd86cSFilipe Manana 			} else {
4943d96b3424SFilipe Manana 				down_read(&fs_info->commit_root_sem);
4944d96b3424SFilipe Manana 			}
4945bdcdd86cSFilipe Manana 		}
4946925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4947d96b3424SFilipe Manana 	}
4948925baeddSChris Mason 	path->keep_locks = 0;
4949925baeddSChris Mason 
4950925baeddSChris Mason 	if (ret < 0)
4951d96b3424SFilipe Manana 		goto done;
4952925baeddSChris Mason 
4953a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4954168fd7d2SChris Mason 	/*
4955168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4956168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4957168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4958168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4959168fd7d2SChris Mason 	 */
4960a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4961e457afecSYan Zheng 		if (ret == 0)
4962168fd7d2SChris Mason 			path->slots[0]++;
49638e73f275SChris Mason 		ret = 0;
4964925baeddSChris Mason 		goto done;
4965925baeddSChris Mason 	}
49660b43e04fSLiu Bo 	/*
49670b43e04fSLiu Bo 	 * So the above check misses one case:
49680b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
49690b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
49700b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
49710b43e04fSLiu Bo 	 *
49720b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
49730b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
49740b43e04fSLiu Bo 	 *
49750b43e04fSLiu Bo 	 * And a bit more explanation about this check,
49760b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
49770b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
49780b43e04fSLiu Bo 	 * bigger one.
49790b43e04fSLiu Bo 	 */
49800b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
49810b43e04fSLiu Bo 		ret = 0;
49820b43e04fSLiu Bo 		goto done;
49830b43e04fSLiu Bo 	}
4984d97e63b6SChris Mason 
4985234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
49868e73f275SChris Mason 		if (!path->nodes[level]) {
49878e73f275SChris Mason 			ret = 1;
49888e73f275SChris Mason 			goto done;
49898e73f275SChris Mason 		}
49905f39d397SChris Mason 
4991d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4992d97e63b6SChris Mason 		c = path->nodes[level];
49935f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4994d97e63b6SChris Mason 			level++;
49958e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
49968e73f275SChris Mason 				ret = 1;
49978e73f275SChris Mason 				goto done;
49988e73f275SChris Mason 			}
4999d97e63b6SChris Mason 			continue;
5000d97e63b6SChris Mason 		}
50015f39d397SChris Mason 
50020e46318dSJosef Bacik 
50030e46318dSJosef Bacik 		/*
50040e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
50050e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
50060e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
50070e46318dSJosef Bacik 		 */
50080e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
50090e46318dSJosef Bacik 			if (path->locks[level]) {
50100e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
50110e46318dSJosef Bacik 				path->locks[i] = 0;
50120e46318dSJosef Bacik 			}
50130e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
50140e46318dSJosef Bacik 			path->nodes[i] = NULL;
5015925baeddSChris Mason 		}
50165f39d397SChris Mason 
50178e73f275SChris Mason 		next = c;
5018d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5019cda79c54SDavid Sterba 					    slot, &key);
5020bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
50218e73f275SChris Mason 			goto again;
50225f39d397SChris Mason 
502376a05b35SChris Mason 		if (ret < 0) {
5024b3b4aa74SDavid Sterba 			btrfs_release_path(path);
502576a05b35SChris Mason 			goto done;
502676a05b35SChris Mason 		}
502776a05b35SChris Mason 
50285cd57b2cSChris Mason 		if (!path->skip_locking) {
5029bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5030bdcdd86cSFilipe Manana 			if (!ret && path->nowait) {
5031bdcdd86cSFilipe Manana 				ret = -EAGAIN;
5032bdcdd86cSFilipe Manana 				goto done;
5033bdcdd86cSFilipe Manana 			}
5034d42244a0SJan Schmidt 			if (!ret && time_seq) {
5035d42244a0SJan Schmidt 				/*
5036d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5037d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5038d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5039d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5040d42244a0SJan Schmidt 				 * on our lock and cycle.
5041d42244a0SJan Schmidt 				 */
5042cf538830SJan Schmidt 				free_extent_buffer(next);
5043d42244a0SJan Schmidt 				btrfs_release_path(path);
5044d42244a0SJan Schmidt 				cond_resched();
5045d42244a0SJan Schmidt 				goto again;
5046d42244a0SJan Schmidt 			}
50470e46318dSJosef Bacik 			if (!ret)
50480e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
5049bd681513SChris Mason 		}
5050d97e63b6SChris Mason 		break;
5051d97e63b6SChris Mason 	}
5052d97e63b6SChris Mason 	path->slots[level] = slot;
5053d97e63b6SChris Mason 	while (1) {
5054d97e63b6SChris Mason 		level--;
5055d97e63b6SChris Mason 		path->nodes[level] = next;
5056d97e63b6SChris Mason 		path->slots[level] = 0;
5057a74a4b97SChris Mason 		if (!path->skip_locking)
5058ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
5059d97e63b6SChris Mason 		if (!level)
5060d97e63b6SChris Mason 			break;
5061b4ce94deSChris Mason 
5062d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5063cda79c54SDavid Sterba 					    0, &key);
5064bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
50658e73f275SChris Mason 			goto again;
50668e73f275SChris Mason 
506776a05b35SChris Mason 		if (ret < 0) {
5068b3b4aa74SDavid Sterba 			btrfs_release_path(path);
506976a05b35SChris Mason 			goto done;
507076a05b35SChris Mason 		}
507176a05b35SChris Mason 
5072bdcdd86cSFilipe Manana 		if (!path->skip_locking) {
5073bdcdd86cSFilipe Manana 			if (path->nowait) {
5074bdcdd86cSFilipe Manana 				if (!btrfs_try_tree_read_lock(next)) {
5075bdcdd86cSFilipe Manana 					ret = -EAGAIN;
5076bdcdd86cSFilipe Manana 					goto done;
5077bdcdd86cSFilipe Manana 				}
5078bdcdd86cSFilipe Manana 			} else {
50790e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
5080d97e63b6SChris Mason 			}
5081bdcdd86cSFilipe Manana 		}
5082bdcdd86cSFilipe Manana 	}
50838e73f275SChris Mason 	ret = 0;
5084925baeddSChris Mason done:
5085f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
5086d96b3424SFilipe Manana 	if (need_commit_sem) {
5087d96b3424SFilipe Manana 		int ret2;
5088d96b3424SFilipe Manana 
5089d96b3424SFilipe Manana 		path->need_commit_sem = 1;
5090d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
5091d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
5092d96b3424SFilipe Manana 		if (ret2)
5093d96b3424SFilipe Manana 			ret = ret2;
5094d96b3424SFilipe Manana 	}
50958e73f275SChris Mason 
50968e73f275SChris Mason 	return ret;
5097d97e63b6SChris Mason }
50980b86a832SChris Mason 
5099890d2b1aSJosef Bacik int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
5100890d2b1aSJosef Bacik {
5101890d2b1aSJosef Bacik 	path->slots[0]++;
5102890d2b1aSJosef Bacik 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
5103890d2b1aSJosef Bacik 		return btrfs_next_old_leaf(root, path, time_seq);
5104890d2b1aSJosef Bacik 	return 0;
5105890d2b1aSJosef Bacik }
5106890d2b1aSJosef Bacik 
51073f157a2fSChris Mason /*
51083f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
51093f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
51103f157a2fSChris Mason  *
51113f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
51123f157a2fSChris Mason  */
51130b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
51140b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
51150b86a832SChris Mason 			int type)
51160b86a832SChris Mason {
51170b86a832SChris Mason 	struct btrfs_key found_key;
51180b86a832SChris Mason 	struct extent_buffer *leaf;
5119e02119d5SChris Mason 	u32 nritems;
51200b86a832SChris Mason 	int ret;
51210b86a832SChris Mason 
51220b86a832SChris Mason 	while (1) {
51230b86a832SChris Mason 		if (path->slots[0] == 0) {
51240b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
51250b86a832SChris Mason 			if (ret != 0)
51260b86a832SChris Mason 				return ret;
51270b86a832SChris Mason 		} else {
51280b86a832SChris Mason 			path->slots[0]--;
51290b86a832SChris Mason 		}
51300b86a832SChris Mason 		leaf = path->nodes[0];
5131e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5132e02119d5SChris Mason 		if (nritems == 0)
5133e02119d5SChris Mason 			return 1;
5134e02119d5SChris Mason 		if (path->slots[0] == nritems)
5135e02119d5SChris Mason 			path->slots[0]--;
5136e02119d5SChris Mason 
51370b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5138e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5139e02119d5SChris Mason 			break;
51400a4eefbbSYan Zheng 		if (found_key.type == type)
51410a4eefbbSYan Zheng 			return 0;
5142e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5143e02119d5SChris Mason 		    found_key.type < type)
5144e02119d5SChris Mason 			break;
51450b86a832SChris Mason 	}
51460b86a832SChris Mason 	return 1;
51470b86a832SChris Mason }
5148ade2e0b3SWang Shilong 
5149ade2e0b3SWang Shilong /*
5150ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5151ade2e0b3SWang Shilong  * min objecitd.
5152ade2e0b3SWang Shilong  *
5153ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5154ade2e0b3SWang Shilong  */
5155ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5156ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5157ade2e0b3SWang Shilong {
5158ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5159ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5160ade2e0b3SWang Shilong 	u32 nritems;
5161ade2e0b3SWang Shilong 	int ret;
5162ade2e0b3SWang Shilong 
5163ade2e0b3SWang Shilong 	while (1) {
5164ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5165ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5166ade2e0b3SWang Shilong 			if (ret != 0)
5167ade2e0b3SWang Shilong 				return ret;
5168ade2e0b3SWang Shilong 		} else {
5169ade2e0b3SWang Shilong 			path->slots[0]--;
5170ade2e0b3SWang Shilong 		}
5171ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5172ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5173ade2e0b3SWang Shilong 		if (nritems == 0)
5174ade2e0b3SWang Shilong 			return 1;
5175ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5176ade2e0b3SWang Shilong 			path->slots[0]--;
5177ade2e0b3SWang Shilong 
5178ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5179ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5180ade2e0b3SWang Shilong 			break;
5181ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5182ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5183ade2e0b3SWang Shilong 			return 0;
5184ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5185ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5186ade2e0b3SWang Shilong 			break;
5187ade2e0b3SWang Shilong 	}
5188ade2e0b3SWang Shilong 	return 1;
5189ade2e0b3SWang Shilong }
5190226463d7SJosef Bacik 
5191226463d7SJosef Bacik int __init btrfs_ctree_init(void)
5192226463d7SJosef Bacik {
5193226463d7SJosef Bacik 	btrfs_path_cachep = kmem_cache_create("btrfs_path",
5194226463d7SJosef Bacik 			sizeof(struct btrfs_path), 0,
5195226463d7SJosef Bacik 			SLAB_MEM_SPREAD, NULL);
5196226463d7SJosef Bacik 	if (!btrfs_path_cachep)
5197226463d7SJosef Bacik 		return -ENOMEM;
5198226463d7SJosef Bacik 	return 0;
5199226463d7SJosef Bacik }
5200226463d7SJosef Bacik 
5201226463d7SJosef Bacik void __cold btrfs_ctree_exit(void)
5202226463d7SJosef Bacik {
5203226463d7SJosef Bacik 	kmem_cache_destroy(btrfs_path_cachep);
5204226463d7SJosef Bacik }
5205