xref: /openbmc/linux/fs/btrfs/ctree.c (revision daefe4d435d75118af302dae650547b8b760da0b)
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 
587406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
58840b0a749SFilipe Manana 		if (ret < 0) {
58940b0a749SFilipe Manana 			btrfs_tree_unlock(cow);
59040b0a749SFilipe Manana 			free_extent_buffer(cow);
59140b0a749SFilipe Manana 			btrfs_abort_transaction(trans, ret);
59240b0a749SFilipe Manana 			return ret;
59340b0a749SFilipe Manana 		}
59440b0a749SFilipe Manana 		atomic_inc(&cow->refs);
595240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
596925baeddSChris Mason 
5977a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
5987a163608SFilipe Manana 				      parent_start, last_ref);
5995f39d397SChris Mason 		free_extent_buffer(buf);
6000b86a832SChris Mason 		add_root_to_dirty_list(root);
6016702ed49SChris Mason 	} else {
6025d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
603d09c5152SFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, parent_slot,
60433cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
605d09c5152SFilipe Manana 		if (ret) {
606d09c5152SFilipe Manana 			btrfs_tree_unlock(cow);
607d09c5152SFilipe Manana 			free_extent_buffer(cow);
608d09c5152SFilipe Manana 			btrfs_abort_transaction(trans, ret);
609d09c5152SFilipe Manana 			return ret;
610d09c5152SFilipe Manana 		}
6115f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
612db94535dSChris Mason 					cow->start);
61374493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
61474493f7aSChris Mason 					      trans->transid);
6156702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
6165de865eeSFilipe David Borba Manana 		if (last_ref) {
617f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
6185de865eeSFilipe David Borba Manana 			if (ret) {
619572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
620572c83acSJosef Bacik 				free_extent_buffer(cow);
62166642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
6225de865eeSFilipe David Borba Manana 				return ret;
6235de865eeSFilipe David Borba Manana 			}
6245de865eeSFilipe David Borba Manana 		}
6257a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
6267a163608SFilipe Manana 				      parent_start, last_ref);
6276702ed49SChris Mason 	}
628925baeddSChris Mason 	if (unlock_orig)
629925baeddSChris Mason 		btrfs_tree_unlock(buf);
6303083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
6316702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
6326702ed49SChris Mason 	*cow_ret = cow;
6336702ed49SChris Mason 	return 0;
6346702ed49SChris Mason }
6356702ed49SChris Mason 
6365d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
6375d4f98a2SYan Zheng 				   struct btrfs_root *root,
6385d4f98a2SYan Zheng 				   struct extent_buffer *buf)
6395d4f98a2SYan Zheng {
640f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
641faa2dbf0SJosef Bacik 		return 0;
642fccb84c9SDavid Sterba 
643d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
644d1980131SDavid Sterba 	smp_mb__before_atomic();
645f1ebcc74SLiu Bo 
646f1ebcc74SLiu Bo 	/*
647f1ebcc74SLiu Bo 	 * We do not need to cow a block if
648f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
649f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
650f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
651f1ebcc74SLiu Bo 	 *
652f1ebcc74SLiu Bo 	 * What is forced COW:
65301327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
65452042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
655f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
656f1ebcc74SLiu Bo 	 */
6575d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
6585d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
6595d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
660f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
66127cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
6625d4f98a2SYan Zheng 		return 0;
6635d4f98a2SYan Zheng 	return 1;
6645d4f98a2SYan Zheng }
6655d4f98a2SYan Zheng 
666d352ac68SChris Mason /*
667d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
66801327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
669d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
670d352ac68SChris Mason  */
671d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
6725f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
6735f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
6749631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
6759631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
67602217ed2SChris Mason {
6770b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6786702ed49SChris Mason 	u64 search_start;
679f510cfecSChris Mason 	int ret;
680dc17ff8fSChris Mason 
68183354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
68283354f07SJosef Bacik 		btrfs_err(fs_info,
68383354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
68483354f07SJosef Bacik 
6850b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
68631b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
687c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
6880b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
68931b1a2bdSJulia Lawall 
6900b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
69131b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
6920b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
693dc17ff8fSChris Mason 
6945d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
69502217ed2SChris Mason 		*cow_ret = buf;
69602217ed2SChris Mason 		return 0;
69702217ed2SChris Mason 	}
698c487685dSChris Mason 
699ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
700b4ce94deSChris Mason 
701f616f5cdSQu Wenruo 	/*
702f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
703f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
704f616f5cdSQu Wenruo 	 *
705f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
706f616f5cdSQu Wenruo 	 */
707f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
708f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
7099631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
7101abe9b8aSliubo 
7111abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
7121abe9b8aSliubo 
713f510cfecSChris Mason 	return ret;
7142c90e5d6SChris Mason }
715f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
7166702ed49SChris Mason 
717d352ac68SChris Mason /*
718d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
719d352ac68SChris Mason  * node are actually close by
720d352ac68SChris Mason  */
7216b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
7226702ed49SChris Mason {
7236b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
7246702ed49SChris Mason 		return 1;
7256b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
7266702ed49SChris Mason 		return 1;
72702217ed2SChris Mason 	return 0;
72802217ed2SChris Mason }
72902217ed2SChris Mason 
730ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
731ce6ef5abSDavid Sterba 
732ce6ef5abSDavid Sterba /*
733ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
734ce6ef5abSDavid Sterba  * we can avoid the conversion.
735ce6ef5abSDavid Sterba  */
736ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
737ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
738ce6ef5abSDavid Sterba {
739ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
740ce6ef5abSDavid Sterba 
741ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
742ce6ef5abSDavid Sterba }
743ce6ef5abSDavid Sterba 
744ce6ef5abSDavid Sterba #else
745ce6ef5abSDavid Sterba 
746081e9573SChris Mason /*
747081e9573SChris Mason  * compare two keys in a memcmp fashion
748081e9573SChris Mason  */
749310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
750310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
751081e9573SChris Mason {
752081e9573SChris Mason 	struct btrfs_key k1;
753081e9573SChris Mason 
754081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
755081e9573SChris Mason 
75620736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
757081e9573SChris Mason }
758ce6ef5abSDavid Sterba #endif
759081e9573SChris Mason 
760f3465ca4SJosef Bacik /*
761f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
762f3465ca4SJosef Bacik  */
763e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
764f3465ca4SJosef Bacik {
765f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
766f3465ca4SJosef Bacik 		return 1;
767f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
768f3465ca4SJosef Bacik 		return -1;
769f3465ca4SJosef Bacik 	if (k1->type > k2->type)
770f3465ca4SJosef Bacik 		return 1;
771f3465ca4SJosef Bacik 	if (k1->type < k2->type)
772f3465ca4SJosef Bacik 		return -1;
773f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
774f3465ca4SJosef Bacik 		return 1;
775f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
776f3465ca4SJosef Bacik 		return -1;
777f3465ca4SJosef Bacik 	return 0;
778f3465ca4SJosef Bacik }
779081e9573SChris Mason 
780d352ac68SChris Mason /*
781d352ac68SChris Mason  * this is used by the defrag code to go through all the
782d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
783d352ac68SChris Mason  * disk order is close to key order
784d352ac68SChris Mason  */
7856702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
7865f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
787de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
788a6b6e75eSChris Mason 		       struct btrfs_key *progress)
7896702ed49SChris Mason {
7900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
7916b80053dSChris Mason 	struct extent_buffer *cur;
7926702ed49SChris Mason 	u64 blocknr;
793e9d0b13bSChris Mason 	u64 search_start = *last_ret;
794e9d0b13bSChris Mason 	u64 last_block = 0;
7956702ed49SChris Mason 	u64 other;
7966702ed49SChris Mason 	u32 parent_nritems;
7976702ed49SChris Mason 	int end_slot;
7986702ed49SChris Mason 	int i;
7996702ed49SChris Mason 	int err = 0;
8006b80053dSChris Mason 	u32 blocksize;
801081e9573SChris Mason 	int progress_passed = 0;
802081e9573SChris Mason 	struct btrfs_disk_key disk_key;
8036702ed49SChris Mason 
8040b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
8050b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
80686479a04SChris Mason 
8076b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
8080b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
8095dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
8106702ed49SChris Mason 
8115dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
8126702ed49SChris Mason 		return 0;
8136702ed49SChris Mason 
8145dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
8156702ed49SChris Mason 		int close = 1;
816a6b6e75eSChris Mason 
817081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
818081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
819081e9573SChris Mason 			continue;
820081e9573SChris Mason 
821081e9573SChris Mason 		progress_passed = 1;
8226b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
823e9d0b13bSChris Mason 		if (last_block == 0)
824e9d0b13bSChris Mason 			last_block = blocknr;
8255708b959SChris Mason 
8266702ed49SChris Mason 		if (i > 0) {
8276b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
8286b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
8296702ed49SChris Mason 		}
8305dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
8316b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
8326b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
8336702ed49SChris Mason 		}
834e9d0b13bSChris Mason 		if (close) {
835e9d0b13bSChris Mason 			last_block = blocknr;
8366702ed49SChris Mason 			continue;
837e9d0b13bSChris Mason 		}
8386702ed49SChris Mason 
839206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
840206983b7SJosef Bacik 		if (IS_ERR(cur))
84164c043deSLiu Bo 			return PTR_ERR(cur);
842e9d0b13bSChris Mason 		if (search_start == 0)
8436b80053dSChris Mason 			search_start = last_block;
844e9d0b13bSChris Mason 
845e7a84565SChris Mason 		btrfs_tree_lock(cur);
8466b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
847e7a84565SChris Mason 					&cur, search_start,
8486b80053dSChris Mason 					min(16 * blocksize,
8499631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
8509631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
851252c38f0SYan 		if (err) {
852e7a84565SChris Mason 			btrfs_tree_unlock(cur);
8536b80053dSChris Mason 			free_extent_buffer(cur);
8546702ed49SChris Mason 			break;
855252c38f0SYan 		}
856e7a84565SChris Mason 		search_start = cur->start;
857e7a84565SChris Mason 		last_block = cur->start;
858f2183bdeSChris Mason 		*last_ret = search_start;
859e7a84565SChris Mason 		btrfs_tree_unlock(cur);
860e7a84565SChris Mason 		free_extent_buffer(cur);
8616702ed49SChris Mason 	}
8626702ed49SChris Mason 	return err;
8636702ed49SChris Mason }
8646702ed49SChris Mason 
86574123bd7SChris Mason /*
866fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
8675f39d397SChris Mason  *
868a724f313SFilipe Manana  * The lower boundary for the search is specified by the slot number @first_slot.
869fdf8d595SAnand Jain  * Use a value of 0 to search over the whole extent buffer. Works for both
870fdf8d595SAnand Jain  * leaves and nodes.
87174123bd7SChris Mason  *
872fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
873fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
874fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
875fb81212cSFilipe Manana  *
876fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
877fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
87874123bd7SChris Mason  */
879fdf8d595SAnand Jain int btrfs_bin_search(struct extent_buffer *eb, int first_slot,
88067d5e289SMarcos Paulo de Souza 		     const struct btrfs_key *key, int *slot)
881be0e5c09SChris Mason {
882fb81212cSFilipe Manana 	unsigned long p;
883fb81212cSFilipe Manana 	int item_size;
884a724f313SFilipe Manana 	/*
885a724f313SFilipe Manana 	 * Use unsigned types for the low and high slots, so that we get a more
886a724f313SFilipe Manana 	 * efficient division in the search loop below.
887a724f313SFilipe Manana 	 */
888a724f313SFilipe Manana 	u32 low = first_slot;
889a724f313SFilipe Manana 	u32 high = btrfs_header_nritems(eb);
890be0e5c09SChris Mason 	int ret;
8915cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
892be0e5c09SChris Mason 
893a724f313SFilipe Manana 	if (unlikely(low > high)) {
8945e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
895a724f313SFilipe Manana 		 "%s: low (%u) > high (%u) eb %llu owner %llu level %d",
8965e24e9afSLiu Bo 			  __func__, low, high, eb->start,
8975e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
8985e24e9afSLiu Bo 		return -EINVAL;
8995e24e9afSLiu Bo 	}
9005e24e9afSLiu Bo 
901fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
902fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
903fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
904fb81212cSFilipe Manana 	} else {
905fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
906fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
907fb81212cSFilipe Manana 	}
908fb81212cSFilipe Manana 
909be0e5c09SChris Mason 	while (low < high) {
9105cd17f34SDavid Sterba 		unsigned long oip;
9115cd17f34SDavid Sterba 		unsigned long offset;
9125cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
9135cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
9145cd17f34SDavid Sterba 		int mid;
9155cd17f34SDavid Sterba 
916be0e5c09SChris Mason 		mid = (low + high) / 2;
9175f39d397SChris Mason 		offset = p + mid * item_size;
9185cd17f34SDavid Sterba 		oip = offset_in_page(offset);
9195f39d397SChris Mason 
9205cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
921884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
9225cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
923934d375bSChris Mason 
924884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
9255cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
9265cd17f34SDavid Sterba 		} else {
9275cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
9285f39d397SChris Mason 			tmp = &unaligned;
929479965d6SChris Mason 		}
930479965d6SChris Mason 
931be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
932be0e5c09SChris Mason 
933be0e5c09SChris Mason 		if (ret < 0)
934be0e5c09SChris Mason 			low = mid + 1;
935be0e5c09SChris Mason 		else if (ret > 0)
936be0e5c09SChris Mason 			high = mid;
937be0e5c09SChris Mason 		else {
938be0e5c09SChris Mason 			*slot = mid;
939be0e5c09SChris Mason 			return 0;
940be0e5c09SChris Mason 		}
941be0e5c09SChris Mason 	}
942be0e5c09SChris Mason 	*slot = low;
943be0e5c09SChris Mason 	return 1;
944be0e5c09SChris Mason }
945be0e5c09SChris Mason 
946f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
947f0486c68SYan, Zheng {
948f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
949f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
950f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
951f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
952f0486c68SYan, Zheng }
953f0486c68SYan, Zheng 
954f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
955f0486c68SYan, Zheng {
956f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
957f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
958f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
959f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
960f0486c68SYan, Zheng }
961f0486c68SYan, Zheng 
962d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
963d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
964d352ac68SChris Mason  */
9654b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
9664b231ae4SDavid Sterba 					   int slot)
967bb803951SChris Mason {
968ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
969789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
970416bc658SJosef Bacik 	struct extent_buffer *eb;
971416bc658SJosef Bacik 
972fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
973fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
974ca7a79adSChris Mason 
975d4694728SJosef Bacik 	ASSERT(level);
976ca7a79adSChris Mason 
977789d6a3aSQu Wenruo 	check.level = level - 1;
978789d6a3aSQu Wenruo 	check.transid = btrfs_node_ptr_generation(parent, slot);
979789d6a3aSQu Wenruo 	check.owner_root = btrfs_header_owner(parent);
980789d6a3aSQu Wenruo 	check.has_first_key = true;
981789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(parent, &check.first_key, slot);
982789d6a3aSQu Wenruo 
983d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
984789d6a3aSQu Wenruo 			     &check);
9854eb150d6SQu Wenruo 	if (IS_ERR(eb))
9864eb150d6SQu Wenruo 		return eb;
9874eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
988416bc658SJosef Bacik 		free_extent_buffer(eb);
9894eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
990416bc658SJosef Bacik 	}
991416bc658SJosef Bacik 
992416bc658SJosef Bacik 	return eb;
993bb803951SChris Mason }
994bb803951SChris Mason 
995d352ac68SChris Mason /*
996d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
997d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
998d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
999d352ac68SChris Mason  */
1000e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
100198ed5174SChris Mason 			 struct btrfs_root *root,
100298ed5174SChris Mason 			 struct btrfs_path *path, int level)
1003bb803951SChris Mason {
10040b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10055f39d397SChris Mason 	struct extent_buffer *right = NULL;
10065f39d397SChris Mason 	struct extent_buffer *mid;
10075f39d397SChris Mason 	struct extent_buffer *left = NULL;
10085f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1009bb803951SChris Mason 	int ret = 0;
1010bb803951SChris Mason 	int wret;
1011bb803951SChris Mason 	int pslot;
1012bb803951SChris Mason 	int orig_slot = path->slots[level];
101379f95c82SChris Mason 	u64 orig_ptr;
1014bb803951SChris Mason 
101598e6b1ebSLiu Bo 	ASSERT(level > 0);
1016bb803951SChris Mason 
10175f39d397SChris Mason 	mid = path->nodes[level];
1018b4ce94deSChris Mason 
1019ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
10207bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
10217bb86316SChris Mason 
10221d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
102379f95c82SChris Mason 
1024a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
10255f39d397SChris Mason 		parent = path->nodes[level + 1];
1026bb803951SChris Mason 		pslot = path->slots[level + 1];
1027a05a9bb1SLi Zefan 	}
1028bb803951SChris Mason 
102940689478SChris Mason 	/*
103040689478SChris Mason 	 * deal with the case where there is only one pointer in the root
103140689478SChris Mason 	 * by promoting the node below to a root
103240689478SChris Mason 	 */
10335f39d397SChris Mason 	if (!parent) {
10345f39d397SChris Mason 		struct extent_buffer *child;
1035bb803951SChris Mason 
10365f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
1037bb803951SChris Mason 			return 0;
1038bb803951SChris Mason 
1039bb803951SChris Mason 		/* promote the child to a root */
10404b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
1041fb770ae4SLiu Bo 		if (IS_ERR(child)) {
1042fb770ae4SLiu Bo 			ret = PTR_ERR(child);
10430b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1044*daefe4d4SFilipe Manana 			goto out;
1045305a26afSMark Fasheh 		}
1046305a26afSMark Fasheh 
1047925baeddSChris Mason 		btrfs_tree_lock(child);
10489631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
10499631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
1050f0486c68SYan, Zheng 		if (ret) {
1051f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
1052f0486c68SYan, Zheng 			free_extent_buffer(child);
1053*daefe4d4SFilipe Manana 			goto out;
1054f0486c68SYan, Zheng 		}
10552f375ab9SYan 
1056406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
105739020d8aSFilipe Manana 		if (ret < 0) {
105839020d8aSFilipe Manana 			btrfs_tree_unlock(child);
105939020d8aSFilipe Manana 			free_extent_buffer(child);
106039020d8aSFilipe Manana 			btrfs_abort_transaction(trans, ret);
1061*daefe4d4SFilipe Manana 			goto out;
106239020d8aSFilipe Manana 		}
1063240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
1064925baeddSChris Mason 
10650b86a832SChris Mason 		add_root_to_dirty_list(root);
1066925baeddSChris Mason 		btrfs_tree_unlock(child);
1067b4ce94deSChris Mason 
1068925baeddSChris Mason 		path->locks[level] = 0;
1069bb803951SChris Mason 		path->nodes[level] = NULL;
1070190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, mid);
1071925baeddSChris Mason 		btrfs_tree_unlock(mid);
1072bb803951SChris Mason 		/* once for the path */
10735f39d397SChris Mason 		free_extent_buffer(mid);
1074f0486c68SYan, Zheng 
1075f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10767a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1077bb803951SChris Mason 		/* once for the root ptr */
10783083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1079f0486c68SYan, Zheng 		return 0;
1080bb803951SChris Mason 	}
10815f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
10820b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1083bb803951SChris Mason 		return 0;
1084bb803951SChris Mason 
10859cf14029SJosef Bacik 	if (pslot) {
10864b231ae4SDavid Sterba 		left = btrfs_read_node_slot(parent, pslot - 1);
10879cf14029SJosef Bacik 		if (IS_ERR(left)) {
10889cf14029SJosef Bacik 			ret = PTR_ERR(left);
1089fb770ae4SLiu Bo 			left = NULL;
1090*daefe4d4SFilipe Manana 			goto out;
10919cf14029SJosef Bacik 		}
1092fb770ae4SLiu Bo 
1093bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
10945f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
10959631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
1096bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
109754aa1f4dSChris Mason 		if (wret) {
109854aa1f4dSChris Mason 			ret = wret;
1099*daefe4d4SFilipe Manana 			goto out;
110054aa1f4dSChris Mason 		}
11012cc58cf2SChris Mason 	}
1102fb770ae4SLiu Bo 
11039cf14029SJosef Bacik 	if (pslot + 1 < btrfs_header_nritems(parent)) {
11044b231ae4SDavid Sterba 		right = btrfs_read_node_slot(parent, pslot + 1);
11059cf14029SJosef Bacik 		if (IS_ERR(right)) {
11069cf14029SJosef Bacik 			ret = PTR_ERR(right);
1107fb770ae4SLiu Bo 			right = NULL;
1108*daefe4d4SFilipe Manana 			goto out;
11099cf14029SJosef Bacik 		}
1110fb770ae4SLiu Bo 
1111bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
11125f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
11139631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
1114bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
11152cc58cf2SChris Mason 		if (wret) {
11162cc58cf2SChris Mason 			ret = wret;
1117*daefe4d4SFilipe Manana 			goto out;
11182cc58cf2SChris Mason 		}
11192cc58cf2SChris Mason 	}
11202cc58cf2SChris Mason 
11212cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
11225f39d397SChris Mason 	if (left) {
11235f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1124d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
112579f95c82SChris Mason 		if (wret < 0)
112679f95c82SChris Mason 			ret = wret;
1127bb803951SChris Mason 	}
112879f95c82SChris Mason 
112979f95c82SChris Mason 	/*
113079f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
113179f95c82SChris Mason 	 */
11325f39d397SChris Mason 	if (right) {
1133d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
113454aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
113579f95c82SChris Mason 			ret = wret;
11365f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
1137190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, right);
1138925baeddSChris Mason 			btrfs_tree_unlock(right);
1139016f9d0bSJosef Bacik 			btrfs_del_ptr(root, path, level + 1, pslot + 1);
1140f0486c68SYan, Zheng 			root_sub_used(root, right->len);
11417a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
11427a163608SFilipe Manana 					      0, 1);
11433083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1144f0486c68SYan, Zheng 			right = NULL;
1145bb803951SChris Mason 		} else {
11465f39d397SChris Mason 			struct btrfs_disk_key right_key;
11475f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1148f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
114933cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
115039020d8aSFilipe Manana 			if (ret < 0) {
115139020d8aSFilipe Manana 				btrfs_abort_transaction(trans, ret);
1152*daefe4d4SFilipe Manana 				goto out;
115339020d8aSFilipe Manana 			}
11545f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
11555f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1156bb803951SChris Mason 		}
1157bb803951SChris Mason 	}
11585f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
115979f95c82SChris Mason 		/*
116079f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
116179f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
116279f95c82SChris Mason 		 * could try to delete the only pointer in this node.
116379f95c82SChris Mason 		 * So, pull some keys from the left.
116479f95c82SChris Mason 		 * There has to be a left pointer at this point because
116579f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
116679f95c82SChris Mason 		 * right
116779f95c82SChris Mason 		 */
1168305a26afSMark Fasheh 		if (!left) {
1169305a26afSMark Fasheh 			ret = -EROFS;
11700b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1171*daefe4d4SFilipe Manana 			goto out;
1172305a26afSMark Fasheh 		}
117355d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
117454aa1f4dSChris Mason 		if (wret < 0) {
117579f95c82SChris Mason 			ret = wret;
1176*daefe4d4SFilipe Manana 			goto out;
117754aa1f4dSChris Mason 		}
1178bce4eae9SChris Mason 		if (wret == 1) {
1179d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1180bce4eae9SChris Mason 			if (wret < 0)
1181bce4eae9SChris Mason 				ret = wret;
1182bce4eae9SChris Mason 		}
118379f95c82SChris Mason 		BUG_ON(wret == 1);
118479f95c82SChris Mason 	}
11855f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
1186190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, mid);
1187925baeddSChris Mason 		btrfs_tree_unlock(mid);
1188016f9d0bSJosef Bacik 		btrfs_del_ptr(root, path, level + 1, pslot);
1189f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
11907a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
11913083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1192f0486c68SYan, Zheng 		mid = NULL;
119379f95c82SChris Mason 	} else {
119479f95c82SChris Mason 		/* update the parent key to reflect our changes */
11955f39d397SChris Mason 		struct btrfs_disk_key mid_key;
11965f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1197f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
119833cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
119939020d8aSFilipe Manana 		if (ret < 0) {
120039020d8aSFilipe Manana 			btrfs_abort_transaction(trans, ret);
1201*daefe4d4SFilipe Manana 			goto out;
120239020d8aSFilipe Manana 		}
12035f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
12045f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
120579f95c82SChris Mason 	}
1206bb803951SChris Mason 
120779f95c82SChris Mason 	/* update the path */
12085f39d397SChris Mason 	if (left) {
12095f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
121067439dadSDavid Sterba 			atomic_inc(&left->refs);
1211925baeddSChris Mason 			/* left was locked after cow */
12125f39d397SChris Mason 			path->nodes[level] = left;
1213bb803951SChris Mason 			path->slots[level + 1] -= 1;
1214bb803951SChris Mason 			path->slots[level] = orig_slot;
1215925baeddSChris Mason 			if (mid) {
1216925baeddSChris Mason 				btrfs_tree_unlock(mid);
12175f39d397SChris Mason 				free_extent_buffer(mid);
1218925baeddSChris Mason 			}
1219bb803951SChris Mason 		} else {
12205f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1221bb803951SChris Mason 			path->slots[level] = orig_slot;
1222bb803951SChris Mason 		}
1223bb803951SChris Mason 	}
122479f95c82SChris Mason 	/* double check we haven't messed things up */
1225e20d96d6SChris Mason 	if (orig_ptr !=
12265f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
122779f95c82SChris Mason 		BUG();
1228*daefe4d4SFilipe Manana out:
1229925baeddSChris Mason 	if (right) {
1230925baeddSChris Mason 		btrfs_tree_unlock(right);
12315f39d397SChris Mason 		free_extent_buffer(right);
1232925baeddSChris Mason 	}
1233925baeddSChris Mason 	if (left) {
1234925baeddSChris Mason 		if (path->nodes[level] != left)
1235925baeddSChris Mason 			btrfs_tree_unlock(left);
12365f39d397SChris Mason 		free_extent_buffer(left);
1237925baeddSChris Mason 	}
1238bb803951SChris Mason 	return ret;
1239bb803951SChris Mason }
1240bb803951SChris Mason 
1241d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1242d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1243d352ac68SChris Mason  * have to be pessimistic.
1244d352ac68SChris Mason  */
1245d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1246e66f709bSChris Mason 					  struct btrfs_root *root,
1247e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1248e66f709bSChris Mason {
12490b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12505f39d397SChris Mason 	struct extent_buffer *right = NULL;
12515f39d397SChris Mason 	struct extent_buffer *mid;
12525f39d397SChris Mason 	struct extent_buffer *left = NULL;
12535f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1254e66f709bSChris Mason 	int ret = 0;
1255e66f709bSChris Mason 	int wret;
1256e66f709bSChris Mason 	int pslot;
1257e66f709bSChris Mason 	int orig_slot = path->slots[level];
1258e66f709bSChris Mason 
1259e66f709bSChris Mason 	if (level == 0)
1260e66f709bSChris Mason 		return 1;
1261e66f709bSChris Mason 
12625f39d397SChris Mason 	mid = path->nodes[level];
12637bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1264e66f709bSChris Mason 
1265a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
12665f39d397SChris Mason 		parent = path->nodes[level + 1];
1267e66f709bSChris Mason 		pslot = path->slots[level + 1];
1268a05a9bb1SLi Zefan 	}
1269e66f709bSChris Mason 
12705f39d397SChris Mason 	if (!parent)
1271e66f709bSChris Mason 		return 1;
1272e66f709bSChris Mason 
12739cf14029SJosef Bacik 	/* first, try to make some room in the middle buffer */
12749cf14029SJosef Bacik 	if (pslot) {
12759cf14029SJosef Bacik 		u32 left_nr;
12769cf14029SJosef Bacik 
12774b231ae4SDavid Sterba 		left = btrfs_read_node_slot(parent, pslot - 1);
1278fb770ae4SLiu Bo 		if (IS_ERR(left))
12799cf14029SJosef Bacik 			return PTR_ERR(left);
1280925baeddSChris Mason 
1281bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1282b4ce94deSChris Mason 
12835f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
12840b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
128533ade1f8SChris Mason 			wret = 1;
128633ade1f8SChris Mason 		} else {
12875f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
12889631e4ccSJosef Bacik 					      pslot - 1, &left,
1289bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
129054aa1f4dSChris Mason 			if (ret)
129154aa1f4dSChris Mason 				wret = 1;
129254aa1f4dSChris Mason 			else {
1293d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
129454aa1f4dSChris Mason 			}
129533ade1f8SChris Mason 		}
1296e66f709bSChris Mason 		if (wret < 0)
1297e66f709bSChris Mason 			ret = wret;
1298e66f709bSChris Mason 		if (wret == 0) {
12995f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1300e66f709bSChris Mason 			orig_slot += left_nr;
13015f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1302f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
130333cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
13040e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
13055f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
13065f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
13075f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
13085f39d397SChris Mason 				path->nodes[level] = left;
1309e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1310e66f709bSChris Mason 				path->slots[level] = orig_slot;
1311925baeddSChris Mason 				btrfs_tree_unlock(mid);
13125f39d397SChris Mason 				free_extent_buffer(mid);
1313e66f709bSChris Mason 			} else {
1314e66f709bSChris Mason 				orig_slot -=
13155f39d397SChris Mason 					btrfs_header_nritems(left);
1316e66f709bSChris Mason 				path->slots[level] = orig_slot;
1317925baeddSChris Mason 				btrfs_tree_unlock(left);
13185f39d397SChris Mason 				free_extent_buffer(left);
1319e66f709bSChris Mason 			}
1320e66f709bSChris Mason 			return 0;
1321e66f709bSChris Mason 		}
1322925baeddSChris Mason 		btrfs_tree_unlock(left);
13235f39d397SChris Mason 		free_extent_buffer(left);
1324e66f709bSChris Mason 	}
1325e66f709bSChris Mason 
1326e66f709bSChris Mason 	/*
1327e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1328e66f709bSChris Mason 	 */
13299cf14029SJosef Bacik 	if (pslot + 1 < btrfs_header_nritems(parent)) {
133033ade1f8SChris Mason 		u32 right_nr;
1331b4ce94deSChris Mason 
13329cf14029SJosef Bacik 		right = btrfs_read_node_slot(parent, pslot + 1);
13339cf14029SJosef Bacik 		if (IS_ERR(right))
13349cf14029SJosef Bacik 			return PTR_ERR(right);
13359cf14029SJosef Bacik 
1336bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1337b4ce94deSChris Mason 
13385f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
13390b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
134033ade1f8SChris Mason 			wret = 1;
134133ade1f8SChris Mason 		} else {
13425f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
13435f39d397SChris Mason 					      parent, pslot + 1,
1344bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
134554aa1f4dSChris Mason 			if (ret)
134654aa1f4dSChris Mason 				wret = 1;
134754aa1f4dSChris Mason 			else {
134855d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
134933ade1f8SChris Mason 			}
135054aa1f4dSChris Mason 		}
1351e66f709bSChris Mason 		if (wret < 0)
1352e66f709bSChris Mason 			ret = wret;
1353e66f709bSChris Mason 		if (wret == 0) {
13545f39d397SChris Mason 			struct btrfs_disk_key disk_key;
13555f39d397SChris Mason 
13565f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1357f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
135833cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
13590e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
13605f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
13615f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
13625f39d397SChris Mason 
13635f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
13645f39d397SChris Mason 				path->nodes[level] = right;
1365e66f709bSChris Mason 				path->slots[level + 1] += 1;
1366e66f709bSChris Mason 				path->slots[level] = orig_slot -
13675f39d397SChris Mason 					btrfs_header_nritems(mid);
1368925baeddSChris Mason 				btrfs_tree_unlock(mid);
13695f39d397SChris Mason 				free_extent_buffer(mid);
1370e66f709bSChris Mason 			} else {
1371925baeddSChris Mason 				btrfs_tree_unlock(right);
13725f39d397SChris Mason 				free_extent_buffer(right);
1373e66f709bSChris Mason 			}
1374e66f709bSChris Mason 			return 0;
1375e66f709bSChris Mason 		}
1376925baeddSChris Mason 		btrfs_tree_unlock(right);
13775f39d397SChris Mason 		free_extent_buffer(right);
1378e66f709bSChris Mason 	}
1379e66f709bSChris Mason 	return 1;
1380e66f709bSChris Mason }
1381e66f709bSChris Mason 
138274123bd7SChris Mason /*
1383d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1384d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
13853c69faecSChris Mason  */
13862ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1387e02119d5SChris Mason 			     struct btrfs_path *path,
138801f46658SChris Mason 			     int level, int slot, u64 objectid)
13893c69faecSChris Mason {
13905f39d397SChris Mason 	struct extent_buffer *node;
139101f46658SChris Mason 	struct btrfs_disk_key disk_key;
13923c69faecSChris Mason 	u32 nritems;
13933c69faecSChris Mason 	u64 search;
1394a7175319SChris Mason 	u64 target;
13956b80053dSChris Mason 	u64 nread = 0;
1396ace75066SFilipe Manana 	u64 nread_max;
13976b80053dSChris Mason 	u32 nr;
13986b80053dSChris Mason 	u32 blocksize;
13996b80053dSChris Mason 	u32 nscan = 0;
1400db94535dSChris Mason 
1401ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
14023c69faecSChris Mason 		return;
14033c69faecSChris Mason 
14046702ed49SChris Mason 	if (!path->nodes[level])
14056702ed49SChris Mason 		return;
14066702ed49SChris Mason 
14075f39d397SChris Mason 	node = path->nodes[level];
1408925baeddSChris Mason 
1409ace75066SFilipe Manana 	/*
1410ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1411ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1412ace75066SFilipe Manana 	 * much IO at once (possibly random).
1413ace75066SFilipe Manana 	 */
1414ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1415ace75066SFilipe Manana 		if (level > 1)
1416ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1417ace75066SFilipe Manana 		else
1418ace75066SFilipe Manana 			nread_max = SZ_128K;
1419ace75066SFilipe Manana 	} else {
1420ace75066SFilipe Manana 		nread_max = SZ_64K;
1421ace75066SFilipe Manana 	}
1422ace75066SFilipe Manana 
14233c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
14240b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1425069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1426069a2e37SFilipe Manana 		struct extent_buffer *eb;
1427069a2e37SFilipe Manana 
14280b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
14295f39d397SChris Mason 		if (eb) {
14305f39d397SChris Mason 			free_extent_buffer(eb);
14313c69faecSChris Mason 			return;
14323c69faecSChris Mason 		}
1433069a2e37SFilipe Manana 	}
14343c69faecSChris Mason 
1435a7175319SChris Mason 	target = search;
14366b80053dSChris Mason 
14375f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
14386b80053dSChris Mason 	nr = slot;
143925b8b936SJosef Bacik 
14403c69faecSChris Mason 	while (1) {
1441e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
14426b80053dSChris Mason 			if (nr == 0)
14433c69faecSChris Mason 				break;
14446b80053dSChris Mason 			nr--;
1445ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1446ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
14476b80053dSChris Mason 			nr++;
14486b80053dSChris Mason 			if (nr >= nritems)
14496b80053dSChris Mason 				break;
14503c69faecSChris Mason 		}
1451e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
145201f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
145301f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
145401f46658SChris Mason 				break;
145501f46658SChris Mason 		}
14566b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1457ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1458ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1459a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1460bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
14616b80053dSChris Mason 			nread += blocksize;
14623c69faecSChris Mason 		}
14636b80053dSChris Mason 		nscan++;
1464ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
14656b80053dSChris Mason 			break;
14663c69faecSChris Mason 	}
14673c69faecSChris Mason }
1468925baeddSChris Mason 
1469bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1470b4ce94deSChris Mason {
1471bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1472b4ce94deSChris Mason 	int slot;
1473b4ce94deSChris Mason 	int nritems;
1474b4ce94deSChris Mason 
14758c594ea8SChris Mason 	parent = path->nodes[level + 1];
1476b4ce94deSChris Mason 	if (!parent)
14770b08851fSJosef Bacik 		return;
1478b4ce94deSChris Mason 
1479b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
14808c594ea8SChris Mason 	slot = path->slots[level + 1];
1481b4ce94deSChris Mason 
1482bfb484d9SJosef Bacik 	if (slot > 0)
1483bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1484bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1485bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1486b4ce94deSChris Mason }
1487b4ce94deSChris Mason 
1488b4ce94deSChris Mason 
1489b4ce94deSChris Mason /*
1490d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1491d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1492d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1493d397712bSChris Mason  * tree.
1494d352ac68SChris Mason  *
1495d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1496d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1497d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1498d352ac68SChris Mason  *
1499d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1500d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1501d352ac68SChris Mason  */
1502e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1503f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1504f7c79f30SChris Mason 			       int *write_lock_level)
1505925baeddSChris Mason {
1506925baeddSChris Mason 	int i;
1507925baeddSChris Mason 	int skip_level = level;
1508c1227996SNikolay Borisov 	bool check_skip = true;
1509925baeddSChris Mason 
1510925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1511925baeddSChris Mason 		if (!path->nodes[i])
1512925baeddSChris Mason 			break;
1513925baeddSChris Mason 		if (!path->locks[i])
1514925baeddSChris Mason 			break;
1515c1227996SNikolay Borisov 
1516c1227996SNikolay Borisov 		if (check_skip) {
1517c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1518925baeddSChris Mason 				skip_level = i + 1;
1519925baeddSChris Mason 				continue;
1520925baeddSChris Mason 			}
1521c1227996SNikolay Borisov 
1522c1227996SNikolay Borisov 			if (path->keep_locks) {
1523925baeddSChris Mason 				u32 nritems;
1524c1227996SNikolay Borisov 
1525c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1526051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1527925baeddSChris Mason 					skip_level = i + 1;
1528925baeddSChris Mason 					continue;
1529925baeddSChris Mason 				}
1530925baeddSChris Mason 			}
1531c1227996SNikolay Borisov 		}
1532051e1b9fSChris Mason 
1533d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1534c1227996SNikolay Borisov 			check_skip = false;
1535c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1536925baeddSChris Mason 			path->locks[i] = 0;
1537f7c79f30SChris Mason 			if (write_lock_level &&
1538f7c79f30SChris Mason 			    i > min_write_lock_level &&
1539f7c79f30SChris Mason 			    i <= *write_lock_level) {
1540f7c79f30SChris Mason 				*write_lock_level = i - 1;
1541f7c79f30SChris Mason 			}
1542925baeddSChris Mason 		}
1543925baeddSChris Mason 	}
1544925baeddSChris Mason }
1545925baeddSChris Mason 
15463c69faecSChris Mason /*
1547376a21d7SFilipe Manana  * Helper function for btrfs_search_slot() and other functions that do a search
1548376a21d7SFilipe Manana  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1549376a21d7SFilipe Manana  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1550376a21d7SFilipe Manana  * its pages from disk.
1551c8c42864SChris Mason  *
1552376a21d7SFilipe Manana  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1553376a21d7SFilipe Manana  * whole btree search, starting again from the current root node.
1554c8c42864SChris Mason  */
1555c8c42864SChris Mason static int
1556d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1557c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1558cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1559c8c42864SChris Mason {
15600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1561789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1562c8c42864SChris Mason 	u64 blocknr;
1563c8c42864SChris Mason 	u64 gen;
1564c8c42864SChris Mason 	struct extent_buffer *tmp;
156576a05b35SChris Mason 	int ret;
1566581c1760SQu Wenruo 	int parent_level;
1567b246666eSFilipe Manana 	bool unlock_up;
1568c8c42864SChris Mason 
1569b246666eSFilipe Manana 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1570213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1571213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1572213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1573789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(*eb_ret, &check.first_key, slot);
1574789d6a3aSQu Wenruo 	check.has_first_key = true;
1575789d6a3aSQu Wenruo 	check.level = parent_level - 1;
1576789d6a3aSQu Wenruo 	check.transid = gen;
1577789d6a3aSQu Wenruo 	check.owner_root = root->root_key.objectid;
1578c8c42864SChris Mason 
1579b246666eSFilipe Manana 	/*
1580b246666eSFilipe Manana 	 * If we need to read an extent buffer from disk and we are holding locks
1581b246666eSFilipe Manana 	 * on upper level nodes, we unlock all the upper nodes before reading the
1582b246666eSFilipe Manana 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1583b246666eSFilipe Manana 	 * restart the search. We don't release the lock on the current level
1584b246666eSFilipe Manana 	 * because we need to walk this node to figure out which blocks to read.
1585b246666eSFilipe Manana 	 */
15860b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1587cb44921aSChris Mason 	if (tmp) {
1588ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1589ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1590ace75066SFilipe Manana 
1591b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1592b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1593448de471SQu Wenruo 			/*
1594448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1595448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1596448de471SQu Wenruo 			 * parents (shared tree blocks).
1597448de471SQu Wenruo 			 */
1598e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1599789d6a3aSQu Wenruo 					parent_level - 1, &check.first_key, gen)) {
1600448de471SQu Wenruo 				free_extent_buffer(tmp);
1601448de471SQu Wenruo 				return -EUCLEAN;
1602448de471SQu Wenruo 			}
1603c8c42864SChris Mason 			*eb_ret = tmp;
1604c8c42864SChris Mason 			return 0;
1605c8c42864SChris Mason 		}
1606bdf7c00eSJosef Bacik 
1607857bc13fSJosef Bacik 		if (p->nowait) {
1608857bc13fSJosef Bacik 			free_extent_buffer(tmp);
1609857bc13fSJosef Bacik 			return -EAGAIN;
1610857bc13fSJosef Bacik 		}
1611857bc13fSJosef Bacik 
1612b246666eSFilipe Manana 		if (unlock_up)
1613b246666eSFilipe Manana 			btrfs_unlock_up_safe(p, level + 1);
1614b246666eSFilipe Manana 
1615b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
1616789d6a3aSQu Wenruo 		ret = btrfs_read_extent_buffer(tmp, &check);
16179a4ffa1bSQu Wenruo 		if (ret) {
1618cb44921aSChris Mason 			free_extent_buffer(tmp);
1619b3b4aa74SDavid Sterba 			btrfs_release_path(p);
1620cb44921aSChris Mason 			return -EIO;
1621cb44921aSChris Mason 		}
162288c602abSQu Wenruo 		if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
162388c602abSQu Wenruo 			free_extent_buffer(tmp);
162488c602abSQu Wenruo 			btrfs_release_path(p);
162588c602abSQu Wenruo 			return -EUCLEAN;
162688c602abSQu Wenruo 		}
1627b246666eSFilipe Manana 
1628b246666eSFilipe Manana 		if (unlock_up)
1629b246666eSFilipe Manana 			ret = -EAGAIN;
1630b246666eSFilipe Manana 
1631b246666eSFilipe Manana 		goto out;
1632857bc13fSJosef Bacik 	} else if (p->nowait) {
1633857bc13fSJosef Bacik 		return -EAGAIN;
16349a4ffa1bSQu Wenruo 	}
1635c8c42864SChris Mason 
1636b246666eSFilipe Manana 	if (unlock_up) {
16378c594ea8SChris Mason 		btrfs_unlock_up_safe(p, level + 1);
16384bb59055SFilipe Manana 		ret = -EAGAIN;
16394bb59055SFilipe Manana 	} else {
16404bb59055SFilipe Manana 		ret = 0;
16414bb59055SFilipe Manana 	}
16428c594ea8SChris Mason 
1643e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
16442ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1645c8c42864SChris Mason 
1646789d6a3aSQu Wenruo 	tmp = read_tree_block(fs_info, blocknr, &check);
16474eb150d6SQu Wenruo 	if (IS_ERR(tmp)) {
16484eb150d6SQu Wenruo 		btrfs_release_path(p);
16494eb150d6SQu Wenruo 		return PTR_ERR(tmp);
16504eb150d6SQu Wenruo 	}
165176a05b35SChris Mason 	/*
165276a05b35SChris Mason 	 * If the read above didn't mark this buffer up to date,
165376a05b35SChris Mason 	 * it will never end up being up to date.  Set ret to EIO now
165476a05b35SChris Mason 	 * and give up so that our caller doesn't loop forever
165576a05b35SChris Mason 	 * on our EAGAINs.
165676a05b35SChris Mason 	 */
1657e6a1d6fdSLiu Bo 	if (!extent_buffer_uptodate(tmp))
165876a05b35SChris Mason 		ret = -EIO;
165902a3307aSLiu Bo 
1660b246666eSFilipe Manana out:
16614bb59055SFilipe Manana 	if (ret == 0) {
16624bb59055SFilipe Manana 		*eb_ret = tmp;
16634bb59055SFilipe Manana 	} else {
16644bb59055SFilipe Manana 		free_extent_buffer(tmp);
166502a3307aSLiu Bo 		btrfs_release_path(p);
16664bb59055SFilipe Manana 	}
16674bb59055SFilipe Manana 
166876a05b35SChris Mason 	return ret;
1669c8c42864SChris Mason }
1670c8c42864SChris Mason 
1671c8c42864SChris Mason /*
1672c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1673c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1674c8c42864SChris Mason  * the ins_len.
1675c8c42864SChris Mason  *
1676c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1677c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1678c8c42864SChris Mason  * start over
1679c8c42864SChris Mason  */
1680c8c42864SChris Mason static int
1681c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1682c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1683bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1684bd681513SChris Mason 		       int *write_lock_level)
1685c8c42864SChris Mason {
16860b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
168795b982deSNikolay Borisov 	int ret = 0;
16880b246afaSJeff Mahoney 
1689c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
16900b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1691c8c42864SChris Mason 
1692bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1693bd681513SChris Mason 			*write_lock_level = level + 1;
1694bd681513SChris Mason 			btrfs_release_path(p);
169595b982deSNikolay Borisov 			return -EAGAIN;
1696bd681513SChris Mason 		}
1697bd681513SChris Mason 
1698bfb484d9SJosef Bacik 		reada_for_balance(p, level);
169995b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1700c8c42864SChris Mason 
1701c8c42864SChris Mason 		b = p->nodes[level];
1702c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
17030b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1704c8c42864SChris Mason 
1705bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1706bd681513SChris Mason 			*write_lock_level = level + 1;
1707bd681513SChris Mason 			btrfs_release_path(p);
170895b982deSNikolay Borisov 			return -EAGAIN;
1709bd681513SChris Mason 		}
1710bd681513SChris Mason 
1711bfb484d9SJosef Bacik 		reada_for_balance(p, level);
171295b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
171395b982deSNikolay Borisov 		if (ret)
171495b982deSNikolay Borisov 			return ret;
1715c8c42864SChris Mason 
1716c8c42864SChris Mason 		b = p->nodes[level];
1717c8c42864SChris Mason 		if (!b) {
1718b3b4aa74SDavid Sterba 			btrfs_release_path(p);
171995b982deSNikolay Borisov 			return -EAGAIN;
1720c8c42864SChris Mason 		}
1721c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1722c8c42864SChris Mason 	}
1723c8c42864SChris Mason 	return ret;
1724c8c42864SChris Mason }
1725c8c42864SChris Mason 
1726381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1727e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1728e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1729e33d5c3dSKelley Nielsen {
1730e33d5c3dSKelley Nielsen 	int ret;
1731e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1732e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1733381cf658SDavid Sterba 
1734381cf658SDavid Sterba 	ASSERT(path);
17351d4c08e0SDavid Sterba 	ASSERT(found_key);
1736e33d5c3dSKelley Nielsen 
1737e33d5c3dSKelley Nielsen 	key.type = key_type;
1738e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1739e33d5c3dSKelley Nielsen 	key.offset = ioff;
1740e33d5c3dSKelley Nielsen 
1741e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
17421d4c08e0SDavid Sterba 	if (ret < 0)
1743e33d5c3dSKelley Nielsen 		return ret;
1744e33d5c3dSKelley Nielsen 
1745e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1746e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1747e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1748e33d5c3dSKelley Nielsen 		if (ret)
1749e33d5c3dSKelley Nielsen 			return ret;
1750e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1751e33d5c3dSKelley Nielsen 	}
1752e33d5c3dSKelley Nielsen 
1753e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1754e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1755e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1756e33d5c3dSKelley Nielsen 		return 1;
1757e33d5c3dSKelley Nielsen 
1758e33d5c3dSKelley Nielsen 	return 0;
1759e33d5c3dSKelley Nielsen }
1760e33d5c3dSKelley Nielsen 
17611fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
17621fc28d8eSLiu Bo 							struct btrfs_path *p,
17631fc28d8eSLiu Bo 							int write_lock_level)
17641fc28d8eSLiu Bo {
17651fc28d8eSLiu Bo 	struct extent_buffer *b;
1766120de408SJosef Bacik 	int root_lock = 0;
17671fc28d8eSLiu Bo 	int level = 0;
17681fc28d8eSLiu Bo 
17691fc28d8eSLiu Bo 	if (p->search_commit_root) {
17701fc28d8eSLiu Bo 		b = root->commit_root;
177167439dadSDavid Sterba 		atomic_inc(&b->refs);
17721fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1773f9ddfd05SLiu Bo 		/*
1774f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1775f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1776f9ddfd05SLiu Bo 		 */
1777f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
17781fc28d8eSLiu Bo 
17791fc28d8eSLiu Bo 		goto out;
17801fc28d8eSLiu Bo 	}
17811fc28d8eSLiu Bo 
17821fc28d8eSLiu Bo 	if (p->skip_locking) {
17831fc28d8eSLiu Bo 		b = btrfs_root_node(root);
17841fc28d8eSLiu Bo 		level = btrfs_header_level(b);
17851fc28d8eSLiu Bo 		goto out;
17861fc28d8eSLiu Bo 	}
17871fc28d8eSLiu Bo 
1788120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1789120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1790120de408SJosef Bacik 
17911fc28d8eSLiu Bo 	/*
1792662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1793662c653bSLiu Bo 	 * lock.
1794662c653bSLiu Bo 	 */
1795662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1796662c653bSLiu Bo 		/*
1797662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1798662c653bSLiu Bo 		 * have it read locked
17991fc28d8eSLiu Bo 		 */
1800857bc13fSJosef Bacik 		if (p->nowait) {
1801857bc13fSJosef Bacik 			b = btrfs_try_read_lock_root_node(root);
1802857bc13fSJosef Bacik 			if (IS_ERR(b))
1803857bc13fSJosef Bacik 				return b;
1804857bc13fSJosef Bacik 		} else {
18051bb96598SJosef Bacik 			b = btrfs_read_lock_root_node(root);
1806857bc13fSJosef Bacik 		}
18071fc28d8eSLiu Bo 		level = btrfs_header_level(b);
18081fc28d8eSLiu Bo 		if (level > write_lock_level)
18091fc28d8eSLiu Bo 			goto out;
18101fc28d8eSLiu Bo 
1811662c653bSLiu Bo 		/* Whoops, must trade for write lock */
18121fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
18131fc28d8eSLiu Bo 		free_extent_buffer(b);
1814662c653bSLiu Bo 	}
1815662c653bSLiu Bo 
18161fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
18171fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
18181fc28d8eSLiu Bo 
18191fc28d8eSLiu Bo 	/* The level might have changed, check again */
18201fc28d8eSLiu Bo 	level = btrfs_header_level(b);
18211fc28d8eSLiu Bo 
18221fc28d8eSLiu Bo out:
1823120de408SJosef Bacik 	/*
1824120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1825120de408SJosef Bacik 	 * longer valid, return an error in this case.
1826120de408SJosef Bacik 	 */
1827120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1828120de408SJosef Bacik 		if (root_lock)
1829120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1830120de408SJosef Bacik 		free_extent_buffer(b);
1831120de408SJosef Bacik 		return ERR_PTR(-EIO);
1832120de408SJosef Bacik 	}
1833120de408SJosef Bacik 
18341fc28d8eSLiu Bo 	p->nodes[level] = b;
18351fc28d8eSLiu Bo 	if (!p->skip_locking)
18361fc28d8eSLiu Bo 		p->locks[level] = root_lock;
18371fc28d8eSLiu Bo 	/*
18381fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
18391fc28d8eSLiu Bo 	 */
18401fc28d8eSLiu Bo 	return b;
18411fc28d8eSLiu Bo }
18421fc28d8eSLiu Bo 
1843d96b3424SFilipe Manana /*
1844d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1845d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1846d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1847d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1848d96b3424SFilipe Manana  * reallocated in the next transaction.
1849d96b3424SFilipe Manana  *
1850d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1851d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1852d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1853d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1854d96b3424SFilipe Manana  */
1855d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1856d96b3424SFilipe Manana {
1857d96b3424SFilipe Manana 	const int i = path->lowest_level;
1858d96b3424SFilipe Manana 	const int slot = path->slots[i];
1859d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1860d96b3424SFilipe Manana 	struct extent_buffer *clone;
1861d96b3424SFilipe Manana 
1862d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1863d96b3424SFilipe Manana 
1864d96b3424SFilipe Manana 	if (!lowest)
1865d96b3424SFilipe Manana 		return 0;
1866d96b3424SFilipe Manana 
1867d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1868d96b3424SFilipe Manana 
1869d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1870d96b3424SFilipe Manana 	if (!clone)
1871d96b3424SFilipe Manana 		return -ENOMEM;
1872d96b3424SFilipe Manana 
1873d96b3424SFilipe Manana 	btrfs_release_path(path);
1874d96b3424SFilipe Manana 	path->nodes[i] = clone;
1875d96b3424SFilipe Manana 	path->slots[i] = slot;
1876d96b3424SFilipe Manana 
1877d96b3424SFilipe Manana 	return 0;
1878d96b3424SFilipe Manana }
18791fc28d8eSLiu Bo 
1880e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1881e2e58d0fSFilipe Manana 				      int search_low_slot,
1882e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1883e2e58d0fSFilipe Manana 				      int prev_cmp,
1884e2e58d0fSFilipe Manana 				      int *slot)
1885e2e58d0fSFilipe Manana {
1886e2e58d0fSFilipe Manana 	/*
1887e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1888e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1889e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1890e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1891e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1892e2e58d0fSFilipe Manana 	 */
1893e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1894e2e58d0fSFilipe Manana 		*slot = 0;
1895e2e58d0fSFilipe Manana 		return 0;
1896e2e58d0fSFilipe Manana 	}
1897e2e58d0fSFilipe Manana 
1898fdf8d595SAnand Jain 	return btrfs_bin_search(eb, search_low_slot, key, slot);
1899e2e58d0fSFilipe Manana }
1900e2e58d0fSFilipe Manana 
1901109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1902109324cfSFilipe Manana 		       struct btrfs_root *root,
1903109324cfSFilipe Manana 		       const struct btrfs_key *key,
1904109324cfSFilipe Manana 		       struct btrfs_path *path,
1905109324cfSFilipe Manana 		       int ins_len,
1906109324cfSFilipe Manana 		       int prev_cmp)
1907109324cfSFilipe Manana {
1908109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
1909109324cfSFilipe Manana 	int leaf_free_space = -1;
1910109324cfSFilipe Manana 	int search_low_slot = 0;
1911109324cfSFilipe Manana 	int ret;
1912109324cfSFilipe Manana 	bool do_bin_search = true;
1913109324cfSFilipe Manana 
1914109324cfSFilipe Manana 	/*
1915109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
1916109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
1917109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
1918109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1919109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
1920109324cfSFilipe Manana 	 */
1921109324cfSFilipe Manana 	if (ins_len > 0) {
1922109324cfSFilipe Manana 		/*
1923109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
1924109324cfSFilipe Manana 		 * will not change until then.
1925109324cfSFilipe Manana 		 */
1926109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
1927109324cfSFilipe Manana 
1928109324cfSFilipe Manana 		/*
1929109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
1930109324cfSFilipe Manana 		 * the root of the tree.
1931109324cfSFilipe Manana 		 */
1932109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
1933109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
1934109324cfSFilipe Manana 
1935109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
1936109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
1937109324cfSFilipe Manana 
1938109324cfSFilipe Manana 			/*
1939109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
1940109324cfSFilipe Manana 			 * taking into account that the first key is very likely
1941109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
1942109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
1943109324cfSFilipe Manana 			 * the header's level field.
1944109324cfSFilipe Manana 			 */
1945109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
1946109324cfSFilipe Manana 			if (ret < 0) {
1947109324cfSFilipe Manana 				/*
1948109324cfSFilipe Manana 				 * The first key is smaller than the key we want
1949109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
1950109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
1951109324cfSFilipe Manana 				 *
1952109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
1953109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
1954109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
1955109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
1956109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
1957109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
1958109324cfSFilipe Manana 				 */
1959109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
1960109324cfSFilipe Manana 				search_low_slot = 1;
1961109324cfSFilipe Manana 			} else {
1962109324cfSFilipe Manana 				/*
1963109324cfSFilipe Manana 				 * The first key is >= then the key we want to
1964109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
1965109324cfSFilipe Manana 				 * the target key will be at slot 0.
1966109324cfSFilipe Manana 				 *
1967109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
1968109324cfSFilipe Manana 				 * less than the first key, because we will need
1969109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
1970109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
1971109324cfSFilipe Manana 				 * If the key matches the first key, then we can
1972109324cfSFilipe Manana 				 * unlock all the upper nodes, using
1973109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
1974109324cfSFilipe Manana 				 * as stated above.
1975109324cfSFilipe Manana 				 */
1976109324cfSFilipe Manana 				if (ret == 0)
1977109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
1978109324cfSFilipe Manana 				/*
1979109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
1980109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
1981109324cfSFilipe Manana 				 * to adjust it.
1982109324cfSFilipe Manana 				 */
1983109324cfSFilipe Manana 				do_bin_search = false;
1984109324cfSFilipe Manana 				path->slots[0] = 0;
1985109324cfSFilipe Manana 			}
1986109324cfSFilipe Manana 		}
1987109324cfSFilipe Manana 	}
1988109324cfSFilipe Manana 
1989109324cfSFilipe Manana 	if (do_bin_search) {
1990109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
1991109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
1992109324cfSFilipe Manana 		if (ret < 0)
1993109324cfSFilipe Manana 			return ret;
1994109324cfSFilipe Manana 	}
1995109324cfSFilipe Manana 
1996109324cfSFilipe Manana 	if (ins_len > 0) {
1997109324cfSFilipe Manana 		/*
1998109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
1999109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
2000109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
2001109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
2002109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
2003109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
2004109324cfSFilipe Manana 		 * check will be correct.
2005109324cfSFilipe Manana 		 */
2006109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
2007109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
2008109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
2009109324cfSFilipe Manana 		}
2010109324cfSFilipe Manana 
2011109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
2012109324cfSFilipe Manana 
2013109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
2014109324cfSFilipe Manana 			int err;
2015109324cfSFilipe Manana 
2016109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
2017109324cfSFilipe Manana 					 (ret == 0));
2018bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
2019bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
2020bb8e9a60SFilipe Manana 				err = -EUCLEAN;
2021109324cfSFilipe Manana 			if (err)
2022109324cfSFilipe Manana 				ret = err;
2023109324cfSFilipe Manana 		}
2024109324cfSFilipe Manana 	}
2025109324cfSFilipe Manana 
2026109324cfSFilipe Manana 	return ret;
2027109324cfSFilipe Manana }
2028109324cfSFilipe Manana 
2029c8c42864SChris Mason /*
20304271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
20314271eceaSNikolay Borisov  * modifications to preserve tree invariants.
203274123bd7SChris Mason  *
20334271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
20344271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
20354271eceaSNikolay Borisov  * @root:	The root node of the tree
20364271eceaSNikolay Borisov  * @key:	The key we are looking for
20379a664971Sethanwu  * @ins_len:	Indicates purpose of search:
20389a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
20399a664971Sethanwu  *              <0  for deletions
20409a664971Sethanwu  *               0  for plain searches, not modifying the tree
20419a664971Sethanwu  *
20429a664971Sethanwu  *              (*) If size of item inserted doesn't include
20439a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
20449a664971Sethanwu  *              be set.
20454271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
20464271eceaSNikolay Borisov  *		when modifying the tree.
204797571fd0SChris Mason  *
20484271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
20494271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
20504271eceaSNikolay Borisov  *
20514271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
20524271eceaSNikolay Borisov  * of the path (level 0)
20534271eceaSNikolay Borisov  *
20544271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
20554271eceaSNikolay Borisov  * points to the slot where it should be inserted
20564271eceaSNikolay Borisov  *
20574271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
20584271eceaSNikolay Borisov  * is returned
205974123bd7SChris Mason  */
2060310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2061310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
2062310712b2SOmar Sandoval 		      int ins_len, int cow)
2063be0e5c09SChris Mason {
2064d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
20655f39d397SChris Mason 	struct extent_buffer *b;
2066be0e5c09SChris Mason 	int slot;
2067be0e5c09SChris Mason 	int ret;
206833c66f43SYan Zheng 	int err;
2069be0e5c09SChris Mason 	int level;
2070925baeddSChris Mason 	int lowest_unlock = 1;
2071bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
2072bd681513SChris Mason 	int write_lock_level = 0;
20739f3a7427SChris Mason 	u8 lowest_level = 0;
2074f7c79f30SChris Mason 	int min_write_lock_level;
2075d7396f07SFilipe David Borba Manana 	int prev_cmp;
20769f3a7427SChris Mason 
2077a4c853afSChenXiaoSong 	might_sleep();
2078a4c853afSChenXiaoSong 
20796702ed49SChris Mason 	lowest_level = p->lowest_level;
2080323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
208122b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
2082eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
208325179201SJosef Bacik 
2084857bc13fSJosef Bacik 	/*
2085857bc13fSJosef Bacik 	 * For now only allow nowait for read only operations.  There's no
2086857bc13fSJosef Bacik 	 * strict reason why we can't, we just only need it for reads so it's
2087857bc13fSJosef Bacik 	 * only implemented for reads.
2088857bc13fSJosef Bacik 	 */
2089857bc13fSJosef Bacik 	ASSERT(!p->nowait || !cow);
2090857bc13fSJosef Bacik 
2091bd681513SChris Mason 	if (ins_len < 0) {
2092925baeddSChris Mason 		lowest_unlock = 2;
209365b51a00SChris Mason 
2094bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
2095bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
2096bd681513SChris Mason 		 * for those levels as well
2097bd681513SChris Mason 		 */
2098bd681513SChris Mason 		write_lock_level = 2;
2099bd681513SChris Mason 	} else if (ins_len > 0) {
2100bd681513SChris Mason 		/*
2101bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
2102bd681513SChris Mason 		 * level 1 so we can update keys
2103bd681513SChris Mason 		 */
2104bd681513SChris Mason 		write_lock_level = 1;
2105bd681513SChris Mason 	}
2106bd681513SChris Mason 
2107bd681513SChris Mason 	if (!cow)
2108bd681513SChris Mason 		write_lock_level = -1;
2109bd681513SChris Mason 
211009a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
2111bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
2112bd681513SChris Mason 
2113f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
2114f7c79f30SChris Mason 
2115d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2116d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
2117857bc13fSJosef Bacik 		if (p->nowait) {
2118857bc13fSJosef Bacik 			if (!down_read_trylock(&fs_info->commit_root_sem))
2119857bc13fSJosef Bacik 				return -EAGAIN;
2120857bc13fSJosef Bacik 		} else {
2121d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
2122d96b3424SFilipe Manana 		}
2123857bc13fSJosef Bacik 	}
2124d96b3424SFilipe Manana 
2125bb803951SChris Mason again:
2126d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
21271fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2128be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2129be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2130be6821f8SFilipe Manana 		goto done;
2131be6821f8SFilipe Manana 	}
2132925baeddSChris Mason 
2133eb60ceacSChris Mason 	while (b) {
2134f624d976SQu Wenruo 		int dec = 0;
2135f624d976SQu Wenruo 
21365f39d397SChris Mason 		level = btrfs_header_level(b);
213765b51a00SChris Mason 
213802217ed2SChris Mason 		if (cow) {
21399ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
21409ea2c7c9SNikolay Borisov 
2141c8c42864SChris Mason 			/*
2142c8c42864SChris Mason 			 * if we don't really need to cow this block
2143c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2144c8c42864SChris Mason 			 * so we test it here
2145c8c42864SChris Mason 			 */
21465963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
214765b51a00SChris Mason 				goto cow_done;
21485d4f98a2SYan Zheng 
2149bd681513SChris Mason 			/*
2150bd681513SChris Mason 			 * must have write locks on this node and the
2151bd681513SChris Mason 			 * parent
2152bd681513SChris Mason 			 */
21535124e00eSJosef Bacik 			if (level > write_lock_level ||
21545124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
21555124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
21565124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2157bd681513SChris Mason 				write_lock_level = level + 1;
2158bd681513SChris Mason 				btrfs_release_path(p);
2159bd681513SChris Mason 				goto again;
2160bd681513SChris Mason 			}
2161bd681513SChris Mason 
21629ea2c7c9SNikolay Borisov 			if (last_level)
21639ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
21649631e4ccSJosef Bacik 						      &b,
21659631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
21669ea2c7c9SNikolay Borisov 			else
216733c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2168e20d96d6SChris Mason 						      p->nodes[level + 1],
21699631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
21709631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
217133c66f43SYan Zheng 			if (err) {
217233c66f43SYan Zheng 				ret = err;
217365b51a00SChris Mason 				goto done;
217454aa1f4dSChris Mason 			}
217502217ed2SChris Mason 		}
217665b51a00SChris Mason cow_done:
2177eb60ceacSChris Mason 		p->nodes[level] = b;
2178b4ce94deSChris Mason 
2179b4ce94deSChris Mason 		/*
2180b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2181b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2182b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2183b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2184b4ce94deSChris Mason 		 *
2185eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2186eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2187eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2188eb653de1SFilipe David Borba Manana 		 * we're operating on.
2189b4ce94deSChris Mason 		 */
2190eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2191eb653de1SFilipe David Borba Manana 			int u = level + 1;
2192eb653de1SFilipe David Borba Manana 
2193eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2194eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2195eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2196eb653de1SFilipe David Borba Manana 			}
2197eb653de1SFilipe David Borba Manana 		}
2198b4ce94deSChris Mason 
2199e2e58d0fSFilipe Manana 		if (level == 0) {
2200109324cfSFilipe Manana 			if (ins_len > 0)
2201e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
2202bd681513SChris Mason 
2203109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2204459931ecSChris Mason 			if (!p->search_for_split)
2205f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
22064b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
220765b51a00SChris Mason 			goto done;
220865b51a00SChris Mason 		}
2209e2e58d0fSFilipe Manana 
2210e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2211e2e58d0fSFilipe Manana 		if (ret < 0)
2212e2e58d0fSFilipe Manana 			goto done;
2213e2e58d0fSFilipe Manana 		prev_cmp = ret;
2214e2e58d0fSFilipe Manana 
2215f624d976SQu Wenruo 		if (ret && slot > 0) {
2216f624d976SQu Wenruo 			dec = 1;
2217f624d976SQu Wenruo 			slot--;
2218f624d976SQu Wenruo 		}
2219f624d976SQu Wenruo 		p->slots[level] = slot;
2220f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2221f624d976SQu Wenruo 					     &write_lock_level);
2222f624d976SQu Wenruo 		if (err == -EAGAIN)
2223f624d976SQu Wenruo 			goto again;
2224f624d976SQu Wenruo 		if (err) {
2225f624d976SQu Wenruo 			ret = err;
2226f624d976SQu Wenruo 			goto done;
2227f624d976SQu Wenruo 		}
2228f624d976SQu Wenruo 		b = p->nodes[level];
2229f624d976SQu Wenruo 		slot = p->slots[level];
2230f624d976SQu Wenruo 
2231f624d976SQu Wenruo 		/*
2232f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2233f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2234f624d976SQu Wenruo 		 * the parent
2235f624d976SQu Wenruo 		 */
2236f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2237f624d976SQu Wenruo 			write_lock_level = level + 1;
2238f624d976SQu Wenruo 			btrfs_release_path(p);
2239f624d976SQu Wenruo 			goto again;
2240f624d976SQu Wenruo 		}
2241f624d976SQu Wenruo 
2242f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2243f624d976SQu Wenruo 			  &write_lock_level);
2244f624d976SQu Wenruo 
2245f624d976SQu Wenruo 		if (level == lowest_level) {
2246f624d976SQu Wenruo 			if (dec)
2247f624d976SQu Wenruo 				p->slots[level]++;
2248f624d976SQu Wenruo 			goto done;
2249f624d976SQu Wenruo 		}
2250f624d976SQu Wenruo 
2251f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2252f624d976SQu Wenruo 		if (err == -EAGAIN)
2253f624d976SQu Wenruo 			goto again;
2254f624d976SQu Wenruo 		if (err) {
2255f624d976SQu Wenruo 			ret = err;
2256f624d976SQu Wenruo 			goto done;
2257f624d976SQu Wenruo 		}
2258f624d976SQu Wenruo 
2259f624d976SQu Wenruo 		if (!p->skip_locking) {
2260f624d976SQu Wenruo 			level = btrfs_header_level(b);
2261b40130b2SJosef Bacik 
2262b40130b2SJosef Bacik 			btrfs_maybe_reset_lockdep_class(root, b);
2263b40130b2SJosef Bacik 
2264f624d976SQu Wenruo 			if (level <= write_lock_level) {
2265f624d976SQu Wenruo 				btrfs_tree_lock(b);
2266f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2267f624d976SQu Wenruo 			} else {
2268857bc13fSJosef Bacik 				if (p->nowait) {
2269857bc13fSJosef Bacik 					if (!btrfs_try_tree_read_lock(b)) {
2270857bc13fSJosef Bacik 						free_extent_buffer(b);
2271857bc13fSJosef Bacik 						ret = -EAGAIN;
2272857bc13fSJosef Bacik 						goto done;
2273857bc13fSJosef Bacik 					}
2274857bc13fSJosef Bacik 				} else {
2275fe596ca3SJosef Bacik 					btrfs_tree_read_lock(b);
2276857bc13fSJosef Bacik 				}
2277f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2278f624d976SQu Wenruo 			}
2279f624d976SQu Wenruo 			p->nodes[level] = b;
2280f624d976SQu Wenruo 		}
228165b51a00SChris Mason 	}
228265b51a00SChris Mason 	ret = 1;
228365b51a00SChris Mason done:
22845f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2285b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2286d96b3424SFilipe Manana 
2287d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2288d96b3424SFilipe Manana 		int ret2;
2289d96b3424SFilipe Manana 
2290d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2291d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2292d96b3424SFilipe Manana 		if (ret2)
2293d96b3424SFilipe Manana 			ret = ret2;
2294d96b3424SFilipe Manana 	}
2295d96b3424SFilipe Manana 
2296be0e5c09SChris Mason 	return ret;
2297be0e5c09SChris Mason }
2298f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2299be0e5c09SChris Mason 
230074123bd7SChris Mason /*
23015d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
23025d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
23035d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
23045d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
23055d9e75c4SJan Schmidt  *
23065d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
23075d9e75c4SJan Schmidt  *
23085d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
23095d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
23105d9e75c4SJan Schmidt  */
2311310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
23125d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
23135d9e75c4SJan Schmidt {
23140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
23155d9e75c4SJan Schmidt 	struct extent_buffer *b;
23165d9e75c4SJan Schmidt 	int slot;
23175d9e75c4SJan Schmidt 	int ret;
23185d9e75c4SJan Schmidt 	int err;
23195d9e75c4SJan Schmidt 	int level;
23205d9e75c4SJan Schmidt 	int lowest_unlock = 1;
23215d9e75c4SJan Schmidt 	u8 lowest_level = 0;
23225d9e75c4SJan Schmidt 
23235d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
23245d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
2325c922b016SStefan Roesch 	ASSERT(!p->nowait);
23265d9e75c4SJan Schmidt 
23275d9e75c4SJan Schmidt 	if (p->search_commit_root) {
23285d9e75c4SJan Schmidt 		BUG_ON(time_seq);
23295d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
23305d9e75c4SJan Schmidt 	}
23315d9e75c4SJan Schmidt 
23325d9e75c4SJan Schmidt again:
2333f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2334315bed43SNikolay Borisov 	if (!b) {
2335315bed43SNikolay Borisov 		ret = -EIO;
2336315bed43SNikolay Borisov 		goto done;
2337315bed43SNikolay Borisov 	}
23385d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
23395d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
23405d9e75c4SJan Schmidt 
23415d9e75c4SJan Schmidt 	while (b) {
2342abe9339dSQu Wenruo 		int dec = 0;
2343abe9339dSQu Wenruo 
23445d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
23455d9e75c4SJan Schmidt 		p->nodes[level] = b;
23465d9e75c4SJan Schmidt 
23475d9e75c4SJan Schmidt 		/*
23485d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
23495d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
23505d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
23515d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
23525d9e75c4SJan Schmidt 		 */
23535d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
23545d9e75c4SJan Schmidt 
2355fdf8d595SAnand Jain 		ret = btrfs_bin_search(b, 0, key, &slot);
2356cbca7d59SFilipe Manana 		if (ret < 0)
2357cbca7d59SFilipe Manana 			goto done;
23585d9e75c4SJan Schmidt 
2359abe9339dSQu Wenruo 		if (level == 0) {
2360abe9339dSQu Wenruo 			p->slots[level] = slot;
2361abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2362abe9339dSQu Wenruo 			goto done;
2363abe9339dSQu Wenruo 		}
2364abe9339dSQu Wenruo 
23655d9e75c4SJan Schmidt 		if (ret && slot > 0) {
23665d9e75c4SJan Schmidt 			dec = 1;
2367abe9339dSQu Wenruo 			slot--;
23685d9e75c4SJan Schmidt 		}
23695d9e75c4SJan Schmidt 		p->slots[level] = slot;
23705d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
23715d9e75c4SJan Schmidt 
23725d9e75c4SJan Schmidt 		if (level == lowest_level) {
23735d9e75c4SJan Schmidt 			if (dec)
23745d9e75c4SJan Schmidt 				p->slots[level]++;
23755d9e75c4SJan Schmidt 			goto done;
23765d9e75c4SJan Schmidt 		}
23775d9e75c4SJan Schmidt 
2378abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
23795d9e75c4SJan Schmidt 		if (err == -EAGAIN)
23805d9e75c4SJan Schmidt 			goto again;
23815d9e75c4SJan Schmidt 		if (err) {
23825d9e75c4SJan Schmidt 			ret = err;
23835d9e75c4SJan Schmidt 			goto done;
23845d9e75c4SJan Schmidt 		}
23855d9e75c4SJan Schmidt 
23865d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
23875d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2388f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2389db7f3436SJosef Bacik 		if (!b) {
2390db7f3436SJosef Bacik 			ret = -ENOMEM;
2391db7f3436SJosef Bacik 			goto done;
2392db7f3436SJosef Bacik 		}
23935d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
23945d9e75c4SJan Schmidt 		p->nodes[level] = b;
23955d9e75c4SJan Schmidt 	}
23965d9e75c4SJan Schmidt 	ret = 1;
23975d9e75c4SJan Schmidt done:
23985d9e75c4SJan Schmidt 	if (ret < 0)
23995d9e75c4SJan Schmidt 		btrfs_release_path(p);
24005d9e75c4SJan Schmidt 
24015d9e75c4SJan Schmidt 	return ret;
24025d9e75c4SJan Schmidt }
24035d9e75c4SJan Schmidt 
24045d9e75c4SJan Schmidt /*
2405f469c8bdSFilipe Manana  * Search the tree again to find a leaf with smaller keys.
2406f469c8bdSFilipe Manana  * Returns 0 if it found something.
2407f469c8bdSFilipe Manana  * Returns 1 if there are no smaller keys.
2408f469c8bdSFilipe Manana  * Returns < 0 on error.
2409f469c8bdSFilipe Manana  *
2410f469c8bdSFilipe Manana  * This may release the path, and so you may lose any locks held at the
2411f469c8bdSFilipe Manana  * time you call it.
2412f469c8bdSFilipe Manana  */
2413f469c8bdSFilipe Manana static int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
2414f469c8bdSFilipe Manana {
2415f469c8bdSFilipe Manana 	struct btrfs_key key;
2416f469c8bdSFilipe Manana 	struct btrfs_key orig_key;
2417f469c8bdSFilipe Manana 	struct btrfs_disk_key found_key;
2418f469c8bdSFilipe Manana 	int ret;
2419f469c8bdSFilipe Manana 
2420f469c8bdSFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
2421f469c8bdSFilipe Manana 	orig_key = key;
2422f469c8bdSFilipe Manana 
2423f469c8bdSFilipe Manana 	if (key.offset > 0) {
2424f469c8bdSFilipe Manana 		key.offset--;
2425f469c8bdSFilipe Manana 	} else if (key.type > 0) {
2426f469c8bdSFilipe Manana 		key.type--;
2427f469c8bdSFilipe Manana 		key.offset = (u64)-1;
2428f469c8bdSFilipe Manana 	} else if (key.objectid > 0) {
2429f469c8bdSFilipe Manana 		key.objectid--;
2430f469c8bdSFilipe Manana 		key.type = (u8)-1;
2431f469c8bdSFilipe Manana 		key.offset = (u64)-1;
2432f469c8bdSFilipe Manana 	} else {
2433f469c8bdSFilipe Manana 		return 1;
2434f469c8bdSFilipe Manana 	}
2435f469c8bdSFilipe Manana 
2436f469c8bdSFilipe Manana 	btrfs_release_path(path);
2437f469c8bdSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2438f469c8bdSFilipe Manana 	if (ret <= 0)
2439f469c8bdSFilipe Manana 		return ret;
2440f469c8bdSFilipe Manana 
2441f469c8bdSFilipe Manana 	/*
2442f469c8bdSFilipe Manana 	 * Previous key not found. Even if we were at slot 0 of the leaf we had
2443f469c8bdSFilipe Manana 	 * before releasing the path and calling btrfs_search_slot(), we now may
2444f469c8bdSFilipe Manana 	 * be in a slot pointing to the same original key - this can happen if
2445f469c8bdSFilipe Manana 	 * after we released the path, one of more items were moved from a
2446f469c8bdSFilipe Manana 	 * sibling leaf into the front of the leaf we had due to an insertion
2447f469c8bdSFilipe Manana 	 * (see push_leaf_right()).
2448f469c8bdSFilipe Manana 	 * If we hit this case and our slot is > 0 and just decrement the slot
2449f469c8bdSFilipe Manana 	 * so that the caller does not process the same key again, which may or
2450f469c8bdSFilipe Manana 	 * may not break the caller, depending on its logic.
2451f469c8bdSFilipe Manana 	 */
2452f469c8bdSFilipe Manana 	if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
2453f469c8bdSFilipe Manana 		btrfs_item_key(path->nodes[0], &found_key, path->slots[0]);
2454f469c8bdSFilipe Manana 		ret = comp_keys(&found_key, &orig_key);
2455f469c8bdSFilipe Manana 		if (ret == 0) {
2456f469c8bdSFilipe Manana 			if (path->slots[0] > 0) {
2457f469c8bdSFilipe Manana 				path->slots[0]--;
2458f469c8bdSFilipe Manana 				return 0;
2459f469c8bdSFilipe Manana 			}
2460f469c8bdSFilipe Manana 			/*
2461f469c8bdSFilipe Manana 			 * At slot 0, same key as before, it means orig_key is
2462f469c8bdSFilipe Manana 			 * the lowest, leftmost, key in the tree. We're done.
2463f469c8bdSFilipe Manana 			 */
2464f469c8bdSFilipe Manana 			return 1;
2465f469c8bdSFilipe Manana 		}
2466f469c8bdSFilipe Manana 	}
2467f469c8bdSFilipe Manana 
2468f469c8bdSFilipe Manana 	btrfs_item_key(path->nodes[0], &found_key, 0);
2469f469c8bdSFilipe Manana 	ret = comp_keys(&found_key, &key);
2470f469c8bdSFilipe Manana 	/*
2471f469c8bdSFilipe Manana 	 * We might have had an item with the previous key in the tree right
2472f469c8bdSFilipe Manana 	 * before we released our path. And after we released our path, that
2473f469c8bdSFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
2474f469c8bdSFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
2475f469c8bdSFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
2476f469c8bdSFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
2477f469c8bdSFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
2478f469c8bdSFilipe Manana 	 * the previous key we computed above.
2479f469c8bdSFilipe Manana 	 */
2480f469c8bdSFilipe Manana 	if (ret <= 0)
2481f469c8bdSFilipe Manana 		return 0;
2482f469c8bdSFilipe Manana 	return 1;
2483f469c8bdSFilipe Manana }
2484f469c8bdSFilipe Manana 
2485f469c8bdSFilipe Manana /*
24862f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
24872f38b3e1SArne Jansen  * instead the next or previous item should be returned.
24882f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
24892f38b3e1SArne Jansen  * otherwise.
24902f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
24912f38b3e1SArne Jansen  * return the next lower instead.
24922f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
24932f38b3e1SArne Jansen  * return the next higher instead.
24942f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
24952f38b3e1SArne Jansen  * < 0 on error
24962f38b3e1SArne Jansen  */
24972f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2498310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2499310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2500310712b2SOmar Sandoval 			       int return_any)
25012f38b3e1SArne Jansen {
25022f38b3e1SArne Jansen 	int ret;
25032f38b3e1SArne Jansen 	struct extent_buffer *leaf;
25042f38b3e1SArne Jansen 
25052f38b3e1SArne Jansen again:
25062f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
25072f38b3e1SArne Jansen 	if (ret <= 0)
25082f38b3e1SArne Jansen 		return ret;
25092f38b3e1SArne Jansen 	/*
25102f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
25112f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
25122f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
25132f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
25142f38b3e1SArne Jansen 	 * item.
25152f38b3e1SArne Jansen 	 */
25162f38b3e1SArne Jansen 	leaf = p->nodes[0];
25172f38b3e1SArne Jansen 
25182f38b3e1SArne Jansen 	if (find_higher) {
25192f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
25202f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
25212f38b3e1SArne Jansen 			if (ret <= 0)
25222f38b3e1SArne Jansen 				return ret;
25232f38b3e1SArne Jansen 			if (!return_any)
25242f38b3e1SArne Jansen 				return 1;
25252f38b3e1SArne Jansen 			/*
25262f38b3e1SArne Jansen 			 * no higher item found, return the next
25272f38b3e1SArne Jansen 			 * lower instead
25282f38b3e1SArne Jansen 			 */
25292f38b3e1SArne Jansen 			return_any = 0;
25302f38b3e1SArne Jansen 			find_higher = 0;
25312f38b3e1SArne Jansen 			btrfs_release_path(p);
25322f38b3e1SArne Jansen 			goto again;
25332f38b3e1SArne Jansen 		}
25342f38b3e1SArne Jansen 	} else {
25352f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
25362f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2537e6793769SArne Jansen 			if (ret < 0)
25382f38b3e1SArne Jansen 				return ret;
2539e6793769SArne Jansen 			if (!ret) {
254023c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
254123c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
254223c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2543e6793769SArne Jansen 				return 0;
2544e6793769SArne Jansen 			}
25452f38b3e1SArne Jansen 			if (!return_any)
25462f38b3e1SArne Jansen 				return 1;
25472f38b3e1SArne Jansen 			/*
25482f38b3e1SArne Jansen 			 * no lower item found, return the next
25492f38b3e1SArne Jansen 			 * higher instead
25502f38b3e1SArne Jansen 			 */
25512f38b3e1SArne Jansen 			return_any = 0;
25522f38b3e1SArne Jansen 			find_higher = 1;
25532f38b3e1SArne Jansen 			btrfs_release_path(p);
25542f38b3e1SArne Jansen 			goto again;
2555e6793769SArne Jansen 		} else {
25562f38b3e1SArne Jansen 			--p->slots[0];
25572f38b3e1SArne Jansen 		}
25582f38b3e1SArne Jansen 	}
25592f38b3e1SArne Jansen 	return 0;
25602f38b3e1SArne Jansen }
25612f38b3e1SArne Jansen 
25622f38b3e1SArne Jansen /*
25630ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
25640ff40a91SMarcos Paulo de Souza  * was not found.
25650ff40a91SMarcos Paulo de Souza  *
25660ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
25670ff40a91SMarcos Paulo de Souza  */
25680ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
25690ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
25700ff40a91SMarcos Paulo de Souza {
25710ff40a91SMarcos Paulo de Souza 	int ret;
25720ff40a91SMarcos Paulo de Souza 
25730ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
25740ff40a91SMarcos Paulo de Souza 	if (ret > 0)
25750ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
25760ff40a91SMarcos Paulo de Souza 
25770ff40a91SMarcos Paulo de Souza 	if (ret == 0)
25780ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
25790ff40a91SMarcos Paulo de Souza 
25800ff40a91SMarcos Paulo de Souza 	return ret;
25810ff40a91SMarcos Paulo de Souza }
25820ff40a91SMarcos Paulo de Souza 
258343dd529aSDavid Sterba /*
258462142be3SGabriel Niebler  * Search for a valid slot for the given path.
258562142be3SGabriel Niebler  *
258662142be3SGabriel Niebler  * @root:	The root node of the tree.
258762142be3SGabriel Niebler  * @key:	Will contain a valid item if found.
258862142be3SGabriel Niebler  * @path:	The starting point to validate the slot.
258962142be3SGabriel Niebler  *
259062142be3SGabriel Niebler  * Return: 0  if the item is valid
259162142be3SGabriel Niebler  *         1  if not found
259262142be3SGabriel Niebler  *         <0 if error.
259362142be3SGabriel Niebler  */
259462142be3SGabriel Niebler int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
259562142be3SGabriel Niebler 			      struct btrfs_path *path)
259662142be3SGabriel Niebler {
2597524f14bbSFilipe Manana 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
259862142be3SGabriel Niebler 		int ret;
259962142be3SGabriel Niebler 
260062142be3SGabriel Niebler 		ret = btrfs_next_leaf(root, path);
260162142be3SGabriel Niebler 		if (ret)
260262142be3SGabriel Niebler 			return ret;
260362142be3SGabriel Niebler 	}
2604524f14bbSFilipe Manana 
2605524f14bbSFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
260662142be3SGabriel Niebler 	return 0;
260762142be3SGabriel Niebler }
260862142be3SGabriel Niebler 
26090ff40a91SMarcos Paulo de Souza /*
261074123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
261174123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
261274123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
261374123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
261474123bd7SChris Mason  * higher levels
2615aa5d6bedSChris Mason  *
261674123bd7SChris Mason  */
2617b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
26185f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2619be0e5c09SChris Mason {
2620be0e5c09SChris Mason 	int i;
26215f39d397SChris Mason 	struct extent_buffer *t;
26220e82bcfeSDavid Sterba 	int ret;
26235f39d397SChris Mason 
2624234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2625be0e5c09SChris Mason 		int tslot = path->slots[i];
26260e82bcfeSDavid Sterba 
2627eb60ceacSChris Mason 		if (!path->nodes[i])
2628be0e5c09SChris Mason 			break;
26295f39d397SChris Mason 		t = path->nodes[i];
2630f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
263133cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
26320e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
26335f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2634d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2635be0e5c09SChris Mason 		if (tslot != 0)
2636be0e5c09SChris Mason 			break;
2637be0e5c09SChris Mason 	}
2638be0e5c09SChris Mason }
2639be0e5c09SChris Mason 
264074123bd7SChris Mason /*
264131840ae1SZheng Yan  * update item key.
264231840ae1SZheng Yan  *
264331840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
264431840ae1SZheng Yan  * that the new key won't break the order
264531840ae1SZheng Yan  */
2646b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2647b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2648310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
264931840ae1SZheng Yan {
265031840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
265131840ae1SZheng Yan 	struct extent_buffer *eb;
265231840ae1SZheng Yan 	int slot;
265331840ae1SZheng Yan 
265431840ae1SZheng Yan 	eb = path->nodes[0];
265531840ae1SZheng Yan 	slot = path->slots[0];
265631840ae1SZheng Yan 	if (slot > 0) {
265731840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
26587c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
2659eee3b811SQu Wenruo 			btrfs_print_leaf(eb);
26607c15d410SQu Wenruo 			btrfs_crit(fs_info,
26617c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
26627c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
26637c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
26647c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
26657c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
26667c15d410SQu Wenruo 				   new_key->offset);
26677c15d410SQu Wenruo 			BUG();
26687c15d410SQu Wenruo 		}
266931840ae1SZheng Yan 	}
267031840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
267131840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
26727c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
2673eee3b811SQu Wenruo 			btrfs_print_leaf(eb);
26747c15d410SQu Wenruo 			btrfs_crit(fs_info,
26757c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
26767c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
26777c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
26787c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
26797c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
26807c15d410SQu Wenruo 				   new_key->offset);
26817c15d410SQu Wenruo 			BUG();
26827c15d410SQu Wenruo 		}
268331840ae1SZheng Yan 	}
268431840ae1SZheng Yan 
268531840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
268631840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
268731840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
268831840ae1SZheng Yan 	if (slot == 0)
2689b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
269031840ae1SZheng Yan }
269131840ae1SZheng Yan 
269231840ae1SZheng Yan /*
2693d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2694d16c702fSQu Wenruo  *
2695d16c702fSQu Wenruo  * Return true if something is wrong.
2696d16c702fSQu Wenruo  * Return false if everything is fine.
2697d16c702fSQu Wenruo  *
2698d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2699d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2700d16c702fSQu Wenruo  *
2701d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2702d16c702fSQu Wenruo  * --------------------------------------------------------------
2703d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2704d16c702fSQu Wenruo  *
2705d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2706d16c702fSQu Wenruo  * key in leaf @right is 7.
2707d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2708d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2709d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2710d16c702fSQu Wenruo  * key of @right.
2711d16c702fSQu Wenruo  */
2712d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2713d16c702fSQu Wenruo 			       struct extent_buffer *right)
2714d16c702fSQu Wenruo {
2715d16c702fSQu Wenruo 	struct btrfs_key left_last;
2716d16c702fSQu Wenruo 	struct btrfs_key right_first;
2717d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2718d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2719d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2720d16c702fSQu Wenruo 
2721d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2722d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2723d16c702fSQu Wenruo 		return false;
2724d16c702fSQu Wenruo 
2725d16c702fSQu Wenruo 	if (level) {
2726d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2727d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2728d16c702fSQu Wenruo 	} else {
2729d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2730d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2731d16c702fSQu Wenruo 	}
2732d16c702fSQu Wenruo 
273388ad95b0SFilipe Manana 	if (unlikely(btrfs_comp_cpu_keys(&left_last, &right_first) >= 0)) {
2734a2cea677SFilipe Manana 		btrfs_crit(left->fs_info, "left extent buffer:");
2735a2cea677SFilipe Manana 		btrfs_print_tree(left, false);
2736a2cea677SFilipe Manana 		btrfs_crit(left->fs_info, "right extent buffer:");
2737a2cea677SFilipe Manana 		btrfs_print_tree(right, false);
2738d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2739d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2740d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2741d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2742d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2743d16c702fSQu Wenruo 		return true;
2744d16c702fSQu Wenruo 	}
2745d16c702fSQu Wenruo 	return false;
2746d16c702fSQu Wenruo }
2747d16c702fSQu Wenruo 
2748d16c702fSQu Wenruo /*
274974123bd7SChris Mason  * try to push data from one node into the next node left in the
275079f95c82SChris Mason  * tree.
2751aa5d6bedSChris Mason  *
2752aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2753aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
275474123bd7SChris Mason  */
275598ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
27562ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2757971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2758be0e5c09SChris Mason {
2759d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2760be0e5c09SChris Mason 	int push_items = 0;
2761bb803951SChris Mason 	int src_nritems;
2762bb803951SChris Mason 	int dst_nritems;
2763aa5d6bedSChris Mason 	int ret = 0;
2764be0e5c09SChris Mason 
27655f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
27665f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
27670b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
27687bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
27697bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
277054aa1f4dSChris Mason 
2771bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2772971a1f66SChris Mason 		return 1;
2773971a1f66SChris Mason 
2774d397712bSChris Mason 	if (push_items <= 0)
2775be0e5c09SChris Mason 		return 1;
2776be0e5c09SChris Mason 
2777bce4eae9SChris Mason 	if (empty) {
2778971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2779bce4eae9SChris Mason 		if (push_items < src_nritems) {
2780bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2781bce4eae9SChris Mason 			 * we aren't going to empty it
2782bce4eae9SChris Mason 			 */
2783bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2784bce4eae9SChris Mason 				if (push_items <= 8)
2785bce4eae9SChris Mason 					return 1;
2786bce4eae9SChris Mason 				push_items -= 8;
2787bce4eae9SChris Mason 			}
2788bce4eae9SChris Mason 		}
2789bce4eae9SChris Mason 	} else
2790bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
279179f95c82SChris Mason 
2792d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2793d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2794d16c702fSQu Wenruo 		ret = -EUCLEAN;
2795d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2796d16c702fSQu Wenruo 		return ret;
2797d16c702fSQu Wenruo 	}
2798f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
27995de865eeSFilipe David Borba Manana 	if (ret) {
280066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
28015de865eeSFilipe David Borba Manana 		return ret;
28025de865eeSFilipe David Borba Manana 	}
28035f39d397SChris Mason 	copy_extent_buffer(dst, src,
2804e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, dst_nritems),
2805e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, 0),
2806123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
28075f39d397SChris Mason 
2808bb803951SChris Mason 	if (push_items < src_nritems) {
280957911b8bSJan Schmidt 		/*
28105cead542SBoris Burkov 		 * btrfs_tree_mod_log_eb_copy handles logging the move, so we
28115cead542SBoris Burkov 		 * don't need to do an explicit tree mod log operation for it.
281257911b8bSJan Schmidt 		 */
2813e23efd8eSJosef Bacik 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(src, 0),
2814e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(src, push_items),
2815e2fa7227SChris Mason 				      (src_nritems - push_items) *
2816123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2817bb803951SChris Mason 	}
28185f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
28195f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
28205f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
28215f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
282231840ae1SZheng Yan 
2823bb803951SChris Mason 	return ret;
2824be0e5c09SChris Mason }
2825be0e5c09SChris Mason 
282697571fd0SChris Mason /*
282779f95c82SChris Mason  * try to push data from one node into the next node right in the
282879f95c82SChris Mason  * tree.
282979f95c82SChris Mason  *
283079f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
283179f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
283279f95c82SChris Mason  *
283379f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
283479f95c82SChris Mason  */
28355f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
28365f39d397SChris Mason 			      struct extent_buffer *dst,
28375f39d397SChris Mason 			      struct extent_buffer *src)
283879f95c82SChris Mason {
283955d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
284079f95c82SChris Mason 	int push_items = 0;
284179f95c82SChris Mason 	int max_push;
284279f95c82SChris Mason 	int src_nritems;
284379f95c82SChris Mason 	int dst_nritems;
284479f95c82SChris Mason 	int ret = 0;
284579f95c82SChris Mason 
28467bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
28477bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
28487bb86316SChris Mason 
28495f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
28505f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
28510b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2852d397712bSChris Mason 	if (push_items <= 0)
285379f95c82SChris Mason 		return 1;
2854bce4eae9SChris Mason 
2855d397712bSChris Mason 	if (src_nritems < 4)
2856bce4eae9SChris Mason 		return 1;
285779f95c82SChris Mason 
285879f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
285979f95c82SChris Mason 	/* don't try to empty the node */
2860d397712bSChris Mason 	if (max_push >= src_nritems)
286179f95c82SChris Mason 		return 1;
2862252c38f0SYan 
286379f95c82SChris Mason 	if (max_push < push_items)
286479f95c82SChris Mason 		push_items = max_push;
286579f95c82SChris Mason 
2866d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2867d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2868d16c702fSQu Wenruo 		ret = -EUCLEAN;
2869d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2870d16c702fSQu Wenruo 		return ret;
2871d16c702fSQu Wenruo 	}
28725cead542SBoris Burkov 
28735cead542SBoris Burkov 	/*
28745cead542SBoris Burkov 	 * btrfs_tree_mod_log_eb_copy handles logging the move, so we don't
28755cead542SBoris Burkov 	 * need to do an explicit tree mod log operation for it.
28765cead542SBoris Burkov 	 */
2877e23efd8eSJosef Bacik 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(dst, push_items),
2878e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(dst, 0),
28795f39d397SChris Mason 				      (dst_nritems) *
28805f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2881d6025579SChris Mason 
2882f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2883ed874f0dSDavid Sterba 					 push_items);
28845de865eeSFilipe David Borba Manana 	if (ret) {
288566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
28865de865eeSFilipe David Borba Manana 		return ret;
28875de865eeSFilipe David Borba Manana 	}
28885f39d397SChris Mason 	copy_extent_buffer(dst, src,
2889e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, 0),
2890e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, src_nritems - push_items),
2891123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
289279f95c82SChris Mason 
28935f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
28945f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
289579f95c82SChris Mason 
28965f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
28975f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
289831840ae1SZheng Yan 
289979f95c82SChris Mason 	return ret;
290079f95c82SChris Mason }
290179f95c82SChris Mason 
290279f95c82SChris Mason /*
290397571fd0SChris Mason  * helper function to insert a new root level in the tree.
290497571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
290597571fd0SChris Mason  * point to the existing root
2906aa5d6bedSChris Mason  *
2907aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
290897571fd0SChris Mason  */
2909d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
29105f39d397SChris Mason 			   struct btrfs_root *root,
2911fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
291274123bd7SChris Mason {
29130b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
29147bb86316SChris Mason 	u64 lower_gen;
29155f39d397SChris Mason 	struct extent_buffer *lower;
29165f39d397SChris Mason 	struct extent_buffer *c;
2917925baeddSChris Mason 	struct extent_buffer *old;
29185f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2919d9d19a01SDavid Sterba 	int ret;
29205c680ed6SChris Mason 
29215c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
29225c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
29235c680ed6SChris Mason 
29247bb86316SChris Mason 	lower = path->nodes[level-1];
29257bb86316SChris Mason 	if (level == 1)
29267bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
29277bb86316SChris Mason 	else
29287bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
29297bb86316SChris Mason 
293079bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
293179bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2932cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
29335f39d397SChris Mason 	if (IS_ERR(c))
29345f39d397SChris Mason 		return PTR_ERR(c);
2935925baeddSChris Mason 
29360b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2937f0486c68SYan, Zheng 
29385f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
29395f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2940db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
29417bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
294231840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
29437bb86316SChris Mason 
29447bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
29455f39d397SChris Mason 
29465f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2947d5719762SChris Mason 
2948925baeddSChris Mason 	old = root->node;
2949406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2950d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2951240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2952925baeddSChris Mason 
2953925baeddSChris Mason 	/* the super has an extra ref to root->node */
2954925baeddSChris Mason 	free_extent_buffer(old);
2955925baeddSChris Mason 
29560b86a832SChris Mason 	add_root_to_dirty_list(root);
295767439dadSDavid Sterba 	atomic_inc(&c->refs);
29585f39d397SChris Mason 	path->nodes[level] = c;
2959ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
296074123bd7SChris Mason 	path->slots[level] = 0;
296174123bd7SChris Mason 	return 0;
296274123bd7SChris Mason }
29635c680ed6SChris Mason 
29645c680ed6SChris Mason /*
29655c680ed6SChris Mason  * worker function to insert a single pointer in a node.
29665c680ed6SChris Mason  * the node should have enough room for the pointer already
296797571fd0SChris Mason  *
29685c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
29695c680ed6SChris Mason  * blocknr is the block the key points to.
29705c680ed6SChris Mason  */
2971143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
29726ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2973143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2974c3e06965SJan Schmidt 		       int slot, int level)
29755c680ed6SChris Mason {
29765f39d397SChris Mason 	struct extent_buffer *lower;
29775c680ed6SChris Mason 	int nritems;
2978f3ea38daSJan Schmidt 	int ret;
29795c680ed6SChris Mason 
29805c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
298149d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
29825f39d397SChris Mason 	lower = path->nodes[level];
29835f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2984c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
29856ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
298674123bd7SChris Mason 	if (slot != nritems) {
2987bf1d3425SDavid Sterba 		if (level) {
2988f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2989f3a84ccdSFilipe Manana 					slot, nritems - slot);
2990bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2991bf1d3425SDavid Sterba 		}
29925f39d397SChris Mason 		memmove_extent_buffer(lower,
2993e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot + 1),
2994e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot),
2995123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
299674123bd7SChris Mason 	}
2997c3e06965SJan Schmidt 	if (level) {
2998f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
299933cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_ADD);
3000f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
3001f3ea38daSJan Schmidt 	}
30025f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
3003db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
300474493f7aSChris Mason 	WARN_ON(trans->transid == 0);
300574493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
30065f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
30075f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
300874123bd7SChris Mason }
300974123bd7SChris Mason 
301097571fd0SChris Mason /*
301197571fd0SChris Mason  * split the node at the specified level in path in two.
301297571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
301397571fd0SChris Mason  *
301497571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
301597571fd0SChris Mason  * left and right, if either one works, it returns right away.
3016aa5d6bedSChris Mason  *
3017aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
301897571fd0SChris Mason  */
3019e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
3020e02119d5SChris Mason 			       struct btrfs_root *root,
3021e02119d5SChris Mason 			       struct btrfs_path *path, int level)
3022be0e5c09SChris Mason {
30230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
30245f39d397SChris Mason 	struct extent_buffer *c;
30255f39d397SChris Mason 	struct extent_buffer *split;
30265f39d397SChris Mason 	struct btrfs_disk_key disk_key;
3027be0e5c09SChris Mason 	int mid;
30285c680ed6SChris Mason 	int ret;
30297518a238SChris Mason 	u32 c_nritems;
3030be0e5c09SChris Mason 
30315f39d397SChris Mason 	c = path->nodes[level];
30327bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
30335f39d397SChris Mason 	if (c == root->node) {
3034d9abbf1cSJan Schmidt 		/*
303590f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
303690f8d62eSJan Schmidt 		 *
3037fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
303890f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
303990f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
3040f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
3041f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
3042f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
3043d9abbf1cSJan Schmidt 		 */
3044fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
30455c680ed6SChris Mason 		if (ret)
30465c680ed6SChris Mason 			return ret;
3047b3612421SChris Mason 	} else {
3048e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
30495f39d397SChris Mason 		c = path->nodes[level];
30505f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
30510b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
3052e66f709bSChris Mason 			return 0;
305354aa1f4dSChris Mason 		if (ret < 0)
305454aa1f4dSChris Mason 			return ret;
30555c680ed6SChris Mason 	}
3056e66f709bSChris Mason 
30575f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
30585d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
30595d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
30607bb86316SChris Mason 
306179bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
306279bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
306379bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
30645f39d397SChris Mason 	if (IS_ERR(split))
30655f39d397SChris Mason 		return PTR_ERR(split);
306654aa1f4dSChris Mason 
30670b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
3068bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
30695f39d397SChris Mason 
3070f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
30715de865eeSFilipe David Borba Manana 	if (ret) {
3072ede600e4SFilipe Manana 		btrfs_tree_unlock(split);
3073ede600e4SFilipe Manana 		free_extent_buffer(split);
307466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
30755de865eeSFilipe David Borba Manana 		return ret;
30765de865eeSFilipe David Borba Manana 	}
30775f39d397SChris Mason 	copy_extent_buffer(split, c,
3078e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(split, 0),
3079e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(c, mid),
3080123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
30815f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
30825f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
3083aa5d6bedSChris Mason 
30845f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
30855f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
30865f39d397SChris Mason 
30876ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
3088c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
3089aa5d6bedSChris Mason 
30905de08d7dSChris Mason 	if (path->slots[level] >= mid) {
30915c680ed6SChris Mason 		path->slots[level] -= mid;
3092925baeddSChris Mason 		btrfs_tree_unlock(c);
30935f39d397SChris Mason 		free_extent_buffer(c);
30945f39d397SChris Mason 		path->nodes[level] = split;
30955c680ed6SChris Mason 		path->slots[level + 1] += 1;
3096eb60ceacSChris Mason 	} else {
3097925baeddSChris Mason 		btrfs_tree_unlock(split);
30985f39d397SChris Mason 		free_extent_buffer(split);
3099be0e5c09SChris Mason 	}
3100d5286a92SNikolay Borisov 	return 0;
3101be0e5c09SChris Mason }
3102be0e5c09SChris Mason 
310374123bd7SChris Mason /*
310474123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
310574123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
310674123bd7SChris Mason  * space used both by the item structs and the item data
310774123bd7SChris Mason  */
31086c75a589SQu Wenruo static int leaf_space_used(const struct extent_buffer *l, int start, int nr)
3109be0e5c09SChris Mason {
3110be0e5c09SChris Mason 	int data_len;
31115f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
3112d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
3113be0e5c09SChris Mason 
3114be0e5c09SChris Mason 	if (!nr)
3115be0e5c09SChris Mason 		return 0;
31163212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
31173212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
31180783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
3119d4dbff95SChris Mason 	WARN_ON(data_len < 0);
3120be0e5c09SChris Mason 	return data_len;
3121be0e5c09SChris Mason }
3122be0e5c09SChris Mason 
312374123bd7SChris Mason /*
3124d4dbff95SChris Mason  * The space between the end of the leaf items and
3125d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
3126d4dbff95SChris Mason  * the leaf has left for both items and data
3127d4dbff95SChris Mason  */
31286c75a589SQu Wenruo int btrfs_leaf_free_space(const struct extent_buffer *leaf)
3129d4dbff95SChris Mason {
3130e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
31315f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
31325f39d397SChris Mason 	int ret;
31330b246afaSJeff Mahoney 
31340b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
31355f39d397SChris Mason 	if (ret < 0) {
31360b246afaSJeff Mahoney 		btrfs_crit(fs_info,
3137efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3138da17066cSJeff Mahoney 			   ret,
31390b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
31405f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
31415f39d397SChris Mason 	}
31425f39d397SChris Mason 	return ret;
3143d4dbff95SChris Mason }
3144d4dbff95SChris Mason 
314599d8f83cSChris Mason /*
314699d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
314799d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
314899d8f83cSChris Mason  */
3149ed25dab3SJosef Bacik static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
3150ed25dab3SJosef Bacik 				      struct btrfs_path *path,
315144871b1bSChris Mason 				      int data_size, int empty,
315244871b1bSChris Mason 				      struct extent_buffer *right,
315399d8f83cSChris Mason 				      int free_space, u32 left_nritems,
315499d8f83cSChris Mason 				      u32 min_slot)
315500ec4c51SChris Mason {
3156f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
31575f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
315844871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
3159cfed81a0SChris Mason 	struct btrfs_map_token token;
31605f39d397SChris Mason 	struct btrfs_disk_key disk_key;
316100ec4c51SChris Mason 	int slot;
316234a38218SChris Mason 	u32 i;
316300ec4c51SChris Mason 	int push_space = 0;
316400ec4c51SChris Mason 	int push_items = 0;
316534a38218SChris Mason 	u32 nr;
31667518a238SChris Mason 	u32 right_nritems;
31675f39d397SChris Mason 	u32 data_end;
3168db94535dSChris Mason 	u32 this_item_size;
316900ec4c51SChris Mason 
317034a38218SChris Mason 	if (empty)
317134a38218SChris Mason 		nr = 0;
317234a38218SChris Mason 	else
317399d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
317434a38218SChris Mason 
317531840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
317687b29b20SYan Zheng 		push_space += data_size;
317731840ae1SZheng Yan 
317844871b1bSChris Mason 	slot = path->slots[1];
317934a38218SChris Mason 	i = left_nritems - 1;
318034a38218SChris Mason 	while (i >= nr) {
318131840ae1SZheng Yan 		if (!empty && push_items > 0) {
318231840ae1SZheng Yan 			if (path->slots[0] > i)
318331840ae1SZheng Yan 				break;
318431840ae1SZheng Yan 			if (path->slots[0] == i) {
3185e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
3186e902baacSDavid Sterba 
318731840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
318831840ae1SZheng Yan 					break;
318931840ae1SZheng Yan 			}
319031840ae1SZheng Yan 		}
319131840ae1SZheng Yan 
319200ec4c51SChris Mason 		if (path->slots[0] == i)
319387b29b20SYan Zheng 			push_space += data_size;
3194db94535dSChris Mason 
31953212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
319674794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
319774794207SJosef Bacik 		    push_space > free_space)
319800ec4c51SChris Mason 			break;
319931840ae1SZheng Yan 
320000ec4c51SChris Mason 		push_items++;
320174794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
320234a38218SChris Mason 		if (i == 0)
320334a38218SChris Mason 			break;
320434a38218SChris Mason 		i--;
3205db94535dSChris Mason 	}
32065f39d397SChris Mason 
3207925baeddSChris Mason 	if (push_items == 0)
3208925baeddSChris Mason 		goto out_unlock;
32095f39d397SChris Mason 
32106c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
32115f39d397SChris Mason 
321200ec4c51SChris Mason 	/* push left to right */
32135f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
321434a38218SChris Mason 
3215dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
32168f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
32175f39d397SChris Mason 
321800ec4c51SChris Mason 	/* make room in the right data area */
32198f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
3220637e3b48SJosef Bacik 	memmove_leaf_data(right, data_end - push_space, data_end,
32210b246afaSJeff Mahoney 			  BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
32225f39d397SChris Mason 
322300ec4c51SChris Mason 	/* copy from the left data area */
3224637e3b48SJosef Bacik 	copy_leaf_data(right, left, BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3225637e3b48SJosef Bacik 		       leaf_data_end(left), push_space);
32265f39d397SChris Mason 
3227637e3b48SJosef Bacik 	memmove_leaf_items(right, push_items, 0, right_nritems);
32285f39d397SChris Mason 
322900ec4c51SChris Mason 	/* copy the items from left to right */
3230637e3b48SJosef Bacik 	copy_leaf_items(right, left, 0, left_nritems - push_items, push_items);
323100ec4c51SChris Mason 
323200ec4c51SChris Mason 	/* update the item pointers */
3233c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
32347518a238SChris Mason 	right_nritems += push_items;
32355f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
32360b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
32377518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
32383212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
32393212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3240db94535dSChris Mason 	}
3241db94535dSChris Mason 
32427518a238SChris Mason 	left_nritems -= push_items;
32435f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
324400ec4c51SChris Mason 
324534a38218SChris Mason 	if (left_nritems)
32465f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3247f0486c68SYan, Zheng 	else
3248190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, left);
3249f0486c68SYan, Zheng 
32505f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3251a429e513SChris Mason 
32525f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
32535f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3254d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
325502217ed2SChris Mason 
325600ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
32577518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
32587518a238SChris Mason 		path->slots[0] -= left_nritems;
3259925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3260190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, path->nodes[0]);
3261925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32625f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32635f39d397SChris Mason 		path->nodes[0] = right;
326400ec4c51SChris Mason 		path->slots[1] += 1;
326500ec4c51SChris Mason 	} else {
3266925baeddSChris Mason 		btrfs_tree_unlock(right);
32675f39d397SChris Mason 		free_extent_buffer(right);
326800ec4c51SChris Mason 	}
326900ec4c51SChris Mason 	return 0;
3270925baeddSChris Mason 
3271925baeddSChris Mason out_unlock:
3272925baeddSChris Mason 	btrfs_tree_unlock(right);
3273925baeddSChris Mason 	free_extent_buffer(right);
3274925baeddSChris Mason 	return 1;
327500ec4c51SChris Mason }
3276925baeddSChris Mason 
327700ec4c51SChris Mason /*
327844871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
327974123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
328044871b1bSChris Mason  *
328144871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
328244871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
328399d8f83cSChris Mason  *
328499d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
328599d8f83cSChris Mason  * push any slot lower than min_slot
328674123bd7SChris Mason  */
328744871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
328899d8f83cSChris Mason 			   *root, struct btrfs_path *path,
328999d8f83cSChris Mason 			   int min_data_size, int data_size,
329099d8f83cSChris Mason 			   int empty, u32 min_slot)
3291be0e5c09SChris Mason {
329244871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
329344871b1bSChris Mason 	struct extent_buffer *right;
329444871b1bSChris Mason 	struct extent_buffer *upper;
329544871b1bSChris Mason 	int slot;
329644871b1bSChris Mason 	int free_space;
329744871b1bSChris Mason 	u32 left_nritems;
329844871b1bSChris Mason 	int ret;
329944871b1bSChris Mason 
330044871b1bSChris Mason 	if (!path->nodes[1])
330144871b1bSChris Mason 		return 1;
330244871b1bSChris Mason 
330344871b1bSChris Mason 	slot = path->slots[1];
330444871b1bSChris Mason 	upper = path->nodes[1];
330544871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
330644871b1bSChris Mason 		return 1;
330744871b1bSChris Mason 
330849d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
330944871b1bSChris Mason 
33104b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3311fb770ae4SLiu Bo 	if (IS_ERR(right))
33129cf14029SJosef Bacik 		return PTR_ERR(right);
331391ca338dSTsutomu Itoh 
3314bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
331544871b1bSChris Mason 
3316e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
331744871b1bSChris Mason 	if (free_space < data_size)
331844871b1bSChris Mason 		goto out_unlock;
331944871b1bSChris Mason 
332044871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3321bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
332244871b1bSChris Mason 	if (ret)
332344871b1bSChris Mason 		goto out_unlock;
332444871b1bSChris Mason 
332544871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
332644871b1bSChris Mason 	if (left_nritems == 0)
332744871b1bSChris Mason 		goto out_unlock;
332844871b1bSChris Mason 
3329d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3330d16c702fSQu Wenruo 		ret = -EUCLEAN;
33319ae5afd0SFilipe Manana 		btrfs_abort_transaction(trans, ret);
3332d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3333d16c702fSQu Wenruo 		free_extent_buffer(right);
3334d16c702fSQu Wenruo 		return ret;
3335d16c702fSQu Wenruo 	}
33362ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
33372ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
33382ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
33392ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
334052042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
33412ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
33422ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
33432ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
33442ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
33452ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
33462ef1fed2SFilipe David Borba Manana 		return 0;
33472ef1fed2SFilipe David Borba Manana 	}
33482ef1fed2SFilipe David Borba Manana 
3349ed25dab3SJosef Bacik 	return __push_leaf_right(trans, path, min_data_size, empty, right,
3350ed25dab3SJosef Bacik 				 free_space, left_nritems, min_slot);
335144871b1bSChris Mason out_unlock:
335244871b1bSChris Mason 	btrfs_tree_unlock(right);
335344871b1bSChris Mason 	free_extent_buffer(right);
335444871b1bSChris Mason 	return 1;
335544871b1bSChris Mason }
335644871b1bSChris Mason 
335744871b1bSChris Mason /*
335844871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
335944871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
336099d8f83cSChris Mason  *
336199d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
336299d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
336399d8f83cSChris Mason  * items
336444871b1bSChris Mason  */
3365ed25dab3SJosef Bacik static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
3366ed25dab3SJosef Bacik 				     struct btrfs_path *path, int data_size,
336744871b1bSChris Mason 				     int empty, struct extent_buffer *left,
336899d8f83cSChris Mason 				     int free_space, u32 right_nritems,
336999d8f83cSChris Mason 				     u32 max_slot)
337044871b1bSChris Mason {
33718087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
33725f39d397SChris Mason 	struct btrfs_disk_key disk_key;
33735f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3374be0e5c09SChris Mason 	int i;
3375be0e5c09SChris Mason 	int push_space = 0;
3376be0e5c09SChris Mason 	int push_items = 0;
33777518a238SChris Mason 	u32 old_left_nritems;
337834a38218SChris Mason 	u32 nr;
3379aa5d6bedSChris Mason 	int ret = 0;
3380db94535dSChris Mason 	u32 this_item_size;
3381db94535dSChris Mason 	u32 old_left_item_size;
3382cfed81a0SChris Mason 	struct btrfs_map_token token;
3383cfed81a0SChris Mason 
338434a38218SChris Mason 	if (empty)
338599d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
338634a38218SChris Mason 	else
338799d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
338834a38218SChris Mason 
338934a38218SChris Mason 	for (i = 0; i < nr; i++) {
339031840ae1SZheng Yan 		if (!empty && push_items > 0) {
339131840ae1SZheng Yan 			if (path->slots[0] < i)
339231840ae1SZheng Yan 				break;
339331840ae1SZheng Yan 			if (path->slots[0] == i) {
3394e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3395e902baacSDavid Sterba 
339631840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
339731840ae1SZheng Yan 					break;
339831840ae1SZheng Yan 			}
339931840ae1SZheng Yan 		}
340031840ae1SZheng Yan 
3401be0e5c09SChris Mason 		if (path->slots[0] == i)
340287b29b20SYan Zheng 			push_space += data_size;
3403db94535dSChris Mason 
34043212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
340574794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
340674794207SJosef Bacik 		    free_space)
3407be0e5c09SChris Mason 			break;
3408db94535dSChris Mason 
3409be0e5c09SChris Mason 		push_items++;
341074794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3411be0e5c09SChris Mason 	}
3412db94535dSChris Mason 
3413be0e5c09SChris Mason 	if (push_items == 0) {
3414925baeddSChris Mason 		ret = 1;
3415925baeddSChris Mason 		goto out;
3416be0e5c09SChris Mason 	}
3417fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
34185f39d397SChris Mason 
3419be0e5c09SChris Mason 	/* push data from right to left */
3420637e3b48SJosef Bacik 	copy_leaf_items(left, right, btrfs_header_nritems(left), 0, push_items);
34215f39d397SChris Mason 
34220b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
34233212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
34245f39d397SChris Mason 
3425637e3b48SJosef Bacik 	copy_leaf_data(left, right, leaf_data_end(left) - push_space,
3426637e3b48SJosef Bacik 		       btrfs_item_offset(right, push_items - 1), push_space);
34275f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
342887b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3429eb60ceacSChris Mason 
3430c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
34313212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3432be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
34335f39d397SChris Mason 		u32 ioff;
3434db94535dSChris Mason 
34353212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
34363212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3437cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3438be0e5c09SChris Mason 	}
34395f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3440be0e5c09SChris Mason 
3441be0e5c09SChris Mason 	/* fixup right node */
344231b1a2bdSJulia Lawall 	if (push_items > right_nritems)
344331b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3444d397712bSChris Mason 		       right_nritems);
344534a38218SChris Mason 
344634a38218SChris Mason 	if (push_items < right_nritems) {
34473212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
34488f881e8cSDavid Sterba 						  leaf_data_end(right);
3449637e3b48SJosef Bacik 		memmove_leaf_data(right,
34500b246afaSJeff Mahoney 				  BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
34518f881e8cSDavid Sterba 				  leaf_data_end(right), push_space);
34525f39d397SChris Mason 
3453637e3b48SJosef Bacik 		memmove_leaf_items(right, 0, push_items,
3454637e3b48SJosef Bacik 				   btrfs_header_nritems(right) - push_items);
345534a38218SChris Mason 	}
3456c82f823cSDavid Sterba 
3457c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3458eef1c494SYan 	right_nritems -= push_items;
3459eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
34600b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
34615f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
34623212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
34633212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3464db94535dSChris Mason 	}
3465eb60ceacSChris Mason 
34665f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
346734a38218SChris Mason 	if (right_nritems)
34685f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3469f0486c68SYan, Zheng 	else
3470190a8339SJosef Bacik 		btrfs_clear_buffer_dirty(trans, right);
3471098f59c2SChris Mason 
34725f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3473b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3474be0e5c09SChris Mason 
3475be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3476be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3477be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3478925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
34795f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
34805f39d397SChris Mason 		path->nodes[0] = left;
3481be0e5c09SChris Mason 		path->slots[1] -= 1;
3482be0e5c09SChris Mason 	} else {
3483925baeddSChris Mason 		btrfs_tree_unlock(left);
34845f39d397SChris Mason 		free_extent_buffer(left);
3485be0e5c09SChris Mason 		path->slots[0] -= push_items;
3486be0e5c09SChris Mason 	}
3487eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3488aa5d6bedSChris Mason 	return ret;
3489925baeddSChris Mason out:
3490925baeddSChris Mason 	btrfs_tree_unlock(left);
3491925baeddSChris Mason 	free_extent_buffer(left);
3492925baeddSChris Mason 	return ret;
3493be0e5c09SChris Mason }
3494be0e5c09SChris Mason 
349574123bd7SChris Mason /*
349644871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
349744871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
349899d8f83cSChris Mason  *
349999d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
350099d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
350199d8f83cSChris Mason  * items
350244871b1bSChris Mason  */
350344871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
350499d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
350599d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
350644871b1bSChris Mason {
350744871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
350844871b1bSChris Mason 	struct extent_buffer *left;
350944871b1bSChris Mason 	int slot;
351044871b1bSChris Mason 	int free_space;
351144871b1bSChris Mason 	u32 right_nritems;
351244871b1bSChris Mason 	int ret = 0;
351344871b1bSChris Mason 
351444871b1bSChris Mason 	slot = path->slots[1];
351544871b1bSChris Mason 	if (slot == 0)
351644871b1bSChris Mason 		return 1;
351744871b1bSChris Mason 	if (!path->nodes[1])
351844871b1bSChris Mason 		return 1;
351944871b1bSChris Mason 
352044871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
352144871b1bSChris Mason 	if (right_nritems == 0)
352244871b1bSChris Mason 		return 1;
352344871b1bSChris Mason 
352449d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
352544871b1bSChris Mason 
35264b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3527fb770ae4SLiu Bo 	if (IS_ERR(left))
35289cf14029SJosef Bacik 		return PTR_ERR(left);
352991ca338dSTsutomu Itoh 
3530bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
353144871b1bSChris Mason 
3532e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
353344871b1bSChris Mason 	if (free_space < data_size) {
353444871b1bSChris Mason 		ret = 1;
353544871b1bSChris Mason 		goto out;
353644871b1bSChris Mason 	}
353744871b1bSChris Mason 
353844871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
35399631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3540bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
354144871b1bSChris Mason 	if (ret) {
354244871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
354379787eaaSJeff Mahoney 		if (ret == -ENOSPC)
354444871b1bSChris Mason 			ret = 1;
354544871b1bSChris Mason 		goto out;
354644871b1bSChris Mason 	}
354744871b1bSChris Mason 
3548d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3549d16c702fSQu Wenruo 		ret = -EUCLEAN;
35509ae5afd0SFilipe Manana 		btrfs_abort_transaction(trans, ret);
3551d16c702fSQu Wenruo 		goto out;
3552d16c702fSQu Wenruo 	}
3553ed25dab3SJosef Bacik 	return __push_leaf_left(trans, path, min_data_size, empty, left,
3554ed25dab3SJosef Bacik 				free_space, right_nritems, max_slot);
355544871b1bSChris Mason out:
355644871b1bSChris Mason 	btrfs_tree_unlock(left);
355744871b1bSChris Mason 	free_extent_buffer(left);
355844871b1bSChris Mason 	return ret;
355944871b1bSChris Mason }
356044871b1bSChris Mason 
356144871b1bSChris Mason /*
356274123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
356374123bd7SChris Mason  * available for the resulting leaf level of the path.
356474123bd7SChris Mason  */
3565143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
356644871b1bSChris Mason 				    struct btrfs_path *path,
356744871b1bSChris Mason 				    struct extent_buffer *l,
356844871b1bSChris Mason 				    struct extent_buffer *right,
356944871b1bSChris Mason 				    int slot, int mid, int nritems)
3570be0e5c09SChris Mason {
357194f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3572be0e5c09SChris Mason 	int data_copy_size;
3573be0e5c09SChris Mason 	int rt_data_off;
3574be0e5c09SChris Mason 	int i;
3575d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3576cfed81a0SChris Mason 	struct btrfs_map_token token;
3577cfed81a0SChris Mason 
35785f39d397SChris Mason 	nritems = nritems - mid;
35795f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3580dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
35815f39d397SChris Mason 
3582637e3b48SJosef Bacik 	copy_leaf_items(right, l, 0, mid, nritems);
35835f39d397SChris Mason 
3584637e3b48SJosef Bacik 	copy_leaf_data(right, l, BTRFS_LEAF_DATA_SIZE(fs_info) - data_copy_size,
35858f881e8cSDavid Sterba 		       leaf_data_end(l), data_copy_size);
358674123bd7SChris Mason 
3587dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
35885f39d397SChris Mason 
3589c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
35905f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3591db94535dSChris Mason 		u32 ioff;
3592db94535dSChris Mason 
35933212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
35943212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
35950783fcfcSChris Mason 	}
359674123bd7SChris Mason 
35975f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
35985f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
35996ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
36005f39d397SChris Mason 
36015f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
36025f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3603eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
36045f39d397SChris Mason 
3605be0e5c09SChris Mason 	if (mid <= slot) {
3606925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
36075f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
36085f39d397SChris Mason 		path->nodes[0] = right;
3609be0e5c09SChris Mason 		path->slots[0] -= mid;
3610be0e5c09SChris Mason 		path->slots[1] += 1;
3611925baeddSChris Mason 	} else {
3612925baeddSChris Mason 		btrfs_tree_unlock(right);
36135f39d397SChris Mason 		free_extent_buffer(right);
3614925baeddSChris Mason 	}
36155f39d397SChris Mason 
3616eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
361744871b1bSChris Mason }
361844871b1bSChris Mason 
361944871b1bSChris Mason /*
362099d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
362199d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
362299d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
362399d8f83cSChris Mason  *          A                 B                 C
362499d8f83cSChris Mason  *
362599d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
362699d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
362799d8f83cSChris Mason  * completely.
362899d8f83cSChris Mason  */
362999d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
363099d8f83cSChris Mason 					  struct btrfs_root *root,
363199d8f83cSChris Mason 					  struct btrfs_path *path,
363299d8f83cSChris Mason 					  int data_size)
363399d8f83cSChris Mason {
363499d8f83cSChris Mason 	int ret;
363599d8f83cSChris Mason 	int progress = 0;
363699d8f83cSChris Mason 	int slot;
363799d8f83cSChris Mason 	u32 nritems;
36385a4267caSFilipe David Borba Manana 	int space_needed = data_size;
363999d8f83cSChris Mason 
364099d8f83cSChris Mason 	slot = path->slots[0];
36415a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3642e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
364399d8f83cSChris Mason 
364499d8f83cSChris Mason 	/*
364599d8f83cSChris Mason 	 * try to push all the items after our slot into the
364699d8f83cSChris Mason 	 * right leaf
364799d8f83cSChris Mason 	 */
36485a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
364999d8f83cSChris Mason 	if (ret < 0)
365099d8f83cSChris Mason 		return ret;
365199d8f83cSChris Mason 
365299d8f83cSChris Mason 	if (ret == 0)
365399d8f83cSChris Mason 		progress++;
365499d8f83cSChris Mason 
365599d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
365699d8f83cSChris Mason 	/*
365799d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
365899d8f83cSChris Mason 	 * we've done so we're done
365999d8f83cSChris Mason 	 */
366099d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
366199d8f83cSChris Mason 		return 0;
366299d8f83cSChris Mason 
3663e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
366499d8f83cSChris Mason 		return 0;
366599d8f83cSChris Mason 
366699d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
366799d8f83cSChris Mason 	slot = path->slots[0];
3668263d3995SFilipe Manana 	space_needed = data_size;
3669263d3995SFilipe Manana 	if (slot > 0)
3670e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
36715a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
367299d8f83cSChris Mason 	if (ret < 0)
367399d8f83cSChris Mason 		return ret;
367499d8f83cSChris Mason 
367599d8f83cSChris Mason 	if (ret == 0)
367699d8f83cSChris Mason 		progress++;
367799d8f83cSChris Mason 
367899d8f83cSChris Mason 	if (progress)
367999d8f83cSChris Mason 		return 0;
368099d8f83cSChris Mason 	return 1;
368199d8f83cSChris Mason }
368299d8f83cSChris Mason 
368399d8f83cSChris Mason /*
368444871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
368544871b1bSChris Mason  * available for the resulting leaf level of the path.
368644871b1bSChris Mason  *
368744871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
368844871b1bSChris Mason  */
368944871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
369044871b1bSChris Mason 			       struct btrfs_root *root,
3691310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
369244871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
369344871b1bSChris Mason 			       int extend)
369444871b1bSChris Mason {
36955d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
369644871b1bSChris Mason 	struct extent_buffer *l;
369744871b1bSChris Mason 	u32 nritems;
369844871b1bSChris Mason 	int mid;
369944871b1bSChris Mason 	int slot;
370044871b1bSChris Mason 	struct extent_buffer *right;
3701b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
370244871b1bSChris Mason 	int ret = 0;
370344871b1bSChris Mason 	int wret;
37045d4f98a2SYan Zheng 	int split;
370544871b1bSChris Mason 	int num_doubles = 0;
370699d8f83cSChris Mason 	int tried_avoid_double = 0;
370744871b1bSChris Mason 
3708a5719521SYan, Zheng 	l = path->nodes[0];
3709a5719521SYan, Zheng 	slot = path->slots[0];
37103212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
37110b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3712a5719521SYan, Zheng 		return -EOVERFLOW;
3713a5719521SYan, Zheng 
371444871b1bSChris Mason 	/* first try to make some room by pushing left and right */
371533157e05SLiu Bo 	if (data_size && path->nodes[1]) {
37165a4267caSFilipe David Borba Manana 		int space_needed = data_size;
37175a4267caSFilipe David Borba Manana 
37185a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3719e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
37205a4267caSFilipe David Borba Manana 
37215a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
37225a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
372344871b1bSChris Mason 		if (wret < 0)
372444871b1bSChris Mason 			return wret;
372544871b1bSChris Mason 		if (wret) {
3726263d3995SFilipe Manana 			space_needed = data_size;
3727263d3995SFilipe Manana 			if (slot > 0)
3728e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
37295a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
37305a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
373144871b1bSChris Mason 			if (wret < 0)
373244871b1bSChris Mason 				return wret;
373344871b1bSChris Mason 		}
373444871b1bSChris Mason 		l = path->nodes[0];
373544871b1bSChris Mason 
373644871b1bSChris Mason 		/* did the pushes work? */
3737e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
373844871b1bSChris Mason 			return 0;
373944871b1bSChris Mason 	}
374044871b1bSChris Mason 
374144871b1bSChris Mason 	if (!path->nodes[1]) {
3742fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
374344871b1bSChris Mason 		if (ret)
374444871b1bSChris Mason 			return ret;
374544871b1bSChris Mason 	}
374644871b1bSChris Mason again:
37475d4f98a2SYan Zheng 	split = 1;
374844871b1bSChris Mason 	l = path->nodes[0];
374944871b1bSChris Mason 	slot = path->slots[0];
375044871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
375144871b1bSChris Mason 	mid = (nritems + 1) / 2;
375244871b1bSChris Mason 
37535d4f98a2SYan Zheng 	if (mid <= slot) {
37545d4f98a2SYan Zheng 		if (nritems == 1 ||
37555d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
37560b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
37575d4f98a2SYan Zheng 			if (slot >= nritems) {
37585d4f98a2SYan Zheng 				split = 0;
37595d4f98a2SYan Zheng 			} else {
37605d4f98a2SYan Zheng 				mid = slot;
37615d4f98a2SYan Zheng 				if (mid != nritems &&
37625d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
37630b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
376499d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
376599d8f83cSChris Mason 						goto push_for_double;
37665d4f98a2SYan Zheng 					split = 2;
37675d4f98a2SYan Zheng 				}
37685d4f98a2SYan Zheng 			}
37695d4f98a2SYan Zheng 		}
37705d4f98a2SYan Zheng 	} else {
37715d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
37720b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
37735d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
37745d4f98a2SYan Zheng 				split = 0;
37755d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
37765d4f98a2SYan Zheng 				mid = 1;
37775d4f98a2SYan Zheng 			} else {
37785d4f98a2SYan Zheng 				mid = slot;
37795d4f98a2SYan Zheng 				if (mid != nritems &&
37805d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
37810b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
378299d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
378399d8f83cSChris Mason 						goto push_for_double;
37845d4f98a2SYan Zheng 					split = 2;
37855d4f98a2SYan Zheng 				}
37865d4f98a2SYan Zheng 			}
37875d4f98a2SYan Zheng 		}
37885d4f98a2SYan Zheng 	}
37895d4f98a2SYan Zheng 
37905d4f98a2SYan Zheng 	if (split == 0)
37915d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
37925d4f98a2SYan Zheng 	else
37935d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
37945d4f98a2SYan Zheng 
3795ca9d473aSJosef Bacik 	/*
3796ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3797ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3798ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3799ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3800ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3801ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3802ca9d473aSJosef Bacik 	 */
380379bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
380479bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
380579bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3806ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3807f0486c68SYan, Zheng 	if (IS_ERR(right))
380844871b1bSChris Mason 		return PTR_ERR(right);
3809f0486c68SYan, Zheng 
38100b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
381144871b1bSChris Mason 
38125d4f98a2SYan Zheng 	if (split == 0) {
381344871b1bSChris Mason 		if (mid <= slot) {
381444871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
38156ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
38162ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
381744871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
381844871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
381944871b1bSChris Mason 			path->nodes[0] = right;
382044871b1bSChris Mason 			path->slots[0] = 0;
382144871b1bSChris Mason 			path->slots[1] += 1;
382244871b1bSChris Mason 		} else {
382344871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
38246ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
38252ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
382644871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
382744871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
382844871b1bSChris Mason 			path->nodes[0] = right;
382944871b1bSChris Mason 			path->slots[0] = 0;
3830143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3831b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
38325d4f98a2SYan Zheng 		}
3833196e0249SLiu Bo 		/*
3834196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3835196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3836196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3837196e0249SLiu Bo 		 */
383844871b1bSChris Mason 		return ret;
383944871b1bSChris Mason 	}
384044871b1bSChris Mason 
384194f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
384244871b1bSChris Mason 
38435d4f98a2SYan Zheng 	if (split == 2) {
3844cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3845cc0c5538SChris Mason 		num_doubles++;
3846cc0c5538SChris Mason 		goto again;
38473326d1b0SChris Mason 	}
384844871b1bSChris Mason 
3849143bede5SJeff Mahoney 	return 0;
385099d8f83cSChris Mason 
385199d8f83cSChris Mason push_for_double:
385299d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
385399d8f83cSChris Mason 	tried_avoid_double = 1;
3854e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
385599d8f83cSChris Mason 		return 0;
385699d8f83cSChris Mason 	goto again;
3857be0e5c09SChris Mason }
3858be0e5c09SChris Mason 
3859ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3860ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3861ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3862ad48fd75SYan, Zheng {
3863ad48fd75SYan, Zheng 	struct btrfs_key key;
3864ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3865ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3866ad48fd75SYan, Zheng 	u64 extent_len = 0;
3867ad48fd75SYan, Zheng 	u32 item_size;
3868ad48fd75SYan, Zheng 	int ret;
3869ad48fd75SYan, Zheng 
3870ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3871ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3872ad48fd75SYan, Zheng 
3873ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3874ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3875ad48fd75SYan, Zheng 
3876e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3877ad48fd75SYan, Zheng 		return 0;
3878ad48fd75SYan, Zheng 
38793212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3880ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3881ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3882ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3883ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3884ad48fd75SYan, Zheng 	}
3885b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3886ad48fd75SYan, Zheng 
3887ad48fd75SYan, Zheng 	path->keep_locks = 1;
3888ad48fd75SYan, Zheng 	path->search_for_split = 1;
3889ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3890ad48fd75SYan, Zheng 	path->search_for_split = 0;
3891a8df6fe6SFilipe Manana 	if (ret > 0)
3892a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3893ad48fd75SYan, Zheng 	if (ret < 0)
3894ad48fd75SYan, Zheng 		goto err;
3895ad48fd75SYan, Zheng 
3896ad48fd75SYan, Zheng 	ret = -EAGAIN;
3897ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3898a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
38993212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3900ad48fd75SYan, Zheng 		goto err;
3901ad48fd75SYan, Zheng 
3902109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3903e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3904109f6aefSChris Mason 		goto err;
3905109f6aefSChris Mason 
3906ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3907ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3908ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3909ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3910ad48fd75SYan, Zheng 			goto err;
3911ad48fd75SYan, Zheng 	}
3912ad48fd75SYan, Zheng 
3913ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3914f0486c68SYan, Zheng 	if (ret)
3915f0486c68SYan, Zheng 		goto err;
3916ad48fd75SYan, Zheng 
3917ad48fd75SYan, Zheng 	path->keep_locks = 0;
3918ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3919ad48fd75SYan, Zheng 	return 0;
3920ad48fd75SYan, Zheng err:
3921ad48fd75SYan, Zheng 	path->keep_locks = 0;
3922ad48fd75SYan, Zheng 	return ret;
3923ad48fd75SYan, Zheng }
3924ad48fd75SYan, Zheng 
392525263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3926310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3927459931ecSChris Mason 			       unsigned long split_offset)
3928459931ecSChris Mason {
3929459931ecSChris Mason 	struct extent_buffer *leaf;
3930c91666b1SJosef Bacik 	int orig_slot, slot;
3931ad48fd75SYan, Zheng 	char *buf;
3932459931ecSChris Mason 	u32 nritems;
3933ad48fd75SYan, Zheng 	u32 item_size;
3934459931ecSChris Mason 	u32 orig_offset;
3935459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3936459931ecSChris Mason 
3937459931ecSChris Mason 	leaf = path->nodes[0];
3938e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3939b9473439SChris Mason 
3940c91666b1SJosef Bacik 	orig_slot = path->slots[0];
39413212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
39423212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3943459931ecSChris Mason 
3944459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3945ad48fd75SYan, Zheng 	if (!buf)
3946ad48fd75SYan, Zheng 		return -ENOMEM;
3947ad48fd75SYan, Zheng 
3948459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3949459931ecSChris Mason 			    path->slots[0]), item_size);
3950ad48fd75SYan, Zheng 
3951459931ecSChris Mason 	slot = path->slots[0] + 1;
3952459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3953459931ecSChris Mason 	if (slot != nritems) {
3954459931ecSChris Mason 		/* shift the items */
3955637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot + 1, slot, nritems - slot);
3956459931ecSChris Mason 	}
3957459931ecSChris Mason 
3958459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3959459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3960459931ecSChris Mason 
39613212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
39623212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3963459931ecSChris Mason 
39643212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
3965459931ecSChris Mason 				 orig_offset + item_size - split_offset);
39663212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3967459931ecSChris Mason 
3968459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3969459931ecSChris Mason 
3970459931ecSChris Mason 	/* write the data for the start of the original item */
3971459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3972459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3973459931ecSChris Mason 			    split_offset);
3974459931ecSChris Mason 
3975459931ecSChris Mason 	/* write the data for the new item */
3976459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3977459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3978459931ecSChris Mason 			    item_size - split_offset);
3979459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3980459931ecSChris Mason 
3981e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3982459931ecSChris Mason 	kfree(buf);
3983ad48fd75SYan, Zheng 	return 0;
3984ad48fd75SYan, Zheng }
3985ad48fd75SYan, Zheng 
3986ad48fd75SYan, Zheng /*
3987ad48fd75SYan, Zheng  * This function splits a single item into two items,
3988ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3989ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3990ad48fd75SYan, Zheng  *
3991ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3992ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3993ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3994ad48fd75SYan, Zheng  *
3995ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3996ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3997ad48fd75SYan, Zheng  *
3998ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3999ad48fd75SYan, Zheng  * leaf the entire time.
4000ad48fd75SYan, Zheng  */
4001ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
4002ad48fd75SYan, Zheng 		     struct btrfs_root *root,
4003ad48fd75SYan, Zheng 		     struct btrfs_path *path,
4004310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
4005ad48fd75SYan, Zheng 		     unsigned long split_offset)
4006ad48fd75SYan, Zheng {
4007ad48fd75SYan, Zheng 	int ret;
4008ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
4009ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
4010ad48fd75SYan, Zheng 	if (ret)
4011459931ecSChris Mason 		return ret;
4012ad48fd75SYan, Zheng 
401325263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
4014ad48fd75SYan, Zheng 	return ret;
4015ad48fd75SYan, Zheng }
4016ad48fd75SYan, Zheng 
4017ad48fd75SYan, Zheng /*
4018d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
4019d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
4020d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
4021d352ac68SChris Mason  * the front.
4022d352ac68SChris Mason  */
402378ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
4024b18c6685SChris Mason {
4025b18c6685SChris Mason 	int slot;
40265f39d397SChris Mason 	struct extent_buffer *leaf;
4027b18c6685SChris Mason 	u32 nritems;
4028b18c6685SChris Mason 	unsigned int data_end;
4029b18c6685SChris Mason 	unsigned int old_data_start;
4030b18c6685SChris Mason 	unsigned int old_size;
4031b18c6685SChris Mason 	unsigned int size_diff;
4032b18c6685SChris Mason 	int i;
4033cfed81a0SChris Mason 	struct btrfs_map_token token;
4034cfed81a0SChris Mason 
40355f39d397SChris Mason 	leaf = path->nodes[0];
4036179e29e4SChris Mason 	slot = path->slots[0];
4037179e29e4SChris Mason 
40383212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
4039179e29e4SChris Mason 	if (old_size == new_size)
4040143bede5SJeff Mahoney 		return;
4041b18c6685SChris Mason 
40425f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
40438f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4044b18c6685SChris Mason 
40453212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
4046179e29e4SChris Mason 
4047b18c6685SChris Mason 	size_diff = old_size - new_size;
4048b18c6685SChris Mason 
4049b18c6685SChris Mason 	BUG_ON(slot < 0);
4050b18c6685SChris Mason 	BUG_ON(slot >= nritems);
4051b18c6685SChris Mason 
4052b18c6685SChris Mason 	/*
4053b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4054b18c6685SChris Mason 	 */
4055b18c6685SChris Mason 	/* first correct the data pointers */
4056c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4057b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
40585f39d397SChris Mason 		u32 ioff;
4059db94535dSChris Mason 
40603212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
40613212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
4062b18c6685SChris Mason 	}
4063db94535dSChris Mason 
4064b18c6685SChris Mason 	/* shift the data */
4065179e29e4SChris Mason 	if (from_end) {
4066637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
4067637e3b48SJosef Bacik 				  old_data_start + new_size - data_end);
4068179e29e4SChris Mason 	} else {
4069179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
4070179e29e4SChris Mason 		u64 offset;
4071179e29e4SChris Mason 
4072179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
4073179e29e4SChris Mason 
4074179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4075179e29e4SChris Mason 			unsigned long ptr;
4076179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
4077179e29e4SChris Mason 
4078179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
4079179e29e4SChris Mason 					    struct btrfs_file_extent_item);
4080179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
4081179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
4082179e29e4SChris Mason 
4083179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
4084179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
4085179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
4086179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
4087179e29e4SChris Mason 				      (unsigned long)fi,
40887ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
4089179e29e4SChris Mason 			}
4090179e29e4SChris Mason 		}
4091179e29e4SChris Mason 
4092637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
4093637e3b48SJosef Bacik 				  old_data_start - data_end);
4094179e29e4SChris Mason 
4095179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
4096179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4097179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
4098179e29e4SChris Mason 		if (slot == 0)
4099b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4100179e29e4SChris Mason 	}
41015f39d397SChris Mason 
41023212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
41035f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4104b18c6685SChris Mason 
4105e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4106a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4107b18c6685SChris Mason 		BUG();
41085f39d397SChris Mason 	}
4109b18c6685SChris Mason }
4110b18c6685SChris Mason 
4111d352ac68SChris Mason /*
41128f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
4113d352ac68SChris Mason  */
4114c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
41156567e837SChris Mason {
41166567e837SChris Mason 	int slot;
41175f39d397SChris Mason 	struct extent_buffer *leaf;
41186567e837SChris Mason 	u32 nritems;
41196567e837SChris Mason 	unsigned int data_end;
41206567e837SChris Mason 	unsigned int old_data;
41216567e837SChris Mason 	unsigned int old_size;
41226567e837SChris Mason 	int i;
4123cfed81a0SChris Mason 	struct btrfs_map_token token;
4124cfed81a0SChris Mason 
41255f39d397SChris Mason 	leaf = path->nodes[0];
41266567e837SChris Mason 
41275f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
41288f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
41296567e837SChris Mason 
4130e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
4131a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
41326567e837SChris Mason 		BUG();
41335f39d397SChris Mason 	}
41346567e837SChris Mason 	slot = path->slots[0];
4135dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
41366567e837SChris Mason 
41376567e837SChris Mason 	BUG_ON(slot < 0);
41383326d1b0SChris Mason 	if (slot >= nritems) {
4139a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4140c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4141d397712bSChris Mason 			   slot, nritems);
4142290342f6SArnd Bergmann 		BUG();
41433326d1b0SChris Mason 	}
41446567e837SChris Mason 
41456567e837SChris Mason 	/*
41466567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
41476567e837SChris Mason 	 */
41486567e837SChris Mason 	/* first correct the data pointers */
4149c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
41506567e837SChris Mason 	for (i = slot; i < nritems; i++) {
41515f39d397SChris Mason 		u32 ioff;
4152db94535dSChris Mason 
41533212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
41543212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
41556567e837SChris Mason 	}
41565f39d397SChris Mason 
41576567e837SChris Mason 	/* shift the data */
4158637e3b48SJosef Bacik 	memmove_leaf_data(leaf, data_end - data_size, data_end,
4159637e3b48SJosef Bacik 			  old_data - data_end);
41605f39d397SChris Mason 
41616567e837SChris Mason 	data_end = old_data;
41623212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
41633212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
41645f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
41656567e837SChris Mason 
4166e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4167a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
41686567e837SChris Mason 		BUG();
41695f39d397SChris Mason 	}
41706567e837SChris Mason }
41716567e837SChris Mason 
417243dd529aSDavid Sterba /*
417343dd529aSDavid Sterba  * Make space in the node before inserting one or more items.
4174da9ffb24SNikolay Borisov  *
4175da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
4176da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
4177b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
417843dd529aSDavid Sterba  *
417943dd529aSDavid Sterba  * Main purpose is to save stack depth by doing the bulk of the work in a
418043dd529aSDavid Sterba  * function that doesn't call btrfs_search_slot
418174123bd7SChris Mason  */
4182f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4183b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
4184be0e5c09SChris Mason {
41850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
41869c58309dSChris Mason 	int i;
41877518a238SChris Mason 	u32 nritems;
4188be0e5c09SChris Mason 	unsigned int data_end;
4189e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
419044871b1bSChris Mason 	struct extent_buffer *leaf;
419144871b1bSChris Mason 	int slot;
4192cfed81a0SChris Mason 	struct btrfs_map_token token;
4193fc0d82e1SNikolay Borisov 	u32 total_size;
4194fc0d82e1SNikolay Borisov 
4195b7ef5f3aSFilipe Manana 	/*
4196b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
4197b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
4198b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
4199b7ef5f3aSFilipe Manana 	 */
420024cdc847SFilipe Manana 	if (path->slots[0] == 0) {
4201b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4202b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
420324cdc847SFilipe Manana 	}
420424cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
420524cdc847SFilipe Manana 
42065f39d397SChris Mason 	leaf = path->nodes[0];
420744871b1bSChris Mason 	slot = path->slots[0];
420874123bd7SChris Mason 
42095f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
42108f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4211b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4212eb60ceacSChris Mason 
4213e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4214a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
42150b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4216e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4217be0e5c09SChris Mason 		BUG();
4218d4dbff95SChris Mason 	}
42195f39d397SChris Mason 
4220c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4221be0e5c09SChris Mason 	if (slot != nritems) {
4222dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4223be0e5c09SChris Mason 
42245f39d397SChris Mason 		if (old_data < data_end) {
4225a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
42267269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
42277269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
42285f39d397SChris Mason 				   slot, old_data, data_end);
4229290342f6SArnd Bergmann 			BUG();
42305f39d397SChris Mason 		}
4231be0e5c09SChris Mason 		/*
4232be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4233be0e5c09SChris Mason 		 */
4234be0e5c09SChris Mason 		/* first correct the data pointers */
42350783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
42365f39d397SChris Mason 			u32 ioff;
4237db94535dSChris Mason 
42383212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
42393212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
4240b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
42410783fcfcSChris Mason 		}
4242be0e5c09SChris Mason 		/* shift the items */
4243637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot + batch->nr, slot, nritems - slot);
4244be0e5c09SChris Mason 
4245be0e5c09SChris Mason 		/* shift the data */
4246637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end - batch->total_data_size,
4247637e3b48SJosef Bacik 				  data_end, old_data - data_end);
4248be0e5c09SChris Mason 		data_end = old_data;
4249be0e5c09SChris Mason 	}
42505f39d397SChris Mason 
425162e2749eSChris Mason 	/* setup the item for the new data */
4252b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
4253b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
42549c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4255b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
42563212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
42573212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
42589c58309dSChris Mason 	}
425944871b1bSChris Mason 
4260b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4261b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4262aa5d6bedSChris Mason 
4263e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4264a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4265be0e5c09SChris Mason 		BUG();
42665f39d397SChris Mason 	}
426744871b1bSChris Mason }
426844871b1bSChris Mason 
426944871b1bSChris Mason /*
4270f0641656SFilipe Manana  * Insert a new item into a leaf.
4271f0641656SFilipe Manana  *
4272f0641656SFilipe Manana  * @root:      The root of the btree.
4273f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
4274f0641656SFilipe Manana  * @key:       The key of the new item.
4275f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
4276f0641656SFilipe Manana  */
4277f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
4278f0641656SFilipe Manana 				 struct btrfs_path *path,
4279f0641656SFilipe Manana 				 const struct btrfs_key *key,
4280f0641656SFilipe Manana 				 u32 data_size)
4281f0641656SFilipe Manana {
4282f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4283f0641656SFilipe Manana 
4284f0641656SFilipe Manana 	batch.keys = key;
4285f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4286f0641656SFilipe Manana 	batch.total_data_size = data_size;
4287f0641656SFilipe Manana 	batch.nr = 1;
4288f0641656SFilipe Manana 
4289f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
4290f0641656SFilipe Manana }
4291f0641656SFilipe Manana 
4292f0641656SFilipe Manana /*
429344871b1bSChris Mason  * Given a key and some data, insert items into the tree.
429444871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
429544871b1bSChris Mason  */
429644871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
429744871b1bSChris Mason 			    struct btrfs_root *root,
429844871b1bSChris Mason 			    struct btrfs_path *path,
4299b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
430044871b1bSChris Mason {
430144871b1bSChris Mason 	int ret = 0;
430244871b1bSChris Mason 	int slot;
4303b7ef5f3aSFilipe Manana 	u32 total_size;
430444871b1bSChris Mason 
4305b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4306b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
430744871b1bSChris Mason 	if (ret == 0)
430844871b1bSChris Mason 		return -EEXIST;
430944871b1bSChris Mason 	if (ret < 0)
4310143bede5SJeff Mahoney 		return ret;
431144871b1bSChris Mason 
431244871b1bSChris Mason 	slot = path->slots[0];
431344871b1bSChris Mason 	BUG_ON(slot < 0);
431444871b1bSChris Mason 
4315b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4316143bede5SJeff Mahoney 	return 0;
431762e2749eSChris Mason }
431862e2749eSChris Mason 
431962e2749eSChris Mason /*
432062e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
432162e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
432262e2749eSChris Mason  */
4323310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4324310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4325310712b2SOmar Sandoval 		      u32 data_size)
432662e2749eSChris Mason {
432762e2749eSChris Mason 	int ret = 0;
43282c90e5d6SChris Mason 	struct btrfs_path *path;
43295f39d397SChris Mason 	struct extent_buffer *leaf;
43305f39d397SChris Mason 	unsigned long ptr;
433162e2749eSChris Mason 
43322c90e5d6SChris Mason 	path = btrfs_alloc_path();
4333db5b493aSTsutomu Itoh 	if (!path)
4334db5b493aSTsutomu Itoh 		return -ENOMEM;
43352c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
433662e2749eSChris Mason 	if (!ret) {
43375f39d397SChris Mason 		leaf = path->nodes[0];
43385f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
43395f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
43405f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
434162e2749eSChris Mason 	}
43422c90e5d6SChris Mason 	btrfs_free_path(path);
4343aa5d6bedSChris Mason 	return ret;
4344be0e5c09SChris Mason }
4345be0e5c09SChris Mason 
434674123bd7SChris Mason /*
4347f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4348f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4349f0641656SFilipe Manana  * contiguous with the original item.
4350f0641656SFilipe Manana  *
4351f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4352f0641656SFilipe Manana  * the entire time.
4353f0641656SFilipe Manana  */
4354f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4355f0641656SFilipe Manana 			 struct btrfs_root *root,
4356f0641656SFilipe Manana 			 struct btrfs_path *path,
4357f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4358f0641656SFilipe Manana {
4359f0641656SFilipe Manana 	struct extent_buffer *leaf;
4360f0641656SFilipe Manana 	int ret;
4361f0641656SFilipe Manana 	u32 item_size;
4362f0641656SFilipe Manana 
4363f0641656SFilipe Manana 	leaf = path->nodes[0];
43643212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4365f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4366f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4367f0641656SFilipe Manana 	if (ret)
4368f0641656SFilipe Manana 		return ret;
4369f0641656SFilipe Manana 
4370f0641656SFilipe Manana 	path->slots[0]++;
4371f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4372f0641656SFilipe Manana 	leaf = path->nodes[0];
4373f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4374f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4375f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4376f0641656SFilipe Manana 			     item_size);
4377f0641656SFilipe Manana 	return 0;
4378f0641656SFilipe Manana }
4379f0641656SFilipe Manana 
4380f0641656SFilipe Manana /*
43815de08d7dSChris Mason  * delete the pointer from a given node.
438274123bd7SChris Mason  *
4383d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4384d352ac68SChris Mason  * empty a node.
4385016f9d0bSJosef Bacik  *
4386016f9d0bSJosef Bacik  * This is exported for use inside btrfs-progs, don't un-export it.
438774123bd7SChris Mason  */
4388016f9d0bSJosef Bacik void btrfs_del_ptr(struct btrfs_root *root, struct btrfs_path *path, int level,
4389016f9d0bSJosef Bacik 		   int slot)
4390be0e5c09SChris Mason {
43915f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
43927518a238SChris Mason 	u32 nritems;
4393f3ea38daSJan Schmidt 	int ret;
4394be0e5c09SChris Mason 
43955f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4396be0e5c09SChris Mason 	if (slot != nritems - 1) {
4397bf1d3425SDavid Sterba 		if (level) {
4398f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4399f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4400bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4401bf1d3425SDavid Sterba 		}
44025f39d397SChris Mason 		memmove_extent_buffer(parent,
4403e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot),
4404e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot + 1),
4405d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4406d6025579SChris Mason 			      (nritems - slot - 1));
440757ba86c0SChris Mason 	} else if (level) {
4408f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
440933cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REMOVE);
441057ba86c0SChris Mason 		BUG_ON(ret < 0);
4411be0e5c09SChris Mason 	}
4412f3ea38daSJan Schmidt 
44137518a238SChris Mason 	nritems--;
44145f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
44157518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
44165f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4417eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
44185f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4419bb803951SChris Mason 	} else if (slot == 0) {
44205f39d397SChris Mason 		struct btrfs_disk_key disk_key;
44215f39d397SChris Mason 
44225f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4423b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4424be0e5c09SChris Mason 	}
4425d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4426be0e5c09SChris Mason }
4427be0e5c09SChris Mason 
442874123bd7SChris Mason /*
4429323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
44305d4f98a2SYan Zheng  * path->nodes[1].
4431323ac95bSChris Mason  *
4432323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4433323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4434323ac95bSChris Mason  *
4435323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4436323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4437323ac95bSChris Mason  */
4438143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4439323ac95bSChris Mason 				    struct btrfs_root *root,
44405d4f98a2SYan Zheng 				    struct btrfs_path *path,
44415d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4442323ac95bSChris Mason {
44435d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4444016f9d0bSJosef Bacik 	btrfs_del_ptr(root, path, 1, path->slots[1]);
4445323ac95bSChris Mason 
44464d081c41SChris Mason 	/*
44474d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
44484d081c41SChris Mason 	 * aren't holding any locks when we call it
44494d081c41SChris Mason 	 */
44504d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
44514d081c41SChris Mason 
4452f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4453f0486c68SYan, Zheng 
445467439dadSDavid Sterba 	atomic_inc(&leaf->refs);
44557a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
44563083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4457323ac95bSChris Mason }
4458323ac95bSChris Mason /*
445974123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
446074123bd7SChris Mason  * the leaf, remove it from the tree
446174123bd7SChris Mason  */
446285e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
446385e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4464be0e5c09SChris Mason {
44650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
44665f39d397SChris Mason 	struct extent_buffer *leaf;
4467aa5d6bedSChris Mason 	int ret = 0;
4468aa5d6bedSChris Mason 	int wret;
44697518a238SChris Mason 	u32 nritems;
4470be0e5c09SChris Mason 
44715f39d397SChris Mason 	leaf = path->nodes[0];
44725f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4473be0e5c09SChris Mason 
447485e21bacSChris Mason 	if (slot + nr != nritems) {
44750cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
44760cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4477c82f823cSDavid Sterba 		struct btrfs_map_token token;
44780cae23b6SFilipe Manana 		u32 dsize = 0;
44790cae23b6SFilipe Manana 		int i;
44800cae23b6SFilipe Manana 
44810cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
44820cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
44835f39d397SChris Mason 
4484637e3b48SJosef Bacik 		memmove_leaf_data(leaf, data_end + dsize, data_end,
448585e21bacSChris Mason 				  last_off - data_end);
44865f39d397SChris Mason 
4487c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
448885e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
44895f39d397SChris Mason 			u32 ioff;
4490db94535dSChris Mason 
44913212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
44923212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
44930783fcfcSChris Mason 		}
4494db94535dSChris Mason 
4495637e3b48SJosef Bacik 		memmove_leaf_items(leaf, slot, slot + nr, nritems - slot - nr);
4496be0e5c09SChris Mason 	}
449785e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
449885e21bacSChris Mason 	nritems -= nr;
44995f39d397SChris Mason 
450074123bd7SChris Mason 	/* delete the leaf if we've emptied it */
45017518a238SChris Mason 	if (nritems == 0) {
45025f39d397SChris Mason 		if (leaf == root->node) {
45035f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
45049a8dd150SChris Mason 		} else {
4505190a8339SJosef Bacik 			btrfs_clear_buffer_dirty(trans, leaf);
4506143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
45079a8dd150SChris Mason 		}
4508be0e5c09SChris Mason 	} else {
45097518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4510aa5d6bedSChris Mason 		if (slot == 0) {
45115f39d397SChris Mason 			struct btrfs_disk_key disk_key;
45125f39d397SChris Mason 
45135f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4514b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4515aa5d6bedSChris Mason 		}
4516aa5d6bedSChris Mason 
45177c4063d1SFilipe Manana 		/*
45187c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
45197c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
45207c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
45217c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
45227c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
45237c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
45247c4063d1SFilipe Manana 		 */
45250b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
45267c4063d1SFilipe Manana 			u32 min_push_space;
45277c4063d1SFilipe Manana 
4528be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4529be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4530016f9d0bSJosef Bacik 			 * for possible call to btrfs_del_ptr below
4531be0e5c09SChris Mason 			 */
45324920c9acSChris Mason 			slot = path->slots[1];
453367439dadSDavid Sterba 			atomic_inc(&leaf->refs);
45347c4063d1SFilipe Manana 			/*
45357c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
45367c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
45377c4063d1SFilipe Manana 			 */
45387c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
45397c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
45407c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
45417c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
454254aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4543aa5d6bedSChris Mason 				ret = wret;
45445f39d397SChris Mason 
45455f39d397SChris Mason 			if (path->nodes[0] == leaf &&
45465f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
45477c4063d1SFilipe Manana 				/*
45487c4063d1SFilipe Manana 				 * If we were not able to push all items from our
45497c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
45507c4063d1SFilipe Manana 				 * either push all the remaining items to the
45517c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
45527c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
45537c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
45547c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
45557c4063d1SFilipe Manana 				 * or nearly full.
45567c4063d1SFilipe Manana 				 */
45577c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
45587c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
45597c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
45607c4063d1SFilipe Manana 						       min_push_space, 1, 0);
456154aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4562aa5d6bedSChris Mason 					ret = wret;
4563aa5d6bedSChris Mason 			}
45645f39d397SChris Mason 
45655f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4566323ac95bSChris Mason 				path->slots[1] = slot;
4567143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
45685f39d397SChris Mason 				free_extent_buffer(leaf);
4569143bede5SJeff Mahoney 				ret = 0;
45705de08d7dSChris Mason 			} else {
4571925baeddSChris Mason 				/* if we're still in the path, make sure
4572925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4573925baeddSChris Mason 				 * push_leaf functions must have already
4574925baeddSChris Mason 				 * dirtied this buffer
4575925baeddSChris Mason 				 */
4576925baeddSChris Mason 				if (path->nodes[0] == leaf)
45775f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
45785f39d397SChris Mason 				free_extent_buffer(leaf);
4579be0e5c09SChris Mason 			}
4580d5719762SChris Mason 		} else {
45815f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4582be0e5c09SChris Mason 		}
45839a8dd150SChris Mason 	}
4584aa5d6bedSChris Mason 	return ret;
45859a8dd150SChris Mason }
45869a8dd150SChris Mason 
458797571fd0SChris Mason /*
45883f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4589de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4590de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
45913f157a2fSChris Mason  *
45923f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
45933f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
45943f157a2fSChris Mason  * key and get a writable path.
45953f157a2fSChris Mason  *
45963f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
45973f157a2fSChris Mason  * of the tree.
45983f157a2fSChris Mason  *
4599d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4600d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4601d352ac68SChris Mason  * skipped over (without reading them).
4602d352ac68SChris Mason  *
46033f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
46043f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
46053f157a2fSChris Mason  */
46063f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4607de78b51aSEric Sandeen 			 struct btrfs_path *path,
46083f157a2fSChris Mason 			 u64 min_trans)
46093f157a2fSChris Mason {
46103f157a2fSChris Mason 	struct extent_buffer *cur;
46113f157a2fSChris Mason 	struct btrfs_key found_key;
46123f157a2fSChris Mason 	int slot;
46139652480bSYan 	int sret;
46143f157a2fSChris Mason 	u32 nritems;
46153f157a2fSChris Mason 	int level;
46163f157a2fSChris Mason 	int ret = 1;
4617f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
46183f157a2fSChris Mason 
4619c922b016SStefan Roesch 	ASSERT(!path->nowait);
4620f98de9b9SFilipe Manana 	path->keep_locks = 1;
46213f157a2fSChris Mason again:
4622bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
46233f157a2fSChris Mason 	level = btrfs_header_level(cur);
4624e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
46253f157a2fSChris Mason 	path->nodes[level] = cur;
4626bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
46273f157a2fSChris Mason 
46283f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
46293f157a2fSChris Mason 		ret = 1;
46303f157a2fSChris Mason 		goto out;
46313f157a2fSChris Mason 	}
46323f157a2fSChris Mason 	while (1) {
46333f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
46343f157a2fSChris Mason 		level = btrfs_header_level(cur);
4635fdf8d595SAnand Jain 		sret = btrfs_bin_search(cur, 0, min_key, &slot);
4636cbca7d59SFilipe Manana 		if (sret < 0) {
4637cbca7d59SFilipe Manana 			ret = sret;
4638cbca7d59SFilipe Manana 			goto out;
4639cbca7d59SFilipe Manana 		}
46403f157a2fSChris Mason 
4641323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4642323ac95bSChris Mason 		if (level == path->lowest_level) {
4643e02119d5SChris Mason 			if (slot >= nritems)
4644e02119d5SChris Mason 				goto find_next_key;
46453f157a2fSChris Mason 			ret = 0;
46463f157a2fSChris Mason 			path->slots[level] = slot;
46473f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
46483f157a2fSChris Mason 			goto out;
46493f157a2fSChris Mason 		}
46509652480bSYan 		if (sret && slot > 0)
46519652480bSYan 			slot--;
46523f157a2fSChris Mason 		/*
4653de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4654260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
46553f157a2fSChris Mason 		 */
46563f157a2fSChris Mason 		while (slot < nritems) {
46573f157a2fSChris Mason 			u64 gen;
4658e02119d5SChris Mason 
46593f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
46603f157a2fSChris Mason 			if (gen < min_trans) {
46613f157a2fSChris Mason 				slot++;
46623f157a2fSChris Mason 				continue;
46633f157a2fSChris Mason 			}
46643f157a2fSChris Mason 			break;
46653f157a2fSChris Mason 		}
4666e02119d5SChris Mason find_next_key:
46673f157a2fSChris Mason 		/*
46683f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
46693f157a2fSChris Mason 		 * and find another one
46703f157a2fSChris Mason 		 */
46713f157a2fSChris Mason 		if (slot >= nritems) {
4672e02119d5SChris Mason 			path->slots[level] = slot;
4673e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4674de78b51aSEric Sandeen 						  min_trans);
4675e02119d5SChris Mason 			if (sret == 0) {
4676b3b4aa74SDavid Sterba 				btrfs_release_path(path);
46773f157a2fSChris Mason 				goto again;
46783f157a2fSChris Mason 			} else {
46793f157a2fSChris Mason 				goto out;
46803f157a2fSChris Mason 			}
46813f157a2fSChris Mason 		}
46823f157a2fSChris Mason 		/* save our key for returning back */
46833f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
46843f157a2fSChris Mason 		path->slots[level] = slot;
46853f157a2fSChris Mason 		if (level == path->lowest_level) {
46863f157a2fSChris Mason 			ret = 0;
46873f157a2fSChris Mason 			goto out;
46883f157a2fSChris Mason 		}
46894b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4690fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4691fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4692fb770ae4SLiu Bo 			goto out;
4693fb770ae4SLiu Bo 		}
46943f157a2fSChris Mason 
4695bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4696b4ce94deSChris Mason 
4697bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
46983f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4699f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
47003f157a2fSChris Mason 	}
47013f157a2fSChris Mason out:
4702f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4703f98de9b9SFilipe Manana 	if (ret == 0) {
4704f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4705f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4706f98de9b9SFilipe Manana 	}
47073f157a2fSChris Mason 	return ret;
47083f157a2fSChris Mason }
47093f157a2fSChris Mason 
47103f157a2fSChris Mason /*
47113f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
47123f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4713de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
47143f157a2fSChris Mason  *
47153f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
47163f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
47173f157a2fSChris Mason  *
47183f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
47193f157a2fSChris Mason  * calling this function.
47203f157a2fSChris Mason  */
4721e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4722de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4723e7a84565SChris Mason {
4724e7a84565SChris Mason 	int slot;
4725e7a84565SChris Mason 	struct extent_buffer *c;
4726e7a84565SChris Mason 
47276a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4728e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4729e7a84565SChris Mason 		if (!path->nodes[level])
4730e7a84565SChris Mason 			return 1;
4731e7a84565SChris Mason 
4732e7a84565SChris Mason 		slot = path->slots[level] + 1;
4733e7a84565SChris Mason 		c = path->nodes[level];
47343f157a2fSChris Mason next:
4735e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
473633c66f43SYan Zheng 			int ret;
473733c66f43SYan Zheng 			int orig_lowest;
473833c66f43SYan Zheng 			struct btrfs_key cur_key;
473933c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
474033c66f43SYan Zheng 			    !path->nodes[level + 1])
4741e7a84565SChris Mason 				return 1;
474233c66f43SYan Zheng 
47436a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
474433c66f43SYan Zheng 				level++;
4745e7a84565SChris Mason 				continue;
4746e7a84565SChris Mason 			}
474733c66f43SYan Zheng 
474833c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
474933c66f43SYan Zheng 			if (level == 0)
475033c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
475133c66f43SYan Zheng 			else
475233c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
475333c66f43SYan Zheng 
475433c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4755b3b4aa74SDavid Sterba 			btrfs_release_path(path);
475633c66f43SYan Zheng 			path->lowest_level = level;
475733c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
475833c66f43SYan Zheng 						0, 0);
475933c66f43SYan Zheng 			path->lowest_level = orig_lowest;
476033c66f43SYan Zheng 			if (ret < 0)
476133c66f43SYan Zheng 				return ret;
476233c66f43SYan Zheng 
476333c66f43SYan Zheng 			c = path->nodes[level];
476433c66f43SYan Zheng 			slot = path->slots[level];
476533c66f43SYan Zheng 			if (ret == 0)
476633c66f43SYan Zheng 				slot++;
476733c66f43SYan Zheng 			goto next;
476833c66f43SYan Zheng 		}
476933c66f43SYan Zheng 
4770e7a84565SChris Mason 		if (level == 0)
4771e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
47723f157a2fSChris Mason 		else {
47733f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
47743f157a2fSChris Mason 
47753f157a2fSChris Mason 			if (gen < min_trans) {
47763f157a2fSChris Mason 				slot++;
47773f157a2fSChris Mason 				goto next;
47783f157a2fSChris Mason 			}
4779e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
47803f157a2fSChris Mason 		}
4781e7a84565SChris Mason 		return 0;
4782e7a84565SChris Mason 	}
4783e7a84565SChris Mason 	return 1;
4784e7a84565SChris Mason }
4785e7a84565SChris Mason 
47863d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
47873d7806ecSJan Schmidt 			u64 time_seq)
47883d7806ecSJan Schmidt {
4789d97e63b6SChris Mason 	int slot;
47908e73f275SChris Mason 	int level;
47915f39d397SChris Mason 	struct extent_buffer *c;
47928e73f275SChris Mason 	struct extent_buffer *next;
4793d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4794925baeddSChris Mason 	struct btrfs_key key;
4795d96b3424SFilipe Manana 	bool need_commit_sem = false;
4796925baeddSChris Mason 	u32 nritems;
4797925baeddSChris Mason 	int ret;
47980e46318dSJosef Bacik 	int i;
4799925baeddSChris Mason 
4800bdcdd86cSFilipe Manana 	/*
4801bdcdd86cSFilipe Manana 	 * The nowait semantics are used only for write paths, where we don't
4802bdcdd86cSFilipe Manana 	 * use the tree mod log and sequence numbers.
4803bdcdd86cSFilipe Manana 	 */
4804bdcdd86cSFilipe Manana 	if (time_seq)
4805c922b016SStefan Roesch 		ASSERT(!path->nowait);
4806c922b016SStefan Roesch 
4807925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4808d397712bSChris Mason 	if (nritems == 0)
4809925baeddSChris Mason 		return 1;
4810925baeddSChris Mason 
48118e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
48128e73f275SChris Mason again:
48138e73f275SChris Mason 	level = 1;
48148e73f275SChris Mason 	next = NULL;
4815b3b4aa74SDavid Sterba 	btrfs_release_path(path);
48168e73f275SChris Mason 
4817a2135011SChris Mason 	path->keep_locks = 1;
48188e73f275SChris Mason 
4819d96b3424SFilipe Manana 	if (time_seq) {
48203d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4821d96b3424SFilipe Manana 	} else {
4822d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4823d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4824d96b3424SFilipe Manana 			need_commit_sem = true;
4825bdcdd86cSFilipe Manana 			if (path->nowait) {
4826bdcdd86cSFilipe Manana 				if (!down_read_trylock(&fs_info->commit_root_sem)) {
4827bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4828bdcdd86cSFilipe Manana 					goto done;
4829bdcdd86cSFilipe Manana 				}
4830bdcdd86cSFilipe Manana 			} else {
4831d96b3424SFilipe Manana 				down_read(&fs_info->commit_root_sem);
4832d96b3424SFilipe Manana 			}
4833bdcdd86cSFilipe Manana 		}
4834925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4835d96b3424SFilipe Manana 	}
4836925baeddSChris Mason 	path->keep_locks = 0;
4837925baeddSChris Mason 
4838925baeddSChris Mason 	if (ret < 0)
4839d96b3424SFilipe Manana 		goto done;
4840925baeddSChris Mason 
4841a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4842168fd7d2SChris Mason 	/*
4843168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4844168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4845168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4846168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4847168fd7d2SChris Mason 	 */
4848a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4849e457afecSYan Zheng 		if (ret == 0)
4850168fd7d2SChris Mason 			path->slots[0]++;
48518e73f275SChris Mason 		ret = 0;
4852925baeddSChris Mason 		goto done;
4853925baeddSChris Mason 	}
48540b43e04fSLiu Bo 	/*
48550b43e04fSLiu Bo 	 * So the above check misses one case:
48560b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
48570b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
48580b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
48590b43e04fSLiu Bo 	 *
48600b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
48610b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
48620b43e04fSLiu Bo 	 *
48630b43e04fSLiu Bo 	 * And a bit more explanation about this check,
48640b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
48650b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
48660b43e04fSLiu Bo 	 * bigger one.
48670b43e04fSLiu Bo 	 */
48680b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
48690b43e04fSLiu Bo 		ret = 0;
48700b43e04fSLiu Bo 		goto done;
48710b43e04fSLiu Bo 	}
4872d97e63b6SChris Mason 
4873234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
48748e73f275SChris Mason 		if (!path->nodes[level]) {
48758e73f275SChris Mason 			ret = 1;
48768e73f275SChris Mason 			goto done;
48778e73f275SChris Mason 		}
48785f39d397SChris Mason 
4879d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4880d97e63b6SChris Mason 		c = path->nodes[level];
48815f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4882d97e63b6SChris Mason 			level++;
48838e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
48848e73f275SChris Mason 				ret = 1;
48858e73f275SChris Mason 				goto done;
48868e73f275SChris Mason 			}
4887d97e63b6SChris Mason 			continue;
4888d97e63b6SChris Mason 		}
48895f39d397SChris Mason 
48900e46318dSJosef Bacik 
48910e46318dSJosef Bacik 		/*
48920e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
48930e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
48940e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
48950e46318dSJosef Bacik 		 */
48960e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
48970e46318dSJosef Bacik 			if (path->locks[level]) {
48980e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
48990e46318dSJosef Bacik 				path->locks[i] = 0;
49000e46318dSJosef Bacik 			}
49010e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
49020e46318dSJosef Bacik 			path->nodes[i] = NULL;
4903925baeddSChris Mason 		}
49045f39d397SChris Mason 
49058e73f275SChris Mason 		next = c;
4906d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4907cda79c54SDavid Sterba 					    slot, &key);
4908bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
49098e73f275SChris Mason 			goto again;
49105f39d397SChris Mason 
491176a05b35SChris Mason 		if (ret < 0) {
4912b3b4aa74SDavid Sterba 			btrfs_release_path(path);
491376a05b35SChris Mason 			goto done;
491476a05b35SChris Mason 		}
491576a05b35SChris Mason 
49165cd57b2cSChris Mason 		if (!path->skip_locking) {
4917bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4918bdcdd86cSFilipe Manana 			if (!ret && path->nowait) {
4919bdcdd86cSFilipe Manana 				ret = -EAGAIN;
4920bdcdd86cSFilipe Manana 				goto done;
4921bdcdd86cSFilipe Manana 			}
4922d42244a0SJan Schmidt 			if (!ret && time_seq) {
4923d42244a0SJan Schmidt 				/*
4924d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4925d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4926d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4927d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4928d42244a0SJan Schmidt 				 * on our lock and cycle.
4929d42244a0SJan Schmidt 				 */
4930cf538830SJan Schmidt 				free_extent_buffer(next);
4931d42244a0SJan Schmidt 				btrfs_release_path(path);
4932d42244a0SJan Schmidt 				cond_resched();
4933d42244a0SJan Schmidt 				goto again;
4934d42244a0SJan Schmidt 			}
49350e46318dSJosef Bacik 			if (!ret)
49360e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4937bd681513SChris Mason 		}
4938d97e63b6SChris Mason 		break;
4939d97e63b6SChris Mason 	}
4940d97e63b6SChris Mason 	path->slots[level] = slot;
4941d97e63b6SChris Mason 	while (1) {
4942d97e63b6SChris Mason 		level--;
4943d97e63b6SChris Mason 		path->nodes[level] = next;
4944d97e63b6SChris Mason 		path->slots[level] = 0;
4945a74a4b97SChris Mason 		if (!path->skip_locking)
4946ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4947d97e63b6SChris Mason 		if (!level)
4948d97e63b6SChris Mason 			break;
4949b4ce94deSChris Mason 
4950d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4951cda79c54SDavid Sterba 					    0, &key);
4952bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
49538e73f275SChris Mason 			goto again;
49548e73f275SChris Mason 
495576a05b35SChris Mason 		if (ret < 0) {
4956b3b4aa74SDavid Sterba 			btrfs_release_path(path);
495776a05b35SChris Mason 			goto done;
495876a05b35SChris Mason 		}
495976a05b35SChris Mason 
4960bdcdd86cSFilipe Manana 		if (!path->skip_locking) {
4961bdcdd86cSFilipe Manana 			if (path->nowait) {
4962bdcdd86cSFilipe Manana 				if (!btrfs_try_tree_read_lock(next)) {
4963bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4964bdcdd86cSFilipe Manana 					goto done;
4965bdcdd86cSFilipe Manana 				}
4966bdcdd86cSFilipe Manana 			} else {
49670e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4968d97e63b6SChris Mason 			}
4969bdcdd86cSFilipe Manana 		}
4970bdcdd86cSFilipe Manana 	}
49718e73f275SChris Mason 	ret = 0;
4972925baeddSChris Mason done:
4973f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
4974d96b3424SFilipe Manana 	if (need_commit_sem) {
4975d96b3424SFilipe Manana 		int ret2;
4976d96b3424SFilipe Manana 
4977d96b3424SFilipe Manana 		path->need_commit_sem = 1;
4978d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
4979d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
4980d96b3424SFilipe Manana 		if (ret2)
4981d96b3424SFilipe Manana 			ret = ret2;
4982d96b3424SFilipe Manana 	}
49838e73f275SChris Mason 
49848e73f275SChris Mason 	return ret;
4985d97e63b6SChris Mason }
49860b86a832SChris Mason 
4987890d2b1aSJosef Bacik int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
4988890d2b1aSJosef Bacik {
4989890d2b1aSJosef Bacik 	path->slots[0]++;
4990890d2b1aSJosef Bacik 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
4991890d2b1aSJosef Bacik 		return btrfs_next_old_leaf(root, path, time_seq);
4992890d2b1aSJosef Bacik 	return 0;
4993890d2b1aSJosef Bacik }
4994890d2b1aSJosef Bacik 
49953f157a2fSChris Mason /*
49963f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
49973f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
49983f157a2fSChris Mason  *
49993f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
50003f157a2fSChris Mason  */
50010b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
50020b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
50030b86a832SChris Mason 			int type)
50040b86a832SChris Mason {
50050b86a832SChris Mason 	struct btrfs_key found_key;
50060b86a832SChris Mason 	struct extent_buffer *leaf;
5007e02119d5SChris Mason 	u32 nritems;
50080b86a832SChris Mason 	int ret;
50090b86a832SChris Mason 
50100b86a832SChris Mason 	while (1) {
50110b86a832SChris Mason 		if (path->slots[0] == 0) {
50120b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
50130b86a832SChris Mason 			if (ret != 0)
50140b86a832SChris Mason 				return ret;
50150b86a832SChris Mason 		} else {
50160b86a832SChris Mason 			path->slots[0]--;
50170b86a832SChris Mason 		}
50180b86a832SChris Mason 		leaf = path->nodes[0];
5019e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
5020e02119d5SChris Mason 		if (nritems == 0)
5021e02119d5SChris Mason 			return 1;
5022e02119d5SChris Mason 		if (path->slots[0] == nritems)
5023e02119d5SChris Mason 			path->slots[0]--;
5024e02119d5SChris Mason 
50250b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5026e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
5027e02119d5SChris Mason 			break;
50280a4eefbbSYan Zheng 		if (found_key.type == type)
50290a4eefbbSYan Zheng 			return 0;
5030e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
5031e02119d5SChris Mason 		    found_key.type < type)
5032e02119d5SChris Mason 			break;
50330b86a832SChris Mason 	}
50340b86a832SChris Mason 	return 1;
50350b86a832SChris Mason }
5036ade2e0b3SWang Shilong 
5037ade2e0b3SWang Shilong /*
5038ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
5039ade2e0b3SWang Shilong  * min objecitd.
5040ade2e0b3SWang Shilong  *
5041ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5042ade2e0b3SWang Shilong  */
5043ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
5044ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
5045ade2e0b3SWang Shilong {
5046ade2e0b3SWang Shilong 	struct btrfs_key found_key;
5047ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
5048ade2e0b3SWang Shilong 	u32 nritems;
5049ade2e0b3SWang Shilong 	int ret;
5050ade2e0b3SWang Shilong 
5051ade2e0b3SWang Shilong 	while (1) {
5052ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
5053ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
5054ade2e0b3SWang Shilong 			if (ret != 0)
5055ade2e0b3SWang Shilong 				return ret;
5056ade2e0b3SWang Shilong 		} else {
5057ade2e0b3SWang Shilong 			path->slots[0]--;
5058ade2e0b3SWang Shilong 		}
5059ade2e0b3SWang Shilong 		leaf = path->nodes[0];
5060ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
5061ade2e0b3SWang Shilong 		if (nritems == 0)
5062ade2e0b3SWang Shilong 			return 1;
5063ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
5064ade2e0b3SWang Shilong 			path->slots[0]--;
5065ade2e0b3SWang Shilong 
5066ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5067ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
5068ade2e0b3SWang Shilong 			break;
5069ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5070ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5071ade2e0b3SWang Shilong 			return 0;
5072ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
5073ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5074ade2e0b3SWang Shilong 			break;
5075ade2e0b3SWang Shilong 	}
5076ade2e0b3SWang Shilong 	return 1;
5077ade2e0b3SWang Shilong }
5078226463d7SJosef Bacik 
5079226463d7SJosef Bacik int __init btrfs_ctree_init(void)
5080226463d7SJosef Bacik {
5081226463d7SJosef Bacik 	btrfs_path_cachep = kmem_cache_create("btrfs_path",
5082226463d7SJosef Bacik 			sizeof(struct btrfs_path), 0,
5083226463d7SJosef Bacik 			SLAB_MEM_SPREAD, NULL);
5084226463d7SJosef Bacik 	if (!btrfs_path_cachep)
5085226463d7SJosef Bacik 		return -ENOMEM;
5086226463d7SJosef Bacik 	return 0;
5087226463d7SJosef Bacik }
5088226463d7SJosef Bacik 
5089226463d7SJosef Bacik void __cold btrfs_ctree_exit(void)
5090226463d7SJosef Bacik {
5091226463d7SJosef Bacik 	kmem_cache_destroy(btrfs_path_cachep);
5092226463d7SJosef Bacik }
5093