xref: /openbmc/linux/fs/btrfs/ctree.c (revision 67d5e289a193c643a70ceda437c625e2bc876dbc)
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>
10eb60ceacSChris Mason #include "ctree.h"
11eb60ceacSChris Mason #include "disk-io.h"
127f5c1516SChris Mason #include "transaction.h"
135f39d397SChris Mason #include "print-tree.h"
14925baeddSChris Mason #include "locking.h"
15de37aa51SNikolay Borisov #include "volumes.h"
16f616f5cdSQu Wenruo #include "qgroup.h"
17f3a84ccdSFilipe Manana #include "tree-mod-log.h"
189a8dd150SChris Mason 
19e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
20e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
21310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
22310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
23310712b2SOmar Sandoval 		      int data_size, int extend);
245f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
252ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
26971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
275f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
285f39d397SChris Mason 			      struct extent_buffer *dst_buf,
295f39d397SChris Mason 			      struct extent_buffer *src_buf);
30afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
31afe5fea7STsutomu Itoh 		    int level, int slot);
32d97e63b6SChris Mason 
33af024ed2SJohannes Thumshirn static const struct btrfs_csums {
34af024ed2SJohannes Thumshirn 	u16		size;
3559a0fcdbSDavid Sterba 	const char	name[10];
3659a0fcdbSDavid Sterba 	const char	driver[12];
37af024ed2SJohannes Thumshirn } btrfs_csums[] = {
38af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
393951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
403831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
41352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
42352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
43af024ed2SJohannes Thumshirn };
44af024ed2SJohannes Thumshirn 
45af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
46af024ed2SJohannes Thumshirn {
47af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
48af024ed2SJohannes Thumshirn 	/*
49af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
50af024ed2SJohannes Thumshirn 	 */
51af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
52af024ed2SJohannes Thumshirn }
53af024ed2SJohannes Thumshirn 
54af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
55af024ed2SJohannes Thumshirn {
56af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
57af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
58af024ed2SJohannes Thumshirn }
59af024ed2SJohannes Thumshirn 
60b4e967beSDavid Sterba /*
61b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
62b4e967beSDavid Sterba  * name
63b4e967beSDavid Sterba  */
64b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
65b4e967beSDavid Sterba {
66b4e967beSDavid Sterba 	/* csum type is validated at mount time */
6759a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
6859a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
69b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
70b4e967beSDavid Sterba }
71b4e967beSDavid Sterba 
72604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
73f7cea56cSDavid Sterba {
74f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
75f7cea56cSDavid Sterba }
76f7cea56cSDavid Sterba 
772c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
782c90e5d6SChris Mason {
79e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
802c90e5d6SChris Mason }
812c90e5d6SChris Mason 
82d352ac68SChris Mason /* this also releases the path */
832c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
842c90e5d6SChris Mason {
85ff175d57SJesper Juhl 	if (!p)
86ff175d57SJesper Juhl 		return;
87b3b4aa74SDavid Sterba 	btrfs_release_path(p);
882c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
892c90e5d6SChris Mason }
902c90e5d6SChris Mason 
91d352ac68SChris Mason /*
92d352ac68SChris Mason  * path release drops references on the extent buffers in the path
93d352ac68SChris Mason  * and it drops any locks held by this path
94d352ac68SChris Mason  *
95d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
96d352ac68SChris Mason  */
97b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
98eb60ceacSChris Mason {
99eb60ceacSChris Mason 	int i;
100a2135011SChris Mason 
101234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1023f157a2fSChris Mason 		p->slots[i] = 0;
103eb60ceacSChris Mason 		if (!p->nodes[i])
104925baeddSChris Mason 			continue;
105925baeddSChris Mason 		if (p->locks[i]) {
106bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
107925baeddSChris Mason 			p->locks[i] = 0;
108925baeddSChris Mason 		}
1095f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1103f157a2fSChris Mason 		p->nodes[i] = NULL;
111eb60ceacSChris Mason 	}
112eb60ceacSChris Mason }
113eb60ceacSChris Mason 
114d352ac68SChris Mason /*
115d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
116d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
117d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
118d352ac68SChris Mason  * looping required.
119d352ac68SChris Mason  *
120d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
121d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
122d352ac68SChris Mason  * at any time because there are no locks held.
123d352ac68SChris Mason  */
124925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
125925baeddSChris Mason {
126925baeddSChris Mason 	struct extent_buffer *eb;
127240f62c8SChris Mason 
1283083ee2eSJosef Bacik 	while (1) {
129240f62c8SChris Mason 		rcu_read_lock();
130240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1313083ee2eSJosef Bacik 
1323083ee2eSJosef Bacik 		/*
1333083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
13401327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1353083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1363083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1373083ee2eSJosef Bacik 		 */
1383083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
139240f62c8SChris Mason 			rcu_read_unlock();
1403083ee2eSJosef Bacik 			break;
1413083ee2eSJosef Bacik 		}
1423083ee2eSJosef Bacik 		rcu_read_unlock();
1433083ee2eSJosef Bacik 		synchronize_rcu();
1443083ee2eSJosef Bacik 	}
145925baeddSChris Mason 	return eb;
146925baeddSChris Mason }
147925baeddSChris Mason 
14892a7cc42SQu Wenruo /*
14992a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
15092a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
15192a7cc42SQu Wenruo  * sure they get properly updated on disk.
152d352ac68SChris Mason  */
1530b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1540b86a832SChris Mason {
1550b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1560b246afaSJeff Mahoney 
157e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
158e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
159e7070be1SJosef Bacik 		return;
160e7070be1SJosef Bacik 
1610b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
162e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
163e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
1644fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
165e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
1660b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
167e7070be1SJosef Bacik 		else
168e7070be1SJosef Bacik 			list_move(&root->dirty_list,
1690b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
1700b86a832SChris Mason 	}
1710b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1720b86a832SChris Mason }
1730b86a832SChris Mason 
174d352ac68SChris Mason /*
175d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
176d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
177d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
178d352ac68SChris Mason  */
179be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
180be20aa9dSChris Mason 		      struct btrfs_root *root,
181be20aa9dSChris Mason 		      struct extent_buffer *buf,
182be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
183be20aa9dSChris Mason {
1840b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
185be20aa9dSChris Mason 	struct extent_buffer *cow;
186be20aa9dSChris Mason 	int ret = 0;
187be20aa9dSChris Mason 	int level;
1885d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
189be20aa9dSChris Mason 
19092a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
1910b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
19292a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
19327cdeb70SMiao Xie 		trans->transid != root->last_trans);
194be20aa9dSChris Mason 
195be20aa9dSChris Mason 	level = btrfs_header_level(buf);
1965d4f98a2SYan Zheng 	if (level == 0)
1975d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
1985d4f98a2SYan Zheng 	else
1995d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
20031840ae1SZheng Yan 
2014d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
202cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
203cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
2045d4f98a2SYan Zheng 	if (IS_ERR(cow))
205be20aa9dSChris Mason 		return PTR_ERR(cow);
206be20aa9dSChris Mason 
20758e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
208be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
209be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2105d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2115d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2125d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2135d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2145d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2155d4f98a2SYan Zheng 	else
216be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
217be20aa9dSChris Mason 
218de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2192b82032cSYan Zheng 
220be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2215d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
222e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2235d4f98a2SYan Zheng 	else
224e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
225867ed321SJosef Bacik 	if (ret) {
22672c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
22772c9925fSFilipe Manana 		free_extent_buffer(cow);
228867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
229be20aa9dSChris Mason 		return ret;
230867ed321SJosef Bacik 	}
231be20aa9dSChris Mason 
232be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
233be20aa9dSChris Mason 	*cow_ret = cow;
234be20aa9dSChris Mason 	return 0;
235be20aa9dSChris Mason }
236be20aa9dSChris Mason 
237d352ac68SChris Mason /*
2385d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
2395d4f98a2SYan Zheng  */
2405d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
2415d4f98a2SYan Zheng 			      struct extent_buffer *buf)
2425d4f98a2SYan Zheng {
2435d4f98a2SYan Zheng 	/*
24492a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
24592a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
24692a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
2475d4f98a2SYan Zheng 	 */
24892a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2495d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
2505d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
2515d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
2525d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
2535d4f98a2SYan Zheng 		return 1;
254a79865c6SNikolay Borisov 
2555d4f98a2SYan Zheng 	return 0;
2565d4f98a2SYan Zheng }
2575d4f98a2SYan Zheng 
2585d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
2595d4f98a2SYan Zheng 				       struct btrfs_root *root,
2605d4f98a2SYan Zheng 				       struct extent_buffer *buf,
261f0486c68SYan, Zheng 				       struct extent_buffer *cow,
262f0486c68SYan, Zheng 				       int *last_ref)
2635d4f98a2SYan Zheng {
2640b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2655d4f98a2SYan Zheng 	u64 refs;
2665d4f98a2SYan Zheng 	u64 owner;
2675d4f98a2SYan Zheng 	u64 flags;
2685d4f98a2SYan Zheng 	u64 new_flags = 0;
2695d4f98a2SYan Zheng 	int ret;
2705d4f98a2SYan Zheng 
2715d4f98a2SYan Zheng 	/*
2725d4f98a2SYan Zheng 	 * Backrefs update rules:
2735d4f98a2SYan Zheng 	 *
2745d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
2755d4f98a2SYan Zheng 	 * allocated by tree relocation.
2765d4f98a2SYan Zheng 	 *
2775d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
2785d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
2795d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
2805d4f98a2SYan Zheng 	 *
2815d4f98a2SYan Zheng 	 * If a tree block is been relocating
2825d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
2835d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
2845d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
2855d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
2865d4f98a2SYan Zheng 	 */
2875d4f98a2SYan Zheng 
2885d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
2892ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
2903173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
2913173a18fSJosef Bacik 					       &refs, &flags);
292be1a5564SMark Fasheh 		if (ret)
293be1a5564SMark Fasheh 			return ret;
294e5df9573SMark Fasheh 		if (refs == 0) {
295e5df9573SMark Fasheh 			ret = -EROFS;
2960b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
297e5df9573SMark Fasheh 			return ret;
298e5df9573SMark Fasheh 		}
2995d4f98a2SYan Zheng 	} else {
3005d4f98a2SYan Zheng 		refs = 1;
3015d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
3025d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
3035d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
3045d4f98a2SYan Zheng 		else
3055d4f98a2SYan Zheng 			flags = 0;
3065d4f98a2SYan Zheng 	}
3075d4f98a2SYan Zheng 
3085d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
3095d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
3105d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
3115d4f98a2SYan Zheng 
3125d4f98a2SYan Zheng 	if (refs > 1) {
3135d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
3145d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
3155d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
316e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
317692826b2SJeff Mahoney 			if (ret)
318692826b2SJeff Mahoney 				return ret;
3195d4f98a2SYan Zheng 
3205d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3215d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
322e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
323692826b2SJeff Mahoney 				if (ret)
324692826b2SJeff Mahoney 					return ret;
325e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
326692826b2SJeff Mahoney 				if (ret)
327692826b2SJeff Mahoney 					return ret;
3285d4f98a2SYan Zheng 			}
3295d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
3305d4f98a2SYan Zheng 		} else {
3315d4f98a2SYan Zheng 
3325d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3335d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
334e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3355d4f98a2SYan Zheng 			else
336e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
337692826b2SJeff Mahoney 			if (ret)
338692826b2SJeff Mahoney 				return ret;
3395d4f98a2SYan Zheng 		}
3405d4f98a2SYan Zheng 		if (new_flags != 0) {
341b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
342b1c79e09SJosef Bacik 
34342c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
344b1c79e09SJosef Bacik 							  new_flags, level, 0);
345be1a5564SMark Fasheh 			if (ret)
346be1a5564SMark Fasheh 				return ret;
3475d4f98a2SYan Zheng 		}
3485d4f98a2SYan Zheng 	} else {
3495d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
3505d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3515d4f98a2SYan Zheng 			    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);
355692826b2SJeff Mahoney 			if (ret)
356692826b2SJeff Mahoney 				return ret;
357e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
358692826b2SJeff Mahoney 			if (ret)
359692826b2SJeff Mahoney 				return ret;
3605d4f98a2SYan Zheng 		}
3616a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
362f0486c68SYan, Zheng 		*last_ref = 1;
3635d4f98a2SYan Zheng 	}
3645d4f98a2SYan Zheng 	return 0;
3655d4f98a2SYan Zheng }
3665d4f98a2SYan Zheng 
3675d4f98a2SYan Zheng /*
368d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
369d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
370d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
371d397712bSChris Mason  * dirty again.
372d352ac68SChris Mason  *
373d352ac68SChris Mason  * search_start -- an allocation hint for the new block
374d352ac68SChris Mason  *
375d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
376d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
377d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
378d352ac68SChris Mason  */
379d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
3805f39d397SChris Mason 			     struct btrfs_root *root,
3815f39d397SChris Mason 			     struct extent_buffer *buf,
3825f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
3835f39d397SChris Mason 			     struct extent_buffer **cow_ret,
3849631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
3859631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
3866702ed49SChris Mason {
3870b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3885d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
3895f39d397SChris Mason 	struct extent_buffer *cow;
390be1a5564SMark Fasheh 	int level, ret;
391f0486c68SYan, Zheng 	int last_ref = 0;
392925baeddSChris Mason 	int unlock_orig = 0;
3930f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
3946702ed49SChris Mason 
395925baeddSChris Mason 	if (*cow_ret == buf)
396925baeddSChris Mason 		unlock_orig = 1;
397925baeddSChris Mason 
398b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
399925baeddSChris Mason 
40092a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
4010b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
40292a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
40327cdeb70SMiao Xie 		trans->transid != root->last_trans);
4045f39d397SChris Mason 
4057bb86316SChris Mason 	level = btrfs_header_level(buf);
40631840ae1SZheng Yan 
4075d4f98a2SYan Zheng 	if (level == 0)
4085d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
4095d4f98a2SYan Zheng 	else
4105d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
4115d4f98a2SYan Zheng 
4120f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
4135d4f98a2SYan Zheng 		parent_start = parent->start;
4145d4f98a2SYan Zheng 
41579bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
41679bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
41779bd3712SFilipe Manana 				     search_start, empty_size, nest);
4186702ed49SChris Mason 	if (IS_ERR(cow))
4196702ed49SChris Mason 		return PTR_ERR(cow);
4206702ed49SChris Mason 
421b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
422b4ce94deSChris Mason 
42358e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
424db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
4255f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
4265d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
4275d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
4285d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
4295d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
4305d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
4315d4f98a2SYan Zheng 	else
4325f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
4336702ed49SChris Mason 
434de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
4352b82032cSYan Zheng 
436be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
437b68dc2a9SMark Fasheh 	if (ret) {
438572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
439572c83acSJosef Bacik 		free_extent_buffer(cow);
44066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
441b68dc2a9SMark Fasheh 		return ret;
442b68dc2a9SMark Fasheh 	}
4431a40e23bSZheng Yan 
44492a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
44583d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
44693314e3bSZhaolei 		if (ret) {
447572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
448572c83acSJosef Bacik 			free_extent_buffer(cow);
44966642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
45083d4cfd4SJosef Bacik 			return ret;
45183d4cfd4SJosef Bacik 		}
45293314e3bSZhaolei 	}
4533fd0a558SYan, Zheng 
4546702ed49SChris Mason 	if (buf == root->node) {
455925baeddSChris Mason 		WARN_ON(parent && parent != buf);
4565d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4575d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4585d4f98a2SYan Zheng 			parent_start = buf->start;
459925baeddSChris Mason 
46067439dadSDavid Sterba 		atomic_inc(&cow->refs);
461406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
462d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
463240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
464925baeddSChris Mason 
465f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
4665581a51aSJan Schmidt 				      last_ref);
4675f39d397SChris Mason 		free_extent_buffer(buf);
4680b86a832SChris Mason 		add_root_to_dirty_list(root);
4696702ed49SChris Mason 	} else {
4705d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
471f3a84ccdSFilipe Manana 		btrfs_tree_mod_log_insert_key(parent, parent_slot,
472f3a84ccdSFilipe Manana 					      BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
4735f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
474db94535dSChris Mason 					cow->start);
47574493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
47674493f7aSChris Mason 					      trans->transid);
4776702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
4785de865eeSFilipe David Borba Manana 		if (last_ref) {
479f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
4805de865eeSFilipe David Borba Manana 			if (ret) {
481572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
482572c83acSJosef Bacik 				free_extent_buffer(cow);
48366642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
4845de865eeSFilipe David Borba Manana 				return ret;
4855de865eeSFilipe David Borba Manana 			}
4865de865eeSFilipe David Borba Manana 		}
487f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
4885581a51aSJan Schmidt 				      last_ref);
4896702ed49SChris Mason 	}
490925baeddSChris Mason 	if (unlock_orig)
491925baeddSChris Mason 		btrfs_tree_unlock(buf);
4923083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
4936702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
4946702ed49SChris Mason 	*cow_ret = cow;
4956702ed49SChris Mason 	return 0;
4966702ed49SChris Mason }
4976702ed49SChris Mason 
4985d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
4995d4f98a2SYan Zheng 				   struct btrfs_root *root,
5005d4f98a2SYan Zheng 				   struct extent_buffer *buf)
5015d4f98a2SYan Zheng {
502f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
503faa2dbf0SJosef Bacik 		return 0;
504fccb84c9SDavid Sterba 
505d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
506d1980131SDavid Sterba 	smp_mb__before_atomic();
507f1ebcc74SLiu Bo 
508f1ebcc74SLiu Bo 	/*
509f1ebcc74SLiu Bo 	 * We do not need to cow a block if
510f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
511f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
512f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
513f1ebcc74SLiu Bo 	 *
514f1ebcc74SLiu Bo 	 * What is forced COW:
51501327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
51652042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
517f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
518f1ebcc74SLiu Bo 	 */
5195d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
5205d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
5215d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
522f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
52327cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
5245d4f98a2SYan Zheng 		return 0;
5255d4f98a2SYan Zheng 	return 1;
5265d4f98a2SYan Zheng }
5275d4f98a2SYan Zheng 
528d352ac68SChris Mason /*
529d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
53001327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
531d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
532d352ac68SChris Mason  */
533d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
5345f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
5355f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
5369631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
5379631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
53802217ed2SChris Mason {
5390b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5406702ed49SChris Mason 	u64 search_start;
541f510cfecSChris Mason 	int ret;
542dc17ff8fSChris Mason 
54383354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
54483354f07SJosef Bacik 		btrfs_err(fs_info,
54583354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
54683354f07SJosef Bacik 
5470b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
54831b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
549c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
5500b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
55131b1a2bdSJulia Lawall 
5520b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
55331b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
5540b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
555dc17ff8fSChris Mason 
5565d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
55702217ed2SChris Mason 		*cow_ret = buf;
55802217ed2SChris Mason 		return 0;
55902217ed2SChris Mason 	}
560c487685dSChris Mason 
561ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
562b4ce94deSChris Mason 
563f616f5cdSQu Wenruo 	/*
564f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
565f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
566f616f5cdSQu Wenruo 	 *
567f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
568f616f5cdSQu Wenruo 	 */
569f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
570f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
5719631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
5721abe9b8aSliubo 
5731abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
5741abe9b8aSliubo 
575f510cfecSChris Mason 	return ret;
5762c90e5d6SChris Mason }
577f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
5786702ed49SChris Mason 
579d352ac68SChris Mason /*
580d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
581d352ac68SChris Mason  * node are actually close by
582d352ac68SChris Mason  */
5836b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
5846702ed49SChris Mason {
5856b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
5866702ed49SChris Mason 		return 1;
5876b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
5886702ed49SChris Mason 		return 1;
58902217ed2SChris Mason 	return 0;
59002217ed2SChris Mason }
59102217ed2SChris Mason 
592ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
593ce6ef5abSDavid Sterba 
594ce6ef5abSDavid Sterba /*
595ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
596ce6ef5abSDavid Sterba  * we can avoid the conversion.
597ce6ef5abSDavid Sterba  */
598ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
599ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
600ce6ef5abSDavid Sterba {
601ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
602ce6ef5abSDavid Sterba 
603ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
604ce6ef5abSDavid Sterba }
605ce6ef5abSDavid Sterba 
606ce6ef5abSDavid Sterba #else
607ce6ef5abSDavid Sterba 
608081e9573SChris Mason /*
609081e9573SChris Mason  * compare two keys in a memcmp fashion
610081e9573SChris Mason  */
611310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
612310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
613081e9573SChris Mason {
614081e9573SChris Mason 	struct btrfs_key k1;
615081e9573SChris Mason 
616081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
617081e9573SChris Mason 
61820736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
619081e9573SChris Mason }
620ce6ef5abSDavid Sterba #endif
621081e9573SChris Mason 
622f3465ca4SJosef Bacik /*
623f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
624f3465ca4SJosef Bacik  */
625e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
626f3465ca4SJosef Bacik {
627f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
628f3465ca4SJosef Bacik 		return 1;
629f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
630f3465ca4SJosef Bacik 		return -1;
631f3465ca4SJosef Bacik 	if (k1->type > k2->type)
632f3465ca4SJosef Bacik 		return 1;
633f3465ca4SJosef Bacik 	if (k1->type < k2->type)
634f3465ca4SJosef Bacik 		return -1;
635f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
636f3465ca4SJosef Bacik 		return 1;
637f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
638f3465ca4SJosef Bacik 		return -1;
639f3465ca4SJosef Bacik 	return 0;
640f3465ca4SJosef Bacik }
641081e9573SChris Mason 
642d352ac68SChris Mason /*
643d352ac68SChris Mason  * this is used by the defrag code to go through all the
644d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
645d352ac68SChris Mason  * disk order is close to key order
646d352ac68SChris Mason  */
6476702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
6485f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
649de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
650a6b6e75eSChris Mason 		       struct btrfs_key *progress)
6516702ed49SChris Mason {
6520b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6536b80053dSChris Mason 	struct extent_buffer *cur;
6546702ed49SChris Mason 	u64 blocknr;
655e9d0b13bSChris Mason 	u64 search_start = *last_ret;
656e9d0b13bSChris Mason 	u64 last_block = 0;
6576702ed49SChris Mason 	u64 other;
6586702ed49SChris Mason 	u32 parent_nritems;
6596702ed49SChris Mason 	int end_slot;
6606702ed49SChris Mason 	int i;
6616702ed49SChris Mason 	int err = 0;
6626b80053dSChris Mason 	u32 blocksize;
663081e9573SChris Mason 	int progress_passed = 0;
664081e9573SChris Mason 	struct btrfs_disk_key disk_key;
6656702ed49SChris Mason 
6660b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
6670b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
66886479a04SChris Mason 
6696b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
6700b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
6715dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
6726702ed49SChris Mason 
6735dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
6746702ed49SChris Mason 		return 0;
6756702ed49SChris Mason 
6765dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
6776702ed49SChris Mason 		int close = 1;
678a6b6e75eSChris Mason 
679081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
680081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
681081e9573SChris Mason 			continue;
682081e9573SChris Mason 
683081e9573SChris Mason 		progress_passed = 1;
6846b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
685e9d0b13bSChris Mason 		if (last_block == 0)
686e9d0b13bSChris Mason 			last_block = blocknr;
6875708b959SChris Mason 
6886702ed49SChris Mason 		if (i > 0) {
6896b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
6906b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
6916702ed49SChris Mason 		}
6925dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
6936b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
6946b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
6956702ed49SChris Mason 		}
696e9d0b13bSChris Mason 		if (close) {
697e9d0b13bSChris Mason 			last_block = blocknr;
6986702ed49SChris Mason 			continue;
699e9d0b13bSChris Mason 		}
7006702ed49SChris Mason 
701206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
702206983b7SJosef Bacik 		if (IS_ERR(cur))
70364c043deSLiu Bo 			return PTR_ERR(cur);
704e9d0b13bSChris Mason 		if (search_start == 0)
7056b80053dSChris Mason 			search_start = last_block;
706e9d0b13bSChris Mason 
707e7a84565SChris Mason 		btrfs_tree_lock(cur);
7086b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
709e7a84565SChris Mason 					&cur, search_start,
7106b80053dSChris Mason 					min(16 * blocksize,
7119631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
7129631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
713252c38f0SYan 		if (err) {
714e7a84565SChris Mason 			btrfs_tree_unlock(cur);
7156b80053dSChris Mason 			free_extent_buffer(cur);
7166702ed49SChris Mason 			break;
717252c38f0SYan 		}
718e7a84565SChris Mason 		search_start = cur->start;
719e7a84565SChris Mason 		last_block = cur->start;
720f2183bdeSChris Mason 		*last_ret = search_start;
721e7a84565SChris Mason 		btrfs_tree_unlock(cur);
722e7a84565SChris Mason 		free_extent_buffer(cur);
7236702ed49SChris Mason 	}
7246702ed49SChris Mason 	return err;
7256702ed49SChris Mason }
7266702ed49SChris Mason 
72774123bd7SChris Mason /*
7285f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
729*67d5e289SMarcos Paulo de Souza  * and they are item_size apart.
7305f39d397SChris Mason  *
73174123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
73274123bd7SChris Mason  * the place where you would insert key if it is not found in
73374123bd7SChris Mason  * the array.
73474123bd7SChris Mason  *
735*67d5e289SMarcos Paulo de Souza  * Slot may point to total number of items if the key is bigger than
736*67d5e289SMarcos Paulo de Souza  * all of the keys
73774123bd7SChris Mason  */
738e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
739310712b2SOmar Sandoval 				       unsigned long p, int item_size,
740*67d5e289SMarcos Paulo de Souza 				       const struct btrfs_key *key, int *slot)
741be0e5c09SChris Mason {
742be0e5c09SChris Mason 	int low = 0;
743*67d5e289SMarcos Paulo de Souza 	int high = btrfs_header_nritems(eb);
744be0e5c09SChris Mason 	int ret;
7455cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
746be0e5c09SChris Mason 
7475e24e9afSLiu Bo 	if (low > high) {
7485e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
7495e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
7505e24e9afSLiu Bo 			  __func__, low, high, eb->start,
7515e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
7525e24e9afSLiu Bo 		return -EINVAL;
7535e24e9afSLiu Bo 	}
7545e24e9afSLiu Bo 
755be0e5c09SChris Mason 	while (low < high) {
7565cd17f34SDavid Sterba 		unsigned long oip;
7575cd17f34SDavid Sterba 		unsigned long offset;
7585cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
7595cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
7605cd17f34SDavid Sterba 		int mid;
7615cd17f34SDavid Sterba 
762be0e5c09SChris Mason 		mid = (low + high) / 2;
7635f39d397SChris Mason 		offset = p + mid * item_size;
7645cd17f34SDavid Sterba 		oip = offset_in_page(offset);
7655f39d397SChris Mason 
7665cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
767884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
7685cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
769934d375bSChris Mason 
770884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
7715cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
7725cd17f34SDavid Sterba 		} else {
7735cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
7745f39d397SChris Mason 			tmp = &unaligned;
775479965d6SChris Mason 		}
776479965d6SChris Mason 
777be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
778be0e5c09SChris Mason 
779be0e5c09SChris Mason 		if (ret < 0)
780be0e5c09SChris Mason 			low = mid + 1;
781be0e5c09SChris Mason 		else if (ret > 0)
782be0e5c09SChris Mason 			high = mid;
783be0e5c09SChris Mason 		else {
784be0e5c09SChris Mason 			*slot = mid;
785be0e5c09SChris Mason 			return 0;
786be0e5c09SChris Mason 		}
787be0e5c09SChris Mason 	}
788be0e5c09SChris Mason 	*slot = low;
789be0e5c09SChris Mason 	return 1;
790be0e5c09SChris Mason }
791be0e5c09SChris Mason 
79297571fd0SChris Mason /*
79397571fd0SChris Mason  * simple bin_search frontend that does the right thing for
79497571fd0SChris Mason  * leaves vs nodes
79597571fd0SChris Mason  */
796a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
797e3b83361SQu Wenruo 		     int *slot)
798be0e5c09SChris Mason {
799e3b83361SQu Wenruo 	if (btrfs_header_level(eb) == 0)
8005f39d397SChris Mason 		return generic_bin_search(eb,
8015f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
802*67d5e289SMarcos Paulo de Souza 					  sizeof(struct btrfs_item), key, slot);
803f775738fSWang Sheng-Hui 	else
8045f39d397SChris Mason 		return generic_bin_search(eb,
8055f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
806*67d5e289SMarcos Paulo de Souza 					  sizeof(struct btrfs_key_ptr), key, slot);
807be0e5c09SChris Mason }
808be0e5c09SChris Mason 
809f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
810f0486c68SYan, Zheng {
811f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
812f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
813f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
814f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
815f0486c68SYan, Zheng }
816f0486c68SYan, Zheng 
817f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
818f0486c68SYan, Zheng {
819f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
820f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
821f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
822f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
823f0486c68SYan, Zheng }
824f0486c68SYan, Zheng 
825d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
826d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
827d352ac68SChris Mason  */
8284b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
8294b231ae4SDavid Sterba 					   int slot)
830bb803951SChris Mason {
831ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
832416bc658SJosef Bacik 	struct extent_buffer *eb;
833581c1760SQu Wenruo 	struct btrfs_key first_key;
834416bc658SJosef Bacik 
835fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
836fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
837ca7a79adSChris Mason 
838ca7a79adSChris Mason 	BUG_ON(level == 0);
839ca7a79adSChris Mason 
840581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
841d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
8421b7ec85eSJosef Bacik 			     btrfs_header_owner(parent),
843581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
844581c1760SQu Wenruo 			     level - 1, &first_key);
845fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
846416bc658SJosef Bacik 		free_extent_buffer(eb);
847fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
848416bc658SJosef Bacik 	}
849416bc658SJosef Bacik 
850416bc658SJosef Bacik 	return eb;
851bb803951SChris Mason }
852bb803951SChris Mason 
853d352ac68SChris Mason /*
854d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
855d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
856d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
857d352ac68SChris Mason  */
858e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
85998ed5174SChris Mason 			 struct btrfs_root *root,
86098ed5174SChris Mason 			 struct btrfs_path *path, int level)
861bb803951SChris Mason {
8620b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8635f39d397SChris Mason 	struct extent_buffer *right = NULL;
8645f39d397SChris Mason 	struct extent_buffer *mid;
8655f39d397SChris Mason 	struct extent_buffer *left = NULL;
8665f39d397SChris Mason 	struct extent_buffer *parent = NULL;
867bb803951SChris Mason 	int ret = 0;
868bb803951SChris Mason 	int wret;
869bb803951SChris Mason 	int pslot;
870bb803951SChris Mason 	int orig_slot = path->slots[level];
87179f95c82SChris Mason 	u64 orig_ptr;
872bb803951SChris Mason 
87398e6b1ebSLiu Bo 	ASSERT(level > 0);
874bb803951SChris Mason 
8755f39d397SChris Mason 	mid = path->nodes[level];
876b4ce94deSChris Mason 
877ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
8787bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
8797bb86316SChris Mason 
8801d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
88179f95c82SChris Mason 
882a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
8835f39d397SChris Mason 		parent = path->nodes[level + 1];
884bb803951SChris Mason 		pslot = path->slots[level + 1];
885a05a9bb1SLi Zefan 	}
886bb803951SChris Mason 
88740689478SChris Mason 	/*
88840689478SChris Mason 	 * deal with the case where there is only one pointer in the root
88940689478SChris Mason 	 * by promoting the node below to a root
89040689478SChris Mason 	 */
8915f39d397SChris Mason 	if (!parent) {
8925f39d397SChris Mason 		struct extent_buffer *child;
893bb803951SChris Mason 
8945f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
895bb803951SChris Mason 			return 0;
896bb803951SChris Mason 
897bb803951SChris Mason 		/* promote the child to a root */
8984b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
899fb770ae4SLiu Bo 		if (IS_ERR(child)) {
900fb770ae4SLiu Bo 			ret = PTR_ERR(child);
9010b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
902305a26afSMark Fasheh 			goto enospc;
903305a26afSMark Fasheh 		}
904305a26afSMark Fasheh 
905925baeddSChris Mason 		btrfs_tree_lock(child);
9069631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
9079631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
908f0486c68SYan, Zheng 		if (ret) {
909f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
910f0486c68SYan, Zheng 			free_extent_buffer(child);
911f0486c68SYan, Zheng 			goto enospc;
912f0486c68SYan, Zheng 		}
9132f375ab9SYan 
914406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
915d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
916240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
917925baeddSChris Mason 
9180b86a832SChris Mason 		add_root_to_dirty_list(root);
919925baeddSChris Mason 		btrfs_tree_unlock(child);
920b4ce94deSChris Mason 
921925baeddSChris Mason 		path->locks[level] = 0;
922bb803951SChris Mason 		path->nodes[level] = NULL;
9236a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
924925baeddSChris Mason 		btrfs_tree_unlock(mid);
925bb803951SChris Mason 		/* once for the path */
9265f39d397SChris Mason 		free_extent_buffer(mid);
927f0486c68SYan, Zheng 
928f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
9295581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
930bb803951SChris Mason 		/* once for the root ptr */
9313083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
932f0486c68SYan, Zheng 		return 0;
933bb803951SChris Mason 	}
9345f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
9350b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
936bb803951SChris Mason 		return 0;
937bb803951SChris Mason 
9384b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
939fb770ae4SLiu Bo 	if (IS_ERR(left))
940fb770ae4SLiu Bo 		left = NULL;
941fb770ae4SLiu Bo 
9425f39d397SChris Mason 	if (left) {
943bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
9445f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
9459631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
946bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
94754aa1f4dSChris Mason 		if (wret) {
94854aa1f4dSChris Mason 			ret = wret;
94954aa1f4dSChris Mason 			goto enospc;
95054aa1f4dSChris Mason 		}
9512cc58cf2SChris Mason 	}
952fb770ae4SLiu Bo 
9534b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
954fb770ae4SLiu Bo 	if (IS_ERR(right))
955fb770ae4SLiu Bo 		right = NULL;
956fb770ae4SLiu Bo 
9575f39d397SChris Mason 	if (right) {
958bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
9595f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
9609631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
961bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
9622cc58cf2SChris Mason 		if (wret) {
9632cc58cf2SChris Mason 			ret = wret;
9642cc58cf2SChris Mason 			goto enospc;
9652cc58cf2SChris Mason 		}
9662cc58cf2SChris Mason 	}
9672cc58cf2SChris Mason 
9682cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
9695f39d397SChris Mason 	if (left) {
9705f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
971d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
97279f95c82SChris Mason 		if (wret < 0)
97379f95c82SChris Mason 			ret = wret;
974bb803951SChris Mason 	}
97579f95c82SChris Mason 
97679f95c82SChris Mason 	/*
97779f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
97879f95c82SChris Mason 	 */
9795f39d397SChris Mason 	if (right) {
980d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
98154aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
98279f95c82SChris Mason 			ret = wret;
9835f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
9846a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
985925baeddSChris Mason 			btrfs_tree_unlock(right);
986afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
987f0486c68SYan, Zheng 			root_sub_used(root, right->len);
9885581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
9893083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
990f0486c68SYan, Zheng 			right = NULL;
991bb803951SChris Mason 		} else {
9925f39d397SChris Mason 			struct btrfs_disk_key right_key;
9935f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
994f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
995f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
9960e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
9975f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
9985f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
999bb803951SChris Mason 		}
1000bb803951SChris Mason 	}
10015f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
100279f95c82SChris Mason 		/*
100379f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
100479f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
100579f95c82SChris Mason 		 * could try to delete the only pointer in this node.
100679f95c82SChris Mason 		 * So, pull some keys from the left.
100779f95c82SChris Mason 		 * There has to be a left pointer at this point because
100879f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
100979f95c82SChris Mason 		 * right
101079f95c82SChris Mason 		 */
1011305a26afSMark Fasheh 		if (!left) {
1012305a26afSMark Fasheh 			ret = -EROFS;
10130b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1014305a26afSMark Fasheh 			goto enospc;
1015305a26afSMark Fasheh 		}
101655d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
101754aa1f4dSChris Mason 		if (wret < 0) {
101879f95c82SChris Mason 			ret = wret;
101954aa1f4dSChris Mason 			goto enospc;
102054aa1f4dSChris Mason 		}
1021bce4eae9SChris Mason 		if (wret == 1) {
1022d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1023bce4eae9SChris Mason 			if (wret < 0)
1024bce4eae9SChris Mason 				ret = wret;
1025bce4eae9SChris Mason 		}
102679f95c82SChris Mason 		BUG_ON(wret == 1);
102779f95c82SChris Mason 	}
10285f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
10296a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1030925baeddSChris Mason 		btrfs_tree_unlock(mid);
1031afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1032f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10335581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
10343083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1035f0486c68SYan, Zheng 		mid = NULL;
103679f95c82SChris Mason 	} else {
103779f95c82SChris Mason 		/* update the parent key to reflect our changes */
10385f39d397SChris Mason 		struct btrfs_disk_key mid_key;
10395f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1040f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1041f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
10420e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
10435f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
10445f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
104579f95c82SChris Mason 	}
1046bb803951SChris Mason 
104779f95c82SChris Mason 	/* update the path */
10485f39d397SChris Mason 	if (left) {
10495f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
105067439dadSDavid Sterba 			atomic_inc(&left->refs);
1051925baeddSChris Mason 			/* left was locked after cow */
10525f39d397SChris Mason 			path->nodes[level] = left;
1053bb803951SChris Mason 			path->slots[level + 1] -= 1;
1054bb803951SChris Mason 			path->slots[level] = orig_slot;
1055925baeddSChris Mason 			if (mid) {
1056925baeddSChris Mason 				btrfs_tree_unlock(mid);
10575f39d397SChris Mason 				free_extent_buffer(mid);
1058925baeddSChris Mason 			}
1059bb803951SChris Mason 		} else {
10605f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1061bb803951SChris Mason 			path->slots[level] = orig_slot;
1062bb803951SChris Mason 		}
1063bb803951SChris Mason 	}
106479f95c82SChris Mason 	/* double check we haven't messed things up */
1065e20d96d6SChris Mason 	if (orig_ptr !=
10665f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
106779f95c82SChris Mason 		BUG();
106854aa1f4dSChris Mason enospc:
1069925baeddSChris Mason 	if (right) {
1070925baeddSChris Mason 		btrfs_tree_unlock(right);
10715f39d397SChris Mason 		free_extent_buffer(right);
1072925baeddSChris Mason 	}
1073925baeddSChris Mason 	if (left) {
1074925baeddSChris Mason 		if (path->nodes[level] != left)
1075925baeddSChris Mason 			btrfs_tree_unlock(left);
10765f39d397SChris Mason 		free_extent_buffer(left);
1077925baeddSChris Mason 	}
1078bb803951SChris Mason 	return ret;
1079bb803951SChris Mason }
1080bb803951SChris Mason 
1081d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1082d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1083d352ac68SChris Mason  * have to be pessimistic.
1084d352ac68SChris Mason  */
1085d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1086e66f709bSChris Mason 					  struct btrfs_root *root,
1087e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1088e66f709bSChris Mason {
10890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10905f39d397SChris Mason 	struct extent_buffer *right = NULL;
10915f39d397SChris Mason 	struct extent_buffer *mid;
10925f39d397SChris Mason 	struct extent_buffer *left = NULL;
10935f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1094e66f709bSChris Mason 	int ret = 0;
1095e66f709bSChris Mason 	int wret;
1096e66f709bSChris Mason 	int pslot;
1097e66f709bSChris Mason 	int orig_slot = path->slots[level];
1098e66f709bSChris Mason 
1099e66f709bSChris Mason 	if (level == 0)
1100e66f709bSChris Mason 		return 1;
1101e66f709bSChris Mason 
11025f39d397SChris Mason 	mid = path->nodes[level];
11037bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1104e66f709bSChris Mason 
1105a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
11065f39d397SChris Mason 		parent = path->nodes[level + 1];
1107e66f709bSChris Mason 		pslot = path->slots[level + 1];
1108a05a9bb1SLi Zefan 	}
1109e66f709bSChris Mason 
11105f39d397SChris Mason 	if (!parent)
1111e66f709bSChris Mason 		return 1;
1112e66f709bSChris Mason 
11134b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1114fb770ae4SLiu Bo 	if (IS_ERR(left))
1115fb770ae4SLiu Bo 		left = NULL;
1116e66f709bSChris Mason 
1117e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
11185f39d397SChris Mason 	if (left) {
1119e66f709bSChris Mason 		u32 left_nr;
1120925baeddSChris Mason 
1121bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1122b4ce94deSChris Mason 
11235f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
11240b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
112533ade1f8SChris Mason 			wret = 1;
112633ade1f8SChris Mason 		} else {
11275f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
11289631e4ccSJosef Bacik 					      pslot - 1, &left,
1129bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
113054aa1f4dSChris Mason 			if (ret)
113154aa1f4dSChris Mason 				wret = 1;
113254aa1f4dSChris Mason 			else {
1133d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
113454aa1f4dSChris Mason 			}
113533ade1f8SChris Mason 		}
1136e66f709bSChris Mason 		if (wret < 0)
1137e66f709bSChris Mason 			ret = wret;
1138e66f709bSChris Mason 		if (wret == 0) {
11395f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1140e66f709bSChris Mason 			orig_slot += left_nr;
11415f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1142f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1143f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
11440e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11455f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
11465f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
11475f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
11485f39d397SChris Mason 				path->nodes[level] = left;
1149e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1150e66f709bSChris Mason 				path->slots[level] = orig_slot;
1151925baeddSChris Mason 				btrfs_tree_unlock(mid);
11525f39d397SChris Mason 				free_extent_buffer(mid);
1153e66f709bSChris Mason 			} else {
1154e66f709bSChris Mason 				orig_slot -=
11555f39d397SChris Mason 					btrfs_header_nritems(left);
1156e66f709bSChris Mason 				path->slots[level] = orig_slot;
1157925baeddSChris Mason 				btrfs_tree_unlock(left);
11585f39d397SChris Mason 				free_extent_buffer(left);
1159e66f709bSChris Mason 			}
1160e66f709bSChris Mason 			return 0;
1161e66f709bSChris Mason 		}
1162925baeddSChris Mason 		btrfs_tree_unlock(left);
11635f39d397SChris Mason 		free_extent_buffer(left);
1164e66f709bSChris Mason 	}
11654b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1166fb770ae4SLiu Bo 	if (IS_ERR(right))
1167fb770ae4SLiu Bo 		right = NULL;
1168e66f709bSChris Mason 
1169e66f709bSChris Mason 	/*
1170e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1171e66f709bSChris Mason 	 */
11725f39d397SChris Mason 	if (right) {
117333ade1f8SChris Mason 		u32 right_nr;
1174b4ce94deSChris Mason 
1175bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1176b4ce94deSChris Mason 
11775f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
11780b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
117933ade1f8SChris Mason 			wret = 1;
118033ade1f8SChris Mason 		} else {
11815f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
11825f39d397SChris Mason 					      parent, pslot + 1,
1183bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
118454aa1f4dSChris Mason 			if (ret)
118554aa1f4dSChris Mason 				wret = 1;
118654aa1f4dSChris Mason 			else {
118755d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
118833ade1f8SChris Mason 			}
118954aa1f4dSChris Mason 		}
1190e66f709bSChris Mason 		if (wret < 0)
1191e66f709bSChris Mason 			ret = wret;
1192e66f709bSChris Mason 		if (wret == 0) {
11935f39d397SChris Mason 			struct btrfs_disk_key disk_key;
11945f39d397SChris Mason 
11955f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1196f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1197f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
11980e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11995f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
12005f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12015f39d397SChris Mason 
12025f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
12035f39d397SChris Mason 				path->nodes[level] = right;
1204e66f709bSChris Mason 				path->slots[level + 1] += 1;
1205e66f709bSChris Mason 				path->slots[level] = orig_slot -
12065f39d397SChris Mason 					btrfs_header_nritems(mid);
1207925baeddSChris Mason 				btrfs_tree_unlock(mid);
12085f39d397SChris Mason 				free_extent_buffer(mid);
1209e66f709bSChris Mason 			} else {
1210925baeddSChris Mason 				btrfs_tree_unlock(right);
12115f39d397SChris Mason 				free_extent_buffer(right);
1212e66f709bSChris Mason 			}
1213e66f709bSChris Mason 			return 0;
1214e66f709bSChris Mason 		}
1215925baeddSChris Mason 		btrfs_tree_unlock(right);
12165f39d397SChris Mason 		free_extent_buffer(right);
1217e66f709bSChris Mason 	}
1218e66f709bSChris Mason 	return 1;
1219e66f709bSChris Mason }
1220e66f709bSChris Mason 
122174123bd7SChris Mason /*
1222d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1223d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
12243c69faecSChris Mason  */
12252ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1226e02119d5SChris Mason 			     struct btrfs_path *path,
122701f46658SChris Mason 			     int level, int slot, u64 objectid)
12283c69faecSChris Mason {
12295f39d397SChris Mason 	struct extent_buffer *node;
123001f46658SChris Mason 	struct btrfs_disk_key disk_key;
12313c69faecSChris Mason 	u32 nritems;
12323c69faecSChris Mason 	u64 search;
1233a7175319SChris Mason 	u64 target;
12346b80053dSChris Mason 	u64 nread = 0;
1235ace75066SFilipe Manana 	u64 nread_max;
12365f39d397SChris Mason 	struct extent_buffer *eb;
12376b80053dSChris Mason 	u32 nr;
12386b80053dSChris Mason 	u32 blocksize;
12396b80053dSChris Mason 	u32 nscan = 0;
1240db94535dSChris Mason 
1241ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
12423c69faecSChris Mason 		return;
12433c69faecSChris Mason 
12446702ed49SChris Mason 	if (!path->nodes[level])
12456702ed49SChris Mason 		return;
12466702ed49SChris Mason 
12475f39d397SChris Mason 	node = path->nodes[level];
1248925baeddSChris Mason 
1249ace75066SFilipe Manana 	/*
1250ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1251ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1252ace75066SFilipe Manana 	 * much IO at once (possibly random).
1253ace75066SFilipe Manana 	 */
1254ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1255ace75066SFilipe Manana 		if (level > 1)
1256ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1257ace75066SFilipe Manana 		else
1258ace75066SFilipe Manana 			nread_max = SZ_128K;
1259ace75066SFilipe Manana 	} else {
1260ace75066SFilipe Manana 		nread_max = SZ_64K;
1261ace75066SFilipe Manana 	}
1262ace75066SFilipe Manana 
12633c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
12640b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
12650b246afaSJeff Mahoney 	eb = find_extent_buffer(fs_info, search);
12665f39d397SChris Mason 	if (eb) {
12675f39d397SChris Mason 		free_extent_buffer(eb);
12683c69faecSChris Mason 		return;
12693c69faecSChris Mason 	}
12703c69faecSChris Mason 
1271a7175319SChris Mason 	target = search;
12726b80053dSChris Mason 
12735f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
12746b80053dSChris Mason 	nr = slot;
127525b8b936SJosef Bacik 
12763c69faecSChris Mason 	while (1) {
1277e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
12786b80053dSChris Mason 			if (nr == 0)
12793c69faecSChris Mason 				break;
12806b80053dSChris Mason 			nr--;
1281ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1282ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
12836b80053dSChris Mason 			nr++;
12846b80053dSChris Mason 			if (nr >= nritems)
12856b80053dSChris Mason 				break;
12863c69faecSChris Mason 		}
1287e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
128801f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
128901f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
129001f46658SChris Mason 				break;
129101f46658SChris Mason 		}
12926b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1293ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1294ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1295a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1296bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
12976b80053dSChris Mason 			nread += blocksize;
12983c69faecSChris Mason 		}
12996b80053dSChris Mason 		nscan++;
1300ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
13016b80053dSChris Mason 			break;
13023c69faecSChris Mason 	}
13033c69faecSChris Mason }
1304925baeddSChris Mason 
1305bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1306b4ce94deSChris Mason {
1307bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1308b4ce94deSChris Mason 	int slot;
1309b4ce94deSChris Mason 	int nritems;
1310b4ce94deSChris Mason 
13118c594ea8SChris Mason 	parent = path->nodes[level + 1];
1312b4ce94deSChris Mason 	if (!parent)
13130b08851fSJosef Bacik 		return;
1314b4ce94deSChris Mason 
1315b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
13168c594ea8SChris Mason 	slot = path->slots[level + 1];
1317b4ce94deSChris Mason 
1318bfb484d9SJosef Bacik 	if (slot > 0)
1319bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1320bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1321bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1322b4ce94deSChris Mason }
1323b4ce94deSChris Mason 
1324b4ce94deSChris Mason 
1325b4ce94deSChris Mason /*
1326d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1327d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1328d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1329d397712bSChris Mason  * tree.
1330d352ac68SChris Mason  *
1331d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1332d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1333d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1334d352ac68SChris Mason  *
1335d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1336d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1337d352ac68SChris Mason  */
1338e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1339f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1340f7c79f30SChris Mason 			       int *write_lock_level)
1341925baeddSChris Mason {
1342925baeddSChris Mason 	int i;
1343925baeddSChris Mason 	int skip_level = level;
1344051e1b9fSChris Mason 	int no_skips = 0;
1345925baeddSChris Mason 	struct extent_buffer *t;
1346925baeddSChris Mason 
1347925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1348925baeddSChris Mason 		if (!path->nodes[i])
1349925baeddSChris Mason 			break;
1350925baeddSChris Mason 		if (!path->locks[i])
1351925baeddSChris Mason 			break;
1352051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
1353925baeddSChris Mason 			skip_level = i + 1;
1354925baeddSChris Mason 			continue;
1355925baeddSChris Mason 		}
1356051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
1357925baeddSChris Mason 			u32 nritems;
1358925baeddSChris Mason 			t = path->nodes[i];
1359925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
1360051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
1361925baeddSChris Mason 				skip_level = i + 1;
1362925baeddSChris Mason 				continue;
1363925baeddSChris Mason 			}
1364925baeddSChris Mason 		}
1365051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
1366051e1b9fSChris Mason 			no_skips = 1;
1367051e1b9fSChris Mason 
1368925baeddSChris Mason 		t = path->nodes[i];
1369d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1370bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
1371925baeddSChris Mason 			path->locks[i] = 0;
1372f7c79f30SChris Mason 			if (write_lock_level &&
1373f7c79f30SChris Mason 			    i > min_write_lock_level &&
1374f7c79f30SChris Mason 			    i <= *write_lock_level) {
1375f7c79f30SChris Mason 				*write_lock_level = i - 1;
1376f7c79f30SChris Mason 			}
1377925baeddSChris Mason 		}
1378925baeddSChris Mason 	}
1379925baeddSChris Mason }
1380925baeddSChris Mason 
13813c69faecSChris Mason /*
1382c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
1383c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
1384c8c42864SChris Mason  * we return zero and the path is unchanged.
1385c8c42864SChris Mason  *
1386c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
1387c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
1388c8c42864SChris Mason  */
1389c8c42864SChris Mason static int
1390d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1391c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1392cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1393c8c42864SChris Mason {
13940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1395c8c42864SChris Mason 	u64 blocknr;
1396c8c42864SChris Mason 	u64 gen;
1397c8c42864SChris Mason 	struct extent_buffer *tmp;
1398581c1760SQu Wenruo 	struct btrfs_key first_key;
139976a05b35SChris Mason 	int ret;
1400581c1760SQu Wenruo 	int parent_level;
1401c8c42864SChris Mason 
1402213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1403213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1404213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1405213ff4b7SNikolay Borisov 	btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
1406c8c42864SChris Mason 
14070b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1408cb44921aSChris Mason 	if (tmp) {
1409ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1410ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1411ace75066SFilipe Manana 
1412b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1413b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1414448de471SQu Wenruo 			/*
1415448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1416448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1417448de471SQu Wenruo 			 * parents (shared tree blocks).
1418448de471SQu Wenruo 			 */
1419e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1420448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
1421448de471SQu Wenruo 				free_extent_buffer(tmp);
1422448de471SQu Wenruo 				return -EUCLEAN;
1423448de471SQu Wenruo 			}
1424c8c42864SChris Mason 			*eb_ret = tmp;
1425c8c42864SChris Mason 			return 0;
1426c8c42864SChris Mason 		}
1427bdf7c00eSJosef Bacik 
1428b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
1429581c1760SQu Wenruo 		ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
1430bdf7c00eSJosef Bacik 		if (!ret) {
1431cb44921aSChris Mason 			*eb_ret = tmp;
1432cb44921aSChris Mason 			return 0;
1433cb44921aSChris Mason 		}
1434cb44921aSChris Mason 		free_extent_buffer(tmp);
1435b3b4aa74SDavid Sterba 		btrfs_release_path(p);
1436cb44921aSChris Mason 		return -EIO;
1437cb44921aSChris Mason 	}
1438c8c42864SChris Mason 
1439c8c42864SChris Mason 	/*
1440c8c42864SChris Mason 	 * reduce lock contention at high levels
1441c8c42864SChris Mason 	 * of the btree by dropping locks before
144276a05b35SChris Mason 	 * we read.  Don't release the lock on the current
144376a05b35SChris Mason 	 * level because we need to walk this node to figure
144476a05b35SChris Mason 	 * out which blocks to read.
1445c8c42864SChris Mason 	 */
14468c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
14478c594ea8SChris Mason 
1448e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
14492ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1450c8c42864SChris Mason 
145176a05b35SChris Mason 	ret = -EAGAIN;
14521b7ec85eSJosef Bacik 	tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
14531b7ec85eSJosef Bacik 			      gen, parent_level - 1, &first_key);
145464c043deSLiu Bo 	if (!IS_ERR(tmp)) {
145576a05b35SChris Mason 		/*
145676a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
145776a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
145876a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
145976a05b35SChris Mason 		 * on our EAGAINs.
146076a05b35SChris Mason 		 */
1461e6a1d6fdSLiu Bo 		if (!extent_buffer_uptodate(tmp))
146276a05b35SChris Mason 			ret = -EIO;
1463c8c42864SChris Mason 		free_extent_buffer(tmp);
1464c871b0f2SLiu Bo 	} else {
1465c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
146676a05b35SChris Mason 	}
146702a3307aSLiu Bo 
146802a3307aSLiu Bo 	btrfs_release_path(p);
146976a05b35SChris Mason 	return ret;
1470c8c42864SChris Mason }
1471c8c42864SChris Mason 
1472c8c42864SChris Mason /*
1473c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1474c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1475c8c42864SChris Mason  * the ins_len.
1476c8c42864SChris Mason  *
1477c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1478c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1479c8c42864SChris Mason  * start over
1480c8c42864SChris Mason  */
1481c8c42864SChris Mason static int
1482c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1483c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1484bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1485bd681513SChris Mason 		       int *write_lock_level)
1486c8c42864SChris Mason {
14870b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
148895b982deSNikolay Borisov 	int ret = 0;
14890b246afaSJeff Mahoney 
1490c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
14910b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1492c8c42864SChris Mason 
1493bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1494bd681513SChris Mason 			*write_lock_level = level + 1;
1495bd681513SChris Mason 			btrfs_release_path(p);
149695b982deSNikolay Borisov 			return -EAGAIN;
1497bd681513SChris Mason 		}
1498bd681513SChris Mason 
1499bfb484d9SJosef Bacik 		reada_for_balance(p, level);
150095b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1501c8c42864SChris Mason 
1502c8c42864SChris Mason 		b = p->nodes[level];
1503c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
15040b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1505c8c42864SChris Mason 
1506bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1507bd681513SChris Mason 			*write_lock_level = level + 1;
1508bd681513SChris Mason 			btrfs_release_path(p);
150995b982deSNikolay Borisov 			return -EAGAIN;
1510bd681513SChris Mason 		}
1511bd681513SChris Mason 
1512bfb484d9SJosef Bacik 		reada_for_balance(p, level);
151395b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
151495b982deSNikolay Borisov 		if (ret)
151595b982deSNikolay Borisov 			return ret;
1516c8c42864SChris Mason 
1517c8c42864SChris Mason 		b = p->nodes[level];
1518c8c42864SChris Mason 		if (!b) {
1519b3b4aa74SDavid Sterba 			btrfs_release_path(p);
152095b982deSNikolay Borisov 			return -EAGAIN;
1521c8c42864SChris Mason 		}
1522c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1523c8c42864SChris Mason 	}
1524c8c42864SChris Mason 	return ret;
1525c8c42864SChris Mason }
1526c8c42864SChris Mason 
1527381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1528e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1529e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1530e33d5c3dSKelley Nielsen {
1531e33d5c3dSKelley Nielsen 	int ret;
1532e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1533e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1534381cf658SDavid Sterba 
1535381cf658SDavid Sterba 	ASSERT(path);
15361d4c08e0SDavid Sterba 	ASSERT(found_key);
1537e33d5c3dSKelley Nielsen 
1538e33d5c3dSKelley Nielsen 	key.type = key_type;
1539e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1540e33d5c3dSKelley Nielsen 	key.offset = ioff;
1541e33d5c3dSKelley Nielsen 
1542e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
15431d4c08e0SDavid Sterba 	if (ret < 0)
1544e33d5c3dSKelley Nielsen 		return ret;
1545e33d5c3dSKelley Nielsen 
1546e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1547e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1548e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1549e33d5c3dSKelley Nielsen 		if (ret)
1550e33d5c3dSKelley Nielsen 			return ret;
1551e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1552e33d5c3dSKelley Nielsen 	}
1553e33d5c3dSKelley Nielsen 
1554e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1555e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1556e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1557e33d5c3dSKelley Nielsen 		return 1;
1558e33d5c3dSKelley Nielsen 
1559e33d5c3dSKelley Nielsen 	return 0;
1560e33d5c3dSKelley Nielsen }
1561e33d5c3dSKelley Nielsen 
15621fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
15631fc28d8eSLiu Bo 							struct btrfs_path *p,
15641fc28d8eSLiu Bo 							int write_lock_level)
15651fc28d8eSLiu Bo {
15661fc28d8eSLiu Bo 	struct btrfs_fs_info *fs_info = root->fs_info;
15671fc28d8eSLiu Bo 	struct extent_buffer *b;
15681fc28d8eSLiu Bo 	int root_lock;
15691fc28d8eSLiu Bo 	int level = 0;
15701fc28d8eSLiu Bo 
15711fc28d8eSLiu Bo 	/* We try very hard to do read locks on the root */
15721fc28d8eSLiu Bo 	root_lock = BTRFS_READ_LOCK;
15731fc28d8eSLiu Bo 
15741fc28d8eSLiu Bo 	if (p->search_commit_root) {
1575be6821f8SFilipe Manana 		/*
1576be6821f8SFilipe Manana 		 * The commit roots are read only so we always do read locks,
1577be6821f8SFilipe Manana 		 * and we always must hold the commit_root_sem when doing
1578be6821f8SFilipe Manana 		 * searches on them, the only exception is send where we don't
1579be6821f8SFilipe Manana 		 * want to block transaction commits for a long time, so
1580be6821f8SFilipe Manana 		 * we need to clone the commit root in order to avoid races
1581be6821f8SFilipe Manana 		 * with transaction commits that create a snapshot of one of
1582be6821f8SFilipe Manana 		 * the roots used by a send operation.
1583be6821f8SFilipe Manana 		 */
1584be6821f8SFilipe Manana 		if (p->need_commit_sem) {
15851fc28d8eSLiu Bo 			down_read(&fs_info->commit_root_sem);
1586be6821f8SFilipe Manana 			b = btrfs_clone_extent_buffer(root->commit_root);
1587be6821f8SFilipe Manana 			up_read(&fs_info->commit_root_sem);
1588be6821f8SFilipe Manana 			if (!b)
1589be6821f8SFilipe Manana 				return ERR_PTR(-ENOMEM);
1590be6821f8SFilipe Manana 
1591be6821f8SFilipe Manana 		} else {
15921fc28d8eSLiu Bo 			b = root->commit_root;
159367439dadSDavid Sterba 			atomic_inc(&b->refs);
1594be6821f8SFilipe Manana 		}
15951fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1596f9ddfd05SLiu Bo 		/*
1597f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1598f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1599f9ddfd05SLiu Bo 		 */
1600f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
16011fc28d8eSLiu Bo 
16021fc28d8eSLiu Bo 		goto out;
16031fc28d8eSLiu Bo 	}
16041fc28d8eSLiu Bo 
16051fc28d8eSLiu Bo 	if (p->skip_locking) {
16061fc28d8eSLiu Bo 		b = btrfs_root_node(root);
16071fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16081fc28d8eSLiu Bo 		goto out;
16091fc28d8eSLiu Bo 	}
16101fc28d8eSLiu Bo 
16111fc28d8eSLiu Bo 	/*
1612662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1613662c653bSLiu Bo 	 * lock.
1614662c653bSLiu Bo 	 */
1615662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1616662c653bSLiu Bo 		/*
1617662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1618662c653bSLiu Bo 		 * have it read locked
16191fc28d8eSLiu Bo 		 */
16201bb96598SJosef Bacik 		b = btrfs_read_lock_root_node(root);
16211fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16221fc28d8eSLiu Bo 		if (level > write_lock_level)
16231fc28d8eSLiu Bo 			goto out;
16241fc28d8eSLiu Bo 
1625662c653bSLiu Bo 		/* Whoops, must trade for write lock */
16261fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
16271fc28d8eSLiu Bo 		free_extent_buffer(b);
1628662c653bSLiu Bo 	}
1629662c653bSLiu Bo 
16301fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
16311fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
16321fc28d8eSLiu Bo 
16331fc28d8eSLiu Bo 	/* The level might have changed, check again */
16341fc28d8eSLiu Bo 	level = btrfs_header_level(b);
16351fc28d8eSLiu Bo 
16361fc28d8eSLiu Bo out:
16371fc28d8eSLiu Bo 	p->nodes[level] = b;
16381fc28d8eSLiu Bo 	if (!p->skip_locking)
16391fc28d8eSLiu Bo 		p->locks[level] = root_lock;
16401fc28d8eSLiu Bo 	/*
16411fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
16421fc28d8eSLiu Bo 	 */
16431fc28d8eSLiu Bo 	return b;
16441fc28d8eSLiu Bo }
16451fc28d8eSLiu Bo 
16461fc28d8eSLiu Bo 
1647c8c42864SChris Mason /*
16484271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
16494271eceaSNikolay Borisov  * modifications to preserve tree invariants.
165074123bd7SChris Mason  *
16514271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
16524271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
16534271eceaSNikolay Borisov  * @root:	The root node of the tree
16544271eceaSNikolay Borisov  * @key:	The key we are looking for
16559a664971Sethanwu  * @ins_len:	Indicates purpose of search:
16569a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
16579a664971Sethanwu  *              <0  for deletions
16589a664971Sethanwu  *               0  for plain searches, not modifying the tree
16599a664971Sethanwu  *
16609a664971Sethanwu  *              (*) If size of item inserted doesn't include
16619a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
16629a664971Sethanwu  *              be set.
16634271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
16644271eceaSNikolay Borisov  *		when modifying the tree.
166597571fd0SChris Mason  *
16664271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
16674271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
16684271eceaSNikolay Borisov  *
16694271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
16704271eceaSNikolay Borisov  * of the path (level 0)
16714271eceaSNikolay Borisov  *
16724271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
16734271eceaSNikolay Borisov  * points to the slot where it should be inserted
16744271eceaSNikolay Borisov  *
16754271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
16764271eceaSNikolay Borisov  * is returned
167774123bd7SChris Mason  */
1678310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1679310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
1680310712b2SOmar Sandoval 		      int ins_len, int cow)
1681be0e5c09SChris Mason {
16825f39d397SChris Mason 	struct extent_buffer *b;
1683be0e5c09SChris Mason 	int slot;
1684be0e5c09SChris Mason 	int ret;
168533c66f43SYan Zheng 	int err;
1686be0e5c09SChris Mason 	int level;
1687925baeddSChris Mason 	int lowest_unlock = 1;
1688bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
1689bd681513SChris Mason 	int write_lock_level = 0;
16909f3a7427SChris Mason 	u8 lowest_level = 0;
1691f7c79f30SChris Mason 	int min_write_lock_level;
1692d7396f07SFilipe David Borba Manana 	int prev_cmp;
16939f3a7427SChris Mason 
16946702ed49SChris Mason 	lowest_level = p->lowest_level;
1695323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
169622b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
1697eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
169825179201SJosef Bacik 
1699bd681513SChris Mason 	if (ins_len < 0) {
1700925baeddSChris Mason 		lowest_unlock = 2;
170165b51a00SChris Mason 
1702bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
1703bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
1704bd681513SChris Mason 		 * for those levels as well
1705bd681513SChris Mason 		 */
1706bd681513SChris Mason 		write_lock_level = 2;
1707bd681513SChris Mason 	} else if (ins_len > 0) {
1708bd681513SChris Mason 		/*
1709bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
1710bd681513SChris Mason 		 * level 1 so we can update keys
1711bd681513SChris Mason 		 */
1712bd681513SChris Mason 		write_lock_level = 1;
1713bd681513SChris Mason 	}
1714bd681513SChris Mason 
1715bd681513SChris Mason 	if (!cow)
1716bd681513SChris Mason 		write_lock_level = -1;
1717bd681513SChris Mason 
171809a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
1719bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
1720bd681513SChris Mason 
1721f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
1722f7c79f30SChris Mason 
1723bb803951SChris Mason again:
1724d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
17251fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
1726be6821f8SFilipe Manana 	if (IS_ERR(b)) {
1727be6821f8SFilipe Manana 		ret = PTR_ERR(b);
1728be6821f8SFilipe Manana 		goto done;
1729be6821f8SFilipe Manana 	}
1730925baeddSChris Mason 
1731eb60ceacSChris Mason 	while (b) {
1732f624d976SQu Wenruo 		int dec = 0;
1733f624d976SQu Wenruo 
17345f39d397SChris Mason 		level = btrfs_header_level(b);
173565b51a00SChris Mason 
173602217ed2SChris Mason 		if (cow) {
17379ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
17389ea2c7c9SNikolay Borisov 
1739c8c42864SChris Mason 			/*
1740c8c42864SChris Mason 			 * if we don't really need to cow this block
1741c8c42864SChris Mason 			 * then we don't want to set the path blocking,
1742c8c42864SChris Mason 			 * so we test it here
1743c8c42864SChris Mason 			 */
17445963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
174565b51a00SChris Mason 				goto cow_done;
17465d4f98a2SYan Zheng 
1747bd681513SChris Mason 			/*
1748bd681513SChris Mason 			 * must have write locks on this node and the
1749bd681513SChris Mason 			 * parent
1750bd681513SChris Mason 			 */
17515124e00eSJosef Bacik 			if (level > write_lock_level ||
17525124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
17535124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
17545124e00eSJosef Bacik 			    p->nodes[level + 1])) {
1755bd681513SChris Mason 				write_lock_level = level + 1;
1756bd681513SChris Mason 				btrfs_release_path(p);
1757bd681513SChris Mason 				goto again;
1758bd681513SChris Mason 			}
1759bd681513SChris Mason 
17609ea2c7c9SNikolay Borisov 			if (last_level)
17619ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
17629631e4ccSJosef Bacik 						      &b,
17639631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
17649ea2c7c9SNikolay Borisov 			else
176533c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
1766e20d96d6SChris Mason 						      p->nodes[level + 1],
17679631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
17689631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
176933c66f43SYan Zheng 			if (err) {
177033c66f43SYan Zheng 				ret = err;
177165b51a00SChris Mason 				goto done;
177254aa1f4dSChris Mason 			}
177302217ed2SChris Mason 		}
177465b51a00SChris Mason cow_done:
1775eb60ceacSChris Mason 		p->nodes[level] = b;
177652398340SLiu Bo 		/*
177752398340SLiu Bo 		 * Leave path with blocking locks to avoid massive
177852398340SLiu Bo 		 * lock context switch, this is made on purpose.
177952398340SLiu Bo 		 */
1780b4ce94deSChris Mason 
1781b4ce94deSChris Mason 		/*
1782b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
1783b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
1784b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
1785b4ce94deSChris Mason 		 * go through the expensive btree search on b.
1786b4ce94deSChris Mason 		 *
1787eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
1788eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
1789eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
1790eb653de1SFilipe David Borba Manana 		 * we're operating on.
1791b4ce94deSChris Mason 		 */
1792eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
1793eb653de1SFilipe David Borba Manana 			int u = level + 1;
1794eb653de1SFilipe David Borba Manana 
1795eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
1796eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
1797eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
1798eb653de1SFilipe David Borba Manana 			}
1799eb653de1SFilipe David Borba Manana 		}
1800b4ce94deSChris Mason 
1801995e9a16SNikolay Borisov 		/*
1802995e9a16SNikolay Borisov 		 * If btrfs_bin_search returns an exact match (prev_cmp == 0)
1803995e9a16SNikolay Borisov 		 * we can safely assume the target key will always be in slot 0
1804995e9a16SNikolay Borisov 		 * on lower levels due to the invariants BTRFS' btree provides,
1805995e9a16SNikolay Borisov 		 * namely that a btrfs_key_ptr entry always points to the
1806995e9a16SNikolay Borisov 		 * lowest key in the child node, thus we can skip searching
1807995e9a16SNikolay Borisov 		 * lower levels
1808995e9a16SNikolay Borisov 		 */
1809995e9a16SNikolay Borisov 		if (prev_cmp == 0) {
1810995e9a16SNikolay Borisov 			slot = 0;
1811995e9a16SNikolay Borisov 			ret = 0;
1812995e9a16SNikolay Borisov 		} else {
1813995e9a16SNikolay Borisov 			ret = btrfs_bin_search(b, key, &slot);
1814995e9a16SNikolay Borisov 			prev_cmp = ret;
1815415b35a5SLiu Bo 			if (ret < 0)
1816415b35a5SLiu Bo 				goto done;
1817995e9a16SNikolay Borisov 		}
1818b4ce94deSChris Mason 
1819f624d976SQu Wenruo 		if (level == 0) {
1820be0e5c09SChris Mason 			p->slots[level] = slot;
18219a664971Sethanwu 			/*
18229a664971Sethanwu 			 * Item key already exists. In this case, if we are
18239a664971Sethanwu 			 * allowed to insert the item (for example, in dir_item
18249a664971Sethanwu 			 * case, item key collision is allowed), it will be
18259a664971Sethanwu 			 * merged with the original item. Only the item size
18269a664971Sethanwu 			 * grows, no new btrfs item will be added. If
18279a664971Sethanwu 			 * search_for_extension is not set, ins_len already
18289a664971Sethanwu 			 * accounts the size btrfs_item, deduct it here so leaf
18299a664971Sethanwu 			 * space check will be correct.
18309a664971Sethanwu 			 */
18319a664971Sethanwu 			if (ret == 0 && ins_len > 0 && !p->search_for_extension) {
18329a664971Sethanwu 				ASSERT(ins_len >= sizeof(struct btrfs_item));
18339a664971Sethanwu 				ins_len -= sizeof(struct btrfs_item);
18349a664971Sethanwu 			}
183587b29b20SYan Zheng 			if (ins_len > 0 &&
1836e902baacSDavid Sterba 			    btrfs_leaf_free_space(b) < ins_len) {
1837bd681513SChris Mason 				if (write_lock_level < 1) {
1838bd681513SChris Mason 					write_lock_level = 1;
1839bd681513SChris Mason 					btrfs_release_path(p);
1840bd681513SChris Mason 					goto again;
1841bd681513SChris Mason 				}
1842bd681513SChris Mason 
184333c66f43SYan Zheng 				err = split_leaf(trans, root, key,
1844cc0c5538SChris Mason 						 p, ins_len, ret == 0);
1845b4ce94deSChris Mason 
184633c66f43SYan Zheng 				BUG_ON(err > 0);
184733c66f43SYan Zheng 				if (err) {
184833c66f43SYan Zheng 					ret = err;
184965b51a00SChris Mason 					goto done;
185065b51a00SChris Mason 				}
18515c680ed6SChris Mason 			}
1852459931ecSChris Mason 			if (!p->search_for_split)
1853f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
18544b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
185565b51a00SChris Mason 			goto done;
185665b51a00SChris Mason 		}
1857f624d976SQu Wenruo 		if (ret && slot > 0) {
1858f624d976SQu Wenruo 			dec = 1;
1859f624d976SQu Wenruo 			slot--;
1860f624d976SQu Wenruo 		}
1861f624d976SQu Wenruo 		p->slots[level] = slot;
1862f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
1863f624d976SQu Wenruo 					     &write_lock_level);
1864f624d976SQu Wenruo 		if (err == -EAGAIN)
1865f624d976SQu Wenruo 			goto again;
1866f624d976SQu Wenruo 		if (err) {
1867f624d976SQu Wenruo 			ret = err;
1868f624d976SQu Wenruo 			goto done;
1869f624d976SQu Wenruo 		}
1870f624d976SQu Wenruo 		b = p->nodes[level];
1871f624d976SQu Wenruo 		slot = p->slots[level];
1872f624d976SQu Wenruo 
1873f624d976SQu Wenruo 		/*
1874f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
1875f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
1876f624d976SQu Wenruo 		 * the parent
1877f624d976SQu Wenruo 		 */
1878f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
1879f624d976SQu Wenruo 			write_lock_level = level + 1;
1880f624d976SQu Wenruo 			btrfs_release_path(p);
1881f624d976SQu Wenruo 			goto again;
1882f624d976SQu Wenruo 		}
1883f624d976SQu Wenruo 
1884f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
1885f624d976SQu Wenruo 			  &write_lock_level);
1886f624d976SQu Wenruo 
1887f624d976SQu Wenruo 		if (level == lowest_level) {
1888f624d976SQu Wenruo 			if (dec)
1889f624d976SQu Wenruo 				p->slots[level]++;
1890f624d976SQu Wenruo 			goto done;
1891f624d976SQu Wenruo 		}
1892f624d976SQu Wenruo 
1893f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
1894f624d976SQu Wenruo 		if (err == -EAGAIN)
1895f624d976SQu Wenruo 			goto again;
1896f624d976SQu Wenruo 		if (err) {
1897f624d976SQu Wenruo 			ret = err;
1898f624d976SQu Wenruo 			goto done;
1899f624d976SQu Wenruo 		}
1900f624d976SQu Wenruo 
1901f624d976SQu Wenruo 		if (!p->skip_locking) {
1902f624d976SQu Wenruo 			level = btrfs_header_level(b);
1903f624d976SQu Wenruo 			if (level <= write_lock_level) {
1904f624d976SQu Wenruo 				btrfs_tree_lock(b);
1905f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
1906f624d976SQu Wenruo 			} else {
1907fe596ca3SJosef Bacik 				btrfs_tree_read_lock(b);
1908f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
1909f624d976SQu Wenruo 			}
1910f624d976SQu Wenruo 			p->nodes[level] = b;
1911f624d976SQu Wenruo 		}
191265b51a00SChris Mason 	}
191365b51a00SChris Mason 	ret = 1;
191465b51a00SChris Mason done:
19155f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
1916b3b4aa74SDavid Sterba 		btrfs_release_path(p);
1917be0e5c09SChris Mason 	return ret;
1918be0e5c09SChris Mason }
1919f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
1920be0e5c09SChris Mason 
192174123bd7SChris Mason /*
19225d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
19235d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
19245d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
19255d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
19265d9e75c4SJan Schmidt  *
19275d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
19285d9e75c4SJan Schmidt  *
19295d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
19305d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
19315d9e75c4SJan Schmidt  */
1932310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
19335d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
19345d9e75c4SJan Schmidt {
19350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
19365d9e75c4SJan Schmidt 	struct extent_buffer *b;
19375d9e75c4SJan Schmidt 	int slot;
19385d9e75c4SJan Schmidt 	int ret;
19395d9e75c4SJan Schmidt 	int err;
19405d9e75c4SJan Schmidt 	int level;
19415d9e75c4SJan Schmidt 	int lowest_unlock = 1;
19425d9e75c4SJan Schmidt 	u8 lowest_level = 0;
19435d9e75c4SJan Schmidt 
19445d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
19455d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
19465d9e75c4SJan Schmidt 
19475d9e75c4SJan Schmidt 	if (p->search_commit_root) {
19485d9e75c4SJan Schmidt 		BUG_ON(time_seq);
19495d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
19505d9e75c4SJan Schmidt 	}
19515d9e75c4SJan Schmidt 
19525d9e75c4SJan Schmidt again:
1953f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
1954315bed43SNikolay Borisov 	if (!b) {
1955315bed43SNikolay Borisov 		ret = -EIO;
1956315bed43SNikolay Borisov 		goto done;
1957315bed43SNikolay Borisov 	}
19585d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
19595d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
19605d9e75c4SJan Schmidt 
19615d9e75c4SJan Schmidt 	while (b) {
1962abe9339dSQu Wenruo 		int dec = 0;
1963abe9339dSQu Wenruo 
19645d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
19655d9e75c4SJan Schmidt 		p->nodes[level] = b;
19665d9e75c4SJan Schmidt 
19675d9e75c4SJan Schmidt 		/*
19685d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
19695d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
19705d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
19715d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
19725d9e75c4SJan Schmidt 		 */
19735d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
19745d9e75c4SJan Schmidt 
1975995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
1976cbca7d59SFilipe Manana 		if (ret < 0)
1977cbca7d59SFilipe Manana 			goto done;
19785d9e75c4SJan Schmidt 
1979abe9339dSQu Wenruo 		if (level == 0) {
1980abe9339dSQu Wenruo 			p->slots[level] = slot;
1981abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
1982abe9339dSQu Wenruo 			goto done;
1983abe9339dSQu Wenruo 		}
1984abe9339dSQu Wenruo 
19855d9e75c4SJan Schmidt 		if (ret && slot > 0) {
19865d9e75c4SJan Schmidt 			dec = 1;
1987abe9339dSQu Wenruo 			slot--;
19885d9e75c4SJan Schmidt 		}
19895d9e75c4SJan Schmidt 		p->slots[level] = slot;
19905d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
19915d9e75c4SJan Schmidt 
19925d9e75c4SJan Schmidt 		if (level == lowest_level) {
19935d9e75c4SJan Schmidt 			if (dec)
19945d9e75c4SJan Schmidt 				p->slots[level]++;
19955d9e75c4SJan Schmidt 			goto done;
19965d9e75c4SJan Schmidt 		}
19975d9e75c4SJan Schmidt 
1998abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
19995d9e75c4SJan Schmidt 		if (err == -EAGAIN)
20005d9e75c4SJan Schmidt 			goto again;
20015d9e75c4SJan Schmidt 		if (err) {
20025d9e75c4SJan Schmidt 			ret = err;
20035d9e75c4SJan Schmidt 			goto done;
20045d9e75c4SJan Schmidt 		}
20055d9e75c4SJan Schmidt 
20065d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
20075d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2008f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2009db7f3436SJosef Bacik 		if (!b) {
2010db7f3436SJosef Bacik 			ret = -ENOMEM;
2011db7f3436SJosef Bacik 			goto done;
2012db7f3436SJosef Bacik 		}
20135d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
20145d9e75c4SJan Schmidt 		p->nodes[level] = b;
20155d9e75c4SJan Schmidt 	}
20165d9e75c4SJan Schmidt 	ret = 1;
20175d9e75c4SJan Schmidt done:
20185d9e75c4SJan Schmidt 	if (ret < 0)
20195d9e75c4SJan Schmidt 		btrfs_release_path(p);
20205d9e75c4SJan Schmidt 
20215d9e75c4SJan Schmidt 	return ret;
20225d9e75c4SJan Schmidt }
20235d9e75c4SJan Schmidt 
20245d9e75c4SJan Schmidt /*
20252f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
20262f38b3e1SArne Jansen  * instead the next or previous item should be returned.
20272f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
20282f38b3e1SArne Jansen  * otherwise.
20292f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
20302f38b3e1SArne Jansen  * return the next lower instead.
20312f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
20322f38b3e1SArne Jansen  * return the next higher instead.
20332f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
20342f38b3e1SArne Jansen  * < 0 on error
20352f38b3e1SArne Jansen  */
20362f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2037310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2038310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2039310712b2SOmar Sandoval 			       int return_any)
20402f38b3e1SArne Jansen {
20412f38b3e1SArne Jansen 	int ret;
20422f38b3e1SArne Jansen 	struct extent_buffer *leaf;
20432f38b3e1SArne Jansen 
20442f38b3e1SArne Jansen again:
20452f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
20462f38b3e1SArne Jansen 	if (ret <= 0)
20472f38b3e1SArne Jansen 		return ret;
20482f38b3e1SArne Jansen 	/*
20492f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
20502f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
20512f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
20522f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
20532f38b3e1SArne Jansen 	 * item.
20542f38b3e1SArne Jansen 	 */
20552f38b3e1SArne Jansen 	leaf = p->nodes[0];
20562f38b3e1SArne Jansen 
20572f38b3e1SArne Jansen 	if (find_higher) {
20582f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
20592f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
20602f38b3e1SArne Jansen 			if (ret <= 0)
20612f38b3e1SArne Jansen 				return ret;
20622f38b3e1SArne Jansen 			if (!return_any)
20632f38b3e1SArne Jansen 				return 1;
20642f38b3e1SArne Jansen 			/*
20652f38b3e1SArne Jansen 			 * no higher item found, return the next
20662f38b3e1SArne Jansen 			 * lower instead
20672f38b3e1SArne Jansen 			 */
20682f38b3e1SArne Jansen 			return_any = 0;
20692f38b3e1SArne Jansen 			find_higher = 0;
20702f38b3e1SArne Jansen 			btrfs_release_path(p);
20712f38b3e1SArne Jansen 			goto again;
20722f38b3e1SArne Jansen 		}
20732f38b3e1SArne Jansen 	} else {
20742f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
20752f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2076e6793769SArne Jansen 			if (ret < 0)
20772f38b3e1SArne Jansen 				return ret;
2078e6793769SArne Jansen 			if (!ret) {
207923c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
208023c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
208123c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2082e6793769SArne Jansen 				return 0;
2083e6793769SArne Jansen 			}
20842f38b3e1SArne Jansen 			if (!return_any)
20852f38b3e1SArne Jansen 				return 1;
20862f38b3e1SArne Jansen 			/*
20872f38b3e1SArne Jansen 			 * no lower item found, return the next
20882f38b3e1SArne Jansen 			 * higher instead
20892f38b3e1SArne Jansen 			 */
20902f38b3e1SArne Jansen 			return_any = 0;
20912f38b3e1SArne Jansen 			find_higher = 1;
20922f38b3e1SArne Jansen 			btrfs_release_path(p);
20932f38b3e1SArne Jansen 			goto again;
2094e6793769SArne Jansen 		} else {
20952f38b3e1SArne Jansen 			--p->slots[0];
20962f38b3e1SArne Jansen 		}
20972f38b3e1SArne Jansen 	}
20982f38b3e1SArne Jansen 	return 0;
20992f38b3e1SArne Jansen }
21002f38b3e1SArne Jansen 
21012f38b3e1SArne Jansen /*
210274123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
210374123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
210474123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
210574123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
210674123bd7SChris Mason  * higher levels
2107aa5d6bedSChris Mason  *
210874123bd7SChris Mason  */
2109b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
21105f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2111be0e5c09SChris Mason {
2112be0e5c09SChris Mason 	int i;
21135f39d397SChris Mason 	struct extent_buffer *t;
21140e82bcfeSDavid Sterba 	int ret;
21155f39d397SChris Mason 
2116234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2117be0e5c09SChris Mason 		int tslot = path->slots[i];
21180e82bcfeSDavid Sterba 
2119eb60ceacSChris Mason 		if (!path->nodes[i])
2120be0e5c09SChris Mason 			break;
21215f39d397SChris Mason 		t = path->nodes[i];
2122f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
2123f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REPLACE, GFP_ATOMIC);
21240e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
21255f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2126d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2127be0e5c09SChris Mason 		if (tslot != 0)
2128be0e5c09SChris Mason 			break;
2129be0e5c09SChris Mason 	}
2130be0e5c09SChris Mason }
2131be0e5c09SChris Mason 
213274123bd7SChris Mason /*
213331840ae1SZheng Yan  * update item key.
213431840ae1SZheng Yan  *
213531840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
213631840ae1SZheng Yan  * that the new key won't break the order
213731840ae1SZheng Yan  */
2138b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2139b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2140310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
214131840ae1SZheng Yan {
214231840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
214331840ae1SZheng Yan 	struct extent_buffer *eb;
214431840ae1SZheng Yan 	int slot;
214531840ae1SZheng Yan 
214631840ae1SZheng Yan 	eb = path->nodes[0];
214731840ae1SZheng Yan 	slot = path->slots[0];
214831840ae1SZheng Yan 	if (slot > 0) {
214931840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
21507c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
21517c15d410SQu Wenruo 			btrfs_crit(fs_info,
21527c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
21537c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
21547c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
21557c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
21567c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
21577c15d410SQu Wenruo 				   new_key->offset);
21587c15d410SQu Wenruo 			btrfs_print_leaf(eb);
21597c15d410SQu Wenruo 			BUG();
21607c15d410SQu Wenruo 		}
216131840ae1SZheng Yan 	}
216231840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
216331840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
21647c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
21657c15d410SQu Wenruo 			btrfs_crit(fs_info,
21667c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
21677c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
21687c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
21697c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
21707c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
21717c15d410SQu Wenruo 				   new_key->offset);
21727c15d410SQu Wenruo 			btrfs_print_leaf(eb);
21737c15d410SQu Wenruo 			BUG();
21747c15d410SQu Wenruo 		}
217531840ae1SZheng Yan 	}
217631840ae1SZheng Yan 
217731840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
217831840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
217931840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
218031840ae1SZheng Yan 	if (slot == 0)
2181b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
218231840ae1SZheng Yan }
218331840ae1SZheng Yan 
218431840ae1SZheng Yan /*
2185d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2186d16c702fSQu Wenruo  *
2187d16c702fSQu Wenruo  * Return true if something is wrong.
2188d16c702fSQu Wenruo  * Return false if everything is fine.
2189d16c702fSQu Wenruo  *
2190d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2191d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2192d16c702fSQu Wenruo  *
2193d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2194d16c702fSQu Wenruo  * --------------------------------------------------------------
2195d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2196d16c702fSQu Wenruo  *
2197d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2198d16c702fSQu Wenruo  * key in leaf @right is 7.
2199d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2200d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2201d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2202d16c702fSQu Wenruo  * key of @right.
2203d16c702fSQu Wenruo  */
2204d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2205d16c702fSQu Wenruo 			       struct extent_buffer *right)
2206d16c702fSQu Wenruo {
2207d16c702fSQu Wenruo 	struct btrfs_key left_last;
2208d16c702fSQu Wenruo 	struct btrfs_key right_first;
2209d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2210d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2211d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2212d16c702fSQu Wenruo 
2213d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2214d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2215d16c702fSQu Wenruo 		return false;
2216d16c702fSQu Wenruo 
2217d16c702fSQu Wenruo 	if (level) {
2218d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2219d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2220d16c702fSQu Wenruo 	} else {
2221d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2222d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2223d16c702fSQu Wenruo 	}
2224d16c702fSQu Wenruo 
2225d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2226d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2227d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2228d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2229d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2230d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2231d16c702fSQu Wenruo 		return true;
2232d16c702fSQu Wenruo 	}
2233d16c702fSQu Wenruo 	return false;
2234d16c702fSQu Wenruo }
2235d16c702fSQu Wenruo 
2236d16c702fSQu Wenruo /*
223774123bd7SChris Mason  * try to push data from one node into the next node left in the
223879f95c82SChris Mason  * tree.
2239aa5d6bedSChris Mason  *
2240aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2241aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
224274123bd7SChris Mason  */
224398ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
22442ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2245971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2246be0e5c09SChris Mason {
2247d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2248be0e5c09SChris Mason 	int push_items = 0;
2249bb803951SChris Mason 	int src_nritems;
2250bb803951SChris Mason 	int dst_nritems;
2251aa5d6bedSChris Mason 	int ret = 0;
2252be0e5c09SChris Mason 
22535f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
22545f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
22550b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
22567bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
22577bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
225854aa1f4dSChris Mason 
2259bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2260971a1f66SChris Mason 		return 1;
2261971a1f66SChris Mason 
2262d397712bSChris Mason 	if (push_items <= 0)
2263be0e5c09SChris Mason 		return 1;
2264be0e5c09SChris Mason 
2265bce4eae9SChris Mason 	if (empty) {
2266971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2267bce4eae9SChris Mason 		if (push_items < src_nritems) {
2268bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2269bce4eae9SChris Mason 			 * we aren't going to empty it
2270bce4eae9SChris Mason 			 */
2271bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2272bce4eae9SChris Mason 				if (push_items <= 8)
2273bce4eae9SChris Mason 					return 1;
2274bce4eae9SChris Mason 				push_items -= 8;
2275bce4eae9SChris Mason 			}
2276bce4eae9SChris Mason 		}
2277bce4eae9SChris Mason 	} else
2278bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
227979f95c82SChris Mason 
2280d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2281d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2282d16c702fSQu Wenruo 		ret = -EUCLEAN;
2283d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2284d16c702fSQu Wenruo 		return ret;
2285d16c702fSQu Wenruo 	}
2286f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
22875de865eeSFilipe David Borba Manana 	if (ret) {
228866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
22895de865eeSFilipe David Borba Manana 		return ret;
22905de865eeSFilipe David Borba Manana 	}
22915f39d397SChris Mason 	copy_extent_buffer(dst, src,
22925f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
22935f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2294123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
22955f39d397SChris Mason 
2296bb803951SChris Mason 	if (push_items < src_nritems) {
229757911b8bSJan Schmidt 		/*
2298f3a84ccdSFilipe Manana 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2299f3a84ccdSFilipe Manana 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
230057911b8bSJan Schmidt 		 */
23015f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
23025f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2303e2fa7227SChris Mason 				      (src_nritems - push_items) *
2304123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2305bb803951SChris Mason 	}
23065f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
23075f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
23085f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
23095f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
231031840ae1SZheng Yan 
2311bb803951SChris Mason 	return ret;
2312be0e5c09SChris Mason }
2313be0e5c09SChris Mason 
231497571fd0SChris Mason /*
231579f95c82SChris Mason  * try to push data from one node into the next node right in the
231679f95c82SChris Mason  * tree.
231779f95c82SChris Mason  *
231879f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
231979f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
232079f95c82SChris Mason  *
232179f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
232279f95c82SChris Mason  */
23235f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
23245f39d397SChris Mason 			      struct extent_buffer *dst,
23255f39d397SChris Mason 			      struct extent_buffer *src)
232679f95c82SChris Mason {
232755d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
232879f95c82SChris Mason 	int push_items = 0;
232979f95c82SChris Mason 	int max_push;
233079f95c82SChris Mason 	int src_nritems;
233179f95c82SChris Mason 	int dst_nritems;
233279f95c82SChris Mason 	int ret = 0;
233379f95c82SChris Mason 
23347bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
23357bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
23367bb86316SChris Mason 
23375f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
23385f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
23390b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2340d397712bSChris Mason 	if (push_items <= 0)
234179f95c82SChris Mason 		return 1;
2342bce4eae9SChris Mason 
2343d397712bSChris Mason 	if (src_nritems < 4)
2344bce4eae9SChris Mason 		return 1;
234579f95c82SChris Mason 
234679f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
234779f95c82SChris Mason 	/* don't try to empty the node */
2348d397712bSChris Mason 	if (max_push >= src_nritems)
234979f95c82SChris Mason 		return 1;
2350252c38f0SYan 
235179f95c82SChris Mason 	if (max_push < push_items)
235279f95c82SChris Mason 		push_items = max_push;
235379f95c82SChris Mason 
2354d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2355d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2356d16c702fSQu Wenruo 		ret = -EUCLEAN;
2357d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2358d16c702fSQu Wenruo 		return ret;
2359d16c702fSQu Wenruo 	}
2360f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2361bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
23625f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
23635f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
23645f39d397SChris Mason 				      (dst_nritems) *
23655f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2366d6025579SChris Mason 
2367f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2368ed874f0dSDavid Sterba 					 push_items);
23695de865eeSFilipe David Borba Manana 	if (ret) {
237066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
23715de865eeSFilipe David Borba Manana 		return ret;
23725de865eeSFilipe David Borba Manana 	}
23735f39d397SChris Mason 	copy_extent_buffer(dst, src,
23745f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
23755f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2376123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
237779f95c82SChris Mason 
23785f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
23795f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
238079f95c82SChris Mason 
23815f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
23825f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
238331840ae1SZheng Yan 
238479f95c82SChris Mason 	return ret;
238579f95c82SChris Mason }
238679f95c82SChris Mason 
238779f95c82SChris Mason /*
238897571fd0SChris Mason  * helper function to insert a new root level in the tree.
238997571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
239097571fd0SChris Mason  * point to the existing root
2391aa5d6bedSChris Mason  *
2392aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
239397571fd0SChris Mason  */
2394d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
23955f39d397SChris Mason 			   struct btrfs_root *root,
2396fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
239774123bd7SChris Mason {
23980b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
23997bb86316SChris Mason 	u64 lower_gen;
24005f39d397SChris Mason 	struct extent_buffer *lower;
24015f39d397SChris Mason 	struct extent_buffer *c;
2402925baeddSChris Mason 	struct extent_buffer *old;
24035f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2404d9d19a01SDavid Sterba 	int ret;
24055c680ed6SChris Mason 
24065c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
24075c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
24085c680ed6SChris Mason 
24097bb86316SChris Mason 	lower = path->nodes[level-1];
24107bb86316SChris Mason 	if (level == 1)
24117bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
24127bb86316SChris Mason 	else
24137bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
24147bb86316SChris Mason 
241579bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
241679bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2417cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
24185f39d397SChris Mason 	if (IS_ERR(c))
24195f39d397SChris Mason 		return PTR_ERR(c);
2420925baeddSChris Mason 
24210b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2422f0486c68SYan, Zheng 
24235f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
24245f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2425db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
24267bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
242731840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
24287bb86316SChris Mason 
24297bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
24305f39d397SChris Mason 
24315f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2432d5719762SChris Mason 
2433925baeddSChris Mason 	old = root->node;
2434406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2435d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2436240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2437925baeddSChris Mason 
2438925baeddSChris Mason 	/* the super has an extra ref to root->node */
2439925baeddSChris Mason 	free_extent_buffer(old);
2440925baeddSChris Mason 
24410b86a832SChris Mason 	add_root_to_dirty_list(root);
244267439dadSDavid Sterba 	atomic_inc(&c->refs);
24435f39d397SChris Mason 	path->nodes[level] = c;
2444ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
244574123bd7SChris Mason 	path->slots[level] = 0;
244674123bd7SChris Mason 	return 0;
244774123bd7SChris Mason }
24485c680ed6SChris Mason 
24495c680ed6SChris Mason /*
24505c680ed6SChris Mason  * worker function to insert a single pointer in a node.
24515c680ed6SChris Mason  * the node should have enough room for the pointer already
245297571fd0SChris Mason  *
24535c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
24545c680ed6SChris Mason  * blocknr is the block the key points to.
24555c680ed6SChris Mason  */
2456143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
24576ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2458143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2459c3e06965SJan Schmidt 		       int slot, int level)
24605c680ed6SChris Mason {
24615f39d397SChris Mason 	struct extent_buffer *lower;
24625c680ed6SChris Mason 	int nritems;
2463f3ea38daSJan Schmidt 	int ret;
24645c680ed6SChris Mason 
24655c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
2466f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
24675f39d397SChris Mason 	lower = path->nodes[level];
24685f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2469c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
24706ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
247174123bd7SChris Mason 	if (slot != nritems) {
2472bf1d3425SDavid Sterba 		if (level) {
2473f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2474f3a84ccdSFilipe Manana 					slot, nritems - slot);
2475bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2476bf1d3425SDavid Sterba 		}
24775f39d397SChris Mason 		memmove_extent_buffer(lower,
24785f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
24795f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
2480123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
248174123bd7SChris Mason 	}
2482c3e06965SJan Schmidt 	if (level) {
2483f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
2484f3a84ccdSFilipe Manana 					    BTRFS_MOD_LOG_KEY_ADD, GFP_NOFS);
2485f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2486f3ea38daSJan Schmidt 	}
24875f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2488db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
248974493f7aSChris Mason 	WARN_ON(trans->transid == 0);
249074493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
24915f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
24925f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
249374123bd7SChris Mason }
249474123bd7SChris Mason 
249597571fd0SChris Mason /*
249697571fd0SChris Mason  * split the node at the specified level in path in two.
249797571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
249897571fd0SChris Mason  *
249997571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
250097571fd0SChris Mason  * left and right, if either one works, it returns right away.
2501aa5d6bedSChris Mason  *
2502aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
250397571fd0SChris Mason  */
2504e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
2505e02119d5SChris Mason 			       struct btrfs_root *root,
2506e02119d5SChris Mason 			       struct btrfs_path *path, int level)
2507be0e5c09SChris Mason {
25080b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
25095f39d397SChris Mason 	struct extent_buffer *c;
25105f39d397SChris Mason 	struct extent_buffer *split;
25115f39d397SChris Mason 	struct btrfs_disk_key disk_key;
2512be0e5c09SChris Mason 	int mid;
25135c680ed6SChris Mason 	int ret;
25147518a238SChris Mason 	u32 c_nritems;
2515be0e5c09SChris Mason 
25165f39d397SChris Mason 	c = path->nodes[level];
25177bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
25185f39d397SChris Mason 	if (c == root->node) {
2519d9abbf1cSJan Schmidt 		/*
252090f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
252190f8d62eSJan Schmidt 		 *
2522fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
252390f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
252490f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
2525f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2526f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
2527f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
2528d9abbf1cSJan Schmidt 		 */
2529fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
25305c680ed6SChris Mason 		if (ret)
25315c680ed6SChris Mason 			return ret;
2532b3612421SChris Mason 	} else {
2533e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
25345f39d397SChris Mason 		c = path->nodes[level];
25355f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
25360b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2537e66f709bSChris Mason 			return 0;
253854aa1f4dSChris Mason 		if (ret < 0)
253954aa1f4dSChris Mason 			return ret;
25405c680ed6SChris Mason 	}
2541e66f709bSChris Mason 
25425f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
25435d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
25445d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
25457bb86316SChris Mason 
254679bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
254779bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
254879bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
25495f39d397SChris Mason 	if (IS_ERR(split))
25505f39d397SChris Mason 		return PTR_ERR(split);
255154aa1f4dSChris Mason 
25520b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2553bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
25545f39d397SChris Mason 
2555f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
25565de865eeSFilipe David Borba Manana 	if (ret) {
255766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
25585de865eeSFilipe David Borba Manana 		return ret;
25595de865eeSFilipe David Borba Manana 	}
25605f39d397SChris Mason 	copy_extent_buffer(split, c,
25615f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
25625f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
2563123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
25645f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
25655f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
2566aa5d6bedSChris Mason 
25675f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
25685f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
25695f39d397SChris Mason 
25706ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
2571c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
2572aa5d6bedSChris Mason 
25735de08d7dSChris Mason 	if (path->slots[level] >= mid) {
25745c680ed6SChris Mason 		path->slots[level] -= mid;
2575925baeddSChris Mason 		btrfs_tree_unlock(c);
25765f39d397SChris Mason 		free_extent_buffer(c);
25775f39d397SChris Mason 		path->nodes[level] = split;
25785c680ed6SChris Mason 		path->slots[level + 1] += 1;
2579eb60ceacSChris Mason 	} else {
2580925baeddSChris Mason 		btrfs_tree_unlock(split);
25815f39d397SChris Mason 		free_extent_buffer(split);
2582be0e5c09SChris Mason 	}
2583d5286a92SNikolay Borisov 	return 0;
2584be0e5c09SChris Mason }
2585be0e5c09SChris Mason 
258674123bd7SChris Mason /*
258774123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
258874123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
258974123bd7SChris Mason  * space used both by the item structs and the item data
259074123bd7SChris Mason  */
25915f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2592be0e5c09SChris Mason {
259341be1f3bSJosef Bacik 	struct btrfs_item *start_item;
259441be1f3bSJosef Bacik 	struct btrfs_item *end_item;
2595be0e5c09SChris Mason 	int data_len;
25965f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
2597d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
2598be0e5c09SChris Mason 
2599be0e5c09SChris Mason 	if (!nr)
2600be0e5c09SChris Mason 		return 0;
2601dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
2602dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
2603a31356b9SDavid Sterba 	data_len = btrfs_item_offset(l, start_item) +
2604a31356b9SDavid Sterba 		   btrfs_item_size(l, start_item);
2605a31356b9SDavid Sterba 	data_len = data_len - btrfs_item_offset(l, end_item);
26060783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
2607d4dbff95SChris Mason 	WARN_ON(data_len < 0);
2608be0e5c09SChris Mason 	return data_len;
2609be0e5c09SChris Mason }
2610be0e5c09SChris Mason 
261174123bd7SChris Mason /*
2612d4dbff95SChris Mason  * The space between the end of the leaf items and
2613d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
2614d4dbff95SChris Mason  * the leaf has left for both items and data
2615d4dbff95SChris Mason  */
2616e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
2617d4dbff95SChris Mason {
2618e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
26195f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
26205f39d397SChris Mason 	int ret;
26210b246afaSJeff Mahoney 
26220b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
26235f39d397SChris Mason 	if (ret < 0) {
26240b246afaSJeff Mahoney 		btrfs_crit(fs_info,
2625efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2626da17066cSJeff Mahoney 			   ret,
26270b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
26285f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
26295f39d397SChris Mason 	}
26305f39d397SChris Mason 	return ret;
2631d4dbff95SChris Mason }
2632d4dbff95SChris Mason 
263399d8f83cSChris Mason /*
263499d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
263599d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
263699d8f83cSChris Mason  */
2637f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
263844871b1bSChris Mason 				      int data_size, int empty,
263944871b1bSChris Mason 				      struct extent_buffer *right,
264099d8f83cSChris Mason 				      int free_space, u32 left_nritems,
264199d8f83cSChris Mason 				      u32 min_slot)
264200ec4c51SChris Mason {
2643f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
26445f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
264544871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
2646cfed81a0SChris Mason 	struct btrfs_map_token token;
26475f39d397SChris Mason 	struct btrfs_disk_key disk_key;
264800ec4c51SChris Mason 	int slot;
264934a38218SChris Mason 	u32 i;
265000ec4c51SChris Mason 	int push_space = 0;
265100ec4c51SChris Mason 	int push_items = 0;
26520783fcfcSChris Mason 	struct btrfs_item *item;
265334a38218SChris Mason 	u32 nr;
26547518a238SChris Mason 	u32 right_nritems;
26555f39d397SChris Mason 	u32 data_end;
2656db94535dSChris Mason 	u32 this_item_size;
265700ec4c51SChris Mason 
265834a38218SChris Mason 	if (empty)
265934a38218SChris Mason 		nr = 0;
266034a38218SChris Mason 	else
266199d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
266234a38218SChris Mason 
266331840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
266487b29b20SYan Zheng 		push_space += data_size;
266531840ae1SZheng Yan 
266644871b1bSChris Mason 	slot = path->slots[1];
266734a38218SChris Mason 	i = left_nritems - 1;
266834a38218SChris Mason 	while (i >= nr) {
2669dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
2670db94535dSChris Mason 
267131840ae1SZheng Yan 		if (!empty && push_items > 0) {
267231840ae1SZheng Yan 			if (path->slots[0] > i)
267331840ae1SZheng Yan 				break;
267431840ae1SZheng Yan 			if (path->slots[0] == i) {
2675e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
2676e902baacSDavid Sterba 
267731840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
267831840ae1SZheng Yan 					break;
267931840ae1SZheng Yan 			}
268031840ae1SZheng Yan 		}
268131840ae1SZheng Yan 
268200ec4c51SChris Mason 		if (path->slots[0] == i)
268387b29b20SYan Zheng 			push_space += data_size;
2684db94535dSChris Mason 
2685db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
2686db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
268700ec4c51SChris Mason 			break;
268831840ae1SZheng Yan 
268900ec4c51SChris Mason 		push_items++;
2690db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
269134a38218SChris Mason 		if (i == 0)
269234a38218SChris Mason 			break;
269334a38218SChris Mason 		i--;
2694db94535dSChris Mason 	}
26955f39d397SChris Mason 
2696925baeddSChris Mason 	if (push_items == 0)
2697925baeddSChris Mason 		goto out_unlock;
26985f39d397SChris Mason 
26996c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
27005f39d397SChris Mason 
270100ec4c51SChris Mason 	/* push left to right */
27025f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
270334a38218SChris Mason 
27045f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
27058f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
27065f39d397SChris Mason 
270700ec4c51SChris Mason 	/* make room in the right data area */
27088f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
27095f39d397SChris Mason 	memmove_extent_buffer(right,
27103d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
27113d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
27120b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
27135f39d397SChris Mason 
271400ec4c51SChris Mason 	/* copy from the left data area */
27153d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
27160b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
27178f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
2718d6025579SChris Mason 		     push_space);
27195f39d397SChris Mason 
27205f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
27215f39d397SChris Mason 			      btrfs_item_nr_offset(0),
27220783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
27235f39d397SChris Mason 
272400ec4c51SChris Mason 	/* copy the items from left to right */
27255f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
27265f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
27270783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
272800ec4c51SChris Mason 
272900ec4c51SChris Mason 	/* update the item pointers */
2730c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
27317518a238SChris Mason 	right_nritems += push_items;
27325f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
27330b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
27347518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
2735dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
2736cc4c13d5SDavid Sterba 		push_space -= btrfs_token_item_size(&token, item);
2737cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, push_space);
2738db94535dSChris Mason 	}
2739db94535dSChris Mason 
27407518a238SChris Mason 	left_nritems -= push_items;
27415f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
274200ec4c51SChris Mason 
274334a38218SChris Mason 	if (left_nritems)
27445f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
2745f0486c68SYan, Zheng 	else
27466a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
2747f0486c68SYan, Zheng 
27485f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
2749a429e513SChris Mason 
27505f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
27515f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
2752d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
275302217ed2SChris Mason 
275400ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
27557518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
27567518a238SChris Mason 		path->slots[0] -= left_nritems;
2757925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
27586a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
2759925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
27605f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
27615f39d397SChris Mason 		path->nodes[0] = right;
276200ec4c51SChris Mason 		path->slots[1] += 1;
276300ec4c51SChris Mason 	} else {
2764925baeddSChris Mason 		btrfs_tree_unlock(right);
27655f39d397SChris Mason 		free_extent_buffer(right);
276600ec4c51SChris Mason 	}
276700ec4c51SChris Mason 	return 0;
2768925baeddSChris Mason 
2769925baeddSChris Mason out_unlock:
2770925baeddSChris Mason 	btrfs_tree_unlock(right);
2771925baeddSChris Mason 	free_extent_buffer(right);
2772925baeddSChris Mason 	return 1;
277300ec4c51SChris Mason }
2774925baeddSChris Mason 
277500ec4c51SChris Mason /*
277644871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
277774123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
277844871b1bSChris Mason  *
277944871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
278044871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
278199d8f83cSChris Mason  *
278299d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
278399d8f83cSChris Mason  * push any slot lower than min_slot
278474123bd7SChris Mason  */
278544871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
278699d8f83cSChris Mason 			   *root, struct btrfs_path *path,
278799d8f83cSChris Mason 			   int min_data_size, int data_size,
278899d8f83cSChris Mason 			   int empty, u32 min_slot)
2789be0e5c09SChris Mason {
279044871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
279144871b1bSChris Mason 	struct extent_buffer *right;
279244871b1bSChris Mason 	struct extent_buffer *upper;
279344871b1bSChris Mason 	int slot;
279444871b1bSChris Mason 	int free_space;
279544871b1bSChris Mason 	u32 left_nritems;
279644871b1bSChris Mason 	int ret;
279744871b1bSChris Mason 
279844871b1bSChris Mason 	if (!path->nodes[1])
279944871b1bSChris Mason 		return 1;
280044871b1bSChris Mason 
280144871b1bSChris Mason 	slot = path->slots[1];
280244871b1bSChris Mason 	upper = path->nodes[1];
280344871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
280444871b1bSChris Mason 		return 1;
280544871b1bSChris Mason 
280644871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
280744871b1bSChris Mason 
28084b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
2809fb770ae4SLiu Bo 	/*
2810fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
2811fb770ae4SLiu Bo 	 * no big deal, just return.
2812fb770ae4SLiu Bo 	 */
2813fb770ae4SLiu Bo 	if (IS_ERR(right))
281491ca338dSTsutomu Itoh 		return 1;
281591ca338dSTsutomu Itoh 
2816bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
281744871b1bSChris Mason 
2818e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
281944871b1bSChris Mason 	if (free_space < data_size)
282044871b1bSChris Mason 		goto out_unlock;
282144871b1bSChris Mason 
282244871b1bSChris Mason 	/* cow and double check */
282344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
2824bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
282544871b1bSChris Mason 	if (ret)
282644871b1bSChris Mason 		goto out_unlock;
282744871b1bSChris Mason 
2828e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
282944871b1bSChris Mason 	if (free_space < data_size)
283044871b1bSChris Mason 		goto out_unlock;
283144871b1bSChris Mason 
283244871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
283344871b1bSChris Mason 	if (left_nritems == 0)
283444871b1bSChris Mason 		goto out_unlock;
283544871b1bSChris Mason 
2836d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
2837d16c702fSQu Wenruo 		ret = -EUCLEAN;
2838d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
2839d16c702fSQu Wenruo 		free_extent_buffer(right);
2840d16c702fSQu Wenruo 		return ret;
2841d16c702fSQu Wenruo 	}
28422ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
28432ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
28442ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
28452ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
284652042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
28472ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
28482ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
28492ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
28502ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
28512ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
28522ef1fed2SFilipe David Borba Manana 		return 0;
28532ef1fed2SFilipe David Borba Manana 	}
28542ef1fed2SFilipe David Borba Manana 
2855f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
285699d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
285744871b1bSChris Mason out_unlock:
285844871b1bSChris Mason 	btrfs_tree_unlock(right);
285944871b1bSChris Mason 	free_extent_buffer(right);
286044871b1bSChris Mason 	return 1;
286144871b1bSChris Mason }
286244871b1bSChris Mason 
286344871b1bSChris Mason /*
286444871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
286544871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
286699d8f83cSChris Mason  *
286799d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
286899d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
286999d8f83cSChris Mason  * items
287044871b1bSChris Mason  */
28718087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
287244871b1bSChris Mason 				     int empty, struct extent_buffer *left,
287399d8f83cSChris Mason 				     int free_space, u32 right_nritems,
287499d8f83cSChris Mason 				     u32 max_slot)
287544871b1bSChris Mason {
28768087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
28775f39d397SChris Mason 	struct btrfs_disk_key disk_key;
28785f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
2879be0e5c09SChris Mason 	int i;
2880be0e5c09SChris Mason 	int push_space = 0;
2881be0e5c09SChris Mason 	int push_items = 0;
28820783fcfcSChris Mason 	struct btrfs_item *item;
28837518a238SChris Mason 	u32 old_left_nritems;
288434a38218SChris Mason 	u32 nr;
2885aa5d6bedSChris Mason 	int ret = 0;
2886db94535dSChris Mason 	u32 this_item_size;
2887db94535dSChris Mason 	u32 old_left_item_size;
2888cfed81a0SChris Mason 	struct btrfs_map_token token;
2889cfed81a0SChris Mason 
289034a38218SChris Mason 	if (empty)
289199d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
289234a38218SChris Mason 	else
289399d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
289434a38218SChris Mason 
289534a38218SChris Mason 	for (i = 0; i < nr; i++) {
2896dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
2897db94535dSChris Mason 
289831840ae1SZheng Yan 		if (!empty && push_items > 0) {
289931840ae1SZheng Yan 			if (path->slots[0] < i)
290031840ae1SZheng Yan 				break;
290131840ae1SZheng Yan 			if (path->slots[0] == i) {
2902e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
2903e902baacSDavid Sterba 
290431840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
290531840ae1SZheng Yan 					break;
290631840ae1SZheng Yan 			}
290731840ae1SZheng Yan 		}
290831840ae1SZheng Yan 
2909be0e5c09SChris Mason 		if (path->slots[0] == i)
291087b29b20SYan Zheng 			push_space += data_size;
2911db94535dSChris Mason 
2912db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
2913db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
2914be0e5c09SChris Mason 			break;
2915db94535dSChris Mason 
2916be0e5c09SChris Mason 		push_items++;
2917db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
2918be0e5c09SChris Mason 	}
2919db94535dSChris Mason 
2920be0e5c09SChris Mason 	if (push_items == 0) {
2921925baeddSChris Mason 		ret = 1;
2922925baeddSChris Mason 		goto out;
2923be0e5c09SChris Mason 	}
2924fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
29255f39d397SChris Mason 
2926be0e5c09SChris Mason 	/* push data from right to left */
29275f39d397SChris Mason 	copy_extent_buffer(left, right,
29285f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
29295f39d397SChris Mason 			   btrfs_item_nr_offset(0),
29305f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
29315f39d397SChris Mason 
29320b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
29335f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
29345f39d397SChris Mason 
29353d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
29368f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
29373d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
29385f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
2939be0e5c09SChris Mason 		     push_space);
29405f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
294187b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
2942eb60ceacSChris Mason 
2943c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
2944db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
2945be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
29465f39d397SChris Mason 		u32 ioff;
2947db94535dSChris Mason 
2948dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
2949db94535dSChris Mason 
2950cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
2951cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item,
2952cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
2953be0e5c09SChris Mason 	}
29545f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
2955be0e5c09SChris Mason 
2956be0e5c09SChris Mason 	/* fixup right node */
295731b1a2bdSJulia Lawall 	if (push_items > right_nritems)
295831b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
2959d397712bSChris Mason 		       right_nritems);
296034a38218SChris Mason 
296134a38218SChris Mason 	if (push_items < right_nritems) {
29625f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
29638f881e8cSDavid Sterba 						  leaf_data_end(right);
29643d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
29650b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
29663d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
29678f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
29685f39d397SChris Mason 
29695f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
29705f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
29715f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
29720783fcfcSChris Mason 			     sizeof(struct btrfs_item));
297334a38218SChris Mason 	}
2974c82f823cSDavid Sterba 
2975c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
2976eef1c494SYan 	right_nritems -= push_items;
2977eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
29780b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
29795f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
2980dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
2981db94535dSChris Mason 
2982cc4c13d5SDavid Sterba 		push_space = push_space - btrfs_token_item_size(&token, item);
2983cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, push_space);
2984db94535dSChris Mason 	}
2985eb60ceacSChris Mason 
29865f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
298734a38218SChris Mason 	if (right_nritems)
29885f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
2989f0486c68SYan, Zheng 	else
29906a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
2991098f59c2SChris Mason 
29925f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
2993b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
2994be0e5c09SChris Mason 
2995be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
2996be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
2997be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
2998925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
29995f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
30005f39d397SChris Mason 		path->nodes[0] = left;
3001be0e5c09SChris Mason 		path->slots[1] -= 1;
3002be0e5c09SChris Mason 	} else {
3003925baeddSChris Mason 		btrfs_tree_unlock(left);
30045f39d397SChris Mason 		free_extent_buffer(left);
3005be0e5c09SChris Mason 		path->slots[0] -= push_items;
3006be0e5c09SChris Mason 	}
3007eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3008aa5d6bedSChris Mason 	return ret;
3009925baeddSChris Mason out:
3010925baeddSChris Mason 	btrfs_tree_unlock(left);
3011925baeddSChris Mason 	free_extent_buffer(left);
3012925baeddSChris Mason 	return ret;
3013be0e5c09SChris Mason }
3014be0e5c09SChris Mason 
301574123bd7SChris Mason /*
301644871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
301744871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
301899d8f83cSChris Mason  *
301999d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
302099d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
302199d8f83cSChris Mason  * items
302244871b1bSChris Mason  */
302344871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
302499d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
302599d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
302644871b1bSChris Mason {
302744871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
302844871b1bSChris Mason 	struct extent_buffer *left;
302944871b1bSChris Mason 	int slot;
303044871b1bSChris Mason 	int free_space;
303144871b1bSChris Mason 	u32 right_nritems;
303244871b1bSChris Mason 	int ret = 0;
303344871b1bSChris Mason 
303444871b1bSChris Mason 	slot = path->slots[1];
303544871b1bSChris Mason 	if (slot == 0)
303644871b1bSChris Mason 		return 1;
303744871b1bSChris Mason 	if (!path->nodes[1])
303844871b1bSChris Mason 		return 1;
303944871b1bSChris Mason 
304044871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
304144871b1bSChris Mason 	if (right_nritems == 0)
304244871b1bSChris Mason 		return 1;
304344871b1bSChris Mason 
304444871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
304544871b1bSChris Mason 
30464b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3047fb770ae4SLiu Bo 	/*
3048fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3049fb770ae4SLiu Bo 	 * no big deal, just return.
3050fb770ae4SLiu Bo 	 */
3051fb770ae4SLiu Bo 	if (IS_ERR(left))
305291ca338dSTsutomu Itoh 		return 1;
305391ca338dSTsutomu Itoh 
3054bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
305544871b1bSChris Mason 
3056e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
305744871b1bSChris Mason 	if (free_space < data_size) {
305844871b1bSChris Mason 		ret = 1;
305944871b1bSChris Mason 		goto out;
306044871b1bSChris Mason 	}
306144871b1bSChris Mason 
306244871b1bSChris Mason 	/* cow and double check */
306344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
30649631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3065bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
306644871b1bSChris Mason 	if (ret) {
306744871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
306879787eaaSJeff Mahoney 		if (ret == -ENOSPC)
306944871b1bSChris Mason 			ret = 1;
307044871b1bSChris Mason 		goto out;
307144871b1bSChris Mason 	}
307244871b1bSChris Mason 
3073e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
307444871b1bSChris Mason 	if (free_space < data_size) {
307544871b1bSChris Mason 		ret = 1;
307644871b1bSChris Mason 		goto out;
307744871b1bSChris Mason 	}
307844871b1bSChris Mason 
3079d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3080d16c702fSQu Wenruo 		ret = -EUCLEAN;
3081d16c702fSQu Wenruo 		goto out;
3082d16c702fSQu Wenruo 	}
30838087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
308499d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
308599d8f83cSChris Mason 			       max_slot);
308644871b1bSChris Mason out:
308744871b1bSChris Mason 	btrfs_tree_unlock(left);
308844871b1bSChris Mason 	free_extent_buffer(left);
308944871b1bSChris Mason 	return ret;
309044871b1bSChris Mason }
309144871b1bSChris Mason 
309244871b1bSChris Mason /*
309374123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
309474123bd7SChris Mason  * available for the resulting leaf level of the path.
309574123bd7SChris Mason  */
3096143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
309744871b1bSChris Mason 				    struct btrfs_path *path,
309844871b1bSChris Mason 				    struct extent_buffer *l,
309944871b1bSChris Mason 				    struct extent_buffer *right,
310044871b1bSChris Mason 				    int slot, int mid, int nritems)
3101be0e5c09SChris Mason {
310294f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3103be0e5c09SChris Mason 	int data_copy_size;
3104be0e5c09SChris Mason 	int rt_data_off;
3105be0e5c09SChris Mason 	int i;
3106d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3107cfed81a0SChris Mason 	struct btrfs_map_token token;
3108cfed81a0SChris Mason 
31095f39d397SChris Mason 	nritems = nritems - mid;
31105f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
31118f881e8cSDavid Sterba 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
31125f39d397SChris Mason 
31135f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
31145f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
31155f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
31165f39d397SChris Mason 
31175f39d397SChris Mason 	copy_extent_buffer(right, l,
31183d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
31193d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
31208f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
312174123bd7SChris Mason 
31220b246afaSJeff Mahoney 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
31235f39d397SChris Mason 
3124c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
31255f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3126dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
3127db94535dSChris Mason 		u32 ioff;
3128db94535dSChris Mason 
3129cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
3130cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff + rt_data_off);
31310783fcfcSChris Mason 	}
313274123bd7SChris Mason 
31335f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
31345f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
31356ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
31365f39d397SChris Mason 
31375f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
31385f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3139eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
31405f39d397SChris Mason 
3141be0e5c09SChris Mason 	if (mid <= slot) {
3142925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
31435f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
31445f39d397SChris Mason 		path->nodes[0] = right;
3145be0e5c09SChris Mason 		path->slots[0] -= mid;
3146be0e5c09SChris Mason 		path->slots[1] += 1;
3147925baeddSChris Mason 	} else {
3148925baeddSChris Mason 		btrfs_tree_unlock(right);
31495f39d397SChris Mason 		free_extent_buffer(right);
3150925baeddSChris Mason 	}
31515f39d397SChris Mason 
3152eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
315344871b1bSChris Mason }
315444871b1bSChris Mason 
315544871b1bSChris Mason /*
315699d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
315799d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
315899d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
315999d8f83cSChris Mason  *          A                 B                 C
316099d8f83cSChris Mason  *
316199d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
316299d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
316399d8f83cSChris Mason  * completely.
316499d8f83cSChris Mason  */
316599d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
316699d8f83cSChris Mason 					  struct btrfs_root *root,
316799d8f83cSChris Mason 					  struct btrfs_path *path,
316899d8f83cSChris Mason 					  int data_size)
316999d8f83cSChris Mason {
317099d8f83cSChris Mason 	int ret;
317199d8f83cSChris Mason 	int progress = 0;
317299d8f83cSChris Mason 	int slot;
317399d8f83cSChris Mason 	u32 nritems;
31745a4267caSFilipe David Borba Manana 	int space_needed = data_size;
317599d8f83cSChris Mason 
317699d8f83cSChris Mason 	slot = path->slots[0];
31775a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3178e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
317999d8f83cSChris Mason 
318099d8f83cSChris Mason 	/*
318199d8f83cSChris Mason 	 * try to push all the items after our slot into the
318299d8f83cSChris Mason 	 * right leaf
318399d8f83cSChris Mason 	 */
31845a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
318599d8f83cSChris Mason 	if (ret < 0)
318699d8f83cSChris Mason 		return ret;
318799d8f83cSChris Mason 
318899d8f83cSChris Mason 	if (ret == 0)
318999d8f83cSChris Mason 		progress++;
319099d8f83cSChris Mason 
319199d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
319299d8f83cSChris Mason 	/*
319399d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
319499d8f83cSChris Mason 	 * we've done so we're done
319599d8f83cSChris Mason 	 */
319699d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
319799d8f83cSChris Mason 		return 0;
319899d8f83cSChris Mason 
3199e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
320099d8f83cSChris Mason 		return 0;
320199d8f83cSChris Mason 
320299d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
320399d8f83cSChris Mason 	slot = path->slots[0];
3204263d3995SFilipe Manana 	space_needed = data_size;
3205263d3995SFilipe Manana 	if (slot > 0)
3206e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
32075a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
320899d8f83cSChris Mason 	if (ret < 0)
320999d8f83cSChris Mason 		return ret;
321099d8f83cSChris Mason 
321199d8f83cSChris Mason 	if (ret == 0)
321299d8f83cSChris Mason 		progress++;
321399d8f83cSChris Mason 
321499d8f83cSChris Mason 	if (progress)
321599d8f83cSChris Mason 		return 0;
321699d8f83cSChris Mason 	return 1;
321799d8f83cSChris Mason }
321899d8f83cSChris Mason 
321999d8f83cSChris Mason /*
322044871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
322144871b1bSChris Mason  * available for the resulting leaf level of the path.
322244871b1bSChris Mason  *
322344871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
322444871b1bSChris Mason  */
322544871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
322644871b1bSChris Mason 			       struct btrfs_root *root,
3227310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
322844871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
322944871b1bSChris Mason 			       int extend)
323044871b1bSChris Mason {
32315d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
323244871b1bSChris Mason 	struct extent_buffer *l;
323344871b1bSChris Mason 	u32 nritems;
323444871b1bSChris Mason 	int mid;
323544871b1bSChris Mason 	int slot;
323644871b1bSChris Mason 	struct extent_buffer *right;
3237b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
323844871b1bSChris Mason 	int ret = 0;
323944871b1bSChris Mason 	int wret;
32405d4f98a2SYan Zheng 	int split;
324144871b1bSChris Mason 	int num_doubles = 0;
324299d8f83cSChris Mason 	int tried_avoid_double = 0;
324344871b1bSChris Mason 
3244a5719521SYan, Zheng 	l = path->nodes[0];
3245a5719521SYan, Zheng 	slot = path->slots[0];
3246a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
32470b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3248a5719521SYan, Zheng 		return -EOVERFLOW;
3249a5719521SYan, Zheng 
325044871b1bSChris Mason 	/* first try to make some room by pushing left and right */
325133157e05SLiu Bo 	if (data_size && path->nodes[1]) {
32525a4267caSFilipe David Borba Manana 		int space_needed = data_size;
32535a4267caSFilipe David Borba Manana 
32545a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3255e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
32565a4267caSFilipe David Borba Manana 
32575a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
32585a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
325944871b1bSChris Mason 		if (wret < 0)
326044871b1bSChris Mason 			return wret;
326144871b1bSChris Mason 		if (wret) {
3262263d3995SFilipe Manana 			space_needed = data_size;
3263263d3995SFilipe Manana 			if (slot > 0)
3264e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
32655a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
32665a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
326744871b1bSChris Mason 			if (wret < 0)
326844871b1bSChris Mason 				return wret;
326944871b1bSChris Mason 		}
327044871b1bSChris Mason 		l = path->nodes[0];
327144871b1bSChris Mason 
327244871b1bSChris Mason 		/* did the pushes work? */
3273e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
327444871b1bSChris Mason 			return 0;
327544871b1bSChris Mason 	}
327644871b1bSChris Mason 
327744871b1bSChris Mason 	if (!path->nodes[1]) {
3278fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
327944871b1bSChris Mason 		if (ret)
328044871b1bSChris Mason 			return ret;
328144871b1bSChris Mason 	}
328244871b1bSChris Mason again:
32835d4f98a2SYan Zheng 	split = 1;
328444871b1bSChris Mason 	l = path->nodes[0];
328544871b1bSChris Mason 	slot = path->slots[0];
328644871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
328744871b1bSChris Mason 	mid = (nritems + 1) / 2;
328844871b1bSChris Mason 
32895d4f98a2SYan Zheng 	if (mid <= slot) {
32905d4f98a2SYan Zheng 		if (nritems == 1 ||
32915d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
32920b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
32935d4f98a2SYan Zheng 			if (slot >= nritems) {
32945d4f98a2SYan Zheng 				split = 0;
32955d4f98a2SYan Zheng 			} else {
32965d4f98a2SYan Zheng 				mid = slot;
32975d4f98a2SYan Zheng 				if (mid != nritems &&
32985d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
32990b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
330099d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
330199d8f83cSChris Mason 						goto push_for_double;
33025d4f98a2SYan Zheng 					split = 2;
33035d4f98a2SYan Zheng 				}
33045d4f98a2SYan Zheng 			}
33055d4f98a2SYan Zheng 		}
33065d4f98a2SYan Zheng 	} else {
33075d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
33080b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
33095d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
33105d4f98a2SYan Zheng 				split = 0;
33115d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
33125d4f98a2SYan Zheng 				mid = 1;
33135d4f98a2SYan Zheng 			} else {
33145d4f98a2SYan Zheng 				mid = slot;
33155d4f98a2SYan Zheng 				if (mid != nritems &&
33165d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
33170b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
331899d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
331999d8f83cSChris Mason 						goto push_for_double;
33205d4f98a2SYan Zheng 					split = 2;
33215d4f98a2SYan Zheng 				}
33225d4f98a2SYan Zheng 			}
33235d4f98a2SYan Zheng 		}
33245d4f98a2SYan Zheng 	}
33255d4f98a2SYan Zheng 
33265d4f98a2SYan Zheng 	if (split == 0)
33275d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
33285d4f98a2SYan Zheng 	else
33295d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
33305d4f98a2SYan Zheng 
3331ca9d473aSJosef Bacik 	/*
3332ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3333ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3334ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3335ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3336ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3337ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3338ca9d473aSJosef Bacik 	 */
333979bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
334079bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
334179bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3342ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3343f0486c68SYan, Zheng 	if (IS_ERR(right))
334444871b1bSChris Mason 		return PTR_ERR(right);
3345f0486c68SYan, Zheng 
33460b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
334744871b1bSChris Mason 
33485d4f98a2SYan Zheng 	if (split == 0) {
334944871b1bSChris Mason 		if (mid <= slot) {
335044871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
33516ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
33522ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
335344871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
335444871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
335544871b1bSChris Mason 			path->nodes[0] = right;
335644871b1bSChris Mason 			path->slots[0] = 0;
335744871b1bSChris Mason 			path->slots[1] += 1;
335844871b1bSChris Mason 		} else {
335944871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
33606ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
33612ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
336244871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
336344871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
336444871b1bSChris Mason 			path->nodes[0] = right;
336544871b1bSChris Mason 			path->slots[0] = 0;
3366143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3367b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
33685d4f98a2SYan Zheng 		}
3369196e0249SLiu Bo 		/*
3370196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3371196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3372196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3373196e0249SLiu Bo 		 */
337444871b1bSChris Mason 		return ret;
337544871b1bSChris Mason 	}
337644871b1bSChris Mason 
337794f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
337844871b1bSChris Mason 
33795d4f98a2SYan Zheng 	if (split == 2) {
3380cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3381cc0c5538SChris Mason 		num_doubles++;
3382cc0c5538SChris Mason 		goto again;
33833326d1b0SChris Mason 	}
338444871b1bSChris Mason 
3385143bede5SJeff Mahoney 	return 0;
338699d8f83cSChris Mason 
338799d8f83cSChris Mason push_for_double:
338899d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
338999d8f83cSChris Mason 	tried_avoid_double = 1;
3390e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
339199d8f83cSChris Mason 		return 0;
339299d8f83cSChris Mason 	goto again;
3393be0e5c09SChris Mason }
3394be0e5c09SChris Mason 
3395ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3396ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3397ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3398ad48fd75SYan, Zheng {
3399ad48fd75SYan, Zheng 	struct btrfs_key key;
3400ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3401ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3402ad48fd75SYan, Zheng 	u64 extent_len = 0;
3403ad48fd75SYan, Zheng 	u32 item_size;
3404ad48fd75SYan, Zheng 	int ret;
3405ad48fd75SYan, Zheng 
3406ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3407ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3408ad48fd75SYan, Zheng 
3409ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3410ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3411ad48fd75SYan, Zheng 
3412e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3413ad48fd75SYan, Zheng 		return 0;
3414ad48fd75SYan, Zheng 
3415ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3416ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3417ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3418ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3419ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3420ad48fd75SYan, Zheng 	}
3421b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3422ad48fd75SYan, Zheng 
3423ad48fd75SYan, Zheng 	path->keep_locks = 1;
3424ad48fd75SYan, Zheng 	path->search_for_split = 1;
3425ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3426ad48fd75SYan, Zheng 	path->search_for_split = 0;
3427a8df6fe6SFilipe Manana 	if (ret > 0)
3428a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3429ad48fd75SYan, Zheng 	if (ret < 0)
3430ad48fd75SYan, Zheng 		goto err;
3431ad48fd75SYan, Zheng 
3432ad48fd75SYan, Zheng 	ret = -EAGAIN;
3433ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3434a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
3435a8df6fe6SFilipe Manana 	if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
3436ad48fd75SYan, Zheng 		goto err;
3437ad48fd75SYan, Zheng 
3438109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3439e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3440109f6aefSChris Mason 		goto err;
3441109f6aefSChris Mason 
3442ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3443ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3444ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3445ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3446ad48fd75SYan, Zheng 			goto err;
3447ad48fd75SYan, Zheng 	}
3448ad48fd75SYan, Zheng 
3449ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3450f0486c68SYan, Zheng 	if (ret)
3451f0486c68SYan, Zheng 		goto err;
3452ad48fd75SYan, Zheng 
3453ad48fd75SYan, Zheng 	path->keep_locks = 0;
3454ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3455ad48fd75SYan, Zheng 	return 0;
3456ad48fd75SYan, Zheng err:
3457ad48fd75SYan, Zheng 	path->keep_locks = 0;
3458ad48fd75SYan, Zheng 	return ret;
3459ad48fd75SYan, Zheng }
3460ad48fd75SYan, Zheng 
346125263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3462310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3463459931ecSChris Mason 			       unsigned long split_offset)
3464459931ecSChris Mason {
3465459931ecSChris Mason 	struct extent_buffer *leaf;
3466459931ecSChris Mason 	struct btrfs_item *item;
3467459931ecSChris Mason 	struct btrfs_item *new_item;
3468459931ecSChris Mason 	int slot;
3469ad48fd75SYan, Zheng 	char *buf;
3470459931ecSChris Mason 	u32 nritems;
3471ad48fd75SYan, Zheng 	u32 item_size;
3472459931ecSChris Mason 	u32 orig_offset;
3473459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3474459931ecSChris Mason 
3475459931ecSChris Mason 	leaf = path->nodes[0];
3476e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3477b9473439SChris Mason 
3478dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
3479459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
3480459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
3481459931ecSChris Mason 
3482459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3483ad48fd75SYan, Zheng 	if (!buf)
3484ad48fd75SYan, Zheng 		return -ENOMEM;
3485ad48fd75SYan, Zheng 
3486459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3487459931ecSChris Mason 			    path->slots[0]), item_size);
3488ad48fd75SYan, Zheng 
3489459931ecSChris Mason 	slot = path->slots[0] + 1;
3490459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3491459931ecSChris Mason 	if (slot != nritems) {
3492459931ecSChris Mason 		/* shift the items */
3493459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3494459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3495459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3496459931ecSChris Mason 	}
3497459931ecSChris Mason 
3498459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3499459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3500459931ecSChris Mason 
3501dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
3502459931ecSChris Mason 
3503459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
3504459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
3505459931ecSChris Mason 
3506459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
3507459931ecSChris Mason 			      orig_offset + item_size - split_offset);
3508459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
3509459931ecSChris Mason 
3510459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3511459931ecSChris Mason 
3512459931ecSChris Mason 	/* write the data for the start of the original item */
3513459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3514459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3515459931ecSChris Mason 			    split_offset);
3516459931ecSChris Mason 
3517459931ecSChris Mason 	/* write the data for the new item */
3518459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3519459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3520459931ecSChris Mason 			    item_size - split_offset);
3521459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3522459931ecSChris Mason 
3523e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3524459931ecSChris Mason 	kfree(buf);
3525ad48fd75SYan, Zheng 	return 0;
3526ad48fd75SYan, Zheng }
3527ad48fd75SYan, Zheng 
3528ad48fd75SYan, Zheng /*
3529ad48fd75SYan, Zheng  * This function splits a single item into two items,
3530ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3531ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3532ad48fd75SYan, Zheng  *
3533ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3534ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3535ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3536ad48fd75SYan, Zheng  *
3537ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3538ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3539ad48fd75SYan, Zheng  *
3540ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3541ad48fd75SYan, Zheng  * leaf the entire time.
3542ad48fd75SYan, Zheng  */
3543ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3544ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3545ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3546310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3547ad48fd75SYan, Zheng 		     unsigned long split_offset)
3548ad48fd75SYan, Zheng {
3549ad48fd75SYan, Zheng 	int ret;
3550ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3551ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3552ad48fd75SYan, Zheng 	if (ret)
3553459931ecSChris Mason 		return ret;
3554ad48fd75SYan, Zheng 
355525263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3556ad48fd75SYan, Zheng 	return ret;
3557ad48fd75SYan, Zheng }
3558ad48fd75SYan, Zheng 
3559ad48fd75SYan, Zheng /*
3560ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
3561ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
3562ad48fd75SYan, Zheng  * is contiguous with the original item.
3563ad48fd75SYan, Zheng  *
3564ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
3565ad48fd75SYan, Zheng  * leaf the entire time.
3566ad48fd75SYan, Zheng  */
3567ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
3568ad48fd75SYan, Zheng 			 struct btrfs_root *root,
3569ad48fd75SYan, Zheng 			 struct btrfs_path *path,
3570310712b2SOmar Sandoval 			 const struct btrfs_key *new_key)
3571ad48fd75SYan, Zheng {
3572ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3573ad48fd75SYan, Zheng 	int ret;
3574ad48fd75SYan, Zheng 	u32 item_size;
3575ad48fd75SYan, Zheng 
3576ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3577ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3578ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3579ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
3580ad48fd75SYan, Zheng 	if (ret)
3581ad48fd75SYan, Zheng 		return ret;
3582ad48fd75SYan, Zheng 
3583ad48fd75SYan, Zheng 	path->slots[0]++;
3584fc0d82e1SNikolay Borisov 	setup_items_for_insert(root, path, new_key, &item_size, 1);
3585ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3586ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
3587ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
3588ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
3589ad48fd75SYan, Zheng 			     item_size);
3590ad48fd75SYan, Zheng 	return 0;
3591459931ecSChris Mason }
3592459931ecSChris Mason 
3593459931ecSChris Mason /*
3594d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
3595d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
3596d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
3597d352ac68SChris Mason  * the front.
3598d352ac68SChris Mason  */
359978ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3600b18c6685SChris Mason {
3601b18c6685SChris Mason 	int slot;
36025f39d397SChris Mason 	struct extent_buffer *leaf;
36035f39d397SChris Mason 	struct btrfs_item *item;
3604b18c6685SChris Mason 	u32 nritems;
3605b18c6685SChris Mason 	unsigned int data_end;
3606b18c6685SChris Mason 	unsigned int old_data_start;
3607b18c6685SChris Mason 	unsigned int old_size;
3608b18c6685SChris Mason 	unsigned int size_diff;
3609b18c6685SChris Mason 	int i;
3610cfed81a0SChris Mason 	struct btrfs_map_token token;
3611cfed81a0SChris Mason 
36125f39d397SChris Mason 	leaf = path->nodes[0];
3613179e29e4SChris Mason 	slot = path->slots[0];
3614179e29e4SChris Mason 
3615179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
3616179e29e4SChris Mason 	if (old_size == new_size)
3617143bede5SJeff Mahoney 		return;
3618b18c6685SChris Mason 
36195f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
36208f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3621b18c6685SChris Mason 
36225f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
3623179e29e4SChris Mason 
3624b18c6685SChris Mason 	size_diff = old_size - new_size;
3625b18c6685SChris Mason 
3626b18c6685SChris Mason 	BUG_ON(slot < 0);
3627b18c6685SChris Mason 	BUG_ON(slot >= nritems);
3628b18c6685SChris Mason 
3629b18c6685SChris Mason 	/*
3630b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3631b18c6685SChris Mason 	 */
3632b18c6685SChris Mason 	/* first correct the data pointers */
3633c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3634b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
36355f39d397SChris Mason 		u32 ioff;
3636dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3637db94535dSChris Mason 
3638cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
3639cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff + size_diff);
3640b18c6685SChris Mason 	}
3641db94535dSChris Mason 
3642b18c6685SChris Mason 	/* shift the data */
3643179e29e4SChris Mason 	if (from_end) {
36443d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
36453d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3646b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
3647179e29e4SChris Mason 	} else {
3648179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
3649179e29e4SChris Mason 		u64 offset;
3650179e29e4SChris Mason 
3651179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
3652179e29e4SChris Mason 
3653179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3654179e29e4SChris Mason 			unsigned long ptr;
3655179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
3656179e29e4SChris Mason 
3657179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
3658179e29e4SChris Mason 					    struct btrfs_file_extent_item);
3659179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
3660179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
3661179e29e4SChris Mason 
3662179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
3663179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
3664179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
3665179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
3666179e29e4SChris Mason 				      (unsigned long)fi,
36677ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
3668179e29e4SChris Mason 			}
3669179e29e4SChris Mason 		}
3670179e29e4SChris Mason 
36713d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
36723d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3673179e29e4SChris Mason 			      data_end, old_data_start - data_end);
3674179e29e4SChris Mason 
3675179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
3676179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3677179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
3678179e29e4SChris Mason 		if (slot == 0)
3679b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
3680179e29e4SChris Mason 	}
36815f39d397SChris Mason 
3682dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
36835f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
36845f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3685b18c6685SChris Mason 
3686e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3687a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3688b18c6685SChris Mason 		BUG();
36895f39d397SChris Mason 	}
3690b18c6685SChris Mason }
3691b18c6685SChris Mason 
3692d352ac68SChris Mason /*
36938f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
3694d352ac68SChris Mason  */
3695c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
36966567e837SChris Mason {
36976567e837SChris Mason 	int slot;
36985f39d397SChris Mason 	struct extent_buffer *leaf;
36995f39d397SChris Mason 	struct btrfs_item *item;
37006567e837SChris Mason 	u32 nritems;
37016567e837SChris Mason 	unsigned int data_end;
37026567e837SChris Mason 	unsigned int old_data;
37036567e837SChris Mason 	unsigned int old_size;
37046567e837SChris Mason 	int i;
3705cfed81a0SChris Mason 	struct btrfs_map_token token;
3706cfed81a0SChris Mason 
37075f39d397SChris Mason 	leaf = path->nodes[0];
37086567e837SChris Mason 
37095f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
37108f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
37116567e837SChris Mason 
3712e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
3713a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
37146567e837SChris Mason 		BUG();
37155f39d397SChris Mason 	}
37166567e837SChris Mason 	slot = path->slots[0];
37175f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
37186567e837SChris Mason 
37196567e837SChris Mason 	BUG_ON(slot < 0);
37203326d1b0SChris Mason 	if (slot >= nritems) {
3721a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3722c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
3723d397712bSChris Mason 			   slot, nritems);
3724290342f6SArnd Bergmann 		BUG();
37253326d1b0SChris Mason 	}
37266567e837SChris Mason 
37276567e837SChris Mason 	/*
37286567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
37296567e837SChris Mason 	 */
37306567e837SChris Mason 	/* first correct the data pointers */
3731c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
37326567e837SChris Mason 	for (i = slot; i < nritems; i++) {
37335f39d397SChris Mason 		u32 ioff;
3734dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3735db94535dSChris Mason 
3736cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
3737cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff - data_size);
37386567e837SChris Mason 	}
37395f39d397SChris Mason 
37406567e837SChris Mason 	/* shift the data */
37413d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
37423d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
37436567e837SChris Mason 		      data_end, old_data - data_end);
37445f39d397SChris Mason 
37456567e837SChris Mason 	data_end = old_data;
37465f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
3747dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
37485f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
37495f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
37506567e837SChris Mason 
3751e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3752a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
37536567e837SChris Mason 		BUG();
37545f39d397SChris Mason 	}
37556567e837SChris Mason }
37566567e837SChris Mason 
3757da9ffb24SNikolay Borisov /**
3758da9ffb24SNikolay Borisov  * setup_items_for_insert - Helper called before inserting one or more items
3759da9ffb24SNikolay Borisov  * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
3760da9ffb24SNikolay Borisov  * in a function that doesn't call btrfs_search_slot
3761da9ffb24SNikolay Borisov  *
3762da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
3763da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
3764da9ffb24SNikolay Borisov  * @cpu_key:	array of keys for items to be inserted
3765da9ffb24SNikolay Borisov  * @data_size:	size of the body of each item we are going to insert
3766da9ffb24SNikolay Borisov  * @nr:		size of @cpu_key/@data_size arrays
376774123bd7SChris Mason  */
3768afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
3769310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
3770fc0d82e1SNikolay Borisov 			    int nr)
3771be0e5c09SChris Mason {
37720b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
37735f39d397SChris Mason 	struct btrfs_item *item;
37749c58309dSChris Mason 	int i;
37757518a238SChris Mason 	u32 nritems;
3776be0e5c09SChris Mason 	unsigned int data_end;
3777e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
377844871b1bSChris Mason 	struct extent_buffer *leaf;
377944871b1bSChris Mason 	int slot;
3780cfed81a0SChris Mason 	struct btrfs_map_token token;
3781fc0d82e1SNikolay Borisov 	u32 total_size;
3782fc0d82e1SNikolay Borisov 	u32 total_data = 0;
3783fc0d82e1SNikolay Borisov 
3784fc0d82e1SNikolay Borisov 	for (i = 0; i < nr; i++)
3785fc0d82e1SNikolay Borisov 		total_data += data_size[i];
3786fc0d82e1SNikolay Borisov 	total_size = total_data + (nr * sizeof(struct btrfs_item));
3787cfed81a0SChris Mason 
378824cdc847SFilipe Manana 	if (path->slots[0] == 0) {
378924cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
3790b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
379124cdc847SFilipe Manana 	}
379224cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
379324cdc847SFilipe Manana 
37945f39d397SChris Mason 	leaf = path->nodes[0];
379544871b1bSChris Mason 	slot = path->slots[0];
379674123bd7SChris Mason 
37975f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
37988f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3799eb60ceacSChris Mason 
3800e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
3801a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
38020b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
3803e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
3804be0e5c09SChris Mason 		BUG();
3805d4dbff95SChris Mason 	}
38065f39d397SChris Mason 
3807c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3808be0e5c09SChris Mason 	if (slot != nritems) {
38095f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
3810be0e5c09SChris Mason 
38115f39d397SChris Mason 		if (old_data < data_end) {
3812a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
38137269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
38147269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
38155f39d397SChris Mason 				   slot, old_data, data_end);
3816290342f6SArnd Bergmann 			BUG();
38175f39d397SChris Mason 		}
3818be0e5c09SChris Mason 		/*
3819be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3820be0e5c09SChris Mason 		 */
3821be0e5c09SChris Mason 		/* first correct the data pointers */
38220783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
38235f39d397SChris Mason 			u32 ioff;
3824db94535dSChris Mason 
3825dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
3826cc4c13d5SDavid Sterba 			ioff = btrfs_token_item_offset(&token, item);
3827cc4c13d5SDavid Sterba 			btrfs_set_token_item_offset(&token, item,
3828cc4c13d5SDavid Sterba 						    ioff - total_data);
38290783fcfcSChris Mason 		}
3830be0e5c09SChris Mason 		/* shift the items */
38319c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
38325f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
38330783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
3834be0e5c09SChris Mason 
3835be0e5c09SChris Mason 		/* shift the data */
38363d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
38373d9ec8c4SNikolay Borisov 			      data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
3838be0e5c09SChris Mason 			      data_end, old_data - data_end);
3839be0e5c09SChris Mason 		data_end = old_data;
3840be0e5c09SChris Mason 	}
38415f39d397SChris Mason 
384262e2749eSChris Mason 	/* setup the item for the new data */
38439c58309dSChris Mason 	for (i = 0; i < nr; i++) {
38449c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
38459c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
3846dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
38479c58309dSChris Mason 		data_end -= data_size[i];
3848fc0716c2SNikolay Borisov 		btrfs_set_token_item_offset(&token, item, data_end);
3849cc4c13d5SDavid Sterba 		btrfs_set_token_item_size(&token, item, data_size[i]);
38509c58309dSChris Mason 	}
385144871b1bSChris Mason 
38529c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
3853b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3854aa5d6bedSChris Mason 
3855e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3856a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3857be0e5c09SChris Mason 		BUG();
38585f39d397SChris Mason 	}
385944871b1bSChris Mason }
386044871b1bSChris Mason 
386144871b1bSChris Mason /*
386244871b1bSChris Mason  * Given a key and some data, insert items into the tree.
386344871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
386444871b1bSChris Mason  */
386544871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
386644871b1bSChris Mason 			    struct btrfs_root *root,
386744871b1bSChris Mason 			    struct btrfs_path *path,
3868310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
386944871b1bSChris Mason 			    int nr)
387044871b1bSChris Mason {
387144871b1bSChris Mason 	int ret = 0;
387244871b1bSChris Mason 	int slot;
387344871b1bSChris Mason 	int i;
387444871b1bSChris Mason 	u32 total_size = 0;
387544871b1bSChris Mason 	u32 total_data = 0;
387644871b1bSChris Mason 
387744871b1bSChris Mason 	for (i = 0; i < nr; i++)
387844871b1bSChris Mason 		total_data += data_size[i];
387944871b1bSChris Mason 
388044871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
388144871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
388244871b1bSChris Mason 	if (ret == 0)
388344871b1bSChris Mason 		return -EEXIST;
388444871b1bSChris Mason 	if (ret < 0)
3885143bede5SJeff Mahoney 		return ret;
388644871b1bSChris Mason 
388744871b1bSChris Mason 	slot = path->slots[0];
388844871b1bSChris Mason 	BUG_ON(slot < 0);
388944871b1bSChris Mason 
3890fc0d82e1SNikolay Borisov 	setup_items_for_insert(root, path, cpu_key, data_size, nr);
3891143bede5SJeff Mahoney 	return 0;
389262e2749eSChris Mason }
389362e2749eSChris Mason 
389462e2749eSChris Mason /*
389562e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
389662e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
389762e2749eSChris Mason  */
3898310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3899310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
3900310712b2SOmar Sandoval 		      u32 data_size)
390162e2749eSChris Mason {
390262e2749eSChris Mason 	int ret = 0;
39032c90e5d6SChris Mason 	struct btrfs_path *path;
39045f39d397SChris Mason 	struct extent_buffer *leaf;
39055f39d397SChris Mason 	unsigned long ptr;
390662e2749eSChris Mason 
39072c90e5d6SChris Mason 	path = btrfs_alloc_path();
3908db5b493aSTsutomu Itoh 	if (!path)
3909db5b493aSTsutomu Itoh 		return -ENOMEM;
39102c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
391162e2749eSChris Mason 	if (!ret) {
39125f39d397SChris Mason 		leaf = path->nodes[0];
39135f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
39145f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
39155f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
391662e2749eSChris Mason 	}
39172c90e5d6SChris Mason 	btrfs_free_path(path);
3918aa5d6bedSChris Mason 	return ret;
3919be0e5c09SChris Mason }
3920be0e5c09SChris Mason 
392174123bd7SChris Mason /*
39225de08d7dSChris Mason  * delete the pointer from a given node.
392374123bd7SChris Mason  *
3924d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
3925d352ac68SChris Mason  * empty a node.
392674123bd7SChris Mason  */
3927afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
3928afe5fea7STsutomu Itoh 		    int level, int slot)
3929be0e5c09SChris Mason {
39305f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
39317518a238SChris Mason 	u32 nritems;
3932f3ea38daSJan Schmidt 	int ret;
3933be0e5c09SChris Mason 
39345f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
3935be0e5c09SChris Mason 	if (slot != nritems - 1) {
3936bf1d3425SDavid Sterba 		if (level) {
3937f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
3938f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
3939bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
3940bf1d3425SDavid Sterba 		}
39415f39d397SChris Mason 		memmove_extent_buffer(parent,
39425f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
39435f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
3944d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
3945d6025579SChris Mason 			      (nritems - slot - 1));
394657ba86c0SChris Mason 	} else if (level) {
3947f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
3948f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REMOVE, GFP_NOFS);
394957ba86c0SChris Mason 		BUG_ON(ret < 0);
3950be0e5c09SChris Mason 	}
3951f3ea38daSJan Schmidt 
39527518a238SChris Mason 	nritems--;
39535f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
39547518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
39555f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
3956eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
39575f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
3958bb803951SChris Mason 	} else if (slot == 0) {
39595f39d397SChris Mason 		struct btrfs_disk_key disk_key;
39605f39d397SChris Mason 
39615f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
3962b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
3963be0e5c09SChris Mason 	}
3964d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
3965be0e5c09SChris Mason }
3966be0e5c09SChris Mason 
396774123bd7SChris Mason /*
3968323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
39695d4f98a2SYan Zheng  * path->nodes[1].
3970323ac95bSChris Mason  *
3971323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
3972323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
3973323ac95bSChris Mason  *
3974323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
3975323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
3976323ac95bSChris Mason  */
3977143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
3978323ac95bSChris Mason 				    struct btrfs_root *root,
39795d4f98a2SYan Zheng 				    struct btrfs_path *path,
39805d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
3981323ac95bSChris Mason {
39825d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
3983afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
3984323ac95bSChris Mason 
39854d081c41SChris Mason 	/*
39864d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
39874d081c41SChris Mason 	 * aren't holding any locks when we call it
39884d081c41SChris Mason 	 */
39894d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
39904d081c41SChris Mason 
3991f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
3992f0486c68SYan, Zheng 
399367439dadSDavid Sterba 	atomic_inc(&leaf->refs);
39945581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
39953083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
3996323ac95bSChris Mason }
3997323ac95bSChris Mason /*
399874123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
399974123bd7SChris Mason  * the leaf, remove it from the tree
400074123bd7SChris Mason  */
400185e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
400285e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4003be0e5c09SChris Mason {
40040b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
40055f39d397SChris Mason 	struct extent_buffer *leaf;
40065f39d397SChris Mason 	struct btrfs_item *item;
4007ce0eac2aSAlexandru Moise 	u32 last_off;
4008ce0eac2aSAlexandru Moise 	u32 dsize = 0;
4009aa5d6bedSChris Mason 	int ret = 0;
4010aa5d6bedSChris Mason 	int wret;
401185e21bacSChris Mason 	int i;
40127518a238SChris Mason 	u32 nritems;
4013be0e5c09SChris Mason 
40145f39d397SChris Mason 	leaf = path->nodes[0];
401585e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
401685e21bacSChris Mason 
401785e21bacSChris Mason 	for (i = 0; i < nr; i++)
401885e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
401985e21bacSChris Mason 
40205f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4021be0e5c09SChris Mason 
402285e21bacSChris Mason 	if (slot + nr != nritems) {
40238f881e8cSDavid Sterba 		int data_end = leaf_data_end(leaf);
4024c82f823cSDavid Sterba 		struct btrfs_map_token token;
40255f39d397SChris Mason 
40263d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4027d6025579SChris Mason 			      data_end + dsize,
40283d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
402985e21bacSChris Mason 			      last_off - data_end);
40305f39d397SChris Mason 
4031c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
403285e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
40335f39d397SChris Mason 			u32 ioff;
4034db94535dSChris Mason 
4035dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4036cc4c13d5SDavid Sterba 			ioff = btrfs_token_item_offset(&token, item);
4037cc4c13d5SDavid Sterba 			btrfs_set_token_item_offset(&token, item, ioff + dsize);
40380783fcfcSChris Mason 		}
4039db94535dSChris Mason 
40405f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
404185e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
40420783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
404385e21bacSChris Mason 			      (nritems - slot - nr));
4044be0e5c09SChris Mason 	}
404585e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
404685e21bacSChris Mason 	nritems -= nr;
40475f39d397SChris Mason 
404874123bd7SChris Mason 	/* delete the leaf if we've emptied it */
40497518a238SChris Mason 	if (nritems == 0) {
40505f39d397SChris Mason 		if (leaf == root->node) {
40515f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
40529a8dd150SChris Mason 		} else {
40536a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4054143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
40559a8dd150SChris Mason 		}
4056be0e5c09SChris Mason 	} else {
40577518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4058aa5d6bedSChris Mason 		if (slot == 0) {
40595f39d397SChris Mason 			struct btrfs_disk_key disk_key;
40605f39d397SChris Mason 
40615f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4062b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4063aa5d6bedSChris Mason 		}
4064aa5d6bedSChris Mason 
406574123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
40660b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
4067be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4068be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4069be0e5c09SChris Mason 			 * for possible call to del_ptr below
4070be0e5c09SChris Mason 			 */
40714920c9acSChris Mason 			slot = path->slots[1];
407267439dadSDavid Sterba 			atomic_inc(&leaf->refs);
40735f39d397SChris Mason 
407499d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
407599d8f83cSChris Mason 					      1, (u32)-1);
407654aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4077aa5d6bedSChris Mason 				ret = wret;
40785f39d397SChris Mason 
40795f39d397SChris Mason 			if (path->nodes[0] == leaf &&
40805f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
408199d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
408299d8f83cSChris Mason 						       1, 1, 0);
408354aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4084aa5d6bedSChris Mason 					ret = wret;
4085aa5d6bedSChris Mason 			}
40865f39d397SChris Mason 
40875f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4088323ac95bSChris Mason 				path->slots[1] = slot;
4089143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
40905f39d397SChris Mason 				free_extent_buffer(leaf);
4091143bede5SJeff Mahoney 				ret = 0;
40925de08d7dSChris Mason 			} else {
4093925baeddSChris Mason 				/* if we're still in the path, make sure
4094925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4095925baeddSChris Mason 				 * push_leaf functions must have already
4096925baeddSChris Mason 				 * dirtied this buffer
4097925baeddSChris Mason 				 */
4098925baeddSChris Mason 				if (path->nodes[0] == leaf)
40995f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
41005f39d397SChris Mason 				free_extent_buffer(leaf);
4101be0e5c09SChris Mason 			}
4102d5719762SChris Mason 		} else {
41035f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4104be0e5c09SChris Mason 		}
41059a8dd150SChris Mason 	}
4106aa5d6bedSChris Mason 	return ret;
41079a8dd150SChris Mason }
41089a8dd150SChris Mason 
410997571fd0SChris Mason /*
4110925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
41117bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
41127bb86316SChris Mason  * returns < 0 on io errors.
4113d352ac68SChris Mason  *
4114d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4115d352ac68SChris Mason  * time you call it.
41167bb86316SChris Mason  */
411716e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
41187bb86316SChris Mason {
4119925baeddSChris Mason 	struct btrfs_key key;
4120925baeddSChris Mason 	struct btrfs_disk_key found_key;
4121925baeddSChris Mason 	int ret;
41227bb86316SChris Mason 
4123925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4124925baeddSChris Mason 
4125e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
4126925baeddSChris Mason 		key.offset--;
4127e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
4128925baeddSChris Mason 		key.type--;
4129e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4130e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
4131925baeddSChris Mason 		key.objectid--;
4132e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
4133e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4134e8b0d724SFilipe David Borba Manana 	} else {
41357bb86316SChris Mason 		return 1;
4136e8b0d724SFilipe David Borba Manana 	}
41377bb86316SChris Mason 
4138b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4139925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4140925baeddSChris Mason 	if (ret < 0)
4141925baeddSChris Mason 		return ret;
4142925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4143925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4144337c6f68SFilipe Manana 	/*
4145337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
4146337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
4147337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
4148337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
4149337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
4150337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
4151337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
4152337c6f68SFilipe Manana 	 * the previous key we computed above.
4153337c6f68SFilipe Manana 	 */
4154337c6f68SFilipe Manana 	if (ret <= 0)
41557bb86316SChris Mason 		return 0;
4156925baeddSChris Mason 	return 1;
41577bb86316SChris Mason }
41587bb86316SChris Mason 
41593f157a2fSChris Mason /*
41603f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4161de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4162de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
41633f157a2fSChris Mason  *
41643f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
41653f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
41663f157a2fSChris Mason  * key and get a writable path.
41673f157a2fSChris Mason  *
41683f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
41693f157a2fSChris Mason  * of the tree.
41703f157a2fSChris Mason  *
4171d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4172d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4173d352ac68SChris Mason  * skipped over (without reading them).
4174d352ac68SChris Mason  *
41753f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
41763f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
41773f157a2fSChris Mason  */
41783f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4179de78b51aSEric Sandeen 			 struct btrfs_path *path,
41803f157a2fSChris Mason 			 u64 min_trans)
41813f157a2fSChris Mason {
41823f157a2fSChris Mason 	struct extent_buffer *cur;
41833f157a2fSChris Mason 	struct btrfs_key found_key;
41843f157a2fSChris Mason 	int slot;
41859652480bSYan 	int sret;
41863f157a2fSChris Mason 	u32 nritems;
41873f157a2fSChris Mason 	int level;
41883f157a2fSChris Mason 	int ret = 1;
4189f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
41903f157a2fSChris Mason 
4191f98de9b9SFilipe Manana 	path->keep_locks = 1;
41923f157a2fSChris Mason again:
4193bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
41943f157a2fSChris Mason 	level = btrfs_header_level(cur);
4195e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
41963f157a2fSChris Mason 	path->nodes[level] = cur;
4197bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
41983f157a2fSChris Mason 
41993f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
42003f157a2fSChris Mason 		ret = 1;
42013f157a2fSChris Mason 		goto out;
42023f157a2fSChris Mason 	}
42033f157a2fSChris Mason 	while (1) {
42043f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
42053f157a2fSChris Mason 		level = btrfs_header_level(cur);
4206e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
4207cbca7d59SFilipe Manana 		if (sret < 0) {
4208cbca7d59SFilipe Manana 			ret = sret;
4209cbca7d59SFilipe Manana 			goto out;
4210cbca7d59SFilipe Manana 		}
42113f157a2fSChris Mason 
4212323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4213323ac95bSChris Mason 		if (level == path->lowest_level) {
4214e02119d5SChris Mason 			if (slot >= nritems)
4215e02119d5SChris Mason 				goto find_next_key;
42163f157a2fSChris Mason 			ret = 0;
42173f157a2fSChris Mason 			path->slots[level] = slot;
42183f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
42193f157a2fSChris Mason 			goto out;
42203f157a2fSChris Mason 		}
42219652480bSYan 		if (sret && slot > 0)
42229652480bSYan 			slot--;
42233f157a2fSChris Mason 		/*
4224de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4225260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
42263f157a2fSChris Mason 		 */
42273f157a2fSChris Mason 		while (slot < nritems) {
42283f157a2fSChris Mason 			u64 gen;
4229e02119d5SChris Mason 
42303f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
42313f157a2fSChris Mason 			if (gen < min_trans) {
42323f157a2fSChris Mason 				slot++;
42333f157a2fSChris Mason 				continue;
42343f157a2fSChris Mason 			}
42353f157a2fSChris Mason 			break;
42363f157a2fSChris Mason 		}
4237e02119d5SChris Mason find_next_key:
42383f157a2fSChris Mason 		/*
42393f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
42403f157a2fSChris Mason 		 * and find another one
42413f157a2fSChris Mason 		 */
42423f157a2fSChris Mason 		if (slot >= nritems) {
4243e02119d5SChris Mason 			path->slots[level] = slot;
4244e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4245de78b51aSEric Sandeen 						  min_trans);
4246e02119d5SChris Mason 			if (sret == 0) {
4247b3b4aa74SDavid Sterba 				btrfs_release_path(path);
42483f157a2fSChris Mason 				goto again;
42493f157a2fSChris Mason 			} else {
42503f157a2fSChris Mason 				goto out;
42513f157a2fSChris Mason 			}
42523f157a2fSChris Mason 		}
42533f157a2fSChris Mason 		/* save our key for returning back */
42543f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
42553f157a2fSChris Mason 		path->slots[level] = slot;
42563f157a2fSChris Mason 		if (level == path->lowest_level) {
42573f157a2fSChris Mason 			ret = 0;
42583f157a2fSChris Mason 			goto out;
42593f157a2fSChris Mason 		}
42604b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4261fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4262fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4263fb770ae4SLiu Bo 			goto out;
4264fb770ae4SLiu Bo 		}
42653f157a2fSChris Mason 
4266bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4267b4ce94deSChris Mason 
4268bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
42693f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4270f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
42713f157a2fSChris Mason 	}
42723f157a2fSChris Mason out:
4273f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4274f98de9b9SFilipe Manana 	if (ret == 0) {
4275f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4276f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4277f98de9b9SFilipe Manana 	}
42783f157a2fSChris Mason 	return ret;
42793f157a2fSChris Mason }
42803f157a2fSChris Mason 
42813f157a2fSChris Mason /*
42823f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
42833f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4284de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
42853f157a2fSChris Mason  *
42863f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
42873f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
42883f157a2fSChris Mason  *
42893f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
42903f157a2fSChris Mason  * calling this function.
42913f157a2fSChris Mason  */
4292e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4293de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4294e7a84565SChris Mason {
4295e7a84565SChris Mason 	int slot;
4296e7a84565SChris Mason 	struct extent_buffer *c;
4297e7a84565SChris Mason 
42986a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4299e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4300e7a84565SChris Mason 		if (!path->nodes[level])
4301e7a84565SChris Mason 			return 1;
4302e7a84565SChris Mason 
4303e7a84565SChris Mason 		slot = path->slots[level] + 1;
4304e7a84565SChris Mason 		c = path->nodes[level];
43053f157a2fSChris Mason next:
4306e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
430733c66f43SYan Zheng 			int ret;
430833c66f43SYan Zheng 			int orig_lowest;
430933c66f43SYan Zheng 			struct btrfs_key cur_key;
431033c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
431133c66f43SYan Zheng 			    !path->nodes[level + 1])
4312e7a84565SChris Mason 				return 1;
431333c66f43SYan Zheng 
43146a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
431533c66f43SYan Zheng 				level++;
4316e7a84565SChris Mason 				continue;
4317e7a84565SChris Mason 			}
431833c66f43SYan Zheng 
431933c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
432033c66f43SYan Zheng 			if (level == 0)
432133c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
432233c66f43SYan Zheng 			else
432333c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
432433c66f43SYan Zheng 
432533c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4326b3b4aa74SDavid Sterba 			btrfs_release_path(path);
432733c66f43SYan Zheng 			path->lowest_level = level;
432833c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
432933c66f43SYan Zheng 						0, 0);
433033c66f43SYan Zheng 			path->lowest_level = orig_lowest;
433133c66f43SYan Zheng 			if (ret < 0)
433233c66f43SYan Zheng 				return ret;
433333c66f43SYan Zheng 
433433c66f43SYan Zheng 			c = path->nodes[level];
433533c66f43SYan Zheng 			slot = path->slots[level];
433633c66f43SYan Zheng 			if (ret == 0)
433733c66f43SYan Zheng 				slot++;
433833c66f43SYan Zheng 			goto next;
433933c66f43SYan Zheng 		}
434033c66f43SYan Zheng 
4341e7a84565SChris Mason 		if (level == 0)
4342e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
43433f157a2fSChris Mason 		else {
43443f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
43453f157a2fSChris Mason 
43463f157a2fSChris Mason 			if (gen < min_trans) {
43473f157a2fSChris Mason 				slot++;
43483f157a2fSChris Mason 				goto next;
43493f157a2fSChris Mason 			}
4350e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
43513f157a2fSChris Mason 		}
4352e7a84565SChris Mason 		return 0;
4353e7a84565SChris Mason 	}
4354e7a84565SChris Mason 	return 1;
4355e7a84565SChris Mason }
4356e7a84565SChris Mason 
43577bb86316SChris Mason /*
4358925baeddSChris Mason  * search the tree again to find a leaf with greater keys
43590f70abe2SChris Mason  * returns 0 if it found something or 1 if there are no greater leaves.
43600f70abe2SChris Mason  * returns < 0 on io errors.
436197571fd0SChris Mason  */
4362234b63a0SChris Mason int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
4363d97e63b6SChris Mason {
43643d7806ecSJan Schmidt 	return btrfs_next_old_leaf(root, path, 0);
43653d7806ecSJan Schmidt }
43663d7806ecSJan Schmidt 
43673d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
43683d7806ecSJan Schmidt 			u64 time_seq)
43693d7806ecSJan Schmidt {
4370d97e63b6SChris Mason 	int slot;
43718e73f275SChris Mason 	int level;
43725f39d397SChris Mason 	struct extent_buffer *c;
43738e73f275SChris Mason 	struct extent_buffer *next;
4374925baeddSChris Mason 	struct btrfs_key key;
4375925baeddSChris Mason 	u32 nritems;
4376925baeddSChris Mason 	int ret;
43770e46318dSJosef Bacik 	int i;
4378925baeddSChris Mason 
4379925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4380d397712bSChris Mason 	if (nritems == 0)
4381925baeddSChris Mason 		return 1;
4382925baeddSChris Mason 
43838e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
43848e73f275SChris Mason again:
43858e73f275SChris Mason 	level = 1;
43868e73f275SChris Mason 	next = NULL;
4387b3b4aa74SDavid Sterba 	btrfs_release_path(path);
43888e73f275SChris Mason 
4389a2135011SChris Mason 	path->keep_locks = 1;
43908e73f275SChris Mason 
43913d7806ecSJan Schmidt 	if (time_seq)
43923d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
43933d7806ecSJan Schmidt 	else
4394925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4395925baeddSChris Mason 	path->keep_locks = 0;
4396925baeddSChris Mason 
4397925baeddSChris Mason 	if (ret < 0)
4398925baeddSChris Mason 		return ret;
4399925baeddSChris Mason 
4400a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4401168fd7d2SChris Mason 	/*
4402168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4403168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4404168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4405168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4406168fd7d2SChris Mason 	 */
4407a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4408e457afecSYan Zheng 		if (ret == 0)
4409168fd7d2SChris Mason 			path->slots[0]++;
44108e73f275SChris Mason 		ret = 0;
4411925baeddSChris Mason 		goto done;
4412925baeddSChris Mason 	}
44130b43e04fSLiu Bo 	/*
44140b43e04fSLiu Bo 	 * So the above check misses one case:
44150b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
44160b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
44170b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
44180b43e04fSLiu Bo 	 *
44190b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
44200b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
44210b43e04fSLiu Bo 	 *
44220b43e04fSLiu Bo 	 * And a bit more explanation about this check,
44230b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
44240b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
44250b43e04fSLiu Bo 	 * bigger one.
44260b43e04fSLiu Bo 	 */
44270b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
44280b43e04fSLiu Bo 		ret = 0;
44290b43e04fSLiu Bo 		goto done;
44300b43e04fSLiu Bo 	}
4431d97e63b6SChris Mason 
4432234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
44338e73f275SChris Mason 		if (!path->nodes[level]) {
44348e73f275SChris Mason 			ret = 1;
44358e73f275SChris Mason 			goto done;
44368e73f275SChris Mason 		}
44375f39d397SChris Mason 
4438d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4439d97e63b6SChris Mason 		c = path->nodes[level];
44405f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4441d97e63b6SChris Mason 			level++;
44428e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
44438e73f275SChris Mason 				ret = 1;
44448e73f275SChris Mason 				goto done;
44458e73f275SChris Mason 			}
4446d97e63b6SChris Mason 			continue;
4447d97e63b6SChris Mason 		}
44485f39d397SChris Mason 
44490e46318dSJosef Bacik 
44500e46318dSJosef Bacik 		/*
44510e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
44520e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
44530e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
44540e46318dSJosef Bacik 		 */
44550e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
44560e46318dSJosef Bacik 			if (path->locks[level]) {
44570e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
44580e46318dSJosef Bacik 				path->locks[i] = 0;
44590e46318dSJosef Bacik 			}
44600e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
44610e46318dSJosef Bacik 			path->nodes[i] = NULL;
4462925baeddSChris Mason 		}
44635f39d397SChris Mason 
44648e73f275SChris Mason 		next = c;
4465d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4466cda79c54SDavid Sterba 					    slot, &key);
44678e73f275SChris Mason 		if (ret == -EAGAIN)
44688e73f275SChris Mason 			goto again;
44695f39d397SChris Mason 
447076a05b35SChris Mason 		if (ret < 0) {
4471b3b4aa74SDavid Sterba 			btrfs_release_path(path);
447276a05b35SChris Mason 			goto done;
447376a05b35SChris Mason 		}
447476a05b35SChris Mason 
44755cd57b2cSChris Mason 		if (!path->skip_locking) {
4476bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4477d42244a0SJan Schmidt 			if (!ret && time_seq) {
4478d42244a0SJan Schmidt 				/*
4479d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4480d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4481d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4482d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4483d42244a0SJan Schmidt 				 * on our lock and cycle.
4484d42244a0SJan Schmidt 				 */
4485cf538830SJan Schmidt 				free_extent_buffer(next);
4486d42244a0SJan Schmidt 				btrfs_release_path(path);
4487d42244a0SJan Schmidt 				cond_resched();
4488d42244a0SJan Schmidt 				goto again;
4489d42244a0SJan Schmidt 			}
44900e46318dSJosef Bacik 			if (!ret)
44910e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4492bd681513SChris Mason 		}
4493d97e63b6SChris Mason 		break;
4494d97e63b6SChris Mason 	}
4495d97e63b6SChris Mason 	path->slots[level] = slot;
4496d97e63b6SChris Mason 	while (1) {
4497d97e63b6SChris Mason 		level--;
4498d97e63b6SChris Mason 		path->nodes[level] = next;
4499d97e63b6SChris Mason 		path->slots[level] = 0;
4500a74a4b97SChris Mason 		if (!path->skip_locking)
4501ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4502d97e63b6SChris Mason 		if (!level)
4503d97e63b6SChris Mason 			break;
4504b4ce94deSChris Mason 
4505d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4506cda79c54SDavid Sterba 					    0, &key);
45078e73f275SChris Mason 		if (ret == -EAGAIN)
45088e73f275SChris Mason 			goto again;
45098e73f275SChris Mason 
451076a05b35SChris Mason 		if (ret < 0) {
4511b3b4aa74SDavid Sterba 			btrfs_release_path(path);
451276a05b35SChris Mason 			goto done;
451376a05b35SChris Mason 		}
451476a05b35SChris Mason 
4515ffeb03cfSJosef Bacik 		if (!path->skip_locking)
45160e46318dSJosef Bacik 			btrfs_tree_read_lock(next);
4517d97e63b6SChris Mason 	}
45188e73f275SChris Mason 	ret = 0;
4519925baeddSChris Mason done:
4520f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
45218e73f275SChris Mason 
45228e73f275SChris Mason 	return ret;
4523d97e63b6SChris Mason }
45240b86a832SChris Mason 
45253f157a2fSChris Mason /*
45263f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
45273f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
45283f157a2fSChris Mason  *
45293f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
45303f157a2fSChris Mason  */
45310b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
45320b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
45330b86a832SChris Mason 			int type)
45340b86a832SChris Mason {
45350b86a832SChris Mason 	struct btrfs_key found_key;
45360b86a832SChris Mason 	struct extent_buffer *leaf;
4537e02119d5SChris Mason 	u32 nritems;
45380b86a832SChris Mason 	int ret;
45390b86a832SChris Mason 
45400b86a832SChris Mason 	while (1) {
45410b86a832SChris Mason 		if (path->slots[0] == 0) {
45420b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
45430b86a832SChris Mason 			if (ret != 0)
45440b86a832SChris Mason 				return ret;
45450b86a832SChris Mason 		} else {
45460b86a832SChris Mason 			path->slots[0]--;
45470b86a832SChris Mason 		}
45480b86a832SChris Mason 		leaf = path->nodes[0];
4549e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
4550e02119d5SChris Mason 		if (nritems == 0)
4551e02119d5SChris Mason 			return 1;
4552e02119d5SChris Mason 		if (path->slots[0] == nritems)
4553e02119d5SChris Mason 			path->slots[0]--;
4554e02119d5SChris Mason 
45550b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4556e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
4557e02119d5SChris Mason 			break;
45580a4eefbbSYan Zheng 		if (found_key.type == type)
45590a4eefbbSYan Zheng 			return 0;
4560e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
4561e02119d5SChris Mason 		    found_key.type < type)
4562e02119d5SChris Mason 			break;
45630b86a832SChris Mason 	}
45640b86a832SChris Mason 	return 1;
45650b86a832SChris Mason }
4566ade2e0b3SWang Shilong 
4567ade2e0b3SWang Shilong /*
4568ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
4569ade2e0b3SWang Shilong  * min objecitd.
4570ade2e0b3SWang Shilong  *
4571ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4572ade2e0b3SWang Shilong  */
4573ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
4574ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
4575ade2e0b3SWang Shilong {
4576ade2e0b3SWang Shilong 	struct btrfs_key found_key;
4577ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
4578ade2e0b3SWang Shilong 	u32 nritems;
4579ade2e0b3SWang Shilong 	int ret;
4580ade2e0b3SWang Shilong 
4581ade2e0b3SWang Shilong 	while (1) {
4582ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
4583ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
4584ade2e0b3SWang Shilong 			if (ret != 0)
4585ade2e0b3SWang Shilong 				return ret;
4586ade2e0b3SWang Shilong 		} else {
4587ade2e0b3SWang Shilong 			path->slots[0]--;
4588ade2e0b3SWang Shilong 		}
4589ade2e0b3SWang Shilong 		leaf = path->nodes[0];
4590ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
4591ade2e0b3SWang Shilong 		if (nritems == 0)
4592ade2e0b3SWang Shilong 			return 1;
4593ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
4594ade2e0b3SWang Shilong 			path->slots[0]--;
4595ade2e0b3SWang Shilong 
4596ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4597ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
4598ade2e0b3SWang Shilong 			break;
4599ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4600ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
4601ade2e0b3SWang Shilong 			return 0;
4602ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
4603ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
4604ade2e0b3SWang Shilong 			break;
4605ade2e0b3SWang Shilong 	}
4606ade2e0b3SWang Shilong 	return 1;
4607ade2e0b3SWang Shilong }
4608