xref: /openbmc/linux/fs/btrfs/ctree.c (revision 22d907bcd283d69d5e60497fc0d51969545c583b)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
3d352ac68SChris Mason  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
6a6b6e75eSChris Mason #include <linux/sched.h>
75a0e3ad6STejun Heo #include <linux/slab.h>
8bd989ba3SJan Schmidt #include <linux/rbtree.h>
9adf02123SDavid Sterba #include <linux/mm.h>
10e41d12f5SChristoph Hellwig #include <linux/error-injection.h>
119b569ea0SJosef Bacik #include "messages.h"
12eb60ceacSChris Mason #include "ctree.h"
13eb60ceacSChris Mason #include "disk-io.h"
147f5c1516SChris Mason #include "transaction.h"
155f39d397SChris Mason #include "print-tree.h"
16925baeddSChris Mason #include "locking.h"
17de37aa51SNikolay Borisov #include "volumes.h"
18f616f5cdSQu Wenruo #include "qgroup.h"
19f3a84ccdSFilipe Manana #include "tree-mod-log.h"
2088c602abSQu Wenruo #include "tree-checker.h"
21ec8eb376SJosef Bacik #include "fs.h"
22ad1ac501SJosef Bacik #include "accessors.h"
23a0231804SJosef Bacik #include "extent-tree.h"
2467707479SJosef Bacik #include "relocation.h"
256bfd0ffaSJosef Bacik #include "file-item.h"
269a8dd150SChris Mason 
27226463d7SJosef Bacik static struct kmem_cache *btrfs_path_cachep;
28226463d7SJosef Bacik 
29e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
30e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
31310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
32310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
33310712b2SOmar Sandoval 		      int data_size, int extend);
345f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
352ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
36971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
375f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
385f39d397SChris Mason 			      struct extent_buffer *dst_buf,
395f39d397SChris Mason 			      struct extent_buffer *src_buf);
40d97e63b6SChris Mason 
41af024ed2SJohannes Thumshirn static const struct btrfs_csums {
42af024ed2SJohannes Thumshirn 	u16		size;
4359a0fcdbSDavid Sterba 	const char	name[10];
4459a0fcdbSDavid Sterba 	const char	driver[12];
45af024ed2SJohannes Thumshirn } btrfs_csums[] = {
46af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
473951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
483831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
49352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
50352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
51af024ed2SJohannes Thumshirn };
52af024ed2SJohannes Thumshirn 
533a3178c7SJosef Bacik /*
543a3178c7SJosef Bacik  * The leaf data grows from end-to-front in the node.  this returns the address
553a3178c7SJosef Bacik  * of the start of the last item, which is the stop of the leaf data stack.
563a3178c7SJosef Bacik  */
573a3178c7SJosef Bacik static unsigned int leaf_data_end(const struct extent_buffer *leaf)
583a3178c7SJosef Bacik {
593a3178c7SJosef Bacik 	u32 nr = btrfs_header_nritems(leaf);
603a3178c7SJosef Bacik 
613a3178c7SJosef Bacik 	if (nr == 0)
623a3178c7SJosef Bacik 		return BTRFS_LEAF_DATA_SIZE(leaf->fs_info);
633a3178c7SJosef Bacik 	return btrfs_item_offset(leaf, nr - 1);
643a3178c7SJosef Bacik }
653a3178c7SJosef Bacik 
66637e3b48SJosef Bacik /*
67637e3b48SJosef Bacik  * Move data in a @leaf (using memmove, safe for overlapping ranges).
68637e3b48SJosef Bacik  *
69637e3b48SJosef Bacik  * @leaf:	leaf that we're doing a memmove on
70637e3b48SJosef Bacik  * @dst_offset:	item data offset we're moving to
71637e3b48SJosef Bacik  * @src_offset:	item data offset were' moving from
72637e3b48SJosef Bacik  * @len:	length of the data we're moving
73637e3b48SJosef Bacik  *
74637e3b48SJosef Bacik  * Wrapper around memmove_extent_buffer() that takes into account the header on
75637e3b48SJosef Bacik  * the leaf.  The btrfs_item offset's start directly after the header, so we
76637e3b48SJosef Bacik  * have to adjust any offsets to account for the header in the leaf.  This
77637e3b48SJosef Bacik  * handles that math to simplify the callers.
78637e3b48SJosef Bacik  */
79637e3b48SJosef Bacik static inline void memmove_leaf_data(const struct extent_buffer *leaf,
80637e3b48SJosef Bacik 				     unsigned long dst_offset,
81637e3b48SJosef Bacik 				     unsigned long src_offset,
82637e3b48SJosef Bacik 				     unsigned long len)
83637e3b48SJosef Bacik {
848009adf3SJosef Bacik 	memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, 0) + dst_offset,
858009adf3SJosef Bacik 			      btrfs_item_nr_offset(leaf, 0) + src_offset, len);
86637e3b48SJosef Bacik }
87637e3b48SJosef Bacik 
88637e3b48SJosef Bacik /*
89637e3b48SJosef Bacik  * Copy item data from @src into @dst at the given @offset.
90637e3b48SJosef Bacik  *
91637e3b48SJosef Bacik  * @dst:	destination leaf that we're copying into
92637e3b48SJosef Bacik  * @src:	source leaf that we're copying from
93637e3b48SJosef Bacik  * @dst_offset:	item data offset we're copying to
94637e3b48SJosef Bacik  * @src_offset:	item data offset were' copying from
95637e3b48SJosef Bacik  * @len:	length of the data we're copying
96637e3b48SJosef Bacik  *
97637e3b48SJosef Bacik  * Wrapper around copy_extent_buffer() that takes into account the header on
98637e3b48SJosef Bacik  * the leaf.  The btrfs_item offset's start directly after the header, so we
99637e3b48SJosef Bacik  * have to adjust any offsets to account for the header in the leaf.  This
100637e3b48SJosef Bacik  * handles that math to simplify the callers.
101637e3b48SJosef Bacik  */
102637e3b48SJosef Bacik static inline void copy_leaf_data(const struct extent_buffer *dst,
103637e3b48SJosef Bacik 				  const struct extent_buffer *src,
104637e3b48SJosef Bacik 				  unsigned long dst_offset,
105637e3b48SJosef Bacik 				  unsigned long src_offset, unsigned long len)
106637e3b48SJosef Bacik {
1078009adf3SJosef Bacik 	copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, 0) + dst_offset,
1088009adf3SJosef Bacik 			   btrfs_item_nr_offset(src, 0) + src_offset, len);
109637e3b48SJosef Bacik }
110637e3b48SJosef Bacik 
111637e3b48SJosef Bacik /*
112637e3b48SJosef Bacik  * Move items in a @leaf (using memmove).
113637e3b48SJosef Bacik  *
114637e3b48SJosef Bacik  * @dst:	destination leaf for the items
115637e3b48SJosef Bacik  * @dst_item:	the item nr we're copying into
116637e3b48SJosef Bacik  * @src_item:	the item nr we're copying from
117637e3b48SJosef Bacik  * @nr_items:	the number of items to copy
118637e3b48SJosef Bacik  *
119637e3b48SJosef Bacik  * Wrapper around memmove_extent_buffer() that does the math to get the
120637e3b48SJosef Bacik  * appropriate offsets into the leaf from the item numbers.
121637e3b48SJosef Bacik  */
122637e3b48SJosef Bacik static inline void memmove_leaf_items(const struct extent_buffer *leaf,
123637e3b48SJosef Bacik 				      int dst_item, int src_item, int nr_items)
124637e3b48SJosef Bacik {
125637e3b48SJosef Bacik 	memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, dst_item),
126637e3b48SJosef Bacik 			      btrfs_item_nr_offset(leaf, src_item),
127637e3b48SJosef Bacik 			      nr_items * sizeof(struct btrfs_item));
128637e3b48SJosef Bacik }
129637e3b48SJosef Bacik 
130637e3b48SJosef Bacik /*
131637e3b48SJosef Bacik  * Copy items from @src into @dst at the given @offset.
132637e3b48SJosef Bacik  *
133637e3b48SJosef Bacik  * @dst:	destination leaf for the items
134637e3b48SJosef Bacik  * @src:	source leaf for the items
135637e3b48SJosef Bacik  * @dst_item:	the item nr we're copying into
136637e3b48SJosef Bacik  * @src_item:	the item nr we're copying from
137637e3b48SJosef Bacik  * @nr_items:	the number of items to copy
138637e3b48SJosef Bacik  *
139637e3b48SJosef Bacik  * Wrapper around copy_extent_buffer() that does the math to get the
140637e3b48SJosef Bacik  * appropriate offsets into the leaf from the item numbers.
141637e3b48SJosef Bacik  */
142637e3b48SJosef Bacik static inline void copy_leaf_items(const struct extent_buffer *dst,
143637e3b48SJosef Bacik 				   const struct extent_buffer *src,
144637e3b48SJosef Bacik 				   int dst_item, int src_item, int nr_items)
145637e3b48SJosef Bacik {
146637e3b48SJosef Bacik 	copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, dst_item),
147637e3b48SJosef Bacik 			      btrfs_item_nr_offset(src, src_item),
148637e3b48SJosef Bacik 			      nr_items * sizeof(struct btrfs_item));
149637e3b48SJosef Bacik }
150637e3b48SJosef Bacik 
151b3cbfb0dSJosef Bacik /* This exists for btrfs-progs usages. */
152b3cbfb0dSJosef Bacik u16 btrfs_csum_type_size(u16 type)
153b3cbfb0dSJosef Bacik {
154b3cbfb0dSJosef Bacik 	return btrfs_csums[type].size;
155b3cbfb0dSJosef Bacik }
156b3cbfb0dSJosef Bacik 
157af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
158af024ed2SJohannes Thumshirn {
159af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
160af024ed2SJohannes Thumshirn 	/*
161af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
162af024ed2SJohannes Thumshirn 	 */
163b3cbfb0dSJosef Bacik 	return btrfs_csum_type_size(t);
164af024ed2SJohannes Thumshirn }
165af024ed2SJohannes Thumshirn 
166af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
167af024ed2SJohannes Thumshirn {
168af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
169af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
170af024ed2SJohannes Thumshirn }
171af024ed2SJohannes Thumshirn 
172b4e967beSDavid Sterba /*
173b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
174b4e967beSDavid Sterba  * name
175b4e967beSDavid Sterba  */
176b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
177b4e967beSDavid Sterba {
178b4e967beSDavid Sterba 	/* csum type is validated at mount time */
17959a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
18059a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
181b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
182b4e967beSDavid Sterba }
183b4e967beSDavid Sterba 
184604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
185f7cea56cSDavid Sterba {
186f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
187f7cea56cSDavid Sterba }
188f7cea56cSDavid Sterba 
1892c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
1902c90e5d6SChris Mason {
191a4c853afSChenXiaoSong 	might_sleep();
192a4c853afSChenXiaoSong 
193e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
1942c90e5d6SChris Mason }
1952c90e5d6SChris Mason 
196d352ac68SChris Mason /* this also releases the path */
1972c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1982c90e5d6SChris Mason {
199ff175d57SJesper Juhl 	if (!p)
200ff175d57SJesper Juhl 		return;
201b3b4aa74SDavid Sterba 	btrfs_release_path(p);
2022c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
2032c90e5d6SChris Mason }
2042c90e5d6SChris Mason 
205d352ac68SChris Mason /*
206d352ac68SChris Mason  * path release drops references on the extent buffers in the path
207d352ac68SChris Mason  * and it drops any locks held by this path
208d352ac68SChris Mason  *
209d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
210d352ac68SChris Mason  */
211b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
212eb60ceacSChris Mason {
213eb60ceacSChris Mason 	int i;
214a2135011SChris Mason 
215234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
2163f157a2fSChris Mason 		p->slots[i] = 0;
217eb60ceacSChris Mason 		if (!p->nodes[i])
218925baeddSChris Mason 			continue;
219925baeddSChris Mason 		if (p->locks[i]) {
220bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
221925baeddSChris Mason 			p->locks[i] = 0;
222925baeddSChris Mason 		}
2235f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
2243f157a2fSChris Mason 		p->nodes[i] = NULL;
225eb60ceacSChris Mason 	}
226eb60ceacSChris Mason }
227eb60ceacSChris Mason 
228d352ac68SChris Mason /*
2298bb808c6SDavid Sterba  * We want the transaction abort to print stack trace only for errors where the
2308bb808c6SDavid Sterba  * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
2318bb808c6SDavid Sterba  * caused by external factors.
2328bb808c6SDavid Sterba  */
2338bb808c6SDavid Sterba bool __cold abort_should_print_stack(int errno)
2348bb808c6SDavid Sterba {
2358bb808c6SDavid Sterba 	switch (errno) {
2368bb808c6SDavid Sterba 	case -EIO:
2378bb808c6SDavid Sterba 	case -EROFS:
2388bb808c6SDavid Sterba 	case -ENOMEM:
2398bb808c6SDavid Sterba 		return false;
2408bb808c6SDavid Sterba 	}
2418bb808c6SDavid Sterba 	return true;
2428bb808c6SDavid Sterba }
2438bb808c6SDavid Sterba 
2448bb808c6SDavid Sterba /*
245d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
246d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
247d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
248d352ac68SChris Mason  * looping required.
249d352ac68SChris Mason  *
250d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
251d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
252d352ac68SChris Mason  * at any time because there are no locks held.
253d352ac68SChris Mason  */
254925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
255925baeddSChris Mason {
256925baeddSChris Mason 	struct extent_buffer *eb;
257240f62c8SChris Mason 
2583083ee2eSJosef Bacik 	while (1) {
259240f62c8SChris Mason 		rcu_read_lock();
260240f62c8SChris Mason 		eb = rcu_dereference(root->node);
2613083ee2eSJosef Bacik 
2623083ee2eSJosef Bacik 		/*
2633083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
26401327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
2653083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
2663083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
2673083ee2eSJosef Bacik 		 */
2683083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
269240f62c8SChris Mason 			rcu_read_unlock();
2703083ee2eSJosef Bacik 			break;
2713083ee2eSJosef Bacik 		}
2723083ee2eSJosef Bacik 		rcu_read_unlock();
2733083ee2eSJosef Bacik 		synchronize_rcu();
2743083ee2eSJosef Bacik 	}
275925baeddSChris Mason 	return eb;
276925baeddSChris Mason }
277925baeddSChris Mason 
27892a7cc42SQu Wenruo /*
27992a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
28092a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
28192a7cc42SQu Wenruo  * sure they get properly updated on disk.
282d352ac68SChris Mason  */
2830b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
2840b86a832SChris Mason {
2850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2860b246afaSJeff Mahoney 
287e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
288e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
289e7070be1SJosef Bacik 		return;
290e7070be1SJosef Bacik 
2910b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
292e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
293e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
2944fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
295e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
2960b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
297e7070be1SJosef Bacik 		else
298e7070be1SJosef Bacik 			list_move(&root->dirty_list,
2990b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
3000b86a832SChris Mason 	}
3010b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
3020b86a832SChris Mason }
3030b86a832SChris Mason 
304d352ac68SChris Mason /*
305d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
306d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
307d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
308d352ac68SChris Mason  */
309be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
310be20aa9dSChris Mason 		      struct btrfs_root *root,
311be20aa9dSChris Mason 		      struct extent_buffer *buf,
312be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
313be20aa9dSChris Mason {
3140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
315be20aa9dSChris Mason 	struct extent_buffer *cow;
316be20aa9dSChris Mason 	int ret = 0;
317be20aa9dSChris Mason 	int level;
3185d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
319be20aa9dSChris Mason 
32092a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
3210b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
32292a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
32327cdeb70SMiao Xie 		trans->transid != root->last_trans);
324be20aa9dSChris Mason 
325be20aa9dSChris Mason 	level = btrfs_header_level(buf);
3265d4f98a2SYan Zheng 	if (level == 0)
3275d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
3285d4f98a2SYan Zheng 	else
3295d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
33031840ae1SZheng Yan 
3314d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
332cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
333cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
3345d4f98a2SYan Zheng 	if (IS_ERR(cow))
335be20aa9dSChris Mason 		return PTR_ERR(cow);
336be20aa9dSChris Mason 
33758e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
338be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
339be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
3405d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
3415d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
3425d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
3435d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
3445d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
3455d4f98a2SYan Zheng 	else
346be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
347be20aa9dSChris Mason 
348de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
3492b82032cSYan Zheng 
350be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
3515d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
352e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
3535d4f98a2SYan Zheng 	else
354e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
355867ed321SJosef Bacik 	if (ret) {
35672c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
35772c9925fSFilipe Manana 		free_extent_buffer(cow);
358867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
359be20aa9dSChris Mason 		return ret;
360867ed321SJosef Bacik 	}
361be20aa9dSChris Mason 
362d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, cow);
363be20aa9dSChris Mason 	*cow_ret = cow;
364be20aa9dSChris Mason 	return 0;
365be20aa9dSChris Mason }
366be20aa9dSChris Mason 
367d352ac68SChris Mason /*
3685d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
3695d4f98a2SYan Zheng  */
370eb96e221SFilipe Manana int btrfs_block_can_be_shared(struct btrfs_trans_handle *trans,
371eb96e221SFilipe Manana 			      struct btrfs_root *root,
3725d4f98a2SYan Zheng 			      struct extent_buffer *buf)
3735d4f98a2SYan Zheng {
3745d4f98a2SYan Zheng 	/*
37592a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
37692a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
37792a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
3785d4f98a2SYan Zheng 	 */
37992a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
380eb96e221SFilipe Manana 	    buf != root->node &&
3815d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
3825d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
383eb96e221SFilipe Manana 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))) {
384eb96e221SFilipe Manana 		if (buf != root->commit_root)
3855d4f98a2SYan Zheng 			return 1;
386eb96e221SFilipe Manana 		/*
387eb96e221SFilipe Manana 		 * An extent buffer that used to be the commit root may still be
388eb96e221SFilipe Manana 		 * shared because the tree height may have increased and it
389eb96e221SFilipe Manana 		 * became a child of a higher level root. This can happen when
390eb96e221SFilipe Manana 		 * snapshotting a subvolume created in the current transaction.
391eb96e221SFilipe Manana 		 */
392eb96e221SFilipe Manana 		if (btrfs_header_generation(buf) == trans->transid)
393eb96e221SFilipe Manana 			return 1;
394eb96e221SFilipe Manana 	}
395a79865c6SNikolay Borisov 
3965d4f98a2SYan Zheng 	return 0;
3975d4f98a2SYan Zheng }
3985d4f98a2SYan Zheng 
3995d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
4005d4f98a2SYan Zheng 				       struct btrfs_root *root,
4015d4f98a2SYan Zheng 				       struct extent_buffer *buf,
402f0486c68SYan, Zheng 				       struct extent_buffer *cow,
403f0486c68SYan, Zheng 				       int *last_ref)
4045d4f98a2SYan Zheng {
4050b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4065d4f98a2SYan Zheng 	u64 refs;
4075d4f98a2SYan Zheng 	u64 owner;
4085d4f98a2SYan Zheng 	u64 flags;
4095d4f98a2SYan Zheng 	u64 new_flags = 0;
4105d4f98a2SYan Zheng 	int ret;
4115d4f98a2SYan Zheng 
4125d4f98a2SYan Zheng 	/*
4135d4f98a2SYan Zheng 	 * Backrefs update rules:
4145d4f98a2SYan Zheng 	 *
4155d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
4165d4f98a2SYan Zheng 	 * allocated by tree relocation.
4175d4f98a2SYan Zheng 	 *
4185d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
4195d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
4205d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
4215d4f98a2SYan Zheng 	 *
4225d4f98a2SYan Zheng 	 * If a tree block is been relocating
4235d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
4245d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
4255d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
4265d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
4275d4f98a2SYan Zheng 	 */
4285d4f98a2SYan Zheng 
429eb96e221SFilipe Manana 	if (btrfs_block_can_be_shared(trans, root, buf)) {
4302ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
4313173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
4323173a18fSJosef Bacik 					       &refs, &flags);
433be1a5564SMark Fasheh 		if (ret)
434be1a5564SMark Fasheh 			return ret;
435eced687eSFilipe Manana 		if (unlikely(refs == 0)) {
436eced687eSFilipe Manana 			btrfs_crit(fs_info,
437eced687eSFilipe Manana 		"found 0 references for tree block at bytenr %llu level %d root %llu",
438eced687eSFilipe Manana 				   buf->start, btrfs_header_level(buf),
439eced687eSFilipe Manana 				   btrfs_root_id(root));
440eced687eSFilipe Manana 			ret = -EUCLEAN;
441eced687eSFilipe Manana 			btrfs_abort_transaction(trans, ret);
442e5df9573SMark Fasheh 			return ret;
443e5df9573SMark Fasheh 		}
4445d4f98a2SYan Zheng 	} else {
4455d4f98a2SYan Zheng 		refs = 1;
4465d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4475d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4485d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
4495d4f98a2SYan Zheng 		else
4505d4f98a2SYan Zheng 			flags = 0;
4515d4f98a2SYan Zheng 	}
4525d4f98a2SYan Zheng 
4535d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
45441a0f85eSFilipe Manana 	if (unlikely(owner == BTRFS_TREE_RELOC_OBJECTID &&
45541a0f85eSFilipe Manana 		     !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))) {
45641a0f85eSFilipe Manana 		btrfs_crit(fs_info,
45741a0f85eSFilipe Manana "found tree block at bytenr %llu level %d root %llu refs %llu flags %llx without full backref flag set",
45841a0f85eSFilipe Manana 			   buf->start, btrfs_header_level(buf),
45941a0f85eSFilipe Manana 			   btrfs_root_id(root), refs, flags);
46041a0f85eSFilipe Manana 		ret = -EUCLEAN;
46141a0f85eSFilipe Manana 		btrfs_abort_transaction(trans, ret);
46241a0f85eSFilipe Manana 		return ret;
46341a0f85eSFilipe Manana 	}
4645d4f98a2SYan Zheng 
4655d4f98a2SYan Zheng 	if (refs > 1) {
4665d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
4675d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
4685d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
469e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
470692826b2SJeff Mahoney 			if (ret)
471692826b2SJeff Mahoney 				return ret;
4725d4f98a2SYan Zheng 
4735d4f98a2SYan Zheng 			if (root->root_key.objectid ==
4745d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
475e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
476692826b2SJeff Mahoney 				if (ret)
477692826b2SJeff Mahoney 					return ret;
478e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
479692826b2SJeff Mahoney 				if (ret)
480692826b2SJeff Mahoney 					return ret;
4815d4f98a2SYan Zheng 			}
4825d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4835d4f98a2SYan Zheng 		} else {
4845d4f98a2SYan Zheng 
4855d4f98a2SYan Zheng 			if (root->root_key.objectid ==
4865d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
487e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
4885d4f98a2SYan Zheng 			else
489e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
490692826b2SJeff Mahoney 			if (ret)
491692826b2SJeff Mahoney 				return ret;
4925d4f98a2SYan Zheng 		}
4935d4f98a2SYan Zheng 		if (new_flags != 0) {
4944aec05faSJosef Bacik 			ret = btrfs_set_disk_extent_flags(trans, buf, new_flags);
495be1a5564SMark Fasheh 			if (ret)
496be1a5564SMark Fasheh 				return ret;
4975d4f98a2SYan Zheng 		}
4985d4f98a2SYan Zheng 	} else {
4995d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5005d4f98a2SYan Zheng 			if (root->root_key.objectid ==
5015d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
502e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
5035d4f98a2SYan Zheng 			else
504e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
505692826b2SJeff Mahoney 			if (ret)
506692826b2SJeff Mahoney 				return ret;
507e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
508692826b2SJeff Mahoney 			if (ret)
509692826b2SJeff Mahoney 				return ret;
5105d4f98a2SYan Zheng 		}
511190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, buf);
512f0486c68SYan, Zheng 		*last_ref = 1;
5135d4f98a2SYan Zheng 	}
5145d4f98a2SYan Zheng 	return 0;
5155d4f98a2SYan Zheng }
5165d4f98a2SYan Zheng 
5175d4f98a2SYan Zheng /*
518d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
519d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
520d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
521d397712bSChris Mason  * dirty again.
522d352ac68SChris Mason  *
523d352ac68SChris Mason  * search_start -- an allocation hint for the new block
524d352ac68SChris Mason  *
525d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
526d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
527d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
528d352ac68SChris Mason  */
529d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
5305f39d397SChris Mason 			     struct btrfs_root *root,
5315f39d397SChris Mason 			     struct extent_buffer *buf,
5325f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
5335f39d397SChris Mason 			     struct extent_buffer **cow_ret,
5349631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
5359631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
5366702ed49SChris Mason {
5370b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5385d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
5395f39d397SChris Mason 	struct extent_buffer *cow;
540be1a5564SMark Fasheh 	int level, ret;
541f0486c68SYan, Zheng 	int last_ref = 0;
542925baeddSChris Mason 	int unlock_orig = 0;
5430f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
5446702ed49SChris Mason 
545925baeddSChris Mason 	if (*cow_ret == buf)
546925baeddSChris Mason 		unlock_orig = 1;
547925baeddSChris Mason 
54849d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
549925baeddSChris Mason 
55092a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
5510b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
55292a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
55327cdeb70SMiao Xie 		trans->transid != root->last_trans);
5545f39d397SChris Mason 
5557bb86316SChris Mason 	level = btrfs_header_level(buf);
55631840ae1SZheng Yan 
5575d4f98a2SYan Zheng 	if (level == 0)
5585d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
5595d4f98a2SYan Zheng 	else
5605d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
5615d4f98a2SYan Zheng 
5620f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
5635d4f98a2SYan Zheng 		parent_start = parent->start;
5645d4f98a2SYan Zheng 
56579bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
56679bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
56779bd3712SFilipe Manana 				     search_start, empty_size, nest);
5686702ed49SChris Mason 	if (IS_ERR(cow))
5696702ed49SChris Mason 		return PTR_ERR(cow);
5706702ed49SChris Mason 
571b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
572b4ce94deSChris Mason 
57358e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
574db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
5755f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
5765d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
5775d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
5785d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
5795d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
5805d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
5815d4f98a2SYan Zheng 	else
5825f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
5836702ed49SChris Mason 
584de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
5852b82032cSYan Zheng 
586be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
587b68dc2a9SMark Fasheh 	if (ret) {
588572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
589572c83acSJosef Bacik 		free_extent_buffer(cow);
59066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
591b68dc2a9SMark Fasheh 		return ret;
592b68dc2a9SMark Fasheh 	}
5931a40e23bSZheng Yan 
59492a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
59583d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
59693314e3bSZhaolei 		if (ret) {
597572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
598572c83acSJosef Bacik 			free_extent_buffer(cow);
59966642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
60083d4cfd4SJosef Bacik 			return ret;
60183d4cfd4SJosef Bacik 		}
60293314e3bSZhaolei 	}
6033fd0a558SYan, Zheng 
6046702ed49SChris Mason 	if (buf == root->node) {
605925baeddSChris Mason 		WARN_ON(parent && parent != buf);
6065d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
6075d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
6085d4f98a2SYan Zheng 			parent_start = buf->start;
609925baeddSChris Mason 
610406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
61140b0a749SFilipe Manana 		if (ret < 0) {
61240b0a749SFilipe Manana 			btrfs_tree_unlock(cow);
61340b0a749SFilipe Manana 			free_extent_buffer(cow);
61440b0a749SFilipe Manana 			btrfs_abort_transaction(trans, ret);
61540b0a749SFilipe Manana 			return ret;
61640b0a749SFilipe Manana 		}
61740b0a749SFilipe Manana 		atomic_inc(&cow->refs);
618240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
619925baeddSChris Mason 
620*22d907bcSFilipe Manana 		ret = btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
6217a163608SFilipe Manana 					    parent_start, last_ref);
6225f39d397SChris Mason 		free_extent_buffer(buf);
6230b86a832SChris Mason 		add_root_to_dirty_list(root);
624*22d907bcSFilipe Manana 		if (ret < 0) {
625*22d907bcSFilipe Manana 			btrfs_tree_unlock(cow);
626*22d907bcSFilipe Manana 			free_extent_buffer(cow);
627*22d907bcSFilipe Manana 			btrfs_abort_transaction(trans, ret);
628*22d907bcSFilipe Manana 			return ret;
629*22d907bcSFilipe Manana 		}
6306702ed49SChris Mason 	} else {
6315d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
632d09c5152SFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, parent_slot,
63333cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
634d09c5152SFilipe Manana 		if (ret) {
635d09c5152SFilipe Manana 			btrfs_tree_unlock(cow);
636d09c5152SFilipe Manana 			free_extent_buffer(cow);
637d09c5152SFilipe Manana 			btrfs_abort_transaction(trans, ret);
638d09c5152SFilipe Manana 			return ret;
639d09c5152SFilipe Manana 		}
6405f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
641db94535dSChris Mason 					cow->start);
64274493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
64374493f7aSChris Mason 					      trans->transid);
644d5e09e38SFilipe Manana 		btrfs_mark_buffer_dirty(trans, parent);
6455de865eeSFilipe David Borba Manana 		if (last_ref) {
646f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
6475de865eeSFilipe David Borba Manana 			if (ret) {
648572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
649572c83acSJosef Bacik 				free_extent_buffer(cow);
65066642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
6515de865eeSFilipe David Borba Manana 				return ret;
6525de865eeSFilipe David Borba Manana 			}
6535de865eeSFilipe David Borba Manana 		}
654*22d907bcSFilipe Manana 		ret = btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
6557a163608SFilipe Manana 					    parent_start, last_ref);
656*22d907bcSFilipe Manana 		if (ret < 0) {
657*22d907bcSFilipe Manana 			btrfs_tree_unlock(cow);
658*22d907bcSFilipe Manana 			free_extent_buffer(cow);
659*22d907bcSFilipe Manana 			btrfs_abort_transaction(trans, ret);
660*22d907bcSFilipe Manana 			return ret;
661*22d907bcSFilipe Manana 		}
6626702ed49SChris Mason 	}
663925baeddSChris Mason 	if (unlock_orig)
664925baeddSChris Mason 		btrfs_tree_unlock(buf);
6653083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
666d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, cow);
6676702ed49SChris Mason 	*cow_ret = cow;
6686702ed49SChris Mason 	return 0;
6696702ed49SChris Mason }
6706702ed49SChris Mason 
6715d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
6725d4f98a2SYan Zheng 				   struct btrfs_root *root,
6735d4f98a2SYan Zheng 				   struct extent_buffer *buf)
6745d4f98a2SYan Zheng {
675f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
676faa2dbf0SJosef Bacik 		return 0;
677fccb84c9SDavid Sterba 
678d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
679d1980131SDavid Sterba 	smp_mb__before_atomic();
680f1ebcc74SLiu Bo 
681f1ebcc74SLiu Bo 	/*
682f1ebcc74SLiu Bo 	 * We do not need to cow a block if
683f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
684f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
685f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
686f1ebcc74SLiu Bo 	 *
687f1ebcc74SLiu Bo 	 * What is forced COW:
68801327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
68952042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
690f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
691f1ebcc74SLiu Bo 	 */
6925d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
6935d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
6945d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
695f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
69627cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
6975d4f98a2SYan Zheng 		return 0;
6985d4f98a2SYan Zheng 	return 1;
6995d4f98a2SYan Zheng }
7005d4f98a2SYan Zheng 
701d352ac68SChris Mason /*
702d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
70301327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
704d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
705d352ac68SChris Mason  */
706d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
7075f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
7085f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
7099631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
7109631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
71102217ed2SChris Mason {
7120b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
7136702ed49SChris Mason 	u64 search_start;
714f510cfecSChris Mason 	int ret;
715dc17ff8fSChris Mason 
716a2caab29SFilipe Manana 	if (unlikely(test_bit(BTRFS_ROOT_DELETING, &root->state))) {
717a2caab29SFilipe Manana 		btrfs_abort_transaction(trans, -EUCLEAN);
718a2caab29SFilipe Manana 		btrfs_crit(fs_info,
719a2caab29SFilipe Manana 		   "attempt to COW block %llu on root %llu that is being deleted",
720a2caab29SFilipe Manana 			   buf->start, btrfs_root_id(root));
721a2caab29SFilipe Manana 		return -EUCLEAN;
722a2caab29SFilipe Manana 	}
72383354f07SJosef Bacik 
72448774f3bSFilipe Manana 	/*
72548774f3bSFilipe Manana 	 * COWing must happen through a running transaction, which always
72648774f3bSFilipe Manana 	 * matches the current fs generation (it's a transaction with a state
72748774f3bSFilipe Manana 	 * less than TRANS_STATE_UNBLOCKED). If it doesn't, then turn the fs
72848774f3bSFilipe Manana 	 * into error state to prevent the commit of any transaction.
72948774f3bSFilipe Manana 	 */
73048774f3bSFilipe Manana 	if (unlikely(trans->transaction != fs_info->running_transaction ||
73148774f3bSFilipe Manana 		     trans->transid != fs_info->generation)) {
73248774f3bSFilipe Manana 		btrfs_abort_transaction(trans, -EUCLEAN);
73348774f3bSFilipe Manana 		btrfs_crit(fs_info,
73448774f3bSFilipe Manana "unexpected transaction when attempting to COW block %llu on root %llu, transaction %llu running transaction %llu fs generation %llu",
73548774f3bSFilipe Manana 			   buf->start, btrfs_root_id(root), trans->transid,
73648774f3bSFilipe Manana 			   fs_info->running_transaction->transid,
73748774f3bSFilipe Manana 			   fs_info->generation);
73848774f3bSFilipe Manana 		return -EUCLEAN;
73948774f3bSFilipe Manana 	}
740dc17ff8fSChris Mason 
7415d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
74202217ed2SChris Mason 		*cow_ret = buf;
74302217ed2SChris Mason 		return 0;
74402217ed2SChris Mason 	}
745c487685dSChris Mason 
746ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
747b4ce94deSChris Mason 
748f616f5cdSQu Wenruo 	/*
749f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
750f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
751f616f5cdSQu Wenruo 	 *
752f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
753f616f5cdSQu Wenruo 	 */
754f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
755f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
7569631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
7571abe9b8aSliubo 
7581abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
7591abe9b8aSliubo 
760f510cfecSChris Mason 	return ret;
7612c90e5d6SChris Mason }
762f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
7636702ed49SChris Mason 
764d352ac68SChris Mason /*
765d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
766d352ac68SChris Mason  * node are actually close by
767d352ac68SChris Mason  */
7686b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
7696702ed49SChris Mason {
7706b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
7716702ed49SChris Mason 		return 1;
7726b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
7736702ed49SChris Mason 		return 1;
77402217ed2SChris Mason 	return 0;
77502217ed2SChris Mason }
77602217ed2SChris Mason 
777ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
778ce6ef5abSDavid Sterba 
779ce6ef5abSDavid Sterba /*
780ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
781ce6ef5abSDavid Sterba  * we can avoid the conversion.
782ce6ef5abSDavid Sterba  */
783ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
784ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
785ce6ef5abSDavid Sterba {
786ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
787ce6ef5abSDavid Sterba 
788ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
789ce6ef5abSDavid Sterba }
790ce6ef5abSDavid Sterba 
791ce6ef5abSDavid Sterba #else
792ce6ef5abSDavid Sterba 
793081e9573SChris Mason /*
794081e9573SChris Mason  * compare two keys in a memcmp fashion
795081e9573SChris Mason  */
796310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
797310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
798081e9573SChris Mason {
799081e9573SChris Mason 	struct btrfs_key k1;
800081e9573SChris Mason 
801081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
802081e9573SChris Mason 
80320736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
804081e9573SChris Mason }
805ce6ef5abSDavid Sterba #endif
806081e9573SChris Mason 
807f3465ca4SJosef Bacik /*
808f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
809f3465ca4SJosef Bacik  */
810e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
811f3465ca4SJosef Bacik {
812f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
813f3465ca4SJosef Bacik 		return 1;
814f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
815f3465ca4SJosef Bacik 		return -1;
816f3465ca4SJosef Bacik 	if (k1->type > k2->type)
817f3465ca4SJosef Bacik 		return 1;
818f3465ca4SJosef Bacik 	if (k1->type < k2->type)
819f3465ca4SJosef Bacik 		return -1;
820f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
821f3465ca4SJosef Bacik 		return 1;
822f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
823f3465ca4SJosef Bacik 		return -1;
824f3465ca4SJosef Bacik 	return 0;
825f3465ca4SJosef Bacik }
826081e9573SChris Mason 
827d352ac68SChris Mason /*
828d352ac68SChris Mason  * this is used by the defrag code to go through all the
829d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
830d352ac68SChris Mason  * disk order is close to key order
831d352ac68SChris Mason  */
8326702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
8335f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
834de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
835a6b6e75eSChris Mason 		       struct btrfs_key *progress)
8366702ed49SChris Mason {
8370b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8386b80053dSChris Mason 	struct extent_buffer *cur;
8396702ed49SChris Mason 	u64 blocknr;
840e9d0b13bSChris Mason 	u64 search_start = *last_ret;
841e9d0b13bSChris Mason 	u64 last_block = 0;
8426702ed49SChris Mason 	u64 other;
8436702ed49SChris Mason 	u32 parent_nritems;
8446702ed49SChris Mason 	int end_slot;
8456702ed49SChris Mason 	int i;
8466702ed49SChris Mason 	int err = 0;
8476b80053dSChris Mason 	u32 blocksize;
848081e9573SChris Mason 	int progress_passed = 0;
849081e9573SChris Mason 	struct btrfs_disk_key disk_key;
8506702ed49SChris Mason 
851e36f9491SFilipe Manana 	/*
852e36f9491SFilipe Manana 	 * COWing must happen through a running transaction, which always
853e36f9491SFilipe Manana 	 * matches the current fs generation (it's a transaction with a state
854e36f9491SFilipe Manana 	 * less than TRANS_STATE_UNBLOCKED). If it doesn't, then turn the fs
855e36f9491SFilipe Manana 	 * into error state to prevent the commit of any transaction.
856e36f9491SFilipe Manana 	 */
857e36f9491SFilipe Manana 	if (unlikely(trans->transaction != fs_info->running_transaction ||
858e36f9491SFilipe Manana 		     trans->transid != fs_info->generation)) {
859e36f9491SFilipe Manana 		btrfs_abort_transaction(trans, -EUCLEAN);
860e36f9491SFilipe Manana 		btrfs_crit(fs_info,
861e36f9491SFilipe Manana "unexpected transaction when attempting to reallocate parent %llu for root %llu, transaction %llu running transaction %llu fs generation %llu",
862e36f9491SFilipe Manana 			   parent->start, btrfs_root_id(root), trans->transid,
863e36f9491SFilipe Manana 			   fs_info->running_transaction->transid,
864e36f9491SFilipe Manana 			   fs_info->generation);
865e36f9491SFilipe Manana 		return -EUCLEAN;
866e36f9491SFilipe Manana 	}
86786479a04SChris Mason 
8686b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
8690b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
8705dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
8716702ed49SChris Mason 
8725dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
8736702ed49SChris Mason 		return 0;
8746702ed49SChris Mason 
8755dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
8766702ed49SChris Mason 		int close = 1;
877a6b6e75eSChris Mason 
878081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
879081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
880081e9573SChris Mason 			continue;
881081e9573SChris Mason 
882081e9573SChris Mason 		progress_passed = 1;
8836b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
884e9d0b13bSChris Mason 		if (last_block == 0)
885e9d0b13bSChris Mason 			last_block = blocknr;
8865708b959SChris Mason 
8876702ed49SChris Mason 		if (i > 0) {
8886b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
8896b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
8906702ed49SChris Mason 		}
8915dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
8926b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
8936b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
8946702ed49SChris Mason 		}
895e9d0b13bSChris Mason 		if (close) {
896e9d0b13bSChris Mason 			last_block = blocknr;
8976702ed49SChris Mason 			continue;
898e9d0b13bSChris Mason 		}
8996702ed49SChris Mason 
900206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
901206983b7SJosef Bacik 		if (IS_ERR(cur))
90264c043deSLiu Bo 			return PTR_ERR(cur);
903e9d0b13bSChris Mason 		if (search_start == 0)
9046b80053dSChris Mason 			search_start = last_block;
905e9d0b13bSChris Mason 
906e7a84565SChris Mason 		btrfs_tree_lock(cur);
9076b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
908e7a84565SChris Mason 					&cur, search_start,
9096b80053dSChris Mason 					min(16 * blocksize,
9109631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
9119631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
912252c38f0SYan 		if (err) {
913e7a84565SChris Mason 			btrfs_tree_unlock(cur);
9146b80053dSChris Mason 			free_extent_buffer(cur);
9156702ed49SChris Mason 			break;
916252c38f0SYan 		}
917e7a84565SChris Mason 		search_start = cur->start;
918e7a84565SChris Mason 		last_block = cur->start;
919f2183bdeSChris Mason 		*last_ret = search_start;
920e7a84565SChris Mason 		btrfs_tree_unlock(cur);
921e7a84565SChris Mason 		free_extent_buffer(cur);
9226702ed49SChris Mason 	}
9236702ed49SChris Mason 	return err;
9246702ed49SChris Mason }
9256702ed49SChris Mason 
92674123bd7SChris Mason /*
927fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
9285f39d397SChris Mason  *
929a724f313SFilipe Manana  * The lower boundary for the search is specified by the slot number @first_slot.
930fdf8d595SAnand Jain  * Use a value of 0 to search over the whole extent buffer. Works for both
931fdf8d595SAnand Jain  * leaves and nodes.
93274123bd7SChris Mason  *
933fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
934fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
935fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
936fb81212cSFilipe Manana  *
937fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
938fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
93974123bd7SChris Mason  */
940fdf8d595SAnand Jain int btrfs_bin_search(struct extent_buffer *eb, int first_slot,
94167d5e289SMarcos Paulo de Souza 		     const struct btrfs_key *key, int *slot)
942be0e5c09SChris Mason {
943fb81212cSFilipe Manana 	unsigned long p;
944fb81212cSFilipe Manana 	int item_size;
945a724f313SFilipe Manana 	/*
946a724f313SFilipe Manana 	 * Use unsigned types for the low and high slots, so that we get a more
947a724f313SFilipe Manana 	 * efficient division in the search loop below.
948a724f313SFilipe Manana 	 */
949a724f313SFilipe Manana 	u32 low = first_slot;
950a724f313SFilipe Manana 	u32 high = btrfs_header_nritems(eb);
951be0e5c09SChris Mason 	int ret;
9525cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
953be0e5c09SChris Mason 
954a724f313SFilipe Manana 	if (unlikely(low > high)) {
9555e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
956a724f313SFilipe Manana 		 "%s: low (%u) > high (%u) eb %llu owner %llu level %d",
9575e24e9afSLiu Bo 			  __func__, low, high, eb->start,
9585e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
9595e24e9afSLiu Bo 		return -EINVAL;
9605e24e9afSLiu Bo 	}
9615e24e9afSLiu Bo 
962fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
963fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
964fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
965fb81212cSFilipe Manana 	} else {
966fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
967fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
968fb81212cSFilipe Manana 	}
969fb81212cSFilipe Manana 
970be0e5c09SChris Mason 	while (low < high) {
9715cd17f34SDavid Sterba 		unsigned long oip;
9725cd17f34SDavid Sterba 		unsigned long offset;
9735cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
9745cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
9755cd17f34SDavid Sterba 		int mid;
9765cd17f34SDavid Sterba 
977be0e5c09SChris Mason 		mid = (low + high) / 2;
9785f39d397SChris Mason 		offset = p + mid * item_size;
9795cd17f34SDavid Sterba 		oip = offset_in_page(offset);
9805f39d397SChris Mason 
9815cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
982884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
9835cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
984934d375bSChris Mason 
985884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
9865cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
9875cd17f34SDavid Sterba 		} else {
9885cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
9895f39d397SChris Mason 			tmp = &unaligned;
990479965d6SChris Mason 		}
991479965d6SChris Mason 
992be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
993be0e5c09SChris Mason 
994be0e5c09SChris Mason 		if (ret < 0)
995be0e5c09SChris Mason 			low = mid + 1;
996be0e5c09SChris Mason 		else if (ret > 0)
997be0e5c09SChris Mason 			high = mid;
998be0e5c09SChris Mason 		else {
999be0e5c09SChris Mason 			*slot = mid;
1000be0e5c09SChris Mason 			return 0;
1001be0e5c09SChris Mason 		}
1002be0e5c09SChris Mason 	}
1003be0e5c09SChris Mason 	*slot = low;
1004be0e5c09SChris Mason 	return 1;
1005be0e5c09SChris Mason }
1006be0e5c09SChris Mason 
1007f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
1008f0486c68SYan, Zheng {
1009f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1010f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1011f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
1012f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1013f0486c68SYan, Zheng }
1014f0486c68SYan, Zheng 
1015f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
1016f0486c68SYan, Zheng {
1017f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
1018f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
1019f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
1020f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
1021f0486c68SYan, Zheng }
1022f0486c68SYan, Zheng 
1023d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
1024d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
1025d352ac68SChris Mason  */
10264b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
10274b231ae4SDavid Sterba 					   int slot)
1028bb803951SChris Mason {
1029ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
1030789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1031416bc658SJosef Bacik 	struct extent_buffer *eb;
1032416bc658SJosef Bacik 
1033fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
1034fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
1035ca7a79adSChris Mason 
1036d4694728SJosef Bacik 	ASSERT(level);
1037ca7a79adSChris Mason 
1038789d6a3aSQu Wenruo 	check.level = level - 1;
1039789d6a3aSQu Wenruo 	check.transid = btrfs_node_ptr_generation(parent, slot);
1040789d6a3aSQu Wenruo 	check.owner_root = btrfs_header_owner(parent);
1041789d6a3aSQu Wenruo 	check.has_first_key = true;
1042789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(parent, &check.first_key, slot);
1043789d6a3aSQu Wenruo 
1044d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1045789d6a3aSQu Wenruo 			     &check);
10464eb150d6SQu Wenruo 	if (IS_ERR(eb))
10474eb150d6SQu Wenruo 		return eb;
10484eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
1049416bc658SJosef Bacik 		free_extent_buffer(eb);
10504eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
1051416bc658SJosef Bacik 	}
1052416bc658SJosef Bacik 
1053416bc658SJosef Bacik 	return eb;
1054bb803951SChris Mason }
1055bb803951SChris Mason 
1056d352ac68SChris Mason /*
1057d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
1058d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
1059d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
1060d352ac68SChris Mason  */
1061e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
106298ed5174SChris Mason 			 struct btrfs_root *root,
106398ed5174SChris Mason 			 struct btrfs_path *path, int level)
1064bb803951SChris Mason {
10650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10665f39d397SChris Mason 	struct extent_buffer *right = NULL;
10675f39d397SChris Mason 	struct extent_buffer *mid;
10685f39d397SChris Mason 	struct extent_buffer *left = NULL;
10695f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1070bb803951SChris Mason 	int ret = 0;
1071bb803951SChris Mason 	int wret;
1072bb803951SChris Mason 	int pslot;
1073bb803951SChris Mason 	int orig_slot = path->slots[level];
107479f95c82SChris Mason 	u64 orig_ptr;
1075bb803951SChris Mason 
107698e6b1ebSLiu Bo 	ASSERT(level > 0);
1077bb803951SChris Mason 
10785f39d397SChris Mason 	mid = path->nodes[level];
1079b4ce94deSChris Mason 
1080ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
10817bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
10827bb86316SChris Mason 
10831d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
108479f95c82SChris Mason 
1085a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
10865f39d397SChris Mason 		parent = path->nodes[level + 1];
1087bb803951SChris Mason 		pslot = path->slots[level + 1];
1088a05a9bb1SLi Zefan 	}
1089bb803951SChris Mason 
109040689478SChris Mason 	/*
109140689478SChris Mason 	 * deal with the case where there is only one pointer in the root
109240689478SChris Mason 	 * by promoting the node below to a root
109340689478SChris Mason 	 */
10945f39d397SChris Mason 	if (!parent) {
10955f39d397SChris Mason 		struct extent_buffer *child;
1096bb803951SChris Mason 
10975f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1098bb803951SChris Mason 			return 0;
1099bb803951SChris Mason 
1100bb803951SChris Mason 		/* promote the child to a root */
11014b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1102fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1103fb770ae4SLiu Bo 			ret = PTR_ERR(child);
1104daefe4d4SFilipe Manana 			goto out;
1105305a26afSMark Fasheh 		}
1106305a26afSMark Fasheh 
1107925baeddSChris Mason 		btrfs_tree_lock(child);
11089631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
11099631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
1110f0486c68SYan, Zheng 		if (ret) {
1111f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1112f0486c68SYan, Zheng 			free_extent_buffer(child);
1113daefe4d4SFilipe Manana 			goto out;
1114f0486c68SYan, Zheng 		}
11152f375ab9SYan 
1116406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
111739020d8aSFilipe Manana 		if (ret < 0) {
111839020d8aSFilipe Manana 			btrfs_tree_unlock(child);
111939020d8aSFilipe Manana 			free_extent_buffer(child);
112039020d8aSFilipe Manana 			btrfs_abort_transaction(trans, ret);
1121daefe4d4SFilipe Manana 			goto out;
112239020d8aSFilipe Manana 		}
1123240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1124925baeddSChris Mason 
11250b86a832SChris Mason 		add_root_to_dirty_list(root);
1126925baeddSChris Mason 		btrfs_tree_unlock(child);
1127b4ce94deSChris Mason 
1128925baeddSChris Mason 		path->locks[level] = 0;
1129bb803951SChris Mason 		path->nodes[level] = NULL;
1130190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, mid);
1131925baeddSChris Mason 		btrfs_tree_unlock(mid);
1132bb803951SChris Mason 		/* once for the path */
11335f39d397SChris Mason 		free_extent_buffer(mid);
1134f0486c68SYan, Zheng 
1135f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
1136*22d907bcSFilipe Manana 		ret = btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1137bb803951SChris Mason 		/* once for the root ptr */
11383083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1139*22d907bcSFilipe Manana 		if (ret < 0) {
1140*22d907bcSFilipe Manana 			btrfs_abort_transaction(trans, ret);
1141*22d907bcSFilipe Manana 			goto out;
1142*22d907bcSFilipe Manana 		}
1143f0486c68SYan, Zheng 		return 0;
1144bb803951SChris Mason 	}
11455f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
11460b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1147bb803951SChris Mason 		return 0;
1148bb803951SChris Mason 
11499cf14029SJosef Bacik 	if (pslot) {
11504b231ae4SDavid Sterba 		left = btrfs_read_node_slot(parent, pslot - 1);
11519cf14029SJosef Bacik 		if (IS_ERR(left)) {
11529cf14029SJosef Bacik 			ret = PTR_ERR(left);
1153fb770ae4SLiu Bo 			left = NULL;
1154daefe4d4SFilipe Manana 			goto out;
11559cf14029SJosef Bacik 		}
1156fb770ae4SLiu Bo 
1157bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
11585f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
11599631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
1160bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
116154aa1f4dSChris Mason 		if (wret) {
116254aa1f4dSChris Mason 			ret = wret;
1163daefe4d4SFilipe Manana 			goto out;
116454aa1f4dSChris Mason 		}
11652cc58cf2SChris Mason 	}
1166fb770ae4SLiu Bo 
11679cf14029SJosef Bacik 	if (pslot + 1 < btrfs_header_nritems(parent)) {
11684b231ae4SDavid Sterba 		right = btrfs_read_node_slot(parent, pslot + 1);
11699cf14029SJosef Bacik 		if (IS_ERR(right)) {
11709cf14029SJosef Bacik 			ret = PTR_ERR(right);
1171fb770ae4SLiu Bo 			right = NULL;
1172daefe4d4SFilipe Manana 			goto out;
11739cf14029SJosef Bacik 		}
1174fb770ae4SLiu Bo 
1175bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
11765f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
11779631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
1178bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
11792cc58cf2SChris Mason 		if (wret) {
11802cc58cf2SChris Mason 			ret = wret;
1181daefe4d4SFilipe Manana 			goto out;
11822cc58cf2SChris Mason 		}
11832cc58cf2SChris Mason 	}
11842cc58cf2SChris Mason 
11852cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
11865f39d397SChris Mason 	if (left) {
11875f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1188d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
118979f95c82SChris Mason 		if (wret < 0)
119079f95c82SChris Mason 			ret = wret;
1191bb803951SChris Mason 	}
119279f95c82SChris Mason 
119379f95c82SChris Mason 	/*
119479f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
119579f95c82SChris Mason 	 */
11965f39d397SChris Mason 	if (right) {
1197d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
119854aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
119979f95c82SChris Mason 			ret = wret;
12005f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
1201190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, right);
1202925baeddSChris Mason 			btrfs_tree_unlock(right);
1203751a2761SFilipe Manana 			ret = btrfs_del_ptr(trans, root, path, level + 1, pslot + 1);
1204751a2761SFilipe Manana 			if (ret < 0) {
1205751a2761SFilipe Manana 				free_extent_buffer_stale(right);
1206751a2761SFilipe Manana 				right = NULL;
1207751a2761SFilipe Manana 				goto out;
1208751a2761SFilipe Manana 			}
1209f0486c68SYan, Zheng 			root_sub_used(root, right->len);
1210*22d907bcSFilipe Manana 			ret = btrfs_free_tree_block(trans, btrfs_root_id(root), right,
12117a163608SFilipe Manana 					      0, 1);
12123083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1213f0486c68SYan, Zheng 			right = NULL;
1214*22d907bcSFilipe Manana 			if (ret < 0) {
1215*22d907bcSFilipe Manana 				btrfs_abort_transaction(trans, ret);
1216*22d907bcSFilipe Manana 				goto out;
1217*22d907bcSFilipe Manana 			}
1218bb803951SChris Mason 		} else {
12195f39d397SChris Mason 			struct btrfs_disk_key right_key;
12205f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1221f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
122233cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
122339020d8aSFilipe Manana 			if (ret < 0) {
122439020d8aSFilipe Manana 				btrfs_abort_transaction(trans, ret);
1225daefe4d4SFilipe Manana 				goto out;
122639020d8aSFilipe Manana 			}
12275f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
1228d5e09e38SFilipe Manana 			btrfs_mark_buffer_dirty(trans, parent);
1229bb803951SChris Mason 		}
1230bb803951SChris Mason 	}
12315f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
123279f95c82SChris Mason 		/*
123379f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
123479f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
123579f95c82SChris Mason 		 * could try to delete the only pointer in this node.
123679f95c82SChris Mason 		 * So, pull some keys from the left.
123779f95c82SChris Mason 		 * There has to be a left pointer at this point because
123879f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
123979f95c82SChris Mason 		 * right
124079f95c82SChris Mason 		 */
1241725026edSFilipe Manana 		if (unlikely(!left)) {
1242725026edSFilipe Manana 			btrfs_crit(fs_info,
1243725026edSFilipe Manana "missing left child when middle child only has 1 item, parent bytenr %llu level %d mid bytenr %llu root %llu",
1244725026edSFilipe Manana 				   parent->start, btrfs_header_level(parent),
1245725026edSFilipe Manana 				   mid->start, btrfs_root_id(root));
1246725026edSFilipe Manana 			ret = -EUCLEAN;
1247725026edSFilipe Manana 			btrfs_abort_transaction(trans, ret);
1248daefe4d4SFilipe Manana 			goto out;
1249305a26afSMark Fasheh 		}
125055d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
125154aa1f4dSChris Mason 		if (wret < 0) {
125279f95c82SChris Mason 			ret = wret;
1253daefe4d4SFilipe Manana 			goto out;
125454aa1f4dSChris Mason 		}
1255bce4eae9SChris Mason 		if (wret == 1) {
1256d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1257bce4eae9SChris Mason 			if (wret < 0)
1258bce4eae9SChris Mason 				ret = wret;
1259bce4eae9SChris Mason 		}
126079f95c82SChris Mason 		BUG_ON(wret == 1);
126179f95c82SChris Mason 	}
12625f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
1263190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, mid);
1264925baeddSChris Mason 		btrfs_tree_unlock(mid);
1265751a2761SFilipe Manana 		ret = btrfs_del_ptr(trans, root, path, level + 1, pslot);
1266751a2761SFilipe Manana 		if (ret < 0) {
1267751a2761SFilipe Manana 			free_extent_buffer_stale(mid);
1268751a2761SFilipe Manana 			mid = NULL;
1269751a2761SFilipe Manana 			goto out;
1270751a2761SFilipe Manana 		}
1271f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
1272*22d907bcSFilipe Manana 		ret = btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
12733083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1274f0486c68SYan, Zheng 		mid = NULL;
1275*22d907bcSFilipe Manana 		if (ret < 0) {
1276*22d907bcSFilipe Manana 			btrfs_abort_transaction(trans, ret);
1277*22d907bcSFilipe Manana 			goto out;
1278*22d907bcSFilipe Manana 		}
127979f95c82SChris Mason 	} else {
128079f95c82SChris Mason 		/* update the parent key to reflect our changes */
12815f39d397SChris Mason 		struct btrfs_disk_key mid_key;
12825f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1283f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
128433cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
128539020d8aSFilipe Manana 		if (ret < 0) {
128639020d8aSFilipe Manana 			btrfs_abort_transaction(trans, ret);
1287daefe4d4SFilipe Manana 			goto out;
128839020d8aSFilipe Manana 		}
12895f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
1290d5e09e38SFilipe Manana 		btrfs_mark_buffer_dirty(trans, parent);
129179f95c82SChris Mason 	}
1292bb803951SChris Mason 
129379f95c82SChris Mason 	/* update the path */
12945f39d397SChris Mason 	if (left) {
12955f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
129667439dadSDavid Sterba 			atomic_inc(&left->refs);
1297925baeddSChris Mason 			/* left was locked after cow */
12985f39d397SChris Mason 			path->nodes[level] = left;
1299bb803951SChris Mason 			path->slots[level + 1] -= 1;
1300bb803951SChris Mason 			path->slots[level] = orig_slot;
1301925baeddSChris Mason 			if (mid) {
1302925baeddSChris Mason 				btrfs_tree_unlock(mid);
13035f39d397SChris Mason 				free_extent_buffer(mid);
1304925baeddSChris Mason 			}
1305bb803951SChris Mason 		} else {
13065f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1307bb803951SChris Mason 			path->slots[level] = orig_slot;
1308bb803951SChris Mason 		}
1309bb803951SChris Mason 	}
131079f95c82SChris Mason 	/* double check we haven't messed things up */
1311e20d96d6SChris Mason 	if (orig_ptr !=
13125f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
131379f95c82SChris Mason 		BUG();
1314daefe4d4SFilipe Manana out:
1315925baeddSChris Mason 	if (right) {
1316925baeddSChris Mason 		btrfs_tree_unlock(right);
13175f39d397SChris Mason 		free_extent_buffer(right);
1318925baeddSChris Mason 	}
1319925baeddSChris Mason 	if (left) {
1320925baeddSChris Mason 		if (path->nodes[level] != left)
1321925baeddSChris Mason 			btrfs_tree_unlock(left);
13225f39d397SChris Mason 		free_extent_buffer(left);
1323925baeddSChris Mason 	}
1324bb803951SChris Mason 	return ret;
1325bb803951SChris Mason }
1326bb803951SChris Mason 
1327d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1328d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1329d352ac68SChris Mason  * have to be pessimistic.
1330d352ac68SChris Mason  */
1331d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1332e66f709bSChris Mason 					  struct btrfs_root *root,
1333e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1334e66f709bSChris Mason {
13350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13365f39d397SChris Mason 	struct extent_buffer *right = NULL;
13375f39d397SChris Mason 	struct extent_buffer *mid;
13385f39d397SChris Mason 	struct extent_buffer *left = NULL;
13395f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1340e66f709bSChris Mason 	int ret = 0;
1341e66f709bSChris Mason 	int wret;
1342e66f709bSChris Mason 	int pslot;
1343e66f709bSChris Mason 	int orig_slot = path->slots[level];
1344e66f709bSChris Mason 
1345e66f709bSChris Mason 	if (level == 0)
1346e66f709bSChris Mason 		return 1;
1347e66f709bSChris Mason 
13485f39d397SChris Mason 	mid = path->nodes[level];
13497bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1350e66f709bSChris Mason 
1351a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
13525f39d397SChris Mason 		parent = path->nodes[level + 1];
1353e66f709bSChris Mason 		pslot = path->slots[level + 1];
1354a05a9bb1SLi Zefan 	}
1355e66f709bSChris Mason 
13565f39d397SChris Mason 	if (!parent)
1357e66f709bSChris Mason 		return 1;
1358e66f709bSChris Mason 
13599cf14029SJosef Bacik 	/* first, try to make some room in the middle buffer */
13609cf14029SJosef Bacik 	if (pslot) {
13619cf14029SJosef Bacik 		u32 left_nr;
13629cf14029SJosef Bacik 
13634b231ae4SDavid Sterba 		left = btrfs_read_node_slot(parent, pslot - 1);
1364fb770ae4SLiu Bo 		if (IS_ERR(left))
13659cf14029SJosef Bacik 			return PTR_ERR(left);
1366925baeddSChris Mason 
1367bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1368b4ce94deSChris Mason 
13695f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
13700b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
137133ade1f8SChris Mason 			wret = 1;
137233ade1f8SChris Mason 		} else {
13735f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
13749631e4ccSJosef Bacik 					      pslot - 1, &left,
1375bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
137654aa1f4dSChris Mason 			if (ret)
137754aa1f4dSChris Mason 				wret = 1;
137854aa1f4dSChris Mason 			else {
1379d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
138054aa1f4dSChris Mason 			}
138133ade1f8SChris Mason 		}
1382e66f709bSChris Mason 		if (wret < 0)
1383e66f709bSChris Mason 			ret = wret;
1384e66f709bSChris Mason 		if (wret == 0) {
13855f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1386e66f709bSChris Mason 			orig_slot += left_nr;
13875f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1388f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
138933cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
139011d6ae03SFilipe Manana 			if (ret < 0) {
139111d6ae03SFilipe Manana 				btrfs_tree_unlock(left);
139211d6ae03SFilipe Manana 				free_extent_buffer(left);
139311d6ae03SFilipe Manana 				btrfs_abort_transaction(trans, ret);
139411d6ae03SFilipe Manana 				return ret;
139511d6ae03SFilipe Manana 			}
13965f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
1397d5e09e38SFilipe Manana 			btrfs_mark_buffer_dirty(trans, parent);
13985f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
13995f39d397SChris Mason 				path->nodes[level] = left;
1400e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1401e66f709bSChris Mason 				path->slots[level] = orig_slot;
1402925baeddSChris Mason 				btrfs_tree_unlock(mid);
14035f39d397SChris Mason 				free_extent_buffer(mid);
1404e66f709bSChris Mason 			} else {
1405e66f709bSChris Mason 				orig_slot -=
14065f39d397SChris Mason 					btrfs_header_nritems(left);
1407e66f709bSChris Mason 				path->slots[level] = orig_slot;
1408925baeddSChris Mason 				btrfs_tree_unlock(left);
14095f39d397SChris Mason 				free_extent_buffer(left);
1410e66f709bSChris Mason 			}
1411e66f709bSChris Mason 			return 0;
1412e66f709bSChris Mason 		}
1413925baeddSChris Mason 		btrfs_tree_unlock(left);
14145f39d397SChris Mason 		free_extent_buffer(left);
1415e66f709bSChris Mason 	}
1416e66f709bSChris Mason 
1417e66f709bSChris Mason 	/*
1418e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1419e66f709bSChris Mason 	 */
14209cf14029SJosef Bacik 	if (pslot + 1 < btrfs_header_nritems(parent)) {
142133ade1f8SChris Mason 		u32 right_nr;
1422b4ce94deSChris Mason 
14239cf14029SJosef Bacik 		right = btrfs_read_node_slot(parent, pslot + 1);
14249cf14029SJosef Bacik 		if (IS_ERR(right))
14259cf14029SJosef Bacik 			return PTR_ERR(right);
14269cf14029SJosef Bacik 
1427bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1428b4ce94deSChris Mason 
14295f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
14300b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
143133ade1f8SChris Mason 			wret = 1;
143233ade1f8SChris Mason 		} else {
14335f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
14345f39d397SChris Mason 					      parent, pslot + 1,
1435bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
143654aa1f4dSChris Mason 			if (ret)
143754aa1f4dSChris Mason 				wret = 1;
143854aa1f4dSChris Mason 			else {
143955d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
144033ade1f8SChris Mason 			}
144154aa1f4dSChris Mason 		}
1442e66f709bSChris Mason 		if (wret < 0)
1443e66f709bSChris Mason 			ret = wret;
1444e66f709bSChris Mason 		if (wret == 0) {
14455f39d397SChris Mason 			struct btrfs_disk_key disk_key;
14465f39d397SChris Mason 
14475f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1448f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
144933cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
145011d6ae03SFilipe Manana 			if (ret < 0) {
145111d6ae03SFilipe Manana 				btrfs_tree_unlock(right);
145211d6ae03SFilipe Manana 				free_extent_buffer(right);
145311d6ae03SFilipe Manana 				btrfs_abort_transaction(trans, ret);
145411d6ae03SFilipe Manana 				return ret;
145511d6ae03SFilipe Manana 			}
14565f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
1457d5e09e38SFilipe Manana 			btrfs_mark_buffer_dirty(trans, parent);
14585f39d397SChris Mason 
14595f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
14605f39d397SChris Mason 				path->nodes[level] = right;
1461e66f709bSChris Mason 				path->slots[level + 1] += 1;
1462e66f709bSChris Mason 				path->slots[level] = orig_slot -
14635f39d397SChris Mason 					btrfs_header_nritems(mid);
1464925baeddSChris Mason 				btrfs_tree_unlock(mid);
14655f39d397SChris Mason 				free_extent_buffer(mid);
1466e66f709bSChris Mason 			} else {
1467925baeddSChris Mason 				btrfs_tree_unlock(right);
14685f39d397SChris Mason 				free_extent_buffer(right);
1469e66f709bSChris Mason 			}
1470e66f709bSChris Mason 			return 0;
1471e66f709bSChris Mason 		}
1472925baeddSChris Mason 		btrfs_tree_unlock(right);
14735f39d397SChris Mason 		free_extent_buffer(right);
1474e66f709bSChris Mason 	}
1475e66f709bSChris Mason 	return 1;
1476e66f709bSChris Mason }
1477e66f709bSChris Mason 
147874123bd7SChris Mason /*
1479d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1480d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
14813c69faecSChris Mason  */
14822ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1483e02119d5SChris Mason 			     struct btrfs_path *path,
148401f46658SChris Mason 			     int level, int slot, u64 objectid)
14853c69faecSChris Mason {
14865f39d397SChris Mason 	struct extent_buffer *node;
148701f46658SChris Mason 	struct btrfs_disk_key disk_key;
14883c69faecSChris Mason 	u32 nritems;
14893c69faecSChris Mason 	u64 search;
1490a7175319SChris Mason 	u64 target;
14916b80053dSChris Mason 	u64 nread = 0;
1492ace75066SFilipe Manana 	u64 nread_max;
14936b80053dSChris Mason 	u32 nr;
14946b80053dSChris Mason 	u32 blocksize;
14956b80053dSChris Mason 	u32 nscan = 0;
1496db94535dSChris Mason 
1497ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
14983c69faecSChris Mason 		return;
14993c69faecSChris Mason 
15006702ed49SChris Mason 	if (!path->nodes[level])
15016702ed49SChris Mason 		return;
15026702ed49SChris Mason 
15035f39d397SChris Mason 	node = path->nodes[level];
1504925baeddSChris Mason 
1505ace75066SFilipe Manana 	/*
1506ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1507ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1508ace75066SFilipe Manana 	 * much IO at once (possibly random).
1509ace75066SFilipe Manana 	 */
1510ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1511ace75066SFilipe Manana 		if (level > 1)
1512ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1513ace75066SFilipe Manana 		else
1514ace75066SFilipe Manana 			nread_max = SZ_128K;
1515ace75066SFilipe Manana 	} else {
1516ace75066SFilipe Manana 		nread_max = SZ_64K;
1517ace75066SFilipe Manana 	}
1518ace75066SFilipe Manana 
15193c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
15200b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1521069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1522069a2e37SFilipe Manana 		struct extent_buffer *eb;
1523069a2e37SFilipe Manana 
15240b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
15255f39d397SChris Mason 		if (eb) {
15265f39d397SChris Mason 			free_extent_buffer(eb);
15273c69faecSChris Mason 			return;
15283c69faecSChris Mason 		}
1529069a2e37SFilipe Manana 	}
15303c69faecSChris Mason 
1531a7175319SChris Mason 	target = search;
15326b80053dSChris Mason 
15335f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
15346b80053dSChris Mason 	nr = slot;
153525b8b936SJosef Bacik 
15363c69faecSChris Mason 	while (1) {
1537e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
15386b80053dSChris Mason 			if (nr == 0)
15393c69faecSChris Mason 				break;
15406b80053dSChris Mason 			nr--;
1541ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1542ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
15436b80053dSChris Mason 			nr++;
15446b80053dSChris Mason 			if (nr >= nritems)
15456b80053dSChris Mason 				break;
15463c69faecSChris Mason 		}
1547e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
154801f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
154901f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
155001f46658SChris Mason 				break;
155101f46658SChris Mason 		}
15526b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1553ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1554ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1555a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1556bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
15576b80053dSChris Mason 			nread += blocksize;
15583c69faecSChris Mason 		}
15596b80053dSChris Mason 		nscan++;
1560ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
15616b80053dSChris Mason 			break;
15623c69faecSChris Mason 	}
15633c69faecSChris Mason }
1564925baeddSChris Mason 
1565bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1566b4ce94deSChris Mason {
1567bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1568b4ce94deSChris Mason 	int slot;
1569b4ce94deSChris Mason 	int nritems;
1570b4ce94deSChris Mason 
15718c594ea8SChris Mason 	parent = path->nodes[level + 1];
1572b4ce94deSChris Mason 	if (!parent)
15730b08851fSJosef Bacik 		return;
1574b4ce94deSChris Mason 
1575b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
15768c594ea8SChris Mason 	slot = path->slots[level + 1];
1577b4ce94deSChris Mason 
1578bfb484d9SJosef Bacik 	if (slot > 0)
1579bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1580bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1581bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1582b4ce94deSChris Mason }
1583b4ce94deSChris Mason 
1584b4ce94deSChris Mason 
1585b4ce94deSChris Mason /*
1586d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1587d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1588d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1589d397712bSChris Mason  * tree.
1590d352ac68SChris Mason  *
1591d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1592d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1593d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1594d352ac68SChris Mason  *
1595d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1596d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1597d352ac68SChris Mason  */
1598e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1599f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1600f7c79f30SChris Mason 			       int *write_lock_level)
1601925baeddSChris Mason {
1602925baeddSChris Mason 	int i;
1603925baeddSChris Mason 	int skip_level = level;
1604c1227996SNikolay Borisov 	bool check_skip = true;
1605925baeddSChris Mason 
1606925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1607925baeddSChris Mason 		if (!path->nodes[i])
1608925baeddSChris Mason 			break;
1609925baeddSChris Mason 		if (!path->locks[i])
1610925baeddSChris Mason 			break;
1611c1227996SNikolay Borisov 
1612c1227996SNikolay Borisov 		if (check_skip) {
1613c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1614925baeddSChris Mason 				skip_level = i + 1;
1615925baeddSChris Mason 				continue;
1616925baeddSChris Mason 			}
1617c1227996SNikolay Borisov 
1618c1227996SNikolay Borisov 			if (path->keep_locks) {
1619925baeddSChris Mason 				u32 nritems;
1620c1227996SNikolay Borisov 
1621c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1622051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1623925baeddSChris Mason 					skip_level = i + 1;
1624925baeddSChris Mason 					continue;
1625925baeddSChris Mason 				}
1626925baeddSChris Mason 			}
1627c1227996SNikolay Borisov 		}
1628051e1b9fSChris Mason 
1629d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1630c1227996SNikolay Borisov 			check_skip = false;
1631c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1632925baeddSChris Mason 			path->locks[i] = 0;
1633f7c79f30SChris Mason 			if (write_lock_level &&
1634f7c79f30SChris Mason 			    i > min_write_lock_level &&
1635f7c79f30SChris Mason 			    i <= *write_lock_level) {
1636f7c79f30SChris Mason 				*write_lock_level = i - 1;
1637f7c79f30SChris Mason 			}
1638925baeddSChris Mason 		}
1639925baeddSChris Mason 	}
1640925baeddSChris Mason }
1641925baeddSChris Mason 
16423c69faecSChris Mason /*
1643376a21d7SFilipe Manana  * Helper function for btrfs_search_slot() and other functions that do a search
1644376a21d7SFilipe Manana  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1645376a21d7SFilipe Manana  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1646376a21d7SFilipe Manana  * its pages from disk.
1647c8c42864SChris Mason  *
1648376a21d7SFilipe Manana  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1649376a21d7SFilipe Manana  * whole btree search, starting again from the current root node.
1650c8c42864SChris Mason  */
1651c8c42864SChris Mason static int
1652d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1653c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1654cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1655c8c42864SChris Mason {
16560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1657789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1658c8c42864SChris Mason 	u64 blocknr;
1659c8c42864SChris Mason 	u64 gen;
1660c8c42864SChris Mason 	struct extent_buffer *tmp;
166176a05b35SChris Mason 	int ret;
1662581c1760SQu Wenruo 	int parent_level;
1663b246666eSFilipe Manana 	bool unlock_up;
1664c8c42864SChris Mason 
1665b246666eSFilipe Manana 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1666213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1667213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1668213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1669789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(*eb_ret, &check.first_key, slot);
1670789d6a3aSQu Wenruo 	check.has_first_key = true;
1671789d6a3aSQu Wenruo 	check.level = parent_level - 1;
1672789d6a3aSQu Wenruo 	check.transid = gen;
1673789d6a3aSQu Wenruo 	check.owner_root = root->root_key.objectid;
1674c8c42864SChris Mason 
1675b246666eSFilipe Manana 	/*
1676b246666eSFilipe Manana 	 * If we need to read an extent buffer from disk and we are holding locks
1677b246666eSFilipe Manana 	 * on upper level nodes, we unlock all the upper nodes before reading the
1678b246666eSFilipe Manana 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1679b246666eSFilipe Manana 	 * restart the search. We don't release the lock on the current level
1680b246666eSFilipe Manana 	 * because we need to walk this node to figure out which blocks to read.
1681b246666eSFilipe Manana 	 */
16820b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1683cb44921aSChris Mason 	if (tmp) {
1684ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1685ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1686ace75066SFilipe Manana 
1687b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1688b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1689448de471SQu Wenruo 			/*
1690448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1691448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1692448de471SQu Wenruo 			 * parents (shared tree blocks).
1693448de471SQu Wenruo 			 */
1694e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1695789d6a3aSQu Wenruo 					parent_level - 1, &check.first_key, gen)) {
1696448de471SQu Wenruo 				free_extent_buffer(tmp);
1697448de471SQu Wenruo 				return -EUCLEAN;
1698448de471SQu Wenruo 			}
1699c8c42864SChris Mason 			*eb_ret = tmp;
1700c8c42864SChris Mason 			return 0;
1701c8c42864SChris Mason 		}
1702bdf7c00eSJosef Bacik 
1703857bc13fSJosef Bacik 		if (p->nowait) {
1704857bc13fSJosef Bacik 			free_extent_buffer(tmp);
1705857bc13fSJosef Bacik 			return -EAGAIN;
1706857bc13fSJosef Bacik 		}
1707857bc13fSJosef Bacik 
1708b246666eSFilipe Manana 		if (unlock_up)
1709b246666eSFilipe Manana 			btrfs_unlock_up_safe(p, level + 1);
1710b246666eSFilipe Manana 
1711b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
1712789d6a3aSQu Wenruo 		ret = btrfs_read_extent_buffer(tmp, &check);
17139a4ffa1bSQu Wenruo 		if (ret) {
1714cb44921aSChris Mason 			free_extent_buffer(tmp);
1715b3b4aa74SDavid Sterba 			btrfs_release_path(p);
1716cb44921aSChris Mason 			return -EIO;
1717cb44921aSChris Mason 		}
171888c602abSQu Wenruo 		if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
171988c602abSQu Wenruo 			free_extent_buffer(tmp);
172088c602abSQu Wenruo 			btrfs_release_path(p);
172188c602abSQu Wenruo 			return -EUCLEAN;
172288c602abSQu Wenruo 		}
1723b246666eSFilipe Manana 
1724b246666eSFilipe Manana 		if (unlock_up)
1725b246666eSFilipe Manana 			ret = -EAGAIN;
1726b246666eSFilipe Manana 
1727b246666eSFilipe Manana 		goto out;
1728857bc13fSJosef Bacik 	} else if (p->nowait) {
1729857bc13fSJosef Bacik 		return -EAGAIN;
17309a4ffa1bSQu Wenruo 	}
1731c8c42864SChris Mason 
1732b246666eSFilipe Manana 	if (unlock_up) {
17338c594ea8SChris Mason 		btrfs_unlock_up_safe(p, level + 1);
17344bb59055SFilipe Manana 		ret = -EAGAIN;
17354bb59055SFilipe Manana 	} else {
17364bb59055SFilipe Manana 		ret = 0;
17374bb59055SFilipe Manana 	}
17388c594ea8SChris Mason 
1739e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
17402ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1741c8c42864SChris Mason 
1742789d6a3aSQu Wenruo 	tmp = read_tree_block(fs_info, blocknr, &check);
17434eb150d6SQu Wenruo 	if (IS_ERR(tmp)) {
17444eb150d6SQu Wenruo 		btrfs_release_path(p);
17454eb150d6SQu Wenruo 		return PTR_ERR(tmp);
17464eb150d6SQu Wenruo 	}
174776a05b35SChris Mason 	/*
174876a05b35SChris Mason 	 * If the read above didn't mark this buffer up to date,
174976a05b35SChris Mason 	 * it will never end up being up to date.  Set ret to EIO now
175076a05b35SChris Mason 	 * and give up so that our caller doesn't loop forever
175176a05b35SChris Mason 	 * on our EAGAINs.
175276a05b35SChris Mason 	 */
1753e6a1d6fdSLiu Bo 	if (!extent_buffer_uptodate(tmp))
175476a05b35SChris Mason 		ret = -EIO;
175502a3307aSLiu Bo 
1756b246666eSFilipe Manana out:
17574bb59055SFilipe Manana 	if (ret == 0) {
17584bb59055SFilipe Manana 		*eb_ret = tmp;
17594bb59055SFilipe Manana 	} else {
17604bb59055SFilipe Manana 		free_extent_buffer(tmp);
176102a3307aSLiu Bo 		btrfs_release_path(p);
17624bb59055SFilipe Manana 	}
17634bb59055SFilipe Manana 
176476a05b35SChris Mason 	return ret;
1765c8c42864SChris Mason }
1766c8c42864SChris Mason 
1767c8c42864SChris Mason /*
1768c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1769c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1770c8c42864SChris Mason  * the ins_len.
1771c8c42864SChris Mason  *
1772c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1773c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1774c8c42864SChris Mason  * start over
1775c8c42864SChris Mason  */
1776c8c42864SChris Mason static int
1777c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1778c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1779bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1780bd681513SChris Mason 		       int *write_lock_level)
1781c8c42864SChris Mason {
17820b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
178395b982deSNikolay Borisov 	int ret = 0;
17840b246afaSJeff Mahoney 
1785c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
17860b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1787c8c42864SChris Mason 
1788bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1789bd681513SChris Mason 			*write_lock_level = level + 1;
1790bd681513SChris Mason 			btrfs_release_path(p);
179195b982deSNikolay Borisov 			return -EAGAIN;
1792bd681513SChris Mason 		}
1793bd681513SChris Mason 
1794bfb484d9SJosef Bacik 		reada_for_balance(p, level);
179595b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1796c8c42864SChris Mason 
1797c8c42864SChris Mason 		b = p->nodes[level];
1798c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
17990b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1800c8c42864SChris Mason 
1801bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1802bd681513SChris Mason 			*write_lock_level = level + 1;
1803bd681513SChris Mason 			btrfs_release_path(p);
180495b982deSNikolay Borisov 			return -EAGAIN;
1805bd681513SChris Mason 		}
1806bd681513SChris Mason 
1807bfb484d9SJosef Bacik 		reada_for_balance(p, level);
180895b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
180995b982deSNikolay Borisov 		if (ret)
181095b982deSNikolay Borisov 			return ret;
1811c8c42864SChris Mason 
1812c8c42864SChris Mason 		b = p->nodes[level];
1813c8c42864SChris Mason 		if (!b) {
1814b3b4aa74SDavid Sterba 			btrfs_release_path(p);
181595b982deSNikolay Borisov 			return -EAGAIN;
1816c8c42864SChris Mason 		}
1817c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1818c8c42864SChris Mason 	}
1819c8c42864SChris Mason 	return ret;
1820c8c42864SChris Mason }
1821c8c42864SChris Mason 
1822381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1823e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1824e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1825e33d5c3dSKelley Nielsen {
1826e33d5c3dSKelley Nielsen 	int ret;
1827e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1828e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1829381cf658SDavid Sterba 
1830381cf658SDavid Sterba 	ASSERT(path);
18311d4c08e0SDavid Sterba 	ASSERT(found_key);
1832e33d5c3dSKelley Nielsen 
1833e33d5c3dSKelley Nielsen 	key.type = key_type;
1834e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1835e33d5c3dSKelley Nielsen 	key.offset = ioff;
1836e33d5c3dSKelley Nielsen 
1837e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
18381d4c08e0SDavid Sterba 	if (ret < 0)
1839e33d5c3dSKelley Nielsen 		return ret;
1840e33d5c3dSKelley Nielsen 
1841e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1842e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1843e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1844e33d5c3dSKelley Nielsen 		if (ret)
1845e33d5c3dSKelley Nielsen 			return ret;
1846e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1847e33d5c3dSKelley Nielsen 	}
1848e33d5c3dSKelley Nielsen 
1849e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1850e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1851e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1852e33d5c3dSKelley Nielsen 		return 1;
1853e33d5c3dSKelley Nielsen 
1854e33d5c3dSKelley Nielsen 	return 0;
1855e33d5c3dSKelley Nielsen }
1856e33d5c3dSKelley Nielsen 
18571fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
18581fc28d8eSLiu Bo 							struct btrfs_path *p,
18591fc28d8eSLiu Bo 							int write_lock_level)
18601fc28d8eSLiu Bo {
18611fc28d8eSLiu Bo 	struct extent_buffer *b;
1862120de408SJosef Bacik 	int root_lock = 0;
18631fc28d8eSLiu Bo 	int level = 0;
18641fc28d8eSLiu Bo 
18651fc28d8eSLiu Bo 	if (p->search_commit_root) {
18661fc28d8eSLiu Bo 		b = root->commit_root;
186767439dadSDavid Sterba 		atomic_inc(&b->refs);
18681fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1869f9ddfd05SLiu Bo 		/*
1870f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1871f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1872f9ddfd05SLiu Bo 		 */
1873f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
18741fc28d8eSLiu Bo 
18751fc28d8eSLiu Bo 		goto out;
18761fc28d8eSLiu Bo 	}
18771fc28d8eSLiu Bo 
18781fc28d8eSLiu Bo 	if (p->skip_locking) {
18791fc28d8eSLiu Bo 		b = btrfs_root_node(root);
18801fc28d8eSLiu Bo 		level = btrfs_header_level(b);
18811fc28d8eSLiu Bo 		goto out;
18821fc28d8eSLiu Bo 	}
18831fc28d8eSLiu Bo 
1884120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1885120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1886120de408SJosef Bacik 
18871fc28d8eSLiu Bo 	/*
1888662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1889662c653bSLiu Bo 	 * lock.
1890662c653bSLiu Bo 	 */
1891662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1892662c653bSLiu Bo 		/*
1893662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1894662c653bSLiu Bo 		 * have it read locked
18951fc28d8eSLiu Bo 		 */
1896857bc13fSJosef Bacik 		if (p->nowait) {
1897857bc13fSJosef Bacik 			b = btrfs_try_read_lock_root_node(root);
1898857bc13fSJosef Bacik 			if (IS_ERR(b))
1899857bc13fSJosef Bacik 				return b;
1900857bc13fSJosef Bacik 		} else {
19011bb96598SJosef Bacik 			b = btrfs_read_lock_root_node(root);
1902857bc13fSJosef Bacik 		}
19031fc28d8eSLiu Bo 		level = btrfs_header_level(b);
19041fc28d8eSLiu Bo 		if (level > write_lock_level)
19051fc28d8eSLiu Bo 			goto out;
19061fc28d8eSLiu Bo 
1907662c653bSLiu Bo 		/* Whoops, must trade for write lock */
19081fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
19091fc28d8eSLiu Bo 		free_extent_buffer(b);
1910662c653bSLiu Bo 	}
1911662c653bSLiu Bo 
19121fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
19131fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
19141fc28d8eSLiu Bo 
19151fc28d8eSLiu Bo 	/* The level might have changed, check again */
19161fc28d8eSLiu Bo 	level = btrfs_header_level(b);
19171fc28d8eSLiu Bo 
19181fc28d8eSLiu Bo out:
1919120de408SJosef Bacik 	/*
1920120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1921120de408SJosef Bacik 	 * longer valid, return an error in this case.
1922120de408SJosef Bacik 	 */
1923120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1924120de408SJosef Bacik 		if (root_lock)
1925120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1926120de408SJosef Bacik 		free_extent_buffer(b);
1927120de408SJosef Bacik 		return ERR_PTR(-EIO);
1928120de408SJosef Bacik 	}
1929120de408SJosef Bacik 
19301fc28d8eSLiu Bo 	p->nodes[level] = b;
19311fc28d8eSLiu Bo 	if (!p->skip_locking)
19321fc28d8eSLiu Bo 		p->locks[level] = root_lock;
19331fc28d8eSLiu Bo 	/*
19341fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
19351fc28d8eSLiu Bo 	 */
19361fc28d8eSLiu Bo 	return b;
19371fc28d8eSLiu Bo }
19381fc28d8eSLiu Bo 
1939d96b3424SFilipe Manana /*
1940d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1941d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1942d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1943d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1944d96b3424SFilipe Manana  * reallocated in the next transaction.
1945d96b3424SFilipe Manana  *
1946d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1947d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1948d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1949d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1950d96b3424SFilipe Manana  */
1951d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1952d96b3424SFilipe Manana {
1953d96b3424SFilipe Manana 	const int i = path->lowest_level;
1954d96b3424SFilipe Manana 	const int slot = path->slots[i];
1955d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1956d96b3424SFilipe Manana 	struct extent_buffer *clone;
1957d96b3424SFilipe Manana 
1958d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1959d96b3424SFilipe Manana 
1960d96b3424SFilipe Manana 	if (!lowest)
1961d96b3424SFilipe Manana 		return 0;
1962d96b3424SFilipe Manana 
1963d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1964d96b3424SFilipe Manana 
1965d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1966d96b3424SFilipe Manana 	if (!clone)
1967d96b3424SFilipe Manana 		return -ENOMEM;
1968d96b3424SFilipe Manana 
1969d96b3424SFilipe Manana 	btrfs_release_path(path);
1970d96b3424SFilipe Manana 	path->nodes[i] = clone;
1971d96b3424SFilipe Manana 	path->slots[i] = slot;
1972d96b3424SFilipe Manana 
1973d96b3424SFilipe Manana 	return 0;
1974d96b3424SFilipe Manana }
19751fc28d8eSLiu Bo 
1976e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1977e2e58d0fSFilipe Manana 				      int search_low_slot,
1978e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1979e2e58d0fSFilipe Manana 				      int prev_cmp,
1980e2e58d0fSFilipe Manana 				      int *slot)
1981e2e58d0fSFilipe Manana {
1982e2e58d0fSFilipe Manana 	/*
1983e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1984e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1985e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1986e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1987e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1988e2e58d0fSFilipe Manana 	 */
1989e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1990e2e58d0fSFilipe Manana 		*slot = 0;
1991e2e58d0fSFilipe Manana 		return 0;
1992e2e58d0fSFilipe Manana 	}
1993e2e58d0fSFilipe Manana 
1994fdf8d595SAnand Jain 	return btrfs_bin_search(eb, search_low_slot, key, slot);
1995e2e58d0fSFilipe Manana }
1996e2e58d0fSFilipe Manana 
1997109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1998109324cfSFilipe Manana 		       struct btrfs_root *root,
1999109324cfSFilipe Manana 		       const struct btrfs_key *key,
2000109324cfSFilipe Manana 		       struct btrfs_path *path,
2001109324cfSFilipe Manana 		       int ins_len,
2002109324cfSFilipe Manana 		       int prev_cmp)
2003109324cfSFilipe Manana {
2004109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
2005109324cfSFilipe Manana 	int leaf_free_space = -1;
2006109324cfSFilipe Manana 	int search_low_slot = 0;
2007109324cfSFilipe Manana 	int ret;
2008109324cfSFilipe Manana 	bool do_bin_search = true;
2009109324cfSFilipe Manana 
2010109324cfSFilipe Manana 	/*
2011109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
2012109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
2013109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
2014109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
2015109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
2016109324cfSFilipe Manana 	 */
2017109324cfSFilipe Manana 	if (ins_len > 0) {
2018109324cfSFilipe Manana 		/*
2019109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
2020109324cfSFilipe Manana 		 * will not change until then.
2021109324cfSFilipe Manana 		 */
2022109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
2023109324cfSFilipe Manana 
2024109324cfSFilipe Manana 		/*
2025109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
2026109324cfSFilipe Manana 		 * the root of the tree.
2027109324cfSFilipe Manana 		 */
2028109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
2029109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
2030109324cfSFilipe Manana 
2031109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
2032109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
2033109324cfSFilipe Manana 
2034109324cfSFilipe Manana 			/*
2035109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
2036109324cfSFilipe Manana 			 * taking into account that the first key is very likely
2037109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
2038109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
2039109324cfSFilipe Manana 			 * the header's level field.
2040109324cfSFilipe Manana 			 */
2041109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
2042109324cfSFilipe Manana 			if (ret < 0) {
2043109324cfSFilipe Manana 				/*
2044109324cfSFilipe Manana 				 * The first key is smaller than the key we want
2045109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
2046109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
2047109324cfSFilipe Manana 				 *
2048109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
2049109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
2050109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
2051109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
2052109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
2053109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
2054109324cfSFilipe Manana 				 */
2055109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
2056109324cfSFilipe Manana 				search_low_slot = 1;
2057109324cfSFilipe Manana 			} else {
2058109324cfSFilipe Manana 				/*
2059109324cfSFilipe Manana 				 * The first key is >= then the key we want to
2060109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
2061109324cfSFilipe Manana 				 * the target key will be at slot 0.
2062109324cfSFilipe Manana 				 *
2063109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
2064109324cfSFilipe Manana 				 * less than the first key, because we will need
2065109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
2066109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
2067109324cfSFilipe Manana 				 * If the key matches the first key, then we can
2068109324cfSFilipe Manana 				 * unlock all the upper nodes, using
2069109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
2070109324cfSFilipe Manana 				 * as stated above.
2071109324cfSFilipe Manana 				 */
2072109324cfSFilipe Manana 				if (ret == 0)
2073109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
2074109324cfSFilipe Manana 				/*
2075109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
2076109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
2077109324cfSFilipe Manana 				 * to adjust it.
2078109324cfSFilipe Manana 				 */
2079109324cfSFilipe Manana 				do_bin_search = false;
2080109324cfSFilipe Manana 				path->slots[0] = 0;
2081109324cfSFilipe Manana 			}
2082109324cfSFilipe Manana 		}
2083109324cfSFilipe Manana 	}
2084109324cfSFilipe Manana 
2085109324cfSFilipe Manana 	if (do_bin_search) {
2086109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
2087109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
2088109324cfSFilipe Manana 		if (ret < 0)
2089109324cfSFilipe Manana 			return ret;
2090109324cfSFilipe Manana 	}
2091109324cfSFilipe Manana 
2092109324cfSFilipe Manana 	if (ins_len > 0) {
2093109324cfSFilipe Manana 		/*
2094109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
2095109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
2096109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
2097109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
2098109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
2099109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
2100109324cfSFilipe Manana 		 * check will be correct.
2101109324cfSFilipe Manana 		 */
2102109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
2103109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
2104109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
2105109324cfSFilipe Manana 		}
2106109324cfSFilipe Manana 
2107109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
2108109324cfSFilipe Manana 
2109109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
2110109324cfSFilipe Manana 			int err;
2111109324cfSFilipe Manana 
2112109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
2113109324cfSFilipe Manana 					 (ret == 0));
2114bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
2115bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
2116bb8e9a60SFilipe Manana 				err = -EUCLEAN;
2117109324cfSFilipe Manana 			if (err)
2118109324cfSFilipe Manana 				ret = err;
2119109324cfSFilipe Manana 		}
2120109324cfSFilipe Manana 	}
2121109324cfSFilipe Manana 
2122109324cfSFilipe Manana 	return ret;
2123109324cfSFilipe Manana }
2124109324cfSFilipe Manana 
2125c8c42864SChris Mason /*
21264271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
21274271eceaSNikolay Borisov  * modifications to preserve tree invariants.
212874123bd7SChris Mason  *
21294271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
21304271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
21314271eceaSNikolay Borisov  * @root:	The root node of the tree
21324271eceaSNikolay Borisov  * @key:	The key we are looking for
21339a664971Sethanwu  * @ins_len:	Indicates purpose of search:
21349a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
21359a664971Sethanwu  *              <0  for deletions
21369a664971Sethanwu  *               0  for plain searches, not modifying the tree
21379a664971Sethanwu  *
21389a664971Sethanwu  *              (*) If size of item inserted doesn't include
21399a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
21409a664971Sethanwu  *              be set.
21414271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
21424271eceaSNikolay Borisov  *		when modifying the tree.
214397571fd0SChris Mason  *
21444271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
21454271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
21464271eceaSNikolay Borisov  *
21474271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
21484271eceaSNikolay Borisov  * of the path (level 0)
21494271eceaSNikolay Borisov  *
21504271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
21514271eceaSNikolay Borisov  * points to the slot where it should be inserted
21524271eceaSNikolay Borisov  *
21534271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
21544271eceaSNikolay Borisov  * is returned
215574123bd7SChris Mason  */
2156310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2157310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2158310712b2SOmar Sandoval 		      int ins_len, int cow)
2159be0e5c09SChris Mason {
2160d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
21615f39d397SChris Mason 	struct extent_buffer *b;
2162be0e5c09SChris Mason 	int slot;
2163be0e5c09SChris Mason 	int ret;
216433c66f43SYan Zheng 	int err;
2165be0e5c09SChris Mason 	int level;
2166925baeddSChris Mason 	int lowest_unlock = 1;
2167bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2168bd681513SChris Mason 	int write_lock_level = 0;
21699f3a7427SChris Mason 	u8 lowest_level = 0;
2170f7c79f30SChris Mason 	int min_write_lock_level;
2171d7396f07SFilipe David Borba Manana 	int prev_cmp;
21729f3a7427SChris Mason 
2173a4c853afSChenXiaoSong 	might_sleep();
2174a4c853afSChenXiaoSong 
21756702ed49SChris Mason 	lowest_level = p->lowest_level;
2176323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
217722b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2178eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
217925179201SJosef Bacik 
2180857bc13fSJosef Bacik 	/*
2181857bc13fSJosef Bacik 	 * For now only allow nowait for read only operations.  There's no
2182857bc13fSJosef Bacik 	 * strict reason why we can't, we just only need it for reads so it's
2183857bc13fSJosef Bacik 	 * only implemented for reads.
2184857bc13fSJosef Bacik 	 */
2185857bc13fSJosef Bacik 	ASSERT(!p->nowait || !cow);
2186857bc13fSJosef Bacik 
2187bd681513SChris Mason 	if (ins_len < 0) {
2188925baeddSChris Mason 		lowest_unlock = 2;
218965b51a00SChris Mason 
2190bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2191bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2192bd681513SChris Mason 		 * for those levels as well
2193bd681513SChris Mason 		 */
2194bd681513SChris Mason 		write_lock_level = 2;
2195bd681513SChris Mason 	} else if (ins_len > 0) {
2196bd681513SChris Mason 		/*
2197bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2198bd681513SChris Mason 		 * level 1 so we can update keys
2199bd681513SChris Mason 		 */
2200bd681513SChris Mason 		write_lock_level = 1;
2201bd681513SChris Mason 	}
2202bd681513SChris Mason 
2203bd681513SChris Mason 	if (!cow)
2204bd681513SChris Mason 		write_lock_level = -1;
2205bd681513SChris Mason 
220609a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2207bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2208bd681513SChris Mason 
2209f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2210f7c79f30SChris Mason 
2211d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2212d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
2213857bc13fSJosef Bacik 		if (p->nowait) {
2214857bc13fSJosef Bacik 			if (!down_read_trylock(&fs_info->commit_root_sem))
2215857bc13fSJosef Bacik 				return -EAGAIN;
2216857bc13fSJosef Bacik 		} else {
2217d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
2218d96b3424SFilipe Manana 		}
2219857bc13fSJosef Bacik 	}
2220d96b3424SFilipe Manana 
2221bb803951SChris Mason again:
2222d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
22231fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2224be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2225be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2226be6821f8SFilipe Manana 		goto done;
2227be6821f8SFilipe Manana 	}
2228925baeddSChris Mason 
2229eb60ceacSChris Mason 	while (b) {
2230f624d976SQu Wenruo 		int dec = 0;
2231f624d976SQu Wenruo 
22325f39d397SChris Mason 		level = btrfs_header_level(b);
223365b51a00SChris Mason 
223402217ed2SChris Mason 		if (cow) {
22359ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
22369ea2c7c9SNikolay Borisov 
2237c8c42864SChris Mason 			/*
2238c8c42864SChris Mason 			 * if we don't really need to cow this block
2239c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2240c8c42864SChris Mason 			 * so we test it here
2241c8c42864SChris Mason 			 */
22425963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
224365b51a00SChris Mason 				goto cow_done;
22445d4f98a2SYan Zheng 
2245bd681513SChris Mason 			/*
2246bd681513SChris Mason 			 * must have write locks on this node and the
2247bd681513SChris Mason 			 * parent
2248bd681513SChris Mason 			 */
22495124e00eSJosef Bacik 			if (level > write_lock_level ||
22505124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
22515124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
22525124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2253bd681513SChris Mason 				write_lock_level = level + 1;
2254bd681513SChris Mason 				btrfs_release_path(p);
2255bd681513SChris Mason 				goto again;
2256bd681513SChris Mason 			}
2257bd681513SChris Mason 
22589ea2c7c9SNikolay Borisov 			if (last_level)
22599ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
22609631e4ccSJosef Bacik 						      &b,
22619631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
22629ea2c7c9SNikolay Borisov 			else
226333c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2264e20d96d6SChris Mason 						      p->nodes[level + 1],
22659631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
22669631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
226733c66f43SYan Zheng 			if (err) {
226833c66f43SYan Zheng 				ret = err;
226965b51a00SChris Mason 				goto done;
227054aa1f4dSChris Mason 			}
227102217ed2SChris Mason 		}
227265b51a00SChris Mason cow_done:
2273eb60ceacSChris Mason 		p->nodes[level] = b;
2274b4ce94deSChris Mason 
2275b4ce94deSChris Mason 		/*
2276b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2277b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2278b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2279b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2280b4ce94deSChris Mason 		 *
2281eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2282eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2283eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2284eb653de1SFilipe David Borba Manana 		 * we're operating on.
2285b4ce94deSChris Mason 		 */
2286eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2287eb653de1SFilipe David Borba Manana 			int u = level + 1;
2288eb653de1SFilipe David Borba Manana 
2289eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2290eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2291eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2292eb653de1SFilipe David Borba Manana 			}
2293eb653de1SFilipe David Borba Manana 		}
2294b4ce94deSChris Mason 
2295e2e58d0fSFilipe Manana 		if (level == 0) {
2296109324cfSFilipe Manana 			if (ins_len > 0)
2297e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
2298bd681513SChris Mason 
2299109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2300459931ecSChris Mason 			if (!p->search_for_split)
2301f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
23024b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
230365b51a00SChris Mason 			goto done;
230465b51a00SChris Mason 		}
2305e2e58d0fSFilipe Manana 
2306e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2307e2e58d0fSFilipe Manana 		if (ret < 0)
2308e2e58d0fSFilipe Manana 			goto done;
2309e2e58d0fSFilipe Manana 		prev_cmp = ret;
2310e2e58d0fSFilipe Manana 
2311f624d976SQu Wenruo 		if (ret && slot > 0) {
2312f624d976SQu Wenruo 			dec = 1;
2313f624d976SQu Wenruo 			slot--;
2314f624d976SQu Wenruo 		}
2315f624d976SQu Wenruo 		p->slots[level] = slot;
2316f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2317f624d976SQu Wenruo 					     &write_lock_level);
2318f624d976SQu Wenruo 		if (err == -EAGAIN)
2319f624d976SQu Wenruo 			goto again;
2320f624d976SQu Wenruo 		if (err) {
2321f624d976SQu Wenruo 			ret = err;
2322f624d976SQu Wenruo 			goto done;
2323f624d976SQu Wenruo 		}
2324f624d976SQu Wenruo 		b = p->nodes[level];
2325f624d976SQu Wenruo 		slot = p->slots[level];
2326f624d976SQu Wenruo 
2327f624d976SQu Wenruo 		/*
2328f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2329f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2330f624d976SQu Wenruo 		 * the parent
2331f624d976SQu Wenruo 		 */
2332f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2333f624d976SQu Wenruo 			write_lock_level = level + 1;
2334f624d976SQu Wenruo 			btrfs_release_path(p);
2335f624d976SQu Wenruo 			goto again;
2336f624d976SQu Wenruo 		}
2337f624d976SQu Wenruo 
2338f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2339f624d976SQu Wenruo 			  &write_lock_level);
2340f624d976SQu Wenruo 
2341f624d976SQu Wenruo 		if (level == lowest_level) {
2342f624d976SQu Wenruo 			if (dec)
2343f624d976SQu Wenruo 				p->slots[level]++;
2344f624d976SQu Wenruo 			goto done;
2345f624d976SQu Wenruo 		}
2346f624d976SQu Wenruo 
2347f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2348f624d976SQu Wenruo 		if (err == -EAGAIN)
2349f624d976SQu Wenruo 			goto again;
2350f624d976SQu Wenruo 		if (err) {
2351f624d976SQu Wenruo 			ret = err;
2352f624d976SQu Wenruo 			goto done;
2353f624d976SQu Wenruo 		}
2354f624d976SQu Wenruo 
2355f624d976SQu Wenruo 		if (!p->skip_locking) {
2356f624d976SQu Wenruo 			level = btrfs_header_level(b);
2357b40130b2SJosef Bacik 
2358b40130b2SJosef Bacik 			btrfs_maybe_reset_lockdep_class(root, b);
2359b40130b2SJosef Bacik 
2360f624d976SQu Wenruo 			if (level <= write_lock_level) {
2361f624d976SQu Wenruo 				btrfs_tree_lock(b);
2362f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2363f624d976SQu Wenruo 			} else {
2364857bc13fSJosef Bacik 				if (p->nowait) {
2365857bc13fSJosef Bacik 					if (!btrfs_try_tree_read_lock(b)) {
2366857bc13fSJosef Bacik 						free_extent_buffer(b);
2367857bc13fSJosef Bacik 						ret = -EAGAIN;
2368857bc13fSJosef Bacik 						goto done;
2369857bc13fSJosef Bacik 					}
2370857bc13fSJosef Bacik 				} else {
2371fe596ca3SJosef Bacik 					btrfs_tree_read_lock(b);
2372857bc13fSJosef Bacik 				}
2373f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2374f624d976SQu Wenruo 			}
2375f624d976SQu Wenruo 			p->nodes[level] = b;
2376f624d976SQu Wenruo 		}
237765b51a00SChris Mason 	}
237865b51a00SChris Mason 	ret = 1;
237965b51a00SChris Mason done:
23805f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2381b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2382d96b3424SFilipe Manana 
2383d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2384d96b3424SFilipe Manana 		int ret2;
2385d96b3424SFilipe Manana 
2386d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2387d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2388d96b3424SFilipe Manana 		if (ret2)
2389d96b3424SFilipe Manana 			ret = ret2;
2390d96b3424SFilipe Manana 	}
2391d96b3424SFilipe Manana 
2392be0e5c09SChris Mason 	return ret;
2393be0e5c09SChris Mason }
2394f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2395be0e5c09SChris Mason 
239674123bd7SChris Mason /*
23975d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
23985d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
23995d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
24005d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
24015d9e75c4SJan Schmidt  *
24025d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
24035d9e75c4SJan Schmidt  *
24045d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
24055d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
24065d9e75c4SJan Schmidt  */
2407310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
24085d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
24095d9e75c4SJan Schmidt {
24100b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
24115d9e75c4SJan Schmidt 	struct extent_buffer *b;
24125d9e75c4SJan Schmidt 	int slot;
24135d9e75c4SJan Schmidt 	int ret;
24145d9e75c4SJan Schmidt 	int err;
24155d9e75c4SJan Schmidt 	int level;
24165d9e75c4SJan Schmidt 	int lowest_unlock = 1;
24175d9e75c4SJan Schmidt 	u8 lowest_level = 0;
24185d9e75c4SJan Schmidt 
24195d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
24205d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
2421c922b016SStefan Roesch 	ASSERT(!p->nowait);
24225d9e75c4SJan Schmidt 
24235d9e75c4SJan Schmidt 	if (p->search_commit_root) {
24245d9e75c4SJan Schmidt 		BUG_ON(time_seq);
24255d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
24265d9e75c4SJan Schmidt 	}
24275d9e75c4SJan Schmidt 
24285d9e75c4SJan Schmidt again:
2429f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2430315bed43SNikolay Borisov 	if (!b) {
2431315bed43SNikolay Borisov 		ret = -EIO;
2432315bed43SNikolay Borisov 		goto done;
2433315bed43SNikolay Borisov 	}
24345d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
24355d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
24365d9e75c4SJan Schmidt 
24375d9e75c4SJan Schmidt 	while (b) {
2438abe9339dSQu Wenruo 		int dec = 0;
2439abe9339dSQu Wenruo 
24405d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
24415d9e75c4SJan Schmidt 		p->nodes[level] = b;
24425d9e75c4SJan Schmidt 
24435d9e75c4SJan Schmidt 		/*
24445d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
24455d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
24465d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
24475d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
24485d9e75c4SJan Schmidt 		 */
24495d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
24505d9e75c4SJan Schmidt 
2451fdf8d595SAnand Jain 		ret = btrfs_bin_search(b, 0, key, &slot);
2452cbca7d59SFilipe Manana 		if (ret < 0)
2453cbca7d59SFilipe Manana 			goto done;
24545d9e75c4SJan Schmidt 
2455abe9339dSQu Wenruo 		if (level == 0) {
2456abe9339dSQu Wenruo 			p->slots[level] = slot;
2457abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2458abe9339dSQu Wenruo 			goto done;
2459abe9339dSQu Wenruo 		}
2460abe9339dSQu Wenruo 
24615d9e75c4SJan Schmidt 		if (ret && slot > 0) {
24625d9e75c4SJan Schmidt 			dec = 1;
2463abe9339dSQu Wenruo 			slot--;
24645d9e75c4SJan Schmidt 		}
24655d9e75c4SJan Schmidt 		p->slots[level] = slot;
24665d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
24675d9e75c4SJan Schmidt 
24685d9e75c4SJan Schmidt 		if (level == lowest_level) {
24695d9e75c4SJan Schmidt 			if (dec)
24705d9e75c4SJan Schmidt 				p->slots[level]++;
24715d9e75c4SJan Schmidt 			goto done;
24725d9e75c4SJan Schmidt 		}
24735d9e75c4SJan Schmidt 
2474abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
24755d9e75c4SJan Schmidt 		if (err == -EAGAIN)
24765d9e75c4SJan Schmidt 			goto again;
24775d9e75c4SJan Schmidt 		if (err) {
24785d9e75c4SJan Schmidt 			ret = err;
24795d9e75c4SJan Schmidt 			goto done;
24805d9e75c4SJan Schmidt 		}
24815d9e75c4SJan Schmidt 
24825d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
24835d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2484f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2485db7f3436SJosef Bacik 		if (!b) {
2486db7f3436SJosef Bacik 			ret = -ENOMEM;
2487db7f3436SJosef Bacik 			goto done;
2488db7f3436SJosef Bacik 		}
24895d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
24905d9e75c4SJan Schmidt 		p->nodes[level] = b;
24915d9e75c4SJan Schmidt 	}
24925d9e75c4SJan Schmidt 	ret = 1;
24935d9e75c4SJan Schmidt done:
24945d9e75c4SJan Schmidt 	if (ret < 0)
24955d9e75c4SJan Schmidt 		btrfs_release_path(p);
24965d9e75c4SJan Schmidt 
24975d9e75c4SJan Schmidt 	return ret;
24985d9e75c4SJan Schmidt }
24995d9e75c4SJan Schmidt 
25005d9e75c4SJan Schmidt /*
2501f469c8bdSFilipe Manana  * Search the tree again to find a leaf with smaller keys.
2502f469c8bdSFilipe Manana  * Returns 0 if it found something.
2503f469c8bdSFilipe Manana  * Returns 1 if there are no smaller keys.
2504f469c8bdSFilipe Manana  * Returns < 0 on error.
2505f469c8bdSFilipe Manana  *
2506f469c8bdSFilipe Manana  * This may release the path, and so you may lose any locks held at the
2507f469c8bdSFilipe Manana  * time you call it.
2508f469c8bdSFilipe Manana  */
2509f469c8bdSFilipe Manana static int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
2510f469c8bdSFilipe Manana {
2511f469c8bdSFilipe Manana 	struct btrfs_key key;
2512f469c8bdSFilipe Manana 	struct btrfs_key orig_key;
2513f469c8bdSFilipe Manana 	struct btrfs_disk_key found_key;
2514f469c8bdSFilipe Manana 	int ret;
2515f469c8bdSFilipe Manana 
2516f469c8bdSFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
2517f469c8bdSFilipe Manana 	orig_key = key;
2518f469c8bdSFilipe Manana 
2519f469c8bdSFilipe Manana 	if (key.offset > 0) {
2520f469c8bdSFilipe Manana 		key.offset--;
2521f469c8bdSFilipe Manana 	} else if (key.type > 0) {
2522f469c8bdSFilipe Manana 		key.type--;
2523f469c8bdSFilipe Manana 		key.offset = (u64)-1;
2524f469c8bdSFilipe Manana 	} else if (key.objectid > 0) {
2525f469c8bdSFilipe Manana 		key.objectid--;
2526f469c8bdSFilipe Manana 		key.type = (u8)-1;
2527f469c8bdSFilipe Manana 		key.offset = (u64)-1;
2528f469c8bdSFilipe Manana 	} else {
2529f469c8bdSFilipe Manana 		return 1;
2530f469c8bdSFilipe Manana 	}
2531f469c8bdSFilipe Manana 
2532f469c8bdSFilipe Manana 	btrfs_release_path(path);
2533f469c8bdSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2534f469c8bdSFilipe Manana 	if (ret <= 0)
2535f469c8bdSFilipe Manana 		return ret;
2536f469c8bdSFilipe Manana 
2537f469c8bdSFilipe Manana 	/*
2538f469c8bdSFilipe Manana 	 * Previous key not found. Even if we were at slot 0 of the leaf we had
2539f469c8bdSFilipe Manana 	 * before releasing the path and calling btrfs_search_slot(), we now may
2540f469c8bdSFilipe Manana 	 * be in a slot pointing to the same original key - this can happen if
2541f469c8bdSFilipe Manana 	 * after we released the path, one of more items were moved from a
2542f469c8bdSFilipe Manana 	 * sibling leaf into the front of the leaf we had due to an insertion
2543f469c8bdSFilipe Manana 	 * (see push_leaf_right()).
2544f469c8bdSFilipe Manana 	 * If we hit this case and our slot is > 0 and just decrement the slot
2545f469c8bdSFilipe Manana 	 * so that the caller does not process the same key again, which may or
2546f469c8bdSFilipe Manana 	 * may not break the caller, depending on its logic.
2547f469c8bdSFilipe Manana 	 */
2548f469c8bdSFilipe Manana 	if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
2549f469c8bdSFilipe Manana 		btrfs_item_key(path->nodes[0], &found_key, path->slots[0]);
2550f469c8bdSFilipe Manana 		ret = comp_keys(&found_key, &orig_key);
2551f469c8bdSFilipe Manana 		if (ret == 0) {
2552f469c8bdSFilipe Manana 			if (path->slots[0] > 0) {
2553f469c8bdSFilipe Manana 				path->slots[0]--;
2554f469c8bdSFilipe Manana 				return 0;
2555f469c8bdSFilipe Manana 			}
2556f469c8bdSFilipe Manana 			/*
2557f469c8bdSFilipe Manana 			 * At slot 0, same key as before, it means orig_key is
2558f469c8bdSFilipe Manana 			 * the lowest, leftmost, key in the tree. We're done.
2559f469c8bdSFilipe Manana 			 */
2560f469c8bdSFilipe Manana 			return 1;
2561f469c8bdSFilipe Manana 		}
2562f469c8bdSFilipe Manana 	}
2563f469c8bdSFilipe Manana 
2564f469c8bdSFilipe Manana 	btrfs_item_key(path->nodes[0], &found_key, 0);
2565f469c8bdSFilipe Manana 	ret = comp_keys(&found_key, &key);
2566f469c8bdSFilipe Manana 	/*
2567f469c8bdSFilipe Manana 	 * We might have had an item with the previous key in the tree right
2568f469c8bdSFilipe Manana 	 * before we released our path. And after we released our path, that
2569f469c8bdSFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
2570f469c8bdSFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
2571f469c8bdSFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
2572f469c8bdSFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
2573f469c8bdSFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
2574f469c8bdSFilipe Manana 	 * the previous key we computed above.
2575f469c8bdSFilipe Manana 	 */
2576f469c8bdSFilipe Manana 	if (ret <= 0)
2577f469c8bdSFilipe Manana 		return 0;
2578f469c8bdSFilipe Manana 	return 1;
2579f469c8bdSFilipe Manana }
2580f469c8bdSFilipe Manana 
2581f469c8bdSFilipe Manana /*
25822f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
25832f38b3e1SArne Jansen  * instead the next or previous item should be returned.
25842f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
25852f38b3e1SArne Jansen  * otherwise.
25862f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
25872f38b3e1SArne Jansen  * return the next lower instead.
25882f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
25892f38b3e1SArne Jansen  * return the next higher instead.
25902f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
25912f38b3e1SArne Jansen  * < 0 on error
25922f38b3e1SArne Jansen  */
25932f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2594310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2595310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2596310712b2SOmar Sandoval 			       int return_any)
25972f38b3e1SArne Jansen {
25982f38b3e1SArne Jansen 	int ret;
25992f38b3e1SArne Jansen 	struct extent_buffer *leaf;
26002f38b3e1SArne Jansen 
26012f38b3e1SArne Jansen again:
26022f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
26032f38b3e1SArne Jansen 	if (ret <= 0)
26042f38b3e1SArne Jansen 		return ret;
26052f38b3e1SArne Jansen 	/*
26062f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
26072f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
26082f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
26092f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
26102f38b3e1SArne Jansen 	 * item.
26112f38b3e1SArne Jansen 	 */
26122f38b3e1SArne Jansen 	leaf = p->nodes[0];
26132f38b3e1SArne Jansen 
26142f38b3e1SArne Jansen 	if (find_higher) {
26152f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
26162f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
26172f38b3e1SArne Jansen 			if (ret <= 0)
26182f38b3e1SArne Jansen 				return ret;
26192f38b3e1SArne Jansen 			if (!return_any)
26202f38b3e1SArne Jansen 				return 1;
26212f38b3e1SArne Jansen 			/*
26222f38b3e1SArne Jansen 			 * no higher item found, return the next
26232f38b3e1SArne Jansen 			 * lower instead
26242f38b3e1SArne Jansen 			 */
26252f38b3e1SArne Jansen 			return_any = 0;
26262f38b3e1SArne Jansen 			find_higher = 0;
26272f38b3e1SArne Jansen 			btrfs_release_path(p);
26282f38b3e1SArne Jansen 			goto again;
26292f38b3e1SArne Jansen 		}
26302f38b3e1SArne Jansen 	} else {
26312f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
26322f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2633e6793769SArne Jansen 			if (ret < 0)
26342f38b3e1SArne Jansen 				return ret;
2635e6793769SArne Jansen 			if (!ret) {
263623c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
263723c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
263823c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2639e6793769SArne Jansen 				return 0;
2640e6793769SArne Jansen 			}
26412f38b3e1SArne Jansen 			if (!return_any)
26422f38b3e1SArne Jansen 				return 1;
26432f38b3e1SArne Jansen 			/*
26442f38b3e1SArne Jansen 			 * no lower item found, return the next
26452f38b3e1SArne Jansen 			 * higher instead
26462f38b3e1SArne Jansen 			 */
26472f38b3e1SArne Jansen 			return_any = 0;
26482f38b3e1SArne Jansen 			find_higher = 1;
26492f38b3e1SArne Jansen 			btrfs_release_path(p);
26502f38b3e1SArne Jansen 			goto again;
2651e6793769SArne Jansen 		} else {
26522f38b3e1SArne Jansen 			--p->slots[0];
26532f38b3e1SArne Jansen 		}
26542f38b3e1SArne Jansen 	}
26552f38b3e1SArne Jansen 	return 0;
26562f38b3e1SArne Jansen }
26572f38b3e1SArne Jansen 
26582f38b3e1SArne Jansen /*
26590ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
26600ff40a91SMarcos Paulo de Souza  * was not found.
26610ff40a91SMarcos Paulo de Souza  *
26620ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
26630ff40a91SMarcos Paulo de Souza  */
26640ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
26650ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
26660ff40a91SMarcos Paulo de Souza {
26670ff40a91SMarcos Paulo de Souza 	int ret;
26680ff40a91SMarcos Paulo de Souza 
26690ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
26700ff40a91SMarcos Paulo de Souza 	if (ret > 0)
26710ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
26720ff40a91SMarcos Paulo de Souza 
26730ff40a91SMarcos Paulo de Souza 	if (ret == 0)
26740ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
26750ff40a91SMarcos Paulo de Souza 
26760ff40a91SMarcos Paulo de Souza 	return ret;
26770ff40a91SMarcos Paulo de Souza }
26780ff40a91SMarcos Paulo de Souza 
267943dd529aSDavid Sterba /*
268062142be3SGabriel Niebler  * Search for a valid slot for the given path.
268162142be3SGabriel Niebler  *
268262142be3SGabriel Niebler  * @root:	The root node of the tree.
268362142be3SGabriel Niebler  * @key:	Will contain a valid item if found.
268462142be3SGabriel Niebler  * @path:	The starting point to validate the slot.
268562142be3SGabriel Niebler  *
268662142be3SGabriel Niebler  * Return: 0  if the item is valid
268762142be3SGabriel Niebler  *         1  if not found
268862142be3SGabriel Niebler  *         <0 if error.
268962142be3SGabriel Niebler  */
269062142be3SGabriel Niebler int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
269162142be3SGabriel Niebler 			      struct btrfs_path *path)
269262142be3SGabriel Niebler {
2693524f14bbSFilipe Manana 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
269462142be3SGabriel Niebler 		int ret;
269562142be3SGabriel Niebler 
269662142be3SGabriel Niebler 		ret = btrfs_next_leaf(root, path);
269762142be3SGabriel Niebler 		if (ret)
269862142be3SGabriel Niebler 			return ret;
269962142be3SGabriel Niebler 	}
2700524f14bbSFilipe Manana 
2701524f14bbSFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
270262142be3SGabriel Niebler 	return 0;
270362142be3SGabriel Niebler }
270462142be3SGabriel Niebler 
27050ff40a91SMarcos Paulo de Souza /*
270674123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
270774123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
270874123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
270974123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
271074123bd7SChris Mason  * higher levels
2711aa5d6bedSChris Mason  *
271274123bd7SChris Mason  */
2713d5e09e38SFilipe Manana static void fixup_low_keys(struct btrfs_trans_handle *trans,
2714d5e09e38SFilipe Manana 			   struct btrfs_path *path,
27155f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2716be0e5c09SChris Mason {
2717be0e5c09SChris Mason 	int i;
27185f39d397SChris Mason 	struct extent_buffer *t;
27190e82bcfeSDavid Sterba 	int ret;
27205f39d397SChris Mason 
2721234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2722be0e5c09SChris Mason 		int tslot = path->slots[i];
27230e82bcfeSDavid Sterba 
2724eb60ceacSChris Mason 		if (!path->nodes[i])
2725be0e5c09SChris Mason 			break;
27265f39d397SChris Mason 		t = path->nodes[i];
2727f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
272833cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
27290e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
27305f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2731d5e09e38SFilipe Manana 		btrfs_mark_buffer_dirty(trans, path->nodes[i]);
2732be0e5c09SChris Mason 		if (tslot != 0)
2733be0e5c09SChris Mason 			break;
2734be0e5c09SChris Mason 	}
2735be0e5c09SChris Mason }
2736be0e5c09SChris Mason 
273774123bd7SChris Mason /*
273831840ae1SZheng Yan  * update item key.
273931840ae1SZheng Yan  *
274031840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
274131840ae1SZheng Yan  * that the new key won't break the order
274231840ae1SZheng Yan  */
2743d5e09e38SFilipe Manana void btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
2744b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2745310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
274631840ae1SZheng Yan {
2747d5e09e38SFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
274831840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
274931840ae1SZheng Yan 	struct extent_buffer *eb;
275031840ae1SZheng Yan 	int slot;
275131840ae1SZheng Yan 
275231840ae1SZheng Yan 	eb = path->nodes[0];
275331840ae1SZheng Yan 	slot = path->slots[0];
275431840ae1SZheng Yan 	if (slot > 0) {
275531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
27567c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
2757eee3b811SQu Wenruo 			btrfs_print_leaf(eb);
27587c15d410SQu Wenruo 			btrfs_crit(fs_info,
27597c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
27607c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
27617c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
27627c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
27637c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
27647c15d410SQu Wenruo 				   new_key->offset);
27657c15d410SQu Wenruo 			BUG();
27667c15d410SQu Wenruo 		}
276731840ae1SZheng Yan 	}
276831840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
276931840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
27707c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
2771eee3b811SQu Wenruo 			btrfs_print_leaf(eb);
27727c15d410SQu Wenruo 			btrfs_crit(fs_info,
27737c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
27747c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
27757c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
27767c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
27777c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
27787c15d410SQu Wenruo 				   new_key->offset);
27797c15d410SQu Wenruo 			BUG();
27807c15d410SQu Wenruo 		}
278131840ae1SZheng Yan 	}
278231840ae1SZheng Yan 
278331840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
278431840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
2785d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, eb);
278631840ae1SZheng Yan 	if (slot == 0)
2787d5e09e38SFilipe Manana 		fixup_low_keys(trans, path, &disk_key, 1);
278831840ae1SZheng Yan }
278931840ae1SZheng Yan 
279031840ae1SZheng Yan /*
2791d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2792d16c702fSQu Wenruo  *
2793d16c702fSQu Wenruo  * Return true if something is wrong.
2794d16c702fSQu Wenruo  * Return false if everything is fine.
2795d16c702fSQu Wenruo  *
2796d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2797d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2798d16c702fSQu Wenruo  *
2799d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2800d16c702fSQu Wenruo  * --------------------------------------------------------------
2801d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2802d16c702fSQu Wenruo  *
2803d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2804d16c702fSQu Wenruo  * key in leaf @right is 7.
2805d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2806d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2807d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2808d16c702fSQu Wenruo  * key of @right.
2809d16c702fSQu Wenruo  */
2810d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2811d16c702fSQu Wenruo 			       struct extent_buffer *right)
2812d16c702fSQu Wenruo {
2813d16c702fSQu Wenruo 	struct btrfs_key left_last;
2814d16c702fSQu Wenruo 	struct btrfs_key right_first;
2815d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2816d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2817d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2818d16c702fSQu Wenruo 
2819d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2820d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2821d16c702fSQu Wenruo 		return false;
2822d16c702fSQu Wenruo 
2823d16c702fSQu Wenruo 	if (level) {
2824d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2825d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2826d16c702fSQu Wenruo 	} else {
2827d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2828d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2829d16c702fSQu Wenruo 	}
2830d16c702fSQu Wenruo 
283188ad95b0SFilipe Manana 	if (unlikely(btrfs_comp_cpu_keys(&left_last, &right_first) >= 0)) {
2832a2cea677SFilipe Manana 		btrfs_crit(left->fs_info, "left extent buffer:");
2833a2cea677SFilipe Manana 		btrfs_print_tree(left, false);
2834a2cea677SFilipe Manana 		btrfs_crit(left->fs_info, "right extent buffer:");
2835a2cea677SFilipe Manana 		btrfs_print_tree(right, false);
2836d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2837d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2838d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2839d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2840d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2841d16c702fSQu Wenruo 		return true;
2842d16c702fSQu Wenruo 	}
2843d16c702fSQu Wenruo 	return false;
2844d16c702fSQu Wenruo }
2845d16c702fSQu Wenruo 
2846d16c702fSQu Wenruo /*
284774123bd7SChris Mason  * try to push data from one node into the next node left in the
284879f95c82SChris Mason  * tree.
2849aa5d6bedSChris Mason  *
2850aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2851aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
285274123bd7SChris Mason  */
285398ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
28542ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2855971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2856be0e5c09SChris Mason {
2857d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2858be0e5c09SChris Mason 	int push_items = 0;
2859bb803951SChris Mason 	int src_nritems;
2860bb803951SChris Mason 	int dst_nritems;
2861aa5d6bedSChris Mason 	int ret = 0;
2862be0e5c09SChris Mason 
28635f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28645f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
28650b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
28667bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28677bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
286854aa1f4dSChris Mason 
2869bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2870971a1f66SChris Mason 		return 1;
2871971a1f66SChris Mason 
2872d397712bSChris Mason 	if (push_items <= 0)
2873be0e5c09SChris Mason 		return 1;
2874be0e5c09SChris Mason 
2875bce4eae9SChris Mason 	if (empty) {
2876971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2877bce4eae9SChris Mason 		if (push_items < src_nritems) {
2878bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2879bce4eae9SChris Mason 			 * we aren't going to empty it
2880bce4eae9SChris Mason 			 */
2881bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2882bce4eae9SChris Mason 				if (push_items <= 8)
2883bce4eae9SChris Mason 					return 1;
2884bce4eae9SChris Mason 				push_items -= 8;
2885bce4eae9SChris Mason 			}
2886bce4eae9SChris Mason 		}
2887bce4eae9SChris Mason 	} else
2888bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
288979f95c82SChris Mason 
2890d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2891d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2892d16c702fSQu Wenruo 		ret = -EUCLEAN;
2893d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2894d16c702fSQu Wenruo 		return ret;
2895d16c702fSQu Wenruo 	}
2896f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
28975de865eeSFilipe David Borba Manana 	if (ret) {
289866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
28995de865eeSFilipe David Borba Manana 		return ret;
29005de865eeSFilipe David Borba Manana 	}
29015f39d397SChris Mason 	copy_extent_buffer(dst, src,
2902e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, dst_nritems),
2903e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, 0),
2904123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
29055f39d397SChris Mason 
2906bb803951SChris Mason 	if (push_items < src_nritems) {
290757911b8bSJan Schmidt 		/*
29085cead542SBoris Burkov 		 * btrfs_tree_mod_log_eb_copy handles logging the move, so we
29095cead542SBoris Burkov 		 * don't need to do an explicit tree mod log operation for it.
291057911b8bSJan Schmidt 		 */
2911e23efd8eSJosef Bacik 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(src, 0),
2912e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(src, push_items),
2913e2fa7227SChris Mason 				      (src_nritems - push_items) *
2914123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2915bb803951SChris Mason 	}
29165f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
29175f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
2918d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, src);
2919d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, dst);
292031840ae1SZheng Yan 
2921bb803951SChris Mason 	return ret;
2922be0e5c09SChris Mason }
2923be0e5c09SChris Mason 
292497571fd0SChris Mason /*
292579f95c82SChris Mason  * try to push data from one node into the next node right in the
292679f95c82SChris Mason  * tree.
292779f95c82SChris Mason  *
292879f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
292979f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
293079f95c82SChris Mason  *
293179f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
293279f95c82SChris Mason  */
29335f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
29345f39d397SChris Mason 			      struct extent_buffer *dst,
29355f39d397SChris Mason 			      struct extent_buffer *src)
293679f95c82SChris Mason {
293755d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
293879f95c82SChris Mason 	int push_items = 0;
293979f95c82SChris Mason 	int max_push;
294079f95c82SChris Mason 	int src_nritems;
294179f95c82SChris Mason 	int dst_nritems;
294279f95c82SChris Mason 	int ret = 0;
294379f95c82SChris Mason 
29447bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
29457bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
29467bb86316SChris Mason 
29475f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
29485f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
29490b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2950d397712bSChris Mason 	if (push_items <= 0)
295179f95c82SChris Mason 		return 1;
2952bce4eae9SChris Mason 
2953d397712bSChris Mason 	if (src_nritems < 4)
2954bce4eae9SChris Mason 		return 1;
295579f95c82SChris Mason 
295679f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
295779f95c82SChris Mason 	/* don't try to empty the node */
2958d397712bSChris Mason 	if (max_push >= src_nritems)
295979f95c82SChris Mason 		return 1;
2960252c38f0SYan 
296179f95c82SChris Mason 	if (max_push < push_items)
296279f95c82SChris Mason 		push_items = max_push;
296379f95c82SChris Mason 
2964d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2965d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2966d16c702fSQu Wenruo 		ret = -EUCLEAN;
2967d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2968d16c702fSQu Wenruo 		return ret;
2969d16c702fSQu Wenruo 	}
29705cead542SBoris Burkov 
29715cead542SBoris Burkov 	/*
29725cead542SBoris Burkov 	 * btrfs_tree_mod_log_eb_copy handles logging the move, so we don't
29735cead542SBoris Burkov 	 * need to do an explicit tree mod log operation for it.
29745cead542SBoris Burkov 	 */
2975e23efd8eSJosef Bacik 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(dst, push_items),
2976e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(dst, 0),
29775f39d397SChris Mason 				      (dst_nritems) *
29785f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2979d6025579SChris Mason 
2980f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2981ed874f0dSDavid Sterba 					 push_items);
29825de865eeSFilipe David Borba Manana 	if (ret) {
298366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
29845de865eeSFilipe David Borba Manana 		return ret;
29855de865eeSFilipe David Borba Manana 	}
29865f39d397SChris Mason 	copy_extent_buffer(dst, src,
2987e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, 0),
2988e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, src_nritems - push_items),
2989123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
299079f95c82SChris Mason 
29915f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
29925f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
299379f95c82SChris Mason 
2994d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, src);
2995d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, dst);
299631840ae1SZheng Yan 
299779f95c82SChris Mason 	return ret;
299879f95c82SChris Mason }
299979f95c82SChris Mason 
300079f95c82SChris Mason /*
300197571fd0SChris Mason  * helper function to insert a new root level in the tree.
300297571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
300397571fd0SChris Mason  * point to the existing root
3004aa5d6bedSChris Mason  *
3005aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
300697571fd0SChris Mason  */
3007d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
30085f39d397SChris Mason 			   struct btrfs_root *root,
3009fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
301074123bd7SChris Mason {
30110b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
30127bb86316SChris Mason 	u64 lower_gen;
30135f39d397SChris Mason 	struct extent_buffer *lower;
30145f39d397SChris Mason 	struct extent_buffer *c;
3015925baeddSChris Mason 	struct extent_buffer *old;
30165f39d397SChris Mason 	struct btrfs_disk_key lower_key;
3017d9d19a01SDavid Sterba 	int ret;
30185c680ed6SChris Mason 
30195c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
30205c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
30215c680ed6SChris Mason 
30227bb86316SChris Mason 	lower = path->nodes[level-1];
30237bb86316SChris Mason 	if (level == 1)
30247bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
30257bb86316SChris Mason 	else
30267bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
30277bb86316SChris Mason 
302879bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
302979bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
3030cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
30315f39d397SChris Mason 	if (IS_ERR(c))
30325f39d397SChris Mason 		return PTR_ERR(c);
3033925baeddSChris Mason 
30340b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3035f0486c68SYan, Zheng 
30365f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
30375f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
3038db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
30397bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
304031840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
30417bb86316SChris Mason 
30427bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
30435f39d397SChris Mason 
3044d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, c);
3045d5719762SChris Mason 
3046925baeddSChris Mason 	old = root->node;
3047406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
3048f61aa7baSFilipe Manana 	if (ret < 0) {
3049*22d907bcSFilipe Manana 		int ret2;
3050*22d907bcSFilipe Manana 
3051*22d907bcSFilipe Manana 		ret2 = btrfs_free_tree_block(trans, btrfs_root_id(root), c, 0, 1);
3052*22d907bcSFilipe Manana 		if (ret2 < 0)
3053*22d907bcSFilipe Manana 			btrfs_abort_transaction(trans, ret2);
3054f61aa7baSFilipe Manana 		btrfs_tree_unlock(c);
3055f61aa7baSFilipe Manana 		free_extent_buffer(c);
3056f61aa7baSFilipe Manana 		return ret;
3057f61aa7baSFilipe Manana 	}
3058240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
3059925baeddSChris Mason 
3060925baeddSChris Mason 	/* the super has an extra ref to root->node */
3061925baeddSChris Mason 	free_extent_buffer(old);
3062925baeddSChris Mason 
30630b86a832SChris Mason 	add_root_to_dirty_list(root);
306467439dadSDavid Sterba 	atomic_inc(&c->refs);
30655f39d397SChris Mason 	path->nodes[level] = c;
3066ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
306774123bd7SChris Mason 	path->slots[level] = 0;
306874123bd7SChris Mason 	return 0;
306974123bd7SChris Mason }
30705c680ed6SChris Mason 
30715c680ed6SChris Mason /*
30725c680ed6SChris Mason  * worker function to insert a single pointer in a node.
30735c680ed6SChris Mason  * the node should have enough room for the pointer already
307497571fd0SChris Mason  *
30755c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
30765c680ed6SChris Mason  * blocknr is the block the key points to.
30775c680ed6SChris Mason  */
307850b5d1fcSFilipe Manana static int insert_ptr(struct btrfs_trans_handle *trans,
30796ad3cf6dSDavid Sterba 		      struct btrfs_path *path,
3080143bede5SJeff Mahoney 		      struct btrfs_disk_key *key, u64 bytenr,
3081c3e06965SJan Schmidt 		      int slot, int level)
30825c680ed6SChris Mason {
30835f39d397SChris Mason 	struct extent_buffer *lower;
30845c680ed6SChris Mason 	int nritems;
3085f3ea38daSJan Schmidt 	int ret;
30865c680ed6SChris Mason 
30875c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
308849d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
30895f39d397SChris Mason 	lower = path->nodes[level];
30905f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
3091c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
30926ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
309374123bd7SChris Mason 	if (slot != nritems) {
3094bf1d3425SDavid Sterba 		if (level) {
3095f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
3096f3a84ccdSFilipe Manana 					slot, nritems - slot);
309750b5d1fcSFilipe Manana 			if (ret < 0) {
309850b5d1fcSFilipe Manana 				btrfs_abort_transaction(trans, ret);
309950b5d1fcSFilipe Manana 				return ret;
310050b5d1fcSFilipe Manana 			}
3101bf1d3425SDavid Sterba 		}
31025f39d397SChris Mason 		memmove_extent_buffer(lower,
3103e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot + 1),
3104e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot),
3105123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
310674123bd7SChris Mason 	}
3107c3e06965SJan Schmidt 	if (level) {
3108f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
310933cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_ADD);
311050b5d1fcSFilipe Manana 		if (ret < 0) {
311150b5d1fcSFilipe Manana 			btrfs_abort_transaction(trans, ret);
311250b5d1fcSFilipe Manana 			return ret;
311350b5d1fcSFilipe Manana 		}
3114f3ea38daSJan Schmidt 	}
31155f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3116db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
311774493f7aSChris Mason 	WARN_ON(trans->transid == 0);
311874493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
31195f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
3120d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, lower);
312150b5d1fcSFilipe Manana 
312250b5d1fcSFilipe Manana 	return 0;
312374123bd7SChris Mason }
312474123bd7SChris Mason 
312597571fd0SChris Mason /*
312697571fd0SChris Mason  * split the node at the specified level in path in two.
312797571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
312897571fd0SChris Mason  *
312997571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
313097571fd0SChris Mason  * left and right, if either one works, it returns right away.
3131aa5d6bedSChris Mason  *
3132aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
313397571fd0SChris Mason  */
3134e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3135e02119d5SChris Mason 			       struct btrfs_root *root,
3136e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3137be0e5c09SChris Mason {
31380b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
31395f39d397SChris Mason 	struct extent_buffer *c;
31405f39d397SChris Mason 	struct extent_buffer *split;
31415f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3142be0e5c09SChris Mason 	int mid;
31435c680ed6SChris Mason 	int ret;
31447518a238SChris Mason 	u32 c_nritems;
3145be0e5c09SChris Mason 
31465f39d397SChris Mason 	c = path->nodes[level];
31477bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
31485f39d397SChris Mason 	if (c == root->node) {
3149d9abbf1cSJan Schmidt 		/*
315090f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
315190f8d62eSJan Schmidt 		 *
3152fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
315390f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
315490f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
3155f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
3156f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
3157f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
3158d9abbf1cSJan Schmidt 		 */
3159fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
31605c680ed6SChris Mason 		if (ret)
31615c680ed6SChris Mason 			return ret;
3162b3612421SChris Mason 	} else {
3163e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
31645f39d397SChris Mason 		c = path->nodes[level];
31655f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
31660b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3167e66f709bSChris Mason 			return 0;
316854aa1f4dSChris Mason 		if (ret < 0)
316954aa1f4dSChris Mason 			return ret;
31705c680ed6SChris Mason 	}
3171e66f709bSChris Mason 
31725f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
31735d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
31745d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
31757bb86316SChris Mason 
317679bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
317779bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
317879bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
31795f39d397SChris Mason 	if (IS_ERR(split))
31805f39d397SChris Mason 		return PTR_ERR(split);
318154aa1f4dSChris Mason 
31820b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3183bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
31845f39d397SChris Mason 
3185f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
31865de865eeSFilipe David Borba Manana 	if (ret) {
3187ede600e4SFilipe Manana 		btrfs_tree_unlock(split);
3188ede600e4SFilipe Manana 		free_extent_buffer(split);
318966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
31905de865eeSFilipe David Borba Manana 		return ret;
31915de865eeSFilipe David Borba Manana 	}
31925f39d397SChris Mason 	copy_extent_buffer(split, c,
3193e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(split, 0),
3194e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(c, mid),
3195123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
31965f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
31975f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3198aa5d6bedSChris Mason 
3199d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, c);
3200d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, split);
32015f39d397SChris Mason 
320250b5d1fcSFilipe Manana 	ret = insert_ptr(trans, path, &disk_key, split->start,
3203c3e06965SJan Schmidt 			 path->slots[level + 1] + 1, level + 1);
320450b5d1fcSFilipe Manana 	if (ret < 0) {
320550b5d1fcSFilipe Manana 		btrfs_tree_unlock(split);
320650b5d1fcSFilipe Manana 		free_extent_buffer(split);
320750b5d1fcSFilipe Manana 		return ret;
320850b5d1fcSFilipe Manana 	}
3209aa5d6bedSChris Mason 
32105de08d7dSChris Mason 	if (path->slots[level] >= mid) {
32115c680ed6SChris Mason 		path->slots[level] -= mid;
3212925baeddSChris Mason 		btrfs_tree_unlock(c);
32135f39d397SChris Mason 		free_extent_buffer(c);
32145f39d397SChris Mason 		path->nodes[level] = split;
32155c680ed6SChris Mason 		path->slots[level + 1] += 1;
3216eb60ceacSChris Mason 	} else {
3217925baeddSChris Mason 		btrfs_tree_unlock(split);
32185f39d397SChris Mason 		free_extent_buffer(split);
3219be0e5c09SChris Mason 	}
3220d5286a92SNikolay Borisov 	return 0;
3221be0e5c09SChris Mason }
3222be0e5c09SChris Mason 
322374123bd7SChris Mason /*
322474123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
322574123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
322674123bd7SChris Mason  * space used both by the item structs and the item data
322774123bd7SChris Mason  */
32286c75a589SQu Wenruo static int leaf_space_used(const struct extent_buffer *l, int start, int nr)
3229be0e5c09SChris Mason {
3230be0e5c09SChris Mason 	int data_len;
32315f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3232d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3233be0e5c09SChris Mason 
3234be0e5c09SChris Mason 	if (!nr)
3235be0e5c09SChris Mason 		return 0;
32363212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
32373212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
32380783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3239d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3240be0e5c09SChris Mason 	return data_len;
3241be0e5c09SChris Mason }
3242be0e5c09SChris Mason 
324374123bd7SChris Mason /*
3244d4dbff95SChris Mason  * The space between the end of the leaf items and
3245d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3246d4dbff95SChris Mason  * the leaf has left for both items and data
3247d4dbff95SChris Mason  */
32486c75a589SQu Wenruo int btrfs_leaf_free_space(const struct extent_buffer *leaf)
3249d4dbff95SChris Mason {
3250e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
32515f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
32525f39d397SChris Mason 	int ret;
32530b246afaSJeff Mahoney 
32540b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
32555f39d397SChris Mason 	if (ret < 0) {
32560b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3257efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3258da17066cSJeff Mahoney 			   ret,
32590b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
32605f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
32615f39d397SChris Mason 	}
32625f39d397SChris Mason 	return ret;
3263d4dbff95SChris Mason }
3264d4dbff95SChris Mason 
326599d8f83cSChris Mason /*
326699d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
326799d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
326899d8f83cSChris Mason  */
3269ed25dab3SJosef Bacik static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
3270ed25dab3SJosef Bacik 				      struct btrfs_path *path,
327144871b1bSChris Mason 				      int data_size, int empty,
327244871b1bSChris Mason 				      struct extent_buffer *right,
327399d8f83cSChris Mason 				      int free_space, u32 left_nritems,
327499d8f83cSChris Mason 				      u32 min_slot)
327500ec4c51SChris Mason {
3276f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
32775f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
327844871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3279cfed81a0SChris Mason 	struct btrfs_map_token token;
32805f39d397SChris Mason 	struct btrfs_disk_key disk_key;
328100ec4c51SChris Mason 	int slot;
328234a38218SChris Mason 	u32 i;
328300ec4c51SChris Mason 	int push_space = 0;
328400ec4c51SChris Mason 	int push_items = 0;
328534a38218SChris Mason 	u32 nr;
32867518a238SChris Mason 	u32 right_nritems;
32875f39d397SChris Mason 	u32 data_end;
3288db94535dSChris Mason 	u32 this_item_size;
328900ec4c51SChris Mason 
329034a38218SChris Mason 	if (empty)
329134a38218SChris Mason 		nr = 0;
329234a38218SChris Mason 	else
329399d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
329434a38218SChris Mason 
329531840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
329687b29b20SYan Zheng 		push_space += data_size;
329731840ae1SZheng Yan 
329844871b1bSChris Mason 	slot = path->slots[1];
329934a38218SChris Mason 	i = left_nritems - 1;
330034a38218SChris Mason 	while (i >= nr) {
330131840ae1SZheng Yan 		if (!empty && push_items > 0) {
330231840ae1SZheng Yan 			if (path->slots[0] > i)
330331840ae1SZheng Yan 				break;
330431840ae1SZheng Yan 			if (path->slots[0] == i) {
3305e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3306e902baacSDavid Sterba 
330731840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
330831840ae1SZheng Yan 					break;
330931840ae1SZheng Yan 			}
331031840ae1SZheng Yan 		}
331131840ae1SZheng Yan 
331200ec4c51SChris Mason 		if (path->slots[0] == i)
331387b29b20SYan Zheng 			push_space += data_size;
3314db94535dSChris Mason 
33153212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
331674794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
331774794207SJosef Bacik 		    push_space > free_space)
331800ec4c51SChris Mason 			break;
331931840ae1SZheng Yan 
332000ec4c51SChris Mason 		push_items++;
332174794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
332234a38218SChris Mason 		if (i == 0)
332334a38218SChris Mason 			break;
332434a38218SChris Mason 		i--;
3325db94535dSChris Mason 	}
33265f39d397SChris Mason 
3327925baeddSChris Mason 	if (push_items == 0)
3328925baeddSChris Mason 		goto out_unlock;
33295f39d397SChris Mason 
33306c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
33315f39d397SChris Mason 
333200ec4c51SChris Mason 	/* push left to right */
33335f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
333434a38218SChris Mason 
3335dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
33368f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
33375f39d397SChris Mason 
333800ec4c51SChris Mason 	/* make room in the right data area */
33398f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
3340637e3b48SJosef Bacik 	memmove_leaf_data(right, data_end - push_space, data_end,
33410b246afaSJeff Mahoney 			  BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
33425f39d397SChris Mason 
334300ec4c51SChris Mason 	/* copy from the left data area */
3344637e3b48SJosef Bacik 	copy_leaf_data(right, left, BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3345637e3b48SJosef Bacik 		       leaf_data_end(left), push_space);
33465f39d397SChris Mason 
3347637e3b48SJosef Bacik 	memmove_leaf_items(right, push_items, 0, right_nritems);
33485f39d397SChris Mason 
334900ec4c51SChris Mason 	/* copy the items from left to right */
3350637e3b48SJosef Bacik 	copy_leaf_items(right, left, 0, left_nritems - push_items, push_items);
335100ec4c51SChris Mason 
335200ec4c51SChris Mason 	/* update the item pointers */
3353c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
33547518a238SChris Mason 	right_nritems += push_items;
33555f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
33560b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
33577518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
33583212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
33593212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3360db94535dSChris Mason 	}
3361db94535dSChris Mason 
33627518a238SChris Mason 	left_nritems -= push_items;
33635f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
336400ec4c51SChris Mason 
336534a38218SChris Mason 	if (left_nritems)
3366d5e09e38SFilipe Manana 		btrfs_mark_buffer_dirty(trans, left);
3367f0486c68SYan, Zheng 	else
3368190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, left);
3369f0486c68SYan, Zheng 
3370d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, right);
3371a429e513SChris Mason 
33725f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
33735f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3374d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, upper);
337502217ed2SChris Mason 
337600ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
33777518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
33787518a238SChris Mason 		path->slots[0] -= left_nritems;
3379925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3380190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, path->nodes[0]);
3381925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
33825f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
33835f39d397SChris Mason 		path->nodes[0] = right;
338400ec4c51SChris Mason 		path->slots[1] += 1;
338500ec4c51SChris Mason 	} else {
3386925baeddSChris Mason 		btrfs_tree_unlock(right);
33875f39d397SChris Mason 		free_extent_buffer(right);
338800ec4c51SChris Mason 	}
338900ec4c51SChris Mason 	return 0;
3390925baeddSChris Mason 
3391925baeddSChris Mason out_unlock:
3392925baeddSChris Mason 	btrfs_tree_unlock(right);
3393925baeddSChris Mason 	free_extent_buffer(right);
3394925baeddSChris Mason 	return 1;
339500ec4c51SChris Mason }
3396925baeddSChris Mason 
339700ec4c51SChris Mason /*
339844871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
339974123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
340044871b1bSChris Mason  *
340144871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
340244871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
340399d8f83cSChris Mason  *
340499d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
340599d8f83cSChris Mason  * push any slot lower than min_slot
340674123bd7SChris Mason  */
340744871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
340899d8f83cSChris Mason 			   *root, struct btrfs_path *path,
340999d8f83cSChris Mason 			   int min_data_size, int data_size,
341099d8f83cSChris Mason 			   int empty, u32 min_slot)
3411be0e5c09SChris Mason {
341244871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
341344871b1bSChris Mason 	struct extent_buffer *right;
341444871b1bSChris Mason 	struct extent_buffer *upper;
341544871b1bSChris Mason 	int slot;
341644871b1bSChris Mason 	int free_space;
341744871b1bSChris Mason 	u32 left_nritems;
341844871b1bSChris Mason 	int ret;
341944871b1bSChris Mason 
342044871b1bSChris Mason 	if (!path->nodes[1])
342144871b1bSChris Mason 		return 1;
342244871b1bSChris Mason 
342344871b1bSChris Mason 	slot = path->slots[1];
342444871b1bSChris Mason 	upper = path->nodes[1];
342544871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
342644871b1bSChris Mason 		return 1;
342744871b1bSChris Mason 
342849d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
342944871b1bSChris Mason 
34304b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3431fb770ae4SLiu Bo 	if (IS_ERR(right))
34329cf14029SJosef Bacik 		return PTR_ERR(right);
343391ca338dSTsutomu Itoh 
3434bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
343544871b1bSChris Mason 
3436e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
343744871b1bSChris Mason 	if (free_space < data_size)
343844871b1bSChris Mason 		goto out_unlock;
343944871b1bSChris Mason 
344044871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3441bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
344244871b1bSChris Mason 	if (ret)
344344871b1bSChris Mason 		goto out_unlock;
344444871b1bSChris Mason 
344544871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
344644871b1bSChris Mason 	if (left_nritems == 0)
344744871b1bSChris Mason 		goto out_unlock;
344844871b1bSChris Mason 
3449d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3450d16c702fSQu Wenruo 		ret = -EUCLEAN;
34519ae5afd0SFilipe Manana 		btrfs_abort_transaction(trans, ret);
3452d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3453d16c702fSQu Wenruo 		free_extent_buffer(right);
3454d16c702fSQu Wenruo 		return ret;
3455d16c702fSQu Wenruo 	}
34562ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
34572ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
34582ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
34592ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
346052042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
34612ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
34622ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
34632ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
34642ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
34652ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
34662ef1fed2SFilipe David Borba Manana 		return 0;
34672ef1fed2SFilipe David Borba Manana 	}
34682ef1fed2SFilipe David Borba Manana 
3469ed25dab3SJosef Bacik 	return __push_leaf_right(trans, path, min_data_size, empty, right,
3470ed25dab3SJosef Bacik 				 free_space, left_nritems, min_slot);
347144871b1bSChris Mason out_unlock:
347244871b1bSChris Mason 	btrfs_tree_unlock(right);
347344871b1bSChris Mason 	free_extent_buffer(right);
347444871b1bSChris Mason 	return 1;
347544871b1bSChris Mason }
347644871b1bSChris Mason 
347744871b1bSChris Mason /*
347844871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
347944871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
348099d8f83cSChris Mason  *
348199d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
348299d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
348399d8f83cSChris Mason  * items
348444871b1bSChris Mason  */
3485ed25dab3SJosef Bacik static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
3486ed25dab3SJosef Bacik 				     struct btrfs_path *path, int data_size,
348744871b1bSChris Mason 				     int empty, struct extent_buffer *left,
348899d8f83cSChris Mason 				     int free_space, u32 right_nritems,
348999d8f83cSChris Mason 				     u32 max_slot)
349044871b1bSChris Mason {
34918087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
34925f39d397SChris Mason 	struct btrfs_disk_key disk_key;
34935f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3494be0e5c09SChris Mason 	int i;
3495be0e5c09SChris Mason 	int push_space = 0;
3496be0e5c09SChris Mason 	int push_items = 0;
34977518a238SChris Mason 	u32 old_left_nritems;
349834a38218SChris Mason 	u32 nr;
3499aa5d6bedSChris Mason 	int ret = 0;
3500db94535dSChris Mason 	u32 this_item_size;
3501db94535dSChris Mason 	u32 old_left_item_size;
3502cfed81a0SChris Mason 	struct btrfs_map_token token;
3503cfed81a0SChris Mason 
350434a38218SChris Mason 	if (empty)
350599d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
350634a38218SChris Mason 	else
350799d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
350834a38218SChris Mason 
350934a38218SChris Mason 	for (i = 0; i < nr; i++) {
351031840ae1SZheng Yan 		if (!empty && push_items > 0) {
351131840ae1SZheng Yan 			if (path->slots[0] < i)
351231840ae1SZheng Yan 				break;
351331840ae1SZheng Yan 			if (path->slots[0] == i) {
3514e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3515e902baacSDavid Sterba 
351631840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
351731840ae1SZheng Yan 					break;
351831840ae1SZheng Yan 			}
351931840ae1SZheng Yan 		}
352031840ae1SZheng Yan 
3521be0e5c09SChris Mason 		if (path->slots[0] == i)
352287b29b20SYan Zheng 			push_space += data_size;
3523db94535dSChris Mason 
35243212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
352574794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
352674794207SJosef Bacik 		    free_space)
3527be0e5c09SChris Mason 			break;
3528db94535dSChris Mason 
3529be0e5c09SChris Mason 		push_items++;
353074794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3531be0e5c09SChris Mason 	}
3532db94535dSChris Mason 
3533be0e5c09SChris Mason 	if (push_items == 0) {
3534925baeddSChris Mason 		ret = 1;
3535925baeddSChris Mason 		goto out;
3536be0e5c09SChris Mason 	}
3537fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
35385f39d397SChris Mason 
3539be0e5c09SChris Mason 	/* push data from right to left */
3540637e3b48SJosef Bacik 	copy_leaf_items(left, right, btrfs_header_nritems(left), 0, push_items);
35415f39d397SChris Mason 
35420b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
35433212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
35445f39d397SChris Mason 
3545637e3b48SJosef Bacik 	copy_leaf_data(left, right, leaf_data_end(left) - push_space,
3546637e3b48SJosef Bacik 		       btrfs_item_offset(right, push_items - 1), push_space);
35475f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
354887b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3549eb60ceacSChris Mason 
3550c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
35513212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3552be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
35535f39d397SChris Mason 		u32 ioff;
3554db94535dSChris Mason 
35553212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
35563212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3557cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3558be0e5c09SChris Mason 	}
35595f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3560be0e5c09SChris Mason 
3561be0e5c09SChris Mason 	/* fixup right node */
356231b1a2bdSJulia Lawall 	if (push_items > right_nritems)
356331b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3564d397712bSChris Mason 		       right_nritems);
356534a38218SChris Mason 
356634a38218SChris Mason 	if (push_items < right_nritems) {
35673212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
35688f881e8cSDavid Sterba 						  leaf_data_end(right);
3569637e3b48SJosef Bacik 		memmove_leaf_data(right,
35700b246afaSJeff Mahoney 				  BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
35718f881e8cSDavid Sterba 				  leaf_data_end(right), push_space);
35725f39d397SChris Mason 
3573637e3b48SJosef Bacik 		memmove_leaf_items(right, 0, push_items,
3574637e3b48SJosef Bacik 				   btrfs_header_nritems(right) - push_items);
357534a38218SChris Mason 	}
3576c82f823cSDavid Sterba 
3577c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3578eef1c494SYan 	right_nritems -= push_items;
3579eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
35800b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
35815f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
35823212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
35833212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3584db94535dSChris Mason 	}
3585eb60ceacSChris Mason 
3586d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, left);
358734a38218SChris Mason 	if (right_nritems)
3588d5e09e38SFilipe Manana 		btrfs_mark_buffer_dirty(trans, right);
3589f0486c68SYan, Zheng 	else
3590190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, right);
3591098f59c2SChris Mason 
35925f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3593d5e09e38SFilipe Manana 	fixup_low_keys(trans, path, &disk_key, 1);
3594be0e5c09SChris Mason 
3595be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3596be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3597be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3598925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
35995f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
36005f39d397SChris Mason 		path->nodes[0] = left;
3601be0e5c09SChris Mason 		path->slots[1] -= 1;
3602be0e5c09SChris Mason 	} else {
3603925baeddSChris Mason 		btrfs_tree_unlock(left);
36045f39d397SChris Mason 		free_extent_buffer(left);
3605be0e5c09SChris Mason 		path->slots[0] -= push_items;
3606be0e5c09SChris Mason 	}
3607eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3608aa5d6bedSChris Mason 	return ret;
3609925baeddSChris Mason out:
3610925baeddSChris Mason 	btrfs_tree_unlock(left);
3611925baeddSChris Mason 	free_extent_buffer(left);
3612925baeddSChris Mason 	return ret;
3613be0e5c09SChris Mason }
3614be0e5c09SChris Mason 
361574123bd7SChris Mason /*
361644871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
361744871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
361899d8f83cSChris Mason  *
361999d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
362099d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
362199d8f83cSChris Mason  * items
362244871b1bSChris Mason  */
362344871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
362499d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
362599d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
362644871b1bSChris Mason {
362744871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
362844871b1bSChris Mason 	struct extent_buffer *left;
362944871b1bSChris Mason 	int slot;
363044871b1bSChris Mason 	int free_space;
363144871b1bSChris Mason 	u32 right_nritems;
363244871b1bSChris Mason 	int ret = 0;
363344871b1bSChris Mason 
363444871b1bSChris Mason 	slot = path->slots[1];
363544871b1bSChris Mason 	if (slot == 0)
363644871b1bSChris Mason 		return 1;
363744871b1bSChris Mason 	if (!path->nodes[1])
363844871b1bSChris Mason 		return 1;
363944871b1bSChris Mason 
364044871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
364144871b1bSChris Mason 	if (right_nritems == 0)
364244871b1bSChris Mason 		return 1;
364344871b1bSChris Mason 
364449d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
364544871b1bSChris Mason 
36464b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3647fb770ae4SLiu Bo 	if (IS_ERR(left))
36489cf14029SJosef Bacik 		return PTR_ERR(left);
364991ca338dSTsutomu Itoh 
3650bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
365144871b1bSChris Mason 
3652e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
365344871b1bSChris Mason 	if (free_space < data_size) {
365444871b1bSChris Mason 		ret = 1;
365544871b1bSChris Mason 		goto out;
365644871b1bSChris Mason 	}
365744871b1bSChris Mason 
365844871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
36599631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3660bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
366144871b1bSChris Mason 	if (ret) {
366244871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
366379787eaaSJeff Mahoney 		if (ret == -ENOSPC)
366444871b1bSChris Mason 			ret = 1;
366544871b1bSChris Mason 		goto out;
366644871b1bSChris Mason 	}
366744871b1bSChris Mason 
3668d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3669d16c702fSQu Wenruo 		ret = -EUCLEAN;
36709ae5afd0SFilipe Manana 		btrfs_abort_transaction(trans, ret);
3671d16c702fSQu Wenruo 		goto out;
3672d16c702fSQu Wenruo 	}
3673ed25dab3SJosef Bacik 	return __push_leaf_left(trans, path, min_data_size, empty, left,
3674ed25dab3SJosef Bacik 				free_space, right_nritems, max_slot);
367544871b1bSChris Mason out:
367644871b1bSChris Mason 	btrfs_tree_unlock(left);
367744871b1bSChris Mason 	free_extent_buffer(left);
367844871b1bSChris Mason 	return ret;
367944871b1bSChris Mason }
368044871b1bSChris Mason 
368144871b1bSChris Mason /*
368274123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
368374123bd7SChris Mason  * available for the resulting leaf level of the path.
368474123bd7SChris Mason  */
368550b5d1fcSFilipe Manana static noinline int copy_for_split(struct btrfs_trans_handle *trans,
368644871b1bSChris Mason 				   struct btrfs_path *path,
368744871b1bSChris Mason 				   struct extent_buffer *l,
368844871b1bSChris Mason 				   struct extent_buffer *right,
368944871b1bSChris Mason 				   int slot, int mid, int nritems)
3690be0e5c09SChris Mason {
369194f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3692be0e5c09SChris Mason 	int data_copy_size;
3693be0e5c09SChris Mason 	int rt_data_off;
3694be0e5c09SChris Mason 	int i;
369550b5d1fcSFilipe Manana 	int ret;
3696d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3697cfed81a0SChris Mason 	struct btrfs_map_token token;
3698cfed81a0SChris Mason 
36995f39d397SChris Mason 	nritems = nritems - mid;
37005f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3701dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
37025f39d397SChris Mason 
3703637e3b48SJosef Bacik 	copy_leaf_items(right, l, 0, mid, nritems);
37045f39d397SChris Mason 
3705637e3b48SJosef Bacik 	copy_leaf_data(right, l, BTRFS_LEAF_DATA_SIZE(fs_info) - data_copy_size,
37068f881e8cSDavid Sterba 		       leaf_data_end(l), data_copy_size);
370774123bd7SChris Mason 
3708dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
37095f39d397SChris Mason 
3710c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
37115f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3712db94535dSChris Mason 		u32 ioff;
3713db94535dSChris Mason 
37143212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
37153212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
37160783fcfcSChris Mason 	}
371774123bd7SChris Mason 
37185f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
37195f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
372050b5d1fcSFilipe Manana 	ret = insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
372150b5d1fcSFilipe Manana 	if (ret < 0)
372250b5d1fcSFilipe Manana 		return ret;
37235f39d397SChris Mason 
3724d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, right);
3725d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, l);
3726eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
37275f39d397SChris Mason 
3728be0e5c09SChris Mason 	if (mid <= slot) {
3729925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
37305f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
37315f39d397SChris Mason 		path->nodes[0] = right;
3732be0e5c09SChris Mason 		path->slots[0] -= mid;
3733be0e5c09SChris Mason 		path->slots[1] += 1;
3734925baeddSChris Mason 	} else {
3735925baeddSChris Mason 		btrfs_tree_unlock(right);
37365f39d397SChris Mason 		free_extent_buffer(right);
3737925baeddSChris Mason 	}
37385f39d397SChris Mason 
3739eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
374050b5d1fcSFilipe Manana 
374150b5d1fcSFilipe Manana 	return 0;
374244871b1bSChris Mason }
374344871b1bSChris Mason 
374444871b1bSChris Mason /*
374599d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
374699d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
374799d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
374899d8f83cSChris Mason  *          A                 B                 C
374999d8f83cSChris Mason  *
375099d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
375199d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
375299d8f83cSChris Mason  * completely.
375399d8f83cSChris Mason  */
375499d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
375599d8f83cSChris Mason 					  struct btrfs_root *root,
375699d8f83cSChris Mason 					  struct btrfs_path *path,
375799d8f83cSChris Mason 					  int data_size)
375899d8f83cSChris Mason {
375999d8f83cSChris Mason 	int ret;
376099d8f83cSChris Mason 	int progress = 0;
376199d8f83cSChris Mason 	int slot;
376299d8f83cSChris Mason 	u32 nritems;
37635a4267caSFilipe David Borba Manana 	int space_needed = data_size;
376499d8f83cSChris Mason 
376599d8f83cSChris Mason 	slot = path->slots[0];
37665a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3767e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
376899d8f83cSChris Mason 
376999d8f83cSChris Mason 	/*
377099d8f83cSChris Mason 	 * try to push all the items after our slot into the
377199d8f83cSChris Mason 	 * right leaf
377299d8f83cSChris Mason 	 */
37735a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
377499d8f83cSChris Mason 	if (ret < 0)
377599d8f83cSChris Mason 		return ret;
377699d8f83cSChris Mason 
377799d8f83cSChris Mason 	if (ret == 0)
377899d8f83cSChris Mason 		progress++;
377999d8f83cSChris Mason 
378099d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
378199d8f83cSChris Mason 	/*
378299d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
378399d8f83cSChris Mason 	 * we've done so we're done
378499d8f83cSChris Mason 	 */
378599d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
378699d8f83cSChris Mason 		return 0;
378799d8f83cSChris Mason 
3788e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
378999d8f83cSChris Mason 		return 0;
379099d8f83cSChris Mason 
379199d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
379299d8f83cSChris Mason 	slot = path->slots[0];
3793263d3995SFilipe Manana 	space_needed = data_size;
3794263d3995SFilipe Manana 	if (slot > 0)
3795e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
37965a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
379799d8f83cSChris Mason 	if (ret < 0)
379899d8f83cSChris Mason 		return ret;
379999d8f83cSChris Mason 
380099d8f83cSChris Mason 	if (ret == 0)
380199d8f83cSChris Mason 		progress++;
380299d8f83cSChris Mason 
380399d8f83cSChris Mason 	if (progress)
380499d8f83cSChris Mason 		return 0;
380599d8f83cSChris Mason 	return 1;
380699d8f83cSChris Mason }
380799d8f83cSChris Mason 
380899d8f83cSChris Mason /*
380944871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
381044871b1bSChris Mason  * available for the resulting leaf level of the path.
381144871b1bSChris Mason  *
381244871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
381344871b1bSChris Mason  */
381444871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
381544871b1bSChris Mason 			       struct btrfs_root *root,
3816310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
381744871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
381844871b1bSChris Mason 			       int extend)
381944871b1bSChris Mason {
38205d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
382144871b1bSChris Mason 	struct extent_buffer *l;
382244871b1bSChris Mason 	u32 nritems;
382344871b1bSChris Mason 	int mid;
382444871b1bSChris Mason 	int slot;
382544871b1bSChris Mason 	struct extent_buffer *right;
3826b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
382744871b1bSChris Mason 	int ret = 0;
382844871b1bSChris Mason 	int wret;
38295d4f98a2SYan Zheng 	int split;
383044871b1bSChris Mason 	int num_doubles = 0;
383199d8f83cSChris Mason 	int tried_avoid_double = 0;
383244871b1bSChris Mason 
3833a5719521SYan, Zheng 	l = path->nodes[0];
3834a5719521SYan, Zheng 	slot = path->slots[0];
38353212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
38360b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3837a5719521SYan, Zheng 		return -EOVERFLOW;
3838a5719521SYan, Zheng 
383944871b1bSChris Mason 	/* first try to make some room by pushing left and right */
384033157e05SLiu Bo 	if (data_size && path->nodes[1]) {
38415a4267caSFilipe David Borba Manana 		int space_needed = data_size;
38425a4267caSFilipe David Borba Manana 
38435a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3844e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
38455a4267caSFilipe David Borba Manana 
38465a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
38475a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
384844871b1bSChris Mason 		if (wret < 0)
384944871b1bSChris Mason 			return wret;
385044871b1bSChris Mason 		if (wret) {
3851263d3995SFilipe Manana 			space_needed = data_size;
3852263d3995SFilipe Manana 			if (slot > 0)
3853e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
38545a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
38555a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
385644871b1bSChris Mason 			if (wret < 0)
385744871b1bSChris Mason 				return wret;
385844871b1bSChris Mason 		}
385944871b1bSChris Mason 		l = path->nodes[0];
386044871b1bSChris Mason 
386144871b1bSChris Mason 		/* did the pushes work? */
3862e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
386344871b1bSChris Mason 			return 0;
386444871b1bSChris Mason 	}
386544871b1bSChris Mason 
386644871b1bSChris Mason 	if (!path->nodes[1]) {
3867fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
386844871b1bSChris Mason 		if (ret)
386944871b1bSChris Mason 			return ret;
387044871b1bSChris Mason 	}
387144871b1bSChris Mason again:
38725d4f98a2SYan Zheng 	split = 1;
387344871b1bSChris Mason 	l = path->nodes[0];
387444871b1bSChris Mason 	slot = path->slots[0];
387544871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
387644871b1bSChris Mason 	mid = (nritems + 1) / 2;
387744871b1bSChris Mason 
38785d4f98a2SYan Zheng 	if (mid <= slot) {
38795d4f98a2SYan Zheng 		if (nritems == 1 ||
38805d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
38810b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
38825d4f98a2SYan Zheng 			if (slot >= nritems) {
38835d4f98a2SYan Zheng 				split = 0;
38845d4f98a2SYan Zheng 			} else {
38855d4f98a2SYan Zheng 				mid = slot;
38865d4f98a2SYan Zheng 				if (mid != nritems &&
38875d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
38880b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
388999d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
389099d8f83cSChris Mason 						goto push_for_double;
38915d4f98a2SYan Zheng 					split = 2;
38925d4f98a2SYan Zheng 				}
38935d4f98a2SYan Zheng 			}
38945d4f98a2SYan Zheng 		}
38955d4f98a2SYan Zheng 	} else {
38965d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
38970b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
38985d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
38995d4f98a2SYan Zheng 				split = 0;
39005d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
39015d4f98a2SYan Zheng 				mid = 1;
39025d4f98a2SYan Zheng 			} else {
39035d4f98a2SYan Zheng 				mid = slot;
39045d4f98a2SYan Zheng 				if (mid != nritems &&
39055d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
39060b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
390799d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
390899d8f83cSChris Mason 						goto push_for_double;
39095d4f98a2SYan Zheng 					split = 2;
39105d4f98a2SYan Zheng 				}
39115d4f98a2SYan Zheng 			}
39125d4f98a2SYan Zheng 		}
39135d4f98a2SYan Zheng 	}
39145d4f98a2SYan Zheng 
39155d4f98a2SYan Zheng 	if (split == 0)
39165d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
39175d4f98a2SYan Zheng 	else
39185d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
39195d4f98a2SYan Zheng 
3920ca9d473aSJosef Bacik 	/*
3921ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3922ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3923ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3924ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3925ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3926ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3927ca9d473aSJosef Bacik 	 */
392879bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
392979bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
393079bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3931ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3932f0486c68SYan, Zheng 	if (IS_ERR(right))
393344871b1bSChris Mason 		return PTR_ERR(right);
3934f0486c68SYan, Zheng 
39350b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
393644871b1bSChris Mason 
39375d4f98a2SYan Zheng 	if (split == 0) {
393844871b1bSChris Mason 		if (mid <= slot) {
393944871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
394050b5d1fcSFilipe Manana 			ret = insert_ptr(trans, path, &disk_key,
39412ff7e61eSJeff Mahoney 					 right->start, path->slots[1] + 1, 1);
394250b5d1fcSFilipe Manana 			if (ret < 0) {
394350b5d1fcSFilipe Manana 				btrfs_tree_unlock(right);
394450b5d1fcSFilipe Manana 				free_extent_buffer(right);
394550b5d1fcSFilipe Manana 				return ret;
394650b5d1fcSFilipe Manana 			}
394744871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
394844871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
394944871b1bSChris Mason 			path->nodes[0] = right;
395044871b1bSChris Mason 			path->slots[0] = 0;
395144871b1bSChris Mason 			path->slots[1] += 1;
395244871b1bSChris Mason 		} else {
395344871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
395450b5d1fcSFilipe Manana 			ret = insert_ptr(trans, path, &disk_key,
39552ff7e61eSJeff Mahoney 					 right->start, path->slots[1], 1);
395650b5d1fcSFilipe Manana 			if (ret < 0) {
395750b5d1fcSFilipe Manana 				btrfs_tree_unlock(right);
395850b5d1fcSFilipe Manana 				free_extent_buffer(right);
395950b5d1fcSFilipe Manana 				return ret;
396050b5d1fcSFilipe Manana 			}
396144871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
396244871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
396344871b1bSChris Mason 			path->nodes[0] = right;
396444871b1bSChris Mason 			path->slots[0] = 0;
3965143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3966d5e09e38SFilipe Manana 				fixup_low_keys(trans, path, &disk_key, 1);
39675d4f98a2SYan Zheng 		}
3968196e0249SLiu Bo 		/*
3969196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3970196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3971196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3972196e0249SLiu Bo 		 */
397344871b1bSChris Mason 		return ret;
397444871b1bSChris Mason 	}
397544871b1bSChris Mason 
397650b5d1fcSFilipe Manana 	ret = copy_for_split(trans, path, l, right, slot, mid, nritems);
397750b5d1fcSFilipe Manana 	if (ret < 0) {
397850b5d1fcSFilipe Manana 		btrfs_tree_unlock(right);
397950b5d1fcSFilipe Manana 		free_extent_buffer(right);
398050b5d1fcSFilipe Manana 		return ret;
398150b5d1fcSFilipe Manana 	}
398244871b1bSChris Mason 
39835d4f98a2SYan Zheng 	if (split == 2) {
3984cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3985cc0c5538SChris Mason 		num_doubles++;
3986cc0c5538SChris Mason 		goto again;
39873326d1b0SChris Mason 	}
398844871b1bSChris Mason 
3989143bede5SJeff Mahoney 	return 0;
399099d8f83cSChris Mason 
399199d8f83cSChris Mason push_for_double:
399299d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
399399d8f83cSChris Mason 	tried_avoid_double = 1;
3994e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
399599d8f83cSChris Mason 		return 0;
399699d8f83cSChris Mason 	goto again;
3997be0e5c09SChris Mason }
3998be0e5c09SChris Mason 
3999ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4000ad48fd75SYan, Zheng 					 struct btrfs_root *root,
4001ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
4002ad48fd75SYan, Zheng {
4003ad48fd75SYan, Zheng 	struct btrfs_key key;
4004ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
4005ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
4006ad48fd75SYan, Zheng 	u64 extent_len = 0;
4007ad48fd75SYan, Zheng 	u32 item_size;
4008ad48fd75SYan, Zheng 	int ret;
4009ad48fd75SYan, Zheng 
4010ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4011ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4012ad48fd75SYan, Zheng 
4013ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4014ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
4015ad48fd75SYan, Zheng 
4016e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
4017ad48fd75SYan, Zheng 		return 0;
4018ad48fd75SYan, Zheng 
40193212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4020ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4021ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4022ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4023ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4024ad48fd75SYan, Zheng 	}
4025b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4026ad48fd75SYan, Zheng 
4027ad48fd75SYan, Zheng 	path->keep_locks = 1;
4028ad48fd75SYan, Zheng 	path->search_for_split = 1;
4029ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4030ad48fd75SYan, Zheng 	path->search_for_split = 0;
4031a8df6fe6SFilipe Manana 	if (ret > 0)
4032a8df6fe6SFilipe Manana 		ret = -EAGAIN;
4033ad48fd75SYan, Zheng 	if (ret < 0)
4034ad48fd75SYan, Zheng 		goto err;
4035ad48fd75SYan, Zheng 
4036ad48fd75SYan, Zheng 	ret = -EAGAIN;
4037ad48fd75SYan, Zheng 	leaf = path->nodes[0];
4038a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
40393212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
4040ad48fd75SYan, Zheng 		goto err;
4041ad48fd75SYan, Zheng 
4042109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
4043e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
4044109f6aefSChris Mason 		goto err;
4045109f6aefSChris Mason 
4046ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
4047ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
4048ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
4049ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4050ad48fd75SYan, Zheng 			goto err;
4051ad48fd75SYan, Zheng 	}
4052ad48fd75SYan, Zheng 
4053ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
4054f0486c68SYan, Zheng 	if (ret)
4055f0486c68SYan, Zheng 		goto err;
4056ad48fd75SYan, Zheng 
4057ad48fd75SYan, Zheng 	path->keep_locks = 0;
4058ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
4059ad48fd75SYan, Zheng 	return 0;
4060ad48fd75SYan, Zheng err:
4061ad48fd75SYan, Zheng 	path->keep_locks = 0;
4062ad48fd75SYan, Zheng 	return ret;
4063ad48fd75SYan, Zheng }
4064ad48fd75SYan, Zheng 
4065d5e09e38SFilipe Manana static noinline int split_item(struct btrfs_trans_handle *trans,
4066d5e09e38SFilipe Manana 			       struct btrfs_path *path,
4067310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
4068459931ecSChris Mason 			       unsigned long split_offset)
4069459931ecSChris Mason {
4070459931ecSChris Mason 	struct extent_buffer *leaf;
4071c91666b1SJosef Bacik 	int orig_slot, slot;
4072ad48fd75SYan, Zheng 	char *buf;
4073459931ecSChris Mason 	u32 nritems;
4074ad48fd75SYan, Zheng 	u32 item_size;
4075459931ecSChris Mason 	u32 orig_offset;
4076459931ecSChris Mason 	struct btrfs_disk_key disk_key;
4077459931ecSChris Mason 
4078459931ecSChris Mason 	leaf = path->nodes[0];
40797569141eSFilipe Manana 	/*
40807569141eSFilipe Manana 	 * Shouldn't happen because the caller must have previously called
40817569141eSFilipe Manana 	 * setup_leaf_for_split() to make room for the new item in the leaf.
40827569141eSFilipe Manana 	 */
40837569141eSFilipe Manana 	if (WARN_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item)))
40847569141eSFilipe Manana 		return -ENOSPC;
4085b9473439SChris Mason 
4086c91666b1SJosef Bacik 	orig_slot = path->slots[0];
40873212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
40883212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4089459931ecSChris Mason 
4090459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
4091ad48fd75SYan, Zheng 	if (!buf)
4092ad48fd75SYan, Zheng 		return -ENOMEM;
4093ad48fd75SYan, Zheng 
4094459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4095459931ecSChris Mason 			    path->slots[0]), item_size);
4096ad48fd75SYan, Zheng 
4097459931ecSChris Mason 	slot = path->slots[0] + 1;
4098459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
4099459931ecSChris Mason 	if (slot != nritems) {
4100459931ecSChris Mason 		/* shift the items */
4101637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot + 1, slot, nritems - slot);
4102459931ecSChris Mason 	}
4103459931ecSChris Mason 
4104459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
4105459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
4106459931ecSChris Mason 
41073212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
41083212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
4109459931ecSChris Mason 
41103212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
4111459931ecSChris Mason 				 orig_offset + item_size - split_offset);
41123212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
4113459931ecSChris Mason 
4114459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
4115459931ecSChris Mason 
4116459931ecSChris Mason 	/* write the data for the start of the original item */
4117459931ecSChris Mason 	write_extent_buffer(leaf, buf,
4118459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4119459931ecSChris Mason 			    split_offset);
4120459931ecSChris Mason 
4121459931ecSChris Mason 	/* write the data for the new item */
4122459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
4123459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
4124459931ecSChris Mason 			    item_size - split_offset);
4125d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, leaf);
4126459931ecSChris Mason 
4127e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
4128459931ecSChris Mason 	kfree(buf);
4129ad48fd75SYan, Zheng 	return 0;
4130ad48fd75SYan, Zheng }
4131ad48fd75SYan, Zheng 
4132ad48fd75SYan, Zheng /*
4133ad48fd75SYan, Zheng  * This function splits a single item into two items,
4134ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
4135ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
4136ad48fd75SYan, Zheng  *
4137ad48fd75SYan, Zheng  * The path may be released by this operation.  After
4138ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
4139ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
4140ad48fd75SYan, Zheng  *
4141ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
4142ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
4143ad48fd75SYan, Zheng  *
4144ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
4145ad48fd75SYan, Zheng  * leaf the entire time.
4146ad48fd75SYan, Zheng  */
4147ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4148ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4149ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4150310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
4151ad48fd75SYan, Zheng 		     unsigned long split_offset)
4152ad48fd75SYan, Zheng {
4153ad48fd75SYan, Zheng 	int ret;
4154ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4155ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4156ad48fd75SYan, Zheng 	if (ret)
4157459931ecSChris Mason 		return ret;
4158ad48fd75SYan, Zheng 
4159d5e09e38SFilipe Manana 	ret = split_item(trans, path, new_key, split_offset);
4160ad48fd75SYan, Zheng 	return ret;
4161ad48fd75SYan, Zheng }
4162ad48fd75SYan, Zheng 
4163ad48fd75SYan, Zheng /*
4164d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4165d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4166d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4167d352ac68SChris Mason  * the front.
4168d352ac68SChris Mason  */
4169d5e09e38SFilipe Manana void btrfs_truncate_item(struct btrfs_trans_handle *trans,
4170d5e09e38SFilipe Manana 			 struct btrfs_path *path, u32 new_size, int from_end)
4171b18c6685SChris Mason {
4172b18c6685SChris Mason 	int slot;
41735f39d397SChris Mason 	struct extent_buffer *leaf;
4174b18c6685SChris Mason 	u32 nritems;
4175b18c6685SChris Mason 	unsigned int data_end;
4176b18c6685SChris Mason 	unsigned int old_data_start;
4177b18c6685SChris Mason 	unsigned int old_size;
4178b18c6685SChris Mason 	unsigned int size_diff;
4179b18c6685SChris Mason 	int i;
4180cfed81a0SChris Mason 	struct btrfs_map_token token;
4181cfed81a0SChris Mason 
41825f39d397SChris Mason 	leaf = path->nodes[0];
4183179e29e4SChris Mason 	slot = path->slots[0];
4184179e29e4SChris Mason 
41853212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
4186179e29e4SChris Mason 	if (old_size == new_size)
4187143bede5SJeff Mahoney 		return;
4188b18c6685SChris Mason 
41895f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
41908f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4191b18c6685SChris Mason 
41923212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
4193179e29e4SChris Mason 
4194b18c6685SChris Mason 	size_diff = old_size - new_size;
4195b18c6685SChris Mason 
4196b18c6685SChris Mason 	BUG_ON(slot < 0);
4197b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4198b18c6685SChris Mason 
4199b18c6685SChris Mason 	/*
4200b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4201b18c6685SChris Mason 	 */
4202b18c6685SChris Mason 	/* first correct the data pointers */
4203c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4204b18c6685SChris 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, ioff + size_diff);
4209b18c6685SChris Mason 	}
4210db94535dSChris Mason 
4211b18c6685SChris Mason 	/* shift the data */
4212179e29e4SChris Mason 	if (from_end) {
4213637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
4214637e3b48SJosef Bacik 				  old_data_start + new_size - data_end);
4215179e29e4SChris Mason 	} else {
4216179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4217179e29e4SChris Mason 		u64 offset;
4218179e29e4SChris Mason 
4219179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4220179e29e4SChris Mason 
4221179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4222179e29e4SChris Mason 			unsigned long ptr;
4223179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4224179e29e4SChris Mason 
4225179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4226179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4227179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4228179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4229179e29e4SChris Mason 
4230179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4231179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4232179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4233179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4234179e29e4SChris Mason 				      (unsigned long)fi,
42357ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4236179e29e4SChris Mason 			}
4237179e29e4SChris Mason 		}
4238179e29e4SChris Mason 
4239637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
4240637e3b48SJosef Bacik 				  old_data_start - data_end);
4241179e29e4SChris Mason 
4242179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4243179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4244179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4245179e29e4SChris Mason 		if (slot == 0)
4246d5e09e38SFilipe Manana 			fixup_low_keys(trans, path, &disk_key, 1);
4247179e29e4SChris Mason 	}
42485f39d397SChris Mason 
42493212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
4250d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, leaf);
4251b18c6685SChris Mason 
4252e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4253a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4254b18c6685SChris Mason 		BUG();
42555f39d397SChris Mason 	}
4256b18c6685SChris Mason }
4257b18c6685SChris Mason 
4258d352ac68SChris Mason /*
42598f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4260d352ac68SChris Mason  */
4261d5e09e38SFilipe Manana void btrfs_extend_item(struct btrfs_trans_handle *trans,
4262d5e09e38SFilipe Manana 		       struct btrfs_path *path, u32 data_size)
42636567e837SChris Mason {
42646567e837SChris Mason 	int slot;
42655f39d397SChris Mason 	struct extent_buffer *leaf;
42666567e837SChris Mason 	u32 nritems;
42676567e837SChris Mason 	unsigned int data_end;
42686567e837SChris Mason 	unsigned int old_data;
42696567e837SChris Mason 	unsigned int old_size;
42706567e837SChris Mason 	int i;
4271cfed81a0SChris Mason 	struct btrfs_map_token token;
4272cfed81a0SChris Mason 
42735f39d397SChris Mason 	leaf = path->nodes[0];
42746567e837SChris Mason 
42755f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
42768f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
42776567e837SChris Mason 
4278e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4279a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
42806567e837SChris Mason 		BUG();
42815f39d397SChris Mason 	}
42826567e837SChris Mason 	slot = path->slots[0];
4283dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
42846567e837SChris Mason 
42856567e837SChris Mason 	BUG_ON(slot < 0);
42863326d1b0SChris Mason 	if (slot >= nritems) {
4287a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4288c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4289d397712bSChris Mason 			   slot, nritems);
4290290342f6SArnd Bergmann 		BUG();
42913326d1b0SChris Mason 	}
42926567e837SChris Mason 
42936567e837SChris Mason 	/*
42946567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
42956567e837SChris Mason 	 */
42966567e837SChris Mason 	/* first correct the data pointers */
4297c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
42986567e837SChris Mason 	for (i = slot; i < nritems; i++) {
42995f39d397SChris Mason 		u32 ioff;
4300db94535dSChris Mason 
43013212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
43023212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
43036567e837SChris Mason 	}
43045f39d397SChris Mason 
43056567e837SChris Mason 	/* shift the data */
4306637e3b48SJosef Bacik 	memmove_leaf_data(leaf, data_end - data_size, data_end,
4307637e3b48SJosef Bacik 			  old_data - data_end);
43085f39d397SChris Mason 
43096567e837SChris Mason 	data_end = old_data;
43103212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
43113212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
4312d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, leaf);
43136567e837SChris Mason 
4314e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4315a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
43166567e837SChris Mason 		BUG();
43175f39d397SChris Mason 	}
43186567e837SChris Mason }
43196567e837SChris Mason 
432043dd529aSDavid Sterba /*
432143dd529aSDavid Sterba  * Make space in the node before inserting one or more items.
4322da9ffb24SNikolay Borisov  *
4323d5e09e38SFilipe Manana  * @trans:	transaction handle
4324da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
4325da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
4326b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
432743dd529aSDavid Sterba  *
432843dd529aSDavid Sterba  * Main purpose is to save stack depth by doing the bulk of the work in a
432943dd529aSDavid Sterba  * function that doesn't call btrfs_search_slot
433074123bd7SChris Mason  */
4331d5e09e38SFilipe Manana static void setup_items_for_insert(struct btrfs_trans_handle *trans,
4332d5e09e38SFilipe Manana 				   struct btrfs_root *root, struct btrfs_path *path,
4333b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
4334be0e5c09SChris Mason {
43350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
43369c58309dSChris Mason 	int i;
43377518a238SChris Mason 	u32 nritems;
4338be0e5c09SChris Mason 	unsigned int data_end;
4339e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
434044871b1bSChris Mason 	struct extent_buffer *leaf;
434144871b1bSChris Mason 	int slot;
4342cfed81a0SChris Mason 	struct btrfs_map_token token;
4343fc0d82e1SNikolay Borisov 	u32 total_size;
4344fc0d82e1SNikolay Borisov 
4345b7ef5f3aSFilipe Manana 	/*
4346b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
4347b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
4348b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
4349b7ef5f3aSFilipe Manana 	 */
435024cdc847SFilipe Manana 	if (path->slots[0] == 0) {
4351b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4352d5e09e38SFilipe Manana 		fixup_low_keys(trans, path, &disk_key, 1);
435324cdc847SFilipe Manana 	}
435424cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
435524cdc847SFilipe Manana 
43565f39d397SChris Mason 	leaf = path->nodes[0];
435744871b1bSChris Mason 	slot = path->slots[0];
435874123bd7SChris Mason 
43595f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
43608f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4361b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4362eb60ceacSChris Mason 
4363e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4364a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
43650b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4366e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4367be0e5c09SChris Mason 		BUG();
4368d4dbff95SChris Mason 	}
43695f39d397SChris Mason 
4370c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4371be0e5c09SChris Mason 	if (slot != nritems) {
4372dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4373be0e5c09SChris Mason 
43745f39d397SChris Mason 		if (old_data < data_end) {
4375a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
43767269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
43777269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
43785f39d397SChris Mason 				   slot, old_data, data_end);
4379290342f6SArnd Bergmann 			BUG();
43805f39d397SChris Mason 		}
4381be0e5c09SChris Mason 		/*
4382be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4383be0e5c09SChris Mason 		 */
4384be0e5c09SChris Mason 		/* first correct the data pointers */
43850783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
43865f39d397SChris Mason 			u32 ioff;
4387db94535dSChris Mason 
43883212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
43893212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
4390b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
43910783fcfcSChris Mason 		}
4392be0e5c09SChris Mason 		/* shift the items */
4393637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot + batch->nr, slot, nritems - slot);
4394be0e5c09SChris Mason 
4395be0e5c09SChris Mason 		/* shift the data */
4396637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end - batch->total_data_size,
4397637e3b48SJosef Bacik 				  data_end, old_data - data_end);
4398be0e5c09SChris Mason 		data_end = old_data;
4399be0e5c09SChris Mason 	}
44005f39d397SChris Mason 
440162e2749eSChris Mason 	/* setup the item for the new data */
4402b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
4403b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
44049c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4405b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
44063212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
44073212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
44089c58309dSChris Mason 	}
440944871b1bSChris Mason 
4410b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4411d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, leaf);
4412aa5d6bedSChris Mason 
4413e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4414a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4415be0e5c09SChris Mason 		BUG();
44165f39d397SChris Mason 	}
441744871b1bSChris Mason }
441844871b1bSChris Mason 
441944871b1bSChris Mason /*
4420f0641656SFilipe Manana  * Insert a new item into a leaf.
4421f0641656SFilipe Manana  *
4422d5e09e38SFilipe Manana  * @trans:     Transaction handle.
4423f0641656SFilipe Manana  * @root:      The root of the btree.
4424f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
4425f0641656SFilipe Manana  * @key:       The key of the new item.
4426f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
4427f0641656SFilipe Manana  */
4428d5e09e38SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_trans_handle *trans,
4429d5e09e38SFilipe Manana 				 struct btrfs_root *root,
4430f0641656SFilipe Manana 				 struct btrfs_path *path,
4431f0641656SFilipe Manana 				 const struct btrfs_key *key,
4432f0641656SFilipe Manana 				 u32 data_size)
4433f0641656SFilipe Manana {
4434f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4435f0641656SFilipe Manana 
4436f0641656SFilipe Manana 	batch.keys = key;
4437f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4438f0641656SFilipe Manana 	batch.total_data_size = data_size;
4439f0641656SFilipe Manana 	batch.nr = 1;
4440f0641656SFilipe Manana 
4441d5e09e38SFilipe Manana 	setup_items_for_insert(trans, root, path, &batch);
4442f0641656SFilipe Manana }
4443f0641656SFilipe Manana 
4444f0641656SFilipe Manana /*
444544871b1bSChris Mason  * Given a key and some data, insert items into the tree.
444644871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
444744871b1bSChris Mason  */
444844871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
444944871b1bSChris Mason 			    struct btrfs_root *root,
445044871b1bSChris Mason 			    struct btrfs_path *path,
4451b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
445244871b1bSChris Mason {
445344871b1bSChris Mason 	int ret = 0;
445444871b1bSChris Mason 	int slot;
4455b7ef5f3aSFilipe Manana 	u32 total_size;
445644871b1bSChris Mason 
4457b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4458b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
445944871b1bSChris Mason 	if (ret == 0)
446044871b1bSChris Mason 		return -EEXIST;
446144871b1bSChris Mason 	if (ret < 0)
4462143bede5SJeff Mahoney 		return ret;
446344871b1bSChris Mason 
446444871b1bSChris Mason 	slot = path->slots[0];
446544871b1bSChris Mason 	BUG_ON(slot < 0);
446644871b1bSChris Mason 
4467d5e09e38SFilipe Manana 	setup_items_for_insert(trans, root, path, batch);
4468143bede5SJeff Mahoney 	return 0;
446962e2749eSChris Mason }
447062e2749eSChris Mason 
447162e2749eSChris Mason /*
447262e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
447362e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
447462e2749eSChris Mason  */
4475310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4476310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4477310712b2SOmar Sandoval 		      u32 data_size)
447862e2749eSChris Mason {
447962e2749eSChris Mason 	int ret = 0;
44802c90e5d6SChris Mason 	struct btrfs_path *path;
44815f39d397SChris Mason 	struct extent_buffer *leaf;
44825f39d397SChris Mason 	unsigned long ptr;
448362e2749eSChris Mason 
44842c90e5d6SChris Mason 	path = btrfs_alloc_path();
4485db5b493aSTsutomu Itoh 	if (!path)
4486db5b493aSTsutomu Itoh 		return -ENOMEM;
44872c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
448862e2749eSChris Mason 	if (!ret) {
44895f39d397SChris Mason 		leaf = path->nodes[0];
44905f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
44915f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
4492d5e09e38SFilipe Manana 		btrfs_mark_buffer_dirty(trans, leaf);
449362e2749eSChris Mason 	}
44942c90e5d6SChris Mason 	btrfs_free_path(path);
4495aa5d6bedSChris Mason 	return ret;
4496be0e5c09SChris Mason }
4497be0e5c09SChris Mason 
449874123bd7SChris Mason /*
4499f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4500f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4501f0641656SFilipe Manana  * contiguous with the original item.
4502f0641656SFilipe Manana  *
4503f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4504f0641656SFilipe Manana  * the entire time.
4505f0641656SFilipe Manana  */
4506f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4507f0641656SFilipe Manana 			 struct btrfs_root *root,
4508f0641656SFilipe Manana 			 struct btrfs_path *path,
4509f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4510f0641656SFilipe Manana {
4511f0641656SFilipe Manana 	struct extent_buffer *leaf;
4512f0641656SFilipe Manana 	int ret;
4513f0641656SFilipe Manana 	u32 item_size;
4514f0641656SFilipe Manana 
4515f0641656SFilipe Manana 	leaf = path->nodes[0];
45163212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4517f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4518f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4519f0641656SFilipe Manana 	if (ret)
4520f0641656SFilipe Manana 		return ret;
4521f0641656SFilipe Manana 
4522f0641656SFilipe Manana 	path->slots[0]++;
4523d5e09e38SFilipe Manana 	btrfs_setup_item_for_insert(trans, root, path, new_key, item_size);
4524f0641656SFilipe Manana 	leaf = path->nodes[0];
4525f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4526f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4527f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4528f0641656SFilipe Manana 			     item_size);
4529f0641656SFilipe Manana 	return 0;
4530f0641656SFilipe Manana }
4531f0641656SFilipe Manana 
4532f0641656SFilipe Manana /*
45335de08d7dSChris Mason  * delete the pointer from a given node.
453474123bd7SChris Mason  *
4535d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4536d352ac68SChris Mason  * empty a node.
4537016f9d0bSJosef Bacik  *
4538016f9d0bSJosef Bacik  * This is exported for use inside btrfs-progs, don't un-export it.
453974123bd7SChris Mason  */
4540751a2761SFilipe Manana int btrfs_del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4541751a2761SFilipe Manana 		  struct btrfs_path *path, int level, int slot)
4542be0e5c09SChris Mason {
45435f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
45447518a238SChris Mason 	u32 nritems;
4545f3ea38daSJan Schmidt 	int ret;
4546be0e5c09SChris Mason 
45475f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4548be0e5c09SChris Mason 	if (slot != nritems - 1) {
4549bf1d3425SDavid Sterba 		if (level) {
4550f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4551f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4552751a2761SFilipe Manana 			if (ret < 0) {
4553751a2761SFilipe Manana 				btrfs_abort_transaction(trans, ret);
4554751a2761SFilipe Manana 				return ret;
4555751a2761SFilipe Manana 			}
4556bf1d3425SDavid Sterba 		}
45575f39d397SChris Mason 		memmove_extent_buffer(parent,
4558e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot),
4559e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot + 1),
4560d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4561d6025579SChris Mason 			      (nritems - slot - 1));
456257ba86c0SChris Mason 	} else if (level) {
4563f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
456433cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REMOVE);
4565751a2761SFilipe Manana 		if (ret < 0) {
4566751a2761SFilipe Manana 			btrfs_abort_transaction(trans, ret);
4567751a2761SFilipe Manana 			return ret;
4568751a2761SFilipe Manana 		}
4569be0e5c09SChris Mason 	}
4570f3ea38daSJan Schmidt 
45717518a238SChris Mason 	nritems--;
45725f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
45737518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
45745f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4575eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
45765f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4577bb803951SChris Mason 	} else if (slot == 0) {
45785f39d397SChris Mason 		struct btrfs_disk_key disk_key;
45795f39d397SChris Mason 
45805f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4581d5e09e38SFilipe Manana 		fixup_low_keys(trans, path, &disk_key, level + 1);
4582be0e5c09SChris Mason 	}
4583d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, parent);
4584751a2761SFilipe Manana 	return 0;
4585be0e5c09SChris Mason }
4586be0e5c09SChris Mason 
458774123bd7SChris Mason /*
4588323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
45895d4f98a2SYan Zheng  * path->nodes[1].
4590323ac95bSChris Mason  *
4591323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4592323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4593323ac95bSChris Mason  *
4594323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4595323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4596323ac95bSChris Mason  */
4597751a2761SFilipe Manana static noinline int btrfs_del_leaf(struct btrfs_trans_handle *trans,
4598323ac95bSChris Mason 				   struct btrfs_root *root,
45995d4f98a2SYan Zheng 				   struct btrfs_path *path,
46005d4f98a2SYan Zheng 				   struct extent_buffer *leaf)
4601323ac95bSChris Mason {
4602751a2761SFilipe Manana 	int ret;
4603751a2761SFilipe Manana 
46045d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4605751a2761SFilipe Manana 	ret = btrfs_del_ptr(trans, root, path, 1, path->slots[1]);
4606751a2761SFilipe Manana 	if (ret < 0)
4607751a2761SFilipe Manana 		return ret;
4608323ac95bSChris Mason 
46094d081c41SChris Mason 	/*
46104d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
46114d081c41SChris Mason 	 * aren't holding any locks when we call it
46124d081c41SChris Mason 	 */
46134d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
46144d081c41SChris Mason 
4615f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4616f0486c68SYan, Zheng 
461767439dadSDavid Sterba 	atomic_inc(&leaf->refs);
4618*22d907bcSFilipe Manana 	ret = btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
46193083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4620*22d907bcSFilipe Manana 	if (ret < 0)
4621*22d907bcSFilipe Manana 		btrfs_abort_transaction(trans, ret);
4622*22d907bcSFilipe Manana 
4623*22d907bcSFilipe Manana 	return ret;
4624323ac95bSChris Mason }
4625323ac95bSChris Mason /*
462674123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
462774123bd7SChris Mason  * the leaf, remove it from the tree
462874123bd7SChris Mason  */
462985e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
463085e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4631be0e5c09SChris Mason {
46320b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
46335f39d397SChris Mason 	struct extent_buffer *leaf;
4634aa5d6bedSChris Mason 	int ret = 0;
4635aa5d6bedSChris Mason 	int wret;
46367518a238SChris Mason 	u32 nritems;
4637be0e5c09SChris Mason 
46385f39d397SChris Mason 	leaf = path->nodes[0];
46395f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4640be0e5c09SChris Mason 
464185e21bacSChris Mason 	if (slot + nr != nritems) {
46420cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
46430cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4644c82f823cSDavid Sterba 		struct btrfs_map_token token;
46450cae23b6SFilipe Manana 		u32 dsize = 0;
46460cae23b6SFilipe Manana 		int i;
46470cae23b6SFilipe Manana 
46480cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
46490cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
46505f39d397SChris Mason 
4651637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + dsize, data_end,
465285e21bacSChris Mason 				  last_off - data_end);
46535f39d397SChris Mason 
4654c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
465585e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
46565f39d397SChris Mason 			u32 ioff;
4657db94535dSChris Mason 
46583212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
46593212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
46600783fcfcSChris Mason 		}
4661db94535dSChris Mason 
4662637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot, slot + nr, nritems - slot - nr);
4663be0e5c09SChris Mason 	}
466485e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
466585e21bacSChris Mason 	nritems -= nr;
46665f39d397SChris Mason 
466774123bd7SChris Mason 	/* delete the leaf if we've emptied it */
46687518a238SChris Mason 	if (nritems == 0) {
46695f39d397SChris Mason 		if (leaf == root->node) {
46705f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
46719a8dd150SChris Mason 		} else {
4672190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, leaf);
4673751a2761SFilipe Manana 			ret = btrfs_del_leaf(trans, root, path, leaf);
4674751a2761SFilipe Manana 			if (ret < 0)
4675751a2761SFilipe Manana 				return ret;
46769a8dd150SChris Mason 		}
4677be0e5c09SChris Mason 	} else {
46787518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4679aa5d6bedSChris Mason 		if (slot == 0) {
46805f39d397SChris Mason 			struct btrfs_disk_key disk_key;
46815f39d397SChris Mason 
46825f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4683d5e09e38SFilipe Manana 			fixup_low_keys(trans, path, &disk_key, 1);
4684aa5d6bedSChris Mason 		}
4685aa5d6bedSChris Mason 
46867c4063d1SFilipe Manana 		/*
46877c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
46887c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
46897c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
46907c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
46917c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
46927c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
46937c4063d1SFilipe Manana 		 */
46940b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
46957c4063d1SFilipe Manana 			u32 min_push_space;
46967c4063d1SFilipe Manana 
4697be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4698be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4699016f9d0bSJosef Bacik 			 * for possible call to btrfs_del_ptr below
4700be0e5c09SChris Mason 			 */
47014920c9acSChris Mason 			slot = path->slots[1];
470267439dadSDavid Sterba 			atomic_inc(&leaf->refs);
47037c4063d1SFilipe Manana 			/*
47047c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
47057c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
47067c4063d1SFilipe Manana 			 */
47077c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
47087c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
47097c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
47107c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
471154aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4712aa5d6bedSChris Mason 				ret = wret;
47135f39d397SChris Mason 
47145f39d397SChris Mason 			if (path->nodes[0] == leaf &&
47155f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
47167c4063d1SFilipe Manana 				/*
47177c4063d1SFilipe Manana 				 * If we were not able to push all items from our
47187c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
47197c4063d1SFilipe Manana 				 * either push all the remaining items to the
47207c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
47217c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
47227c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
47237c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
47247c4063d1SFilipe Manana 				 * or nearly full.
47257c4063d1SFilipe Manana 				 */
47267c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
47277c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
47287c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
47297c4063d1SFilipe Manana 						       min_push_space, 1, 0);
473054aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4731aa5d6bedSChris Mason 					ret = wret;
4732aa5d6bedSChris Mason 			}
47335f39d397SChris Mason 
47345f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4735323ac95bSChris Mason 				path->slots[1] = slot;
4736751a2761SFilipe Manana 				ret = btrfs_del_leaf(trans, root, path, leaf);
4737751a2761SFilipe Manana 				if (ret < 0)
4738751a2761SFilipe Manana 					return ret;
47395f39d397SChris Mason 				free_extent_buffer(leaf);
4740143bede5SJeff Mahoney 				ret = 0;
47415de08d7dSChris Mason 			} else {
4742925baeddSChris Mason 				/* if we're still in the path, make sure
4743925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4744925baeddSChris Mason 				 * push_leaf functions must have already
4745925baeddSChris Mason 				 * dirtied this buffer
4746925baeddSChris Mason 				 */
4747925baeddSChris Mason 				if (path->nodes[0] == leaf)
4748d5e09e38SFilipe Manana 					btrfs_mark_buffer_dirty(trans, leaf);
47495f39d397SChris Mason 				free_extent_buffer(leaf);
4750be0e5c09SChris Mason 			}
4751d5719762SChris Mason 		} else {
4752d5e09e38SFilipe Manana 			btrfs_mark_buffer_dirty(trans, leaf);
4753be0e5c09SChris Mason 		}
47549a8dd150SChris Mason 	}
4755aa5d6bedSChris Mason 	return ret;
47569a8dd150SChris Mason }
47579a8dd150SChris Mason 
475897571fd0SChris Mason /*
47593f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4760de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4761de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
47623f157a2fSChris Mason  *
47633f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
47643f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
47653f157a2fSChris Mason  * key and get a writable path.
47663f157a2fSChris Mason  *
47673f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
47683f157a2fSChris Mason  * of the tree.
47693f157a2fSChris Mason  *
4770d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4771d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4772d352ac68SChris Mason  * skipped over (without reading them).
4773d352ac68SChris Mason  *
47743f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
47753f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
47763f157a2fSChris Mason  */
47773f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4778de78b51aSEric Sandeen 			 struct btrfs_path *path,
47793f157a2fSChris Mason 			 u64 min_trans)
47803f157a2fSChris Mason {
47813f157a2fSChris Mason 	struct extent_buffer *cur;
47823f157a2fSChris Mason 	struct btrfs_key found_key;
47833f157a2fSChris Mason 	int slot;
47849652480bSYan 	int sret;
47853f157a2fSChris Mason 	u32 nritems;
47863f157a2fSChris Mason 	int level;
47873f157a2fSChris Mason 	int ret = 1;
4788f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
47893f157a2fSChris Mason 
4790c922b016SStefan Roesch 	ASSERT(!path->nowait);
4791f98de9b9SFilipe Manana 	path->keep_locks = 1;
47923f157a2fSChris Mason again:
4793bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
47943f157a2fSChris Mason 	level = btrfs_header_level(cur);
4795e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
47963f157a2fSChris Mason 	path->nodes[level] = cur;
4797bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
47983f157a2fSChris Mason 
47993f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
48003f157a2fSChris Mason 		ret = 1;
48013f157a2fSChris Mason 		goto out;
48023f157a2fSChris Mason 	}
48033f157a2fSChris Mason 	while (1) {
48043f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
48053f157a2fSChris Mason 		level = btrfs_header_level(cur);
4806fdf8d595SAnand Jain 		sret = btrfs_bin_search(cur, 0, min_key, &slot);
4807cbca7d59SFilipe Manana 		if (sret < 0) {
4808cbca7d59SFilipe Manana 			ret = sret;
4809cbca7d59SFilipe Manana 			goto out;
4810cbca7d59SFilipe Manana 		}
48113f157a2fSChris Mason 
4812323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4813323ac95bSChris Mason 		if (level == path->lowest_level) {
4814e02119d5SChris Mason 			if (slot >= nritems)
4815e02119d5SChris Mason 				goto find_next_key;
48163f157a2fSChris Mason 			ret = 0;
48173f157a2fSChris Mason 			path->slots[level] = slot;
48183f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
48193f157a2fSChris Mason 			goto out;
48203f157a2fSChris Mason 		}
48219652480bSYan 		if (sret && slot > 0)
48229652480bSYan 			slot--;
48233f157a2fSChris Mason 		/*
4824de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4825260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
48263f157a2fSChris Mason 		 */
48273f157a2fSChris Mason 		while (slot < nritems) {
48283f157a2fSChris Mason 			u64 gen;
4829e02119d5SChris Mason 
48303f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
48313f157a2fSChris Mason 			if (gen < min_trans) {
48323f157a2fSChris Mason 				slot++;
48333f157a2fSChris Mason 				continue;
48343f157a2fSChris Mason 			}
48353f157a2fSChris Mason 			break;
48363f157a2fSChris Mason 		}
4837e02119d5SChris Mason find_next_key:
48383f157a2fSChris Mason 		/*
48393f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
48403f157a2fSChris Mason 		 * and find another one
48413f157a2fSChris Mason 		 */
48423f157a2fSChris Mason 		if (slot >= nritems) {
4843e02119d5SChris Mason 			path->slots[level] = slot;
4844e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4845de78b51aSEric Sandeen 						  min_trans);
4846e02119d5SChris Mason 			if (sret == 0) {
4847b3b4aa74SDavid Sterba 				btrfs_release_path(path);
48483f157a2fSChris Mason 				goto again;
48493f157a2fSChris Mason 			} else {
48503f157a2fSChris Mason 				goto out;
48513f157a2fSChris Mason 			}
48523f157a2fSChris Mason 		}
48533f157a2fSChris Mason 		/* save our key for returning back */
48543f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
48553f157a2fSChris Mason 		path->slots[level] = slot;
48563f157a2fSChris Mason 		if (level == path->lowest_level) {
48573f157a2fSChris Mason 			ret = 0;
48583f157a2fSChris Mason 			goto out;
48593f157a2fSChris Mason 		}
48604b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4861fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4862fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4863fb770ae4SLiu Bo 			goto out;
4864fb770ae4SLiu Bo 		}
48653f157a2fSChris Mason 
4866bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4867b4ce94deSChris Mason 
4868bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
48693f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4870f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
48713f157a2fSChris Mason 	}
48723f157a2fSChris Mason out:
4873f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4874f98de9b9SFilipe Manana 	if (ret == 0) {
4875f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4876f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4877f98de9b9SFilipe Manana 	}
48783f157a2fSChris Mason 	return ret;
48793f157a2fSChris Mason }
48803f157a2fSChris Mason 
48813f157a2fSChris Mason /*
48823f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
48833f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4884de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
48853f157a2fSChris Mason  *
48863f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
48873f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
48883f157a2fSChris Mason  *
48893f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
48903f157a2fSChris Mason  * calling this function.
48913f157a2fSChris Mason  */
4892e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4893de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4894e7a84565SChris Mason {
4895e7a84565SChris Mason 	int slot;
4896e7a84565SChris Mason 	struct extent_buffer *c;
4897e7a84565SChris Mason 
48986a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4899e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4900e7a84565SChris Mason 		if (!path->nodes[level])
4901e7a84565SChris Mason 			return 1;
4902e7a84565SChris Mason 
4903e7a84565SChris Mason 		slot = path->slots[level] + 1;
4904e7a84565SChris Mason 		c = path->nodes[level];
49053f157a2fSChris Mason next:
4906e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
490733c66f43SYan Zheng 			int ret;
490833c66f43SYan Zheng 			int orig_lowest;
490933c66f43SYan Zheng 			struct btrfs_key cur_key;
491033c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
491133c66f43SYan Zheng 			    !path->nodes[level + 1])
4912e7a84565SChris Mason 				return 1;
491333c66f43SYan Zheng 
49146a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
491533c66f43SYan Zheng 				level++;
4916e7a84565SChris Mason 				continue;
4917e7a84565SChris Mason 			}
491833c66f43SYan Zheng 
491933c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
492033c66f43SYan Zheng 			if (level == 0)
492133c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
492233c66f43SYan Zheng 			else
492333c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
492433c66f43SYan Zheng 
492533c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4926b3b4aa74SDavid Sterba 			btrfs_release_path(path);
492733c66f43SYan Zheng 			path->lowest_level = level;
492833c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
492933c66f43SYan Zheng 						0, 0);
493033c66f43SYan Zheng 			path->lowest_level = orig_lowest;
493133c66f43SYan Zheng 			if (ret < 0)
493233c66f43SYan Zheng 				return ret;
493333c66f43SYan Zheng 
493433c66f43SYan Zheng 			c = path->nodes[level];
493533c66f43SYan Zheng 			slot = path->slots[level];
493633c66f43SYan Zheng 			if (ret == 0)
493733c66f43SYan Zheng 				slot++;
493833c66f43SYan Zheng 			goto next;
493933c66f43SYan Zheng 		}
494033c66f43SYan Zheng 
4941e7a84565SChris Mason 		if (level == 0)
4942e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
49433f157a2fSChris Mason 		else {
49443f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
49453f157a2fSChris Mason 
49463f157a2fSChris Mason 			if (gen < min_trans) {
49473f157a2fSChris Mason 				slot++;
49483f157a2fSChris Mason 				goto next;
49493f157a2fSChris Mason 			}
4950e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
49513f157a2fSChris Mason 		}
4952e7a84565SChris Mason 		return 0;
4953e7a84565SChris Mason 	}
4954e7a84565SChris Mason 	return 1;
4955e7a84565SChris Mason }
4956e7a84565SChris Mason 
49573d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
49583d7806ecSJan Schmidt 			u64 time_seq)
49593d7806ecSJan Schmidt {
4960d97e63b6SChris Mason 	int slot;
49618e73f275SChris Mason 	int level;
49625f39d397SChris Mason 	struct extent_buffer *c;
49638e73f275SChris Mason 	struct extent_buffer *next;
4964d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4965925baeddSChris Mason 	struct btrfs_key key;
4966d96b3424SFilipe Manana 	bool need_commit_sem = false;
4967925baeddSChris Mason 	u32 nritems;
4968925baeddSChris Mason 	int ret;
49690e46318dSJosef Bacik 	int i;
4970925baeddSChris Mason 
4971bdcdd86cSFilipe Manana 	/*
4972bdcdd86cSFilipe Manana 	 * The nowait semantics are used only for write paths, where we don't
4973bdcdd86cSFilipe Manana 	 * use the tree mod log and sequence numbers.
4974bdcdd86cSFilipe Manana 	 */
4975bdcdd86cSFilipe Manana 	if (time_seq)
4976c922b016SStefan Roesch 		ASSERT(!path->nowait);
4977c922b016SStefan Roesch 
4978925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4979d397712bSChris Mason 	if (nritems == 0)
4980925baeddSChris Mason 		return 1;
4981925baeddSChris Mason 
49828e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
49838e73f275SChris Mason again:
49848e73f275SChris Mason 	level = 1;
49858e73f275SChris Mason 	next = NULL;
4986b3b4aa74SDavid Sterba 	btrfs_release_path(path);
49878e73f275SChris Mason 
4988a2135011SChris Mason 	path->keep_locks = 1;
49898e73f275SChris Mason 
4990d96b3424SFilipe Manana 	if (time_seq) {
49913d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4992d96b3424SFilipe Manana 	} else {
4993d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4994d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4995d96b3424SFilipe Manana 			need_commit_sem = true;
4996bdcdd86cSFilipe Manana 			if (path->nowait) {
4997bdcdd86cSFilipe Manana 				if (!down_read_trylock(&fs_info->commit_root_sem)) {
4998bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4999bdcdd86cSFilipe Manana 					goto done;
5000bdcdd86cSFilipe Manana 				}
5001bdcdd86cSFilipe Manana 			} else {
5002d96b3424SFilipe Manana 				down_read(&fs_info->commit_root_sem);
5003d96b3424SFilipe Manana 			}
5004bdcdd86cSFilipe Manana 		}
5005925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5006d96b3424SFilipe Manana 	}
5007925baeddSChris Mason 	path->keep_locks = 0;
5008925baeddSChris Mason 
5009925baeddSChris Mason 	if (ret < 0)
5010d96b3424SFilipe Manana 		goto done;
5011925baeddSChris Mason 
5012a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
5013168fd7d2SChris Mason 	/*
5014168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
5015168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
5016168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
5017168fd7d2SChris Mason 	 * advance the path if there are now more items available.
5018168fd7d2SChris Mason 	 */
5019a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
5020e457afecSYan Zheng 		if (ret == 0)
5021168fd7d2SChris Mason 			path->slots[0]++;
50228e73f275SChris Mason 		ret = 0;
5023925baeddSChris Mason 		goto done;
5024925baeddSChris Mason 	}
50250b43e04fSLiu Bo 	/*
50260b43e04fSLiu Bo 	 * So the above check misses one case:
50270b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
50280b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
50290b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
50300b43e04fSLiu Bo 	 *
50310b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
50320b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
50330b43e04fSLiu Bo 	 *
50340b43e04fSLiu Bo 	 * And a bit more explanation about this check,
50350b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
50360b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
50370b43e04fSLiu Bo 	 * bigger one.
50380b43e04fSLiu Bo 	 */
50390b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
50400b43e04fSLiu Bo 		ret = 0;
50410b43e04fSLiu Bo 		goto done;
50420b43e04fSLiu Bo 	}
5043d97e63b6SChris Mason 
5044234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
50458e73f275SChris Mason 		if (!path->nodes[level]) {
50468e73f275SChris Mason 			ret = 1;
50478e73f275SChris Mason 			goto done;
50488e73f275SChris Mason 		}
50495f39d397SChris Mason 
5050d97e63b6SChris Mason 		slot = path->slots[level] + 1;
5051d97e63b6SChris Mason 		c = path->nodes[level];
50525f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
5053d97e63b6SChris Mason 			level++;
50548e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
50558e73f275SChris Mason 				ret = 1;
50568e73f275SChris Mason 				goto done;
50578e73f275SChris Mason 			}
5058d97e63b6SChris Mason 			continue;
5059d97e63b6SChris Mason 		}
50605f39d397SChris Mason 
50610e46318dSJosef Bacik 
50620e46318dSJosef Bacik 		/*
50630e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
50640e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
50650e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
50660e46318dSJosef Bacik 		 */
50670e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
50680e46318dSJosef Bacik 			if (path->locks[level]) {
50690e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
50700e46318dSJosef Bacik 				path->locks[i] = 0;
50710e46318dSJosef Bacik 			}
50720e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
50730e46318dSJosef Bacik 			path->nodes[i] = NULL;
5074925baeddSChris Mason 		}
50755f39d397SChris Mason 
50768e73f275SChris Mason 		next = c;
5077d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5078cda79c54SDavid Sterba 					    slot, &key);
5079bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
50808e73f275SChris Mason 			goto again;
50815f39d397SChris Mason 
508276a05b35SChris Mason 		if (ret < 0) {
5083b3b4aa74SDavid Sterba 			btrfs_release_path(path);
508476a05b35SChris Mason 			goto done;
508576a05b35SChris Mason 		}
508676a05b35SChris Mason 
50875cd57b2cSChris Mason 		if (!path->skip_locking) {
5088bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
5089bdcdd86cSFilipe Manana 			if (!ret && path->nowait) {
5090bdcdd86cSFilipe Manana 				ret = -EAGAIN;
5091bdcdd86cSFilipe Manana 				goto done;
5092bdcdd86cSFilipe Manana 			}
5093d42244a0SJan Schmidt 			if (!ret && time_seq) {
5094d42244a0SJan Schmidt 				/*
5095d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
5096d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
5097d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
5098d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
5099d42244a0SJan Schmidt 				 * on our lock and cycle.
5100d42244a0SJan Schmidt 				 */
5101cf538830SJan Schmidt 				free_extent_buffer(next);
5102d42244a0SJan Schmidt 				btrfs_release_path(path);
5103d42244a0SJan Schmidt 				cond_resched();
5104d42244a0SJan Schmidt 				goto again;
5105d42244a0SJan Schmidt 			}
51060e46318dSJosef Bacik 			if (!ret)
51070e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
5108bd681513SChris Mason 		}
5109d97e63b6SChris Mason 		break;
5110d97e63b6SChris Mason 	}
5111d97e63b6SChris Mason 	path->slots[level] = slot;
5112d97e63b6SChris Mason 	while (1) {
5113d97e63b6SChris Mason 		level--;
5114d97e63b6SChris Mason 		path->nodes[level] = next;
5115d97e63b6SChris Mason 		path->slots[level] = 0;
5116a74a4b97SChris Mason 		if (!path->skip_locking)
5117ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
5118d97e63b6SChris Mason 		if (!level)
5119d97e63b6SChris Mason 			break;
5120b4ce94deSChris Mason 
5121d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
5122cda79c54SDavid Sterba 					    0, &key);
5123bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
51248e73f275SChris Mason 			goto again;
51258e73f275SChris Mason 
512676a05b35SChris Mason 		if (ret < 0) {
5127b3b4aa74SDavid Sterba 			btrfs_release_path(path);
512876a05b35SChris Mason 			goto done;
512976a05b35SChris Mason 		}
513076a05b35SChris Mason 
5131bdcdd86cSFilipe Manana 		if (!path->skip_locking) {
5132bdcdd86cSFilipe Manana 			if (path->nowait) {
5133bdcdd86cSFilipe Manana 				if (!btrfs_try_tree_read_lock(next)) {
5134bdcdd86cSFilipe Manana 					ret = -EAGAIN;
5135bdcdd86cSFilipe Manana 					goto done;
5136bdcdd86cSFilipe Manana 				}
5137bdcdd86cSFilipe Manana 			} else {
51380e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
5139d97e63b6SChris Mason 			}
5140bdcdd86cSFilipe Manana 		}
5141bdcdd86cSFilipe Manana 	}
51428e73f275SChris Mason 	ret = 0;
5143925baeddSChris Mason done:
5144f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
5145d96b3424SFilipe Manana 	if (need_commit_sem) {
5146d96b3424SFilipe Manana 		int ret2;
5147d96b3424SFilipe Manana 
5148d96b3424SFilipe Manana 		path->need_commit_sem = 1;
5149d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
5150d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
5151d96b3424SFilipe Manana 		if (ret2)
5152d96b3424SFilipe Manana 			ret = ret2;
5153d96b3424SFilipe Manana 	}
51548e73f275SChris Mason 
51558e73f275SChris Mason 	return ret;
5156d97e63b6SChris Mason }
51570b86a832SChris Mason 
5158890d2b1aSJosef Bacik int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
5159890d2b1aSJosef Bacik {
5160890d2b1aSJosef Bacik 	path->slots[0]++;
5161890d2b1aSJosef Bacik 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
5162890d2b1aSJosef Bacik 		return btrfs_next_old_leaf(root, path, time_seq);
5163890d2b1aSJosef Bacik 	return 0;
5164890d2b1aSJosef Bacik }
5165890d2b1aSJosef Bacik 
51663f157a2fSChris Mason /*
51673f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
51683f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
51693f157a2fSChris Mason  *
51703f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
51713f157a2fSChris Mason  */
51720b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
51730b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
51740b86a832SChris Mason 			int type)
51750b86a832SChris Mason {
51760b86a832SChris Mason 	struct btrfs_key found_key;
51770b86a832SChris Mason 	struct extent_buffer *leaf;
5178e02119d5SChris Mason 	u32 nritems;
51790b86a832SChris Mason 	int ret;
51800b86a832SChris Mason 
51810b86a832SChris Mason 	while (1) {
51820b86a832SChris Mason 		if (path->slots[0] == 0) {
51830b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
51840b86a832SChris Mason 			if (ret != 0)
51850b86a832SChris Mason 				return ret;
51860b86a832SChris Mason 		} else {
51870b86a832SChris Mason 			path->slots[0]--;
51880b86a832SChris Mason 		}
51890b86a832SChris Mason 		leaf = path->nodes[0];
5190e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5191e02119d5SChris Mason 		if (nritems == 0)
5192e02119d5SChris Mason 			return 1;
5193e02119d5SChris Mason 		if (path->slots[0] == nritems)
5194e02119d5SChris Mason 			path->slots[0]--;
5195e02119d5SChris Mason 
51960b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5197e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5198e02119d5SChris Mason 			break;
51990a4eefbbSYan Zheng 		if (found_key.type == type)
52000a4eefbbSYan Zheng 			return 0;
5201e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5202e02119d5SChris Mason 		    found_key.type < type)
5203e02119d5SChris Mason 			break;
52040b86a832SChris Mason 	}
52050b86a832SChris Mason 	return 1;
52060b86a832SChris Mason }
5207ade2e0b3SWang Shilong 
5208ade2e0b3SWang Shilong /*
5209ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5210ade2e0b3SWang Shilong  * min objecitd.
5211ade2e0b3SWang Shilong  *
5212ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5213ade2e0b3SWang Shilong  */
5214ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5215ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5216ade2e0b3SWang Shilong {
5217ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5218ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5219ade2e0b3SWang Shilong 	u32 nritems;
5220ade2e0b3SWang Shilong 	int ret;
5221ade2e0b3SWang Shilong 
5222ade2e0b3SWang Shilong 	while (1) {
5223ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5224ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5225ade2e0b3SWang Shilong 			if (ret != 0)
5226ade2e0b3SWang Shilong 				return ret;
5227ade2e0b3SWang Shilong 		} else {
5228ade2e0b3SWang Shilong 			path->slots[0]--;
5229ade2e0b3SWang Shilong 		}
5230ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5231ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5232ade2e0b3SWang Shilong 		if (nritems == 0)
5233ade2e0b3SWang Shilong 			return 1;
5234ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5235ade2e0b3SWang Shilong 			path->slots[0]--;
5236ade2e0b3SWang Shilong 
5237ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5238ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5239ade2e0b3SWang Shilong 			break;
5240ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5241ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5242ade2e0b3SWang Shilong 			return 0;
5243ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5244ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5245ade2e0b3SWang Shilong 			break;
5246ade2e0b3SWang Shilong 	}
5247ade2e0b3SWang Shilong 	return 1;
5248ade2e0b3SWang Shilong }
5249226463d7SJosef Bacik 
5250226463d7SJosef Bacik int __init btrfs_ctree_init(void)
5251226463d7SJosef Bacik {
5252226463d7SJosef Bacik 	btrfs_path_cachep = kmem_cache_create("btrfs_path",
5253226463d7SJosef Bacik 			sizeof(struct btrfs_path), 0,
5254226463d7SJosef Bacik 			SLAB_MEM_SPREAD, NULL);
5255226463d7SJosef Bacik 	if (!btrfs_path_cachep)
5256226463d7SJosef Bacik 		return -ENOMEM;
5257226463d7SJosef Bacik 	return 0;
5258226463d7SJosef Bacik }
5259226463d7SJosef Bacik 
5260226463d7SJosef Bacik void __cold btrfs_ctree_exit(void)
5261226463d7SJosef Bacik {
5262226463d7SJosef Bacik 	kmem_cache_destroy(btrfs_path_cachep);
5263226463d7SJosef Bacik }
5264