xref: /openbmc/linux/fs/btrfs/ctree.c (revision c922b016f353eafb69997d8c0f06efdf945315ce)
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"
1988c602abSQu Wenruo #include "tree-checker.h"
209a8dd150SChris Mason 
21e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
22e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
23310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
24310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
25310712b2SOmar Sandoval 		      int data_size, int extend);
265f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
272ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
28971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
295f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
305f39d397SChris Mason 			      struct extent_buffer *dst_buf,
315f39d397SChris Mason 			      struct extent_buffer *src_buf);
32afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
33afe5fea7STsutomu Itoh 		    int level, int slot);
34d97e63b6SChris Mason 
35af024ed2SJohannes Thumshirn static const struct btrfs_csums {
36af024ed2SJohannes Thumshirn 	u16		size;
3759a0fcdbSDavid Sterba 	const char	name[10];
3859a0fcdbSDavid Sterba 	const char	driver[12];
39af024ed2SJohannes Thumshirn } btrfs_csums[] = {
40af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
413951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
423831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
43352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
44352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
45af024ed2SJohannes Thumshirn };
46af024ed2SJohannes Thumshirn 
47af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
48af024ed2SJohannes Thumshirn {
49af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
50af024ed2SJohannes Thumshirn 	/*
51af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
52af024ed2SJohannes Thumshirn 	 */
53af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
54af024ed2SJohannes Thumshirn }
55af024ed2SJohannes Thumshirn 
56af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
57af024ed2SJohannes Thumshirn {
58af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
59af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
60af024ed2SJohannes Thumshirn }
61af024ed2SJohannes Thumshirn 
62b4e967beSDavid Sterba /*
63b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
64b4e967beSDavid Sterba  * name
65b4e967beSDavid Sterba  */
66b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
67b4e967beSDavid Sterba {
68b4e967beSDavid Sterba 	/* csum type is validated at mount time */
6959a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
7059a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
71b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
72b4e967beSDavid Sterba }
73b4e967beSDavid Sterba 
74604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
75f7cea56cSDavid Sterba {
76f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
77f7cea56cSDavid Sterba }
78f7cea56cSDavid Sterba 
792c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
802c90e5d6SChris Mason {
81e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
822c90e5d6SChris Mason }
832c90e5d6SChris Mason 
84d352ac68SChris Mason /* this also releases the path */
852c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
862c90e5d6SChris Mason {
87ff175d57SJesper Juhl 	if (!p)
88ff175d57SJesper Juhl 		return;
89b3b4aa74SDavid Sterba 	btrfs_release_path(p);
902c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
912c90e5d6SChris Mason }
922c90e5d6SChris Mason 
93d352ac68SChris Mason /*
94d352ac68SChris Mason  * path release drops references on the extent buffers in the path
95d352ac68SChris Mason  * and it drops any locks held by this path
96d352ac68SChris Mason  *
97d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
98d352ac68SChris Mason  */
99b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
100eb60ceacSChris Mason {
101eb60ceacSChris Mason 	int i;
102a2135011SChris Mason 
103234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1043f157a2fSChris Mason 		p->slots[i] = 0;
105eb60ceacSChris Mason 		if (!p->nodes[i])
106925baeddSChris Mason 			continue;
107925baeddSChris Mason 		if (p->locks[i]) {
108bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
109925baeddSChris Mason 			p->locks[i] = 0;
110925baeddSChris Mason 		}
1115f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1123f157a2fSChris Mason 		p->nodes[i] = NULL;
113eb60ceacSChris Mason 	}
114eb60ceacSChris Mason }
115eb60ceacSChris Mason 
116d352ac68SChris Mason /*
117d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
118d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
119d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
120d352ac68SChris Mason  * looping required.
121d352ac68SChris Mason  *
122d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
123d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
124d352ac68SChris Mason  * at any time because there are no locks held.
125d352ac68SChris Mason  */
126925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
127925baeddSChris Mason {
128925baeddSChris Mason 	struct extent_buffer *eb;
129240f62c8SChris Mason 
1303083ee2eSJosef Bacik 	while (1) {
131240f62c8SChris Mason 		rcu_read_lock();
132240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1333083ee2eSJosef Bacik 
1343083ee2eSJosef Bacik 		/*
1353083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
13601327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1373083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1383083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1393083ee2eSJosef Bacik 		 */
1403083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
141240f62c8SChris Mason 			rcu_read_unlock();
1423083ee2eSJosef Bacik 			break;
1433083ee2eSJosef Bacik 		}
1443083ee2eSJosef Bacik 		rcu_read_unlock();
1453083ee2eSJosef Bacik 		synchronize_rcu();
1463083ee2eSJosef Bacik 	}
147925baeddSChris Mason 	return eb;
148925baeddSChris Mason }
149925baeddSChris Mason 
15092a7cc42SQu Wenruo /*
15192a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
15292a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
15392a7cc42SQu Wenruo  * sure they get properly updated on disk.
154d352ac68SChris Mason  */
1550b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1560b86a832SChris Mason {
1570b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1580b246afaSJeff Mahoney 
159e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
160e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
161e7070be1SJosef Bacik 		return;
162e7070be1SJosef Bacik 
1630b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
164e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
165e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
1664fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
167e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
1680b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
169e7070be1SJosef Bacik 		else
170e7070be1SJosef Bacik 			list_move(&root->dirty_list,
1710b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
1720b86a832SChris Mason 	}
1730b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1740b86a832SChris Mason }
1750b86a832SChris Mason 
176d352ac68SChris Mason /*
177d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
178d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
179d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
180d352ac68SChris Mason  */
181be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
182be20aa9dSChris Mason 		      struct btrfs_root *root,
183be20aa9dSChris Mason 		      struct extent_buffer *buf,
184be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
185be20aa9dSChris Mason {
1860b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
187be20aa9dSChris Mason 	struct extent_buffer *cow;
188be20aa9dSChris Mason 	int ret = 0;
189be20aa9dSChris Mason 	int level;
1905d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
191be20aa9dSChris Mason 
19292a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
1930b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
19492a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
19527cdeb70SMiao Xie 		trans->transid != root->last_trans);
196be20aa9dSChris Mason 
197be20aa9dSChris Mason 	level = btrfs_header_level(buf);
1985d4f98a2SYan Zheng 	if (level == 0)
1995d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2005d4f98a2SYan Zheng 	else
2015d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
20231840ae1SZheng Yan 
2034d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
204cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
205cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
2065d4f98a2SYan Zheng 	if (IS_ERR(cow))
207be20aa9dSChris Mason 		return PTR_ERR(cow);
208be20aa9dSChris Mason 
20958e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
210be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
211be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2125d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2135d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2145d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2155d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2165d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2175d4f98a2SYan Zheng 	else
218be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
219be20aa9dSChris Mason 
220de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2212b82032cSYan Zheng 
222be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2235d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
224e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2255d4f98a2SYan Zheng 	else
226e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
227867ed321SJosef Bacik 	if (ret) {
22872c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
22972c9925fSFilipe Manana 		free_extent_buffer(cow);
230867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
231be20aa9dSChris Mason 		return ret;
232867ed321SJosef Bacik 	}
233be20aa9dSChris Mason 
234be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
235be20aa9dSChris Mason 	*cow_ret = cow;
236be20aa9dSChris Mason 	return 0;
237be20aa9dSChris Mason }
238be20aa9dSChris Mason 
239d352ac68SChris Mason /*
2405d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
2415d4f98a2SYan Zheng  */
2425d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
2435d4f98a2SYan Zheng 			      struct extent_buffer *buf)
2445d4f98a2SYan Zheng {
2455d4f98a2SYan Zheng 	/*
24692a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
24792a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
24892a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
2495d4f98a2SYan Zheng 	 */
25092a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2515d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
2525d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
2535d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
2545d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
2555d4f98a2SYan Zheng 		return 1;
256a79865c6SNikolay Borisov 
2575d4f98a2SYan Zheng 	return 0;
2585d4f98a2SYan Zheng }
2595d4f98a2SYan Zheng 
2605d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
2615d4f98a2SYan Zheng 				       struct btrfs_root *root,
2625d4f98a2SYan Zheng 				       struct extent_buffer *buf,
263f0486c68SYan, Zheng 				       struct extent_buffer *cow,
264f0486c68SYan, Zheng 				       int *last_ref)
2655d4f98a2SYan Zheng {
2660b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2675d4f98a2SYan Zheng 	u64 refs;
2685d4f98a2SYan Zheng 	u64 owner;
2695d4f98a2SYan Zheng 	u64 flags;
2705d4f98a2SYan Zheng 	u64 new_flags = 0;
2715d4f98a2SYan Zheng 	int ret;
2725d4f98a2SYan Zheng 
2735d4f98a2SYan Zheng 	/*
2745d4f98a2SYan Zheng 	 * Backrefs update rules:
2755d4f98a2SYan Zheng 	 *
2765d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
2775d4f98a2SYan Zheng 	 * allocated by tree relocation.
2785d4f98a2SYan Zheng 	 *
2795d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
2805d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
2815d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
2825d4f98a2SYan Zheng 	 *
2835d4f98a2SYan Zheng 	 * If a tree block is been relocating
2845d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
2855d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
2865d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
2875d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
2885d4f98a2SYan Zheng 	 */
2895d4f98a2SYan Zheng 
2905d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
2912ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
2923173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
2933173a18fSJosef Bacik 					       &refs, &flags);
294be1a5564SMark Fasheh 		if (ret)
295be1a5564SMark Fasheh 			return ret;
296e5df9573SMark Fasheh 		if (refs == 0) {
297e5df9573SMark Fasheh 			ret = -EROFS;
2980b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
299e5df9573SMark Fasheh 			return ret;
300e5df9573SMark Fasheh 		}
3015d4f98a2SYan Zheng 	} else {
3025d4f98a2SYan Zheng 		refs = 1;
3035d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
3045d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
3055d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
3065d4f98a2SYan Zheng 		else
3075d4f98a2SYan Zheng 			flags = 0;
3085d4f98a2SYan Zheng 	}
3095d4f98a2SYan Zheng 
3105d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
3115d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
3125d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
3135d4f98a2SYan Zheng 
3145d4f98a2SYan Zheng 	if (refs > 1) {
3155d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
3165d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
3175d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
318e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
319692826b2SJeff Mahoney 			if (ret)
320692826b2SJeff Mahoney 				return ret;
3215d4f98a2SYan Zheng 
3225d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3235d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
324e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
325692826b2SJeff Mahoney 				if (ret)
326692826b2SJeff Mahoney 					return ret;
327e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
328692826b2SJeff Mahoney 				if (ret)
329692826b2SJeff Mahoney 					return ret;
3305d4f98a2SYan Zheng 			}
3315d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
3325d4f98a2SYan Zheng 		} else {
3335d4f98a2SYan Zheng 
3345d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3355d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
336e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3375d4f98a2SYan Zheng 			else
338e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
339692826b2SJeff Mahoney 			if (ret)
340692826b2SJeff Mahoney 				return ret;
3415d4f98a2SYan Zheng 		}
3425d4f98a2SYan Zheng 		if (new_flags != 0) {
343b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
344b1c79e09SJosef Bacik 
34542c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
3462fe6a5a1SDavid Sterba 							  new_flags, level);
347be1a5564SMark Fasheh 			if (ret)
348be1a5564SMark Fasheh 				return ret;
3495d4f98a2SYan Zheng 		}
3505d4f98a2SYan Zheng 	} else {
3515d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
3525d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3535d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
354e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3555d4f98a2SYan Zheng 			else
356e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
357692826b2SJeff Mahoney 			if (ret)
358692826b2SJeff Mahoney 				return ret;
359e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
360692826b2SJeff Mahoney 			if (ret)
361692826b2SJeff Mahoney 				return ret;
3625d4f98a2SYan Zheng 		}
3636a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
364f0486c68SYan, Zheng 		*last_ref = 1;
3655d4f98a2SYan Zheng 	}
3665d4f98a2SYan Zheng 	return 0;
3675d4f98a2SYan Zheng }
3685d4f98a2SYan Zheng 
3695d4f98a2SYan Zheng /*
370d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
371d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
372d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
373d397712bSChris Mason  * dirty again.
374d352ac68SChris Mason  *
375d352ac68SChris Mason  * search_start -- an allocation hint for the new block
376d352ac68SChris Mason  *
377d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
378d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
379d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
380d352ac68SChris Mason  */
381d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
3825f39d397SChris Mason 			     struct btrfs_root *root,
3835f39d397SChris Mason 			     struct extent_buffer *buf,
3845f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
3855f39d397SChris Mason 			     struct extent_buffer **cow_ret,
3869631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
3879631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
3886702ed49SChris Mason {
3890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3905d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
3915f39d397SChris Mason 	struct extent_buffer *cow;
392be1a5564SMark Fasheh 	int level, ret;
393f0486c68SYan, Zheng 	int last_ref = 0;
394925baeddSChris Mason 	int unlock_orig = 0;
3950f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
3966702ed49SChris Mason 
397925baeddSChris Mason 	if (*cow_ret == buf)
398925baeddSChris Mason 		unlock_orig = 1;
399925baeddSChris Mason 
40049d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
401925baeddSChris Mason 
40292a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
4030b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
40492a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
40527cdeb70SMiao Xie 		trans->transid != root->last_trans);
4065f39d397SChris Mason 
4077bb86316SChris Mason 	level = btrfs_header_level(buf);
40831840ae1SZheng Yan 
4095d4f98a2SYan Zheng 	if (level == 0)
4105d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
4115d4f98a2SYan Zheng 	else
4125d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
4135d4f98a2SYan Zheng 
4140f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
4155d4f98a2SYan Zheng 		parent_start = parent->start;
4165d4f98a2SYan Zheng 
41779bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
41879bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
41979bd3712SFilipe Manana 				     search_start, empty_size, nest);
4206702ed49SChris Mason 	if (IS_ERR(cow))
4216702ed49SChris Mason 		return PTR_ERR(cow);
4226702ed49SChris Mason 
423b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
424b4ce94deSChris Mason 
42558e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
426db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
4275f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
4285d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
4295d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
4305d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
4315d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
4325d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
4335d4f98a2SYan Zheng 	else
4345f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
4356702ed49SChris Mason 
436de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
4372b82032cSYan Zheng 
438be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
439b68dc2a9SMark Fasheh 	if (ret) {
440572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
441572c83acSJosef Bacik 		free_extent_buffer(cow);
44266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
443b68dc2a9SMark Fasheh 		return ret;
444b68dc2a9SMark Fasheh 	}
4451a40e23bSZheng Yan 
44692a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
44783d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
44893314e3bSZhaolei 		if (ret) {
449572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
450572c83acSJosef Bacik 			free_extent_buffer(cow);
45166642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
45283d4cfd4SJosef Bacik 			return ret;
45383d4cfd4SJosef Bacik 		}
45493314e3bSZhaolei 	}
4553fd0a558SYan, Zheng 
4566702ed49SChris Mason 	if (buf == root->node) {
457925baeddSChris Mason 		WARN_ON(parent && parent != buf);
4585d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4595d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4605d4f98a2SYan Zheng 			parent_start = buf->start;
461925baeddSChris Mason 
46267439dadSDavid Sterba 		atomic_inc(&cow->refs);
463406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
464d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
465240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
466925baeddSChris Mason 
4677a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
4687a163608SFilipe Manana 				      parent_start, last_ref);
4695f39d397SChris Mason 		free_extent_buffer(buf);
4700b86a832SChris Mason 		add_root_to_dirty_list(root);
4716702ed49SChris Mason 	} else {
4725d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
473f3a84ccdSFilipe Manana 		btrfs_tree_mod_log_insert_key(parent, parent_slot,
474f3a84ccdSFilipe Manana 					      BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
4755f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
476db94535dSChris Mason 					cow->start);
47774493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
47874493f7aSChris Mason 					      trans->transid);
4796702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
4805de865eeSFilipe David Borba Manana 		if (last_ref) {
481f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
4825de865eeSFilipe David Borba Manana 			if (ret) {
483572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
484572c83acSJosef Bacik 				free_extent_buffer(cow);
48566642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
4865de865eeSFilipe David Borba Manana 				return ret;
4875de865eeSFilipe David Borba Manana 			}
4885de865eeSFilipe David Borba Manana 		}
4897a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
4907a163608SFilipe Manana 				      parent_start, last_ref);
4916702ed49SChris Mason 	}
492925baeddSChris Mason 	if (unlock_orig)
493925baeddSChris Mason 		btrfs_tree_unlock(buf);
4943083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
4956702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
4966702ed49SChris Mason 	*cow_ret = cow;
4976702ed49SChris Mason 	return 0;
4986702ed49SChris Mason }
4996702ed49SChris Mason 
5005d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
5015d4f98a2SYan Zheng 				   struct btrfs_root *root,
5025d4f98a2SYan Zheng 				   struct extent_buffer *buf)
5035d4f98a2SYan Zheng {
504f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
505faa2dbf0SJosef Bacik 		return 0;
506fccb84c9SDavid Sterba 
507d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
508d1980131SDavid Sterba 	smp_mb__before_atomic();
509f1ebcc74SLiu Bo 
510f1ebcc74SLiu Bo 	/*
511f1ebcc74SLiu Bo 	 * We do not need to cow a block if
512f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
513f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
514f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
515f1ebcc74SLiu Bo 	 *
516f1ebcc74SLiu Bo 	 * What is forced COW:
51701327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
51852042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
519f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
520f1ebcc74SLiu Bo 	 */
5215d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
5225d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
5235d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
524f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
52527cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
5265d4f98a2SYan Zheng 		return 0;
5275d4f98a2SYan Zheng 	return 1;
5285d4f98a2SYan Zheng }
5295d4f98a2SYan Zheng 
530d352ac68SChris Mason /*
531d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
53201327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
533d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
534d352ac68SChris Mason  */
535d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
5365f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
5375f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
5389631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
5399631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
54002217ed2SChris Mason {
5410b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5426702ed49SChris Mason 	u64 search_start;
543f510cfecSChris Mason 	int ret;
544dc17ff8fSChris Mason 
54583354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
54683354f07SJosef Bacik 		btrfs_err(fs_info,
54783354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
54883354f07SJosef Bacik 
5490b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
55031b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
551c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
5520b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
55331b1a2bdSJulia Lawall 
5540b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
55531b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
5560b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
557dc17ff8fSChris Mason 
5585d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
55902217ed2SChris Mason 		*cow_ret = buf;
56002217ed2SChris Mason 		return 0;
56102217ed2SChris Mason 	}
562c487685dSChris Mason 
563ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
564b4ce94deSChris Mason 
565f616f5cdSQu Wenruo 	/*
566f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
567f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
568f616f5cdSQu Wenruo 	 *
569f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
570f616f5cdSQu Wenruo 	 */
571f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
572f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
5739631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
5741abe9b8aSliubo 
5751abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
5761abe9b8aSliubo 
577f510cfecSChris Mason 	return ret;
5782c90e5d6SChris Mason }
579f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
5806702ed49SChris Mason 
581d352ac68SChris Mason /*
582d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
583d352ac68SChris Mason  * node are actually close by
584d352ac68SChris Mason  */
5856b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
5866702ed49SChris Mason {
5876b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
5886702ed49SChris Mason 		return 1;
5896b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
5906702ed49SChris Mason 		return 1;
59102217ed2SChris Mason 	return 0;
59202217ed2SChris Mason }
59302217ed2SChris Mason 
594ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
595ce6ef5abSDavid Sterba 
596ce6ef5abSDavid Sterba /*
597ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
598ce6ef5abSDavid Sterba  * we can avoid the conversion.
599ce6ef5abSDavid Sterba  */
600ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
601ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
602ce6ef5abSDavid Sterba {
603ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
604ce6ef5abSDavid Sterba 
605ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
606ce6ef5abSDavid Sterba }
607ce6ef5abSDavid Sterba 
608ce6ef5abSDavid Sterba #else
609ce6ef5abSDavid Sterba 
610081e9573SChris Mason /*
611081e9573SChris Mason  * compare two keys in a memcmp fashion
612081e9573SChris Mason  */
613310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
614310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
615081e9573SChris Mason {
616081e9573SChris Mason 	struct btrfs_key k1;
617081e9573SChris Mason 
618081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
619081e9573SChris Mason 
62020736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
621081e9573SChris Mason }
622ce6ef5abSDavid Sterba #endif
623081e9573SChris Mason 
624f3465ca4SJosef Bacik /*
625f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
626f3465ca4SJosef Bacik  */
627e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
628f3465ca4SJosef Bacik {
629f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
630f3465ca4SJosef Bacik 		return 1;
631f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
632f3465ca4SJosef Bacik 		return -1;
633f3465ca4SJosef Bacik 	if (k1->type > k2->type)
634f3465ca4SJosef Bacik 		return 1;
635f3465ca4SJosef Bacik 	if (k1->type < k2->type)
636f3465ca4SJosef Bacik 		return -1;
637f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
638f3465ca4SJosef Bacik 		return 1;
639f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
640f3465ca4SJosef Bacik 		return -1;
641f3465ca4SJosef Bacik 	return 0;
642f3465ca4SJosef Bacik }
643081e9573SChris Mason 
644d352ac68SChris Mason /*
645d352ac68SChris Mason  * this is used by the defrag code to go through all the
646d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
647d352ac68SChris Mason  * disk order is close to key order
648d352ac68SChris Mason  */
6496702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
6505f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
651de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
652a6b6e75eSChris Mason 		       struct btrfs_key *progress)
6536702ed49SChris Mason {
6540b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6556b80053dSChris Mason 	struct extent_buffer *cur;
6566702ed49SChris Mason 	u64 blocknr;
657e9d0b13bSChris Mason 	u64 search_start = *last_ret;
658e9d0b13bSChris Mason 	u64 last_block = 0;
6596702ed49SChris Mason 	u64 other;
6606702ed49SChris Mason 	u32 parent_nritems;
6616702ed49SChris Mason 	int end_slot;
6626702ed49SChris Mason 	int i;
6636702ed49SChris Mason 	int err = 0;
6646b80053dSChris Mason 	u32 blocksize;
665081e9573SChris Mason 	int progress_passed = 0;
666081e9573SChris Mason 	struct btrfs_disk_key disk_key;
6676702ed49SChris Mason 
6680b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
6690b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
67086479a04SChris Mason 
6716b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
6720b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
6735dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
6746702ed49SChris Mason 
6755dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
6766702ed49SChris Mason 		return 0;
6776702ed49SChris Mason 
6785dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
6796702ed49SChris Mason 		int close = 1;
680a6b6e75eSChris Mason 
681081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
682081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
683081e9573SChris Mason 			continue;
684081e9573SChris Mason 
685081e9573SChris Mason 		progress_passed = 1;
6866b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
687e9d0b13bSChris Mason 		if (last_block == 0)
688e9d0b13bSChris Mason 			last_block = blocknr;
6895708b959SChris Mason 
6906702ed49SChris Mason 		if (i > 0) {
6916b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
6926b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
6936702ed49SChris Mason 		}
6945dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
6956b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
6966b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
6976702ed49SChris Mason 		}
698e9d0b13bSChris Mason 		if (close) {
699e9d0b13bSChris Mason 			last_block = blocknr;
7006702ed49SChris Mason 			continue;
701e9d0b13bSChris Mason 		}
7026702ed49SChris Mason 
703206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
704206983b7SJosef Bacik 		if (IS_ERR(cur))
70564c043deSLiu Bo 			return PTR_ERR(cur);
706e9d0b13bSChris Mason 		if (search_start == 0)
7076b80053dSChris Mason 			search_start = last_block;
708e9d0b13bSChris Mason 
709e7a84565SChris Mason 		btrfs_tree_lock(cur);
7106b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
711e7a84565SChris Mason 					&cur, search_start,
7126b80053dSChris Mason 					min(16 * blocksize,
7139631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
7149631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
715252c38f0SYan 		if (err) {
716e7a84565SChris Mason 			btrfs_tree_unlock(cur);
7176b80053dSChris Mason 			free_extent_buffer(cur);
7186702ed49SChris Mason 			break;
719252c38f0SYan 		}
720e7a84565SChris Mason 		search_start = cur->start;
721e7a84565SChris Mason 		last_block = cur->start;
722f2183bdeSChris Mason 		*last_ret = search_start;
723e7a84565SChris Mason 		btrfs_tree_unlock(cur);
724e7a84565SChris Mason 		free_extent_buffer(cur);
7256702ed49SChris Mason 	}
7266702ed49SChris Mason 	return err;
7276702ed49SChris Mason }
7286702ed49SChris Mason 
72974123bd7SChris Mason /*
730fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
7315f39d397SChris Mason  *
732fb81212cSFilipe Manana  * The lower boundary for the search is specified by the slot number @low. Use a
733fb81212cSFilipe Manana  * value of 0 to search over the whole extent buffer.
73474123bd7SChris Mason  *
735fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
736fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
737fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
738fb81212cSFilipe Manana  *
739fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
740fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
74174123bd7SChris Mason  */
742fb81212cSFilipe Manana static noinline int generic_bin_search(struct extent_buffer *eb, int low,
74367d5e289SMarcos Paulo de Souza 				       const struct btrfs_key *key, int *slot)
744be0e5c09SChris Mason {
745fb81212cSFilipe Manana 	unsigned long p;
746fb81212cSFilipe Manana 	int item_size;
74767d5e289SMarcos Paulo de Souza 	int high = btrfs_header_nritems(eb);
748be0e5c09SChris Mason 	int ret;
7495cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
750be0e5c09SChris Mason 
7515e24e9afSLiu Bo 	if (low > high) {
7525e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
7535e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
7545e24e9afSLiu Bo 			  __func__, low, high, eb->start,
7555e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
7565e24e9afSLiu Bo 		return -EINVAL;
7575e24e9afSLiu Bo 	}
7585e24e9afSLiu Bo 
759fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
760fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
761fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
762fb81212cSFilipe Manana 	} else {
763fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
764fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
765fb81212cSFilipe Manana 	}
766fb81212cSFilipe Manana 
767be0e5c09SChris Mason 	while (low < high) {
7685cd17f34SDavid Sterba 		unsigned long oip;
7695cd17f34SDavid Sterba 		unsigned long offset;
7705cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
7715cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
7725cd17f34SDavid Sterba 		int mid;
7735cd17f34SDavid Sterba 
774be0e5c09SChris Mason 		mid = (low + high) / 2;
7755f39d397SChris Mason 		offset = p + mid * item_size;
7765cd17f34SDavid Sterba 		oip = offset_in_page(offset);
7775f39d397SChris Mason 
7785cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
779884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
7805cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
781934d375bSChris Mason 
782884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
7835cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
7845cd17f34SDavid Sterba 		} else {
7855cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
7865f39d397SChris Mason 			tmp = &unaligned;
787479965d6SChris Mason 		}
788479965d6SChris Mason 
789be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
790be0e5c09SChris Mason 
791be0e5c09SChris Mason 		if (ret < 0)
792be0e5c09SChris Mason 			low = mid + 1;
793be0e5c09SChris Mason 		else if (ret > 0)
794be0e5c09SChris Mason 			high = mid;
795be0e5c09SChris Mason 		else {
796be0e5c09SChris Mason 			*slot = mid;
797be0e5c09SChris Mason 			return 0;
798be0e5c09SChris Mason 		}
799be0e5c09SChris Mason 	}
800be0e5c09SChris Mason 	*slot = low;
801be0e5c09SChris Mason 	return 1;
802be0e5c09SChris Mason }
803be0e5c09SChris Mason 
80497571fd0SChris Mason /*
805fb81212cSFilipe Manana  * Simple binary search on an extent buffer. Works for both leaves and nodes, and
806fb81212cSFilipe Manana  * always searches over the whole range of keys (slot 0 to slot 'nritems - 1').
80797571fd0SChris Mason  */
808a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
809e3b83361SQu Wenruo 		     int *slot)
810be0e5c09SChris Mason {
811fb81212cSFilipe Manana 	return generic_bin_search(eb, 0, key, slot);
812be0e5c09SChris Mason }
813be0e5c09SChris Mason 
814f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
815f0486c68SYan, Zheng {
816f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
817f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
818f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
819f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
820f0486c68SYan, Zheng }
821f0486c68SYan, Zheng 
822f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
823f0486c68SYan, Zheng {
824f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
825f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
826f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
827f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
828f0486c68SYan, Zheng }
829f0486c68SYan, Zheng 
830d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
831d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
832d352ac68SChris Mason  */
8334b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
8344b231ae4SDavid Sterba 					   int slot)
835bb803951SChris Mason {
836ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
837416bc658SJosef Bacik 	struct extent_buffer *eb;
838581c1760SQu Wenruo 	struct btrfs_key first_key;
839416bc658SJosef Bacik 
840fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
841fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
842ca7a79adSChris Mason 
843ca7a79adSChris Mason 	BUG_ON(level == 0);
844ca7a79adSChris Mason 
845581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
846d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
8471b7ec85eSJosef Bacik 			     btrfs_header_owner(parent),
848581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
849581c1760SQu Wenruo 			     level - 1, &first_key);
8504eb150d6SQu Wenruo 	if (IS_ERR(eb))
8514eb150d6SQu Wenruo 		return eb;
8524eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
853416bc658SJosef Bacik 		free_extent_buffer(eb);
8544eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
855416bc658SJosef Bacik 	}
856416bc658SJosef Bacik 
857416bc658SJosef Bacik 	return eb;
858bb803951SChris Mason }
859bb803951SChris Mason 
860d352ac68SChris Mason /*
861d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
862d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
863d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
864d352ac68SChris Mason  */
865e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
86698ed5174SChris Mason 			 struct btrfs_root *root,
86798ed5174SChris Mason 			 struct btrfs_path *path, int level)
868bb803951SChris Mason {
8690b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8705f39d397SChris Mason 	struct extent_buffer *right = NULL;
8715f39d397SChris Mason 	struct extent_buffer *mid;
8725f39d397SChris Mason 	struct extent_buffer *left = NULL;
8735f39d397SChris Mason 	struct extent_buffer *parent = NULL;
874bb803951SChris Mason 	int ret = 0;
875bb803951SChris Mason 	int wret;
876bb803951SChris Mason 	int pslot;
877bb803951SChris Mason 	int orig_slot = path->slots[level];
87879f95c82SChris Mason 	u64 orig_ptr;
879bb803951SChris Mason 
88098e6b1ebSLiu Bo 	ASSERT(level > 0);
881bb803951SChris Mason 
8825f39d397SChris Mason 	mid = path->nodes[level];
883b4ce94deSChris Mason 
884ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
8857bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
8867bb86316SChris Mason 
8871d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
88879f95c82SChris Mason 
889a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
8905f39d397SChris Mason 		parent = path->nodes[level + 1];
891bb803951SChris Mason 		pslot = path->slots[level + 1];
892a05a9bb1SLi Zefan 	}
893bb803951SChris Mason 
89440689478SChris Mason 	/*
89540689478SChris Mason 	 * deal with the case where there is only one pointer in the root
89640689478SChris Mason 	 * by promoting the node below to a root
89740689478SChris Mason 	 */
8985f39d397SChris Mason 	if (!parent) {
8995f39d397SChris Mason 		struct extent_buffer *child;
900bb803951SChris Mason 
9015f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
902bb803951SChris Mason 			return 0;
903bb803951SChris Mason 
904bb803951SChris Mason 		/* promote the child to a root */
9054b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
906fb770ae4SLiu Bo 		if (IS_ERR(child)) {
907fb770ae4SLiu Bo 			ret = PTR_ERR(child);
9080b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
909305a26afSMark Fasheh 			goto enospc;
910305a26afSMark Fasheh 		}
911305a26afSMark Fasheh 
912925baeddSChris Mason 		btrfs_tree_lock(child);
9139631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
9149631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
915f0486c68SYan, Zheng 		if (ret) {
916f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
917f0486c68SYan, Zheng 			free_extent_buffer(child);
918f0486c68SYan, Zheng 			goto enospc;
919f0486c68SYan, Zheng 		}
9202f375ab9SYan 
921406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
922d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
923240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
924925baeddSChris Mason 
9250b86a832SChris Mason 		add_root_to_dirty_list(root);
926925baeddSChris Mason 		btrfs_tree_unlock(child);
927b4ce94deSChris Mason 
928925baeddSChris Mason 		path->locks[level] = 0;
929bb803951SChris Mason 		path->nodes[level] = NULL;
9306a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
931925baeddSChris Mason 		btrfs_tree_unlock(mid);
932bb803951SChris Mason 		/* once for the path */
9335f39d397SChris Mason 		free_extent_buffer(mid);
934f0486c68SYan, Zheng 
935f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
9367a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
937bb803951SChris Mason 		/* once for the root ptr */
9383083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
939f0486c68SYan, Zheng 		return 0;
940bb803951SChris Mason 	}
9415f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
9420b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
943bb803951SChris Mason 		return 0;
944bb803951SChris Mason 
9454b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
946fb770ae4SLiu Bo 	if (IS_ERR(left))
947fb770ae4SLiu Bo 		left = NULL;
948fb770ae4SLiu Bo 
9495f39d397SChris Mason 	if (left) {
950bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
9515f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
9529631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
953bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
95454aa1f4dSChris Mason 		if (wret) {
95554aa1f4dSChris Mason 			ret = wret;
95654aa1f4dSChris Mason 			goto enospc;
95754aa1f4dSChris Mason 		}
9582cc58cf2SChris Mason 	}
959fb770ae4SLiu Bo 
9604b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
961fb770ae4SLiu Bo 	if (IS_ERR(right))
962fb770ae4SLiu Bo 		right = NULL;
963fb770ae4SLiu Bo 
9645f39d397SChris Mason 	if (right) {
965bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
9665f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
9679631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
968bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
9692cc58cf2SChris Mason 		if (wret) {
9702cc58cf2SChris Mason 			ret = wret;
9712cc58cf2SChris Mason 			goto enospc;
9722cc58cf2SChris Mason 		}
9732cc58cf2SChris Mason 	}
9742cc58cf2SChris Mason 
9752cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
9765f39d397SChris Mason 	if (left) {
9775f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
978d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
97979f95c82SChris Mason 		if (wret < 0)
98079f95c82SChris Mason 			ret = wret;
981bb803951SChris Mason 	}
98279f95c82SChris Mason 
98379f95c82SChris Mason 	/*
98479f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
98579f95c82SChris Mason 	 */
9865f39d397SChris Mason 	if (right) {
987d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
98854aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
98979f95c82SChris Mason 			ret = wret;
9905f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
9916a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
992925baeddSChris Mason 			btrfs_tree_unlock(right);
993afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
994f0486c68SYan, Zheng 			root_sub_used(root, right->len);
9957a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
9967a163608SFilipe Manana 					      0, 1);
9973083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
998f0486c68SYan, Zheng 			right = NULL;
999bb803951SChris Mason 		} else {
10005f39d397SChris Mason 			struct btrfs_disk_key right_key;
10015f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1002f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1003f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
10040e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
10055f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
10065f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1007bb803951SChris Mason 		}
1008bb803951SChris Mason 	}
10095f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
101079f95c82SChris Mason 		/*
101179f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
101279f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
101379f95c82SChris Mason 		 * could try to delete the only pointer in this node.
101479f95c82SChris Mason 		 * So, pull some keys from the left.
101579f95c82SChris Mason 		 * There has to be a left pointer at this point because
101679f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
101779f95c82SChris Mason 		 * right
101879f95c82SChris Mason 		 */
1019305a26afSMark Fasheh 		if (!left) {
1020305a26afSMark Fasheh 			ret = -EROFS;
10210b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1022305a26afSMark Fasheh 			goto enospc;
1023305a26afSMark Fasheh 		}
102455d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
102554aa1f4dSChris Mason 		if (wret < 0) {
102679f95c82SChris Mason 			ret = wret;
102754aa1f4dSChris Mason 			goto enospc;
102854aa1f4dSChris Mason 		}
1029bce4eae9SChris Mason 		if (wret == 1) {
1030d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1031bce4eae9SChris Mason 			if (wret < 0)
1032bce4eae9SChris Mason 				ret = wret;
1033bce4eae9SChris Mason 		}
103479f95c82SChris Mason 		BUG_ON(wret == 1);
103579f95c82SChris Mason 	}
10365f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
10376a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1038925baeddSChris Mason 		btrfs_tree_unlock(mid);
1039afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1040f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10417a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
10423083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1043f0486c68SYan, Zheng 		mid = NULL;
104479f95c82SChris Mason 	} else {
104579f95c82SChris Mason 		/* update the parent key to reflect our changes */
10465f39d397SChris Mason 		struct btrfs_disk_key mid_key;
10475f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1048f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1049f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
10500e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
10515f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
10525f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
105379f95c82SChris Mason 	}
1054bb803951SChris Mason 
105579f95c82SChris Mason 	/* update the path */
10565f39d397SChris Mason 	if (left) {
10575f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
105867439dadSDavid Sterba 			atomic_inc(&left->refs);
1059925baeddSChris Mason 			/* left was locked after cow */
10605f39d397SChris Mason 			path->nodes[level] = left;
1061bb803951SChris Mason 			path->slots[level + 1] -= 1;
1062bb803951SChris Mason 			path->slots[level] = orig_slot;
1063925baeddSChris Mason 			if (mid) {
1064925baeddSChris Mason 				btrfs_tree_unlock(mid);
10655f39d397SChris Mason 				free_extent_buffer(mid);
1066925baeddSChris Mason 			}
1067bb803951SChris Mason 		} else {
10685f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1069bb803951SChris Mason 			path->slots[level] = orig_slot;
1070bb803951SChris Mason 		}
1071bb803951SChris Mason 	}
107279f95c82SChris Mason 	/* double check we haven't messed things up */
1073e20d96d6SChris Mason 	if (orig_ptr !=
10745f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
107579f95c82SChris Mason 		BUG();
107654aa1f4dSChris Mason enospc:
1077925baeddSChris Mason 	if (right) {
1078925baeddSChris Mason 		btrfs_tree_unlock(right);
10795f39d397SChris Mason 		free_extent_buffer(right);
1080925baeddSChris Mason 	}
1081925baeddSChris Mason 	if (left) {
1082925baeddSChris Mason 		if (path->nodes[level] != left)
1083925baeddSChris Mason 			btrfs_tree_unlock(left);
10845f39d397SChris Mason 		free_extent_buffer(left);
1085925baeddSChris Mason 	}
1086bb803951SChris Mason 	return ret;
1087bb803951SChris Mason }
1088bb803951SChris Mason 
1089d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1090d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1091d352ac68SChris Mason  * have to be pessimistic.
1092d352ac68SChris Mason  */
1093d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1094e66f709bSChris Mason 					  struct btrfs_root *root,
1095e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1096e66f709bSChris Mason {
10970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10985f39d397SChris Mason 	struct extent_buffer *right = NULL;
10995f39d397SChris Mason 	struct extent_buffer *mid;
11005f39d397SChris Mason 	struct extent_buffer *left = NULL;
11015f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1102e66f709bSChris Mason 	int ret = 0;
1103e66f709bSChris Mason 	int wret;
1104e66f709bSChris Mason 	int pslot;
1105e66f709bSChris Mason 	int orig_slot = path->slots[level];
1106e66f709bSChris Mason 
1107e66f709bSChris Mason 	if (level == 0)
1108e66f709bSChris Mason 		return 1;
1109e66f709bSChris Mason 
11105f39d397SChris Mason 	mid = path->nodes[level];
11117bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1112e66f709bSChris Mason 
1113a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
11145f39d397SChris Mason 		parent = path->nodes[level + 1];
1115e66f709bSChris Mason 		pslot = path->slots[level + 1];
1116a05a9bb1SLi Zefan 	}
1117e66f709bSChris Mason 
11185f39d397SChris Mason 	if (!parent)
1119e66f709bSChris Mason 		return 1;
1120e66f709bSChris Mason 
11214b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1122fb770ae4SLiu Bo 	if (IS_ERR(left))
1123fb770ae4SLiu Bo 		left = NULL;
1124e66f709bSChris Mason 
1125e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
11265f39d397SChris Mason 	if (left) {
1127e66f709bSChris Mason 		u32 left_nr;
1128925baeddSChris Mason 
1129bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1130b4ce94deSChris Mason 
11315f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
11320b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
113333ade1f8SChris Mason 			wret = 1;
113433ade1f8SChris Mason 		} else {
11355f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
11369631e4ccSJosef Bacik 					      pslot - 1, &left,
1137bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
113854aa1f4dSChris Mason 			if (ret)
113954aa1f4dSChris Mason 				wret = 1;
114054aa1f4dSChris Mason 			else {
1141d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
114254aa1f4dSChris Mason 			}
114333ade1f8SChris Mason 		}
1144e66f709bSChris Mason 		if (wret < 0)
1145e66f709bSChris Mason 			ret = wret;
1146e66f709bSChris Mason 		if (wret == 0) {
11475f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1148e66f709bSChris Mason 			orig_slot += left_nr;
11495f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1150f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1151f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
11520e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11535f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
11545f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
11555f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
11565f39d397SChris Mason 				path->nodes[level] = left;
1157e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1158e66f709bSChris Mason 				path->slots[level] = orig_slot;
1159925baeddSChris Mason 				btrfs_tree_unlock(mid);
11605f39d397SChris Mason 				free_extent_buffer(mid);
1161e66f709bSChris Mason 			} else {
1162e66f709bSChris Mason 				orig_slot -=
11635f39d397SChris Mason 					btrfs_header_nritems(left);
1164e66f709bSChris Mason 				path->slots[level] = orig_slot;
1165925baeddSChris Mason 				btrfs_tree_unlock(left);
11665f39d397SChris Mason 				free_extent_buffer(left);
1167e66f709bSChris Mason 			}
1168e66f709bSChris Mason 			return 0;
1169e66f709bSChris Mason 		}
1170925baeddSChris Mason 		btrfs_tree_unlock(left);
11715f39d397SChris Mason 		free_extent_buffer(left);
1172e66f709bSChris Mason 	}
11734b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1174fb770ae4SLiu Bo 	if (IS_ERR(right))
1175fb770ae4SLiu Bo 		right = NULL;
1176e66f709bSChris Mason 
1177e66f709bSChris Mason 	/*
1178e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1179e66f709bSChris Mason 	 */
11805f39d397SChris Mason 	if (right) {
118133ade1f8SChris Mason 		u32 right_nr;
1182b4ce94deSChris Mason 
1183bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1184b4ce94deSChris Mason 
11855f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
11860b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
118733ade1f8SChris Mason 			wret = 1;
118833ade1f8SChris Mason 		} else {
11895f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
11905f39d397SChris Mason 					      parent, pslot + 1,
1191bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
119254aa1f4dSChris Mason 			if (ret)
119354aa1f4dSChris Mason 				wret = 1;
119454aa1f4dSChris Mason 			else {
119555d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
119633ade1f8SChris Mason 			}
119754aa1f4dSChris Mason 		}
1198e66f709bSChris Mason 		if (wret < 0)
1199e66f709bSChris Mason 			ret = wret;
1200e66f709bSChris Mason 		if (wret == 0) {
12015f39d397SChris Mason 			struct btrfs_disk_key disk_key;
12025f39d397SChris Mason 
12035f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1204f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1205f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
12060e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
12075f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
12085f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12095f39d397SChris Mason 
12105f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
12115f39d397SChris Mason 				path->nodes[level] = right;
1212e66f709bSChris Mason 				path->slots[level + 1] += 1;
1213e66f709bSChris Mason 				path->slots[level] = orig_slot -
12145f39d397SChris Mason 					btrfs_header_nritems(mid);
1215925baeddSChris Mason 				btrfs_tree_unlock(mid);
12165f39d397SChris Mason 				free_extent_buffer(mid);
1217e66f709bSChris Mason 			} else {
1218925baeddSChris Mason 				btrfs_tree_unlock(right);
12195f39d397SChris Mason 				free_extent_buffer(right);
1220e66f709bSChris Mason 			}
1221e66f709bSChris Mason 			return 0;
1222e66f709bSChris Mason 		}
1223925baeddSChris Mason 		btrfs_tree_unlock(right);
12245f39d397SChris Mason 		free_extent_buffer(right);
1225e66f709bSChris Mason 	}
1226e66f709bSChris Mason 	return 1;
1227e66f709bSChris Mason }
1228e66f709bSChris Mason 
122974123bd7SChris Mason /*
1230d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1231d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
12323c69faecSChris Mason  */
12332ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1234e02119d5SChris Mason 			     struct btrfs_path *path,
123501f46658SChris Mason 			     int level, int slot, u64 objectid)
12363c69faecSChris Mason {
12375f39d397SChris Mason 	struct extent_buffer *node;
123801f46658SChris Mason 	struct btrfs_disk_key disk_key;
12393c69faecSChris Mason 	u32 nritems;
12403c69faecSChris Mason 	u64 search;
1241a7175319SChris Mason 	u64 target;
12426b80053dSChris Mason 	u64 nread = 0;
1243ace75066SFilipe Manana 	u64 nread_max;
12446b80053dSChris Mason 	u32 nr;
12456b80053dSChris Mason 	u32 blocksize;
12466b80053dSChris Mason 	u32 nscan = 0;
1247db94535dSChris Mason 
1248ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
12493c69faecSChris Mason 		return;
12503c69faecSChris Mason 
12516702ed49SChris Mason 	if (!path->nodes[level])
12526702ed49SChris Mason 		return;
12536702ed49SChris Mason 
12545f39d397SChris Mason 	node = path->nodes[level];
1255925baeddSChris Mason 
1256ace75066SFilipe Manana 	/*
1257ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1258ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1259ace75066SFilipe Manana 	 * much IO at once (possibly random).
1260ace75066SFilipe Manana 	 */
1261ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1262ace75066SFilipe Manana 		if (level > 1)
1263ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1264ace75066SFilipe Manana 		else
1265ace75066SFilipe Manana 			nread_max = SZ_128K;
1266ace75066SFilipe Manana 	} else {
1267ace75066SFilipe Manana 		nread_max = SZ_64K;
1268ace75066SFilipe Manana 	}
1269ace75066SFilipe Manana 
12703c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
12710b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1272069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1273069a2e37SFilipe Manana 		struct extent_buffer *eb;
1274069a2e37SFilipe Manana 
12750b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
12765f39d397SChris Mason 		if (eb) {
12775f39d397SChris Mason 			free_extent_buffer(eb);
12783c69faecSChris Mason 			return;
12793c69faecSChris Mason 		}
1280069a2e37SFilipe Manana 	}
12813c69faecSChris Mason 
1282a7175319SChris Mason 	target = search;
12836b80053dSChris Mason 
12845f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
12856b80053dSChris Mason 	nr = slot;
128625b8b936SJosef Bacik 
12873c69faecSChris Mason 	while (1) {
1288e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
12896b80053dSChris Mason 			if (nr == 0)
12903c69faecSChris Mason 				break;
12916b80053dSChris Mason 			nr--;
1292ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1293ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
12946b80053dSChris Mason 			nr++;
12956b80053dSChris Mason 			if (nr >= nritems)
12966b80053dSChris Mason 				break;
12973c69faecSChris Mason 		}
1298e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
129901f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
130001f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
130101f46658SChris Mason 				break;
130201f46658SChris Mason 		}
13036b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1304ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1305ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1306a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1307bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
13086b80053dSChris Mason 			nread += blocksize;
13093c69faecSChris Mason 		}
13106b80053dSChris Mason 		nscan++;
1311ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
13126b80053dSChris Mason 			break;
13133c69faecSChris Mason 	}
13143c69faecSChris Mason }
1315925baeddSChris Mason 
1316bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1317b4ce94deSChris Mason {
1318bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1319b4ce94deSChris Mason 	int slot;
1320b4ce94deSChris Mason 	int nritems;
1321b4ce94deSChris Mason 
13228c594ea8SChris Mason 	parent = path->nodes[level + 1];
1323b4ce94deSChris Mason 	if (!parent)
13240b08851fSJosef Bacik 		return;
1325b4ce94deSChris Mason 
1326b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
13278c594ea8SChris Mason 	slot = path->slots[level + 1];
1328b4ce94deSChris Mason 
1329bfb484d9SJosef Bacik 	if (slot > 0)
1330bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1331bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1332bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1333b4ce94deSChris Mason }
1334b4ce94deSChris Mason 
1335b4ce94deSChris Mason 
1336b4ce94deSChris Mason /*
1337d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1338d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1339d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1340d397712bSChris Mason  * tree.
1341d352ac68SChris Mason  *
1342d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1343d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1344d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1345d352ac68SChris Mason  *
1346d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1347d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1348d352ac68SChris Mason  */
1349e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1350f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1351f7c79f30SChris Mason 			       int *write_lock_level)
1352925baeddSChris Mason {
1353925baeddSChris Mason 	int i;
1354925baeddSChris Mason 	int skip_level = level;
1355c1227996SNikolay Borisov 	bool check_skip = true;
1356925baeddSChris Mason 
1357925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1358925baeddSChris Mason 		if (!path->nodes[i])
1359925baeddSChris Mason 			break;
1360925baeddSChris Mason 		if (!path->locks[i])
1361925baeddSChris Mason 			break;
1362c1227996SNikolay Borisov 
1363c1227996SNikolay Borisov 		if (check_skip) {
1364c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1365925baeddSChris Mason 				skip_level = i + 1;
1366925baeddSChris Mason 				continue;
1367925baeddSChris Mason 			}
1368c1227996SNikolay Borisov 
1369c1227996SNikolay Borisov 			if (path->keep_locks) {
1370925baeddSChris Mason 				u32 nritems;
1371c1227996SNikolay Borisov 
1372c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1373051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1374925baeddSChris Mason 					skip_level = i + 1;
1375925baeddSChris Mason 					continue;
1376925baeddSChris Mason 				}
1377925baeddSChris Mason 			}
1378c1227996SNikolay Borisov 		}
1379051e1b9fSChris Mason 
1380d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1381c1227996SNikolay Borisov 			check_skip = false;
1382c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1383925baeddSChris Mason 			path->locks[i] = 0;
1384f7c79f30SChris Mason 			if (write_lock_level &&
1385f7c79f30SChris Mason 			    i > min_write_lock_level &&
1386f7c79f30SChris Mason 			    i <= *write_lock_level) {
1387f7c79f30SChris Mason 				*write_lock_level = i - 1;
1388f7c79f30SChris Mason 			}
1389925baeddSChris Mason 		}
1390925baeddSChris Mason 	}
1391925baeddSChris Mason }
1392925baeddSChris Mason 
13933c69faecSChris Mason /*
1394376a21d7SFilipe Manana  * Helper function for btrfs_search_slot() and other functions that do a search
1395376a21d7SFilipe Manana  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1396376a21d7SFilipe Manana  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1397376a21d7SFilipe Manana  * its pages from disk.
1398c8c42864SChris Mason  *
1399376a21d7SFilipe Manana  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1400376a21d7SFilipe Manana  * whole btree search, starting again from the current root node.
1401c8c42864SChris Mason  */
1402c8c42864SChris Mason static int
1403d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1404c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1405cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1406c8c42864SChris Mason {
14070b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1408c8c42864SChris Mason 	u64 blocknr;
1409c8c42864SChris Mason 	u64 gen;
1410c8c42864SChris Mason 	struct extent_buffer *tmp;
1411581c1760SQu Wenruo 	struct btrfs_key first_key;
141276a05b35SChris Mason 	int ret;
1413581c1760SQu Wenruo 	int parent_level;
1414b246666eSFilipe Manana 	bool unlock_up;
1415c8c42864SChris Mason 
1416b246666eSFilipe Manana 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1417213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1418213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1419213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1420213ff4b7SNikolay Borisov 	btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
1421c8c42864SChris Mason 
1422b246666eSFilipe Manana 	/*
1423b246666eSFilipe Manana 	 * If we need to read an extent buffer from disk and we are holding locks
1424b246666eSFilipe Manana 	 * on upper level nodes, we unlock all the upper nodes before reading the
1425b246666eSFilipe Manana 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1426b246666eSFilipe Manana 	 * restart the search. We don't release the lock on the current level
1427b246666eSFilipe Manana 	 * because we need to walk this node to figure out which blocks to read.
1428b246666eSFilipe Manana 	 */
14290b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1430cb44921aSChris Mason 	if (tmp) {
1431ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1432ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1433ace75066SFilipe Manana 
1434b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1435b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1436448de471SQu Wenruo 			/*
1437448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1438448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1439448de471SQu Wenruo 			 * parents (shared tree blocks).
1440448de471SQu Wenruo 			 */
1441e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1442448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
1443448de471SQu Wenruo 				free_extent_buffer(tmp);
1444448de471SQu Wenruo 				return -EUCLEAN;
1445448de471SQu Wenruo 			}
1446c8c42864SChris Mason 			*eb_ret = tmp;
1447c8c42864SChris Mason 			return 0;
1448c8c42864SChris Mason 		}
1449bdf7c00eSJosef Bacik 
1450857bc13fSJosef Bacik 		if (p->nowait) {
1451857bc13fSJosef Bacik 			free_extent_buffer(tmp);
1452857bc13fSJosef Bacik 			return -EAGAIN;
1453857bc13fSJosef Bacik 		}
1454857bc13fSJosef Bacik 
1455b246666eSFilipe Manana 		if (unlock_up)
1456b246666eSFilipe Manana 			btrfs_unlock_up_safe(p, level + 1);
1457b246666eSFilipe Manana 
1458b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
14596a2e9dc4SFilipe Manana 		ret = btrfs_read_extent_buffer(tmp, gen, parent_level - 1, &first_key);
14609a4ffa1bSQu Wenruo 		if (ret) {
1461cb44921aSChris Mason 			free_extent_buffer(tmp);
1462b3b4aa74SDavid Sterba 			btrfs_release_path(p);
1463cb44921aSChris Mason 			return -EIO;
1464cb44921aSChris Mason 		}
146588c602abSQu Wenruo 		if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
146688c602abSQu Wenruo 			free_extent_buffer(tmp);
146788c602abSQu Wenruo 			btrfs_release_path(p);
146888c602abSQu Wenruo 			return -EUCLEAN;
146988c602abSQu Wenruo 		}
1470b246666eSFilipe Manana 
1471b246666eSFilipe Manana 		if (unlock_up)
1472b246666eSFilipe Manana 			ret = -EAGAIN;
1473b246666eSFilipe Manana 
1474b246666eSFilipe Manana 		goto out;
1475857bc13fSJosef Bacik 	} else if (p->nowait) {
1476857bc13fSJosef Bacik 		return -EAGAIN;
14779a4ffa1bSQu Wenruo 	}
1478c8c42864SChris Mason 
1479b246666eSFilipe Manana 	if (unlock_up) {
14808c594ea8SChris Mason 		btrfs_unlock_up_safe(p, level + 1);
14814bb59055SFilipe Manana 		ret = -EAGAIN;
14824bb59055SFilipe Manana 	} else {
14834bb59055SFilipe Manana 		ret = 0;
14844bb59055SFilipe Manana 	}
14858c594ea8SChris Mason 
1486e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
14872ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1488c8c42864SChris Mason 
14891b7ec85eSJosef Bacik 	tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
14901b7ec85eSJosef Bacik 			      gen, parent_level - 1, &first_key);
14914eb150d6SQu Wenruo 	if (IS_ERR(tmp)) {
14924eb150d6SQu Wenruo 		btrfs_release_path(p);
14934eb150d6SQu Wenruo 		return PTR_ERR(tmp);
14944eb150d6SQu Wenruo 	}
149576a05b35SChris Mason 	/*
149676a05b35SChris Mason 	 * If the read above didn't mark this buffer up to date,
149776a05b35SChris Mason 	 * it will never end up being up to date.  Set ret to EIO now
149876a05b35SChris Mason 	 * and give up so that our caller doesn't loop forever
149976a05b35SChris Mason 	 * on our EAGAINs.
150076a05b35SChris Mason 	 */
1501e6a1d6fdSLiu Bo 	if (!extent_buffer_uptodate(tmp))
150276a05b35SChris Mason 		ret = -EIO;
150302a3307aSLiu Bo 
1504b246666eSFilipe Manana out:
15054bb59055SFilipe Manana 	if (ret == 0) {
15064bb59055SFilipe Manana 		*eb_ret = tmp;
15074bb59055SFilipe Manana 	} else {
15084bb59055SFilipe Manana 		free_extent_buffer(tmp);
150902a3307aSLiu Bo 		btrfs_release_path(p);
15104bb59055SFilipe Manana 	}
15114bb59055SFilipe Manana 
151276a05b35SChris Mason 	return ret;
1513c8c42864SChris Mason }
1514c8c42864SChris Mason 
1515c8c42864SChris Mason /*
1516c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1517c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1518c8c42864SChris Mason  * the ins_len.
1519c8c42864SChris Mason  *
1520c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1521c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1522c8c42864SChris Mason  * start over
1523c8c42864SChris Mason  */
1524c8c42864SChris Mason static int
1525c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1526c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1527bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1528bd681513SChris Mason 		       int *write_lock_level)
1529c8c42864SChris Mason {
15300b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
153195b982deSNikolay Borisov 	int ret = 0;
15320b246afaSJeff Mahoney 
1533c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
15340b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
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 = split_node(trans, root, p, level);
1544c8c42864SChris Mason 
1545c8c42864SChris Mason 		b = p->nodes[level];
1546c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
15470b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1548c8c42864SChris Mason 
1549bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1550bd681513SChris Mason 			*write_lock_level = level + 1;
1551bd681513SChris Mason 			btrfs_release_path(p);
155295b982deSNikolay Borisov 			return -EAGAIN;
1553bd681513SChris Mason 		}
1554bd681513SChris Mason 
1555bfb484d9SJosef Bacik 		reada_for_balance(p, level);
155695b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
155795b982deSNikolay Borisov 		if (ret)
155895b982deSNikolay Borisov 			return ret;
1559c8c42864SChris Mason 
1560c8c42864SChris Mason 		b = p->nodes[level];
1561c8c42864SChris Mason 		if (!b) {
1562b3b4aa74SDavid Sterba 			btrfs_release_path(p);
156395b982deSNikolay Borisov 			return -EAGAIN;
1564c8c42864SChris Mason 		}
1565c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1566c8c42864SChris Mason 	}
1567c8c42864SChris Mason 	return ret;
1568c8c42864SChris Mason }
1569c8c42864SChris Mason 
1570381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1571e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1572e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1573e33d5c3dSKelley Nielsen {
1574e33d5c3dSKelley Nielsen 	int ret;
1575e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1576e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1577381cf658SDavid Sterba 
1578381cf658SDavid Sterba 	ASSERT(path);
15791d4c08e0SDavid Sterba 	ASSERT(found_key);
1580e33d5c3dSKelley Nielsen 
1581e33d5c3dSKelley Nielsen 	key.type = key_type;
1582e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1583e33d5c3dSKelley Nielsen 	key.offset = ioff;
1584e33d5c3dSKelley Nielsen 
1585e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
15861d4c08e0SDavid Sterba 	if (ret < 0)
1587e33d5c3dSKelley Nielsen 		return ret;
1588e33d5c3dSKelley Nielsen 
1589e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1590e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1591e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1592e33d5c3dSKelley Nielsen 		if (ret)
1593e33d5c3dSKelley Nielsen 			return ret;
1594e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1595e33d5c3dSKelley Nielsen 	}
1596e33d5c3dSKelley Nielsen 
1597e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1598e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1599e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1600e33d5c3dSKelley Nielsen 		return 1;
1601e33d5c3dSKelley Nielsen 
1602e33d5c3dSKelley Nielsen 	return 0;
1603e33d5c3dSKelley Nielsen }
1604e33d5c3dSKelley Nielsen 
16051fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
16061fc28d8eSLiu Bo 							struct btrfs_path *p,
16071fc28d8eSLiu Bo 							int write_lock_level)
16081fc28d8eSLiu Bo {
16091fc28d8eSLiu Bo 	struct extent_buffer *b;
1610120de408SJosef Bacik 	int root_lock = 0;
16111fc28d8eSLiu Bo 	int level = 0;
16121fc28d8eSLiu Bo 
16131fc28d8eSLiu Bo 	if (p->search_commit_root) {
16141fc28d8eSLiu Bo 		b = root->commit_root;
161567439dadSDavid Sterba 		atomic_inc(&b->refs);
16161fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1617f9ddfd05SLiu Bo 		/*
1618f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1619f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1620f9ddfd05SLiu Bo 		 */
1621f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
16221fc28d8eSLiu Bo 
16231fc28d8eSLiu Bo 		goto out;
16241fc28d8eSLiu Bo 	}
16251fc28d8eSLiu Bo 
16261fc28d8eSLiu Bo 	if (p->skip_locking) {
16271fc28d8eSLiu Bo 		b = btrfs_root_node(root);
16281fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16291fc28d8eSLiu Bo 		goto out;
16301fc28d8eSLiu Bo 	}
16311fc28d8eSLiu Bo 
1632120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1633120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1634120de408SJosef Bacik 
16351fc28d8eSLiu Bo 	/*
1636662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1637662c653bSLiu Bo 	 * lock.
1638662c653bSLiu Bo 	 */
1639662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1640662c653bSLiu Bo 		/*
1641662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1642662c653bSLiu Bo 		 * have it read locked
16431fc28d8eSLiu Bo 		 */
1644857bc13fSJosef Bacik 		if (p->nowait) {
1645857bc13fSJosef Bacik 			b = btrfs_try_read_lock_root_node(root);
1646857bc13fSJosef Bacik 			if (IS_ERR(b))
1647857bc13fSJosef Bacik 				return b;
1648857bc13fSJosef Bacik 		} else {
16491bb96598SJosef Bacik 			b = btrfs_read_lock_root_node(root);
1650857bc13fSJosef Bacik 		}
16511fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16521fc28d8eSLiu Bo 		if (level > write_lock_level)
16531fc28d8eSLiu Bo 			goto out;
16541fc28d8eSLiu Bo 
1655662c653bSLiu Bo 		/* Whoops, must trade for write lock */
16561fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
16571fc28d8eSLiu Bo 		free_extent_buffer(b);
1658662c653bSLiu Bo 	}
1659662c653bSLiu Bo 
16601fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
16611fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
16621fc28d8eSLiu Bo 
16631fc28d8eSLiu Bo 	/* The level might have changed, check again */
16641fc28d8eSLiu Bo 	level = btrfs_header_level(b);
16651fc28d8eSLiu Bo 
16661fc28d8eSLiu Bo out:
1667120de408SJosef Bacik 	/*
1668120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1669120de408SJosef Bacik 	 * longer valid, return an error in this case.
1670120de408SJosef Bacik 	 */
1671120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1672120de408SJosef Bacik 		if (root_lock)
1673120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1674120de408SJosef Bacik 		free_extent_buffer(b);
1675120de408SJosef Bacik 		return ERR_PTR(-EIO);
1676120de408SJosef Bacik 	}
1677120de408SJosef Bacik 
16781fc28d8eSLiu Bo 	p->nodes[level] = b;
16791fc28d8eSLiu Bo 	if (!p->skip_locking)
16801fc28d8eSLiu Bo 		p->locks[level] = root_lock;
16811fc28d8eSLiu Bo 	/*
16821fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
16831fc28d8eSLiu Bo 	 */
16841fc28d8eSLiu Bo 	return b;
16851fc28d8eSLiu Bo }
16861fc28d8eSLiu Bo 
1687d96b3424SFilipe Manana /*
1688d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1689d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1690d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1691d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1692d96b3424SFilipe Manana  * reallocated in the next transaction.
1693d96b3424SFilipe Manana  *
1694d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1695d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1696d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1697d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1698d96b3424SFilipe Manana  */
1699d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1700d96b3424SFilipe Manana {
1701d96b3424SFilipe Manana 	const int i = path->lowest_level;
1702d96b3424SFilipe Manana 	const int slot = path->slots[i];
1703d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1704d96b3424SFilipe Manana 	struct extent_buffer *clone;
1705d96b3424SFilipe Manana 
1706d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1707d96b3424SFilipe Manana 
1708d96b3424SFilipe Manana 	if (!lowest)
1709d96b3424SFilipe Manana 		return 0;
1710d96b3424SFilipe Manana 
1711d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1712d96b3424SFilipe Manana 
1713d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1714d96b3424SFilipe Manana 	if (!clone)
1715d96b3424SFilipe Manana 		return -ENOMEM;
1716d96b3424SFilipe Manana 
1717d96b3424SFilipe Manana 	btrfs_release_path(path);
1718d96b3424SFilipe Manana 	path->nodes[i] = clone;
1719d96b3424SFilipe Manana 	path->slots[i] = slot;
1720d96b3424SFilipe Manana 
1721d96b3424SFilipe Manana 	return 0;
1722d96b3424SFilipe Manana }
17231fc28d8eSLiu Bo 
1724e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1725e2e58d0fSFilipe Manana 				      int search_low_slot,
1726e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1727e2e58d0fSFilipe Manana 				      int prev_cmp,
1728e2e58d0fSFilipe Manana 				      int *slot)
1729e2e58d0fSFilipe Manana {
1730e2e58d0fSFilipe Manana 	/*
1731e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1732e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1733e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1734e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1735e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1736e2e58d0fSFilipe Manana 	 */
1737e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1738e2e58d0fSFilipe Manana 		*slot = 0;
1739e2e58d0fSFilipe Manana 		return 0;
1740e2e58d0fSFilipe Manana 	}
1741e2e58d0fSFilipe Manana 
1742e2e58d0fSFilipe Manana 	return generic_bin_search(eb, search_low_slot, key, slot);
1743e2e58d0fSFilipe Manana }
1744e2e58d0fSFilipe Manana 
1745109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1746109324cfSFilipe Manana 		       struct btrfs_root *root,
1747109324cfSFilipe Manana 		       const struct btrfs_key *key,
1748109324cfSFilipe Manana 		       struct btrfs_path *path,
1749109324cfSFilipe Manana 		       int ins_len,
1750109324cfSFilipe Manana 		       int prev_cmp)
1751109324cfSFilipe Manana {
1752109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
1753109324cfSFilipe Manana 	int leaf_free_space = -1;
1754109324cfSFilipe Manana 	int search_low_slot = 0;
1755109324cfSFilipe Manana 	int ret;
1756109324cfSFilipe Manana 	bool do_bin_search = true;
1757109324cfSFilipe Manana 
1758109324cfSFilipe Manana 	/*
1759109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
1760109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
1761109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
1762109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1763109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
1764109324cfSFilipe Manana 	 */
1765109324cfSFilipe Manana 	if (ins_len > 0) {
1766109324cfSFilipe Manana 		/*
1767109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
1768109324cfSFilipe Manana 		 * will not change until then.
1769109324cfSFilipe Manana 		 */
1770109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
1771109324cfSFilipe Manana 
1772109324cfSFilipe Manana 		/*
1773109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
1774109324cfSFilipe Manana 		 * the root of the tree.
1775109324cfSFilipe Manana 		 */
1776109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
1777109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
1778109324cfSFilipe Manana 
1779109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
1780109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
1781109324cfSFilipe Manana 
1782109324cfSFilipe Manana 			/*
1783109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
1784109324cfSFilipe Manana 			 * taking into account that the first key is very likely
1785109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
1786109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
1787109324cfSFilipe Manana 			 * the header's level field.
1788109324cfSFilipe Manana 			 */
1789109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
1790109324cfSFilipe Manana 			if (ret < 0) {
1791109324cfSFilipe Manana 				/*
1792109324cfSFilipe Manana 				 * The first key is smaller than the key we want
1793109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
1794109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
1795109324cfSFilipe Manana 				 *
1796109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
1797109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
1798109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
1799109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
1800109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
1801109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
1802109324cfSFilipe Manana 				 */
1803109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
1804109324cfSFilipe Manana 				search_low_slot = 1;
1805109324cfSFilipe Manana 			} else {
1806109324cfSFilipe Manana 				/*
1807109324cfSFilipe Manana 				 * The first key is >= then the key we want to
1808109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
1809109324cfSFilipe Manana 				 * the target key will be at slot 0.
1810109324cfSFilipe Manana 				 *
1811109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
1812109324cfSFilipe Manana 				 * less than the first key, because we will need
1813109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
1814109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
1815109324cfSFilipe Manana 				 * If the key matches the first key, then we can
1816109324cfSFilipe Manana 				 * unlock all the upper nodes, using
1817109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
1818109324cfSFilipe Manana 				 * as stated above.
1819109324cfSFilipe Manana 				 */
1820109324cfSFilipe Manana 				if (ret == 0)
1821109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
1822109324cfSFilipe Manana 				/*
1823109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
1824109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
1825109324cfSFilipe Manana 				 * to adjust it.
1826109324cfSFilipe Manana 				 */
1827109324cfSFilipe Manana 				do_bin_search = false;
1828109324cfSFilipe Manana 				path->slots[0] = 0;
1829109324cfSFilipe Manana 			}
1830109324cfSFilipe Manana 		}
1831109324cfSFilipe Manana 	}
1832109324cfSFilipe Manana 
1833109324cfSFilipe Manana 	if (do_bin_search) {
1834109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
1835109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
1836109324cfSFilipe Manana 		if (ret < 0)
1837109324cfSFilipe Manana 			return ret;
1838109324cfSFilipe Manana 	}
1839109324cfSFilipe Manana 
1840109324cfSFilipe Manana 	if (ins_len > 0) {
1841109324cfSFilipe Manana 		/*
1842109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
1843109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
1844109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
1845109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
1846109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
1847109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
1848109324cfSFilipe Manana 		 * check will be correct.
1849109324cfSFilipe Manana 		 */
1850109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
1851109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
1852109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
1853109324cfSFilipe Manana 		}
1854109324cfSFilipe Manana 
1855109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
1856109324cfSFilipe Manana 
1857109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
1858109324cfSFilipe Manana 			int err;
1859109324cfSFilipe Manana 
1860109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
1861109324cfSFilipe Manana 					 (ret == 0));
1862bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
1863bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
1864bb8e9a60SFilipe Manana 				err = -EUCLEAN;
1865109324cfSFilipe Manana 			if (err)
1866109324cfSFilipe Manana 				ret = err;
1867109324cfSFilipe Manana 		}
1868109324cfSFilipe Manana 	}
1869109324cfSFilipe Manana 
1870109324cfSFilipe Manana 	return ret;
1871109324cfSFilipe Manana }
1872109324cfSFilipe Manana 
1873c8c42864SChris Mason /*
18744271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
18754271eceaSNikolay Borisov  * modifications to preserve tree invariants.
187674123bd7SChris Mason  *
18774271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
18784271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
18794271eceaSNikolay Borisov  * @root:	The root node of the tree
18804271eceaSNikolay Borisov  * @key:	The key we are looking for
18819a664971Sethanwu  * @ins_len:	Indicates purpose of search:
18829a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
18839a664971Sethanwu  *              <0  for deletions
18849a664971Sethanwu  *               0  for plain searches, not modifying the tree
18859a664971Sethanwu  *
18869a664971Sethanwu  *              (*) If size of item inserted doesn't include
18879a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
18889a664971Sethanwu  *              be set.
18894271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
18904271eceaSNikolay Borisov  *		when modifying the tree.
189197571fd0SChris Mason  *
18924271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
18934271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
18944271eceaSNikolay Borisov  *
18954271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
18964271eceaSNikolay Borisov  * of the path (level 0)
18974271eceaSNikolay Borisov  *
18984271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
18994271eceaSNikolay Borisov  * points to the slot where it should be inserted
19004271eceaSNikolay Borisov  *
19014271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
19024271eceaSNikolay Borisov  * is returned
190374123bd7SChris Mason  */
1904310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1905310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
1906310712b2SOmar Sandoval 		      int ins_len, int cow)
1907be0e5c09SChris Mason {
1908d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
19095f39d397SChris Mason 	struct extent_buffer *b;
1910be0e5c09SChris Mason 	int slot;
1911be0e5c09SChris Mason 	int ret;
191233c66f43SYan Zheng 	int err;
1913be0e5c09SChris Mason 	int level;
1914925baeddSChris Mason 	int lowest_unlock = 1;
1915bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
1916bd681513SChris Mason 	int write_lock_level = 0;
19179f3a7427SChris Mason 	u8 lowest_level = 0;
1918f7c79f30SChris Mason 	int min_write_lock_level;
1919d7396f07SFilipe David Borba Manana 	int prev_cmp;
19209f3a7427SChris Mason 
19216702ed49SChris Mason 	lowest_level = p->lowest_level;
1922323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
192322b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
1924eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
192525179201SJosef Bacik 
1926857bc13fSJosef Bacik 	/*
1927857bc13fSJosef Bacik 	 * For now only allow nowait for read only operations.  There's no
1928857bc13fSJosef Bacik 	 * strict reason why we can't, we just only need it for reads so it's
1929857bc13fSJosef Bacik 	 * only implemented for reads.
1930857bc13fSJosef Bacik 	 */
1931857bc13fSJosef Bacik 	ASSERT(!p->nowait || !cow);
1932857bc13fSJosef Bacik 
1933bd681513SChris Mason 	if (ins_len < 0) {
1934925baeddSChris Mason 		lowest_unlock = 2;
193565b51a00SChris Mason 
1936bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
1937bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
1938bd681513SChris Mason 		 * for those levels as well
1939bd681513SChris Mason 		 */
1940bd681513SChris Mason 		write_lock_level = 2;
1941bd681513SChris Mason 	} else if (ins_len > 0) {
1942bd681513SChris Mason 		/*
1943bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
1944bd681513SChris Mason 		 * level 1 so we can update keys
1945bd681513SChris Mason 		 */
1946bd681513SChris Mason 		write_lock_level = 1;
1947bd681513SChris Mason 	}
1948bd681513SChris Mason 
1949bd681513SChris Mason 	if (!cow)
1950bd681513SChris Mason 		write_lock_level = -1;
1951bd681513SChris Mason 
195209a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
1953bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
1954bd681513SChris Mason 
1955f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
1956f7c79f30SChris Mason 
1957d96b3424SFilipe Manana 	if (p->need_commit_sem) {
1958d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
1959857bc13fSJosef Bacik 		if (p->nowait) {
1960857bc13fSJosef Bacik 			if (!down_read_trylock(&fs_info->commit_root_sem))
1961857bc13fSJosef Bacik 				return -EAGAIN;
1962857bc13fSJosef Bacik 		} else {
1963d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
1964d96b3424SFilipe Manana 		}
1965857bc13fSJosef Bacik 	}
1966d96b3424SFilipe Manana 
1967bb803951SChris Mason again:
1968d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
19691fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
1970be6821f8SFilipe Manana 	if (IS_ERR(b)) {
1971be6821f8SFilipe Manana 		ret = PTR_ERR(b);
1972be6821f8SFilipe Manana 		goto done;
1973be6821f8SFilipe Manana 	}
1974925baeddSChris Mason 
1975eb60ceacSChris Mason 	while (b) {
1976f624d976SQu Wenruo 		int dec = 0;
1977f624d976SQu Wenruo 
19785f39d397SChris Mason 		level = btrfs_header_level(b);
197965b51a00SChris Mason 
198002217ed2SChris Mason 		if (cow) {
19819ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
19829ea2c7c9SNikolay Borisov 
1983c8c42864SChris Mason 			/*
1984c8c42864SChris Mason 			 * if we don't really need to cow this block
1985c8c42864SChris Mason 			 * then we don't want to set the path blocking,
1986c8c42864SChris Mason 			 * so we test it here
1987c8c42864SChris Mason 			 */
19885963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
198965b51a00SChris Mason 				goto cow_done;
19905d4f98a2SYan Zheng 
1991bd681513SChris Mason 			/*
1992bd681513SChris Mason 			 * must have write locks on this node and the
1993bd681513SChris Mason 			 * parent
1994bd681513SChris Mason 			 */
19955124e00eSJosef Bacik 			if (level > write_lock_level ||
19965124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
19975124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
19985124e00eSJosef Bacik 			    p->nodes[level + 1])) {
1999bd681513SChris Mason 				write_lock_level = level + 1;
2000bd681513SChris Mason 				btrfs_release_path(p);
2001bd681513SChris Mason 				goto again;
2002bd681513SChris Mason 			}
2003bd681513SChris Mason 
20049ea2c7c9SNikolay Borisov 			if (last_level)
20059ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
20069631e4ccSJosef Bacik 						      &b,
20079631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
20089ea2c7c9SNikolay Borisov 			else
200933c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2010e20d96d6SChris Mason 						      p->nodes[level + 1],
20119631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
20129631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
201333c66f43SYan Zheng 			if (err) {
201433c66f43SYan Zheng 				ret = err;
201565b51a00SChris Mason 				goto done;
201654aa1f4dSChris Mason 			}
201702217ed2SChris Mason 		}
201865b51a00SChris Mason cow_done:
2019eb60ceacSChris Mason 		p->nodes[level] = b;
2020b4ce94deSChris Mason 
2021b4ce94deSChris Mason 		/*
2022b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2023b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2024b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2025b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2026b4ce94deSChris Mason 		 *
2027eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2028eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2029eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2030eb653de1SFilipe David Borba Manana 		 * we're operating on.
2031b4ce94deSChris Mason 		 */
2032eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2033eb653de1SFilipe David Borba Manana 			int u = level + 1;
2034eb653de1SFilipe David Borba Manana 
2035eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2036eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2037eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2038eb653de1SFilipe David Borba Manana 			}
2039eb653de1SFilipe David Borba Manana 		}
2040b4ce94deSChris Mason 
2041e2e58d0fSFilipe Manana 		if (level == 0) {
2042109324cfSFilipe Manana 			if (ins_len > 0)
2043e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
2044bd681513SChris Mason 
2045109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2046459931ecSChris Mason 			if (!p->search_for_split)
2047f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
20484b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
204965b51a00SChris Mason 			goto done;
205065b51a00SChris Mason 		}
2051e2e58d0fSFilipe Manana 
2052e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2053e2e58d0fSFilipe Manana 		if (ret < 0)
2054e2e58d0fSFilipe Manana 			goto done;
2055e2e58d0fSFilipe Manana 		prev_cmp = ret;
2056e2e58d0fSFilipe Manana 
2057f624d976SQu Wenruo 		if (ret && slot > 0) {
2058f624d976SQu Wenruo 			dec = 1;
2059f624d976SQu Wenruo 			slot--;
2060f624d976SQu Wenruo 		}
2061f624d976SQu Wenruo 		p->slots[level] = slot;
2062f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2063f624d976SQu Wenruo 					     &write_lock_level);
2064f624d976SQu Wenruo 		if (err == -EAGAIN)
2065f624d976SQu Wenruo 			goto again;
2066f624d976SQu Wenruo 		if (err) {
2067f624d976SQu Wenruo 			ret = err;
2068f624d976SQu Wenruo 			goto done;
2069f624d976SQu Wenruo 		}
2070f624d976SQu Wenruo 		b = p->nodes[level];
2071f624d976SQu Wenruo 		slot = p->slots[level];
2072f624d976SQu Wenruo 
2073f624d976SQu Wenruo 		/*
2074f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2075f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2076f624d976SQu Wenruo 		 * the parent
2077f624d976SQu Wenruo 		 */
2078f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2079f624d976SQu Wenruo 			write_lock_level = level + 1;
2080f624d976SQu Wenruo 			btrfs_release_path(p);
2081f624d976SQu Wenruo 			goto again;
2082f624d976SQu Wenruo 		}
2083f624d976SQu Wenruo 
2084f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2085f624d976SQu Wenruo 			  &write_lock_level);
2086f624d976SQu Wenruo 
2087f624d976SQu Wenruo 		if (level == lowest_level) {
2088f624d976SQu Wenruo 			if (dec)
2089f624d976SQu Wenruo 				p->slots[level]++;
2090f624d976SQu Wenruo 			goto done;
2091f624d976SQu Wenruo 		}
2092f624d976SQu Wenruo 
2093f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2094f624d976SQu Wenruo 		if (err == -EAGAIN)
2095f624d976SQu Wenruo 			goto again;
2096f624d976SQu Wenruo 		if (err) {
2097f624d976SQu Wenruo 			ret = err;
2098f624d976SQu Wenruo 			goto done;
2099f624d976SQu Wenruo 		}
2100f624d976SQu Wenruo 
2101f624d976SQu Wenruo 		if (!p->skip_locking) {
2102f624d976SQu Wenruo 			level = btrfs_header_level(b);
2103b40130b2SJosef Bacik 
2104b40130b2SJosef Bacik 			btrfs_maybe_reset_lockdep_class(root, b);
2105b40130b2SJosef Bacik 
2106f624d976SQu Wenruo 			if (level <= write_lock_level) {
2107f624d976SQu Wenruo 				btrfs_tree_lock(b);
2108f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2109f624d976SQu Wenruo 			} else {
2110857bc13fSJosef Bacik 				if (p->nowait) {
2111857bc13fSJosef Bacik 					if (!btrfs_try_tree_read_lock(b)) {
2112857bc13fSJosef Bacik 						free_extent_buffer(b);
2113857bc13fSJosef Bacik 						ret = -EAGAIN;
2114857bc13fSJosef Bacik 						goto done;
2115857bc13fSJosef Bacik 					}
2116857bc13fSJosef Bacik 				} else {
2117fe596ca3SJosef Bacik 					btrfs_tree_read_lock(b);
2118857bc13fSJosef Bacik 				}
2119f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2120f624d976SQu Wenruo 			}
2121f624d976SQu Wenruo 			p->nodes[level] = b;
2122f624d976SQu Wenruo 		}
212365b51a00SChris Mason 	}
212465b51a00SChris Mason 	ret = 1;
212565b51a00SChris Mason done:
21265f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2127b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2128d96b3424SFilipe Manana 
2129d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2130d96b3424SFilipe Manana 		int ret2;
2131d96b3424SFilipe Manana 
2132d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2133d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2134d96b3424SFilipe Manana 		if (ret2)
2135d96b3424SFilipe Manana 			ret = ret2;
2136d96b3424SFilipe Manana 	}
2137d96b3424SFilipe Manana 
2138be0e5c09SChris Mason 	return ret;
2139be0e5c09SChris Mason }
2140f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2141be0e5c09SChris Mason 
214274123bd7SChris Mason /*
21435d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
21445d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
21455d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
21465d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
21475d9e75c4SJan Schmidt  *
21485d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
21495d9e75c4SJan Schmidt  *
21505d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
21515d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
21525d9e75c4SJan Schmidt  */
2153310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
21545d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
21555d9e75c4SJan Schmidt {
21560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
21575d9e75c4SJan Schmidt 	struct extent_buffer *b;
21585d9e75c4SJan Schmidt 	int slot;
21595d9e75c4SJan Schmidt 	int ret;
21605d9e75c4SJan Schmidt 	int err;
21615d9e75c4SJan Schmidt 	int level;
21625d9e75c4SJan Schmidt 	int lowest_unlock = 1;
21635d9e75c4SJan Schmidt 	u8 lowest_level = 0;
21645d9e75c4SJan Schmidt 
21655d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
21665d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
2167*c922b016SStefan Roesch 	ASSERT(!p->nowait);
21685d9e75c4SJan Schmidt 
21695d9e75c4SJan Schmidt 	if (p->search_commit_root) {
21705d9e75c4SJan Schmidt 		BUG_ON(time_seq);
21715d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
21725d9e75c4SJan Schmidt 	}
21735d9e75c4SJan Schmidt 
21745d9e75c4SJan Schmidt again:
2175f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2176315bed43SNikolay Borisov 	if (!b) {
2177315bed43SNikolay Borisov 		ret = -EIO;
2178315bed43SNikolay Borisov 		goto done;
2179315bed43SNikolay Borisov 	}
21805d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
21815d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
21825d9e75c4SJan Schmidt 
21835d9e75c4SJan Schmidt 	while (b) {
2184abe9339dSQu Wenruo 		int dec = 0;
2185abe9339dSQu Wenruo 
21865d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
21875d9e75c4SJan Schmidt 		p->nodes[level] = b;
21885d9e75c4SJan Schmidt 
21895d9e75c4SJan Schmidt 		/*
21905d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
21915d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
21925d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
21935d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
21945d9e75c4SJan Schmidt 		 */
21955d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
21965d9e75c4SJan Schmidt 
2197995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
2198cbca7d59SFilipe Manana 		if (ret < 0)
2199cbca7d59SFilipe Manana 			goto done;
22005d9e75c4SJan Schmidt 
2201abe9339dSQu Wenruo 		if (level == 0) {
2202abe9339dSQu Wenruo 			p->slots[level] = slot;
2203abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2204abe9339dSQu Wenruo 			goto done;
2205abe9339dSQu Wenruo 		}
2206abe9339dSQu Wenruo 
22075d9e75c4SJan Schmidt 		if (ret && slot > 0) {
22085d9e75c4SJan Schmidt 			dec = 1;
2209abe9339dSQu Wenruo 			slot--;
22105d9e75c4SJan Schmidt 		}
22115d9e75c4SJan Schmidt 		p->slots[level] = slot;
22125d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
22135d9e75c4SJan Schmidt 
22145d9e75c4SJan Schmidt 		if (level == lowest_level) {
22155d9e75c4SJan Schmidt 			if (dec)
22165d9e75c4SJan Schmidt 				p->slots[level]++;
22175d9e75c4SJan Schmidt 			goto done;
22185d9e75c4SJan Schmidt 		}
22195d9e75c4SJan Schmidt 
2220abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
22215d9e75c4SJan Schmidt 		if (err == -EAGAIN)
22225d9e75c4SJan Schmidt 			goto again;
22235d9e75c4SJan Schmidt 		if (err) {
22245d9e75c4SJan Schmidt 			ret = err;
22255d9e75c4SJan Schmidt 			goto done;
22265d9e75c4SJan Schmidt 		}
22275d9e75c4SJan Schmidt 
22285d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
22295d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2230f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2231db7f3436SJosef Bacik 		if (!b) {
2232db7f3436SJosef Bacik 			ret = -ENOMEM;
2233db7f3436SJosef Bacik 			goto done;
2234db7f3436SJosef Bacik 		}
22355d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
22365d9e75c4SJan Schmidt 		p->nodes[level] = b;
22375d9e75c4SJan Schmidt 	}
22385d9e75c4SJan Schmidt 	ret = 1;
22395d9e75c4SJan Schmidt done:
22405d9e75c4SJan Schmidt 	if (ret < 0)
22415d9e75c4SJan Schmidt 		btrfs_release_path(p);
22425d9e75c4SJan Schmidt 
22435d9e75c4SJan Schmidt 	return ret;
22445d9e75c4SJan Schmidt }
22455d9e75c4SJan Schmidt 
22465d9e75c4SJan Schmidt /*
22472f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
22482f38b3e1SArne Jansen  * instead the next or previous item should be returned.
22492f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
22502f38b3e1SArne Jansen  * otherwise.
22512f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
22522f38b3e1SArne Jansen  * return the next lower instead.
22532f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
22542f38b3e1SArne Jansen  * return the next higher instead.
22552f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
22562f38b3e1SArne Jansen  * < 0 on error
22572f38b3e1SArne Jansen  */
22582f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2259310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2260310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2261310712b2SOmar Sandoval 			       int return_any)
22622f38b3e1SArne Jansen {
22632f38b3e1SArne Jansen 	int ret;
22642f38b3e1SArne Jansen 	struct extent_buffer *leaf;
22652f38b3e1SArne Jansen 
22662f38b3e1SArne Jansen again:
22672f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
22682f38b3e1SArne Jansen 	if (ret <= 0)
22692f38b3e1SArne Jansen 		return ret;
22702f38b3e1SArne Jansen 	/*
22712f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
22722f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
22732f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
22742f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
22752f38b3e1SArne Jansen 	 * item.
22762f38b3e1SArne Jansen 	 */
22772f38b3e1SArne Jansen 	leaf = p->nodes[0];
22782f38b3e1SArne Jansen 
22792f38b3e1SArne Jansen 	if (find_higher) {
22802f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
22812f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
22822f38b3e1SArne Jansen 			if (ret <= 0)
22832f38b3e1SArne Jansen 				return ret;
22842f38b3e1SArne Jansen 			if (!return_any)
22852f38b3e1SArne Jansen 				return 1;
22862f38b3e1SArne Jansen 			/*
22872f38b3e1SArne Jansen 			 * no higher item found, return the next
22882f38b3e1SArne Jansen 			 * lower instead
22892f38b3e1SArne Jansen 			 */
22902f38b3e1SArne Jansen 			return_any = 0;
22912f38b3e1SArne Jansen 			find_higher = 0;
22922f38b3e1SArne Jansen 			btrfs_release_path(p);
22932f38b3e1SArne Jansen 			goto again;
22942f38b3e1SArne Jansen 		}
22952f38b3e1SArne Jansen 	} else {
22962f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
22972f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2298e6793769SArne Jansen 			if (ret < 0)
22992f38b3e1SArne Jansen 				return ret;
2300e6793769SArne Jansen 			if (!ret) {
230123c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
230223c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
230323c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2304e6793769SArne Jansen 				return 0;
2305e6793769SArne Jansen 			}
23062f38b3e1SArne Jansen 			if (!return_any)
23072f38b3e1SArne Jansen 				return 1;
23082f38b3e1SArne Jansen 			/*
23092f38b3e1SArne Jansen 			 * no lower item found, return the next
23102f38b3e1SArne Jansen 			 * higher instead
23112f38b3e1SArne Jansen 			 */
23122f38b3e1SArne Jansen 			return_any = 0;
23132f38b3e1SArne Jansen 			find_higher = 1;
23142f38b3e1SArne Jansen 			btrfs_release_path(p);
23152f38b3e1SArne Jansen 			goto again;
2316e6793769SArne Jansen 		} else {
23172f38b3e1SArne Jansen 			--p->slots[0];
23182f38b3e1SArne Jansen 		}
23192f38b3e1SArne Jansen 	}
23202f38b3e1SArne Jansen 	return 0;
23212f38b3e1SArne Jansen }
23222f38b3e1SArne Jansen 
23232f38b3e1SArne Jansen /*
23240ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
23250ff40a91SMarcos Paulo de Souza  * was not found.
23260ff40a91SMarcos Paulo de Souza  *
23270ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
23280ff40a91SMarcos Paulo de Souza  */
23290ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
23300ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
23310ff40a91SMarcos Paulo de Souza {
23320ff40a91SMarcos Paulo de Souza 	int ret;
23330ff40a91SMarcos Paulo de Souza 
23340ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
23350ff40a91SMarcos Paulo de Souza 	if (ret > 0)
23360ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
23370ff40a91SMarcos Paulo de Souza 
23380ff40a91SMarcos Paulo de Souza 	if (ret == 0)
23390ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
23400ff40a91SMarcos Paulo de Souza 
23410ff40a91SMarcos Paulo de Souza 	return ret;
23420ff40a91SMarcos Paulo de Souza }
23430ff40a91SMarcos Paulo de Souza 
234462142be3SGabriel Niebler /**
234562142be3SGabriel Niebler  * Search for a valid slot for the given path.
234662142be3SGabriel Niebler  *
234762142be3SGabriel Niebler  * @root:	The root node of the tree.
234862142be3SGabriel Niebler  * @key:	Will contain a valid item if found.
234962142be3SGabriel Niebler  * @path:	The starting point to validate the slot.
235062142be3SGabriel Niebler  *
235162142be3SGabriel Niebler  * Return: 0  if the item is valid
235262142be3SGabriel Niebler  *         1  if not found
235362142be3SGabriel Niebler  *         <0 if error.
235462142be3SGabriel Niebler  */
235562142be3SGabriel Niebler int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
235662142be3SGabriel Niebler 			      struct btrfs_path *path)
235762142be3SGabriel Niebler {
235862142be3SGabriel Niebler 	while (1) {
235962142be3SGabriel Niebler 		int ret;
236062142be3SGabriel Niebler 		const int slot = path->slots[0];
236162142be3SGabriel Niebler 		const struct extent_buffer *leaf = path->nodes[0];
236262142be3SGabriel Niebler 
236362142be3SGabriel Niebler 		/* This is where we start walking the path. */
236462142be3SGabriel Niebler 		if (slot >= btrfs_header_nritems(leaf)) {
236562142be3SGabriel Niebler 			/*
236662142be3SGabriel Niebler 			 * If we've reached the last slot in this leaf we need
236762142be3SGabriel Niebler 			 * to go to the next leaf and reset the path.
236862142be3SGabriel Niebler 			 */
236962142be3SGabriel Niebler 			ret = btrfs_next_leaf(root, path);
237062142be3SGabriel Niebler 			if (ret)
237162142be3SGabriel Niebler 				return ret;
237262142be3SGabriel Niebler 			continue;
237362142be3SGabriel Niebler 		}
237462142be3SGabriel Niebler 		/* Store the found, valid item in @key. */
237562142be3SGabriel Niebler 		btrfs_item_key_to_cpu(leaf, key, slot);
237662142be3SGabriel Niebler 		break;
237762142be3SGabriel Niebler 	}
237862142be3SGabriel Niebler 	return 0;
237962142be3SGabriel Niebler }
238062142be3SGabriel Niebler 
23810ff40a91SMarcos Paulo de Souza /*
238274123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
238374123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
238474123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
238574123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
238674123bd7SChris Mason  * higher levels
2387aa5d6bedSChris Mason  *
238874123bd7SChris Mason  */
2389b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
23905f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2391be0e5c09SChris Mason {
2392be0e5c09SChris Mason 	int i;
23935f39d397SChris Mason 	struct extent_buffer *t;
23940e82bcfeSDavid Sterba 	int ret;
23955f39d397SChris Mason 
2396234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2397be0e5c09SChris Mason 		int tslot = path->slots[i];
23980e82bcfeSDavid Sterba 
2399eb60ceacSChris Mason 		if (!path->nodes[i])
2400be0e5c09SChris Mason 			break;
24015f39d397SChris Mason 		t = path->nodes[i];
2402f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
2403f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REPLACE, GFP_ATOMIC);
24040e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
24055f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2406d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2407be0e5c09SChris Mason 		if (tslot != 0)
2408be0e5c09SChris Mason 			break;
2409be0e5c09SChris Mason 	}
2410be0e5c09SChris Mason }
2411be0e5c09SChris Mason 
241274123bd7SChris Mason /*
241331840ae1SZheng Yan  * update item key.
241431840ae1SZheng Yan  *
241531840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
241631840ae1SZheng Yan  * that the new key won't break the order
241731840ae1SZheng Yan  */
2418b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2419b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2420310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
242131840ae1SZheng Yan {
242231840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
242331840ae1SZheng Yan 	struct extent_buffer *eb;
242431840ae1SZheng Yan 	int slot;
242531840ae1SZheng Yan 
242631840ae1SZheng Yan 	eb = path->nodes[0];
242731840ae1SZheng Yan 	slot = path->slots[0];
242831840ae1SZheng Yan 	if (slot > 0) {
242931840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
24307c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
24317c15d410SQu Wenruo 			btrfs_crit(fs_info,
24327c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
24337c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
24347c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
24357c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
24367c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
24377c15d410SQu Wenruo 				   new_key->offset);
24387c15d410SQu Wenruo 			btrfs_print_leaf(eb);
24397c15d410SQu Wenruo 			BUG();
24407c15d410SQu Wenruo 		}
244131840ae1SZheng Yan 	}
244231840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
244331840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
24447c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
24457c15d410SQu Wenruo 			btrfs_crit(fs_info,
24467c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
24477c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
24487c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
24497c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
24507c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
24517c15d410SQu Wenruo 				   new_key->offset);
24527c15d410SQu Wenruo 			btrfs_print_leaf(eb);
24537c15d410SQu Wenruo 			BUG();
24547c15d410SQu Wenruo 		}
245531840ae1SZheng Yan 	}
245631840ae1SZheng Yan 
245731840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
245831840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
245931840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
246031840ae1SZheng Yan 	if (slot == 0)
2461b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
246231840ae1SZheng Yan }
246331840ae1SZheng Yan 
246431840ae1SZheng Yan /*
2465d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2466d16c702fSQu Wenruo  *
2467d16c702fSQu Wenruo  * Return true if something is wrong.
2468d16c702fSQu Wenruo  * Return false if everything is fine.
2469d16c702fSQu Wenruo  *
2470d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2471d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2472d16c702fSQu Wenruo  *
2473d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2474d16c702fSQu Wenruo  * --------------------------------------------------------------
2475d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2476d16c702fSQu Wenruo  *
2477d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2478d16c702fSQu Wenruo  * key in leaf @right is 7.
2479d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2480d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2481d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2482d16c702fSQu Wenruo  * key of @right.
2483d16c702fSQu Wenruo  */
2484d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2485d16c702fSQu Wenruo 			       struct extent_buffer *right)
2486d16c702fSQu Wenruo {
2487d16c702fSQu Wenruo 	struct btrfs_key left_last;
2488d16c702fSQu Wenruo 	struct btrfs_key right_first;
2489d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2490d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2491d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2492d16c702fSQu Wenruo 
2493d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2494d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2495d16c702fSQu Wenruo 		return false;
2496d16c702fSQu Wenruo 
2497d16c702fSQu Wenruo 	if (level) {
2498d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2499d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2500d16c702fSQu Wenruo 	} else {
2501d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2502d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2503d16c702fSQu Wenruo 	}
2504d16c702fSQu Wenruo 
2505d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2506d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2507d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2508d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2509d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2510d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2511d16c702fSQu Wenruo 		return true;
2512d16c702fSQu Wenruo 	}
2513d16c702fSQu Wenruo 	return false;
2514d16c702fSQu Wenruo }
2515d16c702fSQu Wenruo 
2516d16c702fSQu Wenruo /*
251774123bd7SChris Mason  * try to push data from one node into the next node left in the
251879f95c82SChris Mason  * tree.
2519aa5d6bedSChris Mason  *
2520aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2521aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
252274123bd7SChris Mason  */
252398ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
25242ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2525971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2526be0e5c09SChris Mason {
2527d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2528be0e5c09SChris Mason 	int push_items = 0;
2529bb803951SChris Mason 	int src_nritems;
2530bb803951SChris Mason 	int dst_nritems;
2531aa5d6bedSChris Mason 	int ret = 0;
2532be0e5c09SChris Mason 
25335f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
25345f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
25350b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
25367bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
25377bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
253854aa1f4dSChris Mason 
2539bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2540971a1f66SChris Mason 		return 1;
2541971a1f66SChris Mason 
2542d397712bSChris Mason 	if (push_items <= 0)
2543be0e5c09SChris Mason 		return 1;
2544be0e5c09SChris Mason 
2545bce4eae9SChris Mason 	if (empty) {
2546971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2547bce4eae9SChris Mason 		if (push_items < src_nritems) {
2548bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2549bce4eae9SChris Mason 			 * we aren't going to empty it
2550bce4eae9SChris Mason 			 */
2551bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2552bce4eae9SChris Mason 				if (push_items <= 8)
2553bce4eae9SChris Mason 					return 1;
2554bce4eae9SChris Mason 				push_items -= 8;
2555bce4eae9SChris Mason 			}
2556bce4eae9SChris Mason 		}
2557bce4eae9SChris Mason 	} else
2558bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
255979f95c82SChris Mason 
2560d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2561d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2562d16c702fSQu Wenruo 		ret = -EUCLEAN;
2563d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2564d16c702fSQu Wenruo 		return ret;
2565d16c702fSQu Wenruo 	}
2566f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
25675de865eeSFilipe David Borba Manana 	if (ret) {
256866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
25695de865eeSFilipe David Borba Manana 		return ret;
25705de865eeSFilipe David Borba Manana 	}
25715f39d397SChris Mason 	copy_extent_buffer(dst, src,
25725f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
25735f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2574123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
25755f39d397SChris Mason 
2576bb803951SChris Mason 	if (push_items < src_nritems) {
257757911b8bSJan Schmidt 		/*
2578f3a84ccdSFilipe Manana 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2579f3a84ccdSFilipe Manana 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
258057911b8bSJan Schmidt 		 */
25815f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
25825f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2583e2fa7227SChris Mason 				      (src_nritems - push_items) *
2584123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2585bb803951SChris Mason 	}
25865f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
25875f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
25885f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
25895f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
259031840ae1SZheng Yan 
2591bb803951SChris Mason 	return ret;
2592be0e5c09SChris Mason }
2593be0e5c09SChris Mason 
259497571fd0SChris Mason /*
259579f95c82SChris Mason  * try to push data from one node into the next node right in the
259679f95c82SChris Mason  * tree.
259779f95c82SChris Mason  *
259879f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
259979f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
260079f95c82SChris Mason  *
260179f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
260279f95c82SChris Mason  */
26035f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
26045f39d397SChris Mason 			      struct extent_buffer *dst,
26055f39d397SChris Mason 			      struct extent_buffer *src)
260679f95c82SChris Mason {
260755d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
260879f95c82SChris Mason 	int push_items = 0;
260979f95c82SChris Mason 	int max_push;
261079f95c82SChris Mason 	int src_nritems;
261179f95c82SChris Mason 	int dst_nritems;
261279f95c82SChris Mason 	int ret = 0;
261379f95c82SChris Mason 
26147bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
26157bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
26167bb86316SChris Mason 
26175f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
26185f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
26190b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2620d397712bSChris Mason 	if (push_items <= 0)
262179f95c82SChris Mason 		return 1;
2622bce4eae9SChris Mason 
2623d397712bSChris Mason 	if (src_nritems < 4)
2624bce4eae9SChris Mason 		return 1;
262579f95c82SChris Mason 
262679f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
262779f95c82SChris Mason 	/* don't try to empty the node */
2628d397712bSChris Mason 	if (max_push >= src_nritems)
262979f95c82SChris Mason 		return 1;
2630252c38f0SYan 
263179f95c82SChris Mason 	if (max_push < push_items)
263279f95c82SChris Mason 		push_items = max_push;
263379f95c82SChris Mason 
2634d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2635d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2636d16c702fSQu Wenruo 		ret = -EUCLEAN;
2637d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2638d16c702fSQu Wenruo 		return ret;
2639d16c702fSQu Wenruo 	}
2640f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2641bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
26425f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
26435f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
26445f39d397SChris Mason 				      (dst_nritems) *
26455f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2646d6025579SChris Mason 
2647f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2648ed874f0dSDavid Sterba 					 push_items);
26495de865eeSFilipe David Borba Manana 	if (ret) {
265066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
26515de865eeSFilipe David Borba Manana 		return ret;
26525de865eeSFilipe David Borba Manana 	}
26535f39d397SChris Mason 	copy_extent_buffer(dst, src,
26545f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
26555f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2656123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
265779f95c82SChris Mason 
26585f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
26595f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
266079f95c82SChris Mason 
26615f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
26625f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
266331840ae1SZheng Yan 
266479f95c82SChris Mason 	return ret;
266579f95c82SChris Mason }
266679f95c82SChris Mason 
266779f95c82SChris Mason /*
266897571fd0SChris Mason  * helper function to insert a new root level in the tree.
266997571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
267097571fd0SChris Mason  * point to the existing root
2671aa5d6bedSChris Mason  *
2672aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
267397571fd0SChris Mason  */
2674d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
26755f39d397SChris Mason 			   struct btrfs_root *root,
2676fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
267774123bd7SChris Mason {
26780b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
26797bb86316SChris Mason 	u64 lower_gen;
26805f39d397SChris Mason 	struct extent_buffer *lower;
26815f39d397SChris Mason 	struct extent_buffer *c;
2682925baeddSChris Mason 	struct extent_buffer *old;
26835f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2684d9d19a01SDavid Sterba 	int ret;
26855c680ed6SChris Mason 
26865c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
26875c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
26885c680ed6SChris Mason 
26897bb86316SChris Mason 	lower = path->nodes[level-1];
26907bb86316SChris Mason 	if (level == 1)
26917bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
26927bb86316SChris Mason 	else
26937bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
26947bb86316SChris Mason 
269579bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
269679bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2697cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
26985f39d397SChris Mason 	if (IS_ERR(c))
26995f39d397SChris Mason 		return PTR_ERR(c);
2700925baeddSChris Mason 
27010b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2702f0486c68SYan, Zheng 
27035f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
27045f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2705db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
27067bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
270731840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
27087bb86316SChris Mason 
27097bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
27105f39d397SChris Mason 
27115f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2712d5719762SChris Mason 
2713925baeddSChris Mason 	old = root->node;
2714406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2715d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2716240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2717925baeddSChris Mason 
2718925baeddSChris Mason 	/* the super has an extra ref to root->node */
2719925baeddSChris Mason 	free_extent_buffer(old);
2720925baeddSChris Mason 
27210b86a832SChris Mason 	add_root_to_dirty_list(root);
272267439dadSDavid Sterba 	atomic_inc(&c->refs);
27235f39d397SChris Mason 	path->nodes[level] = c;
2724ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
272574123bd7SChris Mason 	path->slots[level] = 0;
272674123bd7SChris Mason 	return 0;
272774123bd7SChris Mason }
27285c680ed6SChris Mason 
27295c680ed6SChris Mason /*
27305c680ed6SChris Mason  * worker function to insert a single pointer in a node.
27315c680ed6SChris Mason  * the node should have enough room for the pointer already
273297571fd0SChris Mason  *
27335c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
27345c680ed6SChris Mason  * blocknr is the block the key points to.
27355c680ed6SChris Mason  */
2736143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
27376ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2738143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2739c3e06965SJan Schmidt 		       int slot, int level)
27405c680ed6SChris Mason {
27415f39d397SChris Mason 	struct extent_buffer *lower;
27425c680ed6SChris Mason 	int nritems;
2743f3ea38daSJan Schmidt 	int ret;
27445c680ed6SChris Mason 
27455c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
274649d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
27475f39d397SChris Mason 	lower = path->nodes[level];
27485f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2749c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
27506ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
275174123bd7SChris Mason 	if (slot != nritems) {
2752bf1d3425SDavid Sterba 		if (level) {
2753f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2754f3a84ccdSFilipe Manana 					slot, nritems - slot);
2755bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2756bf1d3425SDavid Sterba 		}
27575f39d397SChris Mason 		memmove_extent_buffer(lower,
27585f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
27595f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
2760123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
276174123bd7SChris Mason 	}
2762c3e06965SJan Schmidt 	if (level) {
2763f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
2764f3a84ccdSFilipe Manana 					    BTRFS_MOD_LOG_KEY_ADD, GFP_NOFS);
2765f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2766f3ea38daSJan Schmidt 	}
27675f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2768db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
276974493f7aSChris Mason 	WARN_ON(trans->transid == 0);
277074493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
27715f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
27725f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
277374123bd7SChris Mason }
277474123bd7SChris Mason 
277597571fd0SChris Mason /*
277697571fd0SChris Mason  * split the node at the specified level in path in two.
277797571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
277897571fd0SChris Mason  *
277997571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
278097571fd0SChris Mason  * left and right, if either one works, it returns right away.
2781aa5d6bedSChris Mason  *
2782aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
278397571fd0SChris Mason  */
2784e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
2785e02119d5SChris Mason 			       struct btrfs_root *root,
2786e02119d5SChris Mason 			       struct btrfs_path *path, int level)
2787be0e5c09SChris Mason {
27880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
27895f39d397SChris Mason 	struct extent_buffer *c;
27905f39d397SChris Mason 	struct extent_buffer *split;
27915f39d397SChris Mason 	struct btrfs_disk_key disk_key;
2792be0e5c09SChris Mason 	int mid;
27935c680ed6SChris Mason 	int ret;
27947518a238SChris Mason 	u32 c_nritems;
2795be0e5c09SChris Mason 
27965f39d397SChris Mason 	c = path->nodes[level];
27977bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
27985f39d397SChris Mason 	if (c == root->node) {
2799d9abbf1cSJan Schmidt 		/*
280090f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
280190f8d62eSJan Schmidt 		 *
2802fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
280390f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
280490f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
2805f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2806f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
2807f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
2808d9abbf1cSJan Schmidt 		 */
2809fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
28105c680ed6SChris Mason 		if (ret)
28115c680ed6SChris Mason 			return ret;
2812b3612421SChris Mason 	} else {
2813e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
28145f39d397SChris Mason 		c = path->nodes[level];
28155f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
28160b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2817e66f709bSChris Mason 			return 0;
281854aa1f4dSChris Mason 		if (ret < 0)
281954aa1f4dSChris Mason 			return ret;
28205c680ed6SChris Mason 	}
2821e66f709bSChris Mason 
28225f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
28235d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
28245d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
28257bb86316SChris Mason 
282679bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
282779bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
282879bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
28295f39d397SChris Mason 	if (IS_ERR(split))
28305f39d397SChris Mason 		return PTR_ERR(split);
283154aa1f4dSChris Mason 
28320b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2833bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
28345f39d397SChris Mason 
2835f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
28365de865eeSFilipe David Borba Manana 	if (ret) {
283766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
28385de865eeSFilipe David Borba Manana 		return ret;
28395de865eeSFilipe David Borba Manana 	}
28405f39d397SChris Mason 	copy_extent_buffer(split, c,
28415f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
28425f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
2843123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
28445f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
28455f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
2846aa5d6bedSChris Mason 
28475f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
28485f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
28495f39d397SChris Mason 
28506ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
2851c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
2852aa5d6bedSChris Mason 
28535de08d7dSChris Mason 	if (path->slots[level] >= mid) {
28545c680ed6SChris Mason 		path->slots[level] -= mid;
2855925baeddSChris Mason 		btrfs_tree_unlock(c);
28565f39d397SChris Mason 		free_extent_buffer(c);
28575f39d397SChris Mason 		path->nodes[level] = split;
28585c680ed6SChris Mason 		path->slots[level + 1] += 1;
2859eb60ceacSChris Mason 	} else {
2860925baeddSChris Mason 		btrfs_tree_unlock(split);
28615f39d397SChris Mason 		free_extent_buffer(split);
2862be0e5c09SChris Mason 	}
2863d5286a92SNikolay Borisov 	return 0;
2864be0e5c09SChris Mason }
2865be0e5c09SChris Mason 
286674123bd7SChris Mason /*
286774123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
286874123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
286974123bd7SChris Mason  * space used both by the item structs and the item data
287074123bd7SChris Mason  */
28715f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2872be0e5c09SChris Mason {
2873be0e5c09SChris Mason 	int data_len;
28745f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
2875d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
2876be0e5c09SChris Mason 
2877be0e5c09SChris Mason 	if (!nr)
2878be0e5c09SChris Mason 		return 0;
28793212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
28803212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
28810783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
2882d4dbff95SChris Mason 	WARN_ON(data_len < 0);
2883be0e5c09SChris Mason 	return data_len;
2884be0e5c09SChris Mason }
2885be0e5c09SChris Mason 
288674123bd7SChris Mason /*
2887d4dbff95SChris Mason  * The space between the end of the leaf items and
2888d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
2889d4dbff95SChris Mason  * the leaf has left for both items and data
2890d4dbff95SChris Mason  */
2891e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
2892d4dbff95SChris Mason {
2893e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
28945f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
28955f39d397SChris Mason 	int ret;
28960b246afaSJeff Mahoney 
28970b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
28985f39d397SChris Mason 	if (ret < 0) {
28990b246afaSJeff Mahoney 		btrfs_crit(fs_info,
2900efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2901da17066cSJeff Mahoney 			   ret,
29020b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
29035f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
29045f39d397SChris Mason 	}
29055f39d397SChris Mason 	return ret;
2906d4dbff95SChris Mason }
2907d4dbff95SChris Mason 
290899d8f83cSChris Mason /*
290999d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
291099d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
291199d8f83cSChris Mason  */
2912f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
291344871b1bSChris Mason 				      int data_size, int empty,
291444871b1bSChris Mason 				      struct extent_buffer *right,
291599d8f83cSChris Mason 				      int free_space, u32 left_nritems,
291699d8f83cSChris Mason 				      u32 min_slot)
291700ec4c51SChris Mason {
2918f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
29195f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
292044871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
2921cfed81a0SChris Mason 	struct btrfs_map_token token;
29225f39d397SChris Mason 	struct btrfs_disk_key disk_key;
292300ec4c51SChris Mason 	int slot;
292434a38218SChris Mason 	u32 i;
292500ec4c51SChris Mason 	int push_space = 0;
292600ec4c51SChris Mason 	int push_items = 0;
292734a38218SChris Mason 	u32 nr;
29287518a238SChris Mason 	u32 right_nritems;
29295f39d397SChris Mason 	u32 data_end;
2930db94535dSChris Mason 	u32 this_item_size;
293100ec4c51SChris Mason 
293234a38218SChris Mason 	if (empty)
293334a38218SChris Mason 		nr = 0;
293434a38218SChris Mason 	else
293599d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
293634a38218SChris Mason 
293731840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
293887b29b20SYan Zheng 		push_space += data_size;
293931840ae1SZheng Yan 
294044871b1bSChris Mason 	slot = path->slots[1];
294134a38218SChris Mason 	i = left_nritems - 1;
294234a38218SChris Mason 	while (i >= nr) {
294331840ae1SZheng Yan 		if (!empty && push_items > 0) {
294431840ae1SZheng Yan 			if (path->slots[0] > i)
294531840ae1SZheng Yan 				break;
294631840ae1SZheng Yan 			if (path->slots[0] == i) {
2947e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
2948e902baacSDavid Sterba 
294931840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
295031840ae1SZheng Yan 					break;
295131840ae1SZheng Yan 			}
295231840ae1SZheng Yan 		}
295331840ae1SZheng Yan 
295400ec4c51SChris Mason 		if (path->slots[0] == i)
295587b29b20SYan Zheng 			push_space += data_size;
2956db94535dSChris Mason 
29573212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
295874794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
295974794207SJosef Bacik 		    push_space > free_space)
296000ec4c51SChris Mason 			break;
296131840ae1SZheng Yan 
296200ec4c51SChris Mason 		push_items++;
296374794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
296434a38218SChris Mason 		if (i == 0)
296534a38218SChris Mason 			break;
296634a38218SChris Mason 		i--;
2967db94535dSChris Mason 	}
29685f39d397SChris Mason 
2969925baeddSChris Mason 	if (push_items == 0)
2970925baeddSChris Mason 		goto out_unlock;
29715f39d397SChris Mason 
29726c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
29735f39d397SChris Mason 
297400ec4c51SChris Mason 	/* push left to right */
29755f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
297634a38218SChris Mason 
2977dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
29788f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
29795f39d397SChris Mason 
298000ec4c51SChris Mason 	/* make room in the right data area */
29818f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
29825f39d397SChris Mason 	memmove_extent_buffer(right,
29833d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
29843d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
29850b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
29865f39d397SChris Mason 
298700ec4c51SChris Mason 	/* copy from the left data area */
29883d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
29890b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
29908f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
2991d6025579SChris Mason 		     push_space);
29925f39d397SChris Mason 
29935f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
29945f39d397SChris Mason 			      btrfs_item_nr_offset(0),
29950783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
29965f39d397SChris Mason 
299700ec4c51SChris Mason 	/* copy the items from left to right */
29985f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
29995f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
30000783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
300100ec4c51SChris Mason 
300200ec4c51SChris Mason 	/* update the item pointers */
3003c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
30047518a238SChris Mason 	right_nritems += push_items;
30055f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
30060b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
30077518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
30083212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
30093212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3010db94535dSChris Mason 	}
3011db94535dSChris Mason 
30127518a238SChris Mason 	left_nritems -= push_items;
30135f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
301400ec4c51SChris Mason 
301534a38218SChris Mason 	if (left_nritems)
30165f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3017f0486c68SYan, Zheng 	else
30186a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3019f0486c68SYan, Zheng 
30205f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3021a429e513SChris Mason 
30225f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
30235f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3024d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
302502217ed2SChris Mason 
302600ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
30277518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
30287518a238SChris Mason 		path->slots[0] -= left_nritems;
3029925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
30306a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3031925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
30325f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
30335f39d397SChris Mason 		path->nodes[0] = right;
303400ec4c51SChris Mason 		path->slots[1] += 1;
303500ec4c51SChris Mason 	} else {
3036925baeddSChris Mason 		btrfs_tree_unlock(right);
30375f39d397SChris Mason 		free_extent_buffer(right);
303800ec4c51SChris Mason 	}
303900ec4c51SChris Mason 	return 0;
3040925baeddSChris Mason 
3041925baeddSChris Mason out_unlock:
3042925baeddSChris Mason 	btrfs_tree_unlock(right);
3043925baeddSChris Mason 	free_extent_buffer(right);
3044925baeddSChris Mason 	return 1;
304500ec4c51SChris Mason }
3046925baeddSChris Mason 
304700ec4c51SChris Mason /*
304844871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
304974123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
305044871b1bSChris Mason  *
305144871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
305244871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
305399d8f83cSChris Mason  *
305499d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
305599d8f83cSChris Mason  * push any slot lower than min_slot
305674123bd7SChris Mason  */
305744871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
305899d8f83cSChris Mason 			   *root, struct btrfs_path *path,
305999d8f83cSChris Mason 			   int min_data_size, int data_size,
306099d8f83cSChris Mason 			   int empty, u32 min_slot)
3061be0e5c09SChris Mason {
306244871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
306344871b1bSChris Mason 	struct extent_buffer *right;
306444871b1bSChris Mason 	struct extent_buffer *upper;
306544871b1bSChris Mason 	int slot;
306644871b1bSChris Mason 	int free_space;
306744871b1bSChris Mason 	u32 left_nritems;
306844871b1bSChris Mason 	int ret;
306944871b1bSChris Mason 
307044871b1bSChris Mason 	if (!path->nodes[1])
307144871b1bSChris Mason 		return 1;
307244871b1bSChris Mason 
307344871b1bSChris Mason 	slot = path->slots[1];
307444871b1bSChris Mason 	upper = path->nodes[1];
307544871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
307644871b1bSChris Mason 		return 1;
307744871b1bSChris Mason 
307849d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
307944871b1bSChris Mason 
30804b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3081fb770ae4SLiu Bo 	/*
3082fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3083fb770ae4SLiu Bo 	 * no big deal, just return.
3084fb770ae4SLiu Bo 	 */
3085fb770ae4SLiu Bo 	if (IS_ERR(right))
308691ca338dSTsutomu Itoh 		return 1;
308791ca338dSTsutomu Itoh 
3088bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
308944871b1bSChris Mason 
3090e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
309144871b1bSChris Mason 	if (free_space < data_size)
309244871b1bSChris Mason 		goto out_unlock;
309344871b1bSChris Mason 
309444871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3095bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
309644871b1bSChris Mason 	if (ret)
309744871b1bSChris Mason 		goto out_unlock;
309844871b1bSChris Mason 
309944871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
310044871b1bSChris Mason 	if (left_nritems == 0)
310144871b1bSChris Mason 		goto out_unlock;
310244871b1bSChris Mason 
3103d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3104d16c702fSQu Wenruo 		ret = -EUCLEAN;
3105d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3106d16c702fSQu Wenruo 		free_extent_buffer(right);
3107d16c702fSQu Wenruo 		return ret;
3108d16c702fSQu Wenruo 	}
31092ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
31102ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
31112ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
31122ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
311352042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
31142ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
31152ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
31162ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
31172ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
31182ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
31192ef1fed2SFilipe David Borba Manana 		return 0;
31202ef1fed2SFilipe David Borba Manana 	}
31212ef1fed2SFilipe David Borba Manana 
3122f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
312399d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
312444871b1bSChris Mason out_unlock:
312544871b1bSChris Mason 	btrfs_tree_unlock(right);
312644871b1bSChris Mason 	free_extent_buffer(right);
312744871b1bSChris Mason 	return 1;
312844871b1bSChris Mason }
312944871b1bSChris Mason 
313044871b1bSChris Mason /*
313144871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
313244871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
313399d8f83cSChris Mason  *
313499d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
313599d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
313699d8f83cSChris Mason  * items
313744871b1bSChris Mason  */
31388087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
313944871b1bSChris Mason 				     int empty, struct extent_buffer *left,
314099d8f83cSChris Mason 				     int free_space, u32 right_nritems,
314199d8f83cSChris Mason 				     u32 max_slot)
314244871b1bSChris Mason {
31438087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
31445f39d397SChris Mason 	struct btrfs_disk_key disk_key;
31455f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3146be0e5c09SChris Mason 	int i;
3147be0e5c09SChris Mason 	int push_space = 0;
3148be0e5c09SChris Mason 	int push_items = 0;
31497518a238SChris Mason 	u32 old_left_nritems;
315034a38218SChris Mason 	u32 nr;
3151aa5d6bedSChris Mason 	int ret = 0;
3152db94535dSChris Mason 	u32 this_item_size;
3153db94535dSChris Mason 	u32 old_left_item_size;
3154cfed81a0SChris Mason 	struct btrfs_map_token token;
3155cfed81a0SChris Mason 
315634a38218SChris Mason 	if (empty)
315799d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
315834a38218SChris Mason 	else
315999d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
316034a38218SChris Mason 
316134a38218SChris Mason 	for (i = 0; i < nr; i++) {
316231840ae1SZheng Yan 		if (!empty && push_items > 0) {
316331840ae1SZheng Yan 			if (path->slots[0] < i)
316431840ae1SZheng Yan 				break;
316531840ae1SZheng Yan 			if (path->slots[0] == i) {
3166e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3167e902baacSDavid Sterba 
316831840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
316931840ae1SZheng Yan 					break;
317031840ae1SZheng Yan 			}
317131840ae1SZheng Yan 		}
317231840ae1SZheng Yan 
3173be0e5c09SChris Mason 		if (path->slots[0] == i)
317487b29b20SYan Zheng 			push_space += data_size;
3175db94535dSChris Mason 
31763212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
317774794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
317874794207SJosef Bacik 		    free_space)
3179be0e5c09SChris Mason 			break;
3180db94535dSChris Mason 
3181be0e5c09SChris Mason 		push_items++;
318274794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3183be0e5c09SChris Mason 	}
3184db94535dSChris Mason 
3185be0e5c09SChris Mason 	if (push_items == 0) {
3186925baeddSChris Mason 		ret = 1;
3187925baeddSChris Mason 		goto out;
3188be0e5c09SChris Mason 	}
3189fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
31905f39d397SChris Mason 
3191be0e5c09SChris Mason 	/* push data from right to left */
31925f39d397SChris Mason 	copy_extent_buffer(left, right,
31935f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
31945f39d397SChris Mason 			   btrfs_item_nr_offset(0),
31955f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
31965f39d397SChris Mason 
31970b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
31983212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
31995f39d397SChris Mason 
32003d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
32018f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
32023d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
32033212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1),
3204be0e5c09SChris Mason 		     push_space);
32055f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
320687b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3207eb60ceacSChris Mason 
3208c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
32093212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3210be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
32115f39d397SChris Mason 		u32 ioff;
3212db94535dSChris Mason 
32133212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
32143212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3215cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3216be0e5c09SChris Mason 	}
32175f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3218be0e5c09SChris Mason 
3219be0e5c09SChris Mason 	/* fixup right node */
322031b1a2bdSJulia Lawall 	if (push_items > right_nritems)
322131b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3222d397712bSChris Mason 		       right_nritems);
322334a38218SChris Mason 
322434a38218SChris Mason 	if (push_items < right_nritems) {
32253212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
32268f881e8cSDavid Sterba 						  leaf_data_end(right);
32273d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
32280b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
32293d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
32308f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
32315f39d397SChris Mason 
32325f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
32335f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
32345f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
32350783fcfcSChris Mason 			     sizeof(struct btrfs_item));
323634a38218SChris Mason 	}
3237c82f823cSDavid Sterba 
3238c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3239eef1c494SYan 	right_nritems -= push_items;
3240eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
32410b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
32425f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
32433212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
32443212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3245db94535dSChris Mason 	}
3246eb60ceacSChris Mason 
32475f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
324834a38218SChris Mason 	if (right_nritems)
32495f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3250f0486c68SYan, Zheng 	else
32516a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3252098f59c2SChris Mason 
32535f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3254b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3255be0e5c09SChris Mason 
3256be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3257be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3258be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3259925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32605f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32615f39d397SChris Mason 		path->nodes[0] = left;
3262be0e5c09SChris Mason 		path->slots[1] -= 1;
3263be0e5c09SChris Mason 	} else {
3264925baeddSChris Mason 		btrfs_tree_unlock(left);
32655f39d397SChris Mason 		free_extent_buffer(left);
3266be0e5c09SChris Mason 		path->slots[0] -= push_items;
3267be0e5c09SChris Mason 	}
3268eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3269aa5d6bedSChris Mason 	return ret;
3270925baeddSChris Mason out:
3271925baeddSChris Mason 	btrfs_tree_unlock(left);
3272925baeddSChris Mason 	free_extent_buffer(left);
3273925baeddSChris Mason 	return ret;
3274be0e5c09SChris Mason }
3275be0e5c09SChris Mason 
327674123bd7SChris Mason /*
327744871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
327844871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
327999d8f83cSChris Mason  *
328099d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
328199d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
328299d8f83cSChris Mason  * items
328344871b1bSChris Mason  */
328444871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
328599d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
328699d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
328744871b1bSChris Mason {
328844871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
328944871b1bSChris Mason 	struct extent_buffer *left;
329044871b1bSChris Mason 	int slot;
329144871b1bSChris Mason 	int free_space;
329244871b1bSChris Mason 	u32 right_nritems;
329344871b1bSChris Mason 	int ret = 0;
329444871b1bSChris Mason 
329544871b1bSChris Mason 	slot = path->slots[1];
329644871b1bSChris Mason 	if (slot == 0)
329744871b1bSChris Mason 		return 1;
329844871b1bSChris Mason 	if (!path->nodes[1])
329944871b1bSChris Mason 		return 1;
330044871b1bSChris Mason 
330144871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
330244871b1bSChris Mason 	if (right_nritems == 0)
330344871b1bSChris Mason 		return 1;
330444871b1bSChris Mason 
330549d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
330644871b1bSChris Mason 
33074b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3308fb770ae4SLiu Bo 	/*
3309fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3310fb770ae4SLiu Bo 	 * no big deal, just return.
3311fb770ae4SLiu Bo 	 */
3312fb770ae4SLiu Bo 	if (IS_ERR(left))
331391ca338dSTsutomu Itoh 		return 1;
331491ca338dSTsutomu Itoh 
3315bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
331644871b1bSChris Mason 
3317e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
331844871b1bSChris Mason 	if (free_space < data_size) {
331944871b1bSChris Mason 		ret = 1;
332044871b1bSChris Mason 		goto out;
332144871b1bSChris Mason 	}
332244871b1bSChris Mason 
332344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
33249631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3325bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
332644871b1bSChris Mason 	if (ret) {
332744871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
332879787eaaSJeff Mahoney 		if (ret == -ENOSPC)
332944871b1bSChris Mason 			ret = 1;
333044871b1bSChris Mason 		goto out;
333144871b1bSChris Mason 	}
333244871b1bSChris Mason 
3333d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3334d16c702fSQu Wenruo 		ret = -EUCLEAN;
3335d16c702fSQu Wenruo 		goto out;
3336d16c702fSQu Wenruo 	}
33378087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
333899d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
333999d8f83cSChris Mason 			       max_slot);
334044871b1bSChris Mason out:
334144871b1bSChris Mason 	btrfs_tree_unlock(left);
334244871b1bSChris Mason 	free_extent_buffer(left);
334344871b1bSChris Mason 	return ret;
334444871b1bSChris Mason }
334544871b1bSChris Mason 
334644871b1bSChris Mason /*
334774123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
334874123bd7SChris Mason  * available for the resulting leaf level of the path.
334974123bd7SChris Mason  */
3350143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
335144871b1bSChris Mason 				    struct btrfs_path *path,
335244871b1bSChris Mason 				    struct extent_buffer *l,
335344871b1bSChris Mason 				    struct extent_buffer *right,
335444871b1bSChris Mason 				    int slot, int mid, int nritems)
3355be0e5c09SChris Mason {
335694f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3357be0e5c09SChris Mason 	int data_copy_size;
3358be0e5c09SChris Mason 	int rt_data_off;
3359be0e5c09SChris Mason 	int i;
3360d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3361cfed81a0SChris Mason 	struct btrfs_map_token token;
3362cfed81a0SChris Mason 
33635f39d397SChris Mason 	nritems = nritems - mid;
33645f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3365dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
33665f39d397SChris Mason 
33675f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
33685f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
33695f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
33705f39d397SChris Mason 
33715f39d397SChris Mason 	copy_extent_buffer(right, l,
33723d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
33733d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
33748f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
337574123bd7SChris Mason 
3376dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
33775f39d397SChris Mason 
3378c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
33795f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3380db94535dSChris Mason 		u32 ioff;
3381db94535dSChris Mason 
33823212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
33833212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
33840783fcfcSChris Mason 	}
338574123bd7SChris Mason 
33865f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
33875f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
33886ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
33895f39d397SChris Mason 
33905f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
33915f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3392eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
33935f39d397SChris Mason 
3394be0e5c09SChris Mason 	if (mid <= slot) {
3395925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
33965f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
33975f39d397SChris Mason 		path->nodes[0] = right;
3398be0e5c09SChris Mason 		path->slots[0] -= mid;
3399be0e5c09SChris Mason 		path->slots[1] += 1;
3400925baeddSChris Mason 	} else {
3401925baeddSChris Mason 		btrfs_tree_unlock(right);
34025f39d397SChris Mason 		free_extent_buffer(right);
3403925baeddSChris Mason 	}
34045f39d397SChris Mason 
3405eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
340644871b1bSChris Mason }
340744871b1bSChris Mason 
340844871b1bSChris Mason /*
340999d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
341099d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
341199d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
341299d8f83cSChris Mason  *          A                 B                 C
341399d8f83cSChris Mason  *
341499d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
341599d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
341699d8f83cSChris Mason  * completely.
341799d8f83cSChris Mason  */
341899d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
341999d8f83cSChris Mason 					  struct btrfs_root *root,
342099d8f83cSChris Mason 					  struct btrfs_path *path,
342199d8f83cSChris Mason 					  int data_size)
342299d8f83cSChris Mason {
342399d8f83cSChris Mason 	int ret;
342499d8f83cSChris Mason 	int progress = 0;
342599d8f83cSChris Mason 	int slot;
342699d8f83cSChris Mason 	u32 nritems;
34275a4267caSFilipe David Borba Manana 	int space_needed = data_size;
342899d8f83cSChris Mason 
342999d8f83cSChris Mason 	slot = path->slots[0];
34305a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3431e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
343299d8f83cSChris Mason 
343399d8f83cSChris Mason 	/*
343499d8f83cSChris Mason 	 * try to push all the items after our slot into the
343599d8f83cSChris Mason 	 * right leaf
343699d8f83cSChris Mason 	 */
34375a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
343899d8f83cSChris Mason 	if (ret < 0)
343999d8f83cSChris Mason 		return ret;
344099d8f83cSChris Mason 
344199d8f83cSChris Mason 	if (ret == 0)
344299d8f83cSChris Mason 		progress++;
344399d8f83cSChris Mason 
344499d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
344599d8f83cSChris Mason 	/*
344699d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
344799d8f83cSChris Mason 	 * we've done so we're done
344899d8f83cSChris Mason 	 */
344999d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
345099d8f83cSChris Mason 		return 0;
345199d8f83cSChris Mason 
3452e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
345399d8f83cSChris Mason 		return 0;
345499d8f83cSChris Mason 
345599d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
345699d8f83cSChris Mason 	slot = path->slots[0];
3457263d3995SFilipe Manana 	space_needed = data_size;
3458263d3995SFilipe Manana 	if (slot > 0)
3459e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
34605a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
346199d8f83cSChris Mason 	if (ret < 0)
346299d8f83cSChris Mason 		return ret;
346399d8f83cSChris Mason 
346499d8f83cSChris Mason 	if (ret == 0)
346599d8f83cSChris Mason 		progress++;
346699d8f83cSChris Mason 
346799d8f83cSChris Mason 	if (progress)
346899d8f83cSChris Mason 		return 0;
346999d8f83cSChris Mason 	return 1;
347099d8f83cSChris Mason }
347199d8f83cSChris Mason 
347299d8f83cSChris Mason /*
347344871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
347444871b1bSChris Mason  * available for the resulting leaf level of the path.
347544871b1bSChris Mason  *
347644871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
347744871b1bSChris Mason  */
347844871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
347944871b1bSChris Mason 			       struct btrfs_root *root,
3480310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
348144871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
348244871b1bSChris Mason 			       int extend)
348344871b1bSChris Mason {
34845d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
348544871b1bSChris Mason 	struct extent_buffer *l;
348644871b1bSChris Mason 	u32 nritems;
348744871b1bSChris Mason 	int mid;
348844871b1bSChris Mason 	int slot;
348944871b1bSChris Mason 	struct extent_buffer *right;
3490b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
349144871b1bSChris Mason 	int ret = 0;
349244871b1bSChris Mason 	int wret;
34935d4f98a2SYan Zheng 	int split;
349444871b1bSChris Mason 	int num_doubles = 0;
349599d8f83cSChris Mason 	int tried_avoid_double = 0;
349644871b1bSChris Mason 
3497a5719521SYan, Zheng 	l = path->nodes[0];
3498a5719521SYan, Zheng 	slot = path->slots[0];
34993212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
35000b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3501a5719521SYan, Zheng 		return -EOVERFLOW;
3502a5719521SYan, Zheng 
350344871b1bSChris Mason 	/* first try to make some room by pushing left and right */
350433157e05SLiu Bo 	if (data_size && path->nodes[1]) {
35055a4267caSFilipe David Borba Manana 		int space_needed = data_size;
35065a4267caSFilipe David Borba Manana 
35075a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3508e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
35095a4267caSFilipe David Borba Manana 
35105a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
35115a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
351244871b1bSChris Mason 		if (wret < 0)
351344871b1bSChris Mason 			return wret;
351444871b1bSChris Mason 		if (wret) {
3515263d3995SFilipe Manana 			space_needed = data_size;
3516263d3995SFilipe Manana 			if (slot > 0)
3517e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
35185a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
35195a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
352044871b1bSChris Mason 			if (wret < 0)
352144871b1bSChris Mason 				return wret;
352244871b1bSChris Mason 		}
352344871b1bSChris Mason 		l = path->nodes[0];
352444871b1bSChris Mason 
352544871b1bSChris Mason 		/* did the pushes work? */
3526e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
352744871b1bSChris Mason 			return 0;
352844871b1bSChris Mason 	}
352944871b1bSChris Mason 
353044871b1bSChris Mason 	if (!path->nodes[1]) {
3531fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
353244871b1bSChris Mason 		if (ret)
353344871b1bSChris Mason 			return ret;
353444871b1bSChris Mason 	}
353544871b1bSChris Mason again:
35365d4f98a2SYan Zheng 	split = 1;
353744871b1bSChris Mason 	l = path->nodes[0];
353844871b1bSChris Mason 	slot = path->slots[0];
353944871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
354044871b1bSChris Mason 	mid = (nritems + 1) / 2;
354144871b1bSChris Mason 
35425d4f98a2SYan Zheng 	if (mid <= slot) {
35435d4f98a2SYan Zheng 		if (nritems == 1 ||
35445d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
35450b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
35465d4f98a2SYan Zheng 			if (slot >= nritems) {
35475d4f98a2SYan Zheng 				split = 0;
35485d4f98a2SYan Zheng 			} else {
35495d4f98a2SYan Zheng 				mid = slot;
35505d4f98a2SYan Zheng 				if (mid != nritems &&
35515d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
35520b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
355399d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
355499d8f83cSChris Mason 						goto push_for_double;
35555d4f98a2SYan Zheng 					split = 2;
35565d4f98a2SYan Zheng 				}
35575d4f98a2SYan Zheng 			}
35585d4f98a2SYan Zheng 		}
35595d4f98a2SYan Zheng 	} else {
35605d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
35610b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
35625d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
35635d4f98a2SYan Zheng 				split = 0;
35645d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
35655d4f98a2SYan Zheng 				mid = 1;
35665d4f98a2SYan Zheng 			} else {
35675d4f98a2SYan Zheng 				mid = slot;
35685d4f98a2SYan Zheng 				if (mid != nritems &&
35695d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
35700b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
357199d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
357299d8f83cSChris Mason 						goto push_for_double;
35735d4f98a2SYan Zheng 					split = 2;
35745d4f98a2SYan Zheng 				}
35755d4f98a2SYan Zheng 			}
35765d4f98a2SYan Zheng 		}
35775d4f98a2SYan Zheng 	}
35785d4f98a2SYan Zheng 
35795d4f98a2SYan Zheng 	if (split == 0)
35805d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
35815d4f98a2SYan Zheng 	else
35825d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
35835d4f98a2SYan Zheng 
3584ca9d473aSJosef Bacik 	/*
3585ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3586ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3587ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3588ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3589ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3590ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3591ca9d473aSJosef Bacik 	 */
359279bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
359379bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
359479bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3595ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3596f0486c68SYan, Zheng 	if (IS_ERR(right))
359744871b1bSChris Mason 		return PTR_ERR(right);
3598f0486c68SYan, Zheng 
35990b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
360044871b1bSChris Mason 
36015d4f98a2SYan Zheng 	if (split == 0) {
360244871b1bSChris Mason 		if (mid <= slot) {
360344871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
36046ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
36052ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
360644871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
360744871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
360844871b1bSChris Mason 			path->nodes[0] = right;
360944871b1bSChris Mason 			path->slots[0] = 0;
361044871b1bSChris Mason 			path->slots[1] += 1;
361144871b1bSChris Mason 		} else {
361244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
36136ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
36142ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
361544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
361644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
361744871b1bSChris Mason 			path->nodes[0] = right;
361844871b1bSChris Mason 			path->slots[0] = 0;
3619143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3620b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
36215d4f98a2SYan Zheng 		}
3622196e0249SLiu Bo 		/*
3623196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3624196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3625196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3626196e0249SLiu Bo 		 */
362744871b1bSChris Mason 		return ret;
362844871b1bSChris Mason 	}
362944871b1bSChris Mason 
363094f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
363144871b1bSChris Mason 
36325d4f98a2SYan Zheng 	if (split == 2) {
3633cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3634cc0c5538SChris Mason 		num_doubles++;
3635cc0c5538SChris Mason 		goto again;
36363326d1b0SChris Mason 	}
363744871b1bSChris Mason 
3638143bede5SJeff Mahoney 	return 0;
363999d8f83cSChris Mason 
364099d8f83cSChris Mason push_for_double:
364199d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
364299d8f83cSChris Mason 	tried_avoid_double = 1;
3643e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
364499d8f83cSChris Mason 		return 0;
364599d8f83cSChris Mason 	goto again;
3646be0e5c09SChris Mason }
3647be0e5c09SChris Mason 
3648ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3649ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3650ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3651ad48fd75SYan, Zheng {
3652ad48fd75SYan, Zheng 	struct btrfs_key key;
3653ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3654ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3655ad48fd75SYan, Zheng 	u64 extent_len = 0;
3656ad48fd75SYan, Zheng 	u32 item_size;
3657ad48fd75SYan, Zheng 	int ret;
3658ad48fd75SYan, Zheng 
3659ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3660ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3661ad48fd75SYan, Zheng 
3662ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3663ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3664ad48fd75SYan, Zheng 
3665e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3666ad48fd75SYan, Zheng 		return 0;
3667ad48fd75SYan, Zheng 
36683212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3669ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3670ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3671ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3672ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3673ad48fd75SYan, Zheng 	}
3674b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3675ad48fd75SYan, Zheng 
3676ad48fd75SYan, Zheng 	path->keep_locks = 1;
3677ad48fd75SYan, Zheng 	path->search_for_split = 1;
3678ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3679ad48fd75SYan, Zheng 	path->search_for_split = 0;
3680a8df6fe6SFilipe Manana 	if (ret > 0)
3681a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3682ad48fd75SYan, Zheng 	if (ret < 0)
3683ad48fd75SYan, Zheng 		goto err;
3684ad48fd75SYan, Zheng 
3685ad48fd75SYan, Zheng 	ret = -EAGAIN;
3686ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3687a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
36883212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3689ad48fd75SYan, Zheng 		goto err;
3690ad48fd75SYan, Zheng 
3691109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3692e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3693109f6aefSChris Mason 		goto err;
3694109f6aefSChris Mason 
3695ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3696ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3697ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3698ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3699ad48fd75SYan, Zheng 			goto err;
3700ad48fd75SYan, Zheng 	}
3701ad48fd75SYan, Zheng 
3702ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3703f0486c68SYan, Zheng 	if (ret)
3704f0486c68SYan, Zheng 		goto err;
3705ad48fd75SYan, Zheng 
3706ad48fd75SYan, Zheng 	path->keep_locks = 0;
3707ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3708ad48fd75SYan, Zheng 	return 0;
3709ad48fd75SYan, Zheng err:
3710ad48fd75SYan, Zheng 	path->keep_locks = 0;
3711ad48fd75SYan, Zheng 	return ret;
3712ad48fd75SYan, Zheng }
3713ad48fd75SYan, Zheng 
371425263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3715310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3716459931ecSChris Mason 			       unsigned long split_offset)
3717459931ecSChris Mason {
3718459931ecSChris Mason 	struct extent_buffer *leaf;
3719c91666b1SJosef Bacik 	int orig_slot, slot;
3720ad48fd75SYan, Zheng 	char *buf;
3721459931ecSChris Mason 	u32 nritems;
3722ad48fd75SYan, Zheng 	u32 item_size;
3723459931ecSChris Mason 	u32 orig_offset;
3724459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3725459931ecSChris Mason 
3726459931ecSChris Mason 	leaf = path->nodes[0];
3727e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3728b9473439SChris Mason 
3729c91666b1SJosef Bacik 	orig_slot = path->slots[0];
37303212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
37313212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3732459931ecSChris Mason 
3733459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3734ad48fd75SYan, Zheng 	if (!buf)
3735ad48fd75SYan, Zheng 		return -ENOMEM;
3736ad48fd75SYan, Zheng 
3737459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3738459931ecSChris Mason 			    path->slots[0]), item_size);
3739ad48fd75SYan, Zheng 
3740459931ecSChris Mason 	slot = path->slots[0] + 1;
3741459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3742459931ecSChris Mason 	if (slot != nritems) {
3743459931ecSChris Mason 		/* shift the items */
3744459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3745459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3746459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3747459931ecSChris Mason 	}
3748459931ecSChris Mason 
3749459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3750459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3751459931ecSChris Mason 
37523212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
37533212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3754459931ecSChris Mason 
37553212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
3756459931ecSChris Mason 				 orig_offset + item_size - split_offset);
37573212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3758459931ecSChris Mason 
3759459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3760459931ecSChris Mason 
3761459931ecSChris Mason 	/* write the data for the start of the original item */
3762459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3763459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3764459931ecSChris Mason 			    split_offset);
3765459931ecSChris Mason 
3766459931ecSChris Mason 	/* write the data for the new item */
3767459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3768459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3769459931ecSChris Mason 			    item_size - split_offset);
3770459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3771459931ecSChris Mason 
3772e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3773459931ecSChris Mason 	kfree(buf);
3774ad48fd75SYan, Zheng 	return 0;
3775ad48fd75SYan, Zheng }
3776ad48fd75SYan, Zheng 
3777ad48fd75SYan, Zheng /*
3778ad48fd75SYan, Zheng  * This function splits a single item into two items,
3779ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3780ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3781ad48fd75SYan, Zheng  *
3782ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3783ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3784ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3785ad48fd75SYan, Zheng  *
3786ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3787ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3788ad48fd75SYan, Zheng  *
3789ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3790ad48fd75SYan, Zheng  * leaf the entire time.
3791ad48fd75SYan, Zheng  */
3792ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3793ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3794ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3795310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3796ad48fd75SYan, Zheng 		     unsigned long split_offset)
3797ad48fd75SYan, Zheng {
3798ad48fd75SYan, Zheng 	int ret;
3799ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3800ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3801ad48fd75SYan, Zheng 	if (ret)
3802459931ecSChris Mason 		return ret;
3803ad48fd75SYan, Zheng 
380425263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3805ad48fd75SYan, Zheng 	return ret;
3806ad48fd75SYan, Zheng }
3807ad48fd75SYan, Zheng 
3808ad48fd75SYan, Zheng /*
3809d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
3810d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
3811d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
3812d352ac68SChris Mason  * the front.
3813d352ac68SChris Mason  */
381478ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3815b18c6685SChris Mason {
3816b18c6685SChris Mason 	int slot;
38175f39d397SChris Mason 	struct extent_buffer *leaf;
3818b18c6685SChris Mason 	u32 nritems;
3819b18c6685SChris Mason 	unsigned int data_end;
3820b18c6685SChris Mason 	unsigned int old_data_start;
3821b18c6685SChris Mason 	unsigned int old_size;
3822b18c6685SChris Mason 	unsigned int size_diff;
3823b18c6685SChris Mason 	int i;
3824cfed81a0SChris Mason 	struct btrfs_map_token token;
3825cfed81a0SChris Mason 
38265f39d397SChris Mason 	leaf = path->nodes[0];
3827179e29e4SChris Mason 	slot = path->slots[0];
3828179e29e4SChris Mason 
38293212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
3830179e29e4SChris Mason 	if (old_size == new_size)
3831143bede5SJeff Mahoney 		return;
3832b18c6685SChris Mason 
38335f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
38348f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3835b18c6685SChris Mason 
38363212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
3837179e29e4SChris Mason 
3838b18c6685SChris Mason 	size_diff = old_size - new_size;
3839b18c6685SChris Mason 
3840b18c6685SChris Mason 	BUG_ON(slot < 0);
3841b18c6685SChris Mason 	BUG_ON(slot >= nritems);
3842b18c6685SChris Mason 
3843b18c6685SChris Mason 	/*
3844b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3845b18c6685SChris Mason 	 */
3846b18c6685SChris Mason 	/* first correct the data pointers */
3847c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3848b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
38495f39d397SChris Mason 		u32 ioff;
3850db94535dSChris Mason 
38513212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
38523212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3853b18c6685SChris Mason 	}
3854db94535dSChris Mason 
3855b18c6685SChris Mason 	/* shift the data */
3856179e29e4SChris Mason 	if (from_end) {
38573d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
38583d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3859b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
3860179e29e4SChris Mason 	} else {
3861179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
3862179e29e4SChris Mason 		u64 offset;
3863179e29e4SChris Mason 
3864179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
3865179e29e4SChris Mason 
3866179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3867179e29e4SChris Mason 			unsigned long ptr;
3868179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
3869179e29e4SChris Mason 
3870179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
3871179e29e4SChris Mason 					    struct btrfs_file_extent_item);
3872179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
3873179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
3874179e29e4SChris Mason 
3875179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
3876179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
3877179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
3878179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
3879179e29e4SChris Mason 				      (unsigned long)fi,
38807ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
3881179e29e4SChris Mason 			}
3882179e29e4SChris Mason 		}
3883179e29e4SChris Mason 
38843d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
38853d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3886179e29e4SChris Mason 			      data_end, old_data_start - data_end);
3887179e29e4SChris Mason 
3888179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
3889179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3890179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
3891179e29e4SChris Mason 		if (slot == 0)
3892b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
3893179e29e4SChris Mason 	}
38945f39d397SChris Mason 
38953212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
38965f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3897b18c6685SChris Mason 
3898e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3899a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3900b18c6685SChris Mason 		BUG();
39015f39d397SChris Mason 	}
3902b18c6685SChris Mason }
3903b18c6685SChris Mason 
3904d352ac68SChris Mason /*
39058f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
3906d352ac68SChris Mason  */
3907c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
39086567e837SChris Mason {
39096567e837SChris Mason 	int slot;
39105f39d397SChris Mason 	struct extent_buffer *leaf;
39116567e837SChris Mason 	u32 nritems;
39126567e837SChris Mason 	unsigned int data_end;
39136567e837SChris Mason 	unsigned int old_data;
39146567e837SChris Mason 	unsigned int old_size;
39156567e837SChris Mason 	int i;
3916cfed81a0SChris Mason 	struct btrfs_map_token token;
3917cfed81a0SChris Mason 
39185f39d397SChris Mason 	leaf = path->nodes[0];
39196567e837SChris Mason 
39205f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
39218f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
39226567e837SChris Mason 
3923e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
3924a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39256567e837SChris Mason 		BUG();
39265f39d397SChris Mason 	}
39276567e837SChris Mason 	slot = path->slots[0];
3928dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
39296567e837SChris Mason 
39306567e837SChris Mason 	BUG_ON(slot < 0);
39313326d1b0SChris Mason 	if (slot >= nritems) {
3932a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3933c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
3934d397712bSChris Mason 			   slot, nritems);
3935290342f6SArnd Bergmann 		BUG();
39363326d1b0SChris Mason 	}
39376567e837SChris Mason 
39386567e837SChris Mason 	/*
39396567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
39406567e837SChris Mason 	 */
39416567e837SChris Mason 	/* first correct the data pointers */
3942c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
39436567e837SChris Mason 	for (i = slot; i < nritems; i++) {
39445f39d397SChris Mason 		u32 ioff;
3945db94535dSChris Mason 
39463212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
39473212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
39486567e837SChris Mason 	}
39495f39d397SChris Mason 
39506567e837SChris Mason 	/* shift the data */
39513d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
39523d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
39536567e837SChris Mason 		      data_end, old_data - data_end);
39545f39d397SChris Mason 
39556567e837SChris Mason 	data_end = old_data;
39563212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
39573212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
39585f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
39596567e837SChris Mason 
3960e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3961a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39626567e837SChris Mason 		BUG();
39635f39d397SChris Mason 	}
39646567e837SChris Mason }
39656567e837SChris Mason 
3966da9ffb24SNikolay Borisov /**
3967da9ffb24SNikolay Borisov  * setup_items_for_insert - Helper called before inserting one or more items
3968da9ffb24SNikolay Borisov  * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
3969da9ffb24SNikolay Borisov  * in a function that doesn't call btrfs_search_slot
3970da9ffb24SNikolay Borisov  *
3971da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
3972da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
3973b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
397474123bd7SChris Mason  */
3975f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
3976b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
3977be0e5c09SChris Mason {
39780b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
39799c58309dSChris Mason 	int i;
39807518a238SChris Mason 	u32 nritems;
3981be0e5c09SChris Mason 	unsigned int data_end;
3982e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
398344871b1bSChris Mason 	struct extent_buffer *leaf;
398444871b1bSChris Mason 	int slot;
3985cfed81a0SChris Mason 	struct btrfs_map_token token;
3986fc0d82e1SNikolay Borisov 	u32 total_size;
3987fc0d82e1SNikolay Borisov 
3988b7ef5f3aSFilipe Manana 	/*
3989b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
3990b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
3991b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
3992b7ef5f3aSFilipe Manana 	 */
399324cdc847SFilipe Manana 	if (path->slots[0] == 0) {
3994b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
3995b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
399624cdc847SFilipe Manana 	}
399724cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
399824cdc847SFilipe Manana 
39995f39d397SChris Mason 	leaf = path->nodes[0];
400044871b1bSChris Mason 	slot = path->slots[0];
400174123bd7SChris Mason 
40025f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
40038f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4004b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4005eb60ceacSChris Mason 
4006e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4007a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
40080b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4009e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4010be0e5c09SChris Mason 		BUG();
4011d4dbff95SChris Mason 	}
40125f39d397SChris Mason 
4013c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4014be0e5c09SChris Mason 	if (slot != nritems) {
4015dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4016be0e5c09SChris Mason 
40175f39d397SChris Mason 		if (old_data < data_end) {
4018a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
40197269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
40207269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
40215f39d397SChris Mason 				   slot, old_data, data_end);
4022290342f6SArnd Bergmann 			BUG();
40235f39d397SChris Mason 		}
4024be0e5c09SChris Mason 		/*
4025be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4026be0e5c09SChris Mason 		 */
4027be0e5c09SChris Mason 		/* first correct the data pointers */
40280783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
40295f39d397SChris Mason 			u32 ioff;
4030db94535dSChris Mason 
40313212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
40323212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
4033b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
40340783fcfcSChris Mason 		}
4035be0e5c09SChris Mason 		/* shift the items */
4036b7ef5f3aSFilipe Manana 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + batch->nr),
40375f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
40380783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4039be0e5c09SChris Mason 
4040be0e5c09SChris Mason 		/* shift the data */
40413d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4042b7ef5f3aSFilipe Manana 				      data_end - batch->total_data_size,
4043b7ef5f3aSFilipe Manana 				      BTRFS_LEAF_DATA_OFFSET + data_end,
4044b7ef5f3aSFilipe Manana 				      old_data - data_end);
4045be0e5c09SChris Mason 		data_end = old_data;
4046be0e5c09SChris Mason 	}
40475f39d397SChris Mason 
404862e2749eSChris Mason 	/* setup the item for the new data */
4049b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
4050b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
40519c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4052b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
40533212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
40543212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
40559c58309dSChris Mason 	}
405644871b1bSChris Mason 
4057b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4058b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4059aa5d6bedSChris Mason 
4060e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4061a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4062be0e5c09SChris Mason 		BUG();
40635f39d397SChris Mason 	}
406444871b1bSChris Mason }
406544871b1bSChris Mason 
406644871b1bSChris Mason /*
4067f0641656SFilipe Manana  * Insert a new item into a leaf.
4068f0641656SFilipe Manana  *
4069f0641656SFilipe Manana  * @root:      The root of the btree.
4070f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
4071f0641656SFilipe Manana  * @key:       The key of the new item.
4072f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
4073f0641656SFilipe Manana  */
4074f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
4075f0641656SFilipe Manana 				 struct btrfs_path *path,
4076f0641656SFilipe Manana 				 const struct btrfs_key *key,
4077f0641656SFilipe Manana 				 u32 data_size)
4078f0641656SFilipe Manana {
4079f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4080f0641656SFilipe Manana 
4081f0641656SFilipe Manana 	batch.keys = key;
4082f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4083f0641656SFilipe Manana 	batch.total_data_size = data_size;
4084f0641656SFilipe Manana 	batch.nr = 1;
4085f0641656SFilipe Manana 
4086f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
4087f0641656SFilipe Manana }
4088f0641656SFilipe Manana 
4089f0641656SFilipe Manana /*
409044871b1bSChris Mason  * Given a key and some data, insert items into the tree.
409144871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
409244871b1bSChris Mason  */
409344871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
409444871b1bSChris Mason 			    struct btrfs_root *root,
409544871b1bSChris Mason 			    struct btrfs_path *path,
4096b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
409744871b1bSChris Mason {
409844871b1bSChris Mason 	int ret = 0;
409944871b1bSChris Mason 	int slot;
4100b7ef5f3aSFilipe Manana 	u32 total_size;
410144871b1bSChris Mason 
4102b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4103b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
410444871b1bSChris Mason 	if (ret == 0)
410544871b1bSChris Mason 		return -EEXIST;
410644871b1bSChris Mason 	if (ret < 0)
4107143bede5SJeff Mahoney 		return ret;
410844871b1bSChris Mason 
410944871b1bSChris Mason 	slot = path->slots[0];
411044871b1bSChris Mason 	BUG_ON(slot < 0);
411144871b1bSChris Mason 
4112b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4113143bede5SJeff Mahoney 	return 0;
411462e2749eSChris Mason }
411562e2749eSChris Mason 
411662e2749eSChris Mason /*
411762e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
411862e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
411962e2749eSChris Mason  */
4120310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4121310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4122310712b2SOmar Sandoval 		      u32 data_size)
412362e2749eSChris Mason {
412462e2749eSChris Mason 	int ret = 0;
41252c90e5d6SChris Mason 	struct btrfs_path *path;
41265f39d397SChris Mason 	struct extent_buffer *leaf;
41275f39d397SChris Mason 	unsigned long ptr;
412862e2749eSChris Mason 
41292c90e5d6SChris Mason 	path = btrfs_alloc_path();
4130db5b493aSTsutomu Itoh 	if (!path)
4131db5b493aSTsutomu Itoh 		return -ENOMEM;
41322c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
413362e2749eSChris Mason 	if (!ret) {
41345f39d397SChris Mason 		leaf = path->nodes[0];
41355f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
41365f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
41375f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
413862e2749eSChris Mason 	}
41392c90e5d6SChris Mason 	btrfs_free_path(path);
4140aa5d6bedSChris Mason 	return ret;
4141be0e5c09SChris Mason }
4142be0e5c09SChris Mason 
414374123bd7SChris Mason /*
4144f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4145f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4146f0641656SFilipe Manana  * contiguous with the original item.
4147f0641656SFilipe Manana  *
4148f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4149f0641656SFilipe Manana  * the entire time.
4150f0641656SFilipe Manana  */
4151f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4152f0641656SFilipe Manana 			 struct btrfs_root *root,
4153f0641656SFilipe Manana 			 struct btrfs_path *path,
4154f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4155f0641656SFilipe Manana {
4156f0641656SFilipe Manana 	struct extent_buffer *leaf;
4157f0641656SFilipe Manana 	int ret;
4158f0641656SFilipe Manana 	u32 item_size;
4159f0641656SFilipe Manana 
4160f0641656SFilipe Manana 	leaf = path->nodes[0];
41613212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4162f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4163f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4164f0641656SFilipe Manana 	if (ret)
4165f0641656SFilipe Manana 		return ret;
4166f0641656SFilipe Manana 
4167f0641656SFilipe Manana 	path->slots[0]++;
4168f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4169f0641656SFilipe Manana 	leaf = path->nodes[0];
4170f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4171f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4172f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4173f0641656SFilipe Manana 			     item_size);
4174f0641656SFilipe Manana 	return 0;
4175f0641656SFilipe Manana }
4176f0641656SFilipe Manana 
4177f0641656SFilipe Manana /*
41785de08d7dSChris Mason  * delete the pointer from a given node.
417974123bd7SChris Mason  *
4180d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4181d352ac68SChris Mason  * empty a node.
418274123bd7SChris Mason  */
4183afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4184afe5fea7STsutomu Itoh 		    int level, int slot)
4185be0e5c09SChris Mason {
41865f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
41877518a238SChris Mason 	u32 nritems;
4188f3ea38daSJan Schmidt 	int ret;
4189be0e5c09SChris Mason 
41905f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4191be0e5c09SChris Mason 	if (slot != nritems - 1) {
4192bf1d3425SDavid Sterba 		if (level) {
4193f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4194f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4195bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4196bf1d3425SDavid Sterba 		}
41975f39d397SChris Mason 		memmove_extent_buffer(parent,
41985f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
41995f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4200d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4201d6025579SChris Mason 			      (nritems - slot - 1));
420257ba86c0SChris Mason 	} else if (level) {
4203f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
4204f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REMOVE, GFP_NOFS);
420557ba86c0SChris Mason 		BUG_ON(ret < 0);
4206be0e5c09SChris Mason 	}
4207f3ea38daSJan Schmidt 
42087518a238SChris Mason 	nritems--;
42095f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
42107518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
42115f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4212eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
42135f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4214bb803951SChris Mason 	} else if (slot == 0) {
42155f39d397SChris Mason 		struct btrfs_disk_key disk_key;
42165f39d397SChris Mason 
42175f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4218b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4219be0e5c09SChris Mason 	}
4220d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4221be0e5c09SChris Mason }
4222be0e5c09SChris Mason 
422374123bd7SChris Mason /*
4224323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
42255d4f98a2SYan Zheng  * path->nodes[1].
4226323ac95bSChris Mason  *
4227323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4228323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4229323ac95bSChris Mason  *
4230323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4231323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4232323ac95bSChris Mason  */
4233143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4234323ac95bSChris Mason 				    struct btrfs_root *root,
42355d4f98a2SYan Zheng 				    struct btrfs_path *path,
42365d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4237323ac95bSChris Mason {
42385d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4239afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4240323ac95bSChris Mason 
42414d081c41SChris Mason 	/*
42424d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
42434d081c41SChris Mason 	 * aren't holding any locks when we call it
42444d081c41SChris Mason 	 */
42454d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
42464d081c41SChris Mason 
4247f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4248f0486c68SYan, Zheng 
424967439dadSDavid Sterba 	atomic_inc(&leaf->refs);
42507a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
42513083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4252323ac95bSChris Mason }
4253323ac95bSChris Mason /*
425474123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
425574123bd7SChris Mason  * the leaf, remove it from the tree
425674123bd7SChris Mason  */
425785e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
425885e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4259be0e5c09SChris Mason {
42600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
42615f39d397SChris Mason 	struct extent_buffer *leaf;
4262aa5d6bedSChris Mason 	int ret = 0;
4263aa5d6bedSChris Mason 	int wret;
42647518a238SChris Mason 	u32 nritems;
4265be0e5c09SChris Mason 
42665f39d397SChris Mason 	leaf = path->nodes[0];
42675f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4268be0e5c09SChris Mason 
426985e21bacSChris Mason 	if (slot + nr != nritems) {
42700cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
42710cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4272c82f823cSDavid Sterba 		struct btrfs_map_token token;
42730cae23b6SFilipe Manana 		u32 dsize = 0;
42740cae23b6SFilipe Manana 		int i;
42750cae23b6SFilipe Manana 
42760cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
42770cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
42785f39d397SChris Mason 
42793d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4280d6025579SChris Mason 			      data_end + dsize,
42813d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
428285e21bacSChris Mason 			      last_off - data_end);
42835f39d397SChris Mason 
4284c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
428585e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
42865f39d397SChris Mason 			u32 ioff;
4287db94535dSChris Mason 
42883212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
42893212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
42900783fcfcSChris Mason 		}
4291db94535dSChris Mason 
42925f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
429385e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
42940783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
429585e21bacSChris Mason 			      (nritems - slot - nr));
4296be0e5c09SChris Mason 	}
429785e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
429885e21bacSChris Mason 	nritems -= nr;
42995f39d397SChris Mason 
430074123bd7SChris Mason 	/* delete the leaf if we've emptied it */
43017518a238SChris Mason 	if (nritems == 0) {
43025f39d397SChris Mason 		if (leaf == root->node) {
43035f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
43049a8dd150SChris Mason 		} else {
43056a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4306143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
43079a8dd150SChris Mason 		}
4308be0e5c09SChris Mason 	} else {
43097518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4310aa5d6bedSChris Mason 		if (slot == 0) {
43115f39d397SChris Mason 			struct btrfs_disk_key disk_key;
43125f39d397SChris Mason 
43135f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4314b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4315aa5d6bedSChris Mason 		}
4316aa5d6bedSChris Mason 
43177c4063d1SFilipe Manana 		/*
43187c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
43197c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
43207c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
43217c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
43227c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
43237c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
43247c4063d1SFilipe Manana 		 */
43250b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
43267c4063d1SFilipe Manana 			u32 min_push_space;
43277c4063d1SFilipe Manana 
4328be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4329be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4330be0e5c09SChris Mason 			 * for possible call to del_ptr below
4331be0e5c09SChris Mason 			 */
43324920c9acSChris Mason 			slot = path->slots[1];
433367439dadSDavid Sterba 			atomic_inc(&leaf->refs);
43347c4063d1SFilipe Manana 			/*
43357c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
43367c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
43377c4063d1SFilipe Manana 			 */
43387c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
43397c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
43407c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
43417c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
434254aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4343aa5d6bedSChris Mason 				ret = wret;
43445f39d397SChris Mason 
43455f39d397SChris Mason 			if (path->nodes[0] == leaf &&
43465f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
43477c4063d1SFilipe Manana 				/*
43487c4063d1SFilipe Manana 				 * If we were not able to push all items from our
43497c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
43507c4063d1SFilipe Manana 				 * either push all the remaining items to the
43517c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
43527c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
43537c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
43547c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
43557c4063d1SFilipe Manana 				 * or nearly full.
43567c4063d1SFilipe Manana 				 */
43577c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
43587c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
43597c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
43607c4063d1SFilipe Manana 						       min_push_space, 1, 0);
436154aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4362aa5d6bedSChris Mason 					ret = wret;
4363aa5d6bedSChris Mason 			}
43645f39d397SChris Mason 
43655f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4366323ac95bSChris Mason 				path->slots[1] = slot;
4367143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
43685f39d397SChris Mason 				free_extent_buffer(leaf);
4369143bede5SJeff Mahoney 				ret = 0;
43705de08d7dSChris Mason 			} else {
4371925baeddSChris Mason 				/* if we're still in the path, make sure
4372925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4373925baeddSChris Mason 				 * push_leaf functions must have already
4374925baeddSChris Mason 				 * dirtied this buffer
4375925baeddSChris Mason 				 */
4376925baeddSChris Mason 				if (path->nodes[0] == leaf)
43775f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
43785f39d397SChris Mason 				free_extent_buffer(leaf);
4379be0e5c09SChris Mason 			}
4380d5719762SChris Mason 		} else {
43815f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4382be0e5c09SChris Mason 		}
43839a8dd150SChris Mason 	}
4384aa5d6bedSChris Mason 	return ret;
43859a8dd150SChris Mason }
43869a8dd150SChris Mason 
438797571fd0SChris Mason /*
4388925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
43897bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
43907bb86316SChris Mason  * returns < 0 on io errors.
4391d352ac68SChris Mason  *
4392d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4393d352ac68SChris Mason  * time you call it.
43947bb86316SChris Mason  */
439516e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
43967bb86316SChris Mason {
4397925baeddSChris Mason 	struct btrfs_key key;
4398925baeddSChris Mason 	struct btrfs_disk_key found_key;
4399925baeddSChris Mason 	int ret;
44007bb86316SChris Mason 
4401925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4402925baeddSChris Mason 
4403e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
4404925baeddSChris Mason 		key.offset--;
4405e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
4406925baeddSChris Mason 		key.type--;
4407e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4408e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
4409925baeddSChris Mason 		key.objectid--;
4410e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
4411e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4412e8b0d724SFilipe David Borba Manana 	} else {
44137bb86316SChris Mason 		return 1;
4414e8b0d724SFilipe David Borba Manana 	}
44157bb86316SChris Mason 
4416b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4417925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4418925baeddSChris Mason 	if (ret < 0)
4419925baeddSChris Mason 		return ret;
4420925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4421925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4422337c6f68SFilipe Manana 	/*
4423337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
4424337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
4425337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
4426337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
4427337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
4428337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
4429337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
4430337c6f68SFilipe Manana 	 * the previous key we computed above.
4431337c6f68SFilipe Manana 	 */
4432337c6f68SFilipe Manana 	if (ret <= 0)
44337bb86316SChris Mason 		return 0;
4434925baeddSChris Mason 	return 1;
44357bb86316SChris Mason }
44367bb86316SChris Mason 
44373f157a2fSChris Mason /*
44383f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4439de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4440de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
44413f157a2fSChris Mason  *
44423f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
44433f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
44443f157a2fSChris Mason  * key and get a writable path.
44453f157a2fSChris Mason  *
44463f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
44473f157a2fSChris Mason  * of the tree.
44483f157a2fSChris Mason  *
4449d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4450d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4451d352ac68SChris Mason  * skipped over (without reading them).
4452d352ac68SChris Mason  *
44533f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
44543f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
44553f157a2fSChris Mason  */
44563f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4457de78b51aSEric Sandeen 			 struct btrfs_path *path,
44583f157a2fSChris Mason 			 u64 min_trans)
44593f157a2fSChris Mason {
44603f157a2fSChris Mason 	struct extent_buffer *cur;
44613f157a2fSChris Mason 	struct btrfs_key found_key;
44623f157a2fSChris Mason 	int slot;
44639652480bSYan 	int sret;
44643f157a2fSChris Mason 	u32 nritems;
44653f157a2fSChris Mason 	int level;
44663f157a2fSChris Mason 	int ret = 1;
4467f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
44683f157a2fSChris Mason 
4469*c922b016SStefan Roesch 	ASSERT(!path->nowait);
4470f98de9b9SFilipe Manana 	path->keep_locks = 1;
44713f157a2fSChris Mason again:
4472bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
44733f157a2fSChris Mason 	level = btrfs_header_level(cur);
4474e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
44753f157a2fSChris Mason 	path->nodes[level] = cur;
4476bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
44773f157a2fSChris Mason 
44783f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
44793f157a2fSChris Mason 		ret = 1;
44803f157a2fSChris Mason 		goto out;
44813f157a2fSChris Mason 	}
44823f157a2fSChris Mason 	while (1) {
44833f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
44843f157a2fSChris Mason 		level = btrfs_header_level(cur);
4485e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
4486cbca7d59SFilipe Manana 		if (sret < 0) {
4487cbca7d59SFilipe Manana 			ret = sret;
4488cbca7d59SFilipe Manana 			goto out;
4489cbca7d59SFilipe Manana 		}
44903f157a2fSChris Mason 
4491323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4492323ac95bSChris Mason 		if (level == path->lowest_level) {
4493e02119d5SChris Mason 			if (slot >= nritems)
4494e02119d5SChris Mason 				goto find_next_key;
44953f157a2fSChris Mason 			ret = 0;
44963f157a2fSChris Mason 			path->slots[level] = slot;
44973f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
44983f157a2fSChris Mason 			goto out;
44993f157a2fSChris Mason 		}
45009652480bSYan 		if (sret && slot > 0)
45019652480bSYan 			slot--;
45023f157a2fSChris Mason 		/*
4503de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4504260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
45053f157a2fSChris Mason 		 */
45063f157a2fSChris Mason 		while (slot < nritems) {
45073f157a2fSChris Mason 			u64 gen;
4508e02119d5SChris Mason 
45093f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
45103f157a2fSChris Mason 			if (gen < min_trans) {
45113f157a2fSChris Mason 				slot++;
45123f157a2fSChris Mason 				continue;
45133f157a2fSChris Mason 			}
45143f157a2fSChris Mason 			break;
45153f157a2fSChris Mason 		}
4516e02119d5SChris Mason find_next_key:
45173f157a2fSChris Mason 		/*
45183f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
45193f157a2fSChris Mason 		 * and find another one
45203f157a2fSChris Mason 		 */
45213f157a2fSChris Mason 		if (slot >= nritems) {
4522e02119d5SChris Mason 			path->slots[level] = slot;
4523e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4524de78b51aSEric Sandeen 						  min_trans);
4525e02119d5SChris Mason 			if (sret == 0) {
4526b3b4aa74SDavid Sterba 				btrfs_release_path(path);
45273f157a2fSChris Mason 				goto again;
45283f157a2fSChris Mason 			} else {
45293f157a2fSChris Mason 				goto out;
45303f157a2fSChris Mason 			}
45313f157a2fSChris Mason 		}
45323f157a2fSChris Mason 		/* save our key for returning back */
45333f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
45343f157a2fSChris Mason 		path->slots[level] = slot;
45353f157a2fSChris Mason 		if (level == path->lowest_level) {
45363f157a2fSChris Mason 			ret = 0;
45373f157a2fSChris Mason 			goto out;
45383f157a2fSChris Mason 		}
45394b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4540fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4541fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4542fb770ae4SLiu Bo 			goto out;
4543fb770ae4SLiu Bo 		}
45443f157a2fSChris Mason 
4545bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4546b4ce94deSChris Mason 
4547bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
45483f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4549f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
45503f157a2fSChris Mason 	}
45513f157a2fSChris Mason out:
4552f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4553f98de9b9SFilipe Manana 	if (ret == 0) {
4554f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4555f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4556f98de9b9SFilipe Manana 	}
45573f157a2fSChris Mason 	return ret;
45583f157a2fSChris Mason }
45593f157a2fSChris Mason 
45603f157a2fSChris Mason /*
45613f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
45623f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4563de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
45643f157a2fSChris Mason  *
45653f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
45663f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
45673f157a2fSChris Mason  *
45683f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
45693f157a2fSChris Mason  * calling this function.
45703f157a2fSChris Mason  */
4571e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4572de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4573e7a84565SChris Mason {
4574e7a84565SChris Mason 	int slot;
4575e7a84565SChris Mason 	struct extent_buffer *c;
4576e7a84565SChris Mason 
45776a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4578e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4579e7a84565SChris Mason 		if (!path->nodes[level])
4580e7a84565SChris Mason 			return 1;
4581e7a84565SChris Mason 
4582e7a84565SChris Mason 		slot = path->slots[level] + 1;
4583e7a84565SChris Mason 		c = path->nodes[level];
45843f157a2fSChris Mason next:
4585e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
458633c66f43SYan Zheng 			int ret;
458733c66f43SYan Zheng 			int orig_lowest;
458833c66f43SYan Zheng 			struct btrfs_key cur_key;
458933c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
459033c66f43SYan Zheng 			    !path->nodes[level + 1])
4591e7a84565SChris Mason 				return 1;
459233c66f43SYan Zheng 
45936a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
459433c66f43SYan Zheng 				level++;
4595e7a84565SChris Mason 				continue;
4596e7a84565SChris Mason 			}
459733c66f43SYan Zheng 
459833c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
459933c66f43SYan Zheng 			if (level == 0)
460033c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
460133c66f43SYan Zheng 			else
460233c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
460333c66f43SYan Zheng 
460433c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4605b3b4aa74SDavid Sterba 			btrfs_release_path(path);
460633c66f43SYan Zheng 			path->lowest_level = level;
460733c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
460833c66f43SYan Zheng 						0, 0);
460933c66f43SYan Zheng 			path->lowest_level = orig_lowest;
461033c66f43SYan Zheng 			if (ret < 0)
461133c66f43SYan Zheng 				return ret;
461233c66f43SYan Zheng 
461333c66f43SYan Zheng 			c = path->nodes[level];
461433c66f43SYan Zheng 			slot = path->slots[level];
461533c66f43SYan Zheng 			if (ret == 0)
461633c66f43SYan Zheng 				slot++;
461733c66f43SYan Zheng 			goto next;
461833c66f43SYan Zheng 		}
461933c66f43SYan Zheng 
4620e7a84565SChris Mason 		if (level == 0)
4621e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
46223f157a2fSChris Mason 		else {
46233f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
46243f157a2fSChris Mason 
46253f157a2fSChris Mason 			if (gen < min_trans) {
46263f157a2fSChris Mason 				slot++;
46273f157a2fSChris Mason 				goto next;
46283f157a2fSChris Mason 			}
4629e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
46303f157a2fSChris Mason 		}
4631e7a84565SChris Mason 		return 0;
4632e7a84565SChris Mason 	}
4633e7a84565SChris Mason 	return 1;
4634e7a84565SChris Mason }
4635e7a84565SChris Mason 
46363d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
46373d7806ecSJan Schmidt 			u64 time_seq)
46383d7806ecSJan Schmidt {
4639d97e63b6SChris Mason 	int slot;
46408e73f275SChris Mason 	int level;
46415f39d397SChris Mason 	struct extent_buffer *c;
46428e73f275SChris Mason 	struct extent_buffer *next;
4643d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4644925baeddSChris Mason 	struct btrfs_key key;
4645d96b3424SFilipe Manana 	bool need_commit_sem = false;
4646925baeddSChris Mason 	u32 nritems;
4647925baeddSChris Mason 	int ret;
46480e46318dSJosef Bacik 	int i;
4649925baeddSChris Mason 
4650*c922b016SStefan Roesch 	ASSERT(!path->nowait);
4651*c922b016SStefan Roesch 
4652925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4653d397712bSChris Mason 	if (nritems == 0)
4654925baeddSChris Mason 		return 1;
4655925baeddSChris Mason 
46568e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
46578e73f275SChris Mason again:
46588e73f275SChris Mason 	level = 1;
46598e73f275SChris Mason 	next = NULL;
4660b3b4aa74SDavid Sterba 	btrfs_release_path(path);
46618e73f275SChris Mason 
4662a2135011SChris Mason 	path->keep_locks = 1;
46638e73f275SChris Mason 
4664d96b3424SFilipe Manana 	if (time_seq) {
46653d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4666d96b3424SFilipe Manana 	} else {
4667d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4668d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4669d96b3424SFilipe Manana 			need_commit_sem = true;
4670d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
4671d96b3424SFilipe Manana 		}
4672925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4673d96b3424SFilipe Manana 	}
4674925baeddSChris Mason 	path->keep_locks = 0;
4675925baeddSChris Mason 
4676925baeddSChris Mason 	if (ret < 0)
4677d96b3424SFilipe Manana 		goto done;
4678925baeddSChris Mason 
4679a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4680168fd7d2SChris Mason 	/*
4681168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4682168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4683168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4684168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4685168fd7d2SChris Mason 	 */
4686a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4687e457afecSYan Zheng 		if (ret == 0)
4688168fd7d2SChris Mason 			path->slots[0]++;
46898e73f275SChris Mason 		ret = 0;
4690925baeddSChris Mason 		goto done;
4691925baeddSChris Mason 	}
46920b43e04fSLiu Bo 	/*
46930b43e04fSLiu Bo 	 * So the above check misses one case:
46940b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
46950b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
46960b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
46970b43e04fSLiu Bo 	 *
46980b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
46990b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
47000b43e04fSLiu Bo 	 *
47010b43e04fSLiu Bo 	 * And a bit more explanation about this check,
47020b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
47030b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
47040b43e04fSLiu Bo 	 * bigger one.
47050b43e04fSLiu Bo 	 */
47060b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
47070b43e04fSLiu Bo 		ret = 0;
47080b43e04fSLiu Bo 		goto done;
47090b43e04fSLiu Bo 	}
4710d97e63b6SChris Mason 
4711234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
47128e73f275SChris Mason 		if (!path->nodes[level]) {
47138e73f275SChris Mason 			ret = 1;
47148e73f275SChris Mason 			goto done;
47158e73f275SChris Mason 		}
47165f39d397SChris Mason 
4717d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4718d97e63b6SChris Mason 		c = path->nodes[level];
47195f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4720d97e63b6SChris Mason 			level++;
47218e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
47228e73f275SChris Mason 				ret = 1;
47238e73f275SChris Mason 				goto done;
47248e73f275SChris Mason 			}
4725d97e63b6SChris Mason 			continue;
4726d97e63b6SChris Mason 		}
47275f39d397SChris Mason 
47280e46318dSJosef Bacik 
47290e46318dSJosef Bacik 		/*
47300e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
47310e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
47320e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
47330e46318dSJosef Bacik 		 */
47340e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
47350e46318dSJosef Bacik 			if (path->locks[level]) {
47360e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
47370e46318dSJosef Bacik 				path->locks[i] = 0;
47380e46318dSJosef Bacik 			}
47390e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
47400e46318dSJosef Bacik 			path->nodes[i] = NULL;
4741925baeddSChris Mason 		}
47425f39d397SChris Mason 
47438e73f275SChris Mason 		next = c;
4744d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4745cda79c54SDavid Sterba 					    slot, &key);
47468e73f275SChris Mason 		if (ret == -EAGAIN)
47478e73f275SChris Mason 			goto again;
47485f39d397SChris Mason 
474976a05b35SChris Mason 		if (ret < 0) {
4750b3b4aa74SDavid Sterba 			btrfs_release_path(path);
475176a05b35SChris Mason 			goto done;
475276a05b35SChris Mason 		}
475376a05b35SChris Mason 
47545cd57b2cSChris Mason 		if (!path->skip_locking) {
4755bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4756d42244a0SJan Schmidt 			if (!ret && time_seq) {
4757d42244a0SJan Schmidt 				/*
4758d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4759d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4760d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4761d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4762d42244a0SJan Schmidt 				 * on our lock and cycle.
4763d42244a0SJan Schmidt 				 */
4764cf538830SJan Schmidt 				free_extent_buffer(next);
4765d42244a0SJan Schmidt 				btrfs_release_path(path);
4766d42244a0SJan Schmidt 				cond_resched();
4767d42244a0SJan Schmidt 				goto again;
4768d42244a0SJan Schmidt 			}
47690e46318dSJosef Bacik 			if (!ret)
47700e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4771bd681513SChris Mason 		}
4772d97e63b6SChris Mason 		break;
4773d97e63b6SChris Mason 	}
4774d97e63b6SChris Mason 	path->slots[level] = slot;
4775d97e63b6SChris Mason 	while (1) {
4776d97e63b6SChris Mason 		level--;
4777d97e63b6SChris Mason 		path->nodes[level] = next;
4778d97e63b6SChris Mason 		path->slots[level] = 0;
4779a74a4b97SChris Mason 		if (!path->skip_locking)
4780ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4781d97e63b6SChris Mason 		if (!level)
4782d97e63b6SChris Mason 			break;
4783b4ce94deSChris Mason 
4784d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4785cda79c54SDavid Sterba 					    0, &key);
47868e73f275SChris Mason 		if (ret == -EAGAIN)
47878e73f275SChris Mason 			goto again;
47888e73f275SChris Mason 
478976a05b35SChris Mason 		if (ret < 0) {
4790b3b4aa74SDavid Sterba 			btrfs_release_path(path);
479176a05b35SChris Mason 			goto done;
479276a05b35SChris Mason 		}
479376a05b35SChris Mason 
4794ffeb03cfSJosef Bacik 		if (!path->skip_locking)
47950e46318dSJosef Bacik 			btrfs_tree_read_lock(next);
4796d97e63b6SChris Mason 	}
47978e73f275SChris Mason 	ret = 0;
4798925baeddSChris Mason done:
4799f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
4800d96b3424SFilipe Manana 	if (need_commit_sem) {
4801d96b3424SFilipe Manana 		int ret2;
4802d96b3424SFilipe Manana 
4803d96b3424SFilipe Manana 		path->need_commit_sem = 1;
4804d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
4805d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
4806d96b3424SFilipe Manana 		if (ret2)
4807d96b3424SFilipe Manana 			ret = ret2;
4808d96b3424SFilipe Manana 	}
48098e73f275SChris Mason 
48108e73f275SChris Mason 	return ret;
4811d97e63b6SChris Mason }
48120b86a832SChris Mason 
48133f157a2fSChris Mason /*
48143f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
48153f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
48163f157a2fSChris Mason  *
48173f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
48183f157a2fSChris Mason  */
48190b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
48200b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
48210b86a832SChris Mason 			int type)
48220b86a832SChris Mason {
48230b86a832SChris Mason 	struct btrfs_key found_key;
48240b86a832SChris Mason 	struct extent_buffer *leaf;
4825e02119d5SChris Mason 	u32 nritems;
48260b86a832SChris Mason 	int ret;
48270b86a832SChris Mason 
48280b86a832SChris Mason 	while (1) {
48290b86a832SChris Mason 		if (path->slots[0] == 0) {
48300b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
48310b86a832SChris Mason 			if (ret != 0)
48320b86a832SChris Mason 				return ret;
48330b86a832SChris Mason 		} else {
48340b86a832SChris Mason 			path->slots[0]--;
48350b86a832SChris Mason 		}
48360b86a832SChris Mason 		leaf = path->nodes[0];
4837e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
4838e02119d5SChris Mason 		if (nritems == 0)
4839e02119d5SChris Mason 			return 1;
4840e02119d5SChris Mason 		if (path->slots[0] == nritems)
4841e02119d5SChris Mason 			path->slots[0]--;
4842e02119d5SChris Mason 
48430b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4844e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
4845e02119d5SChris Mason 			break;
48460a4eefbbSYan Zheng 		if (found_key.type == type)
48470a4eefbbSYan Zheng 			return 0;
4848e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
4849e02119d5SChris Mason 		    found_key.type < type)
4850e02119d5SChris Mason 			break;
48510b86a832SChris Mason 	}
48520b86a832SChris Mason 	return 1;
48530b86a832SChris Mason }
4854ade2e0b3SWang Shilong 
4855ade2e0b3SWang Shilong /*
4856ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
4857ade2e0b3SWang Shilong  * min objecitd.
4858ade2e0b3SWang Shilong  *
4859ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4860ade2e0b3SWang Shilong  */
4861ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
4862ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
4863ade2e0b3SWang Shilong {
4864ade2e0b3SWang Shilong 	struct btrfs_key found_key;
4865ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
4866ade2e0b3SWang Shilong 	u32 nritems;
4867ade2e0b3SWang Shilong 	int ret;
4868ade2e0b3SWang Shilong 
4869ade2e0b3SWang Shilong 	while (1) {
4870ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
4871ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
4872ade2e0b3SWang Shilong 			if (ret != 0)
4873ade2e0b3SWang Shilong 				return ret;
4874ade2e0b3SWang Shilong 		} else {
4875ade2e0b3SWang Shilong 			path->slots[0]--;
4876ade2e0b3SWang Shilong 		}
4877ade2e0b3SWang Shilong 		leaf = path->nodes[0];
4878ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
4879ade2e0b3SWang Shilong 		if (nritems == 0)
4880ade2e0b3SWang Shilong 			return 1;
4881ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
4882ade2e0b3SWang Shilong 			path->slots[0]--;
4883ade2e0b3SWang Shilong 
4884ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4885ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
4886ade2e0b3SWang Shilong 			break;
4887ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4888ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
4889ade2e0b3SWang Shilong 			return 0;
4890ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
4891ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
4892ade2e0b3SWang Shilong 			break;
4893ade2e0b3SWang Shilong 	}
4894ade2e0b3SWang Shilong 	return 1;
4895ade2e0b3SWang Shilong }
4896