xref: /openbmc/linux/fs/btrfs/ctree.c (revision 9b569ea0be6fb27a4985acc9325896a3edc95ede)
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>
11*9b569ea0SJosef Bacik #include "messages.h"
12eb60ceacSChris Mason #include "ctree.h"
13eb60ceacSChris Mason #include "disk-io.h"
147f5c1516SChris Mason #include "transaction.h"
155f39d397SChris Mason #include "print-tree.h"
16925baeddSChris Mason #include "locking.h"
17de37aa51SNikolay Borisov #include "volumes.h"
18f616f5cdSQu Wenruo #include "qgroup.h"
19f3a84ccdSFilipe Manana #include "tree-mod-log.h"
2088c602abSQu Wenruo #include "tree-checker.h"
219a8dd150SChris Mason 
22226463d7SJosef Bacik static struct kmem_cache *btrfs_path_cachep;
23226463d7SJosef Bacik 
24e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
25e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
26310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
27310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
28310712b2SOmar Sandoval 		      int data_size, int extend);
295f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
302ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
31971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
325f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
335f39d397SChris Mason 			      struct extent_buffer *dst_buf,
345f39d397SChris Mason 			      struct extent_buffer *src_buf);
35afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
36afe5fea7STsutomu Itoh 		    int level, int slot);
37d97e63b6SChris Mason 
38af024ed2SJohannes Thumshirn static const struct btrfs_csums {
39af024ed2SJohannes Thumshirn 	u16		size;
4059a0fcdbSDavid Sterba 	const char	name[10];
4159a0fcdbSDavid Sterba 	const char	driver[12];
42af024ed2SJohannes Thumshirn } btrfs_csums[] = {
43af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
443951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
453831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
46352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
47352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
48af024ed2SJohannes Thumshirn };
49af024ed2SJohannes Thumshirn 
50af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
51af024ed2SJohannes Thumshirn {
52af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
53af024ed2SJohannes Thumshirn 	/*
54af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
55af024ed2SJohannes Thumshirn 	 */
56af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
57af024ed2SJohannes Thumshirn }
58af024ed2SJohannes Thumshirn 
59af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
60af024ed2SJohannes Thumshirn {
61af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
62af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
63af024ed2SJohannes Thumshirn }
64af024ed2SJohannes Thumshirn 
65b4e967beSDavid Sterba /*
66b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
67b4e967beSDavid Sterba  * name
68b4e967beSDavid Sterba  */
69b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
70b4e967beSDavid Sterba {
71b4e967beSDavid Sterba 	/* csum type is validated at mount time */
7259a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
7359a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
74b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
75b4e967beSDavid Sterba }
76b4e967beSDavid Sterba 
77604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
78f7cea56cSDavid Sterba {
79f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
80f7cea56cSDavid Sterba }
81f7cea56cSDavid Sterba 
822c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
832c90e5d6SChris Mason {
84e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
852c90e5d6SChris Mason }
862c90e5d6SChris Mason 
87d352ac68SChris Mason /* this also releases the path */
882c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
892c90e5d6SChris Mason {
90ff175d57SJesper Juhl 	if (!p)
91ff175d57SJesper Juhl 		return;
92b3b4aa74SDavid Sterba 	btrfs_release_path(p);
932c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
942c90e5d6SChris Mason }
952c90e5d6SChris Mason 
96d352ac68SChris Mason /*
97d352ac68SChris Mason  * path release drops references on the extent buffers in the path
98d352ac68SChris Mason  * and it drops any locks held by this path
99d352ac68SChris Mason  *
100d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
101d352ac68SChris Mason  */
102b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
103eb60ceacSChris Mason {
104eb60ceacSChris Mason 	int i;
105a2135011SChris Mason 
106234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1073f157a2fSChris Mason 		p->slots[i] = 0;
108eb60ceacSChris Mason 		if (!p->nodes[i])
109925baeddSChris Mason 			continue;
110925baeddSChris Mason 		if (p->locks[i]) {
111bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
112925baeddSChris Mason 			p->locks[i] = 0;
113925baeddSChris Mason 		}
1145f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1153f157a2fSChris Mason 		p->nodes[i] = NULL;
116eb60ceacSChris Mason 	}
117eb60ceacSChris Mason }
118eb60ceacSChris Mason 
119d352ac68SChris Mason /*
1208bb808c6SDavid Sterba  * We want the transaction abort to print stack trace only for errors where the
1218bb808c6SDavid Sterba  * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
1228bb808c6SDavid Sterba  * caused by external factors.
1238bb808c6SDavid Sterba  */
1248bb808c6SDavid Sterba bool __cold abort_should_print_stack(int errno)
1258bb808c6SDavid Sterba {
1268bb808c6SDavid Sterba 	switch (errno) {
1278bb808c6SDavid Sterba 	case -EIO:
1288bb808c6SDavid Sterba 	case -EROFS:
1298bb808c6SDavid Sterba 	case -ENOMEM:
1308bb808c6SDavid Sterba 		return false;
1318bb808c6SDavid Sterba 	}
1328bb808c6SDavid Sterba 	return true;
1338bb808c6SDavid Sterba }
1348bb808c6SDavid Sterba 
1358bb808c6SDavid Sterba /*
136d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
137d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
138d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
139d352ac68SChris Mason  * looping required.
140d352ac68SChris Mason  *
141d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
142d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
143d352ac68SChris Mason  * at any time because there are no locks held.
144d352ac68SChris Mason  */
145925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
146925baeddSChris Mason {
147925baeddSChris Mason 	struct extent_buffer *eb;
148240f62c8SChris Mason 
1493083ee2eSJosef Bacik 	while (1) {
150240f62c8SChris Mason 		rcu_read_lock();
151240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1523083ee2eSJosef Bacik 
1533083ee2eSJosef Bacik 		/*
1543083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
15501327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1563083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1573083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1583083ee2eSJosef Bacik 		 */
1593083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
160240f62c8SChris Mason 			rcu_read_unlock();
1613083ee2eSJosef Bacik 			break;
1623083ee2eSJosef Bacik 		}
1633083ee2eSJosef Bacik 		rcu_read_unlock();
1643083ee2eSJosef Bacik 		synchronize_rcu();
1653083ee2eSJosef Bacik 	}
166925baeddSChris Mason 	return eb;
167925baeddSChris Mason }
168925baeddSChris Mason 
16992a7cc42SQu Wenruo /*
17092a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
17192a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
17292a7cc42SQu Wenruo  * sure they get properly updated on disk.
173d352ac68SChris Mason  */
1740b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1750b86a832SChris Mason {
1760b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1770b246afaSJeff Mahoney 
178e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
179e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
180e7070be1SJosef Bacik 		return;
181e7070be1SJosef Bacik 
1820b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
183e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
184e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
1854fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
186e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
1870b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
188e7070be1SJosef Bacik 		else
189e7070be1SJosef Bacik 			list_move(&root->dirty_list,
1900b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
1910b86a832SChris Mason 	}
1920b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1930b86a832SChris Mason }
1940b86a832SChris Mason 
195d352ac68SChris Mason /*
196d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
197d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
198d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
199d352ac68SChris Mason  */
200be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
201be20aa9dSChris Mason 		      struct btrfs_root *root,
202be20aa9dSChris Mason 		      struct extent_buffer *buf,
203be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
204be20aa9dSChris Mason {
2050b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
206be20aa9dSChris Mason 	struct extent_buffer *cow;
207be20aa9dSChris Mason 	int ret = 0;
208be20aa9dSChris Mason 	int level;
2095d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
210be20aa9dSChris Mason 
21192a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2120b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
21392a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
21427cdeb70SMiao Xie 		trans->transid != root->last_trans);
215be20aa9dSChris Mason 
216be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2175d4f98a2SYan Zheng 	if (level == 0)
2185d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2195d4f98a2SYan Zheng 	else
2205d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
22131840ae1SZheng Yan 
2224d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
223cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
224cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
2255d4f98a2SYan Zheng 	if (IS_ERR(cow))
226be20aa9dSChris Mason 		return PTR_ERR(cow);
227be20aa9dSChris Mason 
22858e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
229be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
230be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2315d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2325d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2335d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2345d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2355d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2365d4f98a2SYan Zheng 	else
237be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
238be20aa9dSChris Mason 
239de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2402b82032cSYan Zheng 
241be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2425d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
243e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2445d4f98a2SYan Zheng 	else
245e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
246867ed321SJosef Bacik 	if (ret) {
24772c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
24872c9925fSFilipe Manana 		free_extent_buffer(cow);
249867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
250be20aa9dSChris Mason 		return ret;
251867ed321SJosef Bacik 	}
252be20aa9dSChris Mason 
253be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
254be20aa9dSChris Mason 	*cow_ret = cow;
255be20aa9dSChris Mason 	return 0;
256be20aa9dSChris Mason }
257be20aa9dSChris Mason 
258d352ac68SChris Mason /*
2595d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
2605d4f98a2SYan Zheng  */
2615d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
2625d4f98a2SYan Zheng 			      struct extent_buffer *buf)
2635d4f98a2SYan Zheng {
2645d4f98a2SYan Zheng 	/*
26592a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
26692a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
26792a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
2685d4f98a2SYan Zheng 	 */
26992a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2705d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
2715d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
2725d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
2735d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
2745d4f98a2SYan Zheng 		return 1;
275a79865c6SNikolay Borisov 
2765d4f98a2SYan Zheng 	return 0;
2775d4f98a2SYan Zheng }
2785d4f98a2SYan Zheng 
2795d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
2805d4f98a2SYan Zheng 				       struct btrfs_root *root,
2815d4f98a2SYan Zheng 				       struct extent_buffer *buf,
282f0486c68SYan, Zheng 				       struct extent_buffer *cow,
283f0486c68SYan, Zheng 				       int *last_ref)
2845d4f98a2SYan Zheng {
2850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2865d4f98a2SYan Zheng 	u64 refs;
2875d4f98a2SYan Zheng 	u64 owner;
2885d4f98a2SYan Zheng 	u64 flags;
2895d4f98a2SYan Zheng 	u64 new_flags = 0;
2905d4f98a2SYan Zheng 	int ret;
2915d4f98a2SYan Zheng 
2925d4f98a2SYan Zheng 	/*
2935d4f98a2SYan Zheng 	 * Backrefs update rules:
2945d4f98a2SYan Zheng 	 *
2955d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
2965d4f98a2SYan Zheng 	 * allocated by tree relocation.
2975d4f98a2SYan Zheng 	 *
2985d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
2995d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
3005d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
3015d4f98a2SYan Zheng 	 *
3025d4f98a2SYan Zheng 	 * If a tree block is been relocating
3035d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
3045d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
3055d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
3065d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
3075d4f98a2SYan Zheng 	 */
3085d4f98a2SYan Zheng 
3095d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
3102ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
3113173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
3123173a18fSJosef Bacik 					       &refs, &flags);
313be1a5564SMark Fasheh 		if (ret)
314be1a5564SMark Fasheh 			return ret;
315e5df9573SMark Fasheh 		if (refs == 0) {
316e5df9573SMark Fasheh 			ret = -EROFS;
3170b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
318e5df9573SMark Fasheh 			return ret;
319e5df9573SMark Fasheh 		}
3205d4f98a2SYan Zheng 	} else {
3215d4f98a2SYan Zheng 		refs = 1;
3225d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
3235d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
3245d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
3255d4f98a2SYan Zheng 		else
3265d4f98a2SYan Zheng 			flags = 0;
3275d4f98a2SYan Zheng 	}
3285d4f98a2SYan Zheng 
3295d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
3305d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
3315d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
3325d4f98a2SYan Zheng 
3335d4f98a2SYan Zheng 	if (refs > 1) {
3345d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
3355d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
3365d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
337e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
338692826b2SJeff Mahoney 			if (ret)
339692826b2SJeff Mahoney 				return ret;
3405d4f98a2SYan Zheng 
3415d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3425d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
343e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
344692826b2SJeff Mahoney 				if (ret)
345692826b2SJeff Mahoney 					return ret;
346e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
347692826b2SJeff Mahoney 				if (ret)
348692826b2SJeff Mahoney 					return ret;
3495d4f98a2SYan Zheng 			}
3505d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
3515d4f98a2SYan Zheng 		} else {
3525d4f98a2SYan Zheng 
3535d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3545d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
355e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3565d4f98a2SYan Zheng 			else
357e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
358692826b2SJeff Mahoney 			if (ret)
359692826b2SJeff Mahoney 				return ret;
3605d4f98a2SYan Zheng 		}
3615d4f98a2SYan Zheng 		if (new_flags != 0) {
362b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
363b1c79e09SJosef Bacik 
36442c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
3652fe6a5a1SDavid Sterba 							  new_flags, level);
366be1a5564SMark Fasheh 			if (ret)
367be1a5564SMark Fasheh 				return ret;
3685d4f98a2SYan Zheng 		}
3695d4f98a2SYan Zheng 	} else {
3705d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
3715d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3725d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
373e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3745d4f98a2SYan Zheng 			else
375e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
376692826b2SJeff Mahoney 			if (ret)
377692826b2SJeff Mahoney 				return ret;
378e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
379692826b2SJeff Mahoney 			if (ret)
380692826b2SJeff Mahoney 				return ret;
3815d4f98a2SYan Zheng 		}
3826a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
383f0486c68SYan, Zheng 		*last_ref = 1;
3845d4f98a2SYan Zheng 	}
3855d4f98a2SYan Zheng 	return 0;
3865d4f98a2SYan Zheng }
3875d4f98a2SYan Zheng 
3885d4f98a2SYan Zheng /*
389d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
390d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
391d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
392d397712bSChris Mason  * dirty again.
393d352ac68SChris Mason  *
394d352ac68SChris Mason  * search_start -- an allocation hint for the new block
395d352ac68SChris Mason  *
396d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
397d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
398d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
399d352ac68SChris Mason  */
400d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
4015f39d397SChris Mason 			     struct btrfs_root *root,
4025f39d397SChris Mason 			     struct extent_buffer *buf,
4035f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
4045f39d397SChris Mason 			     struct extent_buffer **cow_ret,
4059631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
4069631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
4076702ed49SChris Mason {
4080b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4095d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
4105f39d397SChris Mason 	struct extent_buffer *cow;
411be1a5564SMark Fasheh 	int level, ret;
412f0486c68SYan, Zheng 	int last_ref = 0;
413925baeddSChris Mason 	int unlock_orig = 0;
4140f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
4156702ed49SChris Mason 
416925baeddSChris Mason 	if (*cow_ret == buf)
417925baeddSChris Mason 		unlock_orig = 1;
418925baeddSChris Mason 
41949d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
420925baeddSChris Mason 
42192a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
4220b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
42392a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
42427cdeb70SMiao Xie 		trans->transid != root->last_trans);
4255f39d397SChris Mason 
4267bb86316SChris Mason 	level = btrfs_header_level(buf);
42731840ae1SZheng Yan 
4285d4f98a2SYan Zheng 	if (level == 0)
4295d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
4305d4f98a2SYan Zheng 	else
4315d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
4325d4f98a2SYan Zheng 
4330f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
4345d4f98a2SYan Zheng 		parent_start = parent->start;
4355d4f98a2SYan Zheng 
43679bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
43779bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
43879bd3712SFilipe Manana 				     search_start, empty_size, nest);
4396702ed49SChris Mason 	if (IS_ERR(cow))
4406702ed49SChris Mason 		return PTR_ERR(cow);
4416702ed49SChris Mason 
442b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
443b4ce94deSChris Mason 
44458e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
445db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
4465f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
4475d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
4485d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
4495d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
4505d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
4515d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
4525d4f98a2SYan Zheng 	else
4535f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
4546702ed49SChris Mason 
455de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
4562b82032cSYan Zheng 
457be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
458b68dc2a9SMark Fasheh 	if (ret) {
459572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
460572c83acSJosef Bacik 		free_extent_buffer(cow);
46166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
462b68dc2a9SMark Fasheh 		return ret;
463b68dc2a9SMark Fasheh 	}
4641a40e23bSZheng Yan 
46592a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
46683d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
46793314e3bSZhaolei 		if (ret) {
468572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
469572c83acSJosef Bacik 			free_extent_buffer(cow);
47066642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
47183d4cfd4SJosef Bacik 			return ret;
47283d4cfd4SJosef Bacik 		}
47393314e3bSZhaolei 	}
4743fd0a558SYan, Zheng 
4756702ed49SChris Mason 	if (buf == root->node) {
476925baeddSChris Mason 		WARN_ON(parent && parent != buf);
4775d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4785d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4795d4f98a2SYan Zheng 			parent_start = buf->start;
480925baeddSChris Mason 
48167439dadSDavid Sterba 		atomic_inc(&cow->refs);
482406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
483d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
484240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
485925baeddSChris Mason 
4867a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
4877a163608SFilipe Manana 				      parent_start, last_ref);
4885f39d397SChris Mason 		free_extent_buffer(buf);
4890b86a832SChris Mason 		add_root_to_dirty_list(root);
4906702ed49SChris Mason 	} else {
4915d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
492f3a84ccdSFilipe Manana 		btrfs_tree_mod_log_insert_key(parent, parent_slot,
49333cff222SFilipe Manana 					      BTRFS_MOD_LOG_KEY_REPLACE);
4945f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
495db94535dSChris Mason 					cow->start);
49674493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
49774493f7aSChris Mason 					      trans->transid);
4986702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
4995de865eeSFilipe David Borba Manana 		if (last_ref) {
500f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
5015de865eeSFilipe David Borba Manana 			if (ret) {
502572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
503572c83acSJosef Bacik 				free_extent_buffer(cow);
50466642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
5055de865eeSFilipe David Borba Manana 				return ret;
5065de865eeSFilipe David Borba Manana 			}
5075de865eeSFilipe David Borba Manana 		}
5087a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
5097a163608SFilipe Manana 				      parent_start, last_ref);
5106702ed49SChris Mason 	}
511925baeddSChris Mason 	if (unlock_orig)
512925baeddSChris Mason 		btrfs_tree_unlock(buf);
5133083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
5146702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
5156702ed49SChris Mason 	*cow_ret = cow;
5166702ed49SChris Mason 	return 0;
5176702ed49SChris Mason }
5186702ed49SChris Mason 
5195d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
5205d4f98a2SYan Zheng 				   struct btrfs_root *root,
5215d4f98a2SYan Zheng 				   struct extent_buffer *buf)
5225d4f98a2SYan Zheng {
523f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
524faa2dbf0SJosef Bacik 		return 0;
525fccb84c9SDavid Sterba 
526d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
527d1980131SDavid Sterba 	smp_mb__before_atomic();
528f1ebcc74SLiu Bo 
529f1ebcc74SLiu Bo 	/*
530f1ebcc74SLiu Bo 	 * We do not need to cow a block if
531f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
532f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
533f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
534f1ebcc74SLiu Bo 	 *
535f1ebcc74SLiu Bo 	 * What is forced COW:
53601327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
53752042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
538f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
539f1ebcc74SLiu Bo 	 */
5405d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
5415d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
5425d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
543f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
54427cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
5455d4f98a2SYan Zheng 		return 0;
5465d4f98a2SYan Zheng 	return 1;
5475d4f98a2SYan Zheng }
5485d4f98a2SYan Zheng 
549d352ac68SChris Mason /*
550d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
55101327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
552d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
553d352ac68SChris Mason  */
554d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
5555f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
5565f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
5579631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
5589631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
55902217ed2SChris Mason {
5600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5616702ed49SChris Mason 	u64 search_start;
562f510cfecSChris Mason 	int ret;
563dc17ff8fSChris Mason 
56483354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
56583354f07SJosef Bacik 		btrfs_err(fs_info,
56683354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
56783354f07SJosef Bacik 
5680b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
56931b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
570c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
5710b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
57231b1a2bdSJulia Lawall 
5730b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
57431b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
5750b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
576dc17ff8fSChris Mason 
5775d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
57802217ed2SChris Mason 		*cow_ret = buf;
57902217ed2SChris Mason 		return 0;
58002217ed2SChris Mason 	}
581c487685dSChris Mason 
582ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
583b4ce94deSChris Mason 
584f616f5cdSQu Wenruo 	/*
585f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
586f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
587f616f5cdSQu Wenruo 	 *
588f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
589f616f5cdSQu Wenruo 	 */
590f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
591f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
5929631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
5931abe9b8aSliubo 
5941abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
5951abe9b8aSliubo 
596f510cfecSChris Mason 	return ret;
5972c90e5d6SChris Mason }
598f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
5996702ed49SChris Mason 
600d352ac68SChris Mason /*
601d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
602d352ac68SChris Mason  * node are actually close by
603d352ac68SChris Mason  */
6046b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
6056702ed49SChris Mason {
6066b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
6076702ed49SChris Mason 		return 1;
6086b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
6096702ed49SChris Mason 		return 1;
61002217ed2SChris Mason 	return 0;
61102217ed2SChris Mason }
61202217ed2SChris Mason 
613ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
614ce6ef5abSDavid Sterba 
615ce6ef5abSDavid Sterba /*
616ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
617ce6ef5abSDavid Sterba  * we can avoid the conversion.
618ce6ef5abSDavid Sterba  */
619ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
620ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
621ce6ef5abSDavid Sterba {
622ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
623ce6ef5abSDavid Sterba 
624ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
625ce6ef5abSDavid Sterba }
626ce6ef5abSDavid Sterba 
627ce6ef5abSDavid Sterba #else
628ce6ef5abSDavid Sterba 
629081e9573SChris Mason /*
630081e9573SChris Mason  * compare two keys in a memcmp fashion
631081e9573SChris Mason  */
632310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
633310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
634081e9573SChris Mason {
635081e9573SChris Mason 	struct btrfs_key k1;
636081e9573SChris Mason 
637081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
638081e9573SChris Mason 
63920736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
640081e9573SChris Mason }
641ce6ef5abSDavid Sterba #endif
642081e9573SChris Mason 
643f3465ca4SJosef Bacik /*
644f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
645f3465ca4SJosef Bacik  */
646e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
647f3465ca4SJosef Bacik {
648f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
649f3465ca4SJosef Bacik 		return 1;
650f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
651f3465ca4SJosef Bacik 		return -1;
652f3465ca4SJosef Bacik 	if (k1->type > k2->type)
653f3465ca4SJosef Bacik 		return 1;
654f3465ca4SJosef Bacik 	if (k1->type < k2->type)
655f3465ca4SJosef Bacik 		return -1;
656f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
657f3465ca4SJosef Bacik 		return 1;
658f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
659f3465ca4SJosef Bacik 		return -1;
660f3465ca4SJosef Bacik 	return 0;
661f3465ca4SJosef Bacik }
662081e9573SChris Mason 
663d352ac68SChris Mason /*
664d352ac68SChris Mason  * this is used by the defrag code to go through all the
665d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
666d352ac68SChris Mason  * disk order is close to key order
667d352ac68SChris Mason  */
6686702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
6695f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
670de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
671a6b6e75eSChris Mason 		       struct btrfs_key *progress)
6726702ed49SChris Mason {
6730b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6746b80053dSChris Mason 	struct extent_buffer *cur;
6756702ed49SChris Mason 	u64 blocknr;
676e9d0b13bSChris Mason 	u64 search_start = *last_ret;
677e9d0b13bSChris Mason 	u64 last_block = 0;
6786702ed49SChris Mason 	u64 other;
6796702ed49SChris Mason 	u32 parent_nritems;
6806702ed49SChris Mason 	int end_slot;
6816702ed49SChris Mason 	int i;
6826702ed49SChris Mason 	int err = 0;
6836b80053dSChris Mason 	u32 blocksize;
684081e9573SChris Mason 	int progress_passed = 0;
685081e9573SChris Mason 	struct btrfs_disk_key disk_key;
6866702ed49SChris Mason 
6870b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
6880b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
68986479a04SChris Mason 
6906b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
6910b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
6925dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
6936702ed49SChris Mason 
6945dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
6956702ed49SChris Mason 		return 0;
6966702ed49SChris Mason 
6975dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
6986702ed49SChris Mason 		int close = 1;
699a6b6e75eSChris Mason 
700081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
701081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
702081e9573SChris Mason 			continue;
703081e9573SChris Mason 
704081e9573SChris Mason 		progress_passed = 1;
7056b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
706e9d0b13bSChris Mason 		if (last_block == 0)
707e9d0b13bSChris Mason 			last_block = blocknr;
7085708b959SChris Mason 
7096702ed49SChris Mason 		if (i > 0) {
7106b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
7116b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
7126702ed49SChris Mason 		}
7135dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
7146b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
7156b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
7166702ed49SChris Mason 		}
717e9d0b13bSChris Mason 		if (close) {
718e9d0b13bSChris Mason 			last_block = blocknr;
7196702ed49SChris Mason 			continue;
720e9d0b13bSChris Mason 		}
7216702ed49SChris Mason 
722206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
723206983b7SJosef Bacik 		if (IS_ERR(cur))
72464c043deSLiu Bo 			return PTR_ERR(cur);
725e9d0b13bSChris Mason 		if (search_start == 0)
7266b80053dSChris Mason 			search_start = last_block;
727e9d0b13bSChris Mason 
728e7a84565SChris Mason 		btrfs_tree_lock(cur);
7296b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
730e7a84565SChris Mason 					&cur, search_start,
7316b80053dSChris Mason 					min(16 * blocksize,
7329631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
7339631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
734252c38f0SYan 		if (err) {
735e7a84565SChris Mason 			btrfs_tree_unlock(cur);
7366b80053dSChris Mason 			free_extent_buffer(cur);
7376702ed49SChris Mason 			break;
738252c38f0SYan 		}
739e7a84565SChris Mason 		search_start = cur->start;
740e7a84565SChris Mason 		last_block = cur->start;
741f2183bdeSChris Mason 		*last_ret = search_start;
742e7a84565SChris Mason 		btrfs_tree_unlock(cur);
743e7a84565SChris Mason 		free_extent_buffer(cur);
7446702ed49SChris Mason 	}
7456702ed49SChris Mason 	return err;
7466702ed49SChris Mason }
7476702ed49SChris Mason 
74874123bd7SChris Mason /*
749fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
7505f39d397SChris Mason  *
751fb81212cSFilipe Manana  * The lower boundary for the search is specified by the slot number @low. Use a
752fb81212cSFilipe Manana  * value of 0 to search over the whole extent buffer.
75374123bd7SChris Mason  *
754fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
755fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
756fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
757fb81212cSFilipe Manana  *
758fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
759fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
76074123bd7SChris Mason  */
761fb81212cSFilipe Manana static noinline int generic_bin_search(struct extent_buffer *eb, int low,
76267d5e289SMarcos Paulo de Souza 				       const struct btrfs_key *key, int *slot)
763be0e5c09SChris Mason {
764fb81212cSFilipe Manana 	unsigned long p;
765fb81212cSFilipe Manana 	int item_size;
76667d5e289SMarcos Paulo de Souza 	int high = btrfs_header_nritems(eb);
767be0e5c09SChris Mason 	int ret;
7685cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
769be0e5c09SChris Mason 
7705e24e9afSLiu Bo 	if (low > high) {
7715e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
7725e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
7735e24e9afSLiu Bo 			  __func__, low, high, eb->start,
7745e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
7755e24e9afSLiu Bo 		return -EINVAL;
7765e24e9afSLiu Bo 	}
7775e24e9afSLiu Bo 
778fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
779fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
780fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
781fb81212cSFilipe Manana 	} else {
782fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
783fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
784fb81212cSFilipe Manana 	}
785fb81212cSFilipe Manana 
786be0e5c09SChris Mason 	while (low < high) {
7875cd17f34SDavid Sterba 		unsigned long oip;
7885cd17f34SDavid Sterba 		unsigned long offset;
7895cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
7905cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
7915cd17f34SDavid Sterba 		int mid;
7925cd17f34SDavid Sterba 
793be0e5c09SChris Mason 		mid = (low + high) / 2;
7945f39d397SChris Mason 		offset = p + mid * item_size;
7955cd17f34SDavid Sterba 		oip = offset_in_page(offset);
7965f39d397SChris Mason 
7975cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
798884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
7995cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
800934d375bSChris Mason 
801884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
8025cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
8035cd17f34SDavid Sterba 		} else {
8045cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
8055f39d397SChris Mason 			tmp = &unaligned;
806479965d6SChris Mason 		}
807479965d6SChris Mason 
808be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
809be0e5c09SChris Mason 
810be0e5c09SChris Mason 		if (ret < 0)
811be0e5c09SChris Mason 			low = mid + 1;
812be0e5c09SChris Mason 		else if (ret > 0)
813be0e5c09SChris Mason 			high = mid;
814be0e5c09SChris Mason 		else {
815be0e5c09SChris Mason 			*slot = mid;
816be0e5c09SChris Mason 			return 0;
817be0e5c09SChris Mason 		}
818be0e5c09SChris Mason 	}
819be0e5c09SChris Mason 	*slot = low;
820be0e5c09SChris Mason 	return 1;
821be0e5c09SChris Mason }
822be0e5c09SChris Mason 
82397571fd0SChris Mason /*
824fb81212cSFilipe Manana  * Simple binary search on an extent buffer. Works for both leaves and nodes, and
825fb81212cSFilipe Manana  * always searches over the whole range of keys (slot 0 to slot 'nritems - 1').
82697571fd0SChris Mason  */
827a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
828e3b83361SQu Wenruo 		     int *slot)
829be0e5c09SChris Mason {
830fb81212cSFilipe Manana 	return generic_bin_search(eb, 0, key, slot);
831be0e5c09SChris Mason }
832be0e5c09SChris Mason 
833f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
834f0486c68SYan, Zheng {
835f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
836f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
837f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
838f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
839f0486c68SYan, Zheng }
840f0486c68SYan, Zheng 
841f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
842f0486c68SYan, Zheng {
843f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
844f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
845f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
846f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
847f0486c68SYan, Zheng }
848f0486c68SYan, Zheng 
849d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
850d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
851d352ac68SChris Mason  */
8524b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
8534b231ae4SDavid Sterba 					   int slot)
854bb803951SChris Mason {
855ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
856416bc658SJosef Bacik 	struct extent_buffer *eb;
857581c1760SQu Wenruo 	struct btrfs_key first_key;
858416bc658SJosef Bacik 
859fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
860fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
861ca7a79adSChris Mason 
862ca7a79adSChris Mason 	BUG_ON(level == 0);
863ca7a79adSChris Mason 
864581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
865d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
8661b7ec85eSJosef Bacik 			     btrfs_header_owner(parent),
867581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
868581c1760SQu Wenruo 			     level - 1, &first_key);
8694eb150d6SQu Wenruo 	if (IS_ERR(eb))
8704eb150d6SQu Wenruo 		return eb;
8714eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
872416bc658SJosef Bacik 		free_extent_buffer(eb);
8734eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
874416bc658SJosef Bacik 	}
875416bc658SJosef Bacik 
876416bc658SJosef Bacik 	return eb;
877bb803951SChris Mason }
878bb803951SChris Mason 
879d352ac68SChris Mason /*
880d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
881d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
882d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
883d352ac68SChris Mason  */
884e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
88598ed5174SChris Mason 			 struct btrfs_root *root,
88698ed5174SChris Mason 			 struct btrfs_path *path, int level)
887bb803951SChris Mason {
8880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8895f39d397SChris Mason 	struct extent_buffer *right = NULL;
8905f39d397SChris Mason 	struct extent_buffer *mid;
8915f39d397SChris Mason 	struct extent_buffer *left = NULL;
8925f39d397SChris Mason 	struct extent_buffer *parent = NULL;
893bb803951SChris Mason 	int ret = 0;
894bb803951SChris Mason 	int wret;
895bb803951SChris Mason 	int pslot;
896bb803951SChris Mason 	int orig_slot = path->slots[level];
89779f95c82SChris Mason 	u64 orig_ptr;
898bb803951SChris Mason 
89998e6b1ebSLiu Bo 	ASSERT(level > 0);
900bb803951SChris Mason 
9015f39d397SChris Mason 	mid = path->nodes[level];
902b4ce94deSChris Mason 
903ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
9047bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
9057bb86316SChris Mason 
9061d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
90779f95c82SChris Mason 
908a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
9095f39d397SChris Mason 		parent = path->nodes[level + 1];
910bb803951SChris Mason 		pslot = path->slots[level + 1];
911a05a9bb1SLi Zefan 	}
912bb803951SChris Mason 
91340689478SChris Mason 	/*
91440689478SChris Mason 	 * deal with the case where there is only one pointer in the root
91540689478SChris Mason 	 * by promoting the node below to a root
91640689478SChris Mason 	 */
9175f39d397SChris Mason 	if (!parent) {
9185f39d397SChris Mason 		struct extent_buffer *child;
919bb803951SChris Mason 
9205f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
921bb803951SChris Mason 			return 0;
922bb803951SChris Mason 
923bb803951SChris Mason 		/* promote the child to a root */
9244b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
925fb770ae4SLiu Bo 		if (IS_ERR(child)) {
926fb770ae4SLiu Bo 			ret = PTR_ERR(child);
9270b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
928305a26afSMark Fasheh 			goto enospc;
929305a26afSMark Fasheh 		}
930305a26afSMark Fasheh 
931925baeddSChris Mason 		btrfs_tree_lock(child);
9329631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
9339631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
934f0486c68SYan, Zheng 		if (ret) {
935f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
936f0486c68SYan, Zheng 			free_extent_buffer(child);
937f0486c68SYan, Zheng 			goto enospc;
938f0486c68SYan, Zheng 		}
9392f375ab9SYan 
940406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
941d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
942240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
943925baeddSChris Mason 
9440b86a832SChris Mason 		add_root_to_dirty_list(root);
945925baeddSChris Mason 		btrfs_tree_unlock(child);
946b4ce94deSChris Mason 
947925baeddSChris Mason 		path->locks[level] = 0;
948bb803951SChris Mason 		path->nodes[level] = NULL;
9496a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
950925baeddSChris Mason 		btrfs_tree_unlock(mid);
951bb803951SChris Mason 		/* once for the path */
9525f39d397SChris Mason 		free_extent_buffer(mid);
953f0486c68SYan, Zheng 
954f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
9557a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
956bb803951SChris Mason 		/* once for the root ptr */
9573083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
958f0486c68SYan, Zheng 		return 0;
959bb803951SChris Mason 	}
9605f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
9610b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
962bb803951SChris Mason 		return 0;
963bb803951SChris Mason 
9644b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
965fb770ae4SLiu Bo 	if (IS_ERR(left))
966fb770ae4SLiu Bo 		left = NULL;
967fb770ae4SLiu Bo 
9685f39d397SChris Mason 	if (left) {
969bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
9705f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
9719631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
972bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
97354aa1f4dSChris Mason 		if (wret) {
97454aa1f4dSChris Mason 			ret = wret;
97554aa1f4dSChris Mason 			goto enospc;
97654aa1f4dSChris Mason 		}
9772cc58cf2SChris Mason 	}
978fb770ae4SLiu Bo 
9794b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
980fb770ae4SLiu Bo 	if (IS_ERR(right))
981fb770ae4SLiu Bo 		right = NULL;
982fb770ae4SLiu Bo 
9835f39d397SChris Mason 	if (right) {
984bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
9855f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
9869631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
987bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
9882cc58cf2SChris Mason 		if (wret) {
9892cc58cf2SChris Mason 			ret = wret;
9902cc58cf2SChris Mason 			goto enospc;
9912cc58cf2SChris Mason 		}
9922cc58cf2SChris Mason 	}
9932cc58cf2SChris Mason 
9942cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
9955f39d397SChris Mason 	if (left) {
9965f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
997d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
99879f95c82SChris Mason 		if (wret < 0)
99979f95c82SChris Mason 			ret = wret;
1000bb803951SChris Mason 	}
100179f95c82SChris Mason 
100279f95c82SChris Mason 	/*
100379f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
100479f95c82SChris Mason 	 */
10055f39d397SChris Mason 	if (right) {
1006d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
100754aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
100879f95c82SChris Mason 			ret = wret;
10095f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
10106a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1011925baeddSChris Mason 			btrfs_tree_unlock(right);
1012afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1013f0486c68SYan, Zheng 			root_sub_used(root, right->len);
10147a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
10157a163608SFilipe Manana 					      0, 1);
10163083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1017f0486c68SYan, Zheng 			right = NULL;
1018bb803951SChris Mason 		} else {
10195f39d397SChris Mason 			struct btrfs_disk_key right_key;
10205f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1021f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
102233cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
10230e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
10245f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
10255f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1026bb803951SChris Mason 		}
1027bb803951SChris Mason 	}
10285f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
102979f95c82SChris Mason 		/*
103079f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
103179f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
103279f95c82SChris Mason 		 * could try to delete the only pointer in this node.
103379f95c82SChris Mason 		 * So, pull some keys from the left.
103479f95c82SChris Mason 		 * There has to be a left pointer at this point because
103579f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
103679f95c82SChris Mason 		 * right
103779f95c82SChris Mason 		 */
1038305a26afSMark Fasheh 		if (!left) {
1039305a26afSMark Fasheh 			ret = -EROFS;
10400b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1041305a26afSMark Fasheh 			goto enospc;
1042305a26afSMark Fasheh 		}
104355d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
104454aa1f4dSChris Mason 		if (wret < 0) {
104579f95c82SChris Mason 			ret = wret;
104654aa1f4dSChris Mason 			goto enospc;
104754aa1f4dSChris Mason 		}
1048bce4eae9SChris Mason 		if (wret == 1) {
1049d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1050bce4eae9SChris Mason 			if (wret < 0)
1051bce4eae9SChris Mason 				ret = wret;
1052bce4eae9SChris Mason 		}
105379f95c82SChris Mason 		BUG_ON(wret == 1);
105479f95c82SChris Mason 	}
10555f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
10566a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1057925baeddSChris Mason 		btrfs_tree_unlock(mid);
1058afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1059f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10607a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
10613083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1062f0486c68SYan, Zheng 		mid = NULL;
106379f95c82SChris Mason 	} else {
106479f95c82SChris Mason 		/* update the parent key to reflect our changes */
10655f39d397SChris Mason 		struct btrfs_disk_key mid_key;
10665f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1067f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
106833cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
10690e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
10705f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
10715f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
107279f95c82SChris Mason 	}
1073bb803951SChris Mason 
107479f95c82SChris Mason 	/* update the path */
10755f39d397SChris Mason 	if (left) {
10765f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
107767439dadSDavid Sterba 			atomic_inc(&left->refs);
1078925baeddSChris Mason 			/* left was locked after cow */
10795f39d397SChris Mason 			path->nodes[level] = left;
1080bb803951SChris Mason 			path->slots[level + 1] -= 1;
1081bb803951SChris Mason 			path->slots[level] = orig_slot;
1082925baeddSChris Mason 			if (mid) {
1083925baeddSChris Mason 				btrfs_tree_unlock(mid);
10845f39d397SChris Mason 				free_extent_buffer(mid);
1085925baeddSChris Mason 			}
1086bb803951SChris Mason 		} else {
10875f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1088bb803951SChris Mason 			path->slots[level] = orig_slot;
1089bb803951SChris Mason 		}
1090bb803951SChris Mason 	}
109179f95c82SChris Mason 	/* double check we haven't messed things up */
1092e20d96d6SChris Mason 	if (orig_ptr !=
10935f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
109479f95c82SChris Mason 		BUG();
109554aa1f4dSChris Mason enospc:
1096925baeddSChris Mason 	if (right) {
1097925baeddSChris Mason 		btrfs_tree_unlock(right);
10985f39d397SChris Mason 		free_extent_buffer(right);
1099925baeddSChris Mason 	}
1100925baeddSChris Mason 	if (left) {
1101925baeddSChris Mason 		if (path->nodes[level] != left)
1102925baeddSChris Mason 			btrfs_tree_unlock(left);
11035f39d397SChris Mason 		free_extent_buffer(left);
1104925baeddSChris Mason 	}
1105bb803951SChris Mason 	return ret;
1106bb803951SChris Mason }
1107bb803951SChris Mason 
1108d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1109d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1110d352ac68SChris Mason  * have to be pessimistic.
1111d352ac68SChris Mason  */
1112d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1113e66f709bSChris Mason 					  struct btrfs_root *root,
1114e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1115e66f709bSChris Mason {
11160b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11175f39d397SChris Mason 	struct extent_buffer *right = NULL;
11185f39d397SChris Mason 	struct extent_buffer *mid;
11195f39d397SChris Mason 	struct extent_buffer *left = NULL;
11205f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1121e66f709bSChris Mason 	int ret = 0;
1122e66f709bSChris Mason 	int wret;
1123e66f709bSChris Mason 	int pslot;
1124e66f709bSChris Mason 	int orig_slot = path->slots[level];
1125e66f709bSChris Mason 
1126e66f709bSChris Mason 	if (level == 0)
1127e66f709bSChris Mason 		return 1;
1128e66f709bSChris Mason 
11295f39d397SChris Mason 	mid = path->nodes[level];
11307bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1131e66f709bSChris Mason 
1132a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
11335f39d397SChris Mason 		parent = path->nodes[level + 1];
1134e66f709bSChris Mason 		pslot = path->slots[level + 1];
1135a05a9bb1SLi Zefan 	}
1136e66f709bSChris Mason 
11375f39d397SChris Mason 	if (!parent)
1138e66f709bSChris Mason 		return 1;
1139e66f709bSChris Mason 
11404b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1141fb770ae4SLiu Bo 	if (IS_ERR(left))
1142fb770ae4SLiu Bo 		left = NULL;
1143e66f709bSChris Mason 
1144e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
11455f39d397SChris Mason 	if (left) {
1146e66f709bSChris Mason 		u32 left_nr;
1147925baeddSChris Mason 
1148bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1149b4ce94deSChris Mason 
11505f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
11510b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
115233ade1f8SChris Mason 			wret = 1;
115333ade1f8SChris Mason 		} else {
11545f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
11559631e4ccSJosef Bacik 					      pslot - 1, &left,
1156bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
115754aa1f4dSChris Mason 			if (ret)
115854aa1f4dSChris Mason 				wret = 1;
115954aa1f4dSChris Mason 			else {
1160d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
116154aa1f4dSChris Mason 			}
116233ade1f8SChris Mason 		}
1163e66f709bSChris Mason 		if (wret < 0)
1164e66f709bSChris Mason 			ret = wret;
1165e66f709bSChris Mason 		if (wret == 0) {
11665f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1167e66f709bSChris Mason 			orig_slot += left_nr;
11685f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1169f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
117033cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
11710e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11725f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
11735f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
11745f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
11755f39d397SChris Mason 				path->nodes[level] = left;
1176e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1177e66f709bSChris Mason 				path->slots[level] = orig_slot;
1178925baeddSChris Mason 				btrfs_tree_unlock(mid);
11795f39d397SChris Mason 				free_extent_buffer(mid);
1180e66f709bSChris Mason 			} else {
1181e66f709bSChris Mason 				orig_slot -=
11825f39d397SChris Mason 					btrfs_header_nritems(left);
1183e66f709bSChris Mason 				path->slots[level] = orig_slot;
1184925baeddSChris Mason 				btrfs_tree_unlock(left);
11855f39d397SChris Mason 				free_extent_buffer(left);
1186e66f709bSChris Mason 			}
1187e66f709bSChris Mason 			return 0;
1188e66f709bSChris Mason 		}
1189925baeddSChris Mason 		btrfs_tree_unlock(left);
11905f39d397SChris Mason 		free_extent_buffer(left);
1191e66f709bSChris Mason 	}
11924b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1193fb770ae4SLiu Bo 	if (IS_ERR(right))
1194fb770ae4SLiu Bo 		right = NULL;
1195e66f709bSChris Mason 
1196e66f709bSChris Mason 	/*
1197e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1198e66f709bSChris Mason 	 */
11995f39d397SChris Mason 	if (right) {
120033ade1f8SChris Mason 		u32 right_nr;
1201b4ce94deSChris Mason 
1202bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1203b4ce94deSChris Mason 
12045f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
12050b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
120633ade1f8SChris Mason 			wret = 1;
120733ade1f8SChris Mason 		} else {
12085f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
12095f39d397SChris Mason 					      parent, pslot + 1,
1210bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
121154aa1f4dSChris Mason 			if (ret)
121254aa1f4dSChris Mason 				wret = 1;
121354aa1f4dSChris Mason 			else {
121455d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
121533ade1f8SChris Mason 			}
121654aa1f4dSChris Mason 		}
1217e66f709bSChris Mason 		if (wret < 0)
1218e66f709bSChris Mason 			ret = wret;
1219e66f709bSChris Mason 		if (wret == 0) {
12205f39d397SChris Mason 			struct btrfs_disk_key disk_key;
12215f39d397SChris Mason 
12225f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1223f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
122433cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
12250e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
12265f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
12275f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12285f39d397SChris Mason 
12295f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
12305f39d397SChris Mason 				path->nodes[level] = right;
1231e66f709bSChris Mason 				path->slots[level + 1] += 1;
1232e66f709bSChris Mason 				path->slots[level] = orig_slot -
12335f39d397SChris Mason 					btrfs_header_nritems(mid);
1234925baeddSChris Mason 				btrfs_tree_unlock(mid);
12355f39d397SChris Mason 				free_extent_buffer(mid);
1236e66f709bSChris Mason 			} else {
1237925baeddSChris Mason 				btrfs_tree_unlock(right);
12385f39d397SChris Mason 				free_extent_buffer(right);
1239e66f709bSChris Mason 			}
1240e66f709bSChris Mason 			return 0;
1241e66f709bSChris Mason 		}
1242925baeddSChris Mason 		btrfs_tree_unlock(right);
12435f39d397SChris Mason 		free_extent_buffer(right);
1244e66f709bSChris Mason 	}
1245e66f709bSChris Mason 	return 1;
1246e66f709bSChris Mason }
1247e66f709bSChris Mason 
124874123bd7SChris Mason /*
1249d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1250d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
12513c69faecSChris Mason  */
12522ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1253e02119d5SChris Mason 			     struct btrfs_path *path,
125401f46658SChris Mason 			     int level, int slot, u64 objectid)
12553c69faecSChris Mason {
12565f39d397SChris Mason 	struct extent_buffer *node;
125701f46658SChris Mason 	struct btrfs_disk_key disk_key;
12583c69faecSChris Mason 	u32 nritems;
12593c69faecSChris Mason 	u64 search;
1260a7175319SChris Mason 	u64 target;
12616b80053dSChris Mason 	u64 nread = 0;
1262ace75066SFilipe Manana 	u64 nread_max;
12636b80053dSChris Mason 	u32 nr;
12646b80053dSChris Mason 	u32 blocksize;
12656b80053dSChris Mason 	u32 nscan = 0;
1266db94535dSChris Mason 
1267ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
12683c69faecSChris Mason 		return;
12693c69faecSChris Mason 
12706702ed49SChris Mason 	if (!path->nodes[level])
12716702ed49SChris Mason 		return;
12726702ed49SChris Mason 
12735f39d397SChris Mason 	node = path->nodes[level];
1274925baeddSChris Mason 
1275ace75066SFilipe Manana 	/*
1276ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1277ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1278ace75066SFilipe Manana 	 * much IO at once (possibly random).
1279ace75066SFilipe Manana 	 */
1280ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1281ace75066SFilipe Manana 		if (level > 1)
1282ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1283ace75066SFilipe Manana 		else
1284ace75066SFilipe Manana 			nread_max = SZ_128K;
1285ace75066SFilipe Manana 	} else {
1286ace75066SFilipe Manana 		nread_max = SZ_64K;
1287ace75066SFilipe Manana 	}
1288ace75066SFilipe Manana 
12893c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
12900b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1291069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1292069a2e37SFilipe Manana 		struct extent_buffer *eb;
1293069a2e37SFilipe Manana 
12940b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
12955f39d397SChris Mason 		if (eb) {
12965f39d397SChris Mason 			free_extent_buffer(eb);
12973c69faecSChris Mason 			return;
12983c69faecSChris Mason 		}
1299069a2e37SFilipe Manana 	}
13003c69faecSChris Mason 
1301a7175319SChris Mason 	target = search;
13026b80053dSChris Mason 
13035f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
13046b80053dSChris Mason 	nr = slot;
130525b8b936SJosef Bacik 
13063c69faecSChris Mason 	while (1) {
1307e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
13086b80053dSChris Mason 			if (nr == 0)
13093c69faecSChris Mason 				break;
13106b80053dSChris Mason 			nr--;
1311ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1312ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
13136b80053dSChris Mason 			nr++;
13146b80053dSChris Mason 			if (nr >= nritems)
13156b80053dSChris Mason 				break;
13163c69faecSChris Mason 		}
1317e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
131801f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
131901f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
132001f46658SChris Mason 				break;
132101f46658SChris Mason 		}
13226b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1323ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1324ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1325a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1326bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
13276b80053dSChris Mason 			nread += blocksize;
13283c69faecSChris Mason 		}
13296b80053dSChris Mason 		nscan++;
1330ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
13316b80053dSChris Mason 			break;
13323c69faecSChris Mason 	}
13333c69faecSChris Mason }
1334925baeddSChris Mason 
1335bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1336b4ce94deSChris Mason {
1337bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1338b4ce94deSChris Mason 	int slot;
1339b4ce94deSChris Mason 	int nritems;
1340b4ce94deSChris Mason 
13418c594ea8SChris Mason 	parent = path->nodes[level + 1];
1342b4ce94deSChris Mason 	if (!parent)
13430b08851fSJosef Bacik 		return;
1344b4ce94deSChris Mason 
1345b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
13468c594ea8SChris Mason 	slot = path->slots[level + 1];
1347b4ce94deSChris Mason 
1348bfb484d9SJosef Bacik 	if (slot > 0)
1349bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1350bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1351bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1352b4ce94deSChris Mason }
1353b4ce94deSChris Mason 
1354b4ce94deSChris Mason 
1355b4ce94deSChris Mason /*
1356d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1357d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1358d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1359d397712bSChris Mason  * tree.
1360d352ac68SChris Mason  *
1361d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1362d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1363d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1364d352ac68SChris Mason  *
1365d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1366d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1367d352ac68SChris Mason  */
1368e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1369f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1370f7c79f30SChris Mason 			       int *write_lock_level)
1371925baeddSChris Mason {
1372925baeddSChris Mason 	int i;
1373925baeddSChris Mason 	int skip_level = level;
1374c1227996SNikolay Borisov 	bool check_skip = true;
1375925baeddSChris Mason 
1376925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1377925baeddSChris Mason 		if (!path->nodes[i])
1378925baeddSChris Mason 			break;
1379925baeddSChris Mason 		if (!path->locks[i])
1380925baeddSChris Mason 			break;
1381c1227996SNikolay Borisov 
1382c1227996SNikolay Borisov 		if (check_skip) {
1383c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1384925baeddSChris Mason 				skip_level = i + 1;
1385925baeddSChris Mason 				continue;
1386925baeddSChris Mason 			}
1387c1227996SNikolay Borisov 
1388c1227996SNikolay Borisov 			if (path->keep_locks) {
1389925baeddSChris Mason 				u32 nritems;
1390c1227996SNikolay Borisov 
1391c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1392051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1393925baeddSChris Mason 					skip_level = i + 1;
1394925baeddSChris Mason 					continue;
1395925baeddSChris Mason 				}
1396925baeddSChris Mason 			}
1397c1227996SNikolay Borisov 		}
1398051e1b9fSChris Mason 
1399d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1400c1227996SNikolay Borisov 			check_skip = false;
1401c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1402925baeddSChris Mason 			path->locks[i] = 0;
1403f7c79f30SChris Mason 			if (write_lock_level &&
1404f7c79f30SChris Mason 			    i > min_write_lock_level &&
1405f7c79f30SChris Mason 			    i <= *write_lock_level) {
1406f7c79f30SChris Mason 				*write_lock_level = i - 1;
1407f7c79f30SChris Mason 			}
1408925baeddSChris Mason 		}
1409925baeddSChris Mason 	}
1410925baeddSChris Mason }
1411925baeddSChris Mason 
14123c69faecSChris Mason /*
1413376a21d7SFilipe Manana  * Helper function for btrfs_search_slot() and other functions that do a search
1414376a21d7SFilipe Manana  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1415376a21d7SFilipe Manana  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1416376a21d7SFilipe Manana  * its pages from disk.
1417c8c42864SChris Mason  *
1418376a21d7SFilipe Manana  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1419376a21d7SFilipe Manana  * whole btree search, starting again from the current root node.
1420c8c42864SChris Mason  */
1421c8c42864SChris Mason static int
1422d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1423c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1424cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1425c8c42864SChris Mason {
14260b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1427c8c42864SChris Mason 	u64 blocknr;
1428c8c42864SChris Mason 	u64 gen;
1429c8c42864SChris Mason 	struct extent_buffer *tmp;
1430581c1760SQu Wenruo 	struct btrfs_key first_key;
143176a05b35SChris Mason 	int ret;
1432581c1760SQu Wenruo 	int parent_level;
1433b246666eSFilipe Manana 	bool unlock_up;
1434c8c42864SChris Mason 
1435b246666eSFilipe Manana 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1436213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1437213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1438213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1439213ff4b7SNikolay Borisov 	btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
1440c8c42864SChris Mason 
1441b246666eSFilipe Manana 	/*
1442b246666eSFilipe Manana 	 * If we need to read an extent buffer from disk and we are holding locks
1443b246666eSFilipe Manana 	 * on upper level nodes, we unlock all the upper nodes before reading the
1444b246666eSFilipe Manana 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1445b246666eSFilipe Manana 	 * restart the search. We don't release the lock on the current level
1446b246666eSFilipe Manana 	 * because we need to walk this node to figure out which blocks to read.
1447b246666eSFilipe Manana 	 */
14480b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1449cb44921aSChris Mason 	if (tmp) {
1450ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1451ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1452ace75066SFilipe Manana 
1453b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1454b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1455448de471SQu Wenruo 			/*
1456448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1457448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1458448de471SQu Wenruo 			 * parents (shared tree blocks).
1459448de471SQu Wenruo 			 */
1460e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1461448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
1462448de471SQu Wenruo 				free_extent_buffer(tmp);
1463448de471SQu Wenruo 				return -EUCLEAN;
1464448de471SQu Wenruo 			}
1465c8c42864SChris Mason 			*eb_ret = tmp;
1466c8c42864SChris Mason 			return 0;
1467c8c42864SChris Mason 		}
1468bdf7c00eSJosef Bacik 
1469857bc13fSJosef Bacik 		if (p->nowait) {
1470857bc13fSJosef Bacik 			free_extent_buffer(tmp);
1471857bc13fSJosef Bacik 			return -EAGAIN;
1472857bc13fSJosef Bacik 		}
1473857bc13fSJosef Bacik 
1474b246666eSFilipe Manana 		if (unlock_up)
1475b246666eSFilipe Manana 			btrfs_unlock_up_safe(p, level + 1);
1476b246666eSFilipe Manana 
1477b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
14786a2e9dc4SFilipe Manana 		ret = btrfs_read_extent_buffer(tmp, gen, parent_level - 1, &first_key);
14799a4ffa1bSQu Wenruo 		if (ret) {
1480cb44921aSChris Mason 			free_extent_buffer(tmp);
1481b3b4aa74SDavid Sterba 			btrfs_release_path(p);
1482cb44921aSChris Mason 			return -EIO;
1483cb44921aSChris Mason 		}
148488c602abSQu Wenruo 		if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
148588c602abSQu Wenruo 			free_extent_buffer(tmp);
148688c602abSQu Wenruo 			btrfs_release_path(p);
148788c602abSQu Wenruo 			return -EUCLEAN;
148888c602abSQu Wenruo 		}
1489b246666eSFilipe Manana 
1490b246666eSFilipe Manana 		if (unlock_up)
1491b246666eSFilipe Manana 			ret = -EAGAIN;
1492b246666eSFilipe Manana 
1493b246666eSFilipe Manana 		goto out;
1494857bc13fSJosef Bacik 	} else if (p->nowait) {
1495857bc13fSJosef Bacik 		return -EAGAIN;
14969a4ffa1bSQu Wenruo 	}
1497c8c42864SChris Mason 
1498b246666eSFilipe Manana 	if (unlock_up) {
14998c594ea8SChris Mason 		btrfs_unlock_up_safe(p, level + 1);
15004bb59055SFilipe Manana 		ret = -EAGAIN;
15014bb59055SFilipe Manana 	} else {
15024bb59055SFilipe Manana 		ret = 0;
15034bb59055SFilipe Manana 	}
15048c594ea8SChris Mason 
1505e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
15062ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1507c8c42864SChris Mason 
15081b7ec85eSJosef Bacik 	tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
15091b7ec85eSJosef Bacik 			      gen, parent_level - 1, &first_key);
15104eb150d6SQu Wenruo 	if (IS_ERR(tmp)) {
15114eb150d6SQu Wenruo 		btrfs_release_path(p);
15124eb150d6SQu Wenruo 		return PTR_ERR(tmp);
15134eb150d6SQu Wenruo 	}
151476a05b35SChris Mason 	/*
151576a05b35SChris Mason 	 * If the read above didn't mark this buffer up to date,
151676a05b35SChris Mason 	 * it will never end up being up to date.  Set ret to EIO now
151776a05b35SChris Mason 	 * and give up so that our caller doesn't loop forever
151876a05b35SChris Mason 	 * on our EAGAINs.
151976a05b35SChris Mason 	 */
1520e6a1d6fdSLiu Bo 	if (!extent_buffer_uptodate(tmp))
152176a05b35SChris Mason 		ret = -EIO;
152202a3307aSLiu Bo 
1523b246666eSFilipe Manana out:
15244bb59055SFilipe Manana 	if (ret == 0) {
15254bb59055SFilipe Manana 		*eb_ret = tmp;
15264bb59055SFilipe Manana 	} else {
15274bb59055SFilipe Manana 		free_extent_buffer(tmp);
152802a3307aSLiu Bo 		btrfs_release_path(p);
15294bb59055SFilipe Manana 	}
15304bb59055SFilipe Manana 
153176a05b35SChris Mason 	return ret;
1532c8c42864SChris Mason }
1533c8c42864SChris Mason 
1534c8c42864SChris Mason /*
1535c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1536c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1537c8c42864SChris Mason  * the ins_len.
1538c8c42864SChris Mason  *
1539c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1540c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1541c8c42864SChris Mason  * start over
1542c8c42864SChris Mason  */
1543c8c42864SChris Mason static int
1544c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1545c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1546bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1547bd681513SChris Mason 		       int *write_lock_level)
1548c8c42864SChris Mason {
15490b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
155095b982deSNikolay Borisov 	int ret = 0;
15510b246afaSJeff Mahoney 
1552c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
15530b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1554c8c42864SChris Mason 
1555bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1556bd681513SChris Mason 			*write_lock_level = level + 1;
1557bd681513SChris Mason 			btrfs_release_path(p);
155895b982deSNikolay Borisov 			return -EAGAIN;
1559bd681513SChris Mason 		}
1560bd681513SChris Mason 
1561bfb484d9SJosef Bacik 		reada_for_balance(p, level);
156295b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1563c8c42864SChris Mason 
1564c8c42864SChris Mason 		b = p->nodes[level];
1565c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
15660b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1567c8c42864SChris Mason 
1568bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1569bd681513SChris Mason 			*write_lock_level = level + 1;
1570bd681513SChris Mason 			btrfs_release_path(p);
157195b982deSNikolay Borisov 			return -EAGAIN;
1572bd681513SChris Mason 		}
1573bd681513SChris Mason 
1574bfb484d9SJosef Bacik 		reada_for_balance(p, level);
157595b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
157695b982deSNikolay Borisov 		if (ret)
157795b982deSNikolay Borisov 			return ret;
1578c8c42864SChris Mason 
1579c8c42864SChris Mason 		b = p->nodes[level];
1580c8c42864SChris Mason 		if (!b) {
1581b3b4aa74SDavid Sterba 			btrfs_release_path(p);
158295b982deSNikolay Borisov 			return -EAGAIN;
1583c8c42864SChris Mason 		}
1584c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1585c8c42864SChris Mason 	}
1586c8c42864SChris Mason 	return ret;
1587c8c42864SChris Mason }
1588c8c42864SChris Mason 
1589381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1590e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1591e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1592e33d5c3dSKelley Nielsen {
1593e33d5c3dSKelley Nielsen 	int ret;
1594e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1595e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1596381cf658SDavid Sterba 
1597381cf658SDavid Sterba 	ASSERT(path);
15981d4c08e0SDavid Sterba 	ASSERT(found_key);
1599e33d5c3dSKelley Nielsen 
1600e33d5c3dSKelley Nielsen 	key.type = key_type;
1601e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1602e33d5c3dSKelley Nielsen 	key.offset = ioff;
1603e33d5c3dSKelley Nielsen 
1604e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
16051d4c08e0SDavid Sterba 	if (ret < 0)
1606e33d5c3dSKelley Nielsen 		return ret;
1607e33d5c3dSKelley Nielsen 
1608e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1609e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1610e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1611e33d5c3dSKelley Nielsen 		if (ret)
1612e33d5c3dSKelley Nielsen 			return ret;
1613e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1614e33d5c3dSKelley Nielsen 	}
1615e33d5c3dSKelley Nielsen 
1616e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1617e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1618e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1619e33d5c3dSKelley Nielsen 		return 1;
1620e33d5c3dSKelley Nielsen 
1621e33d5c3dSKelley Nielsen 	return 0;
1622e33d5c3dSKelley Nielsen }
1623e33d5c3dSKelley Nielsen 
16241fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
16251fc28d8eSLiu Bo 							struct btrfs_path *p,
16261fc28d8eSLiu Bo 							int write_lock_level)
16271fc28d8eSLiu Bo {
16281fc28d8eSLiu Bo 	struct extent_buffer *b;
1629120de408SJosef Bacik 	int root_lock = 0;
16301fc28d8eSLiu Bo 	int level = 0;
16311fc28d8eSLiu Bo 
16321fc28d8eSLiu Bo 	if (p->search_commit_root) {
16331fc28d8eSLiu Bo 		b = root->commit_root;
163467439dadSDavid Sterba 		atomic_inc(&b->refs);
16351fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1636f9ddfd05SLiu Bo 		/*
1637f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1638f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1639f9ddfd05SLiu Bo 		 */
1640f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
16411fc28d8eSLiu Bo 
16421fc28d8eSLiu Bo 		goto out;
16431fc28d8eSLiu Bo 	}
16441fc28d8eSLiu Bo 
16451fc28d8eSLiu Bo 	if (p->skip_locking) {
16461fc28d8eSLiu Bo 		b = btrfs_root_node(root);
16471fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16481fc28d8eSLiu Bo 		goto out;
16491fc28d8eSLiu Bo 	}
16501fc28d8eSLiu Bo 
1651120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1652120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1653120de408SJosef Bacik 
16541fc28d8eSLiu Bo 	/*
1655662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1656662c653bSLiu Bo 	 * lock.
1657662c653bSLiu Bo 	 */
1658662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1659662c653bSLiu Bo 		/*
1660662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1661662c653bSLiu Bo 		 * have it read locked
16621fc28d8eSLiu Bo 		 */
1663857bc13fSJosef Bacik 		if (p->nowait) {
1664857bc13fSJosef Bacik 			b = btrfs_try_read_lock_root_node(root);
1665857bc13fSJosef Bacik 			if (IS_ERR(b))
1666857bc13fSJosef Bacik 				return b;
1667857bc13fSJosef Bacik 		} else {
16681bb96598SJosef Bacik 			b = btrfs_read_lock_root_node(root);
1669857bc13fSJosef Bacik 		}
16701fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16711fc28d8eSLiu Bo 		if (level > write_lock_level)
16721fc28d8eSLiu Bo 			goto out;
16731fc28d8eSLiu Bo 
1674662c653bSLiu Bo 		/* Whoops, must trade for write lock */
16751fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
16761fc28d8eSLiu Bo 		free_extent_buffer(b);
1677662c653bSLiu Bo 	}
1678662c653bSLiu Bo 
16791fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
16801fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
16811fc28d8eSLiu Bo 
16821fc28d8eSLiu Bo 	/* The level might have changed, check again */
16831fc28d8eSLiu Bo 	level = btrfs_header_level(b);
16841fc28d8eSLiu Bo 
16851fc28d8eSLiu Bo out:
1686120de408SJosef Bacik 	/*
1687120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1688120de408SJosef Bacik 	 * longer valid, return an error in this case.
1689120de408SJosef Bacik 	 */
1690120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1691120de408SJosef Bacik 		if (root_lock)
1692120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1693120de408SJosef Bacik 		free_extent_buffer(b);
1694120de408SJosef Bacik 		return ERR_PTR(-EIO);
1695120de408SJosef Bacik 	}
1696120de408SJosef Bacik 
16971fc28d8eSLiu Bo 	p->nodes[level] = b;
16981fc28d8eSLiu Bo 	if (!p->skip_locking)
16991fc28d8eSLiu Bo 		p->locks[level] = root_lock;
17001fc28d8eSLiu Bo 	/*
17011fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
17021fc28d8eSLiu Bo 	 */
17031fc28d8eSLiu Bo 	return b;
17041fc28d8eSLiu Bo }
17051fc28d8eSLiu Bo 
1706d96b3424SFilipe Manana /*
1707d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1708d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1709d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1710d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1711d96b3424SFilipe Manana  * reallocated in the next transaction.
1712d96b3424SFilipe Manana  *
1713d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1714d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1715d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1716d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1717d96b3424SFilipe Manana  */
1718d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1719d96b3424SFilipe Manana {
1720d96b3424SFilipe Manana 	const int i = path->lowest_level;
1721d96b3424SFilipe Manana 	const int slot = path->slots[i];
1722d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1723d96b3424SFilipe Manana 	struct extent_buffer *clone;
1724d96b3424SFilipe Manana 
1725d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1726d96b3424SFilipe Manana 
1727d96b3424SFilipe Manana 	if (!lowest)
1728d96b3424SFilipe Manana 		return 0;
1729d96b3424SFilipe Manana 
1730d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1731d96b3424SFilipe Manana 
1732d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1733d96b3424SFilipe Manana 	if (!clone)
1734d96b3424SFilipe Manana 		return -ENOMEM;
1735d96b3424SFilipe Manana 
1736d96b3424SFilipe Manana 	btrfs_release_path(path);
1737d96b3424SFilipe Manana 	path->nodes[i] = clone;
1738d96b3424SFilipe Manana 	path->slots[i] = slot;
1739d96b3424SFilipe Manana 
1740d96b3424SFilipe Manana 	return 0;
1741d96b3424SFilipe Manana }
17421fc28d8eSLiu Bo 
1743e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1744e2e58d0fSFilipe Manana 				      int search_low_slot,
1745e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1746e2e58d0fSFilipe Manana 				      int prev_cmp,
1747e2e58d0fSFilipe Manana 				      int *slot)
1748e2e58d0fSFilipe Manana {
1749e2e58d0fSFilipe Manana 	/*
1750e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1751e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1752e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1753e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1754e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1755e2e58d0fSFilipe Manana 	 */
1756e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1757e2e58d0fSFilipe Manana 		*slot = 0;
1758e2e58d0fSFilipe Manana 		return 0;
1759e2e58d0fSFilipe Manana 	}
1760e2e58d0fSFilipe Manana 
1761e2e58d0fSFilipe Manana 	return generic_bin_search(eb, search_low_slot, key, slot);
1762e2e58d0fSFilipe Manana }
1763e2e58d0fSFilipe Manana 
1764109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1765109324cfSFilipe Manana 		       struct btrfs_root *root,
1766109324cfSFilipe Manana 		       const struct btrfs_key *key,
1767109324cfSFilipe Manana 		       struct btrfs_path *path,
1768109324cfSFilipe Manana 		       int ins_len,
1769109324cfSFilipe Manana 		       int prev_cmp)
1770109324cfSFilipe Manana {
1771109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
1772109324cfSFilipe Manana 	int leaf_free_space = -1;
1773109324cfSFilipe Manana 	int search_low_slot = 0;
1774109324cfSFilipe Manana 	int ret;
1775109324cfSFilipe Manana 	bool do_bin_search = true;
1776109324cfSFilipe Manana 
1777109324cfSFilipe Manana 	/*
1778109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
1779109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
1780109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
1781109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1782109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
1783109324cfSFilipe Manana 	 */
1784109324cfSFilipe Manana 	if (ins_len > 0) {
1785109324cfSFilipe Manana 		/*
1786109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
1787109324cfSFilipe Manana 		 * will not change until then.
1788109324cfSFilipe Manana 		 */
1789109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
1790109324cfSFilipe Manana 
1791109324cfSFilipe Manana 		/*
1792109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
1793109324cfSFilipe Manana 		 * the root of the tree.
1794109324cfSFilipe Manana 		 */
1795109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
1796109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
1797109324cfSFilipe Manana 
1798109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
1799109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
1800109324cfSFilipe Manana 
1801109324cfSFilipe Manana 			/*
1802109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
1803109324cfSFilipe Manana 			 * taking into account that the first key is very likely
1804109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
1805109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
1806109324cfSFilipe Manana 			 * the header's level field.
1807109324cfSFilipe Manana 			 */
1808109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
1809109324cfSFilipe Manana 			if (ret < 0) {
1810109324cfSFilipe Manana 				/*
1811109324cfSFilipe Manana 				 * The first key is smaller than the key we want
1812109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
1813109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
1814109324cfSFilipe Manana 				 *
1815109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
1816109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
1817109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
1818109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
1819109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
1820109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
1821109324cfSFilipe Manana 				 */
1822109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
1823109324cfSFilipe Manana 				search_low_slot = 1;
1824109324cfSFilipe Manana 			} else {
1825109324cfSFilipe Manana 				/*
1826109324cfSFilipe Manana 				 * The first key is >= then the key we want to
1827109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
1828109324cfSFilipe Manana 				 * the target key will be at slot 0.
1829109324cfSFilipe Manana 				 *
1830109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
1831109324cfSFilipe Manana 				 * less than the first key, because we will need
1832109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
1833109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
1834109324cfSFilipe Manana 				 * If the key matches the first key, then we can
1835109324cfSFilipe Manana 				 * unlock all the upper nodes, using
1836109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
1837109324cfSFilipe Manana 				 * as stated above.
1838109324cfSFilipe Manana 				 */
1839109324cfSFilipe Manana 				if (ret == 0)
1840109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
1841109324cfSFilipe Manana 				/*
1842109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
1843109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
1844109324cfSFilipe Manana 				 * to adjust it.
1845109324cfSFilipe Manana 				 */
1846109324cfSFilipe Manana 				do_bin_search = false;
1847109324cfSFilipe Manana 				path->slots[0] = 0;
1848109324cfSFilipe Manana 			}
1849109324cfSFilipe Manana 		}
1850109324cfSFilipe Manana 	}
1851109324cfSFilipe Manana 
1852109324cfSFilipe Manana 	if (do_bin_search) {
1853109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
1854109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
1855109324cfSFilipe Manana 		if (ret < 0)
1856109324cfSFilipe Manana 			return ret;
1857109324cfSFilipe Manana 	}
1858109324cfSFilipe Manana 
1859109324cfSFilipe Manana 	if (ins_len > 0) {
1860109324cfSFilipe Manana 		/*
1861109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
1862109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
1863109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
1864109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
1865109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
1866109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
1867109324cfSFilipe Manana 		 * check will be correct.
1868109324cfSFilipe Manana 		 */
1869109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
1870109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
1871109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
1872109324cfSFilipe Manana 		}
1873109324cfSFilipe Manana 
1874109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
1875109324cfSFilipe Manana 
1876109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
1877109324cfSFilipe Manana 			int err;
1878109324cfSFilipe Manana 
1879109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
1880109324cfSFilipe Manana 					 (ret == 0));
1881bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
1882bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
1883bb8e9a60SFilipe Manana 				err = -EUCLEAN;
1884109324cfSFilipe Manana 			if (err)
1885109324cfSFilipe Manana 				ret = err;
1886109324cfSFilipe Manana 		}
1887109324cfSFilipe Manana 	}
1888109324cfSFilipe Manana 
1889109324cfSFilipe Manana 	return ret;
1890109324cfSFilipe Manana }
1891109324cfSFilipe Manana 
1892c8c42864SChris Mason /*
18934271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
18944271eceaSNikolay Borisov  * modifications to preserve tree invariants.
189574123bd7SChris Mason  *
18964271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
18974271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
18984271eceaSNikolay Borisov  * @root:	The root node of the tree
18994271eceaSNikolay Borisov  * @key:	The key we are looking for
19009a664971Sethanwu  * @ins_len:	Indicates purpose of search:
19019a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
19029a664971Sethanwu  *              <0  for deletions
19039a664971Sethanwu  *               0  for plain searches, not modifying the tree
19049a664971Sethanwu  *
19059a664971Sethanwu  *              (*) If size of item inserted doesn't include
19069a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
19079a664971Sethanwu  *              be set.
19084271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
19094271eceaSNikolay Borisov  *		when modifying the tree.
191097571fd0SChris Mason  *
19114271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
19124271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
19134271eceaSNikolay Borisov  *
19144271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
19154271eceaSNikolay Borisov  * of the path (level 0)
19164271eceaSNikolay Borisov  *
19174271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
19184271eceaSNikolay Borisov  * points to the slot where it should be inserted
19194271eceaSNikolay Borisov  *
19204271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
19214271eceaSNikolay Borisov  * is returned
192274123bd7SChris Mason  */
1923310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1924310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
1925310712b2SOmar Sandoval 		      int ins_len, int cow)
1926be0e5c09SChris Mason {
1927d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
19285f39d397SChris Mason 	struct extent_buffer *b;
1929be0e5c09SChris Mason 	int slot;
1930be0e5c09SChris Mason 	int ret;
193133c66f43SYan Zheng 	int err;
1932be0e5c09SChris Mason 	int level;
1933925baeddSChris Mason 	int lowest_unlock = 1;
1934bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
1935bd681513SChris Mason 	int write_lock_level = 0;
19369f3a7427SChris Mason 	u8 lowest_level = 0;
1937f7c79f30SChris Mason 	int min_write_lock_level;
1938d7396f07SFilipe David Borba Manana 	int prev_cmp;
19399f3a7427SChris Mason 
19406702ed49SChris Mason 	lowest_level = p->lowest_level;
1941323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
194222b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
1943eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
194425179201SJosef Bacik 
1945857bc13fSJosef Bacik 	/*
1946857bc13fSJosef Bacik 	 * For now only allow nowait for read only operations.  There's no
1947857bc13fSJosef Bacik 	 * strict reason why we can't, we just only need it for reads so it's
1948857bc13fSJosef Bacik 	 * only implemented for reads.
1949857bc13fSJosef Bacik 	 */
1950857bc13fSJosef Bacik 	ASSERT(!p->nowait || !cow);
1951857bc13fSJosef Bacik 
1952bd681513SChris Mason 	if (ins_len < 0) {
1953925baeddSChris Mason 		lowest_unlock = 2;
195465b51a00SChris Mason 
1955bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
1956bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
1957bd681513SChris Mason 		 * for those levels as well
1958bd681513SChris Mason 		 */
1959bd681513SChris Mason 		write_lock_level = 2;
1960bd681513SChris Mason 	} else if (ins_len > 0) {
1961bd681513SChris Mason 		/*
1962bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
1963bd681513SChris Mason 		 * level 1 so we can update keys
1964bd681513SChris Mason 		 */
1965bd681513SChris Mason 		write_lock_level = 1;
1966bd681513SChris Mason 	}
1967bd681513SChris Mason 
1968bd681513SChris Mason 	if (!cow)
1969bd681513SChris Mason 		write_lock_level = -1;
1970bd681513SChris Mason 
197109a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
1972bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
1973bd681513SChris Mason 
1974f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
1975f7c79f30SChris Mason 
1976d96b3424SFilipe Manana 	if (p->need_commit_sem) {
1977d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
1978857bc13fSJosef Bacik 		if (p->nowait) {
1979857bc13fSJosef Bacik 			if (!down_read_trylock(&fs_info->commit_root_sem))
1980857bc13fSJosef Bacik 				return -EAGAIN;
1981857bc13fSJosef Bacik 		} else {
1982d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
1983d96b3424SFilipe Manana 		}
1984857bc13fSJosef Bacik 	}
1985d96b3424SFilipe Manana 
1986bb803951SChris Mason again:
1987d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
19881fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
1989be6821f8SFilipe Manana 	if (IS_ERR(b)) {
1990be6821f8SFilipe Manana 		ret = PTR_ERR(b);
1991be6821f8SFilipe Manana 		goto done;
1992be6821f8SFilipe Manana 	}
1993925baeddSChris Mason 
1994eb60ceacSChris Mason 	while (b) {
1995f624d976SQu Wenruo 		int dec = 0;
1996f624d976SQu Wenruo 
19975f39d397SChris Mason 		level = btrfs_header_level(b);
199865b51a00SChris Mason 
199902217ed2SChris Mason 		if (cow) {
20009ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
20019ea2c7c9SNikolay Borisov 
2002c8c42864SChris Mason 			/*
2003c8c42864SChris Mason 			 * if we don't really need to cow this block
2004c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2005c8c42864SChris Mason 			 * so we test it here
2006c8c42864SChris Mason 			 */
20075963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
200865b51a00SChris Mason 				goto cow_done;
20095d4f98a2SYan Zheng 
2010bd681513SChris Mason 			/*
2011bd681513SChris Mason 			 * must have write locks on this node and the
2012bd681513SChris Mason 			 * parent
2013bd681513SChris Mason 			 */
20145124e00eSJosef Bacik 			if (level > write_lock_level ||
20155124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
20165124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
20175124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2018bd681513SChris Mason 				write_lock_level = level + 1;
2019bd681513SChris Mason 				btrfs_release_path(p);
2020bd681513SChris Mason 				goto again;
2021bd681513SChris Mason 			}
2022bd681513SChris Mason 
20239ea2c7c9SNikolay Borisov 			if (last_level)
20249ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
20259631e4ccSJosef Bacik 						      &b,
20269631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
20279ea2c7c9SNikolay Borisov 			else
202833c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2029e20d96d6SChris Mason 						      p->nodes[level + 1],
20309631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
20319631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
203233c66f43SYan Zheng 			if (err) {
203333c66f43SYan Zheng 				ret = err;
203465b51a00SChris Mason 				goto done;
203554aa1f4dSChris Mason 			}
203602217ed2SChris Mason 		}
203765b51a00SChris Mason cow_done:
2038eb60ceacSChris Mason 		p->nodes[level] = b;
2039b4ce94deSChris Mason 
2040b4ce94deSChris Mason 		/*
2041b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2042b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2043b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2044b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2045b4ce94deSChris Mason 		 *
2046eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2047eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2048eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2049eb653de1SFilipe David Borba Manana 		 * we're operating on.
2050b4ce94deSChris Mason 		 */
2051eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2052eb653de1SFilipe David Borba Manana 			int u = level + 1;
2053eb653de1SFilipe David Borba Manana 
2054eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2055eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2056eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2057eb653de1SFilipe David Borba Manana 			}
2058eb653de1SFilipe David Borba Manana 		}
2059b4ce94deSChris Mason 
2060e2e58d0fSFilipe Manana 		if (level == 0) {
2061109324cfSFilipe Manana 			if (ins_len > 0)
2062e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
2063bd681513SChris Mason 
2064109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2065459931ecSChris Mason 			if (!p->search_for_split)
2066f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
20674b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
206865b51a00SChris Mason 			goto done;
206965b51a00SChris Mason 		}
2070e2e58d0fSFilipe Manana 
2071e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2072e2e58d0fSFilipe Manana 		if (ret < 0)
2073e2e58d0fSFilipe Manana 			goto done;
2074e2e58d0fSFilipe Manana 		prev_cmp = ret;
2075e2e58d0fSFilipe Manana 
2076f624d976SQu Wenruo 		if (ret && slot > 0) {
2077f624d976SQu Wenruo 			dec = 1;
2078f624d976SQu Wenruo 			slot--;
2079f624d976SQu Wenruo 		}
2080f624d976SQu Wenruo 		p->slots[level] = slot;
2081f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2082f624d976SQu Wenruo 					     &write_lock_level);
2083f624d976SQu Wenruo 		if (err == -EAGAIN)
2084f624d976SQu Wenruo 			goto again;
2085f624d976SQu Wenruo 		if (err) {
2086f624d976SQu Wenruo 			ret = err;
2087f624d976SQu Wenruo 			goto done;
2088f624d976SQu Wenruo 		}
2089f624d976SQu Wenruo 		b = p->nodes[level];
2090f624d976SQu Wenruo 		slot = p->slots[level];
2091f624d976SQu Wenruo 
2092f624d976SQu Wenruo 		/*
2093f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2094f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2095f624d976SQu Wenruo 		 * the parent
2096f624d976SQu Wenruo 		 */
2097f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2098f624d976SQu Wenruo 			write_lock_level = level + 1;
2099f624d976SQu Wenruo 			btrfs_release_path(p);
2100f624d976SQu Wenruo 			goto again;
2101f624d976SQu Wenruo 		}
2102f624d976SQu Wenruo 
2103f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2104f624d976SQu Wenruo 			  &write_lock_level);
2105f624d976SQu Wenruo 
2106f624d976SQu Wenruo 		if (level == lowest_level) {
2107f624d976SQu Wenruo 			if (dec)
2108f624d976SQu Wenruo 				p->slots[level]++;
2109f624d976SQu Wenruo 			goto done;
2110f624d976SQu Wenruo 		}
2111f624d976SQu Wenruo 
2112f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2113f624d976SQu Wenruo 		if (err == -EAGAIN)
2114f624d976SQu Wenruo 			goto again;
2115f624d976SQu Wenruo 		if (err) {
2116f624d976SQu Wenruo 			ret = err;
2117f624d976SQu Wenruo 			goto done;
2118f624d976SQu Wenruo 		}
2119f624d976SQu Wenruo 
2120f624d976SQu Wenruo 		if (!p->skip_locking) {
2121f624d976SQu Wenruo 			level = btrfs_header_level(b);
2122b40130b2SJosef Bacik 
2123b40130b2SJosef Bacik 			btrfs_maybe_reset_lockdep_class(root, b);
2124b40130b2SJosef Bacik 
2125f624d976SQu Wenruo 			if (level <= write_lock_level) {
2126f624d976SQu Wenruo 				btrfs_tree_lock(b);
2127f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2128f624d976SQu Wenruo 			} else {
2129857bc13fSJosef Bacik 				if (p->nowait) {
2130857bc13fSJosef Bacik 					if (!btrfs_try_tree_read_lock(b)) {
2131857bc13fSJosef Bacik 						free_extent_buffer(b);
2132857bc13fSJosef Bacik 						ret = -EAGAIN;
2133857bc13fSJosef Bacik 						goto done;
2134857bc13fSJosef Bacik 					}
2135857bc13fSJosef Bacik 				} else {
2136fe596ca3SJosef Bacik 					btrfs_tree_read_lock(b);
2137857bc13fSJosef Bacik 				}
2138f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2139f624d976SQu Wenruo 			}
2140f624d976SQu Wenruo 			p->nodes[level] = b;
2141f624d976SQu Wenruo 		}
214265b51a00SChris Mason 	}
214365b51a00SChris Mason 	ret = 1;
214465b51a00SChris Mason done:
21455f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2146b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2147d96b3424SFilipe Manana 
2148d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2149d96b3424SFilipe Manana 		int ret2;
2150d96b3424SFilipe Manana 
2151d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2152d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2153d96b3424SFilipe Manana 		if (ret2)
2154d96b3424SFilipe Manana 			ret = ret2;
2155d96b3424SFilipe Manana 	}
2156d96b3424SFilipe Manana 
2157be0e5c09SChris Mason 	return ret;
2158be0e5c09SChris Mason }
2159f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2160be0e5c09SChris Mason 
216174123bd7SChris Mason /*
21625d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
21635d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
21645d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
21655d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
21665d9e75c4SJan Schmidt  *
21675d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
21685d9e75c4SJan Schmidt  *
21695d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
21705d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
21715d9e75c4SJan Schmidt  */
2172310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
21735d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
21745d9e75c4SJan Schmidt {
21750b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
21765d9e75c4SJan Schmidt 	struct extent_buffer *b;
21775d9e75c4SJan Schmidt 	int slot;
21785d9e75c4SJan Schmidt 	int ret;
21795d9e75c4SJan Schmidt 	int err;
21805d9e75c4SJan Schmidt 	int level;
21815d9e75c4SJan Schmidt 	int lowest_unlock = 1;
21825d9e75c4SJan Schmidt 	u8 lowest_level = 0;
21835d9e75c4SJan Schmidt 
21845d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
21855d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
2186c922b016SStefan Roesch 	ASSERT(!p->nowait);
21875d9e75c4SJan Schmidt 
21885d9e75c4SJan Schmidt 	if (p->search_commit_root) {
21895d9e75c4SJan Schmidt 		BUG_ON(time_seq);
21905d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
21915d9e75c4SJan Schmidt 	}
21925d9e75c4SJan Schmidt 
21935d9e75c4SJan Schmidt again:
2194f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2195315bed43SNikolay Borisov 	if (!b) {
2196315bed43SNikolay Borisov 		ret = -EIO;
2197315bed43SNikolay Borisov 		goto done;
2198315bed43SNikolay Borisov 	}
21995d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
22005d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
22015d9e75c4SJan Schmidt 
22025d9e75c4SJan Schmidt 	while (b) {
2203abe9339dSQu Wenruo 		int dec = 0;
2204abe9339dSQu Wenruo 
22055d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
22065d9e75c4SJan Schmidt 		p->nodes[level] = b;
22075d9e75c4SJan Schmidt 
22085d9e75c4SJan Schmidt 		/*
22095d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
22105d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
22115d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
22125d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
22135d9e75c4SJan Schmidt 		 */
22145d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
22155d9e75c4SJan Schmidt 
2216995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
2217cbca7d59SFilipe Manana 		if (ret < 0)
2218cbca7d59SFilipe Manana 			goto done;
22195d9e75c4SJan Schmidt 
2220abe9339dSQu Wenruo 		if (level == 0) {
2221abe9339dSQu Wenruo 			p->slots[level] = slot;
2222abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2223abe9339dSQu Wenruo 			goto done;
2224abe9339dSQu Wenruo 		}
2225abe9339dSQu Wenruo 
22265d9e75c4SJan Schmidt 		if (ret && slot > 0) {
22275d9e75c4SJan Schmidt 			dec = 1;
2228abe9339dSQu Wenruo 			slot--;
22295d9e75c4SJan Schmidt 		}
22305d9e75c4SJan Schmidt 		p->slots[level] = slot;
22315d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
22325d9e75c4SJan Schmidt 
22335d9e75c4SJan Schmidt 		if (level == lowest_level) {
22345d9e75c4SJan Schmidt 			if (dec)
22355d9e75c4SJan Schmidt 				p->slots[level]++;
22365d9e75c4SJan Schmidt 			goto done;
22375d9e75c4SJan Schmidt 		}
22385d9e75c4SJan Schmidt 
2239abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
22405d9e75c4SJan Schmidt 		if (err == -EAGAIN)
22415d9e75c4SJan Schmidt 			goto again;
22425d9e75c4SJan Schmidt 		if (err) {
22435d9e75c4SJan Schmidt 			ret = err;
22445d9e75c4SJan Schmidt 			goto done;
22455d9e75c4SJan Schmidt 		}
22465d9e75c4SJan Schmidt 
22475d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
22485d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2249f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2250db7f3436SJosef Bacik 		if (!b) {
2251db7f3436SJosef Bacik 			ret = -ENOMEM;
2252db7f3436SJosef Bacik 			goto done;
2253db7f3436SJosef Bacik 		}
22545d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
22555d9e75c4SJan Schmidt 		p->nodes[level] = b;
22565d9e75c4SJan Schmidt 	}
22575d9e75c4SJan Schmidt 	ret = 1;
22585d9e75c4SJan Schmidt done:
22595d9e75c4SJan Schmidt 	if (ret < 0)
22605d9e75c4SJan Schmidt 		btrfs_release_path(p);
22615d9e75c4SJan Schmidt 
22625d9e75c4SJan Schmidt 	return ret;
22635d9e75c4SJan Schmidt }
22645d9e75c4SJan Schmidt 
22655d9e75c4SJan Schmidt /*
22662f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
22672f38b3e1SArne Jansen  * instead the next or previous item should be returned.
22682f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
22692f38b3e1SArne Jansen  * otherwise.
22702f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
22712f38b3e1SArne Jansen  * return the next lower instead.
22722f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
22732f38b3e1SArne Jansen  * return the next higher instead.
22742f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
22752f38b3e1SArne Jansen  * < 0 on error
22762f38b3e1SArne Jansen  */
22772f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2278310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2279310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2280310712b2SOmar Sandoval 			       int return_any)
22812f38b3e1SArne Jansen {
22822f38b3e1SArne Jansen 	int ret;
22832f38b3e1SArne Jansen 	struct extent_buffer *leaf;
22842f38b3e1SArne Jansen 
22852f38b3e1SArne Jansen again:
22862f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
22872f38b3e1SArne Jansen 	if (ret <= 0)
22882f38b3e1SArne Jansen 		return ret;
22892f38b3e1SArne Jansen 	/*
22902f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
22912f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
22922f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
22932f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
22942f38b3e1SArne Jansen 	 * item.
22952f38b3e1SArne Jansen 	 */
22962f38b3e1SArne Jansen 	leaf = p->nodes[0];
22972f38b3e1SArne Jansen 
22982f38b3e1SArne Jansen 	if (find_higher) {
22992f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
23002f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
23012f38b3e1SArne Jansen 			if (ret <= 0)
23022f38b3e1SArne Jansen 				return ret;
23032f38b3e1SArne Jansen 			if (!return_any)
23042f38b3e1SArne Jansen 				return 1;
23052f38b3e1SArne Jansen 			/*
23062f38b3e1SArne Jansen 			 * no higher item found, return the next
23072f38b3e1SArne Jansen 			 * lower instead
23082f38b3e1SArne Jansen 			 */
23092f38b3e1SArne Jansen 			return_any = 0;
23102f38b3e1SArne Jansen 			find_higher = 0;
23112f38b3e1SArne Jansen 			btrfs_release_path(p);
23122f38b3e1SArne Jansen 			goto again;
23132f38b3e1SArne Jansen 		}
23142f38b3e1SArne Jansen 	} else {
23152f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
23162f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2317e6793769SArne Jansen 			if (ret < 0)
23182f38b3e1SArne Jansen 				return ret;
2319e6793769SArne Jansen 			if (!ret) {
232023c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
232123c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
232223c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2323e6793769SArne Jansen 				return 0;
2324e6793769SArne Jansen 			}
23252f38b3e1SArne Jansen 			if (!return_any)
23262f38b3e1SArne Jansen 				return 1;
23272f38b3e1SArne Jansen 			/*
23282f38b3e1SArne Jansen 			 * no lower item found, return the next
23292f38b3e1SArne Jansen 			 * higher instead
23302f38b3e1SArne Jansen 			 */
23312f38b3e1SArne Jansen 			return_any = 0;
23322f38b3e1SArne Jansen 			find_higher = 1;
23332f38b3e1SArne Jansen 			btrfs_release_path(p);
23342f38b3e1SArne Jansen 			goto again;
2335e6793769SArne Jansen 		} else {
23362f38b3e1SArne Jansen 			--p->slots[0];
23372f38b3e1SArne Jansen 		}
23382f38b3e1SArne Jansen 	}
23392f38b3e1SArne Jansen 	return 0;
23402f38b3e1SArne Jansen }
23412f38b3e1SArne Jansen 
23422f38b3e1SArne Jansen /*
23430ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
23440ff40a91SMarcos Paulo de Souza  * was not found.
23450ff40a91SMarcos Paulo de Souza  *
23460ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
23470ff40a91SMarcos Paulo de Souza  */
23480ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
23490ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
23500ff40a91SMarcos Paulo de Souza {
23510ff40a91SMarcos Paulo de Souza 	int ret;
23520ff40a91SMarcos Paulo de Souza 
23530ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
23540ff40a91SMarcos Paulo de Souza 	if (ret > 0)
23550ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
23560ff40a91SMarcos Paulo de Souza 
23570ff40a91SMarcos Paulo de Souza 	if (ret == 0)
23580ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
23590ff40a91SMarcos Paulo de Souza 
23600ff40a91SMarcos Paulo de Souza 	return ret;
23610ff40a91SMarcos Paulo de Souza }
23620ff40a91SMarcos Paulo de Souza 
236362142be3SGabriel Niebler /**
236462142be3SGabriel Niebler  * Search for a valid slot for the given path.
236562142be3SGabriel Niebler  *
236662142be3SGabriel Niebler  * @root:	The root node of the tree.
236762142be3SGabriel Niebler  * @key:	Will contain a valid item if found.
236862142be3SGabriel Niebler  * @path:	The starting point to validate the slot.
236962142be3SGabriel Niebler  *
237062142be3SGabriel Niebler  * Return: 0  if the item is valid
237162142be3SGabriel Niebler  *         1  if not found
237262142be3SGabriel Niebler  *         <0 if error.
237362142be3SGabriel Niebler  */
237462142be3SGabriel Niebler int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
237562142be3SGabriel Niebler 			      struct btrfs_path *path)
237662142be3SGabriel Niebler {
237762142be3SGabriel Niebler 	while (1) {
237862142be3SGabriel Niebler 		int ret;
237962142be3SGabriel Niebler 		const int slot = path->slots[0];
238062142be3SGabriel Niebler 		const struct extent_buffer *leaf = path->nodes[0];
238162142be3SGabriel Niebler 
238262142be3SGabriel Niebler 		/* This is where we start walking the path. */
238362142be3SGabriel Niebler 		if (slot >= btrfs_header_nritems(leaf)) {
238462142be3SGabriel Niebler 			/*
238562142be3SGabriel Niebler 			 * If we've reached the last slot in this leaf we need
238662142be3SGabriel Niebler 			 * to go to the next leaf and reset the path.
238762142be3SGabriel Niebler 			 */
238862142be3SGabriel Niebler 			ret = btrfs_next_leaf(root, path);
238962142be3SGabriel Niebler 			if (ret)
239062142be3SGabriel Niebler 				return ret;
239162142be3SGabriel Niebler 			continue;
239262142be3SGabriel Niebler 		}
239362142be3SGabriel Niebler 		/* Store the found, valid item in @key. */
239462142be3SGabriel Niebler 		btrfs_item_key_to_cpu(leaf, key, slot);
239562142be3SGabriel Niebler 		break;
239662142be3SGabriel Niebler 	}
239762142be3SGabriel Niebler 	return 0;
239862142be3SGabriel Niebler }
239962142be3SGabriel Niebler 
24000ff40a91SMarcos Paulo de Souza /*
240174123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
240274123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
240374123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
240474123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
240574123bd7SChris Mason  * higher levels
2406aa5d6bedSChris Mason  *
240774123bd7SChris Mason  */
2408b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
24095f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2410be0e5c09SChris Mason {
2411be0e5c09SChris Mason 	int i;
24125f39d397SChris Mason 	struct extent_buffer *t;
24130e82bcfeSDavid Sterba 	int ret;
24145f39d397SChris Mason 
2415234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2416be0e5c09SChris Mason 		int tslot = path->slots[i];
24170e82bcfeSDavid Sterba 
2418eb60ceacSChris Mason 		if (!path->nodes[i])
2419be0e5c09SChris Mason 			break;
24205f39d397SChris Mason 		t = path->nodes[i];
2421f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
242233cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
24230e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
24245f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2425d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2426be0e5c09SChris Mason 		if (tslot != 0)
2427be0e5c09SChris Mason 			break;
2428be0e5c09SChris Mason 	}
2429be0e5c09SChris Mason }
2430be0e5c09SChris Mason 
243174123bd7SChris Mason /*
243231840ae1SZheng Yan  * update item key.
243331840ae1SZheng Yan  *
243431840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
243531840ae1SZheng Yan  * that the new key won't break the order
243631840ae1SZheng Yan  */
2437b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2438b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2439310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
244031840ae1SZheng Yan {
244131840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
244231840ae1SZheng Yan 	struct extent_buffer *eb;
244331840ae1SZheng Yan 	int slot;
244431840ae1SZheng Yan 
244531840ae1SZheng Yan 	eb = path->nodes[0];
244631840ae1SZheng Yan 	slot = path->slots[0];
244731840ae1SZheng Yan 	if (slot > 0) {
244831840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
24497c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
24507c15d410SQu Wenruo 			btrfs_crit(fs_info,
24517c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
24527c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
24537c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
24547c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
24557c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
24567c15d410SQu Wenruo 				   new_key->offset);
24577c15d410SQu Wenruo 			btrfs_print_leaf(eb);
24587c15d410SQu Wenruo 			BUG();
24597c15d410SQu Wenruo 		}
246031840ae1SZheng Yan 	}
246131840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
246231840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
24637c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
24647c15d410SQu Wenruo 			btrfs_crit(fs_info,
24657c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
24667c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
24677c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
24687c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
24697c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
24707c15d410SQu Wenruo 				   new_key->offset);
24717c15d410SQu Wenruo 			btrfs_print_leaf(eb);
24727c15d410SQu Wenruo 			BUG();
24737c15d410SQu Wenruo 		}
247431840ae1SZheng Yan 	}
247531840ae1SZheng Yan 
247631840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
247731840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
247831840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
247931840ae1SZheng Yan 	if (slot == 0)
2480b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
248131840ae1SZheng Yan }
248231840ae1SZheng Yan 
248331840ae1SZheng Yan /*
2484d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2485d16c702fSQu Wenruo  *
2486d16c702fSQu Wenruo  * Return true if something is wrong.
2487d16c702fSQu Wenruo  * Return false if everything is fine.
2488d16c702fSQu Wenruo  *
2489d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2490d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2491d16c702fSQu Wenruo  *
2492d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2493d16c702fSQu Wenruo  * --------------------------------------------------------------
2494d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2495d16c702fSQu Wenruo  *
2496d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2497d16c702fSQu Wenruo  * key in leaf @right is 7.
2498d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2499d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2500d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2501d16c702fSQu Wenruo  * key of @right.
2502d16c702fSQu Wenruo  */
2503d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2504d16c702fSQu Wenruo 			       struct extent_buffer *right)
2505d16c702fSQu Wenruo {
2506d16c702fSQu Wenruo 	struct btrfs_key left_last;
2507d16c702fSQu Wenruo 	struct btrfs_key right_first;
2508d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2509d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2510d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2511d16c702fSQu Wenruo 
2512d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2513d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2514d16c702fSQu Wenruo 		return false;
2515d16c702fSQu Wenruo 
2516d16c702fSQu Wenruo 	if (level) {
2517d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2518d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2519d16c702fSQu Wenruo 	} else {
2520d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2521d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2522d16c702fSQu Wenruo 	}
2523d16c702fSQu Wenruo 
2524d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2525d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2526d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2527d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2528d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2529d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2530d16c702fSQu Wenruo 		return true;
2531d16c702fSQu Wenruo 	}
2532d16c702fSQu Wenruo 	return false;
2533d16c702fSQu Wenruo }
2534d16c702fSQu Wenruo 
2535d16c702fSQu Wenruo /*
253674123bd7SChris Mason  * try to push data from one node into the next node left in the
253779f95c82SChris Mason  * tree.
2538aa5d6bedSChris Mason  *
2539aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2540aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
254174123bd7SChris Mason  */
254298ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
25432ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2544971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2545be0e5c09SChris Mason {
2546d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2547be0e5c09SChris Mason 	int push_items = 0;
2548bb803951SChris Mason 	int src_nritems;
2549bb803951SChris Mason 	int dst_nritems;
2550aa5d6bedSChris Mason 	int ret = 0;
2551be0e5c09SChris Mason 
25525f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
25535f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
25540b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
25557bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
25567bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
255754aa1f4dSChris Mason 
2558bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2559971a1f66SChris Mason 		return 1;
2560971a1f66SChris Mason 
2561d397712bSChris Mason 	if (push_items <= 0)
2562be0e5c09SChris Mason 		return 1;
2563be0e5c09SChris Mason 
2564bce4eae9SChris Mason 	if (empty) {
2565971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2566bce4eae9SChris Mason 		if (push_items < src_nritems) {
2567bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2568bce4eae9SChris Mason 			 * we aren't going to empty it
2569bce4eae9SChris Mason 			 */
2570bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2571bce4eae9SChris Mason 				if (push_items <= 8)
2572bce4eae9SChris Mason 					return 1;
2573bce4eae9SChris Mason 				push_items -= 8;
2574bce4eae9SChris Mason 			}
2575bce4eae9SChris Mason 		}
2576bce4eae9SChris Mason 	} else
2577bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
257879f95c82SChris Mason 
2579d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2580d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2581d16c702fSQu Wenruo 		ret = -EUCLEAN;
2582d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2583d16c702fSQu Wenruo 		return ret;
2584d16c702fSQu Wenruo 	}
2585f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
25865de865eeSFilipe David Borba Manana 	if (ret) {
258766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
25885de865eeSFilipe David Borba Manana 		return ret;
25895de865eeSFilipe David Borba Manana 	}
25905f39d397SChris Mason 	copy_extent_buffer(dst, src,
25915f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
25925f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2593123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
25945f39d397SChris Mason 
2595bb803951SChris Mason 	if (push_items < src_nritems) {
259657911b8bSJan Schmidt 		/*
2597f3a84ccdSFilipe Manana 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2598f3a84ccdSFilipe Manana 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
259957911b8bSJan Schmidt 		 */
26005f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
26015f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2602e2fa7227SChris Mason 				      (src_nritems - push_items) *
2603123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2604bb803951SChris Mason 	}
26055f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
26065f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
26075f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
26085f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
260931840ae1SZheng Yan 
2610bb803951SChris Mason 	return ret;
2611be0e5c09SChris Mason }
2612be0e5c09SChris Mason 
261397571fd0SChris Mason /*
261479f95c82SChris Mason  * try to push data from one node into the next node right in the
261579f95c82SChris Mason  * tree.
261679f95c82SChris Mason  *
261779f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
261879f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
261979f95c82SChris Mason  *
262079f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
262179f95c82SChris Mason  */
26225f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
26235f39d397SChris Mason 			      struct extent_buffer *dst,
26245f39d397SChris Mason 			      struct extent_buffer *src)
262579f95c82SChris Mason {
262655d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
262779f95c82SChris Mason 	int push_items = 0;
262879f95c82SChris Mason 	int max_push;
262979f95c82SChris Mason 	int src_nritems;
263079f95c82SChris Mason 	int dst_nritems;
263179f95c82SChris Mason 	int ret = 0;
263279f95c82SChris Mason 
26337bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
26347bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
26357bb86316SChris Mason 
26365f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
26375f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
26380b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2639d397712bSChris Mason 	if (push_items <= 0)
264079f95c82SChris Mason 		return 1;
2641bce4eae9SChris Mason 
2642d397712bSChris Mason 	if (src_nritems < 4)
2643bce4eae9SChris Mason 		return 1;
264479f95c82SChris Mason 
264579f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
264679f95c82SChris Mason 	/* don't try to empty the node */
2647d397712bSChris Mason 	if (max_push >= src_nritems)
264879f95c82SChris Mason 		return 1;
2649252c38f0SYan 
265079f95c82SChris Mason 	if (max_push < push_items)
265179f95c82SChris Mason 		push_items = max_push;
265279f95c82SChris Mason 
2653d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2654d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2655d16c702fSQu Wenruo 		ret = -EUCLEAN;
2656d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2657d16c702fSQu Wenruo 		return ret;
2658d16c702fSQu Wenruo 	}
2659f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2660bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
26615f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
26625f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
26635f39d397SChris Mason 				      (dst_nritems) *
26645f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2665d6025579SChris Mason 
2666f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2667ed874f0dSDavid Sterba 					 push_items);
26685de865eeSFilipe David Borba Manana 	if (ret) {
266966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
26705de865eeSFilipe David Borba Manana 		return ret;
26715de865eeSFilipe David Borba Manana 	}
26725f39d397SChris Mason 	copy_extent_buffer(dst, src,
26735f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
26745f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2675123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
267679f95c82SChris Mason 
26775f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
26785f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
267979f95c82SChris Mason 
26805f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
26815f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
268231840ae1SZheng Yan 
268379f95c82SChris Mason 	return ret;
268479f95c82SChris Mason }
268579f95c82SChris Mason 
268679f95c82SChris Mason /*
268797571fd0SChris Mason  * helper function to insert a new root level in the tree.
268897571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
268997571fd0SChris Mason  * point to the existing root
2690aa5d6bedSChris Mason  *
2691aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
269297571fd0SChris Mason  */
2693d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
26945f39d397SChris Mason 			   struct btrfs_root *root,
2695fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
269674123bd7SChris Mason {
26970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
26987bb86316SChris Mason 	u64 lower_gen;
26995f39d397SChris Mason 	struct extent_buffer *lower;
27005f39d397SChris Mason 	struct extent_buffer *c;
2701925baeddSChris Mason 	struct extent_buffer *old;
27025f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2703d9d19a01SDavid Sterba 	int ret;
27045c680ed6SChris Mason 
27055c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
27065c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
27075c680ed6SChris Mason 
27087bb86316SChris Mason 	lower = path->nodes[level-1];
27097bb86316SChris Mason 	if (level == 1)
27107bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
27117bb86316SChris Mason 	else
27127bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
27137bb86316SChris Mason 
271479bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
271579bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2716cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
27175f39d397SChris Mason 	if (IS_ERR(c))
27185f39d397SChris Mason 		return PTR_ERR(c);
2719925baeddSChris Mason 
27200b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2721f0486c68SYan, Zheng 
27225f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
27235f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2724db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
27257bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
272631840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
27277bb86316SChris Mason 
27287bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
27295f39d397SChris Mason 
27305f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2731d5719762SChris Mason 
2732925baeddSChris Mason 	old = root->node;
2733406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2734d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2735240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2736925baeddSChris Mason 
2737925baeddSChris Mason 	/* the super has an extra ref to root->node */
2738925baeddSChris Mason 	free_extent_buffer(old);
2739925baeddSChris Mason 
27400b86a832SChris Mason 	add_root_to_dirty_list(root);
274167439dadSDavid Sterba 	atomic_inc(&c->refs);
27425f39d397SChris Mason 	path->nodes[level] = c;
2743ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
274474123bd7SChris Mason 	path->slots[level] = 0;
274574123bd7SChris Mason 	return 0;
274674123bd7SChris Mason }
27475c680ed6SChris Mason 
27485c680ed6SChris Mason /*
27495c680ed6SChris Mason  * worker function to insert a single pointer in a node.
27505c680ed6SChris Mason  * the node should have enough room for the pointer already
275197571fd0SChris Mason  *
27525c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
27535c680ed6SChris Mason  * blocknr is the block the key points to.
27545c680ed6SChris Mason  */
2755143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
27566ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2757143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2758c3e06965SJan Schmidt 		       int slot, int level)
27595c680ed6SChris Mason {
27605f39d397SChris Mason 	struct extent_buffer *lower;
27615c680ed6SChris Mason 	int nritems;
2762f3ea38daSJan Schmidt 	int ret;
27635c680ed6SChris Mason 
27645c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
276549d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
27665f39d397SChris Mason 	lower = path->nodes[level];
27675f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2768c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
27696ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
277074123bd7SChris Mason 	if (slot != nritems) {
2771bf1d3425SDavid Sterba 		if (level) {
2772f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2773f3a84ccdSFilipe Manana 					slot, nritems - slot);
2774bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2775bf1d3425SDavid Sterba 		}
27765f39d397SChris Mason 		memmove_extent_buffer(lower,
27775f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
27785f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
2779123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
278074123bd7SChris Mason 	}
2781c3e06965SJan Schmidt 	if (level) {
2782f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
278333cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_ADD);
2784f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2785f3ea38daSJan Schmidt 	}
27865f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2787db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
278874493f7aSChris Mason 	WARN_ON(trans->transid == 0);
278974493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
27905f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
27915f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
279274123bd7SChris Mason }
279374123bd7SChris Mason 
279497571fd0SChris Mason /*
279597571fd0SChris Mason  * split the node at the specified level in path in two.
279697571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
279797571fd0SChris Mason  *
279897571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
279997571fd0SChris Mason  * left and right, if either one works, it returns right away.
2800aa5d6bedSChris Mason  *
2801aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
280297571fd0SChris Mason  */
2803e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
2804e02119d5SChris Mason 			       struct btrfs_root *root,
2805e02119d5SChris Mason 			       struct btrfs_path *path, int level)
2806be0e5c09SChris Mason {
28070b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
28085f39d397SChris Mason 	struct extent_buffer *c;
28095f39d397SChris Mason 	struct extent_buffer *split;
28105f39d397SChris Mason 	struct btrfs_disk_key disk_key;
2811be0e5c09SChris Mason 	int mid;
28125c680ed6SChris Mason 	int ret;
28137518a238SChris Mason 	u32 c_nritems;
2814be0e5c09SChris Mason 
28155f39d397SChris Mason 	c = path->nodes[level];
28167bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
28175f39d397SChris Mason 	if (c == root->node) {
2818d9abbf1cSJan Schmidt 		/*
281990f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
282090f8d62eSJan Schmidt 		 *
2821fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
282290f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
282390f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
2824f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2825f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
2826f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
2827d9abbf1cSJan Schmidt 		 */
2828fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
28295c680ed6SChris Mason 		if (ret)
28305c680ed6SChris Mason 			return ret;
2831b3612421SChris Mason 	} else {
2832e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
28335f39d397SChris Mason 		c = path->nodes[level];
28345f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
28350b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2836e66f709bSChris Mason 			return 0;
283754aa1f4dSChris Mason 		if (ret < 0)
283854aa1f4dSChris Mason 			return ret;
28395c680ed6SChris Mason 	}
2840e66f709bSChris Mason 
28415f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
28425d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
28435d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
28447bb86316SChris Mason 
284579bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
284679bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
284779bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
28485f39d397SChris Mason 	if (IS_ERR(split))
28495f39d397SChris Mason 		return PTR_ERR(split);
285054aa1f4dSChris Mason 
28510b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2852bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
28535f39d397SChris Mason 
2854f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
28555de865eeSFilipe David Borba Manana 	if (ret) {
285666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
28575de865eeSFilipe David Borba Manana 		return ret;
28585de865eeSFilipe David Borba Manana 	}
28595f39d397SChris Mason 	copy_extent_buffer(split, c,
28605f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
28615f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
2862123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
28635f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
28645f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
2865aa5d6bedSChris Mason 
28665f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
28675f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
28685f39d397SChris Mason 
28696ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
2870c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
2871aa5d6bedSChris Mason 
28725de08d7dSChris Mason 	if (path->slots[level] >= mid) {
28735c680ed6SChris Mason 		path->slots[level] -= mid;
2874925baeddSChris Mason 		btrfs_tree_unlock(c);
28755f39d397SChris Mason 		free_extent_buffer(c);
28765f39d397SChris Mason 		path->nodes[level] = split;
28775c680ed6SChris Mason 		path->slots[level + 1] += 1;
2878eb60ceacSChris Mason 	} else {
2879925baeddSChris Mason 		btrfs_tree_unlock(split);
28805f39d397SChris Mason 		free_extent_buffer(split);
2881be0e5c09SChris Mason 	}
2882d5286a92SNikolay Borisov 	return 0;
2883be0e5c09SChris Mason }
2884be0e5c09SChris Mason 
288574123bd7SChris Mason /*
288674123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
288774123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
288874123bd7SChris Mason  * space used both by the item structs and the item data
288974123bd7SChris Mason  */
28905f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2891be0e5c09SChris Mason {
2892be0e5c09SChris Mason 	int data_len;
28935f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
2894d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
2895be0e5c09SChris Mason 
2896be0e5c09SChris Mason 	if (!nr)
2897be0e5c09SChris Mason 		return 0;
28983212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
28993212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
29000783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
2901d4dbff95SChris Mason 	WARN_ON(data_len < 0);
2902be0e5c09SChris Mason 	return data_len;
2903be0e5c09SChris Mason }
2904be0e5c09SChris Mason 
290574123bd7SChris Mason /*
2906d4dbff95SChris Mason  * The space between the end of the leaf items and
2907d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
2908d4dbff95SChris Mason  * the leaf has left for both items and data
2909d4dbff95SChris Mason  */
2910e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
2911d4dbff95SChris Mason {
2912e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
29135f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
29145f39d397SChris Mason 	int ret;
29150b246afaSJeff Mahoney 
29160b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
29175f39d397SChris Mason 	if (ret < 0) {
29180b246afaSJeff Mahoney 		btrfs_crit(fs_info,
2919efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2920da17066cSJeff Mahoney 			   ret,
29210b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
29225f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
29235f39d397SChris Mason 	}
29245f39d397SChris Mason 	return ret;
2925d4dbff95SChris Mason }
2926d4dbff95SChris Mason 
292799d8f83cSChris Mason /*
292899d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
292999d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
293099d8f83cSChris Mason  */
2931f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
293244871b1bSChris Mason 				      int data_size, int empty,
293344871b1bSChris Mason 				      struct extent_buffer *right,
293499d8f83cSChris Mason 				      int free_space, u32 left_nritems,
293599d8f83cSChris Mason 				      u32 min_slot)
293600ec4c51SChris Mason {
2937f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
29385f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
293944871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
2940cfed81a0SChris Mason 	struct btrfs_map_token token;
29415f39d397SChris Mason 	struct btrfs_disk_key disk_key;
294200ec4c51SChris Mason 	int slot;
294334a38218SChris Mason 	u32 i;
294400ec4c51SChris Mason 	int push_space = 0;
294500ec4c51SChris Mason 	int push_items = 0;
294634a38218SChris Mason 	u32 nr;
29477518a238SChris Mason 	u32 right_nritems;
29485f39d397SChris Mason 	u32 data_end;
2949db94535dSChris Mason 	u32 this_item_size;
295000ec4c51SChris Mason 
295134a38218SChris Mason 	if (empty)
295234a38218SChris Mason 		nr = 0;
295334a38218SChris Mason 	else
295499d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
295534a38218SChris Mason 
295631840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
295787b29b20SYan Zheng 		push_space += data_size;
295831840ae1SZheng Yan 
295944871b1bSChris Mason 	slot = path->slots[1];
296034a38218SChris Mason 	i = left_nritems - 1;
296134a38218SChris Mason 	while (i >= nr) {
296231840ae1SZheng Yan 		if (!empty && push_items > 0) {
296331840ae1SZheng Yan 			if (path->slots[0] > i)
296431840ae1SZheng Yan 				break;
296531840ae1SZheng Yan 			if (path->slots[0] == i) {
2966e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
2967e902baacSDavid Sterba 
296831840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
296931840ae1SZheng Yan 					break;
297031840ae1SZheng Yan 			}
297131840ae1SZheng Yan 		}
297231840ae1SZheng Yan 
297300ec4c51SChris Mason 		if (path->slots[0] == i)
297487b29b20SYan Zheng 			push_space += data_size;
2975db94535dSChris Mason 
29763212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
297774794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
297874794207SJosef Bacik 		    push_space > free_space)
297900ec4c51SChris Mason 			break;
298031840ae1SZheng Yan 
298100ec4c51SChris Mason 		push_items++;
298274794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
298334a38218SChris Mason 		if (i == 0)
298434a38218SChris Mason 			break;
298534a38218SChris Mason 		i--;
2986db94535dSChris Mason 	}
29875f39d397SChris Mason 
2988925baeddSChris Mason 	if (push_items == 0)
2989925baeddSChris Mason 		goto out_unlock;
29905f39d397SChris Mason 
29916c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
29925f39d397SChris Mason 
299300ec4c51SChris Mason 	/* push left to right */
29945f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
299534a38218SChris Mason 
2996dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
29978f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
29985f39d397SChris Mason 
299900ec4c51SChris Mason 	/* make room in the right data area */
30008f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
30015f39d397SChris Mason 	memmove_extent_buffer(right,
30023d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
30033d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
30040b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
30055f39d397SChris Mason 
300600ec4c51SChris Mason 	/* copy from the left data area */
30073d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
30080b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
30098f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3010d6025579SChris Mason 		     push_space);
30115f39d397SChris Mason 
30125f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
30135f39d397SChris Mason 			      btrfs_item_nr_offset(0),
30140783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
30155f39d397SChris Mason 
301600ec4c51SChris Mason 	/* copy the items from left to right */
30175f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
30185f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
30190783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
302000ec4c51SChris Mason 
302100ec4c51SChris Mason 	/* update the item pointers */
3022c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
30237518a238SChris Mason 	right_nritems += push_items;
30245f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
30250b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
30267518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
30273212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
30283212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3029db94535dSChris Mason 	}
3030db94535dSChris Mason 
30317518a238SChris Mason 	left_nritems -= push_items;
30325f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
303300ec4c51SChris Mason 
303434a38218SChris Mason 	if (left_nritems)
30355f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3036f0486c68SYan, Zheng 	else
30376a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3038f0486c68SYan, Zheng 
30395f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3040a429e513SChris Mason 
30415f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
30425f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3043d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
304402217ed2SChris Mason 
304500ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
30467518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
30477518a238SChris Mason 		path->slots[0] -= left_nritems;
3048925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
30496a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3050925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
30515f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
30525f39d397SChris Mason 		path->nodes[0] = right;
305300ec4c51SChris Mason 		path->slots[1] += 1;
305400ec4c51SChris Mason 	} else {
3055925baeddSChris Mason 		btrfs_tree_unlock(right);
30565f39d397SChris Mason 		free_extent_buffer(right);
305700ec4c51SChris Mason 	}
305800ec4c51SChris Mason 	return 0;
3059925baeddSChris Mason 
3060925baeddSChris Mason out_unlock:
3061925baeddSChris Mason 	btrfs_tree_unlock(right);
3062925baeddSChris Mason 	free_extent_buffer(right);
3063925baeddSChris Mason 	return 1;
306400ec4c51SChris Mason }
3065925baeddSChris Mason 
306600ec4c51SChris Mason /*
306744871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
306874123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
306944871b1bSChris Mason  *
307044871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
307144871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
307299d8f83cSChris Mason  *
307399d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
307499d8f83cSChris Mason  * push any slot lower than min_slot
307574123bd7SChris Mason  */
307644871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
307799d8f83cSChris Mason 			   *root, struct btrfs_path *path,
307899d8f83cSChris Mason 			   int min_data_size, int data_size,
307999d8f83cSChris Mason 			   int empty, u32 min_slot)
3080be0e5c09SChris Mason {
308144871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
308244871b1bSChris Mason 	struct extent_buffer *right;
308344871b1bSChris Mason 	struct extent_buffer *upper;
308444871b1bSChris Mason 	int slot;
308544871b1bSChris Mason 	int free_space;
308644871b1bSChris Mason 	u32 left_nritems;
308744871b1bSChris Mason 	int ret;
308844871b1bSChris Mason 
308944871b1bSChris Mason 	if (!path->nodes[1])
309044871b1bSChris Mason 		return 1;
309144871b1bSChris Mason 
309244871b1bSChris Mason 	slot = path->slots[1];
309344871b1bSChris Mason 	upper = path->nodes[1];
309444871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
309544871b1bSChris Mason 		return 1;
309644871b1bSChris Mason 
309749d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
309844871b1bSChris Mason 
30994b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3100fb770ae4SLiu Bo 	/*
3101fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3102fb770ae4SLiu Bo 	 * no big deal, just return.
3103fb770ae4SLiu Bo 	 */
3104fb770ae4SLiu Bo 	if (IS_ERR(right))
310591ca338dSTsutomu Itoh 		return 1;
310691ca338dSTsutomu Itoh 
3107bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
310844871b1bSChris Mason 
3109e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
311044871b1bSChris Mason 	if (free_space < data_size)
311144871b1bSChris Mason 		goto out_unlock;
311244871b1bSChris Mason 
311344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3114bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
311544871b1bSChris Mason 	if (ret)
311644871b1bSChris Mason 		goto out_unlock;
311744871b1bSChris Mason 
311844871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
311944871b1bSChris Mason 	if (left_nritems == 0)
312044871b1bSChris Mason 		goto out_unlock;
312144871b1bSChris Mason 
3122d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3123d16c702fSQu Wenruo 		ret = -EUCLEAN;
3124d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3125d16c702fSQu Wenruo 		free_extent_buffer(right);
3126d16c702fSQu Wenruo 		return ret;
3127d16c702fSQu Wenruo 	}
31282ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
31292ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
31302ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
31312ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
313252042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
31332ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
31342ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
31352ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
31362ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
31372ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
31382ef1fed2SFilipe David Borba Manana 		return 0;
31392ef1fed2SFilipe David Borba Manana 	}
31402ef1fed2SFilipe David Borba Manana 
3141f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
314299d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
314344871b1bSChris Mason out_unlock:
314444871b1bSChris Mason 	btrfs_tree_unlock(right);
314544871b1bSChris Mason 	free_extent_buffer(right);
314644871b1bSChris Mason 	return 1;
314744871b1bSChris Mason }
314844871b1bSChris Mason 
314944871b1bSChris Mason /*
315044871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
315144871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
315299d8f83cSChris Mason  *
315399d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
315499d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
315599d8f83cSChris Mason  * items
315644871b1bSChris Mason  */
31578087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
315844871b1bSChris Mason 				     int empty, struct extent_buffer *left,
315999d8f83cSChris Mason 				     int free_space, u32 right_nritems,
316099d8f83cSChris Mason 				     u32 max_slot)
316144871b1bSChris Mason {
31628087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
31635f39d397SChris Mason 	struct btrfs_disk_key disk_key;
31645f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3165be0e5c09SChris Mason 	int i;
3166be0e5c09SChris Mason 	int push_space = 0;
3167be0e5c09SChris Mason 	int push_items = 0;
31687518a238SChris Mason 	u32 old_left_nritems;
316934a38218SChris Mason 	u32 nr;
3170aa5d6bedSChris Mason 	int ret = 0;
3171db94535dSChris Mason 	u32 this_item_size;
3172db94535dSChris Mason 	u32 old_left_item_size;
3173cfed81a0SChris Mason 	struct btrfs_map_token token;
3174cfed81a0SChris Mason 
317534a38218SChris Mason 	if (empty)
317699d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
317734a38218SChris Mason 	else
317899d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
317934a38218SChris Mason 
318034a38218SChris Mason 	for (i = 0; i < nr; i++) {
318131840ae1SZheng Yan 		if (!empty && push_items > 0) {
318231840ae1SZheng Yan 			if (path->slots[0] < i)
318331840ae1SZheng Yan 				break;
318431840ae1SZheng Yan 			if (path->slots[0] == i) {
3185e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3186e902baacSDavid Sterba 
318731840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
318831840ae1SZheng Yan 					break;
318931840ae1SZheng Yan 			}
319031840ae1SZheng Yan 		}
319131840ae1SZheng Yan 
3192be0e5c09SChris Mason 		if (path->slots[0] == i)
319387b29b20SYan Zheng 			push_space += data_size;
3194db94535dSChris Mason 
31953212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
319674794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
319774794207SJosef Bacik 		    free_space)
3198be0e5c09SChris Mason 			break;
3199db94535dSChris Mason 
3200be0e5c09SChris Mason 		push_items++;
320174794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3202be0e5c09SChris Mason 	}
3203db94535dSChris Mason 
3204be0e5c09SChris Mason 	if (push_items == 0) {
3205925baeddSChris Mason 		ret = 1;
3206925baeddSChris Mason 		goto out;
3207be0e5c09SChris Mason 	}
3208fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
32095f39d397SChris Mason 
3210be0e5c09SChris Mason 	/* push data from right to left */
32115f39d397SChris Mason 	copy_extent_buffer(left, right,
32125f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
32135f39d397SChris Mason 			   btrfs_item_nr_offset(0),
32145f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
32155f39d397SChris Mason 
32160b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
32173212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
32185f39d397SChris Mason 
32193d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
32208f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
32213d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
32223212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1),
3223be0e5c09SChris Mason 		     push_space);
32245f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
322587b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3226eb60ceacSChris Mason 
3227c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
32283212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3229be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
32305f39d397SChris Mason 		u32 ioff;
3231db94535dSChris Mason 
32323212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
32333212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3234cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3235be0e5c09SChris Mason 	}
32365f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3237be0e5c09SChris Mason 
3238be0e5c09SChris Mason 	/* fixup right node */
323931b1a2bdSJulia Lawall 	if (push_items > right_nritems)
324031b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3241d397712bSChris Mason 		       right_nritems);
324234a38218SChris Mason 
324334a38218SChris Mason 	if (push_items < right_nritems) {
32443212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
32458f881e8cSDavid Sterba 						  leaf_data_end(right);
32463d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
32470b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
32483d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
32498f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
32505f39d397SChris Mason 
32515f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
32525f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
32535f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
32540783fcfcSChris Mason 			     sizeof(struct btrfs_item));
325534a38218SChris Mason 	}
3256c82f823cSDavid Sterba 
3257c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3258eef1c494SYan 	right_nritems -= push_items;
3259eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
32600b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
32615f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
32623212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
32633212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3264db94535dSChris Mason 	}
3265eb60ceacSChris Mason 
32665f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
326734a38218SChris Mason 	if (right_nritems)
32685f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3269f0486c68SYan, Zheng 	else
32706a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3271098f59c2SChris Mason 
32725f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3273b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3274be0e5c09SChris Mason 
3275be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3276be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3277be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3278925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32795f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32805f39d397SChris Mason 		path->nodes[0] = left;
3281be0e5c09SChris Mason 		path->slots[1] -= 1;
3282be0e5c09SChris Mason 	} else {
3283925baeddSChris Mason 		btrfs_tree_unlock(left);
32845f39d397SChris Mason 		free_extent_buffer(left);
3285be0e5c09SChris Mason 		path->slots[0] -= push_items;
3286be0e5c09SChris Mason 	}
3287eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3288aa5d6bedSChris Mason 	return ret;
3289925baeddSChris Mason out:
3290925baeddSChris Mason 	btrfs_tree_unlock(left);
3291925baeddSChris Mason 	free_extent_buffer(left);
3292925baeddSChris Mason 	return ret;
3293be0e5c09SChris Mason }
3294be0e5c09SChris Mason 
329574123bd7SChris Mason /*
329644871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
329744871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
329899d8f83cSChris Mason  *
329999d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
330099d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
330199d8f83cSChris Mason  * items
330244871b1bSChris Mason  */
330344871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
330499d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
330599d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
330644871b1bSChris Mason {
330744871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
330844871b1bSChris Mason 	struct extent_buffer *left;
330944871b1bSChris Mason 	int slot;
331044871b1bSChris Mason 	int free_space;
331144871b1bSChris Mason 	u32 right_nritems;
331244871b1bSChris Mason 	int ret = 0;
331344871b1bSChris Mason 
331444871b1bSChris Mason 	slot = path->slots[1];
331544871b1bSChris Mason 	if (slot == 0)
331644871b1bSChris Mason 		return 1;
331744871b1bSChris Mason 	if (!path->nodes[1])
331844871b1bSChris Mason 		return 1;
331944871b1bSChris Mason 
332044871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
332144871b1bSChris Mason 	if (right_nritems == 0)
332244871b1bSChris Mason 		return 1;
332344871b1bSChris Mason 
332449d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
332544871b1bSChris Mason 
33264b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3327fb770ae4SLiu Bo 	/*
3328fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3329fb770ae4SLiu Bo 	 * no big deal, just return.
3330fb770ae4SLiu Bo 	 */
3331fb770ae4SLiu Bo 	if (IS_ERR(left))
333291ca338dSTsutomu Itoh 		return 1;
333391ca338dSTsutomu Itoh 
3334bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
333544871b1bSChris Mason 
3336e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
333744871b1bSChris Mason 	if (free_space < data_size) {
333844871b1bSChris Mason 		ret = 1;
333944871b1bSChris Mason 		goto out;
334044871b1bSChris Mason 	}
334144871b1bSChris Mason 
334244871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
33439631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3344bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
334544871b1bSChris Mason 	if (ret) {
334644871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
334779787eaaSJeff Mahoney 		if (ret == -ENOSPC)
334844871b1bSChris Mason 			ret = 1;
334944871b1bSChris Mason 		goto out;
335044871b1bSChris Mason 	}
335144871b1bSChris Mason 
3352d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3353d16c702fSQu Wenruo 		ret = -EUCLEAN;
3354d16c702fSQu Wenruo 		goto out;
3355d16c702fSQu Wenruo 	}
33568087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
335799d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
335899d8f83cSChris Mason 			       max_slot);
335944871b1bSChris Mason out:
336044871b1bSChris Mason 	btrfs_tree_unlock(left);
336144871b1bSChris Mason 	free_extent_buffer(left);
336244871b1bSChris Mason 	return ret;
336344871b1bSChris Mason }
336444871b1bSChris Mason 
336544871b1bSChris Mason /*
336674123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
336774123bd7SChris Mason  * available for the resulting leaf level of the path.
336874123bd7SChris Mason  */
3369143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
337044871b1bSChris Mason 				    struct btrfs_path *path,
337144871b1bSChris Mason 				    struct extent_buffer *l,
337244871b1bSChris Mason 				    struct extent_buffer *right,
337344871b1bSChris Mason 				    int slot, int mid, int nritems)
3374be0e5c09SChris Mason {
337594f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3376be0e5c09SChris Mason 	int data_copy_size;
3377be0e5c09SChris Mason 	int rt_data_off;
3378be0e5c09SChris Mason 	int i;
3379d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3380cfed81a0SChris Mason 	struct btrfs_map_token token;
3381cfed81a0SChris Mason 
33825f39d397SChris Mason 	nritems = nritems - mid;
33835f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3384dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
33855f39d397SChris Mason 
33865f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
33875f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
33885f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
33895f39d397SChris Mason 
33905f39d397SChris Mason 	copy_extent_buffer(right, l,
33913d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
33923d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
33938f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
339474123bd7SChris Mason 
3395dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
33965f39d397SChris Mason 
3397c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
33985f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3399db94535dSChris Mason 		u32 ioff;
3400db94535dSChris Mason 
34013212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
34023212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
34030783fcfcSChris Mason 	}
340474123bd7SChris Mason 
34055f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
34065f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
34076ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
34085f39d397SChris Mason 
34095f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
34105f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3411eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
34125f39d397SChris Mason 
3413be0e5c09SChris Mason 	if (mid <= slot) {
3414925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
34155f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
34165f39d397SChris Mason 		path->nodes[0] = right;
3417be0e5c09SChris Mason 		path->slots[0] -= mid;
3418be0e5c09SChris Mason 		path->slots[1] += 1;
3419925baeddSChris Mason 	} else {
3420925baeddSChris Mason 		btrfs_tree_unlock(right);
34215f39d397SChris Mason 		free_extent_buffer(right);
3422925baeddSChris Mason 	}
34235f39d397SChris Mason 
3424eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
342544871b1bSChris Mason }
342644871b1bSChris Mason 
342744871b1bSChris Mason /*
342899d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
342999d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
343099d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
343199d8f83cSChris Mason  *          A                 B                 C
343299d8f83cSChris Mason  *
343399d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
343499d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
343599d8f83cSChris Mason  * completely.
343699d8f83cSChris Mason  */
343799d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
343899d8f83cSChris Mason 					  struct btrfs_root *root,
343999d8f83cSChris Mason 					  struct btrfs_path *path,
344099d8f83cSChris Mason 					  int data_size)
344199d8f83cSChris Mason {
344299d8f83cSChris Mason 	int ret;
344399d8f83cSChris Mason 	int progress = 0;
344499d8f83cSChris Mason 	int slot;
344599d8f83cSChris Mason 	u32 nritems;
34465a4267caSFilipe David Borba Manana 	int space_needed = data_size;
344799d8f83cSChris Mason 
344899d8f83cSChris Mason 	slot = path->slots[0];
34495a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3450e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
345199d8f83cSChris Mason 
345299d8f83cSChris Mason 	/*
345399d8f83cSChris Mason 	 * try to push all the items after our slot into the
345499d8f83cSChris Mason 	 * right leaf
345599d8f83cSChris Mason 	 */
34565a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
345799d8f83cSChris Mason 	if (ret < 0)
345899d8f83cSChris Mason 		return ret;
345999d8f83cSChris Mason 
346099d8f83cSChris Mason 	if (ret == 0)
346199d8f83cSChris Mason 		progress++;
346299d8f83cSChris Mason 
346399d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
346499d8f83cSChris Mason 	/*
346599d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
346699d8f83cSChris Mason 	 * we've done so we're done
346799d8f83cSChris Mason 	 */
346899d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
346999d8f83cSChris Mason 		return 0;
347099d8f83cSChris Mason 
3471e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
347299d8f83cSChris Mason 		return 0;
347399d8f83cSChris Mason 
347499d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
347599d8f83cSChris Mason 	slot = path->slots[0];
3476263d3995SFilipe Manana 	space_needed = data_size;
3477263d3995SFilipe Manana 	if (slot > 0)
3478e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
34795a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
348099d8f83cSChris Mason 	if (ret < 0)
348199d8f83cSChris Mason 		return ret;
348299d8f83cSChris Mason 
348399d8f83cSChris Mason 	if (ret == 0)
348499d8f83cSChris Mason 		progress++;
348599d8f83cSChris Mason 
348699d8f83cSChris Mason 	if (progress)
348799d8f83cSChris Mason 		return 0;
348899d8f83cSChris Mason 	return 1;
348999d8f83cSChris Mason }
349099d8f83cSChris Mason 
349199d8f83cSChris Mason /*
349244871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
349344871b1bSChris Mason  * available for the resulting leaf level of the path.
349444871b1bSChris Mason  *
349544871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
349644871b1bSChris Mason  */
349744871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
349844871b1bSChris Mason 			       struct btrfs_root *root,
3499310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
350044871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
350144871b1bSChris Mason 			       int extend)
350244871b1bSChris Mason {
35035d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
350444871b1bSChris Mason 	struct extent_buffer *l;
350544871b1bSChris Mason 	u32 nritems;
350644871b1bSChris Mason 	int mid;
350744871b1bSChris Mason 	int slot;
350844871b1bSChris Mason 	struct extent_buffer *right;
3509b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
351044871b1bSChris Mason 	int ret = 0;
351144871b1bSChris Mason 	int wret;
35125d4f98a2SYan Zheng 	int split;
351344871b1bSChris Mason 	int num_doubles = 0;
351499d8f83cSChris Mason 	int tried_avoid_double = 0;
351544871b1bSChris Mason 
3516a5719521SYan, Zheng 	l = path->nodes[0];
3517a5719521SYan, Zheng 	slot = path->slots[0];
35183212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
35190b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3520a5719521SYan, Zheng 		return -EOVERFLOW;
3521a5719521SYan, Zheng 
352244871b1bSChris Mason 	/* first try to make some room by pushing left and right */
352333157e05SLiu Bo 	if (data_size && path->nodes[1]) {
35245a4267caSFilipe David Borba Manana 		int space_needed = data_size;
35255a4267caSFilipe David Borba Manana 
35265a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3527e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
35285a4267caSFilipe David Borba Manana 
35295a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
35305a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
353144871b1bSChris Mason 		if (wret < 0)
353244871b1bSChris Mason 			return wret;
353344871b1bSChris Mason 		if (wret) {
3534263d3995SFilipe Manana 			space_needed = data_size;
3535263d3995SFilipe Manana 			if (slot > 0)
3536e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
35375a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
35385a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
353944871b1bSChris Mason 			if (wret < 0)
354044871b1bSChris Mason 				return wret;
354144871b1bSChris Mason 		}
354244871b1bSChris Mason 		l = path->nodes[0];
354344871b1bSChris Mason 
354444871b1bSChris Mason 		/* did the pushes work? */
3545e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
354644871b1bSChris Mason 			return 0;
354744871b1bSChris Mason 	}
354844871b1bSChris Mason 
354944871b1bSChris Mason 	if (!path->nodes[1]) {
3550fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
355144871b1bSChris Mason 		if (ret)
355244871b1bSChris Mason 			return ret;
355344871b1bSChris Mason 	}
355444871b1bSChris Mason again:
35555d4f98a2SYan Zheng 	split = 1;
355644871b1bSChris Mason 	l = path->nodes[0];
355744871b1bSChris Mason 	slot = path->slots[0];
355844871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
355944871b1bSChris Mason 	mid = (nritems + 1) / 2;
356044871b1bSChris Mason 
35615d4f98a2SYan Zheng 	if (mid <= slot) {
35625d4f98a2SYan Zheng 		if (nritems == 1 ||
35635d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
35640b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
35655d4f98a2SYan Zheng 			if (slot >= nritems) {
35665d4f98a2SYan Zheng 				split = 0;
35675d4f98a2SYan Zheng 			} else {
35685d4f98a2SYan Zheng 				mid = slot;
35695d4f98a2SYan Zheng 				if (mid != nritems &&
35705d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
35710b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
357299d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
357399d8f83cSChris Mason 						goto push_for_double;
35745d4f98a2SYan Zheng 					split = 2;
35755d4f98a2SYan Zheng 				}
35765d4f98a2SYan Zheng 			}
35775d4f98a2SYan Zheng 		}
35785d4f98a2SYan Zheng 	} else {
35795d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
35800b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
35815d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
35825d4f98a2SYan Zheng 				split = 0;
35835d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
35845d4f98a2SYan Zheng 				mid = 1;
35855d4f98a2SYan Zheng 			} else {
35865d4f98a2SYan Zheng 				mid = slot;
35875d4f98a2SYan Zheng 				if (mid != nritems &&
35885d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
35890b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
359099d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
359199d8f83cSChris Mason 						goto push_for_double;
35925d4f98a2SYan Zheng 					split = 2;
35935d4f98a2SYan Zheng 				}
35945d4f98a2SYan Zheng 			}
35955d4f98a2SYan Zheng 		}
35965d4f98a2SYan Zheng 	}
35975d4f98a2SYan Zheng 
35985d4f98a2SYan Zheng 	if (split == 0)
35995d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
36005d4f98a2SYan Zheng 	else
36015d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
36025d4f98a2SYan Zheng 
3603ca9d473aSJosef Bacik 	/*
3604ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3605ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3606ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3607ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3608ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3609ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3610ca9d473aSJosef Bacik 	 */
361179bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
361279bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
361379bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3614ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3615f0486c68SYan, Zheng 	if (IS_ERR(right))
361644871b1bSChris Mason 		return PTR_ERR(right);
3617f0486c68SYan, Zheng 
36180b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
361944871b1bSChris Mason 
36205d4f98a2SYan Zheng 	if (split == 0) {
362144871b1bSChris Mason 		if (mid <= slot) {
362244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
36236ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
36242ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
362544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
362644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
362744871b1bSChris Mason 			path->nodes[0] = right;
362844871b1bSChris Mason 			path->slots[0] = 0;
362944871b1bSChris Mason 			path->slots[1] += 1;
363044871b1bSChris Mason 		} else {
363144871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
36326ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
36332ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
363444871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
363544871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
363644871b1bSChris Mason 			path->nodes[0] = right;
363744871b1bSChris Mason 			path->slots[0] = 0;
3638143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3639b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
36405d4f98a2SYan Zheng 		}
3641196e0249SLiu Bo 		/*
3642196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3643196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3644196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3645196e0249SLiu Bo 		 */
364644871b1bSChris Mason 		return ret;
364744871b1bSChris Mason 	}
364844871b1bSChris Mason 
364994f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
365044871b1bSChris Mason 
36515d4f98a2SYan Zheng 	if (split == 2) {
3652cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3653cc0c5538SChris Mason 		num_doubles++;
3654cc0c5538SChris Mason 		goto again;
36553326d1b0SChris Mason 	}
365644871b1bSChris Mason 
3657143bede5SJeff Mahoney 	return 0;
365899d8f83cSChris Mason 
365999d8f83cSChris Mason push_for_double:
366099d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
366199d8f83cSChris Mason 	tried_avoid_double = 1;
3662e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
366399d8f83cSChris Mason 		return 0;
366499d8f83cSChris Mason 	goto again;
3665be0e5c09SChris Mason }
3666be0e5c09SChris Mason 
3667ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3668ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3669ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3670ad48fd75SYan, Zheng {
3671ad48fd75SYan, Zheng 	struct btrfs_key key;
3672ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3673ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3674ad48fd75SYan, Zheng 	u64 extent_len = 0;
3675ad48fd75SYan, Zheng 	u32 item_size;
3676ad48fd75SYan, Zheng 	int ret;
3677ad48fd75SYan, Zheng 
3678ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3679ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3680ad48fd75SYan, Zheng 
3681ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3682ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3683ad48fd75SYan, Zheng 
3684e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3685ad48fd75SYan, Zheng 		return 0;
3686ad48fd75SYan, Zheng 
36873212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3688ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3689ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3690ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3691ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3692ad48fd75SYan, Zheng 	}
3693b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3694ad48fd75SYan, Zheng 
3695ad48fd75SYan, Zheng 	path->keep_locks = 1;
3696ad48fd75SYan, Zheng 	path->search_for_split = 1;
3697ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3698ad48fd75SYan, Zheng 	path->search_for_split = 0;
3699a8df6fe6SFilipe Manana 	if (ret > 0)
3700a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3701ad48fd75SYan, Zheng 	if (ret < 0)
3702ad48fd75SYan, Zheng 		goto err;
3703ad48fd75SYan, Zheng 
3704ad48fd75SYan, Zheng 	ret = -EAGAIN;
3705ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3706a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
37073212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3708ad48fd75SYan, Zheng 		goto err;
3709ad48fd75SYan, Zheng 
3710109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3711e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3712109f6aefSChris Mason 		goto err;
3713109f6aefSChris Mason 
3714ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3715ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3716ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3717ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3718ad48fd75SYan, Zheng 			goto err;
3719ad48fd75SYan, Zheng 	}
3720ad48fd75SYan, Zheng 
3721ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3722f0486c68SYan, Zheng 	if (ret)
3723f0486c68SYan, Zheng 		goto err;
3724ad48fd75SYan, Zheng 
3725ad48fd75SYan, Zheng 	path->keep_locks = 0;
3726ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3727ad48fd75SYan, Zheng 	return 0;
3728ad48fd75SYan, Zheng err:
3729ad48fd75SYan, Zheng 	path->keep_locks = 0;
3730ad48fd75SYan, Zheng 	return ret;
3731ad48fd75SYan, Zheng }
3732ad48fd75SYan, Zheng 
373325263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3734310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3735459931ecSChris Mason 			       unsigned long split_offset)
3736459931ecSChris Mason {
3737459931ecSChris Mason 	struct extent_buffer *leaf;
3738c91666b1SJosef Bacik 	int orig_slot, slot;
3739ad48fd75SYan, Zheng 	char *buf;
3740459931ecSChris Mason 	u32 nritems;
3741ad48fd75SYan, Zheng 	u32 item_size;
3742459931ecSChris Mason 	u32 orig_offset;
3743459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3744459931ecSChris Mason 
3745459931ecSChris Mason 	leaf = path->nodes[0];
3746e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3747b9473439SChris Mason 
3748c91666b1SJosef Bacik 	orig_slot = path->slots[0];
37493212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
37503212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3751459931ecSChris Mason 
3752459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3753ad48fd75SYan, Zheng 	if (!buf)
3754ad48fd75SYan, Zheng 		return -ENOMEM;
3755ad48fd75SYan, Zheng 
3756459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3757459931ecSChris Mason 			    path->slots[0]), item_size);
3758ad48fd75SYan, Zheng 
3759459931ecSChris Mason 	slot = path->slots[0] + 1;
3760459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3761459931ecSChris Mason 	if (slot != nritems) {
3762459931ecSChris Mason 		/* shift the items */
3763459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3764459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3765459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3766459931ecSChris Mason 	}
3767459931ecSChris Mason 
3768459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3769459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3770459931ecSChris Mason 
37713212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
37723212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3773459931ecSChris Mason 
37743212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
3775459931ecSChris Mason 				 orig_offset + item_size - split_offset);
37763212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3777459931ecSChris Mason 
3778459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3779459931ecSChris Mason 
3780459931ecSChris Mason 	/* write the data for the start of the original item */
3781459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3782459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3783459931ecSChris Mason 			    split_offset);
3784459931ecSChris Mason 
3785459931ecSChris Mason 	/* write the data for the new item */
3786459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3787459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3788459931ecSChris Mason 			    item_size - split_offset);
3789459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3790459931ecSChris Mason 
3791e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3792459931ecSChris Mason 	kfree(buf);
3793ad48fd75SYan, Zheng 	return 0;
3794ad48fd75SYan, Zheng }
3795ad48fd75SYan, Zheng 
3796ad48fd75SYan, Zheng /*
3797ad48fd75SYan, Zheng  * This function splits a single item into two items,
3798ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3799ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3800ad48fd75SYan, Zheng  *
3801ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3802ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3803ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3804ad48fd75SYan, Zheng  *
3805ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3806ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3807ad48fd75SYan, Zheng  *
3808ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3809ad48fd75SYan, Zheng  * leaf the entire time.
3810ad48fd75SYan, Zheng  */
3811ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3812ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3813ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3814310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3815ad48fd75SYan, Zheng 		     unsigned long split_offset)
3816ad48fd75SYan, Zheng {
3817ad48fd75SYan, Zheng 	int ret;
3818ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3819ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3820ad48fd75SYan, Zheng 	if (ret)
3821459931ecSChris Mason 		return ret;
3822ad48fd75SYan, Zheng 
382325263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3824ad48fd75SYan, Zheng 	return ret;
3825ad48fd75SYan, Zheng }
3826ad48fd75SYan, Zheng 
3827ad48fd75SYan, Zheng /*
3828d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
3829d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
3830d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
3831d352ac68SChris Mason  * the front.
3832d352ac68SChris Mason  */
383378ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3834b18c6685SChris Mason {
3835b18c6685SChris Mason 	int slot;
38365f39d397SChris Mason 	struct extent_buffer *leaf;
3837b18c6685SChris Mason 	u32 nritems;
3838b18c6685SChris Mason 	unsigned int data_end;
3839b18c6685SChris Mason 	unsigned int old_data_start;
3840b18c6685SChris Mason 	unsigned int old_size;
3841b18c6685SChris Mason 	unsigned int size_diff;
3842b18c6685SChris Mason 	int i;
3843cfed81a0SChris Mason 	struct btrfs_map_token token;
3844cfed81a0SChris Mason 
38455f39d397SChris Mason 	leaf = path->nodes[0];
3846179e29e4SChris Mason 	slot = path->slots[0];
3847179e29e4SChris Mason 
38483212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
3849179e29e4SChris Mason 	if (old_size == new_size)
3850143bede5SJeff Mahoney 		return;
3851b18c6685SChris Mason 
38525f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
38538f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3854b18c6685SChris Mason 
38553212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
3856179e29e4SChris Mason 
3857b18c6685SChris Mason 	size_diff = old_size - new_size;
3858b18c6685SChris Mason 
3859b18c6685SChris Mason 	BUG_ON(slot < 0);
3860b18c6685SChris Mason 	BUG_ON(slot >= nritems);
3861b18c6685SChris Mason 
3862b18c6685SChris Mason 	/*
3863b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3864b18c6685SChris Mason 	 */
3865b18c6685SChris Mason 	/* first correct the data pointers */
3866c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3867b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
38685f39d397SChris Mason 		u32 ioff;
3869db94535dSChris Mason 
38703212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
38713212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3872b18c6685SChris Mason 	}
3873db94535dSChris Mason 
3874b18c6685SChris Mason 	/* shift the data */
3875179e29e4SChris Mason 	if (from_end) {
38763d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
38773d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3878b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
3879179e29e4SChris Mason 	} else {
3880179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
3881179e29e4SChris Mason 		u64 offset;
3882179e29e4SChris Mason 
3883179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
3884179e29e4SChris Mason 
3885179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3886179e29e4SChris Mason 			unsigned long ptr;
3887179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
3888179e29e4SChris Mason 
3889179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
3890179e29e4SChris Mason 					    struct btrfs_file_extent_item);
3891179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
3892179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
3893179e29e4SChris Mason 
3894179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
3895179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
3896179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
3897179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
3898179e29e4SChris Mason 				      (unsigned long)fi,
38997ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
3900179e29e4SChris Mason 			}
3901179e29e4SChris Mason 		}
3902179e29e4SChris Mason 
39033d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
39043d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3905179e29e4SChris Mason 			      data_end, old_data_start - data_end);
3906179e29e4SChris Mason 
3907179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
3908179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3909179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
3910179e29e4SChris Mason 		if (slot == 0)
3911b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
3912179e29e4SChris Mason 	}
39135f39d397SChris Mason 
39143212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
39155f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3916b18c6685SChris Mason 
3917e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3918a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3919b18c6685SChris Mason 		BUG();
39205f39d397SChris Mason 	}
3921b18c6685SChris Mason }
3922b18c6685SChris Mason 
3923d352ac68SChris Mason /*
39248f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
3925d352ac68SChris Mason  */
3926c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
39276567e837SChris Mason {
39286567e837SChris Mason 	int slot;
39295f39d397SChris Mason 	struct extent_buffer *leaf;
39306567e837SChris Mason 	u32 nritems;
39316567e837SChris Mason 	unsigned int data_end;
39326567e837SChris Mason 	unsigned int old_data;
39336567e837SChris Mason 	unsigned int old_size;
39346567e837SChris Mason 	int i;
3935cfed81a0SChris Mason 	struct btrfs_map_token token;
3936cfed81a0SChris Mason 
39375f39d397SChris Mason 	leaf = path->nodes[0];
39386567e837SChris Mason 
39395f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
39408f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
39416567e837SChris Mason 
3942e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
3943a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39446567e837SChris Mason 		BUG();
39455f39d397SChris Mason 	}
39466567e837SChris Mason 	slot = path->slots[0];
3947dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
39486567e837SChris Mason 
39496567e837SChris Mason 	BUG_ON(slot < 0);
39503326d1b0SChris Mason 	if (slot >= nritems) {
3951a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3952c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
3953d397712bSChris Mason 			   slot, nritems);
3954290342f6SArnd Bergmann 		BUG();
39553326d1b0SChris Mason 	}
39566567e837SChris Mason 
39576567e837SChris Mason 	/*
39586567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
39596567e837SChris Mason 	 */
39606567e837SChris Mason 	/* first correct the data pointers */
3961c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
39626567e837SChris Mason 	for (i = slot; i < nritems; i++) {
39635f39d397SChris Mason 		u32 ioff;
3964db94535dSChris Mason 
39653212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
39663212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
39676567e837SChris Mason 	}
39685f39d397SChris Mason 
39696567e837SChris Mason 	/* shift the data */
39703d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
39713d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
39726567e837SChris Mason 		      data_end, old_data - data_end);
39735f39d397SChris Mason 
39746567e837SChris Mason 	data_end = old_data;
39753212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
39763212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
39775f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
39786567e837SChris Mason 
3979e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3980a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39816567e837SChris Mason 		BUG();
39825f39d397SChris Mason 	}
39836567e837SChris Mason }
39846567e837SChris Mason 
3985da9ffb24SNikolay Borisov /**
3986da9ffb24SNikolay Borisov  * setup_items_for_insert - Helper called before inserting one or more items
3987da9ffb24SNikolay Borisov  * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
3988da9ffb24SNikolay Borisov  * in a function that doesn't call btrfs_search_slot
3989da9ffb24SNikolay Borisov  *
3990da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
3991da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
3992b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
399374123bd7SChris Mason  */
3994f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
3995b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
3996be0e5c09SChris Mason {
39970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
39989c58309dSChris Mason 	int i;
39997518a238SChris Mason 	u32 nritems;
4000be0e5c09SChris Mason 	unsigned int data_end;
4001e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
400244871b1bSChris Mason 	struct extent_buffer *leaf;
400344871b1bSChris Mason 	int slot;
4004cfed81a0SChris Mason 	struct btrfs_map_token token;
4005fc0d82e1SNikolay Borisov 	u32 total_size;
4006fc0d82e1SNikolay Borisov 
4007b7ef5f3aSFilipe Manana 	/*
4008b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
4009b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
4010b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
4011b7ef5f3aSFilipe Manana 	 */
401224cdc847SFilipe Manana 	if (path->slots[0] == 0) {
4013b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4014b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
401524cdc847SFilipe Manana 	}
401624cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
401724cdc847SFilipe Manana 
40185f39d397SChris Mason 	leaf = path->nodes[0];
401944871b1bSChris Mason 	slot = path->slots[0];
402074123bd7SChris Mason 
40215f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
40228f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4023b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4024eb60ceacSChris Mason 
4025e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4026a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
40270b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4028e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4029be0e5c09SChris Mason 		BUG();
4030d4dbff95SChris Mason 	}
40315f39d397SChris Mason 
4032c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4033be0e5c09SChris Mason 	if (slot != nritems) {
4034dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4035be0e5c09SChris Mason 
40365f39d397SChris Mason 		if (old_data < data_end) {
4037a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
40387269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
40397269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
40405f39d397SChris Mason 				   slot, old_data, data_end);
4041290342f6SArnd Bergmann 			BUG();
40425f39d397SChris Mason 		}
4043be0e5c09SChris Mason 		/*
4044be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4045be0e5c09SChris Mason 		 */
4046be0e5c09SChris Mason 		/* first correct the data pointers */
40470783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
40485f39d397SChris Mason 			u32 ioff;
4049db94535dSChris Mason 
40503212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
40513212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
4052b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
40530783fcfcSChris Mason 		}
4054be0e5c09SChris Mason 		/* shift the items */
4055b7ef5f3aSFilipe Manana 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + batch->nr),
40565f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
40570783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4058be0e5c09SChris Mason 
4059be0e5c09SChris Mason 		/* shift the data */
40603d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4061b7ef5f3aSFilipe Manana 				      data_end - batch->total_data_size,
4062b7ef5f3aSFilipe Manana 				      BTRFS_LEAF_DATA_OFFSET + data_end,
4063b7ef5f3aSFilipe Manana 				      old_data - data_end);
4064be0e5c09SChris Mason 		data_end = old_data;
4065be0e5c09SChris Mason 	}
40665f39d397SChris Mason 
406762e2749eSChris Mason 	/* setup the item for the new data */
4068b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
4069b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
40709c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4071b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
40723212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
40733212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
40749c58309dSChris Mason 	}
407544871b1bSChris Mason 
4076b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4077b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4078aa5d6bedSChris Mason 
4079e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4080a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4081be0e5c09SChris Mason 		BUG();
40825f39d397SChris Mason 	}
408344871b1bSChris Mason }
408444871b1bSChris Mason 
408544871b1bSChris Mason /*
4086f0641656SFilipe Manana  * Insert a new item into a leaf.
4087f0641656SFilipe Manana  *
4088f0641656SFilipe Manana  * @root:      The root of the btree.
4089f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
4090f0641656SFilipe Manana  * @key:       The key of the new item.
4091f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
4092f0641656SFilipe Manana  */
4093f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
4094f0641656SFilipe Manana 				 struct btrfs_path *path,
4095f0641656SFilipe Manana 				 const struct btrfs_key *key,
4096f0641656SFilipe Manana 				 u32 data_size)
4097f0641656SFilipe Manana {
4098f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4099f0641656SFilipe Manana 
4100f0641656SFilipe Manana 	batch.keys = key;
4101f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4102f0641656SFilipe Manana 	batch.total_data_size = data_size;
4103f0641656SFilipe Manana 	batch.nr = 1;
4104f0641656SFilipe Manana 
4105f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
4106f0641656SFilipe Manana }
4107f0641656SFilipe Manana 
4108f0641656SFilipe Manana /*
410944871b1bSChris Mason  * Given a key and some data, insert items into the tree.
411044871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
411144871b1bSChris Mason  */
411244871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
411344871b1bSChris Mason 			    struct btrfs_root *root,
411444871b1bSChris Mason 			    struct btrfs_path *path,
4115b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
411644871b1bSChris Mason {
411744871b1bSChris Mason 	int ret = 0;
411844871b1bSChris Mason 	int slot;
4119b7ef5f3aSFilipe Manana 	u32 total_size;
412044871b1bSChris Mason 
4121b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4122b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
412344871b1bSChris Mason 	if (ret == 0)
412444871b1bSChris Mason 		return -EEXIST;
412544871b1bSChris Mason 	if (ret < 0)
4126143bede5SJeff Mahoney 		return ret;
412744871b1bSChris Mason 
412844871b1bSChris Mason 	slot = path->slots[0];
412944871b1bSChris Mason 	BUG_ON(slot < 0);
413044871b1bSChris Mason 
4131b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4132143bede5SJeff Mahoney 	return 0;
413362e2749eSChris Mason }
413462e2749eSChris Mason 
413562e2749eSChris Mason /*
413662e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
413762e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
413862e2749eSChris Mason  */
4139310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4140310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4141310712b2SOmar Sandoval 		      u32 data_size)
414262e2749eSChris Mason {
414362e2749eSChris Mason 	int ret = 0;
41442c90e5d6SChris Mason 	struct btrfs_path *path;
41455f39d397SChris Mason 	struct extent_buffer *leaf;
41465f39d397SChris Mason 	unsigned long ptr;
414762e2749eSChris Mason 
41482c90e5d6SChris Mason 	path = btrfs_alloc_path();
4149db5b493aSTsutomu Itoh 	if (!path)
4150db5b493aSTsutomu Itoh 		return -ENOMEM;
41512c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
415262e2749eSChris Mason 	if (!ret) {
41535f39d397SChris Mason 		leaf = path->nodes[0];
41545f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
41555f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
41565f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
415762e2749eSChris Mason 	}
41582c90e5d6SChris Mason 	btrfs_free_path(path);
4159aa5d6bedSChris Mason 	return ret;
4160be0e5c09SChris Mason }
4161be0e5c09SChris Mason 
416274123bd7SChris Mason /*
4163f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4164f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4165f0641656SFilipe Manana  * contiguous with the original item.
4166f0641656SFilipe Manana  *
4167f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4168f0641656SFilipe Manana  * the entire time.
4169f0641656SFilipe Manana  */
4170f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4171f0641656SFilipe Manana 			 struct btrfs_root *root,
4172f0641656SFilipe Manana 			 struct btrfs_path *path,
4173f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4174f0641656SFilipe Manana {
4175f0641656SFilipe Manana 	struct extent_buffer *leaf;
4176f0641656SFilipe Manana 	int ret;
4177f0641656SFilipe Manana 	u32 item_size;
4178f0641656SFilipe Manana 
4179f0641656SFilipe Manana 	leaf = path->nodes[0];
41803212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4181f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4182f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4183f0641656SFilipe Manana 	if (ret)
4184f0641656SFilipe Manana 		return ret;
4185f0641656SFilipe Manana 
4186f0641656SFilipe Manana 	path->slots[0]++;
4187f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4188f0641656SFilipe Manana 	leaf = path->nodes[0];
4189f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4190f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4191f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4192f0641656SFilipe Manana 			     item_size);
4193f0641656SFilipe Manana 	return 0;
4194f0641656SFilipe Manana }
4195f0641656SFilipe Manana 
4196f0641656SFilipe Manana /*
41975de08d7dSChris Mason  * delete the pointer from a given node.
419874123bd7SChris Mason  *
4199d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4200d352ac68SChris Mason  * empty a node.
420174123bd7SChris Mason  */
4202afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4203afe5fea7STsutomu Itoh 		    int level, int slot)
4204be0e5c09SChris Mason {
42055f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
42067518a238SChris Mason 	u32 nritems;
4207f3ea38daSJan Schmidt 	int ret;
4208be0e5c09SChris Mason 
42095f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4210be0e5c09SChris Mason 	if (slot != nritems - 1) {
4211bf1d3425SDavid Sterba 		if (level) {
4212f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4213f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4214bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4215bf1d3425SDavid Sterba 		}
42165f39d397SChris Mason 		memmove_extent_buffer(parent,
42175f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
42185f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4219d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4220d6025579SChris Mason 			      (nritems - slot - 1));
422157ba86c0SChris Mason 	} else if (level) {
4222f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
422333cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REMOVE);
422457ba86c0SChris Mason 		BUG_ON(ret < 0);
4225be0e5c09SChris Mason 	}
4226f3ea38daSJan Schmidt 
42277518a238SChris Mason 	nritems--;
42285f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
42297518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
42305f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4231eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
42325f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4233bb803951SChris Mason 	} else if (slot == 0) {
42345f39d397SChris Mason 		struct btrfs_disk_key disk_key;
42355f39d397SChris Mason 
42365f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4237b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4238be0e5c09SChris Mason 	}
4239d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4240be0e5c09SChris Mason }
4241be0e5c09SChris Mason 
424274123bd7SChris Mason /*
4243323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
42445d4f98a2SYan Zheng  * path->nodes[1].
4245323ac95bSChris Mason  *
4246323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4247323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4248323ac95bSChris Mason  *
4249323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4250323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4251323ac95bSChris Mason  */
4252143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4253323ac95bSChris Mason 				    struct btrfs_root *root,
42545d4f98a2SYan Zheng 				    struct btrfs_path *path,
42555d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4256323ac95bSChris Mason {
42575d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4258afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4259323ac95bSChris Mason 
42604d081c41SChris Mason 	/*
42614d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
42624d081c41SChris Mason 	 * aren't holding any locks when we call it
42634d081c41SChris Mason 	 */
42644d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
42654d081c41SChris Mason 
4266f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4267f0486c68SYan, Zheng 
426867439dadSDavid Sterba 	atomic_inc(&leaf->refs);
42697a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
42703083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4271323ac95bSChris Mason }
4272323ac95bSChris Mason /*
427374123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
427474123bd7SChris Mason  * the leaf, remove it from the tree
427574123bd7SChris Mason  */
427685e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
427785e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4278be0e5c09SChris Mason {
42790b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
42805f39d397SChris Mason 	struct extent_buffer *leaf;
4281aa5d6bedSChris Mason 	int ret = 0;
4282aa5d6bedSChris Mason 	int wret;
42837518a238SChris Mason 	u32 nritems;
4284be0e5c09SChris Mason 
42855f39d397SChris Mason 	leaf = path->nodes[0];
42865f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4287be0e5c09SChris Mason 
428885e21bacSChris Mason 	if (slot + nr != nritems) {
42890cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
42900cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4291c82f823cSDavid Sterba 		struct btrfs_map_token token;
42920cae23b6SFilipe Manana 		u32 dsize = 0;
42930cae23b6SFilipe Manana 		int i;
42940cae23b6SFilipe Manana 
42950cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
42960cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
42975f39d397SChris Mason 
42983d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4299d6025579SChris Mason 			      data_end + dsize,
43003d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
430185e21bacSChris Mason 			      last_off - data_end);
43025f39d397SChris Mason 
4303c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
430485e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
43055f39d397SChris Mason 			u32 ioff;
4306db94535dSChris Mason 
43073212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
43083212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
43090783fcfcSChris Mason 		}
4310db94535dSChris Mason 
43115f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
431285e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
43130783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
431485e21bacSChris Mason 			      (nritems - slot - nr));
4315be0e5c09SChris Mason 	}
431685e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
431785e21bacSChris Mason 	nritems -= nr;
43185f39d397SChris Mason 
431974123bd7SChris Mason 	/* delete the leaf if we've emptied it */
43207518a238SChris Mason 	if (nritems == 0) {
43215f39d397SChris Mason 		if (leaf == root->node) {
43225f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
43239a8dd150SChris Mason 		} else {
43246a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4325143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
43269a8dd150SChris Mason 		}
4327be0e5c09SChris Mason 	} else {
43287518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4329aa5d6bedSChris Mason 		if (slot == 0) {
43305f39d397SChris Mason 			struct btrfs_disk_key disk_key;
43315f39d397SChris Mason 
43325f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4333b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4334aa5d6bedSChris Mason 		}
4335aa5d6bedSChris Mason 
43367c4063d1SFilipe Manana 		/*
43377c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
43387c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
43397c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
43407c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
43417c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
43427c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
43437c4063d1SFilipe Manana 		 */
43440b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
43457c4063d1SFilipe Manana 			u32 min_push_space;
43467c4063d1SFilipe Manana 
4347be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4348be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4349be0e5c09SChris Mason 			 * for possible call to del_ptr below
4350be0e5c09SChris Mason 			 */
43514920c9acSChris Mason 			slot = path->slots[1];
435267439dadSDavid Sterba 			atomic_inc(&leaf->refs);
43537c4063d1SFilipe Manana 			/*
43547c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
43557c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
43567c4063d1SFilipe Manana 			 */
43577c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
43587c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
43597c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
43607c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
436154aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4362aa5d6bedSChris Mason 				ret = wret;
43635f39d397SChris Mason 
43645f39d397SChris Mason 			if (path->nodes[0] == leaf &&
43655f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
43667c4063d1SFilipe Manana 				/*
43677c4063d1SFilipe Manana 				 * If we were not able to push all items from our
43687c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
43697c4063d1SFilipe Manana 				 * either push all the remaining items to the
43707c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
43717c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
43727c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
43737c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
43747c4063d1SFilipe Manana 				 * or nearly full.
43757c4063d1SFilipe Manana 				 */
43767c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
43777c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
43787c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
43797c4063d1SFilipe Manana 						       min_push_space, 1, 0);
438054aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4381aa5d6bedSChris Mason 					ret = wret;
4382aa5d6bedSChris Mason 			}
43835f39d397SChris Mason 
43845f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4385323ac95bSChris Mason 				path->slots[1] = slot;
4386143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
43875f39d397SChris Mason 				free_extent_buffer(leaf);
4388143bede5SJeff Mahoney 				ret = 0;
43895de08d7dSChris Mason 			} else {
4390925baeddSChris Mason 				/* if we're still in the path, make sure
4391925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4392925baeddSChris Mason 				 * push_leaf functions must have already
4393925baeddSChris Mason 				 * dirtied this buffer
4394925baeddSChris Mason 				 */
4395925baeddSChris Mason 				if (path->nodes[0] == leaf)
43965f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
43975f39d397SChris Mason 				free_extent_buffer(leaf);
4398be0e5c09SChris Mason 			}
4399d5719762SChris Mason 		} else {
44005f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4401be0e5c09SChris Mason 		}
44029a8dd150SChris Mason 	}
4403aa5d6bedSChris Mason 	return ret;
44049a8dd150SChris Mason }
44059a8dd150SChris Mason 
440697571fd0SChris Mason /*
4407925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
44087bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
44097bb86316SChris Mason  * returns < 0 on io errors.
4410d352ac68SChris Mason  *
4411d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4412d352ac68SChris Mason  * time you call it.
44137bb86316SChris Mason  */
441416e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
44157bb86316SChris Mason {
4416925baeddSChris Mason 	struct btrfs_key key;
4417925baeddSChris Mason 	struct btrfs_disk_key found_key;
4418925baeddSChris Mason 	int ret;
44197bb86316SChris Mason 
4420925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4421925baeddSChris Mason 
4422e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
4423925baeddSChris Mason 		key.offset--;
4424e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
4425925baeddSChris Mason 		key.type--;
4426e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4427e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
4428925baeddSChris Mason 		key.objectid--;
4429e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
4430e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4431e8b0d724SFilipe David Borba Manana 	} else {
44327bb86316SChris Mason 		return 1;
4433e8b0d724SFilipe David Borba Manana 	}
44347bb86316SChris Mason 
4435b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4436925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4437925baeddSChris Mason 	if (ret < 0)
4438925baeddSChris Mason 		return ret;
4439925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4440925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4441337c6f68SFilipe Manana 	/*
4442337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
4443337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
4444337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
4445337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
4446337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
4447337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
4448337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
4449337c6f68SFilipe Manana 	 * the previous key we computed above.
4450337c6f68SFilipe Manana 	 */
4451337c6f68SFilipe Manana 	if (ret <= 0)
44527bb86316SChris Mason 		return 0;
4453925baeddSChris Mason 	return 1;
44547bb86316SChris Mason }
44557bb86316SChris Mason 
44563f157a2fSChris Mason /*
44573f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4458de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4459de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
44603f157a2fSChris Mason  *
44613f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
44623f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
44633f157a2fSChris Mason  * key and get a writable path.
44643f157a2fSChris Mason  *
44653f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
44663f157a2fSChris Mason  * of the tree.
44673f157a2fSChris Mason  *
4468d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4469d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4470d352ac68SChris Mason  * skipped over (without reading them).
4471d352ac68SChris Mason  *
44723f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
44733f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
44743f157a2fSChris Mason  */
44753f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4476de78b51aSEric Sandeen 			 struct btrfs_path *path,
44773f157a2fSChris Mason 			 u64 min_trans)
44783f157a2fSChris Mason {
44793f157a2fSChris Mason 	struct extent_buffer *cur;
44803f157a2fSChris Mason 	struct btrfs_key found_key;
44813f157a2fSChris Mason 	int slot;
44829652480bSYan 	int sret;
44833f157a2fSChris Mason 	u32 nritems;
44843f157a2fSChris Mason 	int level;
44853f157a2fSChris Mason 	int ret = 1;
4486f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
44873f157a2fSChris Mason 
4488c922b016SStefan Roesch 	ASSERT(!path->nowait);
4489f98de9b9SFilipe Manana 	path->keep_locks = 1;
44903f157a2fSChris Mason again:
4491bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
44923f157a2fSChris Mason 	level = btrfs_header_level(cur);
4493e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
44943f157a2fSChris Mason 	path->nodes[level] = cur;
4495bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
44963f157a2fSChris Mason 
44973f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
44983f157a2fSChris Mason 		ret = 1;
44993f157a2fSChris Mason 		goto out;
45003f157a2fSChris Mason 	}
45013f157a2fSChris Mason 	while (1) {
45023f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
45033f157a2fSChris Mason 		level = btrfs_header_level(cur);
4504e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
4505cbca7d59SFilipe Manana 		if (sret < 0) {
4506cbca7d59SFilipe Manana 			ret = sret;
4507cbca7d59SFilipe Manana 			goto out;
4508cbca7d59SFilipe Manana 		}
45093f157a2fSChris Mason 
4510323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4511323ac95bSChris Mason 		if (level == path->lowest_level) {
4512e02119d5SChris Mason 			if (slot >= nritems)
4513e02119d5SChris Mason 				goto find_next_key;
45143f157a2fSChris Mason 			ret = 0;
45153f157a2fSChris Mason 			path->slots[level] = slot;
45163f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
45173f157a2fSChris Mason 			goto out;
45183f157a2fSChris Mason 		}
45199652480bSYan 		if (sret && slot > 0)
45209652480bSYan 			slot--;
45213f157a2fSChris Mason 		/*
4522de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4523260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
45243f157a2fSChris Mason 		 */
45253f157a2fSChris Mason 		while (slot < nritems) {
45263f157a2fSChris Mason 			u64 gen;
4527e02119d5SChris Mason 
45283f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
45293f157a2fSChris Mason 			if (gen < min_trans) {
45303f157a2fSChris Mason 				slot++;
45313f157a2fSChris Mason 				continue;
45323f157a2fSChris Mason 			}
45333f157a2fSChris Mason 			break;
45343f157a2fSChris Mason 		}
4535e02119d5SChris Mason find_next_key:
45363f157a2fSChris Mason 		/*
45373f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
45383f157a2fSChris Mason 		 * and find another one
45393f157a2fSChris Mason 		 */
45403f157a2fSChris Mason 		if (slot >= nritems) {
4541e02119d5SChris Mason 			path->slots[level] = slot;
4542e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4543de78b51aSEric Sandeen 						  min_trans);
4544e02119d5SChris Mason 			if (sret == 0) {
4545b3b4aa74SDavid Sterba 				btrfs_release_path(path);
45463f157a2fSChris Mason 				goto again;
45473f157a2fSChris Mason 			} else {
45483f157a2fSChris Mason 				goto out;
45493f157a2fSChris Mason 			}
45503f157a2fSChris Mason 		}
45513f157a2fSChris Mason 		/* save our key for returning back */
45523f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
45533f157a2fSChris Mason 		path->slots[level] = slot;
45543f157a2fSChris Mason 		if (level == path->lowest_level) {
45553f157a2fSChris Mason 			ret = 0;
45563f157a2fSChris Mason 			goto out;
45573f157a2fSChris Mason 		}
45584b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4559fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4560fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4561fb770ae4SLiu Bo 			goto out;
4562fb770ae4SLiu Bo 		}
45633f157a2fSChris Mason 
4564bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4565b4ce94deSChris Mason 
4566bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
45673f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4568f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
45693f157a2fSChris Mason 	}
45703f157a2fSChris Mason out:
4571f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4572f98de9b9SFilipe Manana 	if (ret == 0) {
4573f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4574f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4575f98de9b9SFilipe Manana 	}
45763f157a2fSChris Mason 	return ret;
45773f157a2fSChris Mason }
45783f157a2fSChris Mason 
45793f157a2fSChris Mason /*
45803f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
45813f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4582de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
45833f157a2fSChris Mason  *
45843f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
45853f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
45863f157a2fSChris Mason  *
45873f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
45883f157a2fSChris Mason  * calling this function.
45893f157a2fSChris Mason  */
4590e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4591de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4592e7a84565SChris Mason {
4593e7a84565SChris Mason 	int slot;
4594e7a84565SChris Mason 	struct extent_buffer *c;
4595e7a84565SChris Mason 
45966a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4597e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4598e7a84565SChris Mason 		if (!path->nodes[level])
4599e7a84565SChris Mason 			return 1;
4600e7a84565SChris Mason 
4601e7a84565SChris Mason 		slot = path->slots[level] + 1;
4602e7a84565SChris Mason 		c = path->nodes[level];
46033f157a2fSChris Mason next:
4604e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
460533c66f43SYan Zheng 			int ret;
460633c66f43SYan Zheng 			int orig_lowest;
460733c66f43SYan Zheng 			struct btrfs_key cur_key;
460833c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
460933c66f43SYan Zheng 			    !path->nodes[level + 1])
4610e7a84565SChris Mason 				return 1;
461133c66f43SYan Zheng 
46126a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
461333c66f43SYan Zheng 				level++;
4614e7a84565SChris Mason 				continue;
4615e7a84565SChris Mason 			}
461633c66f43SYan Zheng 
461733c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
461833c66f43SYan Zheng 			if (level == 0)
461933c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
462033c66f43SYan Zheng 			else
462133c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
462233c66f43SYan Zheng 
462333c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4624b3b4aa74SDavid Sterba 			btrfs_release_path(path);
462533c66f43SYan Zheng 			path->lowest_level = level;
462633c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
462733c66f43SYan Zheng 						0, 0);
462833c66f43SYan Zheng 			path->lowest_level = orig_lowest;
462933c66f43SYan Zheng 			if (ret < 0)
463033c66f43SYan Zheng 				return ret;
463133c66f43SYan Zheng 
463233c66f43SYan Zheng 			c = path->nodes[level];
463333c66f43SYan Zheng 			slot = path->slots[level];
463433c66f43SYan Zheng 			if (ret == 0)
463533c66f43SYan Zheng 				slot++;
463633c66f43SYan Zheng 			goto next;
463733c66f43SYan Zheng 		}
463833c66f43SYan Zheng 
4639e7a84565SChris Mason 		if (level == 0)
4640e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
46413f157a2fSChris Mason 		else {
46423f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
46433f157a2fSChris Mason 
46443f157a2fSChris Mason 			if (gen < min_trans) {
46453f157a2fSChris Mason 				slot++;
46463f157a2fSChris Mason 				goto next;
46473f157a2fSChris Mason 			}
4648e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
46493f157a2fSChris Mason 		}
4650e7a84565SChris Mason 		return 0;
4651e7a84565SChris Mason 	}
4652e7a84565SChris Mason 	return 1;
4653e7a84565SChris Mason }
4654e7a84565SChris Mason 
46553d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
46563d7806ecSJan Schmidt 			u64 time_seq)
46573d7806ecSJan Schmidt {
4658d97e63b6SChris Mason 	int slot;
46598e73f275SChris Mason 	int level;
46605f39d397SChris Mason 	struct extent_buffer *c;
46618e73f275SChris Mason 	struct extent_buffer *next;
4662d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4663925baeddSChris Mason 	struct btrfs_key key;
4664d96b3424SFilipe Manana 	bool need_commit_sem = false;
4665925baeddSChris Mason 	u32 nritems;
4666925baeddSChris Mason 	int ret;
46670e46318dSJosef Bacik 	int i;
4668925baeddSChris Mason 
4669bdcdd86cSFilipe Manana 	/*
4670bdcdd86cSFilipe Manana 	 * The nowait semantics are used only for write paths, where we don't
4671bdcdd86cSFilipe Manana 	 * use the tree mod log and sequence numbers.
4672bdcdd86cSFilipe Manana 	 */
4673bdcdd86cSFilipe Manana 	if (time_seq)
4674c922b016SStefan Roesch 		ASSERT(!path->nowait);
4675c922b016SStefan Roesch 
4676925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4677d397712bSChris Mason 	if (nritems == 0)
4678925baeddSChris Mason 		return 1;
4679925baeddSChris Mason 
46808e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
46818e73f275SChris Mason again:
46828e73f275SChris Mason 	level = 1;
46838e73f275SChris Mason 	next = NULL;
4684b3b4aa74SDavid Sterba 	btrfs_release_path(path);
46858e73f275SChris Mason 
4686a2135011SChris Mason 	path->keep_locks = 1;
46878e73f275SChris Mason 
4688d96b3424SFilipe Manana 	if (time_seq) {
46893d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4690d96b3424SFilipe Manana 	} else {
4691d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4692d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4693d96b3424SFilipe Manana 			need_commit_sem = true;
4694bdcdd86cSFilipe Manana 			if (path->nowait) {
4695bdcdd86cSFilipe Manana 				if (!down_read_trylock(&fs_info->commit_root_sem)) {
4696bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4697bdcdd86cSFilipe Manana 					goto done;
4698bdcdd86cSFilipe Manana 				}
4699bdcdd86cSFilipe Manana 			} else {
4700d96b3424SFilipe Manana 				down_read(&fs_info->commit_root_sem);
4701d96b3424SFilipe Manana 			}
4702bdcdd86cSFilipe Manana 		}
4703925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4704d96b3424SFilipe Manana 	}
4705925baeddSChris Mason 	path->keep_locks = 0;
4706925baeddSChris Mason 
4707925baeddSChris Mason 	if (ret < 0)
4708d96b3424SFilipe Manana 		goto done;
4709925baeddSChris Mason 
4710a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4711168fd7d2SChris Mason 	/*
4712168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4713168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4714168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4715168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4716168fd7d2SChris Mason 	 */
4717a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4718e457afecSYan Zheng 		if (ret == 0)
4719168fd7d2SChris Mason 			path->slots[0]++;
47208e73f275SChris Mason 		ret = 0;
4721925baeddSChris Mason 		goto done;
4722925baeddSChris Mason 	}
47230b43e04fSLiu Bo 	/*
47240b43e04fSLiu Bo 	 * So the above check misses one case:
47250b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
47260b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
47270b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
47280b43e04fSLiu Bo 	 *
47290b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
47300b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
47310b43e04fSLiu Bo 	 *
47320b43e04fSLiu Bo 	 * And a bit more explanation about this check,
47330b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
47340b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
47350b43e04fSLiu Bo 	 * bigger one.
47360b43e04fSLiu Bo 	 */
47370b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
47380b43e04fSLiu Bo 		ret = 0;
47390b43e04fSLiu Bo 		goto done;
47400b43e04fSLiu Bo 	}
4741d97e63b6SChris Mason 
4742234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
47438e73f275SChris Mason 		if (!path->nodes[level]) {
47448e73f275SChris Mason 			ret = 1;
47458e73f275SChris Mason 			goto done;
47468e73f275SChris Mason 		}
47475f39d397SChris Mason 
4748d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4749d97e63b6SChris Mason 		c = path->nodes[level];
47505f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4751d97e63b6SChris Mason 			level++;
47528e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
47538e73f275SChris Mason 				ret = 1;
47548e73f275SChris Mason 				goto done;
47558e73f275SChris Mason 			}
4756d97e63b6SChris Mason 			continue;
4757d97e63b6SChris Mason 		}
47585f39d397SChris Mason 
47590e46318dSJosef Bacik 
47600e46318dSJosef Bacik 		/*
47610e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
47620e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
47630e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
47640e46318dSJosef Bacik 		 */
47650e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
47660e46318dSJosef Bacik 			if (path->locks[level]) {
47670e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
47680e46318dSJosef Bacik 				path->locks[i] = 0;
47690e46318dSJosef Bacik 			}
47700e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
47710e46318dSJosef Bacik 			path->nodes[i] = NULL;
4772925baeddSChris Mason 		}
47735f39d397SChris Mason 
47748e73f275SChris Mason 		next = c;
4775d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4776cda79c54SDavid Sterba 					    slot, &key);
4777bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
47788e73f275SChris Mason 			goto again;
47795f39d397SChris Mason 
478076a05b35SChris Mason 		if (ret < 0) {
4781b3b4aa74SDavid Sterba 			btrfs_release_path(path);
478276a05b35SChris Mason 			goto done;
478376a05b35SChris Mason 		}
478476a05b35SChris Mason 
47855cd57b2cSChris Mason 		if (!path->skip_locking) {
4786bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4787bdcdd86cSFilipe Manana 			if (!ret && path->nowait) {
4788bdcdd86cSFilipe Manana 				ret = -EAGAIN;
4789bdcdd86cSFilipe Manana 				goto done;
4790bdcdd86cSFilipe Manana 			}
4791d42244a0SJan Schmidt 			if (!ret && time_seq) {
4792d42244a0SJan Schmidt 				/*
4793d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4794d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4795d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4796d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4797d42244a0SJan Schmidt 				 * on our lock and cycle.
4798d42244a0SJan Schmidt 				 */
4799cf538830SJan Schmidt 				free_extent_buffer(next);
4800d42244a0SJan Schmidt 				btrfs_release_path(path);
4801d42244a0SJan Schmidt 				cond_resched();
4802d42244a0SJan Schmidt 				goto again;
4803d42244a0SJan Schmidt 			}
48040e46318dSJosef Bacik 			if (!ret)
48050e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4806bd681513SChris Mason 		}
4807d97e63b6SChris Mason 		break;
4808d97e63b6SChris Mason 	}
4809d97e63b6SChris Mason 	path->slots[level] = slot;
4810d97e63b6SChris Mason 	while (1) {
4811d97e63b6SChris Mason 		level--;
4812d97e63b6SChris Mason 		path->nodes[level] = next;
4813d97e63b6SChris Mason 		path->slots[level] = 0;
4814a74a4b97SChris Mason 		if (!path->skip_locking)
4815ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4816d97e63b6SChris Mason 		if (!level)
4817d97e63b6SChris Mason 			break;
4818b4ce94deSChris Mason 
4819d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4820cda79c54SDavid Sterba 					    0, &key);
4821bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
48228e73f275SChris Mason 			goto again;
48238e73f275SChris Mason 
482476a05b35SChris Mason 		if (ret < 0) {
4825b3b4aa74SDavid Sterba 			btrfs_release_path(path);
482676a05b35SChris Mason 			goto done;
482776a05b35SChris Mason 		}
482876a05b35SChris Mason 
4829bdcdd86cSFilipe Manana 		if (!path->skip_locking) {
4830bdcdd86cSFilipe Manana 			if (path->nowait) {
4831bdcdd86cSFilipe Manana 				if (!btrfs_try_tree_read_lock(next)) {
4832bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4833bdcdd86cSFilipe Manana 					goto done;
4834bdcdd86cSFilipe Manana 				}
4835bdcdd86cSFilipe Manana 			} else {
48360e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4837d97e63b6SChris Mason 			}
4838bdcdd86cSFilipe Manana 		}
4839bdcdd86cSFilipe Manana 	}
48408e73f275SChris Mason 	ret = 0;
4841925baeddSChris Mason done:
4842f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
4843d96b3424SFilipe Manana 	if (need_commit_sem) {
4844d96b3424SFilipe Manana 		int ret2;
4845d96b3424SFilipe Manana 
4846d96b3424SFilipe Manana 		path->need_commit_sem = 1;
4847d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
4848d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
4849d96b3424SFilipe Manana 		if (ret2)
4850d96b3424SFilipe Manana 			ret = ret2;
4851d96b3424SFilipe Manana 	}
48528e73f275SChris Mason 
48538e73f275SChris Mason 	return ret;
4854d97e63b6SChris Mason }
48550b86a832SChris Mason 
4856890d2b1aSJosef Bacik int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
4857890d2b1aSJosef Bacik {
4858890d2b1aSJosef Bacik 	path->slots[0]++;
4859890d2b1aSJosef Bacik 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
4860890d2b1aSJosef Bacik 		return btrfs_next_old_leaf(root, path, time_seq);
4861890d2b1aSJosef Bacik 	return 0;
4862890d2b1aSJosef Bacik }
4863890d2b1aSJosef Bacik 
48643f157a2fSChris Mason /*
48653f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
48663f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
48673f157a2fSChris Mason  *
48683f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
48693f157a2fSChris Mason  */
48700b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
48710b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
48720b86a832SChris Mason 			int type)
48730b86a832SChris Mason {
48740b86a832SChris Mason 	struct btrfs_key found_key;
48750b86a832SChris Mason 	struct extent_buffer *leaf;
4876e02119d5SChris Mason 	u32 nritems;
48770b86a832SChris Mason 	int ret;
48780b86a832SChris Mason 
48790b86a832SChris Mason 	while (1) {
48800b86a832SChris Mason 		if (path->slots[0] == 0) {
48810b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
48820b86a832SChris Mason 			if (ret != 0)
48830b86a832SChris Mason 				return ret;
48840b86a832SChris Mason 		} else {
48850b86a832SChris Mason 			path->slots[0]--;
48860b86a832SChris Mason 		}
48870b86a832SChris Mason 		leaf = path->nodes[0];
4888e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
4889e02119d5SChris Mason 		if (nritems == 0)
4890e02119d5SChris Mason 			return 1;
4891e02119d5SChris Mason 		if (path->slots[0] == nritems)
4892e02119d5SChris Mason 			path->slots[0]--;
4893e02119d5SChris Mason 
48940b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4895e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
4896e02119d5SChris Mason 			break;
48970a4eefbbSYan Zheng 		if (found_key.type == type)
48980a4eefbbSYan Zheng 			return 0;
4899e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
4900e02119d5SChris Mason 		    found_key.type < type)
4901e02119d5SChris Mason 			break;
49020b86a832SChris Mason 	}
49030b86a832SChris Mason 	return 1;
49040b86a832SChris Mason }
4905ade2e0b3SWang Shilong 
4906ade2e0b3SWang Shilong /*
4907ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
4908ade2e0b3SWang Shilong  * min objecitd.
4909ade2e0b3SWang Shilong  *
4910ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4911ade2e0b3SWang Shilong  */
4912ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
4913ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
4914ade2e0b3SWang Shilong {
4915ade2e0b3SWang Shilong 	struct btrfs_key found_key;
4916ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
4917ade2e0b3SWang Shilong 	u32 nritems;
4918ade2e0b3SWang Shilong 	int ret;
4919ade2e0b3SWang Shilong 
4920ade2e0b3SWang Shilong 	while (1) {
4921ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
4922ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
4923ade2e0b3SWang Shilong 			if (ret != 0)
4924ade2e0b3SWang Shilong 				return ret;
4925ade2e0b3SWang Shilong 		} else {
4926ade2e0b3SWang Shilong 			path->slots[0]--;
4927ade2e0b3SWang Shilong 		}
4928ade2e0b3SWang Shilong 		leaf = path->nodes[0];
4929ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
4930ade2e0b3SWang Shilong 		if (nritems == 0)
4931ade2e0b3SWang Shilong 			return 1;
4932ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
4933ade2e0b3SWang Shilong 			path->slots[0]--;
4934ade2e0b3SWang Shilong 
4935ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4936ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
4937ade2e0b3SWang Shilong 			break;
4938ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4939ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
4940ade2e0b3SWang Shilong 			return 0;
4941ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
4942ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
4943ade2e0b3SWang Shilong 			break;
4944ade2e0b3SWang Shilong 	}
4945ade2e0b3SWang Shilong 	return 1;
4946ade2e0b3SWang Shilong }
4947226463d7SJosef Bacik 
4948226463d7SJosef Bacik int __init btrfs_ctree_init(void)
4949226463d7SJosef Bacik {
4950226463d7SJosef Bacik 	btrfs_path_cachep = kmem_cache_create("btrfs_path",
4951226463d7SJosef Bacik 			sizeof(struct btrfs_path), 0,
4952226463d7SJosef Bacik 			SLAB_MEM_SPREAD, NULL);
4953226463d7SJosef Bacik 	if (!btrfs_path_cachep)
4954226463d7SJosef Bacik 		return -ENOMEM;
4955226463d7SJosef Bacik 	return 0;
4956226463d7SJosef Bacik }
4957226463d7SJosef Bacik 
4958226463d7SJosef Bacik void __cold btrfs_ctree_exit(void)
4959226463d7SJosef Bacik {
4960226463d7SJosef Bacik 	kmem_cache_destroy(btrfs_path_cachep);
4961226463d7SJosef Bacik }
4962