xref: /openbmc/linux/fs/btrfs/ctree.c (revision ede600e4)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
3d352ac68SChris Mason  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
6a6b6e75eSChris Mason #include <linux/sched.h>
75a0e3ad6STejun Heo #include <linux/slab.h>
8bd989ba3SJan Schmidt #include <linux/rbtree.h>
9adf02123SDavid Sterba #include <linux/mm.h>
10e41d12f5SChristoph Hellwig #include <linux/error-injection.h>
119b569ea0SJosef Bacik #include "messages.h"
12eb60ceacSChris Mason #include "ctree.h"
13eb60ceacSChris Mason #include "disk-io.h"
147f5c1516SChris Mason #include "transaction.h"
155f39d397SChris Mason #include "print-tree.h"
16925baeddSChris Mason #include "locking.h"
17de37aa51SNikolay Borisov #include "volumes.h"
18f616f5cdSQu Wenruo #include "qgroup.h"
19f3a84ccdSFilipe Manana #include "tree-mod-log.h"
2088c602abSQu Wenruo #include "tree-checker.h"
21ec8eb376SJosef Bacik #include "fs.h"
22ad1ac501SJosef Bacik #include "accessors.h"
23a0231804SJosef Bacik #include "extent-tree.h"
2467707479SJosef Bacik #include "relocation.h"
256bfd0ffaSJosef Bacik #include "file-item.h"
269a8dd150SChris Mason 
27226463d7SJosef Bacik static struct kmem_cache *btrfs_path_cachep;
28226463d7SJosef Bacik 
29e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
30e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
31310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
32310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
33310712b2SOmar Sandoval 		      int data_size, int extend);
345f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
352ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
36971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
375f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
385f39d397SChris Mason 			      struct extent_buffer *dst_buf,
395f39d397SChris Mason 			      struct extent_buffer *src_buf);
40d97e63b6SChris Mason 
41af024ed2SJohannes Thumshirn static const struct btrfs_csums {
42af024ed2SJohannes Thumshirn 	u16		size;
4359a0fcdbSDavid Sterba 	const char	name[10];
4459a0fcdbSDavid Sterba 	const char	driver[12];
45af024ed2SJohannes Thumshirn } btrfs_csums[] = {
46af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
473951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
483831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
49352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
50352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
51af024ed2SJohannes Thumshirn };
52af024ed2SJohannes Thumshirn 
533a3178c7SJosef Bacik /*
543a3178c7SJosef Bacik  * The leaf data grows from end-to-front in the node.  this returns the address
553a3178c7SJosef Bacik  * of the start of the last item, which is the stop of the leaf data stack.
563a3178c7SJosef Bacik  */
573a3178c7SJosef Bacik static unsigned int leaf_data_end(const struct extent_buffer *leaf)
583a3178c7SJosef Bacik {
593a3178c7SJosef Bacik 	u32 nr = btrfs_header_nritems(leaf);
603a3178c7SJosef Bacik 
613a3178c7SJosef Bacik 	if (nr == 0)
623a3178c7SJosef Bacik 		return BTRFS_LEAF_DATA_SIZE(leaf->fs_info);
633a3178c7SJosef Bacik 	return btrfs_item_offset(leaf, nr - 1);
643a3178c7SJosef Bacik }
653a3178c7SJosef Bacik 
66637e3b48SJosef Bacik /*
67637e3b48SJosef Bacik  * Move data in a @leaf (using memmove, safe for overlapping ranges).
68637e3b48SJosef Bacik  *
69637e3b48SJosef Bacik  * @leaf:	leaf that we're doing a memmove on
70637e3b48SJosef Bacik  * @dst_offset:	item data offset we're moving to
71637e3b48SJosef Bacik  * @src_offset:	item data offset were' moving from
72637e3b48SJosef Bacik  * @len:	length of the data we're moving
73637e3b48SJosef Bacik  *
74637e3b48SJosef Bacik  * Wrapper around memmove_extent_buffer() that takes into account the header on
75637e3b48SJosef Bacik  * the leaf.  The btrfs_item offset's start directly after the header, so we
76637e3b48SJosef Bacik  * have to adjust any offsets to account for the header in the leaf.  This
77637e3b48SJosef Bacik  * handles that math to simplify the callers.
78637e3b48SJosef Bacik  */
79637e3b48SJosef Bacik static inline void memmove_leaf_data(const struct extent_buffer *leaf,
80637e3b48SJosef Bacik 				     unsigned long dst_offset,
81637e3b48SJosef Bacik 				     unsigned long src_offset,
82637e3b48SJosef Bacik 				     unsigned long len)
83637e3b48SJosef Bacik {
848009adf3SJosef Bacik 	memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, 0) + dst_offset,
858009adf3SJosef Bacik 			      btrfs_item_nr_offset(leaf, 0) + src_offset, len);
86637e3b48SJosef Bacik }
87637e3b48SJosef Bacik 
88637e3b48SJosef Bacik /*
89637e3b48SJosef Bacik  * Copy item data from @src into @dst at the given @offset.
90637e3b48SJosef Bacik  *
91637e3b48SJosef Bacik  * @dst:	destination leaf that we're copying into
92637e3b48SJosef Bacik  * @src:	source leaf that we're copying from
93637e3b48SJosef Bacik  * @dst_offset:	item data offset we're copying to
94637e3b48SJosef Bacik  * @src_offset:	item data offset were' copying from
95637e3b48SJosef Bacik  * @len:	length of the data we're copying
96637e3b48SJosef Bacik  *
97637e3b48SJosef Bacik  * Wrapper around copy_extent_buffer() that takes into account the header on
98637e3b48SJosef Bacik  * the leaf.  The btrfs_item offset's start directly after the header, so we
99637e3b48SJosef Bacik  * have to adjust any offsets to account for the header in the leaf.  This
100637e3b48SJosef Bacik  * handles that math to simplify the callers.
101637e3b48SJosef Bacik  */
102637e3b48SJosef Bacik static inline void copy_leaf_data(const struct extent_buffer *dst,
103637e3b48SJosef Bacik 				  const struct extent_buffer *src,
104637e3b48SJosef Bacik 				  unsigned long dst_offset,
105637e3b48SJosef Bacik 				  unsigned long src_offset, unsigned long len)
106637e3b48SJosef Bacik {
1078009adf3SJosef Bacik 	copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, 0) + dst_offset,
1088009adf3SJosef Bacik 			   btrfs_item_nr_offset(src, 0) + src_offset, len);
109637e3b48SJosef Bacik }
110637e3b48SJosef Bacik 
111637e3b48SJosef Bacik /*
112637e3b48SJosef Bacik  * Move items in a @leaf (using memmove).
113637e3b48SJosef Bacik  *
114637e3b48SJosef Bacik  * @dst:	destination leaf for the items
115637e3b48SJosef Bacik  * @dst_item:	the item nr we're copying into
116637e3b48SJosef Bacik  * @src_item:	the item nr we're copying from
117637e3b48SJosef Bacik  * @nr_items:	the number of items to copy
118637e3b48SJosef Bacik  *
119637e3b48SJosef Bacik  * Wrapper around memmove_extent_buffer() that does the math to get the
120637e3b48SJosef Bacik  * appropriate offsets into the leaf from the item numbers.
121637e3b48SJosef Bacik  */
122637e3b48SJosef Bacik static inline void memmove_leaf_items(const struct extent_buffer *leaf,
123637e3b48SJosef Bacik 				      int dst_item, int src_item, int nr_items)
124637e3b48SJosef Bacik {
125637e3b48SJosef Bacik 	memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, dst_item),
126637e3b48SJosef Bacik 			      btrfs_item_nr_offset(leaf, src_item),
127637e3b48SJosef Bacik 			      nr_items * sizeof(struct btrfs_item));
128637e3b48SJosef Bacik }
129637e3b48SJosef Bacik 
130637e3b48SJosef Bacik /*
131637e3b48SJosef Bacik  * Copy items from @src into @dst at the given @offset.
132637e3b48SJosef Bacik  *
133637e3b48SJosef Bacik  * @dst:	destination leaf for the items
134637e3b48SJosef Bacik  * @src:	source leaf for the items
135637e3b48SJosef Bacik  * @dst_item:	the item nr we're copying into
136637e3b48SJosef Bacik  * @src_item:	the item nr we're copying from
137637e3b48SJosef Bacik  * @nr_items:	the number of items to copy
138637e3b48SJosef Bacik  *
139637e3b48SJosef Bacik  * Wrapper around copy_extent_buffer() that does the math to get the
140637e3b48SJosef Bacik  * appropriate offsets into the leaf from the item numbers.
141637e3b48SJosef Bacik  */
142637e3b48SJosef Bacik static inline void copy_leaf_items(const struct extent_buffer *dst,
143637e3b48SJosef Bacik 				   const struct extent_buffer *src,
144637e3b48SJosef Bacik 				   int dst_item, int src_item, int nr_items)
145637e3b48SJosef Bacik {
146637e3b48SJosef Bacik 	copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, dst_item),
147637e3b48SJosef Bacik 			      btrfs_item_nr_offset(src, src_item),
148637e3b48SJosef Bacik 			      nr_items * sizeof(struct btrfs_item));
149637e3b48SJosef Bacik }
150637e3b48SJosef Bacik 
151b3cbfb0dSJosef Bacik /* This exists for btrfs-progs usages. */
152b3cbfb0dSJosef Bacik u16 btrfs_csum_type_size(u16 type)
153b3cbfb0dSJosef Bacik {
154b3cbfb0dSJosef Bacik 	return btrfs_csums[type].size;
155b3cbfb0dSJosef Bacik }
156b3cbfb0dSJosef Bacik 
157af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
158af024ed2SJohannes Thumshirn {
159af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
160af024ed2SJohannes Thumshirn 	/*
161af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
162af024ed2SJohannes Thumshirn 	 */
163b3cbfb0dSJosef Bacik 	return btrfs_csum_type_size(t);
164af024ed2SJohannes Thumshirn }
165af024ed2SJohannes Thumshirn 
166af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
167af024ed2SJohannes Thumshirn {
168af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
169af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
170af024ed2SJohannes Thumshirn }
171af024ed2SJohannes Thumshirn 
172b4e967beSDavid Sterba /*
173b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
174b4e967beSDavid Sterba  * name
175b4e967beSDavid Sterba  */
176b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
177b4e967beSDavid Sterba {
178b4e967beSDavid Sterba 	/* csum type is validated at mount time */
17959a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
18059a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
181b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
182b4e967beSDavid Sterba }
183b4e967beSDavid Sterba 
184604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
185f7cea56cSDavid Sterba {
186f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
187f7cea56cSDavid Sterba }
188f7cea56cSDavid Sterba 
1892c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
1902c90e5d6SChris Mason {
191a4c853afSChenXiaoSong 	might_sleep();
192a4c853afSChenXiaoSong 
193e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
1942c90e5d6SChris Mason }
1952c90e5d6SChris Mason 
196d352ac68SChris Mason /* this also releases the path */
1972c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1982c90e5d6SChris Mason {
199ff175d57SJesper Juhl 	if (!p)
200ff175d57SJesper Juhl 		return;
201b3b4aa74SDavid Sterba 	btrfs_release_path(p);
2022c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
2032c90e5d6SChris Mason }
2042c90e5d6SChris Mason 
205d352ac68SChris Mason /*
206d352ac68SChris Mason  * path release drops references on the extent buffers in the path
207d352ac68SChris Mason  * and it drops any locks held by this path
208d352ac68SChris Mason  *
209d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
210d352ac68SChris Mason  */
211b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
212eb60ceacSChris Mason {
213eb60ceacSChris Mason 	int i;
214a2135011SChris Mason 
215234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
2163f157a2fSChris Mason 		p->slots[i] = 0;
217eb60ceacSChris Mason 		if (!p->nodes[i])
218925baeddSChris Mason 			continue;
219925baeddSChris Mason 		if (p->locks[i]) {
220bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
221925baeddSChris Mason 			p->locks[i] = 0;
222925baeddSChris Mason 		}
2235f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
2243f157a2fSChris Mason 		p->nodes[i] = NULL;
225eb60ceacSChris Mason 	}
226eb60ceacSChris Mason }
227eb60ceacSChris Mason 
228d352ac68SChris Mason /*
2298bb808c6SDavid Sterba  * We want the transaction abort to print stack trace only for errors where the
2308bb808c6SDavid Sterba  * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
2318bb808c6SDavid Sterba  * caused by external factors.
2328bb808c6SDavid Sterba  */
2338bb808c6SDavid Sterba bool __cold abort_should_print_stack(int errno)
2348bb808c6SDavid Sterba {
2358bb808c6SDavid Sterba 	switch (errno) {
2368bb808c6SDavid Sterba 	case -EIO:
2378bb808c6SDavid Sterba 	case -EROFS:
2388bb808c6SDavid Sterba 	case -ENOMEM:
2398bb808c6SDavid Sterba 		return false;
2408bb808c6SDavid Sterba 	}
2418bb808c6SDavid Sterba 	return true;
2428bb808c6SDavid Sterba }
2438bb808c6SDavid Sterba 
2448bb808c6SDavid Sterba /*
245d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
246d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
247d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
248d352ac68SChris Mason  * looping required.
249d352ac68SChris Mason  *
250d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
251d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
252d352ac68SChris Mason  * at any time because there are no locks held.
253d352ac68SChris Mason  */
254925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
255925baeddSChris Mason {
256925baeddSChris Mason 	struct extent_buffer *eb;
257240f62c8SChris Mason 
2583083ee2eSJosef Bacik 	while (1) {
259240f62c8SChris Mason 		rcu_read_lock();
260240f62c8SChris Mason 		eb = rcu_dereference(root->node);
2613083ee2eSJosef Bacik 
2623083ee2eSJosef Bacik 		/*
2633083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
26401327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
2653083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
2663083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
2673083ee2eSJosef Bacik 		 */
2683083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
269240f62c8SChris Mason 			rcu_read_unlock();
2703083ee2eSJosef Bacik 			break;
2713083ee2eSJosef Bacik 		}
2723083ee2eSJosef Bacik 		rcu_read_unlock();
2733083ee2eSJosef Bacik 		synchronize_rcu();
2743083ee2eSJosef Bacik 	}
275925baeddSChris Mason 	return eb;
276925baeddSChris Mason }
277925baeddSChris Mason 
27892a7cc42SQu Wenruo /*
27992a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
28092a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
28192a7cc42SQu Wenruo  * sure they get properly updated on disk.
282d352ac68SChris Mason  */
2830b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
2840b86a832SChris Mason {
2850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2860b246afaSJeff Mahoney 
287e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
288e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
289e7070be1SJosef Bacik 		return;
290e7070be1SJosef Bacik 
2910b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
292e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
293e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
2944fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
295e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
2960b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
297e7070be1SJosef Bacik 		else
298e7070be1SJosef Bacik 			list_move(&root->dirty_list,
2990b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
3000b86a832SChris Mason 	}
3010b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
3020b86a832SChris Mason }
3030b86a832SChris Mason 
304d352ac68SChris Mason /*
305d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
306d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
307d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
308d352ac68SChris Mason  */
309be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
310be20aa9dSChris Mason 		      struct btrfs_root *root,
311be20aa9dSChris Mason 		      struct extent_buffer *buf,
312be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
313be20aa9dSChris Mason {
3140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
315be20aa9dSChris Mason 	struct extent_buffer *cow;
316be20aa9dSChris Mason 	int ret = 0;
317be20aa9dSChris Mason 	int level;
3185d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
319be20aa9dSChris Mason 
32092a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
3210b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
32292a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
32327cdeb70SMiao Xie 		trans->transid != root->last_trans);
324be20aa9dSChris Mason 
325be20aa9dSChris Mason 	level = btrfs_header_level(buf);
3265d4f98a2SYan Zheng 	if (level == 0)
3275d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
3285d4f98a2SYan Zheng 	else
3295d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
33031840ae1SZheng Yan 
3314d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
332cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
333cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
3345d4f98a2SYan Zheng 	if (IS_ERR(cow))
335be20aa9dSChris Mason 		return PTR_ERR(cow);
336be20aa9dSChris Mason 
33758e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
338be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
339be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
3405d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
3415d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
3425d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
3435d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
3445d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
3455d4f98a2SYan Zheng 	else
346be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
347be20aa9dSChris Mason 
348de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
3492b82032cSYan Zheng 
350be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
3515d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
352e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
3535d4f98a2SYan Zheng 	else
354e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
355867ed321SJosef Bacik 	if (ret) {
35672c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
35772c9925fSFilipe Manana 		free_extent_buffer(cow);
358867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
359be20aa9dSChris Mason 		return ret;
360867ed321SJosef Bacik 	}
361be20aa9dSChris Mason 
362be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
363be20aa9dSChris Mason 	*cow_ret = cow;
364be20aa9dSChris Mason 	return 0;
365be20aa9dSChris Mason }
366be20aa9dSChris Mason 
367d352ac68SChris Mason /*
3685d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
3695d4f98a2SYan Zheng  */
3705d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
3715d4f98a2SYan Zheng 			      struct extent_buffer *buf)
3725d4f98a2SYan Zheng {
3735d4f98a2SYan Zheng 	/*
37492a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
37592a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
37692a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
3775d4f98a2SYan Zheng 	 */
37892a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
3795d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
3805d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
3815d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
3825d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
3835d4f98a2SYan Zheng 		return 1;
384a79865c6SNikolay Borisov 
3855d4f98a2SYan Zheng 	return 0;
3865d4f98a2SYan Zheng }
3875d4f98a2SYan Zheng 
3885d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
3895d4f98a2SYan Zheng 				       struct btrfs_root *root,
3905d4f98a2SYan Zheng 				       struct extent_buffer *buf,
391f0486c68SYan, Zheng 				       struct extent_buffer *cow,
392f0486c68SYan, Zheng 				       int *last_ref)
3935d4f98a2SYan Zheng {
3940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3955d4f98a2SYan Zheng 	u64 refs;
3965d4f98a2SYan Zheng 	u64 owner;
3975d4f98a2SYan Zheng 	u64 flags;
3985d4f98a2SYan Zheng 	u64 new_flags = 0;
3995d4f98a2SYan Zheng 	int ret;
4005d4f98a2SYan Zheng 
4015d4f98a2SYan Zheng 	/*
4025d4f98a2SYan Zheng 	 * Backrefs update rules:
4035d4f98a2SYan Zheng 	 *
4045d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
4055d4f98a2SYan Zheng 	 * allocated by tree relocation.
4065d4f98a2SYan Zheng 	 *
4075d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
4085d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
4095d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
4105d4f98a2SYan Zheng 	 *
4115d4f98a2SYan Zheng 	 * If a tree block is been relocating
4125d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
4135d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
4145d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
4155d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
4165d4f98a2SYan Zheng 	 */
4175d4f98a2SYan Zheng 
4185d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
4192ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
4203173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
4213173a18fSJosef Bacik 					       &refs, &flags);
422be1a5564SMark Fasheh 		if (ret)
423be1a5564SMark Fasheh 			return ret;
424e5df9573SMark Fasheh 		if (refs == 0) {
425e5df9573SMark Fasheh 			ret = -EROFS;
4260b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
427e5df9573SMark Fasheh 			return ret;
428e5df9573SMark Fasheh 		}
4295d4f98a2SYan Zheng 	} else {
4305d4f98a2SYan Zheng 		refs = 1;
4315d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4325d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4335d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
4345d4f98a2SYan Zheng 		else
4355d4f98a2SYan Zheng 			flags = 0;
4365d4f98a2SYan Zheng 	}
4375d4f98a2SYan Zheng 
4385d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
4395d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
4405d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
4415d4f98a2SYan Zheng 
4425d4f98a2SYan Zheng 	if (refs > 1) {
4435d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
4445d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
4455d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
446e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
447692826b2SJeff Mahoney 			if (ret)
448692826b2SJeff Mahoney 				return ret;
4495d4f98a2SYan Zheng 
4505d4f98a2SYan Zheng 			if (root->root_key.objectid ==
4515d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
452e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
453692826b2SJeff Mahoney 				if (ret)
454692826b2SJeff Mahoney 					return ret;
455e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
456692826b2SJeff Mahoney 				if (ret)
457692826b2SJeff Mahoney 					return ret;
4585d4f98a2SYan Zheng 			}
4595d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4605d4f98a2SYan Zheng 		} else {
4615d4f98a2SYan Zheng 
4625d4f98a2SYan Zheng 			if (root->root_key.objectid ==
4635d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
464e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
4655d4f98a2SYan Zheng 			else
466e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
467692826b2SJeff Mahoney 			if (ret)
468692826b2SJeff Mahoney 				return ret;
4695d4f98a2SYan Zheng 		}
4705d4f98a2SYan Zheng 		if (new_flags != 0) {
4714aec05faSJosef Bacik 			ret = btrfs_set_disk_extent_flags(trans, buf, new_flags);
472be1a5564SMark Fasheh 			if (ret)
473be1a5564SMark Fasheh 				return ret;
4745d4f98a2SYan Zheng 		}
4755d4f98a2SYan Zheng 	} else {
4765d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
4775d4f98a2SYan Zheng 			if (root->root_key.objectid ==
4785d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
479e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
4805d4f98a2SYan Zheng 			else
481e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
482692826b2SJeff Mahoney 			if (ret)
483692826b2SJeff Mahoney 				return ret;
484e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
485692826b2SJeff Mahoney 			if (ret)
486692826b2SJeff Mahoney 				return ret;
4875d4f98a2SYan Zheng 		}
488190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, buf);
489f0486c68SYan, Zheng 		*last_ref = 1;
4905d4f98a2SYan Zheng 	}
4915d4f98a2SYan Zheng 	return 0;
4925d4f98a2SYan Zheng }
4935d4f98a2SYan Zheng 
4945d4f98a2SYan Zheng /*
495d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
496d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
497d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
498d397712bSChris Mason  * dirty again.
499d352ac68SChris Mason  *
500d352ac68SChris Mason  * search_start -- an allocation hint for the new block
501d352ac68SChris Mason  *
502d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
503d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
504d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
505d352ac68SChris Mason  */
506d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
5075f39d397SChris Mason 			     struct btrfs_root *root,
5085f39d397SChris Mason 			     struct extent_buffer *buf,
5095f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
5105f39d397SChris Mason 			     struct extent_buffer **cow_ret,
5119631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
5129631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
5136702ed49SChris Mason {
5140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5155d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
5165f39d397SChris Mason 	struct extent_buffer *cow;
517be1a5564SMark Fasheh 	int level, ret;
518f0486c68SYan, Zheng 	int last_ref = 0;
519925baeddSChris Mason 	int unlock_orig = 0;
5200f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
5216702ed49SChris Mason 
522925baeddSChris Mason 	if (*cow_ret == buf)
523925baeddSChris Mason 		unlock_orig = 1;
524925baeddSChris Mason 
52549d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
526925baeddSChris Mason 
52792a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
5280b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
52992a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
53027cdeb70SMiao Xie 		trans->transid != root->last_trans);
5315f39d397SChris Mason 
5327bb86316SChris Mason 	level = btrfs_header_level(buf);
53331840ae1SZheng Yan 
5345d4f98a2SYan Zheng 	if (level == 0)
5355d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
5365d4f98a2SYan Zheng 	else
5375d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
5385d4f98a2SYan Zheng 
5390f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
5405d4f98a2SYan Zheng 		parent_start = parent->start;
5415d4f98a2SYan Zheng 
54279bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
54379bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
54479bd3712SFilipe Manana 				     search_start, empty_size, nest);
5456702ed49SChris Mason 	if (IS_ERR(cow))
5466702ed49SChris Mason 		return PTR_ERR(cow);
5476702ed49SChris Mason 
548b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
549b4ce94deSChris Mason 
55058e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
551db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
5525f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
5535d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
5545d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
5555d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
5565d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
5575d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
5585d4f98a2SYan Zheng 	else
5595f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
5606702ed49SChris Mason 
561de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
5622b82032cSYan Zheng 
563be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
564b68dc2a9SMark Fasheh 	if (ret) {
565572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
566572c83acSJosef Bacik 		free_extent_buffer(cow);
56766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
568b68dc2a9SMark Fasheh 		return ret;
569b68dc2a9SMark Fasheh 	}
5701a40e23bSZheng Yan 
57192a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
57283d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
57393314e3bSZhaolei 		if (ret) {
574572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
575572c83acSJosef Bacik 			free_extent_buffer(cow);
57666642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
57783d4cfd4SJosef Bacik 			return ret;
57883d4cfd4SJosef Bacik 		}
57993314e3bSZhaolei 	}
5803fd0a558SYan, Zheng 
5816702ed49SChris Mason 	if (buf == root->node) {
582925baeddSChris Mason 		WARN_ON(parent && parent != buf);
5835d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
5845d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
5855d4f98a2SYan Zheng 			parent_start = buf->start;
586925baeddSChris Mason 
58767439dadSDavid Sterba 		atomic_inc(&cow->refs);
588406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
589d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
590240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
591925baeddSChris Mason 
5927a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
5937a163608SFilipe Manana 				      parent_start, last_ref);
5945f39d397SChris Mason 		free_extent_buffer(buf);
5950b86a832SChris Mason 		add_root_to_dirty_list(root);
5966702ed49SChris Mason 	} else {
5975d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
598d09c5152SFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, parent_slot,
59933cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
600d09c5152SFilipe Manana 		if (ret) {
601d09c5152SFilipe Manana 			btrfs_tree_unlock(cow);
602d09c5152SFilipe Manana 			free_extent_buffer(cow);
603d09c5152SFilipe Manana 			btrfs_abort_transaction(trans, ret);
604d09c5152SFilipe Manana 			return ret;
605d09c5152SFilipe Manana 		}
6065f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
607db94535dSChris Mason 					cow->start);
60874493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
60974493f7aSChris Mason 					      trans->transid);
6106702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
6115de865eeSFilipe David Borba Manana 		if (last_ref) {
612f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
6135de865eeSFilipe David Borba Manana 			if (ret) {
614572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
615572c83acSJosef Bacik 				free_extent_buffer(cow);
61666642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
6175de865eeSFilipe David Borba Manana 				return ret;
6185de865eeSFilipe David Borba Manana 			}
6195de865eeSFilipe David Borba Manana 		}
6207a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
6217a163608SFilipe Manana 				      parent_start, last_ref);
6226702ed49SChris Mason 	}
623925baeddSChris Mason 	if (unlock_orig)
624925baeddSChris Mason 		btrfs_tree_unlock(buf);
6253083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
6266702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
6276702ed49SChris Mason 	*cow_ret = cow;
6286702ed49SChris Mason 	return 0;
6296702ed49SChris Mason }
6306702ed49SChris Mason 
6315d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
6325d4f98a2SYan Zheng 				   struct btrfs_root *root,
6335d4f98a2SYan Zheng 				   struct extent_buffer *buf)
6345d4f98a2SYan Zheng {
635f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
636faa2dbf0SJosef Bacik 		return 0;
637fccb84c9SDavid Sterba 
638d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
639d1980131SDavid Sterba 	smp_mb__before_atomic();
640f1ebcc74SLiu Bo 
641f1ebcc74SLiu Bo 	/*
642f1ebcc74SLiu Bo 	 * We do not need to cow a block if
643f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
644f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
645f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
646f1ebcc74SLiu Bo 	 *
647f1ebcc74SLiu Bo 	 * What is forced COW:
64801327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
64952042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
650f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
651f1ebcc74SLiu Bo 	 */
6525d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
6535d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
6545d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
655f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
65627cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
6575d4f98a2SYan Zheng 		return 0;
6585d4f98a2SYan Zheng 	return 1;
6595d4f98a2SYan Zheng }
6605d4f98a2SYan Zheng 
661d352ac68SChris Mason /*
662d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
66301327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
664d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
665d352ac68SChris Mason  */
666d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
6675f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
6685f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
6699631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
6709631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
67102217ed2SChris Mason {
6720b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6736702ed49SChris Mason 	u64 search_start;
674f510cfecSChris Mason 	int ret;
675dc17ff8fSChris Mason 
67683354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
67783354f07SJosef Bacik 		btrfs_err(fs_info,
67883354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
67983354f07SJosef Bacik 
6800b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
68131b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
682c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
6830b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
68431b1a2bdSJulia Lawall 
6850b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
68631b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
6870b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
688dc17ff8fSChris Mason 
6895d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
69002217ed2SChris Mason 		*cow_ret = buf;
69102217ed2SChris Mason 		return 0;
69202217ed2SChris Mason 	}
693c487685dSChris Mason 
694ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
695b4ce94deSChris Mason 
696f616f5cdSQu Wenruo 	/*
697f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
698f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
699f616f5cdSQu Wenruo 	 *
700f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
701f616f5cdSQu Wenruo 	 */
702f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
703f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
7049631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
7051abe9b8aSliubo 
7061abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
7071abe9b8aSliubo 
708f510cfecSChris Mason 	return ret;
7092c90e5d6SChris Mason }
710f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
7116702ed49SChris Mason 
712d352ac68SChris Mason /*
713d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
714d352ac68SChris Mason  * node are actually close by
715d352ac68SChris Mason  */
7166b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
7176702ed49SChris Mason {
7186b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
7196702ed49SChris Mason 		return 1;
7206b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
7216702ed49SChris Mason 		return 1;
72202217ed2SChris Mason 	return 0;
72302217ed2SChris Mason }
72402217ed2SChris Mason 
725ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
726ce6ef5abSDavid Sterba 
727ce6ef5abSDavid Sterba /*
728ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
729ce6ef5abSDavid Sterba  * we can avoid the conversion.
730ce6ef5abSDavid Sterba  */
731ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
732ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
733ce6ef5abSDavid Sterba {
734ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
735ce6ef5abSDavid Sterba 
736ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
737ce6ef5abSDavid Sterba }
738ce6ef5abSDavid Sterba 
739ce6ef5abSDavid Sterba #else
740ce6ef5abSDavid Sterba 
741081e9573SChris Mason /*
742081e9573SChris Mason  * compare two keys in a memcmp fashion
743081e9573SChris Mason  */
744310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
745310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
746081e9573SChris Mason {
747081e9573SChris Mason 	struct btrfs_key k1;
748081e9573SChris Mason 
749081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
750081e9573SChris Mason 
75120736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
752081e9573SChris Mason }
753ce6ef5abSDavid Sterba #endif
754081e9573SChris Mason 
755f3465ca4SJosef Bacik /*
756f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
757f3465ca4SJosef Bacik  */
758e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
759f3465ca4SJosef Bacik {
760f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
761f3465ca4SJosef Bacik 		return 1;
762f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
763f3465ca4SJosef Bacik 		return -1;
764f3465ca4SJosef Bacik 	if (k1->type > k2->type)
765f3465ca4SJosef Bacik 		return 1;
766f3465ca4SJosef Bacik 	if (k1->type < k2->type)
767f3465ca4SJosef Bacik 		return -1;
768f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
769f3465ca4SJosef Bacik 		return 1;
770f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
771f3465ca4SJosef Bacik 		return -1;
772f3465ca4SJosef Bacik 	return 0;
773f3465ca4SJosef Bacik }
774081e9573SChris Mason 
775d352ac68SChris Mason /*
776d352ac68SChris Mason  * this is used by the defrag code to go through all the
777d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
778d352ac68SChris Mason  * disk order is close to key order
779d352ac68SChris Mason  */
7806702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
7815f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
782de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
783a6b6e75eSChris Mason 		       struct btrfs_key *progress)
7846702ed49SChris Mason {
7850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
7866b80053dSChris Mason 	struct extent_buffer *cur;
7876702ed49SChris Mason 	u64 blocknr;
788e9d0b13bSChris Mason 	u64 search_start = *last_ret;
789e9d0b13bSChris Mason 	u64 last_block = 0;
7906702ed49SChris Mason 	u64 other;
7916702ed49SChris Mason 	u32 parent_nritems;
7926702ed49SChris Mason 	int end_slot;
7936702ed49SChris Mason 	int i;
7946702ed49SChris Mason 	int err = 0;
7956b80053dSChris Mason 	u32 blocksize;
796081e9573SChris Mason 	int progress_passed = 0;
797081e9573SChris Mason 	struct btrfs_disk_key disk_key;
7986702ed49SChris Mason 
7990b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
8000b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
80186479a04SChris Mason 
8026b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
8030b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
8045dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
8056702ed49SChris Mason 
8065dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
8076702ed49SChris Mason 		return 0;
8086702ed49SChris Mason 
8095dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
8106702ed49SChris Mason 		int close = 1;
811a6b6e75eSChris Mason 
812081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
813081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
814081e9573SChris Mason 			continue;
815081e9573SChris Mason 
816081e9573SChris Mason 		progress_passed = 1;
8176b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
818e9d0b13bSChris Mason 		if (last_block == 0)
819e9d0b13bSChris Mason 			last_block = blocknr;
8205708b959SChris Mason 
8216702ed49SChris Mason 		if (i > 0) {
8226b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
8236b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
8246702ed49SChris Mason 		}
8255dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
8266b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
8276b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
8286702ed49SChris Mason 		}
829e9d0b13bSChris Mason 		if (close) {
830e9d0b13bSChris Mason 			last_block = blocknr;
8316702ed49SChris Mason 			continue;
832e9d0b13bSChris Mason 		}
8336702ed49SChris Mason 
834206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
835206983b7SJosef Bacik 		if (IS_ERR(cur))
83664c043deSLiu Bo 			return PTR_ERR(cur);
837e9d0b13bSChris Mason 		if (search_start == 0)
8386b80053dSChris Mason 			search_start = last_block;
839e9d0b13bSChris Mason 
840e7a84565SChris Mason 		btrfs_tree_lock(cur);
8416b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
842e7a84565SChris Mason 					&cur, search_start,
8436b80053dSChris Mason 					min(16 * blocksize,
8449631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
8459631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
846252c38f0SYan 		if (err) {
847e7a84565SChris Mason 			btrfs_tree_unlock(cur);
8486b80053dSChris Mason 			free_extent_buffer(cur);
8496702ed49SChris Mason 			break;
850252c38f0SYan 		}
851e7a84565SChris Mason 		search_start = cur->start;
852e7a84565SChris Mason 		last_block = cur->start;
853f2183bdeSChris Mason 		*last_ret = search_start;
854e7a84565SChris Mason 		btrfs_tree_unlock(cur);
855e7a84565SChris Mason 		free_extent_buffer(cur);
8566702ed49SChris Mason 	}
8576702ed49SChris Mason 	return err;
8586702ed49SChris Mason }
8596702ed49SChris Mason 
86074123bd7SChris Mason /*
861fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
8625f39d397SChris Mason  *
863a724f313SFilipe Manana  * The lower boundary for the search is specified by the slot number @first_slot.
864fdf8d595SAnand Jain  * Use a value of 0 to search over the whole extent buffer. Works for both
865fdf8d595SAnand Jain  * leaves and nodes.
86674123bd7SChris Mason  *
867fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
868fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
869fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
870fb81212cSFilipe Manana  *
871fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
872fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
87374123bd7SChris Mason  */
874fdf8d595SAnand Jain int btrfs_bin_search(struct extent_buffer *eb, int first_slot,
87567d5e289SMarcos Paulo de Souza 		     const struct btrfs_key *key, int *slot)
876be0e5c09SChris Mason {
877fb81212cSFilipe Manana 	unsigned long p;
878fb81212cSFilipe Manana 	int item_size;
879a724f313SFilipe Manana 	/*
880a724f313SFilipe Manana 	 * Use unsigned types for the low and high slots, so that we get a more
881a724f313SFilipe Manana 	 * efficient division in the search loop below.
882a724f313SFilipe Manana 	 */
883a724f313SFilipe Manana 	u32 low = first_slot;
884a724f313SFilipe Manana 	u32 high = btrfs_header_nritems(eb);
885be0e5c09SChris Mason 	int ret;
8865cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
887be0e5c09SChris Mason 
888a724f313SFilipe Manana 	if (unlikely(low > high)) {
8895e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
890a724f313SFilipe Manana 		 "%s: low (%u) > high (%u) eb %llu owner %llu level %d",
8915e24e9afSLiu Bo 			  __func__, low, high, eb->start,
8925e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
8935e24e9afSLiu Bo 		return -EINVAL;
8945e24e9afSLiu Bo 	}
8955e24e9afSLiu Bo 
896fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
897fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
898fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
899fb81212cSFilipe Manana 	} else {
900fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
901fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
902fb81212cSFilipe Manana 	}
903fb81212cSFilipe Manana 
904be0e5c09SChris Mason 	while (low < high) {
9055cd17f34SDavid Sterba 		unsigned long oip;
9065cd17f34SDavid Sterba 		unsigned long offset;
9075cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
9085cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
9095cd17f34SDavid Sterba 		int mid;
9105cd17f34SDavid Sterba 
911be0e5c09SChris Mason 		mid = (low + high) / 2;
9125f39d397SChris Mason 		offset = p + mid * item_size;
9135cd17f34SDavid Sterba 		oip = offset_in_page(offset);
9145f39d397SChris Mason 
9155cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
916884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
9175cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
918934d375bSChris Mason 
919884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
9205cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
9215cd17f34SDavid Sterba 		} else {
9225cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
9235f39d397SChris Mason 			tmp = &unaligned;
924479965d6SChris Mason 		}
925479965d6SChris Mason 
926be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
927be0e5c09SChris Mason 
928be0e5c09SChris Mason 		if (ret < 0)
929be0e5c09SChris Mason 			low = mid + 1;
930be0e5c09SChris Mason 		else if (ret > 0)
931be0e5c09SChris Mason 			high = mid;
932be0e5c09SChris Mason 		else {
933be0e5c09SChris Mason 			*slot = mid;
934be0e5c09SChris Mason 			return 0;
935be0e5c09SChris Mason 		}
936be0e5c09SChris Mason 	}
937be0e5c09SChris Mason 	*slot = low;
938be0e5c09SChris Mason 	return 1;
939be0e5c09SChris Mason }
940be0e5c09SChris Mason 
941f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
942f0486c68SYan, Zheng {
943f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
944f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
945f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
946f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
947f0486c68SYan, Zheng }
948f0486c68SYan, Zheng 
949f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
950f0486c68SYan, Zheng {
951f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
952f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
953f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
954f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
955f0486c68SYan, Zheng }
956f0486c68SYan, Zheng 
957d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
958d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
959d352ac68SChris Mason  */
9604b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
9614b231ae4SDavid Sterba 					   int slot)
962bb803951SChris Mason {
963ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
964789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
965416bc658SJosef Bacik 	struct extent_buffer *eb;
966416bc658SJosef Bacik 
967fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
968fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
969ca7a79adSChris Mason 
970d4694728SJosef Bacik 	ASSERT(level);
971ca7a79adSChris Mason 
972789d6a3aSQu Wenruo 	check.level = level - 1;
973789d6a3aSQu Wenruo 	check.transid = btrfs_node_ptr_generation(parent, slot);
974789d6a3aSQu Wenruo 	check.owner_root = btrfs_header_owner(parent);
975789d6a3aSQu Wenruo 	check.has_first_key = true;
976789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(parent, &check.first_key, slot);
977789d6a3aSQu Wenruo 
978d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
979789d6a3aSQu Wenruo 			     &check);
9804eb150d6SQu Wenruo 	if (IS_ERR(eb))
9814eb150d6SQu Wenruo 		return eb;
9824eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
983416bc658SJosef Bacik 		free_extent_buffer(eb);
9844eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
985416bc658SJosef Bacik 	}
986416bc658SJosef Bacik 
987416bc658SJosef Bacik 	return eb;
988bb803951SChris Mason }
989bb803951SChris Mason 
990d352ac68SChris Mason /*
991d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
992d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
993d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
994d352ac68SChris Mason  */
995e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
99698ed5174SChris Mason 			 struct btrfs_root *root,
99798ed5174SChris Mason 			 struct btrfs_path *path, int level)
998bb803951SChris Mason {
9990b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10005f39d397SChris Mason 	struct extent_buffer *right = NULL;
10015f39d397SChris Mason 	struct extent_buffer *mid;
10025f39d397SChris Mason 	struct extent_buffer *left = NULL;
10035f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1004bb803951SChris Mason 	int ret = 0;
1005bb803951SChris Mason 	int wret;
1006bb803951SChris Mason 	int pslot;
1007bb803951SChris Mason 	int orig_slot = path->slots[level];
100879f95c82SChris Mason 	u64 orig_ptr;
1009bb803951SChris Mason 
101098e6b1ebSLiu Bo 	ASSERT(level > 0);
1011bb803951SChris Mason 
10125f39d397SChris Mason 	mid = path->nodes[level];
1013b4ce94deSChris Mason 
1014ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
10157bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
10167bb86316SChris Mason 
10171d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
101879f95c82SChris Mason 
1019a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
10205f39d397SChris Mason 		parent = path->nodes[level + 1];
1021bb803951SChris Mason 		pslot = path->slots[level + 1];
1022a05a9bb1SLi Zefan 	}
1023bb803951SChris Mason 
102440689478SChris Mason 	/*
102540689478SChris Mason 	 * deal with the case where there is only one pointer in the root
102640689478SChris Mason 	 * by promoting the node below to a root
102740689478SChris Mason 	 */
10285f39d397SChris Mason 	if (!parent) {
10295f39d397SChris Mason 		struct extent_buffer *child;
1030bb803951SChris Mason 
10315f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1032bb803951SChris Mason 			return 0;
1033bb803951SChris Mason 
1034bb803951SChris Mason 		/* promote the child to a root */
10354b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1036fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1037fb770ae4SLiu Bo 			ret = PTR_ERR(child);
10380b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1039305a26afSMark Fasheh 			goto enospc;
1040305a26afSMark Fasheh 		}
1041305a26afSMark Fasheh 
1042925baeddSChris Mason 		btrfs_tree_lock(child);
10439631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
10449631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
1045f0486c68SYan, Zheng 		if (ret) {
1046f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1047f0486c68SYan, Zheng 			free_extent_buffer(child);
1048f0486c68SYan, Zheng 			goto enospc;
1049f0486c68SYan, Zheng 		}
10502f375ab9SYan 
1051406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
1052d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
1053240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1054925baeddSChris Mason 
10550b86a832SChris Mason 		add_root_to_dirty_list(root);
1056925baeddSChris Mason 		btrfs_tree_unlock(child);
1057b4ce94deSChris Mason 
1058925baeddSChris Mason 		path->locks[level] = 0;
1059bb803951SChris Mason 		path->nodes[level] = NULL;
1060190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, mid);
1061925baeddSChris Mason 		btrfs_tree_unlock(mid);
1062bb803951SChris Mason 		/* once for the path */
10635f39d397SChris Mason 		free_extent_buffer(mid);
1064f0486c68SYan, Zheng 
1065f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10667a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1067bb803951SChris Mason 		/* once for the root ptr */
10683083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1069f0486c68SYan, Zheng 		return 0;
1070bb803951SChris Mason 	}
10715f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
10720b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1073bb803951SChris Mason 		return 0;
1074bb803951SChris Mason 
10759cf14029SJosef Bacik 	if (pslot) {
10764b231ae4SDavid Sterba 		left = btrfs_read_node_slot(parent, pslot - 1);
10779cf14029SJosef Bacik 		if (IS_ERR(left)) {
10789cf14029SJosef Bacik 			ret = PTR_ERR(left);
1079fb770ae4SLiu Bo 			left = NULL;
10809cf14029SJosef Bacik 			goto enospc;
10819cf14029SJosef Bacik 		}
1082fb770ae4SLiu Bo 
1083bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
10845f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
10859631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
1086bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
108754aa1f4dSChris Mason 		if (wret) {
108854aa1f4dSChris Mason 			ret = wret;
108954aa1f4dSChris Mason 			goto enospc;
109054aa1f4dSChris Mason 		}
10912cc58cf2SChris Mason 	}
1092fb770ae4SLiu Bo 
10939cf14029SJosef Bacik 	if (pslot + 1 < btrfs_header_nritems(parent)) {
10944b231ae4SDavid Sterba 		right = btrfs_read_node_slot(parent, pslot + 1);
10959cf14029SJosef Bacik 		if (IS_ERR(right)) {
10969cf14029SJosef Bacik 			ret = PTR_ERR(right);
1097fb770ae4SLiu Bo 			right = NULL;
10989cf14029SJosef Bacik 			goto enospc;
10999cf14029SJosef Bacik 		}
1100fb770ae4SLiu Bo 
1101bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
11025f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
11039631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
1104bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
11052cc58cf2SChris Mason 		if (wret) {
11062cc58cf2SChris Mason 			ret = wret;
11072cc58cf2SChris Mason 			goto enospc;
11082cc58cf2SChris Mason 		}
11092cc58cf2SChris Mason 	}
11102cc58cf2SChris Mason 
11112cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
11125f39d397SChris Mason 	if (left) {
11135f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1114d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
111579f95c82SChris Mason 		if (wret < 0)
111679f95c82SChris Mason 			ret = wret;
1117bb803951SChris Mason 	}
111879f95c82SChris Mason 
111979f95c82SChris Mason 	/*
112079f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
112179f95c82SChris Mason 	 */
11225f39d397SChris Mason 	if (right) {
1123d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
112454aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
112579f95c82SChris Mason 			ret = wret;
11265f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
1127190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, right);
1128925baeddSChris Mason 			btrfs_tree_unlock(right);
1129016f9d0bSJosef Bacik 			btrfs_del_ptr(root, path, level + 1, pslot + 1);
1130f0486c68SYan, Zheng 			root_sub_used(root, right->len);
11317a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
11327a163608SFilipe Manana 					      0, 1);
11333083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1134f0486c68SYan, Zheng 			right = NULL;
1135bb803951SChris Mason 		} else {
11365f39d397SChris Mason 			struct btrfs_disk_key right_key;
11375f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1138f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
113933cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
11400e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11415f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
11425f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1143bb803951SChris Mason 		}
1144bb803951SChris Mason 	}
11455f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
114679f95c82SChris Mason 		/*
114779f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
114879f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
114979f95c82SChris Mason 		 * could try to delete the only pointer in this node.
115079f95c82SChris Mason 		 * So, pull some keys from the left.
115179f95c82SChris Mason 		 * There has to be a left pointer at this point because
115279f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
115379f95c82SChris Mason 		 * right
115479f95c82SChris Mason 		 */
1155305a26afSMark Fasheh 		if (!left) {
1156305a26afSMark Fasheh 			ret = -EROFS;
11570b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1158305a26afSMark Fasheh 			goto enospc;
1159305a26afSMark Fasheh 		}
116055d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
116154aa1f4dSChris Mason 		if (wret < 0) {
116279f95c82SChris Mason 			ret = wret;
116354aa1f4dSChris Mason 			goto enospc;
116454aa1f4dSChris Mason 		}
1165bce4eae9SChris Mason 		if (wret == 1) {
1166d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1167bce4eae9SChris Mason 			if (wret < 0)
1168bce4eae9SChris Mason 				ret = wret;
1169bce4eae9SChris Mason 		}
117079f95c82SChris Mason 		BUG_ON(wret == 1);
117179f95c82SChris Mason 	}
11725f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
1173190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, mid);
1174925baeddSChris Mason 		btrfs_tree_unlock(mid);
1175016f9d0bSJosef Bacik 		btrfs_del_ptr(root, path, level + 1, pslot);
1176f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
11777a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
11783083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1179f0486c68SYan, Zheng 		mid = NULL;
118079f95c82SChris Mason 	} else {
118179f95c82SChris Mason 		/* update the parent key to reflect our changes */
11825f39d397SChris Mason 		struct btrfs_disk_key mid_key;
11835f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1184f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
118533cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
11860e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
11875f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
11885f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
118979f95c82SChris Mason 	}
1190bb803951SChris Mason 
119179f95c82SChris Mason 	/* update the path */
11925f39d397SChris Mason 	if (left) {
11935f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
119467439dadSDavid Sterba 			atomic_inc(&left->refs);
1195925baeddSChris Mason 			/* left was locked after cow */
11965f39d397SChris Mason 			path->nodes[level] = left;
1197bb803951SChris Mason 			path->slots[level + 1] -= 1;
1198bb803951SChris Mason 			path->slots[level] = orig_slot;
1199925baeddSChris Mason 			if (mid) {
1200925baeddSChris Mason 				btrfs_tree_unlock(mid);
12015f39d397SChris Mason 				free_extent_buffer(mid);
1202925baeddSChris Mason 			}
1203bb803951SChris Mason 		} else {
12045f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1205bb803951SChris Mason 			path->slots[level] = orig_slot;
1206bb803951SChris Mason 		}
1207bb803951SChris Mason 	}
120879f95c82SChris Mason 	/* double check we haven't messed things up */
1209e20d96d6SChris Mason 	if (orig_ptr !=
12105f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
121179f95c82SChris Mason 		BUG();
121254aa1f4dSChris Mason enospc:
1213925baeddSChris Mason 	if (right) {
1214925baeddSChris Mason 		btrfs_tree_unlock(right);
12155f39d397SChris Mason 		free_extent_buffer(right);
1216925baeddSChris Mason 	}
1217925baeddSChris Mason 	if (left) {
1218925baeddSChris Mason 		if (path->nodes[level] != left)
1219925baeddSChris Mason 			btrfs_tree_unlock(left);
12205f39d397SChris Mason 		free_extent_buffer(left);
1221925baeddSChris Mason 	}
1222bb803951SChris Mason 	return ret;
1223bb803951SChris Mason }
1224bb803951SChris Mason 
1225d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1226d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1227d352ac68SChris Mason  * have to be pessimistic.
1228d352ac68SChris Mason  */
1229d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1230e66f709bSChris Mason 					  struct btrfs_root *root,
1231e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1232e66f709bSChris Mason {
12330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12345f39d397SChris Mason 	struct extent_buffer *right = NULL;
12355f39d397SChris Mason 	struct extent_buffer *mid;
12365f39d397SChris Mason 	struct extent_buffer *left = NULL;
12375f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1238e66f709bSChris Mason 	int ret = 0;
1239e66f709bSChris Mason 	int wret;
1240e66f709bSChris Mason 	int pslot;
1241e66f709bSChris Mason 	int orig_slot = path->slots[level];
1242e66f709bSChris Mason 
1243e66f709bSChris Mason 	if (level == 0)
1244e66f709bSChris Mason 		return 1;
1245e66f709bSChris Mason 
12465f39d397SChris Mason 	mid = path->nodes[level];
12477bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1248e66f709bSChris Mason 
1249a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
12505f39d397SChris Mason 		parent = path->nodes[level + 1];
1251e66f709bSChris Mason 		pslot = path->slots[level + 1];
1252a05a9bb1SLi Zefan 	}
1253e66f709bSChris Mason 
12545f39d397SChris Mason 	if (!parent)
1255e66f709bSChris Mason 		return 1;
1256e66f709bSChris Mason 
12579cf14029SJosef Bacik 	/* first, try to make some room in the middle buffer */
12589cf14029SJosef Bacik 	if (pslot) {
12599cf14029SJosef Bacik 		u32 left_nr;
12609cf14029SJosef Bacik 
12614b231ae4SDavid Sterba 		left = btrfs_read_node_slot(parent, pslot - 1);
1262fb770ae4SLiu Bo 		if (IS_ERR(left))
12639cf14029SJosef Bacik 			return PTR_ERR(left);
1264925baeddSChris Mason 
1265bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1266b4ce94deSChris Mason 
12675f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
12680b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
126933ade1f8SChris Mason 			wret = 1;
127033ade1f8SChris Mason 		} else {
12715f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
12729631e4ccSJosef Bacik 					      pslot - 1, &left,
1273bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
127454aa1f4dSChris Mason 			if (ret)
127554aa1f4dSChris Mason 				wret = 1;
127654aa1f4dSChris Mason 			else {
1277d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
127854aa1f4dSChris Mason 			}
127933ade1f8SChris Mason 		}
1280e66f709bSChris Mason 		if (wret < 0)
1281e66f709bSChris Mason 			ret = wret;
1282e66f709bSChris Mason 		if (wret == 0) {
12835f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1284e66f709bSChris Mason 			orig_slot += left_nr;
12855f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1286f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
128733cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
12880e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
12895f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
12905f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12915f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
12925f39d397SChris Mason 				path->nodes[level] = left;
1293e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1294e66f709bSChris Mason 				path->slots[level] = orig_slot;
1295925baeddSChris Mason 				btrfs_tree_unlock(mid);
12965f39d397SChris Mason 				free_extent_buffer(mid);
1297e66f709bSChris Mason 			} else {
1298e66f709bSChris Mason 				orig_slot -=
12995f39d397SChris Mason 					btrfs_header_nritems(left);
1300e66f709bSChris Mason 				path->slots[level] = orig_slot;
1301925baeddSChris Mason 				btrfs_tree_unlock(left);
13025f39d397SChris Mason 				free_extent_buffer(left);
1303e66f709bSChris Mason 			}
1304e66f709bSChris Mason 			return 0;
1305e66f709bSChris Mason 		}
1306925baeddSChris Mason 		btrfs_tree_unlock(left);
13075f39d397SChris Mason 		free_extent_buffer(left);
1308e66f709bSChris Mason 	}
1309e66f709bSChris Mason 
1310e66f709bSChris Mason 	/*
1311e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1312e66f709bSChris Mason 	 */
13139cf14029SJosef Bacik 	if (pslot + 1 < btrfs_header_nritems(parent)) {
131433ade1f8SChris Mason 		u32 right_nr;
1315b4ce94deSChris Mason 
13169cf14029SJosef Bacik 		right = btrfs_read_node_slot(parent, pslot + 1);
13179cf14029SJosef Bacik 		if (IS_ERR(right))
13189cf14029SJosef Bacik 			return PTR_ERR(right);
13199cf14029SJosef Bacik 
1320bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1321b4ce94deSChris Mason 
13225f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
13230b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
132433ade1f8SChris Mason 			wret = 1;
132533ade1f8SChris Mason 		} else {
13265f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
13275f39d397SChris Mason 					      parent, pslot + 1,
1328bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
132954aa1f4dSChris Mason 			if (ret)
133054aa1f4dSChris Mason 				wret = 1;
133154aa1f4dSChris Mason 			else {
133255d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
133333ade1f8SChris Mason 			}
133454aa1f4dSChris Mason 		}
1335e66f709bSChris Mason 		if (wret < 0)
1336e66f709bSChris Mason 			ret = wret;
1337e66f709bSChris Mason 		if (wret == 0) {
13385f39d397SChris Mason 			struct btrfs_disk_key disk_key;
13395f39d397SChris Mason 
13405f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1341f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
134233cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
13430e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
13445f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
13455f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
13465f39d397SChris Mason 
13475f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
13485f39d397SChris Mason 				path->nodes[level] = right;
1349e66f709bSChris Mason 				path->slots[level + 1] += 1;
1350e66f709bSChris Mason 				path->slots[level] = orig_slot -
13515f39d397SChris Mason 					btrfs_header_nritems(mid);
1352925baeddSChris Mason 				btrfs_tree_unlock(mid);
13535f39d397SChris Mason 				free_extent_buffer(mid);
1354e66f709bSChris Mason 			} else {
1355925baeddSChris Mason 				btrfs_tree_unlock(right);
13565f39d397SChris Mason 				free_extent_buffer(right);
1357e66f709bSChris Mason 			}
1358e66f709bSChris Mason 			return 0;
1359e66f709bSChris Mason 		}
1360925baeddSChris Mason 		btrfs_tree_unlock(right);
13615f39d397SChris Mason 		free_extent_buffer(right);
1362e66f709bSChris Mason 	}
1363e66f709bSChris Mason 	return 1;
1364e66f709bSChris Mason }
1365e66f709bSChris Mason 
136674123bd7SChris Mason /*
1367d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1368d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
13693c69faecSChris Mason  */
13702ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1371e02119d5SChris Mason 			     struct btrfs_path *path,
137201f46658SChris Mason 			     int level, int slot, u64 objectid)
13733c69faecSChris Mason {
13745f39d397SChris Mason 	struct extent_buffer *node;
137501f46658SChris Mason 	struct btrfs_disk_key disk_key;
13763c69faecSChris Mason 	u32 nritems;
13773c69faecSChris Mason 	u64 search;
1378a7175319SChris Mason 	u64 target;
13796b80053dSChris Mason 	u64 nread = 0;
1380ace75066SFilipe Manana 	u64 nread_max;
13816b80053dSChris Mason 	u32 nr;
13826b80053dSChris Mason 	u32 blocksize;
13836b80053dSChris Mason 	u32 nscan = 0;
1384db94535dSChris Mason 
1385ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
13863c69faecSChris Mason 		return;
13873c69faecSChris Mason 
13886702ed49SChris Mason 	if (!path->nodes[level])
13896702ed49SChris Mason 		return;
13906702ed49SChris Mason 
13915f39d397SChris Mason 	node = path->nodes[level];
1392925baeddSChris Mason 
1393ace75066SFilipe Manana 	/*
1394ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1395ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1396ace75066SFilipe Manana 	 * much IO at once (possibly random).
1397ace75066SFilipe Manana 	 */
1398ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1399ace75066SFilipe Manana 		if (level > 1)
1400ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1401ace75066SFilipe Manana 		else
1402ace75066SFilipe Manana 			nread_max = SZ_128K;
1403ace75066SFilipe Manana 	} else {
1404ace75066SFilipe Manana 		nread_max = SZ_64K;
1405ace75066SFilipe Manana 	}
1406ace75066SFilipe Manana 
14073c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
14080b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1409069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1410069a2e37SFilipe Manana 		struct extent_buffer *eb;
1411069a2e37SFilipe Manana 
14120b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
14135f39d397SChris Mason 		if (eb) {
14145f39d397SChris Mason 			free_extent_buffer(eb);
14153c69faecSChris Mason 			return;
14163c69faecSChris Mason 		}
1417069a2e37SFilipe Manana 	}
14183c69faecSChris Mason 
1419a7175319SChris Mason 	target = search;
14206b80053dSChris Mason 
14215f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
14226b80053dSChris Mason 	nr = slot;
142325b8b936SJosef Bacik 
14243c69faecSChris Mason 	while (1) {
1425e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
14266b80053dSChris Mason 			if (nr == 0)
14273c69faecSChris Mason 				break;
14286b80053dSChris Mason 			nr--;
1429ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1430ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
14316b80053dSChris Mason 			nr++;
14326b80053dSChris Mason 			if (nr >= nritems)
14336b80053dSChris Mason 				break;
14343c69faecSChris Mason 		}
1435e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
143601f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
143701f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
143801f46658SChris Mason 				break;
143901f46658SChris Mason 		}
14406b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1441ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1442ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1443a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1444bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
14456b80053dSChris Mason 			nread += blocksize;
14463c69faecSChris Mason 		}
14476b80053dSChris Mason 		nscan++;
1448ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
14496b80053dSChris Mason 			break;
14503c69faecSChris Mason 	}
14513c69faecSChris Mason }
1452925baeddSChris Mason 
1453bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1454b4ce94deSChris Mason {
1455bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1456b4ce94deSChris Mason 	int slot;
1457b4ce94deSChris Mason 	int nritems;
1458b4ce94deSChris Mason 
14598c594ea8SChris Mason 	parent = path->nodes[level + 1];
1460b4ce94deSChris Mason 	if (!parent)
14610b08851fSJosef Bacik 		return;
1462b4ce94deSChris Mason 
1463b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
14648c594ea8SChris Mason 	slot = path->slots[level + 1];
1465b4ce94deSChris Mason 
1466bfb484d9SJosef Bacik 	if (slot > 0)
1467bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1468bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1469bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1470b4ce94deSChris Mason }
1471b4ce94deSChris Mason 
1472b4ce94deSChris Mason 
1473b4ce94deSChris Mason /*
1474d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1475d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1476d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1477d397712bSChris Mason  * tree.
1478d352ac68SChris Mason  *
1479d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1480d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1481d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1482d352ac68SChris Mason  *
1483d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1484d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1485d352ac68SChris Mason  */
1486e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1487f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1488f7c79f30SChris Mason 			       int *write_lock_level)
1489925baeddSChris Mason {
1490925baeddSChris Mason 	int i;
1491925baeddSChris Mason 	int skip_level = level;
1492c1227996SNikolay Borisov 	bool check_skip = true;
1493925baeddSChris Mason 
1494925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1495925baeddSChris Mason 		if (!path->nodes[i])
1496925baeddSChris Mason 			break;
1497925baeddSChris Mason 		if (!path->locks[i])
1498925baeddSChris Mason 			break;
1499c1227996SNikolay Borisov 
1500c1227996SNikolay Borisov 		if (check_skip) {
1501c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1502925baeddSChris Mason 				skip_level = i + 1;
1503925baeddSChris Mason 				continue;
1504925baeddSChris Mason 			}
1505c1227996SNikolay Borisov 
1506c1227996SNikolay Borisov 			if (path->keep_locks) {
1507925baeddSChris Mason 				u32 nritems;
1508c1227996SNikolay Borisov 
1509c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1510051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1511925baeddSChris Mason 					skip_level = i + 1;
1512925baeddSChris Mason 					continue;
1513925baeddSChris Mason 				}
1514925baeddSChris Mason 			}
1515c1227996SNikolay Borisov 		}
1516051e1b9fSChris Mason 
1517d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1518c1227996SNikolay Borisov 			check_skip = false;
1519c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1520925baeddSChris Mason 			path->locks[i] = 0;
1521f7c79f30SChris Mason 			if (write_lock_level &&
1522f7c79f30SChris Mason 			    i > min_write_lock_level &&
1523f7c79f30SChris Mason 			    i <= *write_lock_level) {
1524f7c79f30SChris Mason 				*write_lock_level = i - 1;
1525f7c79f30SChris Mason 			}
1526925baeddSChris Mason 		}
1527925baeddSChris Mason 	}
1528925baeddSChris Mason }
1529925baeddSChris Mason 
15303c69faecSChris Mason /*
1531376a21d7SFilipe Manana  * Helper function for btrfs_search_slot() and other functions that do a search
1532376a21d7SFilipe Manana  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1533376a21d7SFilipe Manana  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1534376a21d7SFilipe Manana  * its pages from disk.
1535c8c42864SChris Mason  *
1536376a21d7SFilipe Manana  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1537376a21d7SFilipe Manana  * whole btree search, starting again from the current root node.
1538c8c42864SChris Mason  */
1539c8c42864SChris Mason static int
1540d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1541c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1542cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1543c8c42864SChris Mason {
15440b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1545789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1546c8c42864SChris Mason 	u64 blocknr;
1547c8c42864SChris Mason 	u64 gen;
1548c8c42864SChris Mason 	struct extent_buffer *tmp;
154976a05b35SChris Mason 	int ret;
1550581c1760SQu Wenruo 	int parent_level;
1551b246666eSFilipe Manana 	bool unlock_up;
1552c8c42864SChris Mason 
1553b246666eSFilipe Manana 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1554213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1555213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1556213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1557789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(*eb_ret, &check.first_key, slot);
1558789d6a3aSQu Wenruo 	check.has_first_key = true;
1559789d6a3aSQu Wenruo 	check.level = parent_level - 1;
1560789d6a3aSQu Wenruo 	check.transid = gen;
1561789d6a3aSQu Wenruo 	check.owner_root = root->root_key.objectid;
1562c8c42864SChris Mason 
1563b246666eSFilipe Manana 	/*
1564b246666eSFilipe Manana 	 * If we need to read an extent buffer from disk and we are holding locks
1565b246666eSFilipe Manana 	 * on upper level nodes, we unlock all the upper nodes before reading the
1566b246666eSFilipe Manana 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1567b246666eSFilipe Manana 	 * restart the search. We don't release the lock on the current level
1568b246666eSFilipe Manana 	 * because we need to walk this node to figure out which blocks to read.
1569b246666eSFilipe Manana 	 */
15700b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1571cb44921aSChris Mason 	if (tmp) {
1572ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1573ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1574ace75066SFilipe Manana 
1575b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1576b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1577448de471SQu Wenruo 			/*
1578448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1579448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1580448de471SQu Wenruo 			 * parents (shared tree blocks).
1581448de471SQu Wenruo 			 */
1582e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1583789d6a3aSQu Wenruo 					parent_level - 1, &check.first_key, gen)) {
1584448de471SQu Wenruo 				free_extent_buffer(tmp);
1585448de471SQu Wenruo 				return -EUCLEAN;
1586448de471SQu Wenruo 			}
1587c8c42864SChris Mason 			*eb_ret = tmp;
1588c8c42864SChris Mason 			return 0;
1589c8c42864SChris Mason 		}
1590bdf7c00eSJosef Bacik 
1591857bc13fSJosef Bacik 		if (p->nowait) {
1592857bc13fSJosef Bacik 			free_extent_buffer(tmp);
1593857bc13fSJosef Bacik 			return -EAGAIN;
1594857bc13fSJosef Bacik 		}
1595857bc13fSJosef Bacik 
1596b246666eSFilipe Manana 		if (unlock_up)
1597b246666eSFilipe Manana 			btrfs_unlock_up_safe(p, level + 1);
1598b246666eSFilipe Manana 
1599b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
1600789d6a3aSQu Wenruo 		ret = btrfs_read_extent_buffer(tmp, &check);
16019a4ffa1bSQu Wenruo 		if (ret) {
1602cb44921aSChris Mason 			free_extent_buffer(tmp);
1603b3b4aa74SDavid Sterba 			btrfs_release_path(p);
1604cb44921aSChris Mason 			return -EIO;
1605cb44921aSChris Mason 		}
160688c602abSQu Wenruo 		if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
160788c602abSQu Wenruo 			free_extent_buffer(tmp);
160888c602abSQu Wenruo 			btrfs_release_path(p);
160988c602abSQu Wenruo 			return -EUCLEAN;
161088c602abSQu Wenruo 		}
1611b246666eSFilipe Manana 
1612b246666eSFilipe Manana 		if (unlock_up)
1613b246666eSFilipe Manana 			ret = -EAGAIN;
1614b246666eSFilipe Manana 
1615b246666eSFilipe Manana 		goto out;
1616857bc13fSJosef Bacik 	} else if (p->nowait) {
1617857bc13fSJosef Bacik 		return -EAGAIN;
16189a4ffa1bSQu Wenruo 	}
1619c8c42864SChris Mason 
1620b246666eSFilipe Manana 	if (unlock_up) {
16218c594ea8SChris Mason 		btrfs_unlock_up_safe(p, level + 1);
16224bb59055SFilipe Manana 		ret = -EAGAIN;
16234bb59055SFilipe Manana 	} else {
16244bb59055SFilipe Manana 		ret = 0;
16254bb59055SFilipe Manana 	}
16268c594ea8SChris Mason 
1627e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
16282ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1629c8c42864SChris Mason 
1630789d6a3aSQu Wenruo 	tmp = read_tree_block(fs_info, blocknr, &check);
16314eb150d6SQu Wenruo 	if (IS_ERR(tmp)) {
16324eb150d6SQu Wenruo 		btrfs_release_path(p);
16334eb150d6SQu Wenruo 		return PTR_ERR(tmp);
16344eb150d6SQu Wenruo 	}
163576a05b35SChris Mason 	/*
163676a05b35SChris Mason 	 * If the read above didn't mark this buffer up to date,
163776a05b35SChris Mason 	 * it will never end up being up to date.  Set ret to EIO now
163876a05b35SChris Mason 	 * and give up so that our caller doesn't loop forever
163976a05b35SChris Mason 	 * on our EAGAINs.
164076a05b35SChris Mason 	 */
1641e6a1d6fdSLiu Bo 	if (!extent_buffer_uptodate(tmp))
164276a05b35SChris Mason 		ret = -EIO;
164302a3307aSLiu Bo 
1644b246666eSFilipe Manana out:
16454bb59055SFilipe Manana 	if (ret == 0) {
16464bb59055SFilipe Manana 		*eb_ret = tmp;
16474bb59055SFilipe Manana 	} else {
16484bb59055SFilipe Manana 		free_extent_buffer(tmp);
164902a3307aSLiu Bo 		btrfs_release_path(p);
16504bb59055SFilipe Manana 	}
16514bb59055SFilipe Manana 
165276a05b35SChris Mason 	return ret;
1653c8c42864SChris Mason }
1654c8c42864SChris Mason 
1655c8c42864SChris Mason /*
1656c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1657c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1658c8c42864SChris Mason  * the ins_len.
1659c8c42864SChris Mason  *
1660c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1661c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1662c8c42864SChris Mason  * start over
1663c8c42864SChris Mason  */
1664c8c42864SChris Mason static int
1665c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1666c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1667bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1668bd681513SChris Mason 		       int *write_lock_level)
1669c8c42864SChris Mason {
16700b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
167195b982deSNikolay Borisov 	int ret = 0;
16720b246afaSJeff Mahoney 
1673c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
16740b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1675c8c42864SChris Mason 
1676bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1677bd681513SChris Mason 			*write_lock_level = level + 1;
1678bd681513SChris Mason 			btrfs_release_path(p);
167995b982deSNikolay Borisov 			return -EAGAIN;
1680bd681513SChris Mason 		}
1681bd681513SChris Mason 
1682bfb484d9SJosef Bacik 		reada_for_balance(p, level);
168395b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1684c8c42864SChris Mason 
1685c8c42864SChris Mason 		b = p->nodes[level];
1686c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
16870b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1688c8c42864SChris Mason 
1689bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1690bd681513SChris Mason 			*write_lock_level = level + 1;
1691bd681513SChris Mason 			btrfs_release_path(p);
169295b982deSNikolay Borisov 			return -EAGAIN;
1693bd681513SChris Mason 		}
1694bd681513SChris Mason 
1695bfb484d9SJosef Bacik 		reada_for_balance(p, level);
169695b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
169795b982deSNikolay Borisov 		if (ret)
169895b982deSNikolay Borisov 			return ret;
1699c8c42864SChris Mason 
1700c8c42864SChris Mason 		b = p->nodes[level];
1701c8c42864SChris Mason 		if (!b) {
1702b3b4aa74SDavid Sterba 			btrfs_release_path(p);
170395b982deSNikolay Borisov 			return -EAGAIN;
1704c8c42864SChris Mason 		}
1705c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1706c8c42864SChris Mason 	}
1707c8c42864SChris Mason 	return ret;
1708c8c42864SChris Mason }
1709c8c42864SChris Mason 
1710381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1711e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1712e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1713e33d5c3dSKelley Nielsen {
1714e33d5c3dSKelley Nielsen 	int ret;
1715e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1716e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1717381cf658SDavid Sterba 
1718381cf658SDavid Sterba 	ASSERT(path);
17191d4c08e0SDavid Sterba 	ASSERT(found_key);
1720e33d5c3dSKelley Nielsen 
1721e33d5c3dSKelley Nielsen 	key.type = key_type;
1722e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1723e33d5c3dSKelley Nielsen 	key.offset = ioff;
1724e33d5c3dSKelley Nielsen 
1725e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
17261d4c08e0SDavid Sterba 	if (ret < 0)
1727e33d5c3dSKelley Nielsen 		return ret;
1728e33d5c3dSKelley Nielsen 
1729e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1730e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1731e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1732e33d5c3dSKelley Nielsen 		if (ret)
1733e33d5c3dSKelley Nielsen 			return ret;
1734e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1735e33d5c3dSKelley Nielsen 	}
1736e33d5c3dSKelley Nielsen 
1737e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1738e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1739e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1740e33d5c3dSKelley Nielsen 		return 1;
1741e33d5c3dSKelley Nielsen 
1742e33d5c3dSKelley Nielsen 	return 0;
1743e33d5c3dSKelley Nielsen }
1744e33d5c3dSKelley Nielsen 
17451fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
17461fc28d8eSLiu Bo 							struct btrfs_path *p,
17471fc28d8eSLiu Bo 							int write_lock_level)
17481fc28d8eSLiu Bo {
17491fc28d8eSLiu Bo 	struct extent_buffer *b;
1750120de408SJosef Bacik 	int root_lock = 0;
17511fc28d8eSLiu Bo 	int level = 0;
17521fc28d8eSLiu Bo 
17531fc28d8eSLiu Bo 	if (p->search_commit_root) {
17541fc28d8eSLiu Bo 		b = root->commit_root;
175567439dadSDavid Sterba 		atomic_inc(&b->refs);
17561fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1757f9ddfd05SLiu Bo 		/*
1758f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1759f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1760f9ddfd05SLiu Bo 		 */
1761f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
17621fc28d8eSLiu Bo 
17631fc28d8eSLiu Bo 		goto out;
17641fc28d8eSLiu Bo 	}
17651fc28d8eSLiu Bo 
17661fc28d8eSLiu Bo 	if (p->skip_locking) {
17671fc28d8eSLiu Bo 		b = btrfs_root_node(root);
17681fc28d8eSLiu Bo 		level = btrfs_header_level(b);
17691fc28d8eSLiu Bo 		goto out;
17701fc28d8eSLiu Bo 	}
17711fc28d8eSLiu Bo 
1772120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1773120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1774120de408SJosef Bacik 
17751fc28d8eSLiu Bo 	/*
1776662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1777662c653bSLiu Bo 	 * lock.
1778662c653bSLiu Bo 	 */
1779662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1780662c653bSLiu Bo 		/*
1781662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1782662c653bSLiu Bo 		 * have it read locked
17831fc28d8eSLiu Bo 		 */
1784857bc13fSJosef Bacik 		if (p->nowait) {
1785857bc13fSJosef Bacik 			b = btrfs_try_read_lock_root_node(root);
1786857bc13fSJosef Bacik 			if (IS_ERR(b))
1787857bc13fSJosef Bacik 				return b;
1788857bc13fSJosef Bacik 		} else {
17891bb96598SJosef Bacik 			b = btrfs_read_lock_root_node(root);
1790857bc13fSJosef Bacik 		}
17911fc28d8eSLiu Bo 		level = btrfs_header_level(b);
17921fc28d8eSLiu Bo 		if (level > write_lock_level)
17931fc28d8eSLiu Bo 			goto out;
17941fc28d8eSLiu Bo 
1795662c653bSLiu Bo 		/* Whoops, must trade for write lock */
17961fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
17971fc28d8eSLiu Bo 		free_extent_buffer(b);
1798662c653bSLiu Bo 	}
1799662c653bSLiu Bo 
18001fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
18011fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
18021fc28d8eSLiu Bo 
18031fc28d8eSLiu Bo 	/* The level might have changed, check again */
18041fc28d8eSLiu Bo 	level = btrfs_header_level(b);
18051fc28d8eSLiu Bo 
18061fc28d8eSLiu Bo out:
1807120de408SJosef Bacik 	/*
1808120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1809120de408SJosef Bacik 	 * longer valid, return an error in this case.
1810120de408SJosef Bacik 	 */
1811120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1812120de408SJosef Bacik 		if (root_lock)
1813120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1814120de408SJosef Bacik 		free_extent_buffer(b);
1815120de408SJosef Bacik 		return ERR_PTR(-EIO);
1816120de408SJosef Bacik 	}
1817120de408SJosef Bacik 
18181fc28d8eSLiu Bo 	p->nodes[level] = b;
18191fc28d8eSLiu Bo 	if (!p->skip_locking)
18201fc28d8eSLiu Bo 		p->locks[level] = root_lock;
18211fc28d8eSLiu Bo 	/*
18221fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
18231fc28d8eSLiu Bo 	 */
18241fc28d8eSLiu Bo 	return b;
18251fc28d8eSLiu Bo }
18261fc28d8eSLiu Bo 
1827d96b3424SFilipe Manana /*
1828d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1829d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1830d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1831d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1832d96b3424SFilipe Manana  * reallocated in the next transaction.
1833d96b3424SFilipe Manana  *
1834d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1835d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1836d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1837d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1838d96b3424SFilipe Manana  */
1839d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1840d96b3424SFilipe Manana {
1841d96b3424SFilipe Manana 	const int i = path->lowest_level;
1842d96b3424SFilipe Manana 	const int slot = path->slots[i];
1843d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1844d96b3424SFilipe Manana 	struct extent_buffer *clone;
1845d96b3424SFilipe Manana 
1846d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1847d96b3424SFilipe Manana 
1848d96b3424SFilipe Manana 	if (!lowest)
1849d96b3424SFilipe Manana 		return 0;
1850d96b3424SFilipe Manana 
1851d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1852d96b3424SFilipe Manana 
1853d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1854d96b3424SFilipe Manana 	if (!clone)
1855d96b3424SFilipe Manana 		return -ENOMEM;
1856d96b3424SFilipe Manana 
1857d96b3424SFilipe Manana 	btrfs_release_path(path);
1858d96b3424SFilipe Manana 	path->nodes[i] = clone;
1859d96b3424SFilipe Manana 	path->slots[i] = slot;
1860d96b3424SFilipe Manana 
1861d96b3424SFilipe Manana 	return 0;
1862d96b3424SFilipe Manana }
18631fc28d8eSLiu Bo 
1864e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1865e2e58d0fSFilipe Manana 				      int search_low_slot,
1866e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1867e2e58d0fSFilipe Manana 				      int prev_cmp,
1868e2e58d0fSFilipe Manana 				      int *slot)
1869e2e58d0fSFilipe Manana {
1870e2e58d0fSFilipe Manana 	/*
1871e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1872e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1873e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1874e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1875e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1876e2e58d0fSFilipe Manana 	 */
1877e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1878e2e58d0fSFilipe Manana 		*slot = 0;
1879e2e58d0fSFilipe Manana 		return 0;
1880e2e58d0fSFilipe Manana 	}
1881e2e58d0fSFilipe Manana 
1882fdf8d595SAnand Jain 	return btrfs_bin_search(eb, search_low_slot, key, slot);
1883e2e58d0fSFilipe Manana }
1884e2e58d0fSFilipe Manana 
1885109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1886109324cfSFilipe Manana 		       struct btrfs_root *root,
1887109324cfSFilipe Manana 		       const struct btrfs_key *key,
1888109324cfSFilipe Manana 		       struct btrfs_path *path,
1889109324cfSFilipe Manana 		       int ins_len,
1890109324cfSFilipe Manana 		       int prev_cmp)
1891109324cfSFilipe Manana {
1892109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
1893109324cfSFilipe Manana 	int leaf_free_space = -1;
1894109324cfSFilipe Manana 	int search_low_slot = 0;
1895109324cfSFilipe Manana 	int ret;
1896109324cfSFilipe Manana 	bool do_bin_search = true;
1897109324cfSFilipe Manana 
1898109324cfSFilipe Manana 	/*
1899109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
1900109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
1901109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
1902109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1903109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
1904109324cfSFilipe Manana 	 */
1905109324cfSFilipe Manana 	if (ins_len > 0) {
1906109324cfSFilipe Manana 		/*
1907109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
1908109324cfSFilipe Manana 		 * will not change until then.
1909109324cfSFilipe Manana 		 */
1910109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
1911109324cfSFilipe Manana 
1912109324cfSFilipe Manana 		/*
1913109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
1914109324cfSFilipe Manana 		 * the root of the tree.
1915109324cfSFilipe Manana 		 */
1916109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
1917109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
1918109324cfSFilipe Manana 
1919109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
1920109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
1921109324cfSFilipe Manana 
1922109324cfSFilipe Manana 			/*
1923109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
1924109324cfSFilipe Manana 			 * taking into account that the first key is very likely
1925109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
1926109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
1927109324cfSFilipe Manana 			 * the header's level field.
1928109324cfSFilipe Manana 			 */
1929109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
1930109324cfSFilipe Manana 			if (ret < 0) {
1931109324cfSFilipe Manana 				/*
1932109324cfSFilipe Manana 				 * The first key is smaller than the key we want
1933109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
1934109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
1935109324cfSFilipe Manana 				 *
1936109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
1937109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
1938109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
1939109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
1940109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
1941109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
1942109324cfSFilipe Manana 				 */
1943109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
1944109324cfSFilipe Manana 				search_low_slot = 1;
1945109324cfSFilipe Manana 			} else {
1946109324cfSFilipe Manana 				/*
1947109324cfSFilipe Manana 				 * The first key is >= then the key we want to
1948109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
1949109324cfSFilipe Manana 				 * the target key will be at slot 0.
1950109324cfSFilipe Manana 				 *
1951109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
1952109324cfSFilipe Manana 				 * less than the first key, because we will need
1953109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
1954109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
1955109324cfSFilipe Manana 				 * If the key matches the first key, then we can
1956109324cfSFilipe Manana 				 * unlock all the upper nodes, using
1957109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
1958109324cfSFilipe Manana 				 * as stated above.
1959109324cfSFilipe Manana 				 */
1960109324cfSFilipe Manana 				if (ret == 0)
1961109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
1962109324cfSFilipe Manana 				/*
1963109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
1964109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
1965109324cfSFilipe Manana 				 * to adjust it.
1966109324cfSFilipe Manana 				 */
1967109324cfSFilipe Manana 				do_bin_search = false;
1968109324cfSFilipe Manana 				path->slots[0] = 0;
1969109324cfSFilipe Manana 			}
1970109324cfSFilipe Manana 		}
1971109324cfSFilipe Manana 	}
1972109324cfSFilipe Manana 
1973109324cfSFilipe Manana 	if (do_bin_search) {
1974109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
1975109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
1976109324cfSFilipe Manana 		if (ret < 0)
1977109324cfSFilipe Manana 			return ret;
1978109324cfSFilipe Manana 	}
1979109324cfSFilipe Manana 
1980109324cfSFilipe Manana 	if (ins_len > 0) {
1981109324cfSFilipe Manana 		/*
1982109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
1983109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
1984109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
1985109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
1986109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
1987109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
1988109324cfSFilipe Manana 		 * check will be correct.
1989109324cfSFilipe Manana 		 */
1990109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
1991109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
1992109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
1993109324cfSFilipe Manana 		}
1994109324cfSFilipe Manana 
1995109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
1996109324cfSFilipe Manana 
1997109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
1998109324cfSFilipe Manana 			int err;
1999109324cfSFilipe Manana 
2000109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
2001109324cfSFilipe Manana 					 (ret == 0));
2002bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
2003bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
2004bb8e9a60SFilipe Manana 				err = -EUCLEAN;
2005109324cfSFilipe Manana 			if (err)
2006109324cfSFilipe Manana 				ret = err;
2007109324cfSFilipe Manana 		}
2008109324cfSFilipe Manana 	}
2009109324cfSFilipe Manana 
2010109324cfSFilipe Manana 	return ret;
2011109324cfSFilipe Manana }
2012109324cfSFilipe Manana 
2013c8c42864SChris Mason /*
20144271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
20154271eceaSNikolay Borisov  * modifications to preserve tree invariants.
201674123bd7SChris Mason  *
20174271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
20184271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
20194271eceaSNikolay Borisov  * @root:	The root node of the tree
20204271eceaSNikolay Borisov  * @key:	The key we are looking for
20219a664971Sethanwu  * @ins_len:	Indicates purpose of search:
20229a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
20239a664971Sethanwu  *              <0  for deletions
20249a664971Sethanwu  *               0  for plain searches, not modifying the tree
20259a664971Sethanwu  *
20269a664971Sethanwu  *              (*) If size of item inserted doesn't include
20279a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
20289a664971Sethanwu  *              be set.
20294271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
20304271eceaSNikolay Borisov  *		when modifying the tree.
203197571fd0SChris Mason  *
20324271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
20334271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
20344271eceaSNikolay Borisov  *
20354271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
20364271eceaSNikolay Borisov  * of the path (level 0)
20374271eceaSNikolay Borisov  *
20384271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
20394271eceaSNikolay Borisov  * points to the slot where it should be inserted
20404271eceaSNikolay Borisov  *
20414271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
20424271eceaSNikolay Borisov  * is returned
204374123bd7SChris Mason  */
2044310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2045310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2046310712b2SOmar Sandoval 		      int ins_len, int cow)
2047be0e5c09SChris Mason {
2048d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
20495f39d397SChris Mason 	struct extent_buffer *b;
2050be0e5c09SChris Mason 	int slot;
2051be0e5c09SChris Mason 	int ret;
205233c66f43SYan Zheng 	int err;
2053be0e5c09SChris Mason 	int level;
2054925baeddSChris Mason 	int lowest_unlock = 1;
2055bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2056bd681513SChris Mason 	int write_lock_level = 0;
20579f3a7427SChris Mason 	u8 lowest_level = 0;
2058f7c79f30SChris Mason 	int min_write_lock_level;
2059d7396f07SFilipe David Borba Manana 	int prev_cmp;
20609f3a7427SChris Mason 
2061a4c853afSChenXiaoSong 	might_sleep();
2062a4c853afSChenXiaoSong 
20636702ed49SChris Mason 	lowest_level = p->lowest_level;
2064323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
206522b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2066eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
206725179201SJosef Bacik 
2068857bc13fSJosef Bacik 	/*
2069857bc13fSJosef Bacik 	 * For now only allow nowait for read only operations.  There's no
2070857bc13fSJosef Bacik 	 * strict reason why we can't, we just only need it for reads so it's
2071857bc13fSJosef Bacik 	 * only implemented for reads.
2072857bc13fSJosef Bacik 	 */
2073857bc13fSJosef Bacik 	ASSERT(!p->nowait || !cow);
2074857bc13fSJosef Bacik 
2075bd681513SChris Mason 	if (ins_len < 0) {
2076925baeddSChris Mason 		lowest_unlock = 2;
207765b51a00SChris Mason 
2078bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2079bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2080bd681513SChris Mason 		 * for those levels as well
2081bd681513SChris Mason 		 */
2082bd681513SChris Mason 		write_lock_level = 2;
2083bd681513SChris Mason 	} else if (ins_len > 0) {
2084bd681513SChris Mason 		/*
2085bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2086bd681513SChris Mason 		 * level 1 so we can update keys
2087bd681513SChris Mason 		 */
2088bd681513SChris Mason 		write_lock_level = 1;
2089bd681513SChris Mason 	}
2090bd681513SChris Mason 
2091bd681513SChris Mason 	if (!cow)
2092bd681513SChris Mason 		write_lock_level = -1;
2093bd681513SChris Mason 
209409a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2095bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2096bd681513SChris Mason 
2097f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2098f7c79f30SChris Mason 
2099d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2100d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
2101857bc13fSJosef Bacik 		if (p->nowait) {
2102857bc13fSJosef Bacik 			if (!down_read_trylock(&fs_info->commit_root_sem))
2103857bc13fSJosef Bacik 				return -EAGAIN;
2104857bc13fSJosef Bacik 		} else {
2105d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
2106d96b3424SFilipe Manana 		}
2107857bc13fSJosef Bacik 	}
2108d96b3424SFilipe Manana 
2109bb803951SChris Mason again:
2110d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
21111fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2112be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2113be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2114be6821f8SFilipe Manana 		goto done;
2115be6821f8SFilipe Manana 	}
2116925baeddSChris Mason 
2117eb60ceacSChris Mason 	while (b) {
2118f624d976SQu Wenruo 		int dec = 0;
2119f624d976SQu Wenruo 
21205f39d397SChris Mason 		level = btrfs_header_level(b);
212165b51a00SChris Mason 
212202217ed2SChris Mason 		if (cow) {
21239ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
21249ea2c7c9SNikolay Borisov 
2125c8c42864SChris Mason 			/*
2126c8c42864SChris Mason 			 * if we don't really need to cow this block
2127c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2128c8c42864SChris Mason 			 * so we test it here
2129c8c42864SChris Mason 			 */
21305963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
213165b51a00SChris Mason 				goto cow_done;
21325d4f98a2SYan Zheng 
2133bd681513SChris Mason 			/*
2134bd681513SChris Mason 			 * must have write locks on this node and the
2135bd681513SChris Mason 			 * parent
2136bd681513SChris Mason 			 */
21375124e00eSJosef Bacik 			if (level > write_lock_level ||
21385124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
21395124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
21405124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2141bd681513SChris Mason 				write_lock_level = level + 1;
2142bd681513SChris Mason 				btrfs_release_path(p);
2143bd681513SChris Mason 				goto again;
2144bd681513SChris Mason 			}
2145bd681513SChris Mason 
21469ea2c7c9SNikolay Borisov 			if (last_level)
21479ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
21489631e4ccSJosef Bacik 						      &b,
21499631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
21509ea2c7c9SNikolay Borisov 			else
215133c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2152e20d96d6SChris Mason 						      p->nodes[level + 1],
21539631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
21549631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
215533c66f43SYan Zheng 			if (err) {
215633c66f43SYan Zheng 				ret = err;
215765b51a00SChris Mason 				goto done;
215854aa1f4dSChris Mason 			}
215902217ed2SChris Mason 		}
216065b51a00SChris Mason cow_done:
2161eb60ceacSChris Mason 		p->nodes[level] = b;
2162b4ce94deSChris Mason 
2163b4ce94deSChris Mason 		/*
2164b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2165b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2166b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2167b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2168b4ce94deSChris Mason 		 *
2169eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2170eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2171eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2172eb653de1SFilipe David Borba Manana 		 * we're operating on.
2173b4ce94deSChris Mason 		 */
2174eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2175eb653de1SFilipe David Borba Manana 			int u = level + 1;
2176eb653de1SFilipe David Borba Manana 
2177eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2178eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2179eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2180eb653de1SFilipe David Borba Manana 			}
2181eb653de1SFilipe David Borba Manana 		}
2182b4ce94deSChris Mason 
2183e2e58d0fSFilipe Manana 		if (level == 0) {
2184109324cfSFilipe Manana 			if (ins_len > 0)
2185e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
2186bd681513SChris Mason 
2187109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2188459931ecSChris Mason 			if (!p->search_for_split)
2189f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
21904b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
219165b51a00SChris Mason 			goto done;
219265b51a00SChris Mason 		}
2193e2e58d0fSFilipe Manana 
2194e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2195e2e58d0fSFilipe Manana 		if (ret < 0)
2196e2e58d0fSFilipe Manana 			goto done;
2197e2e58d0fSFilipe Manana 		prev_cmp = ret;
2198e2e58d0fSFilipe Manana 
2199f624d976SQu Wenruo 		if (ret && slot > 0) {
2200f624d976SQu Wenruo 			dec = 1;
2201f624d976SQu Wenruo 			slot--;
2202f624d976SQu Wenruo 		}
2203f624d976SQu Wenruo 		p->slots[level] = slot;
2204f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2205f624d976SQu Wenruo 					     &write_lock_level);
2206f624d976SQu Wenruo 		if (err == -EAGAIN)
2207f624d976SQu Wenruo 			goto again;
2208f624d976SQu Wenruo 		if (err) {
2209f624d976SQu Wenruo 			ret = err;
2210f624d976SQu Wenruo 			goto done;
2211f624d976SQu Wenruo 		}
2212f624d976SQu Wenruo 		b = p->nodes[level];
2213f624d976SQu Wenruo 		slot = p->slots[level];
2214f624d976SQu Wenruo 
2215f624d976SQu Wenruo 		/*
2216f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2217f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2218f624d976SQu Wenruo 		 * the parent
2219f624d976SQu Wenruo 		 */
2220f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2221f624d976SQu Wenruo 			write_lock_level = level + 1;
2222f624d976SQu Wenruo 			btrfs_release_path(p);
2223f624d976SQu Wenruo 			goto again;
2224f624d976SQu Wenruo 		}
2225f624d976SQu Wenruo 
2226f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2227f624d976SQu Wenruo 			  &write_lock_level);
2228f624d976SQu Wenruo 
2229f624d976SQu Wenruo 		if (level == lowest_level) {
2230f624d976SQu Wenruo 			if (dec)
2231f624d976SQu Wenruo 				p->slots[level]++;
2232f624d976SQu Wenruo 			goto done;
2233f624d976SQu Wenruo 		}
2234f624d976SQu Wenruo 
2235f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2236f624d976SQu Wenruo 		if (err == -EAGAIN)
2237f624d976SQu Wenruo 			goto again;
2238f624d976SQu Wenruo 		if (err) {
2239f624d976SQu Wenruo 			ret = err;
2240f624d976SQu Wenruo 			goto done;
2241f624d976SQu Wenruo 		}
2242f624d976SQu Wenruo 
2243f624d976SQu Wenruo 		if (!p->skip_locking) {
2244f624d976SQu Wenruo 			level = btrfs_header_level(b);
2245b40130b2SJosef Bacik 
2246b40130b2SJosef Bacik 			btrfs_maybe_reset_lockdep_class(root, b);
2247b40130b2SJosef Bacik 
2248f624d976SQu Wenruo 			if (level <= write_lock_level) {
2249f624d976SQu Wenruo 				btrfs_tree_lock(b);
2250f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2251f624d976SQu Wenruo 			} else {
2252857bc13fSJosef Bacik 				if (p->nowait) {
2253857bc13fSJosef Bacik 					if (!btrfs_try_tree_read_lock(b)) {
2254857bc13fSJosef Bacik 						free_extent_buffer(b);
2255857bc13fSJosef Bacik 						ret = -EAGAIN;
2256857bc13fSJosef Bacik 						goto done;
2257857bc13fSJosef Bacik 					}
2258857bc13fSJosef Bacik 				} else {
2259fe596ca3SJosef Bacik 					btrfs_tree_read_lock(b);
2260857bc13fSJosef Bacik 				}
2261f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2262f624d976SQu Wenruo 			}
2263f624d976SQu Wenruo 			p->nodes[level] = b;
2264f624d976SQu Wenruo 		}
226565b51a00SChris Mason 	}
226665b51a00SChris Mason 	ret = 1;
226765b51a00SChris Mason done:
22685f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2269b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2270d96b3424SFilipe Manana 
2271d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2272d96b3424SFilipe Manana 		int ret2;
2273d96b3424SFilipe Manana 
2274d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2275d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2276d96b3424SFilipe Manana 		if (ret2)
2277d96b3424SFilipe Manana 			ret = ret2;
2278d96b3424SFilipe Manana 	}
2279d96b3424SFilipe Manana 
2280be0e5c09SChris Mason 	return ret;
2281be0e5c09SChris Mason }
2282f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2283be0e5c09SChris Mason 
228474123bd7SChris Mason /*
22855d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
22865d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
22875d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
22885d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
22895d9e75c4SJan Schmidt  *
22905d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
22915d9e75c4SJan Schmidt  *
22925d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
22935d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
22945d9e75c4SJan Schmidt  */
2295310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
22965d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
22975d9e75c4SJan Schmidt {
22980b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
22995d9e75c4SJan Schmidt 	struct extent_buffer *b;
23005d9e75c4SJan Schmidt 	int slot;
23015d9e75c4SJan Schmidt 	int ret;
23025d9e75c4SJan Schmidt 	int err;
23035d9e75c4SJan Schmidt 	int level;
23045d9e75c4SJan Schmidt 	int lowest_unlock = 1;
23055d9e75c4SJan Schmidt 	u8 lowest_level = 0;
23065d9e75c4SJan Schmidt 
23075d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
23085d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
2309c922b016SStefan Roesch 	ASSERT(!p->nowait);
23105d9e75c4SJan Schmidt 
23115d9e75c4SJan Schmidt 	if (p->search_commit_root) {
23125d9e75c4SJan Schmidt 		BUG_ON(time_seq);
23135d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
23145d9e75c4SJan Schmidt 	}
23155d9e75c4SJan Schmidt 
23165d9e75c4SJan Schmidt again:
2317f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2318315bed43SNikolay Borisov 	if (!b) {
2319315bed43SNikolay Borisov 		ret = -EIO;
2320315bed43SNikolay Borisov 		goto done;
2321315bed43SNikolay Borisov 	}
23225d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
23235d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
23245d9e75c4SJan Schmidt 
23255d9e75c4SJan Schmidt 	while (b) {
2326abe9339dSQu Wenruo 		int dec = 0;
2327abe9339dSQu Wenruo 
23285d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
23295d9e75c4SJan Schmidt 		p->nodes[level] = b;
23305d9e75c4SJan Schmidt 
23315d9e75c4SJan Schmidt 		/*
23325d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
23335d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
23345d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
23355d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
23365d9e75c4SJan Schmidt 		 */
23375d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
23385d9e75c4SJan Schmidt 
2339fdf8d595SAnand Jain 		ret = btrfs_bin_search(b, 0, key, &slot);
2340cbca7d59SFilipe Manana 		if (ret < 0)
2341cbca7d59SFilipe Manana 			goto done;
23425d9e75c4SJan Schmidt 
2343abe9339dSQu Wenruo 		if (level == 0) {
2344abe9339dSQu Wenruo 			p->slots[level] = slot;
2345abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2346abe9339dSQu Wenruo 			goto done;
2347abe9339dSQu Wenruo 		}
2348abe9339dSQu Wenruo 
23495d9e75c4SJan Schmidt 		if (ret && slot > 0) {
23505d9e75c4SJan Schmidt 			dec = 1;
2351abe9339dSQu Wenruo 			slot--;
23525d9e75c4SJan Schmidt 		}
23535d9e75c4SJan Schmidt 		p->slots[level] = slot;
23545d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
23555d9e75c4SJan Schmidt 
23565d9e75c4SJan Schmidt 		if (level == lowest_level) {
23575d9e75c4SJan Schmidt 			if (dec)
23585d9e75c4SJan Schmidt 				p->slots[level]++;
23595d9e75c4SJan Schmidt 			goto done;
23605d9e75c4SJan Schmidt 		}
23615d9e75c4SJan Schmidt 
2362abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
23635d9e75c4SJan Schmidt 		if (err == -EAGAIN)
23645d9e75c4SJan Schmidt 			goto again;
23655d9e75c4SJan Schmidt 		if (err) {
23665d9e75c4SJan Schmidt 			ret = err;
23675d9e75c4SJan Schmidt 			goto done;
23685d9e75c4SJan Schmidt 		}
23695d9e75c4SJan Schmidt 
23705d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
23715d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2372f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2373db7f3436SJosef Bacik 		if (!b) {
2374db7f3436SJosef Bacik 			ret = -ENOMEM;
2375db7f3436SJosef Bacik 			goto done;
2376db7f3436SJosef Bacik 		}
23775d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
23785d9e75c4SJan Schmidt 		p->nodes[level] = b;
23795d9e75c4SJan Schmidt 	}
23805d9e75c4SJan Schmidt 	ret = 1;
23815d9e75c4SJan Schmidt done:
23825d9e75c4SJan Schmidt 	if (ret < 0)
23835d9e75c4SJan Schmidt 		btrfs_release_path(p);
23845d9e75c4SJan Schmidt 
23855d9e75c4SJan Schmidt 	return ret;
23865d9e75c4SJan Schmidt }
23875d9e75c4SJan Schmidt 
23885d9e75c4SJan Schmidt /*
2389f469c8bdSFilipe Manana  * Search the tree again to find a leaf with smaller keys.
2390f469c8bdSFilipe Manana  * Returns 0 if it found something.
2391f469c8bdSFilipe Manana  * Returns 1 if there are no smaller keys.
2392f469c8bdSFilipe Manana  * Returns < 0 on error.
2393f469c8bdSFilipe Manana  *
2394f469c8bdSFilipe Manana  * This may release the path, and so you may lose any locks held at the
2395f469c8bdSFilipe Manana  * time you call it.
2396f469c8bdSFilipe Manana  */
2397f469c8bdSFilipe Manana static int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
2398f469c8bdSFilipe Manana {
2399f469c8bdSFilipe Manana 	struct btrfs_key key;
2400f469c8bdSFilipe Manana 	struct btrfs_key orig_key;
2401f469c8bdSFilipe Manana 	struct btrfs_disk_key found_key;
2402f469c8bdSFilipe Manana 	int ret;
2403f469c8bdSFilipe Manana 
2404f469c8bdSFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
2405f469c8bdSFilipe Manana 	orig_key = key;
2406f469c8bdSFilipe Manana 
2407f469c8bdSFilipe Manana 	if (key.offset > 0) {
2408f469c8bdSFilipe Manana 		key.offset--;
2409f469c8bdSFilipe Manana 	} else if (key.type > 0) {
2410f469c8bdSFilipe Manana 		key.type--;
2411f469c8bdSFilipe Manana 		key.offset = (u64)-1;
2412f469c8bdSFilipe Manana 	} else if (key.objectid > 0) {
2413f469c8bdSFilipe Manana 		key.objectid--;
2414f469c8bdSFilipe Manana 		key.type = (u8)-1;
2415f469c8bdSFilipe Manana 		key.offset = (u64)-1;
2416f469c8bdSFilipe Manana 	} else {
2417f469c8bdSFilipe Manana 		return 1;
2418f469c8bdSFilipe Manana 	}
2419f469c8bdSFilipe Manana 
2420f469c8bdSFilipe Manana 	btrfs_release_path(path);
2421f469c8bdSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2422f469c8bdSFilipe Manana 	if (ret <= 0)
2423f469c8bdSFilipe Manana 		return ret;
2424f469c8bdSFilipe Manana 
2425f469c8bdSFilipe Manana 	/*
2426f469c8bdSFilipe Manana 	 * Previous key not found. Even if we were at slot 0 of the leaf we had
2427f469c8bdSFilipe Manana 	 * before releasing the path and calling btrfs_search_slot(), we now may
2428f469c8bdSFilipe Manana 	 * be in a slot pointing to the same original key - this can happen if
2429f469c8bdSFilipe Manana 	 * after we released the path, one of more items were moved from a
2430f469c8bdSFilipe Manana 	 * sibling leaf into the front of the leaf we had due to an insertion
2431f469c8bdSFilipe Manana 	 * (see push_leaf_right()).
2432f469c8bdSFilipe Manana 	 * If we hit this case and our slot is > 0 and just decrement the slot
2433f469c8bdSFilipe Manana 	 * so that the caller does not process the same key again, which may or
2434f469c8bdSFilipe Manana 	 * may not break the caller, depending on its logic.
2435f469c8bdSFilipe Manana 	 */
2436f469c8bdSFilipe Manana 	if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
2437f469c8bdSFilipe Manana 		btrfs_item_key(path->nodes[0], &found_key, path->slots[0]);
2438f469c8bdSFilipe Manana 		ret = comp_keys(&found_key, &orig_key);
2439f469c8bdSFilipe Manana 		if (ret == 0) {
2440f469c8bdSFilipe Manana 			if (path->slots[0] > 0) {
2441f469c8bdSFilipe Manana 				path->slots[0]--;
2442f469c8bdSFilipe Manana 				return 0;
2443f469c8bdSFilipe Manana 			}
2444f469c8bdSFilipe Manana 			/*
2445f469c8bdSFilipe Manana 			 * At slot 0, same key as before, it means orig_key is
2446f469c8bdSFilipe Manana 			 * the lowest, leftmost, key in the tree. We're done.
2447f469c8bdSFilipe Manana 			 */
2448f469c8bdSFilipe Manana 			return 1;
2449f469c8bdSFilipe Manana 		}
2450f469c8bdSFilipe Manana 	}
2451f469c8bdSFilipe Manana 
2452f469c8bdSFilipe Manana 	btrfs_item_key(path->nodes[0], &found_key, 0);
2453f469c8bdSFilipe Manana 	ret = comp_keys(&found_key, &key);
2454f469c8bdSFilipe Manana 	/*
2455f469c8bdSFilipe Manana 	 * We might have had an item with the previous key in the tree right
2456f469c8bdSFilipe Manana 	 * before we released our path. And after we released our path, that
2457f469c8bdSFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
2458f469c8bdSFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
2459f469c8bdSFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
2460f469c8bdSFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
2461f469c8bdSFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
2462f469c8bdSFilipe Manana 	 * the previous key we computed above.
2463f469c8bdSFilipe Manana 	 */
2464f469c8bdSFilipe Manana 	if (ret <= 0)
2465f469c8bdSFilipe Manana 		return 0;
2466f469c8bdSFilipe Manana 	return 1;
2467f469c8bdSFilipe Manana }
2468f469c8bdSFilipe Manana 
2469f469c8bdSFilipe Manana /*
24702f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
24712f38b3e1SArne Jansen  * instead the next or previous item should be returned.
24722f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
24732f38b3e1SArne Jansen  * otherwise.
24742f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
24752f38b3e1SArne Jansen  * return the next lower instead.
24762f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
24772f38b3e1SArne Jansen  * return the next higher instead.
24782f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
24792f38b3e1SArne Jansen  * < 0 on error
24802f38b3e1SArne Jansen  */
24812f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2482310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2483310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2484310712b2SOmar Sandoval 			       int return_any)
24852f38b3e1SArne Jansen {
24862f38b3e1SArne Jansen 	int ret;
24872f38b3e1SArne Jansen 	struct extent_buffer *leaf;
24882f38b3e1SArne Jansen 
24892f38b3e1SArne Jansen again:
24902f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
24912f38b3e1SArne Jansen 	if (ret <= 0)
24922f38b3e1SArne Jansen 		return ret;
24932f38b3e1SArne Jansen 	/*
24942f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
24952f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
24962f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
24972f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
24982f38b3e1SArne Jansen 	 * item.
24992f38b3e1SArne Jansen 	 */
25002f38b3e1SArne Jansen 	leaf = p->nodes[0];
25012f38b3e1SArne Jansen 
25022f38b3e1SArne Jansen 	if (find_higher) {
25032f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
25042f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
25052f38b3e1SArne Jansen 			if (ret <= 0)
25062f38b3e1SArne Jansen 				return ret;
25072f38b3e1SArne Jansen 			if (!return_any)
25082f38b3e1SArne Jansen 				return 1;
25092f38b3e1SArne Jansen 			/*
25102f38b3e1SArne Jansen 			 * no higher item found, return the next
25112f38b3e1SArne Jansen 			 * lower instead
25122f38b3e1SArne Jansen 			 */
25132f38b3e1SArne Jansen 			return_any = 0;
25142f38b3e1SArne Jansen 			find_higher = 0;
25152f38b3e1SArne Jansen 			btrfs_release_path(p);
25162f38b3e1SArne Jansen 			goto again;
25172f38b3e1SArne Jansen 		}
25182f38b3e1SArne Jansen 	} else {
25192f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
25202f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2521e6793769SArne Jansen 			if (ret < 0)
25222f38b3e1SArne Jansen 				return ret;
2523e6793769SArne Jansen 			if (!ret) {
252423c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
252523c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
252623c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2527e6793769SArne Jansen 				return 0;
2528e6793769SArne Jansen 			}
25292f38b3e1SArne Jansen 			if (!return_any)
25302f38b3e1SArne Jansen 				return 1;
25312f38b3e1SArne Jansen 			/*
25322f38b3e1SArne Jansen 			 * no lower item found, return the next
25332f38b3e1SArne Jansen 			 * higher instead
25342f38b3e1SArne Jansen 			 */
25352f38b3e1SArne Jansen 			return_any = 0;
25362f38b3e1SArne Jansen 			find_higher = 1;
25372f38b3e1SArne Jansen 			btrfs_release_path(p);
25382f38b3e1SArne Jansen 			goto again;
2539e6793769SArne Jansen 		} else {
25402f38b3e1SArne Jansen 			--p->slots[0];
25412f38b3e1SArne Jansen 		}
25422f38b3e1SArne Jansen 	}
25432f38b3e1SArne Jansen 	return 0;
25442f38b3e1SArne Jansen }
25452f38b3e1SArne Jansen 
25462f38b3e1SArne Jansen /*
25470ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
25480ff40a91SMarcos Paulo de Souza  * was not found.
25490ff40a91SMarcos Paulo de Souza  *
25500ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
25510ff40a91SMarcos Paulo de Souza  */
25520ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
25530ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
25540ff40a91SMarcos Paulo de Souza {
25550ff40a91SMarcos Paulo de Souza 	int ret;
25560ff40a91SMarcos Paulo de Souza 
25570ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
25580ff40a91SMarcos Paulo de Souza 	if (ret > 0)
25590ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
25600ff40a91SMarcos Paulo de Souza 
25610ff40a91SMarcos Paulo de Souza 	if (ret == 0)
25620ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
25630ff40a91SMarcos Paulo de Souza 
25640ff40a91SMarcos Paulo de Souza 	return ret;
25650ff40a91SMarcos Paulo de Souza }
25660ff40a91SMarcos Paulo de Souza 
256743dd529aSDavid Sterba /*
256862142be3SGabriel Niebler  * Search for a valid slot for the given path.
256962142be3SGabriel Niebler  *
257062142be3SGabriel Niebler  * @root:	The root node of the tree.
257162142be3SGabriel Niebler  * @key:	Will contain a valid item if found.
257262142be3SGabriel Niebler  * @path:	The starting point to validate the slot.
257362142be3SGabriel Niebler  *
257462142be3SGabriel Niebler  * Return: 0  if the item is valid
257562142be3SGabriel Niebler  *         1  if not found
257662142be3SGabriel Niebler  *         <0 if error.
257762142be3SGabriel Niebler  */
257862142be3SGabriel Niebler int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
257962142be3SGabriel Niebler 			      struct btrfs_path *path)
258062142be3SGabriel Niebler {
2581524f14bbSFilipe Manana 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
258262142be3SGabriel Niebler 		int ret;
258362142be3SGabriel Niebler 
258462142be3SGabriel Niebler 		ret = btrfs_next_leaf(root, path);
258562142be3SGabriel Niebler 		if (ret)
258662142be3SGabriel Niebler 			return ret;
258762142be3SGabriel Niebler 	}
2588524f14bbSFilipe Manana 
2589524f14bbSFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
259062142be3SGabriel Niebler 	return 0;
259162142be3SGabriel Niebler }
259262142be3SGabriel Niebler 
25930ff40a91SMarcos Paulo de Souza /*
259474123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
259574123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
259674123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
259774123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
259874123bd7SChris Mason  * higher levels
2599aa5d6bedSChris Mason  *
260074123bd7SChris Mason  */
2601b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
26025f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2603be0e5c09SChris Mason {
2604be0e5c09SChris Mason 	int i;
26055f39d397SChris Mason 	struct extent_buffer *t;
26060e82bcfeSDavid Sterba 	int ret;
26075f39d397SChris Mason 
2608234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2609be0e5c09SChris Mason 		int tslot = path->slots[i];
26100e82bcfeSDavid Sterba 
2611eb60ceacSChris Mason 		if (!path->nodes[i])
2612be0e5c09SChris Mason 			break;
26135f39d397SChris Mason 		t = path->nodes[i];
2614f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
261533cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
26160e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
26175f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2618d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2619be0e5c09SChris Mason 		if (tslot != 0)
2620be0e5c09SChris Mason 			break;
2621be0e5c09SChris Mason 	}
2622be0e5c09SChris Mason }
2623be0e5c09SChris Mason 
262474123bd7SChris Mason /*
262531840ae1SZheng Yan  * update item key.
262631840ae1SZheng Yan  *
262731840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
262831840ae1SZheng Yan  * that the new key won't break the order
262931840ae1SZheng Yan  */
2630b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2631b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2632310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
263331840ae1SZheng Yan {
263431840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
263531840ae1SZheng Yan 	struct extent_buffer *eb;
263631840ae1SZheng Yan 	int slot;
263731840ae1SZheng Yan 
263831840ae1SZheng Yan 	eb = path->nodes[0];
263931840ae1SZheng Yan 	slot = path->slots[0];
264031840ae1SZheng Yan 	if (slot > 0) {
264131840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
26427c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
2643eee3b811SQu Wenruo 			btrfs_print_leaf(eb);
26447c15d410SQu Wenruo 			btrfs_crit(fs_info,
26457c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
26467c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
26477c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
26487c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
26497c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
26507c15d410SQu Wenruo 				   new_key->offset);
26517c15d410SQu Wenruo 			BUG();
26527c15d410SQu Wenruo 		}
265331840ae1SZheng Yan 	}
265431840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
265531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
26567c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
2657eee3b811SQu Wenruo 			btrfs_print_leaf(eb);
26587c15d410SQu Wenruo 			btrfs_crit(fs_info,
26597c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
26607c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
26617c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
26627c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
26637c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
26647c15d410SQu Wenruo 				   new_key->offset);
26657c15d410SQu Wenruo 			BUG();
26667c15d410SQu Wenruo 		}
266731840ae1SZheng Yan 	}
266831840ae1SZheng Yan 
266931840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
267031840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
267131840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
267231840ae1SZheng Yan 	if (slot == 0)
2673b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
267431840ae1SZheng Yan }
267531840ae1SZheng Yan 
267631840ae1SZheng Yan /*
2677d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2678d16c702fSQu Wenruo  *
2679d16c702fSQu Wenruo  * Return true if something is wrong.
2680d16c702fSQu Wenruo  * Return false if everything is fine.
2681d16c702fSQu Wenruo  *
2682d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2683d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2684d16c702fSQu Wenruo  *
2685d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2686d16c702fSQu Wenruo  * --------------------------------------------------------------
2687d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2688d16c702fSQu Wenruo  *
2689d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2690d16c702fSQu Wenruo  * key in leaf @right is 7.
2691d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2692d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2693d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2694d16c702fSQu Wenruo  * key of @right.
2695d16c702fSQu Wenruo  */
2696d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2697d16c702fSQu Wenruo 			       struct extent_buffer *right)
2698d16c702fSQu Wenruo {
2699d16c702fSQu Wenruo 	struct btrfs_key left_last;
2700d16c702fSQu Wenruo 	struct btrfs_key right_first;
2701d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2702d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2703d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2704d16c702fSQu Wenruo 
2705d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2706d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2707d16c702fSQu Wenruo 		return false;
2708d16c702fSQu Wenruo 
2709d16c702fSQu Wenruo 	if (level) {
2710d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2711d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2712d16c702fSQu Wenruo 	} else {
2713d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2714d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2715d16c702fSQu Wenruo 	}
2716d16c702fSQu Wenruo 
271788ad95b0SFilipe Manana 	if (unlikely(btrfs_comp_cpu_keys(&left_last, &right_first) >= 0)) {
2718a2cea677SFilipe Manana 		btrfs_crit(left->fs_info, "left extent buffer:");
2719a2cea677SFilipe Manana 		btrfs_print_tree(left, false);
2720a2cea677SFilipe Manana 		btrfs_crit(left->fs_info, "right extent buffer:");
2721a2cea677SFilipe Manana 		btrfs_print_tree(right, false);
2722d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2723d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2724d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2725d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2726d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2727d16c702fSQu Wenruo 		return true;
2728d16c702fSQu Wenruo 	}
2729d16c702fSQu Wenruo 	return false;
2730d16c702fSQu Wenruo }
2731d16c702fSQu Wenruo 
2732d16c702fSQu Wenruo /*
273374123bd7SChris Mason  * try to push data from one node into the next node left in the
273479f95c82SChris Mason  * tree.
2735aa5d6bedSChris Mason  *
2736aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2737aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
273874123bd7SChris Mason  */
273998ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
27402ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2741971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2742be0e5c09SChris Mason {
2743d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2744be0e5c09SChris Mason 	int push_items = 0;
2745bb803951SChris Mason 	int src_nritems;
2746bb803951SChris Mason 	int dst_nritems;
2747aa5d6bedSChris Mason 	int ret = 0;
2748be0e5c09SChris Mason 
27495f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
27505f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
27510b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
27527bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
27537bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
275454aa1f4dSChris Mason 
2755bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2756971a1f66SChris Mason 		return 1;
2757971a1f66SChris Mason 
2758d397712bSChris Mason 	if (push_items <= 0)
2759be0e5c09SChris Mason 		return 1;
2760be0e5c09SChris Mason 
2761bce4eae9SChris Mason 	if (empty) {
2762971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2763bce4eae9SChris Mason 		if (push_items < src_nritems) {
2764bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2765bce4eae9SChris Mason 			 * we aren't going to empty it
2766bce4eae9SChris Mason 			 */
2767bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2768bce4eae9SChris Mason 				if (push_items <= 8)
2769bce4eae9SChris Mason 					return 1;
2770bce4eae9SChris Mason 				push_items -= 8;
2771bce4eae9SChris Mason 			}
2772bce4eae9SChris Mason 		}
2773bce4eae9SChris Mason 	} else
2774bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
277579f95c82SChris Mason 
2776d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2777d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2778d16c702fSQu Wenruo 		ret = -EUCLEAN;
2779d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2780d16c702fSQu Wenruo 		return ret;
2781d16c702fSQu Wenruo 	}
2782f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
27835de865eeSFilipe David Borba Manana 	if (ret) {
278466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
27855de865eeSFilipe David Borba Manana 		return ret;
27865de865eeSFilipe David Borba Manana 	}
27875f39d397SChris Mason 	copy_extent_buffer(dst, src,
2788e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, dst_nritems),
2789e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, 0),
2790123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
27915f39d397SChris Mason 
2792bb803951SChris Mason 	if (push_items < src_nritems) {
279357911b8bSJan Schmidt 		/*
27945cead542SBoris Burkov 		 * btrfs_tree_mod_log_eb_copy handles logging the move, so we
27955cead542SBoris Burkov 		 * don't need to do an explicit tree mod log operation for it.
279657911b8bSJan Schmidt 		 */
2797e23efd8eSJosef Bacik 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(src, 0),
2798e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(src, push_items),
2799e2fa7227SChris Mason 				      (src_nritems - push_items) *
2800123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2801bb803951SChris Mason 	}
28025f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
28035f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
28045f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
28055f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
280631840ae1SZheng Yan 
2807bb803951SChris Mason 	return ret;
2808be0e5c09SChris Mason }
2809be0e5c09SChris Mason 
281097571fd0SChris Mason /*
281179f95c82SChris Mason  * try to push data from one node into the next node right in the
281279f95c82SChris Mason  * tree.
281379f95c82SChris Mason  *
281479f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
281579f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
281679f95c82SChris Mason  *
281779f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
281879f95c82SChris Mason  */
28195f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
28205f39d397SChris Mason 			      struct extent_buffer *dst,
28215f39d397SChris Mason 			      struct extent_buffer *src)
282279f95c82SChris Mason {
282355d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
282479f95c82SChris Mason 	int push_items = 0;
282579f95c82SChris Mason 	int max_push;
282679f95c82SChris Mason 	int src_nritems;
282779f95c82SChris Mason 	int dst_nritems;
282879f95c82SChris Mason 	int ret = 0;
282979f95c82SChris Mason 
28307bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28317bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
28327bb86316SChris Mason 
28335f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28345f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
28350b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2836d397712bSChris Mason 	if (push_items <= 0)
283779f95c82SChris Mason 		return 1;
2838bce4eae9SChris Mason 
2839d397712bSChris Mason 	if (src_nritems < 4)
2840bce4eae9SChris Mason 		return 1;
284179f95c82SChris Mason 
284279f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
284379f95c82SChris Mason 	/* don't try to empty the node */
2844d397712bSChris Mason 	if (max_push >= src_nritems)
284579f95c82SChris Mason 		return 1;
2846252c38f0SYan 
284779f95c82SChris Mason 	if (max_push < push_items)
284879f95c82SChris Mason 		push_items = max_push;
284979f95c82SChris Mason 
2850d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2851d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2852d16c702fSQu Wenruo 		ret = -EUCLEAN;
2853d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2854d16c702fSQu Wenruo 		return ret;
2855d16c702fSQu Wenruo 	}
28565cead542SBoris Burkov 
28575cead542SBoris Burkov 	/*
28585cead542SBoris Burkov 	 * btrfs_tree_mod_log_eb_copy handles logging the move, so we don't
28595cead542SBoris Burkov 	 * need to do an explicit tree mod log operation for it.
28605cead542SBoris Burkov 	 */
2861e23efd8eSJosef Bacik 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(dst, push_items),
2862e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(dst, 0),
28635f39d397SChris Mason 				      (dst_nritems) *
28645f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2865d6025579SChris Mason 
2866f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2867ed874f0dSDavid Sterba 					 push_items);
28685de865eeSFilipe David Borba Manana 	if (ret) {
286966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
28705de865eeSFilipe David Borba Manana 		return ret;
28715de865eeSFilipe David Borba Manana 	}
28725f39d397SChris Mason 	copy_extent_buffer(dst, src,
2873e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, 0),
2874e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, src_nritems - push_items),
2875123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
287679f95c82SChris Mason 
28775f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
28785f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
287979f95c82SChris Mason 
28805f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
28815f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
288231840ae1SZheng Yan 
288379f95c82SChris Mason 	return ret;
288479f95c82SChris Mason }
288579f95c82SChris Mason 
288679f95c82SChris Mason /*
288797571fd0SChris Mason  * helper function to insert a new root level in the tree.
288897571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
288997571fd0SChris Mason  * point to the existing root
2890aa5d6bedSChris Mason  *
2891aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
289297571fd0SChris Mason  */
2893d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
28945f39d397SChris Mason 			   struct btrfs_root *root,
2895fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
289674123bd7SChris Mason {
28970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
28987bb86316SChris Mason 	u64 lower_gen;
28995f39d397SChris Mason 	struct extent_buffer *lower;
29005f39d397SChris Mason 	struct extent_buffer *c;
2901925baeddSChris Mason 	struct extent_buffer *old;
29025f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2903d9d19a01SDavid Sterba 	int ret;
29045c680ed6SChris Mason 
29055c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
29065c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
29075c680ed6SChris Mason 
29087bb86316SChris Mason 	lower = path->nodes[level-1];
29097bb86316SChris Mason 	if (level == 1)
29107bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
29117bb86316SChris Mason 	else
29127bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
29137bb86316SChris Mason 
291479bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
291579bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2916cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
29175f39d397SChris Mason 	if (IS_ERR(c))
29185f39d397SChris Mason 		return PTR_ERR(c);
2919925baeddSChris Mason 
29200b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2921f0486c68SYan, Zheng 
29225f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
29235f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2924db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
29257bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
292631840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
29277bb86316SChris Mason 
29287bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
29295f39d397SChris Mason 
29305f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2931d5719762SChris Mason 
2932925baeddSChris Mason 	old = root->node;
2933406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2934d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2935240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2936925baeddSChris Mason 
2937925baeddSChris Mason 	/* the super has an extra ref to root->node */
2938925baeddSChris Mason 	free_extent_buffer(old);
2939925baeddSChris Mason 
29400b86a832SChris Mason 	add_root_to_dirty_list(root);
294167439dadSDavid Sterba 	atomic_inc(&c->refs);
29425f39d397SChris Mason 	path->nodes[level] = c;
2943ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
294474123bd7SChris Mason 	path->slots[level] = 0;
294574123bd7SChris Mason 	return 0;
294674123bd7SChris Mason }
29475c680ed6SChris Mason 
29485c680ed6SChris Mason /*
29495c680ed6SChris Mason  * worker function to insert a single pointer in a node.
29505c680ed6SChris Mason  * the node should have enough room for the pointer already
295197571fd0SChris Mason  *
29525c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
29535c680ed6SChris Mason  * blocknr is the block the key points to.
29545c680ed6SChris Mason  */
2955143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
29566ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2957143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2958c3e06965SJan Schmidt 		       int slot, int level)
29595c680ed6SChris Mason {
29605f39d397SChris Mason 	struct extent_buffer *lower;
29615c680ed6SChris Mason 	int nritems;
2962f3ea38daSJan Schmidt 	int ret;
29635c680ed6SChris Mason 
29645c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
296549d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
29665f39d397SChris Mason 	lower = path->nodes[level];
29675f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2968c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
29696ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
297074123bd7SChris Mason 	if (slot != nritems) {
2971bf1d3425SDavid Sterba 		if (level) {
2972f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2973f3a84ccdSFilipe Manana 					slot, nritems - slot);
2974bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2975bf1d3425SDavid Sterba 		}
29765f39d397SChris Mason 		memmove_extent_buffer(lower,
2977e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot + 1),
2978e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot),
2979123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
298074123bd7SChris Mason 	}
2981c3e06965SJan Schmidt 	if (level) {
2982f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
298333cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_ADD);
2984f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2985f3ea38daSJan Schmidt 	}
29865f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2987db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
298874493f7aSChris Mason 	WARN_ON(trans->transid == 0);
298974493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
29905f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
29915f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
299274123bd7SChris Mason }
299374123bd7SChris Mason 
299497571fd0SChris Mason /*
299597571fd0SChris Mason  * split the node at the specified level in path in two.
299697571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
299797571fd0SChris Mason  *
299897571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
299997571fd0SChris Mason  * left and right, if either one works, it returns right away.
3000aa5d6bedSChris Mason  *
3001aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
300297571fd0SChris Mason  */
3003e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3004e02119d5SChris Mason 			       struct btrfs_root *root,
3005e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3006be0e5c09SChris Mason {
30070b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
30085f39d397SChris Mason 	struct extent_buffer *c;
30095f39d397SChris Mason 	struct extent_buffer *split;
30105f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3011be0e5c09SChris Mason 	int mid;
30125c680ed6SChris Mason 	int ret;
30137518a238SChris Mason 	u32 c_nritems;
3014be0e5c09SChris Mason 
30155f39d397SChris Mason 	c = path->nodes[level];
30167bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
30175f39d397SChris Mason 	if (c == root->node) {
3018d9abbf1cSJan Schmidt 		/*
301990f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
302090f8d62eSJan Schmidt 		 *
3021fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
302290f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
302390f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
3024f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
3025f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
3026f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
3027d9abbf1cSJan Schmidt 		 */
3028fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
30295c680ed6SChris Mason 		if (ret)
30305c680ed6SChris Mason 			return ret;
3031b3612421SChris Mason 	} else {
3032e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
30335f39d397SChris Mason 		c = path->nodes[level];
30345f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
30350b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3036e66f709bSChris Mason 			return 0;
303754aa1f4dSChris Mason 		if (ret < 0)
303854aa1f4dSChris Mason 			return ret;
30395c680ed6SChris Mason 	}
3040e66f709bSChris Mason 
30415f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
30425d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
30435d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
30447bb86316SChris Mason 
304579bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
304679bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
304779bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
30485f39d397SChris Mason 	if (IS_ERR(split))
30495f39d397SChris Mason 		return PTR_ERR(split);
305054aa1f4dSChris Mason 
30510b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3052bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
30535f39d397SChris Mason 
3054f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
30555de865eeSFilipe David Borba Manana 	if (ret) {
3056*ede600e4SFilipe Manana 		btrfs_tree_unlock(split);
3057*ede600e4SFilipe Manana 		free_extent_buffer(split);
305866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
30595de865eeSFilipe David Borba Manana 		return ret;
30605de865eeSFilipe David Borba Manana 	}
30615f39d397SChris Mason 	copy_extent_buffer(split, c,
3062e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(split, 0),
3063e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(c, mid),
3064123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
30655f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
30665f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3067aa5d6bedSChris Mason 
30685f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
30695f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
30705f39d397SChris Mason 
30716ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
3072c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3073aa5d6bedSChris Mason 
30745de08d7dSChris Mason 	if (path->slots[level] >= mid) {
30755c680ed6SChris Mason 		path->slots[level] -= mid;
3076925baeddSChris Mason 		btrfs_tree_unlock(c);
30775f39d397SChris Mason 		free_extent_buffer(c);
30785f39d397SChris Mason 		path->nodes[level] = split;
30795c680ed6SChris Mason 		path->slots[level + 1] += 1;
3080eb60ceacSChris Mason 	} else {
3081925baeddSChris Mason 		btrfs_tree_unlock(split);
30825f39d397SChris Mason 		free_extent_buffer(split);
3083be0e5c09SChris Mason 	}
3084d5286a92SNikolay Borisov 	return 0;
3085be0e5c09SChris Mason }
3086be0e5c09SChris Mason 
308774123bd7SChris Mason /*
308874123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
308974123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
309074123bd7SChris Mason  * space used both by the item structs and the item data
309174123bd7SChris Mason  */
30926c75a589SQu Wenruo static int leaf_space_used(const struct extent_buffer *l, int start, int nr)
3093be0e5c09SChris Mason {
3094be0e5c09SChris Mason 	int data_len;
30955f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3096d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3097be0e5c09SChris Mason 
3098be0e5c09SChris Mason 	if (!nr)
3099be0e5c09SChris Mason 		return 0;
31003212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
31013212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
31020783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3103d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3104be0e5c09SChris Mason 	return data_len;
3105be0e5c09SChris Mason }
3106be0e5c09SChris Mason 
310774123bd7SChris Mason /*
3108d4dbff95SChris Mason  * The space between the end of the leaf items and
3109d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3110d4dbff95SChris Mason  * the leaf has left for both items and data
3111d4dbff95SChris Mason  */
31126c75a589SQu Wenruo int btrfs_leaf_free_space(const struct extent_buffer *leaf)
3113d4dbff95SChris Mason {
3114e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
31155f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
31165f39d397SChris Mason 	int ret;
31170b246afaSJeff Mahoney 
31180b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
31195f39d397SChris Mason 	if (ret < 0) {
31200b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3121efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3122da17066cSJeff Mahoney 			   ret,
31230b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
31245f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
31255f39d397SChris Mason 	}
31265f39d397SChris Mason 	return ret;
3127d4dbff95SChris Mason }
3128d4dbff95SChris Mason 
312999d8f83cSChris Mason /*
313099d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
313199d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
313299d8f83cSChris Mason  */
3133ed25dab3SJosef Bacik static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
3134ed25dab3SJosef Bacik 				      struct btrfs_path *path,
313544871b1bSChris Mason 				      int data_size, int empty,
313644871b1bSChris Mason 				      struct extent_buffer *right,
313799d8f83cSChris Mason 				      int free_space, u32 left_nritems,
313899d8f83cSChris Mason 				      u32 min_slot)
313900ec4c51SChris Mason {
3140f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
31415f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
314244871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3143cfed81a0SChris Mason 	struct btrfs_map_token token;
31445f39d397SChris Mason 	struct btrfs_disk_key disk_key;
314500ec4c51SChris Mason 	int slot;
314634a38218SChris Mason 	u32 i;
314700ec4c51SChris Mason 	int push_space = 0;
314800ec4c51SChris Mason 	int push_items = 0;
314934a38218SChris Mason 	u32 nr;
31507518a238SChris Mason 	u32 right_nritems;
31515f39d397SChris Mason 	u32 data_end;
3152db94535dSChris Mason 	u32 this_item_size;
315300ec4c51SChris Mason 
315434a38218SChris Mason 	if (empty)
315534a38218SChris Mason 		nr = 0;
315634a38218SChris Mason 	else
315799d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
315834a38218SChris Mason 
315931840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
316087b29b20SYan Zheng 		push_space += data_size;
316131840ae1SZheng Yan 
316244871b1bSChris Mason 	slot = path->slots[1];
316334a38218SChris Mason 	i = left_nritems - 1;
316434a38218SChris Mason 	while (i >= nr) {
316531840ae1SZheng Yan 		if (!empty && push_items > 0) {
316631840ae1SZheng Yan 			if (path->slots[0] > i)
316731840ae1SZheng Yan 				break;
316831840ae1SZheng Yan 			if (path->slots[0] == i) {
3169e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3170e902baacSDavid Sterba 
317131840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
317231840ae1SZheng Yan 					break;
317331840ae1SZheng Yan 			}
317431840ae1SZheng Yan 		}
317531840ae1SZheng Yan 
317600ec4c51SChris Mason 		if (path->slots[0] == i)
317787b29b20SYan Zheng 			push_space += data_size;
3178db94535dSChris Mason 
31793212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
318074794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
318174794207SJosef Bacik 		    push_space > free_space)
318200ec4c51SChris Mason 			break;
318331840ae1SZheng Yan 
318400ec4c51SChris Mason 		push_items++;
318574794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
318634a38218SChris Mason 		if (i == 0)
318734a38218SChris Mason 			break;
318834a38218SChris Mason 		i--;
3189db94535dSChris Mason 	}
31905f39d397SChris Mason 
3191925baeddSChris Mason 	if (push_items == 0)
3192925baeddSChris Mason 		goto out_unlock;
31935f39d397SChris Mason 
31946c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
31955f39d397SChris Mason 
319600ec4c51SChris Mason 	/* push left to right */
31975f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
319834a38218SChris Mason 
3199dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
32008f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
32015f39d397SChris Mason 
320200ec4c51SChris Mason 	/* make room in the right data area */
32038f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
3204637e3b48SJosef Bacik 	memmove_leaf_data(right, data_end - push_space, data_end,
32050b246afaSJeff Mahoney 			  BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
32065f39d397SChris Mason 
320700ec4c51SChris Mason 	/* copy from the left data area */
3208637e3b48SJosef Bacik 	copy_leaf_data(right, left, BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3209637e3b48SJosef Bacik 		       leaf_data_end(left), push_space);
32105f39d397SChris Mason 
3211637e3b48SJosef Bacik 	memmove_leaf_items(right, push_items, 0, right_nritems);
32125f39d397SChris Mason 
321300ec4c51SChris Mason 	/* copy the items from left to right */
3214637e3b48SJosef Bacik 	copy_leaf_items(right, left, 0, left_nritems - push_items, push_items);
321500ec4c51SChris Mason 
321600ec4c51SChris Mason 	/* update the item pointers */
3217c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
32187518a238SChris Mason 	right_nritems += push_items;
32195f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
32200b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
32217518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
32223212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
32233212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3224db94535dSChris Mason 	}
3225db94535dSChris Mason 
32267518a238SChris Mason 	left_nritems -= push_items;
32275f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
322800ec4c51SChris Mason 
322934a38218SChris Mason 	if (left_nritems)
32305f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3231f0486c68SYan, Zheng 	else
3232190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, left);
3233f0486c68SYan, Zheng 
32345f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3235a429e513SChris Mason 
32365f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
32375f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3238d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
323902217ed2SChris Mason 
324000ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
32417518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
32427518a238SChris Mason 		path->slots[0] -= left_nritems;
3243925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3244190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, path->nodes[0]);
3245925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32465f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32475f39d397SChris Mason 		path->nodes[0] = right;
324800ec4c51SChris Mason 		path->slots[1] += 1;
324900ec4c51SChris Mason 	} else {
3250925baeddSChris Mason 		btrfs_tree_unlock(right);
32515f39d397SChris Mason 		free_extent_buffer(right);
325200ec4c51SChris Mason 	}
325300ec4c51SChris Mason 	return 0;
3254925baeddSChris Mason 
3255925baeddSChris Mason out_unlock:
3256925baeddSChris Mason 	btrfs_tree_unlock(right);
3257925baeddSChris Mason 	free_extent_buffer(right);
3258925baeddSChris Mason 	return 1;
325900ec4c51SChris Mason }
3260925baeddSChris Mason 
326100ec4c51SChris Mason /*
326244871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
326374123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
326444871b1bSChris Mason  *
326544871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
326644871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
326799d8f83cSChris Mason  *
326899d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
326999d8f83cSChris Mason  * push any slot lower than min_slot
327074123bd7SChris Mason  */
327144871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
327299d8f83cSChris Mason 			   *root, struct btrfs_path *path,
327399d8f83cSChris Mason 			   int min_data_size, int data_size,
327499d8f83cSChris Mason 			   int empty, u32 min_slot)
3275be0e5c09SChris Mason {
327644871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
327744871b1bSChris Mason 	struct extent_buffer *right;
327844871b1bSChris Mason 	struct extent_buffer *upper;
327944871b1bSChris Mason 	int slot;
328044871b1bSChris Mason 	int free_space;
328144871b1bSChris Mason 	u32 left_nritems;
328244871b1bSChris Mason 	int ret;
328344871b1bSChris Mason 
328444871b1bSChris Mason 	if (!path->nodes[1])
328544871b1bSChris Mason 		return 1;
328644871b1bSChris Mason 
328744871b1bSChris Mason 	slot = path->slots[1];
328844871b1bSChris Mason 	upper = path->nodes[1];
328944871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
329044871b1bSChris Mason 		return 1;
329144871b1bSChris Mason 
329249d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
329344871b1bSChris Mason 
32944b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3295fb770ae4SLiu Bo 	if (IS_ERR(right))
32969cf14029SJosef Bacik 		return PTR_ERR(right);
329791ca338dSTsutomu Itoh 
3298bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
329944871b1bSChris Mason 
3300e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
330144871b1bSChris Mason 	if (free_space < data_size)
330244871b1bSChris Mason 		goto out_unlock;
330344871b1bSChris Mason 
330444871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3305bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
330644871b1bSChris Mason 	if (ret)
330744871b1bSChris Mason 		goto out_unlock;
330844871b1bSChris Mason 
330944871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
331044871b1bSChris Mason 	if (left_nritems == 0)
331144871b1bSChris Mason 		goto out_unlock;
331244871b1bSChris Mason 
3313d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3314d16c702fSQu Wenruo 		ret = -EUCLEAN;
33159ae5afd0SFilipe Manana 		btrfs_abort_transaction(trans, ret);
3316d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3317d16c702fSQu Wenruo 		free_extent_buffer(right);
3318d16c702fSQu Wenruo 		return ret;
3319d16c702fSQu Wenruo 	}
33202ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
33212ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
33222ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
33232ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
332452042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
33252ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
33262ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
33272ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
33282ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
33292ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
33302ef1fed2SFilipe David Borba Manana 		return 0;
33312ef1fed2SFilipe David Borba Manana 	}
33322ef1fed2SFilipe David Borba Manana 
3333ed25dab3SJosef Bacik 	return __push_leaf_right(trans, path, min_data_size, empty, right,
3334ed25dab3SJosef Bacik 				 free_space, left_nritems, min_slot);
333544871b1bSChris Mason out_unlock:
333644871b1bSChris Mason 	btrfs_tree_unlock(right);
333744871b1bSChris Mason 	free_extent_buffer(right);
333844871b1bSChris Mason 	return 1;
333944871b1bSChris Mason }
334044871b1bSChris Mason 
334144871b1bSChris Mason /*
334244871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
334344871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
334499d8f83cSChris Mason  *
334599d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
334699d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
334799d8f83cSChris Mason  * items
334844871b1bSChris Mason  */
3349ed25dab3SJosef Bacik static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
3350ed25dab3SJosef Bacik 				     struct btrfs_path *path, int data_size,
335144871b1bSChris Mason 				     int empty, struct extent_buffer *left,
335299d8f83cSChris Mason 				     int free_space, u32 right_nritems,
335399d8f83cSChris Mason 				     u32 max_slot)
335444871b1bSChris Mason {
33558087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
33565f39d397SChris Mason 	struct btrfs_disk_key disk_key;
33575f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3358be0e5c09SChris Mason 	int i;
3359be0e5c09SChris Mason 	int push_space = 0;
3360be0e5c09SChris Mason 	int push_items = 0;
33617518a238SChris Mason 	u32 old_left_nritems;
336234a38218SChris Mason 	u32 nr;
3363aa5d6bedSChris Mason 	int ret = 0;
3364db94535dSChris Mason 	u32 this_item_size;
3365db94535dSChris Mason 	u32 old_left_item_size;
3366cfed81a0SChris Mason 	struct btrfs_map_token token;
3367cfed81a0SChris Mason 
336834a38218SChris Mason 	if (empty)
336999d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
337034a38218SChris Mason 	else
337199d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
337234a38218SChris Mason 
337334a38218SChris Mason 	for (i = 0; i < nr; i++) {
337431840ae1SZheng Yan 		if (!empty && push_items > 0) {
337531840ae1SZheng Yan 			if (path->slots[0] < i)
337631840ae1SZheng Yan 				break;
337731840ae1SZheng Yan 			if (path->slots[0] == i) {
3378e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3379e902baacSDavid Sterba 
338031840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
338131840ae1SZheng Yan 					break;
338231840ae1SZheng Yan 			}
338331840ae1SZheng Yan 		}
338431840ae1SZheng Yan 
3385be0e5c09SChris Mason 		if (path->slots[0] == i)
338687b29b20SYan Zheng 			push_space += data_size;
3387db94535dSChris Mason 
33883212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
338974794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
339074794207SJosef Bacik 		    free_space)
3391be0e5c09SChris Mason 			break;
3392db94535dSChris Mason 
3393be0e5c09SChris Mason 		push_items++;
339474794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3395be0e5c09SChris Mason 	}
3396db94535dSChris Mason 
3397be0e5c09SChris Mason 	if (push_items == 0) {
3398925baeddSChris Mason 		ret = 1;
3399925baeddSChris Mason 		goto out;
3400be0e5c09SChris Mason 	}
3401fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
34025f39d397SChris Mason 
3403be0e5c09SChris Mason 	/* push data from right to left */
3404637e3b48SJosef Bacik 	copy_leaf_items(left, right, btrfs_header_nritems(left), 0, push_items);
34055f39d397SChris Mason 
34060b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
34073212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
34085f39d397SChris Mason 
3409637e3b48SJosef Bacik 	copy_leaf_data(left, right, leaf_data_end(left) - push_space,
3410637e3b48SJosef Bacik 		       btrfs_item_offset(right, push_items - 1), push_space);
34115f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
341287b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3413eb60ceacSChris Mason 
3414c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
34153212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3416be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
34175f39d397SChris Mason 		u32 ioff;
3418db94535dSChris Mason 
34193212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
34203212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3421cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3422be0e5c09SChris Mason 	}
34235f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3424be0e5c09SChris Mason 
3425be0e5c09SChris Mason 	/* fixup right node */
342631b1a2bdSJulia Lawall 	if (push_items > right_nritems)
342731b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3428d397712bSChris Mason 		       right_nritems);
342934a38218SChris Mason 
343034a38218SChris Mason 	if (push_items < right_nritems) {
34313212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
34328f881e8cSDavid Sterba 						  leaf_data_end(right);
3433637e3b48SJosef Bacik 		memmove_leaf_data(right,
34340b246afaSJeff Mahoney 				  BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
34358f881e8cSDavid Sterba 				  leaf_data_end(right), push_space);
34365f39d397SChris Mason 
3437637e3b48SJosef Bacik 		memmove_leaf_items(right, 0, push_items,
3438637e3b48SJosef Bacik 				   btrfs_header_nritems(right) - push_items);
343934a38218SChris Mason 	}
3440c82f823cSDavid Sterba 
3441c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3442eef1c494SYan 	right_nritems -= push_items;
3443eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
34440b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
34455f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
34463212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
34473212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3448db94535dSChris Mason 	}
3449eb60ceacSChris Mason 
34505f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
345134a38218SChris Mason 	if (right_nritems)
34525f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3453f0486c68SYan, Zheng 	else
3454190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, right);
3455098f59c2SChris Mason 
34565f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3457b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3458be0e5c09SChris Mason 
3459be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3460be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3461be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3462925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
34635f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
34645f39d397SChris Mason 		path->nodes[0] = left;
3465be0e5c09SChris Mason 		path->slots[1] -= 1;
3466be0e5c09SChris Mason 	} else {
3467925baeddSChris Mason 		btrfs_tree_unlock(left);
34685f39d397SChris Mason 		free_extent_buffer(left);
3469be0e5c09SChris Mason 		path->slots[0] -= push_items;
3470be0e5c09SChris Mason 	}
3471eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3472aa5d6bedSChris Mason 	return ret;
3473925baeddSChris Mason out:
3474925baeddSChris Mason 	btrfs_tree_unlock(left);
3475925baeddSChris Mason 	free_extent_buffer(left);
3476925baeddSChris Mason 	return ret;
3477be0e5c09SChris Mason }
3478be0e5c09SChris Mason 
347974123bd7SChris Mason /*
348044871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
348144871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
348299d8f83cSChris Mason  *
348399d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
348499d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
348599d8f83cSChris Mason  * items
348644871b1bSChris Mason  */
348744871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
348899d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
348999d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
349044871b1bSChris Mason {
349144871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
349244871b1bSChris Mason 	struct extent_buffer *left;
349344871b1bSChris Mason 	int slot;
349444871b1bSChris Mason 	int free_space;
349544871b1bSChris Mason 	u32 right_nritems;
349644871b1bSChris Mason 	int ret = 0;
349744871b1bSChris Mason 
349844871b1bSChris Mason 	slot = path->slots[1];
349944871b1bSChris Mason 	if (slot == 0)
350044871b1bSChris Mason 		return 1;
350144871b1bSChris Mason 	if (!path->nodes[1])
350244871b1bSChris Mason 		return 1;
350344871b1bSChris Mason 
350444871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
350544871b1bSChris Mason 	if (right_nritems == 0)
350644871b1bSChris Mason 		return 1;
350744871b1bSChris Mason 
350849d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
350944871b1bSChris Mason 
35104b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3511fb770ae4SLiu Bo 	if (IS_ERR(left))
35129cf14029SJosef Bacik 		return PTR_ERR(left);
351391ca338dSTsutomu Itoh 
3514bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
351544871b1bSChris Mason 
3516e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
351744871b1bSChris Mason 	if (free_space < data_size) {
351844871b1bSChris Mason 		ret = 1;
351944871b1bSChris Mason 		goto out;
352044871b1bSChris Mason 	}
352144871b1bSChris Mason 
352244871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
35239631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3524bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
352544871b1bSChris Mason 	if (ret) {
352644871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
352779787eaaSJeff Mahoney 		if (ret == -ENOSPC)
352844871b1bSChris Mason 			ret = 1;
352944871b1bSChris Mason 		goto out;
353044871b1bSChris Mason 	}
353144871b1bSChris Mason 
3532d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3533d16c702fSQu Wenruo 		ret = -EUCLEAN;
35349ae5afd0SFilipe Manana 		btrfs_abort_transaction(trans, ret);
3535d16c702fSQu Wenruo 		goto out;
3536d16c702fSQu Wenruo 	}
3537ed25dab3SJosef Bacik 	return __push_leaf_left(trans, path, min_data_size, empty, left,
3538ed25dab3SJosef Bacik 				free_space, right_nritems, max_slot);
353944871b1bSChris Mason out:
354044871b1bSChris Mason 	btrfs_tree_unlock(left);
354144871b1bSChris Mason 	free_extent_buffer(left);
354244871b1bSChris Mason 	return ret;
354344871b1bSChris Mason }
354444871b1bSChris Mason 
354544871b1bSChris Mason /*
354674123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
354774123bd7SChris Mason  * available for the resulting leaf level of the path.
354874123bd7SChris Mason  */
3549143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
355044871b1bSChris Mason 				    struct btrfs_path *path,
355144871b1bSChris Mason 				    struct extent_buffer *l,
355244871b1bSChris Mason 				    struct extent_buffer *right,
355344871b1bSChris Mason 				    int slot, int mid, int nritems)
3554be0e5c09SChris Mason {
355594f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3556be0e5c09SChris Mason 	int data_copy_size;
3557be0e5c09SChris Mason 	int rt_data_off;
3558be0e5c09SChris Mason 	int i;
3559d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3560cfed81a0SChris Mason 	struct btrfs_map_token token;
3561cfed81a0SChris Mason 
35625f39d397SChris Mason 	nritems = nritems - mid;
35635f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3564dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
35655f39d397SChris Mason 
3566637e3b48SJosef Bacik 	copy_leaf_items(right, l, 0, mid, nritems);
35675f39d397SChris Mason 
3568637e3b48SJosef Bacik 	copy_leaf_data(right, l, BTRFS_LEAF_DATA_SIZE(fs_info) - data_copy_size,
35698f881e8cSDavid Sterba 		       leaf_data_end(l), data_copy_size);
357074123bd7SChris Mason 
3571dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
35725f39d397SChris Mason 
3573c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
35745f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3575db94535dSChris Mason 		u32 ioff;
3576db94535dSChris Mason 
35773212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
35783212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
35790783fcfcSChris Mason 	}
358074123bd7SChris Mason 
35815f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
35825f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
35836ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
35845f39d397SChris Mason 
35855f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
35865f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3587eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
35885f39d397SChris Mason 
3589be0e5c09SChris Mason 	if (mid <= slot) {
3590925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
35915f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
35925f39d397SChris Mason 		path->nodes[0] = right;
3593be0e5c09SChris Mason 		path->slots[0] -= mid;
3594be0e5c09SChris Mason 		path->slots[1] += 1;
3595925baeddSChris Mason 	} else {
3596925baeddSChris Mason 		btrfs_tree_unlock(right);
35975f39d397SChris Mason 		free_extent_buffer(right);
3598925baeddSChris Mason 	}
35995f39d397SChris Mason 
3600eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
360144871b1bSChris Mason }
360244871b1bSChris Mason 
360344871b1bSChris Mason /*
360499d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
360599d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
360699d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
360799d8f83cSChris Mason  *          A                 B                 C
360899d8f83cSChris Mason  *
360999d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
361099d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
361199d8f83cSChris Mason  * completely.
361299d8f83cSChris Mason  */
361399d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
361499d8f83cSChris Mason 					  struct btrfs_root *root,
361599d8f83cSChris Mason 					  struct btrfs_path *path,
361699d8f83cSChris Mason 					  int data_size)
361799d8f83cSChris Mason {
361899d8f83cSChris Mason 	int ret;
361999d8f83cSChris Mason 	int progress = 0;
362099d8f83cSChris Mason 	int slot;
362199d8f83cSChris Mason 	u32 nritems;
36225a4267caSFilipe David Borba Manana 	int space_needed = data_size;
362399d8f83cSChris Mason 
362499d8f83cSChris Mason 	slot = path->slots[0];
36255a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3626e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
362799d8f83cSChris Mason 
362899d8f83cSChris Mason 	/*
362999d8f83cSChris Mason 	 * try to push all the items after our slot into the
363099d8f83cSChris Mason 	 * right leaf
363199d8f83cSChris Mason 	 */
36325a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
363399d8f83cSChris Mason 	if (ret < 0)
363499d8f83cSChris Mason 		return ret;
363599d8f83cSChris Mason 
363699d8f83cSChris Mason 	if (ret == 0)
363799d8f83cSChris Mason 		progress++;
363899d8f83cSChris Mason 
363999d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
364099d8f83cSChris Mason 	/*
364199d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
364299d8f83cSChris Mason 	 * we've done so we're done
364399d8f83cSChris Mason 	 */
364499d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
364599d8f83cSChris Mason 		return 0;
364699d8f83cSChris Mason 
3647e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
364899d8f83cSChris Mason 		return 0;
364999d8f83cSChris Mason 
365099d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
365199d8f83cSChris Mason 	slot = path->slots[0];
3652263d3995SFilipe Manana 	space_needed = data_size;
3653263d3995SFilipe Manana 	if (slot > 0)
3654e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
36555a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
365699d8f83cSChris Mason 	if (ret < 0)
365799d8f83cSChris Mason 		return ret;
365899d8f83cSChris Mason 
365999d8f83cSChris Mason 	if (ret == 0)
366099d8f83cSChris Mason 		progress++;
366199d8f83cSChris Mason 
366299d8f83cSChris Mason 	if (progress)
366399d8f83cSChris Mason 		return 0;
366499d8f83cSChris Mason 	return 1;
366599d8f83cSChris Mason }
366699d8f83cSChris Mason 
366799d8f83cSChris Mason /*
366844871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
366944871b1bSChris Mason  * available for the resulting leaf level of the path.
367044871b1bSChris Mason  *
367144871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
367244871b1bSChris Mason  */
367344871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
367444871b1bSChris Mason 			       struct btrfs_root *root,
3675310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
367644871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
367744871b1bSChris Mason 			       int extend)
367844871b1bSChris Mason {
36795d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
368044871b1bSChris Mason 	struct extent_buffer *l;
368144871b1bSChris Mason 	u32 nritems;
368244871b1bSChris Mason 	int mid;
368344871b1bSChris Mason 	int slot;
368444871b1bSChris Mason 	struct extent_buffer *right;
3685b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
368644871b1bSChris Mason 	int ret = 0;
368744871b1bSChris Mason 	int wret;
36885d4f98a2SYan Zheng 	int split;
368944871b1bSChris Mason 	int num_doubles = 0;
369099d8f83cSChris Mason 	int tried_avoid_double = 0;
369144871b1bSChris Mason 
3692a5719521SYan, Zheng 	l = path->nodes[0];
3693a5719521SYan, Zheng 	slot = path->slots[0];
36943212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
36950b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3696a5719521SYan, Zheng 		return -EOVERFLOW;
3697a5719521SYan, Zheng 
369844871b1bSChris Mason 	/* first try to make some room by pushing left and right */
369933157e05SLiu Bo 	if (data_size && path->nodes[1]) {
37005a4267caSFilipe David Borba Manana 		int space_needed = data_size;
37015a4267caSFilipe David Borba Manana 
37025a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3703e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
37045a4267caSFilipe David Borba Manana 
37055a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
37065a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
370744871b1bSChris Mason 		if (wret < 0)
370844871b1bSChris Mason 			return wret;
370944871b1bSChris Mason 		if (wret) {
3710263d3995SFilipe Manana 			space_needed = data_size;
3711263d3995SFilipe Manana 			if (slot > 0)
3712e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
37135a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
37145a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
371544871b1bSChris Mason 			if (wret < 0)
371644871b1bSChris Mason 				return wret;
371744871b1bSChris Mason 		}
371844871b1bSChris Mason 		l = path->nodes[0];
371944871b1bSChris Mason 
372044871b1bSChris Mason 		/* did the pushes work? */
3721e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
372244871b1bSChris Mason 			return 0;
372344871b1bSChris Mason 	}
372444871b1bSChris Mason 
372544871b1bSChris Mason 	if (!path->nodes[1]) {
3726fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
372744871b1bSChris Mason 		if (ret)
372844871b1bSChris Mason 			return ret;
372944871b1bSChris Mason 	}
373044871b1bSChris Mason again:
37315d4f98a2SYan Zheng 	split = 1;
373244871b1bSChris Mason 	l = path->nodes[0];
373344871b1bSChris Mason 	slot = path->slots[0];
373444871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
373544871b1bSChris Mason 	mid = (nritems + 1) / 2;
373644871b1bSChris Mason 
37375d4f98a2SYan Zheng 	if (mid <= slot) {
37385d4f98a2SYan Zheng 		if (nritems == 1 ||
37395d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
37400b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
37415d4f98a2SYan Zheng 			if (slot >= nritems) {
37425d4f98a2SYan Zheng 				split = 0;
37435d4f98a2SYan Zheng 			} else {
37445d4f98a2SYan Zheng 				mid = slot;
37455d4f98a2SYan Zheng 				if (mid != nritems &&
37465d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
37470b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
374899d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
374999d8f83cSChris Mason 						goto push_for_double;
37505d4f98a2SYan Zheng 					split = 2;
37515d4f98a2SYan Zheng 				}
37525d4f98a2SYan Zheng 			}
37535d4f98a2SYan Zheng 		}
37545d4f98a2SYan Zheng 	} else {
37555d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
37560b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
37575d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
37585d4f98a2SYan Zheng 				split = 0;
37595d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
37605d4f98a2SYan Zheng 				mid = 1;
37615d4f98a2SYan Zheng 			} else {
37625d4f98a2SYan Zheng 				mid = slot;
37635d4f98a2SYan Zheng 				if (mid != nritems &&
37645d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
37650b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
376699d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
376799d8f83cSChris Mason 						goto push_for_double;
37685d4f98a2SYan Zheng 					split = 2;
37695d4f98a2SYan Zheng 				}
37705d4f98a2SYan Zheng 			}
37715d4f98a2SYan Zheng 		}
37725d4f98a2SYan Zheng 	}
37735d4f98a2SYan Zheng 
37745d4f98a2SYan Zheng 	if (split == 0)
37755d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
37765d4f98a2SYan Zheng 	else
37775d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
37785d4f98a2SYan Zheng 
3779ca9d473aSJosef Bacik 	/*
3780ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3781ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3782ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3783ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3784ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3785ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3786ca9d473aSJosef Bacik 	 */
378779bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
378879bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
378979bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3790ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3791f0486c68SYan, Zheng 	if (IS_ERR(right))
379244871b1bSChris Mason 		return PTR_ERR(right);
3793f0486c68SYan, Zheng 
37940b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
379544871b1bSChris Mason 
37965d4f98a2SYan Zheng 	if (split == 0) {
379744871b1bSChris Mason 		if (mid <= slot) {
379844871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
37996ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
38002ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
380144871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
380244871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
380344871b1bSChris Mason 			path->nodes[0] = right;
380444871b1bSChris Mason 			path->slots[0] = 0;
380544871b1bSChris Mason 			path->slots[1] += 1;
380644871b1bSChris Mason 		} else {
380744871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
38086ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
38092ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
381044871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
381144871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
381244871b1bSChris Mason 			path->nodes[0] = right;
381344871b1bSChris Mason 			path->slots[0] = 0;
3814143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3815b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
38165d4f98a2SYan Zheng 		}
3817196e0249SLiu Bo 		/*
3818196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3819196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3820196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3821196e0249SLiu Bo 		 */
382244871b1bSChris Mason 		return ret;
382344871b1bSChris Mason 	}
382444871b1bSChris Mason 
382594f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
382644871b1bSChris Mason 
38275d4f98a2SYan Zheng 	if (split == 2) {
3828cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3829cc0c5538SChris Mason 		num_doubles++;
3830cc0c5538SChris Mason 		goto again;
38313326d1b0SChris Mason 	}
383244871b1bSChris Mason 
3833143bede5SJeff Mahoney 	return 0;
383499d8f83cSChris Mason 
383599d8f83cSChris Mason push_for_double:
383699d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
383799d8f83cSChris Mason 	tried_avoid_double = 1;
3838e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
383999d8f83cSChris Mason 		return 0;
384099d8f83cSChris Mason 	goto again;
3841be0e5c09SChris Mason }
3842be0e5c09SChris Mason 
3843ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3844ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3845ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3846ad48fd75SYan, Zheng {
3847ad48fd75SYan, Zheng 	struct btrfs_key key;
3848ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3849ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3850ad48fd75SYan, Zheng 	u64 extent_len = 0;
3851ad48fd75SYan, Zheng 	u32 item_size;
3852ad48fd75SYan, Zheng 	int ret;
3853ad48fd75SYan, Zheng 
3854ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3855ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3856ad48fd75SYan, Zheng 
3857ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3858ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3859ad48fd75SYan, Zheng 
3860e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3861ad48fd75SYan, Zheng 		return 0;
3862ad48fd75SYan, Zheng 
38633212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3864ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3865ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3866ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3867ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3868ad48fd75SYan, Zheng 	}
3869b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3870ad48fd75SYan, Zheng 
3871ad48fd75SYan, Zheng 	path->keep_locks = 1;
3872ad48fd75SYan, Zheng 	path->search_for_split = 1;
3873ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3874ad48fd75SYan, Zheng 	path->search_for_split = 0;
3875a8df6fe6SFilipe Manana 	if (ret > 0)
3876a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3877ad48fd75SYan, Zheng 	if (ret < 0)
3878ad48fd75SYan, Zheng 		goto err;
3879ad48fd75SYan, Zheng 
3880ad48fd75SYan, Zheng 	ret = -EAGAIN;
3881ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3882a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
38833212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3884ad48fd75SYan, Zheng 		goto err;
3885ad48fd75SYan, Zheng 
3886109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3887e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3888109f6aefSChris Mason 		goto err;
3889109f6aefSChris Mason 
3890ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3891ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3892ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3893ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3894ad48fd75SYan, Zheng 			goto err;
3895ad48fd75SYan, Zheng 	}
3896ad48fd75SYan, Zheng 
3897ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3898f0486c68SYan, Zheng 	if (ret)
3899f0486c68SYan, Zheng 		goto err;
3900ad48fd75SYan, Zheng 
3901ad48fd75SYan, Zheng 	path->keep_locks = 0;
3902ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3903ad48fd75SYan, Zheng 	return 0;
3904ad48fd75SYan, Zheng err:
3905ad48fd75SYan, Zheng 	path->keep_locks = 0;
3906ad48fd75SYan, Zheng 	return ret;
3907ad48fd75SYan, Zheng }
3908ad48fd75SYan, Zheng 
390925263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3910310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3911459931ecSChris Mason 			       unsigned long split_offset)
3912459931ecSChris Mason {
3913459931ecSChris Mason 	struct extent_buffer *leaf;
3914c91666b1SJosef Bacik 	int orig_slot, slot;
3915ad48fd75SYan, Zheng 	char *buf;
3916459931ecSChris Mason 	u32 nritems;
3917ad48fd75SYan, Zheng 	u32 item_size;
3918459931ecSChris Mason 	u32 orig_offset;
3919459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3920459931ecSChris Mason 
3921459931ecSChris Mason 	leaf = path->nodes[0];
3922e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3923b9473439SChris Mason 
3924c91666b1SJosef Bacik 	orig_slot = path->slots[0];
39253212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
39263212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3927459931ecSChris Mason 
3928459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3929ad48fd75SYan, Zheng 	if (!buf)
3930ad48fd75SYan, Zheng 		return -ENOMEM;
3931ad48fd75SYan, Zheng 
3932459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3933459931ecSChris Mason 			    path->slots[0]), item_size);
3934ad48fd75SYan, Zheng 
3935459931ecSChris Mason 	slot = path->slots[0] + 1;
3936459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3937459931ecSChris Mason 	if (slot != nritems) {
3938459931ecSChris Mason 		/* shift the items */
3939637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot + 1, slot, nritems - slot);
3940459931ecSChris Mason 	}
3941459931ecSChris Mason 
3942459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3943459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3944459931ecSChris Mason 
39453212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
39463212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3947459931ecSChris Mason 
39483212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
3949459931ecSChris Mason 				 orig_offset + item_size - split_offset);
39503212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3951459931ecSChris Mason 
3952459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3953459931ecSChris Mason 
3954459931ecSChris Mason 	/* write the data for the start of the original item */
3955459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3956459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3957459931ecSChris Mason 			    split_offset);
3958459931ecSChris Mason 
3959459931ecSChris Mason 	/* write the data for the new item */
3960459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3961459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3962459931ecSChris Mason 			    item_size - split_offset);
3963459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3964459931ecSChris Mason 
3965e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3966459931ecSChris Mason 	kfree(buf);
3967ad48fd75SYan, Zheng 	return 0;
3968ad48fd75SYan, Zheng }
3969ad48fd75SYan, Zheng 
3970ad48fd75SYan, Zheng /*
3971ad48fd75SYan, Zheng  * This function splits a single item into two items,
3972ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3973ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3974ad48fd75SYan, Zheng  *
3975ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3976ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3977ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3978ad48fd75SYan, Zheng  *
3979ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3980ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3981ad48fd75SYan, Zheng  *
3982ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3983ad48fd75SYan, Zheng  * leaf the entire time.
3984ad48fd75SYan, Zheng  */
3985ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3986ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3987ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3988310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3989ad48fd75SYan, Zheng 		     unsigned long split_offset)
3990ad48fd75SYan, Zheng {
3991ad48fd75SYan, Zheng 	int ret;
3992ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3993ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3994ad48fd75SYan, Zheng 	if (ret)
3995459931ecSChris Mason 		return ret;
3996ad48fd75SYan, Zheng 
399725263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3998ad48fd75SYan, Zheng 	return ret;
3999ad48fd75SYan, Zheng }
4000ad48fd75SYan, Zheng 
4001ad48fd75SYan, Zheng /*
4002d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4003d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4004d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4005d352ac68SChris Mason  * the front.
4006d352ac68SChris Mason  */
400778ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
4008b18c6685SChris Mason {
4009b18c6685SChris Mason 	int slot;
40105f39d397SChris Mason 	struct extent_buffer *leaf;
4011b18c6685SChris Mason 	u32 nritems;
4012b18c6685SChris Mason 	unsigned int data_end;
4013b18c6685SChris Mason 	unsigned int old_data_start;
4014b18c6685SChris Mason 	unsigned int old_size;
4015b18c6685SChris Mason 	unsigned int size_diff;
4016b18c6685SChris Mason 	int i;
4017cfed81a0SChris Mason 	struct btrfs_map_token token;
4018cfed81a0SChris Mason 
40195f39d397SChris Mason 	leaf = path->nodes[0];
4020179e29e4SChris Mason 	slot = path->slots[0];
4021179e29e4SChris Mason 
40223212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
4023179e29e4SChris Mason 	if (old_size == new_size)
4024143bede5SJeff Mahoney 		return;
4025b18c6685SChris Mason 
40265f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
40278f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4028b18c6685SChris Mason 
40293212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
4030179e29e4SChris Mason 
4031b18c6685SChris Mason 	size_diff = old_size - new_size;
4032b18c6685SChris Mason 
4033b18c6685SChris Mason 	BUG_ON(slot < 0);
4034b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4035b18c6685SChris Mason 
4036b18c6685SChris Mason 	/*
4037b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4038b18c6685SChris Mason 	 */
4039b18c6685SChris Mason 	/* first correct the data pointers */
4040c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4041b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
40425f39d397SChris Mason 		u32 ioff;
4043db94535dSChris Mason 
40443212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
40453212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
4046b18c6685SChris Mason 	}
4047db94535dSChris Mason 
4048b18c6685SChris Mason 	/* shift the data */
4049179e29e4SChris Mason 	if (from_end) {
4050637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
4051637e3b48SJosef Bacik 				  old_data_start + new_size - data_end);
4052179e29e4SChris Mason 	} else {
4053179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4054179e29e4SChris Mason 		u64 offset;
4055179e29e4SChris Mason 
4056179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4057179e29e4SChris Mason 
4058179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4059179e29e4SChris Mason 			unsigned long ptr;
4060179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4061179e29e4SChris Mason 
4062179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4063179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4064179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4065179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4066179e29e4SChris Mason 
4067179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4068179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4069179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4070179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4071179e29e4SChris Mason 				      (unsigned long)fi,
40727ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4073179e29e4SChris Mason 			}
4074179e29e4SChris Mason 		}
4075179e29e4SChris Mason 
4076637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
4077637e3b48SJosef Bacik 				  old_data_start - data_end);
4078179e29e4SChris Mason 
4079179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4080179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4081179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4082179e29e4SChris Mason 		if (slot == 0)
4083b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4084179e29e4SChris Mason 	}
40855f39d397SChris Mason 
40863212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
40875f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4088b18c6685SChris Mason 
4089e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4090a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4091b18c6685SChris Mason 		BUG();
40925f39d397SChris Mason 	}
4093b18c6685SChris Mason }
4094b18c6685SChris Mason 
4095d352ac68SChris Mason /*
40968f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4097d352ac68SChris Mason  */
4098c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
40996567e837SChris Mason {
41006567e837SChris Mason 	int slot;
41015f39d397SChris Mason 	struct extent_buffer *leaf;
41026567e837SChris Mason 	u32 nritems;
41036567e837SChris Mason 	unsigned int data_end;
41046567e837SChris Mason 	unsigned int old_data;
41056567e837SChris Mason 	unsigned int old_size;
41066567e837SChris Mason 	int i;
4107cfed81a0SChris Mason 	struct btrfs_map_token token;
4108cfed81a0SChris Mason 
41095f39d397SChris Mason 	leaf = path->nodes[0];
41106567e837SChris Mason 
41115f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
41128f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
41136567e837SChris Mason 
4114e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4115a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
41166567e837SChris Mason 		BUG();
41175f39d397SChris Mason 	}
41186567e837SChris Mason 	slot = path->slots[0];
4119dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
41206567e837SChris Mason 
41216567e837SChris Mason 	BUG_ON(slot < 0);
41223326d1b0SChris Mason 	if (slot >= nritems) {
4123a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4124c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4125d397712bSChris Mason 			   slot, nritems);
4126290342f6SArnd Bergmann 		BUG();
41273326d1b0SChris Mason 	}
41286567e837SChris Mason 
41296567e837SChris Mason 	/*
41306567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
41316567e837SChris Mason 	 */
41326567e837SChris Mason 	/* first correct the data pointers */
4133c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
41346567e837SChris Mason 	for (i = slot; i < nritems; i++) {
41355f39d397SChris Mason 		u32 ioff;
4136db94535dSChris Mason 
41373212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
41383212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
41396567e837SChris Mason 	}
41405f39d397SChris Mason 
41416567e837SChris Mason 	/* shift the data */
4142637e3b48SJosef Bacik 	memmove_leaf_data(leaf, data_end - data_size, data_end,
4143637e3b48SJosef Bacik 			  old_data - data_end);
41445f39d397SChris Mason 
41456567e837SChris Mason 	data_end = old_data;
41463212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
41473212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
41485f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
41496567e837SChris Mason 
4150e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4151a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
41526567e837SChris Mason 		BUG();
41535f39d397SChris Mason 	}
41546567e837SChris Mason }
41556567e837SChris Mason 
415643dd529aSDavid Sterba /*
415743dd529aSDavid Sterba  * Make space in the node before inserting one or more items.
4158da9ffb24SNikolay Borisov  *
4159da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
4160da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
4161b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
416243dd529aSDavid Sterba  *
416343dd529aSDavid Sterba  * Main purpose is to save stack depth by doing the bulk of the work in a
416443dd529aSDavid Sterba  * function that doesn't call btrfs_search_slot
416574123bd7SChris Mason  */
4166f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4167b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
4168be0e5c09SChris Mason {
41690b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
41709c58309dSChris Mason 	int i;
41717518a238SChris Mason 	u32 nritems;
4172be0e5c09SChris Mason 	unsigned int data_end;
4173e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
417444871b1bSChris Mason 	struct extent_buffer *leaf;
417544871b1bSChris Mason 	int slot;
4176cfed81a0SChris Mason 	struct btrfs_map_token token;
4177fc0d82e1SNikolay Borisov 	u32 total_size;
4178fc0d82e1SNikolay Borisov 
4179b7ef5f3aSFilipe Manana 	/*
4180b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
4181b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
4182b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
4183b7ef5f3aSFilipe Manana 	 */
418424cdc847SFilipe Manana 	if (path->slots[0] == 0) {
4185b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4186b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
418724cdc847SFilipe Manana 	}
418824cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
418924cdc847SFilipe Manana 
41905f39d397SChris Mason 	leaf = path->nodes[0];
419144871b1bSChris Mason 	slot = path->slots[0];
419274123bd7SChris Mason 
41935f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
41948f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4195b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4196eb60ceacSChris Mason 
4197e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4198a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
41990b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4200e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4201be0e5c09SChris Mason 		BUG();
4202d4dbff95SChris Mason 	}
42035f39d397SChris Mason 
4204c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4205be0e5c09SChris Mason 	if (slot != nritems) {
4206dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4207be0e5c09SChris Mason 
42085f39d397SChris Mason 		if (old_data < data_end) {
4209a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
42107269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
42117269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
42125f39d397SChris Mason 				   slot, old_data, data_end);
4213290342f6SArnd Bergmann 			BUG();
42145f39d397SChris Mason 		}
4215be0e5c09SChris Mason 		/*
4216be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4217be0e5c09SChris Mason 		 */
4218be0e5c09SChris Mason 		/* first correct the data pointers */
42190783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
42205f39d397SChris Mason 			u32 ioff;
4221db94535dSChris Mason 
42223212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
42233212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
4224b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
42250783fcfcSChris Mason 		}
4226be0e5c09SChris Mason 		/* shift the items */
4227637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot + batch->nr, slot, nritems - slot);
4228be0e5c09SChris Mason 
4229be0e5c09SChris Mason 		/* shift the data */
4230637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end - batch->total_data_size,
4231637e3b48SJosef Bacik 				  data_end, old_data - data_end);
4232be0e5c09SChris Mason 		data_end = old_data;
4233be0e5c09SChris Mason 	}
42345f39d397SChris Mason 
423562e2749eSChris Mason 	/* setup the item for the new data */
4236b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
4237b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
42389c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4239b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
42403212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
42413212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
42429c58309dSChris Mason 	}
424344871b1bSChris Mason 
4244b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4245b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4246aa5d6bedSChris Mason 
4247e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4248a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4249be0e5c09SChris Mason 		BUG();
42505f39d397SChris Mason 	}
425144871b1bSChris Mason }
425244871b1bSChris Mason 
425344871b1bSChris Mason /*
4254f0641656SFilipe Manana  * Insert a new item into a leaf.
4255f0641656SFilipe Manana  *
4256f0641656SFilipe Manana  * @root:      The root of the btree.
4257f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
4258f0641656SFilipe Manana  * @key:       The key of the new item.
4259f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
4260f0641656SFilipe Manana  */
4261f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
4262f0641656SFilipe Manana 				 struct btrfs_path *path,
4263f0641656SFilipe Manana 				 const struct btrfs_key *key,
4264f0641656SFilipe Manana 				 u32 data_size)
4265f0641656SFilipe Manana {
4266f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4267f0641656SFilipe Manana 
4268f0641656SFilipe Manana 	batch.keys = key;
4269f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4270f0641656SFilipe Manana 	batch.total_data_size = data_size;
4271f0641656SFilipe Manana 	batch.nr = 1;
4272f0641656SFilipe Manana 
4273f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
4274f0641656SFilipe Manana }
4275f0641656SFilipe Manana 
4276f0641656SFilipe Manana /*
427744871b1bSChris Mason  * Given a key and some data, insert items into the tree.
427844871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
427944871b1bSChris Mason  */
428044871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
428144871b1bSChris Mason 			    struct btrfs_root *root,
428244871b1bSChris Mason 			    struct btrfs_path *path,
4283b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
428444871b1bSChris Mason {
428544871b1bSChris Mason 	int ret = 0;
428644871b1bSChris Mason 	int slot;
4287b7ef5f3aSFilipe Manana 	u32 total_size;
428844871b1bSChris Mason 
4289b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4290b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
429144871b1bSChris Mason 	if (ret == 0)
429244871b1bSChris Mason 		return -EEXIST;
429344871b1bSChris Mason 	if (ret < 0)
4294143bede5SJeff Mahoney 		return ret;
429544871b1bSChris Mason 
429644871b1bSChris Mason 	slot = path->slots[0];
429744871b1bSChris Mason 	BUG_ON(slot < 0);
429844871b1bSChris Mason 
4299b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4300143bede5SJeff Mahoney 	return 0;
430162e2749eSChris Mason }
430262e2749eSChris Mason 
430362e2749eSChris Mason /*
430462e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
430562e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
430662e2749eSChris Mason  */
4307310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4308310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4309310712b2SOmar Sandoval 		      u32 data_size)
431062e2749eSChris Mason {
431162e2749eSChris Mason 	int ret = 0;
43122c90e5d6SChris Mason 	struct btrfs_path *path;
43135f39d397SChris Mason 	struct extent_buffer *leaf;
43145f39d397SChris Mason 	unsigned long ptr;
431562e2749eSChris Mason 
43162c90e5d6SChris Mason 	path = btrfs_alloc_path();
4317db5b493aSTsutomu Itoh 	if (!path)
4318db5b493aSTsutomu Itoh 		return -ENOMEM;
43192c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
432062e2749eSChris Mason 	if (!ret) {
43215f39d397SChris Mason 		leaf = path->nodes[0];
43225f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
43235f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
43245f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
432562e2749eSChris Mason 	}
43262c90e5d6SChris Mason 	btrfs_free_path(path);
4327aa5d6bedSChris Mason 	return ret;
4328be0e5c09SChris Mason }
4329be0e5c09SChris Mason 
433074123bd7SChris Mason /*
4331f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4332f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4333f0641656SFilipe Manana  * contiguous with the original item.
4334f0641656SFilipe Manana  *
4335f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4336f0641656SFilipe Manana  * the entire time.
4337f0641656SFilipe Manana  */
4338f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4339f0641656SFilipe Manana 			 struct btrfs_root *root,
4340f0641656SFilipe Manana 			 struct btrfs_path *path,
4341f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4342f0641656SFilipe Manana {
4343f0641656SFilipe Manana 	struct extent_buffer *leaf;
4344f0641656SFilipe Manana 	int ret;
4345f0641656SFilipe Manana 	u32 item_size;
4346f0641656SFilipe Manana 
4347f0641656SFilipe Manana 	leaf = path->nodes[0];
43483212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4349f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4350f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4351f0641656SFilipe Manana 	if (ret)
4352f0641656SFilipe Manana 		return ret;
4353f0641656SFilipe Manana 
4354f0641656SFilipe Manana 	path->slots[0]++;
4355f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4356f0641656SFilipe Manana 	leaf = path->nodes[0];
4357f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4358f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4359f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4360f0641656SFilipe Manana 			     item_size);
4361f0641656SFilipe Manana 	return 0;
4362f0641656SFilipe Manana }
4363f0641656SFilipe Manana 
4364f0641656SFilipe Manana /*
43655de08d7dSChris Mason  * delete the pointer from a given node.
436674123bd7SChris Mason  *
4367d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4368d352ac68SChris Mason  * empty a node.
4369016f9d0bSJosef Bacik  *
4370016f9d0bSJosef Bacik  * This is exported for use inside btrfs-progs, don't un-export it.
437174123bd7SChris Mason  */
4372016f9d0bSJosef Bacik void btrfs_del_ptr(struct btrfs_root *root, struct btrfs_path *path, int level,
4373016f9d0bSJosef Bacik 		   int slot)
4374be0e5c09SChris Mason {
43755f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
43767518a238SChris Mason 	u32 nritems;
4377f3ea38daSJan Schmidt 	int ret;
4378be0e5c09SChris Mason 
43795f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4380be0e5c09SChris Mason 	if (slot != nritems - 1) {
4381bf1d3425SDavid Sterba 		if (level) {
4382f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4383f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4384bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4385bf1d3425SDavid Sterba 		}
43865f39d397SChris Mason 		memmove_extent_buffer(parent,
4387e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot),
4388e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot + 1),
4389d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4390d6025579SChris Mason 			      (nritems - slot - 1));
439157ba86c0SChris Mason 	} else if (level) {
4392f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
439333cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REMOVE);
439457ba86c0SChris Mason 		BUG_ON(ret < 0);
4395be0e5c09SChris Mason 	}
4396f3ea38daSJan Schmidt 
43977518a238SChris Mason 	nritems--;
43985f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
43997518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
44005f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4401eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
44025f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4403bb803951SChris Mason 	} else if (slot == 0) {
44045f39d397SChris Mason 		struct btrfs_disk_key disk_key;
44055f39d397SChris Mason 
44065f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4407b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4408be0e5c09SChris Mason 	}
4409d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4410be0e5c09SChris Mason }
4411be0e5c09SChris Mason 
441274123bd7SChris Mason /*
4413323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
44145d4f98a2SYan Zheng  * path->nodes[1].
4415323ac95bSChris Mason  *
4416323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4417323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4418323ac95bSChris Mason  *
4419323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4420323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4421323ac95bSChris Mason  */
4422143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4423323ac95bSChris Mason 				    struct btrfs_root *root,
44245d4f98a2SYan Zheng 				    struct btrfs_path *path,
44255d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4426323ac95bSChris Mason {
44275d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4428016f9d0bSJosef Bacik 	btrfs_del_ptr(root, path, 1, path->slots[1]);
4429323ac95bSChris Mason 
44304d081c41SChris Mason 	/*
44314d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
44324d081c41SChris Mason 	 * aren't holding any locks when we call it
44334d081c41SChris Mason 	 */
44344d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
44354d081c41SChris Mason 
4436f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4437f0486c68SYan, Zheng 
443867439dadSDavid Sterba 	atomic_inc(&leaf->refs);
44397a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
44403083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4441323ac95bSChris Mason }
4442323ac95bSChris Mason /*
444374123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
444474123bd7SChris Mason  * the leaf, remove it from the tree
444574123bd7SChris Mason  */
444685e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
444785e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4448be0e5c09SChris Mason {
44490b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
44505f39d397SChris Mason 	struct extent_buffer *leaf;
4451aa5d6bedSChris Mason 	int ret = 0;
4452aa5d6bedSChris Mason 	int wret;
44537518a238SChris Mason 	u32 nritems;
4454be0e5c09SChris Mason 
44555f39d397SChris Mason 	leaf = path->nodes[0];
44565f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4457be0e5c09SChris Mason 
445885e21bacSChris Mason 	if (slot + nr != nritems) {
44590cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
44600cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4461c82f823cSDavid Sterba 		struct btrfs_map_token token;
44620cae23b6SFilipe Manana 		u32 dsize = 0;
44630cae23b6SFilipe Manana 		int i;
44640cae23b6SFilipe Manana 
44650cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
44660cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
44675f39d397SChris Mason 
4468637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + dsize, data_end,
446985e21bacSChris Mason 				  last_off - data_end);
44705f39d397SChris Mason 
4471c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
447285e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
44735f39d397SChris Mason 			u32 ioff;
4474db94535dSChris Mason 
44753212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
44763212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
44770783fcfcSChris Mason 		}
4478db94535dSChris Mason 
4479637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot, slot + nr, nritems - slot - nr);
4480be0e5c09SChris Mason 	}
448185e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
448285e21bacSChris Mason 	nritems -= nr;
44835f39d397SChris Mason 
448474123bd7SChris Mason 	/* delete the leaf if we've emptied it */
44857518a238SChris Mason 	if (nritems == 0) {
44865f39d397SChris Mason 		if (leaf == root->node) {
44875f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
44889a8dd150SChris Mason 		} else {
4489190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, leaf);
4490143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
44919a8dd150SChris Mason 		}
4492be0e5c09SChris Mason 	} else {
44937518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4494aa5d6bedSChris Mason 		if (slot == 0) {
44955f39d397SChris Mason 			struct btrfs_disk_key disk_key;
44965f39d397SChris Mason 
44975f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4498b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4499aa5d6bedSChris Mason 		}
4500aa5d6bedSChris Mason 
45017c4063d1SFilipe Manana 		/*
45027c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
45037c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
45047c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
45057c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
45067c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
45077c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
45087c4063d1SFilipe Manana 		 */
45090b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
45107c4063d1SFilipe Manana 			u32 min_push_space;
45117c4063d1SFilipe Manana 
4512be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4513be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4514016f9d0bSJosef Bacik 			 * for possible call to btrfs_del_ptr below
4515be0e5c09SChris Mason 			 */
45164920c9acSChris Mason 			slot = path->slots[1];
451767439dadSDavid Sterba 			atomic_inc(&leaf->refs);
45187c4063d1SFilipe Manana 			/*
45197c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
45207c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
45217c4063d1SFilipe Manana 			 */
45227c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
45237c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
45247c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
45257c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
452654aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4527aa5d6bedSChris Mason 				ret = wret;
45285f39d397SChris Mason 
45295f39d397SChris Mason 			if (path->nodes[0] == leaf &&
45305f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
45317c4063d1SFilipe Manana 				/*
45327c4063d1SFilipe Manana 				 * If we were not able to push all items from our
45337c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
45347c4063d1SFilipe Manana 				 * either push all the remaining items to the
45357c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
45367c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
45377c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
45387c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
45397c4063d1SFilipe Manana 				 * or nearly full.
45407c4063d1SFilipe Manana 				 */
45417c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
45427c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
45437c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
45447c4063d1SFilipe Manana 						       min_push_space, 1, 0);
454554aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4546aa5d6bedSChris Mason 					ret = wret;
4547aa5d6bedSChris Mason 			}
45485f39d397SChris Mason 
45495f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4550323ac95bSChris Mason 				path->slots[1] = slot;
4551143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
45525f39d397SChris Mason 				free_extent_buffer(leaf);
4553143bede5SJeff Mahoney 				ret = 0;
45545de08d7dSChris Mason 			} else {
4555925baeddSChris Mason 				/* if we're still in the path, make sure
4556925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4557925baeddSChris Mason 				 * push_leaf functions must have already
4558925baeddSChris Mason 				 * dirtied this buffer
4559925baeddSChris Mason 				 */
4560925baeddSChris Mason 				if (path->nodes[0] == leaf)
45615f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
45625f39d397SChris Mason 				free_extent_buffer(leaf);
4563be0e5c09SChris Mason 			}
4564d5719762SChris Mason 		} else {
45655f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4566be0e5c09SChris Mason 		}
45679a8dd150SChris Mason 	}
4568aa5d6bedSChris Mason 	return ret;
45699a8dd150SChris Mason }
45709a8dd150SChris Mason 
457197571fd0SChris Mason /*
45723f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4573de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4574de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
45753f157a2fSChris Mason  *
45763f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
45773f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
45783f157a2fSChris Mason  * key and get a writable path.
45793f157a2fSChris Mason  *
45803f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
45813f157a2fSChris Mason  * of the tree.
45823f157a2fSChris Mason  *
4583d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4584d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4585d352ac68SChris Mason  * skipped over (without reading them).
4586d352ac68SChris Mason  *
45873f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
45883f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
45893f157a2fSChris Mason  */
45903f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4591de78b51aSEric Sandeen 			 struct btrfs_path *path,
45923f157a2fSChris Mason 			 u64 min_trans)
45933f157a2fSChris Mason {
45943f157a2fSChris Mason 	struct extent_buffer *cur;
45953f157a2fSChris Mason 	struct btrfs_key found_key;
45963f157a2fSChris Mason 	int slot;
45979652480bSYan 	int sret;
45983f157a2fSChris Mason 	u32 nritems;
45993f157a2fSChris Mason 	int level;
46003f157a2fSChris Mason 	int ret = 1;
4601f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
46023f157a2fSChris Mason 
4603c922b016SStefan Roesch 	ASSERT(!path->nowait);
4604f98de9b9SFilipe Manana 	path->keep_locks = 1;
46053f157a2fSChris Mason again:
4606bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
46073f157a2fSChris Mason 	level = btrfs_header_level(cur);
4608e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
46093f157a2fSChris Mason 	path->nodes[level] = cur;
4610bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
46113f157a2fSChris Mason 
46123f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
46133f157a2fSChris Mason 		ret = 1;
46143f157a2fSChris Mason 		goto out;
46153f157a2fSChris Mason 	}
46163f157a2fSChris Mason 	while (1) {
46173f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
46183f157a2fSChris Mason 		level = btrfs_header_level(cur);
4619fdf8d595SAnand Jain 		sret = btrfs_bin_search(cur, 0, min_key, &slot);
4620cbca7d59SFilipe Manana 		if (sret < 0) {
4621cbca7d59SFilipe Manana 			ret = sret;
4622cbca7d59SFilipe Manana 			goto out;
4623cbca7d59SFilipe Manana 		}
46243f157a2fSChris Mason 
4625323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4626323ac95bSChris Mason 		if (level == path->lowest_level) {
4627e02119d5SChris Mason 			if (slot >= nritems)
4628e02119d5SChris Mason 				goto find_next_key;
46293f157a2fSChris Mason 			ret = 0;
46303f157a2fSChris Mason 			path->slots[level] = slot;
46313f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
46323f157a2fSChris Mason 			goto out;
46333f157a2fSChris Mason 		}
46349652480bSYan 		if (sret && slot > 0)
46359652480bSYan 			slot--;
46363f157a2fSChris Mason 		/*
4637de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4638260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
46393f157a2fSChris Mason 		 */
46403f157a2fSChris Mason 		while (slot < nritems) {
46413f157a2fSChris Mason 			u64 gen;
4642e02119d5SChris Mason 
46433f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
46443f157a2fSChris Mason 			if (gen < min_trans) {
46453f157a2fSChris Mason 				slot++;
46463f157a2fSChris Mason 				continue;
46473f157a2fSChris Mason 			}
46483f157a2fSChris Mason 			break;
46493f157a2fSChris Mason 		}
4650e02119d5SChris Mason find_next_key:
46513f157a2fSChris Mason 		/*
46523f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
46533f157a2fSChris Mason 		 * and find another one
46543f157a2fSChris Mason 		 */
46553f157a2fSChris Mason 		if (slot >= nritems) {
4656e02119d5SChris Mason 			path->slots[level] = slot;
4657e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4658de78b51aSEric Sandeen 						  min_trans);
4659e02119d5SChris Mason 			if (sret == 0) {
4660b3b4aa74SDavid Sterba 				btrfs_release_path(path);
46613f157a2fSChris Mason 				goto again;
46623f157a2fSChris Mason 			} else {
46633f157a2fSChris Mason 				goto out;
46643f157a2fSChris Mason 			}
46653f157a2fSChris Mason 		}
46663f157a2fSChris Mason 		/* save our key for returning back */
46673f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
46683f157a2fSChris Mason 		path->slots[level] = slot;
46693f157a2fSChris Mason 		if (level == path->lowest_level) {
46703f157a2fSChris Mason 			ret = 0;
46713f157a2fSChris Mason 			goto out;
46723f157a2fSChris Mason 		}
46734b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4674fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4675fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4676fb770ae4SLiu Bo 			goto out;
4677fb770ae4SLiu Bo 		}
46783f157a2fSChris Mason 
4679bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4680b4ce94deSChris Mason 
4681bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
46823f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4683f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
46843f157a2fSChris Mason 	}
46853f157a2fSChris Mason out:
4686f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4687f98de9b9SFilipe Manana 	if (ret == 0) {
4688f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4689f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4690f98de9b9SFilipe Manana 	}
46913f157a2fSChris Mason 	return ret;
46923f157a2fSChris Mason }
46933f157a2fSChris Mason 
46943f157a2fSChris Mason /*
46953f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
46963f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4697de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
46983f157a2fSChris Mason  *
46993f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
47003f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
47013f157a2fSChris Mason  *
47023f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
47033f157a2fSChris Mason  * calling this function.
47043f157a2fSChris Mason  */
4705e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4706de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4707e7a84565SChris Mason {
4708e7a84565SChris Mason 	int slot;
4709e7a84565SChris Mason 	struct extent_buffer *c;
4710e7a84565SChris Mason 
47116a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4712e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4713e7a84565SChris Mason 		if (!path->nodes[level])
4714e7a84565SChris Mason 			return 1;
4715e7a84565SChris Mason 
4716e7a84565SChris Mason 		slot = path->slots[level] + 1;
4717e7a84565SChris Mason 		c = path->nodes[level];
47183f157a2fSChris Mason next:
4719e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
472033c66f43SYan Zheng 			int ret;
472133c66f43SYan Zheng 			int orig_lowest;
472233c66f43SYan Zheng 			struct btrfs_key cur_key;
472333c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
472433c66f43SYan Zheng 			    !path->nodes[level + 1])
4725e7a84565SChris Mason 				return 1;
472633c66f43SYan Zheng 
47276a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
472833c66f43SYan Zheng 				level++;
4729e7a84565SChris Mason 				continue;
4730e7a84565SChris Mason 			}
473133c66f43SYan Zheng 
473233c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
473333c66f43SYan Zheng 			if (level == 0)
473433c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
473533c66f43SYan Zheng 			else
473633c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
473733c66f43SYan Zheng 
473833c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4739b3b4aa74SDavid Sterba 			btrfs_release_path(path);
474033c66f43SYan Zheng 			path->lowest_level = level;
474133c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
474233c66f43SYan Zheng 						0, 0);
474333c66f43SYan Zheng 			path->lowest_level = orig_lowest;
474433c66f43SYan Zheng 			if (ret < 0)
474533c66f43SYan Zheng 				return ret;
474633c66f43SYan Zheng 
474733c66f43SYan Zheng 			c = path->nodes[level];
474833c66f43SYan Zheng 			slot = path->slots[level];
474933c66f43SYan Zheng 			if (ret == 0)
475033c66f43SYan Zheng 				slot++;
475133c66f43SYan Zheng 			goto next;
475233c66f43SYan Zheng 		}
475333c66f43SYan Zheng 
4754e7a84565SChris Mason 		if (level == 0)
4755e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
47563f157a2fSChris Mason 		else {
47573f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
47583f157a2fSChris Mason 
47593f157a2fSChris Mason 			if (gen < min_trans) {
47603f157a2fSChris Mason 				slot++;
47613f157a2fSChris Mason 				goto next;
47623f157a2fSChris Mason 			}
4763e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
47643f157a2fSChris Mason 		}
4765e7a84565SChris Mason 		return 0;
4766e7a84565SChris Mason 	}
4767e7a84565SChris Mason 	return 1;
4768e7a84565SChris Mason }
4769e7a84565SChris Mason 
47703d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
47713d7806ecSJan Schmidt 			u64 time_seq)
47723d7806ecSJan Schmidt {
4773d97e63b6SChris Mason 	int slot;
47748e73f275SChris Mason 	int level;
47755f39d397SChris Mason 	struct extent_buffer *c;
47768e73f275SChris Mason 	struct extent_buffer *next;
4777d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4778925baeddSChris Mason 	struct btrfs_key key;
4779d96b3424SFilipe Manana 	bool need_commit_sem = false;
4780925baeddSChris Mason 	u32 nritems;
4781925baeddSChris Mason 	int ret;
47820e46318dSJosef Bacik 	int i;
4783925baeddSChris Mason 
4784bdcdd86cSFilipe Manana 	/*
4785bdcdd86cSFilipe Manana 	 * The nowait semantics are used only for write paths, where we don't
4786bdcdd86cSFilipe Manana 	 * use the tree mod log and sequence numbers.
4787bdcdd86cSFilipe Manana 	 */
4788bdcdd86cSFilipe Manana 	if (time_seq)
4789c922b016SStefan Roesch 		ASSERT(!path->nowait);
4790c922b016SStefan Roesch 
4791925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4792d397712bSChris Mason 	if (nritems == 0)
4793925baeddSChris Mason 		return 1;
4794925baeddSChris Mason 
47958e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
47968e73f275SChris Mason again:
47978e73f275SChris Mason 	level = 1;
47988e73f275SChris Mason 	next = NULL;
4799b3b4aa74SDavid Sterba 	btrfs_release_path(path);
48008e73f275SChris Mason 
4801a2135011SChris Mason 	path->keep_locks = 1;
48028e73f275SChris Mason 
4803d96b3424SFilipe Manana 	if (time_seq) {
48043d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4805d96b3424SFilipe Manana 	} else {
4806d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4807d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4808d96b3424SFilipe Manana 			need_commit_sem = true;
4809bdcdd86cSFilipe Manana 			if (path->nowait) {
4810bdcdd86cSFilipe Manana 				if (!down_read_trylock(&fs_info->commit_root_sem)) {
4811bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4812bdcdd86cSFilipe Manana 					goto done;
4813bdcdd86cSFilipe Manana 				}
4814bdcdd86cSFilipe Manana 			} else {
4815d96b3424SFilipe Manana 				down_read(&fs_info->commit_root_sem);
4816d96b3424SFilipe Manana 			}
4817bdcdd86cSFilipe Manana 		}
4818925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4819d96b3424SFilipe Manana 	}
4820925baeddSChris Mason 	path->keep_locks = 0;
4821925baeddSChris Mason 
4822925baeddSChris Mason 	if (ret < 0)
4823d96b3424SFilipe Manana 		goto done;
4824925baeddSChris Mason 
4825a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4826168fd7d2SChris Mason 	/*
4827168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4828168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4829168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4830168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4831168fd7d2SChris Mason 	 */
4832a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4833e457afecSYan Zheng 		if (ret == 0)
4834168fd7d2SChris Mason 			path->slots[0]++;
48358e73f275SChris Mason 		ret = 0;
4836925baeddSChris Mason 		goto done;
4837925baeddSChris Mason 	}
48380b43e04fSLiu Bo 	/*
48390b43e04fSLiu Bo 	 * So the above check misses one case:
48400b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
48410b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
48420b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
48430b43e04fSLiu Bo 	 *
48440b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
48450b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
48460b43e04fSLiu Bo 	 *
48470b43e04fSLiu Bo 	 * And a bit more explanation about this check,
48480b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
48490b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
48500b43e04fSLiu Bo 	 * bigger one.
48510b43e04fSLiu Bo 	 */
48520b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
48530b43e04fSLiu Bo 		ret = 0;
48540b43e04fSLiu Bo 		goto done;
48550b43e04fSLiu Bo 	}
4856d97e63b6SChris Mason 
4857234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
48588e73f275SChris Mason 		if (!path->nodes[level]) {
48598e73f275SChris Mason 			ret = 1;
48608e73f275SChris Mason 			goto done;
48618e73f275SChris Mason 		}
48625f39d397SChris Mason 
4863d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4864d97e63b6SChris Mason 		c = path->nodes[level];
48655f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4866d97e63b6SChris Mason 			level++;
48678e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
48688e73f275SChris Mason 				ret = 1;
48698e73f275SChris Mason 				goto done;
48708e73f275SChris Mason 			}
4871d97e63b6SChris Mason 			continue;
4872d97e63b6SChris Mason 		}
48735f39d397SChris Mason 
48740e46318dSJosef Bacik 
48750e46318dSJosef Bacik 		/*
48760e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
48770e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
48780e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
48790e46318dSJosef Bacik 		 */
48800e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
48810e46318dSJosef Bacik 			if (path->locks[level]) {
48820e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
48830e46318dSJosef Bacik 				path->locks[i] = 0;
48840e46318dSJosef Bacik 			}
48850e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
48860e46318dSJosef Bacik 			path->nodes[i] = NULL;
4887925baeddSChris Mason 		}
48885f39d397SChris Mason 
48898e73f275SChris Mason 		next = c;
4890d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4891cda79c54SDavid Sterba 					    slot, &key);
4892bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
48938e73f275SChris Mason 			goto again;
48945f39d397SChris Mason 
489576a05b35SChris Mason 		if (ret < 0) {
4896b3b4aa74SDavid Sterba 			btrfs_release_path(path);
489776a05b35SChris Mason 			goto done;
489876a05b35SChris Mason 		}
489976a05b35SChris Mason 
49005cd57b2cSChris Mason 		if (!path->skip_locking) {
4901bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4902bdcdd86cSFilipe Manana 			if (!ret && path->nowait) {
4903bdcdd86cSFilipe Manana 				ret = -EAGAIN;
4904bdcdd86cSFilipe Manana 				goto done;
4905bdcdd86cSFilipe Manana 			}
4906d42244a0SJan Schmidt 			if (!ret && time_seq) {
4907d42244a0SJan Schmidt 				/*
4908d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4909d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4910d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4911d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4912d42244a0SJan Schmidt 				 * on our lock and cycle.
4913d42244a0SJan Schmidt 				 */
4914cf538830SJan Schmidt 				free_extent_buffer(next);
4915d42244a0SJan Schmidt 				btrfs_release_path(path);
4916d42244a0SJan Schmidt 				cond_resched();
4917d42244a0SJan Schmidt 				goto again;
4918d42244a0SJan Schmidt 			}
49190e46318dSJosef Bacik 			if (!ret)
49200e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4921bd681513SChris Mason 		}
4922d97e63b6SChris Mason 		break;
4923d97e63b6SChris Mason 	}
4924d97e63b6SChris Mason 	path->slots[level] = slot;
4925d97e63b6SChris Mason 	while (1) {
4926d97e63b6SChris Mason 		level--;
4927d97e63b6SChris Mason 		path->nodes[level] = next;
4928d97e63b6SChris Mason 		path->slots[level] = 0;
4929a74a4b97SChris Mason 		if (!path->skip_locking)
4930ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4931d97e63b6SChris Mason 		if (!level)
4932d97e63b6SChris Mason 			break;
4933b4ce94deSChris Mason 
4934d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4935cda79c54SDavid Sterba 					    0, &key);
4936bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
49378e73f275SChris Mason 			goto again;
49388e73f275SChris Mason 
493976a05b35SChris Mason 		if (ret < 0) {
4940b3b4aa74SDavid Sterba 			btrfs_release_path(path);
494176a05b35SChris Mason 			goto done;
494276a05b35SChris Mason 		}
494376a05b35SChris Mason 
4944bdcdd86cSFilipe Manana 		if (!path->skip_locking) {
4945bdcdd86cSFilipe Manana 			if (path->nowait) {
4946bdcdd86cSFilipe Manana 				if (!btrfs_try_tree_read_lock(next)) {
4947bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4948bdcdd86cSFilipe Manana 					goto done;
4949bdcdd86cSFilipe Manana 				}
4950bdcdd86cSFilipe Manana 			} else {
49510e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4952d97e63b6SChris Mason 			}
4953bdcdd86cSFilipe Manana 		}
4954bdcdd86cSFilipe Manana 	}
49558e73f275SChris Mason 	ret = 0;
4956925baeddSChris Mason done:
4957f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
4958d96b3424SFilipe Manana 	if (need_commit_sem) {
4959d96b3424SFilipe Manana 		int ret2;
4960d96b3424SFilipe Manana 
4961d96b3424SFilipe Manana 		path->need_commit_sem = 1;
4962d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
4963d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
4964d96b3424SFilipe Manana 		if (ret2)
4965d96b3424SFilipe Manana 			ret = ret2;
4966d96b3424SFilipe Manana 	}
49678e73f275SChris Mason 
49688e73f275SChris Mason 	return ret;
4969d97e63b6SChris Mason }
49700b86a832SChris Mason 
4971890d2b1aSJosef Bacik int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
4972890d2b1aSJosef Bacik {
4973890d2b1aSJosef Bacik 	path->slots[0]++;
4974890d2b1aSJosef Bacik 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
4975890d2b1aSJosef Bacik 		return btrfs_next_old_leaf(root, path, time_seq);
4976890d2b1aSJosef Bacik 	return 0;
4977890d2b1aSJosef Bacik }
4978890d2b1aSJosef Bacik 
49793f157a2fSChris Mason /*
49803f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
49813f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
49823f157a2fSChris Mason  *
49833f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
49843f157a2fSChris Mason  */
49850b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
49860b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
49870b86a832SChris Mason 			int type)
49880b86a832SChris Mason {
49890b86a832SChris Mason 	struct btrfs_key found_key;
49900b86a832SChris Mason 	struct extent_buffer *leaf;
4991e02119d5SChris Mason 	u32 nritems;
49920b86a832SChris Mason 	int ret;
49930b86a832SChris Mason 
49940b86a832SChris Mason 	while (1) {
49950b86a832SChris Mason 		if (path->slots[0] == 0) {
49960b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
49970b86a832SChris Mason 			if (ret != 0)
49980b86a832SChris Mason 				return ret;
49990b86a832SChris Mason 		} else {
50000b86a832SChris Mason 			path->slots[0]--;
50010b86a832SChris Mason 		}
50020b86a832SChris Mason 		leaf = path->nodes[0];
5003e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5004e02119d5SChris Mason 		if (nritems == 0)
5005e02119d5SChris Mason 			return 1;
5006e02119d5SChris Mason 		if (path->slots[0] == nritems)
5007e02119d5SChris Mason 			path->slots[0]--;
5008e02119d5SChris Mason 
50090b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5010e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5011e02119d5SChris Mason 			break;
50120a4eefbbSYan Zheng 		if (found_key.type == type)
50130a4eefbbSYan Zheng 			return 0;
5014e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5015e02119d5SChris Mason 		    found_key.type < type)
5016e02119d5SChris Mason 			break;
50170b86a832SChris Mason 	}
50180b86a832SChris Mason 	return 1;
50190b86a832SChris Mason }
5020ade2e0b3SWang Shilong 
5021ade2e0b3SWang Shilong /*
5022ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5023ade2e0b3SWang Shilong  * min objecitd.
5024ade2e0b3SWang Shilong  *
5025ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5026ade2e0b3SWang Shilong  */
5027ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5028ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5029ade2e0b3SWang Shilong {
5030ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5031ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5032ade2e0b3SWang Shilong 	u32 nritems;
5033ade2e0b3SWang Shilong 	int ret;
5034ade2e0b3SWang Shilong 
5035ade2e0b3SWang Shilong 	while (1) {
5036ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5037ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5038ade2e0b3SWang Shilong 			if (ret != 0)
5039ade2e0b3SWang Shilong 				return ret;
5040ade2e0b3SWang Shilong 		} else {
5041ade2e0b3SWang Shilong 			path->slots[0]--;
5042ade2e0b3SWang Shilong 		}
5043ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5044ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5045ade2e0b3SWang Shilong 		if (nritems == 0)
5046ade2e0b3SWang Shilong 			return 1;
5047ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5048ade2e0b3SWang Shilong 			path->slots[0]--;
5049ade2e0b3SWang Shilong 
5050ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5051ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5052ade2e0b3SWang Shilong 			break;
5053ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5054ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5055ade2e0b3SWang Shilong 			return 0;
5056ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5057ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5058ade2e0b3SWang Shilong 			break;
5059ade2e0b3SWang Shilong 	}
5060ade2e0b3SWang Shilong 	return 1;
5061ade2e0b3SWang Shilong }
5062226463d7SJosef Bacik 
5063226463d7SJosef Bacik int __init btrfs_ctree_init(void)
5064226463d7SJosef Bacik {
5065226463d7SJosef Bacik 	btrfs_path_cachep = kmem_cache_create("btrfs_path",
5066226463d7SJosef Bacik 			sizeof(struct btrfs_path), 0,
5067226463d7SJosef Bacik 			SLAB_MEM_SPREAD, NULL);
5068226463d7SJosef Bacik 	if (!btrfs_path_cachep)
5069226463d7SJosef Bacik 		return -ENOMEM;
5070226463d7SJosef Bacik 	return 0;
5071226463d7SJosef Bacik }
5072226463d7SJosef Bacik 
5073226463d7SJosef Bacik void __cold btrfs_ctree_exit(void)
5074226463d7SJosef Bacik {
5075226463d7SJosef Bacik 	kmem_cache_destroy(btrfs_path_cachep);
5076226463d7SJosef Bacik }
5077