xref: /openbmc/linux/fs/btrfs/ctree.c (revision 376a21d752552b0a2770dc1bdae738be39851b5c)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
3d352ac68SChris Mason  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
6a6b6e75eSChris Mason #include <linux/sched.h>
75a0e3ad6STejun Heo #include <linux/slab.h>
8bd989ba3SJan Schmidt #include <linux/rbtree.h>
9adf02123SDavid Sterba #include <linux/mm.h>
10e41d12f5SChristoph Hellwig #include <linux/error-injection.h>
11eb60ceacSChris Mason #include "ctree.h"
12eb60ceacSChris Mason #include "disk-io.h"
137f5c1516SChris Mason #include "transaction.h"
145f39d397SChris Mason #include "print-tree.h"
15925baeddSChris Mason #include "locking.h"
16de37aa51SNikolay Borisov #include "volumes.h"
17f616f5cdSQu Wenruo #include "qgroup.h"
18f3a84ccdSFilipe Manana #include "tree-mod-log.h"
199a8dd150SChris Mason 
20e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
21e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
22310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
23310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
24310712b2SOmar Sandoval 		      int data_size, int extend);
255f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
262ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
27971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
285f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
295f39d397SChris Mason 			      struct extent_buffer *dst_buf,
305f39d397SChris Mason 			      struct extent_buffer *src_buf);
31afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
32afe5fea7STsutomu Itoh 		    int level, int slot);
33d97e63b6SChris Mason 
34af024ed2SJohannes Thumshirn static const struct btrfs_csums {
35af024ed2SJohannes Thumshirn 	u16		size;
3659a0fcdbSDavid Sterba 	const char	name[10];
3759a0fcdbSDavid Sterba 	const char	driver[12];
38af024ed2SJohannes Thumshirn } btrfs_csums[] = {
39af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
403951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
413831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
42352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
43352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
44af024ed2SJohannes Thumshirn };
45af024ed2SJohannes Thumshirn 
46af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
47af024ed2SJohannes Thumshirn {
48af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
49af024ed2SJohannes Thumshirn 	/*
50af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
51af024ed2SJohannes Thumshirn 	 */
52af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
53af024ed2SJohannes Thumshirn }
54af024ed2SJohannes Thumshirn 
55af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
56af024ed2SJohannes Thumshirn {
57af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
58af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
59af024ed2SJohannes Thumshirn }
60af024ed2SJohannes Thumshirn 
61b4e967beSDavid Sterba /*
62b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
63b4e967beSDavid Sterba  * name
64b4e967beSDavid Sterba  */
65b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
66b4e967beSDavid Sterba {
67b4e967beSDavid Sterba 	/* csum type is validated at mount time */
6859a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
6959a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
70b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
71b4e967beSDavid Sterba }
72b4e967beSDavid Sterba 
73604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
74f7cea56cSDavid Sterba {
75f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
76f7cea56cSDavid Sterba }
77f7cea56cSDavid Sterba 
782c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
792c90e5d6SChris Mason {
80e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
812c90e5d6SChris Mason }
822c90e5d6SChris Mason 
83d352ac68SChris Mason /* this also releases the path */
842c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
852c90e5d6SChris Mason {
86ff175d57SJesper Juhl 	if (!p)
87ff175d57SJesper Juhl 		return;
88b3b4aa74SDavid Sterba 	btrfs_release_path(p);
892c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
902c90e5d6SChris Mason }
912c90e5d6SChris Mason 
92d352ac68SChris Mason /*
93d352ac68SChris Mason  * path release drops references on the extent buffers in the path
94d352ac68SChris Mason  * and it drops any locks held by this path
95d352ac68SChris Mason  *
96d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
97d352ac68SChris Mason  */
98b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
99eb60ceacSChris Mason {
100eb60ceacSChris Mason 	int i;
101a2135011SChris Mason 
102234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1033f157a2fSChris Mason 		p->slots[i] = 0;
104eb60ceacSChris Mason 		if (!p->nodes[i])
105925baeddSChris Mason 			continue;
106925baeddSChris Mason 		if (p->locks[i]) {
107bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
108925baeddSChris Mason 			p->locks[i] = 0;
109925baeddSChris Mason 		}
1105f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1113f157a2fSChris Mason 		p->nodes[i] = NULL;
112eb60ceacSChris Mason 	}
113eb60ceacSChris Mason }
114eb60ceacSChris Mason 
115d352ac68SChris Mason /*
116d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
117d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
118d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
119d352ac68SChris Mason  * looping required.
120d352ac68SChris Mason  *
121d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
122d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
123d352ac68SChris Mason  * at any time because there are no locks held.
124d352ac68SChris Mason  */
125925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
126925baeddSChris Mason {
127925baeddSChris Mason 	struct extent_buffer *eb;
128240f62c8SChris Mason 
1293083ee2eSJosef Bacik 	while (1) {
130240f62c8SChris Mason 		rcu_read_lock();
131240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1323083ee2eSJosef Bacik 
1333083ee2eSJosef Bacik 		/*
1343083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
13501327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1363083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1373083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1383083ee2eSJosef Bacik 		 */
1393083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
140240f62c8SChris Mason 			rcu_read_unlock();
1413083ee2eSJosef Bacik 			break;
1423083ee2eSJosef Bacik 		}
1433083ee2eSJosef Bacik 		rcu_read_unlock();
1443083ee2eSJosef Bacik 		synchronize_rcu();
1453083ee2eSJosef Bacik 	}
146925baeddSChris Mason 	return eb;
147925baeddSChris Mason }
148925baeddSChris Mason 
14992a7cc42SQu Wenruo /*
15092a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
15192a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
15292a7cc42SQu Wenruo  * sure they get properly updated on disk.
153d352ac68SChris Mason  */
1540b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1550b86a832SChris Mason {
1560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1570b246afaSJeff Mahoney 
158e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
159e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
160e7070be1SJosef Bacik 		return;
161e7070be1SJosef Bacik 
1620b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
163e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
164e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
1654fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
166e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
1670b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
168e7070be1SJosef Bacik 		else
169e7070be1SJosef Bacik 			list_move(&root->dirty_list,
1700b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
1710b86a832SChris Mason 	}
1720b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1730b86a832SChris Mason }
1740b86a832SChris Mason 
175d352ac68SChris Mason /*
176d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
177d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
178d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
179d352ac68SChris Mason  */
180be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
181be20aa9dSChris Mason 		      struct btrfs_root *root,
182be20aa9dSChris Mason 		      struct extent_buffer *buf,
183be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
184be20aa9dSChris Mason {
1850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
186be20aa9dSChris Mason 	struct extent_buffer *cow;
187be20aa9dSChris Mason 	int ret = 0;
188be20aa9dSChris Mason 	int level;
1895d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
190be20aa9dSChris Mason 
19192a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
1920b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
19392a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
19427cdeb70SMiao Xie 		trans->transid != root->last_trans);
195be20aa9dSChris Mason 
196be20aa9dSChris Mason 	level = btrfs_header_level(buf);
1975d4f98a2SYan Zheng 	if (level == 0)
1985d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
1995d4f98a2SYan Zheng 	else
2005d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
20131840ae1SZheng Yan 
2024d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
203cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
204cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
2055d4f98a2SYan Zheng 	if (IS_ERR(cow))
206be20aa9dSChris Mason 		return PTR_ERR(cow);
207be20aa9dSChris Mason 
20858e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
209be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
210be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2115d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2125d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2135d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2145d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2155d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2165d4f98a2SYan Zheng 	else
217be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
218be20aa9dSChris Mason 
219de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2202b82032cSYan Zheng 
221be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2225d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
223e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2245d4f98a2SYan Zheng 	else
225e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
226867ed321SJosef Bacik 	if (ret) {
22772c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
22872c9925fSFilipe Manana 		free_extent_buffer(cow);
229867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
230be20aa9dSChris Mason 		return ret;
231867ed321SJosef Bacik 	}
232be20aa9dSChris Mason 
233be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
234be20aa9dSChris Mason 	*cow_ret = cow;
235be20aa9dSChris Mason 	return 0;
236be20aa9dSChris Mason }
237be20aa9dSChris Mason 
238d352ac68SChris Mason /*
2395d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
2405d4f98a2SYan Zheng  */
2415d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
2425d4f98a2SYan Zheng 			      struct extent_buffer *buf)
2435d4f98a2SYan Zheng {
2445d4f98a2SYan Zheng 	/*
24592a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
24692a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
24792a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
2485d4f98a2SYan Zheng 	 */
24992a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2505d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
2515d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
2525d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
2535d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
2545d4f98a2SYan Zheng 		return 1;
255a79865c6SNikolay Borisov 
2565d4f98a2SYan Zheng 	return 0;
2575d4f98a2SYan Zheng }
2585d4f98a2SYan Zheng 
2595d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
2605d4f98a2SYan Zheng 				       struct btrfs_root *root,
2615d4f98a2SYan Zheng 				       struct extent_buffer *buf,
262f0486c68SYan, Zheng 				       struct extent_buffer *cow,
263f0486c68SYan, Zheng 				       int *last_ref)
2645d4f98a2SYan Zheng {
2650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2665d4f98a2SYan Zheng 	u64 refs;
2675d4f98a2SYan Zheng 	u64 owner;
2685d4f98a2SYan Zheng 	u64 flags;
2695d4f98a2SYan Zheng 	u64 new_flags = 0;
2705d4f98a2SYan Zheng 	int ret;
2715d4f98a2SYan Zheng 
2725d4f98a2SYan Zheng 	/*
2735d4f98a2SYan Zheng 	 * Backrefs update rules:
2745d4f98a2SYan Zheng 	 *
2755d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
2765d4f98a2SYan Zheng 	 * allocated by tree relocation.
2775d4f98a2SYan Zheng 	 *
2785d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
2795d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
2805d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
2815d4f98a2SYan Zheng 	 *
2825d4f98a2SYan Zheng 	 * If a tree block is been relocating
2835d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
2845d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
2855d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
2865d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
2875d4f98a2SYan Zheng 	 */
2885d4f98a2SYan Zheng 
2895d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
2902ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
2913173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
2923173a18fSJosef Bacik 					       &refs, &flags);
293be1a5564SMark Fasheh 		if (ret)
294be1a5564SMark Fasheh 			return ret;
295e5df9573SMark Fasheh 		if (refs == 0) {
296e5df9573SMark Fasheh 			ret = -EROFS;
2970b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
298e5df9573SMark Fasheh 			return ret;
299e5df9573SMark Fasheh 		}
3005d4f98a2SYan Zheng 	} else {
3015d4f98a2SYan Zheng 		refs = 1;
3025d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
3035d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
3045d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
3055d4f98a2SYan Zheng 		else
3065d4f98a2SYan Zheng 			flags = 0;
3075d4f98a2SYan Zheng 	}
3085d4f98a2SYan Zheng 
3095d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
3105d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
3115d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
3125d4f98a2SYan Zheng 
3135d4f98a2SYan Zheng 	if (refs > 1) {
3145d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
3155d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
3165d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
317e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
318692826b2SJeff Mahoney 			if (ret)
319692826b2SJeff Mahoney 				return ret;
3205d4f98a2SYan Zheng 
3215d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3225d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
323e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
324692826b2SJeff Mahoney 				if (ret)
325692826b2SJeff Mahoney 					return ret;
326e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
327692826b2SJeff Mahoney 				if (ret)
328692826b2SJeff Mahoney 					return ret;
3295d4f98a2SYan Zheng 			}
3305d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
3315d4f98a2SYan Zheng 		} else {
3325d4f98a2SYan Zheng 
3335d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3345d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
335e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3365d4f98a2SYan Zheng 			else
337e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
338692826b2SJeff Mahoney 			if (ret)
339692826b2SJeff Mahoney 				return ret;
3405d4f98a2SYan Zheng 		}
3415d4f98a2SYan Zheng 		if (new_flags != 0) {
342b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
343b1c79e09SJosef Bacik 
34442c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
345b1c79e09SJosef Bacik 							  new_flags, level, 0);
346be1a5564SMark Fasheh 			if (ret)
347be1a5564SMark Fasheh 				return ret;
3485d4f98a2SYan Zheng 		}
3495d4f98a2SYan Zheng 	} else {
3505d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
3515d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3525d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
353e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3545d4f98a2SYan Zheng 			else
355e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
356692826b2SJeff Mahoney 			if (ret)
357692826b2SJeff Mahoney 				return ret;
358e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
359692826b2SJeff Mahoney 			if (ret)
360692826b2SJeff Mahoney 				return ret;
3615d4f98a2SYan Zheng 		}
3626a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
363f0486c68SYan, Zheng 		*last_ref = 1;
3645d4f98a2SYan Zheng 	}
3655d4f98a2SYan Zheng 	return 0;
3665d4f98a2SYan Zheng }
3675d4f98a2SYan Zheng 
3685d4f98a2SYan Zheng /*
369d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
370d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
371d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
372d397712bSChris Mason  * dirty again.
373d352ac68SChris Mason  *
374d352ac68SChris Mason  * search_start -- an allocation hint for the new block
375d352ac68SChris Mason  *
376d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
377d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
378d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
379d352ac68SChris Mason  */
380d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
3815f39d397SChris Mason 			     struct btrfs_root *root,
3825f39d397SChris Mason 			     struct extent_buffer *buf,
3835f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
3845f39d397SChris Mason 			     struct extent_buffer **cow_ret,
3859631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
3869631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
3876702ed49SChris Mason {
3880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3895d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
3905f39d397SChris Mason 	struct extent_buffer *cow;
391be1a5564SMark Fasheh 	int level, ret;
392f0486c68SYan, Zheng 	int last_ref = 0;
393925baeddSChris Mason 	int unlock_orig = 0;
3940f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
3956702ed49SChris Mason 
396925baeddSChris Mason 	if (*cow_ret == buf)
397925baeddSChris Mason 		unlock_orig = 1;
398925baeddSChris Mason 
39949d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
400925baeddSChris Mason 
40192a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
4020b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
40392a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
40427cdeb70SMiao Xie 		trans->transid != root->last_trans);
4055f39d397SChris Mason 
4067bb86316SChris Mason 	level = btrfs_header_level(buf);
40731840ae1SZheng Yan 
4085d4f98a2SYan Zheng 	if (level == 0)
4095d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
4105d4f98a2SYan Zheng 	else
4115d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
4125d4f98a2SYan Zheng 
4130f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
4145d4f98a2SYan Zheng 		parent_start = parent->start;
4155d4f98a2SYan Zheng 
41679bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
41779bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
41879bd3712SFilipe Manana 				     search_start, empty_size, nest);
4196702ed49SChris Mason 	if (IS_ERR(cow))
4206702ed49SChris Mason 		return PTR_ERR(cow);
4216702ed49SChris Mason 
422b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
423b4ce94deSChris Mason 
42458e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
425db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
4265f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
4275d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
4285d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
4295d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
4305d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
4315d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
4325d4f98a2SYan Zheng 	else
4335f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
4346702ed49SChris Mason 
435de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
4362b82032cSYan Zheng 
437be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
438b68dc2a9SMark Fasheh 	if (ret) {
439572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
440572c83acSJosef Bacik 		free_extent_buffer(cow);
44166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
442b68dc2a9SMark Fasheh 		return ret;
443b68dc2a9SMark Fasheh 	}
4441a40e23bSZheng Yan 
44592a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
44683d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
44793314e3bSZhaolei 		if (ret) {
448572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
449572c83acSJosef Bacik 			free_extent_buffer(cow);
45066642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
45183d4cfd4SJosef Bacik 			return ret;
45283d4cfd4SJosef Bacik 		}
45393314e3bSZhaolei 	}
4543fd0a558SYan, Zheng 
4556702ed49SChris Mason 	if (buf == root->node) {
456925baeddSChris Mason 		WARN_ON(parent && parent != buf);
4575d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4585d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4595d4f98a2SYan Zheng 			parent_start = buf->start;
460925baeddSChris Mason 
46167439dadSDavid Sterba 		atomic_inc(&cow->refs);
462406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
463d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
464240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
465925baeddSChris Mason 
4667a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
4677a163608SFilipe Manana 				      parent_start, last_ref);
4685f39d397SChris Mason 		free_extent_buffer(buf);
4690b86a832SChris Mason 		add_root_to_dirty_list(root);
4706702ed49SChris Mason 	} else {
4715d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
472f3a84ccdSFilipe Manana 		btrfs_tree_mod_log_insert_key(parent, parent_slot,
473f3a84ccdSFilipe Manana 					      BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
4745f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
475db94535dSChris Mason 					cow->start);
47674493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
47774493f7aSChris Mason 					      trans->transid);
4786702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
4795de865eeSFilipe David Borba Manana 		if (last_ref) {
480f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
4815de865eeSFilipe David Borba Manana 			if (ret) {
482572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
483572c83acSJosef Bacik 				free_extent_buffer(cow);
48466642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
4855de865eeSFilipe David Borba Manana 				return ret;
4865de865eeSFilipe David Borba Manana 			}
4875de865eeSFilipe David Borba Manana 		}
4887a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
4897a163608SFilipe Manana 				      parent_start, last_ref);
4906702ed49SChris Mason 	}
491925baeddSChris Mason 	if (unlock_orig)
492925baeddSChris Mason 		btrfs_tree_unlock(buf);
4933083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
4946702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
4956702ed49SChris Mason 	*cow_ret = cow;
4966702ed49SChris Mason 	return 0;
4976702ed49SChris Mason }
4986702ed49SChris Mason 
4995d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
5005d4f98a2SYan Zheng 				   struct btrfs_root *root,
5015d4f98a2SYan Zheng 				   struct extent_buffer *buf)
5025d4f98a2SYan Zheng {
503f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
504faa2dbf0SJosef Bacik 		return 0;
505fccb84c9SDavid Sterba 
506d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
507d1980131SDavid Sterba 	smp_mb__before_atomic();
508f1ebcc74SLiu Bo 
509f1ebcc74SLiu Bo 	/*
510f1ebcc74SLiu Bo 	 * We do not need to cow a block if
511f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
512f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
513f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
514f1ebcc74SLiu Bo 	 *
515f1ebcc74SLiu Bo 	 * What is forced COW:
51601327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
51752042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
518f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
519f1ebcc74SLiu Bo 	 */
5205d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
5215d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
5225d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
523f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
52427cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
5255d4f98a2SYan Zheng 		return 0;
5265d4f98a2SYan Zheng 	return 1;
5275d4f98a2SYan Zheng }
5285d4f98a2SYan Zheng 
529d352ac68SChris Mason /*
530d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
53101327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
532d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
533d352ac68SChris Mason  */
534d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
5355f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
5365f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
5379631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
5389631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
53902217ed2SChris Mason {
5400b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5416702ed49SChris Mason 	u64 search_start;
542f510cfecSChris Mason 	int ret;
543dc17ff8fSChris Mason 
54483354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
54583354f07SJosef Bacik 		btrfs_err(fs_info,
54683354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
54783354f07SJosef Bacik 
5480b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
54931b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
550c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
5510b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
55231b1a2bdSJulia Lawall 
5530b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
55431b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
5550b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
556dc17ff8fSChris Mason 
5575d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
55802217ed2SChris Mason 		*cow_ret = buf;
55902217ed2SChris Mason 		return 0;
56002217ed2SChris Mason 	}
561c487685dSChris Mason 
562ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
563b4ce94deSChris Mason 
564f616f5cdSQu Wenruo 	/*
565f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
566f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
567f616f5cdSQu Wenruo 	 *
568f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
569f616f5cdSQu Wenruo 	 */
570f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
571f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
5729631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
5731abe9b8aSliubo 
5741abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
5751abe9b8aSliubo 
576f510cfecSChris Mason 	return ret;
5772c90e5d6SChris Mason }
578f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
5796702ed49SChris Mason 
580d352ac68SChris Mason /*
581d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
582d352ac68SChris Mason  * node are actually close by
583d352ac68SChris Mason  */
5846b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
5856702ed49SChris Mason {
5866b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
5876702ed49SChris Mason 		return 1;
5886b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
5896702ed49SChris Mason 		return 1;
59002217ed2SChris Mason 	return 0;
59102217ed2SChris Mason }
59202217ed2SChris Mason 
593ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
594ce6ef5abSDavid Sterba 
595ce6ef5abSDavid Sterba /*
596ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
597ce6ef5abSDavid Sterba  * we can avoid the conversion.
598ce6ef5abSDavid Sterba  */
599ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
600ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
601ce6ef5abSDavid Sterba {
602ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
603ce6ef5abSDavid Sterba 
604ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
605ce6ef5abSDavid Sterba }
606ce6ef5abSDavid Sterba 
607ce6ef5abSDavid Sterba #else
608ce6ef5abSDavid Sterba 
609081e9573SChris Mason /*
610081e9573SChris Mason  * compare two keys in a memcmp fashion
611081e9573SChris Mason  */
612310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
613310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
614081e9573SChris Mason {
615081e9573SChris Mason 	struct btrfs_key k1;
616081e9573SChris Mason 
617081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
618081e9573SChris Mason 
61920736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
620081e9573SChris Mason }
621ce6ef5abSDavid Sterba #endif
622081e9573SChris Mason 
623f3465ca4SJosef Bacik /*
624f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
625f3465ca4SJosef Bacik  */
626e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
627f3465ca4SJosef Bacik {
628f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
629f3465ca4SJosef Bacik 		return 1;
630f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
631f3465ca4SJosef Bacik 		return -1;
632f3465ca4SJosef Bacik 	if (k1->type > k2->type)
633f3465ca4SJosef Bacik 		return 1;
634f3465ca4SJosef Bacik 	if (k1->type < k2->type)
635f3465ca4SJosef Bacik 		return -1;
636f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
637f3465ca4SJosef Bacik 		return 1;
638f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
639f3465ca4SJosef Bacik 		return -1;
640f3465ca4SJosef Bacik 	return 0;
641f3465ca4SJosef Bacik }
642081e9573SChris Mason 
643d352ac68SChris Mason /*
644d352ac68SChris Mason  * this is used by the defrag code to go through all the
645d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
646d352ac68SChris Mason  * disk order is close to key order
647d352ac68SChris Mason  */
6486702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
6495f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
650de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
651a6b6e75eSChris Mason 		       struct btrfs_key *progress)
6526702ed49SChris Mason {
6530b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6546b80053dSChris Mason 	struct extent_buffer *cur;
6556702ed49SChris Mason 	u64 blocknr;
656e9d0b13bSChris Mason 	u64 search_start = *last_ret;
657e9d0b13bSChris Mason 	u64 last_block = 0;
6586702ed49SChris Mason 	u64 other;
6596702ed49SChris Mason 	u32 parent_nritems;
6606702ed49SChris Mason 	int end_slot;
6616702ed49SChris Mason 	int i;
6626702ed49SChris Mason 	int err = 0;
6636b80053dSChris Mason 	u32 blocksize;
664081e9573SChris Mason 	int progress_passed = 0;
665081e9573SChris Mason 	struct btrfs_disk_key disk_key;
6666702ed49SChris Mason 
6670b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
6680b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
66986479a04SChris Mason 
6706b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
6710b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
6725dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
6736702ed49SChris Mason 
6745dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
6756702ed49SChris Mason 		return 0;
6766702ed49SChris Mason 
6775dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
6786702ed49SChris Mason 		int close = 1;
679a6b6e75eSChris Mason 
680081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
681081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
682081e9573SChris Mason 			continue;
683081e9573SChris Mason 
684081e9573SChris Mason 		progress_passed = 1;
6856b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
686e9d0b13bSChris Mason 		if (last_block == 0)
687e9d0b13bSChris Mason 			last_block = blocknr;
6885708b959SChris Mason 
6896702ed49SChris Mason 		if (i > 0) {
6906b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
6916b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
6926702ed49SChris Mason 		}
6935dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
6946b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
6956b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
6966702ed49SChris Mason 		}
697e9d0b13bSChris Mason 		if (close) {
698e9d0b13bSChris Mason 			last_block = blocknr;
6996702ed49SChris Mason 			continue;
700e9d0b13bSChris Mason 		}
7016702ed49SChris Mason 
702206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
703206983b7SJosef Bacik 		if (IS_ERR(cur))
70464c043deSLiu Bo 			return PTR_ERR(cur);
705e9d0b13bSChris Mason 		if (search_start == 0)
7066b80053dSChris Mason 			search_start = last_block;
707e9d0b13bSChris Mason 
708e7a84565SChris Mason 		btrfs_tree_lock(cur);
7096b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
710e7a84565SChris Mason 					&cur, search_start,
7116b80053dSChris Mason 					min(16 * blocksize,
7129631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
7139631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
714252c38f0SYan 		if (err) {
715e7a84565SChris Mason 			btrfs_tree_unlock(cur);
7166b80053dSChris Mason 			free_extent_buffer(cur);
7176702ed49SChris Mason 			break;
718252c38f0SYan 		}
719e7a84565SChris Mason 		search_start = cur->start;
720e7a84565SChris Mason 		last_block = cur->start;
721f2183bdeSChris Mason 		*last_ret = search_start;
722e7a84565SChris Mason 		btrfs_tree_unlock(cur);
723e7a84565SChris Mason 		free_extent_buffer(cur);
7246702ed49SChris Mason 	}
7256702ed49SChris Mason 	return err;
7266702ed49SChris Mason }
7276702ed49SChris Mason 
72874123bd7SChris Mason /*
729fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
7305f39d397SChris Mason  *
731fb81212cSFilipe Manana  * The lower boundary for the search is specified by the slot number @low. Use a
732fb81212cSFilipe Manana  * value of 0 to search over the whole extent buffer.
73374123bd7SChris Mason  *
734fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
735fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
736fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
737fb81212cSFilipe Manana  *
738fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
739fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
74074123bd7SChris Mason  */
741fb81212cSFilipe Manana static noinline int generic_bin_search(struct extent_buffer *eb, int low,
74267d5e289SMarcos Paulo de Souza 				       const struct btrfs_key *key, int *slot)
743be0e5c09SChris Mason {
744fb81212cSFilipe Manana 	unsigned long p;
745fb81212cSFilipe Manana 	int item_size;
74667d5e289SMarcos Paulo de Souza 	int high = btrfs_header_nritems(eb);
747be0e5c09SChris Mason 	int ret;
7485cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
749be0e5c09SChris Mason 
7505e24e9afSLiu Bo 	if (low > high) {
7515e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
7525e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
7535e24e9afSLiu Bo 			  __func__, low, high, eb->start,
7545e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
7555e24e9afSLiu Bo 		return -EINVAL;
7565e24e9afSLiu Bo 	}
7575e24e9afSLiu Bo 
758fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
759fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
760fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
761fb81212cSFilipe Manana 	} else {
762fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
763fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
764fb81212cSFilipe Manana 	}
765fb81212cSFilipe Manana 
766be0e5c09SChris Mason 	while (low < high) {
7675cd17f34SDavid Sterba 		unsigned long oip;
7685cd17f34SDavid Sterba 		unsigned long offset;
7695cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
7705cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
7715cd17f34SDavid Sterba 		int mid;
7725cd17f34SDavid Sterba 
773be0e5c09SChris Mason 		mid = (low + high) / 2;
7745f39d397SChris Mason 		offset = p + mid * item_size;
7755cd17f34SDavid Sterba 		oip = offset_in_page(offset);
7765f39d397SChris Mason 
7775cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
778884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
7795cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
780934d375bSChris Mason 
781884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
7825cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
7835cd17f34SDavid Sterba 		} else {
7845cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
7855f39d397SChris Mason 			tmp = &unaligned;
786479965d6SChris Mason 		}
787479965d6SChris Mason 
788be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
789be0e5c09SChris Mason 
790be0e5c09SChris Mason 		if (ret < 0)
791be0e5c09SChris Mason 			low = mid + 1;
792be0e5c09SChris Mason 		else if (ret > 0)
793be0e5c09SChris Mason 			high = mid;
794be0e5c09SChris Mason 		else {
795be0e5c09SChris Mason 			*slot = mid;
796be0e5c09SChris Mason 			return 0;
797be0e5c09SChris Mason 		}
798be0e5c09SChris Mason 	}
799be0e5c09SChris Mason 	*slot = low;
800be0e5c09SChris Mason 	return 1;
801be0e5c09SChris Mason }
802be0e5c09SChris Mason 
80397571fd0SChris Mason /*
804fb81212cSFilipe Manana  * Simple binary search on an extent buffer. Works for both leaves and nodes, and
805fb81212cSFilipe Manana  * always searches over the whole range of keys (slot 0 to slot 'nritems - 1').
80697571fd0SChris Mason  */
807a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
808e3b83361SQu Wenruo 		     int *slot)
809be0e5c09SChris Mason {
810fb81212cSFilipe Manana 	return generic_bin_search(eb, 0, key, slot);
811be0e5c09SChris Mason }
812be0e5c09SChris Mason 
813f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
814f0486c68SYan, Zheng {
815f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
816f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
817f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
818f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
819f0486c68SYan, Zheng }
820f0486c68SYan, Zheng 
821f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
822f0486c68SYan, Zheng {
823f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
824f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
825f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
826f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
827f0486c68SYan, Zheng }
828f0486c68SYan, Zheng 
829d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
830d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
831d352ac68SChris Mason  */
8324b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
8334b231ae4SDavid Sterba 					   int slot)
834bb803951SChris Mason {
835ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
836416bc658SJosef Bacik 	struct extent_buffer *eb;
837581c1760SQu Wenruo 	struct btrfs_key first_key;
838416bc658SJosef Bacik 
839fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
840fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
841ca7a79adSChris Mason 
842ca7a79adSChris Mason 	BUG_ON(level == 0);
843ca7a79adSChris Mason 
844581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
845d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
8461b7ec85eSJosef Bacik 			     btrfs_header_owner(parent),
847581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
848581c1760SQu Wenruo 			     level - 1, &first_key);
8494eb150d6SQu Wenruo 	if (IS_ERR(eb))
8504eb150d6SQu Wenruo 		return eb;
8514eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
852416bc658SJosef Bacik 		free_extent_buffer(eb);
8534eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
854416bc658SJosef Bacik 	}
855416bc658SJosef Bacik 
856416bc658SJosef Bacik 	return eb;
857bb803951SChris Mason }
858bb803951SChris Mason 
859d352ac68SChris Mason /*
860d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
861d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
862d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
863d352ac68SChris Mason  */
864e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
86598ed5174SChris Mason 			 struct btrfs_root *root,
86698ed5174SChris Mason 			 struct btrfs_path *path, int level)
867bb803951SChris Mason {
8680b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8695f39d397SChris Mason 	struct extent_buffer *right = NULL;
8705f39d397SChris Mason 	struct extent_buffer *mid;
8715f39d397SChris Mason 	struct extent_buffer *left = NULL;
8725f39d397SChris Mason 	struct extent_buffer *parent = NULL;
873bb803951SChris Mason 	int ret = 0;
874bb803951SChris Mason 	int wret;
875bb803951SChris Mason 	int pslot;
876bb803951SChris Mason 	int orig_slot = path->slots[level];
87779f95c82SChris Mason 	u64 orig_ptr;
878bb803951SChris Mason 
87998e6b1ebSLiu Bo 	ASSERT(level > 0);
880bb803951SChris Mason 
8815f39d397SChris Mason 	mid = path->nodes[level];
882b4ce94deSChris Mason 
883ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
8847bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
8857bb86316SChris Mason 
8861d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
88779f95c82SChris Mason 
888a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
8895f39d397SChris Mason 		parent = path->nodes[level + 1];
890bb803951SChris Mason 		pslot = path->slots[level + 1];
891a05a9bb1SLi Zefan 	}
892bb803951SChris Mason 
89340689478SChris Mason 	/*
89440689478SChris Mason 	 * deal with the case where there is only one pointer in the root
89540689478SChris Mason 	 * by promoting the node below to a root
89640689478SChris Mason 	 */
8975f39d397SChris Mason 	if (!parent) {
8985f39d397SChris Mason 		struct extent_buffer *child;
899bb803951SChris Mason 
9005f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
901bb803951SChris Mason 			return 0;
902bb803951SChris Mason 
903bb803951SChris Mason 		/* promote the child to a root */
9044b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
905fb770ae4SLiu Bo 		if (IS_ERR(child)) {
906fb770ae4SLiu Bo 			ret = PTR_ERR(child);
9070b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
908305a26afSMark Fasheh 			goto enospc;
909305a26afSMark Fasheh 		}
910305a26afSMark Fasheh 
911925baeddSChris Mason 		btrfs_tree_lock(child);
9129631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
9139631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
914f0486c68SYan, Zheng 		if (ret) {
915f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
916f0486c68SYan, Zheng 			free_extent_buffer(child);
917f0486c68SYan, Zheng 			goto enospc;
918f0486c68SYan, Zheng 		}
9192f375ab9SYan 
920406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
921d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
922240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
923925baeddSChris Mason 
9240b86a832SChris Mason 		add_root_to_dirty_list(root);
925925baeddSChris Mason 		btrfs_tree_unlock(child);
926b4ce94deSChris Mason 
927925baeddSChris Mason 		path->locks[level] = 0;
928bb803951SChris Mason 		path->nodes[level] = NULL;
9296a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
930925baeddSChris Mason 		btrfs_tree_unlock(mid);
931bb803951SChris Mason 		/* once for the path */
9325f39d397SChris Mason 		free_extent_buffer(mid);
933f0486c68SYan, Zheng 
934f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
9357a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
936bb803951SChris Mason 		/* once for the root ptr */
9373083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
938f0486c68SYan, Zheng 		return 0;
939bb803951SChris Mason 	}
9405f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
9410b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
942bb803951SChris Mason 		return 0;
943bb803951SChris Mason 
9444b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
945fb770ae4SLiu Bo 	if (IS_ERR(left))
946fb770ae4SLiu Bo 		left = NULL;
947fb770ae4SLiu Bo 
9485f39d397SChris Mason 	if (left) {
949bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
9505f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
9519631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
952bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
95354aa1f4dSChris Mason 		if (wret) {
95454aa1f4dSChris Mason 			ret = wret;
95554aa1f4dSChris Mason 			goto enospc;
95654aa1f4dSChris Mason 		}
9572cc58cf2SChris Mason 	}
958fb770ae4SLiu Bo 
9594b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
960fb770ae4SLiu Bo 	if (IS_ERR(right))
961fb770ae4SLiu Bo 		right = NULL;
962fb770ae4SLiu Bo 
9635f39d397SChris Mason 	if (right) {
964bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
9655f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
9669631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
967bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
9682cc58cf2SChris Mason 		if (wret) {
9692cc58cf2SChris Mason 			ret = wret;
9702cc58cf2SChris Mason 			goto enospc;
9712cc58cf2SChris Mason 		}
9722cc58cf2SChris Mason 	}
9732cc58cf2SChris Mason 
9742cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
9755f39d397SChris Mason 	if (left) {
9765f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
977d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
97879f95c82SChris Mason 		if (wret < 0)
97979f95c82SChris Mason 			ret = wret;
980bb803951SChris Mason 	}
98179f95c82SChris Mason 
98279f95c82SChris Mason 	/*
98379f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
98479f95c82SChris Mason 	 */
9855f39d397SChris Mason 	if (right) {
986d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
98754aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
98879f95c82SChris Mason 			ret = wret;
9895f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
9906a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
991925baeddSChris Mason 			btrfs_tree_unlock(right);
992afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
993f0486c68SYan, Zheng 			root_sub_used(root, right->len);
9947a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
9957a163608SFilipe Manana 					      0, 1);
9963083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
997f0486c68SYan, Zheng 			right = NULL;
998bb803951SChris Mason 		} else {
9995f39d397SChris Mason 			struct btrfs_disk_key right_key;
10005f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1001f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1002f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
10030e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
10045f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
10055f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1006bb803951SChris Mason 		}
1007bb803951SChris Mason 	}
10085f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
100979f95c82SChris Mason 		/*
101079f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
101179f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
101279f95c82SChris Mason 		 * could try to delete the only pointer in this node.
101379f95c82SChris Mason 		 * So, pull some keys from the left.
101479f95c82SChris Mason 		 * There has to be a left pointer at this point because
101579f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
101679f95c82SChris Mason 		 * right
101779f95c82SChris Mason 		 */
1018305a26afSMark Fasheh 		if (!left) {
1019305a26afSMark Fasheh 			ret = -EROFS;
10200b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1021305a26afSMark Fasheh 			goto enospc;
1022305a26afSMark Fasheh 		}
102355d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
102454aa1f4dSChris Mason 		if (wret < 0) {
102579f95c82SChris Mason 			ret = wret;
102654aa1f4dSChris Mason 			goto enospc;
102754aa1f4dSChris Mason 		}
1028bce4eae9SChris Mason 		if (wret == 1) {
1029d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1030bce4eae9SChris Mason 			if (wret < 0)
1031bce4eae9SChris Mason 				ret = wret;
1032bce4eae9SChris Mason 		}
103379f95c82SChris Mason 		BUG_ON(wret == 1);
103479f95c82SChris Mason 	}
10355f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
10366a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1037925baeddSChris Mason 		btrfs_tree_unlock(mid);
1038afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1039f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10407a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
10413083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1042f0486c68SYan, Zheng 		mid = NULL;
104379f95c82SChris Mason 	} else {
104479f95c82SChris Mason 		/* update the parent key to reflect our changes */
10455f39d397SChris Mason 		struct btrfs_disk_key mid_key;
10465f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1047f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1048f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
10490e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
10505f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
10515f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
105279f95c82SChris Mason 	}
1053bb803951SChris Mason 
105479f95c82SChris Mason 	/* update the path */
10555f39d397SChris Mason 	if (left) {
10565f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
105767439dadSDavid Sterba 			atomic_inc(&left->refs);
1058925baeddSChris Mason 			/* left was locked after cow */
10595f39d397SChris Mason 			path->nodes[level] = left;
1060bb803951SChris Mason 			path->slots[level + 1] -= 1;
1061bb803951SChris Mason 			path->slots[level] = orig_slot;
1062925baeddSChris Mason 			if (mid) {
1063925baeddSChris Mason 				btrfs_tree_unlock(mid);
10645f39d397SChris Mason 				free_extent_buffer(mid);
1065925baeddSChris Mason 			}
1066bb803951SChris Mason 		} else {
10675f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1068bb803951SChris Mason 			path->slots[level] = orig_slot;
1069bb803951SChris Mason 		}
1070bb803951SChris Mason 	}
107179f95c82SChris Mason 	/* double check we haven't messed things up */
1072e20d96d6SChris Mason 	if (orig_ptr !=
10735f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
107479f95c82SChris Mason 		BUG();
107554aa1f4dSChris Mason enospc:
1076925baeddSChris Mason 	if (right) {
1077925baeddSChris Mason 		btrfs_tree_unlock(right);
10785f39d397SChris Mason 		free_extent_buffer(right);
1079925baeddSChris Mason 	}
1080925baeddSChris Mason 	if (left) {
1081925baeddSChris Mason 		if (path->nodes[level] != left)
1082925baeddSChris Mason 			btrfs_tree_unlock(left);
10835f39d397SChris Mason 		free_extent_buffer(left);
1084925baeddSChris Mason 	}
1085bb803951SChris Mason 	return ret;
1086bb803951SChris Mason }
1087bb803951SChris Mason 
1088d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1089d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1090d352ac68SChris Mason  * have to be pessimistic.
1091d352ac68SChris Mason  */
1092d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1093e66f709bSChris Mason 					  struct btrfs_root *root,
1094e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1095e66f709bSChris Mason {
10960b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10975f39d397SChris Mason 	struct extent_buffer *right = NULL;
10985f39d397SChris Mason 	struct extent_buffer *mid;
10995f39d397SChris Mason 	struct extent_buffer *left = NULL;
11005f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1101e66f709bSChris Mason 	int ret = 0;
1102e66f709bSChris Mason 	int wret;
1103e66f709bSChris Mason 	int pslot;
1104e66f709bSChris Mason 	int orig_slot = path->slots[level];
1105e66f709bSChris Mason 
1106e66f709bSChris Mason 	if (level == 0)
1107e66f709bSChris Mason 		return 1;
1108e66f709bSChris Mason 
11095f39d397SChris Mason 	mid = path->nodes[level];
11107bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1111e66f709bSChris Mason 
1112a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
11135f39d397SChris Mason 		parent = path->nodes[level + 1];
1114e66f709bSChris Mason 		pslot = path->slots[level + 1];
1115a05a9bb1SLi Zefan 	}
1116e66f709bSChris Mason 
11175f39d397SChris Mason 	if (!parent)
1118e66f709bSChris Mason 		return 1;
1119e66f709bSChris Mason 
11204b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1121fb770ae4SLiu Bo 	if (IS_ERR(left))
1122fb770ae4SLiu Bo 		left = NULL;
1123e66f709bSChris Mason 
1124e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
11255f39d397SChris Mason 	if (left) {
1126e66f709bSChris Mason 		u32 left_nr;
1127925baeddSChris Mason 
1128bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1129b4ce94deSChris Mason 
11305f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
11310b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
113233ade1f8SChris Mason 			wret = 1;
113333ade1f8SChris Mason 		} else {
11345f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
11359631e4ccSJosef Bacik 					      pslot - 1, &left,
1136bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
113754aa1f4dSChris Mason 			if (ret)
113854aa1f4dSChris Mason 				wret = 1;
113954aa1f4dSChris Mason 			else {
1140d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
114154aa1f4dSChris Mason 			}
114233ade1f8SChris Mason 		}
1143e66f709bSChris Mason 		if (wret < 0)
1144e66f709bSChris Mason 			ret = wret;
1145e66f709bSChris Mason 		if (wret == 0) {
11465f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1147e66f709bSChris Mason 			orig_slot += left_nr;
11485f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1149f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1150f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
11510e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11525f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
11535f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
11545f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
11555f39d397SChris Mason 				path->nodes[level] = left;
1156e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1157e66f709bSChris Mason 				path->slots[level] = orig_slot;
1158925baeddSChris Mason 				btrfs_tree_unlock(mid);
11595f39d397SChris Mason 				free_extent_buffer(mid);
1160e66f709bSChris Mason 			} else {
1161e66f709bSChris Mason 				orig_slot -=
11625f39d397SChris Mason 					btrfs_header_nritems(left);
1163e66f709bSChris Mason 				path->slots[level] = orig_slot;
1164925baeddSChris Mason 				btrfs_tree_unlock(left);
11655f39d397SChris Mason 				free_extent_buffer(left);
1166e66f709bSChris Mason 			}
1167e66f709bSChris Mason 			return 0;
1168e66f709bSChris Mason 		}
1169925baeddSChris Mason 		btrfs_tree_unlock(left);
11705f39d397SChris Mason 		free_extent_buffer(left);
1171e66f709bSChris Mason 	}
11724b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1173fb770ae4SLiu Bo 	if (IS_ERR(right))
1174fb770ae4SLiu Bo 		right = NULL;
1175e66f709bSChris Mason 
1176e66f709bSChris Mason 	/*
1177e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1178e66f709bSChris Mason 	 */
11795f39d397SChris Mason 	if (right) {
118033ade1f8SChris Mason 		u32 right_nr;
1181b4ce94deSChris Mason 
1182bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1183b4ce94deSChris Mason 
11845f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
11850b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
118633ade1f8SChris Mason 			wret = 1;
118733ade1f8SChris Mason 		} else {
11885f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
11895f39d397SChris Mason 					      parent, pslot + 1,
1190bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
119154aa1f4dSChris Mason 			if (ret)
119254aa1f4dSChris Mason 				wret = 1;
119354aa1f4dSChris Mason 			else {
119455d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
119533ade1f8SChris Mason 			}
119654aa1f4dSChris Mason 		}
1197e66f709bSChris Mason 		if (wret < 0)
1198e66f709bSChris Mason 			ret = wret;
1199e66f709bSChris Mason 		if (wret == 0) {
12005f39d397SChris Mason 			struct btrfs_disk_key disk_key;
12015f39d397SChris Mason 
12025f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1203f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1204f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
12050e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
12065f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
12075f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12085f39d397SChris Mason 
12095f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
12105f39d397SChris Mason 				path->nodes[level] = right;
1211e66f709bSChris Mason 				path->slots[level + 1] += 1;
1212e66f709bSChris Mason 				path->slots[level] = orig_slot -
12135f39d397SChris Mason 					btrfs_header_nritems(mid);
1214925baeddSChris Mason 				btrfs_tree_unlock(mid);
12155f39d397SChris Mason 				free_extent_buffer(mid);
1216e66f709bSChris Mason 			} else {
1217925baeddSChris Mason 				btrfs_tree_unlock(right);
12185f39d397SChris Mason 				free_extent_buffer(right);
1219e66f709bSChris Mason 			}
1220e66f709bSChris Mason 			return 0;
1221e66f709bSChris Mason 		}
1222925baeddSChris Mason 		btrfs_tree_unlock(right);
12235f39d397SChris Mason 		free_extent_buffer(right);
1224e66f709bSChris Mason 	}
1225e66f709bSChris Mason 	return 1;
1226e66f709bSChris Mason }
1227e66f709bSChris Mason 
122874123bd7SChris Mason /*
1229d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1230d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
12313c69faecSChris Mason  */
12322ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1233e02119d5SChris Mason 			     struct btrfs_path *path,
123401f46658SChris Mason 			     int level, int slot, u64 objectid)
12353c69faecSChris Mason {
12365f39d397SChris Mason 	struct extent_buffer *node;
123701f46658SChris Mason 	struct btrfs_disk_key disk_key;
12383c69faecSChris Mason 	u32 nritems;
12393c69faecSChris Mason 	u64 search;
1240a7175319SChris Mason 	u64 target;
12416b80053dSChris Mason 	u64 nread = 0;
1242ace75066SFilipe Manana 	u64 nread_max;
12436b80053dSChris Mason 	u32 nr;
12446b80053dSChris Mason 	u32 blocksize;
12456b80053dSChris Mason 	u32 nscan = 0;
1246db94535dSChris Mason 
1247ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
12483c69faecSChris Mason 		return;
12493c69faecSChris Mason 
12506702ed49SChris Mason 	if (!path->nodes[level])
12516702ed49SChris Mason 		return;
12526702ed49SChris Mason 
12535f39d397SChris Mason 	node = path->nodes[level];
1254925baeddSChris Mason 
1255ace75066SFilipe Manana 	/*
1256ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1257ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1258ace75066SFilipe Manana 	 * much IO at once (possibly random).
1259ace75066SFilipe Manana 	 */
1260ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1261ace75066SFilipe Manana 		if (level > 1)
1262ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1263ace75066SFilipe Manana 		else
1264ace75066SFilipe Manana 			nread_max = SZ_128K;
1265ace75066SFilipe Manana 	} else {
1266ace75066SFilipe Manana 		nread_max = SZ_64K;
1267ace75066SFilipe Manana 	}
1268ace75066SFilipe Manana 
12693c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
12700b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1271069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1272069a2e37SFilipe Manana 		struct extent_buffer *eb;
1273069a2e37SFilipe Manana 
12740b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
12755f39d397SChris Mason 		if (eb) {
12765f39d397SChris Mason 			free_extent_buffer(eb);
12773c69faecSChris Mason 			return;
12783c69faecSChris Mason 		}
1279069a2e37SFilipe Manana 	}
12803c69faecSChris Mason 
1281a7175319SChris Mason 	target = search;
12826b80053dSChris Mason 
12835f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
12846b80053dSChris Mason 	nr = slot;
128525b8b936SJosef Bacik 
12863c69faecSChris Mason 	while (1) {
1287e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
12886b80053dSChris Mason 			if (nr == 0)
12893c69faecSChris Mason 				break;
12906b80053dSChris Mason 			nr--;
1291ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1292ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
12936b80053dSChris Mason 			nr++;
12946b80053dSChris Mason 			if (nr >= nritems)
12956b80053dSChris Mason 				break;
12963c69faecSChris Mason 		}
1297e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
129801f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
129901f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
130001f46658SChris Mason 				break;
130101f46658SChris Mason 		}
13026b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1303ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1304ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1305a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1306bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
13076b80053dSChris Mason 			nread += blocksize;
13083c69faecSChris Mason 		}
13096b80053dSChris Mason 		nscan++;
1310ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
13116b80053dSChris Mason 			break;
13123c69faecSChris Mason 	}
13133c69faecSChris Mason }
1314925baeddSChris Mason 
1315bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1316b4ce94deSChris Mason {
1317bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1318b4ce94deSChris Mason 	int slot;
1319b4ce94deSChris Mason 	int nritems;
1320b4ce94deSChris Mason 
13218c594ea8SChris Mason 	parent = path->nodes[level + 1];
1322b4ce94deSChris Mason 	if (!parent)
13230b08851fSJosef Bacik 		return;
1324b4ce94deSChris Mason 
1325b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
13268c594ea8SChris Mason 	slot = path->slots[level + 1];
1327b4ce94deSChris Mason 
1328bfb484d9SJosef Bacik 	if (slot > 0)
1329bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1330bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1331bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1332b4ce94deSChris Mason }
1333b4ce94deSChris Mason 
1334b4ce94deSChris Mason 
1335b4ce94deSChris Mason /*
1336d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1337d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1338d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1339d397712bSChris Mason  * tree.
1340d352ac68SChris Mason  *
1341d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1342d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1343d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1344d352ac68SChris Mason  *
1345d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1346d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1347d352ac68SChris Mason  */
1348e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1349f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1350f7c79f30SChris Mason 			       int *write_lock_level)
1351925baeddSChris Mason {
1352925baeddSChris Mason 	int i;
1353925baeddSChris Mason 	int skip_level = level;
1354c1227996SNikolay Borisov 	bool check_skip = true;
1355925baeddSChris Mason 
1356925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1357925baeddSChris Mason 		if (!path->nodes[i])
1358925baeddSChris Mason 			break;
1359925baeddSChris Mason 		if (!path->locks[i])
1360925baeddSChris Mason 			break;
1361c1227996SNikolay Borisov 
1362c1227996SNikolay Borisov 		if (check_skip) {
1363c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1364925baeddSChris Mason 				skip_level = i + 1;
1365925baeddSChris Mason 				continue;
1366925baeddSChris Mason 			}
1367c1227996SNikolay Borisov 
1368c1227996SNikolay Borisov 			if (path->keep_locks) {
1369925baeddSChris Mason 				u32 nritems;
1370c1227996SNikolay Borisov 
1371c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1372051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1373925baeddSChris Mason 					skip_level = i + 1;
1374925baeddSChris Mason 					continue;
1375925baeddSChris Mason 				}
1376925baeddSChris Mason 			}
1377c1227996SNikolay Borisov 		}
1378051e1b9fSChris Mason 
1379d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1380c1227996SNikolay Borisov 			check_skip = false;
1381c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1382925baeddSChris Mason 			path->locks[i] = 0;
1383f7c79f30SChris Mason 			if (write_lock_level &&
1384f7c79f30SChris Mason 			    i > min_write_lock_level &&
1385f7c79f30SChris Mason 			    i <= *write_lock_level) {
1386f7c79f30SChris Mason 				*write_lock_level = i - 1;
1387f7c79f30SChris Mason 			}
1388925baeddSChris Mason 		}
1389925baeddSChris Mason 	}
1390925baeddSChris Mason }
1391925baeddSChris Mason 
13923c69faecSChris Mason /*
1393*376a21d7SFilipe Manana  * Helper function for btrfs_search_slot() and other functions that do a search
1394*376a21d7SFilipe Manana  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1395*376a21d7SFilipe Manana  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1396*376a21d7SFilipe Manana  * its pages from disk.
1397c8c42864SChris Mason  *
1398*376a21d7SFilipe Manana  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1399*376a21d7SFilipe Manana  * whole btree search, starting again from the current root node.
1400c8c42864SChris Mason  */
1401c8c42864SChris Mason static int
1402d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1403c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1404cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1405c8c42864SChris Mason {
14060b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1407c8c42864SChris Mason 	u64 blocknr;
1408c8c42864SChris Mason 	u64 gen;
1409c8c42864SChris Mason 	struct extent_buffer *tmp;
1410581c1760SQu Wenruo 	struct btrfs_key first_key;
141176a05b35SChris Mason 	int ret;
1412581c1760SQu Wenruo 	int parent_level;
1413b246666eSFilipe Manana 	bool unlock_up;
1414c8c42864SChris Mason 
1415b246666eSFilipe Manana 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1416213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1417213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1418213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1419213ff4b7SNikolay Borisov 	btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
1420c8c42864SChris Mason 
1421b246666eSFilipe Manana 	/*
1422b246666eSFilipe Manana 	 * If we need to read an extent buffer from disk and we are holding locks
1423b246666eSFilipe Manana 	 * on upper level nodes, we unlock all the upper nodes before reading the
1424b246666eSFilipe Manana 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1425b246666eSFilipe Manana 	 * restart the search. We don't release the lock on the current level
1426b246666eSFilipe Manana 	 * because we need to walk this node to figure out which blocks to read.
1427b246666eSFilipe Manana 	 */
14280b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1429cb44921aSChris Mason 	if (tmp) {
1430ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1431ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1432ace75066SFilipe Manana 
1433b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1434b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1435448de471SQu Wenruo 			/*
1436448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1437448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1438448de471SQu Wenruo 			 * parents (shared tree blocks).
1439448de471SQu Wenruo 			 */
1440e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1441448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
1442448de471SQu Wenruo 				free_extent_buffer(tmp);
1443448de471SQu Wenruo 				return -EUCLEAN;
1444448de471SQu Wenruo 			}
1445c8c42864SChris Mason 			*eb_ret = tmp;
1446c8c42864SChris Mason 			return 0;
1447c8c42864SChris Mason 		}
1448bdf7c00eSJosef Bacik 
1449b246666eSFilipe Manana 		if (unlock_up)
1450b246666eSFilipe Manana 			btrfs_unlock_up_safe(p, level + 1);
1451b246666eSFilipe Manana 
1452b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
1453581c1760SQu Wenruo 		ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
14549a4ffa1bSQu Wenruo 		if (ret) {
1455cb44921aSChris Mason 			free_extent_buffer(tmp);
1456b3b4aa74SDavid Sterba 			btrfs_release_path(p);
1457cb44921aSChris Mason 			return -EIO;
1458cb44921aSChris Mason 		}
1459b246666eSFilipe Manana 
1460b246666eSFilipe Manana 		if (unlock_up)
1461b246666eSFilipe Manana 			ret = -EAGAIN;
1462b246666eSFilipe Manana 
1463b246666eSFilipe Manana 		goto out;
14649a4ffa1bSQu Wenruo 	}
1465c8c42864SChris Mason 
1466b246666eSFilipe Manana 	if (unlock_up) {
14678c594ea8SChris Mason 		btrfs_unlock_up_safe(p, level + 1);
14684bb59055SFilipe Manana 		ret = -EAGAIN;
14694bb59055SFilipe Manana 	} else {
14704bb59055SFilipe Manana 		ret = 0;
14714bb59055SFilipe Manana 	}
14728c594ea8SChris Mason 
1473e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
14742ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1475c8c42864SChris Mason 
14761b7ec85eSJosef Bacik 	tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
14771b7ec85eSJosef Bacik 			      gen, parent_level - 1, &first_key);
14784eb150d6SQu Wenruo 	if (IS_ERR(tmp)) {
14794eb150d6SQu Wenruo 		btrfs_release_path(p);
14804eb150d6SQu Wenruo 		return PTR_ERR(tmp);
14814eb150d6SQu Wenruo 	}
148276a05b35SChris Mason 	/*
148376a05b35SChris Mason 	 * If the read above didn't mark this buffer up to date,
148476a05b35SChris Mason 	 * it will never end up being up to date.  Set ret to EIO now
148576a05b35SChris Mason 	 * and give up so that our caller doesn't loop forever
148676a05b35SChris Mason 	 * on our EAGAINs.
148776a05b35SChris Mason 	 */
1488e6a1d6fdSLiu Bo 	if (!extent_buffer_uptodate(tmp))
148976a05b35SChris Mason 		ret = -EIO;
149002a3307aSLiu Bo 
1491b246666eSFilipe Manana out:
14924bb59055SFilipe Manana 	if (ret == 0) {
14934bb59055SFilipe Manana 		*eb_ret = tmp;
14944bb59055SFilipe Manana 	} else {
14954bb59055SFilipe Manana 		free_extent_buffer(tmp);
149602a3307aSLiu Bo 		btrfs_release_path(p);
14974bb59055SFilipe Manana 	}
14984bb59055SFilipe Manana 
149976a05b35SChris Mason 	return ret;
1500c8c42864SChris Mason }
1501c8c42864SChris Mason 
1502c8c42864SChris Mason /*
1503c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1504c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1505c8c42864SChris Mason  * the ins_len.
1506c8c42864SChris Mason  *
1507c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1508c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1509c8c42864SChris Mason  * start over
1510c8c42864SChris Mason  */
1511c8c42864SChris Mason static int
1512c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1513c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1514bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1515bd681513SChris Mason 		       int *write_lock_level)
1516c8c42864SChris Mason {
15170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
151895b982deSNikolay Borisov 	int ret = 0;
15190b246afaSJeff Mahoney 
1520c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
15210b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1522c8c42864SChris Mason 
1523bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1524bd681513SChris Mason 			*write_lock_level = level + 1;
1525bd681513SChris Mason 			btrfs_release_path(p);
152695b982deSNikolay Borisov 			return -EAGAIN;
1527bd681513SChris Mason 		}
1528bd681513SChris Mason 
1529bfb484d9SJosef Bacik 		reada_for_balance(p, level);
153095b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1531c8c42864SChris Mason 
1532c8c42864SChris Mason 		b = p->nodes[level];
1533c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
15340b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1535c8c42864SChris Mason 
1536bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1537bd681513SChris Mason 			*write_lock_level = level + 1;
1538bd681513SChris Mason 			btrfs_release_path(p);
153995b982deSNikolay Borisov 			return -EAGAIN;
1540bd681513SChris Mason 		}
1541bd681513SChris Mason 
1542bfb484d9SJosef Bacik 		reada_for_balance(p, level);
154395b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
154495b982deSNikolay Borisov 		if (ret)
154595b982deSNikolay Borisov 			return ret;
1546c8c42864SChris Mason 
1547c8c42864SChris Mason 		b = p->nodes[level];
1548c8c42864SChris Mason 		if (!b) {
1549b3b4aa74SDavid Sterba 			btrfs_release_path(p);
155095b982deSNikolay Borisov 			return -EAGAIN;
1551c8c42864SChris Mason 		}
1552c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1553c8c42864SChris Mason 	}
1554c8c42864SChris Mason 	return ret;
1555c8c42864SChris Mason }
1556c8c42864SChris Mason 
1557381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1558e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1559e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1560e33d5c3dSKelley Nielsen {
1561e33d5c3dSKelley Nielsen 	int ret;
1562e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1563e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1564381cf658SDavid Sterba 
1565381cf658SDavid Sterba 	ASSERT(path);
15661d4c08e0SDavid Sterba 	ASSERT(found_key);
1567e33d5c3dSKelley Nielsen 
1568e33d5c3dSKelley Nielsen 	key.type = key_type;
1569e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1570e33d5c3dSKelley Nielsen 	key.offset = ioff;
1571e33d5c3dSKelley Nielsen 
1572e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
15731d4c08e0SDavid Sterba 	if (ret < 0)
1574e33d5c3dSKelley Nielsen 		return ret;
1575e33d5c3dSKelley Nielsen 
1576e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1577e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1578e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1579e33d5c3dSKelley Nielsen 		if (ret)
1580e33d5c3dSKelley Nielsen 			return ret;
1581e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1582e33d5c3dSKelley Nielsen 	}
1583e33d5c3dSKelley Nielsen 
1584e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1585e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1586e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1587e33d5c3dSKelley Nielsen 		return 1;
1588e33d5c3dSKelley Nielsen 
1589e33d5c3dSKelley Nielsen 	return 0;
1590e33d5c3dSKelley Nielsen }
1591e33d5c3dSKelley Nielsen 
15921fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
15931fc28d8eSLiu Bo 							struct btrfs_path *p,
15941fc28d8eSLiu Bo 							int write_lock_level)
15951fc28d8eSLiu Bo {
15961fc28d8eSLiu Bo 	struct extent_buffer *b;
1597120de408SJosef Bacik 	int root_lock = 0;
15981fc28d8eSLiu Bo 	int level = 0;
15991fc28d8eSLiu Bo 
16001fc28d8eSLiu Bo 	if (p->search_commit_root) {
16011fc28d8eSLiu Bo 		b = root->commit_root;
160267439dadSDavid Sterba 		atomic_inc(&b->refs);
16031fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1604f9ddfd05SLiu Bo 		/*
1605f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1606f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1607f9ddfd05SLiu Bo 		 */
1608f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
16091fc28d8eSLiu Bo 
16101fc28d8eSLiu Bo 		goto out;
16111fc28d8eSLiu Bo 	}
16121fc28d8eSLiu Bo 
16131fc28d8eSLiu Bo 	if (p->skip_locking) {
16141fc28d8eSLiu Bo 		b = btrfs_root_node(root);
16151fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16161fc28d8eSLiu Bo 		goto out;
16171fc28d8eSLiu Bo 	}
16181fc28d8eSLiu Bo 
1619120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1620120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1621120de408SJosef Bacik 
16221fc28d8eSLiu Bo 	/*
1623662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1624662c653bSLiu Bo 	 * lock.
1625662c653bSLiu Bo 	 */
1626662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1627662c653bSLiu Bo 		/*
1628662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1629662c653bSLiu Bo 		 * have it read locked
16301fc28d8eSLiu Bo 		 */
16311bb96598SJosef Bacik 		b = btrfs_read_lock_root_node(root);
16321fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16331fc28d8eSLiu Bo 		if (level > write_lock_level)
16341fc28d8eSLiu Bo 			goto out;
16351fc28d8eSLiu Bo 
1636662c653bSLiu Bo 		/* Whoops, must trade for write lock */
16371fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
16381fc28d8eSLiu Bo 		free_extent_buffer(b);
1639662c653bSLiu Bo 	}
1640662c653bSLiu Bo 
16411fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
16421fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
16431fc28d8eSLiu Bo 
16441fc28d8eSLiu Bo 	/* The level might have changed, check again */
16451fc28d8eSLiu Bo 	level = btrfs_header_level(b);
16461fc28d8eSLiu Bo 
16471fc28d8eSLiu Bo out:
1648120de408SJosef Bacik 	/*
1649120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1650120de408SJosef Bacik 	 * longer valid, return an error in this case.
1651120de408SJosef Bacik 	 */
1652120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1653120de408SJosef Bacik 		if (root_lock)
1654120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1655120de408SJosef Bacik 		free_extent_buffer(b);
1656120de408SJosef Bacik 		return ERR_PTR(-EIO);
1657120de408SJosef Bacik 	}
1658120de408SJosef Bacik 
16591fc28d8eSLiu Bo 	p->nodes[level] = b;
16601fc28d8eSLiu Bo 	if (!p->skip_locking)
16611fc28d8eSLiu Bo 		p->locks[level] = root_lock;
16621fc28d8eSLiu Bo 	/*
16631fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
16641fc28d8eSLiu Bo 	 */
16651fc28d8eSLiu Bo 	return b;
16661fc28d8eSLiu Bo }
16671fc28d8eSLiu Bo 
1668d96b3424SFilipe Manana /*
1669d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1670d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1671d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1672d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1673d96b3424SFilipe Manana  * reallocated in the next transaction.
1674d96b3424SFilipe Manana  *
1675d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1676d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1677d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1678d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1679d96b3424SFilipe Manana  */
1680d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1681d96b3424SFilipe Manana {
1682d96b3424SFilipe Manana 	const int i = path->lowest_level;
1683d96b3424SFilipe Manana 	const int slot = path->slots[i];
1684d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1685d96b3424SFilipe Manana 	struct extent_buffer *clone;
1686d96b3424SFilipe Manana 
1687d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1688d96b3424SFilipe Manana 
1689d96b3424SFilipe Manana 	if (!lowest)
1690d96b3424SFilipe Manana 		return 0;
1691d96b3424SFilipe Manana 
1692d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1693d96b3424SFilipe Manana 
1694d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1695d96b3424SFilipe Manana 	if (!clone)
1696d96b3424SFilipe Manana 		return -ENOMEM;
1697d96b3424SFilipe Manana 
1698d96b3424SFilipe Manana 	btrfs_release_path(path);
1699d96b3424SFilipe Manana 	path->nodes[i] = clone;
1700d96b3424SFilipe Manana 	path->slots[i] = slot;
1701d96b3424SFilipe Manana 
1702d96b3424SFilipe Manana 	return 0;
1703d96b3424SFilipe Manana }
17041fc28d8eSLiu Bo 
1705e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1706e2e58d0fSFilipe Manana 				      int search_low_slot,
1707e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1708e2e58d0fSFilipe Manana 				      int prev_cmp,
1709e2e58d0fSFilipe Manana 				      int *slot)
1710e2e58d0fSFilipe Manana {
1711e2e58d0fSFilipe Manana 	/*
1712e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1713e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1714e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1715e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1716e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1717e2e58d0fSFilipe Manana 	 */
1718e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1719e2e58d0fSFilipe Manana 		*slot = 0;
1720e2e58d0fSFilipe Manana 		return 0;
1721e2e58d0fSFilipe Manana 	}
1722e2e58d0fSFilipe Manana 
1723e2e58d0fSFilipe Manana 	return generic_bin_search(eb, search_low_slot, key, slot);
1724e2e58d0fSFilipe Manana }
1725e2e58d0fSFilipe Manana 
1726109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1727109324cfSFilipe Manana 		       struct btrfs_root *root,
1728109324cfSFilipe Manana 		       const struct btrfs_key *key,
1729109324cfSFilipe Manana 		       struct btrfs_path *path,
1730109324cfSFilipe Manana 		       int ins_len,
1731109324cfSFilipe Manana 		       int prev_cmp)
1732109324cfSFilipe Manana {
1733109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
1734109324cfSFilipe Manana 	int leaf_free_space = -1;
1735109324cfSFilipe Manana 	int search_low_slot = 0;
1736109324cfSFilipe Manana 	int ret;
1737109324cfSFilipe Manana 	bool do_bin_search = true;
1738109324cfSFilipe Manana 
1739109324cfSFilipe Manana 	/*
1740109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
1741109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
1742109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
1743109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1744109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
1745109324cfSFilipe Manana 	 */
1746109324cfSFilipe Manana 	if (ins_len > 0) {
1747109324cfSFilipe Manana 		/*
1748109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
1749109324cfSFilipe Manana 		 * will not change until then.
1750109324cfSFilipe Manana 		 */
1751109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
1752109324cfSFilipe Manana 
1753109324cfSFilipe Manana 		/*
1754109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
1755109324cfSFilipe Manana 		 * the root of the tree.
1756109324cfSFilipe Manana 		 */
1757109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
1758109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
1759109324cfSFilipe Manana 
1760109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
1761109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
1762109324cfSFilipe Manana 
1763109324cfSFilipe Manana 			/*
1764109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
1765109324cfSFilipe Manana 			 * taking into account that the first key is very likely
1766109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
1767109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
1768109324cfSFilipe Manana 			 * the header's level field.
1769109324cfSFilipe Manana 			 */
1770109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
1771109324cfSFilipe Manana 			if (ret < 0) {
1772109324cfSFilipe Manana 				/*
1773109324cfSFilipe Manana 				 * The first key is smaller than the key we want
1774109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
1775109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
1776109324cfSFilipe Manana 				 *
1777109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
1778109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
1779109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
1780109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
1781109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
1782109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
1783109324cfSFilipe Manana 				 */
1784109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
1785109324cfSFilipe Manana 				search_low_slot = 1;
1786109324cfSFilipe Manana 			} else {
1787109324cfSFilipe Manana 				/*
1788109324cfSFilipe Manana 				 * The first key is >= then the key we want to
1789109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
1790109324cfSFilipe Manana 				 * the target key will be at slot 0.
1791109324cfSFilipe Manana 				 *
1792109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
1793109324cfSFilipe Manana 				 * less than the first key, because we will need
1794109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
1795109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
1796109324cfSFilipe Manana 				 * If the key matches the first key, then we can
1797109324cfSFilipe Manana 				 * unlock all the upper nodes, using
1798109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
1799109324cfSFilipe Manana 				 * as stated above.
1800109324cfSFilipe Manana 				 */
1801109324cfSFilipe Manana 				if (ret == 0)
1802109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
1803109324cfSFilipe Manana 				/*
1804109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
1805109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
1806109324cfSFilipe Manana 				 * to adjust it.
1807109324cfSFilipe Manana 				 */
1808109324cfSFilipe Manana 				do_bin_search = false;
1809109324cfSFilipe Manana 				path->slots[0] = 0;
1810109324cfSFilipe Manana 			}
1811109324cfSFilipe Manana 		}
1812109324cfSFilipe Manana 	}
1813109324cfSFilipe Manana 
1814109324cfSFilipe Manana 	if (do_bin_search) {
1815109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
1816109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
1817109324cfSFilipe Manana 		if (ret < 0)
1818109324cfSFilipe Manana 			return ret;
1819109324cfSFilipe Manana 	}
1820109324cfSFilipe Manana 
1821109324cfSFilipe Manana 	if (ins_len > 0) {
1822109324cfSFilipe Manana 		/*
1823109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
1824109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
1825109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
1826109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
1827109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
1828109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
1829109324cfSFilipe Manana 		 * check will be correct.
1830109324cfSFilipe Manana 		 */
1831109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
1832109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
1833109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
1834109324cfSFilipe Manana 		}
1835109324cfSFilipe Manana 
1836109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
1837109324cfSFilipe Manana 
1838109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
1839109324cfSFilipe Manana 			int err;
1840109324cfSFilipe Manana 
1841109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
1842109324cfSFilipe Manana 					 (ret == 0));
1843bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
1844bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
1845bb8e9a60SFilipe Manana 				err = -EUCLEAN;
1846109324cfSFilipe Manana 			if (err)
1847109324cfSFilipe Manana 				ret = err;
1848109324cfSFilipe Manana 		}
1849109324cfSFilipe Manana 	}
1850109324cfSFilipe Manana 
1851109324cfSFilipe Manana 	return ret;
1852109324cfSFilipe Manana }
1853109324cfSFilipe Manana 
1854c8c42864SChris Mason /*
18554271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
18564271eceaSNikolay Borisov  * modifications to preserve tree invariants.
185774123bd7SChris Mason  *
18584271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
18594271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
18604271eceaSNikolay Borisov  * @root:	The root node of the tree
18614271eceaSNikolay Borisov  * @key:	The key we are looking for
18629a664971Sethanwu  * @ins_len:	Indicates purpose of search:
18639a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
18649a664971Sethanwu  *              <0  for deletions
18659a664971Sethanwu  *               0  for plain searches, not modifying the tree
18669a664971Sethanwu  *
18679a664971Sethanwu  *              (*) If size of item inserted doesn't include
18689a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
18699a664971Sethanwu  *              be set.
18704271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
18714271eceaSNikolay Borisov  *		when modifying the tree.
187297571fd0SChris Mason  *
18734271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
18744271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
18754271eceaSNikolay Borisov  *
18764271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
18774271eceaSNikolay Borisov  * of the path (level 0)
18784271eceaSNikolay Borisov  *
18794271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
18804271eceaSNikolay Borisov  * points to the slot where it should be inserted
18814271eceaSNikolay Borisov  *
18824271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
18834271eceaSNikolay Borisov  * is returned
188474123bd7SChris Mason  */
1885310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1886310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
1887310712b2SOmar Sandoval 		      int ins_len, int cow)
1888be0e5c09SChris Mason {
1889d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
18905f39d397SChris Mason 	struct extent_buffer *b;
1891be0e5c09SChris Mason 	int slot;
1892be0e5c09SChris Mason 	int ret;
189333c66f43SYan Zheng 	int err;
1894be0e5c09SChris Mason 	int level;
1895925baeddSChris Mason 	int lowest_unlock = 1;
1896bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
1897bd681513SChris Mason 	int write_lock_level = 0;
18989f3a7427SChris Mason 	u8 lowest_level = 0;
1899f7c79f30SChris Mason 	int min_write_lock_level;
1900d7396f07SFilipe David Borba Manana 	int prev_cmp;
19019f3a7427SChris Mason 
19026702ed49SChris Mason 	lowest_level = p->lowest_level;
1903323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
190422b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
1905eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
190625179201SJosef Bacik 
1907bd681513SChris Mason 	if (ins_len < 0) {
1908925baeddSChris Mason 		lowest_unlock = 2;
190965b51a00SChris Mason 
1910bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
1911bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
1912bd681513SChris Mason 		 * for those levels as well
1913bd681513SChris Mason 		 */
1914bd681513SChris Mason 		write_lock_level = 2;
1915bd681513SChris Mason 	} else if (ins_len > 0) {
1916bd681513SChris Mason 		/*
1917bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
1918bd681513SChris Mason 		 * level 1 so we can update keys
1919bd681513SChris Mason 		 */
1920bd681513SChris Mason 		write_lock_level = 1;
1921bd681513SChris Mason 	}
1922bd681513SChris Mason 
1923bd681513SChris Mason 	if (!cow)
1924bd681513SChris Mason 		write_lock_level = -1;
1925bd681513SChris Mason 
192609a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
1927bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
1928bd681513SChris Mason 
1929f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
1930f7c79f30SChris Mason 
1931d96b3424SFilipe Manana 	if (p->need_commit_sem) {
1932d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
1933d96b3424SFilipe Manana 		down_read(&fs_info->commit_root_sem);
1934d96b3424SFilipe Manana 	}
1935d96b3424SFilipe Manana 
1936bb803951SChris Mason again:
1937d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
19381fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
1939be6821f8SFilipe Manana 	if (IS_ERR(b)) {
1940be6821f8SFilipe Manana 		ret = PTR_ERR(b);
1941be6821f8SFilipe Manana 		goto done;
1942be6821f8SFilipe Manana 	}
1943925baeddSChris Mason 
1944eb60ceacSChris Mason 	while (b) {
1945f624d976SQu Wenruo 		int dec = 0;
1946f624d976SQu Wenruo 
19475f39d397SChris Mason 		level = btrfs_header_level(b);
194865b51a00SChris Mason 
194902217ed2SChris Mason 		if (cow) {
19509ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
19519ea2c7c9SNikolay Borisov 
1952c8c42864SChris Mason 			/*
1953c8c42864SChris Mason 			 * if we don't really need to cow this block
1954c8c42864SChris Mason 			 * then we don't want to set the path blocking,
1955c8c42864SChris Mason 			 * so we test it here
1956c8c42864SChris Mason 			 */
19575963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
195865b51a00SChris Mason 				goto cow_done;
19595d4f98a2SYan Zheng 
1960bd681513SChris Mason 			/*
1961bd681513SChris Mason 			 * must have write locks on this node and the
1962bd681513SChris Mason 			 * parent
1963bd681513SChris Mason 			 */
19645124e00eSJosef Bacik 			if (level > write_lock_level ||
19655124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
19665124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
19675124e00eSJosef Bacik 			    p->nodes[level + 1])) {
1968bd681513SChris Mason 				write_lock_level = level + 1;
1969bd681513SChris Mason 				btrfs_release_path(p);
1970bd681513SChris Mason 				goto again;
1971bd681513SChris Mason 			}
1972bd681513SChris Mason 
19739ea2c7c9SNikolay Borisov 			if (last_level)
19749ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
19759631e4ccSJosef Bacik 						      &b,
19769631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
19779ea2c7c9SNikolay Borisov 			else
197833c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
1979e20d96d6SChris Mason 						      p->nodes[level + 1],
19809631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
19819631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
198233c66f43SYan Zheng 			if (err) {
198333c66f43SYan Zheng 				ret = err;
198465b51a00SChris Mason 				goto done;
198554aa1f4dSChris Mason 			}
198602217ed2SChris Mason 		}
198765b51a00SChris Mason cow_done:
1988eb60ceacSChris Mason 		p->nodes[level] = b;
1989b4ce94deSChris Mason 
1990b4ce94deSChris Mason 		/*
1991b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
1992b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
1993b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
1994b4ce94deSChris Mason 		 * go through the expensive btree search on b.
1995b4ce94deSChris Mason 		 *
1996eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
1997eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
1998eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
1999eb653de1SFilipe David Borba Manana 		 * we're operating on.
2000b4ce94deSChris Mason 		 */
2001eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2002eb653de1SFilipe David Borba Manana 			int u = level + 1;
2003eb653de1SFilipe David Borba Manana 
2004eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2005eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2006eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2007eb653de1SFilipe David Borba Manana 			}
2008eb653de1SFilipe David Borba Manana 		}
2009b4ce94deSChris Mason 
2010e2e58d0fSFilipe Manana 		if (level == 0) {
2011109324cfSFilipe Manana 			if (ins_len > 0)
2012e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
2013bd681513SChris Mason 
2014109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2015459931ecSChris Mason 			if (!p->search_for_split)
2016f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
20174b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
201865b51a00SChris Mason 			goto done;
201965b51a00SChris Mason 		}
2020e2e58d0fSFilipe Manana 
2021e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2022e2e58d0fSFilipe Manana 		if (ret < 0)
2023e2e58d0fSFilipe Manana 			goto done;
2024e2e58d0fSFilipe Manana 		prev_cmp = ret;
2025e2e58d0fSFilipe Manana 
2026f624d976SQu Wenruo 		if (ret && slot > 0) {
2027f624d976SQu Wenruo 			dec = 1;
2028f624d976SQu Wenruo 			slot--;
2029f624d976SQu Wenruo 		}
2030f624d976SQu Wenruo 		p->slots[level] = slot;
2031f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2032f624d976SQu Wenruo 					     &write_lock_level);
2033f624d976SQu Wenruo 		if (err == -EAGAIN)
2034f624d976SQu Wenruo 			goto again;
2035f624d976SQu Wenruo 		if (err) {
2036f624d976SQu Wenruo 			ret = err;
2037f624d976SQu Wenruo 			goto done;
2038f624d976SQu Wenruo 		}
2039f624d976SQu Wenruo 		b = p->nodes[level];
2040f624d976SQu Wenruo 		slot = p->slots[level];
2041f624d976SQu Wenruo 
2042f624d976SQu Wenruo 		/*
2043f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2044f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2045f624d976SQu Wenruo 		 * the parent
2046f624d976SQu Wenruo 		 */
2047f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2048f624d976SQu Wenruo 			write_lock_level = level + 1;
2049f624d976SQu Wenruo 			btrfs_release_path(p);
2050f624d976SQu Wenruo 			goto again;
2051f624d976SQu Wenruo 		}
2052f624d976SQu Wenruo 
2053f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2054f624d976SQu Wenruo 			  &write_lock_level);
2055f624d976SQu Wenruo 
2056f624d976SQu Wenruo 		if (level == lowest_level) {
2057f624d976SQu Wenruo 			if (dec)
2058f624d976SQu Wenruo 				p->slots[level]++;
2059f624d976SQu Wenruo 			goto done;
2060f624d976SQu Wenruo 		}
2061f624d976SQu Wenruo 
2062f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2063f624d976SQu Wenruo 		if (err == -EAGAIN)
2064f624d976SQu Wenruo 			goto again;
2065f624d976SQu Wenruo 		if (err) {
2066f624d976SQu Wenruo 			ret = err;
2067f624d976SQu Wenruo 			goto done;
2068f624d976SQu Wenruo 		}
2069f624d976SQu Wenruo 
2070f624d976SQu Wenruo 		if (!p->skip_locking) {
2071f624d976SQu Wenruo 			level = btrfs_header_level(b);
2072f624d976SQu Wenruo 			if (level <= write_lock_level) {
2073f624d976SQu Wenruo 				btrfs_tree_lock(b);
2074f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2075f624d976SQu Wenruo 			} else {
2076fe596ca3SJosef Bacik 				btrfs_tree_read_lock(b);
2077f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2078f624d976SQu Wenruo 			}
2079f624d976SQu Wenruo 			p->nodes[level] = b;
2080f624d976SQu Wenruo 		}
208165b51a00SChris Mason 	}
208265b51a00SChris Mason 	ret = 1;
208365b51a00SChris Mason done:
20845f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2085b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2086d96b3424SFilipe Manana 
2087d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2088d96b3424SFilipe Manana 		int ret2;
2089d96b3424SFilipe Manana 
2090d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2091d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2092d96b3424SFilipe Manana 		if (ret2)
2093d96b3424SFilipe Manana 			ret = ret2;
2094d96b3424SFilipe Manana 	}
2095d96b3424SFilipe Manana 
2096be0e5c09SChris Mason 	return ret;
2097be0e5c09SChris Mason }
2098f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2099be0e5c09SChris Mason 
210074123bd7SChris Mason /*
21015d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
21025d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
21035d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
21045d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
21055d9e75c4SJan Schmidt  *
21065d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
21075d9e75c4SJan Schmidt  *
21085d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
21095d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
21105d9e75c4SJan Schmidt  */
2111310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
21125d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
21135d9e75c4SJan Schmidt {
21140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
21155d9e75c4SJan Schmidt 	struct extent_buffer *b;
21165d9e75c4SJan Schmidt 	int slot;
21175d9e75c4SJan Schmidt 	int ret;
21185d9e75c4SJan Schmidt 	int err;
21195d9e75c4SJan Schmidt 	int level;
21205d9e75c4SJan Schmidt 	int lowest_unlock = 1;
21215d9e75c4SJan Schmidt 	u8 lowest_level = 0;
21225d9e75c4SJan Schmidt 
21235d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
21245d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
21255d9e75c4SJan Schmidt 
21265d9e75c4SJan Schmidt 	if (p->search_commit_root) {
21275d9e75c4SJan Schmidt 		BUG_ON(time_seq);
21285d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
21295d9e75c4SJan Schmidt 	}
21305d9e75c4SJan Schmidt 
21315d9e75c4SJan Schmidt again:
2132f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2133315bed43SNikolay Borisov 	if (!b) {
2134315bed43SNikolay Borisov 		ret = -EIO;
2135315bed43SNikolay Borisov 		goto done;
2136315bed43SNikolay Borisov 	}
21375d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
21385d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
21395d9e75c4SJan Schmidt 
21405d9e75c4SJan Schmidt 	while (b) {
2141abe9339dSQu Wenruo 		int dec = 0;
2142abe9339dSQu Wenruo 
21435d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
21445d9e75c4SJan Schmidt 		p->nodes[level] = b;
21455d9e75c4SJan Schmidt 
21465d9e75c4SJan Schmidt 		/*
21475d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
21485d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
21495d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
21505d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
21515d9e75c4SJan Schmidt 		 */
21525d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
21535d9e75c4SJan Schmidt 
2154995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
2155cbca7d59SFilipe Manana 		if (ret < 0)
2156cbca7d59SFilipe Manana 			goto done;
21575d9e75c4SJan Schmidt 
2158abe9339dSQu Wenruo 		if (level == 0) {
2159abe9339dSQu Wenruo 			p->slots[level] = slot;
2160abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2161abe9339dSQu Wenruo 			goto done;
2162abe9339dSQu Wenruo 		}
2163abe9339dSQu Wenruo 
21645d9e75c4SJan Schmidt 		if (ret && slot > 0) {
21655d9e75c4SJan Schmidt 			dec = 1;
2166abe9339dSQu Wenruo 			slot--;
21675d9e75c4SJan Schmidt 		}
21685d9e75c4SJan Schmidt 		p->slots[level] = slot;
21695d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
21705d9e75c4SJan Schmidt 
21715d9e75c4SJan Schmidt 		if (level == lowest_level) {
21725d9e75c4SJan Schmidt 			if (dec)
21735d9e75c4SJan Schmidt 				p->slots[level]++;
21745d9e75c4SJan Schmidt 			goto done;
21755d9e75c4SJan Schmidt 		}
21765d9e75c4SJan Schmidt 
2177abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
21785d9e75c4SJan Schmidt 		if (err == -EAGAIN)
21795d9e75c4SJan Schmidt 			goto again;
21805d9e75c4SJan Schmidt 		if (err) {
21815d9e75c4SJan Schmidt 			ret = err;
21825d9e75c4SJan Schmidt 			goto done;
21835d9e75c4SJan Schmidt 		}
21845d9e75c4SJan Schmidt 
21855d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
21865d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2187f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2188db7f3436SJosef Bacik 		if (!b) {
2189db7f3436SJosef Bacik 			ret = -ENOMEM;
2190db7f3436SJosef Bacik 			goto done;
2191db7f3436SJosef Bacik 		}
21925d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
21935d9e75c4SJan Schmidt 		p->nodes[level] = b;
21945d9e75c4SJan Schmidt 	}
21955d9e75c4SJan Schmidt 	ret = 1;
21965d9e75c4SJan Schmidt done:
21975d9e75c4SJan Schmidt 	if (ret < 0)
21985d9e75c4SJan Schmidt 		btrfs_release_path(p);
21995d9e75c4SJan Schmidt 
22005d9e75c4SJan Schmidt 	return ret;
22015d9e75c4SJan Schmidt }
22025d9e75c4SJan Schmidt 
22035d9e75c4SJan Schmidt /*
22042f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
22052f38b3e1SArne Jansen  * instead the next or previous item should be returned.
22062f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
22072f38b3e1SArne Jansen  * otherwise.
22082f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
22092f38b3e1SArne Jansen  * return the next lower instead.
22102f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
22112f38b3e1SArne Jansen  * return the next higher instead.
22122f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
22132f38b3e1SArne Jansen  * < 0 on error
22142f38b3e1SArne Jansen  */
22152f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2216310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2217310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2218310712b2SOmar Sandoval 			       int return_any)
22192f38b3e1SArne Jansen {
22202f38b3e1SArne Jansen 	int ret;
22212f38b3e1SArne Jansen 	struct extent_buffer *leaf;
22222f38b3e1SArne Jansen 
22232f38b3e1SArne Jansen again:
22242f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
22252f38b3e1SArne Jansen 	if (ret <= 0)
22262f38b3e1SArne Jansen 		return ret;
22272f38b3e1SArne Jansen 	/*
22282f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
22292f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
22302f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
22312f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
22322f38b3e1SArne Jansen 	 * item.
22332f38b3e1SArne Jansen 	 */
22342f38b3e1SArne Jansen 	leaf = p->nodes[0];
22352f38b3e1SArne Jansen 
22362f38b3e1SArne Jansen 	if (find_higher) {
22372f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
22382f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
22392f38b3e1SArne Jansen 			if (ret <= 0)
22402f38b3e1SArne Jansen 				return ret;
22412f38b3e1SArne Jansen 			if (!return_any)
22422f38b3e1SArne Jansen 				return 1;
22432f38b3e1SArne Jansen 			/*
22442f38b3e1SArne Jansen 			 * no higher item found, return the next
22452f38b3e1SArne Jansen 			 * lower instead
22462f38b3e1SArne Jansen 			 */
22472f38b3e1SArne Jansen 			return_any = 0;
22482f38b3e1SArne Jansen 			find_higher = 0;
22492f38b3e1SArne Jansen 			btrfs_release_path(p);
22502f38b3e1SArne Jansen 			goto again;
22512f38b3e1SArne Jansen 		}
22522f38b3e1SArne Jansen 	} else {
22532f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
22542f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2255e6793769SArne Jansen 			if (ret < 0)
22562f38b3e1SArne Jansen 				return ret;
2257e6793769SArne Jansen 			if (!ret) {
225823c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
225923c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
226023c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2261e6793769SArne Jansen 				return 0;
2262e6793769SArne Jansen 			}
22632f38b3e1SArne Jansen 			if (!return_any)
22642f38b3e1SArne Jansen 				return 1;
22652f38b3e1SArne Jansen 			/*
22662f38b3e1SArne Jansen 			 * no lower item found, return the next
22672f38b3e1SArne Jansen 			 * higher instead
22682f38b3e1SArne Jansen 			 */
22692f38b3e1SArne Jansen 			return_any = 0;
22702f38b3e1SArne Jansen 			find_higher = 1;
22712f38b3e1SArne Jansen 			btrfs_release_path(p);
22722f38b3e1SArne Jansen 			goto again;
2273e6793769SArne Jansen 		} else {
22742f38b3e1SArne Jansen 			--p->slots[0];
22752f38b3e1SArne Jansen 		}
22762f38b3e1SArne Jansen 	}
22772f38b3e1SArne Jansen 	return 0;
22782f38b3e1SArne Jansen }
22792f38b3e1SArne Jansen 
22802f38b3e1SArne Jansen /*
22810ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
22820ff40a91SMarcos Paulo de Souza  * was not found.
22830ff40a91SMarcos Paulo de Souza  *
22840ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
22850ff40a91SMarcos Paulo de Souza  */
22860ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
22870ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
22880ff40a91SMarcos Paulo de Souza {
22890ff40a91SMarcos Paulo de Souza 	int ret;
22900ff40a91SMarcos Paulo de Souza 
22910ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
22920ff40a91SMarcos Paulo de Souza 	if (ret > 0)
22930ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
22940ff40a91SMarcos Paulo de Souza 
22950ff40a91SMarcos Paulo de Souza 	if (ret == 0)
22960ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
22970ff40a91SMarcos Paulo de Souza 
22980ff40a91SMarcos Paulo de Souza 	return ret;
22990ff40a91SMarcos Paulo de Souza }
23000ff40a91SMarcos Paulo de Souza 
23010ff40a91SMarcos Paulo de Souza /*
230274123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
230374123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
230474123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
230574123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
230674123bd7SChris Mason  * higher levels
2307aa5d6bedSChris Mason  *
230874123bd7SChris Mason  */
2309b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
23105f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2311be0e5c09SChris Mason {
2312be0e5c09SChris Mason 	int i;
23135f39d397SChris Mason 	struct extent_buffer *t;
23140e82bcfeSDavid Sterba 	int ret;
23155f39d397SChris Mason 
2316234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2317be0e5c09SChris Mason 		int tslot = path->slots[i];
23180e82bcfeSDavid Sterba 
2319eb60ceacSChris Mason 		if (!path->nodes[i])
2320be0e5c09SChris Mason 			break;
23215f39d397SChris Mason 		t = path->nodes[i];
2322f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
2323f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REPLACE, GFP_ATOMIC);
23240e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
23255f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2326d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2327be0e5c09SChris Mason 		if (tslot != 0)
2328be0e5c09SChris Mason 			break;
2329be0e5c09SChris Mason 	}
2330be0e5c09SChris Mason }
2331be0e5c09SChris Mason 
233274123bd7SChris Mason /*
233331840ae1SZheng Yan  * update item key.
233431840ae1SZheng Yan  *
233531840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
233631840ae1SZheng Yan  * that the new key won't break the order
233731840ae1SZheng Yan  */
2338b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2339b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2340310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
234131840ae1SZheng Yan {
234231840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
234331840ae1SZheng Yan 	struct extent_buffer *eb;
234431840ae1SZheng Yan 	int slot;
234531840ae1SZheng Yan 
234631840ae1SZheng Yan 	eb = path->nodes[0];
234731840ae1SZheng Yan 	slot = path->slots[0];
234831840ae1SZheng Yan 	if (slot > 0) {
234931840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
23507c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
23517c15d410SQu Wenruo 			btrfs_crit(fs_info,
23527c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
23537c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
23547c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
23557c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
23567c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
23577c15d410SQu Wenruo 				   new_key->offset);
23587c15d410SQu Wenruo 			btrfs_print_leaf(eb);
23597c15d410SQu Wenruo 			BUG();
23607c15d410SQu Wenruo 		}
236131840ae1SZheng Yan 	}
236231840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
236331840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
23647c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
23657c15d410SQu Wenruo 			btrfs_crit(fs_info,
23667c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
23677c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
23687c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
23697c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
23707c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
23717c15d410SQu Wenruo 				   new_key->offset);
23727c15d410SQu Wenruo 			btrfs_print_leaf(eb);
23737c15d410SQu Wenruo 			BUG();
23747c15d410SQu Wenruo 		}
237531840ae1SZheng Yan 	}
237631840ae1SZheng Yan 
237731840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
237831840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
237931840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
238031840ae1SZheng Yan 	if (slot == 0)
2381b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
238231840ae1SZheng Yan }
238331840ae1SZheng Yan 
238431840ae1SZheng Yan /*
2385d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2386d16c702fSQu Wenruo  *
2387d16c702fSQu Wenruo  * Return true if something is wrong.
2388d16c702fSQu Wenruo  * Return false if everything is fine.
2389d16c702fSQu Wenruo  *
2390d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2391d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2392d16c702fSQu Wenruo  *
2393d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2394d16c702fSQu Wenruo  * --------------------------------------------------------------
2395d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2396d16c702fSQu Wenruo  *
2397d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2398d16c702fSQu Wenruo  * key in leaf @right is 7.
2399d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2400d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2401d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2402d16c702fSQu Wenruo  * key of @right.
2403d16c702fSQu Wenruo  */
2404d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2405d16c702fSQu Wenruo 			       struct extent_buffer *right)
2406d16c702fSQu Wenruo {
2407d16c702fSQu Wenruo 	struct btrfs_key left_last;
2408d16c702fSQu Wenruo 	struct btrfs_key right_first;
2409d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2410d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2411d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2412d16c702fSQu Wenruo 
2413d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2414d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2415d16c702fSQu Wenruo 		return false;
2416d16c702fSQu Wenruo 
2417d16c702fSQu Wenruo 	if (level) {
2418d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2419d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2420d16c702fSQu Wenruo 	} else {
2421d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2422d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2423d16c702fSQu Wenruo 	}
2424d16c702fSQu Wenruo 
2425d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2426d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2427d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2428d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2429d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2430d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2431d16c702fSQu Wenruo 		return true;
2432d16c702fSQu Wenruo 	}
2433d16c702fSQu Wenruo 	return false;
2434d16c702fSQu Wenruo }
2435d16c702fSQu Wenruo 
2436d16c702fSQu Wenruo /*
243774123bd7SChris Mason  * try to push data from one node into the next node left in the
243879f95c82SChris Mason  * tree.
2439aa5d6bedSChris Mason  *
2440aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2441aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
244274123bd7SChris Mason  */
244398ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
24442ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2445971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2446be0e5c09SChris Mason {
2447d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2448be0e5c09SChris Mason 	int push_items = 0;
2449bb803951SChris Mason 	int src_nritems;
2450bb803951SChris Mason 	int dst_nritems;
2451aa5d6bedSChris Mason 	int ret = 0;
2452be0e5c09SChris Mason 
24535f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
24545f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
24550b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
24567bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
24577bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
245854aa1f4dSChris Mason 
2459bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2460971a1f66SChris Mason 		return 1;
2461971a1f66SChris Mason 
2462d397712bSChris Mason 	if (push_items <= 0)
2463be0e5c09SChris Mason 		return 1;
2464be0e5c09SChris Mason 
2465bce4eae9SChris Mason 	if (empty) {
2466971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2467bce4eae9SChris Mason 		if (push_items < src_nritems) {
2468bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2469bce4eae9SChris Mason 			 * we aren't going to empty it
2470bce4eae9SChris Mason 			 */
2471bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2472bce4eae9SChris Mason 				if (push_items <= 8)
2473bce4eae9SChris Mason 					return 1;
2474bce4eae9SChris Mason 				push_items -= 8;
2475bce4eae9SChris Mason 			}
2476bce4eae9SChris Mason 		}
2477bce4eae9SChris Mason 	} else
2478bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
247979f95c82SChris Mason 
2480d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2481d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2482d16c702fSQu Wenruo 		ret = -EUCLEAN;
2483d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2484d16c702fSQu Wenruo 		return ret;
2485d16c702fSQu Wenruo 	}
2486f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
24875de865eeSFilipe David Borba Manana 	if (ret) {
248866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
24895de865eeSFilipe David Borba Manana 		return ret;
24905de865eeSFilipe David Borba Manana 	}
24915f39d397SChris Mason 	copy_extent_buffer(dst, src,
24925f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
24935f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2494123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
24955f39d397SChris Mason 
2496bb803951SChris Mason 	if (push_items < src_nritems) {
249757911b8bSJan Schmidt 		/*
2498f3a84ccdSFilipe Manana 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2499f3a84ccdSFilipe Manana 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
250057911b8bSJan Schmidt 		 */
25015f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
25025f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2503e2fa7227SChris Mason 				      (src_nritems - push_items) *
2504123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2505bb803951SChris Mason 	}
25065f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
25075f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
25085f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
25095f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
251031840ae1SZheng Yan 
2511bb803951SChris Mason 	return ret;
2512be0e5c09SChris Mason }
2513be0e5c09SChris Mason 
251497571fd0SChris Mason /*
251579f95c82SChris Mason  * try to push data from one node into the next node right in the
251679f95c82SChris Mason  * tree.
251779f95c82SChris Mason  *
251879f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
251979f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
252079f95c82SChris Mason  *
252179f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
252279f95c82SChris Mason  */
25235f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
25245f39d397SChris Mason 			      struct extent_buffer *dst,
25255f39d397SChris Mason 			      struct extent_buffer *src)
252679f95c82SChris Mason {
252755d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
252879f95c82SChris Mason 	int push_items = 0;
252979f95c82SChris Mason 	int max_push;
253079f95c82SChris Mason 	int src_nritems;
253179f95c82SChris Mason 	int dst_nritems;
253279f95c82SChris Mason 	int ret = 0;
253379f95c82SChris Mason 
25347bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
25357bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
25367bb86316SChris Mason 
25375f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
25385f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
25390b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2540d397712bSChris Mason 	if (push_items <= 0)
254179f95c82SChris Mason 		return 1;
2542bce4eae9SChris Mason 
2543d397712bSChris Mason 	if (src_nritems < 4)
2544bce4eae9SChris Mason 		return 1;
254579f95c82SChris Mason 
254679f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
254779f95c82SChris Mason 	/* don't try to empty the node */
2548d397712bSChris Mason 	if (max_push >= src_nritems)
254979f95c82SChris Mason 		return 1;
2550252c38f0SYan 
255179f95c82SChris Mason 	if (max_push < push_items)
255279f95c82SChris Mason 		push_items = max_push;
255379f95c82SChris Mason 
2554d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2555d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2556d16c702fSQu Wenruo 		ret = -EUCLEAN;
2557d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2558d16c702fSQu Wenruo 		return ret;
2559d16c702fSQu Wenruo 	}
2560f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2561bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
25625f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
25635f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
25645f39d397SChris Mason 				      (dst_nritems) *
25655f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2566d6025579SChris Mason 
2567f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2568ed874f0dSDavid Sterba 					 push_items);
25695de865eeSFilipe David Borba Manana 	if (ret) {
257066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
25715de865eeSFilipe David Borba Manana 		return ret;
25725de865eeSFilipe David Borba Manana 	}
25735f39d397SChris Mason 	copy_extent_buffer(dst, src,
25745f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
25755f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2576123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
257779f95c82SChris Mason 
25785f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
25795f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
258079f95c82SChris Mason 
25815f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
25825f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
258331840ae1SZheng Yan 
258479f95c82SChris Mason 	return ret;
258579f95c82SChris Mason }
258679f95c82SChris Mason 
258779f95c82SChris Mason /*
258897571fd0SChris Mason  * helper function to insert a new root level in the tree.
258997571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
259097571fd0SChris Mason  * point to the existing root
2591aa5d6bedSChris Mason  *
2592aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
259397571fd0SChris Mason  */
2594d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
25955f39d397SChris Mason 			   struct btrfs_root *root,
2596fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
259774123bd7SChris Mason {
25980b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
25997bb86316SChris Mason 	u64 lower_gen;
26005f39d397SChris Mason 	struct extent_buffer *lower;
26015f39d397SChris Mason 	struct extent_buffer *c;
2602925baeddSChris Mason 	struct extent_buffer *old;
26035f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2604d9d19a01SDavid Sterba 	int ret;
26055c680ed6SChris Mason 
26065c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
26075c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
26085c680ed6SChris Mason 
26097bb86316SChris Mason 	lower = path->nodes[level-1];
26107bb86316SChris Mason 	if (level == 1)
26117bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
26127bb86316SChris Mason 	else
26137bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
26147bb86316SChris Mason 
261579bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
261679bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2617cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
26185f39d397SChris Mason 	if (IS_ERR(c))
26195f39d397SChris Mason 		return PTR_ERR(c);
2620925baeddSChris Mason 
26210b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2622f0486c68SYan, Zheng 
26235f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
26245f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2625db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
26267bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
262731840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
26287bb86316SChris Mason 
26297bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
26305f39d397SChris Mason 
26315f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2632d5719762SChris Mason 
2633925baeddSChris Mason 	old = root->node;
2634406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2635d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2636240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2637925baeddSChris Mason 
2638925baeddSChris Mason 	/* the super has an extra ref to root->node */
2639925baeddSChris Mason 	free_extent_buffer(old);
2640925baeddSChris Mason 
26410b86a832SChris Mason 	add_root_to_dirty_list(root);
264267439dadSDavid Sterba 	atomic_inc(&c->refs);
26435f39d397SChris Mason 	path->nodes[level] = c;
2644ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
264574123bd7SChris Mason 	path->slots[level] = 0;
264674123bd7SChris Mason 	return 0;
264774123bd7SChris Mason }
26485c680ed6SChris Mason 
26495c680ed6SChris Mason /*
26505c680ed6SChris Mason  * worker function to insert a single pointer in a node.
26515c680ed6SChris Mason  * the node should have enough room for the pointer already
265297571fd0SChris Mason  *
26535c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
26545c680ed6SChris Mason  * blocknr is the block the key points to.
26555c680ed6SChris Mason  */
2656143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
26576ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2658143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2659c3e06965SJan Schmidt 		       int slot, int level)
26605c680ed6SChris Mason {
26615f39d397SChris Mason 	struct extent_buffer *lower;
26625c680ed6SChris Mason 	int nritems;
2663f3ea38daSJan Schmidt 	int ret;
26645c680ed6SChris Mason 
26655c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
266649d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
26675f39d397SChris Mason 	lower = path->nodes[level];
26685f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2669c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
26706ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
267174123bd7SChris Mason 	if (slot != nritems) {
2672bf1d3425SDavid Sterba 		if (level) {
2673f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2674f3a84ccdSFilipe Manana 					slot, nritems - slot);
2675bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2676bf1d3425SDavid Sterba 		}
26775f39d397SChris Mason 		memmove_extent_buffer(lower,
26785f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
26795f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
2680123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
268174123bd7SChris Mason 	}
2682c3e06965SJan Schmidt 	if (level) {
2683f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
2684f3a84ccdSFilipe Manana 					    BTRFS_MOD_LOG_KEY_ADD, GFP_NOFS);
2685f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2686f3ea38daSJan Schmidt 	}
26875f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2688db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
268974493f7aSChris Mason 	WARN_ON(trans->transid == 0);
269074493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
26915f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
26925f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
269374123bd7SChris Mason }
269474123bd7SChris Mason 
269597571fd0SChris Mason /*
269697571fd0SChris Mason  * split the node at the specified level in path in two.
269797571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
269897571fd0SChris Mason  *
269997571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
270097571fd0SChris Mason  * left and right, if either one works, it returns right away.
2701aa5d6bedSChris Mason  *
2702aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
270397571fd0SChris Mason  */
2704e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
2705e02119d5SChris Mason 			       struct btrfs_root *root,
2706e02119d5SChris Mason 			       struct btrfs_path *path, int level)
2707be0e5c09SChris Mason {
27080b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
27095f39d397SChris Mason 	struct extent_buffer *c;
27105f39d397SChris Mason 	struct extent_buffer *split;
27115f39d397SChris Mason 	struct btrfs_disk_key disk_key;
2712be0e5c09SChris Mason 	int mid;
27135c680ed6SChris Mason 	int ret;
27147518a238SChris Mason 	u32 c_nritems;
2715be0e5c09SChris Mason 
27165f39d397SChris Mason 	c = path->nodes[level];
27177bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
27185f39d397SChris Mason 	if (c == root->node) {
2719d9abbf1cSJan Schmidt 		/*
272090f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
272190f8d62eSJan Schmidt 		 *
2722fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
272390f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
272490f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
2725f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2726f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
2727f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
2728d9abbf1cSJan Schmidt 		 */
2729fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
27305c680ed6SChris Mason 		if (ret)
27315c680ed6SChris Mason 			return ret;
2732b3612421SChris Mason 	} else {
2733e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
27345f39d397SChris Mason 		c = path->nodes[level];
27355f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
27360b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2737e66f709bSChris Mason 			return 0;
273854aa1f4dSChris Mason 		if (ret < 0)
273954aa1f4dSChris Mason 			return ret;
27405c680ed6SChris Mason 	}
2741e66f709bSChris Mason 
27425f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
27435d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
27445d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
27457bb86316SChris Mason 
274679bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
274779bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
274879bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
27495f39d397SChris Mason 	if (IS_ERR(split))
27505f39d397SChris Mason 		return PTR_ERR(split);
275154aa1f4dSChris Mason 
27520b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2753bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
27545f39d397SChris Mason 
2755f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
27565de865eeSFilipe David Borba Manana 	if (ret) {
275766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
27585de865eeSFilipe David Borba Manana 		return ret;
27595de865eeSFilipe David Borba Manana 	}
27605f39d397SChris Mason 	copy_extent_buffer(split, c,
27615f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
27625f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
2763123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
27645f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
27655f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
2766aa5d6bedSChris Mason 
27675f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
27685f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
27695f39d397SChris Mason 
27706ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
2771c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
2772aa5d6bedSChris Mason 
27735de08d7dSChris Mason 	if (path->slots[level] >= mid) {
27745c680ed6SChris Mason 		path->slots[level] -= mid;
2775925baeddSChris Mason 		btrfs_tree_unlock(c);
27765f39d397SChris Mason 		free_extent_buffer(c);
27775f39d397SChris Mason 		path->nodes[level] = split;
27785c680ed6SChris Mason 		path->slots[level + 1] += 1;
2779eb60ceacSChris Mason 	} else {
2780925baeddSChris Mason 		btrfs_tree_unlock(split);
27815f39d397SChris Mason 		free_extent_buffer(split);
2782be0e5c09SChris Mason 	}
2783d5286a92SNikolay Borisov 	return 0;
2784be0e5c09SChris Mason }
2785be0e5c09SChris Mason 
278674123bd7SChris Mason /*
278774123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
278874123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
278974123bd7SChris Mason  * space used both by the item structs and the item data
279074123bd7SChris Mason  */
27915f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2792be0e5c09SChris Mason {
2793be0e5c09SChris Mason 	int data_len;
27945f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
2795d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
2796be0e5c09SChris Mason 
2797be0e5c09SChris Mason 	if (!nr)
2798be0e5c09SChris Mason 		return 0;
27993212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
28003212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
28010783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
2802d4dbff95SChris Mason 	WARN_ON(data_len < 0);
2803be0e5c09SChris Mason 	return data_len;
2804be0e5c09SChris Mason }
2805be0e5c09SChris Mason 
280674123bd7SChris Mason /*
2807d4dbff95SChris Mason  * The space between the end of the leaf items and
2808d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
2809d4dbff95SChris Mason  * the leaf has left for both items and data
2810d4dbff95SChris Mason  */
2811e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
2812d4dbff95SChris Mason {
2813e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
28145f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
28155f39d397SChris Mason 	int ret;
28160b246afaSJeff Mahoney 
28170b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
28185f39d397SChris Mason 	if (ret < 0) {
28190b246afaSJeff Mahoney 		btrfs_crit(fs_info,
2820efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2821da17066cSJeff Mahoney 			   ret,
28220b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
28235f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
28245f39d397SChris Mason 	}
28255f39d397SChris Mason 	return ret;
2826d4dbff95SChris Mason }
2827d4dbff95SChris Mason 
282899d8f83cSChris Mason /*
282999d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
283099d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
283199d8f83cSChris Mason  */
2832f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
283344871b1bSChris Mason 				      int data_size, int empty,
283444871b1bSChris Mason 				      struct extent_buffer *right,
283599d8f83cSChris Mason 				      int free_space, u32 left_nritems,
283699d8f83cSChris Mason 				      u32 min_slot)
283700ec4c51SChris Mason {
2838f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
28395f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
284044871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
2841cfed81a0SChris Mason 	struct btrfs_map_token token;
28425f39d397SChris Mason 	struct btrfs_disk_key disk_key;
284300ec4c51SChris Mason 	int slot;
284434a38218SChris Mason 	u32 i;
284500ec4c51SChris Mason 	int push_space = 0;
284600ec4c51SChris Mason 	int push_items = 0;
284734a38218SChris Mason 	u32 nr;
28487518a238SChris Mason 	u32 right_nritems;
28495f39d397SChris Mason 	u32 data_end;
2850db94535dSChris Mason 	u32 this_item_size;
285100ec4c51SChris Mason 
285234a38218SChris Mason 	if (empty)
285334a38218SChris Mason 		nr = 0;
285434a38218SChris Mason 	else
285599d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
285634a38218SChris Mason 
285731840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
285887b29b20SYan Zheng 		push_space += data_size;
285931840ae1SZheng Yan 
286044871b1bSChris Mason 	slot = path->slots[1];
286134a38218SChris Mason 	i = left_nritems - 1;
286234a38218SChris Mason 	while (i >= nr) {
286331840ae1SZheng Yan 		if (!empty && push_items > 0) {
286431840ae1SZheng Yan 			if (path->slots[0] > i)
286531840ae1SZheng Yan 				break;
286631840ae1SZheng Yan 			if (path->slots[0] == i) {
2867e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
2868e902baacSDavid Sterba 
286931840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
287031840ae1SZheng Yan 					break;
287131840ae1SZheng Yan 			}
287231840ae1SZheng Yan 		}
287331840ae1SZheng Yan 
287400ec4c51SChris Mason 		if (path->slots[0] == i)
287587b29b20SYan Zheng 			push_space += data_size;
2876db94535dSChris Mason 
28773212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
287874794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
287974794207SJosef Bacik 		    push_space > free_space)
288000ec4c51SChris Mason 			break;
288131840ae1SZheng Yan 
288200ec4c51SChris Mason 		push_items++;
288374794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
288434a38218SChris Mason 		if (i == 0)
288534a38218SChris Mason 			break;
288634a38218SChris Mason 		i--;
2887db94535dSChris Mason 	}
28885f39d397SChris Mason 
2889925baeddSChris Mason 	if (push_items == 0)
2890925baeddSChris Mason 		goto out_unlock;
28915f39d397SChris Mason 
28926c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
28935f39d397SChris Mason 
289400ec4c51SChris Mason 	/* push left to right */
28955f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
289634a38218SChris Mason 
2897dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
28988f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
28995f39d397SChris Mason 
290000ec4c51SChris Mason 	/* make room in the right data area */
29018f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
29025f39d397SChris Mason 	memmove_extent_buffer(right,
29033d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
29043d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
29050b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
29065f39d397SChris Mason 
290700ec4c51SChris Mason 	/* copy from the left data area */
29083d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
29090b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
29108f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
2911d6025579SChris Mason 		     push_space);
29125f39d397SChris Mason 
29135f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
29145f39d397SChris Mason 			      btrfs_item_nr_offset(0),
29150783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
29165f39d397SChris Mason 
291700ec4c51SChris Mason 	/* copy the items from left to right */
29185f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
29195f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
29200783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
292100ec4c51SChris Mason 
292200ec4c51SChris Mason 	/* update the item pointers */
2923c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
29247518a238SChris Mason 	right_nritems += push_items;
29255f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
29260b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
29277518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
29283212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
29293212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
2930db94535dSChris Mason 	}
2931db94535dSChris Mason 
29327518a238SChris Mason 	left_nritems -= push_items;
29335f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
293400ec4c51SChris Mason 
293534a38218SChris Mason 	if (left_nritems)
29365f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
2937f0486c68SYan, Zheng 	else
29386a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
2939f0486c68SYan, Zheng 
29405f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
2941a429e513SChris Mason 
29425f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
29435f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
2944d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
294502217ed2SChris Mason 
294600ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
29477518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
29487518a238SChris Mason 		path->slots[0] -= left_nritems;
2949925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
29506a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
2951925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
29525f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
29535f39d397SChris Mason 		path->nodes[0] = right;
295400ec4c51SChris Mason 		path->slots[1] += 1;
295500ec4c51SChris Mason 	} else {
2956925baeddSChris Mason 		btrfs_tree_unlock(right);
29575f39d397SChris Mason 		free_extent_buffer(right);
295800ec4c51SChris Mason 	}
295900ec4c51SChris Mason 	return 0;
2960925baeddSChris Mason 
2961925baeddSChris Mason out_unlock:
2962925baeddSChris Mason 	btrfs_tree_unlock(right);
2963925baeddSChris Mason 	free_extent_buffer(right);
2964925baeddSChris Mason 	return 1;
296500ec4c51SChris Mason }
2966925baeddSChris Mason 
296700ec4c51SChris Mason /*
296844871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
296974123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
297044871b1bSChris Mason  *
297144871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
297244871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
297399d8f83cSChris Mason  *
297499d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
297599d8f83cSChris Mason  * push any slot lower than min_slot
297674123bd7SChris Mason  */
297744871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
297899d8f83cSChris Mason 			   *root, struct btrfs_path *path,
297999d8f83cSChris Mason 			   int min_data_size, int data_size,
298099d8f83cSChris Mason 			   int empty, u32 min_slot)
2981be0e5c09SChris Mason {
298244871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
298344871b1bSChris Mason 	struct extent_buffer *right;
298444871b1bSChris Mason 	struct extent_buffer *upper;
298544871b1bSChris Mason 	int slot;
298644871b1bSChris Mason 	int free_space;
298744871b1bSChris Mason 	u32 left_nritems;
298844871b1bSChris Mason 	int ret;
298944871b1bSChris Mason 
299044871b1bSChris Mason 	if (!path->nodes[1])
299144871b1bSChris Mason 		return 1;
299244871b1bSChris Mason 
299344871b1bSChris Mason 	slot = path->slots[1];
299444871b1bSChris Mason 	upper = path->nodes[1];
299544871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
299644871b1bSChris Mason 		return 1;
299744871b1bSChris Mason 
299849d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
299944871b1bSChris Mason 
30004b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3001fb770ae4SLiu Bo 	/*
3002fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3003fb770ae4SLiu Bo 	 * no big deal, just return.
3004fb770ae4SLiu Bo 	 */
3005fb770ae4SLiu Bo 	if (IS_ERR(right))
300691ca338dSTsutomu Itoh 		return 1;
300791ca338dSTsutomu Itoh 
3008bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
300944871b1bSChris Mason 
3010e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
301144871b1bSChris Mason 	if (free_space < data_size)
301244871b1bSChris Mason 		goto out_unlock;
301344871b1bSChris Mason 
301444871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3015bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
301644871b1bSChris Mason 	if (ret)
301744871b1bSChris Mason 		goto out_unlock;
301844871b1bSChris Mason 
301944871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
302044871b1bSChris Mason 	if (left_nritems == 0)
302144871b1bSChris Mason 		goto out_unlock;
302244871b1bSChris Mason 
3023d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3024d16c702fSQu Wenruo 		ret = -EUCLEAN;
3025d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3026d16c702fSQu Wenruo 		free_extent_buffer(right);
3027d16c702fSQu Wenruo 		return ret;
3028d16c702fSQu Wenruo 	}
30292ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
30302ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
30312ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
30322ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
303352042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
30342ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
30352ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
30362ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
30372ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
30382ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
30392ef1fed2SFilipe David Borba Manana 		return 0;
30402ef1fed2SFilipe David Borba Manana 	}
30412ef1fed2SFilipe David Borba Manana 
3042f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
304399d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
304444871b1bSChris Mason out_unlock:
304544871b1bSChris Mason 	btrfs_tree_unlock(right);
304644871b1bSChris Mason 	free_extent_buffer(right);
304744871b1bSChris Mason 	return 1;
304844871b1bSChris Mason }
304944871b1bSChris Mason 
305044871b1bSChris Mason /*
305144871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
305244871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
305399d8f83cSChris Mason  *
305499d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
305599d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
305699d8f83cSChris Mason  * items
305744871b1bSChris Mason  */
30588087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
305944871b1bSChris Mason 				     int empty, struct extent_buffer *left,
306099d8f83cSChris Mason 				     int free_space, u32 right_nritems,
306199d8f83cSChris Mason 				     u32 max_slot)
306244871b1bSChris Mason {
30638087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
30645f39d397SChris Mason 	struct btrfs_disk_key disk_key;
30655f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3066be0e5c09SChris Mason 	int i;
3067be0e5c09SChris Mason 	int push_space = 0;
3068be0e5c09SChris Mason 	int push_items = 0;
30697518a238SChris Mason 	u32 old_left_nritems;
307034a38218SChris Mason 	u32 nr;
3071aa5d6bedSChris Mason 	int ret = 0;
3072db94535dSChris Mason 	u32 this_item_size;
3073db94535dSChris Mason 	u32 old_left_item_size;
3074cfed81a0SChris Mason 	struct btrfs_map_token token;
3075cfed81a0SChris Mason 
307634a38218SChris Mason 	if (empty)
307799d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
307834a38218SChris Mason 	else
307999d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
308034a38218SChris Mason 
308134a38218SChris Mason 	for (i = 0; i < nr; i++) {
308231840ae1SZheng Yan 		if (!empty && push_items > 0) {
308331840ae1SZheng Yan 			if (path->slots[0] < i)
308431840ae1SZheng Yan 				break;
308531840ae1SZheng Yan 			if (path->slots[0] == i) {
3086e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3087e902baacSDavid Sterba 
308831840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
308931840ae1SZheng Yan 					break;
309031840ae1SZheng Yan 			}
309131840ae1SZheng Yan 		}
309231840ae1SZheng Yan 
3093be0e5c09SChris Mason 		if (path->slots[0] == i)
309487b29b20SYan Zheng 			push_space += data_size;
3095db94535dSChris Mason 
30963212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
309774794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
309874794207SJosef Bacik 		    free_space)
3099be0e5c09SChris Mason 			break;
3100db94535dSChris Mason 
3101be0e5c09SChris Mason 		push_items++;
310274794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3103be0e5c09SChris Mason 	}
3104db94535dSChris Mason 
3105be0e5c09SChris Mason 	if (push_items == 0) {
3106925baeddSChris Mason 		ret = 1;
3107925baeddSChris Mason 		goto out;
3108be0e5c09SChris Mason 	}
3109fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
31105f39d397SChris Mason 
3111be0e5c09SChris Mason 	/* push data from right to left */
31125f39d397SChris Mason 	copy_extent_buffer(left, right,
31135f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
31145f39d397SChris Mason 			   btrfs_item_nr_offset(0),
31155f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
31165f39d397SChris Mason 
31170b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
31183212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
31195f39d397SChris Mason 
31203d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
31218f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
31223d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
31233212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1),
3124be0e5c09SChris Mason 		     push_space);
31255f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
312687b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3127eb60ceacSChris Mason 
3128c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
31293212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3130be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
31315f39d397SChris Mason 		u32 ioff;
3132db94535dSChris Mason 
31333212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
31343212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3135cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3136be0e5c09SChris Mason 	}
31375f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3138be0e5c09SChris Mason 
3139be0e5c09SChris Mason 	/* fixup right node */
314031b1a2bdSJulia Lawall 	if (push_items > right_nritems)
314131b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3142d397712bSChris Mason 		       right_nritems);
314334a38218SChris Mason 
314434a38218SChris Mason 	if (push_items < right_nritems) {
31453212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
31468f881e8cSDavid Sterba 						  leaf_data_end(right);
31473d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
31480b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
31493d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
31508f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
31515f39d397SChris Mason 
31525f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
31535f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
31545f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
31550783fcfcSChris Mason 			     sizeof(struct btrfs_item));
315634a38218SChris Mason 	}
3157c82f823cSDavid Sterba 
3158c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3159eef1c494SYan 	right_nritems -= push_items;
3160eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
31610b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
31625f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
31633212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
31643212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3165db94535dSChris Mason 	}
3166eb60ceacSChris Mason 
31675f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
316834a38218SChris Mason 	if (right_nritems)
31695f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3170f0486c68SYan, Zheng 	else
31716a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3172098f59c2SChris Mason 
31735f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3174b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3175be0e5c09SChris Mason 
3176be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3177be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3178be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3179925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
31805f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
31815f39d397SChris Mason 		path->nodes[0] = left;
3182be0e5c09SChris Mason 		path->slots[1] -= 1;
3183be0e5c09SChris Mason 	} else {
3184925baeddSChris Mason 		btrfs_tree_unlock(left);
31855f39d397SChris Mason 		free_extent_buffer(left);
3186be0e5c09SChris Mason 		path->slots[0] -= push_items;
3187be0e5c09SChris Mason 	}
3188eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3189aa5d6bedSChris Mason 	return ret;
3190925baeddSChris Mason out:
3191925baeddSChris Mason 	btrfs_tree_unlock(left);
3192925baeddSChris Mason 	free_extent_buffer(left);
3193925baeddSChris Mason 	return ret;
3194be0e5c09SChris Mason }
3195be0e5c09SChris Mason 
319674123bd7SChris Mason /*
319744871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
319844871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
319999d8f83cSChris Mason  *
320099d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
320199d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
320299d8f83cSChris Mason  * items
320344871b1bSChris Mason  */
320444871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
320599d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
320699d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
320744871b1bSChris Mason {
320844871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
320944871b1bSChris Mason 	struct extent_buffer *left;
321044871b1bSChris Mason 	int slot;
321144871b1bSChris Mason 	int free_space;
321244871b1bSChris Mason 	u32 right_nritems;
321344871b1bSChris Mason 	int ret = 0;
321444871b1bSChris Mason 
321544871b1bSChris Mason 	slot = path->slots[1];
321644871b1bSChris Mason 	if (slot == 0)
321744871b1bSChris Mason 		return 1;
321844871b1bSChris Mason 	if (!path->nodes[1])
321944871b1bSChris Mason 		return 1;
322044871b1bSChris Mason 
322144871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
322244871b1bSChris Mason 	if (right_nritems == 0)
322344871b1bSChris Mason 		return 1;
322444871b1bSChris Mason 
322549d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
322644871b1bSChris Mason 
32274b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3228fb770ae4SLiu Bo 	/*
3229fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3230fb770ae4SLiu Bo 	 * no big deal, just return.
3231fb770ae4SLiu Bo 	 */
3232fb770ae4SLiu Bo 	if (IS_ERR(left))
323391ca338dSTsutomu Itoh 		return 1;
323491ca338dSTsutomu Itoh 
3235bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
323644871b1bSChris Mason 
3237e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
323844871b1bSChris Mason 	if (free_space < data_size) {
323944871b1bSChris Mason 		ret = 1;
324044871b1bSChris Mason 		goto out;
324144871b1bSChris Mason 	}
324244871b1bSChris Mason 
324344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
32449631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3245bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
324644871b1bSChris Mason 	if (ret) {
324744871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
324879787eaaSJeff Mahoney 		if (ret == -ENOSPC)
324944871b1bSChris Mason 			ret = 1;
325044871b1bSChris Mason 		goto out;
325144871b1bSChris Mason 	}
325244871b1bSChris Mason 
3253d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3254d16c702fSQu Wenruo 		ret = -EUCLEAN;
3255d16c702fSQu Wenruo 		goto out;
3256d16c702fSQu Wenruo 	}
32578087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
325899d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
325999d8f83cSChris Mason 			       max_slot);
326044871b1bSChris Mason out:
326144871b1bSChris Mason 	btrfs_tree_unlock(left);
326244871b1bSChris Mason 	free_extent_buffer(left);
326344871b1bSChris Mason 	return ret;
326444871b1bSChris Mason }
326544871b1bSChris Mason 
326644871b1bSChris Mason /*
326774123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
326874123bd7SChris Mason  * available for the resulting leaf level of the path.
326974123bd7SChris Mason  */
3270143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
327144871b1bSChris Mason 				    struct btrfs_path *path,
327244871b1bSChris Mason 				    struct extent_buffer *l,
327344871b1bSChris Mason 				    struct extent_buffer *right,
327444871b1bSChris Mason 				    int slot, int mid, int nritems)
3275be0e5c09SChris Mason {
327694f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3277be0e5c09SChris Mason 	int data_copy_size;
3278be0e5c09SChris Mason 	int rt_data_off;
3279be0e5c09SChris Mason 	int i;
3280d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3281cfed81a0SChris Mason 	struct btrfs_map_token token;
3282cfed81a0SChris Mason 
32835f39d397SChris Mason 	nritems = nritems - mid;
32845f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3285dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
32865f39d397SChris Mason 
32875f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
32885f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
32895f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
32905f39d397SChris Mason 
32915f39d397SChris Mason 	copy_extent_buffer(right, l,
32923d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
32933d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
32948f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
329574123bd7SChris Mason 
3296dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
32975f39d397SChris Mason 
3298c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
32995f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3300db94535dSChris Mason 		u32 ioff;
3301db94535dSChris Mason 
33023212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
33033212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
33040783fcfcSChris Mason 	}
330574123bd7SChris Mason 
33065f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
33075f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
33086ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
33095f39d397SChris Mason 
33105f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
33115f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3312eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
33135f39d397SChris Mason 
3314be0e5c09SChris Mason 	if (mid <= slot) {
3315925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
33165f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
33175f39d397SChris Mason 		path->nodes[0] = right;
3318be0e5c09SChris Mason 		path->slots[0] -= mid;
3319be0e5c09SChris Mason 		path->slots[1] += 1;
3320925baeddSChris Mason 	} else {
3321925baeddSChris Mason 		btrfs_tree_unlock(right);
33225f39d397SChris Mason 		free_extent_buffer(right);
3323925baeddSChris Mason 	}
33245f39d397SChris Mason 
3325eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
332644871b1bSChris Mason }
332744871b1bSChris Mason 
332844871b1bSChris Mason /*
332999d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
333099d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
333199d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
333299d8f83cSChris Mason  *          A                 B                 C
333399d8f83cSChris Mason  *
333499d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
333599d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
333699d8f83cSChris Mason  * completely.
333799d8f83cSChris Mason  */
333899d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
333999d8f83cSChris Mason 					  struct btrfs_root *root,
334099d8f83cSChris Mason 					  struct btrfs_path *path,
334199d8f83cSChris Mason 					  int data_size)
334299d8f83cSChris Mason {
334399d8f83cSChris Mason 	int ret;
334499d8f83cSChris Mason 	int progress = 0;
334599d8f83cSChris Mason 	int slot;
334699d8f83cSChris Mason 	u32 nritems;
33475a4267caSFilipe David Borba Manana 	int space_needed = data_size;
334899d8f83cSChris Mason 
334999d8f83cSChris Mason 	slot = path->slots[0];
33505a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3351e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
335299d8f83cSChris Mason 
335399d8f83cSChris Mason 	/*
335499d8f83cSChris Mason 	 * try to push all the items after our slot into the
335599d8f83cSChris Mason 	 * right leaf
335699d8f83cSChris Mason 	 */
33575a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
335899d8f83cSChris Mason 	if (ret < 0)
335999d8f83cSChris Mason 		return ret;
336099d8f83cSChris Mason 
336199d8f83cSChris Mason 	if (ret == 0)
336299d8f83cSChris Mason 		progress++;
336399d8f83cSChris Mason 
336499d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
336599d8f83cSChris Mason 	/*
336699d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
336799d8f83cSChris Mason 	 * we've done so we're done
336899d8f83cSChris Mason 	 */
336999d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
337099d8f83cSChris Mason 		return 0;
337199d8f83cSChris Mason 
3372e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
337399d8f83cSChris Mason 		return 0;
337499d8f83cSChris Mason 
337599d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
337699d8f83cSChris Mason 	slot = path->slots[0];
3377263d3995SFilipe Manana 	space_needed = data_size;
3378263d3995SFilipe Manana 	if (slot > 0)
3379e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
33805a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
338199d8f83cSChris Mason 	if (ret < 0)
338299d8f83cSChris Mason 		return ret;
338399d8f83cSChris Mason 
338499d8f83cSChris Mason 	if (ret == 0)
338599d8f83cSChris Mason 		progress++;
338699d8f83cSChris Mason 
338799d8f83cSChris Mason 	if (progress)
338899d8f83cSChris Mason 		return 0;
338999d8f83cSChris Mason 	return 1;
339099d8f83cSChris Mason }
339199d8f83cSChris Mason 
339299d8f83cSChris Mason /*
339344871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
339444871b1bSChris Mason  * available for the resulting leaf level of the path.
339544871b1bSChris Mason  *
339644871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
339744871b1bSChris Mason  */
339844871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
339944871b1bSChris Mason 			       struct btrfs_root *root,
3400310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
340144871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
340244871b1bSChris Mason 			       int extend)
340344871b1bSChris Mason {
34045d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
340544871b1bSChris Mason 	struct extent_buffer *l;
340644871b1bSChris Mason 	u32 nritems;
340744871b1bSChris Mason 	int mid;
340844871b1bSChris Mason 	int slot;
340944871b1bSChris Mason 	struct extent_buffer *right;
3410b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
341144871b1bSChris Mason 	int ret = 0;
341244871b1bSChris Mason 	int wret;
34135d4f98a2SYan Zheng 	int split;
341444871b1bSChris Mason 	int num_doubles = 0;
341599d8f83cSChris Mason 	int tried_avoid_double = 0;
341644871b1bSChris Mason 
3417a5719521SYan, Zheng 	l = path->nodes[0];
3418a5719521SYan, Zheng 	slot = path->slots[0];
34193212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
34200b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3421a5719521SYan, Zheng 		return -EOVERFLOW;
3422a5719521SYan, Zheng 
342344871b1bSChris Mason 	/* first try to make some room by pushing left and right */
342433157e05SLiu Bo 	if (data_size && path->nodes[1]) {
34255a4267caSFilipe David Borba Manana 		int space_needed = data_size;
34265a4267caSFilipe David Borba Manana 
34275a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3428e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
34295a4267caSFilipe David Borba Manana 
34305a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
34315a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
343244871b1bSChris Mason 		if (wret < 0)
343344871b1bSChris Mason 			return wret;
343444871b1bSChris Mason 		if (wret) {
3435263d3995SFilipe Manana 			space_needed = data_size;
3436263d3995SFilipe Manana 			if (slot > 0)
3437e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
34385a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
34395a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
344044871b1bSChris Mason 			if (wret < 0)
344144871b1bSChris Mason 				return wret;
344244871b1bSChris Mason 		}
344344871b1bSChris Mason 		l = path->nodes[0];
344444871b1bSChris Mason 
344544871b1bSChris Mason 		/* did the pushes work? */
3446e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
344744871b1bSChris Mason 			return 0;
344844871b1bSChris Mason 	}
344944871b1bSChris Mason 
345044871b1bSChris Mason 	if (!path->nodes[1]) {
3451fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
345244871b1bSChris Mason 		if (ret)
345344871b1bSChris Mason 			return ret;
345444871b1bSChris Mason 	}
345544871b1bSChris Mason again:
34565d4f98a2SYan Zheng 	split = 1;
345744871b1bSChris Mason 	l = path->nodes[0];
345844871b1bSChris Mason 	slot = path->slots[0];
345944871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
346044871b1bSChris Mason 	mid = (nritems + 1) / 2;
346144871b1bSChris Mason 
34625d4f98a2SYan Zheng 	if (mid <= slot) {
34635d4f98a2SYan Zheng 		if (nritems == 1 ||
34645d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
34650b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
34665d4f98a2SYan Zheng 			if (slot >= nritems) {
34675d4f98a2SYan Zheng 				split = 0;
34685d4f98a2SYan Zheng 			} else {
34695d4f98a2SYan Zheng 				mid = slot;
34705d4f98a2SYan Zheng 				if (mid != nritems &&
34715d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
34720b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
347399d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
347499d8f83cSChris Mason 						goto push_for_double;
34755d4f98a2SYan Zheng 					split = 2;
34765d4f98a2SYan Zheng 				}
34775d4f98a2SYan Zheng 			}
34785d4f98a2SYan Zheng 		}
34795d4f98a2SYan Zheng 	} else {
34805d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
34810b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
34825d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
34835d4f98a2SYan Zheng 				split = 0;
34845d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
34855d4f98a2SYan Zheng 				mid = 1;
34865d4f98a2SYan Zheng 			} else {
34875d4f98a2SYan Zheng 				mid = slot;
34885d4f98a2SYan Zheng 				if (mid != nritems &&
34895d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
34900b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
349199d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
349299d8f83cSChris Mason 						goto push_for_double;
34935d4f98a2SYan Zheng 					split = 2;
34945d4f98a2SYan Zheng 				}
34955d4f98a2SYan Zheng 			}
34965d4f98a2SYan Zheng 		}
34975d4f98a2SYan Zheng 	}
34985d4f98a2SYan Zheng 
34995d4f98a2SYan Zheng 	if (split == 0)
35005d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
35015d4f98a2SYan Zheng 	else
35025d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
35035d4f98a2SYan Zheng 
3504ca9d473aSJosef Bacik 	/*
3505ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3506ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3507ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3508ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3509ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3510ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3511ca9d473aSJosef Bacik 	 */
351279bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
351379bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
351479bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3515ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3516f0486c68SYan, Zheng 	if (IS_ERR(right))
351744871b1bSChris Mason 		return PTR_ERR(right);
3518f0486c68SYan, Zheng 
35190b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
352044871b1bSChris Mason 
35215d4f98a2SYan Zheng 	if (split == 0) {
352244871b1bSChris Mason 		if (mid <= slot) {
352344871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
35246ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
35252ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
352644871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
352744871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
352844871b1bSChris Mason 			path->nodes[0] = right;
352944871b1bSChris Mason 			path->slots[0] = 0;
353044871b1bSChris Mason 			path->slots[1] += 1;
353144871b1bSChris Mason 		} else {
353244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
35336ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
35342ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
353544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
353644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
353744871b1bSChris Mason 			path->nodes[0] = right;
353844871b1bSChris Mason 			path->slots[0] = 0;
3539143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3540b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
35415d4f98a2SYan Zheng 		}
3542196e0249SLiu Bo 		/*
3543196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3544196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3545196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3546196e0249SLiu Bo 		 */
354744871b1bSChris Mason 		return ret;
354844871b1bSChris Mason 	}
354944871b1bSChris Mason 
355094f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
355144871b1bSChris Mason 
35525d4f98a2SYan Zheng 	if (split == 2) {
3553cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3554cc0c5538SChris Mason 		num_doubles++;
3555cc0c5538SChris Mason 		goto again;
35563326d1b0SChris Mason 	}
355744871b1bSChris Mason 
3558143bede5SJeff Mahoney 	return 0;
355999d8f83cSChris Mason 
356099d8f83cSChris Mason push_for_double:
356199d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
356299d8f83cSChris Mason 	tried_avoid_double = 1;
3563e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
356499d8f83cSChris Mason 		return 0;
356599d8f83cSChris Mason 	goto again;
3566be0e5c09SChris Mason }
3567be0e5c09SChris Mason 
3568ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3569ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3570ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3571ad48fd75SYan, Zheng {
3572ad48fd75SYan, Zheng 	struct btrfs_key key;
3573ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3574ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3575ad48fd75SYan, Zheng 	u64 extent_len = 0;
3576ad48fd75SYan, Zheng 	u32 item_size;
3577ad48fd75SYan, Zheng 	int ret;
3578ad48fd75SYan, Zheng 
3579ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3580ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3581ad48fd75SYan, Zheng 
3582ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3583ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3584ad48fd75SYan, Zheng 
3585e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3586ad48fd75SYan, Zheng 		return 0;
3587ad48fd75SYan, Zheng 
35883212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3589ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3590ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3591ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3592ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3593ad48fd75SYan, Zheng 	}
3594b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3595ad48fd75SYan, Zheng 
3596ad48fd75SYan, Zheng 	path->keep_locks = 1;
3597ad48fd75SYan, Zheng 	path->search_for_split = 1;
3598ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3599ad48fd75SYan, Zheng 	path->search_for_split = 0;
3600a8df6fe6SFilipe Manana 	if (ret > 0)
3601a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3602ad48fd75SYan, Zheng 	if (ret < 0)
3603ad48fd75SYan, Zheng 		goto err;
3604ad48fd75SYan, Zheng 
3605ad48fd75SYan, Zheng 	ret = -EAGAIN;
3606ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3607a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
36083212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3609ad48fd75SYan, Zheng 		goto err;
3610ad48fd75SYan, Zheng 
3611109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3612e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3613109f6aefSChris Mason 		goto err;
3614109f6aefSChris Mason 
3615ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3616ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3617ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3618ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3619ad48fd75SYan, Zheng 			goto err;
3620ad48fd75SYan, Zheng 	}
3621ad48fd75SYan, Zheng 
3622ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3623f0486c68SYan, Zheng 	if (ret)
3624f0486c68SYan, Zheng 		goto err;
3625ad48fd75SYan, Zheng 
3626ad48fd75SYan, Zheng 	path->keep_locks = 0;
3627ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3628ad48fd75SYan, Zheng 	return 0;
3629ad48fd75SYan, Zheng err:
3630ad48fd75SYan, Zheng 	path->keep_locks = 0;
3631ad48fd75SYan, Zheng 	return ret;
3632ad48fd75SYan, Zheng }
3633ad48fd75SYan, Zheng 
363425263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3635310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3636459931ecSChris Mason 			       unsigned long split_offset)
3637459931ecSChris Mason {
3638459931ecSChris Mason 	struct extent_buffer *leaf;
3639c91666b1SJosef Bacik 	int orig_slot, slot;
3640ad48fd75SYan, Zheng 	char *buf;
3641459931ecSChris Mason 	u32 nritems;
3642ad48fd75SYan, Zheng 	u32 item_size;
3643459931ecSChris Mason 	u32 orig_offset;
3644459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3645459931ecSChris Mason 
3646459931ecSChris Mason 	leaf = path->nodes[0];
3647e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3648b9473439SChris Mason 
3649c91666b1SJosef Bacik 	orig_slot = path->slots[0];
36503212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
36513212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3652459931ecSChris Mason 
3653459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3654ad48fd75SYan, Zheng 	if (!buf)
3655ad48fd75SYan, Zheng 		return -ENOMEM;
3656ad48fd75SYan, Zheng 
3657459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3658459931ecSChris Mason 			    path->slots[0]), item_size);
3659ad48fd75SYan, Zheng 
3660459931ecSChris Mason 	slot = path->slots[0] + 1;
3661459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3662459931ecSChris Mason 	if (slot != nritems) {
3663459931ecSChris Mason 		/* shift the items */
3664459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3665459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3666459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3667459931ecSChris Mason 	}
3668459931ecSChris Mason 
3669459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3670459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3671459931ecSChris Mason 
36723212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
36733212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3674459931ecSChris Mason 
36753212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
3676459931ecSChris Mason 				 orig_offset + item_size - split_offset);
36773212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3678459931ecSChris Mason 
3679459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3680459931ecSChris Mason 
3681459931ecSChris Mason 	/* write the data for the start of the original item */
3682459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3683459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3684459931ecSChris Mason 			    split_offset);
3685459931ecSChris Mason 
3686459931ecSChris Mason 	/* write the data for the new item */
3687459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3688459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3689459931ecSChris Mason 			    item_size - split_offset);
3690459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3691459931ecSChris Mason 
3692e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3693459931ecSChris Mason 	kfree(buf);
3694ad48fd75SYan, Zheng 	return 0;
3695ad48fd75SYan, Zheng }
3696ad48fd75SYan, Zheng 
3697ad48fd75SYan, Zheng /*
3698ad48fd75SYan, Zheng  * This function splits a single item into two items,
3699ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3700ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3701ad48fd75SYan, Zheng  *
3702ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3703ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3704ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3705ad48fd75SYan, Zheng  *
3706ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3707ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3708ad48fd75SYan, Zheng  *
3709ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3710ad48fd75SYan, Zheng  * leaf the entire time.
3711ad48fd75SYan, Zheng  */
3712ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3713ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3714ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3715310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3716ad48fd75SYan, Zheng 		     unsigned long split_offset)
3717ad48fd75SYan, Zheng {
3718ad48fd75SYan, Zheng 	int ret;
3719ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3720ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3721ad48fd75SYan, Zheng 	if (ret)
3722459931ecSChris Mason 		return ret;
3723ad48fd75SYan, Zheng 
372425263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3725ad48fd75SYan, Zheng 	return ret;
3726ad48fd75SYan, Zheng }
3727ad48fd75SYan, Zheng 
3728ad48fd75SYan, Zheng /*
3729d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
3730d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
3731d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
3732d352ac68SChris Mason  * the front.
3733d352ac68SChris Mason  */
373478ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3735b18c6685SChris Mason {
3736b18c6685SChris Mason 	int slot;
37375f39d397SChris Mason 	struct extent_buffer *leaf;
3738b18c6685SChris Mason 	u32 nritems;
3739b18c6685SChris Mason 	unsigned int data_end;
3740b18c6685SChris Mason 	unsigned int old_data_start;
3741b18c6685SChris Mason 	unsigned int old_size;
3742b18c6685SChris Mason 	unsigned int size_diff;
3743b18c6685SChris Mason 	int i;
3744cfed81a0SChris Mason 	struct btrfs_map_token token;
3745cfed81a0SChris Mason 
37465f39d397SChris Mason 	leaf = path->nodes[0];
3747179e29e4SChris Mason 	slot = path->slots[0];
3748179e29e4SChris Mason 
37493212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
3750179e29e4SChris Mason 	if (old_size == new_size)
3751143bede5SJeff Mahoney 		return;
3752b18c6685SChris Mason 
37535f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
37548f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3755b18c6685SChris Mason 
37563212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
3757179e29e4SChris Mason 
3758b18c6685SChris Mason 	size_diff = old_size - new_size;
3759b18c6685SChris Mason 
3760b18c6685SChris Mason 	BUG_ON(slot < 0);
3761b18c6685SChris Mason 	BUG_ON(slot >= nritems);
3762b18c6685SChris Mason 
3763b18c6685SChris Mason 	/*
3764b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3765b18c6685SChris Mason 	 */
3766b18c6685SChris Mason 	/* first correct the data pointers */
3767c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3768b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
37695f39d397SChris Mason 		u32 ioff;
3770db94535dSChris Mason 
37713212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
37723212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3773b18c6685SChris Mason 	}
3774db94535dSChris Mason 
3775b18c6685SChris Mason 	/* shift the data */
3776179e29e4SChris Mason 	if (from_end) {
37773d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
37783d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3779b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
3780179e29e4SChris Mason 	} else {
3781179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
3782179e29e4SChris Mason 		u64 offset;
3783179e29e4SChris Mason 
3784179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
3785179e29e4SChris Mason 
3786179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3787179e29e4SChris Mason 			unsigned long ptr;
3788179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
3789179e29e4SChris Mason 
3790179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
3791179e29e4SChris Mason 					    struct btrfs_file_extent_item);
3792179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
3793179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
3794179e29e4SChris Mason 
3795179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
3796179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
3797179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
3798179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
3799179e29e4SChris Mason 				      (unsigned long)fi,
38007ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
3801179e29e4SChris Mason 			}
3802179e29e4SChris Mason 		}
3803179e29e4SChris Mason 
38043d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
38053d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3806179e29e4SChris Mason 			      data_end, old_data_start - data_end);
3807179e29e4SChris Mason 
3808179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
3809179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3810179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
3811179e29e4SChris Mason 		if (slot == 0)
3812b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
3813179e29e4SChris Mason 	}
38145f39d397SChris Mason 
38153212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
38165f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3817b18c6685SChris Mason 
3818e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3819a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3820b18c6685SChris Mason 		BUG();
38215f39d397SChris Mason 	}
3822b18c6685SChris Mason }
3823b18c6685SChris Mason 
3824d352ac68SChris Mason /*
38258f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
3826d352ac68SChris Mason  */
3827c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
38286567e837SChris Mason {
38296567e837SChris Mason 	int slot;
38305f39d397SChris Mason 	struct extent_buffer *leaf;
38316567e837SChris Mason 	u32 nritems;
38326567e837SChris Mason 	unsigned int data_end;
38336567e837SChris Mason 	unsigned int old_data;
38346567e837SChris Mason 	unsigned int old_size;
38356567e837SChris Mason 	int i;
3836cfed81a0SChris Mason 	struct btrfs_map_token token;
3837cfed81a0SChris Mason 
38385f39d397SChris Mason 	leaf = path->nodes[0];
38396567e837SChris Mason 
38405f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
38418f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
38426567e837SChris Mason 
3843e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
3844a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
38456567e837SChris Mason 		BUG();
38465f39d397SChris Mason 	}
38476567e837SChris Mason 	slot = path->slots[0];
3848dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
38496567e837SChris Mason 
38506567e837SChris Mason 	BUG_ON(slot < 0);
38513326d1b0SChris Mason 	if (slot >= nritems) {
3852a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3853c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
3854d397712bSChris Mason 			   slot, nritems);
3855290342f6SArnd Bergmann 		BUG();
38563326d1b0SChris Mason 	}
38576567e837SChris Mason 
38586567e837SChris Mason 	/*
38596567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
38606567e837SChris Mason 	 */
38616567e837SChris Mason 	/* first correct the data pointers */
3862c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
38636567e837SChris Mason 	for (i = slot; i < nritems; i++) {
38645f39d397SChris Mason 		u32 ioff;
3865db94535dSChris Mason 
38663212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
38673212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
38686567e837SChris Mason 	}
38695f39d397SChris Mason 
38706567e837SChris Mason 	/* shift the data */
38713d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
38723d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
38736567e837SChris Mason 		      data_end, old_data - data_end);
38745f39d397SChris Mason 
38756567e837SChris Mason 	data_end = old_data;
38763212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
38773212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
38785f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
38796567e837SChris Mason 
3880e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3881a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
38826567e837SChris Mason 		BUG();
38835f39d397SChris Mason 	}
38846567e837SChris Mason }
38856567e837SChris Mason 
3886da9ffb24SNikolay Borisov /**
3887da9ffb24SNikolay Borisov  * setup_items_for_insert - Helper called before inserting one or more items
3888da9ffb24SNikolay Borisov  * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
3889da9ffb24SNikolay Borisov  * in a function that doesn't call btrfs_search_slot
3890da9ffb24SNikolay Borisov  *
3891da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
3892da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
3893b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
389474123bd7SChris Mason  */
3895f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
3896b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
3897be0e5c09SChris Mason {
38980b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
38999c58309dSChris Mason 	int i;
39007518a238SChris Mason 	u32 nritems;
3901be0e5c09SChris Mason 	unsigned int data_end;
3902e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
390344871b1bSChris Mason 	struct extent_buffer *leaf;
390444871b1bSChris Mason 	int slot;
3905cfed81a0SChris Mason 	struct btrfs_map_token token;
3906fc0d82e1SNikolay Borisov 	u32 total_size;
3907fc0d82e1SNikolay Borisov 
3908b7ef5f3aSFilipe Manana 	/*
3909b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
3910b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
3911b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
3912b7ef5f3aSFilipe Manana 	 */
391324cdc847SFilipe Manana 	if (path->slots[0] == 0) {
3914b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
3915b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
391624cdc847SFilipe Manana 	}
391724cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
391824cdc847SFilipe Manana 
39195f39d397SChris Mason 	leaf = path->nodes[0];
392044871b1bSChris Mason 	slot = path->slots[0];
392174123bd7SChris Mason 
39225f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
39238f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3924b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
3925eb60ceacSChris Mason 
3926e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
3927a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39280b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
3929e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
3930be0e5c09SChris Mason 		BUG();
3931d4dbff95SChris Mason 	}
39325f39d397SChris Mason 
3933c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3934be0e5c09SChris Mason 	if (slot != nritems) {
3935dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
3936be0e5c09SChris Mason 
39375f39d397SChris Mason 		if (old_data < data_end) {
3938a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
39397269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
39407269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
39415f39d397SChris Mason 				   slot, old_data, data_end);
3942290342f6SArnd Bergmann 			BUG();
39435f39d397SChris Mason 		}
3944be0e5c09SChris Mason 		/*
3945be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3946be0e5c09SChris Mason 		 */
3947be0e5c09SChris Mason 		/* first correct the data pointers */
39480783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
39495f39d397SChris Mason 			u32 ioff;
3950db94535dSChris Mason 
39513212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
39523212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
3953b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
39540783fcfcSChris Mason 		}
3955be0e5c09SChris Mason 		/* shift the items */
3956b7ef5f3aSFilipe Manana 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + batch->nr),
39575f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
39580783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
3959be0e5c09SChris Mason 
3960be0e5c09SChris Mason 		/* shift the data */
39613d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
3962b7ef5f3aSFilipe Manana 				      data_end - batch->total_data_size,
3963b7ef5f3aSFilipe Manana 				      BTRFS_LEAF_DATA_OFFSET + data_end,
3964b7ef5f3aSFilipe Manana 				      old_data - data_end);
3965be0e5c09SChris Mason 		data_end = old_data;
3966be0e5c09SChris Mason 	}
39675f39d397SChris Mason 
396862e2749eSChris Mason 	/* setup the item for the new data */
3969b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
3970b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
39719c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
3972b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
39733212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
39743212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
39759c58309dSChris Mason 	}
397644871b1bSChris Mason 
3977b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
3978b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3979aa5d6bedSChris Mason 
3980e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3981a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3982be0e5c09SChris Mason 		BUG();
39835f39d397SChris Mason 	}
398444871b1bSChris Mason }
398544871b1bSChris Mason 
398644871b1bSChris Mason /*
3987f0641656SFilipe Manana  * Insert a new item into a leaf.
3988f0641656SFilipe Manana  *
3989f0641656SFilipe Manana  * @root:      The root of the btree.
3990f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
3991f0641656SFilipe Manana  * @key:       The key of the new item.
3992f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
3993f0641656SFilipe Manana  */
3994f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
3995f0641656SFilipe Manana 				 struct btrfs_path *path,
3996f0641656SFilipe Manana 				 const struct btrfs_key *key,
3997f0641656SFilipe Manana 				 u32 data_size)
3998f0641656SFilipe Manana {
3999f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4000f0641656SFilipe Manana 
4001f0641656SFilipe Manana 	batch.keys = key;
4002f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4003f0641656SFilipe Manana 	batch.total_data_size = data_size;
4004f0641656SFilipe Manana 	batch.nr = 1;
4005f0641656SFilipe Manana 
4006f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
4007f0641656SFilipe Manana }
4008f0641656SFilipe Manana 
4009f0641656SFilipe Manana /*
401044871b1bSChris Mason  * Given a key and some data, insert items into the tree.
401144871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
401244871b1bSChris Mason  */
401344871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
401444871b1bSChris Mason 			    struct btrfs_root *root,
401544871b1bSChris Mason 			    struct btrfs_path *path,
4016b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
401744871b1bSChris Mason {
401844871b1bSChris Mason 	int ret = 0;
401944871b1bSChris Mason 	int slot;
4020b7ef5f3aSFilipe Manana 	u32 total_size;
402144871b1bSChris Mason 
4022b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4023b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
402444871b1bSChris Mason 	if (ret == 0)
402544871b1bSChris Mason 		return -EEXIST;
402644871b1bSChris Mason 	if (ret < 0)
4027143bede5SJeff Mahoney 		return ret;
402844871b1bSChris Mason 
402944871b1bSChris Mason 	slot = path->slots[0];
403044871b1bSChris Mason 	BUG_ON(slot < 0);
403144871b1bSChris Mason 
4032b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4033143bede5SJeff Mahoney 	return 0;
403462e2749eSChris Mason }
403562e2749eSChris Mason 
403662e2749eSChris Mason /*
403762e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
403862e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
403962e2749eSChris Mason  */
4040310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4041310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4042310712b2SOmar Sandoval 		      u32 data_size)
404362e2749eSChris Mason {
404462e2749eSChris Mason 	int ret = 0;
40452c90e5d6SChris Mason 	struct btrfs_path *path;
40465f39d397SChris Mason 	struct extent_buffer *leaf;
40475f39d397SChris Mason 	unsigned long ptr;
404862e2749eSChris Mason 
40492c90e5d6SChris Mason 	path = btrfs_alloc_path();
4050db5b493aSTsutomu Itoh 	if (!path)
4051db5b493aSTsutomu Itoh 		return -ENOMEM;
40522c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
405362e2749eSChris Mason 	if (!ret) {
40545f39d397SChris Mason 		leaf = path->nodes[0];
40555f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
40565f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
40575f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
405862e2749eSChris Mason 	}
40592c90e5d6SChris Mason 	btrfs_free_path(path);
4060aa5d6bedSChris Mason 	return ret;
4061be0e5c09SChris Mason }
4062be0e5c09SChris Mason 
406374123bd7SChris Mason /*
4064f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4065f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4066f0641656SFilipe Manana  * contiguous with the original item.
4067f0641656SFilipe Manana  *
4068f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4069f0641656SFilipe Manana  * the entire time.
4070f0641656SFilipe Manana  */
4071f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4072f0641656SFilipe Manana 			 struct btrfs_root *root,
4073f0641656SFilipe Manana 			 struct btrfs_path *path,
4074f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4075f0641656SFilipe Manana {
4076f0641656SFilipe Manana 	struct extent_buffer *leaf;
4077f0641656SFilipe Manana 	int ret;
4078f0641656SFilipe Manana 	u32 item_size;
4079f0641656SFilipe Manana 
4080f0641656SFilipe Manana 	leaf = path->nodes[0];
40813212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4082f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4083f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4084f0641656SFilipe Manana 	if (ret)
4085f0641656SFilipe Manana 		return ret;
4086f0641656SFilipe Manana 
4087f0641656SFilipe Manana 	path->slots[0]++;
4088f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4089f0641656SFilipe Manana 	leaf = path->nodes[0];
4090f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4091f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4092f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4093f0641656SFilipe Manana 			     item_size);
4094f0641656SFilipe Manana 	return 0;
4095f0641656SFilipe Manana }
4096f0641656SFilipe Manana 
4097f0641656SFilipe Manana /*
40985de08d7dSChris Mason  * delete the pointer from a given node.
409974123bd7SChris Mason  *
4100d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4101d352ac68SChris Mason  * empty a node.
410274123bd7SChris Mason  */
4103afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4104afe5fea7STsutomu Itoh 		    int level, int slot)
4105be0e5c09SChris Mason {
41065f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
41077518a238SChris Mason 	u32 nritems;
4108f3ea38daSJan Schmidt 	int ret;
4109be0e5c09SChris Mason 
41105f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4111be0e5c09SChris Mason 	if (slot != nritems - 1) {
4112bf1d3425SDavid Sterba 		if (level) {
4113f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4114f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4115bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4116bf1d3425SDavid Sterba 		}
41175f39d397SChris Mason 		memmove_extent_buffer(parent,
41185f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
41195f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4120d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4121d6025579SChris Mason 			      (nritems - slot - 1));
412257ba86c0SChris Mason 	} else if (level) {
4123f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
4124f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REMOVE, GFP_NOFS);
412557ba86c0SChris Mason 		BUG_ON(ret < 0);
4126be0e5c09SChris Mason 	}
4127f3ea38daSJan Schmidt 
41287518a238SChris Mason 	nritems--;
41295f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
41307518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
41315f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4132eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
41335f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4134bb803951SChris Mason 	} else if (slot == 0) {
41355f39d397SChris Mason 		struct btrfs_disk_key disk_key;
41365f39d397SChris Mason 
41375f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4138b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4139be0e5c09SChris Mason 	}
4140d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4141be0e5c09SChris Mason }
4142be0e5c09SChris Mason 
414374123bd7SChris Mason /*
4144323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
41455d4f98a2SYan Zheng  * path->nodes[1].
4146323ac95bSChris Mason  *
4147323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4148323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4149323ac95bSChris Mason  *
4150323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4151323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4152323ac95bSChris Mason  */
4153143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4154323ac95bSChris Mason 				    struct btrfs_root *root,
41555d4f98a2SYan Zheng 				    struct btrfs_path *path,
41565d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4157323ac95bSChris Mason {
41585d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4159afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4160323ac95bSChris Mason 
41614d081c41SChris Mason 	/*
41624d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
41634d081c41SChris Mason 	 * aren't holding any locks when we call it
41644d081c41SChris Mason 	 */
41654d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
41664d081c41SChris Mason 
4167f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4168f0486c68SYan, Zheng 
416967439dadSDavid Sterba 	atomic_inc(&leaf->refs);
41707a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
41713083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4172323ac95bSChris Mason }
4173323ac95bSChris Mason /*
417474123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
417574123bd7SChris Mason  * the leaf, remove it from the tree
417674123bd7SChris Mason  */
417785e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
417885e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4179be0e5c09SChris Mason {
41800b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
41815f39d397SChris Mason 	struct extent_buffer *leaf;
4182aa5d6bedSChris Mason 	int ret = 0;
4183aa5d6bedSChris Mason 	int wret;
41847518a238SChris Mason 	u32 nritems;
4185be0e5c09SChris Mason 
41865f39d397SChris Mason 	leaf = path->nodes[0];
41875f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4188be0e5c09SChris Mason 
418985e21bacSChris Mason 	if (slot + nr != nritems) {
41900cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
41910cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4192c82f823cSDavid Sterba 		struct btrfs_map_token token;
41930cae23b6SFilipe Manana 		u32 dsize = 0;
41940cae23b6SFilipe Manana 		int i;
41950cae23b6SFilipe Manana 
41960cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
41970cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
41985f39d397SChris Mason 
41993d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4200d6025579SChris Mason 			      data_end + dsize,
42013d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
420285e21bacSChris Mason 			      last_off - data_end);
42035f39d397SChris Mason 
4204c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
420585e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
42065f39d397SChris Mason 			u32 ioff;
4207db94535dSChris Mason 
42083212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
42093212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
42100783fcfcSChris Mason 		}
4211db94535dSChris Mason 
42125f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
421385e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
42140783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
421585e21bacSChris Mason 			      (nritems - slot - nr));
4216be0e5c09SChris Mason 	}
421785e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
421885e21bacSChris Mason 	nritems -= nr;
42195f39d397SChris Mason 
422074123bd7SChris Mason 	/* delete the leaf if we've emptied it */
42217518a238SChris Mason 	if (nritems == 0) {
42225f39d397SChris Mason 		if (leaf == root->node) {
42235f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
42249a8dd150SChris Mason 		} else {
42256a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4226143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
42279a8dd150SChris Mason 		}
4228be0e5c09SChris Mason 	} else {
42297518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4230aa5d6bedSChris Mason 		if (slot == 0) {
42315f39d397SChris Mason 			struct btrfs_disk_key disk_key;
42325f39d397SChris Mason 
42335f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4234b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4235aa5d6bedSChris Mason 		}
4236aa5d6bedSChris Mason 
42377c4063d1SFilipe Manana 		/*
42387c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
42397c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
42407c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
42417c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
42427c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
42437c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
42447c4063d1SFilipe Manana 		 */
42450b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
42467c4063d1SFilipe Manana 			u32 min_push_space;
42477c4063d1SFilipe Manana 
4248be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4249be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4250be0e5c09SChris Mason 			 * for possible call to del_ptr below
4251be0e5c09SChris Mason 			 */
42524920c9acSChris Mason 			slot = path->slots[1];
425367439dadSDavid Sterba 			atomic_inc(&leaf->refs);
42547c4063d1SFilipe Manana 			/*
42557c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
42567c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
42577c4063d1SFilipe Manana 			 */
42587c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
42597c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
42607c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
42617c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
426254aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4263aa5d6bedSChris Mason 				ret = wret;
42645f39d397SChris Mason 
42655f39d397SChris Mason 			if (path->nodes[0] == leaf &&
42665f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
42677c4063d1SFilipe Manana 				/*
42687c4063d1SFilipe Manana 				 * If we were not able to push all items from our
42697c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
42707c4063d1SFilipe Manana 				 * either push all the remaining items to the
42717c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
42727c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
42737c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
42747c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
42757c4063d1SFilipe Manana 				 * or nearly full.
42767c4063d1SFilipe Manana 				 */
42777c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
42787c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
42797c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
42807c4063d1SFilipe Manana 						       min_push_space, 1, 0);
428154aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4282aa5d6bedSChris Mason 					ret = wret;
4283aa5d6bedSChris Mason 			}
42845f39d397SChris Mason 
42855f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4286323ac95bSChris Mason 				path->slots[1] = slot;
4287143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
42885f39d397SChris Mason 				free_extent_buffer(leaf);
4289143bede5SJeff Mahoney 				ret = 0;
42905de08d7dSChris Mason 			} else {
4291925baeddSChris Mason 				/* if we're still in the path, make sure
4292925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4293925baeddSChris Mason 				 * push_leaf functions must have already
4294925baeddSChris Mason 				 * dirtied this buffer
4295925baeddSChris Mason 				 */
4296925baeddSChris Mason 				if (path->nodes[0] == leaf)
42975f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
42985f39d397SChris Mason 				free_extent_buffer(leaf);
4299be0e5c09SChris Mason 			}
4300d5719762SChris Mason 		} else {
43015f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4302be0e5c09SChris Mason 		}
43039a8dd150SChris Mason 	}
4304aa5d6bedSChris Mason 	return ret;
43059a8dd150SChris Mason }
43069a8dd150SChris Mason 
430797571fd0SChris Mason /*
4308925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
43097bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
43107bb86316SChris Mason  * returns < 0 on io errors.
4311d352ac68SChris Mason  *
4312d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4313d352ac68SChris Mason  * time you call it.
43147bb86316SChris Mason  */
431516e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
43167bb86316SChris Mason {
4317925baeddSChris Mason 	struct btrfs_key key;
4318925baeddSChris Mason 	struct btrfs_disk_key found_key;
4319925baeddSChris Mason 	int ret;
43207bb86316SChris Mason 
4321925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4322925baeddSChris Mason 
4323e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
4324925baeddSChris Mason 		key.offset--;
4325e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
4326925baeddSChris Mason 		key.type--;
4327e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4328e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
4329925baeddSChris Mason 		key.objectid--;
4330e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
4331e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4332e8b0d724SFilipe David Borba Manana 	} else {
43337bb86316SChris Mason 		return 1;
4334e8b0d724SFilipe David Borba Manana 	}
43357bb86316SChris Mason 
4336b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4337925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4338925baeddSChris Mason 	if (ret < 0)
4339925baeddSChris Mason 		return ret;
4340925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4341925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4342337c6f68SFilipe Manana 	/*
4343337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
4344337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
4345337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
4346337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
4347337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
4348337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
4349337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
4350337c6f68SFilipe Manana 	 * the previous key we computed above.
4351337c6f68SFilipe Manana 	 */
4352337c6f68SFilipe Manana 	if (ret <= 0)
43537bb86316SChris Mason 		return 0;
4354925baeddSChris Mason 	return 1;
43557bb86316SChris Mason }
43567bb86316SChris Mason 
43573f157a2fSChris Mason /*
43583f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4359de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4360de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
43613f157a2fSChris Mason  *
43623f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
43633f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
43643f157a2fSChris Mason  * key and get a writable path.
43653f157a2fSChris Mason  *
43663f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
43673f157a2fSChris Mason  * of the tree.
43683f157a2fSChris Mason  *
4369d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4370d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4371d352ac68SChris Mason  * skipped over (without reading them).
4372d352ac68SChris Mason  *
43733f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
43743f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
43753f157a2fSChris Mason  */
43763f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4377de78b51aSEric Sandeen 			 struct btrfs_path *path,
43783f157a2fSChris Mason 			 u64 min_trans)
43793f157a2fSChris Mason {
43803f157a2fSChris Mason 	struct extent_buffer *cur;
43813f157a2fSChris Mason 	struct btrfs_key found_key;
43823f157a2fSChris Mason 	int slot;
43839652480bSYan 	int sret;
43843f157a2fSChris Mason 	u32 nritems;
43853f157a2fSChris Mason 	int level;
43863f157a2fSChris Mason 	int ret = 1;
4387f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
43883f157a2fSChris Mason 
4389f98de9b9SFilipe Manana 	path->keep_locks = 1;
43903f157a2fSChris Mason again:
4391bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
43923f157a2fSChris Mason 	level = btrfs_header_level(cur);
4393e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
43943f157a2fSChris Mason 	path->nodes[level] = cur;
4395bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
43963f157a2fSChris Mason 
43973f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
43983f157a2fSChris Mason 		ret = 1;
43993f157a2fSChris Mason 		goto out;
44003f157a2fSChris Mason 	}
44013f157a2fSChris Mason 	while (1) {
44023f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
44033f157a2fSChris Mason 		level = btrfs_header_level(cur);
4404e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
4405cbca7d59SFilipe Manana 		if (sret < 0) {
4406cbca7d59SFilipe Manana 			ret = sret;
4407cbca7d59SFilipe Manana 			goto out;
4408cbca7d59SFilipe Manana 		}
44093f157a2fSChris Mason 
4410323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4411323ac95bSChris Mason 		if (level == path->lowest_level) {
4412e02119d5SChris Mason 			if (slot >= nritems)
4413e02119d5SChris Mason 				goto find_next_key;
44143f157a2fSChris Mason 			ret = 0;
44153f157a2fSChris Mason 			path->slots[level] = slot;
44163f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
44173f157a2fSChris Mason 			goto out;
44183f157a2fSChris Mason 		}
44199652480bSYan 		if (sret && slot > 0)
44209652480bSYan 			slot--;
44213f157a2fSChris Mason 		/*
4422de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4423260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
44243f157a2fSChris Mason 		 */
44253f157a2fSChris Mason 		while (slot < nritems) {
44263f157a2fSChris Mason 			u64 gen;
4427e02119d5SChris Mason 
44283f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
44293f157a2fSChris Mason 			if (gen < min_trans) {
44303f157a2fSChris Mason 				slot++;
44313f157a2fSChris Mason 				continue;
44323f157a2fSChris Mason 			}
44333f157a2fSChris Mason 			break;
44343f157a2fSChris Mason 		}
4435e02119d5SChris Mason find_next_key:
44363f157a2fSChris Mason 		/*
44373f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
44383f157a2fSChris Mason 		 * and find another one
44393f157a2fSChris Mason 		 */
44403f157a2fSChris Mason 		if (slot >= nritems) {
4441e02119d5SChris Mason 			path->slots[level] = slot;
4442e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4443de78b51aSEric Sandeen 						  min_trans);
4444e02119d5SChris Mason 			if (sret == 0) {
4445b3b4aa74SDavid Sterba 				btrfs_release_path(path);
44463f157a2fSChris Mason 				goto again;
44473f157a2fSChris Mason 			} else {
44483f157a2fSChris Mason 				goto out;
44493f157a2fSChris Mason 			}
44503f157a2fSChris Mason 		}
44513f157a2fSChris Mason 		/* save our key for returning back */
44523f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
44533f157a2fSChris Mason 		path->slots[level] = slot;
44543f157a2fSChris Mason 		if (level == path->lowest_level) {
44553f157a2fSChris Mason 			ret = 0;
44563f157a2fSChris Mason 			goto out;
44573f157a2fSChris Mason 		}
44584b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4459fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4460fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4461fb770ae4SLiu Bo 			goto out;
4462fb770ae4SLiu Bo 		}
44633f157a2fSChris Mason 
4464bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4465b4ce94deSChris Mason 
4466bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
44673f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4468f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
44693f157a2fSChris Mason 	}
44703f157a2fSChris Mason out:
4471f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4472f98de9b9SFilipe Manana 	if (ret == 0) {
4473f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4474f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4475f98de9b9SFilipe Manana 	}
44763f157a2fSChris Mason 	return ret;
44773f157a2fSChris Mason }
44783f157a2fSChris Mason 
44793f157a2fSChris Mason /*
44803f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
44813f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4482de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
44833f157a2fSChris Mason  *
44843f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
44853f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
44863f157a2fSChris Mason  *
44873f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
44883f157a2fSChris Mason  * calling this function.
44893f157a2fSChris Mason  */
4490e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4491de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4492e7a84565SChris Mason {
4493e7a84565SChris Mason 	int slot;
4494e7a84565SChris Mason 	struct extent_buffer *c;
4495e7a84565SChris Mason 
44966a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4497e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4498e7a84565SChris Mason 		if (!path->nodes[level])
4499e7a84565SChris Mason 			return 1;
4500e7a84565SChris Mason 
4501e7a84565SChris Mason 		slot = path->slots[level] + 1;
4502e7a84565SChris Mason 		c = path->nodes[level];
45033f157a2fSChris Mason next:
4504e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
450533c66f43SYan Zheng 			int ret;
450633c66f43SYan Zheng 			int orig_lowest;
450733c66f43SYan Zheng 			struct btrfs_key cur_key;
450833c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
450933c66f43SYan Zheng 			    !path->nodes[level + 1])
4510e7a84565SChris Mason 				return 1;
451133c66f43SYan Zheng 
45126a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
451333c66f43SYan Zheng 				level++;
4514e7a84565SChris Mason 				continue;
4515e7a84565SChris Mason 			}
451633c66f43SYan Zheng 
451733c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
451833c66f43SYan Zheng 			if (level == 0)
451933c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
452033c66f43SYan Zheng 			else
452133c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
452233c66f43SYan Zheng 
452333c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4524b3b4aa74SDavid Sterba 			btrfs_release_path(path);
452533c66f43SYan Zheng 			path->lowest_level = level;
452633c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
452733c66f43SYan Zheng 						0, 0);
452833c66f43SYan Zheng 			path->lowest_level = orig_lowest;
452933c66f43SYan Zheng 			if (ret < 0)
453033c66f43SYan Zheng 				return ret;
453133c66f43SYan Zheng 
453233c66f43SYan Zheng 			c = path->nodes[level];
453333c66f43SYan Zheng 			slot = path->slots[level];
453433c66f43SYan Zheng 			if (ret == 0)
453533c66f43SYan Zheng 				slot++;
453633c66f43SYan Zheng 			goto next;
453733c66f43SYan Zheng 		}
453833c66f43SYan Zheng 
4539e7a84565SChris Mason 		if (level == 0)
4540e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
45413f157a2fSChris Mason 		else {
45423f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
45433f157a2fSChris Mason 
45443f157a2fSChris Mason 			if (gen < min_trans) {
45453f157a2fSChris Mason 				slot++;
45463f157a2fSChris Mason 				goto next;
45473f157a2fSChris Mason 			}
4548e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
45493f157a2fSChris Mason 		}
4550e7a84565SChris Mason 		return 0;
4551e7a84565SChris Mason 	}
4552e7a84565SChris Mason 	return 1;
4553e7a84565SChris Mason }
4554e7a84565SChris Mason 
45553d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
45563d7806ecSJan Schmidt 			u64 time_seq)
45573d7806ecSJan Schmidt {
4558d97e63b6SChris Mason 	int slot;
45598e73f275SChris Mason 	int level;
45605f39d397SChris Mason 	struct extent_buffer *c;
45618e73f275SChris Mason 	struct extent_buffer *next;
4562d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4563925baeddSChris Mason 	struct btrfs_key key;
4564d96b3424SFilipe Manana 	bool need_commit_sem = false;
4565925baeddSChris Mason 	u32 nritems;
4566925baeddSChris Mason 	int ret;
45670e46318dSJosef Bacik 	int i;
4568925baeddSChris Mason 
4569925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4570d397712bSChris Mason 	if (nritems == 0)
4571925baeddSChris Mason 		return 1;
4572925baeddSChris Mason 
45738e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
45748e73f275SChris Mason again:
45758e73f275SChris Mason 	level = 1;
45768e73f275SChris Mason 	next = NULL;
4577b3b4aa74SDavid Sterba 	btrfs_release_path(path);
45788e73f275SChris Mason 
4579a2135011SChris Mason 	path->keep_locks = 1;
45808e73f275SChris Mason 
4581d96b3424SFilipe Manana 	if (time_seq) {
45823d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4583d96b3424SFilipe Manana 	} else {
4584d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4585d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4586d96b3424SFilipe Manana 			need_commit_sem = true;
4587d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
4588d96b3424SFilipe Manana 		}
4589925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4590d96b3424SFilipe Manana 	}
4591925baeddSChris Mason 	path->keep_locks = 0;
4592925baeddSChris Mason 
4593925baeddSChris Mason 	if (ret < 0)
4594d96b3424SFilipe Manana 		goto done;
4595925baeddSChris Mason 
4596a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4597168fd7d2SChris Mason 	/*
4598168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4599168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4600168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4601168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4602168fd7d2SChris Mason 	 */
4603a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4604e457afecSYan Zheng 		if (ret == 0)
4605168fd7d2SChris Mason 			path->slots[0]++;
46068e73f275SChris Mason 		ret = 0;
4607925baeddSChris Mason 		goto done;
4608925baeddSChris Mason 	}
46090b43e04fSLiu Bo 	/*
46100b43e04fSLiu Bo 	 * So the above check misses one case:
46110b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
46120b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
46130b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
46140b43e04fSLiu Bo 	 *
46150b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
46160b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
46170b43e04fSLiu Bo 	 *
46180b43e04fSLiu Bo 	 * And a bit more explanation about this check,
46190b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
46200b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
46210b43e04fSLiu Bo 	 * bigger one.
46220b43e04fSLiu Bo 	 */
46230b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
46240b43e04fSLiu Bo 		ret = 0;
46250b43e04fSLiu Bo 		goto done;
46260b43e04fSLiu Bo 	}
4627d97e63b6SChris Mason 
4628234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
46298e73f275SChris Mason 		if (!path->nodes[level]) {
46308e73f275SChris Mason 			ret = 1;
46318e73f275SChris Mason 			goto done;
46328e73f275SChris Mason 		}
46335f39d397SChris Mason 
4634d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4635d97e63b6SChris Mason 		c = path->nodes[level];
46365f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4637d97e63b6SChris Mason 			level++;
46388e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
46398e73f275SChris Mason 				ret = 1;
46408e73f275SChris Mason 				goto done;
46418e73f275SChris Mason 			}
4642d97e63b6SChris Mason 			continue;
4643d97e63b6SChris Mason 		}
46445f39d397SChris Mason 
46450e46318dSJosef Bacik 
46460e46318dSJosef Bacik 		/*
46470e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
46480e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
46490e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
46500e46318dSJosef Bacik 		 */
46510e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
46520e46318dSJosef Bacik 			if (path->locks[level]) {
46530e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
46540e46318dSJosef Bacik 				path->locks[i] = 0;
46550e46318dSJosef Bacik 			}
46560e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
46570e46318dSJosef Bacik 			path->nodes[i] = NULL;
4658925baeddSChris Mason 		}
46595f39d397SChris Mason 
46608e73f275SChris Mason 		next = c;
4661d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4662cda79c54SDavid Sterba 					    slot, &key);
46638e73f275SChris Mason 		if (ret == -EAGAIN)
46648e73f275SChris Mason 			goto again;
46655f39d397SChris Mason 
466676a05b35SChris Mason 		if (ret < 0) {
4667b3b4aa74SDavid Sterba 			btrfs_release_path(path);
466876a05b35SChris Mason 			goto done;
466976a05b35SChris Mason 		}
467076a05b35SChris Mason 
46715cd57b2cSChris Mason 		if (!path->skip_locking) {
4672bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4673d42244a0SJan Schmidt 			if (!ret && time_seq) {
4674d42244a0SJan Schmidt 				/*
4675d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4676d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4677d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4678d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4679d42244a0SJan Schmidt 				 * on our lock and cycle.
4680d42244a0SJan Schmidt 				 */
4681cf538830SJan Schmidt 				free_extent_buffer(next);
4682d42244a0SJan Schmidt 				btrfs_release_path(path);
4683d42244a0SJan Schmidt 				cond_resched();
4684d42244a0SJan Schmidt 				goto again;
4685d42244a0SJan Schmidt 			}
46860e46318dSJosef Bacik 			if (!ret)
46870e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4688bd681513SChris Mason 		}
4689d97e63b6SChris Mason 		break;
4690d97e63b6SChris Mason 	}
4691d97e63b6SChris Mason 	path->slots[level] = slot;
4692d97e63b6SChris Mason 	while (1) {
4693d97e63b6SChris Mason 		level--;
4694d97e63b6SChris Mason 		path->nodes[level] = next;
4695d97e63b6SChris Mason 		path->slots[level] = 0;
4696a74a4b97SChris Mason 		if (!path->skip_locking)
4697ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4698d97e63b6SChris Mason 		if (!level)
4699d97e63b6SChris Mason 			break;
4700b4ce94deSChris Mason 
4701d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4702cda79c54SDavid Sterba 					    0, &key);
47038e73f275SChris Mason 		if (ret == -EAGAIN)
47048e73f275SChris Mason 			goto again;
47058e73f275SChris Mason 
470676a05b35SChris Mason 		if (ret < 0) {
4707b3b4aa74SDavid Sterba 			btrfs_release_path(path);
470876a05b35SChris Mason 			goto done;
470976a05b35SChris Mason 		}
471076a05b35SChris Mason 
4711ffeb03cfSJosef Bacik 		if (!path->skip_locking)
47120e46318dSJosef Bacik 			btrfs_tree_read_lock(next);
4713d97e63b6SChris Mason 	}
47148e73f275SChris Mason 	ret = 0;
4715925baeddSChris Mason done:
4716f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
4717d96b3424SFilipe Manana 	if (need_commit_sem) {
4718d96b3424SFilipe Manana 		int ret2;
4719d96b3424SFilipe Manana 
4720d96b3424SFilipe Manana 		path->need_commit_sem = 1;
4721d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
4722d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
4723d96b3424SFilipe Manana 		if (ret2)
4724d96b3424SFilipe Manana 			ret = ret2;
4725d96b3424SFilipe Manana 	}
47268e73f275SChris Mason 
47278e73f275SChris Mason 	return ret;
4728d97e63b6SChris Mason }
47290b86a832SChris Mason 
47303f157a2fSChris Mason /*
47313f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
47323f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
47333f157a2fSChris Mason  *
47343f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
47353f157a2fSChris Mason  */
47360b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
47370b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
47380b86a832SChris Mason 			int type)
47390b86a832SChris Mason {
47400b86a832SChris Mason 	struct btrfs_key found_key;
47410b86a832SChris Mason 	struct extent_buffer *leaf;
4742e02119d5SChris Mason 	u32 nritems;
47430b86a832SChris Mason 	int ret;
47440b86a832SChris Mason 
47450b86a832SChris Mason 	while (1) {
47460b86a832SChris Mason 		if (path->slots[0] == 0) {
47470b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
47480b86a832SChris Mason 			if (ret != 0)
47490b86a832SChris Mason 				return ret;
47500b86a832SChris Mason 		} else {
47510b86a832SChris Mason 			path->slots[0]--;
47520b86a832SChris Mason 		}
47530b86a832SChris Mason 		leaf = path->nodes[0];
4754e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
4755e02119d5SChris Mason 		if (nritems == 0)
4756e02119d5SChris Mason 			return 1;
4757e02119d5SChris Mason 		if (path->slots[0] == nritems)
4758e02119d5SChris Mason 			path->slots[0]--;
4759e02119d5SChris Mason 
47600b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4761e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
4762e02119d5SChris Mason 			break;
47630a4eefbbSYan Zheng 		if (found_key.type == type)
47640a4eefbbSYan Zheng 			return 0;
4765e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
4766e02119d5SChris Mason 		    found_key.type < type)
4767e02119d5SChris Mason 			break;
47680b86a832SChris Mason 	}
47690b86a832SChris Mason 	return 1;
47700b86a832SChris Mason }
4771ade2e0b3SWang Shilong 
4772ade2e0b3SWang Shilong /*
4773ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
4774ade2e0b3SWang Shilong  * min objecitd.
4775ade2e0b3SWang Shilong  *
4776ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4777ade2e0b3SWang Shilong  */
4778ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
4779ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
4780ade2e0b3SWang Shilong {
4781ade2e0b3SWang Shilong 	struct btrfs_key found_key;
4782ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
4783ade2e0b3SWang Shilong 	u32 nritems;
4784ade2e0b3SWang Shilong 	int ret;
4785ade2e0b3SWang Shilong 
4786ade2e0b3SWang Shilong 	while (1) {
4787ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
4788ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
4789ade2e0b3SWang Shilong 			if (ret != 0)
4790ade2e0b3SWang Shilong 				return ret;
4791ade2e0b3SWang Shilong 		} else {
4792ade2e0b3SWang Shilong 			path->slots[0]--;
4793ade2e0b3SWang Shilong 		}
4794ade2e0b3SWang Shilong 		leaf = path->nodes[0];
4795ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
4796ade2e0b3SWang Shilong 		if (nritems == 0)
4797ade2e0b3SWang Shilong 			return 1;
4798ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
4799ade2e0b3SWang Shilong 			path->slots[0]--;
4800ade2e0b3SWang Shilong 
4801ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4802ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
4803ade2e0b3SWang Shilong 			break;
4804ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4805ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
4806ade2e0b3SWang Shilong 			return 0;
4807ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
4808ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
4809ade2e0b3SWang Shilong 			break;
4810ade2e0b3SWang Shilong 	}
4811ade2e0b3SWang Shilong 	return 1;
4812ade2e0b3SWang Shilong }
4813