xref: /openbmc/linux/fs/btrfs/ctree.c (revision 4aec05fa5a190d641664c2bca8ad270cf8190b8c)
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 {
187a4c853afSChenXiaoSong 	might_sleep();
188a4c853afSChenXiaoSong 
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) {
467*4aec05faSJosef Bacik 			ret = btrfs_set_disk_extent_flags(trans, buf, new_flags);
468be1a5564SMark Fasheh 			if (ret)
469be1a5564SMark Fasheh 				return ret;
4705d4f98a2SYan Zheng 		}
4715d4f98a2SYan Zheng 	} else {
4725d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
4735d4f98a2SYan Zheng 			if (root->root_key.objectid ==
4745d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
475e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
4765d4f98a2SYan Zheng 			else
477e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
478692826b2SJeff Mahoney 			if (ret)
479692826b2SJeff Mahoney 				return ret;
480e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
481692826b2SJeff Mahoney 			if (ret)
482692826b2SJeff Mahoney 				return ret;
4835d4f98a2SYan Zheng 		}
484190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, buf);
485f0486c68SYan, Zheng 		*last_ref = 1;
4865d4f98a2SYan Zheng 	}
4875d4f98a2SYan Zheng 	return 0;
4885d4f98a2SYan Zheng }
4895d4f98a2SYan Zheng 
4905d4f98a2SYan Zheng /*
491d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
492d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
493d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
494d397712bSChris Mason  * dirty again.
495d352ac68SChris Mason  *
496d352ac68SChris Mason  * search_start -- an allocation hint for the new block
497d352ac68SChris Mason  *
498d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
499d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
500d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
501d352ac68SChris Mason  */
502d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
5035f39d397SChris Mason 			     struct btrfs_root *root,
5045f39d397SChris Mason 			     struct extent_buffer *buf,
5055f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
5065f39d397SChris Mason 			     struct extent_buffer **cow_ret,
5079631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
5089631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
5096702ed49SChris Mason {
5100b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5115d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
5125f39d397SChris Mason 	struct extent_buffer *cow;
513be1a5564SMark Fasheh 	int level, ret;
514f0486c68SYan, Zheng 	int last_ref = 0;
515925baeddSChris Mason 	int unlock_orig = 0;
5160f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
5176702ed49SChris Mason 
518925baeddSChris Mason 	if (*cow_ret == buf)
519925baeddSChris Mason 		unlock_orig = 1;
520925baeddSChris Mason 
52149d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
522925baeddSChris Mason 
52392a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
5240b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
52592a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
52627cdeb70SMiao Xie 		trans->transid != root->last_trans);
5275f39d397SChris Mason 
5287bb86316SChris Mason 	level = btrfs_header_level(buf);
52931840ae1SZheng Yan 
5305d4f98a2SYan Zheng 	if (level == 0)
5315d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
5325d4f98a2SYan Zheng 	else
5335d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
5345d4f98a2SYan Zheng 
5350f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
5365d4f98a2SYan Zheng 		parent_start = parent->start;
5375d4f98a2SYan Zheng 
53879bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
53979bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
54079bd3712SFilipe Manana 				     search_start, empty_size, nest);
5416702ed49SChris Mason 	if (IS_ERR(cow))
5426702ed49SChris Mason 		return PTR_ERR(cow);
5436702ed49SChris Mason 
544b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
545b4ce94deSChris Mason 
54658e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
547db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
5485f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
5495d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
5505d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
5515d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
5525d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
5535d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
5545d4f98a2SYan Zheng 	else
5555f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
5566702ed49SChris Mason 
557de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
5582b82032cSYan Zheng 
559be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
560b68dc2a9SMark Fasheh 	if (ret) {
561572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
562572c83acSJosef Bacik 		free_extent_buffer(cow);
56366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
564b68dc2a9SMark Fasheh 		return ret;
565b68dc2a9SMark Fasheh 	}
5661a40e23bSZheng Yan 
56792a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
56883d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
56993314e3bSZhaolei 		if (ret) {
570572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
571572c83acSJosef Bacik 			free_extent_buffer(cow);
57266642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
57383d4cfd4SJosef Bacik 			return ret;
57483d4cfd4SJosef Bacik 		}
57593314e3bSZhaolei 	}
5763fd0a558SYan, Zheng 
5776702ed49SChris Mason 	if (buf == root->node) {
578925baeddSChris Mason 		WARN_ON(parent && parent != buf);
5795d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
5805d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
5815d4f98a2SYan Zheng 			parent_start = buf->start;
582925baeddSChris Mason 
58367439dadSDavid Sterba 		atomic_inc(&cow->refs);
584406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
585d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
586240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
587925baeddSChris Mason 
5887a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
5897a163608SFilipe Manana 				      parent_start, last_ref);
5905f39d397SChris Mason 		free_extent_buffer(buf);
5910b86a832SChris Mason 		add_root_to_dirty_list(root);
5926702ed49SChris Mason 	} else {
5935d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
594f3a84ccdSFilipe Manana 		btrfs_tree_mod_log_insert_key(parent, parent_slot,
59533cff222SFilipe Manana 					      BTRFS_MOD_LOG_KEY_REPLACE);
5965f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
597db94535dSChris Mason 					cow->start);
59874493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
59974493f7aSChris Mason 					      trans->transid);
6006702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
6015de865eeSFilipe David Borba Manana 		if (last_ref) {
602f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
6035de865eeSFilipe David Borba Manana 			if (ret) {
604572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
605572c83acSJosef Bacik 				free_extent_buffer(cow);
60666642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
6075de865eeSFilipe David Borba Manana 				return ret;
6085de865eeSFilipe David Borba Manana 			}
6095de865eeSFilipe David Borba Manana 		}
6107a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
6117a163608SFilipe Manana 				      parent_start, last_ref);
6126702ed49SChris Mason 	}
613925baeddSChris Mason 	if (unlock_orig)
614925baeddSChris Mason 		btrfs_tree_unlock(buf);
6153083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
6166702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
6176702ed49SChris Mason 	*cow_ret = cow;
6186702ed49SChris Mason 	return 0;
6196702ed49SChris Mason }
6206702ed49SChris Mason 
6215d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
6225d4f98a2SYan Zheng 				   struct btrfs_root *root,
6235d4f98a2SYan Zheng 				   struct extent_buffer *buf)
6245d4f98a2SYan Zheng {
625f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
626faa2dbf0SJosef Bacik 		return 0;
627fccb84c9SDavid Sterba 
628d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
629d1980131SDavid Sterba 	smp_mb__before_atomic();
630f1ebcc74SLiu Bo 
631f1ebcc74SLiu Bo 	/*
632f1ebcc74SLiu Bo 	 * We do not need to cow a block if
633f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
634f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
635f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
636f1ebcc74SLiu Bo 	 *
637f1ebcc74SLiu Bo 	 * What is forced COW:
63801327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
63952042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
640f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
641f1ebcc74SLiu Bo 	 */
6425d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
6435d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
6445d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
645f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
64627cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
6475d4f98a2SYan Zheng 		return 0;
6485d4f98a2SYan Zheng 	return 1;
6495d4f98a2SYan Zheng }
6505d4f98a2SYan Zheng 
651d352ac68SChris Mason /*
652d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
65301327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
654d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
655d352ac68SChris Mason  */
656d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
6575f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
6585f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
6599631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
6609631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
66102217ed2SChris Mason {
6620b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6636702ed49SChris Mason 	u64 search_start;
664f510cfecSChris Mason 	int ret;
665dc17ff8fSChris Mason 
66683354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
66783354f07SJosef Bacik 		btrfs_err(fs_info,
66883354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
66983354f07SJosef Bacik 
6700b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
67131b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
672c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
6730b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
67431b1a2bdSJulia Lawall 
6750b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
67631b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
6770b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
678dc17ff8fSChris Mason 
6795d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
68002217ed2SChris Mason 		*cow_ret = buf;
68102217ed2SChris Mason 		return 0;
68202217ed2SChris Mason 	}
683c487685dSChris Mason 
684ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
685b4ce94deSChris Mason 
686f616f5cdSQu Wenruo 	/*
687f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
688f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
689f616f5cdSQu Wenruo 	 *
690f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
691f616f5cdSQu Wenruo 	 */
692f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
693f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
6949631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
6951abe9b8aSliubo 
6961abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
6971abe9b8aSliubo 
698f510cfecSChris Mason 	return ret;
6992c90e5d6SChris Mason }
700f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
7016702ed49SChris Mason 
702d352ac68SChris Mason /*
703d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
704d352ac68SChris Mason  * node are actually close by
705d352ac68SChris Mason  */
7066b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
7076702ed49SChris Mason {
7086b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
7096702ed49SChris Mason 		return 1;
7106b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
7116702ed49SChris Mason 		return 1;
71202217ed2SChris Mason 	return 0;
71302217ed2SChris Mason }
71402217ed2SChris Mason 
715ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
716ce6ef5abSDavid Sterba 
717ce6ef5abSDavid Sterba /*
718ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
719ce6ef5abSDavid Sterba  * we can avoid the conversion.
720ce6ef5abSDavid Sterba  */
721ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
722ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
723ce6ef5abSDavid Sterba {
724ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
725ce6ef5abSDavid Sterba 
726ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
727ce6ef5abSDavid Sterba }
728ce6ef5abSDavid Sterba 
729ce6ef5abSDavid Sterba #else
730ce6ef5abSDavid Sterba 
731081e9573SChris Mason /*
732081e9573SChris Mason  * compare two keys in a memcmp fashion
733081e9573SChris Mason  */
734310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
735310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
736081e9573SChris Mason {
737081e9573SChris Mason 	struct btrfs_key k1;
738081e9573SChris Mason 
739081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
740081e9573SChris Mason 
74120736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
742081e9573SChris Mason }
743ce6ef5abSDavid Sterba #endif
744081e9573SChris Mason 
745f3465ca4SJosef Bacik /*
746f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
747f3465ca4SJosef Bacik  */
748e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
749f3465ca4SJosef Bacik {
750f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
751f3465ca4SJosef Bacik 		return 1;
752f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
753f3465ca4SJosef Bacik 		return -1;
754f3465ca4SJosef Bacik 	if (k1->type > k2->type)
755f3465ca4SJosef Bacik 		return 1;
756f3465ca4SJosef Bacik 	if (k1->type < k2->type)
757f3465ca4SJosef Bacik 		return -1;
758f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
759f3465ca4SJosef Bacik 		return 1;
760f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
761f3465ca4SJosef Bacik 		return -1;
762f3465ca4SJosef Bacik 	return 0;
763f3465ca4SJosef Bacik }
764081e9573SChris Mason 
765d352ac68SChris Mason /*
766d352ac68SChris Mason  * this is used by the defrag code to go through all the
767d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
768d352ac68SChris Mason  * disk order is close to key order
769d352ac68SChris Mason  */
7706702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
7715f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
772de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
773a6b6e75eSChris Mason 		       struct btrfs_key *progress)
7746702ed49SChris Mason {
7750b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
7766b80053dSChris Mason 	struct extent_buffer *cur;
7776702ed49SChris Mason 	u64 blocknr;
778e9d0b13bSChris Mason 	u64 search_start = *last_ret;
779e9d0b13bSChris Mason 	u64 last_block = 0;
7806702ed49SChris Mason 	u64 other;
7816702ed49SChris Mason 	u32 parent_nritems;
7826702ed49SChris Mason 	int end_slot;
7836702ed49SChris Mason 	int i;
7846702ed49SChris Mason 	int err = 0;
7856b80053dSChris Mason 	u32 blocksize;
786081e9573SChris Mason 	int progress_passed = 0;
787081e9573SChris Mason 	struct btrfs_disk_key disk_key;
7886702ed49SChris Mason 
7890b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
7900b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
79186479a04SChris Mason 
7926b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
7930b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
7945dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
7956702ed49SChris Mason 
7965dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
7976702ed49SChris Mason 		return 0;
7986702ed49SChris Mason 
7995dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
8006702ed49SChris Mason 		int close = 1;
801a6b6e75eSChris Mason 
802081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
803081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
804081e9573SChris Mason 			continue;
805081e9573SChris Mason 
806081e9573SChris Mason 		progress_passed = 1;
8076b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
808e9d0b13bSChris Mason 		if (last_block == 0)
809e9d0b13bSChris Mason 			last_block = blocknr;
8105708b959SChris Mason 
8116702ed49SChris Mason 		if (i > 0) {
8126b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
8136b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
8146702ed49SChris Mason 		}
8155dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
8166b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
8176b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
8186702ed49SChris Mason 		}
819e9d0b13bSChris Mason 		if (close) {
820e9d0b13bSChris Mason 			last_block = blocknr;
8216702ed49SChris Mason 			continue;
822e9d0b13bSChris Mason 		}
8236702ed49SChris Mason 
824206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
825206983b7SJosef Bacik 		if (IS_ERR(cur))
82664c043deSLiu Bo 			return PTR_ERR(cur);
827e9d0b13bSChris Mason 		if (search_start == 0)
8286b80053dSChris Mason 			search_start = last_block;
829e9d0b13bSChris Mason 
830e7a84565SChris Mason 		btrfs_tree_lock(cur);
8316b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
832e7a84565SChris Mason 					&cur, search_start,
8336b80053dSChris Mason 					min(16 * blocksize,
8349631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
8359631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
836252c38f0SYan 		if (err) {
837e7a84565SChris Mason 			btrfs_tree_unlock(cur);
8386b80053dSChris Mason 			free_extent_buffer(cur);
8396702ed49SChris Mason 			break;
840252c38f0SYan 		}
841e7a84565SChris Mason 		search_start = cur->start;
842e7a84565SChris Mason 		last_block = cur->start;
843f2183bdeSChris Mason 		*last_ret = search_start;
844e7a84565SChris Mason 		btrfs_tree_unlock(cur);
845e7a84565SChris Mason 		free_extent_buffer(cur);
8466702ed49SChris Mason 	}
8476702ed49SChris Mason 	return err;
8486702ed49SChris Mason }
8496702ed49SChris Mason 
85074123bd7SChris Mason /*
851fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
8525f39d397SChris Mason  *
853a724f313SFilipe Manana  * The lower boundary for the search is specified by the slot number @first_slot.
854fdf8d595SAnand Jain  * Use a value of 0 to search over the whole extent buffer. Works for both
855fdf8d595SAnand Jain  * leaves and nodes.
85674123bd7SChris Mason  *
857fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
858fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
859fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
860fb81212cSFilipe Manana  *
861fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
862fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
86374123bd7SChris Mason  */
864fdf8d595SAnand Jain int btrfs_bin_search(struct extent_buffer *eb, int first_slot,
86567d5e289SMarcos Paulo de Souza 		     const struct btrfs_key *key, int *slot)
866be0e5c09SChris Mason {
867fb81212cSFilipe Manana 	unsigned long p;
868fb81212cSFilipe Manana 	int item_size;
869a724f313SFilipe Manana 	/*
870a724f313SFilipe Manana 	 * Use unsigned types for the low and high slots, so that we get a more
871a724f313SFilipe Manana 	 * efficient division in the search loop below.
872a724f313SFilipe Manana 	 */
873a724f313SFilipe Manana 	u32 low = first_slot;
874a724f313SFilipe Manana 	u32 high = btrfs_header_nritems(eb);
875be0e5c09SChris Mason 	int ret;
8765cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
877be0e5c09SChris Mason 
878a724f313SFilipe Manana 	if (unlikely(low > high)) {
8795e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
880a724f313SFilipe Manana 		 "%s: low (%u) > high (%u) eb %llu owner %llu level %d",
8815e24e9afSLiu Bo 			  __func__, low, high, eb->start,
8825e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
8835e24e9afSLiu Bo 		return -EINVAL;
8845e24e9afSLiu Bo 	}
8855e24e9afSLiu Bo 
886fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
887fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
888fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
889fb81212cSFilipe Manana 	} else {
890fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
891fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
892fb81212cSFilipe Manana 	}
893fb81212cSFilipe Manana 
894be0e5c09SChris Mason 	while (low < high) {
8955cd17f34SDavid Sterba 		unsigned long oip;
8965cd17f34SDavid Sterba 		unsigned long offset;
8975cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
8985cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
8995cd17f34SDavid Sterba 		int mid;
9005cd17f34SDavid Sterba 
901be0e5c09SChris Mason 		mid = (low + high) / 2;
9025f39d397SChris Mason 		offset = p + mid * item_size;
9035cd17f34SDavid Sterba 		oip = offset_in_page(offset);
9045f39d397SChris Mason 
9055cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
906884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
9075cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
908934d375bSChris Mason 
909884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
9105cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
9115cd17f34SDavid Sterba 		} else {
9125cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
9135f39d397SChris Mason 			tmp = &unaligned;
914479965d6SChris Mason 		}
915479965d6SChris Mason 
916be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
917be0e5c09SChris Mason 
918be0e5c09SChris Mason 		if (ret < 0)
919be0e5c09SChris Mason 			low = mid + 1;
920be0e5c09SChris Mason 		else if (ret > 0)
921be0e5c09SChris Mason 			high = mid;
922be0e5c09SChris Mason 		else {
923be0e5c09SChris Mason 			*slot = mid;
924be0e5c09SChris Mason 			return 0;
925be0e5c09SChris Mason 		}
926be0e5c09SChris Mason 	}
927be0e5c09SChris Mason 	*slot = low;
928be0e5c09SChris Mason 	return 1;
929be0e5c09SChris Mason }
930be0e5c09SChris Mason 
931f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
932f0486c68SYan, Zheng {
933f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
934f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
935f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
936f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
937f0486c68SYan, Zheng }
938f0486c68SYan, Zheng 
939f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
940f0486c68SYan, Zheng {
941f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
942f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
943f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
944f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
945f0486c68SYan, Zheng }
946f0486c68SYan, Zheng 
947d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
948d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
949d352ac68SChris Mason  */
9504b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
9514b231ae4SDavid Sterba 					   int slot)
952bb803951SChris Mason {
953ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
954789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
955416bc658SJosef Bacik 	struct extent_buffer *eb;
956416bc658SJosef Bacik 
957fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
958fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
959ca7a79adSChris Mason 
960d4694728SJosef Bacik 	ASSERT(level);
961ca7a79adSChris Mason 
962789d6a3aSQu Wenruo 	check.level = level - 1;
963789d6a3aSQu Wenruo 	check.transid = btrfs_node_ptr_generation(parent, slot);
964789d6a3aSQu Wenruo 	check.owner_root = btrfs_header_owner(parent);
965789d6a3aSQu Wenruo 	check.has_first_key = true;
966789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(parent, &check.first_key, slot);
967789d6a3aSQu Wenruo 
968d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
969789d6a3aSQu Wenruo 			     &check);
9704eb150d6SQu Wenruo 	if (IS_ERR(eb))
9714eb150d6SQu Wenruo 		return eb;
9724eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
973416bc658SJosef Bacik 		free_extent_buffer(eb);
9744eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
975416bc658SJosef Bacik 	}
976416bc658SJosef Bacik 
977416bc658SJosef Bacik 	return eb;
978bb803951SChris Mason }
979bb803951SChris Mason 
980d352ac68SChris Mason /*
981d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
982d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
983d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
984d352ac68SChris Mason  */
985e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
98698ed5174SChris Mason 			 struct btrfs_root *root,
98798ed5174SChris Mason 			 struct btrfs_path *path, int level)
988bb803951SChris Mason {
9890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
9905f39d397SChris Mason 	struct extent_buffer *right = NULL;
9915f39d397SChris Mason 	struct extent_buffer *mid;
9925f39d397SChris Mason 	struct extent_buffer *left = NULL;
9935f39d397SChris Mason 	struct extent_buffer *parent = NULL;
994bb803951SChris Mason 	int ret = 0;
995bb803951SChris Mason 	int wret;
996bb803951SChris Mason 	int pslot;
997bb803951SChris Mason 	int orig_slot = path->slots[level];
99879f95c82SChris Mason 	u64 orig_ptr;
999bb803951SChris Mason 
100098e6b1ebSLiu Bo 	ASSERT(level > 0);
1001bb803951SChris Mason 
10025f39d397SChris Mason 	mid = path->nodes[level];
1003b4ce94deSChris Mason 
1004ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
10057bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
10067bb86316SChris Mason 
10071d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
100879f95c82SChris Mason 
1009a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
10105f39d397SChris Mason 		parent = path->nodes[level + 1];
1011bb803951SChris Mason 		pslot = path->slots[level + 1];
1012a05a9bb1SLi Zefan 	}
1013bb803951SChris Mason 
101440689478SChris Mason 	/*
101540689478SChris Mason 	 * deal with the case where there is only one pointer in the root
101640689478SChris Mason 	 * by promoting the node below to a root
101740689478SChris Mason 	 */
10185f39d397SChris Mason 	if (!parent) {
10195f39d397SChris Mason 		struct extent_buffer *child;
1020bb803951SChris Mason 
10215f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1022bb803951SChris Mason 			return 0;
1023bb803951SChris Mason 
1024bb803951SChris Mason 		/* promote the child to a root */
10254b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1026fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1027fb770ae4SLiu Bo 			ret = PTR_ERR(child);
10280b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1029305a26afSMark Fasheh 			goto enospc;
1030305a26afSMark Fasheh 		}
1031305a26afSMark Fasheh 
1032925baeddSChris Mason 		btrfs_tree_lock(child);
10339631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
10349631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
1035f0486c68SYan, Zheng 		if (ret) {
1036f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1037f0486c68SYan, Zheng 			free_extent_buffer(child);
1038f0486c68SYan, Zheng 			goto enospc;
1039f0486c68SYan, Zheng 		}
10402f375ab9SYan 
1041406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
1042d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1043240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1044925baeddSChris Mason 
10450b86a832SChris Mason 		add_root_to_dirty_list(root);
1046925baeddSChris Mason 		btrfs_tree_unlock(child);
1047b4ce94deSChris Mason 
1048925baeddSChris Mason 		path->locks[level] = 0;
1049bb803951SChris Mason 		path->nodes[level] = NULL;
1050190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, mid);
1051925baeddSChris Mason 		btrfs_tree_unlock(mid);
1052bb803951SChris Mason 		/* once for the path */
10535f39d397SChris Mason 		free_extent_buffer(mid);
1054f0486c68SYan, Zheng 
1055f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10567a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1057bb803951SChris Mason 		/* once for the root ptr */
10583083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1059f0486c68SYan, Zheng 		return 0;
1060bb803951SChris Mason 	}
10615f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
10620b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1063bb803951SChris Mason 		return 0;
1064bb803951SChris Mason 
10659cf14029SJosef Bacik 	if (pslot) {
10664b231ae4SDavid Sterba 		left = btrfs_read_node_slot(parent, pslot - 1);
10679cf14029SJosef Bacik 		if (IS_ERR(left)) {
10689cf14029SJosef Bacik 			ret = PTR_ERR(left);
1069fb770ae4SLiu Bo 			left = NULL;
10709cf14029SJosef Bacik 			goto enospc;
10719cf14029SJosef Bacik 		}
1072fb770ae4SLiu Bo 
1073bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
10745f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
10759631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
1076bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
107754aa1f4dSChris Mason 		if (wret) {
107854aa1f4dSChris Mason 			ret = wret;
107954aa1f4dSChris Mason 			goto enospc;
108054aa1f4dSChris Mason 		}
10812cc58cf2SChris Mason 	}
1082fb770ae4SLiu Bo 
10839cf14029SJosef Bacik 	if (pslot + 1 < btrfs_header_nritems(parent)) {
10844b231ae4SDavid Sterba 		right = btrfs_read_node_slot(parent, pslot + 1);
10859cf14029SJosef Bacik 		if (IS_ERR(right)) {
10869cf14029SJosef Bacik 			ret = PTR_ERR(right);
1087fb770ae4SLiu Bo 			right = NULL;
10889cf14029SJosef Bacik 			goto enospc;
10899cf14029SJosef Bacik 		}
1090fb770ae4SLiu Bo 
1091bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
10925f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
10939631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
1094bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
10952cc58cf2SChris Mason 		if (wret) {
10962cc58cf2SChris Mason 			ret = wret;
10972cc58cf2SChris Mason 			goto enospc;
10982cc58cf2SChris Mason 		}
10992cc58cf2SChris Mason 	}
11002cc58cf2SChris Mason 
11012cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
11025f39d397SChris Mason 	if (left) {
11035f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1104d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
110579f95c82SChris Mason 		if (wret < 0)
110679f95c82SChris Mason 			ret = wret;
1107bb803951SChris Mason 	}
110879f95c82SChris Mason 
110979f95c82SChris Mason 	/*
111079f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
111179f95c82SChris Mason 	 */
11125f39d397SChris Mason 	if (right) {
1113d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
111454aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
111579f95c82SChris Mason 			ret = wret;
11165f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
1117190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, right);
1118925baeddSChris Mason 			btrfs_tree_unlock(right);
1119afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1120f0486c68SYan, Zheng 			root_sub_used(root, right->len);
11217a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
11227a163608SFilipe Manana 					      0, 1);
11233083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1124f0486c68SYan, Zheng 			right = NULL;
1125bb803951SChris Mason 		} else {
11265f39d397SChris Mason 			struct btrfs_disk_key right_key;
11275f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1128f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
112933cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
11300e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11315f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
11325f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1133bb803951SChris Mason 		}
1134bb803951SChris Mason 	}
11355f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
113679f95c82SChris Mason 		/*
113779f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
113879f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
113979f95c82SChris Mason 		 * could try to delete the only pointer in this node.
114079f95c82SChris Mason 		 * So, pull some keys from the left.
114179f95c82SChris Mason 		 * There has to be a left pointer at this point because
114279f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
114379f95c82SChris Mason 		 * right
114479f95c82SChris Mason 		 */
1145305a26afSMark Fasheh 		if (!left) {
1146305a26afSMark Fasheh 			ret = -EROFS;
11470b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1148305a26afSMark Fasheh 			goto enospc;
1149305a26afSMark Fasheh 		}
115055d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
115154aa1f4dSChris Mason 		if (wret < 0) {
115279f95c82SChris Mason 			ret = wret;
115354aa1f4dSChris Mason 			goto enospc;
115454aa1f4dSChris Mason 		}
1155bce4eae9SChris Mason 		if (wret == 1) {
1156d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1157bce4eae9SChris Mason 			if (wret < 0)
1158bce4eae9SChris Mason 				ret = wret;
1159bce4eae9SChris Mason 		}
116079f95c82SChris Mason 		BUG_ON(wret == 1);
116179f95c82SChris Mason 	}
11625f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
1163190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, mid);
1164925baeddSChris Mason 		btrfs_tree_unlock(mid);
1165afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1166f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
11677a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
11683083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1169f0486c68SYan, Zheng 		mid = NULL;
117079f95c82SChris Mason 	} else {
117179f95c82SChris Mason 		/* update the parent key to reflect our changes */
11725f39d397SChris Mason 		struct btrfs_disk_key mid_key;
11735f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1174f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
117533cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
11760e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
11775f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
11785f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
117979f95c82SChris Mason 	}
1180bb803951SChris Mason 
118179f95c82SChris Mason 	/* update the path */
11825f39d397SChris Mason 	if (left) {
11835f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
118467439dadSDavid Sterba 			atomic_inc(&left->refs);
1185925baeddSChris Mason 			/* left was locked after cow */
11865f39d397SChris Mason 			path->nodes[level] = left;
1187bb803951SChris Mason 			path->slots[level + 1] -= 1;
1188bb803951SChris Mason 			path->slots[level] = orig_slot;
1189925baeddSChris Mason 			if (mid) {
1190925baeddSChris Mason 				btrfs_tree_unlock(mid);
11915f39d397SChris Mason 				free_extent_buffer(mid);
1192925baeddSChris Mason 			}
1193bb803951SChris Mason 		} else {
11945f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1195bb803951SChris Mason 			path->slots[level] = orig_slot;
1196bb803951SChris Mason 		}
1197bb803951SChris Mason 	}
119879f95c82SChris Mason 	/* double check we haven't messed things up */
1199e20d96d6SChris Mason 	if (orig_ptr !=
12005f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
120179f95c82SChris Mason 		BUG();
120254aa1f4dSChris Mason enospc:
1203925baeddSChris Mason 	if (right) {
1204925baeddSChris Mason 		btrfs_tree_unlock(right);
12055f39d397SChris Mason 		free_extent_buffer(right);
1206925baeddSChris Mason 	}
1207925baeddSChris Mason 	if (left) {
1208925baeddSChris Mason 		if (path->nodes[level] != left)
1209925baeddSChris Mason 			btrfs_tree_unlock(left);
12105f39d397SChris Mason 		free_extent_buffer(left);
1211925baeddSChris Mason 	}
1212bb803951SChris Mason 	return ret;
1213bb803951SChris Mason }
1214bb803951SChris Mason 
1215d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1216d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1217d352ac68SChris Mason  * have to be pessimistic.
1218d352ac68SChris Mason  */
1219d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1220e66f709bSChris Mason 					  struct btrfs_root *root,
1221e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1222e66f709bSChris Mason {
12230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12245f39d397SChris Mason 	struct extent_buffer *right = NULL;
12255f39d397SChris Mason 	struct extent_buffer *mid;
12265f39d397SChris Mason 	struct extent_buffer *left = NULL;
12275f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1228e66f709bSChris Mason 	int ret = 0;
1229e66f709bSChris Mason 	int wret;
1230e66f709bSChris Mason 	int pslot;
1231e66f709bSChris Mason 	int orig_slot = path->slots[level];
1232e66f709bSChris Mason 
1233e66f709bSChris Mason 	if (level == 0)
1234e66f709bSChris Mason 		return 1;
1235e66f709bSChris Mason 
12365f39d397SChris Mason 	mid = path->nodes[level];
12377bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1238e66f709bSChris Mason 
1239a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
12405f39d397SChris Mason 		parent = path->nodes[level + 1];
1241e66f709bSChris Mason 		pslot = path->slots[level + 1];
1242a05a9bb1SLi Zefan 	}
1243e66f709bSChris Mason 
12445f39d397SChris Mason 	if (!parent)
1245e66f709bSChris Mason 		return 1;
1246e66f709bSChris Mason 
12479cf14029SJosef Bacik 	/* first, try to make some room in the middle buffer */
12489cf14029SJosef Bacik 	if (pslot) {
12499cf14029SJosef Bacik 		u32 left_nr;
12509cf14029SJosef Bacik 
12514b231ae4SDavid Sterba 		left = btrfs_read_node_slot(parent, pslot - 1);
1252fb770ae4SLiu Bo 		if (IS_ERR(left))
12539cf14029SJosef Bacik 			return PTR_ERR(left);
1254925baeddSChris Mason 
1255bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1256b4ce94deSChris Mason 
12575f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
12580b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
125933ade1f8SChris Mason 			wret = 1;
126033ade1f8SChris Mason 		} else {
12615f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
12629631e4ccSJosef Bacik 					      pslot - 1, &left,
1263bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
126454aa1f4dSChris Mason 			if (ret)
126554aa1f4dSChris Mason 				wret = 1;
126654aa1f4dSChris Mason 			else {
1267d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
126854aa1f4dSChris Mason 			}
126933ade1f8SChris Mason 		}
1270e66f709bSChris Mason 		if (wret < 0)
1271e66f709bSChris Mason 			ret = wret;
1272e66f709bSChris Mason 		if (wret == 0) {
12735f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1274e66f709bSChris Mason 			orig_slot += left_nr;
12755f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1276f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
127733cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
12780e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
12795f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
12805f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12815f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
12825f39d397SChris Mason 				path->nodes[level] = left;
1283e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1284e66f709bSChris Mason 				path->slots[level] = orig_slot;
1285925baeddSChris Mason 				btrfs_tree_unlock(mid);
12865f39d397SChris Mason 				free_extent_buffer(mid);
1287e66f709bSChris Mason 			} else {
1288e66f709bSChris Mason 				orig_slot -=
12895f39d397SChris Mason 					btrfs_header_nritems(left);
1290e66f709bSChris Mason 				path->slots[level] = orig_slot;
1291925baeddSChris Mason 				btrfs_tree_unlock(left);
12925f39d397SChris Mason 				free_extent_buffer(left);
1293e66f709bSChris Mason 			}
1294e66f709bSChris Mason 			return 0;
1295e66f709bSChris Mason 		}
1296925baeddSChris Mason 		btrfs_tree_unlock(left);
12975f39d397SChris Mason 		free_extent_buffer(left);
1298e66f709bSChris Mason 	}
1299e66f709bSChris Mason 
1300e66f709bSChris Mason 	/*
1301e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1302e66f709bSChris Mason 	 */
13039cf14029SJosef Bacik 	if (pslot + 1 < btrfs_header_nritems(parent)) {
130433ade1f8SChris Mason 		u32 right_nr;
1305b4ce94deSChris Mason 
13069cf14029SJosef Bacik 		right = btrfs_read_node_slot(parent, pslot + 1);
13079cf14029SJosef Bacik 		if (IS_ERR(right))
13089cf14029SJosef Bacik 			return PTR_ERR(right);
13099cf14029SJosef Bacik 
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 
1872fdf8d595SAnand Jain 	return btrfs_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 
2051a4c853afSChenXiaoSong 	might_sleep();
2052a4c853afSChenXiaoSong 
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 
2329fdf8d595SAnand Jain 		ret = btrfs_bin_search(b, 0, 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 /*
2379f469c8bdSFilipe Manana  * Search the tree again to find a leaf with smaller keys.
2380f469c8bdSFilipe Manana  * Returns 0 if it found something.
2381f469c8bdSFilipe Manana  * Returns 1 if there are no smaller keys.
2382f469c8bdSFilipe Manana  * Returns < 0 on error.
2383f469c8bdSFilipe Manana  *
2384f469c8bdSFilipe Manana  * This may release the path, and so you may lose any locks held at the
2385f469c8bdSFilipe Manana  * time you call it.
2386f469c8bdSFilipe Manana  */
2387f469c8bdSFilipe Manana static int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
2388f469c8bdSFilipe Manana {
2389f469c8bdSFilipe Manana 	struct btrfs_key key;
2390f469c8bdSFilipe Manana 	struct btrfs_key orig_key;
2391f469c8bdSFilipe Manana 	struct btrfs_disk_key found_key;
2392f469c8bdSFilipe Manana 	int ret;
2393f469c8bdSFilipe Manana 
2394f469c8bdSFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
2395f469c8bdSFilipe Manana 	orig_key = key;
2396f469c8bdSFilipe Manana 
2397f469c8bdSFilipe Manana 	if (key.offset > 0) {
2398f469c8bdSFilipe Manana 		key.offset--;
2399f469c8bdSFilipe Manana 	} else if (key.type > 0) {
2400f469c8bdSFilipe Manana 		key.type--;
2401f469c8bdSFilipe Manana 		key.offset = (u64)-1;
2402f469c8bdSFilipe Manana 	} else if (key.objectid > 0) {
2403f469c8bdSFilipe Manana 		key.objectid--;
2404f469c8bdSFilipe Manana 		key.type = (u8)-1;
2405f469c8bdSFilipe Manana 		key.offset = (u64)-1;
2406f469c8bdSFilipe Manana 	} else {
2407f469c8bdSFilipe Manana 		return 1;
2408f469c8bdSFilipe Manana 	}
2409f469c8bdSFilipe Manana 
2410f469c8bdSFilipe Manana 	btrfs_release_path(path);
2411f469c8bdSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2412f469c8bdSFilipe Manana 	if (ret <= 0)
2413f469c8bdSFilipe Manana 		return ret;
2414f469c8bdSFilipe Manana 
2415f469c8bdSFilipe Manana 	/*
2416f469c8bdSFilipe Manana 	 * Previous key not found. Even if we were at slot 0 of the leaf we had
2417f469c8bdSFilipe Manana 	 * before releasing the path and calling btrfs_search_slot(), we now may
2418f469c8bdSFilipe Manana 	 * be in a slot pointing to the same original key - this can happen if
2419f469c8bdSFilipe Manana 	 * after we released the path, one of more items were moved from a
2420f469c8bdSFilipe Manana 	 * sibling leaf into the front of the leaf we had due to an insertion
2421f469c8bdSFilipe Manana 	 * (see push_leaf_right()).
2422f469c8bdSFilipe Manana 	 * If we hit this case and our slot is > 0 and just decrement the slot
2423f469c8bdSFilipe Manana 	 * so that the caller does not process the same key again, which may or
2424f469c8bdSFilipe Manana 	 * may not break the caller, depending on its logic.
2425f469c8bdSFilipe Manana 	 */
2426f469c8bdSFilipe Manana 	if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
2427f469c8bdSFilipe Manana 		btrfs_item_key(path->nodes[0], &found_key, path->slots[0]);
2428f469c8bdSFilipe Manana 		ret = comp_keys(&found_key, &orig_key);
2429f469c8bdSFilipe Manana 		if (ret == 0) {
2430f469c8bdSFilipe Manana 			if (path->slots[0] > 0) {
2431f469c8bdSFilipe Manana 				path->slots[0]--;
2432f469c8bdSFilipe Manana 				return 0;
2433f469c8bdSFilipe Manana 			}
2434f469c8bdSFilipe Manana 			/*
2435f469c8bdSFilipe Manana 			 * At slot 0, same key as before, it means orig_key is
2436f469c8bdSFilipe Manana 			 * the lowest, leftmost, key in the tree. We're done.
2437f469c8bdSFilipe Manana 			 */
2438f469c8bdSFilipe Manana 			return 1;
2439f469c8bdSFilipe Manana 		}
2440f469c8bdSFilipe Manana 	}
2441f469c8bdSFilipe Manana 
2442f469c8bdSFilipe Manana 	btrfs_item_key(path->nodes[0], &found_key, 0);
2443f469c8bdSFilipe Manana 	ret = comp_keys(&found_key, &key);
2444f469c8bdSFilipe Manana 	/*
2445f469c8bdSFilipe Manana 	 * We might have had an item with the previous key in the tree right
2446f469c8bdSFilipe Manana 	 * before we released our path. And after we released our path, that
2447f469c8bdSFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
2448f469c8bdSFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
2449f469c8bdSFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
2450f469c8bdSFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
2451f469c8bdSFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
2452f469c8bdSFilipe Manana 	 * the previous key we computed above.
2453f469c8bdSFilipe Manana 	 */
2454f469c8bdSFilipe Manana 	if (ret <= 0)
2455f469c8bdSFilipe Manana 		return 0;
2456f469c8bdSFilipe Manana 	return 1;
2457f469c8bdSFilipe Manana }
2458f469c8bdSFilipe Manana 
2459f469c8bdSFilipe Manana /*
24602f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
24612f38b3e1SArne Jansen  * instead the next or previous item should be returned.
24622f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
24632f38b3e1SArne Jansen  * otherwise.
24642f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
24652f38b3e1SArne Jansen  * return the next lower instead.
24662f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
24672f38b3e1SArne Jansen  * return the next higher instead.
24682f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
24692f38b3e1SArne Jansen  * < 0 on error
24702f38b3e1SArne Jansen  */
24712f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2472310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2473310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2474310712b2SOmar Sandoval 			       int return_any)
24752f38b3e1SArne Jansen {
24762f38b3e1SArne Jansen 	int ret;
24772f38b3e1SArne Jansen 	struct extent_buffer *leaf;
24782f38b3e1SArne Jansen 
24792f38b3e1SArne Jansen again:
24802f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
24812f38b3e1SArne Jansen 	if (ret <= 0)
24822f38b3e1SArne Jansen 		return ret;
24832f38b3e1SArne Jansen 	/*
24842f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
24852f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
24862f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
24872f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
24882f38b3e1SArne Jansen 	 * item.
24892f38b3e1SArne Jansen 	 */
24902f38b3e1SArne Jansen 	leaf = p->nodes[0];
24912f38b3e1SArne Jansen 
24922f38b3e1SArne Jansen 	if (find_higher) {
24932f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
24942f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
24952f38b3e1SArne Jansen 			if (ret <= 0)
24962f38b3e1SArne Jansen 				return ret;
24972f38b3e1SArne Jansen 			if (!return_any)
24982f38b3e1SArne Jansen 				return 1;
24992f38b3e1SArne Jansen 			/*
25002f38b3e1SArne Jansen 			 * no higher item found, return the next
25012f38b3e1SArne Jansen 			 * lower instead
25022f38b3e1SArne Jansen 			 */
25032f38b3e1SArne Jansen 			return_any = 0;
25042f38b3e1SArne Jansen 			find_higher = 0;
25052f38b3e1SArne Jansen 			btrfs_release_path(p);
25062f38b3e1SArne Jansen 			goto again;
25072f38b3e1SArne Jansen 		}
25082f38b3e1SArne Jansen 	} else {
25092f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
25102f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2511e6793769SArne Jansen 			if (ret < 0)
25122f38b3e1SArne Jansen 				return ret;
2513e6793769SArne Jansen 			if (!ret) {
251423c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
251523c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
251623c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2517e6793769SArne Jansen 				return 0;
2518e6793769SArne Jansen 			}
25192f38b3e1SArne Jansen 			if (!return_any)
25202f38b3e1SArne Jansen 				return 1;
25212f38b3e1SArne Jansen 			/*
25222f38b3e1SArne Jansen 			 * no lower item found, return the next
25232f38b3e1SArne Jansen 			 * higher instead
25242f38b3e1SArne Jansen 			 */
25252f38b3e1SArne Jansen 			return_any = 0;
25262f38b3e1SArne Jansen 			find_higher = 1;
25272f38b3e1SArne Jansen 			btrfs_release_path(p);
25282f38b3e1SArne Jansen 			goto again;
2529e6793769SArne Jansen 		} else {
25302f38b3e1SArne Jansen 			--p->slots[0];
25312f38b3e1SArne Jansen 		}
25322f38b3e1SArne Jansen 	}
25332f38b3e1SArne Jansen 	return 0;
25342f38b3e1SArne Jansen }
25352f38b3e1SArne Jansen 
25362f38b3e1SArne Jansen /*
25370ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
25380ff40a91SMarcos Paulo de Souza  * was not found.
25390ff40a91SMarcos Paulo de Souza  *
25400ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
25410ff40a91SMarcos Paulo de Souza  */
25420ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
25430ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
25440ff40a91SMarcos Paulo de Souza {
25450ff40a91SMarcos Paulo de Souza 	int ret;
25460ff40a91SMarcos Paulo de Souza 
25470ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
25480ff40a91SMarcos Paulo de Souza 	if (ret > 0)
25490ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
25500ff40a91SMarcos Paulo de Souza 
25510ff40a91SMarcos Paulo de Souza 	if (ret == 0)
25520ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
25530ff40a91SMarcos Paulo de Souza 
25540ff40a91SMarcos Paulo de Souza 	return ret;
25550ff40a91SMarcos Paulo de Souza }
25560ff40a91SMarcos Paulo de Souza 
255743dd529aSDavid Sterba /*
255862142be3SGabriel Niebler  * Search for a valid slot for the given path.
255962142be3SGabriel Niebler  *
256062142be3SGabriel Niebler  * @root:	The root node of the tree.
256162142be3SGabriel Niebler  * @key:	Will contain a valid item if found.
256262142be3SGabriel Niebler  * @path:	The starting point to validate the slot.
256362142be3SGabriel Niebler  *
256462142be3SGabriel Niebler  * Return: 0  if the item is valid
256562142be3SGabriel Niebler  *         1  if not found
256662142be3SGabriel Niebler  *         <0 if error.
256762142be3SGabriel Niebler  */
256862142be3SGabriel Niebler int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
256962142be3SGabriel Niebler 			      struct btrfs_path *path)
257062142be3SGabriel Niebler {
2571524f14bbSFilipe Manana 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
257262142be3SGabriel Niebler 		int ret;
257362142be3SGabriel Niebler 
257462142be3SGabriel Niebler 		ret = btrfs_next_leaf(root, path);
257562142be3SGabriel Niebler 		if (ret)
257662142be3SGabriel Niebler 			return ret;
257762142be3SGabriel Niebler 	}
2578524f14bbSFilipe Manana 
2579524f14bbSFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
258062142be3SGabriel Niebler 	return 0;
258162142be3SGabriel Niebler }
258262142be3SGabriel Niebler 
25830ff40a91SMarcos Paulo de Souza /*
258474123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
258574123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
258674123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
258774123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
258874123bd7SChris Mason  * higher levels
2589aa5d6bedSChris Mason  *
259074123bd7SChris Mason  */
2591b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
25925f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2593be0e5c09SChris Mason {
2594be0e5c09SChris Mason 	int i;
25955f39d397SChris Mason 	struct extent_buffer *t;
25960e82bcfeSDavid Sterba 	int ret;
25975f39d397SChris Mason 
2598234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2599be0e5c09SChris Mason 		int tslot = path->slots[i];
26000e82bcfeSDavid Sterba 
2601eb60ceacSChris Mason 		if (!path->nodes[i])
2602be0e5c09SChris Mason 			break;
26035f39d397SChris Mason 		t = path->nodes[i];
2604f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
260533cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
26060e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
26075f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2608d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2609be0e5c09SChris Mason 		if (tslot != 0)
2610be0e5c09SChris Mason 			break;
2611be0e5c09SChris Mason 	}
2612be0e5c09SChris Mason }
2613be0e5c09SChris Mason 
261474123bd7SChris Mason /*
261531840ae1SZheng Yan  * update item key.
261631840ae1SZheng Yan  *
261731840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
261831840ae1SZheng Yan  * that the new key won't break the order
261931840ae1SZheng Yan  */
2620b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2621b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2622310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
262331840ae1SZheng Yan {
262431840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
262531840ae1SZheng Yan 	struct extent_buffer *eb;
262631840ae1SZheng Yan 	int slot;
262731840ae1SZheng Yan 
262831840ae1SZheng Yan 	eb = path->nodes[0];
262931840ae1SZheng Yan 	slot = path->slots[0];
263031840ae1SZheng Yan 	if (slot > 0) {
263131840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
26327c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
2633eee3b811SQu Wenruo 			btrfs_print_leaf(eb);
26347c15d410SQu Wenruo 			btrfs_crit(fs_info,
26357c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
26367c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
26377c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
26387c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
26397c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
26407c15d410SQu Wenruo 				   new_key->offset);
26417c15d410SQu Wenruo 			BUG();
26427c15d410SQu Wenruo 		}
264331840ae1SZheng Yan 	}
264431840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
264531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
26467c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
2647eee3b811SQu Wenruo 			btrfs_print_leaf(eb);
26487c15d410SQu Wenruo 			btrfs_crit(fs_info,
26497c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
26507c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
26517c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
26527c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
26537c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
26547c15d410SQu Wenruo 				   new_key->offset);
26557c15d410SQu Wenruo 			BUG();
26567c15d410SQu Wenruo 		}
265731840ae1SZheng Yan 	}
265831840ae1SZheng Yan 
265931840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
266031840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
266131840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
266231840ae1SZheng Yan 	if (slot == 0)
2663b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
266431840ae1SZheng Yan }
266531840ae1SZheng Yan 
266631840ae1SZheng Yan /*
2667d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2668d16c702fSQu Wenruo  *
2669d16c702fSQu Wenruo  * Return true if something is wrong.
2670d16c702fSQu Wenruo  * Return false if everything is fine.
2671d16c702fSQu Wenruo  *
2672d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2673d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2674d16c702fSQu Wenruo  *
2675d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2676d16c702fSQu Wenruo  * --------------------------------------------------------------
2677d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2678d16c702fSQu Wenruo  *
2679d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2680d16c702fSQu Wenruo  * key in leaf @right is 7.
2681d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2682d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2683d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2684d16c702fSQu Wenruo  * key of @right.
2685d16c702fSQu Wenruo  */
2686d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2687d16c702fSQu Wenruo 			       struct extent_buffer *right)
2688d16c702fSQu Wenruo {
2689d16c702fSQu Wenruo 	struct btrfs_key left_last;
2690d16c702fSQu Wenruo 	struct btrfs_key right_first;
2691d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2692d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2693d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2694d16c702fSQu Wenruo 
2695d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2696d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2697d16c702fSQu Wenruo 		return false;
2698d16c702fSQu Wenruo 
2699d16c702fSQu Wenruo 	if (level) {
2700d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2701d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2702d16c702fSQu Wenruo 	} else {
2703d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2704d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2705d16c702fSQu Wenruo 	}
2706d16c702fSQu Wenruo 
270788ad95b0SFilipe Manana 	if (unlikely(btrfs_comp_cpu_keys(&left_last, &right_first) >= 0)) {
2708a2cea677SFilipe Manana 		btrfs_crit(left->fs_info, "left extent buffer:");
2709a2cea677SFilipe Manana 		btrfs_print_tree(left, false);
2710a2cea677SFilipe Manana 		btrfs_crit(left->fs_info, "right extent buffer:");
2711a2cea677SFilipe Manana 		btrfs_print_tree(right, false);
2712d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2713d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2714d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2715d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2716d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2717d16c702fSQu Wenruo 		return true;
2718d16c702fSQu Wenruo 	}
2719d16c702fSQu Wenruo 	return false;
2720d16c702fSQu Wenruo }
2721d16c702fSQu Wenruo 
2722d16c702fSQu Wenruo /*
272374123bd7SChris Mason  * try to push data from one node into the next node left in the
272479f95c82SChris Mason  * tree.
2725aa5d6bedSChris Mason  *
2726aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2727aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
272874123bd7SChris Mason  */
272998ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
27302ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2731971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2732be0e5c09SChris Mason {
2733d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2734be0e5c09SChris Mason 	int push_items = 0;
2735bb803951SChris Mason 	int src_nritems;
2736bb803951SChris Mason 	int dst_nritems;
2737aa5d6bedSChris Mason 	int ret = 0;
2738be0e5c09SChris Mason 
27395f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
27405f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
27410b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
27427bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
27437bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
274454aa1f4dSChris Mason 
2745bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2746971a1f66SChris Mason 		return 1;
2747971a1f66SChris Mason 
2748d397712bSChris Mason 	if (push_items <= 0)
2749be0e5c09SChris Mason 		return 1;
2750be0e5c09SChris Mason 
2751bce4eae9SChris Mason 	if (empty) {
2752971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2753bce4eae9SChris Mason 		if (push_items < src_nritems) {
2754bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2755bce4eae9SChris Mason 			 * we aren't going to empty it
2756bce4eae9SChris Mason 			 */
2757bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2758bce4eae9SChris Mason 				if (push_items <= 8)
2759bce4eae9SChris Mason 					return 1;
2760bce4eae9SChris Mason 				push_items -= 8;
2761bce4eae9SChris Mason 			}
2762bce4eae9SChris Mason 		}
2763bce4eae9SChris Mason 	} else
2764bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
276579f95c82SChris Mason 
2766d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2767d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2768d16c702fSQu Wenruo 		ret = -EUCLEAN;
2769d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2770d16c702fSQu Wenruo 		return ret;
2771d16c702fSQu Wenruo 	}
2772f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
27735de865eeSFilipe David Borba Manana 	if (ret) {
277466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
27755de865eeSFilipe David Borba Manana 		return ret;
27765de865eeSFilipe David Borba Manana 	}
27775f39d397SChris Mason 	copy_extent_buffer(dst, src,
2778e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, dst_nritems),
2779e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, 0),
2780123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
27815f39d397SChris Mason 
2782bb803951SChris Mason 	if (push_items < src_nritems) {
278357911b8bSJan Schmidt 		/*
2784f3a84ccdSFilipe Manana 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2785f3a84ccdSFilipe Manana 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
278657911b8bSJan Schmidt 		 */
2787e23efd8eSJosef Bacik 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(src, 0),
2788e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(src, push_items),
2789e2fa7227SChris Mason 				      (src_nritems - push_items) *
2790123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2791bb803951SChris Mason 	}
27925f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
27935f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
27945f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
27955f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
279631840ae1SZheng Yan 
2797bb803951SChris Mason 	return ret;
2798be0e5c09SChris Mason }
2799be0e5c09SChris Mason 
280097571fd0SChris Mason /*
280179f95c82SChris Mason  * try to push data from one node into the next node right in the
280279f95c82SChris Mason  * tree.
280379f95c82SChris Mason  *
280479f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
280579f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
280679f95c82SChris Mason  *
280779f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
280879f95c82SChris Mason  */
28095f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
28105f39d397SChris Mason 			      struct extent_buffer *dst,
28115f39d397SChris Mason 			      struct extent_buffer *src)
281279f95c82SChris Mason {
281355d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
281479f95c82SChris Mason 	int push_items = 0;
281579f95c82SChris Mason 	int max_push;
281679f95c82SChris Mason 	int src_nritems;
281779f95c82SChris Mason 	int dst_nritems;
281879f95c82SChris Mason 	int ret = 0;
281979f95c82SChris Mason 
28207bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28217bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
28227bb86316SChris Mason 
28235f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28245f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
28250b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2826d397712bSChris Mason 	if (push_items <= 0)
282779f95c82SChris Mason 		return 1;
2828bce4eae9SChris Mason 
2829d397712bSChris Mason 	if (src_nritems < 4)
2830bce4eae9SChris Mason 		return 1;
283179f95c82SChris Mason 
283279f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
283379f95c82SChris Mason 	/* don't try to empty the node */
2834d397712bSChris Mason 	if (max_push >= src_nritems)
283579f95c82SChris Mason 		return 1;
2836252c38f0SYan 
283779f95c82SChris Mason 	if (max_push < push_items)
283879f95c82SChris Mason 		push_items = max_push;
283979f95c82SChris Mason 
2840d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2841d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2842d16c702fSQu Wenruo 		ret = -EUCLEAN;
2843d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2844d16c702fSQu Wenruo 		return ret;
2845d16c702fSQu Wenruo 	}
2846f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2847bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
2848e23efd8eSJosef Bacik 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(dst, push_items),
2849e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(dst, 0),
28505f39d397SChris Mason 				      (dst_nritems) *
28515f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2852d6025579SChris Mason 
2853f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2854ed874f0dSDavid Sterba 					 push_items);
28555de865eeSFilipe David Borba Manana 	if (ret) {
285666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
28575de865eeSFilipe David Borba Manana 		return ret;
28585de865eeSFilipe David Borba Manana 	}
28595f39d397SChris Mason 	copy_extent_buffer(dst, src,
2860e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, 0),
2861e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, src_nritems - push_items),
2862123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
286379f95c82SChris Mason 
28645f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
28655f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
286679f95c82SChris Mason 
28675f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
28685f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
286931840ae1SZheng Yan 
287079f95c82SChris Mason 	return ret;
287179f95c82SChris Mason }
287279f95c82SChris Mason 
287379f95c82SChris Mason /*
287497571fd0SChris Mason  * helper function to insert a new root level in the tree.
287597571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
287697571fd0SChris Mason  * point to the existing root
2877aa5d6bedSChris Mason  *
2878aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
287997571fd0SChris Mason  */
2880d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
28815f39d397SChris Mason 			   struct btrfs_root *root,
2882fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
288374123bd7SChris Mason {
28840b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
28857bb86316SChris Mason 	u64 lower_gen;
28865f39d397SChris Mason 	struct extent_buffer *lower;
28875f39d397SChris Mason 	struct extent_buffer *c;
2888925baeddSChris Mason 	struct extent_buffer *old;
28895f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2890d9d19a01SDavid Sterba 	int ret;
28915c680ed6SChris Mason 
28925c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
28935c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
28945c680ed6SChris Mason 
28957bb86316SChris Mason 	lower = path->nodes[level-1];
28967bb86316SChris Mason 	if (level == 1)
28977bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
28987bb86316SChris Mason 	else
28997bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
29007bb86316SChris Mason 
290179bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
290279bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2903cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
29045f39d397SChris Mason 	if (IS_ERR(c))
29055f39d397SChris Mason 		return PTR_ERR(c);
2906925baeddSChris Mason 
29070b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2908f0486c68SYan, Zheng 
29095f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
29105f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2911db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
29127bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
291331840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
29147bb86316SChris Mason 
29157bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
29165f39d397SChris Mason 
29175f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2918d5719762SChris Mason 
2919925baeddSChris Mason 	old = root->node;
2920406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2921d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2922240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2923925baeddSChris Mason 
2924925baeddSChris Mason 	/* the super has an extra ref to root->node */
2925925baeddSChris Mason 	free_extent_buffer(old);
2926925baeddSChris Mason 
29270b86a832SChris Mason 	add_root_to_dirty_list(root);
292867439dadSDavid Sterba 	atomic_inc(&c->refs);
29295f39d397SChris Mason 	path->nodes[level] = c;
2930ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
293174123bd7SChris Mason 	path->slots[level] = 0;
293274123bd7SChris Mason 	return 0;
293374123bd7SChris Mason }
29345c680ed6SChris Mason 
29355c680ed6SChris Mason /*
29365c680ed6SChris Mason  * worker function to insert a single pointer in a node.
29375c680ed6SChris Mason  * the node should have enough room for the pointer already
293897571fd0SChris Mason  *
29395c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
29405c680ed6SChris Mason  * blocknr is the block the key points to.
29415c680ed6SChris Mason  */
2942143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
29436ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2944143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2945c3e06965SJan Schmidt 		       int slot, int level)
29465c680ed6SChris Mason {
29475f39d397SChris Mason 	struct extent_buffer *lower;
29485c680ed6SChris Mason 	int nritems;
2949f3ea38daSJan Schmidt 	int ret;
29505c680ed6SChris Mason 
29515c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
295249d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
29535f39d397SChris Mason 	lower = path->nodes[level];
29545f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2955c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
29566ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
295774123bd7SChris Mason 	if (slot != nritems) {
2958bf1d3425SDavid Sterba 		if (level) {
2959f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2960f3a84ccdSFilipe Manana 					slot, nritems - slot);
2961bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2962bf1d3425SDavid Sterba 		}
29635f39d397SChris Mason 		memmove_extent_buffer(lower,
2964e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot + 1),
2965e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot),
2966123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
296774123bd7SChris Mason 	}
2968c3e06965SJan Schmidt 	if (level) {
2969f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
297033cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_ADD);
2971f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2972f3ea38daSJan Schmidt 	}
29735f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2974db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
297574493f7aSChris Mason 	WARN_ON(trans->transid == 0);
297674493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
29775f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
29785f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
297974123bd7SChris Mason }
298074123bd7SChris Mason 
298197571fd0SChris Mason /*
298297571fd0SChris Mason  * split the node at the specified level in path in two.
298397571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
298497571fd0SChris Mason  *
298597571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
298697571fd0SChris Mason  * left and right, if either one works, it returns right away.
2987aa5d6bedSChris Mason  *
2988aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
298997571fd0SChris Mason  */
2990e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
2991e02119d5SChris Mason 			       struct btrfs_root *root,
2992e02119d5SChris Mason 			       struct btrfs_path *path, int level)
2993be0e5c09SChris Mason {
29940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29955f39d397SChris Mason 	struct extent_buffer *c;
29965f39d397SChris Mason 	struct extent_buffer *split;
29975f39d397SChris Mason 	struct btrfs_disk_key disk_key;
2998be0e5c09SChris Mason 	int mid;
29995c680ed6SChris Mason 	int ret;
30007518a238SChris Mason 	u32 c_nritems;
3001be0e5c09SChris Mason 
30025f39d397SChris Mason 	c = path->nodes[level];
30037bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
30045f39d397SChris Mason 	if (c == root->node) {
3005d9abbf1cSJan Schmidt 		/*
300690f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
300790f8d62eSJan Schmidt 		 *
3008fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
300990f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
301090f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
3011f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
3012f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
3013f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
3014d9abbf1cSJan Schmidt 		 */
3015fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
30165c680ed6SChris Mason 		if (ret)
30175c680ed6SChris Mason 			return ret;
3018b3612421SChris Mason 	} else {
3019e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
30205f39d397SChris Mason 		c = path->nodes[level];
30215f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
30220b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3023e66f709bSChris Mason 			return 0;
302454aa1f4dSChris Mason 		if (ret < 0)
302554aa1f4dSChris Mason 			return ret;
30265c680ed6SChris Mason 	}
3027e66f709bSChris Mason 
30285f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
30295d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
30305d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
30317bb86316SChris Mason 
303279bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
303379bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
303479bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
30355f39d397SChris Mason 	if (IS_ERR(split))
30365f39d397SChris Mason 		return PTR_ERR(split);
303754aa1f4dSChris Mason 
30380b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3039bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
30405f39d397SChris Mason 
3041f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
30425de865eeSFilipe David Borba Manana 	if (ret) {
304366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
30445de865eeSFilipe David Borba Manana 		return ret;
30455de865eeSFilipe David Borba Manana 	}
30465f39d397SChris Mason 	copy_extent_buffer(split, c,
3047e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(split, 0),
3048e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(c, mid),
3049123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
30505f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
30515f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3052aa5d6bedSChris Mason 
30535f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
30545f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
30555f39d397SChris Mason 
30566ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
3057c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3058aa5d6bedSChris Mason 
30595de08d7dSChris Mason 	if (path->slots[level] >= mid) {
30605c680ed6SChris Mason 		path->slots[level] -= mid;
3061925baeddSChris Mason 		btrfs_tree_unlock(c);
30625f39d397SChris Mason 		free_extent_buffer(c);
30635f39d397SChris Mason 		path->nodes[level] = split;
30645c680ed6SChris Mason 		path->slots[level + 1] += 1;
3065eb60ceacSChris Mason 	} else {
3066925baeddSChris Mason 		btrfs_tree_unlock(split);
30675f39d397SChris Mason 		free_extent_buffer(split);
3068be0e5c09SChris Mason 	}
3069d5286a92SNikolay Borisov 	return 0;
3070be0e5c09SChris Mason }
3071be0e5c09SChris Mason 
307274123bd7SChris Mason /*
307374123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
307474123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
307574123bd7SChris Mason  * space used both by the item structs and the item data
307674123bd7SChris Mason  */
30776c75a589SQu Wenruo static int leaf_space_used(const struct extent_buffer *l, int start, int nr)
3078be0e5c09SChris Mason {
3079be0e5c09SChris Mason 	int data_len;
30805f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3081d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3082be0e5c09SChris Mason 
3083be0e5c09SChris Mason 	if (!nr)
3084be0e5c09SChris Mason 		return 0;
30853212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
30863212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
30870783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3088d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3089be0e5c09SChris Mason 	return data_len;
3090be0e5c09SChris Mason }
3091be0e5c09SChris Mason 
309274123bd7SChris Mason /*
3093d4dbff95SChris Mason  * The space between the end of the leaf items and
3094d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3095d4dbff95SChris Mason  * the leaf has left for both items and data
3096d4dbff95SChris Mason  */
30976c75a589SQu Wenruo int btrfs_leaf_free_space(const struct extent_buffer *leaf)
3098d4dbff95SChris Mason {
3099e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
31005f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
31015f39d397SChris Mason 	int ret;
31020b246afaSJeff Mahoney 
31030b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
31045f39d397SChris Mason 	if (ret < 0) {
31050b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3106efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3107da17066cSJeff Mahoney 			   ret,
31080b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
31095f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
31105f39d397SChris Mason 	}
31115f39d397SChris Mason 	return ret;
3112d4dbff95SChris Mason }
3113d4dbff95SChris Mason 
311499d8f83cSChris Mason /*
311599d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
311699d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
311799d8f83cSChris Mason  */
3118ed25dab3SJosef Bacik static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
3119ed25dab3SJosef Bacik 				      struct btrfs_path *path,
312044871b1bSChris Mason 				      int data_size, int empty,
312144871b1bSChris Mason 				      struct extent_buffer *right,
312299d8f83cSChris Mason 				      int free_space, u32 left_nritems,
312399d8f83cSChris Mason 				      u32 min_slot)
312400ec4c51SChris Mason {
3125f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
31265f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
312744871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3128cfed81a0SChris Mason 	struct btrfs_map_token token;
31295f39d397SChris Mason 	struct btrfs_disk_key disk_key;
313000ec4c51SChris Mason 	int slot;
313134a38218SChris Mason 	u32 i;
313200ec4c51SChris Mason 	int push_space = 0;
313300ec4c51SChris Mason 	int push_items = 0;
313434a38218SChris Mason 	u32 nr;
31357518a238SChris Mason 	u32 right_nritems;
31365f39d397SChris Mason 	u32 data_end;
3137db94535dSChris Mason 	u32 this_item_size;
313800ec4c51SChris Mason 
313934a38218SChris Mason 	if (empty)
314034a38218SChris Mason 		nr = 0;
314134a38218SChris Mason 	else
314299d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
314334a38218SChris Mason 
314431840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
314587b29b20SYan Zheng 		push_space += data_size;
314631840ae1SZheng Yan 
314744871b1bSChris Mason 	slot = path->slots[1];
314834a38218SChris Mason 	i = left_nritems - 1;
314934a38218SChris Mason 	while (i >= nr) {
315031840ae1SZheng Yan 		if (!empty && push_items > 0) {
315131840ae1SZheng Yan 			if (path->slots[0] > i)
315231840ae1SZheng Yan 				break;
315331840ae1SZheng Yan 			if (path->slots[0] == i) {
3154e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3155e902baacSDavid Sterba 
315631840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
315731840ae1SZheng Yan 					break;
315831840ae1SZheng Yan 			}
315931840ae1SZheng Yan 		}
316031840ae1SZheng Yan 
316100ec4c51SChris Mason 		if (path->slots[0] == i)
316287b29b20SYan Zheng 			push_space += data_size;
3163db94535dSChris Mason 
31643212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
316574794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
316674794207SJosef Bacik 		    push_space > free_space)
316700ec4c51SChris Mason 			break;
316831840ae1SZheng Yan 
316900ec4c51SChris Mason 		push_items++;
317074794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
317134a38218SChris Mason 		if (i == 0)
317234a38218SChris Mason 			break;
317334a38218SChris Mason 		i--;
3174db94535dSChris Mason 	}
31755f39d397SChris Mason 
3176925baeddSChris Mason 	if (push_items == 0)
3177925baeddSChris Mason 		goto out_unlock;
31785f39d397SChris Mason 
31796c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
31805f39d397SChris Mason 
318100ec4c51SChris Mason 	/* push left to right */
31825f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
318334a38218SChris Mason 
3184dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
31858f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
31865f39d397SChris Mason 
318700ec4c51SChris Mason 	/* make room in the right data area */
31888f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
3189637e3b48SJosef Bacik 	memmove_leaf_data(right, data_end - push_space, data_end,
31900b246afaSJeff Mahoney 			  BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
31915f39d397SChris Mason 
319200ec4c51SChris Mason 	/* copy from the left data area */
3193637e3b48SJosef Bacik 	copy_leaf_data(right, left, BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3194637e3b48SJosef Bacik 		       leaf_data_end(left), push_space);
31955f39d397SChris Mason 
3196637e3b48SJosef Bacik 	memmove_leaf_items(right, push_items, 0, right_nritems);
31975f39d397SChris Mason 
319800ec4c51SChris Mason 	/* copy the items from left to right */
3199637e3b48SJosef Bacik 	copy_leaf_items(right, left, 0, left_nritems - push_items, push_items);
320000ec4c51SChris Mason 
320100ec4c51SChris Mason 	/* update the item pointers */
3202c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
32037518a238SChris Mason 	right_nritems += push_items;
32045f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
32050b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
32067518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
32073212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
32083212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3209db94535dSChris Mason 	}
3210db94535dSChris Mason 
32117518a238SChris Mason 	left_nritems -= push_items;
32125f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
321300ec4c51SChris Mason 
321434a38218SChris Mason 	if (left_nritems)
32155f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3216f0486c68SYan, Zheng 	else
3217190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, left);
3218f0486c68SYan, Zheng 
32195f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3220a429e513SChris Mason 
32215f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
32225f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3223d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
322402217ed2SChris Mason 
322500ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
32267518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
32277518a238SChris Mason 		path->slots[0] -= left_nritems;
3228925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3229190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, path->nodes[0]);
3230925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32315f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32325f39d397SChris Mason 		path->nodes[0] = right;
323300ec4c51SChris Mason 		path->slots[1] += 1;
323400ec4c51SChris Mason 	} else {
3235925baeddSChris Mason 		btrfs_tree_unlock(right);
32365f39d397SChris Mason 		free_extent_buffer(right);
323700ec4c51SChris Mason 	}
323800ec4c51SChris Mason 	return 0;
3239925baeddSChris Mason 
3240925baeddSChris Mason out_unlock:
3241925baeddSChris Mason 	btrfs_tree_unlock(right);
3242925baeddSChris Mason 	free_extent_buffer(right);
3243925baeddSChris Mason 	return 1;
324400ec4c51SChris Mason }
3245925baeddSChris Mason 
324600ec4c51SChris Mason /*
324744871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
324874123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
324944871b1bSChris Mason  *
325044871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
325144871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
325299d8f83cSChris Mason  *
325399d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
325499d8f83cSChris Mason  * push any slot lower than min_slot
325574123bd7SChris Mason  */
325644871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
325799d8f83cSChris Mason 			   *root, struct btrfs_path *path,
325899d8f83cSChris Mason 			   int min_data_size, int data_size,
325999d8f83cSChris Mason 			   int empty, u32 min_slot)
3260be0e5c09SChris Mason {
326144871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
326244871b1bSChris Mason 	struct extent_buffer *right;
326344871b1bSChris Mason 	struct extent_buffer *upper;
326444871b1bSChris Mason 	int slot;
326544871b1bSChris Mason 	int free_space;
326644871b1bSChris Mason 	u32 left_nritems;
326744871b1bSChris Mason 	int ret;
326844871b1bSChris Mason 
326944871b1bSChris Mason 	if (!path->nodes[1])
327044871b1bSChris Mason 		return 1;
327144871b1bSChris Mason 
327244871b1bSChris Mason 	slot = path->slots[1];
327344871b1bSChris Mason 	upper = path->nodes[1];
327444871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
327544871b1bSChris Mason 		return 1;
327644871b1bSChris Mason 
327749d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
327844871b1bSChris Mason 
32794b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3280fb770ae4SLiu Bo 	if (IS_ERR(right))
32819cf14029SJosef Bacik 		return PTR_ERR(right);
328291ca338dSTsutomu Itoh 
3283bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
328444871b1bSChris Mason 
3285e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
328644871b1bSChris Mason 	if (free_space < data_size)
328744871b1bSChris Mason 		goto out_unlock;
328844871b1bSChris Mason 
328944871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3290bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
329144871b1bSChris Mason 	if (ret)
329244871b1bSChris Mason 		goto out_unlock;
329344871b1bSChris Mason 
329444871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
329544871b1bSChris Mason 	if (left_nritems == 0)
329644871b1bSChris Mason 		goto out_unlock;
329744871b1bSChris Mason 
3298d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3299d16c702fSQu Wenruo 		ret = -EUCLEAN;
33009ae5afd0SFilipe Manana 		btrfs_abort_transaction(trans, ret);
3301d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3302d16c702fSQu Wenruo 		free_extent_buffer(right);
3303d16c702fSQu Wenruo 		return ret;
3304d16c702fSQu Wenruo 	}
33052ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
33062ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
33072ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
33082ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
330952042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
33102ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
33112ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
33122ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
33132ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
33142ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
33152ef1fed2SFilipe David Borba Manana 		return 0;
33162ef1fed2SFilipe David Borba Manana 	}
33172ef1fed2SFilipe David Borba Manana 
3318ed25dab3SJosef Bacik 	return __push_leaf_right(trans, path, min_data_size, empty, right,
3319ed25dab3SJosef Bacik 				 free_space, left_nritems, min_slot);
332044871b1bSChris Mason out_unlock:
332144871b1bSChris Mason 	btrfs_tree_unlock(right);
332244871b1bSChris Mason 	free_extent_buffer(right);
332344871b1bSChris Mason 	return 1;
332444871b1bSChris Mason }
332544871b1bSChris Mason 
332644871b1bSChris Mason /*
332744871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
332844871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
332999d8f83cSChris Mason  *
333099d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
333199d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
333299d8f83cSChris Mason  * items
333344871b1bSChris Mason  */
3334ed25dab3SJosef Bacik static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
3335ed25dab3SJosef Bacik 				     struct btrfs_path *path, int data_size,
333644871b1bSChris Mason 				     int empty, struct extent_buffer *left,
333799d8f83cSChris Mason 				     int free_space, u32 right_nritems,
333899d8f83cSChris Mason 				     u32 max_slot)
333944871b1bSChris Mason {
33408087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
33415f39d397SChris Mason 	struct btrfs_disk_key disk_key;
33425f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3343be0e5c09SChris Mason 	int i;
3344be0e5c09SChris Mason 	int push_space = 0;
3345be0e5c09SChris Mason 	int push_items = 0;
33467518a238SChris Mason 	u32 old_left_nritems;
334734a38218SChris Mason 	u32 nr;
3348aa5d6bedSChris Mason 	int ret = 0;
3349db94535dSChris Mason 	u32 this_item_size;
3350db94535dSChris Mason 	u32 old_left_item_size;
3351cfed81a0SChris Mason 	struct btrfs_map_token token;
3352cfed81a0SChris Mason 
335334a38218SChris Mason 	if (empty)
335499d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
335534a38218SChris Mason 	else
335699d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
335734a38218SChris Mason 
335834a38218SChris Mason 	for (i = 0; i < nr; i++) {
335931840ae1SZheng Yan 		if (!empty && push_items > 0) {
336031840ae1SZheng Yan 			if (path->slots[0] < i)
336131840ae1SZheng Yan 				break;
336231840ae1SZheng Yan 			if (path->slots[0] == i) {
3363e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3364e902baacSDavid Sterba 
336531840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
336631840ae1SZheng Yan 					break;
336731840ae1SZheng Yan 			}
336831840ae1SZheng Yan 		}
336931840ae1SZheng Yan 
3370be0e5c09SChris Mason 		if (path->slots[0] == i)
337187b29b20SYan Zheng 			push_space += data_size;
3372db94535dSChris Mason 
33733212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
337474794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
337574794207SJosef Bacik 		    free_space)
3376be0e5c09SChris Mason 			break;
3377db94535dSChris Mason 
3378be0e5c09SChris Mason 		push_items++;
337974794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3380be0e5c09SChris Mason 	}
3381db94535dSChris Mason 
3382be0e5c09SChris Mason 	if (push_items == 0) {
3383925baeddSChris Mason 		ret = 1;
3384925baeddSChris Mason 		goto out;
3385be0e5c09SChris Mason 	}
3386fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
33875f39d397SChris Mason 
3388be0e5c09SChris Mason 	/* push data from right to left */
3389637e3b48SJosef Bacik 	copy_leaf_items(left, right, btrfs_header_nritems(left), 0, push_items);
33905f39d397SChris Mason 
33910b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
33923212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
33935f39d397SChris Mason 
3394637e3b48SJosef Bacik 	copy_leaf_data(left, right, leaf_data_end(left) - push_space,
3395637e3b48SJosef Bacik 		       btrfs_item_offset(right, push_items - 1), push_space);
33965f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
339787b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3398eb60ceacSChris Mason 
3399c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
34003212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3401be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
34025f39d397SChris Mason 		u32 ioff;
3403db94535dSChris Mason 
34043212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
34053212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3406cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3407be0e5c09SChris Mason 	}
34085f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3409be0e5c09SChris Mason 
3410be0e5c09SChris Mason 	/* fixup right node */
341131b1a2bdSJulia Lawall 	if (push_items > right_nritems)
341231b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3413d397712bSChris Mason 		       right_nritems);
341434a38218SChris Mason 
341534a38218SChris Mason 	if (push_items < right_nritems) {
34163212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
34178f881e8cSDavid Sterba 						  leaf_data_end(right);
3418637e3b48SJosef Bacik 		memmove_leaf_data(right,
34190b246afaSJeff Mahoney 				  BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
34208f881e8cSDavid Sterba 				  leaf_data_end(right), push_space);
34215f39d397SChris Mason 
3422637e3b48SJosef Bacik 		memmove_leaf_items(right, 0, push_items,
3423637e3b48SJosef Bacik 				   btrfs_header_nritems(right) - push_items);
342434a38218SChris Mason 	}
3425c82f823cSDavid Sterba 
3426c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3427eef1c494SYan 	right_nritems -= push_items;
3428eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
34290b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
34305f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
34313212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
34323212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3433db94535dSChris Mason 	}
3434eb60ceacSChris Mason 
34355f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
343634a38218SChris Mason 	if (right_nritems)
34375f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3438f0486c68SYan, Zheng 	else
3439190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, right);
3440098f59c2SChris Mason 
34415f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3442b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3443be0e5c09SChris Mason 
3444be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3445be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3446be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3447925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
34485f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
34495f39d397SChris Mason 		path->nodes[0] = left;
3450be0e5c09SChris Mason 		path->slots[1] -= 1;
3451be0e5c09SChris Mason 	} else {
3452925baeddSChris Mason 		btrfs_tree_unlock(left);
34535f39d397SChris Mason 		free_extent_buffer(left);
3454be0e5c09SChris Mason 		path->slots[0] -= push_items;
3455be0e5c09SChris Mason 	}
3456eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3457aa5d6bedSChris Mason 	return ret;
3458925baeddSChris Mason out:
3459925baeddSChris Mason 	btrfs_tree_unlock(left);
3460925baeddSChris Mason 	free_extent_buffer(left);
3461925baeddSChris Mason 	return ret;
3462be0e5c09SChris Mason }
3463be0e5c09SChris Mason 
346474123bd7SChris Mason /*
346544871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
346644871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
346799d8f83cSChris Mason  *
346899d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
346999d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
347099d8f83cSChris Mason  * items
347144871b1bSChris Mason  */
347244871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
347399d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
347499d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
347544871b1bSChris Mason {
347644871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
347744871b1bSChris Mason 	struct extent_buffer *left;
347844871b1bSChris Mason 	int slot;
347944871b1bSChris Mason 	int free_space;
348044871b1bSChris Mason 	u32 right_nritems;
348144871b1bSChris Mason 	int ret = 0;
348244871b1bSChris Mason 
348344871b1bSChris Mason 	slot = path->slots[1];
348444871b1bSChris Mason 	if (slot == 0)
348544871b1bSChris Mason 		return 1;
348644871b1bSChris Mason 	if (!path->nodes[1])
348744871b1bSChris Mason 		return 1;
348844871b1bSChris Mason 
348944871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
349044871b1bSChris Mason 	if (right_nritems == 0)
349144871b1bSChris Mason 		return 1;
349244871b1bSChris Mason 
349349d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
349444871b1bSChris Mason 
34954b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3496fb770ae4SLiu Bo 	if (IS_ERR(left))
34979cf14029SJosef Bacik 		return PTR_ERR(left);
349891ca338dSTsutomu Itoh 
3499bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
350044871b1bSChris Mason 
3501e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
350244871b1bSChris Mason 	if (free_space < data_size) {
350344871b1bSChris Mason 		ret = 1;
350444871b1bSChris Mason 		goto out;
350544871b1bSChris Mason 	}
350644871b1bSChris Mason 
350744871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
35089631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3509bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
351044871b1bSChris Mason 	if (ret) {
351144871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
351279787eaaSJeff Mahoney 		if (ret == -ENOSPC)
351344871b1bSChris Mason 			ret = 1;
351444871b1bSChris Mason 		goto out;
351544871b1bSChris Mason 	}
351644871b1bSChris Mason 
3517d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3518d16c702fSQu Wenruo 		ret = -EUCLEAN;
35199ae5afd0SFilipe Manana 		btrfs_abort_transaction(trans, ret);
3520d16c702fSQu Wenruo 		goto out;
3521d16c702fSQu Wenruo 	}
3522ed25dab3SJosef Bacik 	return __push_leaf_left(trans, path, min_data_size, empty, left,
3523ed25dab3SJosef Bacik 				free_space, right_nritems, max_slot);
352444871b1bSChris Mason out:
352544871b1bSChris Mason 	btrfs_tree_unlock(left);
352644871b1bSChris Mason 	free_extent_buffer(left);
352744871b1bSChris Mason 	return ret;
352844871b1bSChris Mason }
352944871b1bSChris Mason 
353044871b1bSChris Mason /*
353174123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
353274123bd7SChris Mason  * available for the resulting leaf level of the path.
353374123bd7SChris Mason  */
3534143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
353544871b1bSChris Mason 				    struct btrfs_path *path,
353644871b1bSChris Mason 				    struct extent_buffer *l,
353744871b1bSChris Mason 				    struct extent_buffer *right,
353844871b1bSChris Mason 				    int slot, int mid, int nritems)
3539be0e5c09SChris Mason {
354094f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3541be0e5c09SChris Mason 	int data_copy_size;
3542be0e5c09SChris Mason 	int rt_data_off;
3543be0e5c09SChris Mason 	int i;
3544d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3545cfed81a0SChris Mason 	struct btrfs_map_token token;
3546cfed81a0SChris Mason 
35475f39d397SChris Mason 	nritems = nritems - mid;
35485f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3549dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
35505f39d397SChris Mason 
3551637e3b48SJosef Bacik 	copy_leaf_items(right, l, 0, mid, nritems);
35525f39d397SChris Mason 
3553637e3b48SJosef Bacik 	copy_leaf_data(right, l, BTRFS_LEAF_DATA_SIZE(fs_info) - data_copy_size,
35548f881e8cSDavid Sterba 		       leaf_data_end(l), data_copy_size);
355574123bd7SChris Mason 
3556dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
35575f39d397SChris Mason 
3558c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
35595f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3560db94535dSChris Mason 		u32 ioff;
3561db94535dSChris Mason 
35623212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
35633212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
35640783fcfcSChris Mason 	}
356574123bd7SChris Mason 
35665f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
35675f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
35686ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
35695f39d397SChris Mason 
35705f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
35715f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3572eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
35735f39d397SChris Mason 
3574be0e5c09SChris Mason 	if (mid <= slot) {
3575925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
35765f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
35775f39d397SChris Mason 		path->nodes[0] = right;
3578be0e5c09SChris Mason 		path->slots[0] -= mid;
3579be0e5c09SChris Mason 		path->slots[1] += 1;
3580925baeddSChris Mason 	} else {
3581925baeddSChris Mason 		btrfs_tree_unlock(right);
35825f39d397SChris Mason 		free_extent_buffer(right);
3583925baeddSChris Mason 	}
35845f39d397SChris Mason 
3585eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
358644871b1bSChris Mason }
358744871b1bSChris Mason 
358844871b1bSChris Mason /*
358999d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
359099d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
359199d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
359299d8f83cSChris Mason  *          A                 B                 C
359399d8f83cSChris Mason  *
359499d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
359599d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
359699d8f83cSChris Mason  * completely.
359799d8f83cSChris Mason  */
359899d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
359999d8f83cSChris Mason 					  struct btrfs_root *root,
360099d8f83cSChris Mason 					  struct btrfs_path *path,
360199d8f83cSChris Mason 					  int data_size)
360299d8f83cSChris Mason {
360399d8f83cSChris Mason 	int ret;
360499d8f83cSChris Mason 	int progress = 0;
360599d8f83cSChris Mason 	int slot;
360699d8f83cSChris Mason 	u32 nritems;
36075a4267caSFilipe David Borba Manana 	int space_needed = data_size;
360899d8f83cSChris Mason 
360999d8f83cSChris Mason 	slot = path->slots[0];
36105a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3611e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
361299d8f83cSChris Mason 
361399d8f83cSChris Mason 	/*
361499d8f83cSChris Mason 	 * try to push all the items after our slot into the
361599d8f83cSChris Mason 	 * right leaf
361699d8f83cSChris Mason 	 */
36175a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
361899d8f83cSChris Mason 	if (ret < 0)
361999d8f83cSChris Mason 		return ret;
362099d8f83cSChris Mason 
362199d8f83cSChris Mason 	if (ret == 0)
362299d8f83cSChris Mason 		progress++;
362399d8f83cSChris Mason 
362499d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
362599d8f83cSChris Mason 	/*
362699d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
362799d8f83cSChris Mason 	 * we've done so we're done
362899d8f83cSChris Mason 	 */
362999d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
363099d8f83cSChris Mason 		return 0;
363199d8f83cSChris Mason 
3632e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
363399d8f83cSChris Mason 		return 0;
363499d8f83cSChris Mason 
363599d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
363699d8f83cSChris Mason 	slot = path->slots[0];
3637263d3995SFilipe Manana 	space_needed = data_size;
3638263d3995SFilipe Manana 	if (slot > 0)
3639e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
36405a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
364199d8f83cSChris Mason 	if (ret < 0)
364299d8f83cSChris Mason 		return ret;
364399d8f83cSChris Mason 
364499d8f83cSChris Mason 	if (ret == 0)
364599d8f83cSChris Mason 		progress++;
364699d8f83cSChris Mason 
364799d8f83cSChris Mason 	if (progress)
364899d8f83cSChris Mason 		return 0;
364999d8f83cSChris Mason 	return 1;
365099d8f83cSChris Mason }
365199d8f83cSChris Mason 
365299d8f83cSChris Mason /*
365344871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
365444871b1bSChris Mason  * available for the resulting leaf level of the path.
365544871b1bSChris Mason  *
365644871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
365744871b1bSChris Mason  */
365844871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
365944871b1bSChris Mason 			       struct btrfs_root *root,
3660310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
366144871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
366244871b1bSChris Mason 			       int extend)
366344871b1bSChris Mason {
36645d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
366544871b1bSChris Mason 	struct extent_buffer *l;
366644871b1bSChris Mason 	u32 nritems;
366744871b1bSChris Mason 	int mid;
366844871b1bSChris Mason 	int slot;
366944871b1bSChris Mason 	struct extent_buffer *right;
3670b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
367144871b1bSChris Mason 	int ret = 0;
367244871b1bSChris Mason 	int wret;
36735d4f98a2SYan Zheng 	int split;
367444871b1bSChris Mason 	int num_doubles = 0;
367599d8f83cSChris Mason 	int tried_avoid_double = 0;
367644871b1bSChris Mason 
3677a5719521SYan, Zheng 	l = path->nodes[0];
3678a5719521SYan, Zheng 	slot = path->slots[0];
36793212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
36800b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3681a5719521SYan, Zheng 		return -EOVERFLOW;
3682a5719521SYan, Zheng 
368344871b1bSChris Mason 	/* first try to make some room by pushing left and right */
368433157e05SLiu Bo 	if (data_size && path->nodes[1]) {
36855a4267caSFilipe David Borba Manana 		int space_needed = data_size;
36865a4267caSFilipe David Borba Manana 
36875a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3688e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
36895a4267caSFilipe David Borba Manana 
36905a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
36915a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
369244871b1bSChris Mason 		if (wret < 0)
369344871b1bSChris Mason 			return wret;
369444871b1bSChris Mason 		if (wret) {
3695263d3995SFilipe Manana 			space_needed = data_size;
3696263d3995SFilipe Manana 			if (slot > 0)
3697e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
36985a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
36995a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
370044871b1bSChris Mason 			if (wret < 0)
370144871b1bSChris Mason 				return wret;
370244871b1bSChris Mason 		}
370344871b1bSChris Mason 		l = path->nodes[0];
370444871b1bSChris Mason 
370544871b1bSChris Mason 		/* did the pushes work? */
3706e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
370744871b1bSChris Mason 			return 0;
370844871b1bSChris Mason 	}
370944871b1bSChris Mason 
371044871b1bSChris Mason 	if (!path->nodes[1]) {
3711fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
371244871b1bSChris Mason 		if (ret)
371344871b1bSChris Mason 			return ret;
371444871b1bSChris Mason 	}
371544871b1bSChris Mason again:
37165d4f98a2SYan Zheng 	split = 1;
371744871b1bSChris Mason 	l = path->nodes[0];
371844871b1bSChris Mason 	slot = path->slots[0];
371944871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
372044871b1bSChris Mason 	mid = (nritems + 1) / 2;
372144871b1bSChris Mason 
37225d4f98a2SYan Zheng 	if (mid <= slot) {
37235d4f98a2SYan Zheng 		if (nritems == 1 ||
37245d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
37250b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
37265d4f98a2SYan Zheng 			if (slot >= nritems) {
37275d4f98a2SYan Zheng 				split = 0;
37285d4f98a2SYan Zheng 			} else {
37295d4f98a2SYan Zheng 				mid = slot;
37305d4f98a2SYan Zheng 				if (mid != nritems &&
37315d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
37320b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
373399d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
373499d8f83cSChris Mason 						goto push_for_double;
37355d4f98a2SYan Zheng 					split = 2;
37365d4f98a2SYan Zheng 				}
37375d4f98a2SYan Zheng 			}
37385d4f98a2SYan Zheng 		}
37395d4f98a2SYan Zheng 	} else {
37405d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
37410b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
37425d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
37435d4f98a2SYan Zheng 				split = 0;
37445d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
37455d4f98a2SYan Zheng 				mid = 1;
37465d4f98a2SYan Zheng 			} else {
37475d4f98a2SYan Zheng 				mid = slot;
37485d4f98a2SYan Zheng 				if (mid != nritems &&
37495d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
37500b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
375199d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
375299d8f83cSChris Mason 						goto push_for_double;
37535d4f98a2SYan Zheng 					split = 2;
37545d4f98a2SYan Zheng 				}
37555d4f98a2SYan Zheng 			}
37565d4f98a2SYan Zheng 		}
37575d4f98a2SYan Zheng 	}
37585d4f98a2SYan Zheng 
37595d4f98a2SYan Zheng 	if (split == 0)
37605d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
37615d4f98a2SYan Zheng 	else
37625d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
37635d4f98a2SYan Zheng 
3764ca9d473aSJosef Bacik 	/*
3765ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3766ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3767ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3768ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3769ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3770ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3771ca9d473aSJosef Bacik 	 */
377279bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
377379bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
377479bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3775ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3776f0486c68SYan, Zheng 	if (IS_ERR(right))
377744871b1bSChris Mason 		return PTR_ERR(right);
3778f0486c68SYan, Zheng 
37790b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
378044871b1bSChris Mason 
37815d4f98a2SYan Zheng 	if (split == 0) {
378244871b1bSChris Mason 		if (mid <= slot) {
378344871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
37846ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
37852ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
378644871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
378744871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
378844871b1bSChris Mason 			path->nodes[0] = right;
378944871b1bSChris Mason 			path->slots[0] = 0;
379044871b1bSChris Mason 			path->slots[1] += 1;
379144871b1bSChris Mason 		} else {
379244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
37936ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
37942ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
379544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
379644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
379744871b1bSChris Mason 			path->nodes[0] = right;
379844871b1bSChris Mason 			path->slots[0] = 0;
3799143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3800b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
38015d4f98a2SYan Zheng 		}
3802196e0249SLiu Bo 		/*
3803196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3804196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3805196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3806196e0249SLiu Bo 		 */
380744871b1bSChris Mason 		return ret;
380844871b1bSChris Mason 	}
380944871b1bSChris Mason 
381094f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
381144871b1bSChris Mason 
38125d4f98a2SYan Zheng 	if (split == 2) {
3813cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3814cc0c5538SChris Mason 		num_doubles++;
3815cc0c5538SChris Mason 		goto again;
38163326d1b0SChris Mason 	}
381744871b1bSChris Mason 
3818143bede5SJeff Mahoney 	return 0;
381999d8f83cSChris Mason 
382099d8f83cSChris Mason push_for_double:
382199d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
382299d8f83cSChris Mason 	tried_avoid_double = 1;
3823e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
382499d8f83cSChris Mason 		return 0;
382599d8f83cSChris Mason 	goto again;
3826be0e5c09SChris Mason }
3827be0e5c09SChris Mason 
3828ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3829ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3830ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3831ad48fd75SYan, Zheng {
3832ad48fd75SYan, Zheng 	struct btrfs_key key;
3833ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3834ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3835ad48fd75SYan, Zheng 	u64 extent_len = 0;
3836ad48fd75SYan, Zheng 	u32 item_size;
3837ad48fd75SYan, Zheng 	int ret;
3838ad48fd75SYan, Zheng 
3839ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3840ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3841ad48fd75SYan, Zheng 
3842ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3843ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3844ad48fd75SYan, Zheng 
3845e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3846ad48fd75SYan, Zheng 		return 0;
3847ad48fd75SYan, Zheng 
38483212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3849ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3850ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3851ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3852ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3853ad48fd75SYan, Zheng 	}
3854b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3855ad48fd75SYan, Zheng 
3856ad48fd75SYan, Zheng 	path->keep_locks = 1;
3857ad48fd75SYan, Zheng 	path->search_for_split = 1;
3858ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3859ad48fd75SYan, Zheng 	path->search_for_split = 0;
3860a8df6fe6SFilipe Manana 	if (ret > 0)
3861a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3862ad48fd75SYan, Zheng 	if (ret < 0)
3863ad48fd75SYan, Zheng 		goto err;
3864ad48fd75SYan, Zheng 
3865ad48fd75SYan, Zheng 	ret = -EAGAIN;
3866ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3867a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
38683212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3869ad48fd75SYan, Zheng 		goto err;
3870ad48fd75SYan, Zheng 
3871109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3872e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3873109f6aefSChris Mason 		goto err;
3874109f6aefSChris Mason 
3875ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3876ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3877ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3878ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3879ad48fd75SYan, Zheng 			goto err;
3880ad48fd75SYan, Zheng 	}
3881ad48fd75SYan, Zheng 
3882ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3883f0486c68SYan, Zheng 	if (ret)
3884f0486c68SYan, Zheng 		goto err;
3885ad48fd75SYan, Zheng 
3886ad48fd75SYan, Zheng 	path->keep_locks = 0;
3887ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3888ad48fd75SYan, Zheng 	return 0;
3889ad48fd75SYan, Zheng err:
3890ad48fd75SYan, Zheng 	path->keep_locks = 0;
3891ad48fd75SYan, Zheng 	return ret;
3892ad48fd75SYan, Zheng }
3893ad48fd75SYan, Zheng 
389425263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3895310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3896459931ecSChris Mason 			       unsigned long split_offset)
3897459931ecSChris Mason {
3898459931ecSChris Mason 	struct extent_buffer *leaf;
3899c91666b1SJosef Bacik 	int orig_slot, slot;
3900ad48fd75SYan, Zheng 	char *buf;
3901459931ecSChris Mason 	u32 nritems;
3902ad48fd75SYan, Zheng 	u32 item_size;
3903459931ecSChris Mason 	u32 orig_offset;
3904459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3905459931ecSChris Mason 
3906459931ecSChris Mason 	leaf = path->nodes[0];
3907e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3908b9473439SChris Mason 
3909c91666b1SJosef Bacik 	orig_slot = path->slots[0];
39103212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
39113212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3912459931ecSChris Mason 
3913459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3914ad48fd75SYan, Zheng 	if (!buf)
3915ad48fd75SYan, Zheng 		return -ENOMEM;
3916ad48fd75SYan, Zheng 
3917459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3918459931ecSChris Mason 			    path->slots[0]), item_size);
3919ad48fd75SYan, Zheng 
3920459931ecSChris Mason 	slot = path->slots[0] + 1;
3921459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3922459931ecSChris Mason 	if (slot != nritems) {
3923459931ecSChris Mason 		/* shift the items */
3924637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot + 1, slot, nritems - slot);
3925459931ecSChris Mason 	}
3926459931ecSChris Mason 
3927459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3928459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3929459931ecSChris Mason 
39303212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
39313212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3932459931ecSChris Mason 
39333212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
3934459931ecSChris Mason 				 orig_offset + item_size - split_offset);
39353212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3936459931ecSChris Mason 
3937459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3938459931ecSChris Mason 
3939459931ecSChris Mason 	/* write the data for the start of the original item */
3940459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3941459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3942459931ecSChris Mason 			    split_offset);
3943459931ecSChris Mason 
3944459931ecSChris Mason 	/* write the data for the new item */
3945459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3946459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3947459931ecSChris Mason 			    item_size - split_offset);
3948459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3949459931ecSChris Mason 
3950e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3951459931ecSChris Mason 	kfree(buf);
3952ad48fd75SYan, Zheng 	return 0;
3953ad48fd75SYan, Zheng }
3954ad48fd75SYan, Zheng 
3955ad48fd75SYan, Zheng /*
3956ad48fd75SYan, Zheng  * This function splits a single item into two items,
3957ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3958ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3959ad48fd75SYan, Zheng  *
3960ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3961ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3962ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3963ad48fd75SYan, Zheng  *
3964ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3965ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3966ad48fd75SYan, Zheng  *
3967ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3968ad48fd75SYan, Zheng  * leaf the entire time.
3969ad48fd75SYan, Zheng  */
3970ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3971ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3972ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3973310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3974ad48fd75SYan, Zheng 		     unsigned long split_offset)
3975ad48fd75SYan, Zheng {
3976ad48fd75SYan, Zheng 	int ret;
3977ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3978ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3979ad48fd75SYan, Zheng 	if (ret)
3980459931ecSChris Mason 		return ret;
3981ad48fd75SYan, Zheng 
398225263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3983ad48fd75SYan, Zheng 	return ret;
3984ad48fd75SYan, Zheng }
3985ad48fd75SYan, Zheng 
3986ad48fd75SYan, Zheng /*
3987d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
3988d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
3989d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
3990d352ac68SChris Mason  * the front.
3991d352ac68SChris Mason  */
399278ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3993b18c6685SChris Mason {
3994b18c6685SChris Mason 	int slot;
39955f39d397SChris Mason 	struct extent_buffer *leaf;
3996b18c6685SChris Mason 	u32 nritems;
3997b18c6685SChris Mason 	unsigned int data_end;
3998b18c6685SChris Mason 	unsigned int old_data_start;
3999b18c6685SChris Mason 	unsigned int old_size;
4000b18c6685SChris Mason 	unsigned int size_diff;
4001b18c6685SChris Mason 	int i;
4002cfed81a0SChris Mason 	struct btrfs_map_token token;
4003cfed81a0SChris Mason 
40045f39d397SChris Mason 	leaf = path->nodes[0];
4005179e29e4SChris Mason 	slot = path->slots[0];
4006179e29e4SChris Mason 
40073212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
4008179e29e4SChris Mason 	if (old_size == new_size)
4009143bede5SJeff Mahoney 		return;
4010b18c6685SChris Mason 
40115f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
40128f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4013b18c6685SChris Mason 
40143212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
4015179e29e4SChris Mason 
4016b18c6685SChris Mason 	size_diff = old_size - new_size;
4017b18c6685SChris Mason 
4018b18c6685SChris Mason 	BUG_ON(slot < 0);
4019b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4020b18c6685SChris Mason 
4021b18c6685SChris Mason 	/*
4022b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4023b18c6685SChris Mason 	 */
4024b18c6685SChris Mason 	/* first correct the data pointers */
4025c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4026b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
40275f39d397SChris Mason 		u32 ioff;
4028db94535dSChris Mason 
40293212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
40303212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
4031b18c6685SChris Mason 	}
4032db94535dSChris Mason 
4033b18c6685SChris Mason 	/* shift the data */
4034179e29e4SChris Mason 	if (from_end) {
4035637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
4036637e3b48SJosef Bacik 				  old_data_start + new_size - data_end);
4037179e29e4SChris Mason 	} else {
4038179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4039179e29e4SChris Mason 		u64 offset;
4040179e29e4SChris Mason 
4041179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4042179e29e4SChris Mason 
4043179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4044179e29e4SChris Mason 			unsigned long ptr;
4045179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4046179e29e4SChris Mason 
4047179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4048179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4049179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4050179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4051179e29e4SChris Mason 
4052179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4053179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4054179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4055179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4056179e29e4SChris Mason 				      (unsigned long)fi,
40577ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4058179e29e4SChris Mason 			}
4059179e29e4SChris Mason 		}
4060179e29e4SChris Mason 
4061637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
4062637e3b48SJosef Bacik 				  old_data_start - data_end);
4063179e29e4SChris Mason 
4064179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4065179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4066179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4067179e29e4SChris Mason 		if (slot == 0)
4068b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4069179e29e4SChris Mason 	}
40705f39d397SChris Mason 
40713212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
40725f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4073b18c6685SChris Mason 
4074e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4075a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4076b18c6685SChris Mason 		BUG();
40775f39d397SChris Mason 	}
4078b18c6685SChris Mason }
4079b18c6685SChris Mason 
4080d352ac68SChris Mason /*
40818f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4082d352ac68SChris Mason  */
4083c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
40846567e837SChris Mason {
40856567e837SChris Mason 	int slot;
40865f39d397SChris Mason 	struct extent_buffer *leaf;
40876567e837SChris Mason 	u32 nritems;
40886567e837SChris Mason 	unsigned int data_end;
40896567e837SChris Mason 	unsigned int old_data;
40906567e837SChris Mason 	unsigned int old_size;
40916567e837SChris Mason 	int i;
4092cfed81a0SChris Mason 	struct btrfs_map_token token;
4093cfed81a0SChris Mason 
40945f39d397SChris Mason 	leaf = path->nodes[0];
40956567e837SChris Mason 
40965f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
40978f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
40986567e837SChris Mason 
4099e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4100a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
41016567e837SChris Mason 		BUG();
41025f39d397SChris Mason 	}
41036567e837SChris Mason 	slot = path->slots[0];
4104dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
41056567e837SChris Mason 
41066567e837SChris Mason 	BUG_ON(slot < 0);
41073326d1b0SChris Mason 	if (slot >= nritems) {
4108a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4109c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4110d397712bSChris Mason 			   slot, nritems);
4111290342f6SArnd Bergmann 		BUG();
41123326d1b0SChris Mason 	}
41136567e837SChris Mason 
41146567e837SChris Mason 	/*
41156567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
41166567e837SChris Mason 	 */
41176567e837SChris Mason 	/* first correct the data pointers */
4118c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
41196567e837SChris Mason 	for (i = slot; i < nritems; i++) {
41205f39d397SChris Mason 		u32 ioff;
4121db94535dSChris Mason 
41223212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
41233212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
41246567e837SChris Mason 	}
41255f39d397SChris Mason 
41266567e837SChris Mason 	/* shift the data */
4127637e3b48SJosef Bacik 	memmove_leaf_data(leaf, data_end - data_size, data_end,
4128637e3b48SJosef Bacik 			  old_data - data_end);
41295f39d397SChris Mason 
41306567e837SChris Mason 	data_end = old_data;
41313212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
41323212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
41335f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
41346567e837SChris Mason 
4135e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4136a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
41376567e837SChris Mason 		BUG();
41385f39d397SChris Mason 	}
41396567e837SChris Mason }
41406567e837SChris Mason 
414143dd529aSDavid Sterba /*
414243dd529aSDavid Sterba  * Make space in the node before inserting one or more items.
4143da9ffb24SNikolay Borisov  *
4144da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
4145da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
4146b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
414743dd529aSDavid Sterba  *
414843dd529aSDavid Sterba  * Main purpose is to save stack depth by doing the bulk of the work in a
414943dd529aSDavid Sterba  * function that doesn't call btrfs_search_slot
415074123bd7SChris Mason  */
4151f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4152b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
4153be0e5c09SChris Mason {
41540b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
41559c58309dSChris Mason 	int i;
41567518a238SChris Mason 	u32 nritems;
4157be0e5c09SChris Mason 	unsigned int data_end;
4158e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
415944871b1bSChris Mason 	struct extent_buffer *leaf;
416044871b1bSChris Mason 	int slot;
4161cfed81a0SChris Mason 	struct btrfs_map_token token;
4162fc0d82e1SNikolay Borisov 	u32 total_size;
4163fc0d82e1SNikolay Borisov 
4164b7ef5f3aSFilipe Manana 	/*
4165b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
4166b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
4167b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
4168b7ef5f3aSFilipe Manana 	 */
416924cdc847SFilipe Manana 	if (path->slots[0] == 0) {
4170b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4171b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
417224cdc847SFilipe Manana 	}
417324cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
417424cdc847SFilipe Manana 
41755f39d397SChris Mason 	leaf = path->nodes[0];
417644871b1bSChris Mason 	slot = path->slots[0];
417774123bd7SChris Mason 
41785f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
41798f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4180b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4181eb60ceacSChris Mason 
4182e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4183a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
41840b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4185e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4186be0e5c09SChris Mason 		BUG();
4187d4dbff95SChris Mason 	}
41885f39d397SChris Mason 
4189c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4190be0e5c09SChris Mason 	if (slot != nritems) {
4191dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4192be0e5c09SChris Mason 
41935f39d397SChris Mason 		if (old_data < data_end) {
4194a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
41957269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
41967269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
41975f39d397SChris Mason 				   slot, old_data, data_end);
4198290342f6SArnd Bergmann 			BUG();
41995f39d397SChris Mason 		}
4200be0e5c09SChris Mason 		/*
4201be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4202be0e5c09SChris Mason 		 */
4203be0e5c09SChris Mason 		/* first correct the data pointers */
42040783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
42055f39d397SChris Mason 			u32 ioff;
4206db94535dSChris Mason 
42073212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
42083212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
4209b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
42100783fcfcSChris Mason 		}
4211be0e5c09SChris Mason 		/* shift the items */
4212637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot + batch->nr, slot, nritems - slot);
4213be0e5c09SChris Mason 
4214be0e5c09SChris Mason 		/* shift the data */
4215637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end - batch->total_data_size,
4216637e3b48SJosef Bacik 				  data_end, old_data - data_end);
4217be0e5c09SChris Mason 		data_end = old_data;
4218be0e5c09SChris Mason 	}
42195f39d397SChris Mason 
422062e2749eSChris Mason 	/* setup the item for the new data */
4221b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
4222b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
42239c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4224b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
42253212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
42263212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
42279c58309dSChris Mason 	}
422844871b1bSChris Mason 
4229b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4230b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4231aa5d6bedSChris Mason 
4232e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4233a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4234be0e5c09SChris Mason 		BUG();
42355f39d397SChris Mason 	}
423644871b1bSChris Mason }
423744871b1bSChris Mason 
423844871b1bSChris Mason /*
4239f0641656SFilipe Manana  * Insert a new item into a leaf.
4240f0641656SFilipe Manana  *
4241f0641656SFilipe Manana  * @root:      The root of the btree.
4242f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
4243f0641656SFilipe Manana  * @key:       The key of the new item.
4244f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
4245f0641656SFilipe Manana  */
4246f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
4247f0641656SFilipe Manana 				 struct btrfs_path *path,
4248f0641656SFilipe Manana 				 const struct btrfs_key *key,
4249f0641656SFilipe Manana 				 u32 data_size)
4250f0641656SFilipe Manana {
4251f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4252f0641656SFilipe Manana 
4253f0641656SFilipe Manana 	batch.keys = key;
4254f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4255f0641656SFilipe Manana 	batch.total_data_size = data_size;
4256f0641656SFilipe Manana 	batch.nr = 1;
4257f0641656SFilipe Manana 
4258f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
4259f0641656SFilipe Manana }
4260f0641656SFilipe Manana 
4261f0641656SFilipe Manana /*
426244871b1bSChris Mason  * Given a key and some data, insert items into the tree.
426344871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
426444871b1bSChris Mason  */
426544871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
426644871b1bSChris Mason 			    struct btrfs_root *root,
426744871b1bSChris Mason 			    struct btrfs_path *path,
4268b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
426944871b1bSChris Mason {
427044871b1bSChris Mason 	int ret = 0;
427144871b1bSChris Mason 	int slot;
4272b7ef5f3aSFilipe Manana 	u32 total_size;
427344871b1bSChris Mason 
4274b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4275b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
427644871b1bSChris Mason 	if (ret == 0)
427744871b1bSChris Mason 		return -EEXIST;
427844871b1bSChris Mason 	if (ret < 0)
4279143bede5SJeff Mahoney 		return ret;
428044871b1bSChris Mason 
428144871b1bSChris Mason 	slot = path->slots[0];
428244871b1bSChris Mason 	BUG_ON(slot < 0);
428344871b1bSChris Mason 
4284b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4285143bede5SJeff Mahoney 	return 0;
428662e2749eSChris Mason }
428762e2749eSChris Mason 
428862e2749eSChris Mason /*
428962e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
429062e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
429162e2749eSChris Mason  */
4292310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4293310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4294310712b2SOmar Sandoval 		      u32 data_size)
429562e2749eSChris Mason {
429662e2749eSChris Mason 	int ret = 0;
42972c90e5d6SChris Mason 	struct btrfs_path *path;
42985f39d397SChris Mason 	struct extent_buffer *leaf;
42995f39d397SChris Mason 	unsigned long ptr;
430062e2749eSChris Mason 
43012c90e5d6SChris Mason 	path = btrfs_alloc_path();
4302db5b493aSTsutomu Itoh 	if (!path)
4303db5b493aSTsutomu Itoh 		return -ENOMEM;
43042c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
430562e2749eSChris Mason 	if (!ret) {
43065f39d397SChris Mason 		leaf = path->nodes[0];
43075f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
43085f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
43095f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
431062e2749eSChris Mason 	}
43112c90e5d6SChris Mason 	btrfs_free_path(path);
4312aa5d6bedSChris Mason 	return ret;
4313be0e5c09SChris Mason }
4314be0e5c09SChris Mason 
431574123bd7SChris Mason /*
4316f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4317f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4318f0641656SFilipe Manana  * contiguous with the original item.
4319f0641656SFilipe Manana  *
4320f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4321f0641656SFilipe Manana  * the entire time.
4322f0641656SFilipe Manana  */
4323f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4324f0641656SFilipe Manana 			 struct btrfs_root *root,
4325f0641656SFilipe Manana 			 struct btrfs_path *path,
4326f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4327f0641656SFilipe Manana {
4328f0641656SFilipe Manana 	struct extent_buffer *leaf;
4329f0641656SFilipe Manana 	int ret;
4330f0641656SFilipe Manana 	u32 item_size;
4331f0641656SFilipe Manana 
4332f0641656SFilipe Manana 	leaf = path->nodes[0];
43333212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4334f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4335f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4336f0641656SFilipe Manana 	if (ret)
4337f0641656SFilipe Manana 		return ret;
4338f0641656SFilipe Manana 
4339f0641656SFilipe Manana 	path->slots[0]++;
4340f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4341f0641656SFilipe Manana 	leaf = path->nodes[0];
4342f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4343f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4344f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4345f0641656SFilipe Manana 			     item_size);
4346f0641656SFilipe Manana 	return 0;
4347f0641656SFilipe Manana }
4348f0641656SFilipe Manana 
4349f0641656SFilipe Manana /*
43505de08d7dSChris Mason  * delete the pointer from a given node.
435174123bd7SChris Mason  *
4352d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4353d352ac68SChris Mason  * empty a node.
435474123bd7SChris Mason  */
4355afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4356afe5fea7STsutomu Itoh 		    int level, int slot)
4357be0e5c09SChris Mason {
43585f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
43597518a238SChris Mason 	u32 nritems;
4360f3ea38daSJan Schmidt 	int ret;
4361be0e5c09SChris Mason 
43625f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4363be0e5c09SChris Mason 	if (slot != nritems - 1) {
4364bf1d3425SDavid Sterba 		if (level) {
4365f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4366f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4367bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4368bf1d3425SDavid Sterba 		}
43695f39d397SChris Mason 		memmove_extent_buffer(parent,
4370e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot),
4371e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot + 1),
4372d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4373d6025579SChris Mason 			      (nritems - slot - 1));
437457ba86c0SChris Mason 	} else if (level) {
4375f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
437633cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REMOVE);
437757ba86c0SChris Mason 		BUG_ON(ret < 0);
4378be0e5c09SChris Mason 	}
4379f3ea38daSJan Schmidt 
43807518a238SChris Mason 	nritems--;
43815f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
43827518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
43835f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4384eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
43855f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4386bb803951SChris Mason 	} else if (slot == 0) {
43875f39d397SChris Mason 		struct btrfs_disk_key disk_key;
43885f39d397SChris Mason 
43895f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4390b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4391be0e5c09SChris Mason 	}
4392d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4393be0e5c09SChris Mason }
4394be0e5c09SChris Mason 
439574123bd7SChris Mason /*
4396323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
43975d4f98a2SYan Zheng  * path->nodes[1].
4398323ac95bSChris Mason  *
4399323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4400323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4401323ac95bSChris Mason  *
4402323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4403323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4404323ac95bSChris Mason  */
4405143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4406323ac95bSChris Mason 				    struct btrfs_root *root,
44075d4f98a2SYan Zheng 				    struct btrfs_path *path,
44085d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4409323ac95bSChris Mason {
44105d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4411afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4412323ac95bSChris Mason 
44134d081c41SChris Mason 	/*
44144d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
44154d081c41SChris Mason 	 * aren't holding any locks when we call it
44164d081c41SChris Mason 	 */
44174d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
44184d081c41SChris Mason 
4419f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4420f0486c68SYan, Zheng 
442167439dadSDavid Sterba 	atomic_inc(&leaf->refs);
44227a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
44233083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4424323ac95bSChris Mason }
4425323ac95bSChris Mason /*
442674123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
442774123bd7SChris Mason  * the leaf, remove it from the tree
442874123bd7SChris Mason  */
442985e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
443085e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4431be0e5c09SChris Mason {
44320b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
44335f39d397SChris Mason 	struct extent_buffer *leaf;
4434aa5d6bedSChris Mason 	int ret = 0;
4435aa5d6bedSChris Mason 	int wret;
44367518a238SChris Mason 	u32 nritems;
4437be0e5c09SChris Mason 
44385f39d397SChris Mason 	leaf = path->nodes[0];
44395f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4440be0e5c09SChris Mason 
444185e21bacSChris Mason 	if (slot + nr != nritems) {
44420cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
44430cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4444c82f823cSDavid Sterba 		struct btrfs_map_token token;
44450cae23b6SFilipe Manana 		u32 dsize = 0;
44460cae23b6SFilipe Manana 		int i;
44470cae23b6SFilipe Manana 
44480cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
44490cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
44505f39d397SChris Mason 
4451637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + dsize, data_end,
445285e21bacSChris Mason 				  last_off - data_end);
44535f39d397SChris Mason 
4454c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
445585e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
44565f39d397SChris Mason 			u32 ioff;
4457db94535dSChris Mason 
44583212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
44593212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
44600783fcfcSChris Mason 		}
4461db94535dSChris Mason 
4462637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot, slot + nr, nritems - slot - nr);
4463be0e5c09SChris Mason 	}
446485e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
446585e21bacSChris Mason 	nritems -= nr;
44665f39d397SChris Mason 
446774123bd7SChris Mason 	/* delete the leaf if we've emptied it */
44687518a238SChris Mason 	if (nritems == 0) {
44695f39d397SChris Mason 		if (leaf == root->node) {
44705f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
44719a8dd150SChris Mason 		} else {
4472190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, leaf);
4473143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
44749a8dd150SChris Mason 		}
4475be0e5c09SChris Mason 	} else {
44767518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4477aa5d6bedSChris Mason 		if (slot == 0) {
44785f39d397SChris Mason 			struct btrfs_disk_key disk_key;
44795f39d397SChris Mason 
44805f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4481b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4482aa5d6bedSChris Mason 		}
4483aa5d6bedSChris Mason 
44847c4063d1SFilipe Manana 		/*
44857c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
44867c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
44877c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
44887c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
44897c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
44907c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
44917c4063d1SFilipe Manana 		 */
44920b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
44937c4063d1SFilipe Manana 			u32 min_push_space;
44947c4063d1SFilipe Manana 
4495be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4496be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4497be0e5c09SChris Mason 			 * for possible call to del_ptr below
4498be0e5c09SChris Mason 			 */
44994920c9acSChris Mason 			slot = path->slots[1];
450067439dadSDavid Sterba 			atomic_inc(&leaf->refs);
45017c4063d1SFilipe Manana 			/*
45027c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
45037c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
45047c4063d1SFilipe Manana 			 */
45057c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
45067c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
45077c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
45087c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
450954aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4510aa5d6bedSChris Mason 				ret = wret;
45115f39d397SChris Mason 
45125f39d397SChris Mason 			if (path->nodes[0] == leaf &&
45135f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
45147c4063d1SFilipe Manana 				/*
45157c4063d1SFilipe Manana 				 * If we were not able to push all items from our
45167c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
45177c4063d1SFilipe Manana 				 * either push all the remaining items to the
45187c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
45197c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
45207c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
45217c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
45227c4063d1SFilipe Manana 				 * or nearly full.
45237c4063d1SFilipe Manana 				 */
45247c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
45257c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
45267c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
45277c4063d1SFilipe Manana 						       min_push_space, 1, 0);
452854aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4529aa5d6bedSChris Mason 					ret = wret;
4530aa5d6bedSChris Mason 			}
45315f39d397SChris Mason 
45325f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4533323ac95bSChris Mason 				path->slots[1] = slot;
4534143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
45355f39d397SChris Mason 				free_extent_buffer(leaf);
4536143bede5SJeff Mahoney 				ret = 0;
45375de08d7dSChris Mason 			} else {
4538925baeddSChris Mason 				/* if we're still in the path, make sure
4539925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4540925baeddSChris Mason 				 * push_leaf functions must have already
4541925baeddSChris Mason 				 * dirtied this buffer
4542925baeddSChris Mason 				 */
4543925baeddSChris Mason 				if (path->nodes[0] == leaf)
45445f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
45455f39d397SChris Mason 				free_extent_buffer(leaf);
4546be0e5c09SChris Mason 			}
4547d5719762SChris Mason 		} else {
45485f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4549be0e5c09SChris Mason 		}
45509a8dd150SChris Mason 	}
4551aa5d6bedSChris Mason 	return ret;
45529a8dd150SChris Mason }
45539a8dd150SChris Mason 
455497571fd0SChris Mason /*
45553f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4556de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4557de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
45583f157a2fSChris Mason  *
45593f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
45603f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
45613f157a2fSChris Mason  * key and get a writable path.
45623f157a2fSChris Mason  *
45633f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
45643f157a2fSChris Mason  * of the tree.
45653f157a2fSChris Mason  *
4566d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4567d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4568d352ac68SChris Mason  * skipped over (without reading them).
4569d352ac68SChris Mason  *
45703f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
45713f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
45723f157a2fSChris Mason  */
45733f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4574de78b51aSEric Sandeen 			 struct btrfs_path *path,
45753f157a2fSChris Mason 			 u64 min_trans)
45763f157a2fSChris Mason {
45773f157a2fSChris Mason 	struct extent_buffer *cur;
45783f157a2fSChris Mason 	struct btrfs_key found_key;
45793f157a2fSChris Mason 	int slot;
45809652480bSYan 	int sret;
45813f157a2fSChris Mason 	u32 nritems;
45823f157a2fSChris Mason 	int level;
45833f157a2fSChris Mason 	int ret = 1;
4584f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
45853f157a2fSChris Mason 
4586c922b016SStefan Roesch 	ASSERT(!path->nowait);
4587f98de9b9SFilipe Manana 	path->keep_locks = 1;
45883f157a2fSChris Mason again:
4589bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
45903f157a2fSChris Mason 	level = btrfs_header_level(cur);
4591e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
45923f157a2fSChris Mason 	path->nodes[level] = cur;
4593bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
45943f157a2fSChris Mason 
45953f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
45963f157a2fSChris Mason 		ret = 1;
45973f157a2fSChris Mason 		goto out;
45983f157a2fSChris Mason 	}
45993f157a2fSChris Mason 	while (1) {
46003f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
46013f157a2fSChris Mason 		level = btrfs_header_level(cur);
4602fdf8d595SAnand Jain 		sret = btrfs_bin_search(cur, 0, min_key, &slot);
4603cbca7d59SFilipe Manana 		if (sret < 0) {
4604cbca7d59SFilipe Manana 			ret = sret;
4605cbca7d59SFilipe Manana 			goto out;
4606cbca7d59SFilipe Manana 		}
46073f157a2fSChris Mason 
4608323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4609323ac95bSChris Mason 		if (level == path->lowest_level) {
4610e02119d5SChris Mason 			if (slot >= nritems)
4611e02119d5SChris Mason 				goto find_next_key;
46123f157a2fSChris Mason 			ret = 0;
46133f157a2fSChris Mason 			path->slots[level] = slot;
46143f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
46153f157a2fSChris Mason 			goto out;
46163f157a2fSChris Mason 		}
46179652480bSYan 		if (sret && slot > 0)
46189652480bSYan 			slot--;
46193f157a2fSChris Mason 		/*
4620de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4621260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
46223f157a2fSChris Mason 		 */
46233f157a2fSChris Mason 		while (slot < nritems) {
46243f157a2fSChris Mason 			u64 gen;
4625e02119d5SChris Mason 
46263f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
46273f157a2fSChris Mason 			if (gen < min_trans) {
46283f157a2fSChris Mason 				slot++;
46293f157a2fSChris Mason 				continue;
46303f157a2fSChris Mason 			}
46313f157a2fSChris Mason 			break;
46323f157a2fSChris Mason 		}
4633e02119d5SChris Mason find_next_key:
46343f157a2fSChris Mason 		/*
46353f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
46363f157a2fSChris Mason 		 * and find another one
46373f157a2fSChris Mason 		 */
46383f157a2fSChris Mason 		if (slot >= nritems) {
4639e02119d5SChris Mason 			path->slots[level] = slot;
4640e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4641de78b51aSEric Sandeen 						  min_trans);
4642e02119d5SChris Mason 			if (sret == 0) {
4643b3b4aa74SDavid Sterba 				btrfs_release_path(path);
46443f157a2fSChris Mason 				goto again;
46453f157a2fSChris Mason 			} else {
46463f157a2fSChris Mason 				goto out;
46473f157a2fSChris Mason 			}
46483f157a2fSChris Mason 		}
46493f157a2fSChris Mason 		/* save our key for returning back */
46503f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
46513f157a2fSChris Mason 		path->slots[level] = slot;
46523f157a2fSChris Mason 		if (level == path->lowest_level) {
46533f157a2fSChris Mason 			ret = 0;
46543f157a2fSChris Mason 			goto out;
46553f157a2fSChris Mason 		}
46564b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4657fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4658fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4659fb770ae4SLiu Bo 			goto out;
4660fb770ae4SLiu Bo 		}
46613f157a2fSChris Mason 
4662bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4663b4ce94deSChris Mason 
4664bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
46653f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4666f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
46673f157a2fSChris Mason 	}
46683f157a2fSChris Mason out:
4669f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4670f98de9b9SFilipe Manana 	if (ret == 0) {
4671f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4672f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4673f98de9b9SFilipe Manana 	}
46743f157a2fSChris Mason 	return ret;
46753f157a2fSChris Mason }
46763f157a2fSChris Mason 
46773f157a2fSChris Mason /*
46783f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
46793f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4680de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
46813f157a2fSChris Mason  *
46823f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
46833f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
46843f157a2fSChris Mason  *
46853f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
46863f157a2fSChris Mason  * calling this function.
46873f157a2fSChris Mason  */
4688e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4689de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4690e7a84565SChris Mason {
4691e7a84565SChris Mason 	int slot;
4692e7a84565SChris Mason 	struct extent_buffer *c;
4693e7a84565SChris Mason 
46946a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4695e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4696e7a84565SChris Mason 		if (!path->nodes[level])
4697e7a84565SChris Mason 			return 1;
4698e7a84565SChris Mason 
4699e7a84565SChris Mason 		slot = path->slots[level] + 1;
4700e7a84565SChris Mason 		c = path->nodes[level];
47013f157a2fSChris Mason next:
4702e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
470333c66f43SYan Zheng 			int ret;
470433c66f43SYan Zheng 			int orig_lowest;
470533c66f43SYan Zheng 			struct btrfs_key cur_key;
470633c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
470733c66f43SYan Zheng 			    !path->nodes[level + 1])
4708e7a84565SChris Mason 				return 1;
470933c66f43SYan Zheng 
47106a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
471133c66f43SYan Zheng 				level++;
4712e7a84565SChris Mason 				continue;
4713e7a84565SChris Mason 			}
471433c66f43SYan Zheng 
471533c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
471633c66f43SYan Zheng 			if (level == 0)
471733c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
471833c66f43SYan Zheng 			else
471933c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
472033c66f43SYan Zheng 
472133c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4722b3b4aa74SDavid Sterba 			btrfs_release_path(path);
472333c66f43SYan Zheng 			path->lowest_level = level;
472433c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
472533c66f43SYan Zheng 						0, 0);
472633c66f43SYan Zheng 			path->lowest_level = orig_lowest;
472733c66f43SYan Zheng 			if (ret < 0)
472833c66f43SYan Zheng 				return ret;
472933c66f43SYan Zheng 
473033c66f43SYan Zheng 			c = path->nodes[level];
473133c66f43SYan Zheng 			slot = path->slots[level];
473233c66f43SYan Zheng 			if (ret == 0)
473333c66f43SYan Zheng 				slot++;
473433c66f43SYan Zheng 			goto next;
473533c66f43SYan Zheng 		}
473633c66f43SYan Zheng 
4737e7a84565SChris Mason 		if (level == 0)
4738e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
47393f157a2fSChris Mason 		else {
47403f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
47413f157a2fSChris Mason 
47423f157a2fSChris Mason 			if (gen < min_trans) {
47433f157a2fSChris Mason 				slot++;
47443f157a2fSChris Mason 				goto next;
47453f157a2fSChris Mason 			}
4746e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
47473f157a2fSChris Mason 		}
4748e7a84565SChris Mason 		return 0;
4749e7a84565SChris Mason 	}
4750e7a84565SChris Mason 	return 1;
4751e7a84565SChris Mason }
4752e7a84565SChris Mason 
47533d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
47543d7806ecSJan Schmidt 			u64 time_seq)
47553d7806ecSJan Schmidt {
4756d97e63b6SChris Mason 	int slot;
47578e73f275SChris Mason 	int level;
47585f39d397SChris Mason 	struct extent_buffer *c;
47598e73f275SChris Mason 	struct extent_buffer *next;
4760d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4761925baeddSChris Mason 	struct btrfs_key key;
4762d96b3424SFilipe Manana 	bool need_commit_sem = false;
4763925baeddSChris Mason 	u32 nritems;
4764925baeddSChris Mason 	int ret;
47650e46318dSJosef Bacik 	int i;
4766925baeddSChris Mason 
4767bdcdd86cSFilipe Manana 	/*
4768bdcdd86cSFilipe Manana 	 * The nowait semantics are used only for write paths, where we don't
4769bdcdd86cSFilipe Manana 	 * use the tree mod log and sequence numbers.
4770bdcdd86cSFilipe Manana 	 */
4771bdcdd86cSFilipe Manana 	if (time_seq)
4772c922b016SStefan Roesch 		ASSERT(!path->nowait);
4773c922b016SStefan Roesch 
4774925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4775d397712bSChris Mason 	if (nritems == 0)
4776925baeddSChris Mason 		return 1;
4777925baeddSChris Mason 
47788e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
47798e73f275SChris Mason again:
47808e73f275SChris Mason 	level = 1;
47818e73f275SChris Mason 	next = NULL;
4782b3b4aa74SDavid Sterba 	btrfs_release_path(path);
47838e73f275SChris Mason 
4784a2135011SChris Mason 	path->keep_locks = 1;
47858e73f275SChris Mason 
4786d96b3424SFilipe Manana 	if (time_seq) {
47873d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4788d96b3424SFilipe Manana 	} else {
4789d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4790d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4791d96b3424SFilipe Manana 			need_commit_sem = true;
4792bdcdd86cSFilipe Manana 			if (path->nowait) {
4793bdcdd86cSFilipe Manana 				if (!down_read_trylock(&fs_info->commit_root_sem)) {
4794bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4795bdcdd86cSFilipe Manana 					goto done;
4796bdcdd86cSFilipe Manana 				}
4797bdcdd86cSFilipe Manana 			} else {
4798d96b3424SFilipe Manana 				down_read(&fs_info->commit_root_sem);
4799d96b3424SFilipe Manana 			}
4800bdcdd86cSFilipe Manana 		}
4801925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4802d96b3424SFilipe Manana 	}
4803925baeddSChris Mason 	path->keep_locks = 0;
4804925baeddSChris Mason 
4805925baeddSChris Mason 	if (ret < 0)
4806d96b3424SFilipe Manana 		goto done;
4807925baeddSChris Mason 
4808a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4809168fd7d2SChris Mason 	/*
4810168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4811168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4812168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4813168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4814168fd7d2SChris Mason 	 */
4815a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4816e457afecSYan Zheng 		if (ret == 0)
4817168fd7d2SChris Mason 			path->slots[0]++;
48188e73f275SChris Mason 		ret = 0;
4819925baeddSChris Mason 		goto done;
4820925baeddSChris Mason 	}
48210b43e04fSLiu Bo 	/*
48220b43e04fSLiu Bo 	 * So the above check misses one case:
48230b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
48240b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
48250b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
48260b43e04fSLiu Bo 	 *
48270b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
48280b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
48290b43e04fSLiu Bo 	 *
48300b43e04fSLiu Bo 	 * And a bit more explanation about this check,
48310b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
48320b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
48330b43e04fSLiu Bo 	 * bigger one.
48340b43e04fSLiu Bo 	 */
48350b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
48360b43e04fSLiu Bo 		ret = 0;
48370b43e04fSLiu Bo 		goto done;
48380b43e04fSLiu Bo 	}
4839d97e63b6SChris Mason 
4840234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
48418e73f275SChris Mason 		if (!path->nodes[level]) {
48428e73f275SChris Mason 			ret = 1;
48438e73f275SChris Mason 			goto done;
48448e73f275SChris Mason 		}
48455f39d397SChris Mason 
4846d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4847d97e63b6SChris Mason 		c = path->nodes[level];
48485f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4849d97e63b6SChris Mason 			level++;
48508e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
48518e73f275SChris Mason 				ret = 1;
48528e73f275SChris Mason 				goto done;
48538e73f275SChris Mason 			}
4854d97e63b6SChris Mason 			continue;
4855d97e63b6SChris Mason 		}
48565f39d397SChris Mason 
48570e46318dSJosef Bacik 
48580e46318dSJosef Bacik 		/*
48590e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
48600e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
48610e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
48620e46318dSJosef Bacik 		 */
48630e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
48640e46318dSJosef Bacik 			if (path->locks[level]) {
48650e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
48660e46318dSJosef Bacik 				path->locks[i] = 0;
48670e46318dSJosef Bacik 			}
48680e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
48690e46318dSJosef Bacik 			path->nodes[i] = NULL;
4870925baeddSChris Mason 		}
48715f39d397SChris Mason 
48728e73f275SChris Mason 		next = c;
4873d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4874cda79c54SDavid Sterba 					    slot, &key);
4875bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
48768e73f275SChris Mason 			goto again;
48775f39d397SChris Mason 
487876a05b35SChris Mason 		if (ret < 0) {
4879b3b4aa74SDavid Sterba 			btrfs_release_path(path);
488076a05b35SChris Mason 			goto done;
488176a05b35SChris Mason 		}
488276a05b35SChris Mason 
48835cd57b2cSChris Mason 		if (!path->skip_locking) {
4884bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4885bdcdd86cSFilipe Manana 			if (!ret && path->nowait) {
4886bdcdd86cSFilipe Manana 				ret = -EAGAIN;
4887bdcdd86cSFilipe Manana 				goto done;
4888bdcdd86cSFilipe Manana 			}
4889d42244a0SJan Schmidt 			if (!ret && time_seq) {
4890d42244a0SJan Schmidt 				/*
4891d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4892d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4893d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4894d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4895d42244a0SJan Schmidt 				 * on our lock and cycle.
4896d42244a0SJan Schmidt 				 */
4897cf538830SJan Schmidt 				free_extent_buffer(next);
4898d42244a0SJan Schmidt 				btrfs_release_path(path);
4899d42244a0SJan Schmidt 				cond_resched();
4900d42244a0SJan Schmidt 				goto again;
4901d42244a0SJan Schmidt 			}
49020e46318dSJosef Bacik 			if (!ret)
49030e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4904bd681513SChris Mason 		}
4905d97e63b6SChris Mason 		break;
4906d97e63b6SChris Mason 	}
4907d97e63b6SChris Mason 	path->slots[level] = slot;
4908d97e63b6SChris Mason 	while (1) {
4909d97e63b6SChris Mason 		level--;
4910d97e63b6SChris Mason 		path->nodes[level] = next;
4911d97e63b6SChris Mason 		path->slots[level] = 0;
4912a74a4b97SChris Mason 		if (!path->skip_locking)
4913ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4914d97e63b6SChris Mason 		if (!level)
4915d97e63b6SChris Mason 			break;
4916b4ce94deSChris Mason 
4917d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4918cda79c54SDavid Sterba 					    0, &key);
4919bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
49208e73f275SChris Mason 			goto again;
49218e73f275SChris Mason 
492276a05b35SChris Mason 		if (ret < 0) {
4923b3b4aa74SDavid Sterba 			btrfs_release_path(path);
492476a05b35SChris Mason 			goto done;
492576a05b35SChris Mason 		}
492676a05b35SChris Mason 
4927bdcdd86cSFilipe Manana 		if (!path->skip_locking) {
4928bdcdd86cSFilipe Manana 			if (path->nowait) {
4929bdcdd86cSFilipe Manana 				if (!btrfs_try_tree_read_lock(next)) {
4930bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4931bdcdd86cSFilipe Manana 					goto done;
4932bdcdd86cSFilipe Manana 				}
4933bdcdd86cSFilipe Manana 			} else {
49340e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4935d97e63b6SChris Mason 			}
4936bdcdd86cSFilipe Manana 		}
4937bdcdd86cSFilipe Manana 	}
49388e73f275SChris Mason 	ret = 0;
4939925baeddSChris Mason done:
4940f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
4941d96b3424SFilipe Manana 	if (need_commit_sem) {
4942d96b3424SFilipe Manana 		int ret2;
4943d96b3424SFilipe Manana 
4944d96b3424SFilipe Manana 		path->need_commit_sem = 1;
4945d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
4946d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
4947d96b3424SFilipe Manana 		if (ret2)
4948d96b3424SFilipe Manana 			ret = ret2;
4949d96b3424SFilipe Manana 	}
49508e73f275SChris Mason 
49518e73f275SChris Mason 	return ret;
4952d97e63b6SChris Mason }
49530b86a832SChris Mason 
4954890d2b1aSJosef Bacik int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
4955890d2b1aSJosef Bacik {
4956890d2b1aSJosef Bacik 	path->slots[0]++;
4957890d2b1aSJosef Bacik 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
4958890d2b1aSJosef Bacik 		return btrfs_next_old_leaf(root, path, time_seq);
4959890d2b1aSJosef Bacik 	return 0;
4960890d2b1aSJosef Bacik }
4961890d2b1aSJosef Bacik 
49623f157a2fSChris Mason /*
49633f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
49643f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
49653f157a2fSChris Mason  *
49663f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
49673f157a2fSChris Mason  */
49680b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
49690b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
49700b86a832SChris Mason 			int type)
49710b86a832SChris Mason {
49720b86a832SChris Mason 	struct btrfs_key found_key;
49730b86a832SChris Mason 	struct extent_buffer *leaf;
4974e02119d5SChris Mason 	u32 nritems;
49750b86a832SChris Mason 	int ret;
49760b86a832SChris Mason 
49770b86a832SChris Mason 	while (1) {
49780b86a832SChris Mason 		if (path->slots[0] == 0) {
49790b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
49800b86a832SChris Mason 			if (ret != 0)
49810b86a832SChris Mason 				return ret;
49820b86a832SChris Mason 		} else {
49830b86a832SChris Mason 			path->slots[0]--;
49840b86a832SChris Mason 		}
49850b86a832SChris Mason 		leaf = path->nodes[0];
4986e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
4987e02119d5SChris Mason 		if (nritems == 0)
4988e02119d5SChris Mason 			return 1;
4989e02119d5SChris Mason 		if (path->slots[0] == nritems)
4990e02119d5SChris Mason 			path->slots[0]--;
4991e02119d5SChris Mason 
49920b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4993e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
4994e02119d5SChris Mason 			break;
49950a4eefbbSYan Zheng 		if (found_key.type == type)
49960a4eefbbSYan Zheng 			return 0;
4997e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
4998e02119d5SChris Mason 		    found_key.type < type)
4999e02119d5SChris Mason 			break;
50000b86a832SChris Mason 	}
50010b86a832SChris Mason 	return 1;
50020b86a832SChris Mason }
5003ade2e0b3SWang Shilong 
5004ade2e0b3SWang Shilong /*
5005ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5006ade2e0b3SWang Shilong  * min objecitd.
5007ade2e0b3SWang Shilong  *
5008ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5009ade2e0b3SWang Shilong  */
5010ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5011ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5012ade2e0b3SWang Shilong {
5013ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5014ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5015ade2e0b3SWang Shilong 	u32 nritems;
5016ade2e0b3SWang Shilong 	int ret;
5017ade2e0b3SWang Shilong 
5018ade2e0b3SWang Shilong 	while (1) {
5019ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5020ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5021ade2e0b3SWang Shilong 			if (ret != 0)
5022ade2e0b3SWang Shilong 				return ret;
5023ade2e0b3SWang Shilong 		} else {
5024ade2e0b3SWang Shilong 			path->slots[0]--;
5025ade2e0b3SWang Shilong 		}
5026ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5027ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5028ade2e0b3SWang Shilong 		if (nritems == 0)
5029ade2e0b3SWang Shilong 			return 1;
5030ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5031ade2e0b3SWang Shilong 			path->slots[0]--;
5032ade2e0b3SWang Shilong 
5033ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5034ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5035ade2e0b3SWang Shilong 			break;
5036ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5037ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5038ade2e0b3SWang Shilong 			return 0;
5039ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5040ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5041ade2e0b3SWang Shilong 			break;
5042ade2e0b3SWang Shilong 	}
5043ade2e0b3SWang Shilong 	return 1;
5044ade2e0b3SWang Shilong }
5045226463d7SJosef Bacik 
5046226463d7SJosef Bacik int __init btrfs_ctree_init(void)
5047226463d7SJosef Bacik {
5048226463d7SJosef Bacik 	btrfs_path_cachep = kmem_cache_create("btrfs_path",
5049226463d7SJosef Bacik 			sizeof(struct btrfs_path), 0,
5050226463d7SJosef Bacik 			SLAB_MEM_SPREAD, NULL);
5051226463d7SJosef Bacik 	if (!btrfs_path_cachep)
5052226463d7SJosef Bacik 		return -ENOMEM;
5053226463d7SJosef Bacik 	return 0;
5054226463d7SJosef Bacik }
5055226463d7SJosef Bacik 
5056226463d7SJosef Bacik void __cold btrfs_ctree_exit(void)
5057226463d7SJosef Bacik {
5058226463d7SJosef Bacik 	kmem_cache_destroy(btrfs_path_cachep);
5059226463d7SJosef Bacik }
5060