xref: /openbmc/linux/fs/btrfs/ctree.c (revision e23efd8e8767165a6103cf0a4fe273f6b9f182f2)
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"
256bfd0ffaSJosef Bacik #include "file-item.h"
269a8dd150SChris Mason 
27226463d7SJosef Bacik static struct kmem_cache *btrfs_path_cachep;
28226463d7SJosef Bacik 
29e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
30e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
31310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
32310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
33310712b2SOmar Sandoval 		      int data_size, int extend);
345f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
352ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
36971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
375f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
385f39d397SChris Mason 			      struct extent_buffer *dst_buf,
395f39d397SChris Mason 			      struct extent_buffer *src_buf);
40afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
41afe5fea7STsutomu Itoh 		    int level, int slot);
42d97e63b6SChris Mason 
43af024ed2SJohannes Thumshirn static const struct btrfs_csums {
44af024ed2SJohannes Thumshirn 	u16		size;
4559a0fcdbSDavid Sterba 	const char	name[10];
4659a0fcdbSDavid Sterba 	const char	driver[12];
47af024ed2SJohannes Thumshirn } btrfs_csums[] = {
48af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
493951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
503831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
51352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
52352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
53af024ed2SJohannes Thumshirn };
54af024ed2SJohannes Thumshirn 
553a3178c7SJosef Bacik /*
563a3178c7SJosef Bacik  * The leaf data grows from end-to-front in the node.  this returns the address
573a3178c7SJosef Bacik  * of the start of the last item, which is the stop of the leaf data stack.
583a3178c7SJosef Bacik  */
593a3178c7SJosef Bacik static unsigned int leaf_data_end(const struct extent_buffer *leaf)
603a3178c7SJosef Bacik {
613a3178c7SJosef Bacik 	u32 nr = btrfs_header_nritems(leaf);
623a3178c7SJosef Bacik 
633a3178c7SJosef Bacik 	if (nr == 0)
643a3178c7SJosef Bacik 		return BTRFS_LEAF_DATA_SIZE(leaf->fs_info);
653a3178c7SJosef Bacik 	return btrfs_item_offset(leaf, nr - 1);
663a3178c7SJosef Bacik }
673a3178c7SJosef Bacik 
68af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
69af024ed2SJohannes Thumshirn {
70af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
71af024ed2SJohannes Thumshirn 	/*
72af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
73af024ed2SJohannes Thumshirn 	 */
74af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
75af024ed2SJohannes Thumshirn }
76af024ed2SJohannes Thumshirn 
77af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
78af024ed2SJohannes Thumshirn {
79af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
80af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
81af024ed2SJohannes Thumshirn }
82af024ed2SJohannes Thumshirn 
83b4e967beSDavid Sterba /*
84b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
85b4e967beSDavid Sterba  * name
86b4e967beSDavid Sterba  */
87b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
88b4e967beSDavid Sterba {
89b4e967beSDavid Sterba 	/* csum type is validated at mount time */
9059a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
9159a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
92b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
93b4e967beSDavid Sterba }
94b4e967beSDavid Sterba 
95604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
96f7cea56cSDavid Sterba {
97f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
98f7cea56cSDavid Sterba }
99f7cea56cSDavid Sterba 
1002c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
1012c90e5d6SChris Mason {
102e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
1032c90e5d6SChris Mason }
1042c90e5d6SChris Mason 
105d352ac68SChris Mason /* this also releases the path */
1062c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
1072c90e5d6SChris Mason {
108ff175d57SJesper Juhl 	if (!p)
109ff175d57SJesper Juhl 		return;
110b3b4aa74SDavid Sterba 	btrfs_release_path(p);
1112c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
1122c90e5d6SChris Mason }
1132c90e5d6SChris Mason 
114d352ac68SChris Mason /*
115d352ac68SChris Mason  * path release drops references on the extent buffers in the path
116d352ac68SChris Mason  * and it drops any locks held by this path
117d352ac68SChris Mason  *
118d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
119d352ac68SChris Mason  */
120b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
121eb60ceacSChris Mason {
122eb60ceacSChris Mason 	int i;
123a2135011SChris Mason 
124234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1253f157a2fSChris Mason 		p->slots[i] = 0;
126eb60ceacSChris Mason 		if (!p->nodes[i])
127925baeddSChris Mason 			continue;
128925baeddSChris Mason 		if (p->locks[i]) {
129bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
130925baeddSChris Mason 			p->locks[i] = 0;
131925baeddSChris Mason 		}
1325f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1333f157a2fSChris Mason 		p->nodes[i] = NULL;
134eb60ceacSChris Mason 	}
135eb60ceacSChris Mason }
136eb60ceacSChris Mason 
137d352ac68SChris Mason /*
1388bb808c6SDavid Sterba  * We want the transaction abort to print stack trace only for errors where the
1398bb808c6SDavid Sterba  * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
1408bb808c6SDavid Sterba  * caused by external factors.
1418bb808c6SDavid Sterba  */
1428bb808c6SDavid Sterba bool __cold abort_should_print_stack(int errno)
1438bb808c6SDavid Sterba {
1448bb808c6SDavid Sterba 	switch (errno) {
1458bb808c6SDavid Sterba 	case -EIO:
1468bb808c6SDavid Sterba 	case -EROFS:
1478bb808c6SDavid Sterba 	case -ENOMEM:
1488bb808c6SDavid Sterba 		return false;
1498bb808c6SDavid Sterba 	}
1508bb808c6SDavid Sterba 	return true;
1518bb808c6SDavid Sterba }
1528bb808c6SDavid Sterba 
1538bb808c6SDavid Sterba /*
154d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
155d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
156d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
157d352ac68SChris Mason  * looping required.
158d352ac68SChris Mason  *
159d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
160d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
161d352ac68SChris Mason  * at any time because there are no locks held.
162d352ac68SChris Mason  */
163925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
164925baeddSChris Mason {
165925baeddSChris Mason 	struct extent_buffer *eb;
166240f62c8SChris Mason 
1673083ee2eSJosef Bacik 	while (1) {
168240f62c8SChris Mason 		rcu_read_lock();
169240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1703083ee2eSJosef Bacik 
1713083ee2eSJosef Bacik 		/*
1723083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
17301327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1743083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1753083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1763083ee2eSJosef Bacik 		 */
1773083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
178240f62c8SChris Mason 			rcu_read_unlock();
1793083ee2eSJosef Bacik 			break;
1803083ee2eSJosef Bacik 		}
1813083ee2eSJosef Bacik 		rcu_read_unlock();
1823083ee2eSJosef Bacik 		synchronize_rcu();
1833083ee2eSJosef Bacik 	}
184925baeddSChris Mason 	return eb;
185925baeddSChris Mason }
186925baeddSChris Mason 
18792a7cc42SQu Wenruo /*
18892a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
18992a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
19092a7cc42SQu Wenruo  * sure they get properly updated on disk.
191d352ac68SChris Mason  */
1920b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1930b86a832SChris Mason {
1940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1950b246afaSJeff Mahoney 
196e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
197e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
198e7070be1SJosef Bacik 		return;
199e7070be1SJosef Bacik 
2000b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
201e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
202e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
2034fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
204e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
2050b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
206e7070be1SJosef Bacik 		else
207e7070be1SJosef Bacik 			list_move(&root->dirty_list,
2080b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
2090b86a832SChris Mason 	}
2100b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
2110b86a832SChris Mason }
2120b86a832SChris Mason 
213d352ac68SChris Mason /*
214d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
215d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
216d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
217d352ac68SChris Mason  */
218be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
219be20aa9dSChris Mason 		      struct btrfs_root *root,
220be20aa9dSChris Mason 		      struct extent_buffer *buf,
221be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
222be20aa9dSChris Mason {
2230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
224be20aa9dSChris Mason 	struct extent_buffer *cow;
225be20aa9dSChris Mason 	int ret = 0;
226be20aa9dSChris Mason 	int level;
2275d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
228be20aa9dSChris Mason 
22992a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2300b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
23192a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
23227cdeb70SMiao Xie 		trans->transid != root->last_trans);
233be20aa9dSChris Mason 
234be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2355d4f98a2SYan Zheng 	if (level == 0)
2365d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2375d4f98a2SYan Zheng 	else
2385d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
23931840ae1SZheng Yan 
2404d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
241cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
242cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
2435d4f98a2SYan Zheng 	if (IS_ERR(cow))
244be20aa9dSChris Mason 		return PTR_ERR(cow);
245be20aa9dSChris Mason 
24658e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
247be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
248be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2495d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2505d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2515d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2525d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2535d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2545d4f98a2SYan Zheng 	else
255be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
256be20aa9dSChris Mason 
257de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2582b82032cSYan Zheng 
259be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2605d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
261e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2625d4f98a2SYan Zheng 	else
263e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
264867ed321SJosef Bacik 	if (ret) {
26572c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
26672c9925fSFilipe Manana 		free_extent_buffer(cow);
267867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
268be20aa9dSChris Mason 		return ret;
269867ed321SJosef Bacik 	}
270be20aa9dSChris Mason 
271be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
272be20aa9dSChris Mason 	*cow_ret = cow;
273be20aa9dSChris Mason 	return 0;
274be20aa9dSChris Mason }
275be20aa9dSChris Mason 
276d352ac68SChris Mason /*
2775d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
2785d4f98a2SYan Zheng  */
2795d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
2805d4f98a2SYan Zheng 			      struct extent_buffer *buf)
2815d4f98a2SYan Zheng {
2825d4f98a2SYan Zheng 	/*
28392a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
28492a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
28592a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
2865d4f98a2SYan Zheng 	 */
28792a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2885d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
2895d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
2905d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
2915d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
2925d4f98a2SYan Zheng 		return 1;
293a79865c6SNikolay Borisov 
2945d4f98a2SYan Zheng 	return 0;
2955d4f98a2SYan Zheng }
2965d4f98a2SYan Zheng 
2975d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
2985d4f98a2SYan Zheng 				       struct btrfs_root *root,
2995d4f98a2SYan Zheng 				       struct extent_buffer *buf,
300f0486c68SYan, Zheng 				       struct extent_buffer *cow,
301f0486c68SYan, Zheng 				       int *last_ref)
3025d4f98a2SYan Zheng {
3030b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3045d4f98a2SYan Zheng 	u64 refs;
3055d4f98a2SYan Zheng 	u64 owner;
3065d4f98a2SYan Zheng 	u64 flags;
3075d4f98a2SYan Zheng 	u64 new_flags = 0;
3085d4f98a2SYan Zheng 	int ret;
3095d4f98a2SYan Zheng 
3105d4f98a2SYan Zheng 	/*
3115d4f98a2SYan Zheng 	 * Backrefs update rules:
3125d4f98a2SYan Zheng 	 *
3135d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
3145d4f98a2SYan Zheng 	 * allocated by tree relocation.
3155d4f98a2SYan Zheng 	 *
3165d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
3175d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
3185d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
3195d4f98a2SYan Zheng 	 *
3205d4f98a2SYan Zheng 	 * If a tree block is been relocating
3215d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
3225d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
3235d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
3245d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
3255d4f98a2SYan Zheng 	 */
3265d4f98a2SYan Zheng 
3275d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
3282ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
3293173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
3303173a18fSJosef Bacik 					       &refs, &flags);
331be1a5564SMark Fasheh 		if (ret)
332be1a5564SMark Fasheh 			return ret;
333e5df9573SMark Fasheh 		if (refs == 0) {
334e5df9573SMark Fasheh 			ret = -EROFS;
3350b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
336e5df9573SMark Fasheh 			return ret;
337e5df9573SMark Fasheh 		}
3385d4f98a2SYan Zheng 	} else {
3395d4f98a2SYan Zheng 		refs = 1;
3405d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
3415d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
3425d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
3435d4f98a2SYan Zheng 		else
3445d4f98a2SYan Zheng 			flags = 0;
3455d4f98a2SYan Zheng 	}
3465d4f98a2SYan Zheng 
3475d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
3485d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
3495d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
3505d4f98a2SYan Zheng 
3515d4f98a2SYan Zheng 	if (refs > 1) {
3525d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
3535d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
3545d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
355e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
356692826b2SJeff Mahoney 			if (ret)
357692826b2SJeff Mahoney 				return ret;
3585d4f98a2SYan Zheng 
3595d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3605d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
361e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
362692826b2SJeff Mahoney 				if (ret)
363692826b2SJeff Mahoney 					return ret;
364e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
365692826b2SJeff Mahoney 				if (ret)
366692826b2SJeff Mahoney 					return ret;
3675d4f98a2SYan Zheng 			}
3685d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
3695d4f98a2SYan Zheng 		} else {
3705d4f98a2SYan Zheng 
3715d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3725d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
373e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3745d4f98a2SYan Zheng 			else
375e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
376692826b2SJeff Mahoney 			if (ret)
377692826b2SJeff Mahoney 				return ret;
3785d4f98a2SYan Zheng 		}
3795d4f98a2SYan Zheng 		if (new_flags != 0) {
380b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
381b1c79e09SJosef Bacik 
38242c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
3832fe6a5a1SDavid Sterba 							  new_flags, level);
384be1a5564SMark Fasheh 			if (ret)
385be1a5564SMark Fasheh 				return ret;
3865d4f98a2SYan Zheng 		}
3875d4f98a2SYan Zheng 	} else {
3885d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
3895d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3905d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
391e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3925d4f98a2SYan Zheng 			else
393e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
394692826b2SJeff Mahoney 			if (ret)
395692826b2SJeff Mahoney 				return ret;
396e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
397692826b2SJeff Mahoney 			if (ret)
398692826b2SJeff Mahoney 				return ret;
3995d4f98a2SYan Zheng 		}
4006a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
401f0486c68SYan, Zheng 		*last_ref = 1;
4025d4f98a2SYan Zheng 	}
4035d4f98a2SYan Zheng 	return 0;
4045d4f98a2SYan Zheng }
4055d4f98a2SYan Zheng 
4065d4f98a2SYan Zheng /*
407d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
408d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
409d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
410d397712bSChris Mason  * dirty again.
411d352ac68SChris Mason  *
412d352ac68SChris Mason  * search_start -- an allocation hint for the new block
413d352ac68SChris Mason  *
414d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
415d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
416d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
417d352ac68SChris Mason  */
418d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
4195f39d397SChris Mason 			     struct btrfs_root *root,
4205f39d397SChris Mason 			     struct extent_buffer *buf,
4215f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
4225f39d397SChris Mason 			     struct extent_buffer **cow_ret,
4239631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
4249631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
4256702ed49SChris Mason {
4260b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4275d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
4285f39d397SChris Mason 	struct extent_buffer *cow;
429be1a5564SMark Fasheh 	int level, ret;
430f0486c68SYan, Zheng 	int last_ref = 0;
431925baeddSChris Mason 	int unlock_orig = 0;
4320f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
4336702ed49SChris Mason 
434925baeddSChris Mason 	if (*cow_ret == buf)
435925baeddSChris Mason 		unlock_orig = 1;
436925baeddSChris Mason 
43749d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
438925baeddSChris Mason 
43992a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
4400b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
44192a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
44227cdeb70SMiao Xie 		trans->transid != root->last_trans);
4435f39d397SChris Mason 
4447bb86316SChris Mason 	level = btrfs_header_level(buf);
44531840ae1SZheng Yan 
4465d4f98a2SYan Zheng 	if (level == 0)
4475d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
4485d4f98a2SYan Zheng 	else
4495d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
4505d4f98a2SYan Zheng 
4510f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
4525d4f98a2SYan Zheng 		parent_start = parent->start;
4535d4f98a2SYan Zheng 
45479bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
45579bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
45679bd3712SFilipe Manana 				     search_start, empty_size, nest);
4576702ed49SChris Mason 	if (IS_ERR(cow))
4586702ed49SChris Mason 		return PTR_ERR(cow);
4596702ed49SChris Mason 
460b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
461b4ce94deSChris Mason 
46258e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
463db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
4645f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
4655d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
4665d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
4675d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
4685d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
4695d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
4705d4f98a2SYan Zheng 	else
4715f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
4726702ed49SChris Mason 
473de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
4742b82032cSYan Zheng 
475be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
476b68dc2a9SMark Fasheh 	if (ret) {
477572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
478572c83acSJosef Bacik 		free_extent_buffer(cow);
47966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
480b68dc2a9SMark Fasheh 		return ret;
481b68dc2a9SMark Fasheh 	}
4821a40e23bSZheng Yan 
48392a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
48483d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
48593314e3bSZhaolei 		if (ret) {
486572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
487572c83acSJosef Bacik 			free_extent_buffer(cow);
48866642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
48983d4cfd4SJosef Bacik 			return ret;
49083d4cfd4SJosef Bacik 		}
49193314e3bSZhaolei 	}
4923fd0a558SYan, Zheng 
4936702ed49SChris Mason 	if (buf == root->node) {
494925baeddSChris Mason 		WARN_ON(parent && parent != buf);
4955d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4965d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4975d4f98a2SYan Zheng 			parent_start = buf->start;
498925baeddSChris Mason 
49967439dadSDavid Sterba 		atomic_inc(&cow->refs);
500406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
501d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
502240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
503925baeddSChris Mason 
5047a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
5057a163608SFilipe Manana 				      parent_start, last_ref);
5065f39d397SChris Mason 		free_extent_buffer(buf);
5070b86a832SChris Mason 		add_root_to_dirty_list(root);
5086702ed49SChris Mason 	} else {
5095d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
510f3a84ccdSFilipe Manana 		btrfs_tree_mod_log_insert_key(parent, parent_slot,
51133cff222SFilipe Manana 					      BTRFS_MOD_LOG_KEY_REPLACE);
5125f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
513db94535dSChris Mason 					cow->start);
51474493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
51574493f7aSChris Mason 					      trans->transid);
5166702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
5175de865eeSFilipe David Borba Manana 		if (last_ref) {
518f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
5195de865eeSFilipe David Borba Manana 			if (ret) {
520572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
521572c83acSJosef Bacik 				free_extent_buffer(cow);
52266642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
5235de865eeSFilipe David Borba Manana 				return ret;
5245de865eeSFilipe David Borba Manana 			}
5255de865eeSFilipe David Borba Manana 		}
5267a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
5277a163608SFilipe Manana 				      parent_start, last_ref);
5286702ed49SChris Mason 	}
529925baeddSChris Mason 	if (unlock_orig)
530925baeddSChris Mason 		btrfs_tree_unlock(buf);
5313083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
5326702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
5336702ed49SChris Mason 	*cow_ret = cow;
5346702ed49SChris Mason 	return 0;
5356702ed49SChris Mason }
5366702ed49SChris Mason 
5375d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
5385d4f98a2SYan Zheng 				   struct btrfs_root *root,
5395d4f98a2SYan Zheng 				   struct extent_buffer *buf)
5405d4f98a2SYan Zheng {
541f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
542faa2dbf0SJosef Bacik 		return 0;
543fccb84c9SDavid Sterba 
544d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
545d1980131SDavid Sterba 	smp_mb__before_atomic();
546f1ebcc74SLiu Bo 
547f1ebcc74SLiu Bo 	/*
548f1ebcc74SLiu Bo 	 * We do not need to cow a block if
549f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
550f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
551f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
552f1ebcc74SLiu Bo 	 *
553f1ebcc74SLiu Bo 	 * What is forced COW:
55401327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
55552042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
556f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
557f1ebcc74SLiu Bo 	 */
5585d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
5595d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
5605d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
561f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
56227cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
5635d4f98a2SYan Zheng 		return 0;
5645d4f98a2SYan Zheng 	return 1;
5655d4f98a2SYan Zheng }
5665d4f98a2SYan Zheng 
567d352ac68SChris Mason /*
568d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
56901327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
570d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
571d352ac68SChris Mason  */
572d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
5735f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
5745f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
5759631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
5769631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
57702217ed2SChris Mason {
5780b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5796702ed49SChris Mason 	u64 search_start;
580f510cfecSChris Mason 	int ret;
581dc17ff8fSChris Mason 
58283354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
58383354f07SJosef Bacik 		btrfs_err(fs_info,
58483354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
58583354f07SJosef Bacik 
5860b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
58731b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
588c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
5890b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
59031b1a2bdSJulia Lawall 
5910b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
59231b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
5930b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
594dc17ff8fSChris Mason 
5955d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
59602217ed2SChris Mason 		*cow_ret = buf;
59702217ed2SChris Mason 		return 0;
59802217ed2SChris Mason 	}
599c487685dSChris Mason 
600ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
601b4ce94deSChris Mason 
602f616f5cdSQu Wenruo 	/*
603f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
604f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
605f616f5cdSQu Wenruo 	 *
606f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
607f616f5cdSQu Wenruo 	 */
608f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
609f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
6109631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
6111abe9b8aSliubo 
6121abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
6131abe9b8aSliubo 
614f510cfecSChris Mason 	return ret;
6152c90e5d6SChris Mason }
616f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
6176702ed49SChris Mason 
618d352ac68SChris Mason /*
619d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
620d352ac68SChris Mason  * node are actually close by
621d352ac68SChris Mason  */
6226b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
6236702ed49SChris Mason {
6246b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
6256702ed49SChris Mason 		return 1;
6266b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
6276702ed49SChris Mason 		return 1;
62802217ed2SChris Mason 	return 0;
62902217ed2SChris Mason }
63002217ed2SChris Mason 
631ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
632ce6ef5abSDavid Sterba 
633ce6ef5abSDavid Sterba /*
634ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
635ce6ef5abSDavid Sterba  * we can avoid the conversion.
636ce6ef5abSDavid Sterba  */
637ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
638ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
639ce6ef5abSDavid Sterba {
640ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
641ce6ef5abSDavid Sterba 
642ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
643ce6ef5abSDavid Sterba }
644ce6ef5abSDavid Sterba 
645ce6ef5abSDavid Sterba #else
646ce6ef5abSDavid Sterba 
647081e9573SChris Mason /*
648081e9573SChris Mason  * compare two keys in a memcmp fashion
649081e9573SChris Mason  */
650310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
651310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
652081e9573SChris Mason {
653081e9573SChris Mason 	struct btrfs_key k1;
654081e9573SChris Mason 
655081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
656081e9573SChris Mason 
65720736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
658081e9573SChris Mason }
659ce6ef5abSDavid Sterba #endif
660081e9573SChris Mason 
661f3465ca4SJosef Bacik /*
662f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
663f3465ca4SJosef Bacik  */
664e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
665f3465ca4SJosef Bacik {
666f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
667f3465ca4SJosef Bacik 		return 1;
668f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
669f3465ca4SJosef Bacik 		return -1;
670f3465ca4SJosef Bacik 	if (k1->type > k2->type)
671f3465ca4SJosef Bacik 		return 1;
672f3465ca4SJosef Bacik 	if (k1->type < k2->type)
673f3465ca4SJosef Bacik 		return -1;
674f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
675f3465ca4SJosef Bacik 		return 1;
676f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
677f3465ca4SJosef Bacik 		return -1;
678f3465ca4SJosef Bacik 	return 0;
679f3465ca4SJosef Bacik }
680081e9573SChris Mason 
681d352ac68SChris Mason /*
682d352ac68SChris Mason  * this is used by the defrag code to go through all the
683d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
684d352ac68SChris Mason  * disk order is close to key order
685d352ac68SChris Mason  */
6866702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
6875f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
688de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
689a6b6e75eSChris Mason 		       struct btrfs_key *progress)
6906702ed49SChris Mason {
6910b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6926b80053dSChris Mason 	struct extent_buffer *cur;
6936702ed49SChris Mason 	u64 blocknr;
694e9d0b13bSChris Mason 	u64 search_start = *last_ret;
695e9d0b13bSChris Mason 	u64 last_block = 0;
6966702ed49SChris Mason 	u64 other;
6976702ed49SChris Mason 	u32 parent_nritems;
6986702ed49SChris Mason 	int end_slot;
6996702ed49SChris Mason 	int i;
7006702ed49SChris Mason 	int err = 0;
7016b80053dSChris Mason 	u32 blocksize;
702081e9573SChris Mason 	int progress_passed = 0;
703081e9573SChris Mason 	struct btrfs_disk_key disk_key;
7046702ed49SChris Mason 
7050b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
7060b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
70786479a04SChris Mason 
7086b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
7090b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
7105dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
7116702ed49SChris Mason 
7125dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
7136702ed49SChris Mason 		return 0;
7146702ed49SChris Mason 
7155dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
7166702ed49SChris Mason 		int close = 1;
717a6b6e75eSChris Mason 
718081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
719081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
720081e9573SChris Mason 			continue;
721081e9573SChris Mason 
722081e9573SChris Mason 		progress_passed = 1;
7236b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
724e9d0b13bSChris Mason 		if (last_block == 0)
725e9d0b13bSChris Mason 			last_block = blocknr;
7265708b959SChris Mason 
7276702ed49SChris Mason 		if (i > 0) {
7286b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
7296b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
7306702ed49SChris Mason 		}
7315dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
7326b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
7336b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
7346702ed49SChris Mason 		}
735e9d0b13bSChris Mason 		if (close) {
736e9d0b13bSChris Mason 			last_block = blocknr;
7376702ed49SChris Mason 			continue;
738e9d0b13bSChris Mason 		}
7396702ed49SChris Mason 
740206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
741206983b7SJosef Bacik 		if (IS_ERR(cur))
74264c043deSLiu Bo 			return PTR_ERR(cur);
743e9d0b13bSChris Mason 		if (search_start == 0)
7446b80053dSChris Mason 			search_start = last_block;
745e9d0b13bSChris Mason 
746e7a84565SChris Mason 		btrfs_tree_lock(cur);
7476b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
748e7a84565SChris Mason 					&cur, search_start,
7496b80053dSChris Mason 					min(16 * blocksize,
7509631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
7519631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
752252c38f0SYan 		if (err) {
753e7a84565SChris Mason 			btrfs_tree_unlock(cur);
7546b80053dSChris Mason 			free_extent_buffer(cur);
7556702ed49SChris Mason 			break;
756252c38f0SYan 		}
757e7a84565SChris Mason 		search_start = cur->start;
758e7a84565SChris Mason 		last_block = cur->start;
759f2183bdeSChris Mason 		*last_ret = search_start;
760e7a84565SChris Mason 		btrfs_tree_unlock(cur);
761e7a84565SChris Mason 		free_extent_buffer(cur);
7626702ed49SChris Mason 	}
7636702ed49SChris Mason 	return err;
7646702ed49SChris Mason }
7656702ed49SChris Mason 
76674123bd7SChris Mason /*
767fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
7685f39d397SChris Mason  *
769fb81212cSFilipe Manana  * The lower boundary for the search is specified by the slot number @low. Use a
770fb81212cSFilipe Manana  * value of 0 to search over the whole extent buffer.
77174123bd7SChris Mason  *
772fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
773fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
774fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
775fb81212cSFilipe Manana  *
776fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
777fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
77874123bd7SChris Mason  */
779fb81212cSFilipe Manana static noinline int generic_bin_search(struct extent_buffer *eb, int low,
78067d5e289SMarcos Paulo de Souza 				       const struct btrfs_key *key, int *slot)
781be0e5c09SChris Mason {
782fb81212cSFilipe Manana 	unsigned long p;
783fb81212cSFilipe Manana 	int item_size;
78467d5e289SMarcos Paulo de Souza 	int high = btrfs_header_nritems(eb);
785be0e5c09SChris Mason 	int ret;
7865cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
787be0e5c09SChris Mason 
7885e24e9afSLiu Bo 	if (low > high) {
7895e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
7905e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
7915e24e9afSLiu Bo 			  __func__, low, high, eb->start,
7925e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
7935e24e9afSLiu Bo 		return -EINVAL;
7945e24e9afSLiu Bo 	}
7955e24e9afSLiu Bo 
796fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
797fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
798fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
799fb81212cSFilipe Manana 	} else {
800fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
801fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
802fb81212cSFilipe Manana 	}
803fb81212cSFilipe Manana 
804be0e5c09SChris Mason 	while (low < high) {
8055cd17f34SDavid Sterba 		unsigned long oip;
8065cd17f34SDavid Sterba 		unsigned long offset;
8075cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
8085cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
8095cd17f34SDavid Sterba 		int mid;
8105cd17f34SDavid Sterba 
811be0e5c09SChris Mason 		mid = (low + high) / 2;
8125f39d397SChris Mason 		offset = p + mid * item_size;
8135cd17f34SDavid Sterba 		oip = offset_in_page(offset);
8145f39d397SChris Mason 
8155cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
816884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
8175cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
818934d375bSChris Mason 
819884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
8205cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
8215cd17f34SDavid Sterba 		} else {
8225cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
8235f39d397SChris Mason 			tmp = &unaligned;
824479965d6SChris Mason 		}
825479965d6SChris Mason 
826be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
827be0e5c09SChris Mason 
828be0e5c09SChris Mason 		if (ret < 0)
829be0e5c09SChris Mason 			low = mid + 1;
830be0e5c09SChris Mason 		else if (ret > 0)
831be0e5c09SChris Mason 			high = mid;
832be0e5c09SChris Mason 		else {
833be0e5c09SChris Mason 			*slot = mid;
834be0e5c09SChris Mason 			return 0;
835be0e5c09SChris Mason 		}
836be0e5c09SChris Mason 	}
837be0e5c09SChris Mason 	*slot = low;
838be0e5c09SChris Mason 	return 1;
839be0e5c09SChris Mason }
840be0e5c09SChris Mason 
84197571fd0SChris Mason /*
842fb81212cSFilipe Manana  * Simple binary search on an extent buffer. Works for both leaves and nodes, and
843fb81212cSFilipe Manana  * always searches over the whole range of keys (slot 0 to slot 'nritems - 1').
84497571fd0SChris Mason  */
845a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
846e3b83361SQu Wenruo 		     int *slot)
847be0e5c09SChris Mason {
848fb81212cSFilipe Manana 	return generic_bin_search(eb, 0, key, slot);
849be0e5c09SChris Mason }
850be0e5c09SChris Mason 
851f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
852f0486c68SYan, Zheng {
853f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
854f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
855f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
856f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
857f0486c68SYan, Zheng }
858f0486c68SYan, Zheng 
859f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
860f0486c68SYan, Zheng {
861f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
862f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
863f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
864f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
865f0486c68SYan, Zheng }
866f0486c68SYan, Zheng 
867d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
868d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
869d352ac68SChris Mason  */
8704b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
8714b231ae4SDavid Sterba 					   int slot)
872bb803951SChris Mason {
873ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
874789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
875416bc658SJosef Bacik 	struct extent_buffer *eb;
876416bc658SJosef Bacik 
877fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
878fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
879ca7a79adSChris Mason 
880ca7a79adSChris Mason 	BUG_ON(level == 0);
881ca7a79adSChris Mason 
882789d6a3aSQu Wenruo 	check.level = level - 1;
883789d6a3aSQu Wenruo 	check.transid = btrfs_node_ptr_generation(parent, slot);
884789d6a3aSQu Wenruo 	check.owner_root = btrfs_header_owner(parent);
885789d6a3aSQu Wenruo 	check.has_first_key = true;
886789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(parent, &check.first_key, slot);
887789d6a3aSQu Wenruo 
888d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
889789d6a3aSQu Wenruo 			     &check);
8904eb150d6SQu Wenruo 	if (IS_ERR(eb))
8914eb150d6SQu Wenruo 		return eb;
8924eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
893416bc658SJosef Bacik 		free_extent_buffer(eb);
8944eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
895416bc658SJosef Bacik 	}
896416bc658SJosef Bacik 
897416bc658SJosef Bacik 	return eb;
898bb803951SChris Mason }
899bb803951SChris Mason 
900d352ac68SChris Mason /*
901d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
902d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
903d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
904d352ac68SChris Mason  */
905e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
90698ed5174SChris Mason 			 struct btrfs_root *root,
90798ed5174SChris Mason 			 struct btrfs_path *path, int level)
908bb803951SChris Mason {
9090b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
9105f39d397SChris Mason 	struct extent_buffer *right = NULL;
9115f39d397SChris Mason 	struct extent_buffer *mid;
9125f39d397SChris Mason 	struct extent_buffer *left = NULL;
9135f39d397SChris Mason 	struct extent_buffer *parent = NULL;
914bb803951SChris Mason 	int ret = 0;
915bb803951SChris Mason 	int wret;
916bb803951SChris Mason 	int pslot;
917bb803951SChris Mason 	int orig_slot = path->slots[level];
91879f95c82SChris Mason 	u64 orig_ptr;
919bb803951SChris Mason 
92098e6b1ebSLiu Bo 	ASSERT(level > 0);
921bb803951SChris Mason 
9225f39d397SChris Mason 	mid = path->nodes[level];
923b4ce94deSChris Mason 
924ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
9257bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
9267bb86316SChris Mason 
9271d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
92879f95c82SChris Mason 
929a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
9305f39d397SChris Mason 		parent = path->nodes[level + 1];
931bb803951SChris Mason 		pslot = path->slots[level + 1];
932a05a9bb1SLi Zefan 	}
933bb803951SChris Mason 
93440689478SChris Mason 	/*
93540689478SChris Mason 	 * deal with the case where there is only one pointer in the root
93640689478SChris Mason 	 * by promoting the node below to a root
93740689478SChris Mason 	 */
9385f39d397SChris Mason 	if (!parent) {
9395f39d397SChris Mason 		struct extent_buffer *child;
940bb803951SChris Mason 
9415f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
942bb803951SChris Mason 			return 0;
943bb803951SChris Mason 
944bb803951SChris Mason 		/* promote the child to a root */
9454b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
946fb770ae4SLiu Bo 		if (IS_ERR(child)) {
947fb770ae4SLiu Bo 			ret = PTR_ERR(child);
9480b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
949305a26afSMark Fasheh 			goto enospc;
950305a26afSMark Fasheh 		}
951305a26afSMark Fasheh 
952925baeddSChris Mason 		btrfs_tree_lock(child);
9539631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
9549631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
955f0486c68SYan, Zheng 		if (ret) {
956f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
957f0486c68SYan, Zheng 			free_extent_buffer(child);
958f0486c68SYan, Zheng 			goto enospc;
959f0486c68SYan, Zheng 		}
9602f375ab9SYan 
961406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
962d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
963240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
964925baeddSChris Mason 
9650b86a832SChris Mason 		add_root_to_dirty_list(root);
966925baeddSChris Mason 		btrfs_tree_unlock(child);
967b4ce94deSChris Mason 
968925baeddSChris Mason 		path->locks[level] = 0;
969bb803951SChris Mason 		path->nodes[level] = NULL;
9706a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
971925baeddSChris Mason 		btrfs_tree_unlock(mid);
972bb803951SChris Mason 		/* once for the path */
9735f39d397SChris Mason 		free_extent_buffer(mid);
974f0486c68SYan, Zheng 
975f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
9767a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
977bb803951SChris Mason 		/* once for the root ptr */
9783083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
979f0486c68SYan, Zheng 		return 0;
980bb803951SChris Mason 	}
9815f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
9820b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
983bb803951SChris Mason 		return 0;
984bb803951SChris Mason 
9854b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
986fb770ae4SLiu Bo 	if (IS_ERR(left))
987fb770ae4SLiu Bo 		left = NULL;
988fb770ae4SLiu Bo 
9895f39d397SChris Mason 	if (left) {
990bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
9915f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
9929631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
993bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
99454aa1f4dSChris Mason 		if (wret) {
99554aa1f4dSChris Mason 			ret = wret;
99654aa1f4dSChris Mason 			goto enospc;
99754aa1f4dSChris Mason 		}
9982cc58cf2SChris Mason 	}
999fb770ae4SLiu Bo 
10004b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1001fb770ae4SLiu Bo 	if (IS_ERR(right))
1002fb770ae4SLiu Bo 		right = NULL;
1003fb770ae4SLiu Bo 
10045f39d397SChris Mason 	if (right) {
1005bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
10065f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
10079631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
1008bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
10092cc58cf2SChris Mason 		if (wret) {
10102cc58cf2SChris Mason 			ret = wret;
10112cc58cf2SChris Mason 			goto enospc;
10122cc58cf2SChris Mason 		}
10132cc58cf2SChris Mason 	}
10142cc58cf2SChris Mason 
10152cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
10165f39d397SChris Mason 	if (left) {
10175f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1018d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
101979f95c82SChris Mason 		if (wret < 0)
102079f95c82SChris Mason 			ret = wret;
1021bb803951SChris Mason 	}
102279f95c82SChris Mason 
102379f95c82SChris Mason 	/*
102479f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
102579f95c82SChris Mason 	 */
10265f39d397SChris Mason 	if (right) {
1027d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
102854aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
102979f95c82SChris Mason 			ret = wret;
10305f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
10316a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1032925baeddSChris Mason 			btrfs_tree_unlock(right);
1033afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1034f0486c68SYan, Zheng 			root_sub_used(root, right->len);
10357a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
10367a163608SFilipe Manana 					      0, 1);
10373083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1038f0486c68SYan, Zheng 			right = NULL;
1039bb803951SChris Mason 		} else {
10405f39d397SChris Mason 			struct btrfs_disk_key right_key;
10415f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1042f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
104333cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
10440e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
10455f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
10465f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1047bb803951SChris Mason 		}
1048bb803951SChris Mason 	}
10495f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
105079f95c82SChris Mason 		/*
105179f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
105279f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
105379f95c82SChris Mason 		 * could try to delete the only pointer in this node.
105479f95c82SChris Mason 		 * So, pull some keys from the left.
105579f95c82SChris Mason 		 * There has to be a left pointer at this point because
105679f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
105779f95c82SChris Mason 		 * right
105879f95c82SChris Mason 		 */
1059305a26afSMark Fasheh 		if (!left) {
1060305a26afSMark Fasheh 			ret = -EROFS;
10610b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1062305a26afSMark Fasheh 			goto enospc;
1063305a26afSMark Fasheh 		}
106455d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
106554aa1f4dSChris Mason 		if (wret < 0) {
106679f95c82SChris Mason 			ret = wret;
106754aa1f4dSChris Mason 			goto enospc;
106854aa1f4dSChris Mason 		}
1069bce4eae9SChris Mason 		if (wret == 1) {
1070d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1071bce4eae9SChris Mason 			if (wret < 0)
1072bce4eae9SChris Mason 				ret = wret;
1073bce4eae9SChris Mason 		}
107479f95c82SChris Mason 		BUG_ON(wret == 1);
107579f95c82SChris Mason 	}
10765f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
10776a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1078925baeddSChris Mason 		btrfs_tree_unlock(mid);
1079afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1080f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10817a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
10823083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1083f0486c68SYan, Zheng 		mid = NULL;
108479f95c82SChris Mason 	} else {
108579f95c82SChris Mason 		/* update the parent key to reflect our changes */
10865f39d397SChris Mason 		struct btrfs_disk_key mid_key;
10875f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1088f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
108933cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
10900e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
10915f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
10925f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
109379f95c82SChris Mason 	}
1094bb803951SChris Mason 
109579f95c82SChris Mason 	/* update the path */
10965f39d397SChris Mason 	if (left) {
10975f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
109867439dadSDavid Sterba 			atomic_inc(&left->refs);
1099925baeddSChris Mason 			/* left was locked after cow */
11005f39d397SChris Mason 			path->nodes[level] = left;
1101bb803951SChris Mason 			path->slots[level + 1] -= 1;
1102bb803951SChris Mason 			path->slots[level] = orig_slot;
1103925baeddSChris Mason 			if (mid) {
1104925baeddSChris Mason 				btrfs_tree_unlock(mid);
11055f39d397SChris Mason 				free_extent_buffer(mid);
1106925baeddSChris Mason 			}
1107bb803951SChris Mason 		} else {
11085f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1109bb803951SChris Mason 			path->slots[level] = orig_slot;
1110bb803951SChris Mason 		}
1111bb803951SChris Mason 	}
111279f95c82SChris Mason 	/* double check we haven't messed things up */
1113e20d96d6SChris Mason 	if (orig_ptr !=
11145f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
111579f95c82SChris Mason 		BUG();
111654aa1f4dSChris Mason enospc:
1117925baeddSChris Mason 	if (right) {
1118925baeddSChris Mason 		btrfs_tree_unlock(right);
11195f39d397SChris Mason 		free_extent_buffer(right);
1120925baeddSChris Mason 	}
1121925baeddSChris Mason 	if (left) {
1122925baeddSChris Mason 		if (path->nodes[level] != left)
1123925baeddSChris Mason 			btrfs_tree_unlock(left);
11245f39d397SChris Mason 		free_extent_buffer(left);
1125925baeddSChris Mason 	}
1126bb803951SChris Mason 	return ret;
1127bb803951SChris Mason }
1128bb803951SChris Mason 
1129d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1130d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1131d352ac68SChris Mason  * have to be pessimistic.
1132d352ac68SChris Mason  */
1133d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1134e66f709bSChris Mason 					  struct btrfs_root *root,
1135e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1136e66f709bSChris Mason {
11370b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11385f39d397SChris Mason 	struct extent_buffer *right = NULL;
11395f39d397SChris Mason 	struct extent_buffer *mid;
11405f39d397SChris Mason 	struct extent_buffer *left = NULL;
11415f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1142e66f709bSChris Mason 	int ret = 0;
1143e66f709bSChris Mason 	int wret;
1144e66f709bSChris Mason 	int pslot;
1145e66f709bSChris Mason 	int orig_slot = path->slots[level];
1146e66f709bSChris Mason 
1147e66f709bSChris Mason 	if (level == 0)
1148e66f709bSChris Mason 		return 1;
1149e66f709bSChris Mason 
11505f39d397SChris Mason 	mid = path->nodes[level];
11517bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1152e66f709bSChris Mason 
1153a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
11545f39d397SChris Mason 		parent = path->nodes[level + 1];
1155e66f709bSChris Mason 		pslot = path->slots[level + 1];
1156a05a9bb1SLi Zefan 	}
1157e66f709bSChris Mason 
11585f39d397SChris Mason 	if (!parent)
1159e66f709bSChris Mason 		return 1;
1160e66f709bSChris Mason 
11614b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1162fb770ae4SLiu Bo 	if (IS_ERR(left))
1163fb770ae4SLiu Bo 		left = NULL;
1164e66f709bSChris Mason 
1165e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
11665f39d397SChris Mason 	if (left) {
1167e66f709bSChris Mason 		u32 left_nr;
1168925baeddSChris Mason 
1169bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1170b4ce94deSChris Mason 
11715f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
11720b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
117333ade1f8SChris Mason 			wret = 1;
117433ade1f8SChris Mason 		} else {
11755f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
11769631e4ccSJosef Bacik 					      pslot - 1, &left,
1177bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
117854aa1f4dSChris Mason 			if (ret)
117954aa1f4dSChris Mason 				wret = 1;
118054aa1f4dSChris Mason 			else {
1181d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
118254aa1f4dSChris Mason 			}
118333ade1f8SChris Mason 		}
1184e66f709bSChris Mason 		if (wret < 0)
1185e66f709bSChris Mason 			ret = wret;
1186e66f709bSChris Mason 		if (wret == 0) {
11875f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1188e66f709bSChris Mason 			orig_slot += left_nr;
11895f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1190f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
119133cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
11920e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11935f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
11945f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
11955f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
11965f39d397SChris Mason 				path->nodes[level] = left;
1197e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1198e66f709bSChris Mason 				path->slots[level] = orig_slot;
1199925baeddSChris Mason 				btrfs_tree_unlock(mid);
12005f39d397SChris Mason 				free_extent_buffer(mid);
1201e66f709bSChris Mason 			} else {
1202e66f709bSChris Mason 				orig_slot -=
12035f39d397SChris Mason 					btrfs_header_nritems(left);
1204e66f709bSChris Mason 				path->slots[level] = orig_slot;
1205925baeddSChris Mason 				btrfs_tree_unlock(left);
12065f39d397SChris Mason 				free_extent_buffer(left);
1207e66f709bSChris Mason 			}
1208e66f709bSChris Mason 			return 0;
1209e66f709bSChris Mason 		}
1210925baeddSChris Mason 		btrfs_tree_unlock(left);
12115f39d397SChris Mason 		free_extent_buffer(left);
1212e66f709bSChris Mason 	}
12134b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1214fb770ae4SLiu Bo 	if (IS_ERR(right))
1215fb770ae4SLiu Bo 		right = NULL;
1216e66f709bSChris Mason 
1217e66f709bSChris Mason 	/*
1218e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1219e66f709bSChris Mason 	 */
12205f39d397SChris Mason 	if (right) {
122133ade1f8SChris Mason 		u32 right_nr;
1222b4ce94deSChris Mason 
1223bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1224b4ce94deSChris Mason 
12255f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
12260b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
122733ade1f8SChris Mason 			wret = 1;
122833ade1f8SChris Mason 		} else {
12295f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
12305f39d397SChris Mason 					      parent, pslot + 1,
1231bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
123254aa1f4dSChris Mason 			if (ret)
123354aa1f4dSChris Mason 				wret = 1;
123454aa1f4dSChris Mason 			else {
123555d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
123633ade1f8SChris Mason 			}
123754aa1f4dSChris Mason 		}
1238e66f709bSChris Mason 		if (wret < 0)
1239e66f709bSChris Mason 			ret = wret;
1240e66f709bSChris Mason 		if (wret == 0) {
12415f39d397SChris Mason 			struct btrfs_disk_key disk_key;
12425f39d397SChris Mason 
12435f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1244f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
124533cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
12460e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
12475f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
12485f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12495f39d397SChris Mason 
12505f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
12515f39d397SChris Mason 				path->nodes[level] = right;
1252e66f709bSChris Mason 				path->slots[level + 1] += 1;
1253e66f709bSChris Mason 				path->slots[level] = orig_slot -
12545f39d397SChris Mason 					btrfs_header_nritems(mid);
1255925baeddSChris Mason 				btrfs_tree_unlock(mid);
12565f39d397SChris Mason 				free_extent_buffer(mid);
1257e66f709bSChris Mason 			} else {
1258925baeddSChris Mason 				btrfs_tree_unlock(right);
12595f39d397SChris Mason 				free_extent_buffer(right);
1260e66f709bSChris Mason 			}
1261e66f709bSChris Mason 			return 0;
1262e66f709bSChris Mason 		}
1263925baeddSChris Mason 		btrfs_tree_unlock(right);
12645f39d397SChris Mason 		free_extent_buffer(right);
1265e66f709bSChris Mason 	}
1266e66f709bSChris Mason 	return 1;
1267e66f709bSChris Mason }
1268e66f709bSChris Mason 
126974123bd7SChris Mason /*
1270d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1271d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
12723c69faecSChris Mason  */
12732ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1274e02119d5SChris Mason 			     struct btrfs_path *path,
127501f46658SChris Mason 			     int level, int slot, u64 objectid)
12763c69faecSChris Mason {
12775f39d397SChris Mason 	struct extent_buffer *node;
127801f46658SChris Mason 	struct btrfs_disk_key disk_key;
12793c69faecSChris Mason 	u32 nritems;
12803c69faecSChris Mason 	u64 search;
1281a7175319SChris Mason 	u64 target;
12826b80053dSChris Mason 	u64 nread = 0;
1283ace75066SFilipe Manana 	u64 nread_max;
12846b80053dSChris Mason 	u32 nr;
12856b80053dSChris Mason 	u32 blocksize;
12866b80053dSChris Mason 	u32 nscan = 0;
1287db94535dSChris Mason 
1288ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
12893c69faecSChris Mason 		return;
12903c69faecSChris Mason 
12916702ed49SChris Mason 	if (!path->nodes[level])
12926702ed49SChris Mason 		return;
12936702ed49SChris Mason 
12945f39d397SChris Mason 	node = path->nodes[level];
1295925baeddSChris Mason 
1296ace75066SFilipe Manana 	/*
1297ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1298ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1299ace75066SFilipe Manana 	 * much IO at once (possibly random).
1300ace75066SFilipe Manana 	 */
1301ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1302ace75066SFilipe Manana 		if (level > 1)
1303ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1304ace75066SFilipe Manana 		else
1305ace75066SFilipe Manana 			nread_max = SZ_128K;
1306ace75066SFilipe Manana 	} else {
1307ace75066SFilipe Manana 		nread_max = SZ_64K;
1308ace75066SFilipe Manana 	}
1309ace75066SFilipe Manana 
13103c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
13110b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1312069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1313069a2e37SFilipe Manana 		struct extent_buffer *eb;
1314069a2e37SFilipe Manana 
13150b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
13165f39d397SChris Mason 		if (eb) {
13175f39d397SChris Mason 			free_extent_buffer(eb);
13183c69faecSChris Mason 			return;
13193c69faecSChris Mason 		}
1320069a2e37SFilipe Manana 	}
13213c69faecSChris Mason 
1322a7175319SChris Mason 	target = search;
13236b80053dSChris Mason 
13245f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
13256b80053dSChris Mason 	nr = slot;
132625b8b936SJosef Bacik 
13273c69faecSChris Mason 	while (1) {
1328e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
13296b80053dSChris Mason 			if (nr == 0)
13303c69faecSChris Mason 				break;
13316b80053dSChris Mason 			nr--;
1332ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1333ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
13346b80053dSChris Mason 			nr++;
13356b80053dSChris Mason 			if (nr >= nritems)
13366b80053dSChris Mason 				break;
13373c69faecSChris Mason 		}
1338e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
133901f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
134001f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
134101f46658SChris Mason 				break;
134201f46658SChris Mason 		}
13436b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1344ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1345ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1346a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1347bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
13486b80053dSChris Mason 			nread += blocksize;
13493c69faecSChris Mason 		}
13506b80053dSChris Mason 		nscan++;
1351ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
13526b80053dSChris Mason 			break;
13533c69faecSChris Mason 	}
13543c69faecSChris Mason }
1355925baeddSChris Mason 
1356bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1357b4ce94deSChris Mason {
1358bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1359b4ce94deSChris Mason 	int slot;
1360b4ce94deSChris Mason 	int nritems;
1361b4ce94deSChris Mason 
13628c594ea8SChris Mason 	parent = path->nodes[level + 1];
1363b4ce94deSChris Mason 	if (!parent)
13640b08851fSJosef Bacik 		return;
1365b4ce94deSChris Mason 
1366b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
13678c594ea8SChris Mason 	slot = path->slots[level + 1];
1368b4ce94deSChris Mason 
1369bfb484d9SJosef Bacik 	if (slot > 0)
1370bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1371bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1372bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1373b4ce94deSChris Mason }
1374b4ce94deSChris Mason 
1375b4ce94deSChris Mason 
1376b4ce94deSChris Mason /*
1377d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1378d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1379d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1380d397712bSChris Mason  * tree.
1381d352ac68SChris Mason  *
1382d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1383d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1384d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1385d352ac68SChris Mason  *
1386d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1387d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1388d352ac68SChris Mason  */
1389e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1390f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1391f7c79f30SChris Mason 			       int *write_lock_level)
1392925baeddSChris Mason {
1393925baeddSChris Mason 	int i;
1394925baeddSChris Mason 	int skip_level = level;
1395c1227996SNikolay Borisov 	bool check_skip = true;
1396925baeddSChris Mason 
1397925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1398925baeddSChris Mason 		if (!path->nodes[i])
1399925baeddSChris Mason 			break;
1400925baeddSChris Mason 		if (!path->locks[i])
1401925baeddSChris Mason 			break;
1402c1227996SNikolay Borisov 
1403c1227996SNikolay Borisov 		if (check_skip) {
1404c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1405925baeddSChris Mason 				skip_level = i + 1;
1406925baeddSChris Mason 				continue;
1407925baeddSChris Mason 			}
1408c1227996SNikolay Borisov 
1409c1227996SNikolay Borisov 			if (path->keep_locks) {
1410925baeddSChris Mason 				u32 nritems;
1411c1227996SNikolay Borisov 
1412c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1413051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1414925baeddSChris Mason 					skip_level = i + 1;
1415925baeddSChris Mason 					continue;
1416925baeddSChris Mason 				}
1417925baeddSChris Mason 			}
1418c1227996SNikolay Borisov 		}
1419051e1b9fSChris Mason 
1420d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1421c1227996SNikolay Borisov 			check_skip = false;
1422c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1423925baeddSChris Mason 			path->locks[i] = 0;
1424f7c79f30SChris Mason 			if (write_lock_level &&
1425f7c79f30SChris Mason 			    i > min_write_lock_level &&
1426f7c79f30SChris Mason 			    i <= *write_lock_level) {
1427f7c79f30SChris Mason 				*write_lock_level = i - 1;
1428f7c79f30SChris Mason 			}
1429925baeddSChris Mason 		}
1430925baeddSChris Mason 	}
1431925baeddSChris Mason }
1432925baeddSChris Mason 
14333c69faecSChris Mason /*
1434376a21d7SFilipe Manana  * Helper function for btrfs_search_slot() and other functions that do a search
1435376a21d7SFilipe Manana  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1436376a21d7SFilipe Manana  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1437376a21d7SFilipe Manana  * its pages from disk.
1438c8c42864SChris Mason  *
1439376a21d7SFilipe Manana  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1440376a21d7SFilipe Manana  * whole btree search, starting again from the current root node.
1441c8c42864SChris Mason  */
1442c8c42864SChris Mason static int
1443d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1444c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1445cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1446c8c42864SChris Mason {
14470b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1448789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = { 0 };
1449c8c42864SChris Mason 	u64 blocknr;
1450c8c42864SChris Mason 	u64 gen;
1451c8c42864SChris Mason 	struct extent_buffer *tmp;
145276a05b35SChris Mason 	int ret;
1453581c1760SQu Wenruo 	int parent_level;
1454b246666eSFilipe Manana 	bool unlock_up;
1455c8c42864SChris Mason 
1456b246666eSFilipe Manana 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1457213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1458213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1459213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1460789d6a3aSQu Wenruo 	btrfs_node_key_to_cpu(*eb_ret, &check.first_key, slot);
1461789d6a3aSQu Wenruo 	check.has_first_key = true;
1462789d6a3aSQu Wenruo 	check.level = parent_level - 1;
1463789d6a3aSQu Wenruo 	check.transid = gen;
1464789d6a3aSQu Wenruo 	check.owner_root = root->root_key.objectid;
1465c8c42864SChris Mason 
1466b246666eSFilipe Manana 	/*
1467b246666eSFilipe Manana 	 * If we need to read an extent buffer from disk and we are holding locks
1468b246666eSFilipe Manana 	 * on upper level nodes, we unlock all the upper nodes before reading the
1469b246666eSFilipe Manana 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1470b246666eSFilipe Manana 	 * restart the search. We don't release the lock on the current level
1471b246666eSFilipe Manana 	 * because we need to walk this node to figure out which blocks to read.
1472b246666eSFilipe Manana 	 */
14730b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1474cb44921aSChris Mason 	if (tmp) {
1475ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1476ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1477ace75066SFilipe Manana 
1478b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1479b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1480448de471SQu Wenruo 			/*
1481448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1482448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1483448de471SQu Wenruo 			 * parents (shared tree blocks).
1484448de471SQu Wenruo 			 */
1485e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1486789d6a3aSQu Wenruo 					parent_level - 1, &check.first_key, gen)) {
1487448de471SQu Wenruo 				free_extent_buffer(tmp);
1488448de471SQu Wenruo 				return -EUCLEAN;
1489448de471SQu Wenruo 			}
1490c8c42864SChris Mason 			*eb_ret = tmp;
1491c8c42864SChris Mason 			return 0;
1492c8c42864SChris Mason 		}
1493bdf7c00eSJosef Bacik 
1494857bc13fSJosef Bacik 		if (p->nowait) {
1495857bc13fSJosef Bacik 			free_extent_buffer(tmp);
1496857bc13fSJosef Bacik 			return -EAGAIN;
1497857bc13fSJosef Bacik 		}
1498857bc13fSJosef Bacik 
1499b246666eSFilipe Manana 		if (unlock_up)
1500b246666eSFilipe Manana 			btrfs_unlock_up_safe(p, level + 1);
1501b246666eSFilipe Manana 
1502b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
1503789d6a3aSQu Wenruo 		ret = btrfs_read_extent_buffer(tmp, &check);
15049a4ffa1bSQu Wenruo 		if (ret) {
1505cb44921aSChris Mason 			free_extent_buffer(tmp);
1506b3b4aa74SDavid Sterba 			btrfs_release_path(p);
1507cb44921aSChris Mason 			return -EIO;
1508cb44921aSChris Mason 		}
150988c602abSQu Wenruo 		if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
151088c602abSQu Wenruo 			free_extent_buffer(tmp);
151188c602abSQu Wenruo 			btrfs_release_path(p);
151288c602abSQu Wenruo 			return -EUCLEAN;
151388c602abSQu Wenruo 		}
1514b246666eSFilipe Manana 
1515b246666eSFilipe Manana 		if (unlock_up)
1516b246666eSFilipe Manana 			ret = -EAGAIN;
1517b246666eSFilipe Manana 
1518b246666eSFilipe Manana 		goto out;
1519857bc13fSJosef Bacik 	} else if (p->nowait) {
1520857bc13fSJosef Bacik 		return -EAGAIN;
15219a4ffa1bSQu Wenruo 	}
1522c8c42864SChris Mason 
1523b246666eSFilipe Manana 	if (unlock_up) {
15248c594ea8SChris Mason 		btrfs_unlock_up_safe(p, level + 1);
15254bb59055SFilipe Manana 		ret = -EAGAIN;
15264bb59055SFilipe Manana 	} else {
15274bb59055SFilipe Manana 		ret = 0;
15284bb59055SFilipe Manana 	}
15298c594ea8SChris Mason 
1530e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
15312ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1532c8c42864SChris Mason 
1533789d6a3aSQu Wenruo 	tmp = read_tree_block(fs_info, blocknr, &check);
15344eb150d6SQu Wenruo 	if (IS_ERR(tmp)) {
15354eb150d6SQu Wenruo 		btrfs_release_path(p);
15364eb150d6SQu Wenruo 		return PTR_ERR(tmp);
15374eb150d6SQu Wenruo 	}
153876a05b35SChris Mason 	/*
153976a05b35SChris Mason 	 * If the read above didn't mark this buffer up to date,
154076a05b35SChris Mason 	 * it will never end up being up to date.  Set ret to EIO now
154176a05b35SChris Mason 	 * and give up so that our caller doesn't loop forever
154276a05b35SChris Mason 	 * on our EAGAINs.
154376a05b35SChris Mason 	 */
1544e6a1d6fdSLiu Bo 	if (!extent_buffer_uptodate(tmp))
154576a05b35SChris Mason 		ret = -EIO;
154602a3307aSLiu Bo 
1547b246666eSFilipe Manana out:
15484bb59055SFilipe Manana 	if (ret == 0) {
15494bb59055SFilipe Manana 		*eb_ret = tmp;
15504bb59055SFilipe Manana 	} else {
15514bb59055SFilipe Manana 		free_extent_buffer(tmp);
155202a3307aSLiu Bo 		btrfs_release_path(p);
15534bb59055SFilipe Manana 	}
15544bb59055SFilipe Manana 
155576a05b35SChris Mason 	return ret;
1556c8c42864SChris Mason }
1557c8c42864SChris Mason 
1558c8c42864SChris Mason /*
1559c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1560c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1561c8c42864SChris Mason  * the ins_len.
1562c8c42864SChris Mason  *
1563c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1564c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1565c8c42864SChris Mason  * start over
1566c8c42864SChris Mason  */
1567c8c42864SChris Mason static int
1568c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1569c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1570bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1571bd681513SChris Mason 		       int *write_lock_level)
1572c8c42864SChris Mason {
15730b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
157495b982deSNikolay Borisov 	int ret = 0;
15750b246afaSJeff Mahoney 
1576c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
15770b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1578c8c42864SChris Mason 
1579bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1580bd681513SChris Mason 			*write_lock_level = level + 1;
1581bd681513SChris Mason 			btrfs_release_path(p);
158295b982deSNikolay Borisov 			return -EAGAIN;
1583bd681513SChris Mason 		}
1584bd681513SChris Mason 
1585bfb484d9SJosef Bacik 		reada_for_balance(p, level);
158695b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1587c8c42864SChris Mason 
1588c8c42864SChris Mason 		b = p->nodes[level];
1589c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
15900b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1591c8c42864SChris Mason 
1592bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1593bd681513SChris Mason 			*write_lock_level = level + 1;
1594bd681513SChris Mason 			btrfs_release_path(p);
159595b982deSNikolay Borisov 			return -EAGAIN;
1596bd681513SChris Mason 		}
1597bd681513SChris Mason 
1598bfb484d9SJosef Bacik 		reada_for_balance(p, level);
159995b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
160095b982deSNikolay Borisov 		if (ret)
160195b982deSNikolay Borisov 			return ret;
1602c8c42864SChris Mason 
1603c8c42864SChris Mason 		b = p->nodes[level];
1604c8c42864SChris Mason 		if (!b) {
1605b3b4aa74SDavid Sterba 			btrfs_release_path(p);
160695b982deSNikolay Borisov 			return -EAGAIN;
1607c8c42864SChris Mason 		}
1608c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1609c8c42864SChris Mason 	}
1610c8c42864SChris Mason 	return ret;
1611c8c42864SChris Mason }
1612c8c42864SChris Mason 
1613381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1614e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1615e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1616e33d5c3dSKelley Nielsen {
1617e33d5c3dSKelley Nielsen 	int ret;
1618e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1619e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1620381cf658SDavid Sterba 
1621381cf658SDavid Sterba 	ASSERT(path);
16221d4c08e0SDavid Sterba 	ASSERT(found_key);
1623e33d5c3dSKelley Nielsen 
1624e33d5c3dSKelley Nielsen 	key.type = key_type;
1625e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1626e33d5c3dSKelley Nielsen 	key.offset = ioff;
1627e33d5c3dSKelley Nielsen 
1628e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
16291d4c08e0SDavid Sterba 	if (ret < 0)
1630e33d5c3dSKelley Nielsen 		return ret;
1631e33d5c3dSKelley Nielsen 
1632e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1633e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1634e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1635e33d5c3dSKelley Nielsen 		if (ret)
1636e33d5c3dSKelley Nielsen 			return ret;
1637e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1638e33d5c3dSKelley Nielsen 	}
1639e33d5c3dSKelley Nielsen 
1640e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1641e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1642e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1643e33d5c3dSKelley Nielsen 		return 1;
1644e33d5c3dSKelley Nielsen 
1645e33d5c3dSKelley Nielsen 	return 0;
1646e33d5c3dSKelley Nielsen }
1647e33d5c3dSKelley Nielsen 
16481fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
16491fc28d8eSLiu Bo 							struct btrfs_path *p,
16501fc28d8eSLiu Bo 							int write_lock_level)
16511fc28d8eSLiu Bo {
16521fc28d8eSLiu Bo 	struct extent_buffer *b;
1653120de408SJosef Bacik 	int root_lock = 0;
16541fc28d8eSLiu Bo 	int level = 0;
16551fc28d8eSLiu Bo 
16561fc28d8eSLiu Bo 	if (p->search_commit_root) {
16571fc28d8eSLiu Bo 		b = root->commit_root;
165867439dadSDavid Sterba 		atomic_inc(&b->refs);
16591fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1660f9ddfd05SLiu Bo 		/*
1661f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1662f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1663f9ddfd05SLiu Bo 		 */
1664f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
16651fc28d8eSLiu Bo 
16661fc28d8eSLiu Bo 		goto out;
16671fc28d8eSLiu Bo 	}
16681fc28d8eSLiu Bo 
16691fc28d8eSLiu Bo 	if (p->skip_locking) {
16701fc28d8eSLiu Bo 		b = btrfs_root_node(root);
16711fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16721fc28d8eSLiu Bo 		goto out;
16731fc28d8eSLiu Bo 	}
16741fc28d8eSLiu Bo 
1675120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1676120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1677120de408SJosef Bacik 
16781fc28d8eSLiu Bo 	/*
1679662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1680662c653bSLiu Bo 	 * lock.
1681662c653bSLiu Bo 	 */
1682662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1683662c653bSLiu Bo 		/*
1684662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1685662c653bSLiu Bo 		 * have it read locked
16861fc28d8eSLiu Bo 		 */
1687857bc13fSJosef Bacik 		if (p->nowait) {
1688857bc13fSJosef Bacik 			b = btrfs_try_read_lock_root_node(root);
1689857bc13fSJosef Bacik 			if (IS_ERR(b))
1690857bc13fSJosef Bacik 				return b;
1691857bc13fSJosef Bacik 		} else {
16921bb96598SJosef Bacik 			b = btrfs_read_lock_root_node(root);
1693857bc13fSJosef Bacik 		}
16941fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16951fc28d8eSLiu Bo 		if (level > write_lock_level)
16961fc28d8eSLiu Bo 			goto out;
16971fc28d8eSLiu Bo 
1698662c653bSLiu Bo 		/* Whoops, must trade for write lock */
16991fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
17001fc28d8eSLiu Bo 		free_extent_buffer(b);
1701662c653bSLiu Bo 	}
1702662c653bSLiu Bo 
17031fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
17041fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
17051fc28d8eSLiu Bo 
17061fc28d8eSLiu Bo 	/* The level might have changed, check again */
17071fc28d8eSLiu Bo 	level = btrfs_header_level(b);
17081fc28d8eSLiu Bo 
17091fc28d8eSLiu Bo out:
1710120de408SJosef Bacik 	/*
1711120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1712120de408SJosef Bacik 	 * longer valid, return an error in this case.
1713120de408SJosef Bacik 	 */
1714120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1715120de408SJosef Bacik 		if (root_lock)
1716120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1717120de408SJosef Bacik 		free_extent_buffer(b);
1718120de408SJosef Bacik 		return ERR_PTR(-EIO);
1719120de408SJosef Bacik 	}
1720120de408SJosef Bacik 
17211fc28d8eSLiu Bo 	p->nodes[level] = b;
17221fc28d8eSLiu Bo 	if (!p->skip_locking)
17231fc28d8eSLiu Bo 		p->locks[level] = root_lock;
17241fc28d8eSLiu Bo 	/*
17251fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
17261fc28d8eSLiu Bo 	 */
17271fc28d8eSLiu Bo 	return b;
17281fc28d8eSLiu Bo }
17291fc28d8eSLiu Bo 
1730d96b3424SFilipe Manana /*
1731d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1732d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1733d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1734d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1735d96b3424SFilipe Manana  * reallocated in the next transaction.
1736d96b3424SFilipe Manana  *
1737d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1738d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1739d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1740d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1741d96b3424SFilipe Manana  */
1742d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1743d96b3424SFilipe Manana {
1744d96b3424SFilipe Manana 	const int i = path->lowest_level;
1745d96b3424SFilipe Manana 	const int slot = path->slots[i];
1746d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1747d96b3424SFilipe Manana 	struct extent_buffer *clone;
1748d96b3424SFilipe Manana 
1749d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1750d96b3424SFilipe Manana 
1751d96b3424SFilipe Manana 	if (!lowest)
1752d96b3424SFilipe Manana 		return 0;
1753d96b3424SFilipe Manana 
1754d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1755d96b3424SFilipe Manana 
1756d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1757d96b3424SFilipe Manana 	if (!clone)
1758d96b3424SFilipe Manana 		return -ENOMEM;
1759d96b3424SFilipe Manana 
1760d96b3424SFilipe Manana 	btrfs_release_path(path);
1761d96b3424SFilipe Manana 	path->nodes[i] = clone;
1762d96b3424SFilipe Manana 	path->slots[i] = slot;
1763d96b3424SFilipe Manana 
1764d96b3424SFilipe Manana 	return 0;
1765d96b3424SFilipe Manana }
17661fc28d8eSLiu Bo 
1767e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1768e2e58d0fSFilipe Manana 				      int search_low_slot,
1769e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1770e2e58d0fSFilipe Manana 				      int prev_cmp,
1771e2e58d0fSFilipe Manana 				      int *slot)
1772e2e58d0fSFilipe Manana {
1773e2e58d0fSFilipe Manana 	/*
1774e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1775e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1776e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1777e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1778e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1779e2e58d0fSFilipe Manana 	 */
1780e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1781e2e58d0fSFilipe Manana 		*slot = 0;
1782e2e58d0fSFilipe Manana 		return 0;
1783e2e58d0fSFilipe Manana 	}
1784e2e58d0fSFilipe Manana 
1785e2e58d0fSFilipe Manana 	return generic_bin_search(eb, search_low_slot, key, slot);
1786e2e58d0fSFilipe Manana }
1787e2e58d0fSFilipe Manana 
1788109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1789109324cfSFilipe Manana 		       struct btrfs_root *root,
1790109324cfSFilipe Manana 		       const struct btrfs_key *key,
1791109324cfSFilipe Manana 		       struct btrfs_path *path,
1792109324cfSFilipe Manana 		       int ins_len,
1793109324cfSFilipe Manana 		       int prev_cmp)
1794109324cfSFilipe Manana {
1795109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
1796109324cfSFilipe Manana 	int leaf_free_space = -1;
1797109324cfSFilipe Manana 	int search_low_slot = 0;
1798109324cfSFilipe Manana 	int ret;
1799109324cfSFilipe Manana 	bool do_bin_search = true;
1800109324cfSFilipe Manana 
1801109324cfSFilipe Manana 	/*
1802109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
1803109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
1804109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
1805109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1806109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
1807109324cfSFilipe Manana 	 */
1808109324cfSFilipe Manana 	if (ins_len > 0) {
1809109324cfSFilipe Manana 		/*
1810109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
1811109324cfSFilipe Manana 		 * will not change until then.
1812109324cfSFilipe Manana 		 */
1813109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
1814109324cfSFilipe Manana 
1815109324cfSFilipe Manana 		/*
1816109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
1817109324cfSFilipe Manana 		 * the root of the tree.
1818109324cfSFilipe Manana 		 */
1819109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
1820109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
1821109324cfSFilipe Manana 
1822109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
1823109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
1824109324cfSFilipe Manana 
1825109324cfSFilipe Manana 			/*
1826109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
1827109324cfSFilipe Manana 			 * taking into account that the first key is very likely
1828109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
1829109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
1830109324cfSFilipe Manana 			 * the header's level field.
1831109324cfSFilipe Manana 			 */
1832109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
1833109324cfSFilipe Manana 			if (ret < 0) {
1834109324cfSFilipe Manana 				/*
1835109324cfSFilipe Manana 				 * The first key is smaller than the key we want
1836109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
1837109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
1838109324cfSFilipe Manana 				 *
1839109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
1840109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
1841109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
1842109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
1843109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
1844109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
1845109324cfSFilipe Manana 				 */
1846109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
1847109324cfSFilipe Manana 				search_low_slot = 1;
1848109324cfSFilipe Manana 			} else {
1849109324cfSFilipe Manana 				/*
1850109324cfSFilipe Manana 				 * The first key is >= then the key we want to
1851109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
1852109324cfSFilipe Manana 				 * the target key will be at slot 0.
1853109324cfSFilipe Manana 				 *
1854109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
1855109324cfSFilipe Manana 				 * less than the first key, because we will need
1856109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
1857109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
1858109324cfSFilipe Manana 				 * If the key matches the first key, then we can
1859109324cfSFilipe Manana 				 * unlock all the upper nodes, using
1860109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
1861109324cfSFilipe Manana 				 * as stated above.
1862109324cfSFilipe Manana 				 */
1863109324cfSFilipe Manana 				if (ret == 0)
1864109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
1865109324cfSFilipe Manana 				/*
1866109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
1867109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
1868109324cfSFilipe Manana 				 * to adjust it.
1869109324cfSFilipe Manana 				 */
1870109324cfSFilipe Manana 				do_bin_search = false;
1871109324cfSFilipe Manana 				path->slots[0] = 0;
1872109324cfSFilipe Manana 			}
1873109324cfSFilipe Manana 		}
1874109324cfSFilipe Manana 	}
1875109324cfSFilipe Manana 
1876109324cfSFilipe Manana 	if (do_bin_search) {
1877109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
1878109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
1879109324cfSFilipe Manana 		if (ret < 0)
1880109324cfSFilipe Manana 			return ret;
1881109324cfSFilipe Manana 	}
1882109324cfSFilipe Manana 
1883109324cfSFilipe Manana 	if (ins_len > 0) {
1884109324cfSFilipe Manana 		/*
1885109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
1886109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
1887109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
1888109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
1889109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
1890109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
1891109324cfSFilipe Manana 		 * check will be correct.
1892109324cfSFilipe Manana 		 */
1893109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
1894109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
1895109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
1896109324cfSFilipe Manana 		}
1897109324cfSFilipe Manana 
1898109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
1899109324cfSFilipe Manana 
1900109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
1901109324cfSFilipe Manana 			int err;
1902109324cfSFilipe Manana 
1903109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
1904109324cfSFilipe Manana 					 (ret == 0));
1905bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
1906bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
1907bb8e9a60SFilipe Manana 				err = -EUCLEAN;
1908109324cfSFilipe Manana 			if (err)
1909109324cfSFilipe Manana 				ret = err;
1910109324cfSFilipe Manana 		}
1911109324cfSFilipe Manana 	}
1912109324cfSFilipe Manana 
1913109324cfSFilipe Manana 	return ret;
1914109324cfSFilipe Manana }
1915109324cfSFilipe Manana 
1916c8c42864SChris Mason /*
19174271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
19184271eceaSNikolay Borisov  * modifications to preserve tree invariants.
191974123bd7SChris Mason  *
19204271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
19214271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
19224271eceaSNikolay Borisov  * @root:	The root node of the tree
19234271eceaSNikolay Borisov  * @key:	The key we are looking for
19249a664971Sethanwu  * @ins_len:	Indicates purpose of search:
19259a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
19269a664971Sethanwu  *              <0  for deletions
19279a664971Sethanwu  *               0  for plain searches, not modifying the tree
19289a664971Sethanwu  *
19299a664971Sethanwu  *              (*) If size of item inserted doesn't include
19309a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
19319a664971Sethanwu  *              be set.
19324271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
19334271eceaSNikolay Borisov  *		when modifying the tree.
193497571fd0SChris Mason  *
19354271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
19364271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
19374271eceaSNikolay Borisov  *
19384271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
19394271eceaSNikolay Borisov  * of the path (level 0)
19404271eceaSNikolay Borisov  *
19414271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
19424271eceaSNikolay Borisov  * points to the slot where it should be inserted
19434271eceaSNikolay Borisov  *
19444271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
19454271eceaSNikolay Borisov  * is returned
194674123bd7SChris Mason  */
1947310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1948310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
1949310712b2SOmar Sandoval 		      int ins_len, int cow)
1950be0e5c09SChris Mason {
1951d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
19525f39d397SChris Mason 	struct extent_buffer *b;
1953be0e5c09SChris Mason 	int slot;
1954be0e5c09SChris Mason 	int ret;
195533c66f43SYan Zheng 	int err;
1956be0e5c09SChris Mason 	int level;
1957925baeddSChris Mason 	int lowest_unlock = 1;
1958bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
1959bd681513SChris Mason 	int write_lock_level = 0;
19609f3a7427SChris Mason 	u8 lowest_level = 0;
1961f7c79f30SChris Mason 	int min_write_lock_level;
1962d7396f07SFilipe David Borba Manana 	int prev_cmp;
19639f3a7427SChris Mason 
19646702ed49SChris Mason 	lowest_level = p->lowest_level;
1965323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
196622b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
1967eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
196825179201SJosef Bacik 
1969857bc13fSJosef Bacik 	/*
1970857bc13fSJosef Bacik 	 * For now only allow nowait for read only operations.  There's no
1971857bc13fSJosef Bacik 	 * strict reason why we can't, we just only need it for reads so it's
1972857bc13fSJosef Bacik 	 * only implemented for reads.
1973857bc13fSJosef Bacik 	 */
1974857bc13fSJosef Bacik 	ASSERT(!p->nowait || !cow);
1975857bc13fSJosef Bacik 
1976bd681513SChris Mason 	if (ins_len < 0) {
1977925baeddSChris Mason 		lowest_unlock = 2;
197865b51a00SChris Mason 
1979bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
1980bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
1981bd681513SChris Mason 		 * for those levels as well
1982bd681513SChris Mason 		 */
1983bd681513SChris Mason 		write_lock_level = 2;
1984bd681513SChris Mason 	} else if (ins_len > 0) {
1985bd681513SChris Mason 		/*
1986bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
1987bd681513SChris Mason 		 * level 1 so we can update keys
1988bd681513SChris Mason 		 */
1989bd681513SChris Mason 		write_lock_level = 1;
1990bd681513SChris Mason 	}
1991bd681513SChris Mason 
1992bd681513SChris Mason 	if (!cow)
1993bd681513SChris Mason 		write_lock_level = -1;
1994bd681513SChris Mason 
199509a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
1996bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
1997bd681513SChris Mason 
1998f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
1999f7c79f30SChris Mason 
2000d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2001d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
2002857bc13fSJosef Bacik 		if (p->nowait) {
2003857bc13fSJosef Bacik 			if (!down_read_trylock(&fs_info->commit_root_sem))
2004857bc13fSJosef Bacik 				return -EAGAIN;
2005857bc13fSJosef Bacik 		} else {
2006d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
2007d96b3424SFilipe Manana 		}
2008857bc13fSJosef Bacik 	}
2009d96b3424SFilipe Manana 
2010bb803951SChris Mason again:
2011d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
20121fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2013be6821f8SFilipe Manana 	if (IS_ERR(b)) {
2014be6821f8SFilipe Manana 		ret = PTR_ERR(b);
2015be6821f8SFilipe Manana 		goto done;
2016be6821f8SFilipe Manana 	}
2017925baeddSChris Mason 
2018eb60ceacSChris Mason 	while (b) {
2019f624d976SQu Wenruo 		int dec = 0;
2020f624d976SQu Wenruo 
20215f39d397SChris Mason 		level = btrfs_header_level(b);
202265b51a00SChris Mason 
202302217ed2SChris Mason 		if (cow) {
20249ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
20259ea2c7c9SNikolay Borisov 
2026c8c42864SChris Mason 			/*
2027c8c42864SChris Mason 			 * if we don't really need to cow this block
2028c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2029c8c42864SChris Mason 			 * so we test it here
2030c8c42864SChris Mason 			 */
20315963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
203265b51a00SChris Mason 				goto cow_done;
20335d4f98a2SYan Zheng 
2034bd681513SChris Mason 			/*
2035bd681513SChris Mason 			 * must have write locks on this node and the
2036bd681513SChris Mason 			 * parent
2037bd681513SChris Mason 			 */
20385124e00eSJosef Bacik 			if (level > write_lock_level ||
20395124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
20405124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
20415124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2042bd681513SChris Mason 				write_lock_level = level + 1;
2043bd681513SChris Mason 				btrfs_release_path(p);
2044bd681513SChris Mason 				goto again;
2045bd681513SChris Mason 			}
2046bd681513SChris Mason 
20479ea2c7c9SNikolay Borisov 			if (last_level)
20489ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
20499631e4ccSJosef Bacik 						      &b,
20509631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
20519ea2c7c9SNikolay Borisov 			else
205233c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2053e20d96d6SChris Mason 						      p->nodes[level + 1],
20549631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
20559631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
205633c66f43SYan Zheng 			if (err) {
205733c66f43SYan Zheng 				ret = err;
205865b51a00SChris Mason 				goto done;
205954aa1f4dSChris Mason 			}
206002217ed2SChris Mason 		}
206165b51a00SChris Mason cow_done:
2062eb60ceacSChris Mason 		p->nodes[level] = b;
2063b4ce94deSChris Mason 
2064b4ce94deSChris Mason 		/*
2065b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2066b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2067b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2068b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2069b4ce94deSChris Mason 		 *
2070eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2071eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2072eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2073eb653de1SFilipe David Borba Manana 		 * we're operating on.
2074b4ce94deSChris Mason 		 */
2075eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2076eb653de1SFilipe David Borba Manana 			int u = level + 1;
2077eb653de1SFilipe David Borba Manana 
2078eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2079eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2080eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2081eb653de1SFilipe David Borba Manana 			}
2082eb653de1SFilipe David Borba Manana 		}
2083b4ce94deSChris Mason 
2084e2e58d0fSFilipe Manana 		if (level == 0) {
2085109324cfSFilipe Manana 			if (ins_len > 0)
2086e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
2087bd681513SChris Mason 
2088109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2089459931ecSChris Mason 			if (!p->search_for_split)
2090f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
20914b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
209265b51a00SChris Mason 			goto done;
209365b51a00SChris Mason 		}
2094e2e58d0fSFilipe Manana 
2095e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2096e2e58d0fSFilipe Manana 		if (ret < 0)
2097e2e58d0fSFilipe Manana 			goto done;
2098e2e58d0fSFilipe Manana 		prev_cmp = ret;
2099e2e58d0fSFilipe Manana 
2100f624d976SQu Wenruo 		if (ret && slot > 0) {
2101f624d976SQu Wenruo 			dec = 1;
2102f624d976SQu Wenruo 			slot--;
2103f624d976SQu Wenruo 		}
2104f624d976SQu Wenruo 		p->slots[level] = slot;
2105f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2106f624d976SQu Wenruo 					     &write_lock_level);
2107f624d976SQu Wenruo 		if (err == -EAGAIN)
2108f624d976SQu Wenruo 			goto again;
2109f624d976SQu Wenruo 		if (err) {
2110f624d976SQu Wenruo 			ret = err;
2111f624d976SQu Wenruo 			goto done;
2112f624d976SQu Wenruo 		}
2113f624d976SQu Wenruo 		b = p->nodes[level];
2114f624d976SQu Wenruo 		slot = p->slots[level];
2115f624d976SQu Wenruo 
2116f624d976SQu Wenruo 		/*
2117f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2118f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2119f624d976SQu Wenruo 		 * the parent
2120f624d976SQu Wenruo 		 */
2121f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2122f624d976SQu Wenruo 			write_lock_level = level + 1;
2123f624d976SQu Wenruo 			btrfs_release_path(p);
2124f624d976SQu Wenruo 			goto again;
2125f624d976SQu Wenruo 		}
2126f624d976SQu Wenruo 
2127f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2128f624d976SQu Wenruo 			  &write_lock_level);
2129f624d976SQu Wenruo 
2130f624d976SQu Wenruo 		if (level == lowest_level) {
2131f624d976SQu Wenruo 			if (dec)
2132f624d976SQu Wenruo 				p->slots[level]++;
2133f624d976SQu Wenruo 			goto done;
2134f624d976SQu Wenruo 		}
2135f624d976SQu Wenruo 
2136f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2137f624d976SQu Wenruo 		if (err == -EAGAIN)
2138f624d976SQu Wenruo 			goto again;
2139f624d976SQu Wenruo 		if (err) {
2140f624d976SQu Wenruo 			ret = err;
2141f624d976SQu Wenruo 			goto done;
2142f624d976SQu Wenruo 		}
2143f624d976SQu Wenruo 
2144f624d976SQu Wenruo 		if (!p->skip_locking) {
2145f624d976SQu Wenruo 			level = btrfs_header_level(b);
2146b40130b2SJosef Bacik 
2147b40130b2SJosef Bacik 			btrfs_maybe_reset_lockdep_class(root, b);
2148b40130b2SJosef Bacik 
2149f624d976SQu Wenruo 			if (level <= write_lock_level) {
2150f624d976SQu Wenruo 				btrfs_tree_lock(b);
2151f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2152f624d976SQu Wenruo 			} else {
2153857bc13fSJosef Bacik 				if (p->nowait) {
2154857bc13fSJosef Bacik 					if (!btrfs_try_tree_read_lock(b)) {
2155857bc13fSJosef Bacik 						free_extent_buffer(b);
2156857bc13fSJosef Bacik 						ret = -EAGAIN;
2157857bc13fSJosef Bacik 						goto done;
2158857bc13fSJosef Bacik 					}
2159857bc13fSJosef Bacik 				} else {
2160fe596ca3SJosef Bacik 					btrfs_tree_read_lock(b);
2161857bc13fSJosef Bacik 				}
2162f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2163f624d976SQu Wenruo 			}
2164f624d976SQu Wenruo 			p->nodes[level] = b;
2165f624d976SQu Wenruo 		}
216665b51a00SChris Mason 	}
216765b51a00SChris Mason 	ret = 1;
216865b51a00SChris Mason done:
21695f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2170b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2171d96b3424SFilipe Manana 
2172d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2173d96b3424SFilipe Manana 		int ret2;
2174d96b3424SFilipe Manana 
2175d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2176d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2177d96b3424SFilipe Manana 		if (ret2)
2178d96b3424SFilipe Manana 			ret = ret2;
2179d96b3424SFilipe Manana 	}
2180d96b3424SFilipe Manana 
2181be0e5c09SChris Mason 	return ret;
2182be0e5c09SChris Mason }
2183f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2184be0e5c09SChris Mason 
218574123bd7SChris Mason /*
21865d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
21875d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
21885d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
21895d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
21905d9e75c4SJan Schmidt  *
21915d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
21925d9e75c4SJan Schmidt  *
21935d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
21945d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
21955d9e75c4SJan Schmidt  */
2196310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
21975d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
21985d9e75c4SJan Schmidt {
21990b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
22005d9e75c4SJan Schmidt 	struct extent_buffer *b;
22015d9e75c4SJan Schmidt 	int slot;
22025d9e75c4SJan Schmidt 	int ret;
22035d9e75c4SJan Schmidt 	int err;
22045d9e75c4SJan Schmidt 	int level;
22055d9e75c4SJan Schmidt 	int lowest_unlock = 1;
22065d9e75c4SJan Schmidt 	u8 lowest_level = 0;
22075d9e75c4SJan Schmidt 
22085d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
22095d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
2210c922b016SStefan Roesch 	ASSERT(!p->nowait);
22115d9e75c4SJan Schmidt 
22125d9e75c4SJan Schmidt 	if (p->search_commit_root) {
22135d9e75c4SJan Schmidt 		BUG_ON(time_seq);
22145d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
22155d9e75c4SJan Schmidt 	}
22165d9e75c4SJan Schmidt 
22175d9e75c4SJan Schmidt again:
2218f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2219315bed43SNikolay Borisov 	if (!b) {
2220315bed43SNikolay Borisov 		ret = -EIO;
2221315bed43SNikolay Borisov 		goto done;
2222315bed43SNikolay Borisov 	}
22235d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
22245d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
22255d9e75c4SJan Schmidt 
22265d9e75c4SJan Schmidt 	while (b) {
2227abe9339dSQu Wenruo 		int dec = 0;
2228abe9339dSQu Wenruo 
22295d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
22305d9e75c4SJan Schmidt 		p->nodes[level] = b;
22315d9e75c4SJan Schmidt 
22325d9e75c4SJan Schmidt 		/*
22335d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
22345d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
22355d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
22365d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
22375d9e75c4SJan Schmidt 		 */
22385d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
22395d9e75c4SJan Schmidt 
2240995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
2241cbca7d59SFilipe Manana 		if (ret < 0)
2242cbca7d59SFilipe Manana 			goto done;
22435d9e75c4SJan Schmidt 
2244abe9339dSQu Wenruo 		if (level == 0) {
2245abe9339dSQu Wenruo 			p->slots[level] = slot;
2246abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2247abe9339dSQu Wenruo 			goto done;
2248abe9339dSQu Wenruo 		}
2249abe9339dSQu Wenruo 
22505d9e75c4SJan Schmidt 		if (ret && slot > 0) {
22515d9e75c4SJan Schmidt 			dec = 1;
2252abe9339dSQu Wenruo 			slot--;
22535d9e75c4SJan Schmidt 		}
22545d9e75c4SJan Schmidt 		p->slots[level] = slot;
22555d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
22565d9e75c4SJan Schmidt 
22575d9e75c4SJan Schmidt 		if (level == lowest_level) {
22585d9e75c4SJan Schmidt 			if (dec)
22595d9e75c4SJan Schmidt 				p->slots[level]++;
22605d9e75c4SJan Schmidt 			goto done;
22615d9e75c4SJan Schmidt 		}
22625d9e75c4SJan Schmidt 
2263abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
22645d9e75c4SJan Schmidt 		if (err == -EAGAIN)
22655d9e75c4SJan Schmidt 			goto again;
22665d9e75c4SJan Schmidt 		if (err) {
22675d9e75c4SJan Schmidt 			ret = err;
22685d9e75c4SJan Schmidt 			goto done;
22695d9e75c4SJan Schmidt 		}
22705d9e75c4SJan Schmidt 
22715d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
22725d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2273f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2274db7f3436SJosef Bacik 		if (!b) {
2275db7f3436SJosef Bacik 			ret = -ENOMEM;
2276db7f3436SJosef Bacik 			goto done;
2277db7f3436SJosef Bacik 		}
22785d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
22795d9e75c4SJan Schmidt 		p->nodes[level] = b;
22805d9e75c4SJan Schmidt 	}
22815d9e75c4SJan Schmidt 	ret = 1;
22825d9e75c4SJan Schmidt done:
22835d9e75c4SJan Schmidt 	if (ret < 0)
22845d9e75c4SJan Schmidt 		btrfs_release_path(p);
22855d9e75c4SJan Schmidt 
22865d9e75c4SJan Schmidt 	return ret;
22875d9e75c4SJan Schmidt }
22885d9e75c4SJan Schmidt 
22895d9e75c4SJan Schmidt /*
22902f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
22912f38b3e1SArne Jansen  * instead the next or previous item should be returned.
22922f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
22932f38b3e1SArne Jansen  * otherwise.
22942f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
22952f38b3e1SArne Jansen  * return the next lower instead.
22962f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
22972f38b3e1SArne Jansen  * return the next higher instead.
22982f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
22992f38b3e1SArne Jansen  * < 0 on error
23002f38b3e1SArne Jansen  */
23012f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2302310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2303310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2304310712b2SOmar Sandoval 			       int return_any)
23052f38b3e1SArne Jansen {
23062f38b3e1SArne Jansen 	int ret;
23072f38b3e1SArne Jansen 	struct extent_buffer *leaf;
23082f38b3e1SArne Jansen 
23092f38b3e1SArne Jansen again:
23102f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
23112f38b3e1SArne Jansen 	if (ret <= 0)
23122f38b3e1SArne Jansen 		return ret;
23132f38b3e1SArne Jansen 	/*
23142f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
23152f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
23162f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
23172f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
23182f38b3e1SArne Jansen 	 * item.
23192f38b3e1SArne Jansen 	 */
23202f38b3e1SArne Jansen 	leaf = p->nodes[0];
23212f38b3e1SArne Jansen 
23222f38b3e1SArne Jansen 	if (find_higher) {
23232f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
23242f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
23252f38b3e1SArne Jansen 			if (ret <= 0)
23262f38b3e1SArne Jansen 				return ret;
23272f38b3e1SArne Jansen 			if (!return_any)
23282f38b3e1SArne Jansen 				return 1;
23292f38b3e1SArne Jansen 			/*
23302f38b3e1SArne Jansen 			 * no higher item found, return the next
23312f38b3e1SArne Jansen 			 * lower instead
23322f38b3e1SArne Jansen 			 */
23332f38b3e1SArne Jansen 			return_any = 0;
23342f38b3e1SArne Jansen 			find_higher = 0;
23352f38b3e1SArne Jansen 			btrfs_release_path(p);
23362f38b3e1SArne Jansen 			goto again;
23372f38b3e1SArne Jansen 		}
23382f38b3e1SArne Jansen 	} else {
23392f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
23402f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2341e6793769SArne Jansen 			if (ret < 0)
23422f38b3e1SArne Jansen 				return ret;
2343e6793769SArne Jansen 			if (!ret) {
234423c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
234523c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
234623c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2347e6793769SArne Jansen 				return 0;
2348e6793769SArne Jansen 			}
23492f38b3e1SArne Jansen 			if (!return_any)
23502f38b3e1SArne Jansen 				return 1;
23512f38b3e1SArne Jansen 			/*
23522f38b3e1SArne Jansen 			 * no lower item found, return the next
23532f38b3e1SArne Jansen 			 * higher instead
23542f38b3e1SArne Jansen 			 */
23552f38b3e1SArne Jansen 			return_any = 0;
23562f38b3e1SArne Jansen 			find_higher = 1;
23572f38b3e1SArne Jansen 			btrfs_release_path(p);
23582f38b3e1SArne Jansen 			goto again;
2359e6793769SArne Jansen 		} else {
23602f38b3e1SArne Jansen 			--p->slots[0];
23612f38b3e1SArne Jansen 		}
23622f38b3e1SArne Jansen 	}
23632f38b3e1SArne Jansen 	return 0;
23642f38b3e1SArne Jansen }
23652f38b3e1SArne Jansen 
23662f38b3e1SArne Jansen /*
23670ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
23680ff40a91SMarcos Paulo de Souza  * was not found.
23690ff40a91SMarcos Paulo de Souza  *
23700ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
23710ff40a91SMarcos Paulo de Souza  */
23720ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
23730ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
23740ff40a91SMarcos Paulo de Souza {
23750ff40a91SMarcos Paulo de Souza 	int ret;
23760ff40a91SMarcos Paulo de Souza 
23770ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
23780ff40a91SMarcos Paulo de Souza 	if (ret > 0)
23790ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
23800ff40a91SMarcos Paulo de Souza 
23810ff40a91SMarcos Paulo de Souza 	if (ret == 0)
23820ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
23830ff40a91SMarcos Paulo de Souza 
23840ff40a91SMarcos Paulo de Souza 	return ret;
23850ff40a91SMarcos Paulo de Souza }
23860ff40a91SMarcos Paulo de Souza 
238743dd529aSDavid Sterba /*
238862142be3SGabriel Niebler  * Search for a valid slot for the given path.
238962142be3SGabriel Niebler  *
239062142be3SGabriel Niebler  * @root:	The root node of the tree.
239162142be3SGabriel Niebler  * @key:	Will contain a valid item if found.
239262142be3SGabriel Niebler  * @path:	The starting point to validate the slot.
239362142be3SGabriel Niebler  *
239462142be3SGabriel Niebler  * Return: 0  if the item is valid
239562142be3SGabriel Niebler  *         1  if not found
239662142be3SGabriel Niebler  *         <0 if error.
239762142be3SGabriel Niebler  */
239862142be3SGabriel Niebler int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
239962142be3SGabriel Niebler 			      struct btrfs_path *path)
240062142be3SGabriel Niebler {
240162142be3SGabriel Niebler 	while (1) {
240262142be3SGabriel Niebler 		int ret;
240362142be3SGabriel Niebler 		const int slot = path->slots[0];
240462142be3SGabriel Niebler 		const struct extent_buffer *leaf = path->nodes[0];
240562142be3SGabriel Niebler 
240662142be3SGabriel Niebler 		/* This is where we start walking the path. */
240762142be3SGabriel Niebler 		if (slot >= btrfs_header_nritems(leaf)) {
240862142be3SGabriel Niebler 			/*
240962142be3SGabriel Niebler 			 * If we've reached the last slot in this leaf we need
241062142be3SGabriel Niebler 			 * to go to the next leaf and reset the path.
241162142be3SGabriel Niebler 			 */
241262142be3SGabriel Niebler 			ret = btrfs_next_leaf(root, path);
241362142be3SGabriel Niebler 			if (ret)
241462142be3SGabriel Niebler 				return ret;
241562142be3SGabriel Niebler 			continue;
241662142be3SGabriel Niebler 		}
241762142be3SGabriel Niebler 		/* Store the found, valid item in @key. */
241862142be3SGabriel Niebler 		btrfs_item_key_to_cpu(leaf, key, slot);
241962142be3SGabriel Niebler 		break;
242062142be3SGabriel Niebler 	}
242162142be3SGabriel Niebler 	return 0;
242262142be3SGabriel Niebler }
242362142be3SGabriel Niebler 
24240ff40a91SMarcos Paulo de Souza /*
242574123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
242674123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
242774123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
242874123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
242974123bd7SChris Mason  * higher levels
2430aa5d6bedSChris Mason  *
243174123bd7SChris Mason  */
2432b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
24335f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2434be0e5c09SChris Mason {
2435be0e5c09SChris Mason 	int i;
24365f39d397SChris Mason 	struct extent_buffer *t;
24370e82bcfeSDavid Sterba 	int ret;
24385f39d397SChris Mason 
2439234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2440be0e5c09SChris Mason 		int tslot = path->slots[i];
24410e82bcfeSDavid Sterba 
2442eb60ceacSChris Mason 		if (!path->nodes[i])
2443be0e5c09SChris Mason 			break;
24445f39d397SChris Mason 		t = path->nodes[i];
2445f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
244633cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
24470e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
24485f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2449d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2450be0e5c09SChris Mason 		if (tslot != 0)
2451be0e5c09SChris Mason 			break;
2452be0e5c09SChris Mason 	}
2453be0e5c09SChris Mason }
2454be0e5c09SChris Mason 
245574123bd7SChris Mason /*
245631840ae1SZheng Yan  * update item key.
245731840ae1SZheng Yan  *
245831840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
245931840ae1SZheng Yan  * that the new key won't break the order
246031840ae1SZheng Yan  */
2461b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2462b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2463310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
246431840ae1SZheng Yan {
246531840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
246631840ae1SZheng Yan 	struct extent_buffer *eb;
246731840ae1SZheng Yan 	int slot;
246831840ae1SZheng Yan 
246931840ae1SZheng Yan 	eb = path->nodes[0];
247031840ae1SZheng Yan 	slot = path->slots[0];
247131840ae1SZheng Yan 	if (slot > 0) {
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 	if (slot < btrfs_header_nritems(eb) - 1) {
248631840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
24877c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
24887c15d410SQu Wenruo 			btrfs_crit(fs_info,
24897c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
24907c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
24917c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
24927c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
24937c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
24947c15d410SQu Wenruo 				   new_key->offset);
24957c15d410SQu Wenruo 			btrfs_print_leaf(eb);
24967c15d410SQu Wenruo 			BUG();
24977c15d410SQu Wenruo 		}
249831840ae1SZheng Yan 	}
249931840ae1SZheng Yan 
250031840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
250131840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
250231840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
250331840ae1SZheng Yan 	if (slot == 0)
2504b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
250531840ae1SZheng Yan }
250631840ae1SZheng Yan 
250731840ae1SZheng Yan /*
2508d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2509d16c702fSQu Wenruo  *
2510d16c702fSQu Wenruo  * Return true if something is wrong.
2511d16c702fSQu Wenruo  * Return false if everything is fine.
2512d16c702fSQu Wenruo  *
2513d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2514d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2515d16c702fSQu Wenruo  *
2516d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2517d16c702fSQu Wenruo  * --------------------------------------------------------------
2518d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2519d16c702fSQu Wenruo  *
2520d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2521d16c702fSQu Wenruo  * key in leaf @right is 7.
2522d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2523d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2524d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2525d16c702fSQu Wenruo  * key of @right.
2526d16c702fSQu Wenruo  */
2527d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2528d16c702fSQu Wenruo 			       struct extent_buffer *right)
2529d16c702fSQu Wenruo {
2530d16c702fSQu Wenruo 	struct btrfs_key left_last;
2531d16c702fSQu Wenruo 	struct btrfs_key right_first;
2532d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2533d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2534d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2535d16c702fSQu Wenruo 
2536d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2537d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2538d16c702fSQu Wenruo 		return false;
2539d16c702fSQu Wenruo 
2540d16c702fSQu Wenruo 	if (level) {
2541d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2542d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2543d16c702fSQu Wenruo 	} else {
2544d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2545d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2546d16c702fSQu Wenruo 	}
2547d16c702fSQu Wenruo 
2548d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2549d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2550d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2551d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2552d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2553d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2554d16c702fSQu Wenruo 		return true;
2555d16c702fSQu Wenruo 	}
2556d16c702fSQu Wenruo 	return false;
2557d16c702fSQu Wenruo }
2558d16c702fSQu Wenruo 
2559d16c702fSQu Wenruo /*
256074123bd7SChris Mason  * try to push data from one node into the next node left in the
256179f95c82SChris Mason  * tree.
2562aa5d6bedSChris Mason  *
2563aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2564aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
256574123bd7SChris Mason  */
256698ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
25672ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2568971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2569be0e5c09SChris Mason {
2570d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2571be0e5c09SChris Mason 	int push_items = 0;
2572bb803951SChris Mason 	int src_nritems;
2573bb803951SChris Mason 	int dst_nritems;
2574aa5d6bedSChris Mason 	int ret = 0;
2575be0e5c09SChris Mason 
25765f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
25775f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
25780b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
25797bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
25807bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
258154aa1f4dSChris Mason 
2582bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2583971a1f66SChris Mason 		return 1;
2584971a1f66SChris Mason 
2585d397712bSChris Mason 	if (push_items <= 0)
2586be0e5c09SChris Mason 		return 1;
2587be0e5c09SChris Mason 
2588bce4eae9SChris Mason 	if (empty) {
2589971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2590bce4eae9SChris Mason 		if (push_items < src_nritems) {
2591bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2592bce4eae9SChris Mason 			 * we aren't going to empty it
2593bce4eae9SChris Mason 			 */
2594bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2595bce4eae9SChris Mason 				if (push_items <= 8)
2596bce4eae9SChris Mason 					return 1;
2597bce4eae9SChris Mason 				push_items -= 8;
2598bce4eae9SChris Mason 			}
2599bce4eae9SChris Mason 		}
2600bce4eae9SChris Mason 	} else
2601bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
260279f95c82SChris Mason 
2603d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2604d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2605d16c702fSQu Wenruo 		ret = -EUCLEAN;
2606d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2607d16c702fSQu Wenruo 		return ret;
2608d16c702fSQu Wenruo 	}
2609f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
26105de865eeSFilipe David Borba Manana 	if (ret) {
261166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
26125de865eeSFilipe David Borba Manana 		return ret;
26135de865eeSFilipe David Borba Manana 	}
26145f39d397SChris Mason 	copy_extent_buffer(dst, src,
2615*e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, dst_nritems),
2616*e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, 0),
2617123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
26185f39d397SChris Mason 
2619bb803951SChris Mason 	if (push_items < src_nritems) {
262057911b8bSJan Schmidt 		/*
2621f3a84ccdSFilipe Manana 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2622f3a84ccdSFilipe Manana 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
262357911b8bSJan Schmidt 		 */
2624*e23efd8eSJosef Bacik 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(src, 0),
2625*e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(src, push_items),
2626e2fa7227SChris Mason 				      (src_nritems - push_items) *
2627123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2628bb803951SChris Mason 	}
26295f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
26305f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
26315f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
26325f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
263331840ae1SZheng Yan 
2634bb803951SChris Mason 	return ret;
2635be0e5c09SChris Mason }
2636be0e5c09SChris Mason 
263797571fd0SChris Mason /*
263879f95c82SChris Mason  * try to push data from one node into the next node right in the
263979f95c82SChris Mason  * tree.
264079f95c82SChris Mason  *
264179f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
264279f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
264379f95c82SChris Mason  *
264479f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
264579f95c82SChris Mason  */
26465f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
26475f39d397SChris Mason 			      struct extent_buffer *dst,
26485f39d397SChris Mason 			      struct extent_buffer *src)
264979f95c82SChris Mason {
265055d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
265179f95c82SChris Mason 	int push_items = 0;
265279f95c82SChris Mason 	int max_push;
265379f95c82SChris Mason 	int src_nritems;
265479f95c82SChris Mason 	int dst_nritems;
265579f95c82SChris Mason 	int ret = 0;
265679f95c82SChris Mason 
26577bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
26587bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
26597bb86316SChris Mason 
26605f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
26615f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
26620b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2663d397712bSChris Mason 	if (push_items <= 0)
266479f95c82SChris Mason 		return 1;
2665bce4eae9SChris Mason 
2666d397712bSChris Mason 	if (src_nritems < 4)
2667bce4eae9SChris Mason 		return 1;
266879f95c82SChris Mason 
266979f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
267079f95c82SChris Mason 	/* don't try to empty the node */
2671d397712bSChris Mason 	if (max_push >= src_nritems)
267279f95c82SChris Mason 		return 1;
2673252c38f0SYan 
267479f95c82SChris Mason 	if (max_push < push_items)
267579f95c82SChris Mason 		push_items = max_push;
267679f95c82SChris Mason 
2677d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2678d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2679d16c702fSQu Wenruo 		ret = -EUCLEAN;
2680d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2681d16c702fSQu Wenruo 		return ret;
2682d16c702fSQu Wenruo 	}
2683f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2684bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
2685*e23efd8eSJosef Bacik 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(dst, push_items),
2686*e23efd8eSJosef Bacik 				      btrfs_node_key_ptr_offset(dst, 0),
26875f39d397SChris Mason 				      (dst_nritems) *
26885f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2689d6025579SChris Mason 
2690f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2691ed874f0dSDavid Sterba 					 push_items);
26925de865eeSFilipe David Borba Manana 	if (ret) {
269366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
26945de865eeSFilipe David Borba Manana 		return ret;
26955de865eeSFilipe David Borba Manana 	}
26965f39d397SChris Mason 	copy_extent_buffer(dst, src,
2697*e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(dst, 0),
2698*e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(src, src_nritems - push_items),
2699123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
270079f95c82SChris Mason 
27015f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
27025f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
270379f95c82SChris Mason 
27045f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
27055f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
270631840ae1SZheng Yan 
270779f95c82SChris Mason 	return ret;
270879f95c82SChris Mason }
270979f95c82SChris Mason 
271079f95c82SChris Mason /*
271197571fd0SChris Mason  * helper function to insert a new root level in the tree.
271297571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
271397571fd0SChris Mason  * point to the existing root
2714aa5d6bedSChris Mason  *
2715aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
271697571fd0SChris Mason  */
2717d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
27185f39d397SChris Mason 			   struct btrfs_root *root,
2719fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
272074123bd7SChris Mason {
27210b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
27227bb86316SChris Mason 	u64 lower_gen;
27235f39d397SChris Mason 	struct extent_buffer *lower;
27245f39d397SChris Mason 	struct extent_buffer *c;
2725925baeddSChris Mason 	struct extent_buffer *old;
27265f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2727d9d19a01SDavid Sterba 	int ret;
27285c680ed6SChris Mason 
27295c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
27305c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
27315c680ed6SChris Mason 
27327bb86316SChris Mason 	lower = path->nodes[level-1];
27337bb86316SChris Mason 	if (level == 1)
27347bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
27357bb86316SChris Mason 	else
27367bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
27377bb86316SChris Mason 
273879bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
273979bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2740cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
27415f39d397SChris Mason 	if (IS_ERR(c))
27425f39d397SChris Mason 		return PTR_ERR(c);
2743925baeddSChris Mason 
27440b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2745f0486c68SYan, Zheng 
27465f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
27475f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2748db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
27497bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
275031840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
27517bb86316SChris Mason 
27527bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
27535f39d397SChris Mason 
27545f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2755d5719762SChris Mason 
2756925baeddSChris Mason 	old = root->node;
2757406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2758d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2759240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2760925baeddSChris Mason 
2761925baeddSChris Mason 	/* the super has an extra ref to root->node */
2762925baeddSChris Mason 	free_extent_buffer(old);
2763925baeddSChris Mason 
27640b86a832SChris Mason 	add_root_to_dirty_list(root);
276567439dadSDavid Sterba 	atomic_inc(&c->refs);
27665f39d397SChris Mason 	path->nodes[level] = c;
2767ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
276874123bd7SChris Mason 	path->slots[level] = 0;
276974123bd7SChris Mason 	return 0;
277074123bd7SChris Mason }
27715c680ed6SChris Mason 
27725c680ed6SChris Mason /*
27735c680ed6SChris Mason  * worker function to insert a single pointer in a node.
27745c680ed6SChris Mason  * the node should have enough room for the pointer already
277597571fd0SChris Mason  *
27765c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
27775c680ed6SChris Mason  * blocknr is the block the key points to.
27785c680ed6SChris Mason  */
2779143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
27806ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2781143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2782c3e06965SJan Schmidt 		       int slot, int level)
27835c680ed6SChris Mason {
27845f39d397SChris Mason 	struct extent_buffer *lower;
27855c680ed6SChris Mason 	int nritems;
2786f3ea38daSJan Schmidt 	int ret;
27875c680ed6SChris Mason 
27885c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
278949d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
27905f39d397SChris Mason 	lower = path->nodes[level];
27915f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2792c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
27936ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
279474123bd7SChris Mason 	if (slot != nritems) {
2795bf1d3425SDavid Sterba 		if (level) {
2796f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2797f3a84ccdSFilipe Manana 					slot, nritems - slot);
2798bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2799bf1d3425SDavid Sterba 		}
28005f39d397SChris Mason 		memmove_extent_buffer(lower,
2801*e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot + 1),
2802*e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(lower, slot),
2803123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
280474123bd7SChris Mason 	}
2805c3e06965SJan Schmidt 	if (level) {
2806f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
280733cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_ADD);
2808f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2809f3ea38daSJan Schmidt 	}
28105f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2811db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
281274493f7aSChris Mason 	WARN_ON(trans->transid == 0);
281374493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
28145f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
28155f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
281674123bd7SChris Mason }
281774123bd7SChris Mason 
281897571fd0SChris Mason /*
281997571fd0SChris Mason  * split the node at the specified level in path in two.
282097571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
282197571fd0SChris Mason  *
282297571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
282397571fd0SChris Mason  * left and right, if either one works, it returns right away.
2824aa5d6bedSChris Mason  *
2825aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
282697571fd0SChris Mason  */
2827e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
2828e02119d5SChris Mason 			       struct btrfs_root *root,
2829e02119d5SChris Mason 			       struct btrfs_path *path, int level)
2830be0e5c09SChris Mason {
28310b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
28325f39d397SChris Mason 	struct extent_buffer *c;
28335f39d397SChris Mason 	struct extent_buffer *split;
28345f39d397SChris Mason 	struct btrfs_disk_key disk_key;
2835be0e5c09SChris Mason 	int mid;
28365c680ed6SChris Mason 	int ret;
28377518a238SChris Mason 	u32 c_nritems;
2838be0e5c09SChris Mason 
28395f39d397SChris Mason 	c = path->nodes[level];
28407bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
28415f39d397SChris Mason 	if (c == root->node) {
2842d9abbf1cSJan Schmidt 		/*
284390f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
284490f8d62eSJan Schmidt 		 *
2845fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
284690f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
284790f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
2848f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2849f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
2850f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
2851d9abbf1cSJan Schmidt 		 */
2852fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
28535c680ed6SChris Mason 		if (ret)
28545c680ed6SChris Mason 			return ret;
2855b3612421SChris Mason 	} else {
2856e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
28575f39d397SChris Mason 		c = path->nodes[level];
28585f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
28590b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2860e66f709bSChris Mason 			return 0;
286154aa1f4dSChris Mason 		if (ret < 0)
286254aa1f4dSChris Mason 			return ret;
28635c680ed6SChris Mason 	}
2864e66f709bSChris Mason 
28655f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
28665d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
28675d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
28687bb86316SChris Mason 
286979bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
287079bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
287179bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
28725f39d397SChris Mason 	if (IS_ERR(split))
28735f39d397SChris Mason 		return PTR_ERR(split);
287454aa1f4dSChris Mason 
28750b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2876bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
28775f39d397SChris Mason 
2878f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
28795de865eeSFilipe David Borba Manana 	if (ret) {
288066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
28815de865eeSFilipe David Borba Manana 		return ret;
28825de865eeSFilipe David Borba Manana 	}
28835f39d397SChris Mason 	copy_extent_buffer(split, c,
2884*e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(split, 0),
2885*e23efd8eSJosef Bacik 			   btrfs_node_key_ptr_offset(c, mid),
2886123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
28875f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
28885f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
2889aa5d6bedSChris Mason 
28905f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
28915f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
28925f39d397SChris Mason 
28936ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
2894c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
2895aa5d6bedSChris Mason 
28965de08d7dSChris Mason 	if (path->slots[level] >= mid) {
28975c680ed6SChris Mason 		path->slots[level] -= mid;
2898925baeddSChris Mason 		btrfs_tree_unlock(c);
28995f39d397SChris Mason 		free_extent_buffer(c);
29005f39d397SChris Mason 		path->nodes[level] = split;
29015c680ed6SChris Mason 		path->slots[level + 1] += 1;
2902eb60ceacSChris Mason 	} else {
2903925baeddSChris Mason 		btrfs_tree_unlock(split);
29045f39d397SChris Mason 		free_extent_buffer(split);
2905be0e5c09SChris Mason 	}
2906d5286a92SNikolay Borisov 	return 0;
2907be0e5c09SChris Mason }
2908be0e5c09SChris Mason 
290974123bd7SChris Mason /*
291074123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
291174123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
291274123bd7SChris Mason  * space used both by the item structs and the item data
291374123bd7SChris Mason  */
29145f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2915be0e5c09SChris Mason {
2916be0e5c09SChris Mason 	int data_len;
29175f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
2918d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
2919be0e5c09SChris Mason 
2920be0e5c09SChris Mason 	if (!nr)
2921be0e5c09SChris Mason 		return 0;
29223212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
29233212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
29240783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
2925d4dbff95SChris Mason 	WARN_ON(data_len < 0);
2926be0e5c09SChris Mason 	return data_len;
2927be0e5c09SChris Mason }
2928be0e5c09SChris Mason 
292974123bd7SChris Mason /*
2930d4dbff95SChris Mason  * The space between the end of the leaf items and
2931d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
2932d4dbff95SChris Mason  * the leaf has left for both items and data
2933d4dbff95SChris Mason  */
2934e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
2935d4dbff95SChris Mason {
2936e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
29375f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
29385f39d397SChris Mason 	int ret;
29390b246afaSJeff Mahoney 
29400b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
29415f39d397SChris Mason 	if (ret < 0) {
29420b246afaSJeff Mahoney 		btrfs_crit(fs_info,
2943efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2944da17066cSJeff Mahoney 			   ret,
29450b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
29465f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
29475f39d397SChris Mason 	}
29485f39d397SChris Mason 	return ret;
2949d4dbff95SChris Mason }
2950d4dbff95SChris Mason 
295199d8f83cSChris Mason /*
295299d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
295399d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
295499d8f83cSChris Mason  */
2955f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
295644871b1bSChris Mason 				      int data_size, int empty,
295744871b1bSChris Mason 				      struct extent_buffer *right,
295899d8f83cSChris Mason 				      int free_space, u32 left_nritems,
295999d8f83cSChris Mason 				      u32 min_slot)
296000ec4c51SChris Mason {
2961f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
29625f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
296344871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
2964cfed81a0SChris Mason 	struct btrfs_map_token token;
29655f39d397SChris Mason 	struct btrfs_disk_key disk_key;
296600ec4c51SChris Mason 	int slot;
296734a38218SChris Mason 	u32 i;
296800ec4c51SChris Mason 	int push_space = 0;
296900ec4c51SChris Mason 	int push_items = 0;
297034a38218SChris Mason 	u32 nr;
29717518a238SChris Mason 	u32 right_nritems;
29725f39d397SChris Mason 	u32 data_end;
2973db94535dSChris Mason 	u32 this_item_size;
297400ec4c51SChris Mason 
297534a38218SChris Mason 	if (empty)
297634a38218SChris Mason 		nr = 0;
297734a38218SChris Mason 	else
297899d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
297934a38218SChris Mason 
298031840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
298187b29b20SYan Zheng 		push_space += data_size;
298231840ae1SZheng Yan 
298344871b1bSChris Mason 	slot = path->slots[1];
298434a38218SChris Mason 	i = left_nritems - 1;
298534a38218SChris Mason 	while (i >= nr) {
298631840ae1SZheng Yan 		if (!empty && push_items > 0) {
298731840ae1SZheng Yan 			if (path->slots[0] > i)
298831840ae1SZheng Yan 				break;
298931840ae1SZheng Yan 			if (path->slots[0] == i) {
2990e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
2991e902baacSDavid Sterba 
299231840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
299331840ae1SZheng Yan 					break;
299431840ae1SZheng Yan 			}
299531840ae1SZheng Yan 		}
299631840ae1SZheng Yan 
299700ec4c51SChris Mason 		if (path->slots[0] == i)
299887b29b20SYan Zheng 			push_space += data_size;
2999db94535dSChris Mason 
30003212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
300174794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
300274794207SJosef Bacik 		    push_space > free_space)
300300ec4c51SChris Mason 			break;
300431840ae1SZheng Yan 
300500ec4c51SChris Mason 		push_items++;
300674794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
300734a38218SChris Mason 		if (i == 0)
300834a38218SChris Mason 			break;
300934a38218SChris Mason 		i--;
3010db94535dSChris Mason 	}
30115f39d397SChris Mason 
3012925baeddSChris Mason 	if (push_items == 0)
3013925baeddSChris Mason 		goto out_unlock;
30145f39d397SChris Mason 
30156c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
30165f39d397SChris Mason 
301700ec4c51SChris Mason 	/* push left to right */
30185f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
301934a38218SChris Mason 
3020dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
30218f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
30225f39d397SChris Mason 
302300ec4c51SChris Mason 	/* make room in the right data area */
30248f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
30255f39d397SChris Mason 	memmove_extent_buffer(right,
30263d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
30273d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
30280b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
30295f39d397SChris Mason 
303000ec4c51SChris Mason 	/* copy from the left data area */
30313d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
30320b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
30338f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3034d6025579SChris Mason 		     push_space);
30355f39d397SChris Mason 
303642c9419aSJosef Bacik 	memmove_extent_buffer(right, btrfs_item_nr_offset(right, push_items),
303742c9419aSJosef Bacik 			      btrfs_item_nr_offset(right, 0),
30380783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
30395f39d397SChris Mason 
304000ec4c51SChris Mason 	/* copy the items from left to right */
304142c9419aSJosef Bacik 	copy_extent_buffer(right, left, btrfs_item_nr_offset(right, 0),
304242c9419aSJosef Bacik 		   btrfs_item_nr_offset(left, left_nritems - push_items),
30430783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
304400ec4c51SChris Mason 
304500ec4c51SChris Mason 	/* update the item pointers */
3046c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
30477518a238SChris Mason 	right_nritems += push_items;
30485f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
30490b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
30507518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
30513212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
30523212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3053db94535dSChris Mason 	}
3054db94535dSChris Mason 
30557518a238SChris Mason 	left_nritems -= push_items;
30565f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
305700ec4c51SChris Mason 
305834a38218SChris Mason 	if (left_nritems)
30595f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3060f0486c68SYan, Zheng 	else
30616a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3062f0486c68SYan, Zheng 
30635f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3064a429e513SChris Mason 
30655f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
30665f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3067d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
306802217ed2SChris Mason 
306900ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
30707518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
30717518a238SChris Mason 		path->slots[0] -= left_nritems;
3072925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
30736a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3074925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
30755f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
30765f39d397SChris Mason 		path->nodes[0] = right;
307700ec4c51SChris Mason 		path->slots[1] += 1;
307800ec4c51SChris Mason 	} else {
3079925baeddSChris Mason 		btrfs_tree_unlock(right);
30805f39d397SChris Mason 		free_extent_buffer(right);
308100ec4c51SChris Mason 	}
308200ec4c51SChris Mason 	return 0;
3083925baeddSChris Mason 
3084925baeddSChris Mason out_unlock:
3085925baeddSChris Mason 	btrfs_tree_unlock(right);
3086925baeddSChris Mason 	free_extent_buffer(right);
3087925baeddSChris Mason 	return 1;
308800ec4c51SChris Mason }
3089925baeddSChris Mason 
309000ec4c51SChris Mason /*
309144871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
309274123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
309344871b1bSChris Mason  *
309444871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
309544871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
309699d8f83cSChris Mason  *
309799d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
309899d8f83cSChris Mason  * push any slot lower than min_slot
309974123bd7SChris Mason  */
310044871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
310199d8f83cSChris Mason 			   *root, struct btrfs_path *path,
310299d8f83cSChris Mason 			   int min_data_size, int data_size,
310399d8f83cSChris Mason 			   int empty, u32 min_slot)
3104be0e5c09SChris Mason {
310544871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
310644871b1bSChris Mason 	struct extent_buffer *right;
310744871b1bSChris Mason 	struct extent_buffer *upper;
310844871b1bSChris Mason 	int slot;
310944871b1bSChris Mason 	int free_space;
311044871b1bSChris Mason 	u32 left_nritems;
311144871b1bSChris Mason 	int ret;
311244871b1bSChris Mason 
311344871b1bSChris Mason 	if (!path->nodes[1])
311444871b1bSChris Mason 		return 1;
311544871b1bSChris Mason 
311644871b1bSChris Mason 	slot = path->slots[1];
311744871b1bSChris Mason 	upper = path->nodes[1];
311844871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
311944871b1bSChris Mason 		return 1;
312044871b1bSChris Mason 
312149d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
312244871b1bSChris Mason 
31234b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3124fb770ae4SLiu Bo 	/*
3125fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3126fb770ae4SLiu Bo 	 * no big deal, just return.
3127fb770ae4SLiu Bo 	 */
3128fb770ae4SLiu Bo 	if (IS_ERR(right))
312991ca338dSTsutomu Itoh 		return 1;
313091ca338dSTsutomu Itoh 
3131bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
313244871b1bSChris Mason 
3133e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
313444871b1bSChris Mason 	if (free_space < data_size)
313544871b1bSChris Mason 		goto out_unlock;
313644871b1bSChris Mason 
313744871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3138bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
313944871b1bSChris Mason 	if (ret)
314044871b1bSChris Mason 		goto out_unlock;
314144871b1bSChris Mason 
314244871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
314344871b1bSChris Mason 	if (left_nritems == 0)
314444871b1bSChris Mason 		goto out_unlock;
314544871b1bSChris Mason 
3146d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3147d16c702fSQu Wenruo 		ret = -EUCLEAN;
3148d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3149d16c702fSQu Wenruo 		free_extent_buffer(right);
3150d16c702fSQu Wenruo 		return ret;
3151d16c702fSQu Wenruo 	}
31522ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
31532ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
31542ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
31552ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
315652042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
31572ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
31582ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
31592ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
31602ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
31612ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
31622ef1fed2SFilipe David Borba Manana 		return 0;
31632ef1fed2SFilipe David Borba Manana 	}
31642ef1fed2SFilipe David Borba Manana 
3165f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
316699d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
316744871b1bSChris Mason out_unlock:
316844871b1bSChris Mason 	btrfs_tree_unlock(right);
316944871b1bSChris Mason 	free_extent_buffer(right);
317044871b1bSChris Mason 	return 1;
317144871b1bSChris Mason }
317244871b1bSChris Mason 
317344871b1bSChris Mason /*
317444871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
317544871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
317699d8f83cSChris Mason  *
317799d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
317899d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
317999d8f83cSChris Mason  * items
318044871b1bSChris Mason  */
31818087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
318244871b1bSChris Mason 				     int empty, struct extent_buffer *left,
318399d8f83cSChris Mason 				     int free_space, u32 right_nritems,
318499d8f83cSChris Mason 				     u32 max_slot)
318544871b1bSChris Mason {
31868087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
31875f39d397SChris Mason 	struct btrfs_disk_key disk_key;
31885f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3189be0e5c09SChris Mason 	int i;
3190be0e5c09SChris Mason 	int push_space = 0;
3191be0e5c09SChris Mason 	int push_items = 0;
31927518a238SChris Mason 	u32 old_left_nritems;
319334a38218SChris Mason 	u32 nr;
3194aa5d6bedSChris Mason 	int ret = 0;
3195db94535dSChris Mason 	u32 this_item_size;
3196db94535dSChris Mason 	u32 old_left_item_size;
3197cfed81a0SChris Mason 	struct btrfs_map_token token;
3198cfed81a0SChris Mason 
319934a38218SChris Mason 	if (empty)
320099d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
320134a38218SChris Mason 	else
320299d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
320334a38218SChris Mason 
320434a38218SChris Mason 	for (i = 0; i < nr; i++) {
320531840ae1SZheng Yan 		if (!empty && push_items > 0) {
320631840ae1SZheng Yan 			if (path->slots[0] < i)
320731840ae1SZheng Yan 				break;
320831840ae1SZheng Yan 			if (path->slots[0] == i) {
3209e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3210e902baacSDavid Sterba 
321131840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
321231840ae1SZheng Yan 					break;
321331840ae1SZheng Yan 			}
321431840ae1SZheng Yan 		}
321531840ae1SZheng Yan 
3216be0e5c09SChris Mason 		if (path->slots[0] == i)
321787b29b20SYan Zheng 			push_space += data_size;
3218db94535dSChris Mason 
32193212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
322074794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
322174794207SJosef Bacik 		    free_space)
3222be0e5c09SChris Mason 			break;
3223db94535dSChris Mason 
3224be0e5c09SChris Mason 		push_items++;
322574794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3226be0e5c09SChris Mason 	}
3227db94535dSChris Mason 
3228be0e5c09SChris Mason 	if (push_items == 0) {
3229925baeddSChris Mason 		ret = 1;
3230925baeddSChris Mason 		goto out;
3231be0e5c09SChris Mason 	}
3232fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
32335f39d397SChris Mason 
3234be0e5c09SChris Mason 	/* push data from right to left */
32355f39d397SChris Mason 	copy_extent_buffer(left, right,
323642c9419aSJosef Bacik 			   btrfs_item_nr_offset(left, btrfs_header_nritems(left)),
323742c9419aSJosef Bacik 			   btrfs_item_nr_offset(right, 0),
32385f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
32395f39d397SChris Mason 
32400b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
32413212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
32425f39d397SChris Mason 
32433d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
32448f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
32453d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
32463212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1),
3247be0e5c09SChris Mason 		     push_space);
32485f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
324987b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3250eb60ceacSChris Mason 
3251c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
32523212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3253be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
32545f39d397SChris Mason 		u32 ioff;
3255db94535dSChris Mason 
32563212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
32573212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3258cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3259be0e5c09SChris Mason 	}
32605f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3261be0e5c09SChris Mason 
3262be0e5c09SChris Mason 	/* fixup right node */
326331b1a2bdSJulia Lawall 	if (push_items > right_nritems)
326431b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3265d397712bSChris Mason 		       right_nritems);
326634a38218SChris Mason 
326734a38218SChris Mason 	if (push_items < right_nritems) {
32683212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
32698f881e8cSDavid Sterba 						  leaf_data_end(right);
32703d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
32710b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
32723d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
32738f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
32745f39d397SChris Mason 
327542c9419aSJosef Bacik 		memmove_extent_buffer(right, btrfs_item_nr_offset(right, 0),
327642c9419aSJosef Bacik 			      btrfs_item_nr_offset(left, push_items),
32775f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
32780783fcfcSChris Mason 			     sizeof(struct btrfs_item));
327934a38218SChris Mason 	}
3280c82f823cSDavid Sterba 
3281c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3282eef1c494SYan 	right_nritems -= push_items;
3283eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
32840b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
32855f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
32863212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
32873212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3288db94535dSChris Mason 	}
3289eb60ceacSChris Mason 
32905f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
329134a38218SChris Mason 	if (right_nritems)
32925f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3293f0486c68SYan, Zheng 	else
32946a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3295098f59c2SChris Mason 
32965f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3297b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3298be0e5c09SChris Mason 
3299be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3300be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3301be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3302925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
33035f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
33045f39d397SChris Mason 		path->nodes[0] = left;
3305be0e5c09SChris Mason 		path->slots[1] -= 1;
3306be0e5c09SChris Mason 	} else {
3307925baeddSChris Mason 		btrfs_tree_unlock(left);
33085f39d397SChris Mason 		free_extent_buffer(left);
3309be0e5c09SChris Mason 		path->slots[0] -= push_items;
3310be0e5c09SChris Mason 	}
3311eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3312aa5d6bedSChris Mason 	return ret;
3313925baeddSChris Mason out:
3314925baeddSChris Mason 	btrfs_tree_unlock(left);
3315925baeddSChris Mason 	free_extent_buffer(left);
3316925baeddSChris Mason 	return ret;
3317be0e5c09SChris Mason }
3318be0e5c09SChris Mason 
331974123bd7SChris Mason /*
332044871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
332144871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
332299d8f83cSChris Mason  *
332399d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
332499d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
332599d8f83cSChris Mason  * items
332644871b1bSChris Mason  */
332744871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
332899d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
332999d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
333044871b1bSChris Mason {
333144871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
333244871b1bSChris Mason 	struct extent_buffer *left;
333344871b1bSChris Mason 	int slot;
333444871b1bSChris Mason 	int free_space;
333544871b1bSChris Mason 	u32 right_nritems;
333644871b1bSChris Mason 	int ret = 0;
333744871b1bSChris Mason 
333844871b1bSChris Mason 	slot = path->slots[1];
333944871b1bSChris Mason 	if (slot == 0)
334044871b1bSChris Mason 		return 1;
334144871b1bSChris Mason 	if (!path->nodes[1])
334244871b1bSChris Mason 		return 1;
334344871b1bSChris Mason 
334444871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
334544871b1bSChris Mason 	if (right_nritems == 0)
334644871b1bSChris Mason 		return 1;
334744871b1bSChris Mason 
334849d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
334944871b1bSChris Mason 
33504b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3351fb770ae4SLiu Bo 	/*
3352fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3353fb770ae4SLiu Bo 	 * no big deal, just return.
3354fb770ae4SLiu Bo 	 */
3355fb770ae4SLiu Bo 	if (IS_ERR(left))
335691ca338dSTsutomu Itoh 		return 1;
335791ca338dSTsutomu Itoh 
3358bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
335944871b1bSChris Mason 
3360e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
336144871b1bSChris Mason 	if (free_space < data_size) {
336244871b1bSChris Mason 		ret = 1;
336344871b1bSChris Mason 		goto out;
336444871b1bSChris Mason 	}
336544871b1bSChris Mason 
336644871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
33679631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3368bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
336944871b1bSChris Mason 	if (ret) {
337044871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
337179787eaaSJeff Mahoney 		if (ret == -ENOSPC)
337244871b1bSChris Mason 			ret = 1;
337344871b1bSChris Mason 		goto out;
337444871b1bSChris Mason 	}
337544871b1bSChris Mason 
3376d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3377d16c702fSQu Wenruo 		ret = -EUCLEAN;
3378d16c702fSQu Wenruo 		goto out;
3379d16c702fSQu Wenruo 	}
33808087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
338199d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
338299d8f83cSChris Mason 			       max_slot);
338344871b1bSChris Mason out:
338444871b1bSChris Mason 	btrfs_tree_unlock(left);
338544871b1bSChris Mason 	free_extent_buffer(left);
338644871b1bSChris Mason 	return ret;
338744871b1bSChris Mason }
338844871b1bSChris Mason 
338944871b1bSChris Mason /*
339074123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
339174123bd7SChris Mason  * available for the resulting leaf level of the path.
339274123bd7SChris Mason  */
3393143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
339444871b1bSChris Mason 				    struct btrfs_path *path,
339544871b1bSChris Mason 				    struct extent_buffer *l,
339644871b1bSChris Mason 				    struct extent_buffer *right,
339744871b1bSChris Mason 				    int slot, int mid, int nritems)
3398be0e5c09SChris Mason {
339994f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3400be0e5c09SChris Mason 	int data_copy_size;
3401be0e5c09SChris Mason 	int rt_data_off;
3402be0e5c09SChris Mason 	int i;
3403d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3404cfed81a0SChris Mason 	struct btrfs_map_token token;
3405cfed81a0SChris Mason 
34065f39d397SChris Mason 	nritems = nritems - mid;
34075f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3408dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
34095f39d397SChris Mason 
341042c9419aSJosef Bacik 	copy_extent_buffer(right, l, btrfs_item_nr_offset(right, 0),
341142c9419aSJosef Bacik 			   btrfs_item_nr_offset(l, mid),
34125f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
34135f39d397SChris Mason 
34145f39d397SChris Mason 	copy_extent_buffer(right, l,
34153d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
34163d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
34178f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
341874123bd7SChris Mason 
3419dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
34205f39d397SChris Mason 
3421c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
34225f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3423db94535dSChris Mason 		u32 ioff;
3424db94535dSChris Mason 
34253212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
34263212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
34270783fcfcSChris Mason 	}
342874123bd7SChris Mason 
34295f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
34305f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
34316ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
34325f39d397SChris Mason 
34335f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
34345f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3435eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
34365f39d397SChris Mason 
3437be0e5c09SChris Mason 	if (mid <= slot) {
3438925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
34395f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
34405f39d397SChris Mason 		path->nodes[0] = right;
3441be0e5c09SChris Mason 		path->slots[0] -= mid;
3442be0e5c09SChris Mason 		path->slots[1] += 1;
3443925baeddSChris Mason 	} else {
3444925baeddSChris Mason 		btrfs_tree_unlock(right);
34455f39d397SChris Mason 		free_extent_buffer(right);
3446925baeddSChris Mason 	}
34475f39d397SChris Mason 
3448eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
344944871b1bSChris Mason }
345044871b1bSChris Mason 
345144871b1bSChris Mason /*
345299d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
345399d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
345499d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
345599d8f83cSChris Mason  *          A                 B                 C
345699d8f83cSChris Mason  *
345799d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
345899d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
345999d8f83cSChris Mason  * completely.
346099d8f83cSChris Mason  */
346199d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
346299d8f83cSChris Mason 					  struct btrfs_root *root,
346399d8f83cSChris Mason 					  struct btrfs_path *path,
346499d8f83cSChris Mason 					  int data_size)
346599d8f83cSChris Mason {
346699d8f83cSChris Mason 	int ret;
346799d8f83cSChris Mason 	int progress = 0;
346899d8f83cSChris Mason 	int slot;
346999d8f83cSChris Mason 	u32 nritems;
34705a4267caSFilipe David Borba Manana 	int space_needed = data_size;
347199d8f83cSChris Mason 
347299d8f83cSChris Mason 	slot = path->slots[0];
34735a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3474e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
347599d8f83cSChris Mason 
347699d8f83cSChris Mason 	/*
347799d8f83cSChris Mason 	 * try to push all the items after our slot into the
347899d8f83cSChris Mason 	 * right leaf
347999d8f83cSChris Mason 	 */
34805a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
348199d8f83cSChris Mason 	if (ret < 0)
348299d8f83cSChris Mason 		return ret;
348399d8f83cSChris Mason 
348499d8f83cSChris Mason 	if (ret == 0)
348599d8f83cSChris Mason 		progress++;
348699d8f83cSChris Mason 
348799d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
348899d8f83cSChris Mason 	/*
348999d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
349099d8f83cSChris Mason 	 * we've done so we're done
349199d8f83cSChris Mason 	 */
349299d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
349399d8f83cSChris Mason 		return 0;
349499d8f83cSChris Mason 
3495e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
349699d8f83cSChris Mason 		return 0;
349799d8f83cSChris Mason 
349899d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
349999d8f83cSChris Mason 	slot = path->slots[0];
3500263d3995SFilipe Manana 	space_needed = data_size;
3501263d3995SFilipe Manana 	if (slot > 0)
3502e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
35035a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
350499d8f83cSChris Mason 	if (ret < 0)
350599d8f83cSChris Mason 		return ret;
350699d8f83cSChris Mason 
350799d8f83cSChris Mason 	if (ret == 0)
350899d8f83cSChris Mason 		progress++;
350999d8f83cSChris Mason 
351099d8f83cSChris Mason 	if (progress)
351199d8f83cSChris Mason 		return 0;
351299d8f83cSChris Mason 	return 1;
351399d8f83cSChris Mason }
351499d8f83cSChris Mason 
351599d8f83cSChris Mason /*
351644871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
351744871b1bSChris Mason  * available for the resulting leaf level of the path.
351844871b1bSChris Mason  *
351944871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
352044871b1bSChris Mason  */
352144871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
352244871b1bSChris Mason 			       struct btrfs_root *root,
3523310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
352444871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
352544871b1bSChris Mason 			       int extend)
352644871b1bSChris Mason {
35275d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
352844871b1bSChris Mason 	struct extent_buffer *l;
352944871b1bSChris Mason 	u32 nritems;
353044871b1bSChris Mason 	int mid;
353144871b1bSChris Mason 	int slot;
353244871b1bSChris Mason 	struct extent_buffer *right;
3533b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
353444871b1bSChris Mason 	int ret = 0;
353544871b1bSChris Mason 	int wret;
35365d4f98a2SYan Zheng 	int split;
353744871b1bSChris Mason 	int num_doubles = 0;
353899d8f83cSChris Mason 	int tried_avoid_double = 0;
353944871b1bSChris Mason 
3540a5719521SYan, Zheng 	l = path->nodes[0];
3541a5719521SYan, Zheng 	slot = path->slots[0];
35423212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
35430b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3544a5719521SYan, Zheng 		return -EOVERFLOW;
3545a5719521SYan, Zheng 
354644871b1bSChris Mason 	/* first try to make some room by pushing left and right */
354733157e05SLiu Bo 	if (data_size && path->nodes[1]) {
35485a4267caSFilipe David Borba Manana 		int space_needed = data_size;
35495a4267caSFilipe David Borba Manana 
35505a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3551e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
35525a4267caSFilipe David Borba Manana 
35535a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
35545a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
355544871b1bSChris Mason 		if (wret < 0)
355644871b1bSChris Mason 			return wret;
355744871b1bSChris Mason 		if (wret) {
3558263d3995SFilipe Manana 			space_needed = data_size;
3559263d3995SFilipe Manana 			if (slot > 0)
3560e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
35615a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
35625a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
356344871b1bSChris Mason 			if (wret < 0)
356444871b1bSChris Mason 				return wret;
356544871b1bSChris Mason 		}
356644871b1bSChris Mason 		l = path->nodes[0];
356744871b1bSChris Mason 
356844871b1bSChris Mason 		/* did the pushes work? */
3569e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
357044871b1bSChris Mason 			return 0;
357144871b1bSChris Mason 	}
357244871b1bSChris Mason 
357344871b1bSChris Mason 	if (!path->nodes[1]) {
3574fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
357544871b1bSChris Mason 		if (ret)
357644871b1bSChris Mason 			return ret;
357744871b1bSChris Mason 	}
357844871b1bSChris Mason again:
35795d4f98a2SYan Zheng 	split = 1;
358044871b1bSChris Mason 	l = path->nodes[0];
358144871b1bSChris Mason 	slot = path->slots[0];
358244871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
358344871b1bSChris Mason 	mid = (nritems + 1) / 2;
358444871b1bSChris Mason 
35855d4f98a2SYan Zheng 	if (mid <= slot) {
35865d4f98a2SYan Zheng 		if (nritems == 1 ||
35875d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
35880b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
35895d4f98a2SYan Zheng 			if (slot >= nritems) {
35905d4f98a2SYan Zheng 				split = 0;
35915d4f98a2SYan Zheng 			} else {
35925d4f98a2SYan Zheng 				mid = slot;
35935d4f98a2SYan Zheng 				if (mid != nritems &&
35945d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
35950b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
359699d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
359799d8f83cSChris Mason 						goto push_for_double;
35985d4f98a2SYan Zheng 					split = 2;
35995d4f98a2SYan Zheng 				}
36005d4f98a2SYan Zheng 			}
36015d4f98a2SYan Zheng 		}
36025d4f98a2SYan Zheng 	} else {
36035d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
36040b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
36055d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
36065d4f98a2SYan Zheng 				split = 0;
36075d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
36085d4f98a2SYan Zheng 				mid = 1;
36095d4f98a2SYan Zheng 			} else {
36105d4f98a2SYan Zheng 				mid = slot;
36115d4f98a2SYan Zheng 				if (mid != nritems &&
36125d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
36130b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
361499d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
361599d8f83cSChris Mason 						goto push_for_double;
36165d4f98a2SYan Zheng 					split = 2;
36175d4f98a2SYan Zheng 				}
36185d4f98a2SYan Zheng 			}
36195d4f98a2SYan Zheng 		}
36205d4f98a2SYan Zheng 	}
36215d4f98a2SYan Zheng 
36225d4f98a2SYan Zheng 	if (split == 0)
36235d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
36245d4f98a2SYan Zheng 	else
36255d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
36265d4f98a2SYan Zheng 
3627ca9d473aSJosef Bacik 	/*
3628ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3629ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3630ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3631ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3632ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3633ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3634ca9d473aSJosef Bacik 	 */
363579bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
363679bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
363779bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3638ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3639f0486c68SYan, Zheng 	if (IS_ERR(right))
364044871b1bSChris Mason 		return PTR_ERR(right);
3641f0486c68SYan, Zheng 
36420b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
364344871b1bSChris Mason 
36445d4f98a2SYan Zheng 	if (split == 0) {
364544871b1bSChris Mason 		if (mid <= slot) {
364644871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
36476ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
36482ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
364944871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
365044871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
365144871b1bSChris Mason 			path->nodes[0] = right;
365244871b1bSChris Mason 			path->slots[0] = 0;
365344871b1bSChris Mason 			path->slots[1] += 1;
365444871b1bSChris Mason 		} else {
365544871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
36566ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
36572ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
365844871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
365944871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
366044871b1bSChris Mason 			path->nodes[0] = right;
366144871b1bSChris Mason 			path->slots[0] = 0;
3662143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3663b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
36645d4f98a2SYan Zheng 		}
3665196e0249SLiu Bo 		/*
3666196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3667196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3668196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3669196e0249SLiu Bo 		 */
367044871b1bSChris Mason 		return ret;
367144871b1bSChris Mason 	}
367244871b1bSChris Mason 
367394f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
367444871b1bSChris Mason 
36755d4f98a2SYan Zheng 	if (split == 2) {
3676cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3677cc0c5538SChris Mason 		num_doubles++;
3678cc0c5538SChris Mason 		goto again;
36793326d1b0SChris Mason 	}
368044871b1bSChris Mason 
3681143bede5SJeff Mahoney 	return 0;
368299d8f83cSChris Mason 
368399d8f83cSChris Mason push_for_double:
368499d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
368599d8f83cSChris Mason 	tried_avoid_double = 1;
3686e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
368799d8f83cSChris Mason 		return 0;
368899d8f83cSChris Mason 	goto again;
3689be0e5c09SChris Mason }
3690be0e5c09SChris Mason 
3691ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3692ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3693ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3694ad48fd75SYan, Zheng {
3695ad48fd75SYan, Zheng 	struct btrfs_key key;
3696ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3697ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3698ad48fd75SYan, Zheng 	u64 extent_len = 0;
3699ad48fd75SYan, Zheng 	u32 item_size;
3700ad48fd75SYan, Zheng 	int ret;
3701ad48fd75SYan, Zheng 
3702ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3703ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3704ad48fd75SYan, Zheng 
3705ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3706ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3707ad48fd75SYan, Zheng 
3708e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3709ad48fd75SYan, Zheng 		return 0;
3710ad48fd75SYan, Zheng 
37113212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3712ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3713ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3714ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3715ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3716ad48fd75SYan, Zheng 	}
3717b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3718ad48fd75SYan, Zheng 
3719ad48fd75SYan, Zheng 	path->keep_locks = 1;
3720ad48fd75SYan, Zheng 	path->search_for_split = 1;
3721ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3722ad48fd75SYan, Zheng 	path->search_for_split = 0;
3723a8df6fe6SFilipe Manana 	if (ret > 0)
3724a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3725ad48fd75SYan, Zheng 	if (ret < 0)
3726ad48fd75SYan, Zheng 		goto err;
3727ad48fd75SYan, Zheng 
3728ad48fd75SYan, Zheng 	ret = -EAGAIN;
3729ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3730a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
37313212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3732ad48fd75SYan, Zheng 		goto err;
3733ad48fd75SYan, Zheng 
3734109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3735e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3736109f6aefSChris Mason 		goto err;
3737109f6aefSChris Mason 
3738ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3739ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3740ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3741ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3742ad48fd75SYan, Zheng 			goto err;
3743ad48fd75SYan, Zheng 	}
3744ad48fd75SYan, Zheng 
3745ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3746f0486c68SYan, Zheng 	if (ret)
3747f0486c68SYan, Zheng 		goto err;
3748ad48fd75SYan, Zheng 
3749ad48fd75SYan, Zheng 	path->keep_locks = 0;
3750ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3751ad48fd75SYan, Zheng 	return 0;
3752ad48fd75SYan, Zheng err:
3753ad48fd75SYan, Zheng 	path->keep_locks = 0;
3754ad48fd75SYan, Zheng 	return ret;
3755ad48fd75SYan, Zheng }
3756ad48fd75SYan, Zheng 
375725263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3758310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3759459931ecSChris Mason 			       unsigned long split_offset)
3760459931ecSChris Mason {
3761459931ecSChris Mason 	struct extent_buffer *leaf;
3762c91666b1SJosef Bacik 	int orig_slot, slot;
3763ad48fd75SYan, Zheng 	char *buf;
3764459931ecSChris Mason 	u32 nritems;
3765ad48fd75SYan, Zheng 	u32 item_size;
3766459931ecSChris Mason 	u32 orig_offset;
3767459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3768459931ecSChris Mason 
3769459931ecSChris Mason 	leaf = path->nodes[0];
3770e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3771b9473439SChris Mason 
3772c91666b1SJosef Bacik 	orig_slot = path->slots[0];
37733212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
37743212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3775459931ecSChris Mason 
3776459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3777ad48fd75SYan, Zheng 	if (!buf)
3778ad48fd75SYan, Zheng 		return -ENOMEM;
3779ad48fd75SYan, Zheng 
3780459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3781459931ecSChris Mason 			    path->slots[0]), item_size);
3782ad48fd75SYan, Zheng 
3783459931ecSChris Mason 	slot = path->slots[0] + 1;
3784459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3785459931ecSChris Mason 	if (slot != nritems) {
3786459931ecSChris Mason 		/* shift the items */
378742c9419aSJosef Bacik 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, slot + 1),
378842c9419aSJosef Bacik 				btrfs_item_nr_offset(leaf, slot),
3789459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3790459931ecSChris Mason 	}
3791459931ecSChris Mason 
3792459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3793459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3794459931ecSChris Mason 
37953212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
37963212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3797459931ecSChris Mason 
37983212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
3799459931ecSChris Mason 				 orig_offset + item_size - split_offset);
38003212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3801459931ecSChris Mason 
3802459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3803459931ecSChris Mason 
3804459931ecSChris Mason 	/* write the data for the start of the original item */
3805459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3806459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3807459931ecSChris Mason 			    split_offset);
3808459931ecSChris Mason 
3809459931ecSChris Mason 	/* write the data for the new item */
3810459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3811459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3812459931ecSChris Mason 			    item_size - split_offset);
3813459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3814459931ecSChris Mason 
3815e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3816459931ecSChris Mason 	kfree(buf);
3817ad48fd75SYan, Zheng 	return 0;
3818ad48fd75SYan, Zheng }
3819ad48fd75SYan, Zheng 
3820ad48fd75SYan, Zheng /*
3821ad48fd75SYan, Zheng  * This function splits a single item into two items,
3822ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3823ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3824ad48fd75SYan, Zheng  *
3825ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3826ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3827ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3828ad48fd75SYan, Zheng  *
3829ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3830ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3831ad48fd75SYan, Zheng  *
3832ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3833ad48fd75SYan, Zheng  * leaf the entire time.
3834ad48fd75SYan, Zheng  */
3835ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3836ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3837ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3838310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3839ad48fd75SYan, Zheng 		     unsigned long split_offset)
3840ad48fd75SYan, Zheng {
3841ad48fd75SYan, Zheng 	int ret;
3842ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3843ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3844ad48fd75SYan, Zheng 	if (ret)
3845459931ecSChris Mason 		return ret;
3846ad48fd75SYan, Zheng 
384725263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3848ad48fd75SYan, Zheng 	return ret;
3849ad48fd75SYan, Zheng }
3850ad48fd75SYan, Zheng 
3851ad48fd75SYan, Zheng /*
3852d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
3853d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
3854d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
3855d352ac68SChris Mason  * the front.
3856d352ac68SChris Mason  */
385778ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3858b18c6685SChris Mason {
3859b18c6685SChris Mason 	int slot;
38605f39d397SChris Mason 	struct extent_buffer *leaf;
3861b18c6685SChris Mason 	u32 nritems;
3862b18c6685SChris Mason 	unsigned int data_end;
3863b18c6685SChris Mason 	unsigned int old_data_start;
3864b18c6685SChris Mason 	unsigned int old_size;
3865b18c6685SChris Mason 	unsigned int size_diff;
3866b18c6685SChris Mason 	int i;
3867cfed81a0SChris Mason 	struct btrfs_map_token token;
3868cfed81a0SChris Mason 
38695f39d397SChris Mason 	leaf = path->nodes[0];
3870179e29e4SChris Mason 	slot = path->slots[0];
3871179e29e4SChris Mason 
38723212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
3873179e29e4SChris Mason 	if (old_size == new_size)
3874143bede5SJeff Mahoney 		return;
3875b18c6685SChris Mason 
38765f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
38778f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3878b18c6685SChris Mason 
38793212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
3880179e29e4SChris Mason 
3881b18c6685SChris Mason 	size_diff = old_size - new_size;
3882b18c6685SChris Mason 
3883b18c6685SChris Mason 	BUG_ON(slot < 0);
3884b18c6685SChris Mason 	BUG_ON(slot >= nritems);
3885b18c6685SChris Mason 
3886b18c6685SChris Mason 	/*
3887b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3888b18c6685SChris Mason 	 */
3889b18c6685SChris Mason 	/* first correct the data pointers */
3890c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3891b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
38925f39d397SChris Mason 		u32 ioff;
3893db94535dSChris Mason 
38943212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
38953212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3896b18c6685SChris Mason 	}
3897db94535dSChris Mason 
3898b18c6685SChris Mason 	/* shift the data */
3899179e29e4SChris Mason 	if (from_end) {
39003d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
39013d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3902b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
3903179e29e4SChris Mason 	} else {
3904179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
3905179e29e4SChris Mason 		u64 offset;
3906179e29e4SChris Mason 
3907179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
3908179e29e4SChris Mason 
3909179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3910179e29e4SChris Mason 			unsigned long ptr;
3911179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
3912179e29e4SChris Mason 
3913179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
3914179e29e4SChris Mason 					    struct btrfs_file_extent_item);
3915179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
3916179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
3917179e29e4SChris Mason 
3918179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
3919179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
3920179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
3921179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
3922179e29e4SChris Mason 				      (unsigned long)fi,
39237ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
3924179e29e4SChris Mason 			}
3925179e29e4SChris Mason 		}
3926179e29e4SChris Mason 
39273d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
39283d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3929179e29e4SChris Mason 			      data_end, old_data_start - data_end);
3930179e29e4SChris Mason 
3931179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
3932179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3933179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
3934179e29e4SChris Mason 		if (slot == 0)
3935b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
3936179e29e4SChris Mason 	}
39375f39d397SChris Mason 
39383212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
39395f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3940b18c6685SChris Mason 
3941e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3942a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3943b18c6685SChris Mason 		BUG();
39445f39d397SChris Mason 	}
3945b18c6685SChris Mason }
3946b18c6685SChris Mason 
3947d352ac68SChris Mason /*
39488f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
3949d352ac68SChris Mason  */
3950c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
39516567e837SChris Mason {
39526567e837SChris Mason 	int slot;
39535f39d397SChris Mason 	struct extent_buffer *leaf;
39546567e837SChris Mason 	u32 nritems;
39556567e837SChris Mason 	unsigned int data_end;
39566567e837SChris Mason 	unsigned int old_data;
39576567e837SChris Mason 	unsigned int old_size;
39586567e837SChris Mason 	int i;
3959cfed81a0SChris Mason 	struct btrfs_map_token token;
3960cfed81a0SChris Mason 
39615f39d397SChris Mason 	leaf = path->nodes[0];
39626567e837SChris Mason 
39635f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
39648f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
39656567e837SChris Mason 
3966e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
3967a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39686567e837SChris Mason 		BUG();
39695f39d397SChris Mason 	}
39706567e837SChris Mason 	slot = path->slots[0];
3971dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
39726567e837SChris Mason 
39736567e837SChris Mason 	BUG_ON(slot < 0);
39743326d1b0SChris Mason 	if (slot >= nritems) {
3975a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3976c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
3977d397712bSChris Mason 			   slot, nritems);
3978290342f6SArnd Bergmann 		BUG();
39793326d1b0SChris Mason 	}
39806567e837SChris Mason 
39816567e837SChris Mason 	/*
39826567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
39836567e837SChris Mason 	 */
39846567e837SChris Mason 	/* first correct the data pointers */
3985c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
39866567e837SChris Mason 	for (i = slot; i < nritems; i++) {
39875f39d397SChris Mason 		u32 ioff;
3988db94535dSChris Mason 
39893212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
39903212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
39916567e837SChris Mason 	}
39925f39d397SChris Mason 
39936567e837SChris Mason 	/* shift the data */
39943d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
39953d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
39966567e837SChris Mason 		      data_end, old_data - data_end);
39975f39d397SChris Mason 
39986567e837SChris Mason 	data_end = old_data;
39993212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
40003212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
40015f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
40026567e837SChris Mason 
4003e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4004a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
40056567e837SChris Mason 		BUG();
40065f39d397SChris Mason 	}
40076567e837SChris Mason }
40086567e837SChris Mason 
400943dd529aSDavid Sterba /*
401043dd529aSDavid Sterba  * Make space in the node before inserting one or more items.
4011da9ffb24SNikolay Borisov  *
4012da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
4013da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
4014b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
401543dd529aSDavid Sterba  *
401643dd529aSDavid Sterba  * Main purpose is to save stack depth by doing the bulk of the work in a
401743dd529aSDavid Sterba  * function that doesn't call btrfs_search_slot
401874123bd7SChris Mason  */
4019f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4020b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
4021be0e5c09SChris Mason {
40220b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
40239c58309dSChris Mason 	int i;
40247518a238SChris Mason 	u32 nritems;
4025be0e5c09SChris Mason 	unsigned int data_end;
4026e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
402744871b1bSChris Mason 	struct extent_buffer *leaf;
402844871b1bSChris Mason 	int slot;
4029cfed81a0SChris Mason 	struct btrfs_map_token token;
4030fc0d82e1SNikolay Borisov 	u32 total_size;
4031fc0d82e1SNikolay Borisov 
4032b7ef5f3aSFilipe Manana 	/*
4033b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
4034b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
4035b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
4036b7ef5f3aSFilipe Manana 	 */
403724cdc847SFilipe Manana 	if (path->slots[0] == 0) {
4038b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4039b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
404024cdc847SFilipe Manana 	}
404124cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
404224cdc847SFilipe Manana 
40435f39d397SChris Mason 	leaf = path->nodes[0];
404444871b1bSChris Mason 	slot = path->slots[0];
404574123bd7SChris Mason 
40465f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
40478f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4048b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4049eb60ceacSChris Mason 
4050e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4051a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
40520b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4053e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4054be0e5c09SChris Mason 		BUG();
4055d4dbff95SChris Mason 	}
40565f39d397SChris Mason 
4057c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4058be0e5c09SChris Mason 	if (slot != nritems) {
4059dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4060be0e5c09SChris Mason 
40615f39d397SChris Mason 		if (old_data < data_end) {
4062a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
40637269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
40647269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
40655f39d397SChris Mason 				   slot, old_data, data_end);
4066290342f6SArnd Bergmann 			BUG();
40675f39d397SChris Mason 		}
4068be0e5c09SChris Mason 		/*
4069be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4070be0e5c09SChris Mason 		 */
4071be0e5c09SChris Mason 		/* first correct the data pointers */
40720783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
40735f39d397SChris Mason 			u32 ioff;
4074db94535dSChris Mason 
40753212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
40763212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
4077b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
40780783fcfcSChris Mason 		}
4079be0e5c09SChris Mason 		/* shift the items */
408042c9419aSJosef Bacik 		memmove_extent_buffer(leaf,
408142c9419aSJosef Bacik 				      btrfs_item_nr_offset(leaf, slot + batch->nr),
408242c9419aSJosef Bacik 				      btrfs_item_nr_offset(leaf, slot),
40830783fcfcSChris Mason 				      (nritems - slot) * sizeof(struct btrfs_item));
4084be0e5c09SChris Mason 
4085be0e5c09SChris Mason 		/* shift the data */
40863d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4087b7ef5f3aSFilipe Manana 				      data_end - batch->total_data_size,
4088b7ef5f3aSFilipe Manana 				      BTRFS_LEAF_DATA_OFFSET + data_end,
4089b7ef5f3aSFilipe Manana 				      old_data - data_end);
4090be0e5c09SChris Mason 		data_end = old_data;
4091be0e5c09SChris Mason 	}
40925f39d397SChris Mason 
409362e2749eSChris Mason 	/* setup the item for the new data */
4094b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
4095b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
40969c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4097b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
40983212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
40993212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
41009c58309dSChris Mason 	}
410144871b1bSChris Mason 
4102b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4103b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4104aa5d6bedSChris Mason 
4105e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4106a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4107be0e5c09SChris Mason 		BUG();
41085f39d397SChris Mason 	}
410944871b1bSChris Mason }
411044871b1bSChris Mason 
411144871b1bSChris Mason /*
4112f0641656SFilipe Manana  * Insert a new item into a leaf.
4113f0641656SFilipe Manana  *
4114f0641656SFilipe Manana  * @root:      The root of the btree.
4115f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
4116f0641656SFilipe Manana  * @key:       The key of the new item.
4117f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
4118f0641656SFilipe Manana  */
4119f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
4120f0641656SFilipe Manana 				 struct btrfs_path *path,
4121f0641656SFilipe Manana 				 const struct btrfs_key *key,
4122f0641656SFilipe Manana 				 u32 data_size)
4123f0641656SFilipe Manana {
4124f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4125f0641656SFilipe Manana 
4126f0641656SFilipe Manana 	batch.keys = key;
4127f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4128f0641656SFilipe Manana 	batch.total_data_size = data_size;
4129f0641656SFilipe Manana 	batch.nr = 1;
4130f0641656SFilipe Manana 
4131f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
4132f0641656SFilipe Manana }
4133f0641656SFilipe Manana 
4134f0641656SFilipe Manana /*
413544871b1bSChris Mason  * Given a key and some data, insert items into the tree.
413644871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
413744871b1bSChris Mason  */
413844871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
413944871b1bSChris Mason 			    struct btrfs_root *root,
414044871b1bSChris Mason 			    struct btrfs_path *path,
4141b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
414244871b1bSChris Mason {
414344871b1bSChris Mason 	int ret = 0;
414444871b1bSChris Mason 	int slot;
4145b7ef5f3aSFilipe Manana 	u32 total_size;
414644871b1bSChris Mason 
4147b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4148b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
414944871b1bSChris Mason 	if (ret == 0)
415044871b1bSChris Mason 		return -EEXIST;
415144871b1bSChris Mason 	if (ret < 0)
4152143bede5SJeff Mahoney 		return ret;
415344871b1bSChris Mason 
415444871b1bSChris Mason 	slot = path->slots[0];
415544871b1bSChris Mason 	BUG_ON(slot < 0);
415644871b1bSChris Mason 
4157b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4158143bede5SJeff Mahoney 	return 0;
415962e2749eSChris Mason }
416062e2749eSChris Mason 
416162e2749eSChris Mason /*
416262e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
416362e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
416462e2749eSChris Mason  */
4165310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4166310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4167310712b2SOmar Sandoval 		      u32 data_size)
416862e2749eSChris Mason {
416962e2749eSChris Mason 	int ret = 0;
41702c90e5d6SChris Mason 	struct btrfs_path *path;
41715f39d397SChris Mason 	struct extent_buffer *leaf;
41725f39d397SChris Mason 	unsigned long ptr;
417362e2749eSChris Mason 
41742c90e5d6SChris Mason 	path = btrfs_alloc_path();
4175db5b493aSTsutomu Itoh 	if (!path)
4176db5b493aSTsutomu Itoh 		return -ENOMEM;
41772c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
417862e2749eSChris Mason 	if (!ret) {
41795f39d397SChris Mason 		leaf = path->nodes[0];
41805f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
41815f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
41825f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
418362e2749eSChris Mason 	}
41842c90e5d6SChris Mason 	btrfs_free_path(path);
4185aa5d6bedSChris Mason 	return ret;
4186be0e5c09SChris Mason }
4187be0e5c09SChris Mason 
418874123bd7SChris Mason /*
4189f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4190f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4191f0641656SFilipe Manana  * contiguous with the original item.
4192f0641656SFilipe Manana  *
4193f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4194f0641656SFilipe Manana  * the entire time.
4195f0641656SFilipe Manana  */
4196f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4197f0641656SFilipe Manana 			 struct btrfs_root *root,
4198f0641656SFilipe Manana 			 struct btrfs_path *path,
4199f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4200f0641656SFilipe Manana {
4201f0641656SFilipe Manana 	struct extent_buffer *leaf;
4202f0641656SFilipe Manana 	int ret;
4203f0641656SFilipe Manana 	u32 item_size;
4204f0641656SFilipe Manana 
4205f0641656SFilipe Manana 	leaf = path->nodes[0];
42063212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4207f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4208f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4209f0641656SFilipe Manana 	if (ret)
4210f0641656SFilipe Manana 		return ret;
4211f0641656SFilipe Manana 
4212f0641656SFilipe Manana 	path->slots[0]++;
4213f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4214f0641656SFilipe Manana 	leaf = path->nodes[0];
4215f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4216f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4217f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4218f0641656SFilipe Manana 			     item_size);
4219f0641656SFilipe Manana 	return 0;
4220f0641656SFilipe Manana }
4221f0641656SFilipe Manana 
4222f0641656SFilipe Manana /*
42235de08d7dSChris Mason  * delete the pointer from a given node.
422474123bd7SChris Mason  *
4225d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4226d352ac68SChris Mason  * empty a node.
422774123bd7SChris Mason  */
4228afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4229afe5fea7STsutomu Itoh 		    int level, int slot)
4230be0e5c09SChris Mason {
42315f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
42327518a238SChris Mason 	u32 nritems;
4233f3ea38daSJan Schmidt 	int ret;
4234be0e5c09SChris Mason 
42355f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4236be0e5c09SChris Mason 	if (slot != nritems - 1) {
4237bf1d3425SDavid Sterba 		if (level) {
4238f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4239f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4240bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4241bf1d3425SDavid Sterba 		}
42425f39d397SChris Mason 		memmove_extent_buffer(parent,
4243*e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot),
4244*e23efd8eSJosef Bacik 			      btrfs_node_key_ptr_offset(parent, slot + 1),
4245d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4246d6025579SChris Mason 			      (nritems - slot - 1));
424757ba86c0SChris Mason 	} else if (level) {
4248f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
424933cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REMOVE);
425057ba86c0SChris Mason 		BUG_ON(ret < 0);
4251be0e5c09SChris Mason 	}
4252f3ea38daSJan Schmidt 
42537518a238SChris Mason 	nritems--;
42545f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
42557518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
42565f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4257eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
42585f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4259bb803951SChris Mason 	} else if (slot == 0) {
42605f39d397SChris Mason 		struct btrfs_disk_key disk_key;
42615f39d397SChris Mason 
42625f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4263b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4264be0e5c09SChris Mason 	}
4265d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4266be0e5c09SChris Mason }
4267be0e5c09SChris Mason 
426874123bd7SChris Mason /*
4269323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
42705d4f98a2SYan Zheng  * path->nodes[1].
4271323ac95bSChris Mason  *
4272323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4273323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4274323ac95bSChris Mason  *
4275323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4276323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4277323ac95bSChris Mason  */
4278143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4279323ac95bSChris Mason 				    struct btrfs_root *root,
42805d4f98a2SYan Zheng 				    struct btrfs_path *path,
42815d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4282323ac95bSChris Mason {
42835d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4284afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4285323ac95bSChris Mason 
42864d081c41SChris Mason 	/*
42874d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
42884d081c41SChris Mason 	 * aren't holding any locks when we call it
42894d081c41SChris Mason 	 */
42904d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
42914d081c41SChris Mason 
4292f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4293f0486c68SYan, Zheng 
429467439dadSDavid Sterba 	atomic_inc(&leaf->refs);
42957a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
42963083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4297323ac95bSChris Mason }
4298323ac95bSChris Mason /*
429974123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
430074123bd7SChris Mason  * the leaf, remove it from the tree
430174123bd7SChris Mason  */
430285e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
430385e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4304be0e5c09SChris Mason {
43050b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
43065f39d397SChris Mason 	struct extent_buffer *leaf;
4307aa5d6bedSChris Mason 	int ret = 0;
4308aa5d6bedSChris Mason 	int wret;
43097518a238SChris Mason 	u32 nritems;
4310be0e5c09SChris Mason 
43115f39d397SChris Mason 	leaf = path->nodes[0];
43125f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4313be0e5c09SChris Mason 
431485e21bacSChris Mason 	if (slot + nr != nritems) {
43150cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
43160cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4317c82f823cSDavid Sterba 		struct btrfs_map_token token;
43180cae23b6SFilipe Manana 		u32 dsize = 0;
43190cae23b6SFilipe Manana 		int i;
43200cae23b6SFilipe Manana 
43210cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
43220cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
43235f39d397SChris Mason 
43243d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4325d6025579SChris Mason 			      data_end + dsize,
43263d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
432785e21bacSChris Mason 			      last_off - data_end);
43285f39d397SChris Mason 
4329c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
433085e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
43315f39d397SChris Mason 			u32 ioff;
4332db94535dSChris Mason 
43333212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
43343212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
43350783fcfcSChris Mason 		}
4336db94535dSChris Mason 
433742c9419aSJosef Bacik 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, slot),
433842c9419aSJosef Bacik 			      btrfs_item_nr_offset(leaf, slot + nr),
43390783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
434085e21bacSChris Mason 			      (nritems - slot - nr));
4341be0e5c09SChris Mason 	}
434285e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
434385e21bacSChris Mason 	nritems -= nr;
43445f39d397SChris Mason 
434574123bd7SChris Mason 	/* delete the leaf if we've emptied it */
43467518a238SChris Mason 	if (nritems == 0) {
43475f39d397SChris Mason 		if (leaf == root->node) {
43485f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
43499a8dd150SChris Mason 		} else {
43506a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4351143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
43529a8dd150SChris Mason 		}
4353be0e5c09SChris Mason 	} else {
43547518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4355aa5d6bedSChris Mason 		if (slot == 0) {
43565f39d397SChris Mason 			struct btrfs_disk_key disk_key;
43575f39d397SChris Mason 
43585f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4359b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4360aa5d6bedSChris Mason 		}
4361aa5d6bedSChris Mason 
43627c4063d1SFilipe Manana 		/*
43637c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
43647c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
43657c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
43667c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
43677c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
43687c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
43697c4063d1SFilipe Manana 		 */
43700b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
43717c4063d1SFilipe Manana 			u32 min_push_space;
43727c4063d1SFilipe Manana 
4373be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4374be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4375be0e5c09SChris Mason 			 * for possible call to del_ptr below
4376be0e5c09SChris Mason 			 */
43774920c9acSChris Mason 			slot = path->slots[1];
437867439dadSDavid Sterba 			atomic_inc(&leaf->refs);
43797c4063d1SFilipe Manana 			/*
43807c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
43817c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
43827c4063d1SFilipe Manana 			 */
43837c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
43847c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
43857c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
43867c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
438754aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4388aa5d6bedSChris Mason 				ret = wret;
43895f39d397SChris Mason 
43905f39d397SChris Mason 			if (path->nodes[0] == leaf &&
43915f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
43927c4063d1SFilipe Manana 				/*
43937c4063d1SFilipe Manana 				 * If we were not able to push all items from our
43947c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
43957c4063d1SFilipe Manana 				 * either push all the remaining items to the
43967c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
43977c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
43987c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
43997c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
44007c4063d1SFilipe Manana 				 * or nearly full.
44017c4063d1SFilipe Manana 				 */
44027c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
44037c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
44047c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
44057c4063d1SFilipe Manana 						       min_push_space, 1, 0);
440654aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4407aa5d6bedSChris Mason 					ret = wret;
4408aa5d6bedSChris Mason 			}
44095f39d397SChris Mason 
44105f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4411323ac95bSChris Mason 				path->slots[1] = slot;
4412143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
44135f39d397SChris Mason 				free_extent_buffer(leaf);
4414143bede5SJeff Mahoney 				ret = 0;
44155de08d7dSChris Mason 			} else {
4416925baeddSChris Mason 				/* if we're still in the path, make sure
4417925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4418925baeddSChris Mason 				 * push_leaf functions must have already
4419925baeddSChris Mason 				 * dirtied this buffer
4420925baeddSChris Mason 				 */
4421925baeddSChris Mason 				if (path->nodes[0] == leaf)
44225f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
44235f39d397SChris Mason 				free_extent_buffer(leaf);
4424be0e5c09SChris Mason 			}
4425d5719762SChris Mason 		} else {
44265f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4427be0e5c09SChris Mason 		}
44289a8dd150SChris Mason 	}
4429aa5d6bedSChris Mason 	return ret;
44309a8dd150SChris Mason }
44319a8dd150SChris Mason 
443297571fd0SChris Mason /*
4433925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
44347bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
44357bb86316SChris Mason  * returns < 0 on io errors.
4436d352ac68SChris Mason  *
4437d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4438d352ac68SChris Mason  * time you call it.
44397bb86316SChris Mason  */
444016e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
44417bb86316SChris Mason {
4442925baeddSChris Mason 	struct btrfs_key key;
4443925baeddSChris Mason 	struct btrfs_disk_key found_key;
4444925baeddSChris Mason 	int ret;
44457bb86316SChris Mason 
4446925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4447925baeddSChris Mason 
4448e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
4449925baeddSChris Mason 		key.offset--;
4450e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
4451925baeddSChris Mason 		key.type--;
4452e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4453e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
4454925baeddSChris Mason 		key.objectid--;
4455e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
4456e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4457e8b0d724SFilipe David Borba Manana 	} else {
44587bb86316SChris Mason 		return 1;
4459e8b0d724SFilipe David Borba Manana 	}
44607bb86316SChris Mason 
4461b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4462925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4463925baeddSChris Mason 	if (ret < 0)
4464925baeddSChris Mason 		return ret;
4465925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4466925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4467337c6f68SFilipe Manana 	/*
4468337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
4469337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
4470337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
4471337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
4472337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
4473337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
4474337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
4475337c6f68SFilipe Manana 	 * the previous key we computed above.
4476337c6f68SFilipe Manana 	 */
4477337c6f68SFilipe Manana 	if (ret <= 0)
44787bb86316SChris Mason 		return 0;
4479925baeddSChris Mason 	return 1;
44807bb86316SChris Mason }
44817bb86316SChris Mason 
44823f157a2fSChris Mason /*
44833f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4484de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4485de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
44863f157a2fSChris Mason  *
44873f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
44883f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
44893f157a2fSChris Mason  * key and get a writable path.
44903f157a2fSChris Mason  *
44913f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
44923f157a2fSChris Mason  * of the tree.
44933f157a2fSChris Mason  *
4494d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4495d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4496d352ac68SChris Mason  * skipped over (without reading them).
4497d352ac68SChris Mason  *
44983f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
44993f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
45003f157a2fSChris Mason  */
45013f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4502de78b51aSEric Sandeen 			 struct btrfs_path *path,
45033f157a2fSChris Mason 			 u64 min_trans)
45043f157a2fSChris Mason {
45053f157a2fSChris Mason 	struct extent_buffer *cur;
45063f157a2fSChris Mason 	struct btrfs_key found_key;
45073f157a2fSChris Mason 	int slot;
45089652480bSYan 	int sret;
45093f157a2fSChris Mason 	u32 nritems;
45103f157a2fSChris Mason 	int level;
45113f157a2fSChris Mason 	int ret = 1;
4512f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
45133f157a2fSChris Mason 
4514c922b016SStefan Roesch 	ASSERT(!path->nowait);
4515f98de9b9SFilipe Manana 	path->keep_locks = 1;
45163f157a2fSChris Mason again:
4517bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
45183f157a2fSChris Mason 	level = btrfs_header_level(cur);
4519e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
45203f157a2fSChris Mason 	path->nodes[level] = cur;
4521bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
45223f157a2fSChris Mason 
45233f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
45243f157a2fSChris Mason 		ret = 1;
45253f157a2fSChris Mason 		goto out;
45263f157a2fSChris Mason 	}
45273f157a2fSChris Mason 	while (1) {
45283f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
45293f157a2fSChris Mason 		level = btrfs_header_level(cur);
4530e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
4531cbca7d59SFilipe Manana 		if (sret < 0) {
4532cbca7d59SFilipe Manana 			ret = sret;
4533cbca7d59SFilipe Manana 			goto out;
4534cbca7d59SFilipe Manana 		}
45353f157a2fSChris Mason 
4536323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4537323ac95bSChris Mason 		if (level == path->lowest_level) {
4538e02119d5SChris Mason 			if (slot >= nritems)
4539e02119d5SChris Mason 				goto find_next_key;
45403f157a2fSChris Mason 			ret = 0;
45413f157a2fSChris Mason 			path->slots[level] = slot;
45423f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
45433f157a2fSChris Mason 			goto out;
45443f157a2fSChris Mason 		}
45459652480bSYan 		if (sret && slot > 0)
45469652480bSYan 			slot--;
45473f157a2fSChris Mason 		/*
4548de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4549260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
45503f157a2fSChris Mason 		 */
45513f157a2fSChris Mason 		while (slot < nritems) {
45523f157a2fSChris Mason 			u64 gen;
4553e02119d5SChris Mason 
45543f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
45553f157a2fSChris Mason 			if (gen < min_trans) {
45563f157a2fSChris Mason 				slot++;
45573f157a2fSChris Mason 				continue;
45583f157a2fSChris Mason 			}
45593f157a2fSChris Mason 			break;
45603f157a2fSChris Mason 		}
4561e02119d5SChris Mason find_next_key:
45623f157a2fSChris Mason 		/*
45633f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
45643f157a2fSChris Mason 		 * and find another one
45653f157a2fSChris Mason 		 */
45663f157a2fSChris Mason 		if (slot >= nritems) {
4567e02119d5SChris Mason 			path->slots[level] = slot;
4568e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4569de78b51aSEric Sandeen 						  min_trans);
4570e02119d5SChris Mason 			if (sret == 0) {
4571b3b4aa74SDavid Sterba 				btrfs_release_path(path);
45723f157a2fSChris Mason 				goto again;
45733f157a2fSChris Mason 			} else {
45743f157a2fSChris Mason 				goto out;
45753f157a2fSChris Mason 			}
45763f157a2fSChris Mason 		}
45773f157a2fSChris Mason 		/* save our key for returning back */
45783f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
45793f157a2fSChris Mason 		path->slots[level] = slot;
45803f157a2fSChris Mason 		if (level == path->lowest_level) {
45813f157a2fSChris Mason 			ret = 0;
45823f157a2fSChris Mason 			goto out;
45833f157a2fSChris Mason 		}
45844b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4585fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4586fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4587fb770ae4SLiu Bo 			goto out;
4588fb770ae4SLiu Bo 		}
45893f157a2fSChris Mason 
4590bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4591b4ce94deSChris Mason 
4592bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
45933f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4594f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
45953f157a2fSChris Mason 	}
45963f157a2fSChris Mason out:
4597f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4598f98de9b9SFilipe Manana 	if (ret == 0) {
4599f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4600f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4601f98de9b9SFilipe Manana 	}
46023f157a2fSChris Mason 	return ret;
46033f157a2fSChris Mason }
46043f157a2fSChris Mason 
46053f157a2fSChris Mason /*
46063f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
46073f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4608de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
46093f157a2fSChris Mason  *
46103f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
46113f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
46123f157a2fSChris Mason  *
46133f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
46143f157a2fSChris Mason  * calling this function.
46153f157a2fSChris Mason  */
4616e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4617de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4618e7a84565SChris Mason {
4619e7a84565SChris Mason 	int slot;
4620e7a84565SChris Mason 	struct extent_buffer *c;
4621e7a84565SChris Mason 
46226a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4623e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4624e7a84565SChris Mason 		if (!path->nodes[level])
4625e7a84565SChris Mason 			return 1;
4626e7a84565SChris Mason 
4627e7a84565SChris Mason 		slot = path->slots[level] + 1;
4628e7a84565SChris Mason 		c = path->nodes[level];
46293f157a2fSChris Mason next:
4630e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
463133c66f43SYan Zheng 			int ret;
463233c66f43SYan Zheng 			int orig_lowest;
463333c66f43SYan Zheng 			struct btrfs_key cur_key;
463433c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
463533c66f43SYan Zheng 			    !path->nodes[level + 1])
4636e7a84565SChris Mason 				return 1;
463733c66f43SYan Zheng 
46386a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
463933c66f43SYan Zheng 				level++;
4640e7a84565SChris Mason 				continue;
4641e7a84565SChris Mason 			}
464233c66f43SYan Zheng 
464333c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
464433c66f43SYan Zheng 			if (level == 0)
464533c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
464633c66f43SYan Zheng 			else
464733c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
464833c66f43SYan Zheng 
464933c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4650b3b4aa74SDavid Sterba 			btrfs_release_path(path);
465133c66f43SYan Zheng 			path->lowest_level = level;
465233c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
465333c66f43SYan Zheng 						0, 0);
465433c66f43SYan Zheng 			path->lowest_level = orig_lowest;
465533c66f43SYan Zheng 			if (ret < 0)
465633c66f43SYan Zheng 				return ret;
465733c66f43SYan Zheng 
465833c66f43SYan Zheng 			c = path->nodes[level];
465933c66f43SYan Zheng 			slot = path->slots[level];
466033c66f43SYan Zheng 			if (ret == 0)
466133c66f43SYan Zheng 				slot++;
466233c66f43SYan Zheng 			goto next;
466333c66f43SYan Zheng 		}
466433c66f43SYan Zheng 
4665e7a84565SChris Mason 		if (level == 0)
4666e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
46673f157a2fSChris Mason 		else {
46683f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
46693f157a2fSChris Mason 
46703f157a2fSChris Mason 			if (gen < min_trans) {
46713f157a2fSChris Mason 				slot++;
46723f157a2fSChris Mason 				goto next;
46733f157a2fSChris Mason 			}
4674e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
46753f157a2fSChris Mason 		}
4676e7a84565SChris Mason 		return 0;
4677e7a84565SChris Mason 	}
4678e7a84565SChris Mason 	return 1;
4679e7a84565SChris Mason }
4680e7a84565SChris Mason 
46813d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
46823d7806ecSJan Schmidt 			u64 time_seq)
46833d7806ecSJan Schmidt {
4684d97e63b6SChris Mason 	int slot;
46858e73f275SChris Mason 	int level;
46865f39d397SChris Mason 	struct extent_buffer *c;
46878e73f275SChris Mason 	struct extent_buffer *next;
4688d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4689925baeddSChris Mason 	struct btrfs_key key;
4690d96b3424SFilipe Manana 	bool need_commit_sem = false;
4691925baeddSChris Mason 	u32 nritems;
4692925baeddSChris Mason 	int ret;
46930e46318dSJosef Bacik 	int i;
4694925baeddSChris Mason 
4695bdcdd86cSFilipe Manana 	/*
4696bdcdd86cSFilipe Manana 	 * The nowait semantics are used only for write paths, where we don't
4697bdcdd86cSFilipe Manana 	 * use the tree mod log and sequence numbers.
4698bdcdd86cSFilipe Manana 	 */
4699bdcdd86cSFilipe Manana 	if (time_seq)
4700c922b016SStefan Roesch 		ASSERT(!path->nowait);
4701c922b016SStefan Roesch 
4702925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4703d397712bSChris Mason 	if (nritems == 0)
4704925baeddSChris Mason 		return 1;
4705925baeddSChris Mason 
47068e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
47078e73f275SChris Mason again:
47088e73f275SChris Mason 	level = 1;
47098e73f275SChris Mason 	next = NULL;
4710b3b4aa74SDavid Sterba 	btrfs_release_path(path);
47118e73f275SChris Mason 
4712a2135011SChris Mason 	path->keep_locks = 1;
47138e73f275SChris Mason 
4714d96b3424SFilipe Manana 	if (time_seq) {
47153d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4716d96b3424SFilipe Manana 	} else {
4717d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4718d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4719d96b3424SFilipe Manana 			need_commit_sem = true;
4720bdcdd86cSFilipe Manana 			if (path->nowait) {
4721bdcdd86cSFilipe Manana 				if (!down_read_trylock(&fs_info->commit_root_sem)) {
4722bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4723bdcdd86cSFilipe Manana 					goto done;
4724bdcdd86cSFilipe Manana 				}
4725bdcdd86cSFilipe Manana 			} else {
4726d96b3424SFilipe Manana 				down_read(&fs_info->commit_root_sem);
4727d96b3424SFilipe Manana 			}
4728bdcdd86cSFilipe Manana 		}
4729925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4730d96b3424SFilipe Manana 	}
4731925baeddSChris Mason 	path->keep_locks = 0;
4732925baeddSChris Mason 
4733925baeddSChris Mason 	if (ret < 0)
4734d96b3424SFilipe Manana 		goto done;
4735925baeddSChris Mason 
4736a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4737168fd7d2SChris Mason 	/*
4738168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4739168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4740168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4741168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4742168fd7d2SChris Mason 	 */
4743a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4744e457afecSYan Zheng 		if (ret == 0)
4745168fd7d2SChris Mason 			path->slots[0]++;
47468e73f275SChris Mason 		ret = 0;
4747925baeddSChris Mason 		goto done;
4748925baeddSChris Mason 	}
47490b43e04fSLiu Bo 	/*
47500b43e04fSLiu Bo 	 * So the above check misses one case:
47510b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
47520b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
47530b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
47540b43e04fSLiu Bo 	 *
47550b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
47560b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
47570b43e04fSLiu Bo 	 *
47580b43e04fSLiu Bo 	 * And a bit more explanation about this check,
47590b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
47600b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
47610b43e04fSLiu Bo 	 * bigger one.
47620b43e04fSLiu Bo 	 */
47630b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
47640b43e04fSLiu Bo 		ret = 0;
47650b43e04fSLiu Bo 		goto done;
47660b43e04fSLiu Bo 	}
4767d97e63b6SChris Mason 
4768234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
47698e73f275SChris Mason 		if (!path->nodes[level]) {
47708e73f275SChris Mason 			ret = 1;
47718e73f275SChris Mason 			goto done;
47728e73f275SChris Mason 		}
47735f39d397SChris Mason 
4774d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4775d97e63b6SChris Mason 		c = path->nodes[level];
47765f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4777d97e63b6SChris Mason 			level++;
47788e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
47798e73f275SChris Mason 				ret = 1;
47808e73f275SChris Mason 				goto done;
47818e73f275SChris Mason 			}
4782d97e63b6SChris Mason 			continue;
4783d97e63b6SChris Mason 		}
47845f39d397SChris Mason 
47850e46318dSJosef Bacik 
47860e46318dSJosef Bacik 		/*
47870e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
47880e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
47890e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
47900e46318dSJosef Bacik 		 */
47910e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
47920e46318dSJosef Bacik 			if (path->locks[level]) {
47930e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
47940e46318dSJosef Bacik 				path->locks[i] = 0;
47950e46318dSJosef Bacik 			}
47960e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
47970e46318dSJosef Bacik 			path->nodes[i] = NULL;
4798925baeddSChris Mason 		}
47995f39d397SChris Mason 
48008e73f275SChris Mason 		next = c;
4801d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4802cda79c54SDavid Sterba 					    slot, &key);
4803bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
48048e73f275SChris Mason 			goto again;
48055f39d397SChris Mason 
480676a05b35SChris Mason 		if (ret < 0) {
4807b3b4aa74SDavid Sterba 			btrfs_release_path(path);
480876a05b35SChris Mason 			goto done;
480976a05b35SChris Mason 		}
481076a05b35SChris Mason 
48115cd57b2cSChris Mason 		if (!path->skip_locking) {
4812bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4813bdcdd86cSFilipe Manana 			if (!ret && path->nowait) {
4814bdcdd86cSFilipe Manana 				ret = -EAGAIN;
4815bdcdd86cSFilipe Manana 				goto done;
4816bdcdd86cSFilipe Manana 			}
4817d42244a0SJan Schmidt 			if (!ret && time_seq) {
4818d42244a0SJan Schmidt 				/*
4819d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4820d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4821d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4822d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4823d42244a0SJan Schmidt 				 * on our lock and cycle.
4824d42244a0SJan Schmidt 				 */
4825cf538830SJan Schmidt 				free_extent_buffer(next);
4826d42244a0SJan Schmidt 				btrfs_release_path(path);
4827d42244a0SJan Schmidt 				cond_resched();
4828d42244a0SJan Schmidt 				goto again;
4829d42244a0SJan Schmidt 			}
48300e46318dSJosef Bacik 			if (!ret)
48310e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4832bd681513SChris Mason 		}
4833d97e63b6SChris Mason 		break;
4834d97e63b6SChris Mason 	}
4835d97e63b6SChris Mason 	path->slots[level] = slot;
4836d97e63b6SChris Mason 	while (1) {
4837d97e63b6SChris Mason 		level--;
4838d97e63b6SChris Mason 		path->nodes[level] = next;
4839d97e63b6SChris Mason 		path->slots[level] = 0;
4840a74a4b97SChris Mason 		if (!path->skip_locking)
4841ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4842d97e63b6SChris Mason 		if (!level)
4843d97e63b6SChris Mason 			break;
4844b4ce94deSChris Mason 
4845d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4846cda79c54SDavid Sterba 					    0, &key);
4847bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
48488e73f275SChris Mason 			goto again;
48498e73f275SChris Mason 
485076a05b35SChris Mason 		if (ret < 0) {
4851b3b4aa74SDavid Sterba 			btrfs_release_path(path);
485276a05b35SChris Mason 			goto done;
485376a05b35SChris Mason 		}
485476a05b35SChris Mason 
4855bdcdd86cSFilipe Manana 		if (!path->skip_locking) {
4856bdcdd86cSFilipe Manana 			if (path->nowait) {
4857bdcdd86cSFilipe Manana 				if (!btrfs_try_tree_read_lock(next)) {
4858bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4859bdcdd86cSFilipe Manana 					goto done;
4860bdcdd86cSFilipe Manana 				}
4861bdcdd86cSFilipe Manana 			} else {
48620e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4863d97e63b6SChris Mason 			}
4864bdcdd86cSFilipe Manana 		}
4865bdcdd86cSFilipe Manana 	}
48668e73f275SChris Mason 	ret = 0;
4867925baeddSChris Mason done:
4868f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
4869d96b3424SFilipe Manana 	if (need_commit_sem) {
4870d96b3424SFilipe Manana 		int ret2;
4871d96b3424SFilipe Manana 
4872d96b3424SFilipe Manana 		path->need_commit_sem = 1;
4873d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
4874d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
4875d96b3424SFilipe Manana 		if (ret2)
4876d96b3424SFilipe Manana 			ret = ret2;
4877d96b3424SFilipe Manana 	}
48788e73f275SChris Mason 
48798e73f275SChris Mason 	return ret;
4880d97e63b6SChris Mason }
48810b86a832SChris Mason 
4882890d2b1aSJosef Bacik int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
4883890d2b1aSJosef Bacik {
4884890d2b1aSJosef Bacik 	path->slots[0]++;
4885890d2b1aSJosef Bacik 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
4886890d2b1aSJosef Bacik 		return btrfs_next_old_leaf(root, path, time_seq);
4887890d2b1aSJosef Bacik 	return 0;
4888890d2b1aSJosef Bacik }
4889890d2b1aSJosef Bacik 
48903f157a2fSChris Mason /*
48913f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
48923f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
48933f157a2fSChris Mason  *
48943f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
48953f157a2fSChris Mason  */
48960b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
48970b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
48980b86a832SChris Mason 			int type)
48990b86a832SChris Mason {
49000b86a832SChris Mason 	struct btrfs_key found_key;
49010b86a832SChris Mason 	struct extent_buffer *leaf;
4902e02119d5SChris Mason 	u32 nritems;
49030b86a832SChris Mason 	int ret;
49040b86a832SChris Mason 
49050b86a832SChris Mason 	while (1) {
49060b86a832SChris Mason 		if (path->slots[0] == 0) {
49070b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
49080b86a832SChris Mason 			if (ret != 0)
49090b86a832SChris Mason 				return ret;
49100b86a832SChris Mason 		} else {
49110b86a832SChris Mason 			path->slots[0]--;
49120b86a832SChris Mason 		}
49130b86a832SChris Mason 		leaf = path->nodes[0];
4914e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
4915e02119d5SChris Mason 		if (nritems == 0)
4916e02119d5SChris Mason 			return 1;
4917e02119d5SChris Mason 		if (path->slots[0] == nritems)
4918e02119d5SChris Mason 			path->slots[0]--;
4919e02119d5SChris Mason 
49200b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4921e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
4922e02119d5SChris Mason 			break;
49230a4eefbbSYan Zheng 		if (found_key.type == type)
49240a4eefbbSYan Zheng 			return 0;
4925e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
4926e02119d5SChris Mason 		    found_key.type < type)
4927e02119d5SChris Mason 			break;
49280b86a832SChris Mason 	}
49290b86a832SChris Mason 	return 1;
49300b86a832SChris Mason }
4931ade2e0b3SWang Shilong 
4932ade2e0b3SWang Shilong /*
4933ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
4934ade2e0b3SWang Shilong  * min objecitd.
4935ade2e0b3SWang Shilong  *
4936ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4937ade2e0b3SWang Shilong  */
4938ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
4939ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
4940ade2e0b3SWang Shilong {
4941ade2e0b3SWang Shilong 	struct btrfs_key found_key;
4942ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
4943ade2e0b3SWang Shilong 	u32 nritems;
4944ade2e0b3SWang Shilong 	int ret;
4945ade2e0b3SWang Shilong 
4946ade2e0b3SWang Shilong 	while (1) {
4947ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
4948ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
4949ade2e0b3SWang Shilong 			if (ret != 0)
4950ade2e0b3SWang Shilong 				return ret;
4951ade2e0b3SWang Shilong 		} else {
4952ade2e0b3SWang Shilong 			path->slots[0]--;
4953ade2e0b3SWang Shilong 		}
4954ade2e0b3SWang Shilong 		leaf = path->nodes[0];
4955ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
4956ade2e0b3SWang Shilong 		if (nritems == 0)
4957ade2e0b3SWang Shilong 			return 1;
4958ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
4959ade2e0b3SWang Shilong 			path->slots[0]--;
4960ade2e0b3SWang Shilong 
4961ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4962ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
4963ade2e0b3SWang Shilong 			break;
4964ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4965ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
4966ade2e0b3SWang Shilong 			return 0;
4967ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
4968ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
4969ade2e0b3SWang Shilong 			break;
4970ade2e0b3SWang Shilong 	}
4971ade2e0b3SWang Shilong 	return 1;
4972ade2e0b3SWang Shilong }
4973226463d7SJosef Bacik 
4974226463d7SJosef Bacik int __init btrfs_ctree_init(void)
4975226463d7SJosef Bacik {
4976226463d7SJosef Bacik 	btrfs_path_cachep = kmem_cache_create("btrfs_path",
4977226463d7SJosef Bacik 			sizeof(struct btrfs_path), 0,
4978226463d7SJosef Bacik 			SLAB_MEM_SPREAD, NULL);
4979226463d7SJosef Bacik 	if (!btrfs_path_cachep)
4980226463d7SJosef Bacik 		return -ENOMEM;
4981226463d7SJosef Bacik 	return 0;
4982226463d7SJosef Bacik }
4983226463d7SJosef Bacik 
4984226463d7SJosef Bacik void __cold btrfs_ctree_exit(void)
4985226463d7SJosef Bacik {
4986226463d7SJosef Bacik 	kmem_cache_destroy(btrfs_path_cachep);
4987226463d7SJosef Bacik }
4988