xref: /openbmc/linux/fs/btrfs/ctree.c (revision a4c853af0c511d7e0f7cb306bbc8a4f1dbdb64ca)
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);
40afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
41afe5fea7STsutomu Itoh 		    int level, int slot);
42d97e63b6SChris Mason 
43af024ed2SJohannes Thumshirn static const struct btrfs_csums {
44af024ed2SJohannes Thumshirn 	u16		size;
4559a0fcdbSDavid Sterba 	const char	name[10];
4659a0fcdbSDavid Sterba 	const char	driver[12];
47af024ed2SJohannes Thumshirn } btrfs_csums[] = {
48af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
493951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
503831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
51352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
52352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
53af024ed2SJohannes Thumshirn };
54af024ed2SJohannes Thumshirn 
553a3178c7SJosef Bacik /*
563a3178c7SJosef Bacik  * The leaf data grows from end-to-front in the node.  this returns the address
573a3178c7SJosef Bacik  * of the start of the last item, which is the stop of the leaf data stack.
583a3178c7SJosef Bacik  */
593a3178c7SJosef Bacik static unsigned int leaf_data_end(const struct extent_buffer *leaf)
603a3178c7SJosef Bacik {
613a3178c7SJosef Bacik 	u32 nr = btrfs_header_nritems(leaf);
623a3178c7SJosef Bacik 
633a3178c7SJosef Bacik 	if (nr == 0)
643a3178c7SJosef Bacik 		return BTRFS_LEAF_DATA_SIZE(leaf->fs_info);
653a3178c7SJosef Bacik 	return btrfs_item_offset(leaf, nr - 1);
663a3178c7SJosef Bacik }
673a3178c7SJosef Bacik 
68637e3b48SJosef Bacik /*
69637e3b48SJosef Bacik  * Move data in a @leaf (using memmove, safe for overlapping ranges).
70637e3b48SJosef Bacik  *
71637e3b48SJosef Bacik  * @leaf:	leaf that we're doing a memmove on
72637e3b48SJosef Bacik  * @dst_offset:	item data offset we're moving to
73637e3b48SJosef Bacik  * @src_offset:	item data offset were' moving from
74637e3b48SJosef Bacik  * @len:	length of the data we're moving
75637e3b48SJosef Bacik  *
76637e3b48SJosef Bacik  * Wrapper around memmove_extent_buffer() that takes into account the header on
77637e3b48SJosef Bacik  * the leaf.  The btrfs_item offset's start directly after the header, so we
78637e3b48SJosef Bacik  * have to adjust any offsets to account for the header in the leaf.  This
79637e3b48SJosef Bacik  * handles that math to simplify the callers.
80637e3b48SJosef Bacik  */
81637e3b48SJosef Bacik static inline void memmove_leaf_data(const struct extent_buffer *leaf,
82637e3b48SJosef Bacik 				     unsigned long dst_offset,
83637e3b48SJosef Bacik 				     unsigned long src_offset,
84637e3b48SJosef Bacik 				     unsigned long len)
85637e3b48SJosef Bacik {
868009adf3SJosef Bacik 	memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, 0) + dst_offset,
878009adf3SJosef Bacik 			      btrfs_item_nr_offset(leaf, 0) + src_offset, len);
88637e3b48SJosef Bacik }
89637e3b48SJosef Bacik 
90637e3b48SJosef Bacik /*
91637e3b48SJosef Bacik  * Copy item data from @src into @dst at the given @offset.
92637e3b48SJosef Bacik  *
93637e3b48SJosef Bacik  * @dst:	destination leaf that we're copying into
94637e3b48SJosef Bacik  * @src:	source leaf that we're copying from
95637e3b48SJosef Bacik  * @dst_offset:	item data offset we're copying to
96637e3b48SJosef Bacik  * @src_offset:	item data offset were' copying from
97637e3b48SJosef Bacik  * @len:	length of the data we're copying
98637e3b48SJosef Bacik  *
99637e3b48SJosef Bacik  * Wrapper around copy_extent_buffer() that takes into account the header on
100637e3b48SJosef Bacik  * the leaf.  The btrfs_item offset's start directly after the header, so we
101637e3b48SJosef Bacik  * have to adjust any offsets to account for the header in the leaf.  This
102637e3b48SJosef Bacik  * handles that math to simplify the callers.
103637e3b48SJosef Bacik  */
104637e3b48SJosef Bacik static inline void copy_leaf_data(const struct extent_buffer *dst,
105637e3b48SJosef Bacik 				  const struct extent_buffer *src,
106637e3b48SJosef Bacik 				  unsigned long dst_offset,
107637e3b48SJosef Bacik 				  unsigned long src_offset, unsigned long len)
108637e3b48SJosef Bacik {
1098009adf3SJosef Bacik 	copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, 0) + dst_offset,
1108009adf3SJosef Bacik 			   btrfs_item_nr_offset(src, 0) + src_offset, len);
111637e3b48SJosef Bacik }
112637e3b48SJosef Bacik 
113637e3b48SJosef Bacik /*
114637e3b48SJosef Bacik  * Move items in a @leaf (using memmove).
115637e3b48SJosef Bacik  *
116637e3b48SJosef Bacik  * @dst:	destination leaf for the items
117637e3b48SJosef Bacik  * @dst_item:	the item nr we're copying into
118637e3b48SJosef Bacik  * @src_item:	the item nr we're copying from
119637e3b48SJosef Bacik  * @nr_items:	the number of items to copy
120637e3b48SJosef Bacik  *
121637e3b48SJosef Bacik  * Wrapper around memmove_extent_buffer() that does the math to get the
122637e3b48SJosef Bacik  * appropriate offsets into the leaf from the item numbers.
123637e3b48SJosef Bacik  */
124637e3b48SJosef Bacik static inline void memmove_leaf_items(const struct extent_buffer *leaf,
125637e3b48SJosef Bacik 				      int dst_item, int src_item, int nr_items)
126637e3b48SJosef Bacik {
127637e3b48SJosef Bacik 	memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, dst_item),
128637e3b48SJosef Bacik 			      btrfs_item_nr_offset(leaf, src_item),
129637e3b48SJosef Bacik 			      nr_items * sizeof(struct btrfs_item));
130637e3b48SJosef Bacik }
131637e3b48SJosef Bacik 
132637e3b48SJosef Bacik /*
133637e3b48SJosef Bacik  * Copy items from @src into @dst at the given @offset.
134637e3b48SJosef Bacik  *
135637e3b48SJosef Bacik  * @dst:	destination leaf for the items
136637e3b48SJosef Bacik  * @src:	source leaf for the items
137637e3b48SJosef Bacik  * @dst_item:	the item nr we're copying into
138637e3b48SJosef Bacik  * @src_item:	the item nr we're copying from
139637e3b48SJosef Bacik  * @nr_items:	the number of items to copy
140637e3b48SJosef Bacik  *
141637e3b48SJosef Bacik  * Wrapper around copy_extent_buffer() that does the math to get the
142637e3b48SJosef Bacik  * appropriate offsets into the leaf from the item numbers.
143637e3b48SJosef Bacik  */
144637e3b48SJosef Bacik static inline void copy_leaf_items(const struct extent_buffer *dst,
145637e3b48SJosef Bacik 				   const struct extent_buffer *src,
146637e3b48SJosef Bacik 				   int dst_item, int src_item, int nr_items)
147637e3b48SJosef Bacik {
148637e3b48SJosef Bacik 	copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, dst_item),
149637e3b48SJosef Bacik 			      btrfs_item_nr_offset(src, src_item),
150637e3b48SJosef Bacik 			      nr_items * sizeof(struct btrfs_item));
151637e3b48SJosef Bacik }
152637e3b48SJosef Bacik 
153af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
154af024ed2SJohannes Thumshirn {
155af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
156af024ed2SJohannes Thumshirn 	/*
157af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
158af024ed2SJohannes Thumshirn 	 */
159af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
160af024ed2SJohannes Thumshirn }
161af024ed2SJohannes Thumshirn 
162af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
163af024ed2SJohannes Thumshirn {
164af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
165af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
166af024ed2SJohannes Thumshirn }
167af024ed2SJohannes Thumshirn 
168b4e967beSDavid Sterba /*
169b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
170b4e967beSDavid Sterba  * name
171b4e967beSDavid Sterba  */
172b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
173b4e967beSDavid Sterba {
174b4e967beSDavid Sterba 	/* csum type is validated at mount time */
17559a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
17659a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
177b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
178b4e967beSDavid Sterba }
179b4e967beSDavid Sterba 
180604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
181f7cea56cSDavid Sterba {
182f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
183f7cea56cSDavid Sterba }
184f7cea56cSDavid Sterba 
1852c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
1862c90e5d6SChris Mason {
187*a4c853afSChenXiaoSong 	might_sleep();
188*a4c853afSChenXiaoSong 
189e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
1902c90e5d6SChris Mason }
1912c90e5d6SChris Mason 
192d352ac68SChris Mason /* this also releases the path */
1932c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1942c90e5d6SChris Mason {
195ff175d57SJesper Juhl 	if (!p)
196ff175d57SJesper Juhl 		return;
197b3b4aa74SDavid Sterba 	btrfs_release_path(p);
1982c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
1992c90e5d6SChris Mason }
2002c90e5d6SChris Mason 
201d352ac68SChris Mason /*
202d352ac68SChris Mason  * path release drops references on the extent buffers in the path
203d352ac68SChris Mason  * and it drops any locks held by this path
204d352ac68SChris Mason  *
205d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
206d352ac68SChris Mason  */
207b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
208eb60ceacSChris Mason {
209eb60ceacSChris Mason 	int i;
210a2135011SChris Mason 
211234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
2123f157a2fSChris Mason 		p->slots[i] = 0;
213eb60ceacSChris Mason 		if (!p->nodes[i])
214925baeddSChris Mason 			continue;
215925baeddSChris Mason 		if (p->locks[i]) {
216bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
217925baeddSChris Mason 			p->locks[i] = 0;
218925baeddSChris Mason 		}
2195f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
2203f157a2fSChris Mason 		p->nodes[i] = NULL;
221eb60ceacSChris Mason 	}
222eb60ceacSChris Mason }
223eb60ceacSChris Mason 
224d352ac68SChris Mason /*
2258bb808c6SDavid Sterba  * We want the transaction abort to print stack trace only for errors where the
2268bb808c6SDavid Sterba  * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
2278bb808c6SDavid Sterba  * caused by external factors.
2288bb808c6SDavid Sterba  */
2298bb808c6SDavid Sterba bool __cold abort_should_print_stack(int errno)
2308bb808c6SDavid Sterba {
2318bb808c6SDavid Sterba 	switch (errno) {
2328bb808c6SDavid Sterba 	case -EIO:
2338bb808c6SDavid Sterba 	case -EROFS:
2348bb808c6SDavid Sterba 	case -ENOMEM:
2358bb808c6SDavid Sterba 		return false;
2368bb808c6SDavid Sterba 	}
2378bb808c6SDavid Sterba 	return true;
2388bb808c6SDavid Sterba }
2398bb808c6SDavid Sterba 
2408bb808c6SDavid Sterba /*
241d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
242d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
243d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
244d352ac68SChris Mason  * looping required.
245d352ac68SChris Mason  *
246d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
247d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
248d352ac68SChris Mason  * at any time because there are no locks held.
249d352ac68SChris Mason  */
250925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
251925baeddSChris Mason {
252925baeddSChris Mason 	struct extent_buffer *eb;
253240f62c8SChris Mason 
2543083ee2eSJosef Bacik 	while (1) {
255240f62c8SChris Mason 		rcu_read_lock();
256240f62c8SChris Mason 		eb = rcu_dereference(root->node);
2573083ee2eSJosef Bacik 
2583083ee2eSJosef Bacik 		/*
2593083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
26001327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
2613083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
2623083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
2633083ee2eSJosef Bacik 		 */
2643083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
265240f62c8SChris Mason 			rcu_read_unlock();
2663083ee2eSJosef Bacik 			break;
2673083ee2eSJosef Bacik 		}
2683083ee2eSJosef Bacik 		rcu_read_unlock();
2693083ee2eSJosef Bacik 		synchronize_rcu();
2703083ee2eSJosef Bacik 	}
271925baeddSChris Mason 	return eb;
272925baeddSChris Mason }
273925baeddSChris Mason 
27492a7cc42SQu Wenruo /*
27592a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
27692a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
27792a7cc42SQu Wenruo  * sure they get properly updated on disk.
278d352ac68SChris Mason  */
2790b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
2800b86a832SChris Mason {
2810b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2820b246afaSJeff Mahoney 
283e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
284e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
285e7070be1SJosef Bacik 		return;
286e7070be1SJosef Bacik 
2870b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
288e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
289e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
2904fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
291e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
2920b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
293e7070be1SJosef Bacik 		else
294e7070be1SJosef Bacik 			list_move(&root->dirty_list,
2950b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
2960b86a832SChris Mason 	}
2970b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2980b86a832SChris Mason }
2990b86a832SChris Mason 
300d352ac68SChris Mason /*
301d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
302d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
303d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
304d352ac68SChris Mason  */
305be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
306be20aa9dSChris Mason 		      struct btrfs_root *root,
307be20aa9dSChris Mason 		      struct extent_buffer *buf,
308be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
309be20aa9dSChris Mason {
3100b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
311be20aa9dSChris Mason 	struct extent_buffer *cow;
312be20aa9dSChris Mason 	int ret = 0;
313be20aa9dSChris Mason 	int level;
3145d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
315be20aa9dSChris Mason 
31692a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
3170b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
31892a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
31927cdeb70SMiao Xie 		trans->transid != root->last_trans);
320be20aa9dSChris Mason 
321be20aa9dSChris Mason 	level = btrfs_header_level(buf);
3225d4f98a2SYan Zheng 	if (level == 0)
3235d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
3245d4f98a2SYan Zheng 	else
3255d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
32631840ae1SZheng Yan 
3274d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
328cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
329cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
3305d4f98a2SYan Zheng 	if (IS_ERR(cow))
331be20aa9dSChris Mason 		return PTR_ERR(cow);
332be20aa9dSChris Mason 
33358e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
334be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
335be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
3365d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
3375d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
3385d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
3395d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
3405d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
3415d4f98a2SYan Zheng 	else
342be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
343be20aa9dSChris Mason 
344de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
3452b82032cSYan Zheng 
346be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
3475d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
348e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
3495d4f98a2SYan Zheng 	else
350e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
351867ed321SJosef Bacik 	if (ret) {
35272c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
35372c9925fSFilipe Manana 		free_extent_buffer(cow);
354867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
355be20aa9dSChris Mason 		return ret;
356867ed321SJosef Bacik 	}
357be20aa9dSChris Mason 
358be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
359be20aa9dSChris Mason 	*cow_ret = cow;
360be20aa9dSChris Mason 	return 0;
361be20aa9dSChris Mason }
362be20aa9dSChris Mason 
363d352ac68SChris Mason /*
3645d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
3655d4f98a2SYan Zheng  */
3665d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
3675d4f98a2SYan Zheng 			      struct extent_buffer *buf)
3685d4f98a2SYan Zheng {
3695d4f98a2SYan Zheng 	/*
37092a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
37192a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
37292a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
3735d4f98a2SYan Zheng 	 */
37492a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
3755d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
3765d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
3775d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
3785d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
3795d4f98a2SYan Zheng 		return 1;
380a79865c6SNikolay Borisov 
3815d4f98a2SYan Zheng 	return 0;
3825d4f98a2SYan Zheng }
3835d4f98a2SYan Zheng 
3845d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
3855d4f98a2SYan Zheng 				       struct btrfs_root *root,
3865d4f98a2SYan Zheng 				       struct extent_buffer *buf,
387f0486c68SYan, Zheng 				       struct extent_buffer *cow,
388f0486c68SYan, Zheng 				       int *last_ref)
3895d4f98a2SYan Zheng {
3900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3915d4f98a2SYan Zheng 	u64 refs;
3925d4f98a2SYan Zheng 	u64 owner;
3935d4f98a2SYan Zheng 	u64 flags;
3945d4f98a2SYan Zheng 	u64 new_flags = 0;
3955d4f98a2SYan Zheng 	int ret;
3965d4f98a2SYan Zheng 
3975d4f98a2SYan Zheng 	/*
3985d4f98a2SYan Zheng 	 * Backrefs update rules:
3995d4f98a2SYan Zheng 	 *
4005d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
4015d4f98a2SYan Zheng 	 * allocated by tree relocation.
4025d4f98a2SYan Zheng 	 *
4035d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
4045d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
4055d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
4065d4f98a2SYan Zheng 	 *
4075d4f98a2SYan Zheng 	 * If a tree block is been relocating
4085d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
4095d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
4105d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
4115d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
4125d4f98a2SYan Zheng 	 */
4135d4f98a2SYan Zheng 
4145d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
4152ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
4163173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
4173173a18fSJosef Bacik 					       &refs, &flags);
418be1a5564SMark Fasheh 		if (ret)
419be1a5564SMark Fasheh 			return ret;
420e5df9573SMark Fasheh 		if (refs == 0) {
421e5df9573SMark Fasheh 			ret = -EROFS;
4220b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
423e5df9573SMark Fasheh 			return ret;
424e5df9573SMark Fasheh 		}
4255d4f98a2SYan Zheng 	} else {
4265d4f98a2SYan Zheng 		refs = 1;
4275d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4285d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4295d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
4305d4f98a2SYan Zheng 		else
4315d4f98a2SYan Zheng 			flags = 0;
4325d4f98a2SYan Zheng 	}
4335d4f98a2SYan Zheng 
4345d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
4355d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
4365d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
4375d4f98a2SYan Zheng 
4385d4f98a2SYan Zheng 	if (refs > 1) {
4395d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
4405d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
4415d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
442e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
443692826b2SJeff Mahoney 			if (ret)
444692826b2SJeff Mahoney 				return ret;
4455d4f98a2SYan Zheng 
4465d4f98a2SYan Zheng 			if (root->root_key.objectid ==
4475d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
448e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
449692826b2SJeff Mahoney 				if (ret)
450692826b2SJeff Mahoney 					return ret;
451e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
452692826b2SJeff Mahoney 				if (ret)
453692826b2SJeff Mahoney 					return ret;
4545d4f98a2SYan Zheng 			}
4555d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4565d4f98a2SYan Zheng 		} else {
4575d4f98a2SYan Zheng 
4585d4f98a2SYan Zheng 			if (root->root_key.objectid ==
4595d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
460e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
4615d4f98a2SYan Zheng 			else
462e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
463692826b2SJeff Mahoney 			if (ret)
464692826b2SJeff Mahoney 				return ret;
4655d4f98a2SYan Zheng 		}
4665d4f98a2SYan Zheng 		if (new_flags != 0) {
467b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
468b1c79e09SJosef Bacik 
46942c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
4702fe6a5a1SDavid Sterba 							  new_flags, level);
471be1a5564SMark Fasheh 			if (ret)
472be1a5564SMark Fasheh 				return ret;
4735d4f98a2SYan Zheng 		}
4745d4f98a2SYan Zheng 	} else {
4755d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
4765d4f98a2SYan Zheng 			if (root->root_key.objectid ==
4775d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
478e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
4795d4f98a2SYan Zheng 			else
480e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
481692826b2SJeff Mahoney 			if (ret)
482692826b2SJeff Mahoney 				return ret;
483e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
484692826b2SJeff Mahoney 			if (ret)
485692826b2SJeff Mahoney 				return ret;
4865d4f98a2SYan Zheng 		}
4876a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
488f0486c68SYan, Zheng 		*last_ref = 1;
4895d4f98a2SYan Zheng 	}
4905d4f98a2SYan Zheng 	return 0;
4915d4f98a2SYan Zheng }
4925d4f98a2SYan Zheng 
4935d4f98a2SYan Zheng /*
494d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
495d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
496d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
497d397712bSChris Mason  * dirty again.
498d352ac68SChris Mason  *
499d352ac68SChris Mason  * search_start -- an allocation hint for the new block
500d352ac68SChris Mason  *
501d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
502d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
503d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
504d352ac68SChris Mason  */
505d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
5065f39d397SChris Mason 			     struct btrfs_root *root,
5075f39d397SChris Mason 			     struct extent_buffer *buf,
5085f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
5095f39d397SChris Mason 			     struct extent_buffer **cow_ret,
5109631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
5119631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
5126702ed49SChris Mason {
5130b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5145d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
5155f39d397SChris Mason 	struct extent_buffer *cow;
516be1a5564SMark Fasheh 	int level, ret;
517f0486c68SYan, Zheng 	int last_ref = 0;
518925baeddSChris Mason 	int unlock_orig = 0;
5190f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
5206702ed49SChris Mason 
521925baeddSChris Mason 	if (*cow_ret == buf)
522925baeddSChris Mason 		unlock_orig = 1;
523925baeddSChris Mason 
52449d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
525925baeddSChris Mason 
52692a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
5270b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
52892a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
52927cdeb70SMiao Xie 		trans->transid != root->last_trans);
5305f39d397SChris Mason 
5317bb86316SChris Mason 	level = btrfs_header_level(buf);
53231840ae1SZheng Yan 
5335d4f98a2SYan Zheng 	if (level == 0)
5345d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
5355d4f98a2SYan Zheng 	else
5365d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
5375d4f98a2SYan Zheng 
5380f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
5395d4f98a2SYan Zheng 		parent_start = parent->start;
5405d4f98a2SYan Zheng 
54179bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
54279bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
54379bd3712SFilipe Manana 				     search_start, empty_size, nest);
5446702ed49SChris Mason 	if (IS_ERR(cow))
5456702ed49SChris Mason 		return PTR_ERR(cow);
5466702ed49SChris Mason 
547b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
548b4ce94deSChris Mason 
54958e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
550db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
5515f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
5525d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
5535d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
5545d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
5555d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
5565d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
5575d4f98a2SYan Zheng 	else
5585f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
5596702ed49SChris Mason 
560de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
5612b82032cSYan Zheng 
562be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
563b68dc2a9SMark Fasheh 	if (ret) {
564572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
565572c83acSJosef Bacik 		free_extent_buffer(cow);
56666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
567b68dc2a9SMark Fasheh 		return ret;
568b68dc2a9SMark Fasheh 	}
5691a40e23bSZheng Yan 
57092a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
57183d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
57293314e3bSZhaolei 		if (ret) {
573572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
574572c83acSJosef Bacik 			free_extent_buffer(cow);
57566642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
57683d4cfd4SJosef Bacik 			return ret;
57783d4cfd4SJosef Bacik 		}
57893314e3bSZhaolei 	}
5793fd0a558SYan, Zheng 
5806702ed49SChris Mason 	if (buf == root->node) {
581925baeddSChris Mason 		WARN_ON(parent && parent != buf);
5825d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
5835d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
5845d4f98a2SYan Zheng 			parent_start = buf->start;
585925baeddSChris Mason 
58667439dadSDavid Sterba 		atomic_inc(&cow->refs);
587406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
588d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
589240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
590925baeddSChris Mason 
5917a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
5927a163608SFilipe Manana 				      parent_start, last_ref);
5935f39d397SChris Mason 		free_extent_buffer(buf);
5940b86a832SChris Mason 		add_root_to_dirty_list(root);
5956702ed49SChris Mason 	} else {
5965d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
597f3a84ccdSFilipe Manana 		btrfs_tree_mod_log_insert_key(parent, parent_slot,
59833cff222SFilipe Manana 					      BTRFS_MOD_LOG_KEY_REPLACE);
5995f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
600db94535dSChris Mason 					cow->start);
60174493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
60274493f7aSChris Mason 					      trans->transid);
6036702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
6045de865eeSFilipe David Borba Manana 		if (last_ref) {
605f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
6065de865eeSFilipe David Borba Manana 			if (ret) {
607572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
608572c83acSJosef Bacik 				free_extent_buffer(cow);
60966642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
6105de865eeSFilipe David Borba Manana 				return ret;
6115de865eeSFilipe David Borba Manana 			}
6125de865eeSFilipe David Borba Manana 		}
6137a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
6147a163608SFilipe Manana 				      parent_start, last_ref);
6156702ed49SChris Mason 	}
616925baeddSChris Mason 	if (unlock_orig)
617925baeddSChris Mason 		btrfs_tree_unlock(buf);
6183083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
6196702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
6206702ed49SChris Mason 	*cow_ret = cow;
6216702ed49SChris Mason 	return 0;
6226702ed49SChris Mason }
6236702ed49SChris Mason 
6245d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
6255d4f98a2SYan Zheng 				   struct btrfs_root *root,
6265d4f98a2SYan Zheng 				   struct extent_buffer *buf)
6275d4f98a2SYan Zheng {
628f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
629faa2dbf0SJosef Bacik 		return 0;
630fccb84c9SDavid Sterba 
631d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
632d1980131SDavid Sterba 	smp_mb__before_atomic();
633f1ebcc74SLiu Bo 
634f1ebcc74SLiu Bo 	/*
635f1ebcc74SLiu Bo 	 * We do not need to cow a block if
636f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
637f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
638f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
639f1ebcc74SLiu Bo 	 *
640f1ebcc74SLiu Bo 	 * What is forced COW:
64101327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
64252042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
643f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
644f1ebcc74SLiu Bo 	 */
6455d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
6465d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
6475d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
648f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
64927cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
6505d4f98a2SYan Zheng 		return 0;
6515d4f98a2SYan Zheng 	return 1;
6525d4f98a2SYan Zheng }
6535d4f98a2SYan Zheng 
654d352ac68SChris Mason /*
655d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
65601327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
657d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
658d352ac68SChris Mason  */
659d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
6605f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
6615f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
6629631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
6639631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
66402217ed2SChris Mason {
6650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6666702ed49SChris Mason 	u64 search_start;
667f510cfecSChris Mason 	int ret;
668dc17ff8fSChris Mason 
66983354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
67083354f07SJosef Bacik 		btrfs_err(fs_info,
67183354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
67283354f07SJosef Bacik 
6730b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
67431b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
675c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
6760b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
67731b1a2bdSJulia Lawall 
6780b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
67931b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
6800b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
681dc17ff8fSChris Mason 
6825d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
68302217ed2SChris Mason 		*cow_ret = buf;
68402217ed2SChris Mason 		return 0;
68502217ed2SChris Mason 	}
686c487685dSChris Mason 
687ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
688b4ce94deSChris Mason 
689f616f5cdSQu Wenruo 	/*
690f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
691f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
692f616f5cdSQu Wenruo 	 *
693f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
694f616f5cdSQu Wenruo 	 */
695f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
696f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
6979631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
6981abe9b8aSliubo 
6991abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
7001abe9b8aSliubo 
701f510cfecSChris Mason 	return ret;
7022c90e5d6SChris Mason }
703f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
7046702ed49SChris Mason 
705d352ac68SChris Mason /*
706d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
707d352ac68SChris Mason  * node are actually close by
708d352ac68SChris Mason  */
7096b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
7106702ed49SChris Mason {
7116b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
7126702ed49SChris Mason 		return 1;
7136b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
7146702ed49SChris Mason 		return 1;
71502217ed2SChris Mason 	return 0;
71602217ed2SChris Mason }
71702217ed2SChris Mason 
718ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
719ce6ef5abSDavid Sterba 
720ce6ef5abSDavid Sterba /*
721ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
722ce6ef5abSDavid Sterba  * we can avoid the conversion.
723ce6ef5abSDavid Sterba  */
724ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
725ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
726ce6ef5abSDavid Sterba {
727ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
728ce6ef5abSDavid Sterba 
729ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
730ce6ef5abSDavid Sterba }
731ce6ef5abSDavid Sterba 
732ce6ef5abSDavid Sterba #else
733ce6ef5abSDavid Sterba 
734081e9573SChris Mason /*
735081e9573SChris Mason  * compare two keys in a memcmp fashion
736081e9573SChris Mason  */
737310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
738310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
739081e9573SChris Mason {
740081e9573SChris Mason 	struct btrfs_key k1;
741081e9573SChris Mason 
742081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
743081e9573SChris Mason 
74420736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
745081e9573SChris Mason }
746ce6ef5abSDavid Sterba #endif
747081e9573SChris Mason 
748f3465ca4SJosef Bacik /*
749f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
750f3465ca4SJosef Bacik  */
751e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
752f3465ca4SJosef Bacik {
753f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
754f3465ca4SJosef Bacik 		return 1;
755f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
756f3465ca4SJosef Bacik 		return -1;
757f3465ca4SJosef Bacik 	if (k1->type > k2->type)
758f3465ca4SJosef Bacik 		return 1;
759f3465ca4SJosef Bacik 	if (k1->type < k2->type)
760f3465ca4SJosef Bacik 		return -1;
761f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
762f3465ca4SJosef Bacik 		return 1;
763f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
764f3465ca4SJosef Bacik 		return -1;
765f3465ca4SJosef Bacik 	return 0;
766f3465ca4SJosef Bacik }
767081e9573SChris Mason 
768d352ac68SChris Mason /*
769d352ac68SChris Mason  * this is used by the defrag code to go through all the
770d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
771d352ac68SChris Mason  * disk order is close to key order
772d352ac68SChris Mason  */
7736702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
7745f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
775de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
776a6b6e75eSChris Mason 		       struct btrfs_key *progress)
7776702ed49SChris Mason {
7780b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
7796b80053dSChris Mason 	struct extent_buffer *cur;
7806702ed49SChris Mason 	u64 blocknr;
781e9d0b13bSChris Mason 	u64 search_start = *last_ret;
782e9d0b13bSChris Mason 	u64 last_block = 0;
7836702ed49SChris Mason 	u64 other;
7846702ed49SChris Mason 	u32 parent_nritems;
7856702ed49SChris Mason 	int end_slot;
7866702ed49SChris Mason 	int i;
7876702ed49SChris Mason 	int err = 0;
7886b80053dSChris Mason 	u32 blocksize;
789081e9573SChris Mason 	int progress_passed = 0;
790081e9573SChris Mason 	struct btrfs_disk_key disk_key;
7916702ed49SChris Mason 
7920b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
7930b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
79486479a04SChris Mason 
7956b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
7960b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
7975dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
7986702ed49SChris Mason 
7995dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
8006702ed49SChris Mason 		return 0;
8016702ed49SChris Mason 
8025dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
8036702ed49SChris Mason 		int close = 1;
804a6b6e75eSChris Mason 
805081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
806081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
807081e9573SChris Mason 			continue;
808081e9573SChris Mason 
809081e9573SChris Mason 		progress_passed = 1;
8106b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
811e9d0b13bSChris Mason 		if (last_block == 0)
812e9d0b13bSChris Mason 			last_block = blocknr;
8135708b959SChris Mason 
8146702ed49SChris Mason 		if (i > 0) {
8156b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
8166b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
8176702ed49SChris Mason 		}
8185dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
8196b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
8206b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
8216702ed49SChris Mason 		}
822e9d0b13bSChris Mason 		if (close) {
823e9d0b13bSChris Mason 			last_block = blocknr;
8246702ed49SChris Mason 			continue;
825e9d0b13bSChris Mason 		}
8266702ed49SChris Mason 
827206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
828206983b7SJosef Bacik 		if (IS_ERR(cur))
82964c043deSLiu Bo 			return PTR_ERR(cur);
830e9d0b13bSChris Mason 		if (search_start == 0)
8316b80053dSChris Mason 			search_start = last_block;
832e9d0b13bSChris Mason 
833e7a84565SChris Mason 		btrfs_tree_lock(cur);
8346b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
835e7a84565SChris Mason 					&cur, search_start,
8366b80053dSChris Mason 					min(16 * blocksize,
8379631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
8389631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
839252c38f0SYan 		if (err) {
840e7a84565SChris Mason 			btrfs_tree_unlock(cur);
8416b80053dSChris Mason 			free_extent_buffer(cur);
8426702ed49SChris Mason 			break;
843252c38f0SYan 		}
844e7a84565SChris Mason 		search_start = cur->start;
845e7a84565SChris Mason 		last_block = cur->start;
846f2183bdeSChris Mason 		*last_ret = search_start;
847e7a84565SChris Mason 		btrfs_tree_unlock(cur);
848e7a84565SChris Mason 		free_extent_buffer(cur);
8496702ed49SChris Mason 	}
8506702ed49SChris Mason 	return err;
8516702ed49SChris Mason }
8526702ed49SChris Mason 
85374123bd7SChris Mason /*
854fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
8555f39d397SChris Mason  *
856fb81212cSFilipe Manana  * The lower boundary for the search is specified by the slot number @low. Use a
857fb81212cSFilipe Manana  * value of 0 to search over the whole extent buffer.
85874123bd7SChris Mason  *
859fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
860fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
861fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
862fb81212cSFilipe Manana  *
863fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
864fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
86574123bd7SChris Mason  */
866fb81212cSFilipe Manana static noinline int generic_bin_search(struct extent_buffer *eb, int low,
86767d5e289SMarcos Paulo de Souza 				       const struct btrfs_key *key, int *slot)
868be0e5c09SChris Mason {
869fb81212cSFilipe Manana 	unsigned long p;
870fb81212cSFilipe Manana 	int item_size;
87167d5e289SMarcos Paulo de Souza 	int high = btrfs_header_nritems(eb);
872be0e5c09SChris Mason 	int ret;
8735cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
874be0e5c09SChris Mason 
8755e24e9afSLiu Bo 	if (low > high) {
8765e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
8775e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
8785e24e9afSLiu Bo 			  __func__, low, high, eb->start,
8795e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
8805e24e9afSLiu Bo 		return -EINVAL;
8815e24e9afSLiu Bo 	}
8825e24e9afSLiu Bo 
883fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
884fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
885fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
886fb81212cSFilipe Manana 	} else {
887fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
888fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
889fb81212cSFilipe Manana 	}
890fb81212cSFilipe Manana 
891be0e5c09SChris Mason 	while (low < high) {
8925cd17f34SDavid Sterba 		unsigned long oip;
8935cd17f34SDavid Sterba 		unsigned long offset;
8945cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
8955cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
8965cd17f34SDavid Sterba 		int mid;
8975cd17f34SDavid Sterba 
898be0e5c09SChris Mason 		mid = (low + high) / 2;
8995f39d397SChris Mason 		offset = p + mid * item_size;
9005cd17f34SDavid Sterba 		oip = offset_in_page(offset);
9015f39d397SChris Mason 
9025cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
903884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
9045cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
905934d375bSChris Mason 
906884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
9075cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
9085cd17f34SDavid Sterba 		} else {
9095cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
9105f39d397SChris Mason 			tmp = &unaligned;
911479965d6SChris Mason 		}
912479965d6SChris Mason 
913be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
914be0e5c09SChris Mason 
915be0e5c09SChris Mason 		if (ret < 0)
916be0e5c09SChris Mason 			low = mid + 1;
917be0e5c09SChris Mason 		else if (ret > 0)
918be0e5c09SChris Mason 			high = mid;
919be0e5c09SChris Mason 		else {
920be0e5c09SChris Mason 			*slot = mid;
921be0e5c09SChris Mason 			return 0;
922be0e5c09SChris Mason 		}
923be0e5c09SChris Mason 	}
924be0e5c09SChris Mason 	*slot = low;
925be0e5c09SChris Mason 	return 1;
926be0e5c09SChris Mason }
927be0e5c09SChris Mason 
92897571fd0SChris Mason /*
929fb81212cSFilipe Manana  * Simple binary search on an extent buffer. Works for both leaves and nodes, and
930fb81212cSFilipe Manana  * always searches over the whole range of keys (slot 0 to slot 'nritems - 1').
93197571fd0SChris Mason  */
932a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
933e3b83361SQu Wenruo 		     int *slot)
934be0e5c09SChris Mason {
935fb81212cSFilipe Manana 	return generic_bin_search(eb, 0, key, slot);
936be0e5c09SChris Mason }
937be0e5c09SChris Mason 
938f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
939f0486c68SYan, Zheng {
940f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
941f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
942f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
943f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
944f0486c68SYan, Zheng }
945f0486c68SYan, Zheng 
946f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
947f0486c68SYan, Zheng {
948f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
949f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
950f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
951f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
952f0486c68SYan, Zheng }
953f0486c68SYan, Zheng 
954d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
955d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
956d352ac68SChris Mason  */
9574b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
9584b231ae4SDavid Sterba 					   int slot)
959bb803951SChris Mason {
960ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
961789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
962416bc658SJosef Bacik 	struct extent_buffer *eb;
963416bc658SJosef Bacik 
964fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
965fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
966ca7a79adSChris Mason 
967ca7a79adSChris Mason 	BUG_ON(level == 0);
968ca7a79adSChris Mason 
969789d6a3aSQu Wenruo 	check.level = level - 1;
970789d6a3aSQu Wenruo 	check.transid = btrfs_node_ptr_generation(parent, slot);
971789d6a3aSQu Wenruo 	check.owner_root = btrfs_header_owner(parent);
972789d6a3aSQu Wenruo 	check.has_first_key = true;
973789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(parent, &check.first_key, slot);
974789d6a3aSQu Wenruo 
975d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
976789d6a3aSQu Wenruo 			     &check);
9774eb150d6SQu Wenruo 	if (IS_ERR(eb))
9784eb150d6SQu Wenruo 		return eb;
9794eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
980416bc658SJosef Bacik 		free_extent_buffer(eb);
9814eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
982416bc658SJosef Bacik 	}
983416bc658SJosef Bacik 
984416bc658SJosef Bacik 	return eb;
985bb803951SChris Mason }
986bb803951SChris Mason 
987d352ac68SChris Mason /*
988d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
989d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
990d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
991d352ac68SChris Mason  */
992e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
99398ed5174SChris Mason 			 struct btrfs_root *root,
99498ed5174SChris Mason 			 struct btrfs_path *path, int level)
995bb803951SChris Mason {
9960b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
9975f39d397SChris Mason 	struct extent_buffer *right = NULL;
9985f39d397SChris Mason 	struct extent_buffer *mid;
9995f39d397SChris Mason 	struct extent_buffer *left = NULL;
10005f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1001bb803951SChris Mason 	int ret = 0;
1002bb803951SChris Mason 	int wret;
1003bb803951SChris Mason 	int pslot;
1004bb803951SChris Mason 	int orig_slot = path->slots[level];
100579f95c82SChris Mason 	u64 orig_ptr;
1006bb803951SChris Mason 
100798e6b1ebSLiu Bo 	ASSERT(level > 0);
1008bb803951SChris Mason 
10095f39d397SChris Mason 	mid = path->nodes[level];
1010b4ce94deSChris Mason 
1011ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
10127bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
10137bb86316SChris Mason 
10141d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
101579f95c82SChris Mason 
1016a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
10175f39d397SChris Mason 		parent = path->nodes[level + 1];
1018bb803951SChris Mason 		pslot = path->slots[level + 1];
1019a05a9bb1SLi Zefan 	}
1020bb803951SChris Mason 
102140689478SChris Mason 	/*
102240689478SChris Mason 	 * deal with the case where there is only one pointer in the root
102340689478SChris Mason 	 * by promoting the node below to a root
102440689478SChris Mason 	 */
10255f39d397SChris Mason 	if (!parent) {
10265f39d397SChris Mason 		struct extent_buffer *child;
1027bb803951SChris Mason 
10285f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1029bb803951SChris Mason 			return 0;
1030bb803951SChris Mason 
1031bb803951SChris Mason 		/* promote the child to a root */
10324b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1033fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1034fb770ae4SLiu Bo 			ret = PTR_ERR(child);
10350b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1036305a26afSMark Fasheh 			goto enospc;
1037305a26afSMark Fasheh 		}
1038305a26afSMark Fasheh 
1039925baeddSChris Mason 		btrfs_tree_lock(child);
10409631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
10419631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
1042f0486c68SYan, Zheng 		if (ret) {
1043f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1044f0486c68SYan, Zheng 			free_extent_buffer(child);
1045f0486c68SYan, Zheng 			goto enospc;
1046f0486c68SYan, Zheng 		}
10472f375ab9SYan 
1048406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
1049d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1050240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1051925baeddSChris Mason 
10520b86a832SChris Mason 		add_root_to_dirty_list(root);
1053925baeddSChris Mason 		btrfs_tree_unlock(child);
1054b4ce94deSChris Mason 
1055925baeddSChris Mason 		path->locks[level] = 0;
1056bb803951SChris Mason 		path->nodes[level] = NULL;
10576a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1058925baeddSChris Mason 		btrfs_tree_unlock(mid);
1059bb803951SChris Mason 		/* once for the path */
10605f39d397SChris Mason 		free_extent_buffer(mid);
1061f0486c68SYan, Zheng 
1062f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10637a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1064bb803951SChris Mason 		/* once for the root ptr */
10653083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1066f0486c68SYan, Zheng 		return 0;
1067bb803951SChris Mason 	}
10685f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
10690b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1070bb803951SChris Mason 		return 0;
1071bb803951SChris Mason 
10724b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1073fb770ae4SLiu Bo 	if (IS_ERR(left))
1074fb770ae4SLiu Bo 		left = NULL;
1075fb770ae4SLiu Bo 
10765f39d397SChris Mason 	if (left) {
1077bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
10785f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
10799631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
1080bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
108154aa1f4dSChris Mason 		if (wret) {
108254aa1f4dSChris Mason 			ret = wret;
108354aa1f4dSChris Mason 			goto enospc;
108454aa1f4dSChris Mason 		}
10852cc58cf2SChris Mason 	}
1086fb770ae4SLiu Bo 
10874b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1088fb770ae4SLiu Bo 	if (IS_ERR(right))
1089fb770ae4SLiu Bo 		right = NULL;
1090fb770ae4SLiu Bo 
10915f39d397SChris Mason 	if (right) {
1092bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
10935f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
10949631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
1095bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
10962cc58cf2SChris Mason 		if (wret) {
10972cc58cf2SChris Mason 			ret = wret;
10982cc58cf2SChris Mason 			goto enospc;
10992cc58cf2SChris Mason 		}
11002cc58cf2SChris Mason 	}
11012cc58cf2SChris Mason 
11022cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
11035f39d397SChris Mason 	if (left) {
11045f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1105d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
110679f95c82SChris Mason 		if (wret < 0)
110779f95c82SChris Mason 			ret = wret;
1108bb803951SChris Mason 	}
110979f95c82SChris Mason 
111079f95c82SChris Mason 	/*
111179f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
111279f95c82SChris Mason 	 */
11135f39d397SChris Mason 	if (right) {
1114d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
111554aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
111679f95c82SChris Mason 			ret = wret;
11175f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
11186a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1119925baeddSChris Mason 			btrfs_tree_unlock(right);
1120afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1121f0486c68SYan, Zheng 			root_sub_used(root, right->len);
11227a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
11237a163608SFilipe Manana 					      0, 1);
11243083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1125f0486c68SYan, Zheng 			right = NULL;
1126bb803951SChris Mason 		} else {
11275f39d397SChris Mason 			struct btrfs_disk_key right_key;
11285f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1129f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
113033cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
11310e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11325f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
11335f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1134bb803951SChris Mason 		}
1135bb803951SChris Mason 	}
11365f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
113779f95c82SChris Mason 		/*
113879f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
113979f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
114079f95c82SChris Mason 		 * could try to delete the only pointer in this node.
114179f95c82SChris Mason 		 * So, pull some keys from the left.
114279f95c82SChris Mason 		 * There has to be a left pointer at this point because
114379f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
114479f95c82SChris Mason 		 * right
114579f95c82SChris Mason 		 */
1146305a26afSMark Fasheh 		if (!left) {
1147305a26afSMark Fasheh 			ret = -EROFS;
11480b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1149305a26afSMark Fasheh 			goto enospc;
1150305a26afSMark Fasheh 		}
115155d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
115254aa1f4dSChris Mason 		if (wret < 0) {
115379f95c82SChris Mason 			ret = wret;
115454aa1f4dSChris Mason 			goto enospc;
115554aa1f4dSChris Mason 		}
1156bce4eae9SChris Mason 		if (wret == 1) {
1157d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1158bce4eae9SChris Mason 			if (wret < 0)
1159bce4eae9SChris Mason 				ret = wret;
1160bce4eae9SChris Mason 		}
116179f95c82SChris Mason 		BUG_ON(wret == 1);
116279f95c82SChris Mason 	}
11635f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
11646a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1165925baeddSChris Mason 		btrfs_tree_unlock(mid);
1166afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1167f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
11687a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
11693083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1170f0486c68SYan, Zheng 		mid = NULL;
117179f95c82SChris Mason 	} else {
117279f95c82SChris Mason 		/* update the parent key to reflect our changes */
11735f39d397SChris Mason 		struct btrfs_disk_key mid_key;
11745f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1175f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
117633cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
11770e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
11785f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
11795f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
118079f95c82SChris Mason 	}
1181bb803951SChris Mason 
118279f95c82SChris Mason 	/* update the path */
11835f39d397SChris Mason 	if (left) {
11845f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
118567439dadSDavid Sterba 			atomic_inc(&left->refs);
1186925baeddSChris Mason 			/* left was locked after cow */
11875f39d397SChris Mason 			path->nodes[level] = left;
1188bb803951SChris Mason 			path->slots[level + 1] -= 1;
1189bb803951SChris Mason 			path->slots[level] = orig_slot;
1190925baeddSChris Mason 			if (mid) {
1191925baeddSChris Mason 				btrfs_tree_unlock(mid);
11925f39d397SChris Mason 				free_extent_buffer(mid);
1193925baeddSChris Mason 			}
1194bb803951SChris Mason 		} else {
11955f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1196bb803951SChris Mason 			path->slots[level] = orig_slot;
1197bb803951SChris Mason 		}
1198bb803951SChris Mason 	}
119979f95c82SChris Mason 	/* double check we haven't messed things up */
1200e20d96d6SChris Mason 	if (orig_ptr !=
12015f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
120279f95c82SChris Mason 		BUG();
120354aa1f4dSChris Mason enospc:
1204925baeddSChris Mason 	if (right) {
1205925baeddSChris Mason 		btrfs_tree_unlock(right);
12065f39d397SChris Mason 		free_extent_buffer(right);
1207925baeddSChris Mason 	}
1208925baeddSChris Mason 	if (left) {
1209925baeddSChris Mason 		if (path->nodes[level] != left)
1210925baeddSChris Mason 			btrfs_tree_unlock(left);
12115f39d397SChris Mason 		free_extent_buffer(left);
1212925baeddSChris Mason 	}
1213bb803951SChris Mason 	return ret;
1214bb803951SChris Mason }
1215bb803951SChris Mason 
1216d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1217d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1218d352ac68SChris Mason  * have to be pessimistic.
1219d352ac68SChris Mason  */
1220d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1221e66f709bSChris Mason 					  struct btrfs_root *root,
1222e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1223e66f709bSChris Mason {
12240b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12255f39d397SChris Mason 	struct extent_buffer *right = NULL;
12265f39d397SChris Mason 	struct extent_buffer *mid;
12275f39d397SChris Mason 	struct extent_buffer *left = NULL;
12285f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1229e66f709bSChris Mason 	int ret = 0;
1230e66f709bSChris Mason 	int wret;
1231e66f709bSChris Mason 	int pslot;
1232e66f709bSChris Mason 	int orig_slot = path->slots[level];
1233e66f709bSChris Mason 
1234e66f709bSChris Mason 	if (level == 0)
1235e66f709bSChris Mason 		return 1;
1236e66f709bSChris Mason 
12375f39d397SChris Mason 	mid = path->nodes[level];
12387bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1239e66f709bSChris Mason 
1240a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
12415f39d397SChris Mason 		parent = path->nodes[level + 1];
1242e66f709bSChris Mason 		pslot = path->slots[level + 1];
1243a05a9bb1SLi Zefan 	}
1244e66f709bSChris Mason 
12455f39d397SChris Mason 	if (!parent)
1246e66f709bSChris Mason 		return 1;
1247e66f709bSChris Mason 
12484b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1249fb770ae4SLiu Bo 	if (IS_ERR(left))
1250fb770ae4SLiu Bo 		left = NULL;
1251e66f709bSChris Mason 
1252e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
12535f39d397SChris Mason 	if (left) {
1254e66f709bSChris Mason 		u32 left_nr;
1255925baeddSChris Mason 
1256bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1257b4ce94deSChris Mason 
12585f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
12590b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
126033ade1f8SChris Mason 			wret = 1;
126133ade1f8SChris Mason 		} else {
12625f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
12639631e4ccSJosef Bacik 					      pslot - 1, &left,
1264bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
126554aa1f4dSChris Mason 			if (ret)
126654aa1f4dSChris Mason 				wret = 1;
126754aa1f4dSChris Mason 			else {
1268d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
126954aa1f4dSChris Mason 			}
127033ade1f8SChris Mason 		}
1271e66f709bSChris Mason 		if (wret < 0)
1272e66f709bSChris Mason 			ret = wret;
1273e66f709bSChris Mason 		if (wret == 0) {
12745f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1275e66f709bSChris Mason 			orig_slot += left_nr;
12765f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1277f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
127833cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
12790e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
12805f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
12815f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12825f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
12835f39d397SChris Mason 				path->nodes[level] = left;
1284e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1285e66f709bSChris Mason 				path->slots[level] = orig_slot;
1286925baeddSChris Mason 				btrfs_tree_unlock(mid);
12875f39d397SChris Mason 				free_extent_buffer(mid);
1288e66f709bSChris Mason 			} else {
1289e66f709bSChris Mason 				orig_slot -=
12905f39d397SChris Mason 					btrfs_header_nritems(left);
1291e66f709bSChris Mason 				path->slots[level] = orig_slot;
1292925baeddSChris Mason 				btrfs_tree_unlock(left);
12935f39d397SChris Mason 				free_extent_buffer(left);
1294e66f709bSChris Mason 			}
1295e66f709bSChris Mason 			return 0;
1296e66f709bSChris Mason 		}
1297925baeddSChris Mason 		btrfs_tree_unlock(left);
12985f39d397SChris Mason 		free_extent_buffer(left);
1299e66f709bSChris Mason 	}
13004b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1301fb770ae4SLiu Bo 	if (IS_ERR(right))
1302fb770ae4SLiu Bo 		right = NULL;
1303e66f709bSChris Mason 
1304e66f709bSChris Mason 	/*
1305e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1306e66f709bSChris Mason 	 */
13075f39d397SChris Mason 	if (right) {
130833ade1f8SChris Mason 		u32 right_nr;
1309b4ce94deSChris Mason 
1310bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1311b4ce94deSChris Mason 
13125f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
13130b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
131433ade1f8SChris Mason 			wret = 1;
131533ade1f8SChris Mason 		} else {
13165f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
13175f39d397SChris Mason 					      parent, pslot + 1,
1318bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
131954aa1f4dSChris Mason 			if (ret)
132054aa1f4dSChris Mason 				wret = 1;
132154aa1f4dSChris Mason 			else {
132255d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
132333ade1f8SChris Mason 			}
132454aa1f4dSChris Mason 		}
1325e66f709bSChris Mason 		if (wret < 0)
1326e66f709bSChris Mason 			ret = wret;
1327e66f709bSChris Mason 		if (wret == 0) {
13285f39d397SChris Mason 			struct btrfs_disk_key disk_key;
13295f39d397SChris Mason 
13305f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1331f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
133233cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
13330e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
13345f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
13355f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
13365f39d397SChris Mason 
13375f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
13385f39d397SChris Mason 				path->nodes[level] = right;
1339e66f709bSChris Mason 				path->slots[level + 1] += 1;
1340e66f709bSChris Mason 				path->slots[level] = orig_slot -
13415f39d397SChris Mason 					btrfs_header_nritems(mid);
1342925baeddSChris Mason 				btrfs_tree_unlock(mid);
13435f39d397SChris Mason 				free_extent_buffer(mid);
1344e66f709bSChris Mason 			} else {
1345925baeddSChris Mason 				btrfs_tree_unlock(right);
13465f39d397SChris Mason 				free_extent_buffer(right);
1347e66f709bSChris Mason 			}
1348e66f709bSChris Mason 			return 0;
1349e66f709bSChris Mason 		}
1350925baeddSChris Mason 		btrfs_tree_unlock(right);
13515f39d397SChris Mason 		free_extent_buffer(right);
1352e66f709bSChris Mason 	}
1353e66f709bSChris Mason 	return 1;
1354e66f709bSChris Mason }
1355e66f709bSChris Mason 
135674123bd7SChris Mason /*
1357d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1358d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
13593c69faecSChris Mason  */
13602ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1361e02119d5SChris Mason 			     struct btrfs_path *path,
136201f46658SChris Mason 			     int level, int slot, u64 objectid)
13633c69faecSChris Mason {
13645f39d397SChris Mason 	struct extent_buffer *node;
136501f46658SChris Mason 	struct btrfs_disk_key disk_key;
13663c69faecSChris Mason 	u32 nritems;
13673c69faecSChris Mason 	u64 search;
1368a7175319SChris Mason 	u64 target;
13696b80053dSChris Mason 	u64 nread = 0;
1370ace75066SFilipe Manana 	u64 nread_max;
13716b80053dSChris Mason 	u32 nr;
13726b80053dSChris Mason 	u32 blocksize;
13736b80053dSChris Mason 	u32 nscan = 0;
1374db94535dSChris Mason 
1375ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
13763c69faecSChris Mason 		return;
13773c69faecSChris Mason 
13786702ed49SChris Mason 	if (!path->nodes[level])
13796702ed49SChris Mason 		return;
13806702ed49SChris Mason 
13815f39d397SChris Mason 	node = path->nodes[level];
1382925baeddSChris Mason 
1383ace75066SFilipe Manana 	/*
1384ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1385ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1386ace75066SFilipe Manana 	 * much IO at once (possibly random).
1387ace75066SFilipe Manana 	 */
1388ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1389ace75066SFilipe Manana 		if (level > 1)
1390ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1391ace75066SFilipe Manana 		else
1392ace75066SFilipe Manana 			nread_max = SZ_128K;
1393ace75066SFilipe Manana 	} else {
1394ace75066SFilipe Manana 		nread_max = SZ_64K;
1395ace75066SFilipe Manana 	}
1396ace75066SFilipe Manana 
13973c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
13980b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1399069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1400069a2e37SFilipe Manana 		struct extent_buffer *eb;
1401069a2e37SFilipe Manana 
14020b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
14035f39d397SChris Mason 		if (eb) {
14045f39d397SChris Mason 			free_extent_buffer(eb);
14053c69faecSChris Mason 			return;
14063c69faecSChris Mason 		}
1407069a2e37SFilipe Manana 	}
14083c69faecSChris Mason 
1409a7175319SChris Mason 	target = search;
14106b80053dSChris Mason 
14115f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
14126b80053dSChris Mason 	nr = slot;
141325b8b936SJosef Bacik 
14143c69faecSChris Mason 	while (1) {
1415e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
14166b80053dSChris Mason 			if (nr == 0)
14173c69faecSChris Mason 				break;
14186b80053dSChris Mason 			nr--;
1419ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1420ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
14216b80053dSChris Mason 			nr++;
14226b80053dSChris Mason 			if (nr >= nritems)
14236b80053dSChris Mason 				break;
14243c69faecSChris Mason 		}
1425e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
142601f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
142701f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
142801f46658SChris Mason 				break;
142901f46658SChris Mason 		}
14306b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1431ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1432ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1433a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1434bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
14356b80053dSChris Mason 			nread += blocksize;
14363c69faecSChris Mason 		}
14376b80053dSChris Mason 		nscan++;
1438ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
14396b80053dSChris Mason 			break;
14403c69faecSChris Mason 	}
14413c69faecSChris Mason }
1442925baeddSChris Mason 
1443bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1444b4ce94deSChris Mason {
1445bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1446b4ce94deSChris Mason 	int slot;
1447b4ce94deSChris Mason 	int nritems;
1448b4ce94deSChris Mason 
14498c594ea8SChris Mason 	parent = path->nodes[level + 1];
1450b4ce94deSChris Mason 	if (!parent)
14510b08851fSJosef Bacik 		return;
1452b4ce94deSChris Mason 
1453b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
14548c594ea8SChris Mason 	slot = path->slots[level + 1];
1455b4ce94deSChris Mason 
1456bfb484d9SJosef Bacik 	if (slot > 0)
1457bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1458bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1459bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1460b4ce94deSChris Mason }
1461b4ce94deSChris Mason 
1462b4ce94deSChris Mason 
1463b4ce94deSChris Mason /*
1464d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1465d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1466d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1467d397712bSChris Mason  * tree.
1468d352ac68SChris Mason  *
1469d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1470d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1471d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1472d352ac68SChris Mason  *
1473d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1474d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1475d352ac68SChris Mason  */
1476e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1477f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1478f7c79f30SChris Mason 			       int *write_lock_level)
1479925baeddSChris Mason {
1480925baeddSChris Mason 	int i;
1481925baeddSChris Mason 	int skip_level = level;
1482c1227996SNikolay Borisov 	bool check_skip = true;
1483925baeddSChris Mason 
1484925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1485925baeddSChris Mason 		if (!path->nodes[i])
1486925baeddSChris Mason 			break;
1487925baeddSChris Mason 		if (!path->locks[i])
1488925baeddSChris Mason 			break;
1489c1227996SNikolay Borisov 
1490c1227996SNikolay Borisov 		if (check_skip) {
1491c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1492925baeddSChris Mason 				skip_level = i + 1;
1493925baeddSChris Mason 				continue;
1494925baeddSChris Mason 			}
1495c1227996SNikolay Borisov 
1496c1227996SNikolay Borisov 			if (path->keep_locks) {
1497925baeddSChris Mason 				u32 nritems;
1498c1227996SNikolay Borisov 
1499c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1500051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1501925baeddSChris Mason 					skip_level = i + 1;
1502925baeddSChris Mason 					continue;
1503925baeddSChris Mason 				}
1504925baeddSChris Mason 			}
1505c1227996SNikolay Borisov 		}
1506051e1b9fSChris Mason 
1507d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1508c1227996SNikolay Borisov 			check_skip = false;
1509c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1510925baeddSChris Mason 			path->locks[i] = 0;
1511f7c79f30SChris Mason 			if (write_lock_level &&
1512f7c79f30SChris Mason 			    i > min_write_lock_level &&
1513f7c79f30SChris Mason 			    i <= *write_lock_level) {
1514f7c79f30SChris Mason 				*write_lock_level = i - 1;
1515f7c79f30SChris Mason 			}
1516925baeddSChris Mason 		}
1517925baeddSChris Mason 	}
1518925baeddSChris Mason }
1519925baeddSChris Mason 
15203c69faecSChris Mason /*
1521376a21d7SFilipe Manana  * Helper function for btrfs_search_slot() and other functions that do a search
1522376a21d7SFilipe Manana  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1523376a21d7SFilipe Manana  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1524376a21d7SFilipe Manana  * its pages from disk.
1525c8c42864SChris Mason  *
1526376a21d7SFilipe Manana  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1527376a21d7SFilipe Manana  * whole btree search, starting again from the current root node.
1528c8c42864SChris Mason  */
1529c8c42864SChris Mason static int
1530d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1531c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1532cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1533c8c42864SChris Mason {
15340b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1535789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1536c8c42864SChris Mason 	u64 blocknr;
1537c8c42864SChris Mason 	u64 gen;
1538c8c42864SChris Mason 	struct extent_buffer *tmp;
153976a05b35SChris Mason 	int ret;
1540581c1760SQu Wenruo 	int parent_level;
1541b246666eSFilipe Manana 	bool unlock_up;
1542c8c42864SChris Mason 
1543b246666eSFilipe Manana 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1544213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1545213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1546213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1547789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(*eb_ret, &check.first_key, slot);
1548789d6a3aSQu Wenruo 	check.has_first_key = true;
1549789d6a3aSQu Wenruo 	check.level = parent_level - 1;
1550789d6a3aSQu Wenruo 	check.transid = gen;
1551789d6a3aSQu Wenruo 	check.owner_root = root->root_key.objectid;
1552c8c42864SChris Mason 
1553b246666eSFilipe Manana 	/*
1554b246666eSFilipe Manana 	 * If we need to read an extent buffer from disk and we are holding locks
1555b246666eSFilipe Manana 	 * on upper level nodes, we unlock all the upper nodes before reading the
1556b246666eSFilipe Manana 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1557b246666eSFilipe Manana 	 * restart the search. We don't release the lock on the current level
1558b246666eSFilipe Manana 	 * because we need to walk this node to figure out which blocks to read.
1559b246666eSFilipe Manana 	 */
15600b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1561cb44921aSChris Mason 	if (tmp) {
1562ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1563ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1564ace75066SFilipe Manana 
1565b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1566b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1567448de471SQu Wenruo 			/*
1568448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1569448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1570448de471SQu Wenruo 			 * parents (shared tree blocks).
1571448de471SQu Wenruo 			 */
1572e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1573789d6a3aSQu Wenruo 					parent_level - 1, &check.first_key, gen)) {
1574448de471SQu Wenruo 				free_extent_buffer(tmp);
1575448de471SQu Wenruo 				return -EUCLEAN;
1576448de471SQu Wenruo 			}
1577c8c42864SChris Mason 			*eb_ret = tmp;
1578c8c42864SChris Mason 			return 0;
1579c8c42864SChris Mason 		}
1580bdf7c00eSJosef Bacik 
1581857bc13fSJosef Bacik 		if (p->nowait) {
1582857bc13fSJosef Bacik 			free_extent_buffer(tmp);
1583857bc13fSJosef Bacik 			return -EAGAIN;
1584857bc13fSJosef Bacik 		}
1585857bc13fSJosef Bacik 
1586b246666eSFilipe Manana 		if (unlock_up)
1587b246666eSFilipe Manana 			btrfs_unlock_up_safe(p, level + 1);
1588b246666eSFilipe Manana 
1589b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
1590789d6a3aSQu Wenruo 		ret = btrfs_read_extent_buffer(tmp, &check);
15919a4ffa1bSQu Wenruo 		if (ret) {
1592cb44921aSChris Mason 			free_extent_buffer(tmp);
1593b3b4aa74SDavid Sterba 			btrfs_release_path(p);
1594cb44921aSChris Mason 			return -EIO;
1595cb44921aSChris Mason 		}
159688c602abSQu Wenruo 		if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
159788c602abSQu Wenruo 			free_extent_buffer(tmp);
159888c602abSQu Wenruo 			btrfs_release_path(p);
159988c602abSQu Wenruo 			return -EUCLEAN;
160088c602abSQu Wenruo 		}
1601b246666eSFilipe Manana 
1602b246666eSFilipe Manana 		if (unlock_up)
1603b246666eSFilipe Manana 			ret = -EAGAIN;
1604b246666eSFilipe Manana 
1605b246666eSFilipe Manana 		goto out;
1606857bc13fSJosef Bacik 	} else if (p->nowait) {
1607857bc13fSJosef Bacik 		return -EAGAIN;
16089a4ffa1bSQu Wenruo 	}
1609c8c42864SChris Mason 
1610b246666eSFilipe Manana 	if (unlock_up) {
16118c594ea8SChris Mason 		btrfs_unlock_up_safe(p, level + 1);
16124bb59055SFilipe Manana 		ret = -EAGAIN;
16134bb59055SFilipe Manana 	} else {
16144bb59055SFilipe Manana 		ret = 0;
16154bb59055SFilipe Manana 	}
16168c594ea8SChris Mason 
1617e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
16182ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1619c8c42864SChris Mason 
1620789d6a3aSQu Wenruo 	tmp = read_tree_block(fs_info, blocknr, &check);
16214eb150d6SQu Wenruo 	if (IS_ERR(tmp)) {
16224eb150d6SQu Wenruo 		btrfs_release_path(p);
16234eb150d6SQu Wenruo 		return PTR_ERR(tmp);
16244eb150d6SQu Wenruo 	}
162576a05b35SChris Mason 	/*
162676a05b35SChris Mason 	 * If the read above didn't mark this buffer up to date,
162776a05b35SChris Mason 	 * it will never end up being up to date.  Set ret to EIO now
162876a05b35SChris Mason 	 * and give up so that our caller doesn't loop forever
162976a05b35SChris Mason 	 * on our EAGAINs.
163076a05b35SChris Mason 	 */
1631e6a1d6fdSLiu Bo 	if (!extent_buffer_uptodate(tmp))
163276a05b35SChris Mason 		ret = -EIO;
163302a3307aSLiu Bo 
1634b246666eSFilipe Manana out:
16354bb59055SFilipe Manana 	if (ret == 0) {
16364bb59055SFilipe Manana 		*eb_ret = tmp;
16374bb59055SFilipe Manana 	} else {
16384bb59055SFilipe Manana 		free_extent_buffer(tmp);
163902a3307aSLiu Bo 		btrfs_release_path(p);
16404bb59055SFilipe Manana 	}
16414bb59055SFilipe Manana 
164276a05b35SChris Mason 	return ret;
1643c8c42864SChris Mason }
1644c8c42864SChris Mason 
1645c8c42864SChris Mason /*
1646c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1647c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1648c8c42864SChris Mason  * the ins_len.
1649c8c42864SChris Mason  *
1650c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1651c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1652c8c42864SChris Mason  * start over
1653c8c42864SChris Mason  */
1654c8c42864SChris Mason static int
1655c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1656c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1657bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1658bd681513SChris Mason 		       int *write_lock_level)
1659c8c42864SChris Mason {
16600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
166195b982deSNikolay Borisov 	int ret = 0;
16620b246afaSJeff Mahoney 
1663c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
16640b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1665c8c42864SChris Mason 
1666bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1667bd681513SChris Mason 			*write_lock_level = level + 1;
1668bd681513SChris Mason 			btrfs_release_path(p);
166995b982deSNikolay Borisov 			return -EAGAIN;
1670bd681513SChris Mason 		}
1671bd681513SChris Mason 
1672bfb484d9SJosef Bacik 		reada_for_balance(p, level);
167395b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1674c8c42864SChris Mason 
1675c8c42864SChris Mason 		b = p->nodes[level];
1676c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
16770b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1678c8c42864SChris Mason 
1679bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1680bd681513SChris Mason 			*write_lock_level = level + 1;
1681bd681513SChris Mason 			btrfs_release_path(p);
168295b982deSNikolay Borisov 			return -EAGAIN;
1683bd681513SChris Mason 		}
1684bd681513SChris Mason 
1685bfb484d9SJosef Bacik 		reada_for_balance(p, level);
168695b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
168795b982deSNikolay Borisov 		if (ret)
168895b982deSNikolay Borisov 			return ret;
1689c8c42864SChris Mason 
1690c8c42864SChris Mason 		b = p->nodes[level];
1691c8c42864SChris Mason 		if (!b) {
1692b3b4aa74SDavid Sterba 			btrfs_release_path(p);
169395b982deSNikolay Borisov 			return -EAGAIN;
1694c8c42864SChris Mason 		}
1695c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1696c8c42864SChris Mason 	}
1697c8c42864SChris Mason 	return ret;
1698c8c42864SChris Mason }
1699c8c42864SChris Mason 
1700381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1701e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1702e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1703e33d5c3dSKelley Nielsen {
1704e33d5c3dSKelley Nielsen 	int ret;
1705e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1706e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1707381cf658SDavid Sterba 
1708381cf658SDavid Sterba 	ASSERT(path);
17091d4c08e0SDavid Sterba 	ASSERT(found_key);
1710e33d5c3dSKelley Nielsen 
1711e33d5c3dSKelley Nielsen 	key.type = key_type;
1712e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1713e33d5c3dSKelley Nielsen 	key.offset = ioff;
1714e33d5c3dSKelley Nielsen 
1715e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
17161d4c08e0SDavid Sterba 	if (ret < 0)
1717e33d5c3dSKelley Nielsen 		return ret;
1718e33d5c3dSKelley Nielsen 
1719e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1720e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1721e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1722e33d5c3dSKelley Nielsen 		if (ret)
1723e33d5c3dSKelley Nielsen 			return ret;
1724e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1725e33d5c3dSKelley Nielsen 	}
1726e33d5c3dSKelley Nielsen 
1727e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1728e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1729e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1730e33d5c3dSKelley Nielsen 		return 1;
1731e33d5c3dSKelley Nielsen 
1732e33d5c3dSKelley Nielsen 	return 0;
1733e33d5c3dSKelley Nielsen }
1734e33d5c3dSKelley Nielsen 
17351fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
17361fc28d8eSLiu Bo 							struct btrfs_path *p,
17371fc28d8eSLiu Bo 							int write_lock_level)
17381fc28d8eSLiu Bo {
17391fc28d8eSLiu Bo 	struct extent_buffer *b;
1740120de408SJosef Bacik 	int root_lock = 0;
17411fc28d8eSLiu Bo 	int level = 0;
17421fc28d8eSLiu Bo 
17431fc28d8eSLiu Bo 	if (p->search_commit_root) {
17441fc28d8eSLiu Bo 		b = root->commit_root;
174567439dadSDavid Sterba 		atomic_inc(&b->refs);
17461fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1747f9ddfd05SLiu Bo 		/*
1748f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1749f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1750f9ddfd05SLiu Bo 		 */
1751f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
17521fc28d8eSLiu Bo 
17531fc28d8eSLiu Bo 		goto out;
17541fc28d8eSLiu Bo 	}
17551fc28d8eSLiu Bo 
17561fc28d8eSLiu Bo 	if (p->skip_locking) {
17571fc28d8eSLiu Bo 		b = btrfs_root_node(root);
17581fc28d8eSLiu Bo 		level = btrfs_header_level(b);
17591fc28d8eSLiu Bo 		goto out;
17601fc28d8eSLiu Bo 	}
17611fc28d8eSLiu Bo 
1762120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1763120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1764120de408SJosef Bacik 
17651fc28d8eSLiu Bo 	/*
1766662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1767662c653bSLiu Bo 	 * lock.
1768662c653bSLiu Bo 	 */
1769662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1770662c653bSLiu Bo 		/*
1771662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1772662c653bSLiu Bo 		 * have it read locked
17731fc28d8eSLiu Bo 		 */
1774857bc13fSJosef Bacik 		if (p->nowait) {
1775857bc13fSJosef Bacik 			b = btrfs_try_read_lock_root_node(root);
1776857bc13fSJosef Bacik 			if (IS_ERR(b))
1777857bc13fSJosef Bacik 				return b;
1778857bc13fSJosef Bacik 		} else {
17791bb96598SJosef Bacik 			b = btrfs_read_lock_root_node(root);
1780857bc13fSJosef Bacik 		}
17811fc28d8eSLiu Bo 		level = btrfs_header_level(b);
17821fc28d8eSLiu Bo 		if (level > write_lock_level)
17831fc28d8eSLiu Bo 			goto out;
17841fc28d8eSLiu Bo 
1785662c653bSLiu Bo 		/* Whoops, must trade for write lock */
17861fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
17871fc28d8eSLiu Bo 		free_extent_buffer(b);
1788662c653bSLiu Bo 	}
1789662c653bSLiu Bo 
17901fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
17911fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
17921fc28d8eSLiu Bo 
17931fc28d8eSLiu Bo 	/* The level might have changed, check again */
17941fc28d8eSLiu Bo 	level = btrfs_header_level(b);
17951fc28d8eSLiu Bo 
17961fc28d8eSLiu Bo out:
1797120de408SJosef Bacik 	/*
1798120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1799120de408SJosef Bacik 	 * longer valid, return an error in this case.
1800120de408SJosef Bacik 	 */
1801120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1802120de408SJosef Bacik 		if (root_lock)
1803120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1804120de408SJosef Bacik 		free_extent_buffer(b);
1805120de408SJosef Bacik 		return ERR_PTR(-EIO);
1806120de408SJosef Bacik 	}
1807120de408SJosef Bacik 
18081fc28d8eSLiu Bo 	p->nodes[level] = b;
18091fc28d8eSLiu Bo 	if (!p->skip_locking)
18101fc28d8eSLiu Bo 		p->locks[level] = root_lock;
18111fc28d8eSLiu Bo 	/*
18121fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
18131fc28d8eSLiu Bo 	 */
18141fc28d8eSLiu Bo 	return b;
18151fc28d8eSLiu Bo }
18161fc28d8eSLiu Bo 
1817d96b3424SFilipe Manana /*
1818d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1819d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1820d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1821d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1822d96b3424SFilipe Manana  * reallocated in the next transaction.
1823d96b3424SFilipe Manana  *
1824d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1825d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1826d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1827d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1828d96b3424SFilipe Manana  */
1829d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1830d96b3424SFilipe Manana {
1831d96b3424SFilipe Manana 	const int i = path->lowest_level;
1832d96b3424SFilipe Manana 	const int slot = path->slots[i];
1833d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1834d96b3424SFilipe Manana 	struct extent_buffer *clone;
1835d96b3424SFilipe Manana 
1836d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1837d96b3424SFilipe Manana 
1838d96b3424SFilipe Manana 	if (!lowest)
1839d96b3424SFilipe Manana 		return 0;
1840d96b3424SFilipe Manana 
1841d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1842d96b3424SFilipe Manana 
1843d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1844d96b3424SFilipe Manana 	if (!clone)
1845d96b3424SFilipe Manana 		return -ENOMEM;
1846d96b3424SFilipe Manana 
1847d96b3424SFilipe Manana 	btrfs_release_path(path);
1848d96b3424SFilipe Manana 	path->nodes[i] = clone;
1849d96b3424SFilipe Manana 	path->slots[i] = slot;
1850d96b3424SFilipe Manana 
1851d96b3424SFilipe Manana 	return 0;
1852d96b3424SFilipe Manana }
18531fc28d8eSLiu Bo 
1854e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1855e2e58d0fSFilipe Manana 				      int search_low_slot,
1856e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1857e2e58d0fSFilipe Manana 				      int prev_cmp,
1858e2e58d0fSFilipe Manana 				      int *slot)
1859e2e58d0fSFilipe Manana {
1860e2e58d0fSFilipe Manana 	/*
1861e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1862e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1863e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1864e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1865e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1866e2e58d0fSFilipe Manana 	 */
1867e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1868e2e58d0fSFilipe Manana 		*slot = 0;
1869e2e58d0fSFilipe Manana 		return 0;
1870e2e58d0fSFilipe Manana 	}
1871e2e58d0fSFilipe Manana 
1872e2e58d0fSFilipe Manana 	return generic_bin_search(eb, search_low_slot, key, slot);
1873e2e58d0fSFilipe Manana }
1874e2e58d0fSFilipe Manana 
1875109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1876109324cfSFilipe Manana 		       struct btrfs_root *root,
1877109324cfSFilipe Manana 		       const struct btrfs_key *key,
1878109324cfSFilipe Manana 		       struct btrfs_path *path,
1879109324cfSFilipe Manana 		       int ins_len,
1880109324cfSFilipe Manana 		       int prev_cmp)
1881109324cfSFilipe Manana {
1882109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
1883109324cfSFilipe Manana 	int leaf_free_space = -1;
1884109324cfSFilipe Manana 	int search_low_slot = 0;
1885109324cfSFilipe Manana 	int ret;
1886109324cfSFilipe Manana 	bool do_bin_search = true;
1887109324cfSFilipe Manana 
1888109324cfSFilipe Manana 	/*
1889109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
1890109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
1891109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
1892109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1893109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
1894109324cfSFilipe Manana 	 */
1895109324cfSFilipe Manana 	if (ins_len > 0) {
1896109324cfSFilipe Manana 		/*
1897109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
1898109324cfSFilipe Manana 		 * will not change until then.
1899109324cfSFilipe Manana 		 */
1900109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
1901109324cfSFilipe Manana 
1902109324cfSFilipe Manana 		/*
1903109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
1904109324cfSFilipe Manana 		 * the root of the tree.
1905109324cfSFilipe Manana 		 */
1906109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
1907109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
1908109324cfSFilipe Manana 
1909109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
1910109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
1911109324cfSFilipe Manana 
1912109324cfSFilipe Manana 			/*
1913109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
1914109324cfSFilipe Manana 			 * taking into account that the first key is very likely
1915109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
1916109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
1917109324cfSFilipe Manana 			 * the header's level field.
1918109324cfSFilipe Manana 			 */
1919109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
1920109324cfSFilipe Manana 			if (ret < 0) {
1921109324cfSFilipe Manana 				/*
1922109324cfSFilipe Manana 				 * The first key is smaller than the key we want
1923109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
1924109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
1925109324cfSFilipe Manana 				 *
1926109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
1927109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
1928109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
1929109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
1930109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
1931109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
1932109324cfSFilipe Manana 				 */
1933109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
1934109324cfSFilipe Manana 				search_low_slot = 1;
1935109324cfSFilipe Manana 			} else {
1936109324cfSFilipe Manana 				/*
1937109324cfSFilipe Manana 				 * The first key is >= then the key we want to
1938109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
1939109324cfSFilipe Manana 				 * the target key will be at slot 0.
1940109324cfSFilipe Manana 				 *
1941109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
1942109324cfSFilipe Manana 				 * less than the first key, because we will need
1943109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
1944109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
1945109324cfSFilipe Manana 				 * If the key matches the first key, then we can
1946109324cfSFilipe Manana 				 * unlock all the upper nodes, using
1947109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
1948109324cfSFilipe Manana 				 * as stated above.
1949109324cfSFilipe Manana 				 */
1950109324cfSFilipe Manana 				if (ret == 0)
1951109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
1952109324cfSFilipe Manana 				/*
1953109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
1954109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
1955109324cfSFilipe Manana 				 * to adjust it.
1956109324cfSFilipe Manana 				 */
1957109324cfSFilipe Manana 				do_bin_search = false;
1958109324cfSFilipe Manana 				path->slots[0] = 0;
1959109324cfSFilipe Manana 			}
1960109324cfSFilipe Manana 		}
1961109324cfSFilipe Manana 	}
1962109324cfSFilipe Manana 
1963109324cfSFilipe Manana 	if (do_bin_search) {
1964109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
1965109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
1966109324cfSFilipe Manana 		if (ret < 0)
1967109324cfSFilipe Manana 			return ret;
1968109324cfSFilipe Manana 	}
1969109324cfSFilipe Manana 
1970109324cfSFilipe Manana 	if (ins_len > 0) {
1971109324cfSFilipe Manana 		/*
1972109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
1973109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
1974109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
1975109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
1976109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
1977109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
1978109324cfSFilipe Manana 		 * check will be correct.
1979109324cfSFilipe Manana 		 */
1980109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
1981109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
1982109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
1983109324cfSFilipe Manana 		}
1984109324cfSFilipe Manana 
1985109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
1986109324cfSFilipe Manana 
1987109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
1988109324cfSFilipe Manana 			int err;
1989109324cfSFilipe Manana 
1990109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
1991109324cfSFilipe Manana 					 (ret == 0));
1992bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
1993bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
1994bb8e9a60SFilipe Manana 				err = -EUCLEAN;
1995109324cfSFilipe Manana 			if (err)
1996109324cfSFilipe Manana 				ret = err;
1997109324cfSFilipe Manana 		}
1998109324cfSFilipe Manana 	}
1999109324cfSFilipe Manana 
2000109324cfSFilipe Manana 	return ret;
2001109324cfSFilipe Manana }
2002109324cfSFilipe Manana 
2003c8c42864SChris Mason /*
20044271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
20054271eceaSNikolay Borisov  * modifications to preserve tree invariants.
200674123bd7SChris Mason  *
20074271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
20084271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
20094271eceaSNikolay Borisov  * @root:	The root node of the tree
20104271eceaSNikolay Borisov  * @key:	The key we are looking for
20119a664971Sethanwu  * @ins_len:	Indicates purpose of search:
20129a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
20139a664971Sethanwu  *              <0  for deletions
20149a664971Sethanwu  *               0  for plain searches, not modifying the tree
20159a664971Sethanwu  *
20169a664971Sethanwu  *              (*) If size of item inserted doesn't include
20179a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
20189a664971Sethanwu  *              be set.
20194271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
20204271eceaSNikolay Borisov  *		when modifying the tree.
202197571fd0SChris Mason  *
20224271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
20234271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
20244271eceaSNikolay Borisov  *
20254271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
20264271eceaSNikolay Borisov  * of the path (level 0)
20274271eceaSNikolay Borisov  *
20284271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
20294271eceaSNikolay Borisov  * points to the slot where it should be inserted
20304271eceaSNikolay Borisov  *
20314271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
20324271eceaSNikolay Borisov  * is returned
203374123bd7SChris Mason  */
2034310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2035310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2036310712b2SOmar Sandoval 		      int ins_len, int cow)
2037be0e5c09SChris Mason {
2038d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
20395f39d397SChris Mason 	struct extent_buffer *b;
2040be0e5c09SChris Mason 	int slot;
2041be0e5c09SChris Mason 	int ret;
204233c66f43SYan Zheng 	int err;
2043be0e5c09SChris Mason 	int level;
2044925baeddSChris Mason 	int lowest_unlock = 1;
2045bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2046bd681513SChris Mason 	int write_lock_level = 0;
20479f3a7427SChris Mason 	u8 lowest_level = 0;
2048f7c79f30SChris Mason 	int min_write_lock_level;
2049d7396f07SFilipe David Borba Manana 	int prev_cmp;
20509f3a7427SChris Mason 
2051*a4c853afSChenXiaoSong 	might_sleep();
2052*a4c853afSChenXiaoSong 
20536702ed49SChris Mason 	lowest_level = p->lowest_level;
2054323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
205522b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2056eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
205725179201SJosef Bacik 
2058857bc13fSJosef Bacik 	/*
2059857bc13fSJosef Bacik 	 * For now only allow nowait for read only operations.  There's no
2060857bc13fSJosef Bacik 	 * strict reason why we can't, we just only need it for reads so it's
2061857bc13fSJosef Bacik 	 * only implemented for reads.
2062857bc13fSJosef Bacik 	 */
2063857bc13fSJosef Bacik 	ASSERT(!p->nowait || !cow);
2064857bc13fSJosef Bacik 
2065bd681513SChris Mason 	if (ins_len < 0) {
2066925baeddSChris Mason 		lowest_unlock = 2;
206765b51a00SChris Mason 
2068bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2069bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2070bd681513SChris Mason 		 * for those levels as well
2071bd681513SChris Mason 		 */
2072bd681513SChris Mason 		write_lock_level = 2;
2073bd681513SChris Mason 	} else if (ins_len > 0) {
2074bd681513SChris Mason 		/*
2075bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2076bd681513SChris Mason 		 * level 1 so we can update keys
2077bd681513SChris Mason 		 */
2078bd681513SChris Mason 		write_lock_level = 1;
2079bd681513SChris Mason 	}
2080bd681513SChris Mason 
2081bd681513SChris Mason 	if (!cow)
2082bd681513SChris Mason 		write_lock_level = -1;
2083bd681513SChris Mason 
208409a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2085bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2086bd681513SChris Mason 
2087f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2088f7c79f30SChris Mason 
2089d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2090d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
2091857bc13fSJosef Bacik 		if (p->nowait) {
2092857bc13fSJosef Bacik 			if (!down_read_trylock(&fs_info->commit_root_sem))
2093857bc13fSJosef Bacik 				return -EAGAIN;
2094857bc13fSJosef Bacik 		} else {
2095d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
2096d96b3424SFilipe Manana 		}
2097857bc13fSJosef Bacik 	}
2098d96b3424SFilipe Manana 
2099bb803951SChris Mason again:
2100d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
21011fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2102be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2103be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2104be6821f8SFilipe Manana 		goto done;
2105be6821f8SFilipe Manana 	}
2106925baeddSChris Mason 
2107eb60ceacSChris Mason 	while (b) {
2108f624d976SQu Wenruo 		int dec = 0;
2109f624d976SQu Wenruo 
21105f39d397SChris Mason 		level = btrfs_header_level(b);
211165b51a00SChris Mason 
211202217ed2SChris Mason 		if (cow) {
21139ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
21149ea2c7c9SNikolay Borisov 
2115c8c42864SChris Mason 			/*
2116c8c42864SChris Mason 			 * if we don't really need to cow this block
2117c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2118c8c42864SChris Mason 			 * so we test it here
2119c8c42864SChris Mason 			 */
21205963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
212165b51a00SChris Mason 				goto cow_done;
21225d4f98a2SYan Zheng 
2123bd681513SChris Mason 			/*
2124bd681513SChris Mason 			 * must have write locks on this node and the
2125bd681513SChris Mason 			 * parent
2126bd681513SChris Mason 			 */
21275124e00eSJosef Bacik 			if (level > write_lock_level ||
21285124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
21295124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
21305124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2131bd681513SChris Mason 				write_lock_level = level + 1;
2132bd681513SChris Mason 				btrfs_release_path(p);
2133bd681513SChris Mason 				goto again;
2134bd681513SChris Mason 			}
2135bd681513SChris Mason 
21369ea2c7c9SNikolay Borisov 			if (last_level)
21379ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
21389631e4ccSJosef Bacik 						      &b,
21399631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
21409ea2c7c9SNikolay Borisov 			else
214133c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2142e20d96d6SChris Mason 						      p->nodes[level + 1],
21439631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
21449631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
214533c66f43SYan Zheng 			if (err) {
214633c66f43SYan Zheng 				ret = err;
214765b51a00SChris Mason 				goto done;
214854aa1f4dSChris Mason 			}
214902217ed2SChris Mason 		}
215065b51a00SChris Mason cow_done:
2151eb60ceacSChris Mason 		p->nodes[level] = b;
2152b4ce94deSChris Mason 
2153b4ce94deSChris Mason 		/*
2154b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2155b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2156b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2157b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2158b4ce94deSChris Mason 		 *
2159eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2160eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2161eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2162eb653de1SFilipe David Borba Manana 		 * we're operating on.
2163b4ce94deSChris Mason 		 */
2164eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2165eb653de1SFilipe David Borba Manana 			int u = level + 1;
2166eb653de1SFilipe David Borba Manana 
2167eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2168eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2169eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2170eb653de1SFilipe David Borba Manana 			}
2171eb653de1SFilipe David Borba Manana 		}
2172b4ce94deSChris Mason 
2173e2e58d0fSFilipe Manana 		if (level == 0) {
2174109324cfSFilipe Manana 			if (ins_len > 0)
2175e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
2176bd681513SChris Mason 
2177109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2178459931ecSChris Mason 			if (!p->search_for_split)
2179f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
21804b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
218165b51a00SChris Mason 			goto done;
218265b51a00SChris Mason 		}
2183e2e58d0fSFilipe Manana 
2184e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2185e2e58d0fSFilipe Manana 		if (ret < 0)
2186e2e58d0fSFilipe Manana 			goto done;
2187e2e58d0fSFilipe Manana 		prev_cmp = ret;
2188e2e58d0fSFilipe Manana 
2189f624d976SQu Wenruo 		if (ret && slot > 0) {
2190f624d976SQu Wenruo 			dec = 1;
2191f624d976SQu Wenruo 			slot--;
2192f624d976SQu Wenruo 		}
2193f624d976SQu Wenruo 		p->slots[level] = slot;
2194f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2195f624d976SQu Wenruo 					     &write_lock_level);
2196f624d976SQu Wenruo 		if (err == -EAGAIN)
2197f624d976SQu Wenruo 			goto again;
2198f624d976SQu Wenruo 		if (err) {
2199f624d976SQu Wenruo 			ret = err;
2200f624d976SQu Wenruo 			goto done;
2201f624d976SQu Wenruo 		}
2202f624d976SQu Wenruo 		b = p->nodes[level];
2203f624d976SQu Wenruo 		slot = p->slots[level];
2204f624d976SQu Wenruo 
2205f624d976SQu Wenruo 		/*
2206f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2207f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2208f624d976SQu Wenruo 		 * the parent
2209f624d976SQu Wenruo 		 */
2210f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2211f624d976SQu Wenruo 			write_lock_level = level + 1;
2212f624d976SQu Wenruo 			btrfs_release_path(p);
2213f624d976SQu Wenruo 			goto again;
2214f624d976SQu Wenruo 		}
2215f624d976SQu Wenruo 
2216f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2217f624d976SQu Wenruo 			  &write_lock_level);
2218f624d976SQu Wenruo 
2219f624d976SQu Wenruo 		if (level == lowest_level) {
2220f624d976SQu Wenruo 			if (dec)
2221f624d976SQu Wenruo 				p->slots[level]++;
2222f624d976SQu Wenruo 			goto done;
2223f624d976SQu Wenruo 		}
2224f624d976SQu Wenruo 
2225f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2226f624d976SQu Wenruo 		if (err == -EAGAIN)
2227f624d976SQu Wenruo 			goto again;
2228f624d976SQu Wenruo 		if (err) {
2229f624d976SQu Wenruo 			ret = err;
2230f624d976SQu Wenruo 			goto done;
2231f624d976SQu Wenruo 		}
2232f624d976SQu Wenruo 
2233f624d976SQu Wenruo 		if (!p->skip_locking) {
2234f624d976SQu Wenruo 			level = btrfs_header_level(b);
2235b40130b2SJosef Bacik 
2236b40130b2SJosef Bacik 			btrfs_maybe_reset_lockdep_class(root, b);
2237b40130b2SJosef Bacik 
2238f624d976SQu Wenruo 			if (level <= write_lock_level) {
2239f624d976SQu Wenruo 				btrfs_tree_lock(b);
2240f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2241f624d976SQu Wenruo 			} else {
2242857bc13fSJosef Bacik 				if (p->nowait) {
2243857bc13fSJosef Bacik 					if (!btrfs_try_tree_read_lock(b)) {
2244857bc13fSJosef Bacik 						free_extent_buffer(b);
2245857bc13fSJosef Bacik 						ret = -EAGAIN;
2246857bc13fSJosef Bacik 						goto done;
2247857bc13fSJosef Bacik 					}
2248857bc13fSJosef Bacik 				} else {
2249fe596ca3SJosef Bacik 					btrfs_tree_read_lock(b);
2250857bc13fSJosef Bacik 				}
2251f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2252f624d976SQu Wenruo 			}
2253f624d976SQu Wenruo 			p->nodes[level] = b;
2254f624d976SQu Wenruo 		}
225565b51a00SChris Mason 	}
225665b51a00SChris Mason 	ret = 1;
225765b51a00SChris Mason done:
22585f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2259b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2260d96b3424SFilipe Manana 
2261d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2262d96b3424SFilipe Manana 		int ret2;
2263d96b3424SFilipe Manana 
2264d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2265d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2266d96b3424SFilipe Manana 		if (ret2)
2267d96b3424SFilipe Manana 			ret = ret2;
2268d96b3424SFilipe Manana 	}
2269d96b3424SFilipe Manana 
2270be0e5c09SChris Mason 	return ret;
2271be0e5c09SChris Mason }
2272f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2273be0e5c09SChris Mason 
227474123bd7SChris Mason /*
22755d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
22765d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
22775d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
22785d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
22795d9e75c4SJan Schmidt  *
22805d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
22815d9e75c4SJan Schmidt  *
22825d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
22835d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
22845d9e75c4SJan Schmidt  */
2285310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
22865d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
22875d9e75c4SJan Schmidt {
22880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
22895d9e75c4SJan Schmidt 	struct extent_buffer *b;
22905d9e75c4SJan Schmidt 	int slot;
22915d9e75c4SJan Schmidt 	int ret;
22925d9e75c4SJan Schmidt 	int err;
22935d9e75c4SJan Schmidt 	int level;
22945d9e75c4SJan Schmidt 	int lowest_unlock = 1;
22955d9e75c4SJan Schmidt 	u8 lowest_level = 0;
22965d9e75c4SJan Schmidt 
22975d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
22985d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
2299c922b016SStefan Roesch 	ASSERT(!p->nowait);
23005d9e75c4SJan Schmidt 
23015d9e75c4SJan Schmidt 	if (p->search_commit_root) {
23025d9e75c4SJan Schmidt 		BUG_ON(time_seq);
23035d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
23045d9e75c4SJan Schmidt 	}
23055d9e75c4SJan Schmidt 
23065d9e75c4SJan Schmidt again:
2307f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2308315bed43SNikolay Borisov 	if (!b) {
2309315bed43SNikolay Borisov 		ret = -EIO;
2310315bed43SNikolay Borisov 		goto done;
2311315bed43SNikolay Borisov 	}
23125d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
23135d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
23145d9e75c4SJan Schmidt 
23155d9e75c4SJan Schmidt 	while (b) {
2316abe9339dSQu Wenruo 		int dec = 0;
2317abe9339dSQu Wenruo 
23185d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
23195d9e75c4SJan Schmidt 		p->nodes[level] = b;
23205d9e75c4SJan Schmidt 
23215d9e75c4SJan Schmidt 		/*
23225d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
23235d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
23245d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
23255d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
23265d9e75c4SJan Schmidt 		 */
23275d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
23285d9e75c4SJan Schmidt 
2329995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
2330cbca7d59SFilipe Manana 		if (ret < 0)
2331cbca7d59SFilipe Manana 			goto done;
23325d9e75c4SJan Schmidt 
2333abe9339dSQu Wenruo 		if (level == 0) {
2334abe9339dSQu Wenruo 			p->slots[level] = slot;
2335abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2336abe9339dSQu Wenruo 			goto done;
2337abe9339dSQu Wenruo 		}
2338abe9339dSQu Wenruo 
23395d9e75c4SJan Schmidt 		if (ret && slot > 0) {
23405d9e75c4SJan Schmidt 			dec = 1;
2341abe9339dSQu Wenruo 			slot--;
23425d9e75c4SJan Schmidt 		}
23435d9e75c4SJan Schmidt 		p->slots[level] = slot;
23445d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
23455d9e75c4SJan Schmidt 
23465d9e75c4SJan Schmidt 		if (level == lowest_level) {
23475d9e75c4SJan Schmidt 			if (dec)
23485d9e75c4SJan Schmidt 				p->slots[level]++;
23495d9e75c4SJan Schmidt 			goto done;
23505d9e75c4SJan Schmidt 		}
23515d9e75c4SJan Schmidt 
2352abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
23535d9e75c4SJan Schmidt 		if (err == -EAGAIN)
23545d9e75c4SJan Schmidt 			goto again;
23555d9e75c4SJan Schmidt 		if (err) {
23565d9e75c4SJan Schmidt 			ret = err;
23575d9e75c4SJan Schmidt 			goto done;
23585d9e75c4SJan Schmidt 		}
23595d9e75c4SJan Schmidt 
23605d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
23615d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2362f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2363db7f3436SJosef Bacik 		if (!b) {
2364db7f3436SJosef Bacik 			ret = -ENOMEM;
2365db7f3436SJosef Bacik 			goto done;
2366db7f3436SJosef Bacik 		}
23675d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
23685d9e75c4SJan Schmidt 		p->nodes[level] = b;
23695d9e75c4SJan Schmidt 	}
23705d9e75c4SJan Schmidt 	ret = 1;
23715d9e75c4SJan Schmidt done:
23725d9e75c4SJan Schmidt 	if (ret < 0)
23735d9e75c4SJan Schmidt 		btrfs_release_path(p);
23745d9e75c4SJan Schmidt 
23755d9e75c4SJan Schmidt 	return ret;
23765d9e75c4SJan Schmidt }
23775d9e75c4SJan Schmidt 
23785d9e75c4SJan Schmidt /*
23792f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
23802f38b3e1SArne Jansen  * instead the next or previous item should be returned.
23812f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
23822f38b3e1SArne Jansen  * otherwise.
23832f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
23842f38b3e1SArne Jansen  * return the next lower instead.
23852f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
23862f38b3e1SArne Jansen  * return the next higher instead.
23872f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
23882f38b3e1SArne Jansen  * < 0 on error
23892f38b3e1SArne Jansen  */
23902f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2391310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2392310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2393310712b2SOmar Sandoval 			       int return_any)
23942f38b3e1SArne Jansen {
23952f38b3e1SArne Jansen 	int ret;
23962f38b3e1SArne Jansen 	struct extent_buffer *leaf;
23972f38b3e1SArne Jansen 
23982f38b3e1SArne Jansen again:
23992f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
24002f38b3e1SArne Jansen 	if (ret <= 0)
24012f38b3e1SArne Jansen 		return ret;
24022f38b3e1SArne Jansen 	/*
24032f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
24042f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
24052f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
24062f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
24072f38b3e1SArne Jansen 	 * item.
24082f38b3e1SArne Jansen 	 */
24092f38b3e1SArne Jansen 	leaf = p->nodes[0];
24102f38b3e1SArne Jansen 
24112f38b3e1SArne Jansen 	if (find_higher) {
24122f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
24132f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
24142f38b3e1SArne Jansen 			if (ret <= 0)
24152f38b3e1SArne Jansen 				return ret;
24162f38b3e1SArne Jansen 			if (!return_any)
24172f38b3e1SArne Jansen 				return 1;
24182f38b3e1SArne Jansen 			/*
24192f38b3e1SArne Jansen 			 * no higher item found, return the next
24202f38b3e1SArne Jansen 			 * lower instead
24212f38b3e1SArne Jansen 			 */
24222f38b3e1SArne Jansen 			return_any = 0;
24232f38b3e1SArne Jansen 			find_higher = 0;
24242f38b3e1SArne Jansen 			btrfs_release_path(p);
24252f38b3e1SArne Jansen 			goto again;
24262f38b3e1SArne Jansen 		}
24272f38b3e1SArne Jansen 	} else {
24282f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
24292f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2430e6793769SArne Jansen 			if (ret < 0)
24312f38b3e1SArne Jansen 				return ret;
2432e6793769SArne Jansen 			if (!ret) {
243323c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
243423c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
243523c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2436e6793769SArne Jansen 				return 0;
2437e6793769SArne Jansen 			}
24382f38b3e1SArne Jansen 			if (!return_any)
24392f38b3e1SArne Jansen 				return 1;
24402f38b3e1SArne Jansen 			/*
24412f38b3e1SArne Jansen 			 * no lower item found, return the next
24422f38b3e1SArne Jansen 			 * higher instead
24432f38b3e1SArne Jansen 			 */
24442f38b3e1SArne Jansen 			return_any = 0;
24452f38b3e1SArne Jansen 			find_higher = 1;
24462f38b3e1SArne Jansen 			btrfs_release_path(p);
24472f38b3e1SArne Jansen 			goto again;
2448e6793769SArne Jansen 		} else {
24492f38b3e1SArne Jansen 			--p->slots[0];
24502f38b3e1SArne Jansen 		}
24512f38b3e1SArne Jansen 	}
24522f38b3e1SArne Jansen 	return 0;
24532f38b3e1SArne Jansen }
24542f38b3e1SArne Jansen 
24552f38b3e1SArne Jansen /*
24560ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
24570ff40a91SMarcos Paulo de Souza  * was not found.
24580ff40a91SMarcos Paulo de Souza  *
24590ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
24600ff40a91SMarcos Paulo de Souza  */
24610ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
24620ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
24630ff40a91SMarcos Paulo de Souza {
24640ff40a91SMarcos Paulo de Souza 	int ret;
24650ff40a91SMarcos Paulo de Souza 
24660ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
24670ff40a91SMarcos Paulo de Souza 	if (ret > 0)
24680ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
24690ff40a91SMarcos Paulo de Souza 
24700ff40a91SMarcos Paulo de Souza 	if (ret == 0)
24710ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
24720ff40a91SMarcos Paulo de Souza 
24730ff40a91SMarcos Paulo de Souza 	return ret;
24740ff40a91SMarcos Paulo de Souza }
24750ff40a91SMarcos Paulo de Souza 
247643dd529aSDavid Sterba /*
247762142be3SGabriel Niebler  * Search for a valid slot for the given path.
247862142be3SGabriel Niebler  *
247962142be3SGabriel Niebler  * @root:	The root node of the tree.
248062142be3SGabriel Niebler  * @key:	Will contain a valid item if found.
248162142be3SGabriel Niebler  * @path:	The starting point to validate the slot.
248262142be3SGabriel Niebler  *
248362142be3SGabriel Niebler  * Return: 0  if the item is valid
248462142be3SGabriel Niebler  *         1  if not found
248562142be3SGabriel Niebler  *         <0 if error.
248662142be3SGabriel Niebler  */
248762142be3SGabriel Niebler int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
248862142be3SGabriel Niebler 			      struct btrfs_path *path)
248962142be3SGabriel Niebler {
249062142be3SGabriel Niebler 	while (1) {
249162142be3SGabriel Niebler 		int ret;
249262142be3SGabriel Niebler 		const int slot = path->slots[0];
249362142be3SGabriel Niebler 		const struct extent_buffer *leaf = path->nodes[0];
249462142be3SGabriel Niebler 
249562142be3SGabriel Niebler 		/* This is where we start walking the path. */
249662142be3SGabriel Niebler 		if (slot >= btrfs_header_nritems(leaf)) {
249762142be3SGabriel Niebler 			/*
249862142be3SGabriel Niebler 			 * If we've reached the last slot in this leaf we need
249962142be3SGabriel Niebler 			 * to go to the next leaf and reset the path.
250062142be3SGabriel Niebler 			 */
250162142be3SGabriel Niebler 			ret = btrfs_next_leaf(root, path);
250262142be3SGabriel Niebler 			if (ret)
250362142be3SGabriel Niebler 				return ret;
250462142be3SGabriel Niebler 			continue;
250562142be3SGabriel Niebler 		}
250662142be3SGabriel Niebler 		/* Store the found, valid item in @key. */
250762142be3SGabriel Niebler 		btrfs_item_key_to_cpu(leaf, key, slot);
250862142be3SGabriel Niebler 		break;
250962142be3SGabriel Niebler 	}
251062142be3SGabriel Niebler 	return 0;
251162142be3SGabriel Niebler }
251262142be3SGabriel Niebler 
25130ff40a91SMarcos Paulo de Souza /*
251474123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
251574123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
251674123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
251774123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
251874123bd7SChris Mason  * higher levels
2519aa5d6bedSChris Mason  *
252074123bd7SChris Mason  */
2521b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
25225f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2523be0e5c09SChris Mason {
2524be0e5c09SChris Mason 	int i;
25255f39d397SChris Mason 	struct extent_buffer *t;
25260e82bcfeSDavid Sterba 	int ret;
25275f39d397SChris Mason 
2528234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2529be0e5c09SChris Mason 		int tslot = path->slots[i];
25300e82bcfeSDavid Sterba 
2531eb60ceacSChris Mason 		if (!path->nodes[i])
2532be0e5c09SChris Mason 			break;
25335f39d397SChris Mason 		t = path->nodes[i];
2534f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
253533cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
25360e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
25375f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2538d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2539be0e5c09SChris Mason 		if (tslot != 0)
2540be0e5c09SChris Mason 			break;
2541be0e5c09SChris Mason 	}
2542be0e5c09SChris Mason }
2543be0e5c09SChris Mason 
254474123bd7SChris Mason /*
254531840ae1SZheng Yan  * update item key.
254631840ae1SZheng Yan  *
254731840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
254831840ae1SZheng Yan  * that the new key won't break the order
254931840ae1SZheng Yan  */
2550b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2551b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2552310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
255331840ae1SZheng Yan {
255431840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
255531840ae1SZheng Yan 	struct extent_buffer *eb;
255631840ae1SZheng Yan 	int slot;
255731840ae1SZheng Yan 
255831840ae1SZheng Yan 	eb = path->nodes[0];
255931840ae1SZheng Yan 	slot = path->slots[0];
256031840ae1SZheng Yan 	if (slot > 0) {
256131840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
25627c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
25637c15d410SQu Wenruo 			btrfs_crit(fs_info,
25647c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
25657c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
25667c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
25677c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
25687c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
25697c15d410SQu Wenruo 				   new_key->offset);
25707c15d410SQu Wenruo 			btrfs_print_leaf(eb);
25717c15d410SQu Wenruo 			BUG();
25727c15d410SQu Wenruo 		}
257331840ae1SZheng Yan 	}
257431840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
257531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
25767c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
25777c15d410SQu Wenruo 			btrfs_crit(fs_info,
25787c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
25797c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
25807c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
25817c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
25827c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
25837c15d410SQu Wenruo 				   new_key->offset);
25847c15d410SQu Wenruo 			btrfs_print_leaf(eb);
25857c15d410SQu Wenruo 			BUG();
25867c15d410SQu Wenruo 		}
258731840ae1SZheng Yan 	}
258831840ae1SZheng Yan 
258931840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
259031840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
259131840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
259231840ae1SZheng Yan 	if (slot == 0)
2593b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
259431840ae1SZheng Yan }
259531840ae1SZheng Yan 
259631840ae1SZheng Yan /*
2597d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2598d16c702fSQu Wenruo  *
2599d16c702fSQu Wenruo  * Return true if something is wrong.
2600d16c702fSQu Wenruo  * Return false if everything is fine.
2601d16c702fSQu Wenruo  *
2602d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2603d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2604d16c702fSQu Wenruo  *
2605d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2606d16c702fSQu Wenruo  * --------------------------------------------------------------
2607d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2608d16c702fSQu Wenruo  *
2609d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2610d16c702fSQu Wenruo  * key in leaf @right is 7.
2611d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2612d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2613d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2614d16c702fSQu Wenruo  * key of @right.
2615d16c702fSQu Wenruo  */
2616d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2617d16c702fSQu Wenruo 			       struct extent_buffer *right)
2618d16c702fSQu Wenruo {
2619d16c702fSQu Wenruo 	struct btrfs_key left_last;
2620d16c702fSQu Wenruo 	struct btrfs_key right_first;
2621d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2622d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2623d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2624d16c702fSQu Wenruo 
2625d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2626d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2627d16c702fSQu Wenruo 		return false;
2628d16c702fSQu Wenruo 
2629d16c702fSQu Wenruo 	if (level) {
2630d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2631d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2632d16c702fSQu Wenruo 	} else {
2633d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2634d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2635d16c702fSQu Wenruo 	}
2636d16c702fSQu Wenruo 
2637d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2638d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2639d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2640d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2641d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2642d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2643d16c702fSQu Wenruo 		return true;
2644d16c702fSQu Wenruo 	}
2645d16c702fSQu Wenruo 	return false;
2646d16c702fSQu Wenruo }
2647d16c702fSQu Wenruo 
2648d16c702fSQu Wenruo /*
264974123bd7SChris Mason  * try to push data from one node into the next node left in the
265079f95c82SChris Mason  * tree.
2651aa5d6bedSChris Mason  *
2652aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2653aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
265474123bd7SChris Mason  */
265598ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
26562ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2657971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2658be0e5c09SChris Mason {
2659d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2660be0e5c09SChris Mason 	int push_items = 0;
2661bb803951SChris Mason 	int src_nritems;
2662bb803951SChris Mason 	int dst_nritems;
2663aa5d6bedSChris Mason 	int ret = 0;
2664be0e5c09SChris Mason 
26655f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
26665f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
26670b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
26687bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
26697bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
267054aa1f4dSChris Mason 
2671bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2672971a1f66SChris Mason 		return 1;
2673971a1f66SChris Mason 
2674d397712bSChris Mason 	if (push_items <= 0)
2675be0e5c09SChris Mason 		return 1;
2676be0e5c09SChris Mason 
2677bce4eae9SChris Mason 	if (empty) {
2678971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2679bce4eae9SChris Mason 		if (push_items < src_nritems) {
2680bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2681bce4eae9SChris Mason 			 * we aren't going to empty it
2682bce4eae9SChris Mason 			 */
2683bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2684bce4eae9SChris Mason 				if (push_items <= 8)
2685bce4eae9SChris Mason 					return 1;
2686bce4eae9SChris Mason 				push_items -= 8;
2687bce4eae9SChris Mason 			}
2688bce4eae9SChris Mason 		}
2689bce4eae9SChris Mason 	} else
2690bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
269179f95c82SChris Mason 
2692d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2693d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2694d16c702fSQu Wenruo 		ret = -EUCLEAN;
2695d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2696d16c702fSQu Wenruo 		return ret;
2697d16c702fSQu Wenruo 	}
2698f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
26995de865eeSFilipe David Borba Manana 	if (ret) {
270066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
27015de865eeSFilipe David Borba Manana 		return ret;
27025de865eeSFilipe David Borba Manana 	}
27035f39d397SChris Mason 	copy_extent_buffer(dst, src,
2704e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, dst_nritems),
2705e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, 0),
2706123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
27075f39d397SChris Mason 
2708bb803951SChris Mason 	if (push_items < src_nritems) {
270957911b8bSJan Schmidt 		/*
2710f3a84ccdSFilipe Manana 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2711f3a84ccdSFilipe Manana 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
271257911b8bSJan Schmidt 		 */
2713e23efd8eSJosef Bacik 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(src, 0),
2714e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(src, push_items),
2715e2fa7227SChris Mason 				      (src_nritems - push_items) *
2716123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2717bb803951SChris Mason 	}
27185f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
27195f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
27205f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
27215f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
272231840ae1SZheng Yan 
2723bb803951SChris Mason 	return ret;
2724be0e5c09SChris Mason }
2725be0e5c09SChris Mason 
272697571fd0SChris Mason /*
272779f95c82SChris Mason  * try to push data from one node into the next node right in the
272879f95c82SChris Mason  * tree.
272979f95c82SChris Mason  *
273079f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
273179f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
273279f95c82SChris Mason  *
273379f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
273479f95c82SChris Mason  */
27355f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
27365f39d397SChris Mason 			      struct extent_buffer *dst,
27375f39d397SChris Mason 			      struct extent_buffer *src)
273879f95c82SChris Mason {
273955d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
274079f95c82SChris Mason 	int push_items = 0;
274179f95c82SChris Mason 	int max_push;
274279f95c82SChris Mason 	int src_nritems;
274379f95c82SChris Mason 	int dst_nritems;
274479f95c82SChris Mason 	int ret = 0;
274579f95c82SChris Mason 
27467bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
27477bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
27487bb86316SChris Mason 
27495f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
27505f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
27510b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2752d397712bSChris Mason 	if (push_items <= 0)
275379f95c82SChris Mason 		return 1;
2754bce4eae9SChris Mason 
2755d397712bSChris Mason 	if (src_nritems < 4)
2756bce4eae9SChris Mason 		return 1;
275779f95c82SChris Mason 
275879f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
275979f95c82SChris Mason 	/* don't try to empty the node */
2760d397712bSChris Mason 	if (max_push >= src_nritems)
276179f95c82SChris Mason 		return 1;
2762252c38f0SYan 
276379f95c82SChris Mason 	if (max_push < push_items)
276479f95c82SChris Mason 		push_items = max_push;
276579f95c82SChris Mason 
2766d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2767d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2768d16c702fSQu Wenruo 		ret = -EUCLEAN;
2769d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2770d16c702fSQu Wenruo 		return ret;
2771d16c702fSQu Wenruo 	}
2772f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2773bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
2774e23efd8eSJosef Bacik 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(dst, push_items),
2775e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(dst, 0),
27765f39d397SChris Mason 				      (dst_nritems) *
27775f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2778d6025579SChris Mason 
2779f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2780ed874f0dSDavid Sterba 					 push_items);
27815de865eeSFilipe David Borba Manana 	if (ret) {
278266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
27835de865eeSFilipe David Borba Manana 		return ret;
27845de865eeSFilipe David Borba Manana 	}
27855f39d397SChris Mason 	copy_extent_buffer(dst, src,
2786e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, 0),
2787e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, src_nritems - push_items),
2788123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
278979f95c82SChris Mason 
27905f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
27915f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
279279f95c82SChris Mason 
27935f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
27945f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
279531840ae1SZheng Yan 
279679f95c82SChris Mason 	return ret;
279779f95c82SChris Mason }
279879f95c82SChris Mason 
279979f95c82SChris Mason /*
280097571fd0SChris Mason  * helper function to insert a new root level in the tree.
280197571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
280297571fd0SChris Mason  * point to the existing root
2803aa5d6bedSChris Mason  *
2804aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
280597571fd0SChris Mason  */
2806d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
28075f39d397SChris Mason 			   struct btrfs_root *root,
2808fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
280974123bd7SChris Mason {
28100b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
28117bb86316SChris Mason 	u64 lower_gen;
28125f39d397SChris Mason 	struct extent_buffer *lower;
28135f39d397SChris Mason 	struct extent_buffer *c;
2814925baeddSChris Mason 	struct extent_buffer *old;
28155f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2816d9d19a01SDavid Sterba 	int ret;
28175c680ed6SChris Mason 
28185c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
28195c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
28205c680ed6SChris Mason 
28217bb86316SChris Mason 	lower = path->nodes[level-1];
28227bb86316SChris Mason 	if (level == 1)
28237bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
28247bb86316SChris Mason 	else
28257bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
28267bb86316SChris Mason 
282779bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
282879bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2829cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
28305f39d397SChris Mason 	if (IS_ERR(c))
28315f39d397SChris Mason 		return PTR_ERR(c);
2832925baeddSChris Mason 
28330b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2834f0486c68SYan, Zheng 
28355f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
28365f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2837db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
28387bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
283931840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
28407bb86316SChris Mason 
28417bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
28425f39d397SChris Mason 
28435f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2844d5719762SChris Mason 
2845925baeddSChris Mason 	old = root->node;
2846406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2847d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2848240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2849925baeddSChris Mason 
2850925baeddSChris Mason 	/* the super has an extra ref to root->node */
2851925baeddSChris Mason 	free_extent_buffer(old);
2852925baeddSChris Mason 
28530b86a832SChris Mason 	add_root_to_dirty_list(root);
285467439dadSDavid Sterba 	atomic_inc(&c->refs);
28555f39d397SChris Mason 	path->nodes[level] = c;
2856ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
285774123bd7SChris Mason 	path->slots[level] = 0;
285874123bd7SChris Mason 	return 0;
285974123bd7SChris Mason }
28605c680ed6SChris Mason 
28615c680ed6SChris Mason /*
28625c680ed6SChris Mason  * worker function to insert a single pointer in a node.
28635c680ed6SChris Mason  * the node should have enough room for the pointer already
286497571fd0SChris Mason  *
28655c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
28665c680ed6SChris Mason  * blocknr is the block the key points to.
28675c680ed6SChris Mason  */
2868143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
28696ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2870143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2871c3e06965SJan Schmidt 		       int slot, int level)
28725c680ed6SChris Mason {
28735f39d397SChris Mason 	struct extent_buffer *lower;
28745c680ed6SChris Mason 	int nritems;
2875f3ea38daSJan Schmidt 	int ret;
28765c680ed6SChris Mason 
28775c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
287849d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
28795f39d397SChris Mason 	lower = path->nodes[level];
28805f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2881c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
28826ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
288374123bd7SChris Mason 	if (slot != nritems) {
2884bf1d3425SDavid Sterba 		if (level) {
2885f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2886f3a84ccdSFilipe Manana 					slot, nritems - slot);
2887bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2888bf1d3425SDavid Sterba 		}
28895f39d397SChris Mason 		memmove_extent_buffer(lower,
2890e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot + 1),
2891e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot),
2892123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
289374123bd7SChris Mason 	}
2894c3e06965SJan Schmidt 	if (level) {
2895f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
289633cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_ADD);
2897f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2898f3ea38daSJan Schmidt 	}
28995f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2900db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
290174493f7aSChris Mason 	WARN_ON(trans->transid == 0);
290274493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
29035f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
29045f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
290574123bd7SChris Mason }
290674123bd7SChris Mason 
290797571fd0SChris Mason /*
290897571fd0SChris Mason  * split the node at the specified level in path in two.
290997571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
291097571fd0SChris Mason  *
291197571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
291297571fd0SChris Mason  * left and right, if either one works, it returns right away.
2913aa5d6bedSChris Mason  *
2914aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
291597571fd0SChris Mason  */
2916e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
2917e02119d5SChris Mason 			       struct btrfs_root *root,
2918e02119d5SChris Mason 			       struct btrfs_path *path, int level)
2919be0e5c09SChris Mason {
29200b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29215f39d397SChris Mason 	struct extent_buffer *c;
29225f39d397SChris Mason 	struct extent_buffer *split;
29235f39d397SChris Mason 	struct btrfs_disk_key disk_key;
2924be0e5c09SChris Mason 	int mid;
29255c680ed6SChris Mason 	int ret;
29267518a238SChris Mason 	u32 c_nritems;
2927be0e5c09SChris Mason 
29285f39d397SChris Mason 	c = path->nodes[level];
29297bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
29305f39d397SChris Mason 	if (c == root->node) {
2931d9abbf1cSJan Schmidt 		/*
293290f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
293390f8d62eSJan Schmidt 		 *
2934fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
293590f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
293690f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
2937f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2938f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
2939f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
2940d9abbf1cSJan Schmidt 		 */
2941fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
29425c680ed6SChris Mason 		if (ret)
29435c680ed6SChris Mason 			return ret;
2944b3612421SChris Mason 	} else {
2945e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
29465f39d397SChris Mason 		c = path->nodes[level];
29475f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
29480b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2949e66f709bSChris Mason 			return 0;
295054aa1f4dSChris Mason 		if (ret < 0)
295154aa1f4dSChris Mason 			return ret;
29525c680ed6SChris Mason 	}
2953e66f709bSChris Mason 
29545f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
29555d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
29565d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
29577bb86316SChris Mason 
295879bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
295979bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
296079bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
29615f39d397SChris Mason 	if (IS_ERR(split))
29625f39d397SChris Mason 		return PTR_ERR(split);
296354aa1f4dSChris Mason 
29640b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2965bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
29665f39d397SChris Mason 
2967f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
29685de865eeSFilipe David Borba Manana 	if (ret) {
296966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
29705de865eeSFilipe David Borba Manana 		return ret;
29715de865eeSFilipe David Borba Manana 	}
29725f39d397SChris Mason 	copy_extent_buffer(split, c,
2973e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(split, 0),
2974e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(c, mid),
2975123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
29765f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
29775f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
2978aa5d6bedSChris Mason 
29795f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
29805f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
29815f39d397SChris Mason 
29826ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
2983c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
2984aa5d6bedSChris Mason 
29855de08d7dSChris Mason 	if (path->slots[level] >= mid) {
29865c680ed6SChris Mason 		path->slots[level] -= mid;
2987925baeddSChris Mason 		btrfs_tree_unlock(c);
29885f39d397SChris Mason 		free_extent_buffer(c);
29895f39d397SChris Mason 		path->nodes[level] = split;
29905c680ed6SChris Mason 		path->slots[level + 1] += 1;
2991eb60ceacSChris Mason 	} else {
2992925baeddSChris Mason 		btrfs_tree_unlock(split);
29935f39d397SChris Mason 		free_extent_buffer(split);
2994be0e5c09SChris Mason 	}
2995d5286a92SNikolay Borisov 	return 0;
2996be0e5c09SChris Mason }
2997be0e5c09SChris Mason 
299874123bd7SChris Mason /*
299974123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
300074123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
300174123bd7SChris Mason  * space used both by the item structs and the item data
300274123bd7SChris Mason  */
30035f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3004be0e5c09SChris Mason {
3005be0e5c09SChris Mason 	int data_len;
30065f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3007d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3008be0e5c09SChris Mason 
3009be0e5c09SChris Mason 	if (!nr)
3010be0e5c09SChris Mason 		return 0;
30113212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
30123212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
30130783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3014d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3015be0e5c09SChris Mason 	return data_len;
3016be0e5c09SChris Mason }
3017be0e5c09SChris Mason 
301874123bd7SChris Mason /*
3019d4dbff95SChris Mason  * The space between the end of the leaf items and
3020d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3021d4dbff95SChris Mason  * the leaf has left for both items and data
3022d4dbff95SChris Mason  */
3023e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
3024d4dbff95SChris Mason {
3025e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
30265f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
30275f39d397SChris Mason 	int ret;
30280b246afaSJeff Mahoney 
30290b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
30305f39d397SChris Mason 	if (ret < 0) {
30310b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3032efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3033da17066cSJeff Mahoney 			   ret,
30340b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
30355f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
30365f39d397SChris Mason 	}
30375f39d397SChris Mason 	return ret;
3038d4dbff95SChris Mason }
3039d4dbff95SChris Mason 
304099d8f83cSChris Mason /*
304199d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
304299d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
304399d8f83cSChris Mason  */
3044f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
304544871b1bSChris Mason 				      int data_size, int empty,
304644871b1bSChris Mason 				      struct extent_buffer *right,
304799d8f83cSChris Mason 				      int free_space, u32 left_nritems,
304899d8f83cSChris Mason 				      u32 min_slot)
304900ec4c51SChris Mason {
3050f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
30515f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
305244871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3053cfed81a0SChris Mason 	struct btrfs_map_token token;
30545f39d397SChris Mason 	struct btrfs_disk_key disk_key;
305500ec4c51SChris Mason 	int slot;
305634a38218SChris Mason 	u32 i;
305700ec4c51SChris Mason 	int push_space = 0;
305800ec4c51SChris Mason 	int push_items = 0;
305934a38218SChris Mason 	u32 nr;
30607518a238SChris Mason 	u32 right_nritems;
30615f39d397SChris Mason 	u32 data_end;
3062db94535dSChris Mason 	u32 this_item_size;
306300ec4c51SChris Mason 
306434a38218SChris Mason 	if (empty)
306534a38218SChris Mason 		nr = 0;
306634a38218SChris Mason 	else
306799d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
306834a38218SChris Mason 
306931840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
307087b29b20SYan Zheng 		push_space += data_size;
307131840ae1SZheng Yan 
307244871b1bSChris Mason 	slot = path->slots[1];
307334a38218SChris Mason 	i = left_nritems - 1;
307434a38218SChris Mason 	while (i >= nr) {
307531840ae1SZheng Yan 		if (!empty && push_items > 0) {
307631840ae1SZheng Yan 			if (path->slots[0] > i)
307731840ae1SZheng Yan 				break;
307831840ae1SZheng Yan 			if (path->slots[0] == i) {
3079e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3080e902baacSDavid Sterba 
308131840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
308231840ae1SZheng Yan 					break;
308331840ae1SZheng Yan 			}
308431840ae1SZheng Yan 		}
308531840ae1SZheng Yan 
308600ec4c51SChris Mason 		if (path->slots[0] == i)
308787b29b20SYan Zheng 			push_space += data_size;
3088db94535dSChris Mason 
30893212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
309074794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
309174794207SJosef Bacik 		    push_space > free_space)
309200ec4c51SChris Mason 			break;
309331840ae1SZheng Yan 
309400ec4c51SChris Mason 		push_items++;
309574794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
309634a38218SChris Mason 		if (i == 0)
309734a38218SChris Mason 			break;
309834a38218SChris Mason 		i--;
3099db94535dSChris Mason 	}
31005f39d397SChris Mason 
3101925baeddSChris Mason 	if (push_items == 0)
3102925baeddSChris Mason 		goto out_unlock;
31035f39d397SChris Mason 
31046c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
31055f39d397SChris Mason 
310600ec4c51SChris Mason 	/* push left to right */
31075f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
310834a38218SChris Mason 
3109dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
31108f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
31115f39d397SChris Mason 
311200ec4c51SChris Mason 	/* make room in the right data area */
31138f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
3114637e3b48SJosef Bacik 	memmove_leaf_data(right, data_end - push_space, data_end,
31150b246afaSJeff Mahoney 			  BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
31165f39d397SChris Mason 
311700ec4c51SChris Mason 	/* copy from the left data area */
3118637e3b48SJosef Bacik 	copy_leaf_data(right, left, BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3119637e3b48SJosef Bacik 		       leaf_data_end(left), push_space);
31205f39d397SChris Mason 
3121637e3b48SJosef Bacik 	memmove_leaf_items(right, push_items, 0, right_nritems);
31225f39d397SChris Mason 
312300ec4c51SChris Mason 	/* copy the items from left to right */
3124637e3b48SJosef Bacik 	copy_leaf_items(right, left, 0, left_nritems - push_items, push_items);
312500ec4c51SChris Mason 
312600ec4c51SChris Mason 	/* update the item pointers */
3127c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
31287518a238SChris Mason 	right_nritems += push_items;
31295f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
31300b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
31317518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
31323212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
31333212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3134db94535dSChris Mason 	}
3135db94535dSChris Mason 
31367518a238SChris Mason 	left_nritems -= push_items;
31375f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
313800ec4c51SChris Mason 
313934a38218SChris Mason 	if (left_nritems)
31405f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3141f0486c68SYan, Zheng 	else
31426a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3143f0486c68SYan, Zheng 
31445f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3145a429e513SChris Mason 
31465f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
31475f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3148d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
314902217ed2SChris Mason 
315000ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
31517518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
31527518a238SChris Mason 		path->slots[0] -= left_nritems;
3153925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
31546a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3155925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
31565f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
31575f39d397SChris Mason 		path->nodes[0] = right;
315800ec4c51SChris Mason 		path->slots[1] += 1;
315900ec4c51SChris Mason 	} else {
3160925baeddSChris Mason 		btrfs_tree_unlock(right);
31615f39d397SChris Mason 		free_extent_buffer(right);
316200ec4c51SChris Mason 	}
316300ec4c51SChris Mason 	return 0;
3164925baeddSChris Mason 
3165925baeddSChris Mason out_unlock:
3166925baeddSChris Mason 	btrfs_tree_unlock(right);
3167925baeddSChris Mason 	free_extent_buffer(right);
3168925baeddSChris Mason 	return 1;
316900ec4c51SChris Mason }
3170925baeddSChris Mason 
317100ec4c51SChris Mason /*
317244871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
317374123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
317444871b1bSChris Mason  *
317544871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
317644871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
317799d8f83cSChris Mason  *
317899d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
317999d8f83cSChris Mason  * push any slot lower than min_slot
318074123bd7SChris Mason  */
318144871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
318299d8f83cSChris Mason 			   *root, struct btrfs_path *path,
318399d8f83cSChris Mason 			   int min_data_size, int data_size,
318499d8f83cSChris Mason 			   int empty, u32 min_slot)
3185be0e5c09SChris Mason {
318644871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
318744871b1bSChris Mason 	struct extent_buffer *right;
318844871b1bSChris Mason 	struct extent_buffer *upper;
318944871b1bSChris Mason 	int slot;
319044871b1bSChris Mason 	int free_space;
319144871b1bSChris Mason 	u32 left_nritems;
319244871b1bSChris Mason 	int ret;
319344871b1bSChris Mason 
319444871b1bSChris Mason 	if (!path->nodes[1])
319544871b1bSChris Mason 		return 1;
319644871b1bSChris Mason 
319744871b1bSChris Mason 	slot = path->slots[1];
319844871b1bSChris Mason 	upper = path->nodes[1];
319944871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
320044871b1bSChris Mason 		return 1;
320144871b1bSChris Mason 
320249d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
320344871b1bSChris Mason 
32044b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3205fb770ae4SLiu Bo 	/*
3206fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3207fb770ae4SLiu Bo 	 * no big deal, just return.
3208fb770ae4SLiu Bo 	 */
3209fb770ae4SLiu Bo 	if (IS_ERR(right))
321091ca338dSTsutomu Itoh 		return 1;
321191ca338dSTsutomu Itoh 
3212bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
321344871b1bSChris Mason 
3214e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
321544871b1bSChris Mason 	if (free_space < data_size)
321644871b1bSChris Mason 		goto out_unlock;
321744871b1bSChris Mason 
321844871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3219bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
322044871b1bSChris Mason 	if (ret)
322144871b1bSChris Mason 		goto out_unlock;
322244871b1bSChris Mason 
322344871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
322444871b1bSChris Mason 	if (left_nritems == 0)
322544871b1bSChris Mason 		goto out_unlock;
322644871b1bSChris Mason 
3227d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3228d16c702fSQu Wenruo 		ret = -EUCLEAN;
3229d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3230d16c702fSQu Wenruo 		free_extent_buffer(right);
3231d16c702fSQu Wenruo 		return ret;
3232d16c702fSQu Wenruo 	}
32332ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
32342ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
32352ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
32362ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
323752042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
32382ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
32392ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
32402ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
32412ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
32422ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
32432ef1fed2SFilipe David Borba Manana 		return 0;
32442ef1fed2SFilipe David Borba Manana 	}
32452ef1fed2SFilipe David Borba Manana 
3246f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
324799d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
324844871b1bSChris Mason out_unlock:
324944871b1bSChris Mason 	btrfs_tree_unlock(right);
325044871b1bSChris Mason 	free_extent_buffer(right);
325144871b1bSChris Mason 	return 1;
325244871b1bSChris Mason }
325344871b1bSChris Mason 
325444871b1bSChris Mason /*
325544871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
325644871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
325799d8f83cSChris Mason  *
325899d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
325999d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
326099d8f83cSChris Mason  * items
326144871b1bSChris Mason  */
32628087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
326344871b1bSChris Mason 				     int empty, struct extent_buffer *left,
326499d8f83cSChris Mason 				     int free_space, u32 right_nritems,
326599d8f83cSChris Mason 				     u32 max_slot)
326644871b1bSChris Mason {
32678087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
32685f39d397SChris Mason 	struct btrfs_disk_key disk_key;
32695f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3270be0e5c09SChris Mason 	int i;
3271be0e5c09SChris Mason 	int push_space = 0;
3272be0e5c09SChris Mason 	int push_items = 0;
32737518a238SChris Mason 	u32 old_left_nritems;
327434a38218SChris Mason 	u32 nr;
3275aa5d6bedSChris Mason 	int ret = 0;
3276db94535dSChris Mason 	u32 this_item_size;
3277db94535dSChris Mason 	u32 old_left_item_size;
3278cfed81a0SChris Mason 	struct btrfs_map_token token;
3279cfed81a0SChris Mason 
328034a38218SChris Mason 	if (empty)
328199d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
328234a38218SChris Mason 	else
328399d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
328434a38218SChris Mason 
328534a38218SChris Mason 	for (i = 0; i < nr; i++) {
328631840ae1SZheng Yan 		if (!empty && push_items > 0) {
328731840ae1SZheng Yan 			if (path->slots[0] < i)
328831840ae1SZheng Yan 				break;
328931840ae1SZheng Yan 			if (path->slots[0] == i) {
3290e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3291e902baacSDavid Sterba 
329231840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
329331840ae1SZheng Yan 					break;
329431840ae1SZheng Yan 			}
329531840ae1SZheng Yan 		}
329631840ae1SZheng Yan 
3297be0e5c09SChris Mason 		if (path->slots[0] == i)
329887b29b20SYan Zheng 			push_space += data_size;
3299db94535dSChris Mason 
33003212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
330174794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
330274794207SJosef Bacik 		    free_space)
3303be0e5c09SChris Mason 			break;
3304db94535dSChris Mason 
3305be0e5c09SChris Mason 		push_items++;
330674794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3307be0e5c09SChris Mason 	}
3308db94535dSChris Mason 
3309be0e5c09SChris Mason 	if (push_items == 0) {
3310925baeddSChris Mason 		ret = 1;
3311925baeddSChris Mason 		goto out;
3312be0e5c09SChris Mason 	}
3313fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
33145f39d397SChris Mason 
3315be0e5c09SChris Mason 	/* push data from right to left */
3316637e3b48SJosef Bacik 	copy_leaf_items(left, right, btrfs_header_nritems(left), 0, push_items);
33175f39d397SChris Mason 
33180b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
33193212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
33205f39d397SChris Mason 
3321637e3b48SJosef Bacik 	copy_leaf_data(left, right, leaf_data_end(left) - push_space,
3322637e3b48SJosef Bacik 		       btrfs_item_offset(right, push_items - 1), push_space);
33235f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
332487b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3325eb60ceacSChris Mason 
3326c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
33273212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3328be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
33295f39d397SChris Mason 		u32 ioff;
3330db94535dSChris Mason 
33313212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
33323212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3333cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3334be0e5c09SChris Mason 	}
33355f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3336be0e5c09SChris Mason 
3337be0e5c09SChris Mason 	/* fixup right node */
333831b1a2bdSJulia Lawall 	if (push_items > right_nritems)
333931b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3340d397712bSChris Mason 		       right_nritems);
334134a38218SChris Mason 
334234a38218SChris Mason 	if (push_items < right_nritems) {
33433212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
33448f881e8cSDavid Sterba 						  leaf_data_end(right);
3345637e3b48SJosef Bacik 		memmove_leaf_data(right,
33460b246afaSJeff Mahoney 				  BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
33478f881e8cSDavid Sterba 				  leaf_data_end(right), push_space);
33485f39d397SChris Mason 
3349637e3b48SJosef Bacik 		memmove_leaf_items(right, 0, push_items,
3350637e3b48SJosef Bacik 				   btrfs_header_nritems(right) - push_items);
335134a38218SChris Mason 	}
3352c82f823cSDavid Sterba 
3353c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3354eef1c494SYan 	right_nritems -= push_items;
3355eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
33560b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
33575f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
33583212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
33593212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3360db94535dSChris Mason 	}
3361eb60ceacSChris Mason 
33625f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
336334a38218SChris Mason 	if (right_nritems)
33645f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3365f0486c68SYan, Zheng 	else
33666a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3367098f59c2SChris Mason 
33685f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3369b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3370be0e5c09SChris Mason 
3371be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3372be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3373be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3374925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
33755f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
33765f39d397SChris Mason 		path->nodes[0] = left;
3377be0e5c09SChris Mason 		path->slots[1] -= 1;
3378be0e5c09SChris Mason 	} else {
3379925baeddSChris Mason 		btrfs_tree_unlock(left);
33805f39d397SChris Mason 		free_extent_buffer(left);
3381be0e5c09SChris Mason 		path->slots[0] -= push_items;
3382be0e5c09SChris Mason 	}
3383eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3384aa5d6bedSChris Mason 	return ret;
3385925baeddSChris Mason out:
3386925baeddSChris Mason 	btrfs_tree_unlock(left);
3387925baeddSChris Mason 	free_extent_buffer(left);
3388925baeddSChris Mason 	return ret;
3389be0e5c09SChris Mason }
3390be0e5c09SChris Mason 
339174123bd7SChris Mason /*
339244871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
339344871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
339499d8f83cSChris Mason  *
339599d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
339699d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
339799d8f83cSChris Mason  * items
339844871b1bSChris Mason  */
339944871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
340099d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
340199d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
340244871b1bSChris Mason {
340344871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
340444871b1bSChris Mason 	struct extent_buffer *left;
340544871b1bSChris Mason 	int slot;
340644871b1bSChris Mason 	int free_space;
340744871b1bSChris Mason 	u32 right_nritems;
340844871b1bSChris Mason 	int ret = 0;
340944871b1bSChris Mason 
341044871b1bSChris Mason 	slot = path->slots[1];
341144871b1bSChris Mason 	if (slot == 0)
341244871b1bSChris Mason 		return 1;
341344871b1bSChris Mason 	if (!path->nodes[1])
341444871b1bSChris Mason 		return 1;
341544871b1bSChris Mason 
341644871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
341744871b1bSChris Mason 	if (right_nritems == 0)
341844871b1bSChris Mason 		return 1;
341944871b1bSChris Mason 
342049d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
342144871b1bSChris Mason 
34224b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3423fb770ae4SLiu Bo 	/*
3424fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3425fb770ae4SLiu Bo 	 * no big deal, just return.
3426fb770ae4SLiu Bo 	 */
3427fb770ae4SLiu Bo 	if (IS_ERR(left))
342891ca338dSTsutomu Itoh 		return 1;
342991ca338dSTsutomu Itoh 
3430bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
343144871b1bSChris Mason 
3432e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
343344871b1bSChris Mason 	if (free_space < data_size) {
343444871b1bSChris Mason 		ret = 1;
343544871b1bSChris Mason 		goto out;
343644871b1bSChris Mason 	}
343744871b1bSChris Mason 
343844871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
34399631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3440bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
344144871b1bSChris Mason 	if (ret) {
344244871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
344379787eaaSJeff Mahoney 		if (ret == -ENOSPC)
344444871b1bSChris Mason 			ret = 1;
344544871b1bSChris Mason 		goto out;
344644871b1bSChris Mason 	}
344744871b1bSChris Mason 
3448d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3449d16c702fSQu Wenruo 		ret = -EUCLEAN;
3450d16c702fSQu Wenruo 		goto out;
3451d16c702fSQu Wenruo 	}
34528087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
345399d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
345499d8f83cSChris Mason 			       max_slot);
345544871b1bSChris Mason out:
345644871b1bSChris Mason 	btrfs_tree_unlock(left);
345744871b1bSChris Mason 	free_extent_buffer(left);
345844871b1bSChris Mason 	return ret;
345944871b1bSChris Mason }
346044871b1bSChris Mason 
346144871b1bSChris Mason /*
346274123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
346374123bd7SChris Mason  * available for the resulting leaf level of the path.
346474123bd7SChris Mason  */
3465143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
346644871b1bSChris Mason 				    struct btrfs_path *path,
346744871b1bSChris Mason 				    struct extent_buffer *l,
346844871b1bSChris Mason 				    struct extent_buffer *right,
346944871b1bSChris Mason 				    int slot, int mid, int nritems)
3470be0e5c09SChris Mason {
347194f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3472be0e5c09SChris Mason 	int data_copy_size;
3473be0e5c09SChris Mason 	int rt_data_off;
3474be0e5c09SChris Mason 	int i;
3475d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3476cfed81a0SChris Mason 	struct btrfs_map_token token;
3477cfed81a0SChris Mason 
34785f39d397SChris Mason 	nritems = nritems - mid;
34795f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3480dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
34815f39d397SChris Mason 
3482637e3b48SJosef Bacik 	copy_leaf_items(right, l, 0, mid, nritems);
34835f39d397SChris Mason 
3484637e3b48SJosef Bacik 	copy_leaf_data(right, l, BTRFS_LEAF_DATA_SIZE(fs_info) - data_copy_size,
34858f881e8cSDavid Sterba 		       leaf_data_end(l), data_copy_size);
348674123bd7SChris Mason 
3487dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
34885f39d397SChris Mason 
3489c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
34905f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3491db94535dSChris Mason 		u32 ioff;
3492db94535dSChris Mason 
34933212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
34943212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
34950783fcfcSChris Mason 	}
349674123bd7SChris Mason 
34975f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
34985f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
34996ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
35005f39d397SChris Mason 
35015f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
35025f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3503eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
35045f39d397SChris Mason 
3505be0e5c09SChris Mason 	if (mid <= slot) {
3506925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
35075f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
35085f39d397SChris Mason 		path->nodes[0] = right;
3509be0e5c09SChris Mason 		path->slots[0] -= mid;
3510be0e5c09SChris Mason 		path->slots[1] += 1;
3511925baeddSChris Mason 	} else {
3512925baeddSChris Mason 		btrfs_tree_unlock(right);
35135f39d397SChris Mason 		free_extent_buffer(right);
3514925baeddSChris Mason 	}
35155f39d397SChris Mason 
3516eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
351744871b1bSChris Mason }
351844871b1bSChris Mason 
351944871b1bSChris Mason /*
352099d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
352199d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
352299d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
352399d8f83cSChris Mason  *          A                 B                 C
352499d8f83cSChris Mason  *
352599d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
352699d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
352799d8f83cSChris Mason  * completely.
352899d8f83cSChris Mason  */
352999d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
353099d8f83cSChris Mason 					  struct btrfs_root *root,
353199d8f83cSChris Mason 					  struct btrfs_path *path,
353299d8f83cSChris Mason 					  int data_size)
353399d8f83cSChris Mason {
353499d8f83cSChris Mason 	int ret;
353599d8f83cSChris Mason 	int progress = 0;
353699d8f83cSChris Mason 	int slot;
353799d8f83cSChris Mason 	u32 nritems;
35385a4267caSFilipe David Borba Manana 	int space_needed = data_size;
353999d8f83cSChris Mason 
354099d8f83cSChris Mason 	slot = path->slots[0];
35415a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3542e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
354399d8f83cSChris Mason 
354499d8f83cSChris Mason 	/*
354599d8f83cSChris Mason 	 * try to push all the items after our slot into the
354699d8f83cSChris Mason 	 * right leaf
354799d8f83cSChris Mason 	 */
35485a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
354999d8f83cSChris Mason 	if (ret < 0)
355099d8f83cSChris Mason 		return ret;
355199d8f83cSChris Mason 
355299d8f83cSChris Mason 	if (ret == 0)
355399d8f83cSChris Mason 		progress++;
355499d8f83cSChris Mason 
355599d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
355699d8f83cSChris Mason 	/*
355799d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
355899d8f83cSChris Mason 	 * we've done so we're done
355999d8f83cSChris Mason 	 */
356099d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
356199d8f83cSChris Mason 		return 0;
356299d8f83cSChris Mason 
3563e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
356499d8f83cSChris Mason 		return 0;
356599d8f83cSChris Mason 
356699d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
356799d8f83cSChris Mason 	slot = path->slots[0];
3568263d3995SFilipe Manana 	space_needed = data_size;
3569263d3995SFilipe Manana 	if (slot > 0)
3570e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
35715a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
357299d8f83cSChris Mason 	if (ret < 0)
357399d8f83cSChris Mason 		return ret;
357499d8f83cSChris Mason 
357599d8f83cSChris Mason 	if (ret == 0)
357699d8f83cSChris Mason 		progress++;
357799d8f83cSChris Mason 
357899d8f83cSChris Mason 	if (progress)
357999d8f83cSChris Mason 		return 0;
358099d8f83cSChris Mason 	return 1;
358199d8f83cSChris Mason }
358299d8f83cSChris Mason 
358399d8f83cSChris Mason /*
358444871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
358544871b1bSChris Mason  * available for the resulting leaf level of the path.
358644871b1bSChris Mason  *
358744871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
358844871b1bSChris Mason  */
358944871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
359044871b1bSChris Mason 			       struct btrfs_root *root,
3591310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
359244871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
359344871b1bSChris Mason 			       int extend)
359444871b1bSChris Mason {
35955d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
359644871b1bSChris Mason 	struct extent_buffer *l;
359744871b1bSChris Mason 	u32 nritems;
359844871b1bSChris Mason 	int mid;
359944871b1bSChris Mason 	int slot;
360044871b1bSChris Mason 	struct extent_buffer *right;
3601b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
360244871b1bSChris Mason 	int ret = 0;
360344871b1bSChris Mason 	int wret;
36045d4f98a2SYan Zheng 	int split;
360544871b1bSChris Mason 	int num_doubles = 0;
360699d8f83cSChris Mason 	int tried_avoid_double = 0;
360744871b1bSChris Mason 
3608a5719521SYan, Zheng 	l = path->nodes[0];
3609a5719521SYan, Zheng 	slot = path->slots[0];
36103212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
36110b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3612a5719521SYan, Zheng 		return -EOVERFLOW;
3613a5719521SYan, Zheng 
361444871b1bSChris Mason 	/* first try to make some room by pushing left and right */
361533157e05SLiu Bo 	if (data_size && path->nodes[1]) {
36165a4267caSFilipe David Borba Manana 		int space_needed = data_size;
36175a4267caSFilipe David Borba Manana 
36185a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3619e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
36205a4267caSFilipe David Borba Manana 
36215a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
36225a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
362344871b1bSChris Mason 		if (wret < 0)
362444871b1bSChris Mason 			return wret;
362544871b1bSChris Mason 		if (wret) {
3626263d3995SFilipe Manana 			space_needed = data_size;
3627263d3995SFilipe Manana 			if (slot > 0)
3628e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
36295a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
36305a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
363144871b1bSChris Mason 			if (wret < 0)
363244871b1bSChris Mason 				return wret;
363344871b1bSChris Mason 		}
363444871b1bSChris Mason 		l = path->nodes[0];
363544871b1bSChris Mason 
363644871b1bSChris Mason 		/* did the pushes work? */
3637e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
363844871b1bSChris Mason 			return 0;
363944871b1bSChris Mason 	}
364044871b1bSChris Mason 
364144871b1bSChris Mason 	if (!path->nodes[1]) {
3642fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
364344871b1bSChris Mason 		if (ret)
364444871b1bSChris Mason 			return ret;
364544871b1bSChris Mason 	}
364644871b1bSChris Mason again:
36475d4f98a2SYan Zheng 	split = 1;
364844871b1bSChris Mason 	l = path->nodes[0];
364944871b1bSChris Mason 	slot = path->slots[0];
365044871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
365144871b1bSChris Mason 	mid = (nritems + 1) / 2;
365244871b1bSChris Mason 
36535d4f98a2SYan Zheng 	if (mid <= slot) {
36545d4f98a2SYan Zheng 		if (nritems == 1 ||
36555d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
36560b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
36575d4f98a2SYan Zheng 			if (slot >= nritems) {
36585d4f98a2SYan Zheng 				split = 0;
36595d4f98a2SYan Zheng 			} else {
36605d4f98a2SYan Zheng 				mid = slot;
36615d4f98a2SYan Zheng 				if (mid != nritems &&
36625d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
36630b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
366499d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
366599d8f83cSChris Mason 						goto push_for_double;
36665d4f98a2SYan Zheng 					split = 2;
36675d4f98a2SYan Zheng 				}
36685d4f98a2SYan Zheng 			}
36695d4f98a2SYan Zheng 		}
36705d4f98a2SYan Zheng 	} else {
36715d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
36720b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
36735d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
36745d4f98a2SYan Zheng 				split = 0;
36755d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
36765d4f98a2SYan Zheng 				mid = 1;
36775d4f98a2SYan Zheng 			} else {
36785d4f98a2SYan Zheng 				mid = slot;
36795d4f98a2SYan Zheng 				if (mid != nritems &&
36805d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
36810b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
368299d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
368399d8f83cSChris Mason 						goto push_for_double;
36845d4f98a2SYan Zheng 					split = 2;
36855d4f98a2SYan Zheng 				}
36865d4f98a2SYan Zheng 			}
36875d4f98a2SYan Zheng 		}
36885d4f98a2SYan Zheng 	}
36895d4f98a2SYan Zheng 
36905d4f98a2SYan Zheng 	if (split == 0)
36915d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
36925d4f98a2SYan Zheng 	else
36935d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
36945d4f98a2SYan Zheng 
3695ca9d473aSJosef Bacik 	/*
3696ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3697ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3698ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3699ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3700ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3701ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3702ca9d473aSJosef Bacik 	 */
370379bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
370479bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
370579bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3706ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3707f0486c68SYan, Zheng 	if (IS_ERR(right))
370844871b1bSChris Mason 		return PTR_ERR(right);
3709f0486c68SYan, Zheng 
37100b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
371144871b1bSChris Mason 
37125d4f98a2SYan Zheng 	if (split == 0) {
371344871b1bSChris Mason 		if (mid <= slot) {
371444871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
37156ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
37162ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
371744871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
371844871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
371944871b1bSChris Mason 			path->nodes[0] = right;
372044871b1bSChris Mason 			path->slots[0] = 0;
372144871b1bSChris Mason 			path->slots[1] += 1;
372244871b1bSChris Mason 		} else {
372344871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
37246ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
37252ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
372644871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
372744871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
372844871b1bSChris Mason 			path->nodes[0] = right;
372944871b1bSChris Mason 			path->slots[0] = 0;
3730143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3731b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
37325d4f98a2SYan Zheng 		}
3733196e0249SLiu Bo 		/*
3734196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3735196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3736196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3737196e0249SLiu Bo 		 */
373844871b1bSChris Mason 		return ret;
373944871b1bSChris Mason 	}
374044871b1bSChris Mason 
374194f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
374244871b1bSChris Mason 
37435d4f98a2SYan Zheng 	if (split == 2) {
3744cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3745cc0c5538SChris Mason 		num_doubles++;
3746cc0c5538SChris Mason 		goto again;
37473326d1b0SChris Mason 	}
374844871b1bSChris Mason 
3749143bede5SJeff Mahoney 	return 0;
375099d8f83cSChris Mason 
375199d8f83cSChris Mason push_for_double:
375299d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
375399d8f83cSChris Mason 	tried_avoid_double = 1;
3754e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
375599d8f83cSChris Mason 		return 0;
375699d8f83cSChris Mason 	goto again;
3757be0e5c09SChris Mason }
3758be0e5c09SChris Mason 
3759ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3760ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3761ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3762ad48fd75SYan, Zheng {
3763ad48fd75SYan, Zheng 	struct btrfs_key key;
3764ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3765ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3766ad48fd75SYan, Zheng 	u64 extent_len = 0;
3767ad48fd75SYan, Zheng 	u32 item_size;
3768ad48fd75SYan, Zheng 	int ret;
3769ad48fd75SYan, Zheng 
3770ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3771ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3772ad48fd75SYan, Zheng 
3773ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3774ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3775ad48fd75SYan, Zheng 
3776e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3777ad48fd75SYan, Zheng 		return 0;
3778ad48fd75SYan, Zheng 
37793212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3780ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3781ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3782ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3783ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3784ad48fd75SYan, Zheng 	}
3785b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3786ad48fd75SYan, Zheng 
3787ad48fd75SYan, Zheng 	path->keep_locks = 1;
3788ad48fd75SYan, Zheng 	path->search_for_split = 1;
3789ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3790ad48fd75SYan, Zheng 	path->search_for_split = 0;
3791a8df6fe6SFilipe Manana 	if (ret > 0)
3792a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3793ad48fd75SYan, Zheng 	if (ret < 0)
3794ad48fd75SYan, Zheng 		goto err;
3795ad48fd75SYan, Zheng 
3796ad48fd75SYan, Zheng 	ret = -EAGAIN;
3797ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3798a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
37993212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3800ad48fd75SYan, Zheng 		goto err;
3801ad48fd75SYan, Zheng 
3802109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3803e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3804109f6aefSChris Mason 		goto err;
3805109f6aefSChris Mason 
3806ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3807ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3808ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3809ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3810ad48fd75SYan, Zheng 			goto err;
3811ad48fd75SYan, Zheng 	}
3812ad48fd75SYan, Zheng 
3813ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3814f0486c68SYan, Zheng 	if (ret)
3815f0486c68SYan, Zheng 		goto err;
3816ad48fd75SYan, Zheng 
3817ad48fd75SYan, Zheng 	path->keep_locks = 0;
3818ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3819ad48fd75SYan, Zheng 	return 0;
3820ad48fd75SYan, Zheng err:
3821ad48fd75SYan, Zheng 	path->keep_locks = 0;
3822ad48fd75SYan, Zheng 	return ret;
3823ad48fd75SYan, Zheng }
3824ad48fd75SYan, Zheng 
382525263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3826310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3827459931ecSChris Mason 			       unsigned long split_offset)
3828459931ecSChris Mason {
3829459931ecSChris Mason 	struct extent_buffer *leaf;
3830c91666b1SJosef Bacik 	int orig_slot, slot;
3831ad48fd75SYan, Zheng 	char *buf;
3832459931ecSChris Mason 	u32 nritems;
3833ad48fd75SYan, Zheng 	u32 item_size;
3834459931ecSChris Mason 	u32 orig_offset;
3835459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3836459931ecSChris Mason 
3837459931ecSChris Mason 	leaf = path->nodes[0];
3838e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3839b9473439SChris Mason 
3840c91666b1SJosef Bacik 	orig_slot = path->slots[0];
38413212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
38423212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3843459931ecSChris Mason 
3844459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3845ad48fd75SYan, Zheng 	if (!buf)
3846ad48fd75SYan, Zheng 		return -ENOMEM;
3847ad48fd75SYan, Zheng 
3848459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3849459931ecSChris Mason 			    path->slots[0]), item_size);
3850ad48fd75SYan, Zheng 
3851459931ecSChris Mason 	slot = path->slots[0] + 1;
3852459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3853459931ecSChris Mason 	if (slot != nritems) {
3854459931ecSChris Mason 		/* shift the items */
3855637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot + 1, slot, nritems - slot);
3856459931ecSChris Mason 	}
3857459931ecSChris Mason 
3858459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3859459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3860459931ecSChris Mason 
38613212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
38623212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3863459931ecSChris Mason 
38643212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
3865459931ecSChris Mason 				 orig_offset + item_size - split_offset);
38663212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3867459931ecSChris Mason 
3868459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3869459931ecSChris Mason 
3870459931ecSChris Mason 	/* write the data for the start of the original item */
3871459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3872459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3873459931ecSChris Mason 			    split_offset);
3874459931ecSChris Mason 
3875459931ecSChris Mason 	/* write the data for the new item */
3876459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3877459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3878459931ecSChris Mason 			    item_size - split_offset);
3879459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3880459931ecSChris Mason 
3881e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3882459931ecSChris Mason 	kfree(buf);
3883ad48fd75SYan, Zheng 	return 0;
3884ad48fd75SYan, Zheng }
3885ad48fd75SYan, Zheng 
3886ad48fd75SYan, Zheng /*
3887ad48fd75SYan, Zheng  * This function splits a single item into two items,
3888ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3889ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3890ad48fd75SYan, Zheng  *
3891ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3892ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3893ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3894ad48fd75SYan, Zheng  *
3895ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3896ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3897ad48fd75SYan, Zheng  *
3898ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3899ad48fd75SYan, Zheng  * leaf the entire time.
3900ad48fd75SYan, Zheng  */
3901ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3902ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3903ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3904310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3905ad48fd75SYan, Zheng 		     unsigned long split_offset)
3906ad48fd75SYan, Zheng {
3907ad48fd75SYan, Zheng 	int ret;
3908ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3909ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3910ad48fd75SYan, Zheng 	if (ret)
3911459931ecSChris Mason 		return ret;
3912ad48fd75SYan, Zheng 
391325263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3914ad48fd75SYan, Zheng 	return ret;
3915ad48fd75SYan, Zheng }
3916ad48fd75SYan, Zheng 
3917ad48fd75SYan, Zheng /*
3918d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
3919d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
3920d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
3921d352ac68SChris Mason  * the front.
3922d352ac68SChris Mason  */
392378ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3924b18c6685SChris Mason {
3925b18c6685SChris Mason 	int slot;
39265f39d397SChris Mason 	struct extent_buffer *leaf;
3927b18c6685SChris Mason 	u32 nritems;
3928b18c6685SChris Mason 	unsigned int data_end;
3929b18c6685SChris Mason 	unsigned int old_data_start;
3930b18c6685SChris Mason 	unsigned int old_size;
3931b18c6685SChris Mason 	unsigned int size_diff;
3932b18c6685SChris Mason 	int i;
3933cfed81a0SChris Mason 	struct btrfs_map_token token;
3934cfed81a0SChris Mason 
39355f39d397SChris Mason 	leaf = path->nodes[0];
3936179e29e4SChris Mason 	slot = path->slots[0];
3937179e29e4SChris Mason 
39383212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
3939179e29e4SChris Mason 	if (old_size == new_size)
3940143bede5SJeff Mahoney 		return;
3941b18c6685SChris Mason 
39425f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
39438f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3944b18c6685SChris Mason 
39453212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
3946179e29e4SChris Mason 
3947b18c6685SChris Mason 	size_diff = old_size - new_size;
3948b18c6685SChris Mason 
3949b18c6685SChris Mason 	BUG_ON(slot < 0);
3950b18c6685SChris Mason 	BUG_ON(slot >= nritems);
3951b18c6685SChris Mason 
3952b18c6685SChris Mason 	/*
3953b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3954b18c6685SChris Mason 	 */
3955b18c6685SChris Mason 	/* first correct the data pointers */
3956c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3957b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
39585f39d397SChris Mason 		u32 ioff;
3959db94535dSChris Mason 
39603212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
39613212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3962b18c6685SChris Mason 	}
3963db94535dSChris Mason 
3964b18c6685SChris Mason 	/* shift the data */
3965179e29e4SChris Mason 	if (from_end) {
3966637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
3967637e3b48SJosef Bacik 				  old_data_start + new_size - data_end);
3968179e29e4SChris Mason 	} else {
3969179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
3970179e29e4SChris Mason 		u64 offset;
3971179e29e4SChris Mason 
3972179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
3973179e29e4SChris Mason 
3974179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3975179e29e4SChris Mason 			unsigned long ptr;
3976179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
3977179e29e4SChris Mason 
3978179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
3979179e29e4SChris Mason 					    struct btrfs_file_extent_item);
3980179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
3981179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
3982179e29e4SChris Mason 
3983179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
3984179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
3985179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
3986179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
3987179e29e4SChris Mason 				      (unsigned long)fi,
39887ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
3989179e29e4SChris Mason 			}
3990179e29e4SChris Mason 		}
3991179e29e4SChris Mason 
3992637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
3993637e3b48SJosef Bacik 				  old_data_start - data_end);
3994179e29e4SChris Mason 
3995179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
3996179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3997179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
3998179e29e4SChris Mason 		if (slot == 0)
3999b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4000179e29e4SChris Mason 	}
40015f39d397SChris Mason 
40023212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
40035f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4004b18c6685SChris Mason 
4005e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4006a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4007b18c6685SChris Mason 		BUG();
40085f39d397SChris Mason 	}
4009b18c6685SChris Mason }
4010b18c6685SChris Mason 
4011d352ac68SChris Mason /*
40128f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4013d352ac68SChris Mason  */
4014c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
40156567e837SChris Mason {
40166567e837SChris Mason 	int slot;
40175f39d397SChris Mason 	struct extent_buffer *leaf;
40186567e837SChris Mason 	u32 nritems;
40196567e837SChris Mason 	unsigned int data_end;
40206567e837SChris Mason 	unsigned int old_data;
40216567e837SChris Mason 	unsigned int old_size;
40226567e837SChris Mason 	int i;
4023cfed81a0SChris Mason 	struct btrfs_map_token token;
4024cfed81a0SChris Mason 
40255f39d397SChris Mason 	leaf = path->nodes[0];
40266567e837SChris Mason 
40275f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
40288f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
40296567e837SChris Mason 
4030e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4031a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
40326567e837SChris Mason 		BUG();
40335f39d397SChris Mason 	}
40346567e837SChris Mason 	slot = path->slots[0];
4035dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
40366567e837SChris Mason 
40376567e837SChris Mason 	BUG_ON(slot < 0);
40383326d1b0SChris Mason 	if (slot >= nritems) {
4039a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4040c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4041d397712bSChris Mason 			   slot, nritems);
4042290342f6SArnd Bergmann 		BUG();
40433326d1b0SChris Mason 	}
40446567e837SChris Mason 
40456567e837SChris Mason 	/*
40466567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
40476567e837SChris Mason 	 */
40486567e837SChris Mason 	/* first correct the data pointers */
4049c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
40506567e837SChris Mason 	for (i = slot; i < nritems; i++) {
40515f39d397SChris Mason 		u32 ioff;
4052db94535dSChris Mason 
40533212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
40543212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
40556567e837SChris Mason 	}
40565f39d397SChris Mason 
40576567e837SChris Mason 	/* shift the data */
4058637e3b48SJosef Bacik 	memmove_leaf_data(leaf, data_end - data_size, data_end,
4059637e3b48SJosef Bacik 			  old_data - data_end);
40605f39d397SChris Mason 
40616567e837SChris Mason 	data_end = old_data;
40623212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
40633212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
40645f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
40656567e837SChris Mason 
4066e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4067a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
40686567e837SChris Mason 		BUG();
40695f39d397SChris Mason 	}
40706567e837SChris Mason }
40716567e837SChris Mason 
407243dd529aSDavid Sterba /*
407343dd529aSDavid Sterba  * Make space in the node before inserting one or more items.
4074da9ffb24SNikolay Borisov  *
4075da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
4076da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
4077b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
407843dd529aSDavid Sterba  *
407943dd529aSDavid Sterba  * Main purpose is to save stack depth by doing the bulk of the work in a
408043dd529aSDavid Sterba  * function that doesn't call btrfs_search_slot
408174123bd7SChris Mason  */
4082f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4083b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
4084be0e5c09SChris Mason {
40850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
40869c58309dSChris Mason 	int i;
40877518a238SChris Mason 	u32 nritems;
4088be0e5c09SChris Mason 	unsigned int data_end;
4089e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
409044871b1bSChris Mason 	struct extent_buffer *leaf;
409144871b1bSChris Mason 	int slot;
4092cfed81a0SChris Mason 	struct btrfs_map_token token;
4093fc0d82e1SNikolay Borisov 	u32 total_size;
4094fc0d82e1SNikolay Borisov 
4095b7ef5f3aSFilipe Manana 	/*
4096b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
4097b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
4098b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
4099b7ef5f3aSFilipe Manana 	 */
410024cdc847SFilipe Manana 	if (path->slots[0] == 0) {
4101b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4102b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
410324cdc847SFilipe Manana 	}
410424cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
410524cdc847SFilipe Manana 
41065f39d397SChris Mason 	leaf = path->nodes[0];
410744871b1bSChris Mason 	slot = path->slots[0];
410874123bd7SChris Mason 
41095f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
41108f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4111b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4112eb60ceacSChris Mason 
4113e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4114a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
41150b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4116e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4117be0e5c09SChris Mason 		BUG();
4118d4dbff95SChris Mason 	}
41195f39d397SChris Mason 
4120c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4121be0e5c09SChris Mason 	if (slot != nritems) {
4122dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4123be0e5c09SChris Mason 
41245f39d397SChris Mason 		if (old_data < data_end) {
4125a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
41267269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
41277269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
41285f39d397SChris Mason 				   slot, old_data, data_end);
4129290342f6SArnd Bergmann 			BUG();
41305f39d397SChris Mason 		}
4131be0e5c09SChris Mason 		/*
4132be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4133be0e5c09SChris Mason 		 */
4134be0e5c09SChris Mason 		/* first correct the data pointers */
41350783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
41365f39d397SChris Mason 			u32 ioff;
4137db94535dSChris Mason 
41383212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
41393212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
4140b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
41410783fcfcSChris Mason 		}
4142be0e5c09SChris Mason 		/* shift the items */
4143637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot + batch->nr, slot, nritems - slot);
4144be0e5c09SChris Mason 
4145be0e5c09SChris Mason 		/* shift the data */
4146637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end - batch->total_data_size,
4147637e3b48SJosef Bacik 				  data_end, old_data - data_end);
4148be0e5c09SChris Mason 		data_end = old_data;
4149be0e5c09SChris Mason 	}
41505f39d397SChris Mason 
415162e2749eSChris Mason 	/* setup the item for the new data */
4152b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
4153b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
41549c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4155b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
41563212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
41573212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
41589c58309dSChris Mason 	}
415944871b1bSChris Mason 
4160b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4161b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4162aa5d6bedSChris Mason 
4163e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4164a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4165be0e5c09SChris Mason 		BUG();
41665f39d397SChris Mason 	}
416744871b1bSChris Mason }
416844871b1bSChris Mason 
416944871b1bSChris Mason /*
4170f0641656SFilipe Manana  * Insert a new item into a leaf.
4171f0641656SFilipe Manana  *
4172f0641656SFilipe Manana  * @root:      The root of the btree.
4173f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
4174f0641656SFilipe Manana  * @key:       The key of the new item.
4175f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
4176f0641656SFilipe Manana  */
4177f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
4178f0641656SFilipe Manana 				 struct btrfs_path *path,
4179f0641656SFilipe Manana 				 const struct btrfs_key *key,
4180f0641656SFilipe Manana 				 u32 data_size)
4181f0641656SFilipe Manana {
4182f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4183f0641656SFilipe Manana 
4184f0641656SFilipe Manana 	batch.keys = key;
4185f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4186f0641656SFilipe Manana 	batch.total_data_size = data_size;
4187f0641656SFilipe Manana 	batch.nr = 1;
4188f0641656SFilipe Manana 
4189f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
4190f0641656SFilipe Manana }
4191f0641656SFilipe Manana 
4192f0641656SFilipe Manana /*
419344871b1bSChris Mason  * Given a key and some data, insert items into the tree.
419444871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
419544871b1bSChris Mason  */
419644871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
419744871b1bSChris Mason 			    struct btrfs_root *root,
419844871b1bSChris Mason 			    struct btrfs_path *path,
4199b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
420044871b1bSChris Mason {
420144871b1bSChris Mason 	int ret = 0;
420244871b1bSChris Mason 	int slot;
4203b7ef5f3aSFilipe Manana 	u32 total_size;
420444871b1bSChris Mason 
4205b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4206b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
420744871b1bSChris Mason 	if (ret == 0)
420844871b1bSChris Mason 		return -EEXIST;
420944871b1bSChris Mason 	if (ret < 0)
4210143bede5SJeff Mahoney 		return ret;
421144871b1bSChris Mason 
421244871b1bSChris Mason 	slot = path->slots[0];
421344871b1bSChris Mason 	BUG_ON(slot < 0);
421444871b1bSChris Mason 
4215b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4216143bede5SJeff Mahoney 	return 0;
421762e2749eSChris Mason }
421862e2749eSChris Mason 
421962e2749eSChris Mason /*
422062e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
422162e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
422262e2749eSChris Mason  */
4223310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4224310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4225310712b2SOmar Sandoval 		      u32 data_size)
422662e2749eSChris Mason {
422762e2749eSChris Mason 	int ret = 0;
42282c90e5d6SChris Mason 	struct btrfs_path *path;
42295f39d397SChris Mason 	struct extent_buffer *leaf;
42305f39d397SChris Mason 	unsigned long ptr;
423162e2749eSChris Mason 
42322c90e5d6SChris Mason 	path = btrfs_alloc_path();
4233db5b493aSTsutomu Itoh 	if (!path)
4234db5b493aSTsutomu Itoh 		return -ENOMEM;
42352c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
423662e2749eSChris Mason 	if (!ret) {
42375f39d397SChris Mason 		leaf = path->nodes[0];
42385f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
42395f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
42405f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
424162e2749eSChris Mason 	}
42422c90e5d6SChris Mason 	btrfs_free_path(path);
4243aa5d6bedSChris Mason 	return ret;
4244be0e5c09SChris Mason }
4245be0e5c09SChris Mason 
424674123bd7SChris Mason /*
4247f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4248f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4249f0641656SFilipe Manana  * contiguous with the original item.
4250f0641656SFilipe Manana  *
4251f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4252f0641656SFilipe Manana  * the entire time.
4253f0641656SFilipe Manana  */
4254f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4255f0641656SFilipe Manana 			 struct btrfs_root *root,
4256f0641656SFilipe Manana 			 struct btrfs_path *path,
4257f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4258f0641656SFilipe Manana {
4259f0641656SFilipe Manana 	struct extent_buffer *leaf;
4260f0641656SFilipe Manana 	int ret;
4261f0641656SFilipe Manana 	u32 item_size;
4262f0641656SFilipe Manana 
4263f0641656SFilipe Manana 	leaf = path->nodes[0];
42643212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4265f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4266f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4267f0641656SFilipe Manana 	if (ret)
4268f0641656SFilipe Manana 		return ret;
4269f0641656SFilipe Manana 
4270f0641656SFilipe Manana 	path->slots[0]++;
4271f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4272f0641656SFilipe Manana 	leaf = path->nodes[0];
4273f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4274f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4275f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4276f0641656SFilipe Manana 			     item_size);
4277f0641656SFilipe Manana 	return 0;
4278f0641656SFilipe Manana }
4279f0641656SFilipe Manana 
4280f0641656SFilipe Manana /*
42815de08d7dSChris Mason  * delete the pointer from a given node.
428274123bd7SChris Mason  *
4283d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4284d352ac68SChris Mason  * empty a node.
428574123bd7SChris Mason  */
4286afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4287afe5fea7STsutomu Itoh 		    int level, int slot)
4288be0e5c09SChris Mason {
42895f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
42907518a238SChris Mason 	u32 nritems;
4291f3ea38daSJan Schmidt 	int ret;
4292be0e5c09SChris Mason 
42935f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4294be0e5c09SChris Mason 	if (slot != nritems - 1) {
4295bf1d3425SDavid Sterba 		if (level) {
4296f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4297f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4298bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4299bf1d3425SDavid Sterba 		}
43005f39d397SChris Mason 		memmove_extent_buffer(parent,
4301e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot),
4302e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot + 1),
4303d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4304d6025579SChris Mason 			      (nritems - slot - 1));
430557ba86c0SChris Mason 	} else if (level) {
4306f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
430733cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REMOVE);
430857ba86c0SChris Mason 		BUG_ON(ret < 0);
4309be0e5c09SChris Mason 	}
4310f3ea38daSJan Schmidt 
43117518a238SChris Mason 	nritems--;
43125f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
43137518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
43145f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4315eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
43165f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4317bb803951SChris Mason 	} else if (slot == 0) {
43185f39d397SChris Mason 		struct btrfs_disk_key disk_key;
43195f39d397SChris Mason 
43205f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4321b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4322be0e5c09SChris Mason 	}
4323d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4324be0e5c09SChris Mason }
4325be0e5c09SChris Mason 
432674123bd7SChris Mason /*
4327323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
43285d4f98a2SYan Zheng  * path->nodes[1].
4329323ac95bSChris Mason  *
4330323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4331323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4332323ac95bSChris Mason  *
4333323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4334323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4335323ac95bSChris Mason  */
4336143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4337323ac95bSChris Mason 				    struct btrfs_root *root,
43385d4f98a2SYan Zheng 				    struct btrfs_path *path,
43395d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4340323ac95bSChris Mason {
43415d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4342afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4343323ac95bSChris Mason 
43444d081c41SChris Mason 	/*
43454d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
43464d081c41SChris Mason 	 * aren't holding any locks when we call it
43474d081c41SChris Mason 	 */
43484d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
43494d081c41SChris Mason 
4350f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4351f0486c68SYan, Zheng 
435267439dadSDavid Sterba 	atomic_inc(&leaf->refs);
43537a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
43543083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4355323ac95bSChris Mason }
4356323ac95bSChris Mason /*
435774123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
435874123bd7SChris Mason  * the leaf, remove it from the tree
435974123bd7SChris Mason  */
436085e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
436185e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4362be0e5c09SChris Mason {
43630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
43645f39d397SChris Mason 	struct extent_buffer *leaf;
4365aa5d6bedSChris Mason 	int ret = 0;
4366aa5d6bedSChris Mason 	int wret;
43677518a238SChris Mason 	u32 nritems;
4368be0e5c09SChris Mason 
43695f39d397SChris Mason 	leaf = path->nodes[0];
43705f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4371be0e5c09SChris Mason 
437285e21bacSChris Mason 	if (slot + nr != nritems) {
43730cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
43740cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4375c82f823cSDavid Sterba 		struct btrfs_map_token token;
43760cae23b6SFilipe Manana 		u32 dsize = 0;
43770cae23b6SFilipe Manana 		int i;
43780cae23b6SFilipe Manana 
43790cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
43800cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
43815f39d397SChris Mason 
4382637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + dsize, data_end,
438385e21bacSChris Mason 				  last_off - data_end);
43845f39d397SChris Mason 
4385c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
438685e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
43875f39d397SChris Mason 			u32 ioff;
4388db94535dSChris Mason 
43893212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
43903212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
43910783fcfcSChris Mason 		}
4392db94535dSChris Mason 
4393637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot, slot + nr, nritems - slot - nr);
4394be0e5c09SChris Mason 	}
439585e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
439685e21bacSChris Mason 	nritems -= nr;
43975f39d397SChris Mason 
439874123bd7SChris Mason 	/* delete the leaf if we've emptied it */
43997518a238SChris Mason 	if (nritems == 0) {
44005f39d397SChris Mason 		if (leaf == root->node) {
44015f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
44029a8dd150SChris Mason 		} else {
44036a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4404143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
44059a8dd150SChris Mason 		}
4406be0e5c09SChris Mason 	} else {
44077518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4408aa5d6bedSChris Mason 		if (slot == 0) {
44095f39d397SChris Mason 			struct btrfs_disk_key disk_key;
44105f39d397SChris Mason 
44115f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4412b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4413aa5d6bedSChris Mason 		}
4414aa5d6bedSChris Mason 
44157c4063d1SFilipe Manana 		/*
44167c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
44177c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
44187c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
44197c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
44207c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
44217c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
44227c4063d1SFilipe Manana 		 */
44230b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
44247c4063d1SFilipe Manana 			u32 min_push_space;
44257c4063d1SFilipe Manana 
4426be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4427be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4428be0e5c09SChris Mason 			 * for possible call to del_ptr below
4429be0e5c09SChris Mason 			 */
44304920c9acSChris Mason 			slot = path->slots[1];
443167439dadSDavid Sterba 			atomic_inc(&leaf->refs);
44327c4063d1SFilipe Manana 			/*
44337c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
44347c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
44357c4063d1SFilipe Manana 			 */
44367c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
44377c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
44387c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
44397c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
444054aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4441aa5d6bedSChris Mason 				ret = wret;
44425f39d397SChris Mason 
44435f39d397SChris Mason 			if (path->nodes[0] == leaf &&
44445f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
44457c4063d1SFilipe Manana 				/*
44467c4063d1SFilipe Manana 				 * If we were not able to push all items from our
44477c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
44487c4063d1SFilipe Manana 				 * either push all the remaining items to the
44497c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
44507c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
44517c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
44527c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
44537c4063d1SFilipe Manana 				 * or nearly full.
44547c4063d1SFilipe Manana 				 */
44557c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
44567c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
44577c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
44587c4063d1SFilipe Manana 						       min_push_space, 1, 0);
445954aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4460aa5d6bedSChris Mason 					ret = wret;
4461aa5d6bedSChris Mason 			}
44625f39d397SChris Mason 
44635f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4464323ac95bSChris Mason 				path->slots[1] = slot;
4465143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
44665f39d397SChris Mason 				free_extent_buffer(leaf);
4467143bede5SJeff Mahoney 				ret = 0;
44685de08d7dSChris Mason 			} else {
4469925baeddSChris Mason 				/* if we're still in the path, make sure
4470925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4471925baeddSChris Mason 				 * push_leaf functions must have already
4472925baeddSChris Mason 				 * dirtied this buffer
4473925baeddSChris Mason 				 */
4474925baeddSChris Mason 				if (path->nodes[0] == leaf)
44755f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
44765f39d397SChris Mason 				free_extent_buffer(leaf);
4477be0e5c09SChris Mason 			}
4478d5719762SChris Mason 		} else {
44795f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4480be0e5c09SChris Mason 		}
44819a8dd150SChris Mason 	}
4482aa5d6bedSChris Mason 	return ret;
44839a8dd150SChris Mason }
44849a8dd150SChris Mason 
448597571fd0SChris Mason /*
4486925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
44877bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
44887bb86316SChris Mason  * returns < 0 on io errors.
4489d352ac68SChris Mason  *
4490d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4491d352ac68SChris Mason  * time you call it.
44927bb86316SChris Mason  */
449316e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
44947bb86316SChris Mason {
4495925baeddSChris Mason 	struct btrfs_key key;
4496925baeddSChris Mason 	struct btrfs_disk_key found_key;
4497925baeddSChris Mason 	int ret;
44987bb86316SChris Mason 
4499925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4500925baeddSChris Mason 
4501e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
4502925baeddSChris Mason 		key.offset--;
4503e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
4504925baeddSChris Mason 		key.type--;
4505e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4506e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
4507925baeddSChris Mason 		key.objectid--;
4508e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
4509e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4510e8b0d724SFilipe David Borba Manana 	} else {
45117bb86316SChris Mason 		return 1;
4512e8b0d724SFilipe David Borba Manana 	}
45137bb86316SChris Mason 
4514b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4515925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4516925baeddSChris Mason 	if (ret < 0)
4517925baeddSChris Mason 		return ret;
4518925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4519925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4520337c6f68SFilipe Manana 	/*
4521337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
4522337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
4523337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
4524337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
4525337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
4526337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
4527337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
4528337c6f68SFilipe Manana 	 * the previous key we computed above.
4529337c6f68SFilipe Manana 	 */
4530337c6f68SFilipe Manana 	if (ret <= 0)
45317bb86316SChris Mason 		return 0;
4532925baeddSChris Mason 	return 1;
45337bb86316SChris Mason }
45347bb86316SChris Mason 
45353f157a2fSChris Mason /*
45363f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4537de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4538de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
45393f157a2fSChris Mason  *
45403f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
45413f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
45423f157a2fSChris Mason  * key and get a writable path.
45433f157a2fSChris Mason  *
45443f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
45453f157a2fSChris Mason  * of the tree.
45463f157a2fSChris Mason  *
4547d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4548d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4549d352ac68SChris Mason  * skipped over (without reading them).
4550d352ac68SChris Mason  *
45513f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
45523f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
45533f157a2fSChris Mason  */
45543f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4555de78b51aSEric Sandeen 			 struct btrfs_path *path,
45563f157a2fSChris Mason 			 u64 min_trans)
45573f157a2fSChris Mason {
45583f157a2fSChris Mason 	struct extent_buffer *cur;
45593f157a2fSChris Mason 	struct btrfs_key found_key;
45603f157a2fSChris Mason 	int slot;
45619652480bSYan 	int sret;
45623f157a2fSChris Mason 	u32 nritems;
45633f157a2fSChris Mason 	int level;
45643f157a2fSChris Mason 	int ret = 1;
4565f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
45663f157a2fSChris Mason 
4567c922b016SStefan Roesch 	ASSERT(!path->nowait);
4568f98de9b9SFilipe Manana 	path->keep_locks = 1;
45693f157a2fSChris Mason again:
4570bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
45713f157a2fSChris Mason 	level = btrfs_header_level(cur);
4572e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
45733f157a2fSChris Mason 	path->nodes[level] = cur;
4574bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
45753f157a2fSChris Mason 
45763f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
45773f157a2fSChris Mason 		ret = 1;
45783f157a2fSChris Mason 		goto out;
45793f157a2fSChris Mason 	}
45803f157a2fSChris Mason 	while (1) {
45813f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
45823f157a2fSChris Mason 		level = btrfs_header_level(cur);
4583e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
4584cbca7d59SFilipe Manana 		if (sret < 0) {
4585cbca7d59SFilipe Manana 			ret = sret;
4586cbca7d59SFilipe Manana 			goto out;
4587cbca7d59SFilipe Manana 		}
45883f157a2fSChris Mason 
4589323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4590323ac95bSChris Mason 		if (level == path->lowest_level) {
4591e02119d5SChris Mason 			if (slot >= nritems)
4592e02119d5SChris Mason 				goto find_next_key;
45933f157a2fSChris Mason 			ret = 0;
45943f157a2fSChris Mason 			path->slots[level] = slot;
45953f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
45963f157a2fSChris Mason 			goto out;
45973f157a2fSChris Mason 		}
45989652480bSYan 		if (sret && slot > 0)
45999652480bSYan 			slot--;
46003f157a2fSChris Mason 		/*
4601de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4602260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
46033f157a2fSChris Mason 		 */
46043f157a2fSChris Mason 		while (slot < nritems) {
46053f157a2fSChris Mason 			u64 gen;
4606e02119d5SChris Mason 
46073f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
46083f157a2fSChris Mason 			if (gen < min_trans) {
46093f157a2fSChris Mason 				slot++;
46103f157a2fSChris Mason 				continue;
46113f157a2fSChris Mason 			}
46123f157a2fSChris Mason 			break;
46133f157a2fSChris Mason 		}
4614e02119d5SChris Mason find_next_key:
46153f157a2fSChris Mason 		/*
46163f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
46173f157a2fSChris Mason 		 * and find another one
46183f157a2fSChris Mason 		 */
46193f157a2fSChris Mason 		if (slot >= nritems) {
4620e02119d5SChris Mason 			path->slots[level] = slot;
4621e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4622de78b51aSEric Sandeen 						  min_trans);
4623e02119d5SChris Mason 			if (sret == 0) {
4624b3b4aa74SDavid Sterba 				btrfs_release_path(path);
46253f157a2fSChris Mason 				goto again;
46263f157a2fSChris Mason 			} else {
46273f157a2fSChris Mason 				goto out;
46283f157a2fSChris Mason 			}
46293f157a2fSChris Mason 		}
46303f157a2fSChris Mason 		/* save our key for returning back */
46313f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
46323f157a2fSChris Mason 		path->slots[level] = slot;
46333f157a2fSChris Mason 		if (level == path->lowest_level) {
46343f157a2fSChris Mason 			ret = 0;
46353f157a2fSChris Mason 			goto out;
46363f157a2fSChris Mason 		}
46374b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4638fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4639fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4640fb770ae4SLiu Bo 			goto out;
4641fb770ae4SLiu Bo 		}
46423f157a2fSChris Mason 
4643bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4644b4ce94deSChris Mason 
4645bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
46463f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4647f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
46483f157a2fSChris Mason 	}
46493f157a2fSChris Mason out:
4650f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4651f98de9b9SFilipe Manana 	if (ret == 0) {
4652f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4653f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4654f98de9b9SFilipe Manana 	}
46553f157a2fSChris Mason 	return ret;
46563f157a2fSChris Mason }
46573f157a2fSChris Mason 
46583f157a2fSChris Mason /*
46593f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
46603f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4661de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
46623f157a2fSChris Mason  *
46633f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
46643f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
46653f157a2fSChris Mason  *
46663f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
46673f157a2fSChris Mason  * calling this function.
46683f157a2fSChris Mason  */
4669e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4670de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4671e7a84565SChris Mason {
4672e7a84565SChris Mason 	int slot;
4673e7a84565SChris Mason 	struct extent_buffer *c;
4674e7a84565SChris Mason 
46756a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4676e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4677e7a84565SChris Mason 		if (!path->nodes[level])
4678e7a84565SChris Mason 			return 1;
4679e7a84565SChris Mason 
4680e7a84565SChris Mason 		slot = path->slots[level] + 1;
4681e7a84565SChris Mason 		c = path->nodes[level];
46823f157a2fSChris Mason next:
4683e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
468433c66f43SYan Zheng 			int ret;
468533c66f43SYan Zheng 			int orig_lowest;
468633c66f43SYan Zheng 			struct btrfs_key cur_key;
468733c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
468833c66f43SYan Zheng 			    !path->nodes[level + 1])
4689e7a84565SChris Mason 				return 1;
469033c66f43SYan Zheng 
46916a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
469233c66f43SYan Zheng 				level++;
4693e7a84565SChris Mason 				continue;
4694e7a84565SChris Mason 			}
469533c66f43SYan Zheng 
469633c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
469733c66f43SYan Zheng 			if (level == 0)
469833c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
469933c66f43SYan Zheng 			else
470033c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
470133c66f43SYan Zheng 
470233c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4703b3b4aa74SDavid Sterba 			btrfs_release_path(path);
470433c66f43SYan Zheng 			path->lowest_level = level;
470533c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
470633c66f43SYan Zheng 						0, 0);
470733c66f43SYan Zheng 			path->lowest_level = orig_lowest;
470833c66f43SYan Zheng 			if (ret < 0)
470933c66f43SYan Zheng 				return ret;
471033c66f43SYan Zheng 
471133c66f43SYan Zheng 			c = path->nodes[level];
471233c66f43SYan Zheng 			slot = path->slots[level];
471333c66f43SYan Zheng 			if (ret == 0)
471433c66f43SYan Zheng 				slot++;
471533c66f43SYan Zheng 			goto next;
471633c66f43SYan Zheng 		}
471733c66f43SYan Zheng 
4718e7a84565SChris Mason 		if (level == 0)
4719e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
47203f157a2fSChris Mason 		else {
47213f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
47223f157a2fSChris Mason 
47233f157a2fSChris Mason 			if (gen < min_trans) {
47243f157a2fSChris Mason 				slot++;
47253f157a2fSChris Mason 				goto next;
47263f157a2fSChris Mason 			}
4727e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
47283f157a2fSChris Mason 		}
4729e7a84565SChris Mason 		return 0;
4730e7a84565SChris Mason 	}
4731e7a84565SChris Mason 	return 1;
4732e7a84565SChris Mason }
4733e7a84565SChris Mason 
47343d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
47353d7806ecSJan Schmidt 			u64 time_seq)
47363d7806ecSJan Schmidt {
4737d97e63b6SChris Mason 	int slot;
47388e73f275SChris Mason 	int level;
47395f39d397SChris Mason 	struct extent_buffer *c;
47408e73f275SChris Mason 	struct extent_buffer *next;
4741d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4742925baeddSChris Mason 	struct btrfs_key key;
4743d96b3424SFilipe Manana 	bool need_commit_sem = false;
4744925baeddSChris Mason 	u32 nritems;
4745925baeddSChris Mason 	int ret;
47460e46318dSJosef Bacik 	int i;
4747925baeddSChris Mason 
4748bdcdd86cSFilipe Manana 	/*
4749bdcdd86cSFilipe Manana 	 * The nowait semantics are used only for write paths, where we don't
4750bdcdd86cSFilipe Manana 	 * use the tree mod log and sequence numbers.
4751bdcdd86cSFilipe Manana 	 */
4752bdcdd86cSFilipe Manana 	if (time_seq)
4753c922b016SStefan Roesch 		ASSERT(!path->nowait);
4754c922b016SStefan Roesch 
4755925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4756d397712bSChris Mason 	if (nritems == 0)
4757925baeddSChris Mason 		return 1;
4758925baeddSChris Mason 
47598e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
47608e73f275SChris Mason again:
47618e73f275SChris Mason 	level = 1;
47628e73f275SChris Mason 	next = NULL;
4763b3b4aa74SDavid Sterba 	btrfs_release_path(path);
47648e73f275SChris Mason 
4765a2135011SChris Mason 	path->keep_locks = 1;
47668e73f275SChris Mason 
4767d96b3424SFilipe Manana 	if (time_seq) {
47683d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4769d96b3424SFilipe Manana 	} else {
4770d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4771d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4772d96b3424SFilipe Manana 			need_commit_sem = true;
4773bdcdd86cSFilipe Manana 			if (path->nowait) {
4774bdcdd86cSFilipe Manana 				if (!down_read_trylock(&fs_info->commit_root_sem)) {
4775bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4776bdcdd86cSFilipe Manana 					goto done;
4777bdcdd86cSFilipe Manana 				}
4778bdcdd86cSFilipe Manana 			} else {
4779d96b3424SFilipe Manana 				down_read(&fs_info->commit_root_sem);
4780d96b3424SFilipe Manana 			}
4781bdcdd86cSFilipe Manana 		}
4782925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4783d96b3424SFilipe Manana 	}
4784925baeddSChris Mason 	path->keep_locks = 0;
4785925baeddSChris Mason 
4786925baeddSChris Mason 	if (ret < 0)
4787d96b3424SFilipe Manana 		goto done;
4788925baeddSChris Mason 
4789a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4790168fd7d2SChris Mason 	/*
4791168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4792168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4793168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4794168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4795168fd7d2SChris Mason 	 */
4796a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4797e457afecSYan Zheng 		if (ret == 0)
4798168fd7d2SChris Mason 			path->slots[0]++;
47998e73f275SChris Mason 		ret = 0;
4800925baeddSChris Mason 		goto done;
4801925baeddSChris Mason 	}
48020b43e04fSLiu Bo 	/*
48030b43e04fSLiu Bo 	 * So the above check misses one case:
48040b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
48050b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
48060b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
48070b43e04fSLiu Bo 	 *
48080b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
48090b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
48100b43e04fSLiu Bo 	 *
48110b43e04fSLiu Bo 	 * And a bit more explanation about this check,
48120b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
48130b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
48140b43e04fSLiu Bo 	 * bigger one.
48150b43e04fSLiu Bo 	 */
48160b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
48170b43e04fSLiu Bo 		ret = 0;
48180b43e04fSLiu Bo 		goto done;
48190b43e04fSLiu Bo 	}
4820d97e63b6SChris Mason 
4821234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
48228e73f275SChris Mason 		if (!path->nodes[level]) {
48238e73f275SChris Mason 			ret = 1;
48248e73f275SChris Mason 			goto done;
48258e73f275SChris Mason 		}
48265f39d397SChris Mason 
4827d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4828d97e63b6SChris Mason 		c = path->nodes[level];
48295f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4830d97e63b6SChris Mason 			level++;
48318e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
48328e73f275SChris Mason 				ret = 1;
48338e73f275SChris Mason 				goto done;
48348e73f275SChris Mason 			}
4835d97e63b6SChris Mason 			continue;
4836d97e63b6SChris Mason 		}
48375f39d397SChris Mason 
48380e46318dSJosef Bacik 
48390e46318dSJosef Bacik 		/*
48400e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
48410e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
48420e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
48430e46318dSJosef Bacik 		 */
48440e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
48450e46318dSJosef Bacik 			if (path->locks[level]) {
48460e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
48470e46318dSJosef Bacik 				path->locks[i] = 0;
48480e46318dSJosef Bacik 			}
48490e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
48500e46318dSJosef Bacik 			path->nodes[i] = NULL;
4851925baeddSChris Mason 		}
48525f39d397SChris Mason 
48538e73f275SChris Mason 		next = c;
4854d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4855cda79c54SDavid Sterba 					    slot, &key);
4856bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
48578e73f275SChris Mason 			goto again;
48585f39d397SChris Mason 
485976a05b35SChris Mason 		if (ret < 0) {
4860b3b4aa74SDavid Sterba 			btrfs_release_path(path);
486176a05b35SChris Mason 			goto done;
486276a05b35SChris Mason 		}
486376a05b35SChris Mason 
48645cd57b2cSChris Mason 		if (!path->skip_locking) {
4865bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4866bdcdd86cSFilipe Manana 			if (!ret && path->nowait) {
4867bdcdd86cSFilipe Manana 				ret = -EAGAIN;
4868bdcdd86cSFilipe Manana 				goto done;
4869bdcdd86cSFilipe Manana 			}
4870d42244a0SJan Schmidt 			if (!ret && time_seq) {
4871d42244a0SJan Schmidt 				/*
4872d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4873d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4874d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4875d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4876d42244a0SJan Schmidt 				 * on our lock and cycle.
4877d42244a0SJan Schmidt 				 */
4878cf538830SJan Schmidt 				free_extent_buffer(next);
4879d42244a0SJan Schmidt 				btrfs_release_path(path);
4880d42244a0SJan Schmidt 				cond_resched();
4881d42244a0SJan Schmidt 				goto again;
4882d42244a0SJan Schmidt 			}
48830e46318dSJosef Bacik 			if (!ret)
48840e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4885bd681513SChris Mason 		}
4886d97e63b6SChris Mason 		break;
4887d97e63b6SChris Mason 	}
4888d97e63b6SChris Mason 	path->slots[level] = slot;
4889d97e63b6SChris Mason 	while (1) {
4890d97e63b6SChris Mason 		level--;
4891d97e63b6SChris Mason 		path->nodes[level] = next;
4892d97e63b6SChris Mason 		path->slots[level] = 0;
4893a74a4b97SChris Mason 		if (!path->skip_locking)
4894ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4895d97e63b6SChris Mason 		if (!level)
4896d97e63b6SChris Mason 			break;
4897b4ce94deSChris Mason 
4898d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4899cda79c54SDavid Sterba 					    0, &key);
4900bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
49018e73f275SChris Mason 			goto again;
49028e73f275SChris Mason 
490376a05b35SChris Mason 		if (ret < 0) {
4904b3b4aa74SDavid Sterba 			btrfs_release_path(path);
490576a05b35SChris Mason 			goto done;
490676a05b35SChris Mason 		}
490776a05b35SChris Mason 
4908bdcdd86cSFilipe Manana 		if (!path->skip_locking) {
4909bdcdd86cSFilipe Manana 			if (path->nowait) {
4910bdcdd86cSFilipe Manana 				if (!btrfs_try_tree_read_lock(next)) {
4911bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4912bdcdd86cSFilipe Manana 					goto done;
4913bdcdd86cSFilipe Manana 				}
4914bdcdd86cSFilipe Manana 			} else {
49150e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4916d97e63b6SChris Mason 			}
4917bdcdd86cSFilipe Manana 		}
4918bdcdd86cSFilipe Manana 	}
49198e73f275SChris Mason 	ret = 0;
4920925baeddSChris Mason done:
4921f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
4922d96b3424SFilipe Manana 	if (need_commit_sem) {
4923d96b3424SFilipe Manana 		int ret2;
4924d96b3424SFilipe Manana 
4925d96b3424SFilipe Manana 		path->need_commit_sem = 1;
4926d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
4927d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
4928d96b3424SFilipe Manana 		if (ret2)
4929d96b3424SFilipe Manana 			ret = ret2;
4930d96b3424SFilipe Manana 	}
49318e73f275SChris Mason 
49328e73f275SChris Mason 	return ret;
4933d97e63b6SChris Mason }
49340b86a832SChris Mason 
4935890d2b1aSJosef Bacik int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
4936890d2b1aSJosef Bacik {
4937890d2b1aSJosef Bacik 	path->slots[0]++;
4938890d2b1aSJosef Bacik 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
4939890d2b1aSJosef Bacik 		return btrfs_next_old_leaf(root, path, time_seq);
4940890d2b1aSJosef Bacik 	return 0;
4941890d2b1aSJosef Bacik }
4942890d2b1aSJosef Bacik 
49433f157a2fSChris Mason /*
49443f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
49453f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
49463f157a2fSChris Mason  *
49473f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
49483f157a2fSChris Mason  */
49490b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
49500b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
49510b86a832SChris Mason 			int type)
49520b86a832SChris Mason {
49530b86a832SChris Mason 	struct btrfs_key found_key;
49540b86a832SChris Mason 	struct extent_buffer *leaf;
4955e02119d5SChris Mason 	u32 nritems;
49560b86a832SChris Mason 	int ret;
49570b86a832SChris Mason 
49580b86a832SChris Mason 	while (1) {
49590b86a832SChris Mason 		if (path->slots[0] == 0) {
49600b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
49610b86a832SChris Mason 			if (ret != 0)
49620b86a832SChris Mason 				return ret;
49630b86a832SChris Mason 		} else {
49640b86a832SChris Mason 			path->slots[0]--;
49650b86a832SChris Mason 		}
49660b86a832SChris Mason 		leaf = path->nodes[0];
4967e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
4968e02119d5SChris Mason 		if (nritems == 0)
4969e02119d5SChris Mason 			return 1;
4970e02119d5SChris Mason 		if (path->slots[0] == nritems)
4971e02119d5SChris Mason 			path->slots[0]--;
4972e02119d5SChris Mason 
49730b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4974e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
4975e02119d5SChris Mason 			break;
49760a4eefbbSYan Zheng 		if (found_key.type == type)
49770a4eefbbSYan Zheng 			return 0;
4978e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
4979e02119d5SChris Mason 		    found_key.type < type)
4980e02119d5SChris Mason 			break;
49810b86a832SChris Mason 	}
49820b86a832SChris Mason 	return 1;
49830b86a832SChris Mason }
4984ade2e0b3SWang Shilong 
4985ade2e0b3SWang Shilong /*
4986ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
4987ade2e0b3SWang Shilong  * min objecitd.
4988ade2e0b3SWang Shilong  *
4989ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4990ade2e0b3SWang Shilong  */
4991ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
4992ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
4993ade2e0b3SWang Shilong {
4994ade2e0b3SWang Shilong 	struct btrfs_key found_key;
4995ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
4996ade2e0b3SWang Shilong 	u32 nritems;
4997ade2e0b3SWang Shilong 	int ret;
4998ade2e0b3SWang Shilong 
4999ade2e0b3SWang Shilong 	while (1) {
5000ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5001ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5002ade2e0b3SWang Shilong 			if (ret != 0)
5003ade2e0b3SWang Shilong 				return ret;
5004ade2e0b3SWang Shilong 		} else {
5005ade2e0b3SWang Shilong 			path->slots[0]--;
5006ade2e0b3SWang Shilong 		}
5007ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5008ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5009ade2e0b3SWang Shilong 		if (nritems == 0)
5010ade2e0b3SWang Shilong 			return 1;
5011ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5012ade2e0b3SWang Shilong 			path->slots[0]--;
5013ade2e0b3SWang Shilong 
5014ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5015ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5016ade2e0b3SWang Shilong 			break;
5017ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5018ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5019ade2e0b3SWang Shilong 			return 0;
5020ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5021ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5022ade2e0b3SWang Shilong 			break;
5023ade2e0b3SWang Shilong 	}
5024ade2e0b3SWang Shilong 	return 1;
5025ade2e0b3SWang Shilong }
5026226463d7SJosef Bacik 
5027226463d7SJosef Bacik int __init btrfs_ctree_init(void)
5028226463d7SJosef Bacik {
5029226463d7SJosef Bacik 	btrfs_path_cachep = kmem_cache_create("btrfs_path",
5030226463d7SJosef Bacik 			sizeof(struct btrfs_path), 0,
5031226463d7SJosef Bacik 			SLAB_MEM_SPREAD, NULL);
5032226463d7SJosef Bacik 	if (!btrfs_path_cachep)
5033226463d7SJosef Bacik 		return -ENOMEM;
5034226463d7SJosef Bacik 	return 0;
5035226463d7SJosef Bacik }
5036226463d7SJosef Bacik 
5037226463d7SJosef Bacik void __cold btrfs_ctree_exit(void)
5038226463d7SJosef Bacik {
5039226463d7SJosef Bacik 	kmem_cache_destroy(btrfs_path_cachep);
5040226463d7SJosef Bacik }
5041