xref: /openbmc/linux/fs/btrfs/ctree.c (revision 43dd529abed2bcf1467f13cce83da1c8456587ea)
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"
249a8dd150SChris Mason 
25226463d7SJosef Bacik static struct kmem_cache *btrfs_path_cachep;
26226463d7SJosef Bacik 
27e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
28e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
29310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
30310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
31310712b2SOmar Sandoval 		      int data_size, int extend);
325f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
332ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
34971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
355f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
365f39d397SChris Mason 			      struct extent_buffer *dst_buf,
375f39d397SChris Mason 			      struct extent_buffer *src_buf);
38afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
39afe5fea7STsutomu Itoh 		    int level, int slot);
40d97e63b6SChris Mason 
41af024ed2SJohannes Thumshirn static const struct btrfs_csums {
42af024ed2SJohannes Thumshirn 	u16		size;
4359a0fcdbSDavid Sterba 	const char	name[10];
4459a0fcdbSDavid Sterba 	const char	driver[12];
45af024ed2SJohannes Thumshirn } btrfs_csums[] = {
46af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
473951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
483831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
49352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
50352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
51af024ed2SJohannes Thumshirn };
52af024ed2SJohannes Thumshirn 
53af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
54af024ed2SJohannes Thumshirn {
55af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
56af024ed2SJohannes Thumshirn 	/*
57af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
58af024ed2SJohannes Thumshirn 	 */
59af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
60af024ed2SJohannes Thumshirn }
61af024ed2SJohannes Thumshirn 
62af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
63af024ed2SJohannes Thumshirn {
64af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
65af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
66af024ed2SJohannes Thumshirn }
67af024ed2SJohannes Thumshirn 
68b4e967beSDavid Sterba /*
69b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
70b4e967beSDavid Sterba  * name
71b4e967beSDavid Sterba  */
72b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
73b4e967beSDavid Sterba {
74b4e967beSDavid Sterba 	/* csum type is validated at mount time */
7559a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
7659a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
77b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
78b4e967beSDavid Sterba }
79b4e967beSDavid Sterba 
80604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
81f7cea56cSDavid Sterba {
82f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
83f7cea56cSDavid Sterba }
84f7cea56cSDavid Sterba 
852c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
862c90e5d6SChris Mason {
87e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
882c90e5d6SChris Mason }
892c90e5d6SChris Mason 
90d352ac68SChris Mason /* this also releases the path */
912c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
922c90e5d6SChris Mason {
93ff175d57SJesper Juhl 	if (!p)
94ff175d57SJesper Juhl 		return;
95b3b4aa74SDavid Sterba 	btrfs_release_path(p);
962c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
972c90e5d6SChris Mason }
982c90e5d6SChris Mason 
99d352ac68SChris Mason /*
100d352ac68SChris Mason  * path release drops references on the extent buffers in the path
101d352ac68SChris Mason  * and it drops any locks held by this path
102d352ac68SChris Mason  *
103d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
104d352ac68SChris Mason  */
105b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
106eb60ceacSChris Mason {
107eb60ceacSChris Mason 	int i;
108a2135011SChris Mason 
109234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1103f157a2fSChris Mason 		p->slots[i] = 0;
111eb60ceacSChris Mason 		if (!p->nodes[i])
112925baeddSChris Mason 			continue;
113925baeddSChris Mason 		if (p->locks[i]) {
114bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
115925baeddSChris Mason 			p->locks[i] = 0;
116925baeddSChris Mason 		}
1175f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1183f157a2fSChris Mason 		p->nodes[i] = NULL;
119eb60ceacSChris Mason 	}
120eb60ceacSChris Mason }
121eb60ceacSChris Mason 
122d352ac68SChris Mason /*
1238bb808c6SDavid Sterba  * We want the transaction abort to print stack trace only for errors where the
1248bb808c6SDavid Sterba  * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
1258bb808c6SDavid Sterba  * caused by external factors.
1268bb808c6SDavid Sterba  */
1278bb808c6SDavid Sterba bool __cold abort_should_print_stack(int errno)
1288bb808c6SDavid Sterba {
1298bb808c6SDavid Sterba 	switch (errno) {
1308bb808c6SDavid Sterba 	case -EIO:
1318bb808c6SDavid Sterba 	case -EROFS:
1328bb808c6SDavid Sterba 	case -ENOMEM:
1338bb808c6SDavid Sterba 		return false;
1348bb808c6SDavid Sterba 	}
1358bb808c6SDavid Sterba 	return true;
1368bb808c6SDavid Sterba }
1378bb808c6SDavid Sterba 
1388bb808c6SDavid Sterba /*
139d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
140d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
141d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
142d352ac68SChris Mason  * looping required.
143d352ac68SChris Mason  *
144d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
145d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
146d352ac68SChris Mason  * at any time because there are no locks held.
147d352ac68SChris Mason  */
148925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
149925baeddSChris Mason {
150925baeddSChris Mason 	struct extent_buffer *eb;
151240f62c8SChris Mason 
1523083ee2eSJosef Bacik 	while (1) {
153240f62c8SChris Mason 		rcu_read_lock();
154240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1553083ee2eSJosef Bacik 
1563083ee2eSJosef Bacik 		/*
1573083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
15801327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1593083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1603083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1613083ee2eSJosef Bacik 		 */
1623083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
163240f62c8SChris Mason 			rcu_read_unlock();
1643083ee2eSJosef Bacik 			break;
1653083ee2eSJosef Bacik 		}
1663083ee2eSJosef Bacik 		rcu_read_unlock();
1673083ee2eSJosef Bacik 		synchronize_rcu();
1683083ee2eSJosef Bacik 	}
169925baeddSChris Mason 	return eb;
170925baeddSChris Mason }
171925baeddSChris Mason 
17292a7cc42SQu Wenruo /*
17392a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
17492a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
17592a7cc42SQu Wenruo  * sure they get properly updated on disk.
176d352ac68SChris Mason  */
1770b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1780b86a832SChris Mason {
1790b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1800b246afaSJeff Mahoney 
181e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
182e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
183e7070be1SJosef Bacik 		return;
184e7070be1SJosef Bacik 
1850b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
186e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
187e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
1884fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
189e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
1900b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
191e7070be1SJosef Bacik 		else
192e7070be1SJosef Bacik 			list_move(&root->dirty_list,
1930b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
1940b86a832SChris Mason 	}
1950b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1960b86a832SChris Mason }
1970b86a832SChris Mason 
198d352ac68SChris Mason /*
199d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
200d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
201d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
202d352ac68SChris Mason  */
203be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
204be20aa9dSChris Mason 		      struct btrfs_root *root,
205be20aa9dSChris Mason 		      struct extent_buffer *buf,
206be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
207be20aa9dSChris Mason {
2080b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
209be20aa9dSChris Mason 	struct extent_buffer *cow;
210be20aa9dSChris Mason 	int ret = 0;
211be20aa9dSChris Mason 	int level;
2125d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
213be20aa9dSChris Mason 
21492a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2150b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
21692a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
21727cdeb70SMiao Xie 		trans->transid != root->last_trans);
218be20aa9dSChris Mason 
219be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2205d4f98a2SYan Zheng 	if (level == 0)
2215d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2225d4f98a2SYan Zheng 	else
2235d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
22431840ae1SZheng Yan 
2254d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
226cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
227cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
2285d4f98a2SYan Zheng 	if (IS_ERR(cow))
229be20aa9dSChris Mason 		return PTR_ERR(cow);
230be20aa9dSChris Mason 
23158e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
232be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
233be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2345d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2355d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2365d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2375d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2385d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2395d4f98a2SYan Zheng 	else
240be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
241be20aa9dSChris Mason 
242de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2432b82032cSYan Zheng 
244be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2455d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
246e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2475d4f98a2SYan Zheng 	else
248e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
249867ed321SJosef Bacik 	if (ret) {
25072c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
25172c9925fSFilipe Manana 		free_extent_buffer(cow);
252867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
253be20aa9dSChris Mason 		return ret;
254867ed321SJosef Bacik 	}
255be20aa9dSChris Mason 
256be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
257be20aa9dSChris Mason 	*cow_ret = cow;
258be20aa9dSChris Mason 	return 0;
259be20aa9dSChris Mason }
260be20aa9dSChris Mason 
261d352ac68SChris Mason /*
2625d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
2635d4f98a2SYan Zheng  */
2645d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
2655d4f98a2SYan Zheng 			      struct extent_buffer *buf)
2665d4f98a2SYan Zheng {
2675d4f98a2SYan Zheng 	/*
26892a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
26992a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
27092a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
2715d4f98a2SYan Zheng 	 */
27292a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2735d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
2745d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
2755d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
2765d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
2775d4f98a2SYan Zheng 		return 1;
278a79865c6SNikolay Borisov 
2795d4f98a2SYan Zheng 	return 0;
2805d4f98a2SYan Zheng }
2815d4f98a2SYan Zheng 
2825d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
2835d4f98a2SYan Zheng 				       struct btrfs_root *root,
2845d4f98a2SYan Zheng 				       struct extent_buffer *buf,
285f0486c68SYan, Zheng 				       struct extent_buffer *cow,
286f0486c68SYan, Zheng 				       int *last_ref)
2875d4f98a2SYan Zheng {
2880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2895d4f98a2SYan Zheng 	u64 refs;
2905d4f98a2SYan Zheng 	u64 owner;
2915d4f98a2SYan Zheng 	u64 flags;
2925d4f98a2SYan Zheng 	u64 new_flags = 0;
2935d4f98a2SYan Zheng 	int ret;
2945d4f98a2SYan Zheng 
2955d4f98a2SYan Zheng 	/*
2965d4f98a2SYan Zheng 	 * Backrefs update rules:
2975d4f98a2SYan Zheng 	 *
2985d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
2995d4f98a2SYan Zheng 	 * allocated by tree relocation.
3005d4f98a2SYan Zheng 	 *
3015d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
3025d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
3035d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
3045d4f98a2SYan Zheng 	 *
3055d4f98a2SYan Zheng 	 * If a tree block is been relocating
3065d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
3075d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
3085d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
3095d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
3105d4f98a2SYan Zheng 	 */
3115d4f98a2SYan Zheng 
3125d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
3132ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
3143173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
3153173a18fSJosef Bacik 					       &refs, &flags);
316be1a5564SMark Fasheh 		if (ret)
317be1a5564SMark Fasheh 			return ret;
318e5df9573SMark Fasheh 		if (refs == 0) {
319e5df9573SMark Fasheh 			ret = -EROFS;
3200b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
321e5df9573SMark Fasheh 			return ret;
322e5df9573SMark Fasheh 		}
3235d4f98a2SYan Zheng 	} else {
3245d4f98a2SYan Zheng 		refs = 1;
3255d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
3265d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
3275d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
3285d4f98a2SYan Zheng 		else
3295d4f98a2SYan Zheng 			flags = 0;
3305d4f98a2SYan Zheng 	}
3315d4f98a2SYan Zheng 
3325d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
3335d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
3345d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
3355d4f98a2SYan Zheng 
3365d4f98a2SYan Zheng 	if (refs > 1) {
3375d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
3385d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
3395d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
340e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
341692826b2SJeff Mahoney 			if (ret)
342692826b2SJeff Mahoney 				return ret;
3435d4f98a2SYan Zheng 
3445d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3455d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
346e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
347692826b2SJeff Mahoney 				if (ret)
348692826b2SJeff Mahoney 					return ret;
349e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
350692826b2SJeff Mahoney 				if (ret)
351692826b2SJeff Mahoney 					return ret;
3525d4f98a2SYan Zheng 			}
3535d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
3545d4f98a2SYan Zheng 		} else {
3555d4f98a2SYan Zheng 
3565d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3575d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
358e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3595d4f98a2SYan Zheng 			else
360e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
361692826b2SJeff Mahoney 			if (ret)
362692826b2SJeff Mahoney 				return ret;
3635d4f98a2SYan Zheng 		}
3645d4f98a2SYan Zheng 		if (new_flags != 0) {
365b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
366b1c79e09SJosef Bacik 
36742c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
3682fe6a5a1SDavid Sterba 							  new_flags, level);
369be1a5564SMark Fasheh 			if (ret)
370be1a5564SMark Fasheh 				return ret;
3715d4f98a2SYan Zheng 		}
3725d4f98a2SYan Zheng 	} else {
3735d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
3745d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3755d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
376e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3775d4f98a2SYan Zheng 			else
378e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
379692826b2SJeff Mahoney 			if (ret)
380692826b2SJeff Mahoney 				return ret;
381e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
382692826b2SJeff Mahoney 			if (ret)
383692826b2SJeff Mahoney 				return ret;
3845d4f98a2SYan Zheng 		}
3856a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
386f0486c68SYan, Zheng 		*last_ref = 1;
3875d4f98a2SYan Zheng 	}
3885d4f98a2SYan Zheng 	return 0;
3895d4f98a2SYan Zheng }
3905d4f98a2SYan Zheng 
3915d4f98a2SYan Zheng /*
392d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
393d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
394d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
395d397712bSChris Mason  * dirty again.
396d352ac68SChris Mason  *
397d352ac68SChris Mason  * search_start -- an allocation hint for the new block
398d352ac68SChris Mason  *
399d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
400d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
401d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
402d352ac68SChris Mason  */
403d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
4045f39d397SChris Mason 			     struct btrfs_root *root,
4055f39d397SChris Mason 			     struct extent_buffer *buf,
4065f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
4075f39d397SChris Mason 			     struct extent_buffer **cow_ret,
4089631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
4099631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
4106702ed49SChris Mason {
4110b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4125d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
4135f39d397SChris Mason 	struct extent_buffer *cow;
414be1a5564SMark Fasheh 	int level, ret;
415f0486c68SYan, Zheng 	int last_ref = 0;
416925baeddSChris Mason 	int unlock_orig = 0;
4170f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
4186702ed49SChris Mason 
419925baeddSChris Mason 	if (*cow_ret == buf)
420925baeddSChris Mason 		unlock_orig = 1;
421925baeddSChris Mason 
42249d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
423925baeddSChris Mason 
42492a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
4250b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
42692a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
42727cdeb70SMiao Xie 		trans->transid != root->last_trans);
4285f39d397SChris Mason 
4297bb86316SChris Mason 	level = btrfs_header_level(buf);
43031840ae1SZheng Yan 
4315d4f98a2SYan Zheng 	if (level == 0)
4325d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
4335d4f98a2SYan Zheng 	else
4345d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
4355d4f98a2SYan Zheng 
4360f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
4375d4f98a2SYan Zheng 		parent_start = parent->start;
4385d4f98a2SYan Zheng 
43979bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
44079bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
44179bd3712SFilipe Manana 				     search_start, empty_size, nest);
4426702ed49SChris Mason 	if (IS_ERR(cow))
4436702ed49SChris Mason 		return PTR_ERR(cow);
4446702ed49SChris Mason 
445b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
446b4ce94deSChris Mason 
44758e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
448db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
4495f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
4505d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
4515d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
4525d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
4535d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
4545d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
4555d4f98a2SYan Zheng 	else
4565f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
4576702ed49SChris Mason 
458de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
4592b82032cSYan Zheng 
460be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
461b68dc2a9SMark Fasheh 	if (ret) {
462572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
463572c83acSJosef Bacik 		free_extent_buffer(cow);
46466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
465b68dc2a9SMark Fasheh 		return ret;
466b68dc2a9SMark Fasheh 	}
4671a40e23bSZheng Yan 
46892a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
46983d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
47093314e3bSZhaolei 		if (ret) {
471572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
472572c83acSJosef Bacik 			free_extent_buffer(cow);
47366642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
47483d4cfd4SJosef Bacik 			return ret;
47583d4cfd4SJosef Bacik 		}
47693314e3bSZhaolei 	}
4773fd0a558SYan, Zheng 
4786702ed49SChris Mason 	if (buf == root->node) {
479925baeddSChris Mason 		WARN_ON(parent && parent != buf);
4805d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4815d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4825d4f98a2SYan Zheng 			parent_start = buf->start;
483925baeddSChris Mason 
48467439dadSDavid Sterba 		atomic_inc(&cow->refs);
485406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
486d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
487240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
488925baeddSChris Mason 
4897a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
4907a163608SFilipe Manana 				      parent_start, last_ref);
4915f39d397SChris Mason 		free_extent_buffer(buf);
4920b86a832SChris Mason 		add_root_to_dirty_list(root);
4936702ed49SChris Mason 	} else {
4945d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
495f3a84ccdSFilipe Manana 		btrfs_tree_mod_log_insert_key(parent, parent_slot,
49633cff222SFilipe Manana 					      BTRFS_MOD_LOG_KEY_REPLACE);
4975f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
498db94535dSChris Mason 					cow->start);
49974493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
50074493f7aSChris Mason 					      trans->transid);
5016702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
5025de865eeSFilipe David Borba Manana 		if (last_ref) {
503f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
5045de865eeSFilipe David Borba Manana 			if (ret) {
505572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
506572c83acSJosef Bacik 				free_extent_buffer(cow);
50766642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
5085de865eeSFilipe David Borba Manana 				return ret;
5095de865eeSFilipe David Borba Manana 			}
5105de865eeSFilipe David Borba Manana 		}
5117a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
5127a163608SFilipe Manana 				      parent_start, last_ref);
5136702ed49SChris Mason 	}
514925baeddSChris Mason 	if (unlock_orig)
515925baeddSChris Mason 		btrfs_tree_unlock(buf);
5163083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
5176702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
5186702ed49SChris Mason 	*cow_ret = cow;
5196702ed49SChris Mason 	return 0;
5206702ed49SChris Mason }
5216702ed49SChris Mason 
5225d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
5235d4f98a2SYan Zheng 				   struct btrfs_root *root,
5245d4f98a2SYan Zheng 				   struct extent_buffer *buf)
5255d4f98a2SYan Zheng {
526f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
527faa2dbf0SJosef Bacik 		return 0;
528fccb84c9SDavid Sterba 
529d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
530d1980131SDavid Sterba 	smp_mb__before_atomic();
531f1ebcc74SLiu Bo 
532f1ebcc74SLiu Bo 	/*
533f1ebcc74SLiu Bo 	 * We do not need to cow a block if
534f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
535f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
536f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
537f1ebcc74SLiu Bo 	 *
538f1ebcc74SLiu Bo 	 * What is forced COW:
53901327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
54052042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
541f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
542f1ebcc74SLiu Bo 	 */
5435d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
5445d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
5455d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
546f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
54727cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
5485d4f98a2SYan Zheng 		return 0;
5495d4f98a2SYan Zheng 	return 1;
5505d4f98a2SYan Zheng }
5515d4f98a2SYan Zheng 
552d352ac68SChris Mason /*
553d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
55401327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
555d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
556d352ac68SChris Mason  */
557d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
5585f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
5595f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
5609631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
5619631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
56202217ed2SChris Mason {
5630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5646702ed49SChris Mason 	u64 search_start;
565f510cfecSChris Mason 	int ret;
566dc17ff8fSChris Mason 
56783354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
56883354f07SJosef Bacik 		btrfs_err(fs_info,
56983354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
57083354f07SJosef Bacik 
5710b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
57231b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
573c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
5740b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
57531b1a2bdSJulia Lawall 
5760b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
57731b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
5780b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
579dc17ff8fSChris Mason 
5805d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
58102217ed2SChris Mason 		*cow_ret = buf;
58202217ed2SChris Mason 		return 0;
58302217ed2SChris Mason 	}
584c487685dSChris Mason 
585ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
586b4ce94deSChris Mason 
587f616f5cdSQu Wenruo 	/*
588f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
589f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
590f616f5cdSQu Wenruo 	 *
591f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
592f616f5cdSQu Wenruo 	 */
593f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
594f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
5959631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
5961abe9b8aSliubo 
5971abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
5981abe9b8aSliubo 
599f510cfecSChris Mason 	return ret;
6002c90e5d6SChris Mason }
601f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
6026702ed49SChris Mason 
603d352ac68SChris Mason /*
604d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
605d352ac68SChris Mason  * node are actually close by
606d352ac68SChris Mason  */
6076b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
6086702ed49SChris Mason {
6096b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
6106702ed49SChris Mason 		return 1;
6116b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
6126702ed49SChris Mason 		return 1;
61302217ed2SChris Mason 	return 0;
61402217ed2SChris Mason }
61502217ed2SChris Mason 
616ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
617ce6ef5abSDavid Sterba 
618ce6ef5abSDavid Sterba /*
619ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
620ce6ef5abSDavid Sterba  * we can avoid the conversion.
621ce6ef5abSDavid Sterba  */
622ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
623ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
624ce6ef5abSDavid Sterba {
625ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
626ce6ef5abSDavid Sterba 
627ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
628ce6ef5abSDavid Sterba }
629ce6ef5abSDavid Sterba 
630ce6ef5abSDavid Sterba #else
631ce6ef5abSDavid Sterba 
632081e9573SChris Mason /*
633081e9573SChris Mason  * compare two keys in a memcmp fashion
634081e9573SChris Mason  */
635310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
636310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
637081e9573SChris Mason {
638081e9573SChris Mason 	struct btrfs_key k1;
639081e9573SChris Mason 
640081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
641081e9573SChris Mason 
64220736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
643081e9573SChris Mason }
644ce6ef5abSDavid Sterba #endif
645081e9573SChris Mason 
646f3465ca4SJosef Bacik /*
647f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
648f3465ca4SJosef Bacik  */
649e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
650f3465ca4SJosef Bacik {
651f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
652f3465ca4SJosef Bacik 		return 1;
653f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
654f3465ca4SJosef Bacik 		return -1;
655f3465ca4SJosef Bacik 	if (k1->type > k2->type)
656f3465ca4SJosef Bacik 		return 1;
657f3465ca4SJosef Bacik 	if (k1->type < k2->type)
658f3465ca4SJosef Bacik 		return -1;
659f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
660f3465ca4SJosef Bacik 		return 1;
661f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
662f3465ca4SJosef Bacik 		return -1;
663f3465ca4SJosef Bacik 	return 0;
664f3465ca4SJosef Bacik }
665081e9573SChris Mason 
666d352ac68SChris Mason /*
667d352ac68SChris Mason  * this is used by the defrag code to go through all the
668d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
669d352ac68SChris Mason  * disk order is close to key order
670d352ac68SChris Mason  */
6716702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
6725f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
673de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
674a6b6e75eSChris Mason 		       struct btrfs_key *progress)
6756702ed49SChris Mason {
6760b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6776b80053dSChris Mason 	struct extent_buffer *cur;
6786702ed49SChris Mason 	u64 blocknr;
679e9d0b13bSChris Mason 	u64 search_start = *last_ret;
680e9d0b13bSChris Mason 	u64 last_block = 0;
6816702ed49SChris Mason 	u64 other;
6826702ed49SChris Mason 	u32 parent_nritems;
6836702ed49SChris Mason 	int end_slot;
6846702ed49SChris Mason 	int i;
6856702ed49SChris Mason 	int err = 0;
6866b80053dSChris Mason 	u32 blocksize;
687081e9573SChris Mason 	int progress_passed = 0;
688081e9573SChris Mason 	struct btrfs_disk_key disk_key;
6896702ed49SChris Mason 
6900b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
6910b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
69286479a04SChris Mason 
6936b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
6940b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
6955dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
6966702ed49SChris Mason 
6975dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
6986702ed49SChris Mason 		return 0;
6996702ed49SChris Mason 
7005dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
7016702ed49SChris Mason 		int close = 1;
702a6b6e75eSChris Mason 
703081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
704081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
705081e9573SChris Mason 			continue;
706081e9573SChris Mason 
707081e9573SChris Mason 		progress_passed = 1;
7086b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
709e9d0b13bSChris Mason 		if (last_block == 0)
710e9d0b13bSChris Mason 			last_block = blocknr;
7115708b959SChris Mason 
7126702ed49SChris Mason 		if (i > 0) {
7136b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
7146b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
7156702ed49SChris Mason 		}
7165dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
7176b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
7186b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
7196702ed49SChris Mason 		}
720e9d0b13bSChris Mason 		if (close) {
721e9d0b13bSChris Mason 			last_block = blocknr;
7226702ed49SChris Mason 			continue;
723e9d0b13bSChris Mason 		}
7246702ed49SChris Mason 
725206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
726206983b7SJosef Bacik 		if (IS_ERR(cur))
72764c043deSLiu Bo 			return PTR_ERR(cur);
728e9d0b13bSChris Mason 		if (search_start == 0)
7296b80053dSChris Mason 			search_start = last_block;
730e9d0b13bSChris Mason 
731e7a84565SChris Mason 		btrfs_tree_lock(cur);
7326b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
733e7a84565SChris Mason 					&cur, search_start,
7346b80053dSChris Mason 					min(16 * blocksize,
7359631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
7369631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
737252c38f0SYan 		if (err) {
738e7a84565SChris Mason 			btrfs_tree_unlock(cur);
7396b80053dSChris Mason 			free_extent_buffer(cur);
7406702ed49SChris Mason 			break;
741252c38f0SYan 		}
742e7a84565SChris Mason 		search_start = cur->start;
743e7a84565SChris Mason 		last_block = cur->start;
744f2183bdeSChris Mason 		*last_ret = search_start;
745e7a84565SChris Mason 		btrfs_tree_unlock(cur);
746e7a84565SChris Mason 		free_extent_buffer(cur);
7476702ed49SChris Mason 	}
7486702ed49SChris Mason 	return err;
7496702ed49SChris Mason }
7506702ed49SChris Mason 
75174123bd7SChris Mason /*
752fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
7535f39d397SChris Mason  *
754fb81212cSFilipe Manana  * The lower boundary for the search is specified by the slot number @low. Use a
755fb81212cSFilipe Manana  * value of 0 to search over the whole extent buffer.
75674123bd7SChris Mason  *
757fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
758fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
759fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
760fb81212cSFilipe Manana  *
761fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
762fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
76374123bd7SChris Mason  */
764fb81212cSFilipe Manana static noinline int generic_bin_search(struct extent_buffer *eb, int low,
76567d5e289SMarcos Paulo de Souza 				       const struct btrfs_key *key, int *slot)
766be0e5c09SChris Mason {
767fb81212cSFilipe Manana 	unsigned long p;
768fb81212cSFilipe Manana 	int item_size;
76967d5e289SMarcos Paulo de Souza 	int high = btrfs_header_nritems(eb);
770be0e5c09SChris Mason 	int ret;
7715cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
772be0e5c09SChris Mason 
7735e24e9afSLiu Bo 	if (low > high) {
7745e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
7755e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
7765e24e9afSLiu Bo 			  __func__, low, high, eb->start,
7775e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
7785e24e9afSLiu Bo 		return -EINVAL;
7795e24e9afSLiu Bo 	}
7805e24e9afSLiu Bo 
781fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
782fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
783fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
784fb81212cSFilipe Manana 	} else {
785fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
786fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
787fb81212cSFilipe Manana 	}
788fb81212cSFilipe Manana 
789be0e5c09SChris Mason 	while (low < high) {
7905cd17f34SDavid Sterba 		unsigned long oip;
7915cd17f34SDavid Sterba 		unsigned long offset;
7925cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
7935cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
7945cd17f34SDavid Sterba 		int mid;
7955cd17f34SDavid Sterba 
796be0e5c09SChris Mason 		mid = (low + high) / 2;
7975f39d397SChris Mason 		offset = p + mid * item_size;
7985cd17f34SDavid Sterba 		oip = offset_in_page(offset);
7995f39d397SChris Mason 
8005cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
801884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
8025cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
803934d375bSChris Mason 
804884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
8055cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
8065cd17f34SDavid Sterba 		} else {
8075cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
8085f39d397SChris Mason 			tmp = &unaligned;
809479965d6SChris Mason 		}
810479965d6SChris Mason 
811be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
812be0e5c09SChris Mason 
813be0e5c09SChris Mason 		if (ret < 0)
814be0e5c09SChris Mason 			low = mid + 1;
815be0e5c09SChris Mason 		else if (ret > 0)
816be0e5c09SChris Mason 			high = mid;
817be0e5c09SChris Mason 		else {
818be0e5c09SChris Mason 			*slot = mid;
819be0e5c09SChris Mason 			return 0;
820be0e5c09SChris Mason 		}
821be0e5c09SChris Mason 	}
822be0e5c09SChris Mason 	*slot = low;
823be0e5c09SChris Mason 	return 1;
824be0e5c09SChris Mason }
825be0e5c09SChris Mason 
82697571fd0SChris Mason /*
827fb81212cSFilipe Manana  * Simple binary search on an extent buffer. Works for both leaves and nodes, and
828fb81212cSFilipe Manana  * always searches over the whole range of keys (slot 0 to slot 'nritems - 1').
82997571fd0SChris Mason  */
830a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
831e3b83361SQu Wenruo 		     int *slot)
832be0e5c09SChris Mason {
833fb81212cSFilipe Manana 	return generic_bin_search(eb, 0, key, slot);
834be0e5c09SChris Mason }
835be0e5c09SChris Mason 
836f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
837f0486c68SYan, Zheng {
838f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
839f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
840f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
841f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
842f0486c68SYan, Zheng }
843f0486c68SYan, Zheng 
844f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
845f0486c68SYan, Zheng {
846f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
847f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
848f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
849f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
850f0486c68SYan, Zheng }
851f0486c68SYan, Zheng 
852d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
853d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
854d352ac68SChris Mason  */
8554b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
8564b231ae4SDavid Sterba 					   int slot)
857bb803951SChris Mason {
858ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
859416bc658SJosef Bacik 	struct extent_buffer *eb;
860581c1760SQu Wenruo 	struct btrfs_key first_key;
861416bc658SJosef Bacik 
862fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
863fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
864ca7a79adSChris Mason 
865ca7a79adSChris Mason 	BUG_ON(level == 0);
866ca7a79adSChris Mason 
867581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
868d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
8691b7ec85eSJosef Bacik 			     btrfs_header_owner(parent),
870581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
871581c1760SQu Wenruo 			     level - 1, &first_key);
8724eb150d6SQu Wenruo 	if (IS_ERR(eb))
8734eb150d6SQu Wenruo 		return eb;
8744eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
875416bc658SJosef Bacik 		free_extent_buffer(eb);
8764eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
877416bc658SJosef Bacik 	}
878416bc658SJosef Bacik 
879416bc658SJosef Bacik 	return eb;
880bb803951SChris Mason }
881bb803951SChris Mason 
882d352ac68SChris Mason /*
883d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
884d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
885d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
886d352ac68SChris Mason  */
887e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
88898ed5174SChris Mason 			 struct btrfs_root *root,
88998ed5174SChris Mason 			 struct btrfs_path *path, int level)
890bb803951SChris Mason {
8910b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8925f39d397SChris Mason 	struct extent_buffer *right = NULL;
8935f39d397SChris Mason 	struct extent_buffer *mid;
8945f39d397SChris Mason 	struct extent_buffer *left = NULL;
8955f39d397SChris Mason 	struct extent_buffer *parent = NULL;
896bb803951SChris Mason 	int ret = 0;
897bb803951SChris Mason 	int wret;
898bb803951SChris Mason 	int pslot;
899bb803951SChris Mason 	int orig_slot = path->slots[level];
90079f95c82SChris Mason 	u64 orig_ptr;
901bb803951SChris Mason 
90298e6b1ebSLiu Bo 	ASSERT(level > 0);
903bb803951SChris Mason 
9045f39d397SChris Mason 	mid = path->nodes[level];
905b4ce94deSChris Mason 
906ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
9077bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
9087bb86316SChris Mason 
9091d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
91079f95c82SChris Mason 
911a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
9125f39d397SChris Mason 		parent = path->nodes[level + 1];
913bb803951SChris Mason 		pslot = path->slots[level + 1];
914a05a9bb1SLi Zefan 	}
915bb803951SChris Mason 
91640689478SChris Mason 	/*
91740689478SChris Mason 	 * deal with the case where there is only one pointer in the root
91840689478SChris Mason 	 * by promoting the node below to a root
91940689478SChris Mason 	 */
9205f39d397SChris Mason 	if (!parent) {
9215f39d397SChris Mason 		struct extent_buffer *child;
922bb803951SChris Mason 
9235f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
924bb803951SChris Mason 			return 0;
925bb803951SChris Mason 
926bb803951SChris Mason 		/* promote the child to a root */
9274b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
928fb770ae4SLiu Bo 		if (IS_ERR(child)) {
929fb770ae4SLiu Bo 			ret = PTR_ERR(child);
9300b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
931305a26afSMark Fasheh 			goto enospc;
932305a26afSMark Fasheh 		}
933305a26afSMark Fasheh 
934925baeddSChris Mason 		btrfs_tree_lock(child);
9359631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
9369631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
937f0486c68SYan, Zheng 		if (ret) {
938f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
939f0486c68SYan, Zheng 			free_extent_buffer(child);
940f0486c68SYan, Zheng 			goto enospc;
941f0486c68SYan, Zheng 		}
9422f375ab9SYan 
943406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
944d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
945240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
946925baeddSChris Mason 
9470b86a832SChris Mason 		add_root_to_dirty_list(root);
948925baeddSChris Mason 		btrfs_tree_unlock(child);
949b4ce94deSChris Mason 
950925baeddSChris Mason 		path->locks[level] = 0;
951bb803951SChris Mason 		path->nodes[level] = NULL;
9526a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
953925baeddSChris Mason 		btrfs_tree_unlock(mid);
954bb803951SChris Mason 		/* once for the path */
9555f39d397SChris Mason 		free_extent_buffer(mid);
956f0486c68SYan, Zheng 
957f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
9587a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
959bb803951SChris Mason 		/* once for the root ptr */
9603083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
961f0486c68SYan, Zheng 		return 0;
962bb803951SChris Mason 	}
9635f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
9640b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
965bb803951SChris Mason 		return 0;
966bb803951SChris Mason 
9674b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
968fb770ae4SLiu Bo 	if (IS_ERR(left))
969fb770ae4SLiu Bo 		left = NULL;
970fb770ae4SLiu Bo 
9715f39d397SChris Mason 	if (left) {
972bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
9735f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
9749631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
975bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
97654aa1f4dSChris Mason 		if (wret) {
97754aa1f4dSChris Mason 			ret = wret;
97854aa1f4dSChris Mason 			goto enospc;
97954aa1f4dSChris Mason 		}
9802cc58cf2SChris Mason 	}
981fb770ae4SLiu Bo 
9824b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
983fb770ae4SLiu Bo 	if (IS_ERR(right))
984fb770ae4SLiu Bo 		right = NULL;
985fb770ae4SLiu Bo 
9865f39d397SChris Mason 	if (right) {
987bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
9885f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
9899631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
990bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
9912cc58cf2SChris Mason 		if (wret) {
9922cc58cf2SChris Mason 			ret = wret;
9932cc58cf2SChris Mason 			goto enospc;
9942cc58cf2SChris Mason 		}
9952cc58cf2SChris Mason 	}
9962cc58cf2SChris Mason 
9972cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
9985f39d397SChris Mason 	if (left) {
9995f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
1000d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
100179f95c82SChris Mason 		if (wret < 0)
100279f95c82SChris Mason 			ret = wret;
1003bb803951SChris Mason 	}
100479f95c82SChris Mason 
100579f95c82SChris Mason 	/*
100679f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
100779f95c82SChris Mason 	 */
10085f39d397SChris Mason 	if (right) {
1009d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
101054aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
101179f95c82SChris Mason 			ret = wret;
10125f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
10136a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1014925baeddSChris Mason 			btrfs_tree_unlock(right);
1015afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1016f0486c68SYan, Zheng 			root_sub_used(root, right->len);
10177a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
10187a163608SFilipe Manana 					      0, 1);
10193083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1020f0486c68SYan, Zheng 			right = NULL;
1021bb803951SChris Mason 		} else {
10225f39d397SChris Mason 			struct btrfs_disk_key right_key;
10235f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1024f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
102533cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
10260e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
10275f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
10285f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1029bb803951SChris Mason 		}
1030bb803951SChris Mason 	}
10315f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
103279f95c82SChris Mason 		/*
103379f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
103479f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
103579f95c82SChris Mason 		 * could try to delete the only pointer in this node.
103679f95c82SChris Mason 		 * So, pull some keys from the left.
103779f95c82SChris Mason 		 * There has to be a left pointer at this point because
103879f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
103979f95c82SChris Mason 		 * right
104079f95c82SChris Mason 		 */
1041305a26afSMark Fasheh 		if (!left) {
1042305a26afSMark Fasheh 			ret = -EROFS;
10430b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1044305a26afSMark Fasheh 			goto enospc;
1045305a26afSMark Fasheh 		}
104655d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
104754aa1f4dSChris Mason 		if (wret < 0) {
104879f95c82SChris Mason 			ret = wret;
104954aa1f4dSChris Mason 			goto enospc;
105054aa1f4dSChris Mason 		}
1051bce4eae9SChris Mason 		if (wret == 1) {
1052d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1053bce4eae9SChris Mason 			if (wret < 0)
1054bce4eae9SChris Mason 				ret = wret;
1055bce4eae9SChris Mason 		}
105679f95c82SChris Mason 		BUG_ON(wret == 1);
105779f95c82SChris Mason 	}
10585f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
10596a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1060925baeddSChris Mason 		btrfs_tree_unlock(mid);
1061afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1062f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10637a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
10643083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1065f0486c68SYan, Zheng 		mid = NULL;
106679f95c82SChris Mason 	} else {
106779f95c82SChris Mason 		/* update the parent key to reflect our changes */
10685f39d397SChris Mason 		struct btrfs_disk_key mid_key;
10695f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1070f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
107133cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
10720e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
10735f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
10745f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
107579f95c82SChris Mason 	}
1076bb803951SChris Mason 
107779f95c82SChris Mason 	/* update the path */
10785f39d397SChris Mason 	if (left) {
10795f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
108067439dadSDavid Sterba 			atomic_inc(&left->refs);
1081925baeddSChris Mason 			/* left was locked after cow */
10825f39d397SChris Mason 			path->nodes[level] = left;
1083bb803951SChris Mason 			path->slots[level + 1] -= 1;
1084bb803951SChris Mason 			path->slots[level] = orig_slot;
1085925baeddSChris Mason 			if (mid) {
1086925baeddSChris Mason 				btrfs_tree_unlock(mid);
10875f39d397SChris Mason 				free_extent_buffer(mid);
1088925baeddSChris Mason 			}
1089bb803951SChris Mason 		} else {
10905f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1091bb803951SChris Mason 			path->slots[level] = orig_slot;
1092bb803951SChris Mason 		}
1093bb803951SChris Mason 	}
109479f95c82SChris Mason 	/* double check we haven't messed things up */
1095e20d96d6SChris Mason 	if (orig_ptr !=
10965f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
109779f95c82SChris Mason 		BUG();
109854aa1f4dSChris Mason enospc:
1099925baeddSChris Mason 	if (right) {
1100925baeddSChris Mason 		btrfs_tree_unlock(right);
11015f39d397SChris Mason 		free_extent_buffer(right);
1102925baeddSChris Mason 	}
1103925baeddSChris Mason 	if (left) {
1104925baeddSChris Mason 		if (path->nodes[level] != left)
1105925baeddSChris Mason 			btrfs_tree_unlock(left);
11065f39d397SChris Mason 		free_extent_buffer(left);
1107925baeddSChris Mason 	}
1108bb803951SChris Mason 	return ret;
1109bb803951SChris Mason }
1110bb803951SChris Mason 
1111d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1112d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1113d352ac68SChris Mason  * have to be pessimistic.
1114d352ac68SChris Mason  */
1115d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1116e66f709bSChris Mason 					  struct btrfs_root *root,
1117e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1118e66f709bSChris Mason {
11190b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11205f39d397SChris Mason 	struct extent_buffer *right = NULL;
11215f39d397SChris Mason 	struct extent_buffer *mid;
11225f39d397SChris Mason 	struct extent_buffer *left = NULL;
11235f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1124e66f709bSChris Mason 	int ret = 0;
1125e66f709bSChris Mason 	int wret;
1126e66f709bSChris Mason 	int pslot;
1127e66f709bSChris Mason 	int orig_slot = path->slots[level];
1128e66f709bSChris Mason 
1129e66f709bSChris Mason 	if (level == 0)
1130e66f709bSChris Mason 		return 1;
1131e66f709bSChris Mason 
11325f39d397SChris Mason 	mid = path->nodes[level];
11337bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1134e66f709bSChris Mason 
1135a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
11365f39d397SChris Mason 		parent = path->nodes[level + 1];
1137e66f709bSChris Mason 		pslot = path->slots[level + 1];
1138a05a9bb1SLi Zefan 	}
1139e66f709bSChris Mason 
11405f39d397SChris Mason 	if (!parent)
1141e66f709bSChris Mason 		return 1;
1142e66f709bSChris Mason 
11434b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1144fb770ae4SLiu Bo 	if (IS_ERR(left))
1145fb770ae4SLiu Bo 		left = NULL;
1146e66f709bSChris Mason 
1147e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
11485f39d397SChris Mason 	if (left) {
1149e66f709bSChris Mason 		u32 left_nr;
1150925baeddSChris Mason 
1151bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1152b4ce94deSChris Mason 
11535f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
11540b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
115533ade1f8SChris Mason 			wret = 1;
115633ade1f8SChris Mason 		} else {
11575f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
11589631e4ccSJosef Bacik 					      pslot - 1, &left,
1159bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
116054aa1f4dSChris Mason 			if (ret)
116154aa1f4dSChris Mason 				wret = 1;
116254aa1f4dSChris Mason 			else {
1163d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
116454aa1f4dSChris Mason 			}
116533ade1f8SChris Mason 		}
1166e66f709bSChris Mason 		if (wret < 0)
1167e66f709bSChris Mason 			ret = wret;
1168e66f709bSChris Mason 		if (wret == 0) {
11695f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1170e66f709bSChris Mason 			orig_slot += left_nr;
11715f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1172f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
117333cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
11740e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11755f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
11765f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
11775f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
11785f39d397SChris Mason 				path->nodes[level] = left;
1179e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1180e66f709bSChris Mason 				path->slots[level] = orig_slot;
1181925baeddSChris Mason 				btrfs_tree_unlock(mid);
11825f39d397SChris Mason 				free_extent_buffer(mid);
1183e66f709bSChris Mason 			} else {
1184e66f709bSChris Mason 				orig_slot -=
11855f39d397SChris Mason 					btrfs_header_nritems(left);
1186e66f709bSChris Mason 				path->slots[level] = orig_slot;
1187925baeddSChris Mason 				btrfs_tree_unlock(left);
11885f39d397SChris Mason 				free_extent_buffer(left);
1189e66f709bSChris Mason 			}
1190e66f709bSChris Mason 			return 0;
1191e66f709bSChris Mason 		}
1192925baeddSChris Mason 		btrfs_tree_unlock(left);
11935f39d397SChris Mason 		free_extent_buffer(left);
1194e66f709bSChris Mason 	}
11954b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1196fb770ae4SLiu Bo 	if (IS_ERR(right))
1197fb770ae4SLiu Bo 		right = NULL;
1198e66f709bSChris Mason 
1199e66f709bSChris Mason 	/*
1200e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1201e66f709bSChris Mason 	 */
12025f39d397SChris Mason 	if (right) {
120333ade1f8SChris Mason 		u32 right_nr;
1204b4ce94deSChris Mason 
1205bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1206b4ce94deSChris Mason 
12075f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
12080b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
120933ade1f8SChris Mason 			wret = 1;
121033ade1f8SChris Mason 		} else {
12115f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
12125f39d397SChris Mason 					      parent, pslot + 1,
1213bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
121454aa1f4dSChris Mason 			if (ret)
121554aa1f4dSChris Mason 				wret = 1;
121654aa1f4dSChris Mason 			else {
121755d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
121833ade1f8SChris Mason 			}
121954aa1f4dSChris Mason 		}
1220e66f709bSChris Mason 		if (wret < 0)
1221e66f709bSChris Mason 			ret = wret;
1222e66f709bSChris Mason 		if (wret == 0) {
12235f39d397SChris Mason 			struct btrfs_disk_key disk_key;
12245f39d397SChris Mason 
12255f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1226f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
122733cff222SFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE);
12280e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
12295f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
12305f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12315f39d397SChris Mason 
12325f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
12335f39d397SChris Mason 				path->nodes[level] = right;
1234e66f709bSChris Mason 				path->slots[level + 1] += 1;
1235e66f709bSChris Mason 				path->slots[level] = orig_slot -
12365f39d397SChris Mason 					btrfs_header_nritems(mid);
1237925baeddSChris Mason 				btrfs_tree_unlock(mid);
12385f39d397SChris Mason 				free_extent_buffer(mid);
1239e66f709bSChris Mason 			} else {
1240925baeddSChris Mason 				btrfs_tree_unlock(right);
12415f39d397SChris Mason 				free_extent_buffer(right);
1242e66f709bSChris Mason 			}
1243e66f709bSChris Mason 			return 0;
1244e66f709bSChris Mason 		}
1245925baeddSChris Mason 		btrfs_tree_unlock(right);
12465f39d397SChris Mason 		free_extent_buffer(right);
1247e66f709bSChris Mason 	}
1248e66f709bSChris Mason 	return 1;
1249e66f709bSChris Mason }
1250e66f709bSChris Mason 
125174123bd7SChris Mason /*
1252d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1253d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
12543c69faecSChris Mason  */
12552ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1256e02119d5SChris Mason 			     struct btrfs_path *path,
125701f46658SChris Mason 			     int level, int slot, u64 objectid)
12583c69faecSChris Mason {
12595f39d397SChris Mason 	struct extent_buffer *node;
126001f46658SChris Mason 	struct btrfs_disk_key disk_key;
12613c69faecSChris Mason 	u32 nritems;
12623c69faecSChris Mason 	u64 search;
1263a7175319SChris Mason 	u64 target;
12646b80053dSChris Mason 	u64 nread = 0;
1265ace75066SFilipe Manana 	u64 nread_max;
12666b80053dSChris Mason 	u32 nr;
12676b80053dSChris Mason 	u32 blocksize;
12686b80053dSChris Mason 	u32 nscan = 0;
1269db94535dSChris Mason 
1270ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
12713c69faecSChris Mason 		return;
12723c69faecSChris Mason 
12736702ed49SChris Mason 	if (!path->nodes[level])
12746702ed49SChris Mason 		return;
12756702ed49SChris Mason 
12765f39d397SChris Mason 	node = path->nodes[level];
1277925baeddSChris Mason 
1278ace75066SFilipe Manana 	/*
1279ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1280ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1281ace75066SFilipe Manana 	 * much IO at once (possibly random).
1282ace75066SFilipe Manana 	 */
1283ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1284ace75066SFilipe Manana 		if (level > 1)
1285ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1286ace75066SFilipe Manana 		else
1287ace75066SFilipe Manana 			nread_max = SZ_128K;
1288ace75066SFilipe Manana 	} else {
1289ace75066SFilipe Manana 		nread_max = SZ_64K;
1290ace75066SFilipe Manana 	}
1291ace75066SFilipe Manana 
12923c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
12930b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1294069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1295069a2e37SFilipe Manana 		struct extent_buffer *eb;
1296069a2e37SFilipe Manana 
12970b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
12985f39d397SChris Mason 		if (eb) {
12995f39d397SChris Mason 			free_extent_buffer(eb);
13003c69faecSChris Mason 			return;
13013c69faecSChris Mason 		}
1302069a2e37SFilipe Manana 	}
13033c69faecSChris Mason 
1304a7175319SChris Mason 	target = search;
13056b80053dSChris Mason 
13065f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
13076b80053dSChris Mason 	nr = slot;
130825b8b936SJosef Bacik 
13093c69faecSChris Mason 	while (1) {
1310e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
13116b80053dSChris Mason 			if (nr == 0)
13123c69faecSChris Mason 				break;
13136b80053dSChris Mason 			nr--;
1314ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1315ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
13166b80053dSChris Mason 			nr++;
13176b80053dSChris Mason 			if (nr >= nritems)
13186b80053dSChris Mason 				break;
13193c69faecSChris Mason 		}
1320e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
132101f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
132201f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
132301f46658SChris Mason 				break;
132401f46658SChris Mason 		}
13256b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1326ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1327ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1328a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1329bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
13306b80053dSChris Mason 			nread += blocksize;
13313c69faecSChris Mason 		}
13326b80053dSChris Mason 		nscan++;
1333ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
13346b80053dSChris Mason 			break;
13353c69faecSChris Mason 	}
13363c69faecSChris Mason }
1337925baeddSChris Mason 
1338bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1339b4ce94deSChris Mason {
1340bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1341b4ce94deSChris Mason 	int slot;
1342b4ce94deSChris Mason 	int nritems;
1343b4ce94deSChris Mason 
13448c594ea8SChris Mason 	parent = path->nodes[level + 1];
1345b4ce94deSChris Mason 	if (!parent)
13460b08851fSJosef Bacik 		return;
1347b4ce94deSChris Mason 
1348b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
13498c594ea8SChris Mason 	slot = path->slots[level + 1];
1350b4ce94deSChris Mason 
1351bfb484d9SJosef Bacik 	if (slot > 0)
1352bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1353bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1354bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1355b4ce94deSChris Mason }
1356b4ce94deSChris Mason 
1357b4ce94deSChris Mason 
1358b4ce94deSChris Mason /*
1359d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1360d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1361d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1362d397712bSChris Mason  * tree.
1363d352ac68SChris Mason  *
1364d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1365d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1366d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1367d352ac68SChris Mason  *
1368d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1369d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1370d352ac68SChris Mason  */
1371e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1372f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1373f7c79f30SChris Mason 			       int *write_lock_level)
1374925baeddSChris Mason {
1375925baeddSChris Mason 	int i;
1376925baeddSChris Mason 	int skip_level = level;
1377c1227996SNikolay Borisov 	bool check_skip = true;
1378925baeddSChris Mason 
1379925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1380925baeddSChris Mason 		if (!path->nodes[i])
1381925baeddSChris Mason 			break;
1382925baeddSChris Mason 		if (!path->locks[i])
1383925baeddSChris Mason 			break;
1384c1227996SNikolay Borisov 
1385c1227996SNikolay Borisov 		if (check_skip) {
1386c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1387925baeddSChris Mason 				skip_level = i + 1;
1388925baeddSChris Mason 				continue;
1389925baeddSChris Mason 			}
1390c1227996SNikolay Borisov 
1391c1227996SNikolay Borisov 			if (path->keep_locks) {
1392925baeddSChris Mason 				u32 nritems;
1393c1227996SNikolay Borisov 
1394c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1395051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1396925baeddSChris Mason 					skip_level = i + 1;
1397925baeddSChris Mason 					continue;
1398925baeddSChris Mason 				}
1399925baeddSChris Mason 			}
1400c1227996SNikolay Borisov 		}
1401051e1b9fSChris Mason 
1402d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1403c1227996SNikolay Borisov 			check_skip = false;
1404c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1405925baeddSChris Mason 			path->locks[i] = 0;
1406f7c79f30SChris Mason 			if (write_lock_level &&
1407f7c79f30SChris Mason 			    i > min_write_lock_level &&
1408f7c79f30SChris Mason 			    i <= *write_lock_level) {
1409f7c79f30SChris Mason 				*write_lock_level = i - 1;
1410f7c79f30SChris Mason 			}
1411925baeddSChris Mason 		}
1412925baeddSChris Mason 	}
1413925baeddSChris Mason }
1414925baeddSChris Mason 
14153c69faecSChris Mason /*
1416376a21d7SFilipe Manana  * Helper function for btrfs_search_slot() and other functions that do a search
1417376a21d7SFilipe Manana  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1418376a21d7SFilipe Manana  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1419376a21d7SFilipe Manana  * its pages from disk.
1420c8c42864SChris Mason  *
1421376a21d7SFilipe Manana  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1422376a21d7SFilipe Manana  * whole btree search, starting again from the current root node.
1423c8c42864SChris Mason  */
1424c8c42864SChris Mason static int
1425d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1426c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1427cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1428c8c42864SChris Mason {
14290b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1430c8c42864SChris Mason 	u64 blocknr;
1431c8c42864SChris Mason 	u64 gen;
1432c8c42864SChris Mason 	struct extent_buffer *tmp;
1433581c1760SQu Wenruo 	struct btrfs_key first_key;
143476a05b35SChris Mason 	int ret;
1435581c1760SQu Wenruo 	int parent_level;
1436b246666eSFilipe Manana 	bool unlock_up;
1437c8c42864SChris Mason 
1438b246666eSFilipe Manana 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1439213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1440213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1441213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1442213ff4b7SNikolay Borisov 	btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
1443c8c42864SChris Mason 
1444b246666eSFilipe Manana 	/*
1445b246666eSFilipe Manana 	 * If we need to read an extent buffer from disk and we are holding locks
1446b246666eSFilipe Manana 	 * on upper level nodes, we unlock all the upper nodes before reading the
1447b246666eSFilipe Manana 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1448b246666eSFilipe Manana 	 * restart the search. We don't release the lock on the current level
1449b246666eSFilipe Manana 	 * because we need to walk this node to figure out which blocks to read.
1450b246666eSFilipe Manana 	 */
14510b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1452cb44921aSChris Mason 	if (tmp) {
1453ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1454ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1455ace75066SFilipe Manana 
1456b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1457b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1458448de471SQu Wenruo 			/*
1459448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1460448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1461448de471SQu Wenruo 			 * parents (shared tree blocks).
1462448de471SQu Wenruo 			 */
1463e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1464448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
1465448de471SQu Wenruo 				free_extent_buffer(tmp);
1466448de471SQu Wenruo 				return -EUCLEAN;
1467448de471SQu Wenruo 			}
1468c8c42864SChris Mason 			*eb_ret = tmp;
1469c8c42864SChris Mason 			return 0;
1470c8c42864SChris Mason 		}
1471bdf7c00eSJosef Bacik 
1472857bc13fSJosef Bacik 		if (p->nowait) {
1473857bc13fSJosef Bacik 			free_extent_buffer(tmp);
1474857bc13fSJosef Bacik 			return -EAGAIN;
1475857bc13fSJosef Bacik 		}
1476857bc13fSJosef Bacik 
1477b246666eSFilipe Manana 		if (unlock_up)
1478b246666eSFilipe Manana 			btrfs_unlock_up_safe(p, level + 1);
1479b246666eSFilipe Manana 
1480b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
14816a2e9dc4SFilipe Manana 		ret = btrfs_read_extent_buffer(tmp, gen, parent_level - 1, &first_key);
14829a4ffa1bSQu Wenruo 		if (ret) {
1483cb44921aSChris Mason 			free_extent_buffer(tmp);
1484b3b4aa74SDavid Sterba 			btrfs_release_path(p);
1485cb44921aSChris Mason 			return -EIO;
1486cb44921aSChris Mason 		}
148788c602abSQu Wenruo 		if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
148888c602abSQu Wenruo 			free_extent_buffer(tmp);
148988c602abSQu Wenruo 			btrfs_release_path(p);
149088c602abSQu Wenruo 			return -EUCLEAN;
149188c602abSQu Wenruo 		}
1492b246666eSFilipe Manana 
1493b246666eSFilipe Manana 		if (unlock_up)
1494b246666eSFilipe Manana 			ret = -EAGAIN;
1495b246666eSFilipe Manana 
1496b246666eSFilipe Manana 		goto out;
1497857bc13fSJosef Bacik 	} else if (p->nowait) {
1498857bc13fSJosef Bacik 		return -EAGAIN;
14999a4ffa1bSQu Wenruo 	}
1500c8c42864SChris Mason 
1501b246666eSFilipe Manana 	if (unlock_up) {
15028c594ea8SChris Mason 		btrfs_unlock_up_safe(p, level + 1);
15034bb59055SFilipe Manana 		ret = -EAGAIN;
15044bb59055SFilipe Manana 	} else {
15054bb59055SFilipe Manana 		ret = 0;
15064bb59055SFilipe Manana 	}
15078c594ea8SChris Mason 
1508e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
15092ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1510c8c42864SChris Mason 
15111b7ec85eSJosef Bacik 	tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
15121b7ec85eSJosef Bacik 			      gen, parent_level - 1, &first_key);
15134eb150d6SQu Wenruo 	if (IS_ERR(tmp)) {
15144eb150d6SQu Wenruo 		btrfs_release_path(p);
15154eb150d6SQu Wenruo 		return PTR_ERR(tmp);
15164eb150d6SQu Wenruo 	}
151776a05b35SChris Mason 	/*
151876a05b35SChris Mason 	 * If the read above didn't mark this buffer up to date,
151976a05b35SChris Mason 	 * it will never end up being up to date.  Set ret to EIO now
152076a05b35SChris Mason 	 * and give up so that our caller doesn't loop forever
152176a05b35SChris Mason 	 * on our EAGAINs.
152276a05b35SChris Mason 	 */
1523e6a1d6fdSLiu Bo 	if (!extent_buffer_uptodate(tmp))
152476a05b35SChris Mason 		ret = -EIO;
152502a3307aSLiu Bo 
1526b246666eSFilipe Manana out:
15274bb59055SFilipe Manana 	if (ret == 0) {
15284bb59055SFilipe Manana 		*eb_ret = tmp;
15294bb59055SFilipe Manana 	} else {
15304bb59055SFilipe Manana 		free_extent_buffer(tmp);
153102a3307aSLiu Bo 		btrfs_release_path(p);
15324bb59055SFilipe Manana 	}
15334bb59055SFilipe Manana 
153476a05b35SChris Mason 	return ret;
1535c8c42864SChris Mason }
1536c8c42864SChris Mason 
1537c8c42864SChris Mason /*
1538c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1539c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1540c8c42864SChris Mason  * the ins_len.
1541c8c42864SChris Mason  *
1542c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1543c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1544c8c42864SChris Mason  * start over
1545c8c42864SChris Mason  */
1546c8c42864SChris Mason static int
1547c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1548c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1549bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1550bd681513SChris Mason 		       int *write_lock_level)
1551c8c42864SChris Mason {
15520b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
155395b982deSNikolay Borisov 	int ret = 0;
15540b246afaSJeff Mahoney 
1555c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
15560b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1557c8c42864SChris Mason 
1558bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1559bd681513SChris Mason 			*write_lock_level = level + 1;
1560bd681513SChris Mason 			btrfs_release_path(p);
156195b982deSNikolay Borisov 			return -EAGAIN;
1562bd681513SChris Mason 		}
1563bd681513SChris Mason 
1564bfb484d9SJosef Bacik 		reada_for_balance(p, level);
156595b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1566c8c42864SChris Mason 
1567c8c42864SChris Mason 		b = p->nodes[level];
1568c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
15690b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1570c8c42864SChris Mason 
1571bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1572bd681513SChris Mason 			*write_lock_level = level + 1;
1573bd681513SChris Mason 			btrfs_release_path(p);
157495b982deSNikolay Borisov 			return -EAGAIN;
1575bd681513SChris Mason 		}
1576bd681513SChris Mason 
1577bfb484d9SJosef Bacik 		reada_for_balance(p, level);
157895b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
157995b982deSNikolay Borisov 		if (ret)
158095b982deSNikolay Borisov 			return ret;
1581c8c42864SChris Mason 
1582c8c42864SChris Mason 		b = p->nodes[level];
1583c8c42864SChris Mason 		if (!b) {
1584b3b4aa74SDavid Sterba 			btrfs_release_path(p);
158595b982deSNikolay Borisov 			return -EAGAIN;
1586c8c42864SChris Mason 		}
1587c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1588c8c42864SChris Mason 	}
1589c8c42864SChris Mason 	return ret;
1590c8c42864SChris Mason }
1591c8c42864SChris Mason 
1592381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1593e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1594e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1595e33d5c3dSKelley Nielsen {
1596e33d5c3dSKelley Nielsen 	int ret;
1597e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1598e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1599381cf658SDavid Sterba 
1600381cf658SDavid Sterba 	ASSERT(path);
16011d4c08e0SDavid Sterba 	ASSERT(found_key);
1602e33d5c3dSKelley Nielsen 
1603e33d5c3dSKelley Nielsen 	key.type = key_type;
1604e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1605e33d5c3dSKelley Nielsen 	key.offset = ioff;
1606e33d5c3dSKelley Nielsen 
1607e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
16081d4c08e0SDavid Sterba 	if (ret < 0)
1609e33d5c3dSKelley Nielsen 		return ret;
1610e33d5c3dSKelley Nielsen 
1611e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1612e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1613e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1614e33d5c3dSKelley Nielsen 		if (ret)
1615e33d5c3dSKelley Nielsen 			return ret;
1616e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1617e33d5c3dSKelley Nielsen 	}
1618e33d5c3dSKelley Nielsen 
1619e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1620e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1621e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1622e33d5c3dSKelley Nielsen 		return 1;
1623e33d5c3dSKelley Nielsen 
1624e33d5c3dSKelley Nielsen 	return 0;
1625e33d5c3dSKelley Nielsen }
1626e33d5c3dSKelley Nielsen 
16271fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
16281fc28d8eSLiu Bo 							struct btrfs_path *p,
16291fc28d8eSLiu Bo 							int write_lock_level)
16301fc28d8eSLiu Bo {
16311fc28d8eSLiu Bo 	struct extent_buffer *b;
1632120de408SJosef Bacik 	int root_lock = 0;
16331fc28d8eSLiu Bo 	int level = 0;
16341fc28d8eSLiu Bo 
16351fc28d8eSLiu Bo 	if (p->search_commit_root) {
16361fc28d8eSLiu Bo 		b = root->commit_root;
163767439dadSDavid Sterba 		atomic_inc(&b->refs);
16381fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1639f9ddfd05SLiu Bo 		/*
1640f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1641f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1642f9ddfd05SLiu Bo 		 */
1643f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
16441fc28d8eSLiu Bo 
16451fc28d8eSLiu Bo 		goto out;
16461fc28d8eSLiu Bo 	}
16471fc28d8eSLiu Bo 
16481fc28d8eSLiu Bo 	if (p->skip_locking) {
16491fc28d8eSLiu Bo 		b = btrfs_root_node(root);
16501fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16511fc28d8eSLiu Bo 		goto out;
16521fc28d8eSLiu Bo 	}
16531fc28d8eSLiu Bo 
1654120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1655120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1656120de408SJosef Bacik 
16571fc28d8eSLiu Bo 	/*
1658662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1659662c653bSLiu Bo 	 * lock.
1660662c653bSLiu Bo 	 */
1661662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1662662c653bSLiu Bo 		/*
1663662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1664662c653bSLiu Bo 		 * have it read locked
16651fc28d8eSLiu Bo 		 */
1666857bc13fSJosef Bacik 		if (p->nowait) {
1667857bc13fSJosef Bacik 			b = btrfs_try_read_lock_root_node(root);
1668857bc13fSJosef Bacik 			if (IS_ERR(b))
1669857bc13fSJosef Bacik 				return b;
1670857bc13fSJosef Bacik 		} else {
16711bb96598SJosef Bacik 			b = btrfs_read_lock_root_node(root);
1672857bc13fSJosef Bacik 		}
16731fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16741fc28d8eSLiu Bo 		if (level > write_lock_level)
16751fc28d8eSLiu Bo 			goto out;
16761fc28d8eSLiu Bo 
1677662c653bSLiu Bo 		/* Whoops, must trade for write lock */
16781fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
16791fc28d8eSLiu Bo 		free_extent_buffer(b);
1680662c653bSLiu Bo 	}
1681662c653bSLiu Bo 
16821fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
16831fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
16841fc28d8eSLiu Bo 
16851fc28d8eSLiu Bo 	/* The level might have changed, check again */
16861fc28d8eSLiu Bo 	level = btrfs_header_level(b);
16871fc28d8eSLiu Bo 
16881fc28d8eSLiu Bo out:
1689120de408SJosef Bacik 	/*
1690120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1691120de408SJosef Bacik 	 * longer valid, return an error in this case.
1692120de408SJosef Bacik 	 */
1693120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1694120de408SJosef Bacik 		if (root_lock)
1695120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1696120de408SJosef Bacik 		free_extent_buffer(b);
1697120de408SJosef Bacik 		return ERR_PTR(-EIO);
1698120de408SJosef Bacik 	}
1699120de408SJosef Bacik 
17001fc28d8eSLiu Bo 	p->nodes[level] = b;
17011fc28d8eSLiu Bo 	if (!p->skip_locking)
17021fc28d8eSLiu Bo 		p->locks[level] = root_lock;
17031fc28d8eSLiu Bo 	/*
17041fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
17051fc28d8eSLiu Bo 	 */
17061fc28d8eSLiu Bo 	return b;
17071fc28d8eSLiu Bo }
17081fc28d8eSLiu Bo 
1709d96b3424SFilipe Manana /*
1710d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1711d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1712d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1713d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1714d96b3424SFilipe Manana  * reallocated in the next transaction.
1715d96b3424SFilipe Manana  *
1716d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1717d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1718d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1719d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1720d96b3424SFilipe Manana  */
1721d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1722d96b3424SFilipe Manana {
1723d96b3424SFilipe Manana 	const int i = path->lowest_level;
1724d96b3424SFilipe Manana 	const int slot = path->slots[i];
1725d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1726d96b3424SFilipe Manana 	struct extent_buffer *clone;
1727d96b3424SFilipe Manana 
1728d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1729d96b3424SFilipe Manana 
1730d96b3424SFilipe Manana 	if (!lowest)
1731d96b3424SFilipe Manana 		return 0;
1732d96b3424SFilipe Manana 
1733d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1734d96b3424SFilipe Manana 
1735d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1736d96b3424SFilipe Manana 	if (!clone)
1737d96b3424SFilipe Manana 		return -ENOMEM;
1738d96b3424SFilipe Manana 
1739d96b3424SFilipe Manana 	btrfs_release_path(path);
1740d96b3424SFilipe Manana 	path->nodes[i] = clone;
1741d96b3424SFilipe Manana 	path->slots[i] = slot;
1742d96b3424SFilipe Manana 
1743d96b3424SFilipe Manana 	return 0;
1744d96b3424SFilipe Manana }
17451fc28d8eSLiu Bo 
1746e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1747e2e58d0fSFilipe Manana 				      int search_low_slot,
1748e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1749e2e58d0fSFilipe Manana 				      int prev_cmp,
1750e2e58d0fSFilipe Manana 				      int *slot)
1751e2e58d0fSFilipe Manana {
1752e2e58d0fSFilipe Manana 	/*
1753e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1754e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1755e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1756e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1757e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1758e2e58d0fSFilipe Manana 	 */
1759e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1760e2e58d0fSFilipe Manana 		*slot = 0;
1761e2e58d0fSFilipe Manana 		return 0;
1762e2e58d0fSFilipe Manana 	}
1763e2e58d0fSFilipe Manana 
1764e2e58d0fSFilipe Manana 	return generic_bin_search(eb, search_low_slot, key, slot);
1765e2e58d0fSFilipe Manana }
1766e2e58d0fSFilipe Manana 
1767109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1768109324cfSFilipe Manana 		       struct btrfs_root *root,
1769109324cfSFilipe Manana 		       const struct btrfs_key *key,
1770109324cfSFilipe Manana 		       struct btrfs_path *path,
1771109324cfSFilipe Manana 		       int ins_len,
1772109324cfSFilipe Manana 		       int prev_cmp)
1773109324cfSFilipe Manana {
1774109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
1775109324cfSFilipe Manana 	int leaf_free_space = -1;
1776109324cfSFilipe Manana 	int search_low_slot = 0;
1777109324cfSFilipe Manana 	int ret;
1778109324cfSFilipe Manana 	bool do_bin_search = true;
1779109324cfSFilipe Manana 
1780109324cfSFilipe Manana 	/*
1781109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
1782109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
1783109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
1784109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1785109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
1786109324cfSFilipe Manana 	 */
1787109324cfSFilipe Manana 	if (ins_len > 0) {
1788109324cfSFilipe Manana 		/*
1789109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
1790109324cfSFilipe Manana 		 * will not change until then.
1791109324cfSFilipe Manana 		 */
1792109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
1793109324cfSFilipe Manana 
1794109324cfSFilipe Manana 		/*
1795109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
1796109324cfSFilipe Manana 		 * the root of the tree.
1797109324cfSFilipe Manana 		 */
1798109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
1799109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
1800109324cfSFilipe Manana 
1801109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
1802109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
1803109324cfSFilipe Manana 
1804109324cfSFilipe Manana 			/*
1805109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
1806109324cfSFilipe Manana 			 * taking into account that the first key is very likely
1807109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
1808109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
1809109324cfSFilipe Manana 			 * the header's level field.
1810109324cfSFilipe Manana 			 */
1811109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
1812109324cfSFilipe Manana 			if (ret < 0) {
1813109324cfSFilipe Manana 				/*
1814109324cfSFilipe Manana 				 * The first key is smaller than the key we want
1815109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
1816109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
1817109324cfSFilipe Manana 				 *
1818109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
1819109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
1820109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
1821109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
1822109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
1823109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
1824109324cfSFilipe Manana 				 */
1825109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
1826109324cfSFilipe Manana 				search_low_slot = 1;
1827109324cfSFilipe Manana 			} else {
1828109324cfSFilipe Manana 				/*
1829109324cfSFilipe Manana 				 * The first key is >= then the key we want to
1830109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
1831109324cfSFilipe Manana 				 * the target key will be at slot 0.
1832109324cfSFilipe Manana 				 *
1833109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
1834109324cfSFilipe Manana 				 * less than the first key, because we will need
1835109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
1836109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
1837109324cfSFilipe Manana 				 * If the key matches the first key, then we can
1838109324cfSFilipe Manana 				 * unlock all the upper nodes, using
1839109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
1840109324cfSFilipe Manana 				 * as stated above.
1841109324cfSFilipe Manana 				 */
1842109324cfSFilipe Manana 				if (ret == 0)
1843109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
1844109324cfSFilipe Manana 				/*
1845109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
1846109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
1847109324cfSFilipe Manana 				 * to adjust it.
1848109324cfSFilipe Manana 				 */
1849109324cfSFilipe Manana 				do_bin_search = false;
1850109324cfSFilipe Manana 				path->slots[0] = 0;
1851109324cfSFilipe Manana 			}
1852109324cfSFilipe Manana 		}
1853109324cfSFilipe Manana 	}
1854109324cfSFilipe Manana 
1855109324cfSFilipe Manana 	if (do_bin_search) {
1856109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
1857109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
1858109324cfSFilipe Manana 		if (ret < 0)
1859109324cfSFilipe Manana 			return ret;
1860109324cfSFilipe Manana 	}
1861109324cfSFilipe Manana 
1862109324cfSFilipe Manana 	if (ins_len > 0) {
1863109324cfSFilipe Manana 		/*
1864109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
1865109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
1866109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
1867109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
1868109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
1869109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
1870109324cfSFilipe Manana 		 * check will be correct.
1871109324cfSFilipe Manana 		 */
1872109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
1873109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
1874109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
1875109324cfSFilipe Manana 		}
1876109324cfSFilipe Manana 
1877109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
1878109324cfSFilipe Manana 
1879109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
1880109324cfSFilipe Manana 			int err;
1881109324cfSFilipe Manana 
1882109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
1883109324cfSFilipe Manana 					 (ret == 0));
1884bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
1885bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
1886bb8e9a60SFilipe Manana 				err = -EUCLEAN;
1887109324cfSFilipe Manana 			if (err)
1888109324cfSFilipe Manana 				ret = err;
1889109324cfSFilipe Manana 		}
1890109324cfSFilipe Manana 	}
1891109324cfSFilipe Manana 
1892109324cfSFilipe Manana 	return ret;
1893109324cfSFilipe Manana }
1894109324cfSFilipe Manana 
1895c8c42864SChris Mason /*
18964271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
18974271eceaSNikolay Borisov  * modifications to preserve tree invariants.
189874123bd7SChris Mason  *
18994271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
19004271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
19014271eceaSNikolay Borisov  * @root:	The root node of the tree
19024271eceaSNikolay Borisov  * @key:	The key we are looking for
19039a664971Sethanwu  * @ins_len:	Indicates purpose of search:
19049a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
19059a664971Sethanwu  *              <0  for deletions
19069a664971Sethanwu  *               0  for plain searches, not modifying the tree
19079a664971Sethanwu  *
19089a664971Sethanwu  *              (*) If size of item inserted doesn't include
19099a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
19109a664971Sethanwu  *              be set.
19114271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
19124271eceaSNikolay Borisov  *		when modifying the tree.
191397571fd0SChris Mason  *
19144271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
19154271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
19164271eceaSNikolay Borisov  *
19174271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
19184271eceaSNikolay Borisov  * of the path (level 0)
19194271eceaSNikolay Borisov  *
19204271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
19214271eceaSNikolay Borisov  * points to the slot where it should be inserted
19224271eceaSNikolay Borisov  *
19234271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
19244271eceaSNikolay Borisov  * is returned
192574123bd7SChris Mason  */
1926310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1927310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
1928310712b2SOmar Sandoval 		      int ins_len, int cow)
1929be0e5c09SChris Mason {
1930d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
19315f39d397SChris Mason 	struct extent_buffer *b;
1932be0e5c09SChris Mason 	int slot;
1933be0e5c09SChris Mason 	int ret;
193433c66f43SYan Zheng 	int err;
1935be0e5c09SChris Mason 	int level;
1936925baeddSChris Mason 	int lowest_unlock = 1;
1937bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
1938bd681513SChris Mason 	int write_lock_level = 0;
19399f3a7427SChris Mason 	u8 lowest_level = 0;
1940f7c79f30SChris Mason 	int min_write_lock_level;
1941d7396f07SFilipe David Borba Manana 	int prev_cmp;
19429f3a7427SChris Mason 
19436702ed49SChris Mason 	lowest_level = p->lowest_level;
1944323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
194522b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
1946eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
194725179201SJosef Bacik 
1948857bc13fSJosef Bacik 	/*
1949857bc13fSJosef Bacik 	 * For now only allow nowait for read only operations.  There's no
1950857bc13fSJosef Bacik 	 * strict reason why we can't, we just only need it for reads so it's
1951857bc13fSJosef Bacik 	 * only implemented for reads.
1952857bc13fSJosef Bacik 	 */
1953857bc13fSJosef Bacik 	ASSERT(!p->nowait || !cow);
1954857bc13fSJosef Bacik 
1955bd681513SChris Mason 	if (ins_len < 0) {
1956925baeddSChris Mason 		lowest_unlock = 2;
195765b51a00SChris Mason 
1958bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
1959bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
1960bd681513SChris Mason 		 * for those levels as well
1961bd681513SChris Mason 		 */
1962bd681513SChris Mason 		write_lock_level = 2;
1963bd681513SChris Mason 	} else if (ins_len > 0) {
1964bd681513SChris Mason 		/*
1965bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
1966bd681513SChris Mason 		 * level 1 so we can update keys
1967bd681513SChris Mason 		 */
1968bd681513SChris Mason 		write_lock_level = 1;
1969bd681513SChris Mason 	}
1970bd681513SChris Mason 
1971bd681513SChris Mason 	if (!cow)
1972bd681513SChris Mason 		write_lock_level = -1;
1973bd681513SChris Mason 
197409a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
1975bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
1976bd681513SChris Mason 
1977f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
1978f7c79f30SChris Mason 
1979d96b3424SFilipe Manana 	if (p->need_commit_sem) {
1980d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
1981857bc13fSJosef Bacik 		if (p->nowait) {
1982857bc13fSJosef Bacik 			if (!down_read_trylock(&fs_info->commit_root_sem))
1983857bc13fSJosef Bacik 				return -EAGAIN;
1984857bc13fSJosef Bacik 		} else {
1985d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
1986d96b3424SFilipe Manana 		}
1987857bc13fSJosef Bacik 	}
1988d96b3424SFilipe Manana 
1989bb803951SChris Mason again:
1990d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
19911fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
1992be6821f8SFilipe Manana 	if (IS_ERR(b)) {
1993be6821f8SFilipe Manana 		ret = PTR_ERR(b);
1994be6821f8SFilipe Manana 		goto done;
1995be6821f8SFilipe Manana 	}
1996925baeddSChris Mason 
1997eb60ceacSChris Mason 	while (b) {
1998f624d976SQu Wenruo 		int dec = 0;
1999f624d976SQu Wenruo 
20005f39d397SChris Mason 		level = btrfs_header_level(b);
200165b51a00SChris Mason 
200202217ed2SChris Mason 		if (cow) {
20039ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
20049ea2c7c9SNikolay Borisov 
2005c8c42864SChris Mason 			/*
2006c8c42864SChris Mason 			 * if we don't really need to cow this block
2007c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2008c8c42864SChris Mason 			 * so we test it here
2009c8c42864SChris Mason 			 */
20105963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
201165b51a00SChris Mason 				goto cow_done;
20125d4f98a2SYan Zheng 
2013bd681513SChris Mason 			/*
2014bd681513SChris Mason 			 * must have write locks on this node and the
2015bd681513SChris Mason 			 * parent
2016bd681513SChris Mason 			 */
20175124e00eSJosef Bacik 			if (level > write_lock_level ||
20185124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
20195124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
20205124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2021bd681513SChris Mason 				write_lock_level = level + 1;
2022bd681513SChris Mason 				btrfs_release_path(p);
2023bd681513SChris Mason 				goto again;
2024bd681513SChris Mason 			}
2025bd681513SChris Mason 
20269ea2c7c9SNikolay Borisov 			if (last_level)
20279ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
20289631e4ccSJosef Bacik 						      &b,
20299631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
20309ea2c7c9SNikolay Borisov 			else
203133c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2032e20d96d6SChris Mason 						      p->nodes[level + 1],
20339631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
20349631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
203533c66f43SYan Zheng 			if (err) {
203633c66f43SYan Zheng 				ret = err;
203765b51a00SChris Mason 				goto done;
203854aa1f4dSChris Mason 			}
203902217ed2SChris Mason 		}
204065b51a00SChris Mason cow_done:
2041eb60ceacSChris Mason 		p->nodes[level] = b;
2042b4ce94deSChris Mason 
2043b4ce94deSChris Mason 		/*
2044b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2045b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2046b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2047b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2048b4ce94deSChris Mason 		 *
2049eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2050eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2051eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2052eb653de1SFilipe David Borba Manana 		 * we're operating on.
2053b4ce94deSChris Mason 		 */
2054eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2055eb653de1SFilipe David Borba Manana 			int u = level + 1;
2056eb653de1SFilipe David Borba Manana 
2057eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2058eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2059eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2060eb653de1SFilipe David Borba Manana 			}
2061eb653de1SFilipe David Borba Manana 		}
2062b4ce94deSChris Mason 
2063e2e58d0fSFilipe Manana 		if (level == 0) {
2064109324cfSFilipe Manana 			if (ins_len > 0)
2065e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
2066bd681513SChris Mason 
2067109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2068459931ecSChris Mason 			if (!p->search_for_split)
2069f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
20704b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
207165b51a00SChris Mason 			goto done;
207265b51a00SChris Mason 		}
2073e2e58d0fSFilipe Manana 
2074e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2075e2e58d0fSFilipe Manana 		if (ret < 0)
2076e2e58d0fSFilipe Manana 			goto done;
2077e2e58d0fSFilipe Manana 		prev_cmp = ret;
2078e2e58d0fSFilipe Manana 
2079f624d976SQu Wenruo 		if (ret && slot > 0) {
2080f624d976SQu Wenruo 			dec = 1;
2081f624d976SQu Wenruo 			slot--;
2082f624d976SQu Wenruo 		}
2083f624d976SQu Wenruo 		p->slots[level] = slot;
2084f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2085f624d976SQu Wenruo 					     &write_lock_level);
2086f624d976SQu Wenruo 		if (err == -EAGAIN)
2087f624d976SQu Wenruo 			goto again;
2088f624d976SQu Wenruo 		if (err) {
2089f624d976SQu Wenruo 			ret = err;
2090f624d976SQu Wenruo 			goto done;
2091f624d976SQu Wenruo 		}
2092f624d976SQu Wenruo 		b = p->nodes[level];
2093f624d976SQu Wenruo 		slot = p->slots[level];
2094f624d976SQu Wenruo 
2095f624d976SQu Wenruo 		/*
2096f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2097f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2098f624d976SQu Wenruo 		 * the parent
2099f624d976SQu Wenruo 		 */
2100f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2101f624d976SQu Wenruo 			write_lock_level = level + 1;
2102f624d976SQu Wenruo 			btrfs_release_path(p);
2103f624d976SQu Wenruo 			goto again;
2104f624d976SQu Wenruo 		}
2105f624d976SQu Wenruo 
2106f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2107f624d976SQu Wenruo 			  &write_lock_level);
2108f624d976SQu Wenruo 
2109f624d976SQu Wenruo 		if (level == lowest_level) {
2110f624d976SQu Wenruo 			if (dec)
2111f624d976SQu Wenruo 				p->slots[level]++;
2112f624d976SQu Wenruo 			goto done;
2113f624d976SQu Wenruo 		}
2114f624d976SQu Wenruo 
2115f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2116f624d976SQu Wenruo 		if (err == -EAGAIN)
2117f624d976SQu Wenruo 			goto again;
2118f624d976SQu Wenruo 		if (err) {
2119f624d976SQu Wenruo 			ret = err;
2120f624d976SQu Wenruo 			goto done;
2121f624d976SQu Wenruo 		}
2122f624d976SQu Wenruo 
2123f624d976SQu Wenruo 		if (!p->skip_locking) {
2124f624d976SQu Wenruo 			level = btrfs_header_level(b);
2125b40130b2SJosef Bacik 
2126b40130b2SJosef Bacik 			btrfs_maybe_reset_lockdep_class(root, b);
2127b40130b2SJosef Bacik 
2128f624d976SQu Wenruo 			if (level <= write_lock_level) {
2129f624d976SQu Wenruo 				btrfs_tree_lock(b);
2130f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2131f624d976SQu Wenruo 			} else {
2132857bc13fSJosef Bacik 				if (p->nowait) {
2133857bc13fSJosef Bacik 					if (!btrfs_try_tree_read_lock(b)) {
2134857bc13fSJosef Bacik 						free_extent_buffer(b);
2135857bc13fSJosef Bacik 						ret = -EAGAIN;
2136857bc13fSJosef Bacik 						goto done;
2137857bc13fSJosef Bacik 					}
2138857bc13fSJosef Bacik 				} else {
2139fe596ca3SJosef Bacik 					btrfs_tree_read_lock(b);
2140857bc13fSJosef Bacik 				}
2141f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2142f624d976SQu Wenruo 			}
2143f624d976SQu Wenruo 			p->nodes[level] = b;
2144f624d976SQu Wenruo 		}
214565b51a00SChris Mason 	}
214665b51a00SChris Mason 	ret = 1;
214765b51a00SChris Mason done:
21485f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2149b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2150d96b3424SFilipe Manana 
2151d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2152d96b3424SFilipe Manana 		int ret2;
2153d96b3424SFilipe Manana 
2154d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2155d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2156d96b3424SFilipe Manana 		if (ret2)
2157d96b3424SFilipe Manana 			ret = ret2;
2158d96b3424SFilipe Manana 	}
2159d96b3424SFilipe Manana 
2160be0e5c09SChris Mason 	return ret;
2161be0e5c09SChris Mason }
2162f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2163be0e5c09SChris Mason 
216474123bd7SChris Mason /*
21655d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
21665d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
21675d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
21685d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
21695d9e75c4SJan Schmidt  *
21705d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
21715d9e75c4SJan Schmidt  *
21725d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
21735d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
21745d9e75c4SJan Schmidt  */
2175310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
21765d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
21775d9e75c4SJan Schmidt {
21780b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
21795d9e75c4SJan Schmidt 	struct extent_buffer *b;
21805d9e75c4SJan Schmidt 	int slot;
21815d9e75c4SJan Schmidt 	int ret;
21825d9e75c4SJan Schmidt 	int err;
21835d9e75c4SJan Schmidt 	int level;
21845d9e75c4SJan Schmidt 	int lowest_unlock = 1;
21855d9e75c4SJan Schmidt 	u8 lowest_level = 0;
21865d9e75c4SJan Schmidt 
21875d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
21885d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
2189c922b016SStefan Roesch 	ASSERT(!p->nowait);
21905d9e75c4SJan Schmidt 
21915d9e75c4SJan Schmidt 	if (p->search_commit_root) {
21925d9e75c4SJan Schmidt 		BUG_ON(time_seq);
21935d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
21945d9e75c4SJan Schmidt 	}
21955d9e75c4SJan Schmidt 
21965d9e75c4SJan Schmidt again:
2197f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2198315bed43SNikolay Borisov 	if (!b) {
2199315bed43SNikolay Borisov 		ret = -EIO;
2200315bed43SNikolay Borisov 		goto done;
2201315bed43SNikolay Borisov 	}
22025d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
22035d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
22045d9e75c4SJan Schmidt 
22055d9e75c4SJan Schmidt 	while (b) {
2206abe9339dSQu Wenruo 		int dec = 0;
2207abe9339dSQu Wenruo 
22085d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
22095d9e75c4SJan Schmidt 		p->nodes[level] = b;
22105d9e75c4SJan Schmidt 
22115d9e75c4SJan Schmidt 		/*
22125d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
22135d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
22145d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
22155d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
22165d9e75c4SJan Schmidt 		 */
22175d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
22185d9e75c4SJan Schmidt 
2219995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
2220cbca7d59SFilipe Manana 		if (ret < 0)
2221cbca7d59SFilipe Manana 			goto done;
22225d9e75c4SJan Schmidt 
2223abe9339dSQu Wenruo 		if (level == 0) {
2224abe9339dSQu Wenruo 			p->slots[level] = slot;
2225abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2226abe9339dSQu Wenruo 			goto done;
2227abe9339dSQu Wenruo 		}
2228abe9339dSQu Wenruo 
22295d9e75c4SJan Schmidt 		if (ret && slot > 0) {
22305d9e75c4SJan Schmidt 			dec = 1;
2231abe9339dSQu Wenruo 			slot--;
22325d9e75c4SJan Schmidt 		}
22335d9e75c4SJan Schmidt 		p->slots[level] = slot;
22345d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
22355d9e75c4SJan Schmidt 
22365d9e75c4SJan Schmidt 		if (level == lowest_level) {
22375d9e75c4SJan Schmidt 			if (dec)
22385d9e75c4SJan Schmidt 				p->slots[level]++;
22395d9e75c4SJan Schmidt 			goto done;
22405d9e75c4SJan Schmidt 		}
22415d9e75c4SJan Schmidt 
2242abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
22435d9e75c4SJan Schmidt 		if (err == -EAGAIN)
22445d9e75c4SJan Schmidt 			goto again;
22455d9e75c4SJan Schmidt 		if (err) {
22465d9e75c4SJan Schmidt 			ret = err;
22475d9e75c4SJan Schmidt 			goto done;
22485d9e75c4SJan Schmidt 		}
22495d9e75c4SJan Schmidt 
22505d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
22515d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2252f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2253db7f3436SJosef Bacik 		if (!b) {
2254db7f3436SJosef Bacik 			ret = -ENOMEM;
2255db7f3436SJosef Bacik 			goto done;
2256db7f3436SJosef Bacik 		}
22575d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
22585d9e75c4SJan Schmidt 		p->nodes[level] = b;
22595d9e75c4SJan Schmidt 	}
22605d9e75c4SJan Schmidt 	ret = 1;
22615d9e75c4SJan Schmidt done:
22625d9e75c4SJan Schmidt 	if (ret < 0)
22635d9e75c4SJan Schmidt 		btrfs_release_path(p);
22645d9e75c4SJan Schmidt 
22655d9e75c4SJan Schmidt 	return ret;
22665d9e75c4SJan Schmidt }
22675d9e75c4SJan Schmidt 
22685d9e75c4SJan Schmidt /*
22692f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
22702f38b3e1SArne Jansen  * instead the next or previous item should be returned.
22712f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
22722f38b3e1SArne Jansen  * otherwise.
22732f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
22742f38b3e1SArne Jansen  * return the next lower instead.
22752f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
22762f38b3e1SArne Jansen  * return the next higher instead.
22772f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
22782f38b3e1SArne Jansen  * < 0 on error
22792f38b3e1SArne Jansen  */
22802f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2281310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2282310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2283310712b2SOmar Sandoval 			       int return_any)
22842f38b3e1SArne Jansen {
22852f38b3e1SArne Jansen 	int ret;
22862f38b3e1SArne Jansen 	struct extent_buffer *leaf;
22872f38b3e1SArne Jansen 
22882f38b3e1SArne Jansen again:
22892f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
22902f38b3e1SArne Jansen 	if (ret <= 0)
22912f38b3e1SArne Jansen 		return ret;
22922f38b3e1SArne Jansen 	/*
22932f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
22942f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
22952f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
22962f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
22972f38b3e1SArne Jansen 	 * item.
22982f38b3e1SArne Jansen 	 */
22992f38b3e1SArne Jansen 	leaf = p->nodes[0];
23002f38b3e1SArne Jansen 
23012f38b3e1SArne Jansen 	if (find_higher) {
23022f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
23032f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
23042f38b3e1SArne Jansen 			if (ret <= 0)
23052f38b3e1SArne Jansen 				return ret;
23062f38b3e1SArne Jansen 			if (!return_any)
23072f38b3e1SArne Jansen 				return 1;
23082f38b3e1SArne Jansen 			/*
23092f38b3e1SArne Jansen 			 * no higher item found, return the next
23102f38b3e1SArne Jansen 			 * lower instead
23112f38b3e1SArne Jansen 			 */
23122f38b3e1SArne Jansen 			return_any = 0;
23132f38b3e1SArne Jansen 			find_higher = 0;
23142f38b3e1SArne Jansen 			btrfs_release_path(p);
23152f38b3e1SArne Jansen 			goto again;
23162f38b3e1SArne Jansen 		}
23172f38b3e1SArne Jansen 	} else {
23182f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
23192f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2320e6793769SArne Jansen 			if (ret < 0)
23212f38b3e1SArne Jansen 				return ret;
2322e6793769SArne Jansen 			if (!ret) {
232323c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
232423c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
232523c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2326e6793769SArne Jansen 				return 0;
2327e6793769SArne Jansen 			}
23282f38b3e1SArne Jansen 			if (!return_any)
23292f38b3e1SArne Jansen 				return 1;
23302f38b3e1SArne Jansen 			/*
23312f38b3e1SArne Jansen 			 * no lower item found, return the next
23322f38b3e1SArne Jansen 			 * higher instead
23332f38b3e1SArne Jansen 			 */
23342f38b3e1SArne Jansen 			return_any = 0;
23352f38b3e1SArne Jansen 			find_higher = 1;
23362f38b3e1SArne Jansen 			btrfs_release_path(p);
23372f38b3e1SArne Jansen 			goto again;
2338e6793769SArne Jansen 		} else {
23392f38b3e1SArne Jansen 			--p->slots[0];
23402f38b3e1SArne Jansen 		}
23412f38b3e1SArne Jansen 	}
23422f38b3e1SArne Jansen 	return 0;
23432f38b3e1SArne Jansen }
23442f38b3e1SArne Jansen 
23452f38b3e1SArne Jansen /*
23460ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
23470ff40a91SMarcos Paulo de Souza  * was not found.
23480ff40a91SMarcos Paulo de Souza  *
23490ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
23500ff40a91SMarcos Paulo de Souza  */
23510ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
23520ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
23530ff40a91SMarcos Paulo de Souza {
23540ff40a91SMarcos Paulo de Souza 	int ret;
23550ff40a91SMarcos Paulo de Souza 
23560ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
23570ff40a91SMarcos Paulo de Souza 	if (ret > 0)
23580ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
23590ff40a91SMarcos Paulo de Souza 
23600ff40a91SMarcos Paulo de Souza 	if (ret == 0)
23610ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
23620ff40a91SMarcos Paulo de Souza 
23630ff40a91SMarcos Paulo de Souza 	return ret;
23640ff40a91SMarcos Paulo de Souza }
23650ff40a91SMarcos Paulo de Souza 
2366*43dd529aSDavid Sterba /*
236762142be3SGabriel Niebler  * Search for a valid slot for the given path.
236862142be3SGabriel Niebler  *
236962142be3SGabriel Niebler  * @root:	The root node of the tree.
237062142be3SGabriel Niebler  * @key:	Will contain a valid item if found.
237162142be3SGabriel Niebler  * @path:	The starting point to validate the slot.
237262142be3SGabriel Niebler  *
237362142be3SGabriel Niebler  * Return: 0  if the item is valid
237462142be3SGabriel Niebler  *         1  if not found
237562142be3SGabriel Niebler  *         <0 if error.
237662142be3SGabriel Niebler  */
237762142be3SGabriel Niebler int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
237862142be3SGabriel Niebler 			      struct btrfs_path *path)
237962142be3SGabriel Niebler {
238062142be3SGabriel Niebler 	while (1) {
238162142be3SGabriel Niebler 		int ret;
238262142be3SGabriel Niebler 		const int slot = path->slots[0];
238362142be3SGabriel Niebler 		const struct extent_buffer *leaf = path->nodes[0];
238462142be3SGabriel Niebler 
238562142be3SGabriel Niebler 		/* This is where we start walking the path. */
238662142be3SGabriel Niebler 		if (slot >= btrfs_header_nritems(leaf)) {
238762142be3SGabriel Niebler 			/*
238862142be3SGabriel Niebler 			 * If we've reached the last slot in this leaf we need
238962142be3SGabriel Niebler 			 * to go to the next leaf and reset the path.
239062142be3SGabriel Niebler 			 */
239162142be3SGabriel Niebler 			ret = btrfs_next_leaf(root, path);
239262142be3SGabriel Niebler 			if (ret)
239362142be3SGabriel Niebler 				return ret;
239462142be3SGabriel Niebler 			continue;
239562142be3SGabriel Niebler 		}
239662142be3SGabriel Niebler 		/* Store the found, valid item in @key. */
239762142be3SGabriel Niebler 		btrfs_item_key_to_cpu(leaf, key, slot);
239862142be3SGabriel Niebler 		break;
239962142be3SGabriel Niebler 	}
240062142be3SGabriel Niebler 	return 0;
240162142be3SGabriel Niebler }
240262142be3SGabriel Niebler 
24030ff40a91SMarcos Paulo de Souza /*
240474123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
240574123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
240674123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
240774123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
240874123bd7SChris Mason  * higher levels
2409aa5d6bedSChris Mason  *
241074123bd7SChris Mason  */
2411b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
24125f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2413be0e5c09SChris Mason {
2414be0e5c09SChris Mason 	int i;
24155f39d397SChris Mason 	struct extent_buffer *t;
24160e82bcfeSDavid Sterba 	int ret;
24175f39d397SChris Mason 
2418234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2419be0e5c09SChris Mason 		int tslot = path->slots[i];
24200e82bcfeSDavid Sterba 
2421eb60ceacSChris Mason 		if (!path->nodes[i])
2422be0e5c09SChris Mason 			break;
24235f39d397SChris Mason 		t = path->nodes[i];
2424f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
242533cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REPLACE);
24260e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
24275f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2428d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2429be0e5c09SChris Mason 		if (tslot != 0)
2430be0e5c09SChris Mason 			break;
2431be0e5c09SChris Mason 	}
2432be0e5c09SChris Mason }
2433be0e5c09SChris Mason 
243474123bd7SChris Mason /*
243531840ae1SZheng Yan  * update item key.
243631840ae1SZheng Yan  *
243731840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
243831840ae1SZheng Yan  * that the new key won't break the order
243931840ae1SZheng Yan  */
2440b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2441b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2442310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
244331840ae1SZheng Yan {
244431840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
244531840ae1SZheng Yan 	struct extent_buffer *eb;
244631840ae1SZheng Yan 	int slot;
244731840ae1SZheng Yan 
244831840ae1SZheng Yan 	eb = path->nodes[0];
244931840ae1SZheng Yan 	slot = path->slots[0];
245031840ae1SZheng Yan 	if (slot > 0) {
245131840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
24527c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
24537c15d410SQu Wenruo 			btrfs_crit(fs_info,
24547c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
24557c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
24567c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
24577c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
24587c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
24597c15d410SQu Wenruo 				   new_key->offset);
24607c15d410SQu Wenruo 			btrfs_print_leaf(eb);
24617c15d410SQu Wenruo 			BUG();
24627c15d410SQu Wenruo 		}
246331840ae1SZheng Yan 	}
246431840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
246531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
24667c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
24677c15d410SQu Wenruo 			btrfs_crit(fs_info,
24687c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
24697c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
24707c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
24717c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
24727c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
24737c15d410SQu Wenruo 				   new_key->offset);
24747c15d410SQu Wenruo 			btrfs_print_leaf(eb);
24757c15d410SQu Wenruo 			BUG();
24767c15d410SQu Wenruo 		}
247731840ae1SZheng Yan 	}
247831840ae1SZheng Yan 
247931840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
248031840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
248131840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
248231840ae1SZheng Yan 	if (slot == 0)
2483b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
248431840ae1SZheng Yan }
248531840ae1SZheng Yan 
248631840ae1SZheng Yan /*
2487d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2488d16c702fSQu Wenruo  *
2489d16c702fSQu Wenruo  * Return true if something is wrong.
2490d16c702fSQu Wenruo  * Return false if everything is fine.
2491d16c702fSQu Wenruo  *
2492d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2493d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2494d16c702fSQu Wenruo  *
2495d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2496d16c702fSQu Wenruo  * --------------------------------------------------------------
2497d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2498d16c702fSQu Wenruo  *
2499d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2500d16c702fSQu Wenruo  * key in leaf @right is 7.
2501d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2502d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2503d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2504d16c702fSQu Wenruo  * key of @right.
2505d16c702fSQu Wenruo  */
2506d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2507d16c702fSQu Wenruo 			       struct extent_buffer *right)
2508d16c702fSQu Wenruo {
2509d16c702fSQu Wenruo 	struct btrfs_key left_last;
2510d16c702fSQu Wenruo 	struct btrfs_key right_first;
2511d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2512d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2513d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2514d16c702fSQu Wenruo 
2515d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2516d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2517d16c702fSQu Wenruo 		return false;
2518d16c702fSQu Wenruo 
2519d16c702fSQu Wenruo 	if (level) {
2520d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2521d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2522d16c702fSQu Wenruo 	} else {
2523d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2524d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2525d16c702fSQu Wenruo 	}
2526d16c702fSQu Wenruo 
2527d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2528d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2529d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2530d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2531d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2532d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2533d16c702fSQu Wenruo 		return true;
2534d16c702fSQu Wenruo 	}
2535d16c702fSQu Wenruo 	return false;
2536d16c702fSQu Wenruo }
2537d16c702fSQu Wenruo 
2538d16c702fSQu Wenruo /*
253974123bd7SChris Mason  * try to push data from one node into the next node left in the
254079f95c82SChris Mason  * tree.
2541aa5d6bedSChris Mason  *
2542aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2543aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
254474123bd7SChris Mason  */
254598ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
25462ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2547971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2548be0e5c09SChris Mason {
2549d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2550be0e5c09SChris Mason 	int push_items = 0;
2551bb803951SChris Mason 	int src_nritems;
2552bb803951SChris Mason 	int dst_nritems;
2553aa5d6bedSChris Mason 	int ret = 0;
2554be0e5c09SChris Mason 
25555f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
25565f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
25570b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
25587bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
25597bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
256054aa1f4dSChris Mason 
2561bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2562971a1f66SChris Mason 		return 1;
2563971a1f66SChris Mason 
2564d397712bSChris Mason 	if (push_items <= 0)
2565be0e5c09SChris Mason 		return 1;
2566be0e5c09SChris Mason 
2567bce4eae9SChris Mason 	if (empty) {
2568971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2569bce4eae9SChris Mason 		if (push_items < src_nritems) {
2570bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2571bce4eae9SChris Mason 			 * we aren't going to empty it
2572bce4eae9SChris Mason 			 */
2573bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2574bce4eae9SChris Mason 				if (push_items <= 8)
2575bce4eae9SChris Mason 					return 1;
2576bce4eae9SChris Mason 				push_items -= 8;
2577bce4eae9SChris Mason 			}
2578bce4eae9SChris Mason 		}
2579bce4eae9SChris Mason 	} else
2580bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
258179f95c82SChris Mason 
2582d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2583d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2584d16c702fSQu Wenruo 		ret = -EUCLEAN;
2585d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2586d16c702fSQu Wenruo 		return ret;
2587d16c702fSQu Wenruo 	}
2588f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
25895de865eeSFilipe David Borba Manana 	if (ret) {
259066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
25915de865eeSFilipe David Borba Manana 		return ret;
25925de865eeSFilipe David Borba Manana 	}
25935f39d397SChris Mason 	copy_extent_buffer(dst, src,
25945f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
25955f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2596123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
25975f39d397SChris Mason 
2598bb803951SChris Mason 	if (push_items < src_nritems) {
259957911b8bSJan Schmidt 		/*
2600f3a84ccdSFilipe Manana 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2601f3a84ccdSFilipe Manana 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
260257911b8bSJan Schmidt 		 */
26035f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
26045f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2605e2fa7227SChris Mason 				      (src_nritems - push_items) *
2606123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2607bb803951SChris Mason 	}
26085f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
26095f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
26105f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
26115f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
261231840ae1SZheng Yan 
2613bb803951SChris Mason 	return ret;
2614be0e5c09SChris Mason }
2615be0e5c09SChris Mason 
261697571fd0SChris Mason /*
261779f95c82SChris Mason  * try to push data from one node into the next node right in the
261879f95c82SChris Mason  * tree.
261979f95c82SChris Mason  *
262079f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
262179f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
262279f95c82SChris Mason  *
262379f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
262479f95c82SChris Mason  */
26255f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
26265f39d397SChris Mason 			      struct extent_buffer *dst,
26275f39d397SChris Mason 			      struct extent_buffer *src)
262879f95c82SChris Mason {
262955d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
263079f95c82SChris Mason 	int push_items = 0;
263179f95c82SChris Mason 	int max_push;
263279f95c82SChris Mason 	int src_nritems;
263379f95c82SChris Mason 	int dst_nritems;
263479f95c82SChris Mason 	int ret = 0;
263579f95c82SChris Mason 
26367bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
26377bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
26387bb86316SChris Mason 
26395f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
26405f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
26410b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2642d397712bSChris Mason 	if (push_items <= 0)
264379f95c82SChris Mason 		return 1;
2644bce4eae9SChris Mason 
2645d397712bSChris Mason 	if (src_nritems < 4)
2646bce4eae9SChris Mason 		return 1;
264779f95c82SChris Mason 
264879f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
264979f95c82SChris Mason 	/* don't try to empty the node */
2650d397712bSChris Mason 	if (max_push >= src_nritems)
265179f95c82SChris Mason 		return 1;
2652252c38f0SYan 
265379f95c82SChris Mason 	if (max_push < push_items)
265479f95c82SChris Mason 		push_items = max_push;
265579f95c82SChris Mason 
2656d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2657d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2658d16c702fSQu Wenruo 		ret = -EUCLEAN;
2659d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2660d16c702fSQu Wenruo 		return ret;
2661d16c702fSQu Wenruo 	}
2662f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2663bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
26645f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
26655f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
26665f39d397SChris Mason 				      (dst_nritems) *
26675f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2668d6025579SChris Mason 
2669f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2670ed874f0dSDavid Sterba 					 push_items);
26715de865eeSFilipe David Borba Manana 	if (ret) {
267266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
26735de865eeSFilipe David Borba Manana 		return ret;
26745de865eeSFilipe David Borba Manana 	}
26755f39d397SChris Mason 	copy_extent_buffer(dst, src,
26765f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
26775f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2678123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
267979f95c82SChris Mason 
26805f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
26815f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
268279f95c82SChris Mason 
26835f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
26845f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
268531840ae1SZheng Yan 
268679f95c82SChris Mason 	return ret;
268779f95c82SChris Mason }
268879f95c82SChris Mason 
268979f95c82SChris Mason /*
269097571fd0SChris Mason  * helper function to insert a new root level in the tree.
269197571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
269297571fd0SChris Mason  * point to the existing root
2693aa5d6bedSChris Mason  *
2694aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
269597571fd0SChris Mason  */
2696d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
26975f39d397SChris Mason 			   struct btrfs_root *root,
2698fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
269974123bd7SChris Mason {
27000b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
27017bb86316SChris Mason 	u64 lower_gen;
27025f39d397SChris Mason 	struct extent_buffer *lower;
27035f39d397SChris Mason 	struct extent_buffer *c;
2704925baeddSChris Mason 	struct extent_buffer *old;
27055f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2706d9d19a01SDavid Sterba 	int ret;
27075c680ed6SChris Mason 
27085c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
27095c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
27105c680ed6SChris Mason 
27117bb86316SChris Mason 	lower = path->nodes[level-1];
27127bb86316SChris Mason 	if (level == 1)
27137bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
27147bb86316SChris Mason 	else
27157bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
27167bb86316SChris Mason 
271779bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
271879bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2719cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
27205f39d397SChris Mason 	if (IS_ERR(c))
27215f39d397SChris Mason 		return PTR_ERR(c);
2722925baeddSChris Mason 
27230b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2724f0486c68SYan, Zheng 
27255f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
27265f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2727db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
27287bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
272931840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
27307bb86316SChris Mason 
27317bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
27325f39d397SChris Mason 
27335f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2734d5719762SChris Mason 
2735925baeddSChris Mason 	old = root->node;
2736406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2737d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2738240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2739925baeddSChris Mason 
2740925baeddSChris Mason 	/* the super has an extra ref to root->node */
2741925baeddSChris Mason 	free_extent_buffer(old);
2742925baeddSChris Mason 
27430b86a832SChris Mason 	add_root_to_dirty_list(root);
274467439dadSDavid Sterba 	atomic_inc(&c->refs);
27455f39d397SChris Mason 	path->nodes[level] = c;
2746ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
274774123bd7SChris Mason 	path->slots[level] = 0;
274874123bd7SChris Mason 	return 0;
274974123bd7SChris Mason }
27505c680ed6SChris Mason 
27515c680ed6SChris Mason /*
27525c680ed6SChris Mason  * worker function to insert a single pointer in a node.
27535c680ed6SChris Mason  * the node should have enough room for the pointer already
275497571fd0SChris Mason  *
27555c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
27565c680ed6SChris Mason  * blocknr is the block the key points to.
27575c680ed6SChris Mason  */
2758143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
27596ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2760143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2761c3e06965SJan Schmidt 		       int slot, int level)
27625c680ed6SChris Mason {
27635f39d397SChris Mason 	struct extent_buffer *lower;
27645c680ed6SChris Mason 	int nritems;
2765f3ea38daSJan Schmidt 	int ret;
27665c680ed6SChris Mason 
27675c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
276849d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
27695f39d397SChris Mason 	lower = path->nodes[level];
27705f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2771c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
27726ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
277374123bd7SChris Mason 	if (slot != nritems) {
2774bf1d3425SDavid Sterba 		if (level) {
2775f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2776f3a84ccdSFilipe Manana 					slot, nritems - slot);
2777bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2778bf1d3425SDavid Sterba 		}
27795f39d397SChris Mason 		memmove_extent_buffer(lower,
27805f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
27815f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
2782123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
278374123bd7SChris Mason 	}
2784c3e06965SJan Schmidt 	if (level) {
2785f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
278633cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_ADD);
2787f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2788f3ea38daSJan Schmidt 	}
27895f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2790db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
279174493f7aSChris Mason 	WARN_ON(trans->transid == 0);
279274493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
27935f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
27945f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
279574123bd7SChris Mason }
279674123bd7SChris Mason 
279797571fd0SChris Mason /*
279897571fd0SChris Mason  * split the node at the specified level in path in two.
279997571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
280097571fd0SChris Mason  *
280197571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
280297571fd0SChris Mason  * left and right, if either one works, it returns right away.
2803aa5d6bedSChris Mason  *
2804aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
280597571fd0SChris Mason  */
2806e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
2807e02119d5SChris Mason 			       struct btrfs_root *root,
2808e02119d5SChris Mason 			       struct btrfs_path *path, int level)
2809be0e5c09SChris Mason {
28100b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
28115f39d397SChris Mason 	struct extent_buffer *c;
28125f39d397SChris Mason 	struct extent_buffer *split;
28135f39d397SChris Mason 	struct btrfs_disk_key disk_key;
2814be0e5c09SChris Mason 	int mid;
28155c680ed6SChris Mason 	int ret;
28167518a238SChris Mason 	u32 c_nritems;
2817be0e5c09SChris Mason 
28185f39d397SChris Mason 	c = path->nodes[level];
28197bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
28205f39d397SChris Mason 	if (c == root->node) {
2821d9abbf1cSJan Schmidt 		/*
282290f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
282390f8d62eSJan Schmidt 		 *
2824fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
282590f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
282690f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
2827f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2828f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
2829f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
2830d9abbf1cSJan Schmidt 		 */
2831fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
28325c680ed6SChris Mason 		if (ret)
28335c680ed6SChris Mason 			return ret;
2834b3612421SChris Mason 	} else {
2835e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
28365f39d397SChris Mason 		c = path->nodes[level];
28375f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
28380b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2839e66f709bSChris Mason 			return 0;
284054aa1f4dSChris Mason 		if (ret < 0)
284154aa1f4dSChris Mason 			return ret;
28425c680ed6SChris Mason 	}
2843e66f709bSChris Mason 
28445f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
28455d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
28465d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
28477bb86316SChris Mason 
284879bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
284979bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
285079bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
28515f39d397SChris Mason 	if (IS_ERR(split))
28525f39d397SChris Mason 		return PTR_ERR(split);
285354aa1f4dSChris Mason 
28540b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2855bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
28565f39d397SChris Mason 
2857f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
28585de865eeSFilipe David Borba Manana 	if (ret) {
285966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
28605de865eeSFilipe David Borba Manana 		return ret;
28615de865eeSFilipe David Borba Manana 	}
28625f39d397SChris Mason 	copy_extent_buffer(split, c,
28635f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
28645f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
2865123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
28665f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
28675f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
2868aa5d6bedSChris Mason 
28695f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
28705f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
28715f39d397SChris Mason 
28726ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
2873c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
2874aa5d6bedSChris Mason 
28755de08d7dSChris Mason 	if (path->slots[level] >= mid) {
28765c680ed6SChris Mason 		path->slots[level] -= mid;
2877925baeddSChris Mason 		btrfs_tree_unlock(c);
28785f39d397SChris Mason 		free_extent_buffer(c);
28795f39d397SChris Mason 		path->nodes[level] = split;
28805c680ed6SChris Mason 		path->slots[level + 1] += 1;
2881eb60ceacSChris Mason 	} else {
2882925baeddSChris Mason 		btrfs_tree_unlock(split);
28835f39d397SChris Mason 		free_extent_buffer(split);
2884be0e5c09SChris Mason 	}
2885d5286a92SNikolay Borisov 	return 0;
2886be0e5c09SChris Mason }
2887be0e5c09SChris Mason 
288874123bd7SChris Mason /*
288974123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
289074123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
289174123bd7SChris Mason  * space used both by the item structs and the item data
289274123bd7SChris Mason  */
28935f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2894be0e5c09SChris Mason {
2895be0e5c09SChris Mason 	int data_len;
28965f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
2897d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
2898be0e5c09SChris Mason 
2899be0e5c09SChris Mason 	if (!nr)
2900be0e5c09SChris Mason 		return 0;
29013212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
29023212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
29030783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
2904d4dbff95SChris Mason 	WARN_ON(data_len < 0);
2905be0e5c09SChris Mason 	return data_len;
2906be0e5c09SChris Mason }
2907be0e5c09SChris Mason 
290874123bd7SChris Mason /*
2909d4dbff95SChris Mason  * The space between the end of the leaf items and
2910d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
2911d4dbff95SChris Mason  * the leaf has left for both items and data
2912d4dbff95SChris Mason  */
2913e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
2914d4dbff95SChris Mason {
2915e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
29165f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
29175f39d397SChris Mason 	int ret;
29180b246afaSJeff Mahoney 
29190b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
29205f39d397SChris Mason 	if (ret < 0) {
29210b246afaSJeff Mahoney 		btrfs_crit(fs_info,
2922efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2923da17066cSJeff Mahoney 			   ret,
29240b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
29255f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
29265f39d397SChris Mason 	}
29275f39d397SChris Mason 	return ret;
2928d4dbff95SChris Mason }
2929d4dbff95SChris Mason 
293099d8f83cSChris Mason /*
293199d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
293299d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
293399d8f83cSChris Mason  */
2934f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
293544871b1bSChris Mason 				      int data_size, int empty,
293644871b1bSChris Mason 				      struct extent_buffer *right,
293799d8f83cSChris Mason 				      int free_space, u32 left_nritems,
293899d8f83cSChris Mason 				      u32 min_slot)
293900ec4c51SChris Mason {
2940f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
29415f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
294244871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
2943cfed81a0SChris Mason 	struct btrfs_map_token token;
29445f39d397SChris Mason 	struct btrfs_disk_key disk_key;
294500ec4c51SChris Mason 	int slot;
294634a38218SChris Mason 	u32 i;
294700ec4c51SChris Mason 	int push_space = 0;
294800ec4c51SChris Mason 	int push_items = 0;
294934a38218SChris Mason 	u32 nr;
29507518a238SChris Mason 	u32 right_nritems;
29515f39d397SChris Mason 	u32 data_end;
2952db94535dSChris Mason 	u32 this_item_size;
295300ec4c51SChris Mason 
295434a38218SChris Mason 	if (empty)
295534a38218SChris Mason 		nr = 0;
295634a38218SChris Mason 	else
295799d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
295834a38218SChris Mason 
295931840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
296087b29b20SYan Zheng 		push_space += data_size;
296131840ae1SZheng Yan 
296244871b1bSChris Mason 	slot = path->slots[1];
296334a38218SChris Mason 	i = left_nritems - 1;
296434a38218SChris Mason 	while (i >= nr) {
296531840ae1SZheng Yan 		if (!empty && push_items > 0) {
296631840ae1SZheng Yan 			if (path->slots[0] > i)
296731840ae1SZheng Yan 				break;
296831840ae1SZheng Yan 			if (path->slots[0] == i) {
2969e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
2970e902baacSDavid Sterba 
297131840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
297231840ae1SZheng Yan 					break;
297331840ae1SZheng Yan 			}
297431840ae1SZheng Yan 		}
297531840ae1SZheng Yan 
297600ec4c51SChris Mason 		if (path->slots[0] == i)
297787b29b20SYan Zheng 			push_space += data_size;
2978db94535dSChris Mason 
29793212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
298074794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
298174794207SJosef Bacik 		    push_space > free_space)
298200ec4c51SChris Mason 			break;
298331840ae1SZheng Yan 
298400ec4c51SChris Mason 		push_items++;
298574794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
298634a38218SChris Mason 		if (i == 0)
298734a38218SChris Mason 			break;
298834a38218SChris Mason 		i--;
2989db94535dSChris Mason 	}
29905f39d397SChris Mason 
2991925baeddSChris Mason 	if (push_items == 0)
2992925baeddSChris Mason 		goto out_unlock;
29935f39d397SChris Mason 
29946c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
29955f39d397SChris Mason 
299600ec4c51SChris Mason 	/* push left to right */
29975f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
299834a38218SChris Mason 
2999dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
30008f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
30015f39d397SChris Mason 
300200ec4c51SChris Mason 	/* make room in the right data area */
30038f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
30045f39d397SChris Mason 	memmove_extent_buffer(right,
30053d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
30063d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
30070b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
30085f39d397SChris Mason 
300900ec4c51SChris Mason 	/* copy from the left data area */
30103d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
30110b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
30128f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3013d6025579SChris Mason 		     push_space);
30145f39d397SChris Mason 
30155f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
30165f39d397SChris Mason 			      btrfs_item_nr_offset(0),
30170783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
30185f39d397SChris Mason 
301900ec4c51SChris Mason 	/* copy the items from left to right */
30205f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
30215f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
30220783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
302300ec4c51SChris Mason 
302400ec4c51SChris Mason 	/* update the item pointers */
3025c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
30267518a238SChris Mason 	right_nritems += push_items;
30275f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
30280b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
30297518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
30303212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
30313212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3032db94535dSChris Mason 	}
3033db94535dSChris Mason 
30347518a238SChris Mason 	left_nritems -= push_items;
30355f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
303600ec4c51SChris Mason 
303734a38218SChris Mason 	if (left_nritems)
30385f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3039f0486c68SYan, Zheng 	else
30406a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3041f0486c68SYan, Zheng 
30425f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3043a429e513SChris Mason 
30445f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
30455f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3046d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
304702217ed2SChris Mason 
304800ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
30497518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
30507518a238SChris Mason 		path->slots[0] -= left_nritems;
3051925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
30526a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3053925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
30545f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
30555f39d397SChris Mason 		path->nodes[0] = right;
305600ec4c51SChris Mason 		path->slots[1] += 1;
305700ec4c51SChris Mason 	} else {
3058925baeddSChris Mason 		btrfs_tree_unlock(right);
30595f39d397SChris Mason 		free_extent_buffer(right);
306000ec4c51SChris Mason 	}
306100ec4c51SChris Mason 	return 0;
3062925baeddSChris Mason 
3063925baeddSChris Mason out_unlock:
3064925baeddSChris Mason 	btrfs_tree_unlock(right);
3065925baeddSChris Mason 	free_extent_buffer(right);
3066925baeddSChris Mason 	return 1;
306700ec4c51SChris Mason }
3068925baeddSChris Mason 
306900ec4c51SChris Mason /*
307044871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
307174123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
307244871b1bSChris Mason  *
307344871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
307444871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
307599d8f83cSChris Mason  *
307699d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
307799d8f83cSChris Mason  * push any slot lower than min_slot
307874123bd7SChris Mason  */
307944871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
308099d8f83cSChris Mason 			   *root, struct btrfs_path *path,
308199d8f83cSChris Mason 			   int min_data_size, int data_size,
308299d8f83cSChris Mason 			   int empty, u32 min_slot)
3083be0e5c09SChris Mason {
308444871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
308544871b1bSChris Mason 	struct extent_buffer *right;
308644871b1bSChris Mason 	struct extent_buffer *upper;
308744871b1bSChris Mason 	int slot;
308844871b1bSChris Mason 	int free_space;
308944871b1bSChris Mason 	u32 left_nritems;
309044871b1bSChris Mason 	int ret;
309144871b1bSChris Mason 
309244871b1bSChris Mason 	if (!path->nodes[1])
309344871b1bSChris Mason 		return 1;
309444871b1bSChris Mason 
309544871b1bSChris Mason 	slot = path->slots[1];
309644871b1bSChris Mason 	upper = path->nodes[1];
309744871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
309844871b1bSChris Mason 		return 1;
309944871b1bSChris Mason 
310049d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
310144871b1bSChris Mason 
31024b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3103fb770ae4SLiu Bo 	/*
3104fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3105fb770ae4SLiu Bo 	 * no big deal, just return.
3106fb770ae4SLiu Bo 	 */
3107fb770ae4SLiu Bo 	if (IS_ERR(right))
310891ca338dSTsutomu Itoh 		return 1;
310991ca338dSTsutomu Itoh 
3110bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
311144871b1bSChris Mason 
3112e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
311344871b1bSChris Mason 	if (free_space < data_size)
311444871b1bSChris Mason 		goto out_unlock;
311544871b1bSChris Mason 
311644871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3117bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
311844871b1bSChris Mason 	if (ret)
311944871b1bSChris Mason 		goto out_unlock;
312044871b1bSChris Mason 
312144871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
312244871b1bSChris Mason 	if (left_nritems == 0)
312344871b1bSChris Mason 		goto out_unlock;
312444871b1bSChris Mason 
3125d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3126d16c702fSQu Wenruo 		ret = -EUCLEAN;
3127d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3128d16c702fSQu Wenruo 		free_extent_buffer(right);
3129d16c702fSQu Wenruo 		return ret;
3130d16c702fSQu Wenruo 	}
31312ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
31322ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
31332ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
31342ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
313552042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
31362ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
31372ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
31382ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
31392ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
31402ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
31412ef1fed2SFilipe David Borba Manana 		return 0;
31422ef1fed2SFilipe David Borba Manana 	}
31432ef1fed2SFilipe David Borba Manana 
3144f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
314599d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
314644871b1bSChris Mason out_unlock:
314744871b1bSChris Mason 	btrfs_tree_unlock(right);
314844871b1bSChris Mason 	free_extent_buffer(right);
314944871b1bSChris Mason 	return 1;
315044871b1bSChris Mason }
315144871b1bSChris Mason 
315244871b1bSChris Mason /*
315344871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
315444871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
315599d8f83cSChris Mason  *
315699d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
315799d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
315899d8f83cSChris Mason  * items
315944871b1bSChris Mason  */
31608087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
316144871b1bSChris Mason 				     int empty, struct extent_buffer *left,
316299d8f83cSChris Mason 				     int free_space, u32 right_nritems,
316399d8f83cSChris Mason 				     u32 max_slot)
316444871b1bSChris Mason {
31658087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
31665f39d397SChris Mason 	struct btrfs_disk_key disk_key;
31675f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3168be0e5c09SChris Mason 	int i;
3169be0e5c09SChris Mason 	int push_space = 0;
3170be0e5c09SChris Mason 	int push_items = 0;
31717518a238SChris Mason 	u32 old_left_nritems;
317234a38218SChris Mason 	u32 nr;
3173aa5d6bedSChris Mason 	int ret = 0;
3174db94535dSChris Mason 	u32 this_item_size;
3175db94535dSChris Mason 	u32 old_left_item_size;
3176cfed81a0SChris Mason 	struct btrfs_map_token token;
3177cfed81a0SChris Mason 
317834a38218SChris Mason 	if (empty)
317999d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
318034a38218SChris Mason 	else
318199d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
318234a38218SChris Mason 
318334a38218SChris Mason 	for (i = 0; i < nr; i++) {
318431840ae1SZheng Yan 		if (!empty && push_items > 0) {
318531840ae1SZheng Yan 			if (path->slots[0] < i)
318631840ae1SZheng Yan 				break;
318731840ae1SZheng Yan 			if (path->slots[0] == i) {
3188e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3189e902baacSDavid Sterba 
319031840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
319131840ae1SZheng Yan 					break;
319231840ae1SZheng Yan 			}
319331840ae1SZheng Yan 		}
319431840ae1SZheng Yan 
3195be0e5c09SChris Mason 		if (path->slots[0] == i)
319687b29b20SYan Zheng 			push_space += data_size;
3197db94535dSChris Mason 
31983212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
319974794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
320074794207SJosef Bacik 		    free_space)
3201be0e5c09SChris Mason 			break;
3202db94535dSChris Mason 
3203be0e5c09SChris Mason 		push_items++;
320474794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3205be0e5c09SChris Mason 	}
3206db94535dSChris Mason 
3207be0e5c09SChris Mason 	if (push_items == 0) {
3208925baeddSChris Mason 		ret = 1;
3209925baeddSChris Mason 		goto out;
3210be0e5c09SChris Mason 	}
3211fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
32125f39d397SChris Mason 
3213be0e5c09SChris Mason 	/* push data from right to left */
32145f39d397SChris Mason 	copy_extent_buffer(left, right,
32155f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
32165f39d397SChris Mason 			   btrfs_item_nr_offset(0),
32175f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
32185f39d397SChris Mason 
32190b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
32203212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
32215f39d397SChris Mason 
32223d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
32238f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
32243d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
32253212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1),
3226be0e5c09SChris Mason 		     push_space);
32275f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
322887b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3229eb60ceacSChris Mason 
3230c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
32313212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3232be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
32335f39d397SChris Mason 		u32 ioff;
3234db94535dSChris Mason 
32353212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
32363212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3237cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3238be0e5c09SChris Mason 	}
32395f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3240be0e5c09SChris Mason 
3241be0e5c09SChris Mason 	/* fixup right node */
324231b1a2bdSJulia Lawall 	if (push_items > right_nritems)
324331b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3244d397712bSChris Mason 		       right_nritems);
324534a38218SChris Mason 
324634a38218SChris Mason 	if (push_items < right_nritems) {
32473212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
32488f881e8cSDavid Sterba 						  leaf_data_end(right);
32493d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
32500b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
32513d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
32528f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
32535f39d397SChris Mason 
32545f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
32555f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
32565f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
32570783fcfcSChris Mason 			     sizeof(struct btrfs_item));
325834a38218SChris Mason 	}
3259c82f823cSDavid Sterba 
3260c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3261eef1c494SYan 	right_nritems -= push_items;
3262eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
32630b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
32645f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
32653212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
32663212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3267db94535dSChris Mason 	}
3268eb60ceacSChris Mason 
32695f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
327034a38218SChris Mason 	if (right_nritems)
32715f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3272f0486c68SYan, Zheng 	else
32736a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3274098f59c2SChris Mason 
32755f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3276b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3277be0e5c09SChris Mason 
3278be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3279be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3280be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3281925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32825f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32835f39d397SChris Mason 		path->nodes[0] = left;
3284be0e5c09SChris Mason 		path->slots[1] -= 1;
3285be0e5c09SChris Mason 	} else {
3286925baeddSChris Mason 		btrfs_tree_unlock(left);
32875f39d397SChris Mason 		free_extent_buffer(left);
3288be0e5c09SChris Mason 		path->slots[0] -= push_items;
3289be0e5c09SChris Mason 	}
3290eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3291aa5d6bedSChris Mason 	return ret;
3292925baeddSChris Mason out:
3293925baeddSChris Mason 	btrfs_tree_unlock(left);
3294925baeddSChris Mason 	free_extent_buffer(left);
3295925baeddSChris Mason 	return ret;
3296be0e5c09SChris Mason }
3297be0e5c09SChris Mason 
329874123bd7SChris Mason /*
329944871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
330044871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
330199d8f83cSChris Mason  *
330299d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
330399d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
330499d8f83cSChris Mason  * items
330544871b1bSChris Mason  */
330644871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
330799d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
330899d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
330944871b1bSChris Mason {
331044871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
331144871b1bSChris Mason 	struct extent_buffer *left;
331244871b1bSChris Mason 	int slot;
331344871b1bSChris Mason 	int free_space;
331444871b1bSChris Mason 	u32 right_nritems;
331544871b1bSChris Mason 	int ret = 0;
331644871b1bSChris Mason 
331744871b1bSChris Mason 	slot = path->slots[1];
331844871b1bSChris Mason 	if (slot == 0)
331944871b1bSChris Mason 		return 1;
332044871b1bSChris Mason 	if (!path->nodes[1])
332144871b1bSChris Mason 		return 1;
332244871b1bSChris Mason 
332344871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
332444871b1bSChris Mason 	if (right_nritems == 0)
332544871b1bSChris Mason 		return 1;
332644871b1bSChris Mason 
332749d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
332844871b1bSChris Mason 
33294b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3330fb770ae4SLiu Bo 	/*
3331fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3332fb770ae4SLiu Bo 	 * no big deal, just return.
3333fb770ae4SLiu Bo 	 */
3334fb770ae4SLiu Bo 	if (IS_ERR(left))
333591ca338dSTsutomu Itoh 		return 1;
333691ca338dSTsutomu Itoh 
3337bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
333844871b1bSChris Mason 
3339e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
334044871b1bSChris Mason 	if (free_space < data_size) {
334144871b1bSChris Mason 		ret = 1;
334244871b1bSChris Mason 		goto out;
334344871b1bSChris Mason 	}
334444871b1bSChris Mason 
334544871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
33469631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3347bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
334844871b1bSChris Mason 	if (ret) {
334944871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
335079787eaaSJeff Mahoney 		if (ret == -ENOSPC)
335144871b1bSChris Mason 			ret = 1;
335244871b1bSChris Mason 		goto out;
335344871b1bSChris Mason 	}
335444871b1bSChris Mason 
3355d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3356d16c702fSQu Wenruo 		ret = -EUCLEAN;
3357d16c702fSQu Wenruo 		goto out;
3358d16c702fSQu Wenruo 	}
33598087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
336099d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
336199d8f83cSChris Mason 			       max_slot);
336244871b1bSChris Mason out:
336344871b1bSChris Mason 	btrfs_tree_unlock(left);
336444871b1bSChris Mason 	free_extent_buffer(left);
336544871b1bSChris Mason 	return ret;
336644871b1bSChris Mason }
336744871b1bSChris Mason 
336844871b1bSChris Mason /*
336974123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
337074123bd7SChris Mason  * available for the resulting leaf level of the path.
337174123bd7SChris Mason  */
3372143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
337344871b1bSChris Mason 				    struct btrfs_path *path,
337444871b1bSChris Mason 				    struct extent_buffer *l,
337544871b1bSChris Mason 				    struct extent_buffer *right,
337644871b1bSChris Mason 				    int slot, int mid, int nritems)
3377be0e5c09SChris Mason {
337894f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3379be0e5c09SChris Mason 	int data_copy_size;
3380be0e5c09SChris Mason 	int rt_data_off;
3381be0e5c09SChris Mason 	int i;
3382d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3383cfed81a0SChris Mason 	struct btrfs_map_token token;
3384cfed81a0SChris Mason 
33855f39d397SChris Mason 	nritems = nritems - mid;
33865f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3387dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
33885f39d397SChris Mason 
33895f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
33905f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
33915f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
33925f39d397SChris Mason 
33935f39d397SChris Mason 	copy_extent_buffer(right, l,
33943d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
33953d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
33968f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
339774123bd7SChris Mason 
3398dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
33995f39d397SChris Mason 
3400c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
34015f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3402db94535dSChris Mason 		u32 ioff;
3403db94535dSChris Mason 
34043212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
34053212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
34060783fcfcSChris Mason 	}
340774123bd7SChris Mason 
34085f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
34095f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
34106ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
34115f39d397SChris Mason 
34125f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
34135f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3414eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
34155f39d397SChris Mason 
3416be0e5c09SChris Mason 	if (mid <= slot) {
3417925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
34185f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
34195f39d397SChris Mason 		path->nodes[0] = right;
3420be0e5c09SChris Mason 		path->slots[0] -= mid;
3421be0e5c09SChris Mason 		path->slots[1] += 1;
3422925baeddSChris Mason 	} else {
3423925baeddSChris Mason 		btrfs_tree_unlock(right);
34245f39d397SChris Mason 		free_extent_buffer(right);
3425925baeddSChris Mason 	}
34265f39d397SChris Mason 
3427eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
342844871b1bSChris Mason }
342944871b1bSChris Mason 
343044871b1bSChris Mason /*
343199d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
343299d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
343399d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
343499d8f83cSChris Mason  *          A                 B                 C
343599d8f83cSChris Mason  *
343699d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
343799d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
343899d8f83cSChris Mason  * completely.
343999d8f83cSChris Mason  */
344099d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
344199d8f83cSChris Mason 					  struct btrfs_root *root,
344299d8f83cSChris Mason 					  struct btrfs_path *path,
344399d8f83cSChris Mason 					  int data_size)
344499d8f83cSChris Mason {
344599d8f83cSChris Mason 	int ret;
344699d8f83cSChris Mason 	int progress = 0;
344799d8f83cSChris Mason 	int slot;
344899d8f83cSChris Mason 	u32 nritems;
34495a4267caSFilipe David Borba Manana 	int space_needed = data_size;
345099d8f83cSChris Mason 
345199d8f83cSChris Mason 	slot = path->slots[0];
34525a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3453e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
345499d8f83cSChris Mason 
345599d8f83cSChris Mason 	/*
345699d8f83cSChris Mason 	 * try to push all the items after our slot into the
345799d8f83cSChris Mason 	 * right leaf
345899d8f83cSChris Mason 	 */
34595a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
346099d8f83cSChris Mason 	if (ret < 0)
346199d8f83cSChris Mason 		return ret;
346299d8f83cSChris Mason 
346399d8f83cSChris Mason 	if (ret == 0)
346499d8f83cSChris Mason 		progress++;
346599d8f83cSChris Mason 
346699d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
346799d8f83cSChris Mason 	/*
346899d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
346999d8f83cSChris Mason 	 * we've done so we're done
347099d8f83cSChris Mason 	 */
347199d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
347299d8f83cSChris Mason 		return 0;
347399d8f83cSChris Mason 
3474e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
347599d8f83cSChris Mason 		return 0;
347699d8f83cSChris Mason 
347799d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
347899d8f83cSChris Mason 	slot = path->slots[0];
3479263d3995SFilipe Manana 	space_needed = data_size;
3480263d3995SFilipe Manana 	if (slot > 0)
3481e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
34825a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
348399d8f83cSChris Mason 	if (ret < 0)
348499d8f83cSChris Mason 		return ret;
348599d8f83cSChris Mason 
348699d8f83cSChris Mason 	if (ret == 0)
348799d8f83cSChris Mason 		progress++;
348899d8f83cSChris Mason 
348999d8f83cSChris Mason 	if (progress)
349099d8f83cSChris Mason 		return 0;
349199d8f83cSChris Mason 	return 1;
349299d8f83cSChris Mason }
349399d8f83cSChris Mason 
349499d8f83cSChris Mason /*
349544871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
349644871b1bSChris Mason  * available for the resulting leaf level of the path.
349744871b1bSChris Mason  *
349844871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
349944871b1bSChris Mason  */
350044871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
350144871b1bSChris Mason 			       struct btrfs_root *root,
3502310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
350344871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
350444871b1bSChris Mason 			       int extend)
350544871b1bSChris Mason {
35065d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
350744871b1bSChris Mason 	struct extent_buffer *l;
350844871b1bSChris Mason 	u32 nritems;
350944871b1bSChris Mason 	int mid;
351044871b1bSChris Mason 	int slot;
351144871b1bSChris Mason 	struct extent_buffer *right;
3512b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
351344871b1bSChris Mason 	int ret = 0;
351444871b1bSChris Mason 	int wret;
35155d4f98a2SYan Zheng 	int split;
351644871b1bSChris Mason 	int num_doubles = 0;
351799d8f83cSChris Mason 	int tried_avoid_double = 0;
351844871b1bSChris Mason 
3519a5719521SYan, Zheng 	l = path->nodes[0];
3520a5719521SYan, Zheng 	slot = path->slots[0];
35213212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
35220b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3523a5719521SYan, Zheng 		return -EOVERFLOW;
3524a5719521SYan, Zheng 
352544871b1bSChris Mason 	/* first try to make some room by pushing left and right */
352633157e05SLiu Bo 	if (data_size && path->nodes[1]) {
35275a4267caSFilipe David Borba Manana 		int space_needed = data_size;
35285a4267caSFilipe David Borba Manana 
35295a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3530e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
35315a4267caSFilipe David Borba Manana 
35325a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
35335a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
353444871b1bSChris Mason 		if (wret < 0)
353544871b1bSChris Mason 			return wret;
353644871b1bSChris Mason 		if (wret) {
3537263d3995SFilipe Manana 			space_needed = data_size;
3538263d3995SFilipe Manana 			if (slot > 0)
3539e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
35405a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
35415a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
354244871b1bSChris Mason 			if (wret < 0)
354344871b1bSChris Mason 				return wret;
354444871b1bSChris Mason 		}
354544871b1bSChris Mason 		l = path->nodes[0];
354644871b1bSChris Mason 
354744871b1bSChris Mason 		/* did the pushes work? */
3548e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
354944871b1bSChris Mason 			return 0;
355044871b1bSChris Mason 	}
355144871b1bSChris Mason 
355244871b1bSChris Mason 	if (!path->nodes[1]) {
3553fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
355444871b1bSChris Mason 		if (ret)
355544871b1bSChris Mason 			return ret;
355644871b1bSChris Mason 	}
355744871b1bSChris Mason again:
35585d4f98a2SYan Zheng 	split = 1;
355944871b1bSChris Mason 	l = path->nodes[0];
356044871b1bSChris Mason 	slot = path->slots[0];
356144871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
356244871b1bSChris Mason 	mid = (nritems + 1) / 2;
356344871b1bSChris Mason 
35645d4f98a2SYan Zheng 	if (mid <= slot) {
35655d4f98a2SYan Zheng 		if (nritems == 1 ||
35665d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
35670b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
35685d4f98a2SYan Zheng 			if (slot >= nritems) {
35695d4f98a2SYan Zheng 				split = 0;
35705d4f98a2SYan Zheng 			} else {
35715d4f98a2SYan Zheng 				mid = slot;
35725d4f98a2SYan Zheng 				if (mid != nritems &&
35735d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
35740b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
357599d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
357699d8f83cSChris Mason 						goto push_for_double;
35775d4f98a2SYan Zheng 					split = 2;
35785d4f98a2SYan Zheng 				}
35795d4f98a2SYan Zheng 			}
35805d4f98a2SYan Zheng 		}
35815d4f98a2SYan Zheng 	} else {
35825d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
35830b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
35845d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
35855d4f98a2SYan Zheng 				split = 0;
35865d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
35875d4f98a2SYan Zheng 				mid = 1;
35885d4f98a2SYan Zheng 			} else {
35895d4f98a2SYan Zheng 				mid = slot;
35905d4f98a2SYan Zheng 				if (mid != nritems &&
35915d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
35920b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
359399d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
359499d8f83cSChris Mason 						goto push_for_double;
35955d4f98a2SYan Zheng 					split = 2;
35965d4f98a2SYan Zheng 				}
35975d4f98a2SYan Zheng 			}
35985d4f98a2SYan Zheng 		}
35995d4f98a2SYan Zheng 	}
36005d4f98a2SYan Zheng 
36015d4f98a2SYan Zheng 	if (split == 0)
36025d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
36035d4f98a2SYan Zheng 	else
36045d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
36055d4f98a2SYan Zheng 
3606ca9d473aSJosef Bacik 	/*
3607ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3608ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3609ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3610ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3611ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3612ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3613ca9d473aSJosef Bacik 	 */
361479bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
361579bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
361679bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3617ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3618f0486c68SYan, Zheng 	if (IS_ERR(right))
361944871b1bSChris Mason 		return PTR_ERR(right);
3620f0486c68SYan, Zheng 
36210b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
362244871b1bSChris Mason 
36235d4f98a2SYan Zheng 	if (split == 0) {
362444871b1bSChris Mason 		if (mid <= slot) {
362544871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
36266ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
36272ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
362844871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
362944871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
363044871b1bSChris Mason 			path->nodes[0] = right;
363144871b1bSChris Mason 			path->slots[0] = 0;
363244871b1bSChris Mason 			path->slots[1] += 1;
363344871b1bSChris Mason 		} else {
363444871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
36356ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
36362ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
363744871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
363844871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
363944871b1bSChris Mason 			path->nodes[0] = right;
364044871b1bSChris Mason 			path->slots[0] = 0;
3641143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3642b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
36435d4f98a2SYan Zheng 		}
3644196e0249SLiu Bo 		/*
3645196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3646196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3647196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3648196e0249SLiu Bo 		 */
364944871b1bSChris Mason 		return ret;
365044871b1bSChris Mason 	}
365144871b1bSChris Mason 
365294f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
365344871b1bSChris Mason 
36545d4f98a2SYan Zheng 	if (split == 2) {
3655cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3656cc0c5538SChris Mason 		num_doubles++;
3657cc0c5538SChris Mason 		goto again;
36583326d1b0SChris Mason 	}
365944871b1bSChris Mason 
3660143bede5SJeff Mahoney 	return 0;
366199d8f83cSChris Mason 
366299d8f83cSChris Mason push_for_double:
366399d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
366499d8f83cSChris Mason 	tried_avoid_double = 1;
3665e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
366699d8f83cSChris Mason 		return 0;
366799d8f83cSChris Mason 	goto again;
3668be0e5c09SChris Mason }
3669be0e5c09SChris Mason 
3670ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3671ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3672ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3673ad48fd75SYan, Zheng {
3674ad48fd75SYan, Zheng 	struct btrfs_key key;
3675ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3676ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3677ad48fd75SYan, Zheng 	u64 extent_len = 0;
3678ad48fd75SYan, Zheng 	u32 item_size;
3679ad48fd75SYan, Zheng 	int ret;
3680ad48fd75SYan, Zheng 
3681ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3682ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3683ad48fd75SYan, Zheng 
3684ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3685ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3686ad48fd75SYan, Zheng 
3687e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3688ad48fd75SYan, Zheng 		return 0;
3689ad48fd75SYan, Zheng 
36903212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3691ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3692ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3693ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3694ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3695ad48fd75SYan, Zheng 	}
3696b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3697ad48fd75SYan, Zheng 
3698ad48fd75SYan, Zheng 	path->keep_locks = 1;
3699ad48fd75SYan, Zheng 	path->search_for_split = 1;
3700ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3701ad48fd75SYan, Zheng 	path->search_for_split = 0;
3702a8df6fe6SFilipe Manana 	if (ret > 0)
3703a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3704ad48fd75SYan, Zheng 	if (ret < 0)
3705ad48fd75SYan, Zheng 		goto err;
3706ad48fd75SYan, Zheng 
3707ad48fd75SYan, Zheng 	ret = -EAGAIN;
3708ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3709a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
37103212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3711ad48fd75SYan, Zheng 		goto err;
3712ad48fd75SYan, Zheng 
3713109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3714e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3715109f6aefSChris Mason 		goto err;
3716109f6aefSChris Mason 
3717ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3718ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3719ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3720ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3721ad48fd75SYan, Zheng 			goto err;
3722ad48fd75SYan, Zheng 	}
3723ad48fd75SYan, Zheng 
3724ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3725f0486c68SYan, Zheng 	if (ret)
3726f0486c68SYan, Zheng 		goto err;
3727ad48fd75SYan, Zheng 
3728ad48fd75SYan, Zheng 	path->keep_locks = 0;
3729ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3730ad48fd75SYan, Zheng 	return 0;
3731ad48fd75SYan, Zheng err:
3732ad48fd75SYan, Zheng 	path->keep_locks = 0;
3733ad48fd75SYan, Zheng 	return ret;
3734ad48fd75SYan, Zheng }
3735ad48fd75SYan, Zheng 
373625263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3737310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3738459931ecSChris Mason 			       unsigned long split_offset)
3739459931ecSChris Mason {
3740459931ecSChris Mason 	struct extent_buffer *leaf;
3741c91666b1SJosef Bacik 	int orig_slot, slot;
3742ad48fd75SYan, Zheng 	char *buf;
3743459931ecSChris Mason 	u32 nritems;
3744ad48fd75SYan, Zheng 	u32 item_size;
3745459931ecSChris Mason 	u32 orig_offset;
3746459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3747459931ecSChris Mason 
3748459931ecSChris Mason 	leaf = path->nodes[0];
3749e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3750b9473439SChris Mason 
3751c91666b1SJosef Bacik 	orig_slot = path->slots[0];
37523212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
37533212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3754459931ecSChris Mason 
3755459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3756ad48fd75SYan, Zheng 	if (!buf)
3757ad48fd75SYan, Zheng 		return -ENOMEM;
3758ad48fd75SYan, Zheng 
3759459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3760459931ecSChris Mason 			    path->slots[0]), item_size);
3761ad48fd75SYan, Zheng 
3762459931ecSChris Mason 	slot = path->slots[0] + 1;
3763459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3764459931ecSChris Mason 	if (slot != nritems) {
3765459931ecSChris Mason 		/* shift the items */
3766459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3767459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3768459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3769459931ecSChris Mason 	}
3770459931ecSChris Mason 
3771459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3772459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3773459931ecSChris Mason 
37743212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
37753212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3776459931ecSChris Mason 
37773212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
3778459931ecSChris Mason 				 orig_offset + item_size - split_offset);
37793212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3780459931ecSChris Mason 
3781459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3782459931ecSChris Mason 
3783459931ecSChris Mason 	/* write the data for the start of the original item */
3784459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3785459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3786459931ecSChris Mason 			    split_offset);
3787459931ecSChris Mason 
3788459931ecSChris Mason 	/* write the data for the new item */
3789459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3790459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3791459931ecSChris Mason 			    item_size - split_offset);
3792459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3793459931ecSChris Mason 
3794e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3795459931ecSChris Mason 	kfree(buf);
3796ad48fd75SYan, Zheng 	return 0;
3797ad48fd75SYan, Zheng }
3798ad48fd75SYan, Zheng 
3799ad48fd75SYan, Zheng /*
3800ad48fd75SYan, Zheng  * This function splits a single item into two items,
3801ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3802ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3803ad48fd75SYan, Zheng  *
3804ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3805ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3806ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3807ad48fd75SYan, Zheng  *
3808ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3809ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3810ad48fd75SYan, Zheng  *
3811ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3812ad48fd75SYan, Zheng  * leaf the entire time.
3813ad48fd75SYan, Zheng  */
3814ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3815ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3816ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3817310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3818ad48fd75SYan, Zheng 		     unsigned long split_offset)
3819ad48fd75SYan, Zheng {
3820ad48fd75SYan, Zheng 	int ret;
3821ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3822ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3823ad48fd75SYan, Zheng 	if (ret)
3824459931ecSChris Mason 		return ret;
3825ad48fd75SYan, Zheng 
382625263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3827ad48fd75SYan, Zheng 	return ret;
3828ad48fd75SYan, Zheng }
3829ad48fd75SYan, Zheng 
3830ad48fd75SYan, Zheng /*
3831d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
3832d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
3833d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
3834d352ac68SChris Mason  * the front.
3835d352ac68SChris Mason  */
383678ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3837b18c6685SChris Mason {
3838b18c6685SChris Mason 	int slot;
38395f39d397SChris Mason 	struct extent_buffer *leaf;
3840b18c6685SChris Mason 	u32 nritems;
3841b18c6685SChris Mason 	unsigned int data_end;
3842b18c6685SChris Mason 	unsigned int old_data_start;
3843b18c6685SChris Mason 	unsigned int old_size;
3844b18c6685SChris Mason 	unsigned int size_diff;
3845b18c6685SChris Mason 	int i;
3846cfed81a0SChris Mason 	struct btrfs_map_token token;
3847cfed81a0SChris Mason 
38485f39d397SChris Mason 	leaf = path->nodes[0];
3849179e29e4SChris Mason 	slot = path->slots[0];
3850179e29e4SChris Mason 
38513212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
3852179e29e4SChris Mason 	if (old_size == new_size)
3853143bede5SJeff Mahoney 		return;
3854b18c6685SChris Mason 
38555f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
38568f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3857b18c6685SChris Mason 
38583212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
3859179e29e4SChris Mason 
3860b18c6685SChris Mason 	size_diff = old_size - new_size;
3861b18c6685SChris Mason 
3862b18c6685SChris Mason 	BUG_ON(slot < 0);
3863b18c6685SChris Mason 	BUG_ON(slot >= nritems);
3864b18c6685SChris Mason 
3865b18c6685SChris Mason 	/*
3866b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3867b18c6685SChris Mason 	 */
3868b18c6685SChris Mason 	/* first correct the data pointers */
3869c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3870b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
38715f39d397SChris Mason 		u32 ioff;
3872db94535dSChris Mason 
38733212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
38743212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3875b18c6685SChris Mason 	}
3876db94535dSChris Mason 
3877b18c6685SChris Mason 	/* shift the data */
3878179e29e4SChris Mason 	if (from_end) {
38793d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
38803d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3881b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
3882179e29e4SChris Mason 	} else {
3883179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
3884179e29e4SChris Mason 		u64 offset;
3885179e29e4SChris Mason 
3886179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
3887179e29e4SChris Mason 
3888179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3889179e29e4SChris Mason 			unsigned long ptr;
3890179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
3891179e29e4SChris Mason 
3892179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
3893179e29e4SChris Mason 					    struct btrfs_file_extent_item);
3894179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
3895179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
3896179e29e4SChris Mason 
3897179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
3898179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
3899179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
3900179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
3901179e29e4SChris Mason 				      (unsigned long)fi,
39027ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
3903179e29e4SChris Mason 			}
3904179e29e4SChris Mason 		}
3905179e29e4SChris Mason 
39063d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
39073d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3908179e29e4SChris Mason 			      data_end, old_data_start - data_end);
3909179e29e4SChris Mason 
3910179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
3911179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3912179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
3913179e29e4SChris Mason 		if (slot == 0)
3914b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
3915179e29e4SChris Mason 	}
39165f39d397SChris Mason 
39173212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
39185f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3919b18c6685SChris Mason 
3920e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3921a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3922b18c6685SChris Mason 		BUG();
39235f39d397SChris Mason 	}
3924b18c6685SChris Mason }
3925b18c6685SChris Mason 
3926d352ac68SChris Mason /*
39278f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
3928d352ac68SChris Mason  */
3929c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
39306567e837SChris Mason {
39316567e837SChris Mason 	int slot;
39325f39d397SChris Mason 	struct extent_buffer *leaf;
39336567e837SChris Mason 	u32 nritems;
39346567e837SChris Mason 	unsigned int data_end;
39356567e837SChris Mason 	unsigned int old_data;
39366567e837SChris Mason 	unsigned int old_size;
39376567e837SChris Mason 	int i;
3938cfed81a0SChris Mason 	struct btrfs_map_token token;
3939cfed81a0SChris Mason 
39405f39d397SChris Mason 	leaf = path->nodes[0];
39416567e837SChris Mason 
39425f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
39438f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
39446567e837SChris Mason 
3945e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
3946a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39476567e837SChris Mason 		BUG();
39485f39d397SChris Mason 	}
39496567e837SChris Mason 	slot = path->slots[0];
3950dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
39516567e837SChris Mason 
39526567e837SChris Mason 	BUG_ON(slot < 0);
39533326d1b0SChris Mason 	if (slot >= nritems) {
3954a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3955c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
3956d397712bSChris Mason 			   slot, nritems);
3957290342f6SArnd Bergmann 		BUG();
39583326d1b0SChris Mason 	}
39596567e837SChris Mason 
39606567e837SChris Mason 	/*
39616567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
39626567e837SChris Mason 	 */
39636567e837SChris Mason 	/* first correct the data pointers */
3964c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
39656567e837SChris Mason 	for (i = slot; i < nritems; i++) {
39665f39d397SChris Mason 		u32 ioff;
3967db94535dSChris Mason 
39683212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
39693212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
39706567e837SChris Mason 	}
39715f39d397SChris Mason 
39726567e837SChris Mason 	/* shift the data */
39733d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
39743d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
39756567e837SChris Mason 		      data_end, old_data - data_end);
39765f39d397SChris Mason 
39776567e837SChris Mason 	data_end = old_data;
39783212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
39793212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
39805f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
39816567e837SChris Mason 
3982e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3983a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39846567e837SChris Mason 		BUG();
39855f39d397SChris Mason 	}
39866567e837SChris Mason }
39876567e837SChris Mason 
3988*43dd529aSDavid Sterba /*
3989*43dd529aSDavid Sterba  * Make space in the node before inserting one or more items.
3990da9ffb24SNikolay Borisov  *
3991da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
3992da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
3993b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
3994*43dd529aSDavid Sterba  *
3995*43dd529aSDavid Sterba  * Main purpose is to save stack depth by doing the bulk of the work in a
3996*43dd529aSDavid Sterba  * function that doesn't call btrfs_search_slot
399774123bd7SChris Mason  */
3998f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
3999b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
4000be0e5c09SChris Mason {
40010b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
40029c58309dSChris Mason 	int i;
40037518a238SChris Mason 	u32 nritems;
4004be0e5c09SChris Mason 	unsigned int data_end;
4005e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
400644871b1bSChris Mason 	struct extent_buffer *leaf;
400744871b1bSChris Mason 	int slot;
4008cfed81a0SChris Mason 	struct btrfs_map_token token;
4009fc0d82e1SNikolay Borisov 	u32 total_size;
4010fc0d82e1SNikolay Borisov 
4011b7ef5f3aSFilipe Manana 	/*
4012b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
4013b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
4014b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
4015b7ef5f3aSFilipe Manana 	 */
401624cdc847SFilipe Manana 	if (path->slots[0] == 0) {
4017b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4018b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
401924cdc847SFilipe Manana 	}
402024cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
402124cdc847SFilipe Manana 
40225f39d397SChris Mason 	leaf = path->nodes[0];
402344871b1bSChris Mason 	slot = path->slots[0];
402474123bd7SChris Mason 
40255f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
40268f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4027b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4028eb60ceacSChris Mason 
4029e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4030a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
40310b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4032e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4033be0e5c09SChris Mason 		BUG();
4034d4dbff95SChris Mason 	}
40355f39d397SChris Mason 
4036c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4037be0e5c09SChris Mason 	if (slot != nritems) {
4038dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4039be0e5c09SChris Mason 
40405f39d397SChris Mason 		if (old_data < data_end) {
4041a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
40427269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
40437269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
40445f39d397SChris Mason 				   slot, old_data, data_end);
4045290342f6SArnd Bergmann 			BUG();
40465f39d397SChris Mason 		}
4047be0e5c09SChris Mason 		/*
4048be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4049be0e5c09SChris Mason 		 */
4050be0e5c09SChris Mason 		/* first correct the data pointers */
40510783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
40525f39d397SChris Mason 			u32 ioff;
4053db94535dSChris Mason 
40543212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
40553212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
4056b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
40570783fcfcSChris Mason 		}
4058be0e5c09SChris Mason 		/* shift the items */
4059b7ef5f3aSFilipe Manana 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + batch->nr),
40605f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
40610783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4062be0e5c09SChris Mason 
4063be0e5c09SChris Mason 		/* shift the data */
40643d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4065b7ef5f3aSFilipe Manana 				      data_end - batch->total_data_size,
4066b7ef5f3aSFilipe Manana 				      BTRFS_LEAF_DATA_OFFSET + data_end,
4067b7ef5f3aSFilipe Manana 				      old_data - data_end);
4068be0e5c09SChris Mason 		data_end = old_data;
4069be0e5c09SChris Mason 	}
40705f39d397SChris Mason 
407162e2749eSChris Mason 	/* setup the item for the new data */
4072b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
4073b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
40749c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4075b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
40763212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
40773212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
40789c58309dSChris Mason 	}
407944871b1bSChris Mason 
4080b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4081b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4082aa5d6bedSChris Mason 
4083e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4084a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4085be0e5c09SChris Mason 		BUG();
40865f39d397SChris Mason 	}
408744871b1bSChris Mason }
408844871b1bSChris Mason 
408944871b1bSChris Mason /*
4090f0641656SFilipe Manana  * Insert a new item into a leaf.
4091f0641656SFilipe Manana  *
4092f0641656SFilipe Manana  * @root:      The root of the btree.
4093f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
4094f0641656SFilipe Manana  * @key:       The key of the new item.
4095f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
4096f0641656SFilipe Manana  */
4097f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
4098f0641656SFilipe Manana 				 struct btrfs_path *path,
4099f0641656SFilipe Manana 				 const struct btrfs_key *key,
4100f0641656SFilipe Manana 				 u32 data_size)
4101f0641656SFilipe Manana {
4102f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4103f0641656SFilipe Manana 
4104f0641656SFilipe Manana 	batch.keys = key;
4105f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4106f0641656SFilipe Manana 	batch.total_data_size = data_size;
4107f0641656SFilipe Manana 	batch.nr = 1;
4108f0641656SFilipe Manana 
4109f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
4110f0641656SFilipe Manana }
4111f0641656SFilipe Manana 
4112f0641656SFilipe Manana /*
411344871b1bSChris Mason  * Given a key and some data, insert items into the tree.
411444871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
411544871b1bSChris Mason  */
411644871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
411744871b1bSChris Mason 			    struct btrfs_root *root,
411844871b1bSChris Mason 			    struct btrfs_path *path,
4119b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
412044871b1bSChris Mason {
412144871b1bSChris Mason 	int ret = 0;
412244871b1bSChris Mason 	int slot;
4123b7ef5f3aSFilipe Manana 	u32 total_size;
412444871b1bSChris Mason 
4125b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4126b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
412744871b1bSChris Mason 	if (ret == 0)
412844871b1bSChris Mason 		return -EEXIST;
412944871b1bSChris Mason 	if (ret < 0)
4130143bede5SJeff Mahoney 		return ret;
413144871b1bSChris Mason 
413244871b1bSChris Mason 	slot = path->slots[0];
413344871b1bSChris Mason 	BUG_ON(slot < 0);
413444871b1bSChris Mason 
4135b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4136143bede5SJeff Mahoney 	return 0;
413762e2749eSChris Mason }
413862e2749eSChris Mason 
413962e2749eSChris Mason /*
414062e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
414162e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
414262e2749eSChris Mason  */
4143310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4144310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4145310712b2SOmar Sandoval 		      u32 data_size)
414662e2749eSChris Mason {
414762e2749eSChris Mason 	int ret = 0;
41482c90e5d6SChris Mason 	struct btrfs_path *path;
41495f39d397SChris Mason 	struct extent_buffer *leaf;
41505f39d397SChris Mason 	unsigned long ptr;
415162e2749eSChris Mason 
41522c90e5d6SChris Mason 	path = btrfs_alloc_path();
4153db5b493aSTsutomu Itoh 	if (!path)
4154db5b493aSTsutomu Itoh 		return -ENOMEM;
41552c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
415662e2749eSChris Mason 	if (!ret) {
41575f39d397SChris Mason 		leaf = path->nodes[0];
41585f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
41595f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
41605f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
416162e2749eSChris Mason 	}
41622c90e5d6SChris Mason 	btrfs_free_path(path);
4163aa5d6bedSChris Mason 	return ret;
4164be0e5c09SChris Mason }
4165be0e5c09SChris Mason 
416674123bd7SChris Mason /*
4167f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4168f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4169f0641656SFilipe Manana  * contiguous with the original item.
4170f0641656SFilipe Manana  *
4171f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4172f0641656SFilipe Manana  * the entire time.
4173f0641656SFilipe Manana  */
4174f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4175f0641656SFilipe Manana 			 struct btrfs_root *root,
4176f0641656SFilipe Manana 			 struct btrfs_path *path,
4177f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4178f0641656SFilipe Manana {
4179f0641656SFilipe Manana 	struct extent_buffer *leaf;
4180f0641656SFilipe Manana 	int ret;
4181f0641656SFilipe Manana 	u32 item_size;
4182f0641656SFilipe Manana 
4183f0641656SFilipe Manana 	leaf = path->nodes[0];
41843212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4185f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4186f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4187f0641656SFilipe Manana 	if (ret)
4188f0641656SFilipe Manana 		return ret;
4189f0641656SFilipe Manana 
4190f0641656SFilipe Manana 	path->slots[0]++;
4191f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4192f0641656SFilipe Manana 	leaf = path->nodes[0];
4193f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4194f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4195f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4196f0641656SFilipe Manana 			     item_size);
4197f0641656SFilipe Manana 	return 0;
4198f0641656SFilipe Manana }
4199f0641656SFilipe Manana 
4200f0641656SFilipe Manana /*
42015de08d7dSChris Mason  * delete the pointer from a given node.
420274123bd7SChris Mason  *
4203d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4204d352ac68SChris Mason  * empty a node.
420574123bd7SChris Mason  */
4206afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4207afe5fea7STsutomu Itoh 		    int level, int slot)
4208be0e5c09SChris Mason {
42095f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
42107518a238SChris Mason 	u32 nritems;
4211f3ea38daSJan Schmidt 	int ret;
4212be0e5c09SChris Mason 
42135f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4214be0e5c09SChris Mason 	if (slot != nritems - 1) {
4215bf1d3425SDavid Sterba 		if (level) {
4216f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4217f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4218bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4219bf1d3425SDavid Sterba 		}
42205f39d397SChris Mason 		memmove_extent_buffer(parent,
42215f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
42225f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4223d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4224d6025579SChris Mason 			      (nritems - slot - 1));
422557ba86c0SChris Mason 	} else if (level) {
4226f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
422733cff222SFilipe Manana 						    BTRFS_MOD_LOG_KEY_REMOVE);
422857ba86c0SChris Mason 		BUG_ON(ret < 0);
4229be0e5c09SChris Mason 	}
4230f3ea38daSJan Schmidt 
42317518a238SChris Mason 	nritems--;
42325f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
42337518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
42345f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4235eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
42365f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4237bb803951SChris Mason 	} else if (slot == 0) {
42385f39d397SChris Mason 		struct btrfs_disk_key disk_key;
42395f39d397SChris Mason 
42405f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4241b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4242be0e5c09SChris Mason 	}
4243d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4244be0e5c09SChris Mason }
4245be0e5c09SChris Mason 
424674123bd7SChris Mason /*
4247323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
42485d4f98a2SYan Zheng  * path->nodes[1].
4249323ac95bSChris Mason  *
4250323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4251323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4252323ac95bSChris Mason  *
4253323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4254323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4255323ac95bSChris Mason  */
4256143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4257323ac95bSChris Mason 				    struct btrfs_root *root,
42585d4f98a2SYan Zheng 				    struct btrfs_path *path,
42595d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4260323ac95bSChris Mason {
42615d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4262afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4263323ac95bSChris Mason 
42644d081c41SChris Mason 	/*
42654d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
42664d081c41SChris Mason 	 * aren't holding any locks when we call it
42674d081c41SChris Mason 	 */
42684d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
42694d081c41SChris Mason 
4270f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4271f0486c68SYan, Zheng 
427267439dadSDavid Sterba 	atomic_inc(&leaf->refs);
42737a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
42743083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4275323ac95bSChris Mason }
4276323ac95bSChris Mason /*
427774123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
427874123bd7SChris Mason  * the leaf, remove it from the tree
427974123bd7SChris Mason  */
428085e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
428185e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4282be0e5c09SChris Mason {
42830b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
42845f39d397SChris Mason 	struct extent_buffer *leaf;
4285aa5d6bedSChris Mason 	int ret = 0;
4286aa5d6bedSChris Mason 	int wret;
42877518a238SChris Mason 	u32 nritems;
4288be0e5c09SChris Mason 
42895f39d397SChris Mason 	leaf = path->nodes[0];
42905f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4291be0e5c09SChris Mason 
429285e21bacSChris Mason 	if (slot + nr != nritems) {
42930cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
42940cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4295c82f823cSDavid Sterba 		struct btrfs_map_token token;
42960cae23b6SFilipe Manana 		u32 dsize = 0;
42970cae23b6SFilipe Manana 		int i;
42980cae23b6SFilipe Manana 
42990cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
43000cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
43015f39d397SChris Mason 
43023d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4303d6025579SChris Mason 			      data_end + dsize,
43043d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
430585e21bacSChris Mason 			      last_off - data_end);
43065f39d397SChris Mason 
4307c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
430885e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
43095f39d397SChris Mason 			u32 ioff;
4310db94535dSChris Mason 
43113212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
43123212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
43130783fcfcSChris Mason 		}
4314db94535dSChris Mason 
43155f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
431685e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
43170783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
431885e21bacSChris Mason 			      (nritems - slot - nr));
4319be0e5c09SChris Mason 	}
432085e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
432185e21bacSChris Mason 	nritems -= nr;
43225f39d397SChris Mason 
432374123bd7SChris Mason 	/* delete the leaf if we've emptied it */
43247518a238SChris Mason 	if (nritems == 0) {
43255f39d397SChris Mason 		if (leaf == root->node) {
43265f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
43279a8dd150SChris Mason 		} else {
43286a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4329143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
43309a8dd150SChris Mason 		}
4331be0e5c09SChris Mason 	} else {
43327518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4333aa5d6bedSChris Mason 		if (slot == 0) {
43345f39d397SChris Mason 			struct btrfs_disk_key disk_key;
43355f39d397SChris Mason 
43365f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4337b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4338aa5d6bedSChris Mason 		}
4339aa5d6bedSChris Mason 
43407c4063d1SFilipe Manana 		/*
43417c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
43427c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
43437c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
43447c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
43457c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
43467c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
43477c4063d1SFilipe Manana 		 */
43480b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
43497c4063d1SFilipe Manana 			u32 min_push_space;
43507c4063d1SFilipe Manana 
4351be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4352be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4353be0e5c09SChris Mason 			 * for possible call to del_ptr below
4354be0e5c09SChris Mason 			 */
43554920c9acSChris Mason 			slot = path->slots[1];
435667439dadSDavid Sterba 			atomic_inc(&leaf->refs);
43577c4063d1SFilipe Manana 			/*
43587c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
43597c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
43607c4063d1SFilipe Manana 			 */
43617c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
43627c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
43637c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
43647c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
436554aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4366aa5d6bedSChris Mason 				ret = wret;
43675f39d397SChris Mason 
43685f39d397SChris Mason 			if (path->nodes[0] == leaf &&
43695f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
43707c4063d1SFilipe Manana 				/*
43717c4063d1SFilipe Manana 				 * If we were not able to push all items from our
43727c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
43737c4063d1SFilipe Manana 				 * either push all the remaining items to the
43747c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
43757c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
43767c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
43777c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
43787c4063d1SFilipe Manana 				 * or nearly full.
43797c4063d1SFilipe Manana 				 */
43807c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
43817c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
43827c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
43837c4063d1SFilipe Manana 						       min_push_space, 1, 0);
438454aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4385aa5d6bedSChris Mason 					ret = wret;
4386aa5d6bedSChris Mason 			}
43875f39d397SChris Mason 
43885f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4389323ac95bSChris Mason 				path->slots[1] = slot;
4390143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
43915f39d397SChris Mason 				free_extent_buffer(leaf);
4392143bede5SJeff Mahoney 				ret = 0;
43935de08d7dSChris Mason 			} else {
4394925baeddSChris Mason 				/* if we're still in the path, make sure
4395925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4396925baeddSChris Mason 				 * push_leaf functions must have already
4397925baeddSChris Mason 				 * dirtied this buffer
4398925baeddSChris Mason 				 */
4399925baeddSChris Mason 				if (path->nodes[0] == leaf)
44005f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
44015f39d397SChris Mason 				free_extent_buffer(leaf);
4402be0e5c09SChris Mason 			}
4403d5719762SChris Mason 		} else {
44045f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4405be0e5c09SChris Mason 		}
44069a8dd150SChris Mason 	}
4407aa5d6bedSChris Mason 	return ret;
44089a8dd150SChris Mason }
44099a8dd150SChris Mason 
441097571fd0SChris Mason /*
4411925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
44127bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
44137bb86316SChris Mason  * returns < 0 on io errors.
4414d352ac68SChris Mason  *
4415d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4416d352ac68SChris Mason  * time you call it.
44177bb86316SChris Mason  */
441816e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
44197bb86316SChris Mason {
4420925baeddSChris Mason 	struct btrfs_key key;
4421925baeddSChris Mason 	struct btrfs_disk_key found_key;
4422925baeddSChris Mason 	int ret;
44237bb86316SChris Mason 
4424925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4425925baeddSChris Mason 
4426e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
4427925baeddSChris Mason 		key.offset--;
4428e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
4429925baeddSChris Mason 		key.type--;
4430e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4431e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
4432925baeddSChris Mason 		key.objectid--;
4433e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
4434e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4435e8b0d724SFilipe David Borba Manana 	} else {
44367bb86316SChris Mason 		return 1;
4437e8b0d724SFilipe David Borba Manana 	}
44387bb86316SChris Mason 
4439b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4440925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4441925baeddSChris Mason 	if (ret < 0)
4442925baeddSChris Mason 		return ret;
4443925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4444925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4445337c6f68SFilipe Manana 	/*
4446337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
4447337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
4448337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
4449337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
4450337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
4451337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
4452337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
4453337c6f68SFilipe Manana 	 * the previous key we computed above.
4454337c6f68SFilipe Manana 	 */
4455337c6f68SFilipe Manana 	if (ret <= 0)
44567bb86316SChris Mason 		return 0;
4457925baeddSChris Mason 	return 1;
44587bb86316SChris Mason }
44597bb86316SChris Mason 
44603f157a2fSChris Mason /*
44613f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4462de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4463de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
44643f157a2fSChris Mason  *
44653f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
44663f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
44673f157a2fSChris Mason  * key and get a writable path.
44683f157a2fSChris Mason  *
44693f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
44703f157a2fSChris Mason  * of the tree.
44713f157a2fSChris Mason  *
4472d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4473d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4474d352ac68SChris Mason  * skipped over (without reading them).
4475d352ac68SChris Mason  *
44763f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
44773f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
44783f157a2fSChris Mason  */
44793f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4480de78b51aSEric Sandeen 			 struct btrfs_path *path,
44813f157a2fSChris Mason 			 u64 min_trans)
44823f157a2fSChris Mason {
44833f157a2fSChris Mason 	struct extent_buffer *cur;
44843f157a2fSChris Mason 	struct btrfs_key found_key;
44853f157a2fSChris Mason 	int slot;
44869652480bSYan 	int sret;
44873f157a2fSChris Mason 	u32 nritems;
44883f157a2fSChris Mason 	int level;
44893f157a2fSChris Mason 	int ret = 1;
4490f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
44913f157a2fSChris Mason 
4492c922b016SStefan Roesch 	ASSERT(!path->nowait);
4493f98de9b9SFilipe Manana 	path->keep_locks = 1;
44943f157a2fSChris Mason again:
4495bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
44963f157a2fSChris Mason 	level = btrfs_header_level(cur);
4497e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
44983f157a2fSChris Mason 	path->nodes[level] = cur;
4499bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
45003f157a2fSChris Mason 
45013f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
45023f157a2fSChris Mason 		ret = 1;
45033f157a2fSChris Mason 		goto out;
45043f157a2fSChris Mason 	}
45053f157a2fSChris Mason 	while (1) {
45063f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
45073f157a2fSChris Mason 		level = btrfs_header_level(cur);
4508e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
4509cbca7d59SFilipe Manana 		if (sret < 0) {
4510cbca7d59SFilipe Manana 			ret = sret;
4511cbca7d59SFilipe Manana 			goto out;
4512cbca7d59SFilipe Manana 		}
45133f157a2fSChris Mason 
4514323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4515323ac95bSChris Mason 		if (level == path->lowest_level) {
4516e02119d5SChris Mason 			if (slot >= nritems)
4517e02119d5SChris Mason 				goto find_next_key;
45183f157a2fSChris Mason 			ret = 0;
45193f157a2fSChris Mason 			path->slots[level] = slot;
45203f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
45213f157a2fSChris Mason 			goto out;
45223f157a2fSChris Mason 		}
45239652480bSYan 		if (sret && slot > 0)
45249652480bSYan 			slot--;
45253f157a2fSChris Mason 		/*
4526de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4527260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
45283f157a2fSChris Mason 		 */
45293f157a2fSChris Mason 		while (slot < nritems) {
45303f157a2fSChris Mason 			u64 gen;
4531e02119d5SChris Mason 
45323f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
45333f157a2fSChris Mason 			if (gen < min_trans) {
45343f157a2fSChris Mason 				slot++;
45353f157a2fSChris Mason 				continue;
45363f157a2fSChris Mason 			}
45373f157a2fSChris Mason 			break;
45383f157a2fSChris Mason 		}
4539e02119d5SChris Mason find_next_key:
45403f157a2fSChris Mason 		/*
45413f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
45423f157a2fSChris Mason 		 * and find another one
45433f157a2fSChris Mason 		 */
45443f157a2fSChris Mason 		if (slot >= nritems) {
4545e02119d5SChris Mason 			path->slots[level] = slot;
4546e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4547de78b51aSEric Sandeen 						  min_trans);
4548e02119d5SChris Mason 			if (sret == 0) {
4549b3b4aa74SDavid Sterba 				btrfs_release_path(path);
45503f157a2fSChris Mason 				goto again;
45513f157a2fSChris Mason 			} else {
45523f157a2fSChris Mason 				goto out;
45533f157a2fSChris Mason 			}
45543f157a2fSChris Mason 		}
45553f157a2fSChris Mason 		/* save our key for returning back */
45563f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
45573f157a2fSChris Mason 		path->slots[level] = slot;
45583f157a2fSChris Mason 		if (level == path->lowest_level) {
45593f157a2fSChris Mason 			ret = 0;
45603f157a2fSChris Mason 			goto out;
45613f157a2fSChris Mason 		}
45624b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4563fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4564fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4565fb770ae4SLiu Bo 			goto out;
4566fb770ae4SLiu Bo 		}
45673f157a2fSChris Mason 
4568bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4569b4ce94deSChris Mason 
4570bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
45713f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4572f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
45733f157a2fSChris Mason 	}
45743f157a2fSChris Mason out:
4575f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4576f98de9b9SFilipe Manana 	if (ret == 0) {
4577f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4578f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4579f98de9b9SFilipe Manana 	}
45803f157a2fSChris Mason 	return ret;
45813f157a2fSChris Mason }
45823f157a2fSChris Mason 
45833f157a2fSChris Mason /*
45843f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
45853f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4586de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
45873f157a2fSChris Mason  *
45883f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
45893f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
45903f157a2fSChris Mason  *
45913f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
45923f157a2fSChris Mason  * calling this function.
45933f157a2fSChris Mason  */
4594e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4595de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4596e7a84565SChris Mason {
4597e7a84565SChris Mason 	int slot;
4598e7a84565SChris Mason 	struct extent_buffer *c;
4599e7a84565SChris Mason 
46006a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4601e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4602e7a84565SChris Mason 		if (!path->nodes[level])
4603e7a84565SChris Mason 			return 1;
4604e7a84565SChris Mason 
4605e7a84565SChris Mason 		slot = path->slots[level] + 1;
4606e7a84565SChris Mason 		c = path->nodes[level];
46073f157a2fSChris Mason next:
4608e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
460933c66f43SYan Zheng 			int ret;
461033c66f43SYan Zheng 			int orig_lowest;
461133c66f43SYan Zheng 			struct btrfs_key cur_key;
461233c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
461333c66f43SYan Zheng 			    !path->nodes[level + 1])
4614e7a84565SChris Mason 				return 1;
461533c66f43SYan Zheng 
46166a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
461733c66f43SYan Zheng 				level++;
4618e7a84565SChris Mason 				continue;
4619e7a84565SChris Mason 			}
462033c66f43SYan Zheng 
462133c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
462233c66f43SYan Zheng 			if (level == 0)
462333c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
462433c66f43SYan Zheng 			else
462533c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
462633c66f43SYan Zheng 
462733c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4628b3b4aa74SDavid Sterba 			btrfs_release_path(path);
462933c66f43SYan Zheng 			path->lowest_level = level;
463033c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
463133c66f43SYan Zheng 						0, 0);
463233c66f43SYan Zheng 			path->lowest_level = orig_lowest;
463333c66f43SYan Zheng 			if (ret < 0)
463433c66f43SYan Zheng 				return ret;
463533c66f43SYan Zheng 
463633c66f43SYan Zheng 			c = path->nodes[level];
463733c66f43SYan Zheng 			slot = path->slots[level];
463833c66f43SYan Zheng 			if (ret == 0)
463933c66f43SYan Zheng 				slot++;
464033c66f43SYan Zheng 			goto next;
464133c66f43SYan Zheng 		}
464233c66f43SYan Zheng 
4643e7a84565SChris Mason 		if (level == 0)
4644e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
46453f157a2fSChris Mason 		else {
46463f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
46473f157a2fSChris Mason 
46483f157a2fSChris Mason 			if (gen < min_trans) {
46493f157a2fSChris Mason 				slot++;
46503f157a2fSChris Mason 				goto next;
46513f157a2fSChris Mason 			}
4652e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
46533f157a2fSChris Mason 		}
4654e7a84565SChris Mason 		return 0;
4655e7a84565SChris Mason 	}
4656e7a84565SChris Mason 	return 1;
4657e7a84565SChris Mason }
4658e7a84565SChris Mason 
46593d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
46603d7806ecSJan Schmidt 			u64 time_seq)
46613d7806ecSJan Schmidt {
4662d97e63b6SChris Mason 	int slot;
46638e73f275SChris Mason 	int level;
46645f39d397SChris Mason 	struct extent_buffer *c;
46658e73f275SChris Mason 	struct extent_buffer *next;
4666d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4667925baeddSChris Mason 	struct btrfs_key key;
4668d96b3424SFilipe Manana 	bool need_commit_sem = false;
4669925baeddSChris Mason 	u32 nritems;
4670925baeddSChris Mason 	int ret;
46710e46318dSJosef Bacik 	int i;
4672925baeddSChris Mason 
4673bdcdd86cSFilipe Manana 	/*
4674bdcdd86cSFilipe Manana 	 * The nowait semantics are used only for write paths, where we don't
4675bdcdd86cSFilipe Manana 	 * use the tree mod log and sequence numbers.
4676bdcdd86cSFilipe Manana 	 */
4677bdcdd86cSFilipe Manana 	if (time_seq)
4678c922b016SStefan Roesch 		ASSERT(!path->nowait);
4679c922b016SStefan Roesch 
4680925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4681d397712bSChris Mason 	if (nritems == 0)
4682925baeddSChris Mason 		return 1;
4683925baeddSChris Mason 
46848e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
46858e73f275SChris Mason again:
46868e73f275SChris Mason 	level = 1;
46878e73f275SChris Mason 	next = NULL;
4688b3b4aa74SDavid Sterba 	btrfs_release_path(path);
46898e73f275SChris Mason 
4690a2135011SChris Mason 	path->keep_locks = 1;
46918e73f275SChris Mason 
4692d96b3424SFilipe Manana 	if (time_seq) {
46933d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4694d96b3424SFilipe Manana 	} else {
4695d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4696d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4697d96b3424SFilipe Manana 			need_commit_sem = true;
4698bdcdd86cSFilipe Manana 			if (path->nowait) {
4699bdcdd86cSFilipe Manana 				if (!down_read_trylock(&fs_info->commit_root_sem)) {
4700bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4701bdcdd86cSFilipe Manana 					goto done;
4702bdcdd86cSFilipe Manana 				}
4703bdcdd86cSFilipe Manana 			} else {
4704d96b3424SFilipe Manana 				down_read(&fs_info->commit_root_sem);
4705d96b3424SFilipe Manana 			}
4706bdcdd86cSFilipe Manana 		}
4707925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4708d96b3424SFilipe Manana 	}
4709925baeddSChris Mason 	path->keep_locks = 0;
4710925baeddSChris Mason 
4711925baeddSChris Mason 	if (ret < 0)
4712d96b3424SFilipe Manana 		goto done;
4713925baeddSChris Mason 
4714a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4715168fd7d2SChris Mason 	/*
4716168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4717168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4718168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4719168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4720168fd7d2SChris Mason 	 */
4721a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4722e457afecSYan Zheng 		if (ret == 0)
4723168fd7d2SChris Mason 			path->slots[0]++;
47248e73f275SChris Mason 		ret = 0;
4725925baeddSChris Mason 		goto done;
4726925baeddSChris Mason 	}
47270b43e04fSLiu Bo 	/*
47280b43e04fSLiu Bo 	 * So the above check misses one case:
47290b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
47300b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
47310b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
47320b43e04fSLiu Bo 	 *
47330b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
47340b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
47350b43e04fSLiu Bo 	 *
47360b43e04fSLiu Bo 	 * And a bit more explanation about this check,
47370b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
47380b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
47390b43e04fSLiu Bo 	 * bigger one.
47400b43e04fSLiu Bo 	 */
47410b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
47420b43e04fSLiu Bo 		ret = 0;
47430b43e04fSLiu Bo 		goto done;
47440b43e04fSLiu Bo 	}
4745d97e63b6SChris Mason 
4746234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
47478e73f275SChris Mason 		if (!path->nodes[level]) {
47488e73f275SChris Mason 			ret = 1;
47498e73f275SChris Mason 			goto done;
47508e73f275SChris Mason 		}
47515f39d397SChris Mason 
4752d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4753d97e63b6SChris Mason 		c = path->nodes[level];
47545f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4755d97e63b6SChris Mason 			level++;
47568e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
47578e73f275SChris Mason 				ret = 1;
47588e73f275SChris Mason 				goto done;
47598e73f275SChris Mason 			}
4760d97e63b6SChris Mason 			continue;
4761d97e63b6SChris Mason 		}
47625f39d397SChris Mason 
47630e46318dSJosef Bacik 
47640e46318dSJosef Bacik 		/*
47650e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
47660e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
47670e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
47680e46318dSJosef Bacik 		 */
47690e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
47700e46318dSJosef Bacik 			if (path->locks[level]) {
47710e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
47720e46318dSJosef Bacik 				path->locks[i] = 0;
47730e46318dSJosef Bacik 			}
47740e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
47750e46318dSJosef Bacik 			path->nodes[i] = NULL;
4776925baeddSChris Mason 		}
47775f39d397SChris Mason 
47788e73f275SChris Mason 		next = c;
4779d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4780cda79c54SDavid Sterba 					    slot, &key);
4781bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
47828e73f275SChris Mason 			goto again;
47835f39d397SChris Mason 
478476a05b35SChris Mason 		if (ret < 0) {
4785b3b4aa74SDavid Sterba 			btrfs_release_path(path);
478676a05b35SChris Mason 			goto done;
478776a05b35SChris Mason 		}
478876a05b35SChris Mason 
47895cd57b2cSChris Mason 		if (!path->skip_locking) {
4790bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4791bdcdd86cSFilipe Manana 			if (!ret && path->nowait) {
4792bdcdd86cSFilipe Manana 				ret = -EAGAIN;
4793bdcdd86cSFilipe Manana 				goto done;
4794bdcdd86cSFilipe Manana 			}
4795d42244a0SJan Schmidt 			if (!ret && time_seq) {
4796d42244a0SJan Schmidt 				/*
4797d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4798d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4799d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4800d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4801d42244a0SJan Schmidt 				 * on our lock and cycle.
4802d42244a0SJan Schmidt 				 */
4803cf538830SJan Schmidt 				free_extent_buffer(next);
4804d42244a0SJan Schmidt 				btrfs_release_path(path);
4805d42244a0SJan Schmidt 				cond_resched();
4806d42244a0SJan Schmidt 				goto again;
4807d42244a0SJan Schmidt 			}
48080e46318dSJosef Bacik 			if (!ret)
48090e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4810bd681513SChris Mason 		}
4811d97e63b6SChris Mason 		break;
4812d97e63b6SChris Mason 	}
4813d97e63b6SChris Mason 	path->slots[level] = slot;
4814d97e63b6SChris Mason 	while (1) {
4815d97e63b6SChris Mason 		level--;
4816d97e63b6SChris Mason 		path->nodes[level] = next;
4817d97e63b6SChris Mason 		path->slots[level] = 0;
4818a74a4b97SChris Mason 		if (!path->skip_locking)
4819ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4820d97e63b6SChris Mason 		if (!level)
4821d97e63b6SChris Mason 			break;
4822b4ce94deSChris Mason 
4823d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4824cda79c54SDavid Sterba 					    0, &key);
4825bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
48268e73f275SChris Mason 			goto again;
48278e73f275SChris Mason 
482876a05b35SChris Mason 		if (ret < 0) {
4829b3b4aa74SDavid Sterba 			btrfs_release_path(path);
483076a05b35SChris Mason 			goto done;
483176a05b35SChris Mason 		}
483276a05b35SChris Mason 
4833bdcdd86cSFilipe Manana 		if (!path->skip_locking) {
4834bdcdd86cSFilipe Manana 			if (path->nowait) {
4835bdcdd86cSFilipe Manana 				if (!btrfs_try_tree_read_lock(next)) {
4836bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4837bdcdd86cSFilipe Manana 					goto done;
4838bdcdd86cSFilipe Manana 				}
4839bdcdd86cSFilipe Manana 			} else {
48400e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4841d97e63b6SChris Mason 			}
4842bdcdd86cSFilipe Manana 		}
4843bdcdd86cSFilipe Manana 	}
48448e73f275SChris Mason 	ret = 0;
4845925baeddSChris Mason done:
4846f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
4847d96b3424SFilipe Manana 	if (need_commit_sem) {
4848d96b3424SFilipe Manana 		int ret2;
4849d96b3424SFilipe Manana 
4850d96b3424SFilipe Manana 		path->need_commit_sem = 1;
4851d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
4852d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
4853d96b3424SFilipe Manana 		if (ret2)
4854d96b3424SFilipe Manana 			ret = ret2;
4855d96b3424SFilipe Manana 	}
48568e73f275SChris Mason 
48578e73f275SChris Mason 	return ret;
4858d97e63b6SChris Mason }
48590b86a832SChris Mason 
4860890d2b1aSJosef Bacik int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
4861890d2b1aSJosef Bacik {
4862890d2b1aSJosef Bacik 	path->slots[0]++;
4863890d2b1aSJosef Bacik 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
4864890d2b1aSJosef Bacik 		return btrfs_next_old_leaf(root, path, time_seq);
4865890d2b1aSJosef Bacik 	return 0;
4866890d2b1aSJosef Bacik }
4867890d2b1aSJosef Bacik 
48683f157a2fSChris Mason /*
48693f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
48703f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
48713f157a2fSChris Mason  *
48723f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
48733f157a2fSChris Mason  */
48740b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
48750b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
48760b86a832SChris Mason 			int type)
48770b86a832SChris Mason {
48780b86a832SChris Mason 	struct btrfs_key found_key;
48790b86a832SChris Mason 	struct extent_buffer *leaf;
4880e02119d5SChris Mason 	u32 nritems;
48810b86a832SChris Mason 	int ret;
48820b86a832SChris Mason 
48830b86a832SChris Mason 	while (1) {
48840b86a832SChris Mason 		if (path->slots[0] == 0) {
48850b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
48860b86a832SChris Mason 			if (ret != 0)
48870b86a832SChris Mason 				return ret;
48880b86a832SChris Mason 		} else {
48890b86a832SChris Mason 			path->slots[0]--;
48900b86a832SChris Mason 		}
48910b86a832SChris Mason 		leaf = path->nodes[0];
4892e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
4893e02119d5SChris Mason 		if (nritems == 0)
4894e02119d5SChris Mason 			return 1;
4895e02119d5SChris Mason 		if (path->slots[0] == nritems)
4896e02119d5SChris Mason 			path->slots[0]--;
4897e02119d5SChris Mason 
48980b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4899e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
4900e02119d5SChris Mason 			break;
49010a4eefbbSYan Zheng 		if (found_key.type == type)
49020a4eefbbSYan Zheng 			return 0;
4903e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
4904e02119d5SChris Mason 		    found_key.type < type)
4905e02119d5SChris Mason 			break;
49060b86a832SChris Mason 	}
49070b86a832SChris Mason 	return 1;
49080b86a832SChris Mason }
4909ade2e0b3SWang Shilong 
4910ade2e0b3SWang Shilong /*
4911ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
4912ade2e0b3SWang Shilong  * min objecitd.
4913ade2e0b3SWang Shilong  *
4914ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4915ade2e0b3SWang Shilong  */
4916ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
4917ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
4918ade2e0b3SWang Shilong {
4919ade2e0b3SWang Shilong 	struct btrfs_key found_key;
4920ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
4921ade2e0b3SWang Shilong 	u32 nritems;
4922ade2e0b3SWang Shilong 	int ret;
4923ade2e0b3SWang Shilong 
4924ade2e0b3SWang Shilong 	while (1) {
4925ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
4926ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
4927ade2e0b3SWang Shilong 			if (ret != 0)
4928ade2e0b3SWang Shilong 				return ret;
4929ade2e0b3SWang Shilong 		} else {
4930ade2e0b3SWang Shilong 			path->slots[0]--;
4931ade2e0b3SWang Shilong 		}
4932ade2e0b3SWang Shilong 		leaf = path->nodes[0];
4933ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
4934ade2e0b3SWang Shilong 		if (nritems == 0)
4935ade2e0b3SWang Shilong 			return 1;
4936ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
4937ade2e0b3SWang Shilong 			path->slots[0]--;
4938ade2e0b3SWang Shilong 
4939ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4940ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
4941ade2e0b3SWang Shilong 			break;
4942ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4943ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
4944ade2e0b3SWang Shilong 			return 0;
4945ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
4946ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
4947ade2e0b3SWang Shilong 			break;
4948ade2e0b3SWang Shilong 	}
4949ade2e0b3SWang Shilong 	return 1;
4950ade2e0b3SWang Shilong }
4951226463d7SJosef Bacik 
4952226463d7SJosef Bacik int __init btrfs_ctree_init(void)
4953226463d7SJosef Bacik {
4954226463d7SJosef Bacik 	btrfs_path_cachep = kmem_cache_create("btrfs_path",
4955226463d7SJosef Bacik 			sizeof(struct btrfs_path), 0,
4956226463d7SJosef Bacik 			SLAB_MEM_SPREAD, NULL);
4957226463d7SJosef Bacik 	if (!btrfs_path_cachep)
4958226463d7SJosef Bacik 		return -ENOMEM;
4959226463d7SJosef Bacik 	return 0;
4960226463d7SJosef Bacik }
4961226463d7SJosef Bacik 
4962226463d7SJosef Bacik void __cold btrfs_ctree_exit(void)
4963226463d7SJosef Bacik {
4964226463d7SJosef Bacik 	kmem_cache_destroy(btrfs_path_cachep);
4965226463d7SJosef Bacik }
4966