xref: /openbmc/linux/fs/btrfs/ctree.c (revision 789d6a3a876e32c23fc9633d5b372d02a5188f0e)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
3d352ac68SChris Mason  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
6a6b6e75eSChris Mason #include <linux/sched.h>
75a0e3ad6STejun Heo #include <linux/slab.h>
8bd989ba3SJan Schmidt #include <linux/rbtree.h>
9adf02123SDavid Sterba #include <linux/mm.h>
10e41d12f5SChristoph Hellwig #include <linux/error-injection.h>
119b569ea0SJosef Bacik #include "messages.h"
12eb60ceacSChris Mason #include "ctree.h"
13eb60ceacSChris Mason #include "disk-io.h"
147f5c1516SChris Mason #include "transaction.h"
155f39d397SChris Mason #include "print-tree.h"
16925baeddSChris Mason #include "locking.h"
17de37aa51SNikolay Borisov #include "volumes.h"
18f616f5cdSQu Wenruo #include "qgroup.h"
19f3a84ccdSFilipe Manana #include "tree-mod-log.h"
2088c602abSQu Wenruo #include "tree-checker.h"
21ec8eb376SJosef Bacik #include "fs.h"
22ad1ac501SJosef Bacik #include "accessors.h"
23a0231804SJosef Bacik #include "extent-tree.h"
2467707479SJosef Bacik #include "relocation.h"
259a8dd150SChris Mason 
26226463d7SJosef Bacik static struct kmem_cache *btrfs_path_cachep;
27226463d7SJosef Bacik 
28e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
29e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
30310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
31310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
32310712b2SOmar Sandoval 		      int data_size, int extend);
335f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
342ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
35971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
365f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
375f39d397SChris Mason 			      struct extent_buffer *dst_buf,
385f39d397SChris Mason 			      struct extent_buffer *src_buf);
39afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
40afe5fea7STsutomu Itoh 		    int level, int slot);
41d97e63b6SChris Mason 
42af024ed2SJohannes Thumshirn static const struct btrfs_csums {
43af024ed2SJohannes Thumshirn 	u16		size;
4459a0fcdbSDavid Sterba 	const char	name[10];
4559a0fcdbSDavid Sterba 	const char	driver[12];
46af024ed2SJohannes Thumshirn } btrfs_csums[] = {
47af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
483951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
493831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
50352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
51352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
52af024ed2SJohannes Thumshirn };
53af024ed2SJohannes Thumshirn 
54af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
55af024ed2SJohannes Thumshirn {
56af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
57af024ed2SJohannes Thumshirn 	/*
58af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
59af024ed2SJohannes Thumshirn 	 */
60af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
61af024ed2SJohannes Thumshirn }
62af024ed2SJohannes Thumshirn 
63af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
64af024ed2SJohannes Thumshirn {
65af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
66af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
67af024ed2SJohannes Thumshirn }
68af024ed2SJohannes Thumshirn 
69b4e967beSDavid Sterba /*
70b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
71b4e967beSDavid Sterba  * name
72b4e967beSDavid Sterba  */
73b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
74b4e967beSDavid Sterba {
75b4e967beSDavid Sterba 	/* csum type is validated at mount time */
7659a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
7759a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
78b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
79b4e967beSDavid Sterba }
80b4e967beSDavid Sterba 
81604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
82f7cea56cSDavid Sterba {
83f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
84f7cea56cSDavid Sterba }
85f7cea56cSDavid Sterba 
862c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
872c90e5d6SChris Mason {
88e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
892c90e5d6SChris Mason }
902c90e5d6SChris Mason 
91d352ac68SChris Mason /* this also releases the path */
922c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
932c90e5d6SChris Mason {
94ff175d57SJesper Juhl 	if (!p)
95ff175d57SJesper Juhl 		return;
96b3b4aa74SDavid Sterba 	btrfs_release_path(p);
972c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
982c90e5d6SChris Mason }
992c90e5d6SChris Mason 
100d352ac68SChris Mason /*
101d352ac68SChris Mason  * path release drops references on the extent buffers in the path
102d352ac68SChris Mason  * and it drops any locks held by this path
103d352ac68SChris Mason  *
104d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
105d352ac68SChris Mason  */
106b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
107eb60ceacSChris Mason {
108eb60ceacSChris Mason 	int i;
109a2135011SChris Mason 
110234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1113f157a2fSChris Mason 		p->slots[i] = 0;
112eb60ceacSChris Mason 		if (!p->nodes[i])
113925baeddSChris Mason 			continue;
114925baeddSChris Mason 		if (p->locks[i]) {
115bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
116925baeddSChris Mason 			p->locks[i] = 0;
117925baeddSChris Mason 		}
1185f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1193f157a2fSChris Mason 		p->nodes[i] = NULL;
120eb60ceacSChris Mason 	}
121eb60ceacSChris Mason }
122eb60ceacSChris Mason 
123d352ac68SChris Mason /*
1248bb808c6SDavid Sterba  * We want the transaction abort to print stack trace only for errors where the
1258bb808c6SDavid Sterba  * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
1268bb808c6SDavid Sterba  * caused by external factors.
1278bb808c6SDavid Sterba  */
1288bb808c6SDavid Sterba bool __cold abort_should_print_stack(int errno)
1298bb808c6SDavid Sterba {
1308bb808c6SDavid Sterba 	switch (errno) {
1318bb808c6SDavid Sterba 	case -EIO:
1328bb808c6SDavid Sterba 	case -EROFS:
1338bb808c6SDavid Sterba 	case -ENOMEM:
1348bb808c6SDavid Sterba 		return false;
1358bb808c6SDavid Sterba 	}
1368bb808c6SDavid Sterba 	return true;
1378bb808c6SDavid Sterba }
1388bb808c6SDavid Sterba 
1398bb808c6SDavid Sterba /*
140d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
141d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
142d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
143d352ac68SChris Mason  * looping required.
144d352ac68SChris Mason  *
145d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
146d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
147d352ac68SChris Mason  * at any time because there are no locks held.
148d352ac68SChris Mason  */
149925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
150925baeddSChris Mason {
151925baeddSChris Mason 	struct extent_buffer *eb;
152240f62c8SChris Mason 
1533083ee2eSJosef Bacik 	while (1) {
154240f62c8SChris Mason 		rcu_read_lock();
155240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1563083ee2eSJosef Bacik 
1573083ee2eSJosef Bacik 		/*
1583083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
15901327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1603083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1613083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1623083ee2eSJosef Bacik 		 */
1633083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
164240f62c8SChris Mason 			rcu_read_unlock();
1653083ee2eSJosef Bacik 			break;
1663083ee2eSJosef Bacik 		}
1673083ee2eSJosef Bacik 		rcu_read_unlock();
1683083ee2eSJosef Bacik 		synchronize_rcu();
1693083ee2eSJosef Bacik 	}
170925baeddSChris Mason 	return eb;
171925baeddSChris Mason }
172925baeddSChris Mason 
17392a7cc42SQu Wenruo /*
17492a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
17592a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
17692a7cc42SQu Wenruo  * sure they get properly updated on disk.
177d352ac68SChris Mason  */
1780b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1790b86a832SChris Mason {
1800b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1810b246afaSJeff Mahoney 
182e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
183e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
184e7070be1SJosef Bacik 		return;
185e7070be1SJosef Bacik 
1860b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
187e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
188e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
1894fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
190e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
1910b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
192e7070be1SJosef Bacik 		else
193e7070be1SJosef Bacik 			list_move(&root->dirty_list,
1940b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
1950b86a832SChris Mason 	}
1960b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1970b86a832SChris Mason }
1980b86a832SChris Mason 
199d352ac68SChris Mason /*
200d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
201d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
202d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
203d352ac68SChris Mason  */
204be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
205be20aa9dSChris Mason 		      struct btrfs_root *root,
206be20aa9dSChris Mason 		      struct extent_buffer *buf,
207be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
208be20aa9dSChris Mason {
2090b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
210be20aa9dSChris Mason 	struct extent_buffer *cow;
211be20aa9dSChris Mason 	int ret = 0;
212be20aa9dSChris Mason 	int level;
2135d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
214be20aa9dSChris Mason 
21592a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2160b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
21792a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
21827cdeb70SMiao Xie 		trans->transid != root->last_trans);
219be20aa9dSChris Mason 
220be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2215d4f98a2SYan Zheng 	if (level == 0)
2225d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2235d4f98a2SYan Zheng 	else
2245d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
22531840ae1SZheng Yan 
2264d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
227cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
228cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
2295d4f98a2SYan Zheng 	if (IS_ERR(cow))
230be20aa9dSChris Mason 		return PTR_ERR(cow);
231be20aa9dSChris Mason 
23258e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
233be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
234be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2355d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2365d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2375d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2385d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2395d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2405d4f98a2SYan Zheng 	else
241be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
242be20aa9dSChris Mason 
243de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2442b82032cSYan Zheng 
245be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2465d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
247e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2485d4f98a2SYan Zheng 	else
249e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
250867ed321SJosef Bacik 	if (ret) {
25172c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
25272c9925fSFilipe Manana 		free_extent_buffer(cow);
253867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
254be20aa9dSChris Mason 		return ret;
255867ed321SJosef Bacik 	}
256be20aa9dSChris Mason 
257be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
258be20aa9dSChris Mason 	*cow_ret = cow;
259be20aa9dSChris Mason 	return 0;
260be20aa9dSChris Mason }
261be20aa9dSChris Mason 
262d352ac68SChris Mason /*
2635d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
2645d4f98a2SYan Zheng  */
2655d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
2665d4f98a2SYan Zheng 			      struct extent_buffer *buf)
2675d4f98a2SYan Zheng {
2685d4f98a2SYan Zheng 	/*
26992a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
27092a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
27192a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
2725d4f98a2SYan Zheng 	 */
27392a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2745d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
2755d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
2765d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
2775d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
2785d4f98a2SYan Zheng 		return 1;
279a79865c6SNikolay Borisov 
2805d4f98a2SYan Zheng 	return 0;
2815d4f98a2SYan Zheng }
2825d4f98a2SYan Zheng 
2835d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
2845d4f98a2SYan Zheng 				       struct btrfs_root *root,
2855d4f98a2SYan Zheng 				       struct extent_buffer *buf,
286f0486c68SYan, Zheng 				       struct extent_buffer *cow,
287f0486c68SYan, Zheng 				       int *last_ref)
2885d4f98a2SYan Zheng {
2890b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2905d4f98a2SYan Zheng 	u64 refs;
2915d4f98a2SYan Zheng 	u64 owner;
2925d4f98a2SYan Zheng 	u64 flags;
2935d4f98a2SYan Zheng 	u64 new_flags = 0;
2945d4f98a2SYan Zheng 	int ret;
2955d4f98a2SYan Zheng 
2965d4f98a2SYan Zheng 	/*
2975d4f98a2SYan Zheng 	 * Backrefs update rules:
2985d4f98a2SYan Zheng 	 *
2995d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
3005d4f98a2SYan Zheng 	 * allocated by tree relocation.
3015d4f98a2SYan Zheng 	 *
3025d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
3035d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
3045d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
3055d4f98a2SYan Zheng 	 *
3065d4f98a2SYan Zheng 	 * If a tree block is been relocating
3075d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
3085d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
3095d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
3105d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
3115d4f98a2SYan Zheng 	 */
3125d4f98a2SYan Zheng 
3135d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
3142ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
3153173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
3163173a18fSJosef Bacik 					       &refs, &flags);
317be1a5564SMark Fasheh 		if (ret)
318be1a5564SMark Fasheh 			return ret;
319e5df9573SMark Fasheh 		if (refs == 0) {
320e5df9573SMark Fasheh 			ret = -EROFS;
3210b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
322e5df9573SMark Fasheh 			return ret;
323e5df9573SMark Fasheh 		}
3245d4f98a2SYan Zheng 	} else {
3255d4f98a2SYan Zheng 		refs = 1;
3265d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
3275d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
3285d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
3295d4f98a2SYan Zheng 		else
3305d4f98a2SYan Zheng 			flags = 0;
3315d4f98a2SYan Zheng 	}
3325d4f98a2SYan Zheng 
3335d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
3345d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
3355d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
3365d4f98a2SYan Zheng 
3375d4f98a2SYan Zheng 	if (refs > 1) {
3385d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
3395d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
3405d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
341e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
342692826b2SJeff Mahoney 			if (ret)
343692826b2SJeff Mahoney 				return ret;
3445d4f98a2SYan Zheng 
3455d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3465d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
347e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
348692826b2SJeff Mahoney 				if (ret)
349692826b2SJeff Mahoney 					return ret;
350e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
351692826b2SJeff Mahoney 				if (ret)
352692826b2SJeff Mahoney 					return ret;
3535d4f98a2SYan Zheng 			}
3545d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
3555d4f98a2SYan Zheng 		} else {
3565d4f98a2SYan Zheng 
3575d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3585d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
359e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3605d4f98a2SYan Zheng 			else
361e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
362692826b2SJeff Mahoney 			if (ret)
363692826b2SJeff Mahoney 				return ret;
3645d4f98a2SYan Zheng 		}
3655d4f98a2SYan Zheng 		if (new_flags != 0) {
366b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
367b1c79e09SJosef Bacik 
36842c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
3692fe6a5a1SDavid Sterba 							  new_flags, level);
370be1a5564SMark Fasheh 			if (ret)
371be1a5564SMark Fasheh 				return ret;
3725d4f98a2SYan Zheng 		}
3735d4f98a2SYan Zheng 	} else {
3745d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
3755d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3765d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
377e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3785d4f98a2SYan Zheng 			else
379e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
380692826b2SJeff Mahoney 			if (ret)
381692826b2SJeff Mahoney 				return ret;
382e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
383692826b2SJeff Mahoney 			if (ret)
384692826b2SJeff Mahoney 				return ret;
3855d4f98a2SYan Zheng 		}
3866a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
387f0486c68SYan, Zheng 		*last_ref = 1;
3885d4f98a2SYan Zheng 	}
3895d4f98a2SYan Zheng 	return 0;
3905d4f98a2SYan Zheng }
3915d4f98a2SYan Zheng 
3925d4f98a2SYan Zheng /*
393d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
394d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
395d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
396d397712bSChris Mason  * dirty again.
397d352ac68SChris Mason  *
398d352ac68SChris Mason  * search_start -- an allocation hint for the new block
399d352ac68SChris Mason  *
400d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
401d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
402d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
403d352ac68SChris Mason  */
404d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
4055f39d397SChris Mason 			     struct btrfs_root *root,
4065f39d397SChris Mason 			     struct extent_buffer *buf,
4075f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
4085f39d397SChris Mason 			     struct extent_buffer **cow_ret,
4099631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
4109631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
4116702ed49SChris Mason {
4120b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4135d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
4145f39d397SChris Mason 	struct extent_buffer *cow;
415be1a5564SMark Fasheh 	int level, ret;
416f0486c68SYan, Zheng 	int last_ref = 0;
417925baeddSChris Mason 	int unlock_orig = 0;
4180f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
4196702ed49SChris Mason 
420925baeddSChris Mason 	if (*cow_ret == buf)
421925baeddSChris Mason 		unlock_orig = 1;
422925baeddSChris Mason 
42349d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
424925baeddSChris Mason 
42592a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
4260b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
42792a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
42827cdeb70SMiao Xie 		trans->transid != root->last_trans);
4295f39d397SChris Mason 
4307bb86316SChris Mason 	level = btrfs_header_level(buf);
43131840ae1SZheng Yan 
4325d4f98a2SYan Zheng 	if (level == 0)
4335d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
4345d4f98a2SYan Zheng 	else
4355d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
4365d4f98a2SYan Zheng 
4370f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
4385d4f98a2SYan Zheng 		parent_start = parent->start;
4395d4f98a2SYan Zheng 
44079bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
44179bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
44279bd3712SFilipe Manana 				     search_start, empty_size, nest);
4436702ed49SChris Mason 	if (IS_ERR(cow))
4446702ed49SChris Mason 		return PTR_ERR(cow);
4456702ed49SChris Mason 
446b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
447b4ce94deSChris Mason 
44858e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
449db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
4505f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
4515d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
4525d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
4535d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
4545d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
4555d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
4565d4f98a2SYan Zheng 	else
4575f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
4586702ed49SChris Mason 
459de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
4602b82032cSYan Zheng 
461be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
462b68dc2a9SMark Fasheh 	if (ret) {
463572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
464572c83acSJosef Bacik 		free_extent_buffer(cow);
46566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
466b68dc2a9SMark Fasheh 		return ret;
467b68dc2a9SMark Fasheh 	}
4681a40e23bSZheng Yan 
46992a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
47083d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
47193314e3bSZhaolei 		if (ret) {
472572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
473572c83acSJosef Bacik 			free_extent_buffer(cow);
47466642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
47583d4cfd4SJosef Bacik 			return ret;
47683d4cfd4SJosef Bacik 		}
47793314e3bSZhaolei 	}
4783fd0a558SYan, Zheng 
4796702ed49SChris Mason 	if (buf == root->node) {
480925baeddSChris Mason 		WARN_ON(parent && parent != buf);
4815d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4825d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4835d4f98a2SYan Zheng 			parent_start = buf->start;
484925baeddSChris Mason 
48567439dadSDavid Sterba 		atomic_inc(&cow->refs);
486406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
487d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
488240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
489925baeddSChris Mason 
4907a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
4917a163608SFilipe Manana 				      parent_start, last_ref);
4925f39d397SChris Mason 		free_extent_buffer(buf);
4930b86a832SChris Mason 		add_root_to_dirty_list(root);
4946702ed49SChris Mason 	} else {
4955d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
496f3a84ccdSFilipe Manana 		btrfs_tree_mod_log_insert_key(parent, parent_slot,
49733cff222SFilipe Manana 					      BTRFS_MOD_LOG_KEY_REPLACE);
4985f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
499db94535dSChris Mason 					cow->start);
50074493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
50174493f7aSChris Mason 					      trans->transid);
5026702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
5035de865eeSFilipe David Borba Manana 		if (last_ref) {
504f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
5055de865eeSFilipe David Borba Manana 			if (ret) {
506572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
507572c83acSJosef Bacik 				free_extent_buffer(cow);
50866642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
5095de865eeSFilipe David Borba Manana 				return ret;
5105de865eeSFilipe David Borba Manana 			}
5115de865eeSFilipe David Borba Manana 		}
5127a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
5137a163608SFilipe Manana 				      parent_start, last_ref);
5146702ed49SChris Mason 	}
515925baeddSChris Mason 	if (unlock_orig)
516925baeddSChris Mason 		btrfs_tree_unlock(buf);
5173083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
5186702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
5196702ed49SChris Mason 	*cow_ret = cow;
5206702ed49SChris Mason 	return 0;
5216702ed49SChris Mason }
5226702ed49SChris Mason 
5235d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
5245d4f98a2SYan Zheng 				   struct btrfs_root *root,
5255d4f98a2SYan Zheng 				   struct extent_buffer *buf)
5265d4f98a2SYan Zheng {
527f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
528faa2dbf0SJosef Bacik 		return 0;
529fccb84c9SDavid Sterba 
530d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
531d1980131SDavid Sterba 	smp_mb__before_atomic();
532f1ebcc74SLiu Bo 
533f1ebcc74SLiu Bo 	/*
534f1ebcc74SLiu Bo 	 * We do not need to cow a block if
535f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
536f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
537f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
538f1ebcc74SLiu Bo 	 *
539f1ebcc74SLiu Bo 	 * What is forced COW:
54001327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
54152042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
542f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
543f1ebcc74SLiu Bo 	 */
5445d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
5455d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
5465d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
547f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
54827cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
5495d4f98a2SYan Zheng 		return 0;
5505d4f98a2SYan Zheng 	return 1;
5515d4f98a2SYan Zheng }
5525d4f98a2SYan Zheng 
553d352ac68SChris Mason /*
554d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
55501327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
556d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
557d352ac68SChris Mason  */
558d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
5595f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
5605f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
5619631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
5629631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
56302217ed2SChris Mason {
5640b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5656702ed49SChris Mason 	u64 search_start;
566f510cfecSChris Mason 	int ret;
567dc17ff8fSChris Mason 
56883354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
56983354f07SJosef Bacik 		btrfs_err(fs_info,
57083354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
57183354f07SJosef Bacik 
5720b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
57331b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
574c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
5750b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
57631b1a2bdSJulia Lawall 
5770b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
57831b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
5790b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
580dc17ff8fSChris Mason 
5815d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
58202217ed2SChris Mason 		*cow_ret = buf;
58302217ed2SChris Mason 		return 0;
58402217ed2SChris Mason 	}
585c487685dSChris Mason 
586ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
587b4ce94deSChris Mason 
588f616f5cdSQu Wenruo 	/*
589f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
590f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
591f616f5cdSQu Wenruo 	 *
592f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
593f616f5cdSQu Wenruo 	 */
594f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
595f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
5969631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
5971abe9b8aSliubo 
5981abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
5991abe9b8aSliubo 
600f510cfecSChris Mason 	return ret;
6012c90e5d6SChris Mason }
602f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
6036702ed49SChris Mason 
604d352ac68SChris Mason /*
605d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
606d352ac68SChris Mason  * node are actually close by
607d352ac68SChris Mason  */
6086b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
6096702ed49SChris Mason {
6106b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
6116702ed49SChris Mason 		return 1;
6126b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
6136702ed49SChris Mason 		return 1;
61402217ed2SChris Mason 	return 0;
61502217ed2SChris Mason }
61602217ed2SChris Mason 
617ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
618ce6ef5abSDavid Sterba 
619ce6ef5abSDavid Sterba /*
620ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
621ce6ef5abSDavid Sterba  * we can avoid the conversion.
622ce6ef5abSDavid Sterba  */
623ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
624ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
625ce6ef5abSDavid Sterba {
626ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
627ce6ef5abSDavid Sterba 
628ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
629ce6ef5abSDavid Sterba }
630ce6ef5abSDavid Sterba 
631ce6ef5abSDavid Sterba #else
632ce6ef5abSDavid Sterba 
633081e9573SChris Mason /*
634081e9573SChris Mason  * compare two keys in a memcmp fashion
635081e9573SChris Mason  */
636310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
637310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
638081e9573SChris Mason {
639081e9573SChris Mason 	struct btrfs_key k1;
640081e9573SChris Mason 
641081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
642081e9573SChris Mason 
64320736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
644081e9573SChris Mason }
645ce6ef5abSDavid Sterba #endif
646081e9573SChris Mason 
647f3465ca4SJosef Bacik /*
648f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
649f3465ca4SJosef Bacik  */
650e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
651f3465ca4SJosef Bacik {
652f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
653f3465ca4SJosef Bacik 		return 1;
654f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
655f3465ca4SJosef Bacik 		return -1;
656f3465ca4SJosef Bacik 	if (k1->type > k2->type)
657f3465ca4SJosef Bacik 		return 1;
658f3465ca4SJosef Bacik 	if (k1->type < k2->type)
659f3465ca4SJosef Bacik 		return -1;
660f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
661f3465ca4SJosef Bacik 		return 1;
662f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
663f3465ca4SJosef Bacik 		return -1;
664f3465ca4SJosef Bacik 	return 0;
665f3465ca4SJosef Bacik }
666081e9573SChris Mason 
667d352ac68SChris Mason /*
668d352ac68SChris Mason  * this is used by the defrag code to go through all the
669d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
670d352ac68SChris Mason  * disk order is close to key order
671d352ac68SChris Mason  */
6726702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
6735f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
674de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
675a6b6e75eSChris Mason 		       struct btrfs_key *progress)
6766702ed49SChris Mason {
6770b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6786b80053dSChris Mason 	struct extent_buffer *cur;
6796702ed49SChris Mason 	u64 blocknr;
680e9d0b13bSChris Mason 	u64 search_start = *last_ret;
681e9d0b13bSChris Mason 	u64 last_block = 0;
6826702ed49SChris Mason 	u64 other;
6836702ed49SChris Mason 	u32 parent_nritems;
6846702ed49SChris Mason 	int end_slot;
6856702ed49SChris Mason 	int i;
6866702ed49SChris Mason 	int err = 0;
6876b80053dSChris Mason 	u32 blocksize;
688081e9573SChris Mason 	int progress_passed = 0;
689081e9573SChris Mason 	struct btrfs_disk_key disk_key;
6906702ed49SChris Mason 
6910b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
6920b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
69386479a04SChris Mason 
6946b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
6950b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
6965dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
6976702ed49SChris Mason 
6985dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
6996702ed49SChris Mason 		return 0;
7006702ed49SChris Mason 
7015dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
7026702ed49SChris Mason 		int close = 1;
703a6b6e75eSChris Mason 
704081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
705081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
706081e9573SChris Mason 			continue;
707081e9573SChris Mason 
708081e9573SChris Mason 		progress_passed = 1;
7096b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
710e9d0b13bSChris Mason 		if (last_block == 0)
711e9d0b13bSChris Mason 			last_block = blocknr;
7125708b959SChris Mason 
7136702ed49SChris Mason 		if (i > 0) {
7146b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
7156b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
7166702ed49SChris Mason 		}
7175dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
7186b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
7196b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
7206702ed49SChris Mason 		}
721e9d0b13bSChris Mason 		if (close) {
722e9d0b13bSChris Mason 			last_block = blocknr;
7236702ed49SChris Mason 			continue;
724e9d0b13bSChris Mason 		}
7256702ed49SChris Mason 
726206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
727206983b7SJosef Bacik 		if (IS_ERR(cur))
72864c043deSLiu Bo 			return PTR_ERR(cur);
729e9d0b13bSChris Mason 		if (search_start == 0)
7306b80053dSChris Mason 			search_start = last_block;
731e9d0b13bSChris Mason 
732e7a84565SChris Mason 		btrfs_tree_lock(cur);
7336b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
734e7a84565SChris Mason 					&cur, search_start,
7356b80053dSChris Mason 					min(16 * blocksize,
7369631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
7379631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
738252c38f0SYan 		if (err) {
739e7a84565SChris Mason 			btrfs_tree_unlock(cur);
7406b80053dSChris Mason 			free_extent_buffer(cur);
7416702ed49SChris Mason 			break;
742252c38f0SYan 		}
743e7a84565SChris Mason 		search_start = cur->start;
744e7a84565SChris Mason 		last_block = cur->start;
745f2183bdeSChris Mason 		*last_ret = search_start;
746e7a84565SChris Mason 		btrfs_tree_unlock(cur);
747e7a84565SChris Mason 		free_extent_buffer(cur);
7486702ed49SChris Mason 	}
7496702ed49SChris Mason 	return err;
7506702ed49SChris Mason }
7516702ed49SChris Mason 
75274123bd7SChris Mason /*
753fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
7545f39d397SChris Mason  *
755fb81212cSFilipe Manana  * The lower boundary for the search is specified by the slot number @low. Use a
756fb81212cSFilipe Manana  * value of 0 to search over the whole extent buffer.
75774123bd7SChris Mason  *
758fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
759fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
760fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
761fb81212cSFilipe Manana  *
762fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
763fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
76474123bd7SChris Mason  */
765fb81212cSFilipe Manana static noinline int generic_bin_search(struct extent_buffer *eb, int low,
76667d5e289SMarcos Paulo de Souza 				       const struct btrfs_key *key, int *slot)
767be0e5c09SChris Mason {
768fb81212cSFilipe Manana 	unsigned long p;
769fb81212cSFilipe Manana 	int item_size;
77067d5e289SMarcos Paulo de Souza 	int high = btrfs_header_nritems(eb);
771be0e5c09SChris Mason 	int ret;
7725cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
773be0e5c09SChris Mason 
7745e24e9afSLiu Bo 	if (low > high) {
7755e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
7765e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
7775e24e9afSLiu Bo 			  __func__, low, high, eb->start,
7785e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
7795e24e9afSLiu Bo 		return -EINVAL;
7805e24e9afSLiu Bo 	}
7815e24e9afSLiu Bo 
782fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
783fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
784fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
785fb81212cSFilipe Manana 	} else {
786fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
787fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
788fb81212cSFilipe Manana 	}
789fb81212cSFilipe Manana 
790be0e5c09SChris Mason 	while (low < high) {
7915cd17f34SDavid Sterba 		unsigned long oip;
7925cd17f34SDavid Sterba 		unsigned long offset;
7935cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
7945cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
7955cd17f34SDavid Sterba 		int mid;
7965cd17f34SDavid Sterba 
797be0e5c09SChris Mason 		mid = (low + high) / 2;
7985f39d397SChris Mason 		offset = p + mid * item_size;
7995cd17f34SDavid Sterba 		oip = offset_in_page(offset);
8005f39d397SChris Mason 
8015cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
802884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
8035cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
804934d375bSChris Mason 
805884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
8065cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
8075cd17f34SDavid Sterba 		} else {
8085cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
8095f39d397SChris Mason 			tmp = &unaligned;
810479965d6SChris Mason 		}
811479965d6SChris Mason 
812be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
813be0e5c09SChris Mason 
814be0e5c09SChris Mason 		if (ret < 0)
815be0e5c09SChris Mason 			low = mid + 1;
816be0e5c09SChris Mason 		else if (ret > 0)
817be0e5c09SChris Mason 			high = mid;
818be0e5c09SChris Mason 		else {
819be0e5c09SChris Mason 			*slot = mid;
820be0e5c09SChris Mason 			return 0;
821be0e5c09SChris Mason 		}
822be0e5c09SChris Mason 	}
823be0e5c09SChris Mason 	*slot = low;
824be0e5c09SChris Mason 	return 1;
825be0e5c09SChris Mason }
826be0e5c09SChris Mason 
82797571fd0SChris Mason /*
828fb81212cSFilipe Manana  * Simple binary search on an extent buffer. Works for both leaves and nodes, and
829fb81212cSFilipe Manana  * always searches over the whole range of keys (slot 0 to slot 'nritems - 1').
83097571fd0SChris Mason  */
831a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
832e3b83361SQu Wenruo 		     int *slot)
833be0e5c09SChris Mason {
834fb81212cSFilipe Manana 	return generic_bin_search(eb, 0, key, slot);
835be0e5c09SChris Mason }
836be0e5c09SChris Mason 
837f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
838f0486c68SYan, Zheng {
839f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
840f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
841f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
842f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
843f0486c68SYan, Zheng }
844f0486c68SYan, Zheng 
845f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
846f0486c68SYan, Zheng {
847f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
848f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
849f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
850f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
851f0486c68SYan, Zheng }
852f0486c68SYan, Zheng 
853d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
854d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
855d352ac68SChris Mason  */
8564b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
8574b231ae4SDavid Sterba 					   int slot)
858bb803951SChris Mason {
859ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
860*789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
861416bc658SJosef Bacik 	struct extent_buffer *eb;
862416bc658SJosef Bacik 
863fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
864fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
865ca7a79adSChris Mason 
866ca7a79adSChris Mason 	BUG_ON(level == 0);
867ca7a79adSChris Mason 
868*789d6a3aSQu Wenruo 	check.level = level - 1;
869*789d6a3aSQu Wenruo 	check.transid = btrfs_node_ptr_generation(parent, slot);
870*789d6a3aSQu Wenruo 	check.owner_root = btrfs_header_owner(parent);
871*789d6a3aSQu Wenruo 	check.has_first_key = true;
872*789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(parent, &check.first_key, slot);
873*789d6a3aSQu Wenruo 
874d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
875*789d6a3aSQu Wenruo 			     &check);
8764eb150d6SQu Wenruo 	if (IS_ERR(eb))
8774eb150d6SQu Wenruo 		return eb;
8784eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
879416bc658SJosef Bacik 		free_extent_buffer(eb);
8804eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
881416bc658SJosef Bacik 	}
882416bc658SJosef Bacik 
883416bc658SJosef Bacik 	return eb;
884bb803951SChris Mason }
885bb803951SChris Mason 
886d352ac68SChris Mason /*
887d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
888d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
889d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
890d352ac68SChris Mason  */
891e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
89298ed5174SChris Mason 			 struct btrfs_root *root,
89398ed5174SChris Mason 			 struct btrfs_path *path, int level)
894bb803951SChris Mason {
8950b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8965f39d397SChris Mason 	struct extent_buffer *right = NULL;
8975f39d397SChris Mason 	struct extent_buffer *mid;
8985f39d397SChris Mason 	struct extent_buffer *left = NULL;
8995f39d397SChris Mason 	struct extent_buffer *parent = NULL;
900bb803951SChris Mason 	int ret = 0;
901bb803951SChris Mason 	int wret;
902bb803951SChris Mason 	int pslot;
903bb803951SChris Mason 	int orig_slot = path->slots[level];
90479f95c82SChris Mason 	u64 orig_ptr;
905bb803951SChris Mason 
90698e6b1ebSLiu Bo 	ASSERT(level > 0);
907bb803951SChris Mason 
9085f39d397SChris Mason 	mid = path->nodes[level];
909b4ce94deSChris Mason 
910ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
9117bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
9127bb86316SChris Mason 
9131d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
91479f95c82SChris Mason 
915a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
9165f39d397SChris Mason 		parent = path->nodes[level + 1];
917bb803951SChris Mason 		pslot = path->slots[level + 1];
918a05a9bb1SLi Zefan 	}
919bb803951SChris Mason 
92040689478SChris Mason 	/*
92140689478SChris Mason 	 * deal with the case where there is only one pointer in the root
92240689478SChris Mason 	 * by promoting the node below to a root
92340689478SChris Mason 	 */
9245f39d397SChris Mason 	if (!parent) {
9255f39d397SChris Mason 		struct extent_buffer *child;
926bb803951SChris Mason 
9275f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
928bb803951SChris Mason 			return 0;
929bb803951SChris Mason 
930bb803951SChris Mason 		/* promote the child to a root */
9314b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
932fb770ae4SLiu Bo 		if (IS_ERR(child)) {
933fb770ae4SLiu Bo 			ret = PTR_ERR(child);
9340b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
935305a26afSMark Fasheh 			goto enospc;
936305a26afSMark Fasheh 		}
937305a26afSMark Fasheh 
938925baeddSChris Mason 		btrfs_tree_lock(child);
9399631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
9409631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
941f0486c68SYan, Zheng 		if (ret) {
942f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
943f0486c68SYan, Zheng 			free_extent_buffer(child);
944f0486c68SYan, Zheng 			goto enospc;
945f0486c68SYan, Zheng 		}
9462f375ab9SYan 
947406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
948d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
949240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
950925baeddSChris Mason 
9510b86a832SChris Mason 		add_root_to_dirty_list(root);
952925baeddSChris Mason 		btrfs_tree_unlock(child);
953b4ce94deSChris Mason 
954925baeddSChris Mason 		path->locks[level] = 0;
955bb803951SChris Mason 		path->nodes[level] = NULL;
9566a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
957925baeddSChris Mason 		btrfs_tree_unlock(mid);
958bb803951SChris Mason 		/* once for the path */
9595f39d397SChris Mason 		free_extent_buffer(mid);
960f0486c68SYan, Zheng 
961f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
9627a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
963bb803951SChris Mason 		/* once for the root ptr */
9643083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
965f0486c68SYan, Zheng 		return 0;
966bb803951SChris Mason 	}
9675f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
9680b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
969bb803951SChris Mason 		return 0;
970bb803951SChris Mason 
9714b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
972fb770ae4SLiu Bo 	if (IS_ERR(left))
973fb770ae4SLiu Bo 		left = NULL;
974fb770ae4SLiu Bo 
9755f39d397SChris Mason 	if (left) {
976bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
9775f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
9789631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
979bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
98054aa1f4dSChris Mason 		if (wret) {
98154aa1f4dSChris Mason 			ret = wret;
98254aa1f4dSChris Mason 			goto enospc;
98354aa1f4dSChris Mason 		}
9842cc58cf2SChris Mason 	}
985fb770ae4SLiu Bo 
9864b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
987fb770ae4SLiu Bo 	if (IS_ERR(right))
988fb770ae4SLiu Bo 		right = NULL;
989fb770ae4SLiu Bo 
9905f39d397SChris Mason 	if (right) {
991bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
9925f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
9939631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
994bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
9952cc58cf2SChris Mason 		if (wret) {
9962cc58cf2SChris Mason 			ret = wret;
9972cc58cf2SChris Mason 			goto enospc;
9982cc58cf2SChris Mason 		}
9992cc58cf2SChris Mason 	}
10002cc58cf2SChris Mason 
10012cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
10025f39d397SChris Mason 	if (left) {
10035f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1004d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
100579f95c82SChris Mason 		if (wret < 0)
100679f95c82SChris Mason 			ret = wret;
1007bb803951SChris Mason 	}
100879f95c82SChris Mason 
100979f95c82SChris Mason 	/*
101079f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
101179f95c82SChris Mason 	 */
10125f39d397SChris Mason 	if (right) {
1013d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
101454aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
101579f95c82SChris Mason 			ret = wret;
10165f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
10176a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1018925baeddSChris Mason 			btrfs_tree_unlock(right);
1019afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1020f0486c68SYan, Zheng 			root_sub_used(root, right->len);
10217a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
10227a163608SFilipe Manana 					      0, 1);
10233083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1024f0486c68SYan, Zheng 			right = NULL;
1025bb803951SChris Mason 		} else {
10265f39d397SChris Mason 			struct btrfs_disk_key right_key;
10275f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1028f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
102933cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
10300e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
10315f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
10325f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1033bb803951SChris Mason 		}
1034bb803951SChris Mason 	}
10355f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
103679f95c82SChris Mason 		/*
103779f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
103879f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
103979f95c82SChris Mason 		 * could try to delete the only pointer in this node.
104079f95c82SChris Mason 		 * So, pull some keys from the left.
104179f95c82SChris Mason 		 * There has to be a left pointer at this point because
104279f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
104379f95c82SChris Mason 		 * right
104479f95c82SChris Mason 		 */
1045305a26afSMark Fasheh 		if (!left) {
1046305a26afSMark Fasheh 			ret = -EROFS;
10470b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1048305a26afSMark Fasheh 			goto enospc;
1049305a26afSMark Fasheh 		}
105055d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
105154aa1f4dSChris Mason 		if (wret < 0) {
105279f95c82SChris Mason 			ret = wret;
105354aa1f4dSChris Mason 			goto enospc;
105454aa1f4dSChris Mason 		}
1055bce4eae9SChris Mason 		if (wret == 1) {
1056d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1057bce4eae9SChris Mason 			if (wret < 0)
1058bce4eae9SChris Mason 				ret = wret;
1059bce4eae9SChris Mason 		}
106079f95c82SChris Mason 		BUG_ON(wret == 1);
106179f95c82SChris Mason 	}
10625f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
10636a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1064925baeddSChris Mason 		btrfs_tree_unlock(mid);
1065afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1066f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10677a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
10683083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1069f0486c68SYan, Zheng 		mid = NULL;
107079f95c82SChris Mason 	} else {
107179f95c82SChris Mason 		/* update the parent key to reflect our changes */
10725f39d397SChris Mason 		struct btrfs_disk_key mid_key;
10735f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1074f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
107533cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
10760e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
10775f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
10785f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
107979f95c82SChris Mason 	}
1080bb803951SChris Mason 
108179f95c82SChris Mason 	/* update the path */
10825f39d397SChris Mason 	if (left) {
10835f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
108467439dadSDavid Sterba 			atomic_inc(&left->refs);
1085925baeddSChris Mason 			/* left was locked after cow */
10865f39d397SChris Mason 			path->nodes[level] = left;
1087bb803951SChris Mason 			path->slots[level + 1] -= 1;
1088bb803951SChris Mason 			path->slots[level] = orig_slot;
1089925baeddSChris Mason 			if (mid) {
1090925baeddSChris Mason 				btrfs_tree_unlock(mid);
10915f39d397SChris Mason 				free_extent_buffer(mid);
1092925baeddSChris Mason 			}
1093bb803951SChris Mason 		} else {
10945f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1095bb803951SChris Mason 			path->slots[level] = orig_slot;
1096bb803951SChris Mason 		}
1097bb803951SChris Mason 	}
109879f95c82SChris Mason 	/* double check we haven't messed things up */
1099e20d96d6SChris Mason 	if (orig_ptr !=
11005f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
110179f95c82SChris Mason 		BUG();
110254aa1f4dSChris Mason enospc:
1103925baeddSChris Mason 	if (right) {
1104925baeddSChris Mason 		btrfs_tree_unlock(right);
11055f39d397SChris Mason 		free_extent_buffer(right);
1106925baeddSChris Mason 	}
1107925baeddSChris Mason 	if (left) {
1108925baeddSChris Mason 		if (path->nodes[level] != left)
1109925baeddSChris Mason 			btrfs_tree_unlock(left);
11105f39d397SChris Mason 		free_extent_buffer(left);
1111925baeddSChris Mason 	}
1112bb803951SChris Mason 	return ret;
1113bb803951SChris Mason }
1114bb803951SChris Mason 
1115d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1116d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1117d352ac68SChris Mason  * have to be pessimistic.
1118d352ac68SChris Mason  */
1119d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1120e66f709bSChris Mason 					  struct btrfs_root *root,
1121e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1122e66f709bSChris Mason {
11230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11245f39d397SChris Mason 	struct extent_buffer *right = NULL;
11255f39d397SChris Mason 	struct extent_buffer *mid;
11265f39d397SChris Mason 	struct extent_buffer *left = NULL;
11275f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1128e66f709bSChris Mason 	int ret = 0;
1129e66f709bSChris Mason 	int wret;
1130e66f709bSChris Mason 	int pslot;
1131e66f709bSChris Mason 	int orig_slot = path->slots[level];
1132e66f709bSChris Mason 
1133e66f709bSChris Mason 	if (level == 0)
1134e66f709bSChris Mason 		return 1;
1135e66f709bSChris Mason 
11365f39d397SChris Mason 	mid = path->nodes[level];
11377bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1138e66f709bSChris Mason 
1139a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
11405f39d397SChris Mason 		parent = path->nodes[level + 1];
1141e66f709bSChris Mason 		pslot = path->slots[level + 1];
1142a05a9bb1SLi Zefan 	}
1143e66f709bSChris Mason 
11445f39d397SChris Mason 	if (!parent)
1145e66f709bSChris Mason 		return 1;
1146e66f709bSChris Mason 
11474b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1148fb770ae4SLiu Bo 	if (IS_ERR(left))
1149fb770ae4SLiu Bo 		left = NULL;
1150e66f709bSChris Mason 
1151e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
11525f39d397SChris Mason 	if (left) {
1153e66f709bSChris Mason 		u32 left_nr;
1154925baeddSChris Mason 
1155bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1156b4ce94deSChris Mason 
11575f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
11580b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
115933ade1f8SChris Mason 			wret = 1;
116033ade1f8SChris Mason 		} else {
11615f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
11629631e4ccSJosef Bacik 					      pslot - 1, &left,
1163bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
116454aa1f4dSChris Mason 			if (ret)
116554aa1f4dSChris Mason 				wret = 1;
116654aa1f4dSChris Mason 			else {
1167d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
116854aa1f4dSChris Mason 			}
116933ade1f8SChris Mason 		}
1170e66f709bSChris Mason 		if (wret < 0)
1171e66f709bSChris Mason 			ret = wret;
1172e66f709bSChris Mason 		if (wret == 0) {
11735f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1174e66f709bSChris Mason 			orig_slot += left_nr;
11755f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1176f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
117733cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
11780e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11795f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
11805f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
11815f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
11825f39d397SChris Mason 				path->nodes[level] = left;
1183e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1184e66f709bSChris Mason 				path->slots[level] = orig_slot;
1185925baeddSChris Mason 				btrfs_tree_unlock(mid);
11865f39d397SChris Mason 				free_extent_buffer(mid);
1187e66f709bSChris Mason 			} else {
1188e66f709bSChris Mason 				orig_slot -=
11895f39d397SChris Mason 					btrfs_header_nritems(left);
1190e66f709bSChris Mason 				path->slots[level] = orig_slot;
1191925baeddSChris Mason 				btrfs_tree_unlock(left);
11925f39d397SChris Mason 				free_extent_buffer(left);
1193e66f709bSChris Mason 			}
1194e66f709bSChris Mason 			return 0;
1195e66f709bSChris Mason 		}
1196925baeddSChris Mason 		btrfs_tree_unlock(left);
11975f39d397SChris Mason 		free_extent_buffer(left);
1198e66f709bSChris Mason 	}
11994b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1200fb770ae4SLiu Bo 	if (IS_ERR(right))
1201fb770ae4SLiu Bo 		right = NULL;
1202e66f709bSChris Mason 
1203e66f709bSChris Mason 	/*
1204e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1205e66f709bSChris Mason 	 */
12065f39d397SChris Mason 	if (right) {
120733ade1f8SChris Mason 		u32 right_nr;
1208b4ce94deSChris Mason 
1209bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1210b4ce94deSChris Mason 
12115f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
12120b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
121333ade1f8SChris Mason 			wret = 1;
121433ade1f8SChris Mason 		} else {
12155f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
12165f39d397SChris Mason 					      parent, pslot + 1,
1217bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
121854aa1f4dSChris Mason 			if (ret)
121954aa1f4dSChris Mason 				wret = 1;
122054aa1f4dSChris Mason 			else {
122155d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
122233ade1f8SChris Mason 			}
122354aa1f4dSChris Mason 		}
1224e66f709bSChris Mason 		if (wret < 0)
1225e66f709bSChris Mason 			ret = wret;
1226e66f709bSChris Mason 		if (wret == 0) {
12275f39d397SChris Mason 			struct btrfs_disk_key disk_key;
12285f39d397SChris Mason 
12295f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1230f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
123133cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
12320e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
12335f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
12345f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12355f39d397SChris Mason 
12365f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
12375f39d397SChris Mason 				path->nodes[level] = right;
1238e66f709bSChris Mason 				path->slots[level + 1] += 1;
1239e66f709bSChris Mason 				path->slots[level] = orig_slot -
12405f39d397SChris Mason 					btrfs_header_nritems(mid);
1241925baeddSChris Mason 				btrfs_tree_unlock(mid);
12425f39d397SChris Mason 				free_extent_buffer(mid);
1243e66f709bSChris Mason 			} else {
1244925baeddSChris Mason 				btrfs_tree_unlock(right);
12455f39d397SChris Mason 				free_extent_buffer(right);
1246e66f709bSChris Mason 			}
1247e66f709bSChris Mason 			return 0;
1248e66f709bSChris Mason 		}
1249925baeddSChris Mason 		btrfs_tree_unlock(right);
12505f39d397SChris Mason 		free_extent_buffer(right);
1251e66f709bSChris Mason 	}
1252e66f709bSChris Mason 	return 1;
1253e66f709bSChris Mason }
1254e66f709bSChris Mason 
125574123bd7SChris Mason /*
1256d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1257d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
12583c69faecSChris Mason  */
12592ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1260e02119d5SChris Mason 			     struct btrfs_path *path,
126101f46658SChris Mason 			     int level, int slot, u64 objectid)
12623c69faecSChris Mason {
12635f39d397SChris Mason 	struct extent_buffer *node;
126401f46658SChris Mason 	struct btrfs_disk_key disk_key;
12653c69faecSChris Mason 	u32 nritems;
12663c69faecSChris Mason 	u64 search;
1267a7175319SChris Mason 	u64 target;
12686b80053dSChris Mason 	u64 nread = 0;
1269ace75066SFilipe Manana 	u64 nread_max;
12706b80053dSChris Mason 	u32 nr;
12716b80053dSChris Mason 	u32 blocksize;
12726b80053dSChris Mason 	u32 nscan = 0;
1273db94535dSChris Mason 
1274ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
12753c69faecSChris Mason 		return;
12763c69faecSChris Mason 
12776702ed49SChris Mason 	if (!path->nodes[level])
12786702ed49SChris Mason 		return;
12796702ed49SChris Mason 
12805f39d397SChris Mason 	node = path->nodes[level];
1281925baeddSChris Mason 
1282ace75066SFilipe Manana 	/*
1283ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1284ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1285ace75066SFilipe Manana 	 * much IO at once (possibly random).
1286ace75066SFilipe Manana 	 */
1287ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1288ace75066SFilipe Manana 		if (level > 1)
1289ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1290ace75066SFilipe Manana 		else
1291ace75066SFilipe Manana 			nread_max = SZ_128K;
1292ace75066SFilipe Manana 	} else {
1293ace75066SFilipe Manana 		nread_max = SZ_64K;
1294ace75066SFilipe Manana 	}
1295ace75066SFilipe Manana 
12963c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
12970b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1298069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1299069a2e37SFilipe Manana 		struct extent_buffer *eb;
1300069a2e37SFilipe Manana 
13010b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
13025f39d397SChris Mason 		if (eb) {
13035f39d397SChris Mason 			free_extent_buffer(eb);
13043c69faecSChris Mason 			return;
13053c69faecSChris Mason 		}
1306069a2e37SFilipe Manana 	}
13073c69faecSChris Mason 
1308a7175319SChris Mason 	target = search;
13096b80053dSChris Mason 
13105f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
13116b80053dSChris Mason 	nr = slot;
131225b8b936SJosef Bacik 
13133c69faecSChris Mason 	while (1) {
1314e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
13156b80053dSChris Mason 			if (nr == 0)
13163c69faecSChris Mason 				break;
13176b80053dSChris Mason 			nr--;
1318ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1319ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
13206b80053dSChris Mason 			nr++;
13216b80053dSChris Mason 			if (nr >= nritems)
13226b80053dSChris Mason 				break;
13233c69faecSChris Mason 		}
1324e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
132501f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
132601f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
132701f46658SChris Mason 				break;
132801f46658SChris Mason 		}
13296b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1330ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1331ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1332a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1333bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
13346b80053dSChris Mason 			nread += blocksize;
13353c69faecSChris Mason 		}
13366b80053dSChris Mason 		nscan++;
1337ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
13386b80053dSChris Mason 			break;
13393c69faecSChris Mason 	}
13403c69faecSChris Mason }
1341925baeddSChris Mason 
1342bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1343b4ce94deSChris Mason {
1344bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1345b4ce94deSChris Mason 	int slot;
1346b4ce94deSChris Mason 	int nritems;
1347b4ce94deSChris Mason 
13488c594ea8SChris Mason 	parent = path->nodes[level + 1];
1349b4ce94deSChris Mason 	if (!parent)
13500b08851fSJosef Bacik 		return;
1351b4ce94deSChris Mason 
1352b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
13538c594ea8SChris Mason 	slot = path->slots[level + 1];
1354b4ce94deSChris Mason 
1355bfb484d9SJosef Bacik 	if (slot > 0)
1356bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1357bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1358bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1359b4ce94deSChris Mason }
1360b4ce94deSChris Mason 
1361b4ce94deSChris Mason 
1362b4ce94deSChris Mason /*
1363d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1364d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1365d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1366d397712bSChris Mason  * tree.
1367d352ac68SChris Mason  *
1368d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1369d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1370d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1371d352ac68SChris Mason  *
1372d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1373d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1374d352ac68SChris Mason  */
1375e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1376f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1377f7c79f30SChris Mason 			       int *write_lock_level)
1378925baeddSChris Mason {
1379925baeddSChris Mason 	int i;
1380925baeddSChris Mason 	int skip_level = level;
1381c1227996SNikolay Borisov 	bool check_skip = true;
1382925baeddSChris Mason 
1383925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1384925baeddSChris Mason 		if (!path->nodes[i])
1385925baeddSChris Mason 			break;
1386925baeddSChris Mason 		if (!path->locks[i])
1387925baeddSChris Mason 			break;
1388c1227996SNikolay Borisov 
1389c1227996SNikolay Borisov 		if (check_skip) {
1390c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1391925baeddSChris Mason 				skip_level = i + 1;
1392925baeddSChris Mason 				continue;
1393925baeddSChris Mason 			}
1394c1227996SNikolay Borisov 
1395c1227996SNikolay Borisov 			if (path->keep_locks) {
1396925baeddSChris Mason 				u32 nritems;
1397c1227996SNikolay Borisov 
1398c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1399051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1400925baeddSChris Mason 					skip_level = i + 1;
1401925baeddSChris Mason 					continue;
1402925baeddSChris Mason 				}
1403925baeddSChris Mason 			}
1404c1227996SNikolay Borisov 		}
1405051e1b9fSChris Mason 
1406d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1407c1227996SNikolay Borisov 			check_skip = false;
1408c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1409925baeddSChris Mason 			path->locks[i] = 0;
1410f7c79f30SChris Mason 			if (write_lock_level &&
1411f7c79f30SChris Mason 			    i > min_write_lock_level &&
1412f7c79f30SChris Mason 			    i <= *write_lock_level) {
1413f7c79f30SChris Mason 				*write_lock_level = i - 1;
1414f7c79f30SChris Mason 			}
1415925baeddSChris Mason 		}
1416925baeddSChris Mason 	}
1417925baeddSChris Mason }
1418925baeddSChris Mason 
14193c69faecSChris Mason /*
1420376a21d7SFilipe Manana  * Helper function for btrfs_search_slot() and other functions that do a search
1421376a21d7SFilipe Manana  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1422376a21d7SFilipe Manana  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1423376a21d7SFilipe Manana  * its pages from disk.
1424c8c42864SChris Mason  *
1425376a21d7SFilipe Manana  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1426376a21d7SFilipe Manana  * whole btree search, starting again from the current root node.
1427c8c42864SChris Mason  */
1428c8c42864SChris Mason static int
1429d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1430c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1431cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1432c8c42864SChris Mason {
14330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1434*789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1435c8c42864SChris Mason 	u64 blocknr;
1436c8c42864SChris Mason 	u64 gen;
1437c8c42864SChris Mason 	struct extent_buffer *tmp;
143876a05b35SChris Mason 	int ret;
1439581c1760SQu Wenruo 	int parent_level;
1440b246666eSFilipe Manana 	bool unlock_up;
1441c8c42864SChris Mason 
1442b246666eSFilipe Manana 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1443213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1444213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1445213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1446*789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(*eb_ret, &check.first_key, slot);
1447*789d6a3aSQu Wenruo 	check.has_first_key = true;
1448*789d6a3aSQu Wenruo 	check.level = parent_level - 1;
1449*789d6a3aSQu Wenruo 	check.transid = gen;
1450*789d6a3aSQu Wenruo 	check.owner_root = root->root_key.objectid;
1451c8c42864SChris Mason 
1452b246666eSFilipe Manana 	/*
1453b246666eSFilipe Manana 	 * If we need to read an extent buffer from disk and we are holding locks
1454b246666eSFilipe Manana 	 * on upper level nodes, we unlock all the upper nodes before reading the
1455b246666eSFilipe Manana 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1456b246666eSFilipe Manana 	 * restart the search. We don't release the lock on the current level
1457b246666eSFilipe Manana 	 * because we need to walk this node to figure out which blocks to read.
1458b246666eSFilipe Manana 	 */
14590b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1460cb44921aSChris Mason 	if (tmp) {
1461ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1462ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1463ace75066SFilipe Manana 
1464b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1465b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1466448de471SQu Wenruo 			/*
1467448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1468448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1469448de471SQu Wenruo 			 * parents (shared tree blocks).
1470448de471SQu Wenruo 			 */
1471e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1472*789d6a3aSQu Wenruo 					parent_level - 1, &check.first_key, gen)) {
1473448de471SQu Wenruo 				free_extent_buffer(tmp);
1474448de471SQu Wenruo 				return -EUCLEAN;
1475448de471SQu Wenruo 			}
1476c8c42864SChris Mason 			*eb_ret = tmp;
1477c8c42864SChris Mason 			return 0;
1478c8c42864SChris Mason 		}
1479bdf7c00eSJosef Bacik 
1480857bc13fSJosef Bacik 		if (p->nowait) {
1481857bc13fSJosef Bacik 			free_extent_buffer(tmp);
1482857bc13fSJosef Bacik 			return -EAGAIN;
1483857bc13fSJosef Bacik 		}
1484857bc13fSJosef Bacik 
1485b246666eSFilipe Manana 		if (unlock_up)
1486b246666eSFilipe Manana 			btrfs_unlock_up_safe(p, level + 1);
1487b246666eSFilipe Manana 
1488b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
1489*789d6a3aSQu Wenruo 		ret = btrfs_read_extent_buffer(tmp, &check);
14909a4ffa1bSQu Wenruo 		if (ret) {
1491cb44921aSChris Mason 			free_extent_buffer(tmp);
1492b3b4aa74SDavid Sterba 			btrfs_release_path(p);
1493cb44921aSChris Mason 			return -EIO;
1494cb44921aSChris Mason 		}
149588c602abSQu Wenruo 		if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
149688c602abSQu Wenruo 			free_extent_buffer(tmp);
149788c602abSQu Wenruo 			btrfs_release_path(p);
149888c602abSQu Wenruo 			return -EUCLEAN;
149988c602abSQu Wenruo 		}
1500b246666eSFilipe Manana 
1501b246666eSFilipe Manana 		if (unlock_up)
1502b246666eSFilipe Manana 			ret = -EAGAIN;
1503b246666eSFilipe Manana 
1504b246666eSFilipe Manana 		goto out;
1505857bc13fSJosef Bacik 	} else if (p->nowait) {
1506857bc13fSJosef Bacik 		return -EAGAIN;
15079a4ffa1bSQu Wenruo 	}
1508c8c42864SChris Mason 
1509b246666eSFilipe Manana 	if (unlock_up) {
15108c594ea8SChris Mason 		btrfs_unlock_up_safe(p, level + 1);
15114bb59055SFilipe Manana 		ret = -EAGAIN;
15124bb59055SFilipe Manana 	} else {
15134bb59055SFilipe Manana 		ret = 0;
15144bb59055SFilipe Manana 	}
15158c594ea8SChris Mason 
1516e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
15172ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1518c8c42864SChris Mason 
1519*789d6a3aSQu Wenruo 	tmp = read_tree_block(fs_info, blocknr, &check);
15204eb150d6SQu Wenruo 	if (IS_ERR(tmp)) {
15214eb150d6SQu Wenruo 		btrfs_release_path(p);
15224eb150d6SQu Wenruo 		return PTR_ERR(tmp);
15234eb150d6SQu Wenruo 	}
152476a05b35SChris Mason 	/*
152576a05b35SChris Mason 	 * If the read above didn't mark this buffer up to date,
152676a05b35SChris Mason 	 * it will never end up being up to date.  Set ret to EIO now
152776a05b35SChris Mason 	 * and give up so that our caller doesn't loop forever
152876a05b35SChris Mason 	 * on our EAGAINs.
152976a05b35SChris Mason 	 */
1530e6a1d6fdSLiu Bo 	if (!extent_buffer_uptodate(tmp))
153176a05b35SChris Mason 		ret = -EIO;
153202a3307aSLiu Bo 
1533b246666eSFilipe Manana out:
15344bb59055SFilipe Manana 	if (ret == 0) {
15354bb59055SFilipe Manana 		*eb_ret = tmp;
15364bb59055SFilipe Manana 	} else {
15374bb59055SFilipe Manana 		free_extent_buffer(tmp);
153802a3307aSLiu Bo 		btrfs_release_path(p);
15394bb59055SFilipe Manana 	}
15404bb59055SFilipe Manana 
154176a05b35SChris Mason 	return ret;
1542c8c42864SChris Mason }
1543c8c42864SChris Mason 
1544c8c42864SChris Mason /*
1545c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1546c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1547c8c42864SChris Mason  * the ins_len.
1548c8c42864SChris Mason  *
1549c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1550c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1551c8c42864SChris Mason  * start over
1552c8c42864SChris Mason  */
1553c8c42864SChris Mason static int
1554c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1555c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1556bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1557bd681513SChris Mason 		       int *write_lock_level)
1558c8c42864SChris Mason {
15590b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
156095b982deSNikolay Borisov 	int ret = 0;
15610b246afaSJeff Mahoney 
1562c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
15630b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1564c8c42864SChris Mason 
1565bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1566bd681513SChris Mason 			*write_lock_level = level + 1;
1567bd681513SChris Mason 			btrfs_release_path(p);
156895b982deSNikolay Borisov 			return -EAGAIN;
1569bd681513SChris Mason 		}
1570bd681513SChris Mason 
1571bfb484d9SJosef Bacik 		reada_for_balance(p, level);
157295b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1573c8c42864SChris Mason 
1574c8c42864SChris Mason 		b = p->nodes[level];
1575c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
15760b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1577c8c42864SChris Mason 
1578bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1579bd681513SChris Mason 			*write_lock_level = level + 1;
1580bd681513SChris Mason 			btrfs_release_path(p);
158195b982deSNikolay Borisov 			return -EAGAIN;
1582bd681513SChris Mason 		}
1583bd681513SChris Mason 
1584bfb484d9SJosef Bacik 		reada_for_balance(p, level);
158595b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
158695b982deSNikolay Borisov 		if (ret)
158795b982deSNikolay Borisov 			return ret;
1588c8c42864SChris Mason 
1589c8c42864SChris Mason 		b = p->nodes[level];
1590c8c42864SChris Mason 		if (!b) {
1591b3b4aa74SDavid Sterba 			btrfs_release_path(p);
159295b982deSNikolay Borisov 			return -EAGAIN;
1593c8c42864SChris Mason 		}
1594c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1595c8c42864SChris Mason 	}
1596c8c42864SChris Mason 	return ret;
1597c8c42864SChris Mason }
1598c8c42864SChris Mason 
1599381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1600e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1601e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1602e33d5c3dSKelley Nielsen {
1603e33d5c3dSKelley Nielsen 	int ret;
1604e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1605e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1606381cf658SDavid Sterba 
1607381cf658SDavid Sterba 	ASSERT(path);
16081d4c08e0SDavid Sterba 	ASSERT(found_key);
1609e33d5c3dSKelley Nielsen 
1610e33d5c3dSKelley Nielsen 	key.type = key_type;
1611e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1612e33d5c3dSKelley Nielsen 	key.offset = ioff;
1613e33d5c3dSKelley Nielsen 
1614e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
16151d4c08e0SDavid Sterba 	if (ret < 0)
1616e33d5c3dSKelley Nielsen 		return ret;
1617e33d5c3dSKelley Nielsen 
1618e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1619e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1620e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1621e33d5c3dSKelley Nielsen 		if (ret)
1622e33d5c3dSKelley Nielsen 			return ret;
1623e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1624e33d5c3dSKelley Nielsen 	}
1625e33d5c3dSKelley Nielsen 
1626e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1627e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1628e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1629e33d5c3dSKelley Nielsen 		return 1;
1630e33d5c3dSKelley Nielsen 
1631e33d5c3dSKelley Nielsen 	return 0;
1632e33d5c3dSKelley Nielsen }
1633e33d5c3dSKelley Nielsen 
16341fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
16351fc28d8eSLiu Bo 							struct btrfs_path *p,
16361fc28d8eSLiu Bo 							int write_lock_level)
16371fc28d8eSLiu Bo {
16381fc28d8eSLiu Bo 	struct extent_buffer *b;
1639120de408SJosef Bacik 	int root_lock = 0;
16401fc28d8eSLiu Bo 	int level = 0;
16411fc28d8eSLiu Bo 
16421fc28d8eSLiu Bo 	if (p->search_commit_root) {
16431fc28d8eSLiu Bo 		b = root->commit_root;
164467439dadSDavid Sterba 		atomic_inc(&b->refs);
16451fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1646f9ddfd05SLiu Bo 		/*
1647f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1648f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1649f9ddfd05SLiu Bo 		 */
1650f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
16511fc28d8eSLiu Bo 
16521fc28d8eSLiu Bo 		goto out;
16531fc28d8eSLiu Bo 	}
16541fc28d8eSLiu Bo 
16551fc28d8eSLiu Bo 	if (p->skip_locking) {
16561fc28d8eSLiu Bo 		b = btrfs_root_node(root);
16571fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16581fc28d8eSLiu Bo 		goto out;
16591fc28d8eSLiu Bo 	}
16601fc28d8eSLiu Bo 
1661120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1662120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1663120de408SJosef Bacik 
16641fc28d8eSLiu Bo 	/*
1665662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1666662c653bSLiu Bo 	 * lock.
1667662c653bSLiu Bo 	 */
1668662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1669662c653bSLiu Bo 		/*
1670662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1671662c653bSLiu Bo 		 * have it read locked
16721fc28d8eSLiu Bo 		 */
1673857bc13fSJosef Bacik 		if (p->nowait) {
1674857bc13fSJosef Bacik 			b = btrfs_try_read_lock_root_node(root);
1675857bc13fSJosef Bacik 			if (IS_ERR(b))
1676857bc13fSJosef Bacik 				return b;
1677857bc13fSJosef Bacik 		} else {
16781bb96598SJosef Bacik 			b = btrfs_read_lock_root_node(root);
1679857bc13fSJosef Bacik 		}
16801fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16811fc28d8eSLiu Bo 		if (level > write_lock_level)
16821fc28d8eSLiu Bo 			goto out;
16831fc28d8eSLiu Bo 
1684662c653bSLiu Bo 		/* Whoops, must trade for write lock */
16851fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
16861fc28d8eSLiu Bo 		free_extent_buffer(b);
1687662c653bSLiu Bo 	}
1688662c653bSLiu Bo 
16891fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
16901fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
16911fc28d8eSLiu Bo 
16921fc28d8eSLiu Bo 	/* The level might have changed, check again */
16931fc28d8eSLiu Bo 	level = btrfs_header_level(b);
16941fc28d8eSLiu Bo 
16951fc28d8eSLiu Bo out:
1696120de408SJosef Bacik 	/*
1697120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1698120de408SJosef Bacik 	 * longer valid, return an error in this case.
1699120de408SJosef Bacik 	 */
1700120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1701120de408SJosef Bacik 		if (root_lock)
1702120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1703120de408SJosef Bacik 		free_extent_buffer(b);
1704120de408SJosef Bacik 		return ERR_PTR(-EIO);
1705120de408SJosef Bacik 	}
1706120de408SJosef Bacik 
17071fc28d8eSLiu Bo 	p->nodes[level] = b;
17081fc28d8eSLiu Bo 	if (!p->skip_locking)
17091fc28d8eSLiu Bo 		p->locks[level] = root_lock;
17101fc28d8eSLiu Bo 	/*
17111fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
17121fc28d8eSLiu Bo 	 */
17131fc28d8eSLiu Bo 	return b;
17141fc28d8eSLiu Bo }
17151fc28d8eSLiu Bo 
1716d96b3424SFilipe Manana /*
1717d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1718d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1719d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1720d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1721d96b3424SFilipe Manana  * reallocated in the next transaction.
1722d96b3424SFilipe Manana  *
1723d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1724d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1725d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1726d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1727d96b3424SFilipe Manana  */
1728d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1729d96b3424SFilipe Manana {
1730d96b3424SFilipe Manana 	const int i = path->lowest_level;
1731d96b3424SFilipe Manana 	const int slot = path->slots[i];
1732d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1733d96b3424SFilipe Manana 	struct extent_buffer *clone;
1734d96b3424SFilipe Manana 
1735d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1736d96b3424SFilipe Manana 
1737d96b3424SFilipe Manana 	if (!lowest)
1738d96b3424SFilipe Manana 		return 0;
1739d96b3424SFilipe Manana 
1740d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1741d96b3424SFilipe Manana 
1742d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1743d96b3424SFilipe Manana 	if (!clone)
1744d96b3424SFilipe Manana 		return -ENOMEM;
1745d96b3424SFilipe Manana 
1746d96b3424SFilipe Manana 	btrfs_release_path(path);
1747d96b3424SFilipe Manana 	path->nodes[i] = clone;
1748d96b3424SFilipe Manana 	path->slots[i] = slot;
1749d96b3424SFilipe Manana 
1750d96b3424SFilipe Manana 	return 0;
1751d96b3424SFilipe Manana }
17521fc28d8eSLiu Bo 
1753e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1754e2e58d0fSFilipe Manana 				      int search_low_slot,
1755e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1756e2e58d0fSFilipe Manana 				      int prev_cmp,
1757e2e58d0fSFilipe Manana 				      int *slot)
1758e2e58d0fSFilipe Manana {
1759e2e58d0fSFilipe Manana 	/*
1760e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1761e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1762e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1763e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1764e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1765e2e58d0fSFilipe Manana 	 */
1766e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1767e2e58d0fSFilipe Manana 		*slot = 0;
1768e2e58d0fSFilipe Manana 		return 0;
1769e2e58d0fSFilipe Manana 	}
1770e2e58d0fSFilipe Manana 
1771e2e58d0fSFilipe Manana 	return generic_bin_search(eb, search_low_slot, key, slot);
1772e2e58d0fSFilipe Manana }
1773e2e58d0fSFilipe Manana 
1774109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1775109324cfSFilipe Manana 		       struct btrfs_root *root,
1776109324cfSFilipe Manana 		       const struct btrfs_key *key,
1777109324cfSFilipe Manana 		       struct btrfs_path *path,
1778109324cfSFilipe Manana 		       int ins_len,
1779109324cfSFilipe Manana 		       int prev_cmp)
1780109324cfSFilipe Manana {
1781109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
1782109324cfSFilipe Manana 	int leaf_free_space = -1;
1783109324cfSFilipe Manana 	int search_low_slot = 0;
1784109324cfSFilipe Manana 	int ret;
1785109324cfSFilipe Manana 	bool do_bin_search = true;
1786109324cfSFilipe Manana 
1787109324cfSFilipe Manana 	/*
1788109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
1789109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
1790109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
1791109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1792109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
1793109324cfSFilipe Manana 	 */
1794109324cfSFilipe Manana 	if (ins_len > 0) {
1795109324cfSFilipe Manana 		/*
1796109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
1797109324cfSFilipe Manana 		 * will not change until then.
1798109324cfSFilipe Manana 		 */
1799109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
1800109324cfSFilipe Manana 
1801109324cfSFilipe Manana 		/*
1802109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
1803109324cfSFilipe Manana 		 * the root of the tree.
1804109324cfSFilipe Manana 		 */
1805109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
1806109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
1807109324cfSFilipe Manana 
1808109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
1809109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
1810109324cfSFilipe Manana 
1811109324cfSFilipe Manana 			/*
1812109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
1813109324cfSFilipe Manana 			 * taking into account that the first key is very likely
1814109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
1815109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
1816109324cfSFilipe Manana 			 * the header's level field.
1817109324cfSFilipe Manana 			 */
1818109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
1819109324cfSFilipe Manana 			if (ret < 0) {
1820109324cfSFilipe Manana 				/*
1821109324cfSFilipe Manana 				 * The first key is smaller than the key we want
1822109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
1823109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
1824109324cfSFilipe Manana 				 *
1825109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
1826109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
1827109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
1828109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
1829109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
1830109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
1831109324cfSFilipe Manana 				 */
1832109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
1833109324cfSFilipe Manana 				search_low_slot = 1;
1834109324cfSFilipe Manana 			} else {
1835109324cfSFilipe Manana 				/*
1836109324cfSFilipe Manana 				 * The first key is >= then the key we want to
1837109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
1838109324cfSFilipe Manana 				 * the target key will be at slot 0.
1839109324cfSFilipe Manana 				 *
1840109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
1841109324cfSFilipe Manana 				 * less than the first key, because we will need
1842109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
1843109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
1844109324cfSFilipe Manana 				 * If the key matches the first key, then we can
1845109324cfSFilipe Manana 				 * unlock all the upper nodes, using
1846109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
1847109324cfSFilipe Manana 				 * as stated above.
1848109324cfSFilipe Manana 				 */
1849109324cfSFilipe Manana 				if (ret == 0)
1850109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
1851109324cfSFilipe Manana 				/*
1852109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
1853109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
1854109324cfSFilipe Manana 				 * to adjust it.
1855109324cfSFilipe Manana 				 */
1856109324cfSFilipe Manana 				do_bin_search = false;
1857109324cfSFilipe Manana 				path->slots[0] = 0;
1858109324cfSFilipe Manana 			}
1859109324cfSFilipe Manana 		}
1860109324cfSFilipe Manana 	}
1861109324cfSFilipe Manana 
1862109324cfSFilipe Manana 	if (do_bin_search) {
1863109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
1864109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
1865109324cfSFilipe Manana 		if (ret < 0)
1866109324cfSFilipe Manana 			return ret;
1867109324cfSFilipe Manana 	}
1868109324cfSFilipe Manana 
1869109324cfSFilipe Manana 	if (ins_len > 0) {
1870109324cfSFilipe Manana 		/*
1871109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
1872109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
1873109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
1874109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
1875109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
1876109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
1877109324cfSFilipe Manana 		 * check will be correct.
1878109324cfSFilipe Manana 		 */
1879109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
1880109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
1881109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
1882109324cfSFilipe Manana 		}
1883109324cfSFilipe Manana 
1884109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
1885109324cfSFilipe Manana 
1886109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
1887109324cfSFilipe Manana 			int err;
1888109324cfSFilipe Manana 
1889109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
1890109324cfSFilipe Manana 					 (ret == 0));
1891bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
1892bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
1893bb8e9a60SFilipe Manana 				err = -EUCLEAN;
1894109324cfSFilipe Manana 			if (err)
1895109324cfSFilipe Manana 				ret = err;
1896109324cfSFilipe Manana 		}
1897109324cfSFilipe Manana 	}
1898109324cfSFilipe Manana 
1899109324cfSFilipe Manana 	return ret;
1900109324cfSFilipe Manana }
1901109324cfSFilipe Manana 
1902c8c42864SChris Mason /*
19034271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
19044271eceaSNikolay Borisov  * modifications to preserve tree invariants.
190574123bd7SChris Mason  *
19064271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
19074271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
19084271eceaSNikolay Borisov  * @root:	The root node of the tree
19094271eceaSNikolay Borisov  * @key:	The key we are looking for
19109a664971Sethanwu  * @ins_len:	Indicates purpose of search:
19119a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
19129a664971Sethanwu  *              <0  for deletions
19139a664971Sethanwu  *               0  for plain searches, not modifying the tree
19149a664971Sethanwu  *
19159a664971Sethanwu  *              (*) If size of item inserted doesn't include
19169a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
19179a664971Sethanwu  *              be set.
19184271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
19194271eceaSNikolay Borisov  *		when modifying the tree.
192097571fd0SChris Mason  *
19214271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
19224271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
19234271eceaSNikolay Borisov  *
19244271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
19254271eceaSNikolay Borisov  * of the path (level 0)
19264271eceaSNikolay Borisov  *
19274271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
19284271eceaSNikolay Borisov  * points to the slot where it should be inserted
19294271eceaSNikolay Borisov  *
19304271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
19314271eceaSNikolay Borisov  * is returned
193274123bd7SChris Mason  */
1933310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1934310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
1935310712b2SOmar Sandoval 		      int ins_len, int cow)
1936be0e5c09SChris Mason {
1937d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
19385f39d397SChris Mason 	struct extent_buffer *b;
1939be0e5c09SChris Mason 	int slot;
1940be0e5c09SChris Mason 	int ret;
194133c66f43SYan Zheng 	int err;
1942be0e5c09SChris Mason 	int level;
1943925baeddSChris Mason 	int lowest_unlock = 1;
1944bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
1945bd681513SChris Mason 	int write_lock_level = 0;
19469f3a7427SChris Mason 	u8 lowest_level = 0;
1947f7c79f30SChris Mason 	int min_write_lock_level;
1948d7396f07SFilipe David Borba Manana 	int prev_cmp;
19499f3a7427SChris Mason 
19506702ed49SChris Mason 	lowest_level = p->lowest_level;
1951323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
195222b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
1953eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
195425179201SJosef Bacik 
1955857bc13fSJosef Bacik 	/*
1956857bc13fSJosef Bacik 	 * For now only allow nowait for read only operations.  There's no
1957857bc13fSJosef Bacik 	 * strict reason why we can't, we just only need it for reads so it's
1958857bc13fSJosef Bacik 	 * only implemented for reads.
1959857bc13fSJosef Bacik 	 */
1960857bc13fSJosef Bacik 	ASSERT(!p->nowait || !cow);
1961857bc13fSJosef Bacik 
1962bd681513SChris Mason 	if (ins_len < 0) {
1963925baeddSChris Mason 		lowest_unlock = 2;
196465b51a00SChris Mason 
1965bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
1966bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
1967bd681513SChris Mason 		 * for those levels as well
1968bd681513SChris Mason 		 */
1969bd681513SChris Mason 		write_lock_level = 2;
1970bd681513SChris Mason 	} else if (ins_len > 0) {
1971bd681513SChris Mason 		/*
1972bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
1973bd681513SChris Mason 		 * level 1 so we can update keys
1974bd681513SChris Mason 		 */
1975bd681513SChris Mason 		write_lock_level = 1;
1976bd681513SChris Mason 	}
1977bd681513SChris Mason 
1978bd681513SChris Mason 	if (!cow)
1979bd681513SChris Mason 		write_lock_level = -1;
1980bd681513SChris Mason 
198109a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
1982bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
1983bd681513SChris Mason 
1984f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
1985f7c79f30SChris Mason 
1986d96b3424SFilipe Manana 	if (p->need_commit_sem) {
1987d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
1988857bc13fSJosef Bacik 		if (p->nowait) {
1989857bc13fSJosef Bacik 			if (!down_read_trylock(&fs_info->commit_root_sem))
1990857bc13fSJosef Bacik 				return -EAGAIN;
1991857bc13fSJosef Bacik 		} else {
1992d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
1993d96b3424SFilipe Manana 		}
1994857bc13fSJosef Bacik 	}
1995d96b3424SFilipe Manana 
1996bb803951SChris Mason again:
1997d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
19981fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
1999be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2000be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2001be6821f8SFilipe Manana 		goto done;
2002be6821f8SFilipe Manana 	}
2003925baeddSChris Mason 
2004eb60ceacSChris Mason 	while (b) {
2005f624d976SQu Wenruo 		int dec = 0;
2006f624d976SQu Wenruo 
20075f39d397SChris Mason 		level = btrfs_header_level(b);
200865b51a00SChris Mason 
200902217ed2SChris Mason 		if (cow) {
20109ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
20119ea2c7c9SNikolay Borisov 
2012c8c42864SChris Mason 			/*
2013c8c42864SChris Mason 			 * if we don't really need to cow this block
2014c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2015c8c42864SChris Mason 			 * so we test it here
2016c8c42864SChris Mason 			 */
20175963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
201865b51a00SChris Mason 				goto cow_done;
20195d4f98a2SYan Zheng 
2020bd681513SChris Mason 			/*
2021bd681513SChris Mason 			 * must have write locks on this node and the
2022bd681513SChris Mason 			 * parent
2023bd681513SChris Mason 			 */
20245124e00eSJosef Bacik 			if (level > write_lock_level ||
20255124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
20265124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
20275124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2028bd681513SChris Mason 				write_lock_level = level + 1;
2029bd681513SChris Mason 				btrfs_release_path(p);
2030bd681513SChris Mason 				goto again;
2031bd681513SChris Mason 			}
2032bd681513SChris Mason 
20339ea2c7c9SNikolay Borisov 			if (last_level)
20349ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
20359631e4ccSJosef Bacik 						      &b,
20369631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
20379ea2c7c9SNikolay Borisov 			else
203833c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2039e20d96d6SChris Mason 						      p->nodes[level + 1],
20409631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
20419631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
204233c66f43SYan Zheng 			if (err) {
204333c66f43SYan Zheng 				ret = err;
204465b51a00SChris Mason 				goto done;
204554aa1f4dSChris Mason 			}
204602217ed2SChris Mason 		}
204765b51a00SChris Mason cow_done:
2048eb60ceacSChris Mason 		p->nodes[level] = b;
2049b4ce94deSChris Mason 
2050b4ce94deSChris Mason 		/*
2051b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2052b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2053b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2054b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2055b4ce94deSChris Mason 		 *
2056eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2057eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2058eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2059eb653de1SFilipe David Borba Manana 		 * we're operating on.
2060b4ce94deSChris Mason 		 */
2061eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2062eb653de1SFilipe David Borba Manana 			int u = level + 1;
2063eb653de1SFilipe David Borba Manana 
2064eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2065eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2066eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2067eb653de1SFilipe David Borba Manana 			}
2068eb653de1SFilipe David Borba Manana 		}
2069b4ce94deSChris Mason 
2070e2e58d0fSFilipe Manana 		if (level == 0) {
2071109324cfSFilipe Manana 			if (ins_len > 0)
2072e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
2073bd681513SChris Mason 
2074109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2075459931ecSChris Mason 			if (!p->search_for_split)
2076f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
20774b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
207865b51a00SChris Mason 			goto done;
207965b51a00SChris Mason 		}
2080e2e58d0fSFilipe Manana 
2081e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2082e2e58d0fSFilipe Manana 		if (ret < 0)
2083e2e58d0fSFilipe Manana 			goto done;
2084e2e58d0fSFilipe Manana 		prev_cmp = ret;
2085e2e58d0fSFilipe Manana 
2086f624d976SQu Wenruo 		if (ret && slot > 0) {
2087f624d976SQu Wenruo 			dec = 1;
2088f624d976SQu Wenruo 			slot--;
2089f624d976SQu Wenruo 		}
2090f624d976SQu Wenruo 		p->slots[level] = slot;
2091f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2092f624d976SQu Wenruo 					     &write_lock_level);
2093f624d976SQu Wenruo 		if (err == -EAGAIN)
2094f624d976SQu Wenruo 			goto again;
2095f624d976SQu Wenruo 		if (err) {
2096f624d976SQu Wenruo 			ret = err;
2097f624d976SQu Wenruo 			goto done;
2098f624d976SQu Wenruo 		}
2099f624d976SQu Wenruo 		b = p->nodes[level];
2100f624d976SQu Wenruo 		slot = p->slots[level];
2101f624d976SQu Wenruo 
2102f624d976SQu Wenruo 		/*
2103f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2104f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2105f624d976SQu Wenruo 		 * the parent
2106f624d976SQu Wenruo 		 */
2107f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2108f624d976SQu Wenruo 			write_lock_level = level + 1;
2109f624d976SQu Wenruo 			btrfs_release_path(p);
2110f624d976SQu Wenruo 			goto again;
2111f624d976SQu Wenruo 		}
2112f624d976SQu Wenruo 
2113f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2114f624d976SQu Wenruo 			  &write_lock_level);
2115f624d976SQu Wenruo 
2116f624d976SQu Wenruo 		if (level == lowest_level) {
2117f624d976SQu Wenruo 			if (dec)
2118f624d976SQu Wenruo 				p->slots[level]++;
2119f624d976SQu Wenruo 			goto done;
2120f624d976SQu Wenruo 		}
2121f624d976SQu Wenruo 
2122f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2123f624d976SQu Wenruo 		if (err == -EAGAIN)
2124f624d976SQu Wenruo 			goto again;
2125f624d976SQu Wenruo 		if (err) {
2126f624d976SQu Wenruo 			ret = err;
2127f624d976SQu Wenruo 			goto done;
2128f624d976SQu Wenruo 		}
2129f624d976SQu Wenruo 
2130f624d976SQu Wenruo 		if (!p->skip_locking) {
2131f624d976SQu Wenruo 			level = btrfs_header_level(b);
2132b40130b2SJosef Bacik 
2133b40130b2SJosef Bacik 			btrfs_maybe_reset_lockdep_class(root, b);
2134b40130b2SJosef Bacik 
2135f624d976SQu Wenruo 			if (level <= write_lock_level) {
2136f624d976SQu Wenruo 				btrfs_tree_lock(b);
2137f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2138f624d976SQu Wenruo 			} else {
2139857bc13fSJosef Bacik 				if (p->nowait) {
2140857bc13fSJosef Bacik 					if (!btrfs_try_tree_read_lock(b)) {
2141857bc13fSJosef Bacik 						free_extent_buffer(b);
2142857bc13fSJosef Bacik 						ret = -EAGAIN;
2143857bc13fSJosef Bacik 						goto done;
2144857bc13fSJosef Bacik 					}
2145857bc13fSJosef Bacik 				} else {
2146fe596ca3SJosef Bacik 					btrfs_tree_read_lock(b);
2147857bc13fSJosef Bacik 				}
2148f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2149f624d976SQu Wenruo 			}
2150f624d976SQu Wenruo 			p->nodes[level] = b;
2151f624d976SQu Wenruo 		}
215265b51a00SChris Mason 	}
215365b51a00SChris Mason 	ret = 1;
215465b51a00SChris Mason done:
21555f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2156b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2157d96b3424SFilipe Manana 
2158d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2159d96b3424SFilipe Manana 		int ret2;
2160d96b3424SFilipe Manana 
2161d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2162d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2163d96b3424SFilipe Manana 		if (ret2)
2164d96b3424SFilipe Manana 			ret = ret2;
2165d96b3424SFilipe Manana 	}
2166d96b3424SFilipe Manana 
2167be0e5c09SChris Mason 	return ret;
2168be0e5c09SChris Mason }
2169f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2170be0e5c09SChris Mason 
217174123bd7SChris Mason /*
21725d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
21735d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
21745d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
21755d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
21765d9e75c4SJan Schmidt  *
21775d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
21785d9e75c4SJan Schmidt  *
21795d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
21805d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
21815d9e75c4SJan Schmidt  */
2182310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
21835d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
21845d9e75c4SJan Schmidt {
21850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
21865d9e75c4SJan Schmidt 	struct extent_buffer *b;
21875d9e75c4SJan Schmidt 	int slot;
21885d9e75c4SJan Schmidt 	int ret;
21895d9e75c4SJan Schmidt 	int err;
21905d9e75c4SJan Schmidt 	int level;
21915d9e75c4SJan Schmidt 	int lowest_unlock = 1;
21925d9e75c4SJan Schmidt 	u8 lowest_level = 0;
21935d9e75c4SJan Schmidt 
21945d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
21955d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
2196c922b016SStefan Roesch 	ASSERT(!p->nowait);
21975d9e75c4SJan Schmidt 
21985d9e75c4SJan Schmidt 	if (p->search_commit_root) {
21995d9e75c4SJan Schmidt 		BUG_ON(time_seq);
22005d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
22015d9e75c4SJan Schmidt 	}
22025d9e75c4SJan Schmidt 
22035d9e75c4SJan Schmidt again:
2204f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2205315bed43SNikolay Borisov 	if (!b) {
2206315bed43SNikolay Borisov 		ret = -EIO;
2207315bed43SNikolay Borisov 		goto done;
2208315bed43SNikolay Borisov 	}
22095d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
22105d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
22115d9e75c4SJan Schmidt 
22125d9e75c4SJan Schmidt 	while (b) {
2213abe9339dSQu Wenruo 		int dec = 0;
2214abe9339dSQu Wenruo 
22155d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
22165d9e75c4SJan Schmidt 		p->nodes[level] = b;
22175d9e75c4SJan Schmidt 
22185d9e75c4SJan Schmidt 		/*
22195d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
22205d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
22215d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
22225d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
22235d9e75c4SJan Schmidt 		 */
22245d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
22255d9e75c4SJan Schmidt 
2226995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
2227cbca7d59SFilipe Manana 		if (ret < 0)
2228cbca7d59SFilipe Manana 			goto done;
22295d9e75c4SJan Schmidt 
2230abe9339dSQu Wenruo 		if (level == 0) {
2231abe9339dSQu Wenruo 			p->slots[level] = slot;
2232abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2233abe9339dSQu Wenruo 			goto done;
2234abe9339dSQu Wenruo 		}
2235abe9339dSQu Wenruo 
22365d9e75c4SJan Schmidt 		if (ret && slot > 0) {
22375d9e75c4SJan Schmidt 			dec = 1;
2238abe9339dSQu Wenruo 			slot--;
22395d9e75c4SJan Schmidt 		}
22405d9e75c4SJan Schmidt 		p->slots[level] = slot;
22415d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
22425d9e75c4SJan Schmidt 
22435d9e75c4SJan Schmidt 		if (level == lowest_level) {
22445d9e75c4SJan Schmidt 			if (dec)
22455d9e75c4SJan Schmidt 				p->slots[level]++;
22465d9e75c4SJan Schmidt 			goto done;
22475d9e75c4SJan Schmidt 		}
22485d9e75c4SJan Schmidt 
2249abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
22505d9e75c4SJan Schmidt 		if (err == -EAGAIN)
22515d9e75c4SJan Schmidt 			goto again;
22525d9e75c4SJan Schmidt 		if (err) {
22535d9e75c4SJan Schmidt 			ret = err;
22545d9e75c4SJan Schmidt 			goto done;
22555d9e75c4SJan Schmidt 		}
22565d9e75c4SJan Schmidt 
22575d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
22585d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2259f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2260db7f3436SJosef Bacik 		if (!b) {
2261db7f3436SJosef Bacik 			ret = -ENOMEM;
2262db7f3436SJosef Bacik 			goto done;
2263db7f3436SJosef Bacik 		}
22645d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
22655d9e75c4SJan Schmidt 		p->nodes[level] = b;
22665d9e75c4SJan Schmidt 	}
22675d9e75c4SJan Schmidt 	ret = 1;
22685d9e75c4SJan Schmidt done:
22695d9e75c4SJan Schmidt 	if (ret < 0)
22705d9e75c4SJan Schmidt 		btrfs_release_path(p);
22715d9e75c4SJan Schmidt 
22725d9e75c4SJan Schmidt 	return ret;
22735d9e75c4SJan Schmidt }
22745d9e75c4SJan Schmidt 
22755d9e75c4SJan Schmidt /*
22762f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
22772f38b3e1SArne Jansen  * instead the next or previous item should be returned.
22782f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
22792f38b3e1SArne Jansen  * otherwise.
22802f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
22812f38b3e1SArne Jansen  * return the next lower instead.
22822f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
22832f38b3e1SArne Jansen  * return the next higher instead.
22842f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
22852f38b3e1SArne Jansen  * < 0 on error
22862f38b3e1SArne Jansen  */
22872f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2288310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2289310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2290310712b2SOmar Sandoval 			       int return_any)
22912f38b3e1SArne Jansen {
22922f38b3e1SArne Jansen 	int ret;
22932f38b3e1SArne Jansen 	struct extent_buffer *leaf;
22942f38b3e1SArne Jansen 
22952f38b3e1SArne Jansen again:
22962f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
22972f38b3e1SArne Jansen 	if (ret <= 0)
22982f38b3e1SArne Jansen 		return ret;
22992f38b3e1SArne Jansen 	/*
23002f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
23012f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
23022f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
23032f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
23042f38b3e1SArne Jansen 	 * item.
23052f38b3e1SArne Jansen 	 */
23062f38b3e1SArne Jansen 	leaf = p->nodes[0];
23072f38b3e1SArne Jansen 
23082f38b3e1SArne Jansen 	if (find_higher) {
23092f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
23102f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
23112f38b3e1SArne Jansen 			if (ret <= 0)
23122f38b3e1SArne Jansen 				return ret;
23132f38b3e1SArne Jansen 			if (!return_any)
23142f38b3e1SArne Jansen 				return 1;
23152f38b3e1SArne Jansen 			/*
23162f38b3e1SArne Jansen 			 * no higher item found, return the next
23172f38b3e1SArne Jansen 			 * lower instead
23182f38b3e1SArne Jansen 			 */
23192f38b3e1SArne Jansen 			return_any = 0;
23202f38b3e1SArne Jansen 			find_higher = 0;
23212f38b3e1SArne Jansen 			btrfs_release_path(p);
23222f38b3e1SArne Jansen 			goto again;
23232f38b3e1SArne Jansen 		}
23242f38b3e1SArne Jansen 	} else {
23252f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
23262f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2327e6793769SArne Jansen 			if (ret < 0)
23282f38b3e1SArne Jansen 				return ret;
2329e6793769SArne Jansen 			if (!ret) {
233023c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
233123c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
233223c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2333e6793769SArne Jansen 				return 0;
2334e6793769SArne Jansen 			}
23352f38b3e1SArne Jansen 			if (!return_any)
23362f38b3e1SArne Jansen 				return 1;
23372f38b3e1SArne Jansen 			/*
23382f38b3e1SArne Jansen 			 * no lower item found, return the next
23392f38b3e1SArne Jansen 			 * higher instead
23402f38b3e1SArne Jansen 			 */
23412f38b3e1SArne Jansen 			return_any = 0;
23422f38b3e1SArne Jansen 			find_higher = 1;
23432f38b3e1SArne Jansen 			btrfs_release_path(p);
23442f38b3e1SArne Jansen 			goto again;
2345e6793769SArne Jansen 		} else {
23462f38b3e1SArne Jansen 			--p->slots[0];
23472f38b3e1SArne Jansen 		}
23482f38b3e1SArne Jansen 	}
23492f38b3e1SArne Jansen 	return 0;
23502f38b3e1SArne Jansen }
23512f38b3e1SArne Jansen 
23522f38b3e1SArne Jansen /*
23530ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
23540ff40a91SMarcos Paulo de Souza  * was not found.
23550ff40a91SMarcos Paulo de Souza  *
23560ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
23570ff40a91SMarcos Paulo de Souza  */
23580ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
23590ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
23600ff40a91SMarcos Paulo de Souza {
23610ff40a91SMarcos Paulo de Souza 	int ret;
23620ff40a91SMarcos Paulo de Souza 
23630ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
23640ff40a91SMarcos Paulo de Souza 	if (ret > 0)
23650ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
23660ff40a91SMarcos Paulo de Souza 
23670ff40a91SMarcos Paulo de Souza 	if (ret == 0)
23680ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
23690ff40a91SMarcos Paulo de Souza 
23700ff40a91SMarcos Paulo de Souza 	return ret;
23710ff40a91SMarcos Paulo de Souza }
23720ff40a91SMarcos Paulo de Souza 
237343dd529aSDavid Sterba /*
237462142be3SGabriel Niebler  * Search for a valid slot for the given path.
237562142be3SGabriel Niebler  *
237662142be3SGabriel Niebler  * @root:	The root node of the tree.
237762142be3SGabriel Niebler  * @key:	Will contain a valid item if found.
237862142be3SGabriel Niebler  * @path:	The starting point to validate the slot.
237962142be3SGabriel Niebler  *
238062142be3SGabriel Niebler  * Return: 0  if the item is valid
238162142be3SGabriel Niebler  *         1  if not found
238262142be3SGabriel Niebler  *         <0 if error.
238362142be3SGabriel Niebler  */
238462142be3SGabriel Niebler int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
238562142be3SGabriel Niebler 			      struct btrfs_path *path)
238662142be3SGabriel Niebler {
238762142be3SGabriel Niebler 	while (1) {
238862142be3SGabriel Niebler 		int ret;
238962142be3SGabriel Niebler 		const int slot = path->slots[0];
239062142be3SGabriel Niebler 		const struct extent_buffer *leaf = path->nodes[0];
239162142be3SGabriel Niebler 
239262142be3SGabriel Niebler 		/* This is where we start walking the path. */
239362142be3SGabriel Niebler 		if (slot >= btrfs_header_nritems(leaf)) {
239462142be3SGabriel Niebler 			/*
239562142be3SGabriel Niebler 			 * If we've reached the last slot in this leaf we need
239662142be3SGabriel Niebler 			 * to go to the next leaf and reset the path.
239762142be3SGabriel Niebler 			 */
239862142be3SGabriel Niebler 			ret = btrfs_next_leaf(root, path);
239962142be3SGabriel Niebler 			if (ret)
240062142be3SGabriel Niebler 				return ret;
240162142be3SGabriel Niebler 			continue;
240262142be3SGabriel Niebler 		}
240362142be3SGabriel Niebler 		/* Store the found, valid item in @key. */
240462142be3SGabriel Niebler 		btrfs_item_key_to_cpu(leaf, key, slot);
240562142be3SGabriel Niebler 		break;
240662142be3SGabriel Niebler 	}
240762142be3SGabriel Niebler 	return 0;
240862142be3SGabriel Niebler }
240962142be3SGabriel Niebler 
24100ff40a91SMarcos Paulo de Souza /*
241174123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
241274123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
241374123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
241474123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
241574123bd7SChris Mason  * higher levels
2416aa5d6bedSChris Mason  *
241774123bd7SChris Mason  */
2418b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
24195f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2420be0e5c09SChris Mason {
2421be0e5c09SChris Mason 	int i;
24225f39d397SChris Mason 	struct extent_buffer *t;
24230e82bcfeSDavid Sterba 	int ret;
24245f39d397SChris Mason 
2425234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2426be0e5c09SChris Mason 		int tslot = path->slots[i];
24270e82bcfeSDavid Sterba 
2428eb60ceacSChris Mason 		if (!path->nodes[i])
2429be0e5c09SChris Mason 			break;
24305f39d397SChris Mason 		t = path->nodes[i];
2431f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
243233cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
24330e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
24345f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2435d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2436be0e5c09SChris Mason 		if (tslot != 0)
2437be0e5c09SChris Mason 			break;
2438be0e5c09SChris Mason 	}
2439be0e5c09SChris Mason }
2440be0e5c09SChris Mason 
244174123bd7SChris Mason /*
244231840ae1SZheng Yan  * update item key.
244331840ae1SZheng Yan  *
244431840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
244531840ae1SZheng Yan  * that the new key won't break the order
244631840ae1SZheng Yan  */
2447b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2448b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2449310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
245031840ae1SZheng Yan {
245131840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
245231840ae1SZheng Yan 	struct extent_buffer *eb;
245331840ae1SZheng Yan 	int slot;
245431840ae1SZheng Yan 
245531840ae1SZheng Yan 	eb = path->nodes[0];
245631840ae1SZheng Yan 	slot = path->slots[0];
245731840ae1SZheng Yan 	if (slot > 0) {
245831840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
24597c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
24607c15d410SQu Wenruo 			btrfs_crit(fs_info,
24617c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
24627c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
24637c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
24647c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
24657c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
24667c15d410SQu Wenruo 				   new_key->offset);
24677c15d410SQu Wenruo 			btrfs_print_leaf(eb);
24687c15d410SQu Wenruo 			BUG();
24697c15d410SQu Wenruo 		}
247031840ae1SZheng Yan 	}
247131840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
247231840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
24737c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
24747c15d410SQu Wenruo 			btrfs_crit(fs_info,
24757c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
24767c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
24777c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
24787c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
24797c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
24807c15d410SQu Wenruo 				   new_key->offset);
24817c15d410SQu Wenruo 			btrfs_print_leaf(eb);
24827c15d410SQu Wenruo 			BUG();
24837c15d410SQu Wenruo 		}
248431840ae1SZheng Yan 	}
248531840ae1SZheng Yan 
248631840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
248731840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
248831840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
248931840ae1SZheng Yan 	if (slot == 0)
2490b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
249131840ae1SZheng Yan }
249231840ae1SZheng Yan 
249331840ae1SZheng Yan /*
2494d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2495d16c702fSQu Wenruo  *
2496d16c702fSQu Wenruo  * Return true if something is wrong.
2497d16c702fSQu Wenruo  * Return false if everything is fine.
2498d16c702fSQu Wenruo  *
2499d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2500d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2501d16c702fSQu Wenruo  *
2502d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2503d16c702fSQu Wenruo  * --------------------------------------------------------------
2504d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2505d16c702fSQu Wenruo  *
2506d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2507d16c702fSQu Wenruo  * key in leaf @right is 7.
2508d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2509d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2510d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2511d16c702fSQu Wenruo  * key of @right.
2512d16c702fSQu Wenruo  */
2513d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2514d16c702fSQu Wenruo 			       struct extent_buffer *right)
2515d16c702fSQu Wenruo {
2516d16c702fSQu Wenruo 	struct btrfs_key left_last;
2517d16c702fSQu Wenruo 	struct btrfs_key right_first;
2518d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2519d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2520d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2521d16c702fSQu Wenruo 
2522d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2523d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2524d16c702fSQu Wenruo 		return false;
2525d16c702fSQu Wenruo 
2526d16c702fSQu Wenruo 	if (level) {
2527d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2528d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2529d16c702fSQu Wenruo 	} else {
2530d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2531d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2532d16c702fSQu Wenruo 	}
2533d16c702fSQu Wenruo 
2534d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2535d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2536d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2537d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2538d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2539d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2540d16c702fSQu Wenruo 		return true;
2541d16c702fSQu Wenruo 	}
2542d16c702fSQu Wenruo 	return false;
2543d16c702fSQu Wenruo }
2544d16c702fSQu Wenruo 
2545d16c702fSQu Wenruo /*
254674123bd7SChris Mason  * try to push data from one node into the next node left in the
254779f95c82SChris Mason  * tree.
2548aa5d6bedSChris Mason  *
2549aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2550aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
255174123bd7SChris Mason  */
255298ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
25532ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2554971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2555be0e5c09SChris Mason {
2556d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2557be0e5c09SChris Mason 	int push_items = 0;
2558bb803951SChris Mason 	int src_nritems;
2559bb803951SChris Mason 	int dst_nritems;
2560aa5d6bedSChris Mason 	int ret = 0;
2561be0e5c09SChris Mason 
25625f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
25635f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
25640b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
25657bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
25667bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
256754aa1f4dSChris Mason 
2568bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2569971a1f66SChris Mason 		return 1;
2570971a1f66SChris Mason 
2571d397712bSChris Mason 	if (push_items <= 0)
2572be0e5c09SChris Mason 		return 1;
2573be0e5c09SChris Mason 
2574bce4eae9SChris Mason 	if (empty) {
2575971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2576bce4eae9SChris Mason 		if (push_items < src_nritems) {
2577bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2578bce4eae9SChris Mason 			 * we aren't going to empty it
2579bce4eae9SChris Mason 			 */
2580bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2581bce4eae9SChris Mason 				if (push_items <= 8)
2582bce4eae9SChris Mason 					return 1;
2583bce4eae9SChris Mason 				push_items -= 8;
2584bce4eae9SChris Mason 			}
2585bce4eae9SChris Mason 		}
2586bce4eae9SChris Mason 	} else
2587bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
258879f95c82SChris Mason 
2589d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2590d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2591d16c702fSQu Wenruo 		ret = -EUCLEAN;
2592d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2593d16c702fSQu Wenruo 		return ret;
2594d16c702fSQu Wenruo 	}
2595f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
25965de865eeSFilipe David Borba Manana 	if (ret) {
259766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
25985de865eeSFilipe David Borba Manana 		return ret;
25995de865eeSFilipe David Borba Manana 	}
26005f39d397SChris Mason 	copy_extent_buffer(dst, src,
26015f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
26025f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2603123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
26045f39d397SChris Mason 
2605bb803951SChris Mason 	if (push_items < src_nritems) {
260657911b8bSJan Schmidt 		/*
2607f3a84ccdSFilipe Manana 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2608f3a84ccdSFilipe Manana 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
260957911b8bSJan Schmidt 		 */
26105f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
26115f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2612e2fa7227SChris Mason 				      (src_nritems - push_items) *
2613123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2614bb803951SChris Mason 	}
26155f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
26165f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
26175f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
26185f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
261931840ae1SZheng Yan 
2620bb803951SChris Mason 	return ret;
2621be0e5c09SChris Mason }
2622be0e5c09SChris Mason 
262397571fd0SChris Mason /*
262479f95c82SChris Mason  * try to push data from one node into the next node right in the
262579f95c82SChris Mason  * tree.
262679f95c82SChris Mason  *
262779f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
262879f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
262979f95c82SChris Mason  *
263079f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
263179f95c82SChris Mason  */
26325f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
26335f39d397SChris Mason 			      struct extent_buffer *dst,
26345f39d397SChris Mason 			      struct extent_buffer *src)
263579f95c82SChris Mason {
263655d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
263779f95c82SChris Mason 	int push_items = 0;
263879f95c82SChris Mason 	int max_push;
263979f95c82SChris Mason 	int src_nritems;
264079f95c82SChris Mason 	int dst_nritems;
264179f95c82SChris Mason 	int ret = 0;
264279f95c82SChris Mason 
26437bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
26447bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
26457bb86316SChris Mason 
26465f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
26475f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
26480b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2649d397712bSChris Mason 	if (push_items <= 0)
265079f95c82SChris Mason 		return 1;
2651bce4eae9SChris Mason 
2652d397712bSChris Mason 	if (src_nritems < 4)
2653bce4eae9SChris Mason 		return 1;
265479f95c82SChris Mason 
265579f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
265679f95c82SChris Mason 	/* don't try to empty the node */
2657d397712bSChris Mason 	if (max_push >= src_nritems)
265879f95c82SChris Mason 		return 1;
2659252c38f0SYan 
266079f95c82SChris Mason 	if (max_push < push_items)
266179f95c82SChris Mason 		push_items = max_push;
266279f95c82SChris Mason 
2663d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2664d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2665d16c702fSQu Wenruo 		ret = -EUCLEAN;
2666d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2667d16c702fSQu Wenruo 		return ret;
2668d16c702fSQu Wenruo 	}
2669f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2670bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
26715f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
26725f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
26735f39d397SChris Mason 				      (dst_nritems) *
26745f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2675d6025579SChris Mason 
2676f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2677ed874f0dSDavid Sterba 					 push_items);
26785de865eeSFilipe David Borba Manana 	if (ret) {
267966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
26805de865eeSFilipe David Borba Manana 		return ret;
26815de865eeSFilipe David Borba Manana 	}
26825f39d397SChris Mason 	copy_extent_buffer(dst, src,
26835f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
26845f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2685123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
268679f95c82SChris Mason 
26875f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
26885f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
268979f95c82SChris Mason 
26905f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
26915f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
269231840ae1SZheng Yan 
269379f95c82SChris Mason 	return ret;
269479f95c82SChris Mason }
269579f95c82SChris Mason 
269679f95c82SChris Mason /*
269797571fd0SChris Mason  * helper function to insert a new root level in the tree.
269897571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
269997571fd0SChris Mason  * point to the existing root
2700aa5d6bedSChris Mason  *
2701aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
270297571fd0SChris Mason  */
2703d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
27045f39d397SChris Mason 			   struct btrfs_root *root,
2705fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
270674123bd7SChris Mason {
27070b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
27087bb86316SChris Mason 	u64 lower_gen;
27095f39d397SChris Mason 	struct extent_buffer *lower;
27105f39d397SChris Mason 	struct extent_buffer *c;
2711925baeddSChris Mason 	struct extent_buffer *old;
27125f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2713d9d19a01SDavid Sterba 	int ret;
27145c680ed6SChris Mason 
27155c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
27165c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
27175c680ed6SChris Mason 
27187bb86316SChris Mason 	lower = path->nodes[level-1];
27197bb86316SChris Mason 	if (level == 1)
27207bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
27217bb86316SChris Mason 	else
27227bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
27237bb86316SChris Mason 
272479bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
272579bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2726cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
27275f39d397SChris Mason 	if (IS_ERR(c))
27285f39d397SChris Mason 		return PTR_ERR(c);
2729925baeddSChris Mason 
27300b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2731f0486c68SYan, Zheng 
27325f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
27335f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2734db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
27357bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
273631840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
27377bb86316SChris Mason 
27387bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
27395f39d397SChris Mason 
27405f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2741d5719762SChris Mason 
2742925baeddSChris Mason 	old = root->node;
2743406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2744d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2745240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2746925baeddSChris Mason 
2747925baeddSChris Mason 	/* the super has an extra ref to root->node */
2748925baeddSChris Mason 	free_extent_buffer(old);
2749925baeddSChris Mason 
27500b86a832SChris Mason 	add_root_to_dirty_list(root);
275167439dadSDavid Sterba 	atomic_inc(&c->refs);
27525f39d397SChris Mason 	path->nodes[level] = c;
2753ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
275474123bd7SChris Mason 	path->slots[level] = 0;
275574123bd7SChris Mason 	return 0;
275674123bd7SChris Mason }
27575c680ed6SChris Mason 
27585c680ed6SChris Mason /*
27595c680ed6SChris Mason  * worker function to insert a single pointer in a node.
27605c680ed6SChris Mason  * the node should have enough room for the pointer already
276197571fd0SChris Mason  *
27625c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
27635c680ed6SChris Mason  * blocknr is the block the key points to.
27645c680ed6SChris Mason  */
2765143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
27666ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2767143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2768c3e06965SJan Schmidt 		       int slot, int level)
27695c680ed6SChris Mason {
27705f39d397SChris Mason 	struct extent_buffer *lower;
27715c680ed6SChris Mason 	int nritems;
2772f3ea38daSJan Schmidt 	int ret;
27735c680ed6SChris Mason 
27745c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
277549d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
27765f39d397SChris Mason 	lower = path->nodes[level];
27775f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2778c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
27796ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
278074123bd7SChris Mason 	if (slot != nritems) {
2781bf1d3425SDavid Sterba 		if (level) {
2782f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2783f3a84ccdSFilipe Manana 					slot, nritems - slot);
2784bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2785bf1d3425SDavid Sterba 		}
27865f39d397SChris Mason 		memmove_extent_buffer(lower,
27875f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
27885f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
2789123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
279074123bd7SChris Mason 	}
2791c3e06965SJan Schmidt 	if (level) {
2792f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
279333cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_ADD);
2794f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2795f3ea38daSJan Schmidt 	}
27965f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2797db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
279874493f7aSChris Mason 	WARN_ON(trans->transid == 0);
279974493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
28005f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
28015f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
280274123bd7SChris Mason }
280374123bd7SChris Mason 
280497571fd0SChris Mason /*
280597571fd0SChris Mason  * split the node at the specified level in path in two.
280697571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
280797571fd0SChris Mason  *
280897571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
280997571fd0SChris Mason  * left and right, if either one works, it returns right away.
2810aa5d6bedSChris Mason  *
2811aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
281297571fd0SChris Mason  */
2813e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
2814e02119d5SChris Mason 			       struct btrfs_root *root,
2815e02119d5SChris Mason 			       struct btrfs_path *path, int level)
2816be0e5c09SChris Mason {
28170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
28185f39d397SChris Mason 	struct extent_buffer *c;
28195f39d397SChris Mason 	struct extent_buffer *split;
28205f39d397SChris Mason 	struct btrfs_disk_key disk_key;
2821be0e5c09SChris Mason 	int mid;
28225c680ed6SChris Mason 	int ret;
28237518a238SChris Mason 	u32 c_nritems;
2824be0e5c09SChris Mason 
28255f39d397SChris Mason 	c = path->nodes[level];
28267bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
28275f39d397SChris Mason 	if (c == root->node) {
2828d9abbf1cSJan Schmidt 		/*
282990f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
283090f8d62eSJan Schmidt 		 *
2831fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
283290f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
283390f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
2834f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2835f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
2836f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
2837d9abbf1cSJan Schmidt 		 */
2838fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
28395c680ed6SChris Mason 		if (ret)
28405c680ed6SChris Mason 			return ret;
2841b3612421SChris Mason 	} else {
2842e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
28435f39d397SChris Mason 		c = path->nodes[level];
28445f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
28450b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2846e66f709bSChris Mason 			return 0;
284754aa1f4dSChris Mason 		if (ret < 0)
284854aa1f4dSChris Mason 			return ret;
28495c680ed6SChris Mason 	}
2850e66f709bSChris Mason 
28515f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
28525d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
28535d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
28547bb86316SChris Mason 
285579bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
285679bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
285779bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
28585f39d397SChris Mason 	if (IS_ERR(split))
28595f39d397SChris Mason 		return PTR_ERR(split);
286054aa1f4dSChris Mason 
28610b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2862bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
28635f39d397SChris Mason 
2864f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
28655de865eeSFilipe David Borba Manana 	if (ret) {
286666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
28675de865eeSFilipe David Borba Manana 		return ret;
28685de865eeSFilipe David Borba Manana 	}
28695f39d397SChris Mason 	copy_extent_buffer(split, c,
28705f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
28715f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
2872123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
28735f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
28745f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
2875aa5d6bedSChris Mason 
28765f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
28775f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
28785f39d397SChris Mason 
28796ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
2880c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
2881aa5d6bedSChris Mason 
28825de08d7dSChris Mason 	if (path->slots[level] >= mid) {
28835c680ed6SChris Mason 		path->slots[level] -= mid;
2884925baeddSChris Mason 		btrfs_tree_unlock(c);
28855f39d397SChris Mason 		free_extent_buffer(c);
28865f39d397SChris Mason 		path->nodes[level] = split;
28875c680ed6SChris Mason 		path->slots[level + 1] += 1;
2888eb60ceacSChris Mason 	} else {
2889925baeddSChris Mason 		btrfs_tree_unlock(split);
28905f39d397SChris Mason 		free_extent_buffer(split);
2891be0e5c09SChris Mason 	}
2892d5286a92SNikolay Borisov 	return 0;
2893be0e5c09SChris Mason }
2894be0e5c09SChris Mason 
289574123bd7SChris Mason /*
289674123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
289774123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
289874123bd7SChris Mason  * space used both by the item structs and the item data
289974123bd7SChris Mason  */
29005f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2901be0e5c09SChris Mason {
2902be0e5c09SChris Mason 	int data_len;
29035f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
2904d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
2905be0e5c09SChris Mason 
2906be0e5c09SChris Mason 	if (!nr)
2907be0e5c09SChris Mason 		return 0;
29083212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
29093212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
29100783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
2911d4dbff95SChris Mason 	WARN_ON(data_len < 0);
2912be0e5c09SChris Mason 	return data_len;
2913be0e5c09SChris Mason }
2914be0e5c09SChris Mason 
291574123bd7SChris Mason /*
2916d4dbff95SChris Mason  * The space between the end of the leaf items and
2917d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
2918d4dbff95SChris Mason  * the leaf has left for both items and data
2919d4dbff95SChris Mason  */
2920e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
2921d4dbff95SChris Mason {
2922e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
29235f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
29245f39d397SChris Mason 	int ret;
29250b246afaSJeff Mahoney 
29260b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
29275f39d397SChris Mason 	if (ret < 0) {
29280b246afaSJeff Mahoney 		btrfs_crit(fs_info,
2929efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2930da17066cSJeff Mahoney 			   ret,
29310b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
29325f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
29335f39d397SChris Mason 	}
29345f39d397SChris Mason 	return ret;
2935d4dbff95SChris Mason }
2936d4dbff95SChris Mason 
293799d8f83cSChris Mason /*
293899d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
293999d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
294099d8f83cSChris Mason  */
2941f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
294244871b1bSChris Mason 				      int data_size, int empty,
294344871b1bSChris Mason 				      struct extent_buffer *right,
294499d8f83cSChris Mason 				      int free_space, u32 left_nritems,
294599d8f83cSChris Mason 				      u32 min_slot)
294600ec4c51SChris Mason {
2947f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
29485f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
294944871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
2950cfed81a0SChris Mason 	struct btrfs_map_token token;
29515f39d397SChris Mason 	struct btrfs_disk_key disk_key;
295200ec4c51SChris Mason 	int slot;
295334a38218SChris Mason 	u32 i;
295400ec4c51SChris Mason 	int push_space = 0;
295500ec4c51SChris Mason 	int push_items = 0;
295634a38218SChris Mason 	u32 nr;
29577518a238SChris Mason 	u32 right_nritems;
29585f39d397SChris Mason 	u32 data_end;
2959db94535dSChris Mason 	u32 this_item_size;
296000ec4c51SChris Mason 
296134a38218SChris Mason 	if (empty)
296234a38218SChris Mason 		nr = 0;
296334a38218SChris Mason 	else
296499d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
296534a38218SChris Mason 
296631840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
296787b29b20SYan Zheng 		push_space += data_size;
296831840ae1SZheng Yan 
296944871b1bSChris Mason 	slot = path->slots[1];
297034a38218SChris Mason 	i = left_nritems - 1;
297134a38218SChris Mason 	while (i >= nr) {
297231840ae1SZheng Yan 		if (!empty && push_items > 0) {
297331840ae1SZheng Yan 			if (path->slots[0] > i)
297431840ae1SZheng Yan 				break;
297531840ae1SZheng Yan 			if (path->slots[0] == i) {
2976e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
2977e902baacSDavid Sterba 
297831840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
297931840ae1SZheng Yan 					break;
298031840ae1SZheng Yan 			}
298131840ae1SZheng Yan 		}
298231840ae1SZheng Yan 
298300ec4c51SChris Mason 		if (path->slots[0] == i)
298487b29b20SYan Zheng 			push_space += data_size;
2985db94535dSChris Mason 
29863212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
298774794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
298874794207SJosef Bacik 		    push_space > free_space)
298900ec4c51SChris Mason 			break;
299031840ae1SZheng Yan 
299100ec4c51SChris Mason 		push_items++;
299274794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
299334a38218SChris Mason 		if (i == 0)
299434a38218SChris Mason 			break;
299534a38218SChris Mason 		i--;
2996db94535dSChris Mason 	}
29975f39d397SChris Mason 
2998925baeddSChris Mason 	if (push_items == 0)
2999925baeddSChris Mason 		goto out_unlock;
30005f39d397SChris Mason 
30016c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
30025f39d397SChris Mason 
300300ec4c51SChris Mason 	/* push left to right */
30045f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
300534a38218SChris Mason 
3006dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
30078f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
30085f39d397SChris Mason 
300900ec4c51SChris Mason 	/* make room in the right data area */
30108f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
30115f39d397SChris Mason 	memmove_extent_buffer(right,
30123d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
30133d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
30140b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
30155f39d397SChris Mason 
301600ec4c51SChris Mason 	/* copy from the left data area */
30173d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
30180b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
30198f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3020d6025579SChris Mason 		     push_space);
30215f39d397SChris Mason 
30225f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
30235f39d397SChris Mason 			      btrfs_item_nr_offset(0),
30240783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
30255f39d397SChris Mason 
302600ec4c51SChris Mason 	/* copy the items from left to right */
30275f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
30285f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
30290783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
303000ec4c51SChris Mason 
303100ec4c51SChris Mason 	/* update the item pointers */
3032c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
30337518a238SChris Mason 	right_nritems += push_items;
30345f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
30350b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
30367518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
30373212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
30383212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3039db94535dSChris Mason 	}
3040db94535dSChris Mason 
30417518a238SChris Mason 	left_nritems -= push_items;
30425f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
304300ec4c51SChris Mason 
304434a38218SChris Mason 	if (left_nritems)
30455f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3046f0486c68SYan, Zheng 	else
30476a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3048f0486c68SYan, Zheng 
30495f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3050a429e513SChris Mason 
30515f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
30525f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3053d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
305402217ed2SChris Mason 
305500ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
30567518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
30577518a238SChris Mason 		path->slots[0] -= left_nritems;
3058925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
30596a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3060925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
30615f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
30625f39d397SChris Mason 		path->nodes[0] = right;
306300ec4c51SChris Mason 		path->slots[1] += 1;
306400ec4c51SChris Mason 	} else {
3065925baeddSChris Mason 		btrfs_tree_unlock(right);
30665f39d397SChris Mason 		free_extent_buffer(right);
306700ec4c51SChris Mason 	}
306800ec4c51SChris Mason 	return 0;
3069925baeddSChris Mason 
3070925baeddSChris Mason out_unlock:
3071925baeddSChris Mason 	btrfs_tree_unlock(right);
3072925baeddSChris Mason 	free_extent_buffer(right);
3073925baeddSChris Mason 	return 1;
307400ec4c51SChris Mason }
3075925baeddSChris Mason 
307600ec4c51SChris Mason /*
307744871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
307874123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
307944871b1bSChris Mason  *
308044871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
308144871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
308299d8f83cSChris Mason  *
308399d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
308499d8f83cSChris Mason  * push any slot lower than min_slot
308574123bd7SChris Mason  */
308644871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
308799d8f83cSChris Mason 			   *root, struct btrfs_path *path,
308899d8f83cSChris Mason 			   int min_data_size, int data_size,
308999d8f83cSChris Mason 			   int empty, u32 min_slot)
3090be0e5c09SChris Mason {
309144871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
309244871b1bSChris Mason 	struct extent_buffer *right;
309344871b1bSChris Mason 	struct extent_buffer *upper;
309444871b1bSChris Mason 	int slot;
309544871b1bSChris Mason 	int free_space;
309644871b1bSChris Mason 	u32 left_nritems;
309744871b1bSChris Mason 	int ret;
309844871b1bSChris Mason 
309944871b1bSChris Mason 	if (!path->nodes[1])
310044871b1bSChris Mason 		return 1;
310144871b1bSChris Mason 
310244871b1bSChris Mason 	slot = path->slots[1];
310344871b1bSChris Mason 	upper = path->nodes[1];
310444871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
310544871b1bSChris Mason 		return 1;
310644871b1bSChris Mason 
310749d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
310844871b1bSChris Mason 
31094b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3110fb770ae4SLiu Bo 	/*
3111fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3112fb770ae4SLiu Bo 	 * no big deal, just return.
3113fb770ae4SLiu Bo 	 */
3114fb770ae4SLiu Bo 	if (IS_ERR(right))
311591ca338dSTsutomu Itoh 		return 1;
311691ca338dSTsutomu Itoh 
3117bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
311844871b1bSChris Mason 
3119e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
312044871b1bSChris Mason 	if (free_space < data_size)
312144871b1bSChris Mason 		goto out_unlock;
312244871b1bSChris Mason 
312344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3124bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
312544871b1bSChris Mason 	if (ret)
312644871b1bSChris Mason 		goto out_unlock;
312744871b1bSChris Mason 
312844871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
312944871b1bSChris Mason 	if (left_nritems == 0)
313044871b1bSChris Mason 		goto out_unlock;
313144871b1bSChris Mason 
3132d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3133d16c702fSQu Wenruo 		ret = -EUCLEAN;
3134d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3135d16c702fSQu Wenruo 		free_extent_buffer(right);
3136d16c702fSQu Wenruo 		return ret;
3137d16c702fSQu Wenruo 	}
31382ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
31392ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
31402ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
31412ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
314252042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
31432ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
31442ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
31452ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
31462ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
31472ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
31482ef1fed2SFilipe David Borba Manana 		return 0;
31492ef1fed2SFilipe David Borba Manana 	}
31502ef1fed2SFilipe David Borba Manana 
3151f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
315299d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
315344871b1bSChris Mason out_unlock:
315444871b1bSChris Mason 	btrfs_tree_unlock(right);
315544871b1bSChris Mason 	free_extent_buffer(right);
315644871b1bSChris Mason 	return 1;
315744871b1bSChris Mason }
315844871b1bSChris Mason 
315944871b1bSChris Mason /*
316044871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
316144871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
316299d8f83cSChris Mason  *
316399d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
316499d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
316599d8f83cSChris Mason  * items
316644871b1bSChris Mason  */
31678087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
316844871b1bSChris Mason 				     int empty, struct extent_buffer *left,
316999d8f83cSChris Mason 				     int free_space, u32 right_nritems,
317099d8f83cSChris Mason 				     u32 max_slot)
317144871b1bSChris Mason {
31728087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
31735f39d397SChris Mason 	struct btrfs_disk_key disk_key;
31745f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3175be0e5c09SChris Mason 	int i;
3176be0e5c09SChris Mason 	int push_space = 0;
3177be0e5c09SChris Mason 	int push_items = 0;
31787518a238SChris Mason 	u32 old_left_nritems;
317934a38218SChris Mason 	u32 nr;
3180aa5d6bedSChris Mason 	int ret = 0;
3181db94535dSChris Mason 	u32 this_item_size;
3182db94535dSChris Mason 	u32 old_left_item_size;
3183cfed81a0SChris Mason 	struct btrfs_map_token token;
3184cfed81a0SChris Mason 
318534a38218SChris Mason 	if (empty)
318699d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
318734a38218SChris Mason 	else
318899d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
318934a38218SChris Mason 
319034a38218SChris Mason 	for (i = 0; i < nr; i++) {
319131840ae1SZheng Yan 		if (!empty && push_items > 0) {
319231840ae1SZheng Yan 			if (path->slots[0] < i)
319331840ae1SZheng Yan 				break;
319431840ae1SZheng Yan 			if (path->slots[0] == i) {
3195e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3196e902baacSDavid Sterba 
319731840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
319831840ae1SZheng Yan 					break;
319931840ae1SZheng Yan 			}
320031840ae1SZheng Yan 		}
320131840ae1SZheng Yan 
3202be0e5c09SChris Mason 		if (path->slots[0] == i)
320387b29b20SYan Zheng 			push_space += data_size;
3204db94535dSChris Mason 
32053212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
320674794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
320774794207SJosef Bacik 		    free_space)
3208be0e5c09SChris Mason 			break;
3209db94535dSChris Mason 
3210be0e5c09SChris Mason 		push_items++;
321174794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3212be0e5c09SChris Mason 	}
3213db94535dSChris Mason 
3214be0e5c09SChris Mason 	if (push_items == 0) {
3215925baeddSChris Mason 		ret = 1;
3216925baeddSChris Mason 		goto out;
3217be0e5c09SChris Mason 	}
3218fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
32195f39d397SChris Mason 
3220be0e5c09SChris Mason 	/* push data from right to left */
32215f39d397SChris Mason 	copy_extent_buffer(left, right,
32225f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
32235f39d397SChris Mason 			   btrfs_item_nr_offset(0),
32245f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
32255f39d397SChris Mason 
32260b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
32273212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
32285f39d397SChris Mason 
32293d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
32308f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
32313d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
32323212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1),
3233be0e5c09SChris Mason 		     push_space);
32345f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
323587b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3236eb60ceacSChris Mason 
3237c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
32383212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3239be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
32405f39d397SChris Mason 		u32 ioff;
3241db94535dSChris Mason 
32423212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
32433212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3244cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3245be0e5c09SChris Mason 	}
32465f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3247be0e5c09SChris Mason 
3248be0e5c09SChris Mason 	/* fixup right node */
324931b1a2bdSJulia Lawall 	if (push_items > right_nritems)
325031b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3251d397712bSChris Mason 		       right_nritems);
325234a38218SChris Mason 
325334a38218SChris Mason 	if (push_items < right_nritems) {
32543212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
32558f881e8cSDavid Sterba 						  leaf_data_end(right);
32563d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
32570b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
32583d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
32598f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
32605f39d397SChris Mason 
32615f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
32625f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
32635f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
32640783fcfcSChris Mason 			     sizeof(struct btrfs_item));
326534a38218SChris Mason 	}
3266c82f823cSDavid Sterba 
3267c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3268eef1c494SYan 	right_nritems -= push_items;
3269eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
32700b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
32715f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
32723212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
32733212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3274db94535dSChris Mason 	}
3275eb60ceacSChris Mason 
32765f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
327734a38218SChris Mason 	if (right_nritems)
32785f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3279f0486c68SYan, Zheng 	else
32806a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3281098f59c2SChris Mason 
32825f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3283b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3284be0e5c09SChris Mason 
3285be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3286be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3287be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3288925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32895f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32905f39d397SChris Mason 		path->nodes[0] = left;
3291be0e5c09SChris Mason 		path->slots[1] -= 1;
3292be0e5c09SChris Mason 	} else {
3293925baeddSChris Mason 		btrfs_tree_unlock(left);
32945f39d397SChris Mason 		free_extent_buffer(left);
3295be0e5c09SChris Mason 		path->slots[0] -= push_items;
3296be0e5c09SChris Mason 	}
3297eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3298aa5d6bedSChris Mason 	return ret;
3299925baeddSChris Mason out:
3300925baeddSChris Mason 	btrfs_tree_unlock(left);
3301925baeddSChris Mason 	free_extent_buffer(left);
3302925baeddSChris Mason 	return ret;
3303be0e5c09SChris Mason }
3304be0e5c09SChris Mason 
330574123bd7SChris Mason /*
330644871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
330744871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
330899d8f83cSChris Mason  *
330999d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
331099d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
331199d8f83cSChris Mason  * items
331244871b1bSChris Mason  */
331344871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
331499d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
331599d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
331644871b1bSChris Mason {
331744871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
331844871b1bSChris Mason 	struct extent_buffer *left;
331944871b1bSChris Mason 	int slot;
332044871b1bSChris Mason 	int free_space;
332144871b1bSChris Mason 	u32 right_nritems;
332244871b1bSChris Mason 	int ret = 0;
332344871b1bSChris Mason 
332444871b1bSChris Mason 	slot = path->slots[1];
332544871b1bSChris Mason 	if (slot == 0)
332644871b1bSChris Mason 		return 1;
332744871b1bSChris Mason 	if (!path->nodes[1])
332844871b1bSChris Mason 		return 1;
332944871b1bSChris Mason 
333044871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
333144871b1bSChris Mason 	if (right_nritems == 0)
333244871b1bSChris Mason 		return 1;
333344871b1bSChris Mason 
333449d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
333544871b1bSChris Mason 
33364b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3337fb770ae4SLiu Bo 	/*
3338fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3339fb770ae4SLiu Bo 	 * no big deal, just return.
3340fb770ae4SLiu Bo 	 */
3341fb770ae4SLiu Bo 	if (IS_ERR(left))
334291ca338dSTsutomu Itoh 		return 1;
334391ca338dSTsutomu Itoh 
3344bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
334544871b1bSChris Mason 
3346e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
334744871b1bSChris Mason 	if (free_space < data_size) {
334844871b1bSChris Mason 		ret = 1;
334944871b1bSChris Mason 		goto out;
335044871b1bSChris Mason 	}
335144871b1bSChris Mason 
335244871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
33539631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3354bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
335544871b1bSChris Mason 	if (ret) {
335644871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
335779787eaaSJeff Mahoney 		if (ret == -ENOSPC)
335844871b1bSChris Mason 			ret = 1;
335944871b1bSChris Mason 		goto out;
336044871b1bSChris Mason 	}
336144871b1bSChris Mason 
3362d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3363d16c702fSQu Wenruo 		ret = -EUCLEAN;
3364d16c702fSQu Wenruo 		goto out;
3365d16c702fSQu Wenruo 	}
33668087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
336799d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
336899d8f83cSChris Mason 			       max_slot);
336944871b1bSChris Mason out:
337044871b1bSChris Mason 	btrfs_tree_unlock(left);
337144871b1bSChris Mason 	free_extent_buffer(left);
337244871b1bSChris Mason 	return ret;
337344871b1bSChris Mason }
337444871b1bSChris Mason 
337544871b1bSChris Mason /*
337674123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
337774123bd7SChris Mason  * available for the resulting leaf level of the path.
337874123bd7SChris Mason  */
3379143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
338044871b1bSChris Mason 				    struct btrfs_path *path,
338144871b1bSChris Mason 				    struct extent_buffer *l,
338244871b1bSChris Mason 				    struct extent_buffer *right,
338344871b1bSChris Mason 				    int slot, int mid, int nritems)
3384be0e5c09SChris Mason {
338594f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3386be0e5c09SChris Mason 	int data_copy_size;
3387be0e5c09SChris Mason 	int rt_data_off;
3388be0e5c09SChris Mason 	int i;
3389d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3390cfed81a0SChris Mason 	struct btrfs_map_token token;
3391cfed81a0SChris Mason 
33925f39d397SChris Mason 	nritems = nritems - mid;
33935f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3394dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
33955f39d397SChris Mason 
33965f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
33975f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
33985f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
33995f39d397SChris Mason 
34005f39d397SChris Mason 	copy_extent_buffer(right, l,
34013d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
34023d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
34038f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
340474123bd7SChris Mason 
3405dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
34065f39d397SChris Mason 
3407c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
34085f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3409db94535dSChris Mason 		u32 ioff;
3410db94535dSChris Mason 
34113212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
34123212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
34130783fcfcSChris Mason 	}
341474123bd7SChris Mason 
34155f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
34165f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
34176ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
34185f39d397SChris Mason 
34195f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
34205f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3421eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
34225f39d397SChris Mason 
3423be0e5c09SChris Mason 	if (mid <= slot) {
3424925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
34255f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
34265f39d397SChris Mason 		path->nodes[0] = right;
3427be0e5c09SChris Mason 		path->slots[0] -= mid;
3428be0e5c09SChris Mason 		path->slots[1] += 1;
3429925baeddSChris Mason 	} else {
3430925baeddSChris Mason 		btrfs_tree_unlock(right);
34315f39d397SChris Mason 		free_extent_buffer(right);
3432925baeddSChris Mason 	}
34335f39d397SChris Mason 
3434eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
343544871b1bSChris Mason }
343644871b1bSChris Mason 
343744871b1bSChris Mason /*
343899d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
343999d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
344099d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
344199d8f83cSChris Mason  *          A                 B                 C
344299d8f83cSChris Mason  *
344399d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
344499d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
344599d8f83cSChris Mason  * completely.
344699d8f83cSChris Mason  */
344799d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
344899d8f83cSChris Mason 					  struct btrfs_root *root,
344999d8f83cSChris Mason 					  struct btrfs_path *path,
345099d8f83cSChris Mason 					  int data_size)
345199d8f83cSChris Mason {
345299d8f83cSChris Mason 	int ret;
345399d8f83cSChris Mason 	int progress = 0;
345499d8f83cSChris Mason 	int slot;
345599d8f83cSChris Mason 	u32 nritems;
34565a4267caSFilipe David Borba Manana 	int space_needed = data_size;
345799d8f83cSChris Mason 
345899d8f83cSChris Mason 	slot = path->slots[0];
34595a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3460e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
346199d8f83cSChris Mason 
346299d8f83cSChris Mason 	/*
346399d8f83cSChris Mason 	 * try to push all the items after our slot into the
346499d8f83cSChris Mason 	 * right leaf
346599d8f83cSChris Mason 	 */
34665a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
346799d8f83cSChris Mason 	if (ret < 0)
346899d8f83cSChris Mason 		return ret;
346999d8f83cSChris Mason 
347099d8f83cSChris Mason 	if (ret == 0)
347199d8f83cSChris Mason 		progress++;
347299d8f83cSChris Mason 
347399d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
347499d8f83cSChris Mason 	/*
347599d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
347699d8f83cSChris Mason 	 * we've done so we're done
347799d8f83cSChris Mason 	 */
347899d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
347999d8f83cSChris Mason 		return 0;
348099d8f83cSChris Mason 
3481e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
348299d8f83cSChris Mason 		return 0;
348399d8f83cSChris Mason 
348499d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
348599d8f83cSChris Mason 	slot = path->slots[0];
3486263d3995SFilipe Manana 	space_needed = data_size;
3487263d3995SFilipe Manana 	if (slot > 0)
3488e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
34895a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
349099d8f83cSChris Mason 	if (ret < 0)
349199d8f83cSChris Mason 		return ret;
349299d8f83cSChris Mason 
349399d8f83cSChris Mason 	if (ret == 0)
349499d8f83cSChris Mason 		progress++;
349599d8f83cSChris Mason 
349699d8f83cSChris Mason 	if (progress)
349799d8f83cSChris Mason 		return 0;
349899d8f83cSChris Mason 	return 1;
349999d8f83cSChris Mason }
350099d8f83cSChris Mason 
350199d8f83cSChris Mason /*
350244871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
350344871b1bSChris Mason  * available for the resulting leaf level of the path.
350444871b1bSChris Mason  *
350544871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
350644871b1bSChris Mason  */
350744871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
350844871b1bSChris Mason 			       struct btrfs_root *root,
3509310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
351044871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
351144871b1bSChris Mason 			       int extend)
351244871b1bSChris Mason {
35135d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
351444871b1bSChris Mason 	struct extent_buffer *l;
351544871b1bSChris Mason 	u32 nritems;
351644871b1bSChris Mason 	int mid;
351744871b1bSChris Mason 	int slot;
351844871b1bSChris Mason 	struct extent_buffer *right;
3519b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
352044871b1bSChris Mason 	int ret = 0;
352144871b1bSChris Mason 	int wret;
35225d4f98a2SYan Zheng 	int split;
352344871b1bSChris Mason 	int num_doubles = 0;
352499d8f83cSChris Mason 	int tried_avoid_double = 0;
352544871b1bSChris Mason 
3526a5719521SYan, Zheng 	l = path->nodes[0];
3527a5719521SYan, Zheng 	slot = path->slots[0];
35283212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
35290b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3530a5719521SYan, Zheng 		return -EOVERFLOW;
3531a5719521SYan, Zheng 
353244871b1bSChris Mason 	/* first try to make some room by pushing left and right */
353333157e05SLiu Bo 	if (data_size && path->nodes[1]) {
35345a4267caSFilipe David Borba Manana 		int space_needed = data_size;
35355a4267caSFilipe David Borba Manana 
35365a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3537e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
35385a4267caSFilipe David Borba Manana 
35395a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
35405a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
354144871b1bSChris Mason 		if (wret < 0)
354244871b1bSChris Mason 			return wret;
354344871b1bSChris Mason 		if (wret) {
3544263d3995SFilipe Manana 			space_needed = data_size;
3545263d3995SFilipe Manana 			if (slot > 0)
3546e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
35475a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
35485a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
354944871b1bSChris Mason 			if (wret < 0)
355044871b1bSChris Mason 				return wret;
355144871b1bSChris Mason 		}
355244871b1bSChris Mason 		l = path->nodes[0];
355344871b1bSChris Mason 
355444871b1bSChris Mason 		/* did the pushes work? */
3555e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
355644871b1bSChris Mason 			return 0;
355744871b1bSChris Mason 	}
355844871b1bSChris Mason 
355944871b1bSChris Mason 	if (!path->nodes[1]) {
3560fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
356144871b1bSChris Mason 		if (ret)
356244871b1bSChris Mason 			return ret;
356344871b1bSChris Mason 	}
356444871b1bSChris Mason again:
35655d4f98a2SYan Zheng 	split = 1;
356644871b1bSChris Mason 	l = path->nodes[0];
356744871b1bSChris Mason 	slot = path->slots[0];
356844871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
356944871b1bSChris Mason 	mid = (nritems + 1) / 2;
357044871b1bSChris Mason 
35715d4f98a2SYan Zheng 	if (mid <= slot) {
35725d4f98a2SYan Zheng 		if (nritems == 1 ||
35735d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
35740b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
35755d4f98a2SYan Zheng 			if (slot >= nritems) {
35765d4f98a2SYan Zheng 				split = 0;
35775d4f98a2SYan Zheng 			} else {
35785d4f98a2SYan Zheng 				mid = slot;
35795d4f98a2SYan Zheng 				if (mid != nritems &&
35805d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
35810b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
358299d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
358399d8f83cSChris Mason 						goto push_for_double;
35845d4f98a2SYan Zheng 					split = 2;
35855d4f98a2SYan Zheng 				}
35865d4f98a2SYan Zheng 			}
35875d4f98a2SYan Zheng 		}
35885d4f98a2SYan Zheng 	} else {
35895d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
35900b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
35915d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
35925d4f98a2SYan Zheng 				split = 0;
35935d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
35945d4f98a2SYan Zheng 				mid = 1;
35955d4f98a2SYan Zheng 			} else {
35965d4f98a2SYan Zheng 				mid = slot;
35975d4f98a2SYan Zheng 				if (mid != nritems &&
35985d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
35990b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
360099d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
360199d8f83cSChris Mason 						goto push_for_double;
36025d4f98a2SYan Zheng 					split = 2;
36035d4f98a2SYan Zheng 				}
36045d4f98a2SYan Zheng 			}
36055d4f98a2SYan Zheng 		}
36065d4f98a2SYan Zheng 	}
36075d4f98a2SYan Zheng 
36085d4f98a2SYan Zheng 	if (split == 0)
36095d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
36105d4f98a2SYan Zheng 	else
36115d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
36125d4f98a2SYan Zheng 
3613ca9d473aSJosef Bacik 	/*
3614ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3615ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3616ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3617ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3618ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3619ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3620ca9d473aSJosef Bacik 	 */
362179bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
362279bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
362379bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3624ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3625f0486c68SYan, Zheng 	if (IS_ERR(right))
362644871b1bSChris Mason 		return PTR_ERR(right);
3627f0486c68SYan, Zheng 
36280b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
362944871b1bSChris Mason 
36305d4f98a2SYan Zheng 	if (split == 0) {
363144871b1bSChris Mason 		if (mid <= slot) {
363244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
36336ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
36342ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
363544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
363644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
363744871b1bSChris Mason 			path->nodes[0] = right;
363844871b1bSChris Mason 			path->slots[0] = 0;
363944871b1bSChris Mason 			path->slots[1] += 1;
364044871b1bSChris Mason 		} else {
364144871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
36426ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
36432ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
364444871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
364544871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
364644871b1bSChris Mason 			path->nodes[0] = right;
364744871b1bSChris Mason 			path->slots[0] = 0;
3648143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3649b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
36505d4f98a2SYan Zheng 		}
3651196e0249SLiu Bo 		/*
3652196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3653196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3654196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3655196e0249SLiu Bo 		 */
365644871b1bSChris Mason 		return ret;
365744871b1bSChris Mason 	}
365844871b1bSChris Mason 
365994f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
366044871b1bSChris Mason 
36615d4f98a2SYan Zheng 	if (split == 2) {
3662cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3663cc0c5538SChris Mason 		num_doubles++;
3664cc0c5538SChris Mason 		goto again;
36653326d1b0SChris Mason 	}
366644871b1bSChris Mason 
3667143bede5SJeff Mahoney 	return 0;
366899d8f83cSChris Mason 
366999d8f83cSChris Mason push_for_double:
367099d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
367199d8f83cSChris Mason 	tried_avoid_double = 1;
3672e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
367399d8f83cSChris Mason 		return 0;
367499d8f83cSChris Mason 	goto again;
3675be0e5c09SChris Mason }
3676be0e5c09SChris Mason 
3677ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3678ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3679ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3680ad48fd75SYan, Zheng {
3681ad48fd75SYan, Zheng 	struct btrfs_key key;
3682ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3683ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3684ad48fd75SYan, Zheng 	u64 extent_len = 0;
3685ad48fd75SYan, Zheng 	u32 item_size;
3686ad48fd75SYan, Zheng 	int ret;
3687ad48fd75SYan, Zheng 
3688ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3689ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3690ad48fd75SYan, Zheng 
3691ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3692ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3693ad48fd75SYan, Zheng 
3694e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3695ad48fd75SYan, Zheng 		return 0;
3696ad48fd75SYan, Zheng 
36973212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3698ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3699ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3700ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3701ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3702ad48fd75SYan, Zheng 	}
3703b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3704ad48fd75SYan, Zheng 
3705ad48fd75SYan, Zheng 	path->keep_locks = 1;
3706ad48fd75SYan, Zheng 	path->search_for_split = 1;
3707ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3708ad48fd75SYan, Zheng 	path->search_for_split = 0;
3709a8df6fe6SFilipe Manana 	if (ret > 0)
3710a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3711ad48fd75SYan, Zheng 	if (ret < 0)
3712ad48fd75SYan, Zheng 		goto err;
3713ad48fd75SYan, Zheng 
3714ad48fd75SYan, Zheng 	ret = -EAGAIN;
3715ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3716a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
37173212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3718ad48fd75SYan, Zheng 		goto err;
3719ad48fd75SYan, Zheng 
3720109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3721e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3722109f6aefSChris Mason 		goto err;
3723109f6aefSChris Mason 
3724ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3725ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3726ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3727ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3728ad48fd75SYan, Zheng 			goto err;
3729ad48fd75SYan, Zheng 	}
3730ad48fd75SYan, Zheng 
3731ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3732f0486c68SYan, Zheng 	if (ret)
3733f0486c68SYan, Zheng 		goto err;
3734ad48fd75SYan, Zheng 
3735ad48fd75SYan, Zheng 	path->keep_locks = 0;
3736ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3737ad48fd75SYan, Zheng 	return 0;
3738ad48fd75SYan, Zheng err:
3739ad48fd75SYan, Zheng 	path->keep_locks = 0;
3740ad48fd75SYan, Zheng 	return ret;
3741ad48fd75SYan, Zheng }
3742ad48fd75SYan, Zheng 
374325263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3744310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3745459931ecSChris Mason 			       unsigned long split_offset)
3746459931ecSChris Mason {
3747459931ecSChris Mason 	struct extent_buffer *leaf;
3748c91666b1SJosef Bacik 	int orig_slot, slot;
3749ad48fd75SYan, Zheng 	char *buf;
3750459931ecSChris Mason 	u32 nritems;
3751ad48fd75SYan, Zheng 	u32 item_size;
3752459931ecSChris Mason 	u32 orig_offset;
3753459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3754459931ecSChris Mason 
3755459931ecSChris Mason 	leaf = path->nodes[0];
3756e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3757b9473439SChris Mason 
3758c91666b1SJosef Bacik 	orig_slot = path->slots[0];
37593212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
37603212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3761459931ecSChris Mason 
3762459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3763ad48fd75SYan, Zheng 	if (!buf)
3764ad48fd75SYan, Zheng 		return -ENOMEM;
3765ad48fd75SYan, Zheng 
3766459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3767459931ecSChris Mason 			    path->slots[0]), item_size);
3768ad48fd75SYan, Zheng 
3769459931ecSChris Mason 	slot = path->slots[0] + 1;
3770459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3771459931ecSChris Mason 	if (slot != nritems) {
3772459931ecSChris Mason 		/* shift the items */
3773459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3774459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3775459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3776459931ecSChris Mason 	}
3777459931ecSChris Mason 
3778459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3779459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3780459931ecSChris Mason 
37813212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
37823212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3783459931ecSChris Mason 
37843212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
3785459931ecSChris Mason 				 orig_offset + item_size - split_offset);
37863212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3787459931ecSChris Mason 
3788459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3789459931ecSChris Mason 
3790459931ecSChris Mason 	/* write the data for the start of the original item */
3791459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3792459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3793459931ecSChris Mason 			    split_offset);
3794459931ecSChris Mason 
3795459931ecSChris Mason 	/* write the data for the new item */
3796459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3797459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3798459931ecSChris Mason 			    item_size - split_offset);
3799459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3800459931ecSChris Mason 
3801e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3802459931ecSChris Mason 	kfree(buf);
3803ad48fd75SYan, Zheng 	return 0;
3804ad48fd75SYan, Zheng }
3805ad48fd75SYan, Zheng 
3806ad48fd75SYan, Zheng /*
3807ad48fd75SYan, Zheng  * This function splits a single item into two items,
3808ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3809ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3810ad48fd75SYan, Zheng  *
3811ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3812ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3813ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3814ad48fd75SYan, Zheng  *
3815ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3816ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3817ad48fd75SYan, Zheng  *
3818ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3819ad48fd75SYan, Zheng  * leaf the entire time.
3820ad48fd75SYan, Zheng  */
3821ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3822ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3823ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3824310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3825ad48fd75SYan, Zheng 		     unsigned long split_offset)
3826ad48fd75SYan, Zheng {
3827ad48fd75SYan, Zheng 	int ret;
3828ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3829ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3830ad48fd75SYan, Zheng 	if (ret)
3831459931ecSChris Mason 		return ret;
3832ad48fd75SYan, Zheng 
383325263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3834ad48fd75SYan, Zheng 	return ret;
3835ad48fd75SYan, Zheng }
3836ad48fd75SYan, Zheng 
3837ad48fd75SYan, Zheng /*
3838d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
3839d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
3840d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
3841d352ac68SChris Mason  * the front.
3842d352ac68SChris Mason  */
384378ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3844b18c6685SChris Mason {
3845b18c6685SChris Mason 	int slot;
38465f39d397SChris Mason 	struct extent_buffer *leaf;
3847b18c6685SChris Mason 	u32 nritems;
3848b18c6685SChris Mason 	unsigned int data_end;
3849b18c6685SChris Mason 	unsigned int old_data_start;
3850b18c6685SChris Mason 	unsigned int old_size;
3851b18c6685SChris Mason 	unsigned int size_diff;
3852b18c6685SChris Mason 	int i;
3853cfed81a0SChris Mason 	struct btrfs_map_token token;
3854cfed81a0SChris Mason 
38555f39d397SChris Mason 	leaf = path->nodes[0];
3856179e29e4SChris Mason 	slot = path->slots[0];
3857179e29e4SChris Mason 
38583212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
3859179e29e4SChris Mason 	if (old_size == new_size)
3860143bede5SJeff Mahoney 		return;
3861b18c6685SChris Mason 
38625f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
38638f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3864b18c6685SChris Mason 
38653212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
3866179e29e4SChris Mason 
3867b18c6685SChris Mason 	size_diff = old_size - new_size;
3868b18c6685SChris Mason 
3869b18c6685SChris Mason 	BUG_ON(slot < 0);
3870b18c6685SChris Mason 	BUG_ON(slot >= nritems);
3871b18c6685SChris Mason 
3872b18c6685SChris Mason 	/*
3873b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3874b18c6685SChris Mason 	 */
3875b18c6685SChris Mason 	/* first correct the data pointers */
3876c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3877b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
38785f39d397SChris Mason 		u32 ioff;
3879db94535dSChris Mason 
38803212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
38813212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3882b18c6685SChris Mason 	}
3883db94535dSChris Mason 
3884b18c6685SChris Mason 	/* shift the data */
3885179e29e4SChris Mason 	if (from_end) {
38863d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
38873d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3888b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
3889179e29e4SChris Mason 	} else {
3890179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
3891179e29e4SChris Mason 		u64 offset;
3892179e29e4SChris Mason 
3893179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
3894179e29e4SChris Mason 
3895179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3896179e29e4SChris Mason 			unsigned long ptr;
3897179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
3898179e29e4SChris Mason 
3899179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
3900179e29e4SChris Mason 					    struct btrfs_file_extent_item);
3901179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
3902179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
3903179e29e4SChris Mason 
3904179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
3905179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
3906179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
3907179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
3908179e29e4SChris Mason 				      (unsigned long)fi,
39097ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
3910179e29e4SChris Mason 			}
3911179e29e4SChris Mason 		}
3912179e29e4SChris Mason 
39133d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
39143d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3915179e29e4SChris Mason 			      data_end, old_data_start - data_end);
3916179e29e4SChris Mason 
3917179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
3918179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3919179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
3920179e29e4SChris Mason 		if (slot == 0)
3921b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
3922179e29e4SChris Mason 	}
39235f39d397SChris Mason 
39243212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
39255f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3926b18c6685SChris Mason 
3927e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3928a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3929b18c6685SChris Mason 		BUG();
39305f39d397SChris Mason 	}
3931b18c6685SChris Mason }
3932b18c6685SChris Mason 
3933d352ac68SChris Mason /*
39348f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
3935d352ac68SChris Mason  */
3936c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
39376567e837SChris Mason {
39386567e837SChris Mason 	int slot;
39395f39d397SChris Mason 	struct extent_buffer *leaf;
39406567e837SChris Mason 	u32 nritems;
39416567e837SChris Mason 	unsigned int data_end;
39426567e837SChris Mason 	unsigned int old_data;
39436567e837SChris Mason 	unsigned int old_size;
39446567e837SChris Mason 	int i;
3945cfed81a0SChris Mason 	struct btrfs_map_token token;
3946cfed81a0SChris Mason 
39475f39d397SChris Mason 	leaf = path->nodes[0];
39486567e837SChris Mason 
39495f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
39508f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
39516567e837SChris Mason 
3952e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
3953a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39546567e837SChris Mason 		BUG();
39555f39d397SChris Mason 	}
39566567e837SChris Mason 	slot = path->slots[0];
3957dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
39586567e837SChris Mason 
39596567e837SChris Mason 	BUG_ON(slot < 0);
39603326d1b0SChris Mason 	if (slot >= nritems) {
3961a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3962c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
3963d397712bSChris Mason 			   slot, nritems);
3964290342f6SArnd Bergmann 		BUG();
39653326d1b0SChris Mason 	}
39666567e837SChris Mason 
39676567e837SChris Mason 	/*
39686567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
39696567e837SChris Mason 	 */
39706567e837SChris Mason 	/* first correct the data pointers */
3971c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
39726567e837SChris Mason 	for (i = slot; i < nritems; i++) {
39735f39d397SChris Mason 		u32 ioff;
3974db94535dSChris Mason 
39753212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
39763212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
39776567e837SChris Mason 	}
39785f39d397SChris Mason 
39796567e837SChris Mason 	/* shift the data */
39803d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
39813d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
39826567e837SChris Mason 		      data_end, old_data - data_end);
39835f39d397SChris Mason 
39846567e837SChris Mason 	data_end = old_data;
39853212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
39863212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
39875f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
39886567e837SChris Mason 
3989e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3990a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39916567e837SChris Mason 		BUG();
39925f39d397SChris Mason 	}
39936567e837SChris Mason }
39946567e837SChris Mason 
399543dd529aSDavid Sterba /*
399643dd529aSDavid Sterba  * Make space in the node before inserting one or more items.
3997da9ffb24SNikolay Borisov  *
3998da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
3999da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
4000b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
400143dd529aSDavid Sterba  *
400243dd529aSDavid Sterba  * Main purpose is to save stack depth by doing the bulk of the work in a
400343dd529aSDavid Sterba  * function that doesn't call btrfs_search_slot
400474123bd7SChris Mason  */
4005f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4006b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
4007be0e5c09SChris Mason {
40080b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
40099c58309dSChris Mason 	int i;
40107518a238SChris Mason 	u32 nritems;
4011be0e5c09SChris Mason 	unsigned int data_end;
4012e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
401344871b1bSChris Mason 	struct extent_buffer *leaf;
401444871b1bSChris Mason 	int slot;
4015cfed81a0SChris Mason 	struct btrfs_map_token token;
4016fc0d82e1SNikolay Borisov 	u32 total_size;
4017fc0d82e1SNikolay Borisov 
4018b7ef5f3aSFilipe Manana 	/*
4019b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
4020b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
4021b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
4022b7ef5f3aSFilipe Manana 	 */
402324cdc847SFilipe Manana 	if (path->slots[0] == 0) {
4024b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4025b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
402624cdc847SFilipe Manana 	}
402724cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
402824cdc847SFilipe Manana 
40295f39d397SChris Mason 	leaf = path->nodes[0];
403044871b1bSChris Mason 	slot = path->slots[0];
403174123bd7SChris Mason 
40325f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
40338f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4034b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4035eb60ceacSChris Mason 
4036e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4037a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
40380b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4039e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4040be0e5c09SChris Mason 		BUG();
4041d4dbff95SChris Mason 	}
40425f39d397SChris Mason 
4043c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4044be0e5c09SChris Mason 	if (slot != nritems) {
4045dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4046be0e5c09SChris Mason 
40475f39d397SChris Mason 		if (old_data < data_end) {
4048a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
40497269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
40507269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
40515f39d397SChris Mason 				   slot, old_data, data_end);
4052290342f6SArnd Bergmann 			BUG();
40535f39d397SChris Mason 		}
4054be0e5c09SChris Mason 		/*
4055be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4056be0e5c09SChris Mason 		 */
4057be0e5c09SChris Mason 		/* first correct the data pointers */
40580783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
40595f39d397SChris Mason 			u32 ioff;
4060db94535dSChris Mason 
40613212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
40623212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
4063b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
40640783fcfcSChris Mason 		}
4065be0e5c09SChris Mason 		/* shift the items */
4066b7ef5f3aSFilipe Manana 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + batch->nr),
40675f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
40680783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4069be0e5c09SChris Mason 
4070be0e5c09SChris Mason 		/* shift the data */
40713d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4072b7ef5f3aSFilipe Manana 				      data_end - batch->total_data_size,
4073b7ef5f3aSFilipe Manana 				      BTRFS_LEAF_DATA_OFFSET + data_end,
4074b7ef5f3aSFilipe Manana 				      old_data - data_end);
4075be0e5c09SChris Mason 		data_end = old_data;
4076be0e5c09SChris Mason 	}
40775f39d397SChris Mason 
407862e2749eSChris Mason 	/* setup the item for the new data */
4079b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
4080b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
40819c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4082b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
40833212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
40843212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
40859c58309dSChris Mason 	}
408644871b1bSChris Mason 
4087b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4088b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4089aa5d6bedSChris Mason 
4090e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4091a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4092be0e5c09SChris Mason 		BUG();
40935f39d397SChris Mason 	}
409444871b1bSChris Mason }
409544871b1bSChris Mason 
409644871b1bSChris Mason /*
4097f0641656SFilipe Manana  * Insert a new item into a leaf.
4098f0641656SFilipe Manana  *
4099f0641656SFilipe Manana  * @root:      The root of the btree.
4100f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
4101f0641656SFilipe Manana  * @key:       The key of the new item.
4102f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
4103f0641656SFilipe Manana  */
4104f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
4105f0641656SFilipe Manana 				 struct btrfs_path *path,
4106f0641656SFilipe Manana 				 const struct btrfs_key *key,
4107f0641656SFilipe Manana 				 u32 data_size)
4108f0641656SFilipe Manana {
4109f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4110f0641656SFilipe Manana 
4111f0641656SFilipe Manana 	batch.keys = key;
4112f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4113f0641656SFilipe Manana 	batch.total_data_size = data_size;
4114f0641656SFilipe Manana 	batch.nr = 1;
4115f0641656SFilipe Manana 
4116f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
4117f0641656SFilipe Manana }
4118f0641656SFilipe Manana 
4119f0641656SFilipe Manana /*
412044871b1bSChris Mason  * Given a key and some data, insert items into the tree.
412144871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
412244871b1bSChris Mason  */
412344871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
412444871b1bSChris Mason 			    struct btrfs_root *root,
412544871b1bSChris Mason 			    struct btrfs_path *path,
4126b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
412744871b1bSChris Mason {
412844871b1bSChris Mason 	int ret = 0;
412944871b1bSChris Mason 	int slot;
4130b7ef5f3aSFilipe Manana 	u32 total_size;
413144871b1bSChris Mason 
4132b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4133b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
413444871b1bSChris Mason 	if (ret == 0)
413544871b1bSChris Mason 		return -EEXIST;
413644871b1bSChris Mason 	if (ret < 0)
4137143bede5SJeff Mahoney 		return ret;
413844871b1bSChris Mason 
413944871b1bSChris Mason 	slot = path->slots[0];
414044871b1bSChris Mason 	BUG_ON(slot < 0);
414144871b1bSChris Mason 
4142b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4143143bede5SJeff Mahoney 	return 0;
414462e2749eSChris Mason }
414562e2749eSChris Mason 
414662e2749eSChris Mason /*
414762e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
414862e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
414962e2749eSChris Mason  */
4150310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4151310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4152310712b2SOmar Sandoval 		      u32 data_size)
415362e2749eSChris Mason {
415462e2749eSChris Mason 	int ret = 0;
41552c90e5d6SChris Mason 	struct btrfs_path *path;
41565f39d397SChris Mason 	struct extent_buffer *leaf;
41575f39d397SChris Mason 	unsigned long ptr;
415862e2749eSChris Mason 
41592c90e5d6SChris Mason 	path = btrfs_alloc_path();
4160db5b493aSTsutomu Itoh 	if (!path)
4161db5b493aSTsutomu Itoh 		return -ENOMEM;
41622c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
416362e2749eSChris Mason 	if (!ret) {
41645f39d397SChris Mason 		leaf = path->nodes[0];
41655f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
41665f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
41675f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
416862e2749eSChris Mason 	}
41692c90e5d6SChris Mason 	btrfs_free_path(path);
4170aa5d6bedSChris Mason 	return ret;
4171be0e5c09SChris Mason }
4172be0e5c09SChris Mason 
417374123bd7SChris Mason /*
4174f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4175f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4176f0641656SFilipe Manana  * contiguous with the original item.
4177f0641656SFilipe Manana  *
4178f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4179f0641656SFilipe Manana  * the entire time.
4180f0641656SFilipe Manana  */
4181f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4182f0641656SFilipe Manana 			 struct btrfs_root *root,
4183f0641656SFilipe Manana 			 struct btrfs_path *path,
4184f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4185f0641656SFilipe Manana {
4186f0641656SFilipe Manana 	struct extent_buffer *leaf;
4187f0641656SFilipe Manana 	int ret;
4188f0641656SFilipe Manana 	u32 item_size;
4189f0641656SFilipe Manana 
4190f0641656SFilipe Manana 	leaf = path->nodes[0];
41913212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4192f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4193f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4194f0641656SFilipe Manana 	if (ret)
4195f0641656SFilipe Manana 		return ret;
4196f0641656SFilipe Manana 
4197f0641656SFilipe Manana 	path->slots[0]++;
4198f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4199f0641656SFilipe Manana 	leaf = path->nodes[0];
4200f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4201f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4202f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4203f0641656SFilipe Manana 			     item_size);
4204f0641656SFilipe Manana 	return 0;
4205f0641656SFilipe Manana }
4206f0641656SFilipe Manana 
4207f0641656SFilipe Manana /*
42085de08d7dSChris Mason  * delete the pointer from a given node.
420974123bd7SChris Mason  *
4210d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4211d352ac68SChris Mason  * empty a node.
421274123bd7SChris Mason  */
4213afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4214afe5fea7STsutomu Itoh 		    int level, int slot)
4215be0e5c09SChris Mason {
42165f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
42177518a238SChris Mason 	u32 nritems;
4218f3ea38daSJan Schmidt 	int ret;
4219be0e5c09SChris Mason 
42205f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4221be0e5c09SChris Mason 	if (slot != nritems - 1) {
4222bf1d3425SDavid Sterba 		if (level) {
4223f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4224f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4225bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4226bf1d3425SDavid Sterba 		}
42275f39d397SChris Mason 		memmove_extent_buffer(parent,
42285f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
42295f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4230d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4231d6025579SChris Mason 			      (nritems - slot - 1));
423257ba86c0SChris Mason 	} else if (level) {
4233f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
423433cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REMOVE);
423557ba86c0SChris Mason 		BUG_ON(ret < 0);
4236be0e5c09SChris Mason 	}
4237f3ea38daSJan Schmidt 
42387518a238SChris Mason 	nritems--;
42395f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
42407518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
42415f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4242eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
42435f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4244bb803951SChris Mason 	} else if (slot == 0) {
42455f39d397SChris Mason 		struct btrfs_disk_key disk_key;
42465f39d397SChris Mason 
42475f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4248b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4249be0e5c09SChris Mason 	}
4250d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4251be0e5c09SChris Mason }
4252be0e5c09SChris Mason 
425374123bd7SChris Mason /*
4254323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
42555d4f98a2SYan Zheng  * path->nodes[1].
4256323ac95bSChris Mason  *
4257323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4258323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4259323ac95bSChris Mason  *
4260323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4261323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4262323ac95bSChris Mason  */
4263143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4264323ac95bSChris Mason 				    struct btrfs_root *root,
42655d4f98a2SYan Zheng 				    struct btrfs_path *path,
42665d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4267323ac95bSChris Mason {
42685d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4269afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4270323ac95bSChris Mason 
42714d081c41SChris Mason 	/*
42724d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
42734d081c41SChris Mason 	 * aren't holding any locks when we call it
42744d081c41SChris Mason 	 */
42754d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
42764d081c41SChris Mason 
4277f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4278f0486c68SYan, Zheng 
427967439dadSDavid Sterba 	atomic_inc(&leaf->refs);
42807a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
42813083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4282323ac95bSChris Mason }
4283323ac95bSChris Mason /*
428474123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
428574123bd7SChris Mason  * the leaf, remove it from the tree
428674123bd7SChris Mason  */
428785e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
428885e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4289be0e5c09SChris Mason {
42900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
42915f39d397SChris Mason 	struct extent_buffer *leaf;
4292aa5d6bedSChris Mason 	int ret = 0;
4293aa5d6bedSChris Mason 	int wret;
42947518a238SChris Mason 	u32 nritems;
4295be0e5c09SChris Mason 
42965f39d397SChris Mason 	leaf = path->nodes[0];
42975f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4298be0e5c09SChris Mason 
429985e21bacSChris Mason 	if (slot + nr != nritems) {
43000cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
43010cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4302c82f823cSDavid Sterba 		struct btrfs_map_token token;
43030cae23b6SFilipe Manana 		u32 dsize = 0;
43040cae23b6SFilipe Manana 		int i;
43050cae23b6SFilipe Manana 
43060cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
43070cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
43085f39d397SChris Mason 
43093d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4310d6025579SChris Mason 			      data_end + dsize,
43113d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
431285e21bacSChris Mason 			      last_off - data_end);
43135f39d397SChris Mason 
4314c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
431585e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
43165f39d397SChris Mason 			u32 ioff;
4317db94535dSChris Mason 
43183212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
43193212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
43200783fcfcSChris Mason 		}
4321db94535dSChris Mason 
43225f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
432385e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
43240783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
432585e21bacSChris Mason 			      (nritems - slot - nr));
4326be0e5c09SChris Mason 	}
432785e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
432885e21bacSChris Mason 	nritems -= nr;
43295f39d397SChris Mason 
433074123bd7SChris Mason 	/* delete the leaf if we've emptied it */
43317518a238SChris Mason 	if (nritems == 0) {
43325f39d397SChris Mason 		if (leaf == root->node) {
43335f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
43349a8dd150SChris Mason 		} else {
43356a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4336143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
43379a8dd150SChris Mason 		}
4338be0e5c09SChris Mason 	} else {
43397518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4340aa5d6bedSChris Mason 		if (slot == 0) {
43415f39d397SChris Mason 			struct btrfs_disk_key disk_key;
43425f39d397SChris Mason 
43435f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4344b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4345aa5d6bedSChris Mason 		}
4346aa5d6bedSChris Mason 
43477c4063d1SFilipe Manana 		/*
43487c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
43497c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
43507c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
43517c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
43527c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
43537c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
43547c4063d1SFilipe Manana 		 */
43550b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
43567c4063d1SFilipe Manana 			u32 min_push_space;
43577c4063d1SFilipe Manana 
4358be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4359be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4360be0e5c09SChris Mason 			 * for possible call to del_ptr below
4361be0e5c09SChris Mason 			 */
43624920c9acSChris Mason 			slot = path->slots[1];
436367439dadSDavid Sterba 			atomic_inc(&leaf->refs);
43647c4063d1SFilipe Manana 			/*
43657c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
43667c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
43677c4063d1SFilipe Manana 			 */
43687c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
43697c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
43707c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
43717c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
437254aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4373aa5d6bedSChris Mason 				ret = wret;
43745f39d397SChris Mason 
43755f39d397SChris Mason 			if (path->nodes[0] == leaf &&
43765f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
43777c4063d1SFilipe Manana 				/*
43787c4063d1SFilipe Manana 				 * If we were not able to push all items from our
43797c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
43807c4063d1SFilipe Manana 				 * either push all the remaining items to the
43817c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
43827c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
43837c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
43847c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
43857c4063d1SFilipe Manana 				 * or nearly full.
43867c4063d1SFilipe Manana 				 */
43877c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
43887c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
43897c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
43907c4063d1SFilipe Manana 						       min_push_space, 1, 0);
439154aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4392aa5d6bedSChris Mason 					ret = wret;
4393aa5d6bedSChris Mason 			}
43945f39d397SChris Mason 
43955f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4396323ac95bSChris Mason 				path->slots[1] = slot;
4397143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
43985f39d397SChris Mason 				free_extent_buffer(leaf);
4399143bede5SJeff Mahoney 				ret = 0;
44005de08d7dSChris Mason 			} else {
4401925baeddSChris Mason 				/* if we're still in the path, make sure
4402925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4403925baeddSChris Mason 				 * push_leaf functions must have already
4404925baeddSChris Mason 				 * dirtied this buffer
4405925baeddSChris Mason 				 */
4406925baeddSChris Mason 				if (path->nodes[0] == leaf)
44075f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
44085f39d397SChris Mason 				free_extent_buffer(leaf);
4409be0e5c09SChris Mason 			}
4410d5719762SChris Mason 		} else {
44115f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4412be0e5c09SChris Mason 		}
44139a8dd150SChris Mason 	}
4414aa5d6bedSChris Mason 	return ret;
44159a8dd150SChris Mason }
44169a8dd150SChris Mason 
441797571fd0SChris Mason /*
4418925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
44197bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
44207bb86316SChris Mason  * returns < 0 on io errors.
4421d352ac68SChris Mason  *
4422d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4423d352ac68SChris Mason  * time you call it.
44247bb86316SChris Mason  */
442516e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
44267bb86316SChris Mason {
4427925baeddSChris Mason 	struct btrfs_key key;
4428925baeddSChris Mason 	struct btrfs_disk_key found_key;
4429925baeddSChris Mason 	int ret;
44307bb86316SChris Mason 
4431925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4432925baeddSChris Mason 
4433e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
4434925baeddSChris Mason 		key.offset--;
4435e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
4436925baeddSChris Mason 		key.type--;
4437e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4438e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
4439925baeddSChris Mason 		key.objectid--;
4440e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
4441e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4442e8b0d724SFilipe David Borba Manana 	} else {
44437bb86316SChris Mason 		return 1;
4444e8b0d724SFilipe David Borba Manana 	}
44457bb86316SChris Mason 
4446b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4447925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4448925baeddSChris Mason 	if (ret < 0)
4449925baeddSChris Mason 		return ret;
4450925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4451925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4452337c6f68SFilipe Manana 	/*
4453337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
4454337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
4455337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
4456337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
4457337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
4458337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
4459337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
4460337c6f68SFilipe Manana 	 * the previous key we computed above.
4461337c6f68SFilipe Manana 	 */
4462337c6f68SFilipe Manana 	if (ret <= 0)
44637bb86316SChris Mason 		return 0;
4464925baeddSChris Mason 	return 1;
44657bb86316SChris Mason }
44667bb86316SChris Mason 
44673f157a2fSChris Mason /*
44683f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4469de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4470de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
44713f157a2fSChris Mason  *
44723f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
44733f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
44743f157a2fSChris Mason  * key and get a writable path.
44753f157a2fSChris Mason  *
44763f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
44773f157a2fSChris Mason  * of the tree.
44783f157a2fSChris Mason  *
4479d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4480d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4481d352ac68SChris Mason  * skipped over (without reading them).
4482d352ac68SChris Mason  *
44833f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
44843f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
44853f157a2fSChris Mason  */
44863f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4487de78b51aSEric Sandeen 			 struct btrfs_path *path,
44883f157a2fSChris Mason 			 u64 min_trans)
44893f157a2fSChris Mason {
44903f157a2fSChris Mason 	struct extent_buffer *cur;
44913f157a2fSChris Mason 	struct btrfs_key found_key;
44923f157a2fSChris Mason 	int slot;
44939652480bSYan 	int sret;
44943f157a2fSChris Mason 	u32 nritems;
44953f157a2fSChris Mason 	int level;
44963f157a2fSChris Mason 	int ret = 1;
4497f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
44983f157a2fSChris Mason 
4499c922b016SStefan Roesch 	ASSERT(!path->nowait);
4500f98de9b9SFilipe Manana 	path->keep_locks = 1;
45013f157a2fSChris Mason again:
4502bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
45033f157a2fSChris Mason 	level = btrfs_header_level(cur);
4504e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
45053f157a2fSChris Mason 	path->nodes[level] = cur;
4506bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
45073f157a2fSChris Mason 
45083f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
45093f157a2fSChris Mason 		ret = 1;
45103f157a2fSChris Mason 		goto out;
45113f157a2fSChris Mason 	}
45123f157a2fSChris Mason 	while (1) {
45133f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
45143f157a2fSChris Mason 		level = btrfs_header_level(cur);
4515e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
4516cbca7d59SFilipe Manana 		if (sret < 0) {
4517cbca7d59SFilipe Manana 			ret = sret;
4518cbca7d59SFilipe Manana 			goto out;
4519cbca7d59SFilipe Manana 		}
45203f157a2fSChris Mason 
4521323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4522323ac95bSChris Mason 		if (level == path->lowest_level) {
4523e02119d5SChris Mason 			if (slot >= nritems)
4524e02119d5SChris Mason 				goto find_next_key;
45253f157a2fSChris Mason 			ret = 0;
45263f157a2fSChris Mason 			path->slots[level] = slot;
45273f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
45283f157a2fSChris Mason 			goto out;
45293f157a2fSChris Mason 		}
45309652480bSYan 		if (sret && slot > 0)
45319652480bSYan 			slot--;
45323f157a2fSChris Mason 		/*
4533de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4534260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
45353f157a2fSChris Mason 		 */
45363f157a2fSChris Mason 		while (slot < nritems) {
45373f157a2fSChris Mason 			u64 gen;
4538e02119d5SChris Mason 
45393f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
45403f157a2fSChris Mason 			if (gen < min_trans) {
45413f157a2fSChris Mason 				slot++;
45423f157a2fSChris Mason 				continue;
45433f157a2fSChris Mason 			}
45443f157a2fSChris Mason 			break;
45453f157a2fSChris Mason 		}
4546e02119d5SChris Mason find_next_key:
45473f157a2fSChris Mason 		/*
45483f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
45493f157a2fSChris Mason 		 * and find another one
45503f157a2fSChris Mason 		 */
45513f157a2fSChris Mason 		if (slot >= nritems) {
4552e02119d5SChris Mason 			path->slots[level] = slot;
4553e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4554de78b51aSEric Sandeen 						  min_trans);
4555e02119d5SChris Mason 			if (sret == 0) {
4556b3b4aa74SDavid Sterba 				btrfs_release_path(path);
45573f157a2fSChris Mason 				goto again;
45583f157a2fSChris Mason 			} else {
45593f157a2fSChris Mason 				goto out;
45603f157a2fSChris Mason 			}
45613f157a2fSChris Mason 		}
45623f157a2fSChris Mason 		/* save our key for returning back */
45633f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
45643f157a2fSChris Mason 		path->slots[level] = slot;
45653f157a2fSChris Mason 		if (level == path->lowest_level) {
45663f157a2fSChris Mason 			ret = 0;
45673f157a2fSChris Mason 			goto out;
45683f157a2fSChris Mason 		}
45694b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4570fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4571fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4572fb770ae4SLiu Bo 			goto out;
4573fb770ae4SLiu Bo 		}
45743f157a2fSChris Mason 
4575bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4576b4ce94deSChris Mason 
4577bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
45783f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4579f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
45803f157a2fSChris Mason 	}
45813f157a2fSChris Mason out:
4582f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4583f98de9b9SFilipe Manana 	if (ret == 0) {
4584f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4585f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4586f98de9b9SFilipe Manana 	}
45873f157a2fSChris Mason 	return ret;
45883f157a2fSChris Mason }
45893f157a2fSChris Mason 
45903f157a2fSChris Mason /*
45913f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
45923f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4593de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
45943f157a2fSChris Mason  *
45953f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
45963f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
45973f157a2fSChris Mason  *
45983f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
45993f157a2fSChris Mason  * calling this function.
46003f157a2fSChris Mason  */
4601e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4602de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4603e7a84565SChris Mason {
4604e7a84565SChris Mason 	int slot;
4605e7a84565SChris Mason 	struct extent_buffer *c;
4606e7a84565SChris Mason 
46076a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4608e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4609e7a84565SChris Mason 		if (!path->nodes[level])
4610e7a84565SChris Mason 			return 1;
4611e7a84565SChris Mason 
4612e7a84565SChris Mason 		slot = path->slots[level] + 1;
4613e7a84565SChris Mason 		c = path->nodes[level];
46143f157a2fSChris Mason next:
4615e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
461633c66f43SYan Zheng 			int ret;
461733c66f43SYan Zheng 			int orig_lowest;
461833c66f43SYan Zheng 			struct btrfs_key cur_key;
461933c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
462033c66f43SYan Zheng 			    !path->nodes[level + 1])
4621e7a84565SChris Mason 				return 1;
462233c66f43SYan Zheng 
46236a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
462433c66f43SYan Zheng 				level++;
4625e7a84565SChris Mason 				continue;
4626e7a84565SChris Mason 			}
462733c66f43SYan Zheng 
462833c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
462933c66f43SYan Zheng 			if (level == 0)
463033c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
463133c66f43SYan Zheng 			else
463233c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
463333c66f43SYan Zheng 
463433c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4635b3b4aa74SDavid Sterba 			btrfs_release_path(path);
463633c66f43SYan Zheng 			path->lowest_level = level;
463733c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
463833c66f43SYan Zheng 						0, 0);
463933c66f43SYan Zheng 			path->lowest_level = orig_lowest;
464033c66f43SYan Zheng 			if (ret < 0)
464133c66f43SYan Zheng 				return ret;
464233c66f43SYan Zheng 
464333c66f43SYan Zheng 			c = path->nodes[level];
464433c66f43SYan Zheng 			slot = path->slots[level];
464533c66f43SYan Zheng 			if (ret == 0)
464633c66f43SYan Zheng 				slot++;
464733c66f43SYan Zheng 			goto next;
464833c66f43SYan Zheng 		}
464933c66f43SYan Zheng 
4650e7a84565SChris Mason 		if (level == 0)
4651e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
46523f157a2fSChris Mason 		else {
46533f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
46543f157a2fSChris Mason 
46553f157a2fSChris Mason 			if (gen < min_trans) {
46563f157a2fSChris Mason 				slot++;
46573f157a2fSChris Mason 				goto next;
46583f157a2fSChris Mason 			}
4659e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
46603f157a2fSChris Mason 		}
4661e7a84565SChris Mason 		return 0;
4662e7a84565SChris Mason 	}
4663e7a84565SChris Mason 	return 1;
4664e7a84565SChris Mason }
4665e7a84565SChris Mason 
46663d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
46673d7806ecSJan Schmidt 			u64 time_seq)
46683d7806ecSJan Schmidt {
4669d97e63b6SChris Mason 	int slot;
46708e73f275SChris Mason 	int level;
46715f39d397SChris Mason 	struct extent_buffer *c;
46728e73f275SChris Mason 	struct extent_buffer *next;
4673d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4674925baeddSChris Mason 	struct btrfs_key key;
4675d96b3424SFilipe Manana 	bool need_commit_sem = false;
4676925baeddSChris Mason 	u32 nritems;
4677925baeddSChris Mason 	int ret;
46780e46318dSJosef Bacik 	int i;
4679925baeddSChris Mason 
4680bdcdd86cSFilipe Manana 	/*
4681bdcdd86cSFilipe Manana 	 * The nowait semantics are used only for write paths, where we don't
4682bdcdd86cSFilipe Manana 	 * use the tree mod log and sequence numbers.
4683bdcdd86cSFilipe Manana 	 */
4684bdcdd86cSFilipe Manana 	if (time_seq)
4685c922b016SStefan Roesch 		ASSERT(!path->nowait);
4686c922b016SStefan Roesch 
4687925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4688d397712bSChris Mason 	if (nritems == 0)
4689925baeddSChris Mason 		return 1;
4690925baeddSChris Mason 
46918e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
46928e73f275SChris Mason again:
46938e73f275SChris Mason 	level = 1;
46948e73f275SChris Mason 	next = NULL;
4695b3b4aa74SDavid Sterba 	btrfs_release_path(path);
46968e73f275SChris Mason 
4697a2135011SChris Mason 	path->keep_locks = 1;
46988e73f275SChris Mason 
4699d96b3424SFilipe Manana 	if (time_seq) {
47003d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4701d96b3424SFilipe Manana 	} else {
4702d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4703d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4704d96b3424SFilipe Manana 			need_commit_sem = true;
4705bdcdd86cSFilipe Manana 			if (path->nowait) {
4706bdcdd86cSFilipe Manana 				if (!down_read_trylock(&fs_info->commit_root_sem)) {
4707bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4708bdcdd86cSFilipe Manana 					goto done;
4709bdcdd86cSFilipe Manana 				}
4710bdcdd86cSFilipe Manana 			} else {
4711d96b3424SFilipe Manana 				down_read(&fs_info->commit_root_sem);
4712d96b3424SFilipe Manana 			}
4713bdcdd86cSFilipe Manana 		}
4714925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4715d96b3424SFilipe Manana 	}
4716925baeddSChris Mason 	path->keep_locks = 0;
4717925baeddSChris Mason 
4718925baeddSChris Mason 	if (ret < 0)
4719d96b3424SFilipe Manana 		goto done;
4720925baeddSChris Mason 
4721a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4722168fd7d2SChris Mason 	/*
4723168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4724168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4725168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4726168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4727168fd7d2SChris Mason 	 */
4728a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4729e457afecSYan Zheng 		if (ret == 0)
4730168fd7d2SChris Mason 			path->slots[0]++;
47318e73f275SChris Mason 		ret = 0;
4732925baeddSChris Mason 		goto done;
4733925baeddSChris Mason 	}
47340b43e04fSLiu Bo 	/*
47350b43e04fSLiu Bo 	 * So the above check misses one case:
47360b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
47370b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
47380b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
47390b43e04fSLiu Bo 	 *
47400b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
47410b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
47420b43e04fSLiu Bo 	 *
47430b43e04fSLiu Bo 	 * And a bit more explanation about this check,
47440b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
47450b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
47460b43e04fSLiu Bo 	 * bigger one.
47470b43e04fSLiu Bo 	 */
47480b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
47490b43e04fSLiu Bo 		ret = 0;
47500b43e04fSLiu Bo 		goto done;
47510b43e04fSLiu Bo 	}
4752d97e63b6SChris Mason 
4753234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
47548e73f275SChris Mason 		if (!path->nodes[level]) {
47558e73f275SChris Mason 			ret = 1;
47568e73f275SChris Mason 			goto done;
47578e73f275SChris Mason 		}
47585f39d397SChris Mason 
4759d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4760d97e63b6SChris Mason 		c = path->nodes[level];
47615f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4762d97e63b6SChris Mason 			level++;
47638e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
47648e73f275SChris Mason 				ret = 1;
47658e73f275SChris Mason 				goto done;
47668e73f275SChris Mason 			}
4767d97e63b6SChris Mason 			continue;
4768d97e63b6SChris Mason 		}
47695f39d397SChris Mason 
47700e46318dSJosef Bacik 
47710e46318dSJosef Bacik 		/*
47720e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
47730e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
47740e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
47750e46318dSJosef Bacik 		 */
47760e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
47770e46318dSJosef Bacik 			if (path->locks[level]) {
47780e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
47790e46318dSJosef Bacik 				path->locks[i] = 0;
47800e46318dSJosef Bacik 			}
47810e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
47820e46318dSJosef Bacik 			path->nodes[i] = NULL;
4783925baeddSChris Mason 		}
47845f39d397SChris Mason 
47858e73f275SChris Mason 		next = c;
4786d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4787cda79c54SDavid Sterba 					    slot, &key);
4788bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
47898e73f275SChris Mason 			goto again;
47905f39d397SChris Mason 
479176a05b35SChris Mason 		if (ret < 0) {
4792b3b4aa74SDavid Sterba 			btrfs_release_path(path);
479376a05b35SChris Mason 			goto done;
479476a05b35SChris Mason 		}
479576a05b35SChris Mason 
47965cd57b2cSChris Mason 		if (!path->skip_locking) {
4797bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4798bdcdd86cSFilipe Manana 			if (!ret && path->nowait) {
4799bdcdd86cSFilipe Manana 				ret = -EAGAIN;
4800bdcdd86cSFilipe Manana 				goto done;
4801bdcdd86cSFilipe Manana 			}
4802d42244a0SJan Schmidt 			if (!ret && time_seq) {
4803d42244a0SJan Schmidt 				/*
4804d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4805d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4806d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4807d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4808d42244a0SJan Schmidt 				 * on our lock and cycle.
4809d42244a0SJan Schmidt 				 */
4810cf538830SJan Schmidt 				free_extent_buffer(next);
4811d42244a0SJan Schmidt 				btrfs_release_path(path);
4812d42244a0SJan Schmidt 				cond_resched();
4813d42244a0SJan Schmidt 				goto again;
4814d42244a0SJan Schmidt 			}
48150e46318dSJosef Bacik 			if (!ret)
48160e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4817bd681513SChris Mason 		}
4818d97e63b6SChris Mason 		break;
4819d97e63b6SChris Mason 	}
4820d97e63b6SChris Mason 	path->slots[level] = slot;
4821d97e63b6SChris Mason 	while (1) {
4822d97e63b6SChris Mason 		level--;
4823d97e63b6SChris Mason 		path->nodes[level] = next;
4824d97e63b6SChris Mason 		path->slots[level] = 0;
4825a74a4b97SChris Mason 		if (!path->skip_locking)
4826ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4827d97e63b6SChris Mason 		if (!level)
4828d97e63b6SChris Mason 			break;
4829b4ce94deSChris Mason 
4830d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4831cda79c54SDavid Sterba 					    0, &key);
4832bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
48338e73f275SChris Mason 			goto again;
48348e73f275SChris Mason 
483576a05b35SChris Mason 		if (ret < 0) {
4836b3b4aa74SDavid Sterba 			btrfs_release_path(path);
483776a05b35SChris Mason 			goto done;
483876a05b35SChris Mason 		}
483976a05b35SChris Mason 
4840bdcdd86cSFilipe Manana 		if (!path->skip_locking) {
4841bdcdd86cSFilipe Manana 			if (path->nowait) {
4842bdcdd86cSFilipe Manana 				if (!btrfs_try_tree_read_lock(next)) {
4843bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4844bdcdd86cSFilipe Manana 					goto done;
4845bdcdd86cSFilipe Manana 				}
4846bdcdd86cSFilipe Manana 			} else {
48470e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4848d97e63b6SChris Mason 			}
4849bdcdd86cSFilipe Manana 		}
4850bdcdd86cSFilipe Manana 	}
48518e73f275SChris Mason 	ret = 0;
4852925baeddSChris Mason done:
4853f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
4854d96b3424SFilipe Manana 	if (need_commit_sem) {
4855d96b3424SFilipe Manana 		int ret2;
4856d96b3424SFilipe Manana 
4857d96b3424SFilipe Manana 		path->need_commit_sem = 1;
4858d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
4859d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
4860d96b3424SFilipe Manana 		if (ret2)
4861d96b3424SFilipe Manana 			ret = ret2;
4862d96b3424SFilipe Manana 	}
48638e73f275SChris Mason 
48648e73f275SChris Mason 	return ret;
4865d97e63b6SChris Mason }
48660b86a832SChris Mason 
4867890d2b1aSJosef Bacik int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
4868890d2b1aSJosef Bacik {
4869890d2b1aSJosef Bacik 	path->slots[0]++;
4870890d2b1aSJosef Bacik 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
4871890d2b1aSJosef Bacik 		return btrfs_next_old_leaf(root, path, time_seq);
4872890d2b1aSJosef Bacik 	return 0;
4873890d2b1aSJosef Bacik }
4874890d2b1aSJosef Bacik 
48753f157a2fSChris Mason /*
48763f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
48773f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
48783f157a2fSChris Mason  *
48793f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
48803f157a2fSChris Mason  */
48810b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
48820b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
48830b86a832SChris Mason 			int type)
48840b86a832SChris Mason {
48850b86a832SChris Mason 	struct btrfs_key found_key;
48860b86a832SChris Mason 	struct extent_buffer *leaf;
4887e02119d5SChris Mason 	u32 nritems;
48880b86a832SChris Mason 	int ret;
48890b86a832SChris Mason 
48900b86a832SChris Mason 	while (1) {
48910b86a832SChris Mason 		if (path->slots[0] == 0) {
48920b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
48930b86a832SChris Mason 			if (ret != 0)
48940b86a832SChris Mason 				return ret;
48950b86a832SChris Mason 		} else {
48960b86a832SChris Mason 			path->slots[0]--;
48970b86a832SChris Mason 		}
48980b86a832SChris Mason 		leaf = path->nodes[0];
4899e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
4900e02119d5SChris Mason 		if (nritems == 0)
4901e02119d5SChris Mason 			return 1;
4902e02119d5SChris Mason 		if (path->slots[0] == nritems)
4903e02119d5SChris Mason 			path->slots[0]--;
4904e02119d5SChris Mason 
49050b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4906e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
4907e02119d5SChris Mason 			break;
49080a4eefbbSYan Zheng 		if (found_key.type == type)
49090a4eefbbSYan Zheng 			return 0;
4910e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
4911e02119d5SChris Mason 		    found_key.type < type)
4912e02119d5SChris Mason 			break;
49130b86a832SChris Mason 	}
49140b86a832SChris Mason 	return 1;
49150b86a832SChris Mason }
4916ade2e0b3SWang Shilong 
4917ade2e0b3SWang Shilong /*
4918ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
4919ade2e0b3SWang Shilong  * min objecitd.
4920ade2e0b3SWang Shilong  *
4921ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4922ade2e0b3SWang Shilong  */
4923ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
4924ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
4925ade2e0b3SWang Shilong {
4926ade2e0b3SWang Shilong 	struct btrfs_key found_key;
4927ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
4928ade2e0b3SWang Shilong 	u32 nritems;
4929ade2e0b3SWang Shilong 	int ret;
4930ade2e0b3SWang Shilong 
4931ade2e0b3SWang Shilong 	while (1) {
4932ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
4933ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
4934ade2e0b3SWang Shilong 			if (ret != 0)
4935ade2e0b3SWang Shilong 				return ret;
4936ade2e0b3SWang Shilong 		} else {
4937ade2e0b3SWang Shilong 			path->slots[0]--;
4938ade2e0b3SWang Shilong 		}
4939ade2e0b3SWang Shilong 		leaf = path->nodes[0];
4940ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
4941ade2e0b3SWang Shilong 		if (nritems == 0)
4942ade2e0b3SWang Shilong 			return 1;
4943ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
4944ade2e0b3SWang Shilong 			path->slots[0]--;
4945ade2e0b3SWang Shilong 
4946ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4947ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
4948ade2e0b3SWang Shilong 			break;
4949ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4950ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
4951ade2e0b3SWang Shilong 			return 0;
4952ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
4953ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
4954ade2e0b3SWang Shilong 			break;
4955ade2e0b3SWang Shilong 	}
4956ade2e0b3SWang Shilong 	return 1;
4957ade2e0b3SWang Shilong }
4958226463d7SJosef Bacik 
4959226463d7SJosef Bacik int __init btrfs_ctree_init(void)
4960226463d7SJosef Bacik {
4961226463d7SJosef Bacik 	btrfs_path_cachep = kmem_cache_create("btrfs_path",
4962226463d7SJosef Bacik 			sizeof(struct btrfs_path), 0,
4963226463d7SJosef Bacik 			SLAB_MEM_SPREAD, NULL);
4964226463d7SJosef Bacik 	if (!btrfs_path_cachep)
4965226463d7SJosef Bacik 		return -ENOMEM;
4966226463d7SJosef Bacik 	return 0;
4967226463d7SJosef Bacik }
4968226463d7SJosef Bacik 
4969226463d7SJosef Bacik void __cold btrfs_ctree_exit(void)
4970226463d7SJosef Bacik {
4971226463d7SJosef Bacik 	kmem_cache_destroy(btrfs_path_cachep);
4972226463d7SJosef Bacik }
4973