xref: /openbmc/linux/fs/btrfs/ctree.c (revision e41d12f539f7c8bac9b0897031fee6cc9158a6be)
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>
10*e41d12f5SChristoph Hellwig #include <linux/error-injection.h>
11eb60ceacSChris Mason #include "ctree.h"
12eb60ceacSChris Mason #include "disk-io.h"
137f5c1516SChris Mason #include "transaction.h"
145f39d397SChris Mason #include "print-tree.h"
15925baeddSChris Mason #include "locking.h"
16de37aa51SNikolay Borisov #include "volumes.h"
17f616f5cdSQu Wenruo #include "qgroup.h"
18f3a84ccdSFilipe Manana #include "tree-mod-log.h"
199a8dd150SChris Mason 
20e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
21e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
22310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
23310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
24310712b2SOmar Sandoval 		      int data_size, int extend);
255f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
262ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
27971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
285f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
295f39d397SChris Mason 			      struct extent_buffer *dst_buf,
305f39d397SChris Mason 			      struct extent_buffer *src_buf);
31afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
32afe5fea7STsutomu Itoh 		    int level, int slot);
33d97e63b6SChris Mason 
34af024ed2SJohannes Thumshirn static const struct btrfs_csums {
35af024ed2SJohannes Thumshirn 	u16		size;
3659a0fcdbSDavid Sterba 	const char	name[10];
3759a0fcdbSDavid Sterba 	const char	driver[12];
38af024ed2SJohannes Thumshirn } btrfs_csums[] = {
39af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
403951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
413831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
42352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
43352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
44af024ed2SJohannes Thumshirn };
45af024ed2SJohannes Thumshirn 
46af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
47af024ed2SJohannes Thumshirn {
48af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
49af024ed2SJohannes Thumshirn 	/*
50af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
51af024ed2SJohannes Thumshirn 	 */
52af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
53af024ed2SJohannes Thumshirn }
54af024ed2SJohannes Thumshirn 
55af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
56af024ed2SJohannes Thumshirn {
57af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
58af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
59af024ed2SJohannes Thumshirn }
60af024ed2SJohannes Thumshirn 
61b4e967beSDavid Sterba /*
62b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
63b4e967beSDavid Sterba  * name
64b4e967beSDavid Sterba  */
65b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
66b4e967beSDavid Sterba {
67b4e967beSDavid Sterba 	/* csum type is validated at mount time */
6859a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
6959a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
70b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
71b4e967beSDavid Sterba }
72b4e967beSDavid Sterba 
73604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
74f7cea56cSDavid Sterba {
75f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
76f7cea56cSDavid Sterba }
77f7cea56cSDavid Sterba 
782c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
792c90e5d6SChris Mason {
80e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
812c90e5d6SChris Mason }
822c90e5d6SChris Mason 
83d352ac68SChris Mason /* this also releases the path */
842c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
852c90e5d6SChris Mason {
86ff175d57SJesper Juhl 	if (!p)
87ff175d57SJesper Juhl 		return;
88b3b4aa74SDavid Sterba 	btrfs_release_path(p);
892c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
902c90e5d6SChris Mason }
912c90e5d6SChris Mason 
92d352ac68SChris Mason /*
93d352ac68SChris Mason  * path release drops references on the extent buffers in the path
94d352ac68SChris Mason  * and it drops any locks held by this path
95d352ac68SChris Mason  *
96d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
97d352ac68SChris Mason  */
98b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
99eb60ceacSChris Mason {
100eb60ceacSChris Mason 	int i;
101a2135011SChris Mason 
102234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1033f157a2fSChris Mason 		p->slots[i] = 0;
104eb60ceacSChris Mason 		if (!p->nodes[i])
105925baeddSChris Mason 			continue;
106925baeddSChris Mason 		if (p->locks[i]) {
107bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
108925baeddSChris Mason 			p->locks[i] = 0;
109925baeddSChris Mason 		}
1105f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1113f157a2fSChris Mason 		p->nodes[i] = NULL;
112eb60ceacSChris Mason 	}
113eb60ceacSChris Mason }
114eb60ceacSChris Mason 
115d352ac68SChris Mason /*
116d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
117d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
118d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
119d352ac68SChris Mason  * looping required.
120d352ac68SChris Mason  *
121d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
122d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
123d352ac68SChris Mason  * at any time because there are no locks held.
124d352ac68SChris Mason  */
125925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
126925baeddSChris Mason {
127925baeddSChris Mason 	struct extent_buffer *eb;
128240f62c8SChris Mason 
1293083ee2eSJosef Bacik 	while (1) {
130240f62c8SChris Mason 		rcu_read_lock();
131240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1323083ee2eSJosef Bacik 
1333083ee2eSJosef Bacik 		/*
1343083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
13501327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1363083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1373083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1383083ee2eSJosef Bacik 		 */
1393083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
140240f62c8SChris Mason 			rcu_read_unlock();
1413083ee2eSJosef Bacik 			break;
1423083ee2eSJosef Bacik 		}
1433083ee2eSJosef Bacik 		rcu_read_unlock();
1443083ee2eSJosef Bacik 		synchronize_rcu();
1453083ee2eSJosef Bacik 	}
146925baeddSChris Mason 	return eb;
147925baeddSChris Mason }
148925baeddSChris Mason 
14992a7cc42SQu Wenruo /*
15092a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
15192a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
15292a7cc42SQu Wenruo  * sure they get properly updated on disk.
153d352ac68SChris Mason  */
1540b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1550b86a832SChris Mason {
1560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1570b246afaSJeff Mahoney 
158e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
159e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
160e7070be1SJosef Bacik 		return;
161e7070be1SJosef Bacik 
1620b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
163e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
164e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
1654fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
166e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
1670b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
168e7070be1SJosef Bacik 		else
169e7070be1SJosef Bacik 			list_move(&root->dirty_list,
1700b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
1710b86a832SChris Mason 	}
1720b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1730b86a832SChris Mason }
1740b86a832SChris Mason 
175d352ac68SChris Mason /*
176d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
177d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
178d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
179d352ac68SChris Mason  */
180be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
181be20aa9dSChris Mason 		      struct btrfs_root *root,
182be20aa9dSChris Mason 		      struct extent_buffer *buf,
183be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
184be20aa9dSChris Mason {
1850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
186be20aa9dSChris Mason 	struct extent_buffer *cow;
187be20aa9dSChris Mason 	int ret = 0;
188be20aa9dSChris Mason 	int level;
1895d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
190be20aa9dSChris Mason 
19192a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
1920b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
19392a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
19427cdeb70SMiao Xie 		trans->transid != root->last_trans);
195be20aa9dSChris Mason 
196be20aa9dSChris Mason 	level = btrfs_header_level(buf);
1975d4f98a2SYan Zheng 	if (level == 0)
1985d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
1995d4f98a2SYan Zheng 	else
2005d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
20131840ae1SZheng Yan 
2024d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
203cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
204cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
2055d4f98a2SYan Zheng 	if (IS_ERR(cow))
206be20aa9dSChris Mason 		return PTR_ERR(cow);
207be20aa9dSChris Mason 
20858e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
209be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
210be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2115d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2125d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2135d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2145d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2155d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2165d4f98a2SYan Zheng 	else
217be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
218be20aa9dSChris Mason 
219de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2202b82032cSYan Zheng 
221be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2225d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
223e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2245d4f98a2SYan Zheng 	else
225e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
226867ed321SJosef Bacik 	if (ret) {
22772c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
22872c9925fSFilipe Manana 		free_extent_buffer(cow);
229867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
230be20aa9dSChris Mason 		return ret;
231867ed321SJosef Bacik 	}
232be20aa9dSChris Mason 
233be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
234be20aa9dSChris Mason 	*cow_ret = cow;
235be20aa9dSChris Mason 	return 0;
236be20aa9dSChris Mason }
237be20aa9dSChris Mason 
238d352ac68SChris Mason /*
2395d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
2405d4f98a2SYan Zheng  */
2415d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
2425d4f98a2SYan Zheng 			      struct extent_buffer *buf)
2435d4f98a2SYan Zheng {
2445d4f98a2SYan Zheng 	/*
24592a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
24692a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
24792a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
2485d4f98a2SYan Zheng 	 */
24992a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2505d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
2515d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
2525d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
2535d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
2545d4f98a2SYan Zheng 		return 1;
255a79865c6SNikolay Borisov 
2565d4f98a2SYan Zheng 	return 0;
2575d4f98a2SYan Zheng }
2585d4f98a2SYan Zheng 
2595d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
2605d4f98a2SYan Zheng 				       struct btrfs_root *root,
2615d4f98a2SYan Zheng 				       struct extent_buffer *buf,
262f0486c68SYan, Zheng 				       struct extent_buffer *cow,
263f0486c68SYan, Zheng 				       int *last_ref)
2645d4f98a2SYan Zheng {
2650b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2665d4f98a2SYan Zheng 	u64 refs;
2675d4f98a2SYan Zheng 	u64 owner;
2685d4f98a2SYan Zheng 	u64 flags;
2695d4f98a2SYan Zheng 	u64 new_flags = 0;
2705d4f98a2SYan Zheng 	int ret;
2715d4f98a2SYan Zheng 
2725d4f98a2SYan Zheng 	/*
2735d4f98a2SYan Zheng 	 * Backrefs update rules:
2745d4f98a2SYan Zheng 	 *
2755d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
2765d4f98a2SYan Zheng 	 * allocated by tree relocation.
2775d4f98a2SYan Zheng 	 *
2785d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
2795d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
2805d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
2815d4f98a2SYan Zheng 	 *
2825d4f98a2SYan Zheng 	 * If a tree block is been relocating
2835d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
2845d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
2855d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
2865d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
2875d4f98a2SYan Zheng 	 */
2885d4f98a2SYan Zheng 
2895d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
2902ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
2913173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
2923173a18fSJosef Bacik 					       &refs, &flags);
293be1a5564SMark Fasheh 		if (ret)
294be1a5564SMark Fasheh 			return ret;
295e5df9573SMark Fasheh 		if (refs == 0) {
296e5df9573SMark Fasheh 			ret = -EROFS;
2970b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
298e5df9573SMark Fasheh 			return ret;
299e5df9573SMark Fasheh 		}
3005d4f98a2SYan Zheng 	} else {
3015d4f98a2SYan Zheng 		refs = 1;
3025d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
3035d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
3045d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
3055d4f98a2SYan Zheng 		else
3065d4f98a2SYan Zheng 			flags = 0;
3075d4f98a2SYan Zheng 	}
3085d4f98a2SYan Zheng 
3095d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
3105d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
3115d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
3125d4f98a2SYan Zheng 
3135d4f98a2SYan Zheng 	if (refs > 1) {
3145d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
3155d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
3165d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
317e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
318692826b2SJeff Mahoney 			if (ret)
319692826b2SJeff Mahoney 				return ret;
3205d4f98a2SYan Zheng 
3215d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3225d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
323e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
324692826b2SJeff Mahoney 				if (ret)
325692826b2SJeff Mahoney 					return ret;
326e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
327692826b2SJeff Mahoney 				if (ret)
328692826b2SJeff Mahoney 					return ret;
3295d4f98a2SYan Zheng 			}
3305d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
3315d4f98a2SYan Zheng 		} else {
3325d4f98a2SYan Zheng 
3335d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3345d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
335e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3365d4f98a2SYan Zheng 			else
337e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
338692826b2SJeff Mahoney 			if (ret)
339692826b2SJeff Mahoney 				return ret;
3405d4f98a2SYan Zheng 		}
3415d4f98a2SYan Zheng 		if (new_flags != 0) {
342b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
343b1c79e09SJosef Bacik 
34442c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
345b1c79e09SJosef Bacik 							  new_flags, level, 0);
346be1a5564SMark Fasheh 			if (ret)
347be1a5564SMark Fasheh 				return ret;
3485d4f98a2SYan Zheng 		}
3495d4f98a2SYan Zheng 	} else {
3505d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
3515d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3525d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
353e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3545d4f98a2SYan Zheng 			else
355e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
356692826b2SJeff Mahoney 			if (ret)
357692826b2SJeff Mahoney 				return ret;
358e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
359692826b2SJeff Mahoney 			if (ret)
360692826b2SJeff Mahoney 				return ret;
3615d4f98a2SYan Zheng 		}
3626a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
363f0486c68SYan, Zheng 		*last_ref = 1;
3645d4f98a2SYan Zheng 	}
3655d4f98a2SYan Zheng 	return 0;
3665d4f98a2SYan Zheng }
3675d4f98a2SYan Zheng 
3685d4f98a2SYan Zheng /*
369d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
370d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
371d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
372d397712bSChris Mason  * dirty again.
373d352ac68SChris Mason  *
374d352ac68SChris Mason  * search_start -- an allocation hint for the new block
375d352ac68SChris Mason  *
376d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
377d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
378d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
379d352ac68SChris Mason  */
380d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
3815f39d397SChris Mason 			     struct btrfs_root *root,
3825f39d397SChris Mason 			     struct extent_buffer *buf,
3835f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
3845f39d397SChris Mason 			     struct extent_buffer **cow_ret,
3859631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
3869631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
3876702ed49SChris Mason {
3880b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3895d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
3905f39d397SChris Mason 	struct extent_buffer *cow;
391be1a5564SMark Fasheh 	int level, ret;
392f0486c68SYan, Zheng 	int last_ref = 0;
393925baeddSChris Mason 	int unlock_orig = 0;
3940f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
3956702ed49SChris Mason 
396925baeddSChris Mason 	if (*cow_ret == buf)
397925baeddSChris Mason 		unlock_orig = 1;
398925baeddSChris Mason 
399b9447ef8SChris Mason 	btrfs_assert_tree_locked(buf);
400925baeddSChris Mason 
40192a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
4020b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
40392a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
40427cdeb70SMiao Xie 		trans->transid != root->last_trans);
4055f39d397SChris Mason 
4067bb86316SChris Mason 	level = btrfs_header_level(buf);
40731840ae1SZheng Yan 
4085d4f98a2SYan Zheng 	if (level == 0)
4095d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
4105d4f98a2SYan Zheng 	else
4115d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
4125d4f98a2SYan Zheng 
4130f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
4145d4f98a2SYan Zheng 		parent_start = parent->start;
4155d4f98a2SYan Zheng 
41679bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
41779bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
41879bd3712SFilipe Manana 				     search_start, empty_size, nest);
4196702ed49SChris Mason 	if (IS_ERR(cow))
4206702ed49SChris Mason 		return PTR_ERR(cow);
4216702ed49SChris Mason 
422b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
423b4ce94deSChris Mason 
42458e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
425db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
4265f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
4275d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
4285d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
4295d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
4305d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
4315d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
4325d4f98a2SYan Zheng 	else
4335f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
4346702ed49SChris Mason 
435de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
4362b82032cSYan Zheng 
437be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
438b68dc2a9SMark Fasheh 	if (ret) {
439572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
440572c83acSJosef Bacik 		free_extent_buffer(cow);
44166642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
442b68dc2a9SMark Fasheh 		return ret;
443b68dc2a9SMark Fasheh 	}
4441a40e23bSZheng Yan 
44592a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
44683d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
44793314e3bSZhaolei 		if (ret) {
448572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
449572c83acSJosef Bacik 			free_extent_buffer(cow);
45066642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
45183d4cfd4SJosef Bacik 			return ret;
45283d4cfd4SJosef Bacik 		}
45393314e3bSZhaolei 	}
4543fd0a558SYan, Zheng 
4556702ed49SChris Mason 	if (buf == root->node) {
456925baeddSChris Mason 		WARN_ON(parent && parent != buf);
4575d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4585d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4595d4f98a2SYan Zheng 			parent_start = buf->start;
460925baeddSChris Mason 
46167439dadSDavid Sterba 		atomic_inc(&cow->refs);
462406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
463d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
464240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
465925baeddSChris Mason 
466f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
4675581a51aSJan Schmidt 				      last_ref);
4685f39d397SChris Mason 		free_extent_buffer(buf);
4690b86a832SChris Mason 		add_root_to_dirty_list(root);
4706702ed49SChris Mason 	} else {
4715d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
472f3a84ccdSFilipe Manana 		btrfs_tree_mod_log_insert_key(parent, parent_slot,
473f3a84ccdSFilipe Manana 					      BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
4745f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
475db94535dSChris Mason 					cow->start);
47674493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
47774493f7aSChris Mason 					      trans->transid);
4786702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
4795de865eeSFilipe David Borba Manana 		if (last_ref) {
480f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
4815de865eeSFilipe David Borba Manana 			if (ret) {
482572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
483572c83acSJosef Bacik 				free_extent_buffer(cow);
48466642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
4855de865eeSFilipe David Borba Manana 				return ret;
4865de865eeSFilipe David Borba Manana 			}
4875de865eeSFilipe David Borba Manana 		}
488f0486c68SYan, Zheng 		btrfs_free_tree_block(trans, root, buf, parent_start,
4895581a51aSJan Schmidt 				      last_ref);
4906702ed49SChris Mason 	}
491925baeddSChris Mason 	if (unlock_orig)
492925baeddSChris Mason 		btrfs_tree_unlock(buf);
4933083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
4946702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
4956702ed49SChris Mason 	*cow_ret = cow;
4966702ed49SChris Mason 	return 0;
4976702ed49SChris Mason }
4986702ed49SChris Mason 
4995d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
5005d4f98a2SYan Zheng 				   struct btrfs_root *root,
5015d4f98a2SYan Zheng 				   struct extent_buffer *buf)
5025d4f98a2SYan Zheng {
503f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
504faa2dbf0SJosef Bacik 		return 0;
505fccb84c9SDavid Sterba 
506d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
507d1980131SDavid Sterba 	smp_mb__before_atomic();
508f1ebcc74SLiu Bo 
509f1ebcc74SLiu Bo 	/*
510f1ebcc74SLiu Bo 	 * We do not need to cow a block if
511f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
512f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
513f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
514f1ebcc74SLiu Bo 	 *
515f1ebcc74SLiu Bo 	 * What is forced COW:
51601327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
51752042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
518f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
519f1ebcc74SLiu Bo 	 */
5205d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
5215d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
5225d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
523f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
52427cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
5255d4f98a2SYan Zheng 		return 0;
5265d4f98a2SYan Zheng 	return 1;
5275d4f98a2SYan Zheng }
5285d4f98a2SYan Zheng 
529d352ac68SChris Mason /*
530d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
53101327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
532d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
533d352ac68SChris Mason  */
534d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
5355f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
5365f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
5379631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
5389631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
53902217ed2SChris Mason {
5400b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5416702ed49SChris Mason 	u64 search_start;
542f510cfecSChris Mason 	int ret;
543dc17ff8fSChris Mason 
54483354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
54583354f07SJosef Bacik 		btrfs_err(fs_info,
54683354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
54783354f07SJosef Bacik 
5480b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
54931b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
550c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
5510b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
55231b1a2bdSJulia Lawall 
5530b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
55431b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
5550b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
556dc17ff8fSChris Mason 
5575d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
55802217ed2SChris Mason 		*cow_ret = buf;
55902217ed2SChris Mason 		return 0;
56002217ed2SChris Mason 	}
561c487685dSChris Mason 
562ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
563b4ce94deSChris Mason 
564f616f5cdSQu Wenruo 	/*
565f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
566f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
567f616f5cdSQu Wenruo 	 *
568f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
569f616f5cdSQu Wenruo 	 */
570f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
571f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
5729631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
5731abe9b8aSliubo 
5741abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
5751abe9b8aSliubo 
576f510cfecSChris Mason 	return ret;
5772c90e5d6SChris Mason }
578f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
5796702ed49SChris Mason 
580d352ac68SChris Mason /*
581d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
582d352ac68SChris Mason  * node are actually close by
583d352ac68SChris Mason  */
5846b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
5856702ed49SChris Mason {
5866b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
5876702ed49SChris Mason 		return 1;
5886b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
5896702ed49SChris Mason 		return 1;
59002217ed2SChris Mason 	return 0;
59102217ed2SChris Mason }
59202217ed2SChris Mason 
593ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
594ce6ef5abSDavid Sterba 
595ce6ef5abSDavid Sterba /*
596ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
597ce6ef5abSDavid Sterba  * we can avoid the conversion.
598ce6ef5abSDavid Sterba  */
599ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
600ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
601ce6ef5abSDavid Sterba {
602ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
603ce6ef5abSDavid Sterba 
604ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
605ce6ef5abSDavid Sterba }
606ce6ef5abSDavid Sterba 
607ce6ef5abSDavid Sterba #else
608ce6ef5abSDavid Sterba 
609081e9573SChris Mason /*
610081e9573SChris Mason  * compare two keys in a memcmp fashion
611081e9573SChris Mason  */
612310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
613310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
614081e9573SChris Mason {
615081e9573SChris Mason 	struct btrfs_key k1;
616081e9573SChris Mason 
617081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
618081e9573SChris Mason 
61920736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
620081e9573SChris Mason }
621ce6ef5abSDavid Sterba #endif
622081e9573SChris Mason 
623f3465ca4SJosef Bacik /*
624f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
625f3465ca4SJosef Bacik  */
626e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
627f3465ca4SJosef Bacik {
628f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
629f3465ca4SJosef Bacik 		return 1;
630f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
631f3465ca4SJosef Bacik 		return -1;
632f3465ca4SJosef Bacik 	if (k1->type > k2->type)
633f3465ca4SJosef Bacik 		return 1;
634f3465ca4SJosef Bacik 	if (k1->type < k2->type)
635f3465ca4SJosef Bacik 		return -1;
636f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
637f3465ca4SJosef Bacik 		return 1;
638f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
639f3465ca4SJosef Bacik 		return -1;
640f3465ca4SJosef Bacik 	return 0;
641f3465ca4SJosef Bacik }
642081e9573SChris Mason 
643d352ac68SChris Mason /*
644d352ac68SChris Mason  * this is used by the defrag code to go through all the
645d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
646d352ac68SChris Mason  * disk order is close to key order
647d352ac68SChris Mason  */
6486702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
6495f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
650de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
651a6b6e75eSChris Mason 		       struct btrfs_key *progress)
6526702ed49SChris Mason {
6530b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6546b80053dSChris Mason 	struct extent_buffer *cur;
6556702ed49SChris Mason 	u64 blocknr;
656e9d0b13bSChris Mason 	u64 search_start = *last_ret;
657e9d0b13bSChris Mason 	u64 last_block = 0;
6586702ed49SChris Mason 	u64 other;
6596702ed49SChris Mason 	u32 parent_nritems;
6606702ed49SChris Mason 	int end_slot;
6616702ed49SChris Mason 	int i;
6626702ed49SChris Mason 	int err = 0;
6636b80053dSChris Mason 	u32 blocksize;
664081e9573SChris Mason 	int progress_passed = 0;
665081e9573SChris Mason 	struct btrfs_disk_key disk_key;
6666702ed49SChris Mason 
6670b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
6680b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
66986479a04SChris Mason 
6706b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
6710b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
6725dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
6736702ed49SChris Mason 
6745dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
6756702ed49SChris Mason 		return 0;
6766702ed49SChris Mason 
6775dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
6786702ed49SChris Mason 		int close = 1;
679a6b6e75eSChris Mason 
680081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
681081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
682081e9573SChris Mason 			continue;
683081e9573SChris Mason 
684081e9573SChris Mason 		progress_passed = 1;
6856b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
686e9d0b13bSChris Mason 		if (last_block == 0)
687e9d0b13bSChris Mason 			last_block = blocknr;
6885708b959SChris Mason 
6896702ed49SChris Mason 		if (i > 0) {
6906b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
6916b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
6926702ed49SChris Mason 		}
6935dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
6946b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
6956b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
6966702ed49SChris Mason 		}
697e9d0b13bSChris Mason 		if (close) {
698e9d0b13bSChris Mason 			last_block = blocknr;
6996702ed49SChris Mason 			continue;
700e9d0b13bSChris Mason 		}
7016702ed49SChris Mason 
702206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
703206983b7SJosef Bacik 		if (IS_ERR(cur))
70464c043deSLiu Bo 			return PTR_ERR(cur);
705e9d0b13bSChris Mason 		if (search_start == 0)
7066b80053dSChris Mason 			search_start = last_block;
707e9d0b13bSChris Mason 
708e7a84565SChris Mason 		btrfs_tree_lock(cur);
7096b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
710e7a84565SChris Mason 					&cur, search_start,
7116b80053dSChris Mason 					min(16 * blocksize,
7129631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
7139631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
714252c38f0SYan 		if (err) {
715e7a84565SChris Mason 			btrfs_tree_unlock(cur);
7166b80053dSChris Mason 			free_extent_buffer(cur);
7176702ed49SChris Mason 			break;
718252c38f0SYan 		}
719e7a84565SChris Mason 		search_start = cur->start;
720e7a84565SChris Mason 		last_block = cur->start;
721f2183bdeSChris Mason 		*last_ret = search_start;
722e7a84565SChris Mason 		btrfs_tree_unlock(cur);
723e7a84565SChris Mason 		free_extent_buffer(cur);
7246702ed49SChris Mason 	}
7256702ed49SChris Mason 	return err;
7266702ed49SChris Mason }
7276702ed49SChris Mason 
72874123bd7SChris Mason /*
7295f39d397SChris Mason  * search for key in the extent_buffer.  The items start at offset p,
73067d5e289SMarcos Paulo de Souza  * and they are item_size apart.
7315f39d397SChris Mason  *
73274123bd7SChris Mason  * the slot in the array is returned via slot, and it points to
73374123bd7SChris Mason  * the place where you would insert key if it is not found in
73474123bd7SChris Mason  * the array.
73574123bd7SChris Mason  *
73667d5e289SMarcos Paulo de Souza  * Slot may point to total number of items if the key is bigger than
73767d5e289SMarcos Paulo de Souza  * all of the keys
73874123bd7SChris Mason  */
739e02119d5SChris Mason static noinline int generic_bin_search(struct extent_buffer *eb,
740310712b2SOmar Sandoval 				       unsigned long p, int item_size,
74167d5e289SMarcos Paulo de Souza 				       const struct btrfs_key *key, int *slot)
742be0e5c09SChris Mason {
743be0e5c09SChris Mason 	int low = 0;
74467d5e289SMarcos Paulo de Souza 	int high = btrfs_header_nritems(eb);
745be0e5c09SChris Mason 	int ret;
7465cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
747be0e5c09SChris Mason 
7485e24e9afSLiu Bo 	if (low > high) {
7495e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
7505e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
7515e24e9afSLiu Bo 			  __func__, low, high, eb->start,
7525e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
7535e24e9afSLiu Bo 		return -EINVAL;
7545e24e9afSLiu Bo 	}
7555e24e9afSLiu Bo 
756be0e5c09SChris Mason 	while (low < high) {
7575cd17f34SDavid Sterba 		unsigned long oip;
7585cd17f34SDavid Sterba 		unsigned long offset;
7595cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
7605cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
7615cd17f34SDavid Sterba 		int mid;
7625cd17f34SDavid Sterba 
763be0e5c09SChris Mason 		mid = (low + high) / 2;
7645f39d397SChris Mason 		offset = p + mid * item_size;
7655cd17f34SDavid Sterba 		oip = offset_in_page(offset);
7665f39d397SChris Mason 
7675cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
768884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
7695cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
770934d375bSChris Mason 
771884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
7725cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
7735cd17f34SDavid Sterba 		} else {
7745cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
7755f39d397SChris Mason 			tmp = &unaligned;
776479965d6SChris Mason 		}
777479965d6SChris Mason 
778be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
779be0e5c09SChris Mason 
780be0e5c09SChris Mason 		if (ret < 0)
781be0e5c09SChris Mason 			low = mid + 1;
782be0e5c09SChris Mason 		else if (ret > 0)
783be0e5c09SChris Mason 			high = mid;
784be0e5c09SChris Mason 		else {
785be0e5c09SChris Mason 			*slot = mid;
786be0e5c09SChris Mason 			return 0;
787be0e5c09SChris Mason 		}
788be0e5c09SChris Mason 	}
789be0e5c09SChris Mason 	*slot = low;
790be0e5c09SChris Mason 	return 1;
791be0e5c09SChris Mason }
792be0e5c09SChris Mason 
79397571fd0SChris Mason /*
79497571fd0SChris Mason  * simple bin_search frontend that does the right thing for
79597571fd0SChris Mason  * leaves vs nodes
79697571fd0SChris Mason  */
797a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
798e3b83361SQu Wenruo 		     int *slot)
799be0e5c09SChris Mason {
800e3b83361SQu Wenruo 	if (btrfs_header_level(eb) == 0)
8015f39d397SChris Mason 		return generic_bin_search(eb,
8025f39d397SChris Mason 					  offsetof(struct btrfs_leaf, items),
80367d5e289SMarcos Paulo de Souza 					  sizeof(struct btrfs_item), key, slot);
804f775738fSWang Sheng-Hui 	else
8055f39d397SChris Mason 		return generic_bin_search(eb,
8065f39d397SChris Mason 					  offsetof(struct btrfs_node, ptrs),
80767d5e289SMarcos Paulo de Souza 					  sizeof(struct btrfs_key_ptr), key, slot);
808be0e5c09SChris Mason }
809be0e5c09SChris Mason 
810f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
811f0486c68SYan, Zheng {
812f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
813f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
814f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
815f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
816f0486c68SYan, Zheng }
817f0486c68SYan, Zheng 
818f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
819f0486c68SYan, Zheng {
820f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
821f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
822f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
823f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
824f0486c68SYan, Zheng }
825f0486c68SYan, Zheng 
826d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
827d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
828d352ac68SChris Mason  */
8294b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
8304b231ae4SDavid Sterba 					   int slot)
831bb803951SChris Mason {
832ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
833416bc658SJosef Bacik 	struct extent_buffer *eb;
834581c1760SQu Wenruo 	struct btrfs_key first_key;
835416bc658SJosef Bacik 
836fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
837fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
838ca7a79adSChris Mason 
839ca7a79adSChris Mason 	BUG_ON(level == 0);
840ca7a79adSChris Mason 
841581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
842d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
8431b7ec85eSJosef Bacik 			     btrfs_header_owner(parent),
844581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
845581c1760SQu Wenruo 			     level - 1, &first_key);
846fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
847416bc658SJosef Bacik 		free_extent_buffer(eb);
848fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
849416bc658SJosef Bacik 	}
850416bc658SJosef Bacik 
851416bc658SJosef Bacik 	return eb;
852bb803951SChris Mason }
853bb803951SChris Mason 
854d352ac68SChris Mason /*
855d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
856d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
857d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
858d352ac68SChris Mason  */
859e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
86098ed5174SChris Mason 			 struct btrfs_root *root,
86198ed5174SChris Mason 			 struct btrfs_path *path, int level)
862bb803951SChris Mason {
8630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8645f39d397SChris Mason 	struct extent_buffer *right = NULL;
8655f39d397SChris Mason 	struct extent_buffer *mid;
8665f39d397SChris Mason 	struct extent_buffer *left = NULL;
8675f39d397SChris Mason 	struct extent_buffer *parent = NULL;
868bb803951SChris Mason 	int ret = 0;
869bb803951SChris Mason 	int wret;
870bb803951SChris Mason 	int pslot;
871bb803951SChris Mason 	int orig_slot = path->slots[level];
87279f95c82SChris Mason 	u64 orig_ptr;
873bb803951SChris Mason 
87498e6b1ebSLiu Bo 	ASSERT(level > 0);
875bb803951SChris Mason 
8765f39d397SChris Mason 	mid = path->nodes[level];
877b4ce94deSChris Mason 
878ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
8797bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
8807bb86316SChris Mason 
8811d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
88279f95c82SChris Mason 
883a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
8845f39d397SChris Mason 		parent = path->nodes[level + 1];
885bb803951SChris Mason 		pslot = path->slots[level + 1];
886a05a9bb1SLi Zefan 	}
887bb803951SChris Mason 
88840689478SChris Mason 	/*
88940689478SChris Mason 	 * deal with the case where there is only one pointer in the root
89040689478SChris Mason 	 * by promoting the node below to a root
89140689478SChris Mason 	 */
8925f39d397SChris Mason 	if (!parent) {
8935f39d397SChris Mason 		struct extent_buffer *child;
894bb803951SChris Mason 
8955f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
896bb803951SChris Mason 			return 0;
897bb803951SChris Mason 
898bb803951SChris Mason 		/* promote the child to a root */
8994b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
900fb770ae4SLiu Bo 		if (IS_ERR(child)) {
901fb770ae4SLiu Bo 			ret = PTR_ERR(child);
9020b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
903305a26afSMark Fasheh 			goto enospc;
904305a26afSMark Fasheh 		}
905305a26afSMark Fasheh 
906925baeddSChris Mason 		btrfs_tree_lock(child);
9079631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
9089631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
909f0486c68SYan, Zheng 		if (ret) {
910f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
911f0486c68SYan, Zheng 			free_extent_buffer(child);
912f0486c68SYan, Zheng 			goto enospc;
913f0486c68SYan, Zheng 		}
9142f375ab9SYan 
915406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
916d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
917240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
918925baeddSChris Mason 
9190b86a832SChris Mason 		add_root_to_dirty_list(root);
920925baeddSChris Mason 		btrfs_tree_unlock(child);
921b4ce94deSChris Mason 
922925baeddSChris Mason 		path->locks[level] = 0;
923bb803951SChris Mason 		path->nodes[level] = NULL;
9246a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
925925baeddSChris Mason 		btrfs_tree_unlock(mid);
926bb803951SChris Mason 		/* once for the path */
9275f39d397SChris Mason 		free_extent_buffer(mid);
928f0486c68SYan, Zheng 
929f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
9305581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
931bb803951SChris Mason 		/* once for the root ptr */
9323083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
933f0486c68SYan, Zheng 		return 0;
934bb803951SChris Mason 	}
9355f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
9360b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
937bb803951SChris Mason 		return 0;
938bb803951SChris Mason 
9394b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
940fb770ae4SLiu Bo 	if (IS_ERR(left))
941fb770ae4SLiu Bo 		left = NULL;
942fb770ae4SLiu Bo 
9435f39d397SChris Mason 	if (left) {
944bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
9455f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
9469631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
947bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
94854aa1f4dSChris Mason 		if (wret) {
94954aa1f4dSChris Mason 			ret = wret;
95054aa1f4dSChris Mason 			goto enospc;
95154aa1f4dSChris Mason 		}
9522cc58cf2SChris Mason 	}
953fb770ae4SLiu Bo 
9544b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
955fb770ae4SLiu Bo 	if (IS_ERR(right))
956fb770ae4SLiu Bo 		right = NULL;
957fb770ae4SLiu Bo 
9585f39d397SChris Mason 	if (right) {
959bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
9605f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
9619631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
962bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
9632cc58cf2SChris Mason 		if (wret) {
9642cc58cf2SChris Mason 			ret = wret;
9652cc58cf2SChris Mason 			goto enospc;
9662cc58cf2SChris Mason 		}
9672cc58cf2SChris Mason 	}
9682cc58cf2SChris Mason 
9692cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
9705f39d397SChris Mason 	if (left) {
9715f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
972d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
97379f95c82SChris Mason 		if (wret < 0)
97479f95c82SChris Mason 			ret = wret;
975bb803951SChris Mason 	}
97679f95c82SChris Mason 
97779f95c82SChris Mason 	/*
97879f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
97979f95c82SChris Mason 	 */
9805f39d397SChris Mason 	if (right) {
981d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
98254aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
98379f95c82SChris Mason 			ret = wret;
9845f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
9856a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
986925baeddSChris Mason 			btrfs_tree_unlock(right);
987afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
988f0486c68SYan, Zheng 			root_sub_used(root, right->len);
9895581a51aSJan Schmidt 			btrfs_free_tree_block(trans, root, right, 0, 1);
9903083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
991f0486c68SYan, Zheng 			right = NULL;
992bb803951SChris Mason 		} else {
9935f39d397SChris Mason 			struct btrfs_disk_key right_key;
9945f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
995f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
996f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
9970e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
9985f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
9995f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1000bb803951SChris Mason 		}
1001bb803951SChris Mason 	}
10025f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
100379f95c82SChris Mason 		/*
100479f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
100579f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
100679f95c82SChris Mason 		 * could try to delete the only pointer in this node.
100779f95c82SChris Mason 		 * So, pull some keys from the left.
100879f95c82SChris Mason 		 * There has to be a left pointer at this point because
100979f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
101079f95c82SChris Mason 		 * right
101179f95c82SChris Mason 		 */
1012305a26afSMark Fasheh 		if (!left) {
1013305a26afSMark Fasheh 			ret = -EROFS;
10140b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1015305a26afSMark Fasheh 			goto enospc;
1016305a26afSMark Fasheh 		}
101755d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
101854aa1f4dSChris Mason 		if (wret < 0) {
101979f95c82SChris Mason 			ret = wret;
102054aa1f4dSChris Mason 			goto enospc;
102154aa1f4dSChris Mason 		}
1022bce4eae9SChris Mason 		if (wret == 1) {
1023d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1024bce4eae9SChris Mason 			if (wret < 0)
1025bce4eae9SChris Mason 				ret = wret;
1026bce4eae9SChris Mason 		}
102779f95c82SChris Mason 		BUG_ON(wret == 1);
102879f95c82SChris Mason 	}
10295f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
10306a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1031925baeddSChris Mason 		btrfs_tree_unlock(mid);
1032afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1033f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10345581a51aSJan Schmidt 		btrfs_free_tree_block(trans, root, mid, 0, 1);
10353083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1036f0486c68SYan, Zheng 		mid = NULL;
103779f95c82SChris Mason 	} else {
103879f95c82SChris Mason 		/* update the parent key to reflect our changes */
10395f39d397SChris Mason 		struct btrfs_disk_key mid_key;
10405f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1041f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1042f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
10430e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
10445f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
10455f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
104679f95c82SChris Mason 	}
1047bb803951SChris Mason 
104879f95c82SChris Mason 	/* update the path */
10495f39d397SChris Mason 	if (left) {
10505f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
105167439dadSDavid Sterba 			atomic_inc(&left->refs);
1052925baeddSChris Mason 			/* left was locked after cow */
10535f39d397SChris Mason 			path->nodes[level] = left;
1054bb803951SChris Mason 			path->slots[level + 1] -= 1;
1055bb803951SChris Mason 			path->slots[level] = orig_slot;
1056925baeddSChris Mason 			if (mid) {
1057925baeddSChris Mason 				btrfs_tree_unlock(mid);
10585f39d397SChris Mason 				free_extent_buffer(mid);
1059925baeddSChris Mason 			}
1060bb803951SChris Mason 		} else {
10615f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1062bb803951SChris Mason 			path->slots[level] = orig_slot;
1063bb803951SChris Mason 		}
1064bb803951SChris Mason 	}
106579f95c82SChris Mason 	/* double check we haven't messed things up */
1066e20d96d6SChris Mason 	if (orig_ptr !=
10675f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
106879f95c82SChris Mason 		BUG();
106954aa1f4dSChris Mason enospc:
1070925baeddSChris Mason 	if (right) {
1071925baeddSChris Mason 		btrfs_tree_unlock(right);
10725f39d397SChris Mason 		free_extent_buffer(right);
1073925baeddSChris Mason 	}
1074925baeddSChris Mason 	if (left) {
1075925baeddSChris Mason 		if (path->nodes[level] != left)
1076925baeddSChris Mason 			btrfs_tree_unlock(left);
10775f39d397SChris Mason 		free_extent_buffer(left);
1078925baeddSChris Mason 	}
1079bb803951SChris Mason 	return ret;
1080bb803951SChris Mason }
1081bb803951SChris Mason 
1082d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1083d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1084d352ac68SChris Mason  * have to be pessimistic.
1085d352ac68SChris Mason  */
1086d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1087e66f709bSChris Mason 					  struct btrfs_root *root,
1088e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1089e66f709bSChris Mason {
10900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10915f39d397SChris Mason 	struct extent_buffer *right = NULL;
10925f39d397SChris Mason 	struct extent_buffer *mid;
10935f39d397SChris Mason 	struct extent_buffer *left = NULL;
10945f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1095e66f709bSChris Mason 	int ret = 0;
1096e66f709bSChris Mason 	int wret;
1097e66f709bSChris Mason 	int pslot;
1098e66f709bSChris Mason 	int orig_slot = path->slots[level];
1099e66f709bSChris Mason 
1100e66f709bSChris Mason 	if (level == 0)
1101e66f709bSChris Mason 		return 1;
1102e66f709bSChris Mason 
11035f39d397SChris Mason 	mid = path->nodes[level];
11047bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1105e66f709bSChris Mason 
1106a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
11075f39d397SChris Mason 		parent = path->nodes[level + 1];
1108e66f709bSChris Mason 		pslot = path->slots[level + 1];
1109a05a9bb1SLi Zefan 	}
1110e66f709bSChris Mason 
11115f39d397SChris Mason 	if (!parent)
1112e66f709bSChris Mason 		return 1;
1113e66f709bSChris Mason 
11144b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1115fb770ae4SLiu Bo 	if (IS_ERR(left))
1116fb770ae4SLiu Bo 		left = NULL;
1117e66f709bSChris Mason 
1118e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
11195f39d397SChris Mason 	if (left) {
1120e66f709bSChris Mason 		u32 left_nr;
1121925baeddSChris Mason 
1122bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1123b4ce94deSChris Mason 
11245f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
11250b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
112633ade1f8SChris Mason 			wret = 1;
112733ade1f8SChris Mason 		} else {
11285f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
11299631e4ccSJosef Bacik 					      pslot - 1, &left,
1130bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
113154aa1f4dSChris Mason 			if (ret)
113254aa1f4dSChris Mason 				wret = 1;
113354aa1f4dSChris Mason 			else {
1134d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
113554aa1f4dSChris Mason 			}
113633ade1f8SChris Mason 		}
1137e66f709bSChris Mason 		if (wret < 0)
1138e66f709bSChris Mason 			ret = wret;
1139e66f709bSChris Mason 		if (wret == 0) {
11405f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1141e66f709bSChris Mason 			orig_slot += left_nr;
11425f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1143f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1144f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
11450e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11465f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
11475f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
11485f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
11495f39d397SChris Mason 				path->nodes[level] = left;
1150e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1151e66f709bSChris Mason 				path->slots[level] = orig_slot;
1152925baeddSChris Mason 				btrfs_tree_unlock(mid);
11535f39d397SChris Mason 				free_extent_buffer(mid);
1154e66f709bSChris Mason 			} else {
1155e66f709bSChris Mason 				orig_slot -=
11565f39d397SChris Mason 					btrfs_header_nritems(left);
1157e66f709bSChris Mason 				path->slots[level] = orig_slot;
1158925baeddSChris Mason 				btrfs_tree_unlock(left);
11595f39d397SChris Mason 				free_extent_buffer(left);
1160e66f709bSChris Mason 			}
1161e66f709bSChris Mason 			return 0;
1162e66f709bSChris Mason 		}
1163925baeddSChris Mason 		btrfs_tree_unlock(left);
11645f39d397SChris Mason 		free_extent_buffer(left);
1165e66f709bSChris Mason 	}
11664b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1167fb770ae4SLiu Bo 	if (IS_ERR(right))
1168fb770ae4SLiu Bo 		right = NULL;
1169e66f709bSChris Mason 
1170e66f709bSChris Mason 	/*
1171e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1172e66f709bSChris Mason 	 */
11735f39d397SChris Mason 	if (right) {
117433ade1f8SChris Mason 		u32 right_nr;
1175b4ce94deSChris Mason 
1176bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1177b4ce94deSChris Mason 
11785f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
11790b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
118033ade1f8SChris Mason 			wret = 1;
118133ade1f8SChris Mason 		} else {
11825f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
11835f39d397SChris Mason 					      parent, pslot + 1,
1184bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
118554aa1f4dSChris Mason 			if (ret)
118654aa1f4dSChris Mason 				wret = 1;
118754aa1f4dSChris Mason 			else {
118855d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
118933ade1f8SChris Mason 			}
119054aa1f4dSChris Mason 		}
1191e66f709bSChris Mason 		if (wret < 0)
1192e66f709bSChris Mason 			ret = wret;
1193e66f709bSChris Mason 		if (wret == 0) {
11945f39d397SChris Mason 			struct btrfs_disk_key disk_key;
11955f39d397SChris Mason 
11965f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1197f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1198f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
11990e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
12005f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
12015f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12025f39d397SChris Mason 
12035f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
12045f39d397SChris Mason 				path->nodes[level] = right;
1205e66f709bSChris Mason 				path->slots[level + 1] += 1;
1206e66f709bSChris Mason 				path->slots[level] = orig_slot -
12075f39d397SChris Mason 					btrfs_header_nritems(mid);
1208925baeddSChris Mason 				btrfs_tree_unlock(mid);
12095f39d397SChris Mason 				free_extent_buffer(mid);
1210e66f709bSChris Mason 			} else {
1211925baeddSChris Mason 				btrfs_tree_unlock(right);
12125f39d397SChris Mason 				free_extent_buffer(right);
1213e66f709bSChris Mason 			}
1214e66f709bSChris Mason 			return 0;
1215e66f709bSChris Mason 		}
1216925baeddSChris Mason 		btrfs_tree_unlock(right);
12175f39d397SChris Mason 		free_extent_buffer(right);
1218e66f709bSChris Mason 	}
1219e66f709bSChris Mason 	return 1;
1220e66f709bSChris Mason }
1221e66f709bSChris Mason 
122274123bd7SChris Mason /*
1223d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1224d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
12253c69faecSChris Mason  */
12262ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1227e02119d5SChris Mason 			     struct btrfs_path *path,
122801f46658SChris Mason 			     int level, int slot, u64 objectid)
12293c69faecSChris Mason {
12305f39d397SChris Mason 	struct extent_buffer *node;
123101f46658SChris Mason 	struct btrfs_disk_key disk_key;
12323c69faecSChris Mason 	u32 nritems;
12333c69faecSChris Mason 	u64 search;
1234a7175319SChris Mason 	u64 target;
12356b80053dSChris Mason 	u64 nread = 0;
1236ace75066SFilipe Manana 	u64 nread_max;
12376b80053dSChris Mason 	u32 nr;
12386b80053dSChris Mason 	u32 blocksize;
12396b80053dSChris Mason 	u32 nscan = 0;
1240db94535dSChris Mason 
1241ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
12423c69faecSChris Mason 		return;
12433c69faecSChris Mason 
12446702ed49SChris Mason 	if (!path->nodes[level])
12456702ed49SChris Mason 		return;
12466702ed49SChris Mason 
12475f39d397SChris Mason 	node = path->nodes[level];
1248925baeddSChris Mason 
1249ace75066SFilipe Manana 	/*
1250ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1251ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1252ace75066SFilipe Manana 	 * much IO at once (possibly random).
1253ace75066SFilipe Manana 	 */
1254ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1255ace75066SFilipe Manana 		if (level > 1)
1256ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1257ace75066SFilipe Manana 		else
1258ace75066SFilipe Manana 			nread_max = SZ_128K;
1259ace75066SFilipe Manana 	} else {
1260ace75066SFilipe Manana 		nread_max = SZ_64K;
1261ace75066SFilipe Manana 	}
1262ace75066SFilipe Manana 
12633c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
12640b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1265069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1266069a2e37SFilipe Manana 		struct extent_buffer *eb;
1267069a2e37SFilipe Manana 
12680b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
12695f39d397SChris Mason 		if (eb) {
12705f39d397SChris Mason 			free_extent_buffer(eb);
12713c69faecSChris Mason 			return;
12723c69faecSChris Mason 		}
1273069a2e37SFilipe Manana 	}
12743c69faecSChris Mason 
1275a7175319SChris Mason 	target = search;
12766b80053dSChris Mason 
12775f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
12786b80053dSChris Mason 	nr = slot;
127925b8b936SJosef Bacik 
12803c69faecSChris Mason 	while (1) {
1281e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
12826b80053dSChris Mason 			if (nr == 0)
12833c69faecSChris Mason 				break;
12846b80053dSChris Mason 			nr--;
1285ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1286ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
12876b80053dSChris Mason 			nr++;
12886b80053dSChris Mason 			if (nr >= nritems)
12896b80053dSChris Mason 				break;
12903c69faecSChris Mason 		}
1291e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
129201f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
129301f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
129401f46658SChris Mason 				break;
129501f46658SChris Mason 		}
12966b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1297ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1298ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1299a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1300bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
13016b80053dSChris Mason 			nread += blocksize;
13023c69faecSChris Mason 		}
13036b80053dSChris Mason 		nscan++;
1304ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
13056b80053dSChris Mason 			break;
13063c69faecSChris Mason 	}
13073c69faecSChris Mason }
1308925baeddSChris Mason 
1309bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1310b4ce94deSChris Mason {
1311bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1312b4ce94deSChris Mason 	int slot;
1313b4ce94deSChris Mason 	int nritems;
1314b4ce94deSChris Mason 
13158c594ea8SChris Mason 	parent = path->nodes[level + 1];
1316b4ce94deSChris Mason 	if (!parent)
13170b08851fSJosef Bacik 		return;
1318b4ce94deSChris Mason 
1319b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
13208c594ea8SChris Mason 	slot = path->slots[level + 1];
1321b4ce94deSChris Mason 
1322bfb484d9SJosef Bacik 	if (slot > 0)
1323bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1324bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1325bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1326b4ce94deSChris Mason }
1327b4ce94deSChris Mason 
1328b4ce94deSChris Mason 
1329b4ce94deSChris Mason /*
1330d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1331d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1332d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1333d397712bSChris Mason  * tree.
1334d352ac68SChris Mason  *
1335d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1336d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1337d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1338d352ac68SChris Mason  *
1339d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1340d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1341d352ac68SChris Mason  */
1342e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1343f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1344f7c79f30SChris Mason 			       int *write_lock_level)
1345925baeddSChris Mason {
1346925baeddSChris Mason 	int i;
1347925baeddSChris Mason 	int skip_level = level;
1348051e1b9fSChris Mason 	int no_skips = 0;
1349925baeddSChris Mason 	struct extent_buffer *t;
1350925baeddSChris Mason 
1351925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1352925baeddSChris Mason 		if (!path->nodes[i])
1353925baeddSChris Mason 			break;
1354925baeddSChris Mason 		if (!path->locks[i])
1355925baeddSChris Mason 			break;
1356051e1b9fSChris Mason 		if (!no_skips && path->slots[i] == 0) {
1357925baeddSChris Mason 			skip_level = i + 1;
1358925baeddSChris Mason 			continue;
1359925baeddSChris Mason 		}
1360051e1b9fSChris Mason 		if (!no_skips && path->keep_locks) {
1361925baeddSChris Mason 			u32 nritems;
1362925baeddSChris Mason 			t = path->nodes[i];
1363925baeddSChris Mason 			nritems = btrfs_header_nritems(t);
1364051e1b9fSChris Mason 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
1365925baeddSChris Mason 				skip_level = i + 1;
1366925baeddSChris Mason 				continue;
1367925baeddSChris Mason 			}
1368925baeddSChris Mason 		}
1369051e1b9fSChris Mason 		if (skip_level < i && i >= lowest_unlock)
1370051e1b9fSChris Mason 			no_skips = 1;
1371051e1b9fSChris Mason 
1372925baeddSChris Mason 		t = path->nodes[i];
1373d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1374bd681513SChris Mason 			btrfs_tree_unlock_rw(t, path->locks[i]);
1375925baeddSChris Mason 			path->locks[i] = 0;
1376f7c79f30SChris Mason 			if (write_lock_level &&
1377f7c79f30SChris Mason 			    i > min_write_lock_level &&
1378f7c79f30SChris Mason 			    i <= *write_lock_level) {
1379f7c79f30SChris Mason 				*write_lock_level = i - 1;
1380f7c79f30SChris Mason 			}
1381925baeddSChris Mason 		}
1382925baeddSChris Mason 	}
1383925baeddSChris Mason }
1384925baeddSChris Mason 
13853c69faecSChris Mason /*
1386c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
1387c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
1388c8c42864SChris Mason  * we return zero and the path is unchanged.
1389c8c42864SChris Mason  *
1390c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
1391c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
1392c8c42864SChris Mason  */
1393c8c42864SChris Mason static int
1394d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1395c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1396cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1397c8c42864SChris Mason {
13980b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1399c8c42864SChris Mason 	u64 blocknr;
1400c8c42864SChris Mason 	u64 gen;
1401c8c42864SChris Mason 	struct extent_buffer *tmp;
1402581c1760SQu Wenruo 	struct btrfs_key first_key;
140376a05b35SChris Mason 	int ret;
1404581c1760SQu Wenruo 	int parent_level;
1405c8c42864SChris Mason 
1406213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1407213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1408213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1409213ff4b7SNikolay Borisov 	btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
1410c8c42864SChris Mason 
14110b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1412cb44921aSChris Mason 	if (tmp) {
1413ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1414ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1415ace75066SFilipe Manana 
1416b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1417b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1418448de471SQu Wenruo 			/*
1419448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1420448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1421448de471SQu Wenruo 			 * parents (shared tree blocks).
1422448de471SQu Wenruo 			 */
1423e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1424448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
1425448de471SQu Wenruo 				free_extent_buffer(tmp);
1426448de471SQu Wenruo 				return -EUCLEAN;
1427448de471SQu Wenruo 			}
1428c8c42864SChris Mason 			*eb_ret = tmp;
1429c8c42864SChris Mason 			return 0;
1430c8c42864SChris Mason 		}
1431bdf7c00eSJosef Bacik 
1432b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
1433581c1760SQu Wenruo 		ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
1434bdf7c00eSJosef Bacik 		if (!ret) {
1435cb44921aSChris Mason 			*eb_ret = tmp;
1436cb44921aSChris Mason 			return 0;
1437cb44921aSChris Mason 		}
1438cb44921aSChris Mason 		free_extent_buffer(tmp);
1439b3b4aa74SDavid Sterba 		btrfs_release_path(p);
1440cb44921aSChris Mason 		return -EIO;
1441cb44921aSChris Mason 	}
1442c8c42864SChris Mason 
1443c8c42864SChris Mason 	/*
1444c8c42864SChris Mason 	 * reduce lock contention at high levels
1445c8c42864SChris Mason 	 * of the btree by dropping locks before
144676a05b35SChris Mason 	 * we read.  Don't release the lock on the current
144776a05b35SChris Mason 	 * level because we need to walk this node to figure
144876a05b35SChris Mason 	 * out which blocks to read.
1449c8c42864SChris Mason 	 */
14508c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
14518c594ea8SChris Mason 
1452e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
14532ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1454c8c42864SChris Mason 
145576a05b35SChris Mason 	ret = -EAGAIN;
14561b7ec85eSJosef Bacik 	tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
14571b7ec85eSJosef Bacik 			      gen, parent_level - 1, &first_key);
145864c043deSLiu Bo 	if (!IS_ERR(tmp)) {
145976a05b35SChris Mason 		/*
146076a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
146176a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
146276a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
146376a05b35SChris Mason 		 * on our EAGAINs.
146476a05b35SChris Mason 		 */
1465e6a1d6fdSLiu Bo 		if (!extent_buffer_uptodate(tmp))
146676a05b35SChris Mason 			ret = -EIO;
1467c8c42864SChris Mason 		free_extent_buffer(tmp);
1468c871b0f2SLiu Bo 	} else {
1469c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
147076a05b35SChris Mason 	}
147102a3307aSLiu Bo 
147202a3307aSLiu Bo 	btrfs_release_path(p);
147376a05b35SChris Mason 	return ret;
1474c8c42864SChris Mason }
1475c8c42864SChris Mason 
1476c8c42864SChris Mason /*
1477c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1478c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1479c8c42864SChris Mason  * the ins_len.
1480c8c42864SChris Mason  *
1481c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1482c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1483c8c42864SChris Mason  * start over
1484c8c42864SChris Mason  */
1485c8c42864SChris Mason static int
1486c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1487c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1488bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1489bd681513SChris Mason 		       int *write_lock_level)
1490c8c42864SChris Mason {
14910b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
149295b982deSNikolay Borisov 	int ret = 0;
14930b246afaSJeff Mahoney 
1494c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
14950b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1496c8c42864SChris Mason 
1497bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1498bd681513SChris Mason 			*write_lock_level = level + 1;
1499bd681513SChris Mason 			btrfs_release_path(p);
150095b982deSNikolay Borisov 			return -EAGAIN;
1501bd681513SChris Mason 		}
1502bd681513SChris Mason 
1503bfb484d9SJosef Bacik 		reada_for_balance(p, level);
150495b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1505c8c42864SChris Mason 
1506c8c42864SChris Mason 		b = p->nodes[level];
1507c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
15080b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1509c8c42864SChris Mason 
1510bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1511bd681513SChris Mason 			*write_lock_level = level + 1;
1512bd681513SChris Mason 			btrfs_release_path(p);
151395b982deSNikolay Borisov 			return -EAGAIN;
1514bd681513SChris Mason 		}
1515bd681513SChris Mason 
1516bfb484d9SJosef Bacik 		reada_for_balance(p, level);
151795b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
151895b982deSNikolay Borisov 		if (ret)
151995b982deSNikolay Borisov 			return ret;
1520c8c42864SChris Mason 
1521c8c42864SChris Mason 		b = p->nodes[level];
1522c8c42864SChris Mason 		if (!b) {
1523b3b4aa74SDavid Sterba 			btrfs_release_path(p);
152495b982deSNikolay Borisov 			return -EAGAIN;
1525c8c42864SChris Mason 		}
1526c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1527c8c42864SChris Mason 	}
1528c8c42864SChris Mason 	return ret;
1529c8c42864SChris Mason }
1530c8c42864SChris Mason 
1531381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1532e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1533e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1534e33d5c3dSKelley Nielsen {
1535e33d5c3dSKelley Nielsen 	int ret;
1536e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1537e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1538381cf658SDavid Sterba 
1539381cf658SDavid Sterba 	ASSERT(path);
15401d4c08e0SDavid Sterba 	ASSERT(found_key);
1541e33d5c3dSKelley Nielsen 
1542e33d5c3dSKelley Nielsen 	key.type = key_type;
1543e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1544e33d5c3dSKelley Nielsen 	key.offset = ioff;
1545e33d5c3dSKelley Nielsen 
1546e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
15471d4c08e0SDavid Sterba 	if (ret < 0)
1548e33d5c3dSKelley Nielsen 		return ret;
1549e33d5c3dSKelley Nielsen 
1550e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1551e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1552e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1553e33d5c3dSKelley Nielsen 		if (ret)
1554e33d5c3dSKelley Nielsen 			return ret;
1555e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1556e33d5c3dSKelley Nielsen 	}
1557e33d5c3dSKelley Nielsen 
1558e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1559e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1560e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1561e33d5c3dSKelley Nielsen 		return 1;
1562e33d5c3dSKelley Nielsen 
1563e33d5c3dSKelley Nielsen 	return 0;
1564e33d5c3dSKelley Nielsen }
1565e33d5c3dSKelley Nielsen 
15661fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
15671fc28d8eSLiu Bo 							struct btrfs_path *p,
15681fc28d8eSLiu Bo 							int write_lock_level)
15691fc28d8eSLiu Bo {
15701fc28d8eSLiu Bo 	struct btrfs_fs_info *fs_info = root->fs_info;
15711fc28d8eSLiu Bo 	struct extent_buffer *b;
15721fc28d8eSLiu Bo 	int root_lock;
15731fc28d8eSLiu Bo 	int level = 0;
15741fc28d8eSLiu Bo 
15751fc28d8eSLiu Bo 	/* We try very hard to do read locks on the root */
15761fc28d8eSLiu Bo 	root_lock = BTRFS_READ_LOCK;
15771fc28d8eSLiu Bo 
15781fc28d8eSLiu Bo 	if (p->search_commit_root) {
1579be6821f8SFilipe Manana 		/*
1580be6821f8SFilipe Manana 		 * The commit roots are read only so we always do read locks,
1581be6821f8SFilipe Manana 		 * and we always must hold the commit_root_sem when doing
1582be6821f8SFilipe Manana 		 * searches on them, the only exception is send where we don't
1583be6821f8SFilipe Manana 		 * want to block transaction commits for a long time, so
1584be6821f8SFilipe Manana 		 * we need to clone the commit root in order to avoid races
1585be6821f8SFilipe Manana 		 * with transaction commits that create a snapshot of one of
1586be6821f8SFilipe Manana 		 * the roots used by a send operation.
1587be6821f8SFilipe Manana 		 */
1588be6821f8SFilipe Manana 		if (p->need_commit_sem) {
15891fc28d8eSLiu Bo 			down_read(&fs_info->commit_root_sem);
1590be6821f8SFilipe Manana 			b = btrfs_clone_extent_buffer(root->commit_root);
1591be6821f8SFilipe Manana 			up_read(&fs_info->commit_root_sem);
1592be6821f8SFilipe Manana 			if (!b)
1593be6821f8SFilipe Manana 				return ERR_PTR(-ENOMEM);
1594be6821f8SFilipe Manana 
1595be6821f8SFilipe Manana 		} else {
15961fc28d8eSLiu Bo 			b = root->commit_root;
159767439dadSDavid Sterba 			atomic_inc(&b->refs);
1598be6821f8SFilipe Manana 		}
15991fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1600f9ddfd05SLiu Bo 		/*
1601f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1602f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1603f9ddfd05SLiu Bo 		 */
1604f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
16051fc28d8eSLiu Bo 
16061fc28d8eSLiu Bo 		goto out;
16071fc28d8eSLiu Bo 	}
16081fc28d8eSLiu Bo 
16091fc28d8eSLiu Bo 	if (p->skip_locking) {
16101fc28d8eSLiu Bo 		b = btrfs_root_node(root);
16111fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16121fc28d8eSLiu Bo 		goto out;
16131fc28d8eSLiu Bo 	}
16141fc28d8eSLiu Bo 
16151fc28d8eSLiu Bo 	/*
1616662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1617662c653bSLiu Bo 	 * lock.
1618662c653bSLiu Bo 	 */
1619662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1620662c653bSLiu Bo 		/*
1621662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1622662c653bSLiu Bo 		 * have it read locked
16231fc28d8eSLiu Bo 		 */
16241bb96598SJosef Bacik 		b = btrfs_read_lock_root_node(root);
16251fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16261fc28d8eSLiu Bo 		if (level > write_lock_level)
16271fc28d8eSLiu Bo 			goto out;
16281fc28d8eSLiu Bo 
1629662c653bSLiu Bo 		/* Whoops, must trade for write lock */
16301fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
16311fc28d8eSLiu Bo 		free_extent_buffer(b);
1632662c653bSLiu Bo 	}
1633662c653bSLiu Bo 
16341fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
16351fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
16361fc28d8eSLiu Bo 
16371fc28d8eSLiu Bo 	/* The level might have changed, check again */
16381fc28d8eSLiu Bo 	level = btrfs_header_level(b);
16391fc28d8eSLiu Bo 
16401fc28d8eSLiu Bo out:
16411fc28d8eSLiu Bo 	p->nodes[level] = b;
16421fc28d8eSLiu Bo 	if (!p->skip_locking)
16431fc28d8eSLiu Bo 		p->locks[level] = root_lock;
16441fc28d8eSLiu Bo 	/*
16451fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
16461fc28d8eSLiu Bo 	 */
16471fc28d8eSLiu Bo 	return b;
16481fc28d8eSLiu Bo }
16491fc28d8eSLiu Bo 
16501fc28d8eSLiu Bo 
1651c8c42864SChris Mason /*
16524271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
16534271eceaSNikolay Borisov  * modifications to preserve tree invariants.
165474123bd7SChris Mason  *
16554271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
16564271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
16574271eceaSNikolay Borisov  * @root:	The root node of the tree
16584271eceaSNikolay Borisov  * @key:	The key we are looking for
16599a664971Sethanwu  * @ins_len:	Indicates purpose of search:
16609a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
16619a664971Sethanwu  *              <0  for deletions
16629a664971Sethanwu  *               0  for plain searches, not modifying the tree
16639a664971Sethanwu  *
16649a664971Sethanwu  *              (*) If size of item inserted doesn't include
16659a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
16669a664971Sethanwu  *              be set.
16674271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
16684271eceaSNikolay Borisov  *		when modifying the tree.
166997571fd0SChris Mason  *
16704271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
16714271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
16724271eceaSNikolay Borisov  *
16734271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
16744271eceaSNikolay Borisov  * of the path (level 0)
16754271eceaSNikolay Borisov  *
16764271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
16774271eceaSNikolay Borisov  * points to the slot where it should be inserted
16784271eceaSNikolay Borisov  *
16794271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
16804271eceaSNikolay Borisov  * is returned
168174123bd7SChris Mason  */
1682310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1683310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
1684310712b2SOmar Sandoval 		      int ins_len, int cow)
1685be0e5c09SChris Mason {
16865f39d397SChris Mason 	struct extent_buffer *b;
1687be0e5c09SChris Mason 	int slot;
1688be0e5c09SChris Mason 	int ret;
168933c66f43SYan Zheng 	int err;
1690be0e5c09SChris Mason 	int level;
1691925baeddSChris Mason 	int lowest_unlock = 1;
1692bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
1693bd681513SChris Mason 	int write_lock_level = 0;
16949f3a7427SChris Mason 	u8 lowest_level = 0;
1695f7c79f30SChris Mason 	int min_write_lock_level;
1696d7396f07SFilipe David Borba Manana 	int prev_cmp;
16979f3a7427SChris Mason 
16986702ed49SChris Mason 	lowest_level = p->lowest_level;
1699323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
170022b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
1701eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
170225179201SJosef Bacik 
1703bd681513SChris Mason 	if (ins_len < 0) {
1704925baeddSChris Mason 		lowest_unlock = 2;
170565b51a00SChris Mason 
1706bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
1707bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
1708bd681513SChris Mason 		 * for those levels as well
1709bd681513SChris Mason 		 */
1710bd681513SChris Mason 		write_lock_level = 2;
1711bd681513SChris Mason 	} else if (ins_len > 0) {
1712bd681513SChris Mason 		/*
1713bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
1714bd681513SChris Mason 		 * level 1 so we can update keys
1715bd681513SChris Mason 		 */
1716bd681513SChris Mason 		write_lock_level = 1;
1717bd681513SChris Mason 	}
1718bd681513SChris Mason 
1719bd681513SChris Mason 	if (!cow)
1720bd681513SChris Mason 		write_lock_level = -1;
1721bd681513SChris Mason 
172209a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
1723bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
1724bd681513SChris Mason 
1725f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
1726f7c79f30SChris Mason 
1727bb803951SChris Mason again:
1728d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
17291fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
1730be6821f8SFilipe Manana 	if (IS_ERR(b)) {
1731be6821f8SFilipe Manana 		ret = PTR_ERR(b);
1732be6821f8SFilipe Manana 		goto done;
1733be6821f8SFilipe Manana 	}
1734925baeddSChris Mason 
1735eb60ceacSChris Mason 	while (b) {
1736f624d976SQu Wenruo 		int dec = 0;
1737f624d976SQu Wenruo 
17385f39d397SChris Mason 		level = btrfs_header_level(b);
173965b51a00SChris Mason 
174002217ed2SChris Mason 		if (cow) {
17419ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
17429ea2c7c9SNikolay Borisov 
1743c8c42864SChris Mason 			/*
1744c8c42864SChris Mason 			 * if we don't really need to cow this block
1745c8c42864SChris Mason 			 * then we don't want to set the path blocking,
1746c8c42864SChris Mason 			 * so we test it here
1747c8c42864SChris Mason 			 */
17485963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
174965b51a00SChris Mason 				goto cow_done;
17505d4f98a2SYan Zheng 
1751bd681513SChris Mason 			/*
1752bd681513SChris Mason 			 * must have write locks on this node and the
1753bd681513SChris Mason 			 * parent
1754bd681513SChris Mason 			 */
17555124e00eSJosef Bacik 			if (level > write_lock_level ||
17565124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
17575124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
17585124e00eSJosef Bacik 			    p->nodes[level + 1])) {
1759bd681513SChris Mason 				write_lock_level = level + 1;
1760bd681513SChris Mason 				btrfs_release_path(p);
1761bd681513SChris Mason 				goto again;
1762bd681513SChris Mason 			}
1763bd681513SChris Mason 
17649ea2c7c9SNikolay Borisov 			if (last_level)
17659ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
17669631e4ccSJosef Bacik 						      &b,
17679631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
17689ea2c7c9SNikolay Borisov 			else
176933c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
1770e20d96d6SChris Mason 						      p->nodes[level + 1],
17719631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
17729631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
177333c66f43SYan Zheng 			if (err) {
177433c66f43SYan Zheng 				ret = err;
177565b51a00SChris Mason 				goto done;
177654aa1f4dSChris Mason 			}
177702217ed2SChris Mason 		}
177865b51a00SChris Mason cow_done:
1779eb60ceacSChris Mason 		p->nodes[level] = b;
178052398340SLiu Bo 		/*
178152398340SLiu Bo 		 * Leave path with blocking locks to avoid massive
178252398340SLiu Bo 		 * lock context switch, this is made on purpose.
178352398340SLiu Bo 		 */
1784b4ce94deSChris Mason 
1785b4ce94deSChris Mason 		/*
1786b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
1787b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
1788b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
1789b4ce94deSChris Mason 		 * go through the expensive btree search on b.
1790b4ce94deSChris Mason 		 *
1791eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
1792eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
1793eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
1794eb653de1SFilipe David Borba Manana 		 * we're operating on.
1795b4ce94deSChris Mason 		 */
1796eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
1797eb653de1SFilipe David Borba Manana 			int u = level + 1;
1798eb653de1SFilipe David Borba Manana 
1799eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
1800eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
1801eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
1802eb653de1SFilipe David Borba Manana 			}
1803eb653de1SFilipe David Borba Manana 		}
1804b4ce94deSChris Mason 
1805995e9a16SNikolay Borisov 		/*
1806995e9a16SNikolay Borisov 		 * If btrfs_bin_search returns an exact match (prev_cmp == 0)
1807995e9a16SNikolay Borisov 		 * we can safely assume the target key will always be in slot 0
1808995e9a16SNikolay Borisov 		 * on lower levels due to the invariants BTRFS' btree provides,
1809995e9a16SNikolay Borisov 		 * namely that a btrfs_key_ptr entry always points to the
1810995e9a16SNikolay Borisov 		 * lowest key in the child node, thus we can skip searching
1811995e9a16SNikolay Borisov 		 * lower levels
1812995e9a16SNikolay Borisov 		 */
1813995e9a16SNikolay Borisov 		if (prev_cmp == 0) {
1814995e9a16SNikolay Borisov 			slot = 0;
1815995e9a16SNikolay Borisov 			ret = 0;
1816995e9a16SNikolay Borisov 		} else {
1817995e9a16SNikolay Borisov 			ret = btrfs_bin_search(b, key, &slot);
1818995e9a16SNikolay Borisov 			prev_cmp = ret;
1819415b35a5SLiu Bo 			if (ret < 0)
1820415b35a5SLiu Bo 				goto done;
1821995e9a16SNikolay Borisov 		}
1822b4ce94deSChris Mason 
1823f624d976SQu Wenruo 		if (level == 0) {
1824be0e5c09SChris Mason 			p->slots[level] = slot;
18259a664971Sethanwu 			/*
18269a664971Sethanwu 			 * Item key already exists. In this case, if we are
18279a664971Sethanwu 			 * allowed to insert the item (for example, in dir_item
18289a664971Sethanwu 			 * case, item key collision is allowed), it will be
18299a664971Sethanwu 			 * merged with the original item. Only the item size
18309a664971Sethanwu 			 * grows, no new btrfs item will be added. If
18319a664971Sethanwu 			 * search_for_extension is not set, ins_len already
18329a664971Sethanwu 			 * accounts the size btrfs_item, deduct it here so leaf
18339a664971Sethanwu 			 * space check will be correct.
18349a664971Sethanwu 			 */
18359a664971Sethanwu 			if (ret == 0 && ins_len > 0 && !p->search_for_extension) {
18369a664971Sethanwu 				ASSERT(ins_len >= sizeof(struct btrfs_item));
18379a664971Sethanwu 				ins_len -= sizeof(struct btrfs_item);
18389a664971Sethanwu 			}
183987b29b20SYan Zheng 			if (ins_len > 0 &&
1840e902baacSDavid Sterba 			    btrfs_leaf_free_space(b) < ins_len) {
1841bd681513SChris Mason 				if (write_lock_level < 1) {
1842bd681513SChris Mason 					write_lock_level = 1;
1843bd681513SChris Mason 					btrfs_release_path(p);
1844bd681513SChris Mason 					goto again;
1845bd681513SChris Mason 				}
1846bd681513SChris Mason 
184733c66f43SYan Zheng 				err = split_leaf(trans, root, key,
1848cc0c5538SChris Mason 						 p, ins_len, ret == 0);
1849b4ce94deSChris Mason 
185033c66f43SYan Zheng 				BUG_ON(err > 0);
185133c66f43SYan Zheng 				if (err) {
185233c66f43SYan Zheng 					ret = err;
185365b51a00SChris Mason 					goto done;
185465b51a00SChris Mason 				}
18555c680ed6SChris Mason 			}
1856459931ecSChris Mason 			if (!p->search_for_split)
1857f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
18584b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
185965b51a00SChris Mason 			goto done;
186065b51a00SChris Mason 		}
1861f624d976SQu Wenruo 		if (ret && slot > 0) {
1862f624d976SQu Wenruo 			dec = 1;
1863f624d976SQu Wenruo 			slot--;
1864f624d976SQu Wenruo 		}
1865f624d976SQu Wenruo 		p->slots[level] = slot;
1866f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
1867f624d976SQu Wenruo 					     &write_lock_level);
1868f624d976SQu Wenruo 		if (err == -EAGAIN)
1869f624d976SQu Wenruo 			goto again;
1870f624d976SQu Wenruo 		if (err) {
1871f624d976SQu Wenruo 			ret = err;
1872f624d976SQu Wenruo 			goto done;
1873f624d976SQu Wenruo 		}
1874f624d976SQu Wenruo 		b = p->nodes[level];
1875f624d976SQu Wenruo 		slot = p->slots[level];
1876f624d976SQu Wenruo 
1877f624d976SQu Wenruo 		/*
1878f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
1879f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
1880f624d976SQu Wenruo 		 * the parent
1881f624d976SQu Wenruo 		 */
1882f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
1883f624d976SQu Wenruo 			write_lock_level = level + 1;
1884f624d976SQu Wenruo 			btrfs_release_path(p);
1885f624d976SQu Wenruo 			goto again;
1886f624d976SQu Wenruo 		}
1887f624d976SQu Wenruo 
1888f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
1889f624d976SQu Wenruo 			  &write_lock_level);
1890f624d976SQu Wenruo 
1891f624d976SQu Wenruo 		if (level == lowest_level) {
1892f624d976SQu Wenruo 			if (dec)
1893f624d976SQu Wenruo 				p->slots[level]++;
1894f624d976SQu Wenruo 			goto done;
1895f624d976SQu Wenruo 		}
1896f624d976SQu Wenruo 
1897f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
1898f624d976SQu Wenruo 		if (err == -EAGAIN)
1899f624d976SQu Wenruo 			goto again;
1900f624d976SQu Wenruo 		if (err) {
1901f624d976SQu Wenruo 			ret = err;
1902f624d976SQu Wenruo 			goto done;
1903f624d976SQu Wenruo 		}
1904f624d976SQu Wenruo 
1905f624d976SQu Wenruo 		if (!p->skip_locking) {
1906f624d976SQu Wenruo 			level = btrfs_header_level(b);
1907f624d976SQu Wenruo 			if (level <= write_lock_level) {
1908f624d976SQu Wenruo 				btrfs_tree_lock(b);
1909f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
1910f624d976SQu Wenruo 			} else {
1911fe596ca3SJosef Bacik 				btrfs_tree_read_lock(b);
1912f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
1913f624d976SQu Wenruo 			}
1914f624d976SQu Wenruo 			p->nodes[level] = b;
1915f624d976SQu Wenruo 		}
191665b51a00SChris Mason 	}
191765b51a00SChris Mason 	ret = 1;
191865b51a00SChris Mason done:
19195f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
1920b3b4aa74SDavid Sterba 		btrfs_release_path(p);
1921be0e5c09SChris Mason 	return ret;
1922be0e5c09SChris Mason }
1923f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
1924be0e5c09SChris Mason 
192574123bd7SChris Mason /*
19265d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
19275d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
19285d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
19295d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
19305d9e75c4SJan Schmidt  *
19315d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
19325d9e75c4SJan Schmidt  *
19335d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
19345d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
19355d9e75c4SJan Schmidt  */
1936310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
19375d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
19385d9e75c4SJan Schmidt {
19390b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
19405d9e75c4SJan Schmidt 	struct extent_buffer *b;
19415d9e75c4SJan Schmidt 	int slot;
19425d9e75c4SJan Schmidt 	int ret;
19435d9e75c4SJan Schmidt 	int err;
19445d9e75c4SJan Schmidt 	int level;
19455d9e75c4SJan Schmidt 	int lowest_unlock = 1;
19465d9e75c4SJan Schmidt 	u8 lowest_level = 0;
19475d9e75c4SJan Schmidt 
19485d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
19495d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
19505d9e75c4SJan Schmidt 
19515d9e75c4SJan Schmidt 	if (p->search_commit_root) {
19525d9e75c4SJan Schmidt 		BUG_ON(time_seq);
19535d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
19545d9e75c4SJan Schmidt 	}
19555d9e75c4SJan Schmidt 
19565d9e75c4SJan Schmidt again:
1957f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
1958315bed43SNikolay Borisov 	if (!b) {
1959315bed43SNikolay Borisov 		ret = -EIO;
1960315bed43SNikolay Borisov 		goto done;
1961315bed43SNikolay Borisov 	}
19625d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
19635d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
19645d9e75c4SJan Schmidt 
19655d9e75c4SJan Schmidt 	while (b) {
1966abe9339dSQu Wenruo 		int dec = 0;
1967abe9339dSQu Wenruo 
19685d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
19695d9e75c4SJan Schmidt 		p->nodes[level] = b;
19705d9e75c4SJan Schmidt 
19715d9e75c4SJan Schmidt 		/*
19725d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
19735d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
19745d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
19755d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
19765d9e75c4SJan Schmidt 		 */
19775d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
19785d9e75c4SJan Schmidt 
1979995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
1980cbca7d59SFilipe Manana 		if (ret < 0)
1981cbca7d59SFilipe Manana 			goto done;
19825d9e75c4SJan Schmidt 
1983abe9339dSQu Wenruo 		if (level == 0) {
1984abe9339dSQu Wenruo 			p->slots[level] = slot;
1985abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
1986abe9339dSQu Wenruo 			goto done;
1987abe9339dSQu Wenruo 		}
1988abe9339dSQu Wenruo 
19895d9e75c4SJan Schmidt 		if (ret && slot > 0) {
19905d9e75c4SJan Schmidt 			dec = 1;
1991abe9339dSQu Wenruo 			slot--;
19925d9e75c4SJan Schmidt 		}
19935d9e75c4SJan Schmidt 		p->slots[level] = slot;
19945d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
19955d9e75c4SJan Schmidt 
19965d9e75c4SJan Schmidt 		if (level == lowest_level) {
19975d9e75c4SJan Schmidt 			if (dec)
19985d9e75c4SJan Schmidt 				p->slots[level]++;
19995d9e75c4SJan Schmidt 			goto done;
20005d9e75c4SJan Schmidt 		}
20015d9e75c4SJan Schmidt 
2002abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
20035d9e75c4SJan Schmidt 		if (err == -EAGAIN)
20045d9e75c4SJan Schmidt 			goto again;
20055d9e75c4SJan Schmidt 		if (err) {
20065d9e75c4SJan Schmidt 			ret = err;
20075d9e75c4SJan Schmidt 			goto done;
20085d9e75c4SJan Schmidt 		}
20095d9e75c4SJan Schmidt 
20105d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
20115d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2012f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2013db7f3436SJosef Bacik 		if (!b) {
2014db7f3436SJosef Bacik 			ret = -ENOMEM;
2015db7f3436SJosef Bacik 			goto done;
2016db7f3436SJosef Bacik 		}
20175d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
20185d9e75c4SJan Schmidt 		p->nodes[level] = b;
20195d9e75c4SJan Schmidt 	}
20205d9e75c4SJan Schmidt 	ret = 1;
20215d9e75c4SJan Schmidt done:
20225d9e75c4SJan Schmidt 	if (ret < 0)
20235d9e75c4SJan Schmidt 		btrfs_release_path(p);
20245d9e75c4SJan Schmidt 
20255d9e75c4SJan Schmidt 	return ret;
20265d9e75c4SJan Schmidt }
20275d9e75c4SJan Schmidt 
20285d9e75c4SJan Schmidt /*
20292f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
20302f38b3e1SArne Jansen  * instead the next or previous item should be returned.
20312f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
20322f38b3e1SArne Jansen  * otherwise.
20332f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
20342f38b3e1SArne Jansen  * return the next lower instead.
20352f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
20362f38b3e1SArne Jansen  * return the next higher instead.
20372f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
20382f38b3e1SArne Jansen  * < 0 on error
20392f38b3e1SArne Jansen  */
20402f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2041310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2042310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2043310712b2SOmar Sandoval 			       int return_any)
20442f38b3e1SArne Jansen {
20452f38b3e1SArne Jansen 	int ret;
20462f38b3e1SArne Jansen 	struct extent_buffer *leaf;
20472f38b3e1SArne Jansen 
20482f38b3e1SArne Jansen again:
20492f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
20502f38b3e1SArne Jansen 	if (ret <= 0)
20512f38b3e1SArne Jansen 		return ret;
20522f38b3e1SArne Jansen 	/*
20532f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
20542f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
20552f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
20562f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
20572f38b3e1SArne Jansen 	 * item.
20582f38b3e1SArne Jansen 	 */
20592f38b3e1SArne Jansen 	leaf = p->nodes[0];
20602f38b3e1SArne Jansen 
20612f38b3e1SArne Jansen 	if (find_higher) {
20622f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
20632f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
20642f38b3e1SArne Jansen 			if (ret <= 0)
20652f38b3e1SArne Jansen 				return ret;
20662f38b3e1SArne Jansen 			if (!return_any)
20672f38b3e1SArne Jansen 				return 1;
20682f38b3e1SArne Jansen 			/*
20692f38b3e1SArne Jansen 			 * no higher item found, return the next
20702f38b3e1SArne Jansen 			 * lower instead
20712f38b3e1SArne Jansen 			 */
20722f38b3e1SArne Jansen 			return_any = 0;
20732f38b3e1SArne Jansen 			find_higher = 0;
20742f38b3e1SArne Jansen 			btrfs_release_path(p);
20752f38b3e1SArne Jansen 			goto again;
20762f38b3e1SArne Jansen 		}
20772f38b3e1SArne Jansen 	} else {
20782f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
20792f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2080e6793769SArne Jansen 			if (ret < 0)
20812f38b3e1SArne Jansen 				return ret;
2082e6793769SArne Jansen 			if (!ret) {
208323c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
208423c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
208523c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2086e6793769SArne Jansen 				return 0;
2087e6793769SArne Jansen 			}
20882f38b3e1SArne Jansen 			if (!return_any)
20892f38b3e1SArne Jansen 				return 1;
20902f38b3e1SArne Jansen 			/*
20912f38b3e1SArne Jansen 			 * no lower item found, return the next
20922f38b3e1SArne Jansen 			 * higher instead
20932f38b3e1SArne Jansen 			 */
20942f38b3e1SArne Jansen 			return_any = 0;
20952f38b3e1SArne Jansen 			find_higher = 1;
20962f38b3e1SArne Jansen 			btrfs_release_path(p);
20972f38b3e1SArne Jansen 			goto again;
2098e6793769SArne Jansen 		} else {
20992f38b3e1SArne Jansen 			--p->slots[0];
21002f38b3e1SArne Jansen 		}
21012f38b3e1SArne Jansen 	}
21022f38b3e1SArne Jansen 	return 0;
21032f38b3e1SArne Jansen }
21042f38b3e1SArne Jansen 
21052f38b3e1SArne Jansen /*
21060ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
21070ff40a91SMarcos Paulo de Souza  * was not found.
21080ff40a91SMarcos Paulo de Souza  *
21090ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
21100ff40a91SMarcos Paulo de Souza  */
21110ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
21120ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
21130ff40a91SMarcos Paulo de Souza {
21140ff40a91SMarcos Paulo de Souza 	int ret;
21150ff40a91SMarcos Paulo de Souza 
21160ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
21170ff40a91SMarcos Paulo de Souza 	if (ret > 0)
21180ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
21190ff40a91SMarcos Paulo de Souza 
21200ff40a91SMarcos Paulo de Souza 	if (ret == 0)
21210ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
21220ff40a91SMarcos Paulo de Souza 
21230ff40a91SMarcos Paulo de Souza 	return ret;
21240ff40a91SMarcos Paulo de Souza }
21250ff40a91SMarcos Paulo de Souza 
21260ff40a91SMarcos Paulo de Souza /*
212774123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
212874123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
212974123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
213074123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
213174123bd7SChris Mason  * higher levels
2132aa5d6bedSChris Mason  *
213374123bd7SChris Mason  */
2134b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
21355f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2136be0e5c09SChris Mason {
2137be0e5c09SChris Mason 	int i;
21385f39d397SChris Mason 	struct extent_buffer *t;
21390e82bcfeSDavid Sterba 	int ret;
21405f39d397SChris Mason 
2141234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2142be0e5c09SChris Mason 		int tslot = path->slots[i];
21430e82bcfeSDavid Sterba 
2144eb60ceacSChris Mason 		if (!path->nodes[i])
2145be0e5c09SChris Mason 			break;
21465f39d397SChris Mason 		t = path->nodes[i];
2147f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
2148f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REPLACE, GFP_ATOMIC);
21490e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
21505f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2151d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2152be0e5c09SChris Mason 		if (tslot != 0)
2153be0e5c09SChris Mason 			break;
2154be0e5c09SChris Mason 	}
2155be0e5c09SChris Mason }
2156be0e5c09SChris Mason 
215774123bd7SChris Mason /*
215831840ae1SZheng Yan  * update item key.
215931840ae1SZheng Yan  *
216031840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
216131840ae1SZheng Yan  * that the new key won't break the order
216231840ae1SZheng Yan  */
2163b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2164b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2165310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
216631840ae1SZheng Yan {
216731840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
216831840ae1SZheng Yan 	struct extent_buffer *eb;
216931840ae1SZheng Yan 	int slot;
217031840ae1SZheng Yan 
217131840ae1SZheng Yan 	eb = path->nodes[0];
217231840ae1SZheng Yan 	slot = path->slots[0];
217331840ae1SZheng Yan 	if (slot > 0) {
217431840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
21757c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
21767c15d410SQu Wenruo 			btrfs_crit(fs_info,
21777c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
21787c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
21797c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
21807c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
21817c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
21827c15d410SQu Wenruo 				   new_key->offset);
21837c15d410SQu Wenruo 			btrfs_print_leaf(eb);
21847c15d410SQu Wenruo 			BUG();
21857c15d410SQu Wenruo 		}
218631840ae1SZheng Yan 	}
218731840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
218831840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
21897c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
21907c15d410SQu Wenruo 			btrfs_crit(fs_info,
21917c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
21927c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
21937c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
21947c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
21957c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
21967c15d410SQu Wenruo 				   new_key->offset);
21977c15d410SQu Wenruo 			btrfs_print_leaf(eb);
21987c15d410SQu Wenruo 			BUG();
21997c15d410SQu Wenruo 		}
220031840ae1SZheng Yan 	}
220131840ae1SZheng Yan 
220231840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
220331840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
220431840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
220531840ae1SZheng Yan 	if (slot == 0)
2206b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
220731840ae1SZheng Yan }
220831840ae1SZheng Yan 
220931840ae1SZheng Yan /*
2210d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2211d16c702fSQu Wenruo  *
2212d16c702fSQu Wenruo  * Return true if something is wrong.
2213d16c702fSQu Wenruo  * Return false if everything is fine.
2214d16c702fSQu Wenruo  *
2215d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2216d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2217d16c702fSQu Wenruo  *
2218d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2219d16c702fSQu Wenruo  * --------------------------------------------------------------
2220d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2221d16c702fSQu Wenruo  *
2222d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2223d16c702fSQu Wenruo  * key in leaf @right is 7.
2224d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2225d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2226d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2227d16c702fSQu Wenruo  * key of @right.
2228d16c702fSQu Wenruo  */
2229d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2230d16c702fSQu Wenruo 			       struct extent_buffer *right)
2231d16c702fSQu Wenruo {
2232d16c702fSQu Wenruo 	struct btrfs_key left_last;
2233d16c702fSQu Wenruo 	struct btrfs_key right_first;
2234d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2235d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2236d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2237d16c702fSQu Wenruo 
2238d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2239d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2240d16c702fSQu Wenruo 		return false;
2241d16c702fSQu Wenruo 
2242d16c702fSQu Wenruo 	if (level) {
2243d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2244d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2245d16c702fSQu Wenruo 	} else {
2246d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2247d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2248d16c702fSQu Wenruo 	}
2249d16c702fSQu Wenruo 
2250d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2251d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2252d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2253d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2254d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2255d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2256d16c702fSQu Wenruo 		return true;
2257d16c702fSQu Wenruo 	}
2258d16c702fSQu Wenruo 	return false;
2259d16c702fSQu Wenruo }
2260d16c702fSQu Wenruo 
2261d16c702fSQu Wenruo /*
226274123bd7SChris Mason  * try to push data from one node into the next node left in the
226379f95c82SChris Mason  * tree.
2264aa5d6bedSChris Mason  *
2265aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2266aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
226774123bd7SChris Mason  */
226898ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
22692ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2270971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2271be0e5c09SChris Mason {
2272d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2273be0e5c09SChris Mason 	int push_items = 0;
2274bb803951SChris Mason 	int src_nritems;
2275bb803951SChris Mason 	int dst_nritems;
2276aa5d6bedSChris Mason 	int ret = 0;
2277be0e5c09SChris Mason 
22785f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
22795f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
22800b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
22817bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
22827bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
228354aa1f4dSChris Mason 
2284bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2285971a1f66SChris Mason 		return 1;
2286971a1f66SChris Mason 
2287d397712bSChris Mason 	if (push_items <= 0)
2288be0e5c09SChris Mason 		return 1;
2289be0e5c09SChris Mason 
2290bce4eae9SChris Mason 	if (empty) {
2291971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2292bce4eae9SChris Mason 		if (push_items < src_nritems) {
2293bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2294bce4eae9SChris Mason 			 * we aren't going to empty it
2295bce4eae9SChris Mason 			 */
2296bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2297bce4eae9SChris Mason 				if (push_items <= 8)
2298bce4eae9SChris Mason 					return 1;
2299bce4eae9SChris Mason 				push_items -= 8;
2300bce4eae9SChris Mason 			}
2301bce4eae9SChris Mason 		}
2302bce4eae9SChris Mason 	} else
2303bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
230479f95c82SChris Mason 
2305d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2306d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2307d16c702fSQu Wenruo 		ret = -EUCLEAN;
2308d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2309d16c702fSQu Wenruo 		return ret;
2310d16c702fSQu Wenruo 	}
2311f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
23125de865eeSFilipe David Borba Manana 	if (ret) {
231366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
23145de865eeSFilipe David Borba Manana 		return ret;
23155de865eeSFilipe David Borba Manana 	}
23165f39d397SChris Mason 	copy_extent_buffer(dst, src,
23175f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
23185f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2319123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
23205f39d397SChris Mason 
2321bb803951SChris Mason 	if (push_items < src_nritems) {
232257911b8bSJan Schmidt 		/*
2323f3a84ccdSFilipe Manana 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2324f3a84ccdSFilipe Manana 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
232557911b8bSJan Schmidt 		 */
23265f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
23275f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2328e2fa7227SChris Mason 				      (src_nritems - push_items) *
2329123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2330bb803951SChris Mason 	}
23315f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
23325f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
23335f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
23345f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
233531840ae1SZheng Yan 
2336bb803951SChris Mason 	return ret;
2337be0e5c09SChris Mason }
2338be0e5c09SChris Mason 
233997571fd0SChris Mason /*
234079f95c82SChris Mason  * try to push data from one node into the next node right in the
234179f95c82SChris Mason  * tree.
234279f95c82SChris Mason  *
234379f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
234479f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
234579f95c82SChris Mason  *
234679f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
234779f95c82SChris Mason  */
23485f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
23495f39d397SChris Mason 			      struct extent_buffer *dst,
23505f39d397SChris Mason 			      struct extent_buffer *src)
235179f95c82SChris Mason {
235255d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
235379f95c82SChris Mason 	int push_items = 0;
235479f95c82SChris Mason 	int max_push;
235579f95c82SChris Mason 	int src_nritems;
235679f95c82SChris Mason 	int dst_nritems;
235779f95c82SChris Mason 	int ret = 0;
235879f95c82SChris Mason 
23597bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
23607bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
23617bb86316SChris Mason 
23625f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
23635f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
23640b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2365d397712bSChris Mason 	if (push_items <= 0)
236679f95c82SChris Mason 		return 1;
2367bce4eae9SChris Mason 
2368d397712bSChris Mason 	if (src_nritems < 4)
2369bce4eae9SChris Mason 		return 1;
237079f95c82SChris Mason 
237179f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
237279f95c82SChris Mason 	/* don't try to empty the node */
2373d397712bSChris Mason 	if (max_push >= src_nritems)
237479f95c82SChris Mason 		return 1;
2375252c38f0SYan 
237679f95c82SChris Mason 	if (max_push < push_items)
237779f95c82SChris Mason 		push_items = max_push;
237879f95c82SChris Mason 
2379d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2380d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2381d16c702fSQu Wenruo 		ret = -EUCLEAN;
2382d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2383d16c702fSQu Wenruo 		return ret;
2384d16c702fSQu Wenruo 	}
2385f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2386bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
23875f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
23885f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
23895f39d397SChris Mason 				      (dst_nritems) *
23905f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2391d6025579SChris Mason 
2392f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2393ed874f0dSDavid Sterba 					 push_items);
23945de865eeSFilipe David Borba Manana 	if (ret) {
239566642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
23965de865eeSFilipe David Borba Manana 		return ret;
23975de865eeSFilipe David Borba Manana 	}
23985f39d397SChris Mason 	copy_extent_buffer(dst, src,
23995f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
24005f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2401123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
240279f95c82SChris Mason 
24035f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
24045f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
240579f95c82SChris Mason 
24065f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
24075f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
240831840ae1SZheng Yan 
240979f95c82SChris Mason 	return ret;
241079f95c82SChris Mason }
241179f95c82SChris Mason 
241279f95c82SChris Mason /*
241397571fd0SChris Mason  * helper function to insert a new root level in the tree.
241497571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
241597571fd0SChris Mason  * point to the existing root
2416aa5d6bedSChris Mason  *
2417aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
241897571fd0SChris Mason  */
2419d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
24205f39d397SChris Mason 			   struct btrfs_root *root,
2421fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
242274123bd7SChris Mason {
24230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
24247bb86316SChris Mason 	u64 lower_gen;
24255f39d397SChris Mason 	struct extent_buffer *lower;
24265f39d397SChris Mason 	struct extent_buffer *c;
2427925baeddSChris Mason 	struct extent_buffer *old;
24285f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2429d9d19a01SDavid Sterba 	int ret;
24305c680ed6SChris Mason 
24315c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
24325c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
24335c680ed6SChris Mason 
24347bb86316SChris Mason 	lower = path->nodes[level-1];
24357bb86316SChris Mason 	if (level == 1)
24367bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
24377bb86316SChris Mason 	else
24387bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
24397bb86316SChris Mason 
244079bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
244179bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2442cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
24435f39d397SChris Mason 	if (IS_ERR(c))
24445f39d397SChris Mason 		return PTR_ERR(c);
2445925baeddSChris Mason 
24460b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2447f0486c68SYan, Zheng 
24485f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
24495f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2450db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
24517bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
245231840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
24537bb86316SChris Mason 
24547bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
24555f39d397SChris Mason 
24565f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2457d5719762SChris Mason 
2458925baeddSChris Mason 	old = root->node;
2459406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2460d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2461240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2462925baeddSChris Mason 
2463925baeddSChris Mason 	/* the super has an extra ref to root->node */
2464925baeddSChris Mason 	free_extent_buffer(old);
2465925baeddSChris Mason 
24660b86a832SChris Mason 	add_root_to_dirty_list(root);
246767439dadSDavid Sterba 	atomic_inc(&c->refs);
24685f39d397SChris Mason 	path->nodes[level] = c;
2469ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
247074123bd7SChris Mason 	path->slots[level] = 0;
247174123bd7SChris Mason 	return 0;
247274123bd7SChris Mason }
24735c680ed6SChris Mason 
24745c680ed6SChris Mason /*
24755c680ed6SChris Mason  * worker function to insert a single pointer in a node.
24765c680ed6SChris Mason  * the node should have enough room for the pointer already
247797571fd0SChris Mason  *
24785c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
24795c680ed6SChris Mason  * blocknr is the block the key points to.
24805c680ed6SChris Mason  */
2481143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
24826ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2483143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2484c3e06965SJan Schmidt 		       int slot, int level)
24855c680ed6SChris Mason {
24865f39d397SChris Mason 	struct extent_buffer *lower;
24875c680ed6SChris Mason 	int nritems;
2488f3ea38daSJan Schmidt 	int ret;
24895c680ed6SChris Mason 
24905c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
2491f0486c68SYan, Zheng 	btrfs_assert_tree_locked(path->nodes[level]);
24925f39d397SChris Mason 	lower = path->nodes[level];
24935f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2494c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
24956ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
249674123bd7SChris Mason 	if (slot != nritems) {
2497bf1d3425SDavid Sterba 		if (level) {
2498f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2499f3a84ccdSFilipe Manana 					slot, nritems - slot);
2500bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2501bf1d3425SDavid Sterba 		}
25025f39d397SChris Mason 		memmove_extent_buffer(lower,
25035f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
25045f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
2505123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
250674123bd7SChris Mason 	}
2507c3e06965SJan Schmidt 	if (level) {
2508f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
2509f3a84ccdSFilipe Manana 					    BTRFS_MOD_LOG_KEY_ADD, GFP_NOFS);
2510f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2511f3ea38daSJan Schmidt 	}
25125f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2513db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
251474493f7aSChris Mason 	WARN_ON(trans->transid == 0);
251574493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
25165f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
25175f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
251874123bd7SChris Mason }
251974123bd7SChris Mason 
252097571fd0SChris Mason /*
252197571fd0SChris Mason  * split the node at the specified level in path in two.
252297571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
252397571fd0SChris Mason  *
252497571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
252597571fd0SChris Mason  * left and right, if either one works, it returns right away.
2526aa5d6bedSChris Mason  *
2527aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
252897571fd0SChris Mason  */
2529e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
2530e02119d5SChris Mason 			       struct btrfs_root *root,
2531e02119d5SChris Mason 			       struct btrfs_path *path, int level)
2532be0e5c09SChris Mason {
25330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
25345f39d397SChris Mason 	struct extent_buffer *c;
25355f39d397SChris Mason 	struct extent_buffer *split;
25365f39d397SChris Mason 	struct btrfs_disk_key disk_key;
2537be0e5c09SChris Mason 	int mid;
25385c680ed6SChris Mason 	int ret;
25397518a238SChris Mason 	u32 c_nritems;
2540be0e5c09SChris Mason 
25415f39d397SChris Mason 	c = path->nodes[level];
25427bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
25435f39d397SChris Mason 	if (c == root->node) {
2544d9abbf1cSJan Schmidt 		/*
254590f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
254690f8d62eSJan Schmidt 		 *
2547fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
254890f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
254990f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
2550f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2551f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
2552f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
2553d9abbf1cSJan Schmidt 		 */
2554fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
25555c680ed6SChris Mason 		if (ret)
25565c680ed6SChris Mason 			return ret;
2557b3612421SChris Mason 	} else {
2558e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
25595f39d397SChris Mason 		c = path->nodes[level];
25605f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
25610b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2562e66f709bSChris Mason 			return 0;
256354aa1f4dSChris Mason 		if (ret < 0)
256454aa1f4dSChris Mason 			return ret;
25655c680ed6SChris Mason 	}
2566e66f709bSChris Mason 
25675f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
25685d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
25695d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
25707bb86316SChris Mason 
257179bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
257279bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
257379bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
25745f39d397SChris Mason 	if (IS_ERR(split))
25755f39d397SChris Mason 		return PTR_ERR(split);
257654aa1f4dSChris Mason 
25770b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2578bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
25795f39d397SChris Mason 
2580f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
25815de865eeSFilipe David Borba Manana 	if (ret) {
258266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
25835de865eeSFilipe David Borba Manana 		return ret;
25845de865eeSFilipe David Borba Manana 	}
25855f39d397SChris Mason 	copy_extent_buffer(split, c,
25865f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
25875f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
2588123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
25895f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
25905f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
2591aa5d6bedSChris Mason 
25925f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
25935f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
25945f39d397SChris Mason 
25956ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
2596c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
2597aa5d6bedSChris Mason 
25985de08d7dSChris Mason 	if (path->slots[level] >= mid) {
25995c680ed6SChris Mason 		path->slots[level] -= mid;
2600925baeddSChris Mason 		btrfs_tree_unlock(c);
26015f39d397SChris Mason 		free_extent_buffer(c);
26025f39d397SChris Mason 		path->nodes[level] = split;
26035c680ed6SChris Mason 		path->slots[level + 1] += 1;
2604eb60ceacSChris Mason 	} else {
2605925baeddSChris Mason 		btrfs_tree_unlock(split);
26065f39d397SChris Mason 		free_extent_buffer(split);
2607be0e5c09SChris Mason 	}
2608d5286a92SNikolay Borisov 	return 0;
2609be0e5c09SChris Mason }
2610be0e5c09SChris Mason 
261174123bd7SChris Mason /*
261274123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
261374123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
261474123bd7SChris Mason  * space used both by the item structs and the item data
261574123bd7SChris Mason  */
26165f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2617be0e5c09SChris Mason {
261841be1f3bSJosef Bacik 	struct btrfs_item *start_item;
261941be1f3bSJosef Bacik 	struct btrfs_item *end_item;
2620be0e5c09SChris Mason 	int data_len;
26215f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
2622d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
2623be0e5c09SChris Mason 
2624be0e5c09SChris Mason 	if (!nr)
2625be0e5c09SChris Mason 		return 0;
2626dd3cc16bSRoss Kirk 	start_item = btrfs_item_nr(start);
2627dd3cc16bSRoss Kirk 	end_item = btrfs_item_nr(end);
2628a31356b9SDavid Sterba 	data_len = btrfs_item_offset(l, start_item) +
2629a31356b9SDavid Sterba 		   btrfs_item_size(l, start_item);
2630a31356b9SDavid Sterba 	data_len = data_len - btrfs_item_offset(l, end_item);
26310783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
2632d4dbff95SChris Mason 	WARN_ON(data_len < 0);
2633be0e5c09SChris Mason 	return data_len;
2634be0e5c09SChris Mason }
2635be0e5c09SChris Mason 
263674123bd7SChris Mason /*
2637d4dbff95SChris Mason  * The space between the end of the leaf items and
2638d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
2639d4dbff95SChris Mason  * the leaf has left for both items and data
2640d4dbff95SChris Mason  */
2641e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
2642d4dbff95SChris Mason {
2643e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
26445f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
26455f39d397SChris Mason 	int ret;
26460b246afaSJeff Mahoney 
26470b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
26485f39d397SChris Mason 	if (ret < 0) {
26490b246afaSJeff Mahoney 		btrfs_crit(fs_info,
2650efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2651da17066cSJeff Mahoney 			   ret,
26520b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
26535f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
26545f39d397SChris Mason 	}
26555f39d397SChris Mason 	return ret;
2656d4dbff95SChris Mason }
2657d4dbff95SChris Mason 
265899d8f83cSChris Mason /*
265999d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
266099d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
266199d8f83cSChris Mason  */
2662f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
266344871b1bSChris Mason 				      int data_size, int empty,
266444871b1bSChris Mason 				      struct extent_buffer *right,
266599d8f83cSChris Mason 				      int free_space, u32 left_nritems,
266699d8f83cSChris Mason 				      u32 min_slot)
266700ec4c51SChris Mason {
2668f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
26695f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
267044871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
2671cfed81a0SChris Mason 	struct btrfs_map_token token;
26725f39d397SChris Mason 	struct btrfs_disk_key disk_key;
267300ec4c51SChris Mason 	int slot;
267434a38218SChris Mason 	u32 i;
267500ec4c51SChris Mason 	int push_space = 0;
267600ec4c51SChris Mason 	int push_items = 0;
26770783fcfcSChris Mason 	struct btrfs_item *item;
267834a38218SChris Mason 	u32 nr;
26797518a238SChris Mason 	u32 right_nritems;
26805f39d397SChris Mason 	u32 data_end;
2681db94535dSChris Mason 	u32 this_item_size;
268200ec4c51SChris Mason 
268334a38218SChris Mason 	if (empty)
268434a38218SChris Mason 		nr = 0;
268534a38218SChris Mason 	else
268699d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
268734a38218SChris Mason 
268831840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
268987b29b20SYan Zheng 		push_space += data_size;
269031840ae1SZheng Yan 
269144871b1bSChris Mason 	slot = path->slots[1];
269234a38218SChris Mason 	i = left_nritems - 1;
269334a38218SChris Mason 	while (i >= nr) {
2694dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
2695db94535dSChris Mason 
269631840ae1SZheng Yan 		if (!empty && push_items > 0) {
269731840ae1SZheng Yan 			if (path->slots[0] > i)
269831840ae1SZheng Yan 				break;
269931840ae1SZheng Yan 			if (path->slots[0] == i) {
2700e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
2701e902baacSDavid Sterba 
270231840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
270331840ae1SZheng Yan 					break;
270431840ae1SZheng Yan 			}
270531840ae1SZheng Yan 		}
270631840ae1SZheng Yan 
270700ec4c51SChris Mason 		if (path->slots[0] == i)
270887b29b20SYan Zheng 			push_space += data_size;
2709db94535dSChris Mason 
2710db94535dSChris Mason 		this_item_size = btrfs_item_size(left, item);
2711db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
271200ec4c51SChris Mason 			break;
271331840ae1SZheng Yan 
271400ec4c51SChris Mason 		push_items++;
2715db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
271634a38218SChris Mason 		if (i == 0)
271734a38218SChris Mason 			break;
271834a38218SChris Mason 		i--;
2719db94535dSChris Mason 	}
27205f39d397SChris Mason 
2721925baeddSChris Mason 	if (push_items == 0)
2722925baeddSChris Mason 		goto out_unlock;
27235f39d397SChris Mason 
27246c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
27255f39d397SChris Mason 
272600ec4c51SChris Mason 	/* push left to right */
27275f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
272834a38218SChris Mason 
27295f39d397SChris Mason 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
27308f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
27315f39d397SChris Mason 
273200ec4c51SChris Mason 	/* make room in the right data area */
27338f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
27345f39d397SChris Mason 	memmove_extent_buffer(right,
27353d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
27363d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
27370b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
27385f39d397SChris Mason 
273900ec4c51SChris Mason 	/* copy from the left data area */
27403d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
27410b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
27428f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
2743d6025579SChris Mason 		     push_space);
27445f39d397SChris Mason 
27455f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
27465f39d397SChris Mason 			      btrfs_item_nr_offset(0),
27470783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
27485f39d397SChris Mason 
274900ec4c51SChris Mason 	/* copy the items from left to right */
27505f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
27515f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
27520783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
275300ec4c51SChris Mason 
275400ec4c51SChris Mason 	/* update the item pointers */
2755c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
27567518a238SChris Mason 	right_nritems += push_items;
27575f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
27580b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
27597518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
2760dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
2761cc4c13d5SDavid Sterba 		push_space -= btrfs_token_item_size(&token, item);
2762cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, push_space);
2763db94535dSChris Mason 	}
2764db94535dSChris Mason 
27657518a238SChris Mason 	left_nritems -= push_items;
27665f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
276700ec4c51SChris Mason 
276834a38218SChris Mason 	if (left_nritems)
27695f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
2770f0486c68SYan, Zheng 	else
27716a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
2772f0486c68SYan, Zheng 
27735f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
2774a429e513SChris Mason 
27755f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
27765f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
2777d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
277802217ed2SChris Mason 
277900ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
27807518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
27817518a238SChris Mason 		path->slots[0] -= left_nritems;
2782925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
27836a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
2784925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
27855f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
27865f39d397SChris Mason 		path->nodes[0] = right;
278700ec4c51SChris Mason 		path->slots[1] += 1;
278800ec4c51SChris Mason 	} else {
2789925baeddSChris Mason 		btrfs_tree_unlock(right);
27905f39d397SChris Mason 		free_extent_buffer(right);
279100ec4c51SChris Mason 	}
279200ec4c51SChris Mason 	return 0;
2793925baeddSChris Mason 
2794925baeddSChris Mason out_unlock:
2795925baeddSChris Mason 	btrfs_tree_unlock(right);
2796925baeddSChris Mason 	free_extent_buffer(right);
2797925baeddSChris Mason 	return 1;
279800ec4c51SChris Mason }
2799925baeddSChris Mason 
280000ec4c51SChris Mason /*
280144871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
280274123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
280344871b1bSChris Mason  *
280444871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
280544871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
280699d8f83cSChris Mason  *
280799d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
280899d8f83cSChris Mason  * push any slot lower than min_slot
280974123bd7SChris Mason  */
281044871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
281199d8f83cSChris Mason 			   *root, struct btrfs_path *path,
281299d8f83cSChris Mason 			   int min_data_size, int data_size,
281399d8f83cSChris Mason 			   int empty, u32 min_slot)
2814be0e5c09SChris Mason {
281544871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
281644871b1bSChris Mason 	struct extent_buffer *right;
281744871b1bSChris Mason 	struct extent_buffer *upper;
281844871b1bSChris Mason 	int slot;
281944871b1bSChris Mason 	int free_space;
282044871b1bSChris Mason 	u32 left_nritems;
282144871b1bSChris Mason 	int ret;
282244871b1bSChris Mason 
282344871b1bSChris Mason 	if (!path->nodes[1])
282444871b1bSChris Mason 		return 1;
282544871b1bSChris Mason 
282644871b1bSChris Mason 	slot = path->slots[1];
282744871b1bSChris Mason 	upper = path->nodes[1];
282844871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
282944871b1bSChris Mason 		return 1;
283044871b1bSChris Mason 
283144871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
283244871b1bSChris Mason 
28334b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
2834fb770ae4SLiu Bo 	/*
2835fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
2836fb770ae4SLiu Bo 	 * no big deal, just return.
2837fb770ae4SLiu Bo 	 */
2838fb770ae4SLiu Bo 	if (IS_ERR(right))
283991ca338dSTsutomu Itoh 		return 1;
284091ca338dSTsutomu Itoh 
2841bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
284244871b1bSChris Mason 
2843e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
284444871b1bSChris Mason 	if (free_space < data_size)
284544871b1bSChris Mason 		goto out_unlock;
284644871b1bSChris Mason 
284744871b1bSChris Mason 	/* cow and double check */
284844871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
2849bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
285044871b1bSChris Mason 	if (ret)
285144871b1bSChris Mason 		goto out_unlock;
285244871b1bSChris Mason 
2853e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
285444871b1bSChris Mason 	if (free_space < data_size)
285544871b1bSChris Mason 		goto out_unlock;
285644871b1bSChris Mason 
285744871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
285844871b1bSChris Mason 	if (left_nritems == 0)
285944871b1bSChris Mason 		goto out_unlock;
286044871b1bSChris Mason 
2861d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
2862d16c702fSQu Wenruo 		ret = -EUCLEAN;
2863d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
2864d16c702fSQu Wenruo 		free_extent_buffer(right);
2865d16c702fSQu Wenruo 		return ret;
2866d16c702fSQu Wenruo 	}
28672ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
28682ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
28692ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
28702ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
287152042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
28722ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
28732ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
28742ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
28752ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
28762ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
28772ef1fed2SFilipe David Borba Manana 		return 0;
28782ef1fed2SFilipe David Borba Manana 	}
28792ef1fed2SFilipe David Borba Manana 
2880f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
288199d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
288244871b1bSChris Mason out_unlock:
288344871b1bSChris Mason 	btrfs_tree_unlock(right);
288444871b1bSChris Mason 	free_extent_buffer(right);
288544871b1bSChris Mason 	return 1;
288644871b1bSChris Mason }
288744871b1bSChris Mason 
288844871b1bSChris Mason /*
288944871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
289044871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
289199d8f83cSChris Mason  *
289299d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
289399d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
289499d8f83cSChris Mason  * items
289544871b1bSChris Mason  */
28968087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
289744871b1bSChris Mason 				     int empty, struct extent_buffer *left,
289899d8f83cSChris Mason 				     int free_space, u32 right_nritems,
289999d8f83cSChris Mason 				     u32 max_slot)
290044871b1bSChris Mason {
29018087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
29025f39d397SChris Mason 	struct btrfs_disk_key disk_key;
29035f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
2904be0e5c09SChris Mason 	int i;
2905be0e5c09SChris Mason 	int push_space = 0;
2906be0e5c09SChris Mason 	int push_items = 0;
29070783fcfcSChris Mason 	struct btrfs_item *item;
29087518a238SChris Mason 	u32 old_left_nritems;
290934a38218SChris Mason 	u32 nr;
2910aa5d6bedSChris Mason 	int ret = 0;
2911db94535dSChris Mason 	u32 this_item_size;
2912db94535dSChris Mason 	u32 old_left_item_size;
2913cfed81a0SChris Mason 	struct btrfs_map_token token;
2914cfed81a0SChris Mason 
291534a38218SChris Mason 	if (empty)
291699d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
291734a38218SChris Mason 	else
291899d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
291934a38218SChris Mason 
292034a38218SChris Mason 	for (i = 0; i < nr; i++) {
2921dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
2922db94535dSChris Mason 
292331840ae1SZheng Yan 		if (!empty && push_items > 0) {
292431840ae1SZheng Yan 			if (path->slots[0] < i)
292531840ae1SZheng Yan 				break;
292631840ae1SZheng Yan 			if (path->slots[0] == i) {
2927e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
2928e902baacSDavid Sterba 
292931840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
293031840ae1SZheng Yan 					break;
293131840ae1SZheng Yan 			}
293231840ae1SZheng Yan 		}
293331840ae1SZheng Yan 
2934be0e5c09SChris Mason 		if (path->slots[0] == i)
293587b29b20SYan Zheng 			push_space += data_size;
2936db94535dSChris Mason 
2937db94535dSChris Mason 		this_item_size = btrfs_item_size(right, item);
2938db94535dSChris Mason 		if (this_item_size + sizeof(*item) + push_space > free_space)
2939be0e5c09SChris Mason 			break;
2940db94535dSChris Mason 
2941be0e5c09SChris Mason 		push_items++;
2942db94535dSChris Mason 		push_space += this_item_size + sizeof(*item);
2943be0e5c09SChris Mason 	}
2944db94535dSChris Mason 
2945be0e5c09SChris Mason 	if (push_items == 0) {
2946925baeddSChris Mason 		ret = 1;
2947925baeddSChris Mason 		goto out;
2948be0e5c09SChris Mason 	}
2949fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
29505f39d397SChris Mason 
2951be0e5c09SChris Mason 	/* push data from right to left */
29525f39d397SChris Mason 	copy_extent_buffer(left, right,
29535f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
29545f39d397SChris Mason 			   btrfs_item_nr_offset(0),
29555f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
29565f39d397SChris Mason 
29570b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
29585f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1);
29595f39d397SChris Mason 
29603d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
29618f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
29623d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
29635f39d397SChris Mason 		     btrfs_item_offset_nr(right, push_items - 1),
2964be0e5c09SChris Mason 		     push_space);
29655f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
296687b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
2967eb60ceacSChris Mason 
2968c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
2969db94535dSChris Mason 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
2970be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
29715f39d397SChris Mason 		u32 ioff;
2972db94535dSChris Mason 
2973dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
2974db94535dSChris Mason 
2975cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
2976cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item,
2977cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
2978be0e5c09SChris Mason 	}
29795f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
2980be0e5c09SChris Mason 
2981be0e5c09SChris Mason 	/* fixup right node */
298231b1a2bdSJulia Lawall 	if (push_items > right_nritems)
298331b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
2984d397712bSChris Mason 		       right_nritems);
298534a38218SChris Mason 
298634a38218SChris Mason 	if (push_items < right_nritems) {
29875f39d397SChris Mason 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
29888f881e8cSDavid Sterba 						  leaf_data_end(right);
29893d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
29900b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
29913d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
29928f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
29935f39d397SChris Mason 
29945f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
29955f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
29965f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
29970783fcfcSChris Mason 			     sizeof(struct btrfs_item));
299834a38218SChris Mason 	}
2999c82f823cSDavid Sterba 
3000c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3001eef1c494SYan 	right_nritems -= push_items;
3002eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
30030b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
30045f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
3005dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3006db94535dSChris Mason 
3007cc4c13d5SDavid Sterba 		push_space = push_space - btrfs_token_item_size(&token, item);
3008cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, push_space);
3009db94535dSChris Mason 	}
3010eb60ceacSChris Mason 
30115f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
301234a38218SChris Mason 	if (right_nritems)
30135f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3014f0486c68SYan, Zheng 	else
30156a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3016098f59c2SChris Mason 
30175f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3018b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3019be0e5c09SChris Mason 
3020be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3021be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3022be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3023925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
30245f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
30255f39d397SChris Mason 		path->nodes[0] = left;
3026be0e5c09SChris Mason 		path->slots[1] -= 1;
3027be0e5c09SChris Mason 	} else {
3028925baeddSChris Mason 		btrfs_tree_unlock(left);
30295f39d397SChris Mason 		free_extent_buffer(left);
3030be0e5c09SChris Mason 		path->slots[0] -= push_items;
3031be0e5c09SChris Mason 	}
3032eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3033aa5d6bedSChris Mason 	return ret;
3034925baeddSChris Mason out:
3035925baeddSChris Mason 	btrfs_tree_unlock(left);
3036925baeddSChris Mason 	free_extent_buffer(left);
3037925baeddSChris Mason 	return ret;
3038be0e5c09SChris Mason }
3039be0e5c09SChris Mason 
304074123bd7SChris Mason /*
304144871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
304244871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
304399d8f83cSChris Mason  *
304499d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
304599d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
304699d8f83cSChris Mason  * items
304744871b1bSChris Mason  */
304844871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
304999d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
305099d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
305144871b1bSChris Mason {
305244871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
305344871b1bSChris Mason 	struct extent_buffer *left;
305444871b1bSChris Mason 	int slot;
305544871b1bSChris Mason 	int free_space;
305644871b1bSChris Mason 	u32 right_nritems;
305744871b1bSChris Mason 	int ret = 0;
305844871b1bSChris Mason 
305944871b1bSChris Mason 	slot = path->slots[1];
306044871b1bSChris Mason 	if (slot == 0)
306144871b1bSChris Mason 		return 1;
306244871b1bSChris Mason 	if (!path->nodes[1])
306344871b1bSChris Mason 		return 1;
306444871b1bSChris Mason 
306544871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
306644871b1bSChris Mason 	if (right_nritems == 0)
306744871b1bSChris Mason 		return 1;
306844871b1bSChris Mason 
306944871b1bSChris Mason 	btrfs_assert_tree_locked(path->nodes[1]);
307044871b1bSChris Mason 
30714b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3072fb770ae4SLiu Bo 	/*
3073fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3074fb770ae4SLiu Bo 	 * no big deal, just return.
3075fb770ae4SLiu Bo 	 */
3076fb770ae4SLiu Bo 	if (IS_ERR(left))
307791ca338dSTsutomu Itoh 		return 1;
307891ca338dSTsutomu Itoh 
3079bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
308044871b1bSChris Mason 
3081e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
308244871b1bSChris Mason 	if (free_space < data_size) {
308344871b1bSChris Mason 		ret = 1;
308444871b1bSChris Mason 		goto out;
308544871b1bSChris Mason 	}
308644871b1bSChris Mason 
308744871b1bSChris Mason 	/* cow and double check */
308844871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
30899631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3090bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
309144871b1bSChris Mason 	if (ret) {
309244871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
309379787eaaSJeff Mahoney 		if (ret == -ENOSPC)
309444871b1bSChris Mason 			ret = 1;
309544871b1bSChris Mason 		goto out;
309644871b1bSChris Mason 	}
309744871b1bSChris Mason 
3098e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
309944871b1bSChris Mason 	if (free_space < data_size) {
310044871b1bSChris Mason 		ret = 1;
310144871b1bSChris Mason 		goto out;
310244871b1bSChris Mason 	}
310344871b1bSChris Mason 
3104d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3105d16c702fSQu Wenruo 		ret = -EUCLEAN;
3106d16c702fSQu Wenruo 		goto out;
3107d16c702fSQu Wenruo 	}
31088087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
310999d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
311099d8f83cSChris Mason 			       max_slot);
311144871b1bSChris Mason out:
311244871b1bSChris Mason 	btrfs_tree_unlock(left);
311344871b1bSChris Mason 	free_extent_buffer(left);
311444871b1bSChris Mason 	return ret;
311544871b1bSChris Mason }
311644871b1bSChris Mason 
311744871b1bSChris Mason /*
311874123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
311974123bd7SChris Mason  * available for the resulting leaf level of the path.
312074123bd7SChris Mason  */
3121143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
312244871b1bSChris Mason 				    struct btrfs_path *path,
312344871b1bSChris Mason 				    struct extent_buffer *l,
312444871b1bSChris Mason 				    struct extent_buffer *right,
312544871b1bSChris Mason 				    int slot, int mid, int nritems)
3126be0e5c09SChris Mason {
312794f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3128be0e5c09SChris Mason 	int data_copy_size;
3129be0e5c09SChris Mason 	int rt_data_off;
3130be0e5c09SChris Mason 	int i;
3131d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3132cfed81a0SChris Mason 	struct btrfs_map_token token;
3133cfed81a0SChris Mason 
31345f39d397SChris Mason 	nritems = nritems - mid;
31355f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
31368f881e8cSDavid Sterba 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
31375f39d397SChris Mason 
31385f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
31395f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
31405f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
31415f39d397SChris Mason 
31425f39d397SChris Mason 	copy_extent_buffer(right, l,
31433d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
31443d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
31458f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
314674123bd7SChris Mason 
31470b246afaSJeff Mahoney 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
31485f39d397SChris Mason 
3149c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
31505f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3151dd3cc16bSRoss Kirk 		struct btrfs_item *item = btrfs_item_nr(i);
3152db94535dSChris Mason 		u32 ioff;
3153db94535dSChris Mason 
3154cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
3155cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff + rt_data_off);
31560783fcfcSChris Mason 	}
315774123bd7SChris Mason 
31585f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
31595f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
31606ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
31615f39d397SChris Mason 
31625f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
31635f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3164eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
31655f39d397SChris Mason 
3166be0e5c09SChris Mason 	if (mid <= slot) {
3167925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
31685f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
31695f39d397SChris Mason 		path->nodes[0] = right;
3170be0e5c09SChris Mason 		path->slots[0] -= mid;
3171be0e5c09SChris Mason 		path->slots[1] += 1;
3172925baeddSChris Mason 	} else {
3173925baeddSChris Mason 		btrfs_tree_unlock(right);
31745f39d397SChris Mason 		free_extent_buffer(right);
3175925baeddSChris Mason 	}
31765f39d397SChris Mason 
3177eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
317844871b1bSChris Mason }
317944871b1bSChris Mason 
318044871b1bSChris Mason /*
318199d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
318299d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
318399d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
318499d8f83cSChris Mason  *          A                 B                 C
318599d8f83cSChris Mason  *
318699d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
318799d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
318899d8f83cSChris Mason  * completely.
318999d8f83cSChris Mason  */
319099d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
319199d8f83cSChris Mason 					  struct btrfs_root *root,
319299d8f83cSChris Mason 					  struct btrfs_path *path,
319399d8f83cSChris Mason 					  int data_size)
319499d8f83cSChris Mason {
319599d8f83cSChris Mason 	int ret;
319699d8f83cSChris Mason 	int progress = 0;
319799d8f83cSChris Mason 	int slot;
319899d8f83cSChris Mason 	u32 nritems;
31995a4267caSFilipe David Borba Manana 	int space_needed = data_size;
320099d8f83cSChris Mason 
320199d8f83cSChris Mason 	slot = path->slots[0];
32025a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3203e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
320499d8f83cSChris Mason 
320599d8f83cSChris Mason 	/*
320699d8f83cSChris Mason 	 * try to push all the items after our slot into the
320799d8f83cSChris Mason 	 * right leaf
320899d8f83cSChris Mason 	 */
32095a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
321099d8f83cSChris Mason 	if (ret < 0)
321199d8f83cSChris Mason 		return ret;
321299d8f83cSChris Mason 
321399d8f83cSChris Mason 	if (ret == 0)
321499d8f83cSChris Mason 		progress++;
321599d8f83cSChris Mason 
321699d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
321799d8f83cSChris Mason 	/*
321899d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
321999d8f83cSChris Mason 	 * we've done so we're done
322099d8f83cSChris Mason 	 */
322199d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
322299d8f83cSChris Mason 		return 0;
322399d8f83cSChris Mason 
3224e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
322599d8f83cSChris Mason 		return 0;
322699d8f83cSChris Mason 
322799d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
322899d8f83cSChris Mason 	slot = path->slots[0];
3229263d3995SFilipe Manana 	space_needed = data_size;
3230263d3995SFilipe Manana 	if (slot > 0)
3231e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
32325a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
323399d8f83cSChris Mason 	if (ret < 0)
323499d8f83cSChris Mason 		return ret;
323599d8f83cSChris Mason 
323699d8f83cSChris Mason 	if (ret == 0)
323799d8f83cSChris Mason 		progress++;
323899d8f83cSChris Mason 
323999d8f83cSChris Mason 	if (progress)
324099d8f83cSChris Mason 		return 0;
324199d8f83cSChris Mason 	return 1;
324299d8f83cSChris Mason }
324399d8f83cSChris Mason 
324499d8f83cSChris Mason /*
324544871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
324644871b1bSChris Mason  * available for the resulting leaf level of the path.
324744871b1bSChris Mason  *
324844871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
324944871b1bSChris Mason  */
325044871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
325144871b1bSChris Mason 			       struct btrfs_root *root,
3252310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
325344871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
325444871b1bSChris Mason 			       int extend)
325544871b1bSChris Mason {
32565d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
325744871b1bSChris Mason 	struct extent_buffer *l;
325844871b1bSChris Mason 	u32 nritems;
325944871b1bSChris Mason 	int mid;
326044871b1bSChris Mason 	int slot;
326144871b1bSChris Mason 	struct extent_buffer *right;
3262b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
326344871b1bSChris Mason 	int ret = 0;
326444871b1bSChris Mason 	int wret;
32655d4f98a2SYan Zheng 	int split;
326644871b1bSChris Mason 	int num_doubles = 0;
326799d8f83cSChris Mason 	int tried_avoid_double = 0;
326844871b1bSChris Mason 
3269a5719521SYan, Zheng 	l = path->nodes[0];
3270a5719521SYan, Zheng 	slot = path->slots[0];
3271a5719521SYan, Zheng 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
32720b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3273a5719521SYan, Zheng 		return -EOVERFLOW;
3274a5719521SYan, Zheng 
327544871b1bSChris Mason 	/* first try to make some room by pushing left and right */
327633157e05SLiu Bo 	if (data_size && path->nodes[1]) {
32775a4267caSFilipe David Borba Manana 		int space_needed = data_size;
32785a4267caSFilipe David Borba Manana 
32795a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3280e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
32815a4267caSFilipe David Borba Manana 
32825a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
32835a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
328444871b1bSChris Mason 		if (wret < 0)
328544871b1bSChris Mason 			return wret;
328644871b1bSChris Mason 		if (wret) {
3287263d3995SFilipe Manana 			space_needed = data_size;
3288263d3995SFilipe Manana 			if (slot > 0)
3289e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
32905a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
32915a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
329244871b1bSChris Mason 			if (wret < 0)
329344871b1bSChris Mason 				return wret;
329444871b1bSChris Mason 		}
329544871b1bSChris Mason 		l = path->nodes[0];
329644871b1bSChris Mason 
329744871b1bSChris Mason 		/* did the pushes work? */
3298e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
329944871b1bSChris Mason 			return 0;
330044871b1bSChris Mason 	}
330144871b1bSChris Mason 
330244871b1bSChris Mason 	if (!path->nodes[1]) {
3303fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
330444871b1bSChris Mason 		if (ret)
330544871b1bSChris Mason 			return ret;
330644871b1bSChris Mason 	}
330744871b1bSChris Mason again:
33085d4f98a2SYan Zheng 	split = 1;
330944871b1bSChris Mason 	l = path->nodes[0];
331044871b1bSChris Mason 	slot = path->slots[0];
331144871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
331244871b1bSChris Mason 	mid = (nritems + 1) / 2;
331344871b1bSChris Mason 
33145d4f98a2SYan Zheng 	if (mid <= slot) {
33155d4f98a2SYan Zheng 		if (nritems == 1 ||
33165d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
33170b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
33185d4f98a2SYan Zheng 			if (slot >= nritems) {
33195d4f98a2SYan Zheng 				split = 0;
33205d4f98a2SYan Zheng 			} else {
33215d4f98a2SYan Zheng 				mid = slot;
33225d4f98a2SYan Zheng 				if (mid != nritems &&
33235d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
33240b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
332599d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
332699d8f83cSChris Mason 						goto push_for_double;
33275d4f98a2SYan Zheng 					split = 2;
33285d4f98a2SYan Zheng 				}
33295d4f98a2SYan Zheng 			}
33305d4f98a2SYan Zheng 		}
33315d4f98a2SYan Zheng 	} else {
33325d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
33330b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
33345d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
33355d4f98a2SYan Zheng 				split = 0;
33365d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
33375d4f98a2SYan Zheng 				mid = 1;
33385d4f98a2SYan Zheng 			} else {
33395d4f98a2SYan Zheng 				mid = slot;
33405d4f98a2SYan Zheng 				if (mid != nritems &&
33415d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
33420b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
334399d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
334499d8f83cSChris Mason 						goto push_for_double;
33455d4f98a2SYan Zheng 					split = 2;
33465d4f98a2SYan Zheng 				}
33475d4f98a2SYan Zheng 			}
33485d4f98a2SYan Zheng 		}
33495d4f98a2SYan Zheng 	}
33505d4f98a2SYan Zheng 
33515d4f98a2SYan Zheng 	if (split == 0)
33525d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
33535d4f98a2SYan Zheng 	else
33545d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
33555d4f98a2SYan Zheng 
3356ca9d473aSJosef Bacik 	/*
3357ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3358ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3359ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3360ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3361ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3362ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3363ca9d473aSJosef Bacik 	 */
336479bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
336579bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
336679bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3367ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3368f0486c68SYan, Zheng 	if (IS_ERR(right))
336944871b1bSChris Mason 		return PTR_ERR(right);
3370f0486c68SYan, Zheng 
33710b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
337244871b1bSChris Mason 
33735d4f98a2SYan Zheng 	if (split == 0) {
337444871b1bSChris Mason 		if (mid <= slot) {
337544871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
33766ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
33772ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
337844871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
337944871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
338044871b1bSChris Mason 			path->nodes[0] = right;
338144871b1bSChris Mason 			path->slots[0] = 0;
338244871b1bSChris Mason 			path->slots[1] += 1;
338344871b1bSChris Mason 		} else {
338444871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
33856ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
33862ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
338744871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
338844871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
338944871b1bSChris Mason 			path->nodes[0] = right;
339044871b1bSChris Mason 			path->slots[0] = 0;
3391143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3392b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
33935d4f98a2SYan Zheng 		}
3394196e0249SLiu Bo 		/*
3395196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3396196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3397196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3398196e0249SLiu Bo 		 */
339944871b1bSChris Mason 		return ret;
340044871b1bSChris Mason 	}
340144871b1bSChris Mason 
340294f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
340344871b1bSChris Mason 
34045d4f98a2SYan Zheng 	if (split == 2) {
3405cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3406cc0c5538SChris Mason 		num_doubles++;
3407cc0c5538SChris Mason 		goto again;
34083326d1b0SChris Mason 	}
340944871b1bSChris Mason 
3410143bede5SJeff Mahoney 	return 0;
341199d8f83cSChris Mason 
341299d8f83cSChris Mason push_for_double:
341399d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
341499d8f83cSChris Mason 	tried_avoid_double = 1;
3415e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
341699d8f83cSChris Mason 		return 0;
341799d8f83cSChris Mason 	goto again;
3418be0e5c09SChris Mason }
3419be0e5c09SChris Mason 
3420ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3421ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3422ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3423ad48fd75SYan, Zheng {
3424ad48fd75SYan, Zheng 	struct btrfs_key key;
3425ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3426ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3427ad48fd75SYan, Zheng 	u64 extent_len = 0;
3428ad48fd75SYan, Zheng 	u32 item_size;
3429ad48fd75SYan, Zheng 	int ret;
3430ad48fd75SYan, Zheng 
3431ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3432ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3433ad48fd75SYan, Zheng 
3434ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3435ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3436ad48fd75SYan, Zheng 
3437e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3438ad48fd75SYan, Zheng 		return 0;
3439ad48fd75SYan, Zheng 
3440ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3441ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3442ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3443ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3444ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3445ad48fd75SYan, Zheng 	}
3446b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3447ad48fd75SYan, Zheng 
3448ad48fd75SYan, Zheng 	path->keep_locks = 1;
3449ad48fd75SYan, Zheng 	path->search_for_split = 1;
3450ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3451ad48fd75SYan, Zheng 	path->search_for_split = 0;
3452a8df6fe6SFilipe Manana 	if (ret > 0)
3453a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3454ad48fd75SYan, Zheng 	if (ret < 0)
3455ad48fd75SYan, Zheng 		goto err;
3456ad48fd75SYan, Zheng 
3457ad48fd75SYan, Zheng 	ret = -EAGAIN;
3458ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3459a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
3460a8df6fe6SFilipe Manana 	if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
3461ad48fd75SYan, Zheng 		goto err;
3462ad48fd75SYan, Zheng 
3463109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3464e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3465109f6aefSChris Mason 		goto err;
3466109f6aefSChris Mason 
3467ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3468ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3469ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3470ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3471ad48fd75SYan, Zheng 			goto err;
3472ad48fd75SYan, Zheng 	}
3473ad48fd75SYan, Zheng 
3474ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3475f0486c68SYan, Zheng 	if (ret)
3476f0486c68SYan, Zheng 		goto err;
3477ad48fd75SYan, Zheng 
3478ad48fd75SYan, Zheng 	path->keep_locks = 0;
3479ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3480ad48fd75SYan, Zheng 	return 0;
3481ad48fd75SYan, Zheng err:
3482ad48fd75SYan, Zheng 	path->keep_locks = 0;
3483ad48fd75SYan, Zheng 	return ret;
3484ad48fd75SYan, Zheng }
3485ad48fd75SYan, Zheng 
348625263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3487310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3488459931ecSChris Mason 			       unsigned long split_offset)
3489459931ecSChris Mason {
3490459931ecSChris Mason 	struct extent_buffer *leaf;
3491459931ecSChris Mason 	struct btrfs_item *item;
3492459931ecSChris Mason 	struct btrfs_item *new_item;
3493459931ecSChris Mason 	int slot;
3494ad48fd75SYan, Zheng 	char *buf;
3495459931ecSChris Mason 	u32 nritems;
3496ad48fd75SYan, Zheng 	u32 item_size;
3497459931ecSChris Mason 	u32 orig_offset;
3498459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3499459931ecSChris Mason 
3500459931ecSChris Mason 	leaf = path->nodes[0];
3501e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3502b9473439SChris Mason 
3503dd3cc16bSRoss Kirk 	item = btrfs_item_nr(path->slots[0]);
3504459931ecSChris Mason 	orig_offset = btrfs_item_offset(leaf, item);
3505459931ecSChris Mason 	item_size = btrfs_item_size(leaf, item);
3506459931ecSChris Mason 
3507459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3508ad48fd75SYan, Zheng 	if (!buf)
3509ad48fd75SYan, Zheng 		return -ENOMEM;
3510ad48fd75SYan, Zheng 
3511459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3512459931ecSChris Mason 			    path->slots[0]), item_size);
3513ad48fd75SYan, Zheng 
3514459931ecSChris Mason 	slot = path->slots[0] + 1;
3515459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3516459931ecSChris Mason 	if (slot != nritems) {
3517459931ecSChris Mason 		/* shift the items */
3518459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3519459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3520459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3521459931ecSChris Mason 	}
3522459931ecSChris Mason 
3523459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3524459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3525459931ecSChris Mason 
3526dd3cc16bSRoss Kirk 	new_item = btrfs_item_nr(slot);
3527459931ecSChris Mason 
3528459931ecSChris Mason 	btrfs_set_item_offset(leaf, new_item, orig_offset);
3529459931ecSChris Mason 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
3530459931ecSChris Mason 
3531459931ecSChris Mason 	btrfs_set_item_offset(leaf, item,
3532459931ecSChris Mason 			      orig_offset + item_size - split_offset);
3533459931ecSChris Mason 	btrfs_set_item_size(leaf, item, split_offset);
3534459931ecSChris Mason 
3535459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3536459931ecSChris Mason 
3537459931ecSChris Mason 	/* write the data for the start of the original item */
3538459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3539459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3540459931ecSChris Mason 			    split_offset);
3541459931ecSChris Mason 
3542459931ecSChris Mason 	/* write the data for the new item */
3543459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3544459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3545459931ecSChris Mason 			    item_size - split_offset);
3546459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3547459931ecSChris Mason 
3548e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3549459931ecSChris Mason 	kfree(buf);
3550ad48fd75SYan, Zheng 	return 0;
3551ad48fd75SYan, Zheng }
3552ad48fd75SYan, Zheng 
3553ad48fd75SYan, Zheng /*
3554ad48fd75SYan, Zheng  * This function splits a single item into two items,
3555ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3556ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3557ad48fd75SYan, Zheng  *
3558ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3559ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3560ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3561ad48fd75SYan, Zheng  *
3562ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3563ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3564ad48fd75SYan, Zheng  *
3565ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3566ad48fd75SYan, Zheng  * leaf the entire time.
3567ad48fd75SYan, Zheng  */
3568ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3569ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3570ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3571310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3572ad48fd75SYan, Zheng 		     unsigned long split_offset)
3573ad48fd75SYan, Zheng {
3574ad48fd75SYan, Zheng 	int ret;
3575ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3576ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3577ad48fd75SYan, Zheng 	if (ret)
3578459931ecSChris Mason 		return ret;
3579ad48fd75SYan, Zheng 
358025263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3581ad48fd75SYan, Zheng 	return ret;
3582ad48fd75SYan, Zheng }
3583ad48fd75SYan, Zheng 
3584ad48fd75SYan, Zheng /*
3585ad48fd75SYan, Zheng  * This function duplicate a item, giving 'new_key' to the new item.
3586ad48fd75SYan, Zheng  * It guarantees both items live in the same tree leaf and the new item
3587ad48fd75SYan, Zheng  * is contiguous with the original item.
3588ad48fd75SYan, Zheng  *
3589ad48fd75SYan, Zheng  * This allows us to split file extent in place, keeping a lock on the
3590ad48fd75SYan, Zheng  * leaf the entire time.
3591ad48fd75SYan, Zheng  */
3592ad48fd75SYan, Zheng int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
3593ad48fd75SYan, Zheng 			 struct btrfs_root *root,
3594ad48fd75SYan, Zheng 			 struct btrfs_path *path,
3595310712b2SOmar Sandoval 			 const struct btrfs_key *new_key)
3596ad48fd75SYan, Zheng {
3597ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3598ad48fd75SYan, Zheng 	int ret;
3599ad48fd75SYan, Zheng 	u32 item_size;
3600ad48fd75SYan, Zheng 
3601ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3602ad48fd75SYan, Zheng 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3603ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3604ad48fd75SYan, Zheng 				   item_size + sizeof(struct btrfs_item));
3605ad48fd75SYan, Zheng 	if (ret)
3606ad48fd75SYan, Zheng 		return ret;
3607ad48fd75SYan, Zheng 
3608ad48fd75SYan, Zheng 	path->slots[0]++;
3609fc0d82e1SNikolay Borisov 	setup_items_for_insert(root, path, new_key, &item_size, 1);
3610ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3611ad48fd75SYan, Zheng 	memcpy_extent_buffer(leaf,
3612ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
3613ad48fd75SYan, Zheng 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
3614ad48fd75SYan, Zheng 			     item_size);
3615ad48fd75SYan, Zheng 	return 0;
3616459931ecSChris Mason }
3617459931ecSChris Mason 
3618459931ecSChris Mason /*
3619d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
3620d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
3621d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
3622d352ac68SChris Mason  * the front.
3623d352ac68SChris Mason  */
362478ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3625b18c6685SChris Mason {
3626b18c6685SChris Mason 	int slot;
36275f39d397SChris Mason 	struct extent_buffer *leaf;
36285f39d397SChris Mason 	struct btrfs_item *item;
3629b18c6685SChris Mason 	u32 nritems;
3630b18c6685SChris Mason 	unsigned int data_end;
3631b18c6685SChris Mason 	unsigned int old_data_start;
3632b18c6685SChris Mason 	unsigned int old_size;
3633b18c6685SChris Mason 	unsigned int size_diff;
3634b18c6685SChris Mason 	int i;
3635cfed81a0SChris Mason 	struct btrfs_map_token token;
3636cfed81a0SChris Mason 
36375f39d397SChris Mason 	leaf = path->nodes[0];
3638179e29e4SChris Mason 	slot = path->slots[0];
3639179e29e4SChris Mason 
3640179e29e4SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
3641179e29e4SChris Mason 	if (old_size == new_size)
3642143bede5SJeff Mahoney 		return;
3643b18c6685SChris Mason 
36445f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
36458f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3646b18c6685SChris Mason 
36475f39d397SChris Mason 	old_data_start = btrfs_item_offset_nr(leaf, slot);
3648179e29e4SChris Mason 
3649b18c6685SChris Mason 	size_diff = old_size - new_size;
3650b18c6685SChris Mason 
3651b18c6685SChris Mason 	BUG_ON(slot < 0);
3652b18c6685SChris Mason 	BUG_ON(slot >= nritems);
3653b18c6685SChris Mason 
3654b18c6685SChris Mason 	/*
3655b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3656b18c6685SChris Mason 	 */
3657b18c6685SChris Mason 	/* first correct the data pointers */
3658c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3659b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
36605f39d397SChris Mason 		u32 ioff;
3661dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3662db94535dSChris Mason 
3663cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
3664cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff + size_diff);
3665b18c6685SChris Mason 	}
3666db94535dSChris Mason 
3667b18c6685SChris Mason 	/* shift the data */
3668179e29e4SChris Mason 	if (from_end) {
36693d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
36703d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3671b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
3672179e29e4SChris Mason 	} else {
3673179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
3674179e29e4SChris Mason 		u64 offset;
3675179e29e4SChris Mason 
3676179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
3677179e29e4SChris Mason 
3678179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3679179e29e4SChris Mason 			unsigned long ptr;
3680179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
3681179e29e4SChris Mason 
3682179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
3683179e29e4SChris Mason 					    struct btrfs_file_extent_item);
3684179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
3685179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
3686179e29e4SChris Mason 
3687179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
3688179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
3689179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
3690179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
3691179e29e4SChris Mason 				      (unsigned long)fi,
36927ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
3693179e29e4SChris Mason 			}
3694179e29e4SChris Mason 		}
3695179e29e4SChris Mason 
36963d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
36973d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3698179e29e4SChris Mason 			      data_end, old_data_start - data_end);
3699179e29e4SChris Mason 
3700179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
3701179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3702179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
3703179e29e4SChris Mason 		if (slot == 0)
3704b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
3705179e29e4SChris Mason 	}
37065f39d397SChris Mason 
3707dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
37085f39d397SChris Mason 	btrfs_set_item_size(leaf, item, new_size);
37095f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3710b18c6685SChris Mason 
3711e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3712a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3713b18c6685SChris Mason 		BUG();
37145f39d397SChris Mason 	}
3715b18c6685SChris Mason }
3716b18c6685SChris Mason 
3717d352ac68SChris Mason /*
37188f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
3719d352ac68SChris Mason  */
3720c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
37216567e837SChris Mason {
37226567e837SChris Mason 	int slot;
37235f39d397SChris Mason 	struct extent_buffer *leaf;
37245f39d397SChris Mason 	struct btrfs_item *item;
37256567e837SChris Mason 	u32 nritems;
37266567e837SChris Mason 	unsigned int data_end;
37276567e837SChris Mason 	unsigned int old_data;
37286567e837SChris Mason 	unsigned int old_size;
37296567e837SChris Mason 	int i;
3730cfed81a0SChris Mason 	struct btrfs_map_token token;
3731cfed81a0SChris Mason 
37325f39d397SChris Mason 	leaf = path->nodes[0];
37336567e837SChris Mason 
37345f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
37358f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
37366567e837SChris Mason 
3737e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
3738a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
37396567e837SChris Mason 		BUG();
37405f39d397SChris Mason 	}
37416567e837SChris Mason 	slot = path->slots[0];
37425f39d397SChris Mason 	old_data = btrfs_item_end_nr(leaf, slot);
37436567e837SChris Mason 
37446567e837SChris Mason 	BUG_ON(slot < 0);
37453326d1b0SChris Mason 	if (slot >= nritems) {
3746a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3747c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
3748d397712bSChris Mason 			   slot, nritems);
3749290342f6SArnd Bergmann 		BUG();
37503326d1b0SChris Mason 	}
37516567e837SChris Mason 
37526567e837SChris Mason 	/*
37536567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
37546567e837SChris Mason 	 */
37556567e837SChris Mason 	/* first correct the data pointers */
3756c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
37576567e837SChris Mason 	for (i = slot; i < nritems; i++) {
37585f39d397SChris Mason 		u32 ioff;
3759dd3cc16bSRoss Kirk 		item = btrfs_item_nr(i);
3760db94535dSChris Mason 
3761cc4c13d5SDavid Sterba 		ioff = btrfs_token_item_offset(&token, item);
3762cc4c13d5SDavid Sterba 		btrfs_set_token_item_offset(&token, item, ioff - data_size);
37636567e837SChris Mason 	}
37645f39d397SChris Mason 
37656567e837SChris Mason 	/* shift the data */
37663d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
37673d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
37686567e837SChris Mason 		      data_end, old_data - data_end);
37695f39d397SChris Mason 
37706567e837SChris Mason 	data_end = old_data;
37715f39d397SChris Mason 	old_size = btrfs_item_size_nr(leaf, slot);
3772dd3cc16bSRoss Kirk 	item = btrfs_item_nr(slot);
37735f39d397SChris Mason 	btrfs_set_item_size(leaf, item, old_size + data_size);
37745f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
37756567e837SChris Mason 
3776e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3777a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
37786567e837SChris Mason 		BUG();
37795f39d397SChris Mason 	}
37806567e837SChris Mason }
37816567e837SChris Mason 
3782da9ffb24SNikolay Borisov /**
3783da9ffb24SNikolay Borisov  * setup_items_for_insert - Helper called before inserting one or more items
3784da9ffb24SNikolay Borisov  * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
3785da9ffb24SNikolay Borisov  * in a function that doesn't call btrfs_search_slot
3786da9ffb24SNikolay Borisov  *
3787da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
3788da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
3789da9ffb24SNikolay Borisov  * @cpu_key:	array of keys for items to be inserted
3790da9ffb24SNikolay Borisov  * @data_size:	size of the body of each item we are going to insert
3791da9ffb24SNikolay Borisov  * @nr:		size of @cpu_key/@data_size arrays
379274123bd7SChris Mason  */
3793afe5fea7STsutomu Itoh void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
3794310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
3795fc0d82e1SNikolay Borisov 			    int nr)
3796be0e5c09SChris Mason {
37970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
37985f39d397SChris Mason 	struct btrfs_item *item;
37999c58309dSChris Mason 	int i;
38007518a238SChris Mason 	u32 nritems;
3801be0e5c09SChris Mason 	unsigned int data_end;
3802e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
380344871b1bSChris Mason 	struct extent_buffer *leaf;
380444871b1bSChris Mason 	int slot;
3805cfed81a0SChris Mason 	struct btrfs_map_token token;
3806fc0d82e1SNikolay Borisov 	u32 total_size;
3807fc0d82e1SNikolay Borisov 	u32 total_data = 0;
3808fc0d82e1SNikolay Borisov 
3809fc0d82e1SNikolay Borisov 	for (i = 0; i < nr; i++)
3810fc0d82e1SNikolay Borisov 		total_data += data_size[i];
3811fc0d82e1SNikolay Borisov 	total_size = total_data + (nr * sizeof(struct btrfs_item));
3812cfed81a0SChris Mason 
381324cdc847SFilipe Manana 	if (path->slots[0] == 0) {
381424cdc847SFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
3815b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
381624cdc847SFilipe Manana 	}
381724cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
381824cdc847SFilipe Manana 
38195f39d397SChris Mason 	leaf = path->nodes[0];
382044871b1bSChris Mason 	slot = path->slots[0];
382174123bd7SChris Mason 
38225f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
38238f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3824eb60ceacSChris Mason 
3825e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
3826a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
38270b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
3828e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
3829be0e5c09SChris Mason 		BUG();
3830d4dbff95SChris Mason 	}
38315f39d397SChris Mason 
3832c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3833be0e5c09SChris Mason 	if (slot != nritems) {
38345f39d397SChris Mason 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
3835be0e5c09SChris Mason 
38365f39d397SChris Mason 		if (old_data < data_end) {
3837a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
38387269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
38397269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
38405f39d397SChris Mason 				   slot, old_data, data_end);
3841290342f6SArnd Bergmann 			BUG();
38425f39d397SChris Mason 		}
3843be0e5c09SChris Mason 		/*
3844be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3845be0e5c09SChris Mason 		 */
3846be0e5c09SChris Mason 		/* first correct the data pointers */
38470783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
38485f39d397SChris Mason 			u32 ioff;
3849db94535dSChris Mason 
3850dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
3851cc4c13d5SDavid Sterba 			ioff = btrfs_token_item_offset(&token, item);
3852cc4c13d5SDavid Sterba 			btrfs_set_token_item_offset(&token, item,
3853cc4c13d5SDavid Sterba 						    ioff - total_data);
38540783fcfcSChris Mason 		}
3855be0e5c09SChris Mason 		/* shift the items */
38569c58309dSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
38575f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
38580783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
3859be0e5c09SChris Mason 
3860be0e5c09SChris Mason 		/* shift the data */
38613d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
38623d9ec8c4SNikolay Borisov 			      data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
3863be0e5c09SChris Mason 			      data_end, old_data - data_end);
3864be0e5c09SChris Mason 		data_end = old_data;
3865be0e5c09SChris Mason 	}
38665f39d397SChris Mason 
386762e2749eSChris Mason 	/* setup the item for the new data */
38689c58309dSChris Mason 	for (i = 0; i < nr; i++) {
38699c58309dSChris Mason 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
38709c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
3871dd3cc16bSRoss Kirk 		item = btrfs_item_nr(slot + i);
38729c58309dSChris Mason 		data_end -= data_size[i];
3873fc0716c2SNikolay Borisov 		btrfs_set_token_item_offset(&token, item, data_end);
3874cc4c13d5SDavid Sterba 		btrfs_set_token_item_size(&token, item, data_size[i]);
38759c58309dSChris Mason 	}
387644871b1bSChris Mason 
38779c58309dSChris Mason 	btrfs_set_header_nritems(leaf, nritems + nr);
3878b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3879aa5d6bedSChris Mason 
3880e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3881a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3882be0e5c09SChris Mason 		BUG();
38835f39d397SChris Mason 	}
388444871b1bSChris Mason }
388544871b1bSChris Mason 
388644871b1bSChris Mason /*
388744871b1bSChris Mason  * Given a key and some data, insert items into the tree.
388844871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
388944871b1bSChris Mason  */
389044871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
389144871b1bSChris Mason 			    struct btrfs_root *root,
389244871b1bSChris Mason 			    struct btrfs_path *path,
3893310712b2SOmar Sandoval 			    const struct btrfs_key *cpu_key, u32 *data_size,
389444871b1bSChris Mason 			    int nr)
389544871b1bSChris Mason {
389644871b1bSChris Mason 	int ret = 0;
389744871b1bSChris Mason 	int slot;
389844871b1bSChris Mason 	int i;
389944871b1bSChris Mason 	u32 total_size = 0;
390044871b1bSChris Mason 	u32 total_data = 0;
390144871b1bSChris Mason 
390244871b1bSChris Mason 	for (i = 0; i < nr; i++)
390344871b1bSChris Mason 		total_data += data_size[i];
390444871b1bSChris Mason 
390544871b1bSChris Mason 	total_size = total_data + (nr * sizeof(struct btrfs_item));
390644871b1bSChris Mason 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
390744871b1bSChris Mason 	if (ret == 0)
390844871b1bSChris Mason 		return -EEXIST;
390944871b1bSChris Mason 	if (ret < 0)
3910143bede5SJeff Mahoney 		return ret;
391144871b1bSChris Mason 
391244871b1bSChris Mason 	slot = path->slots[0];
391344871b1bSChris Mason 	BUG_ON(slot < 0);
391444871b1bSChris Mason 
3915fc0d82e1SNikolay Borisov 	setup_items_for_insert(root, path, cpu_key, data_size, nr);
3916143bede5SJeff Mahoney 	return 0;
391762e2749eSChris Mason }
391862e2749eSChris Mason 
391962e2749eSChris Mason /*
392062e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
392162e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
392262e2749eSChris Mason  */
3923310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3924310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
3925310712b2SOmar Sandoval 		      u32 data_size)
392662e2749eSChris Mason {
392762e2749eSChris Mason 	int ret = 0;
39282c90e5d6SChris Mason 	struct btrfs_path *path;
39295f39d397SChris Mason 	struct extent_buffer *leaf;
39305f39d397SChris Mason 	unsigned long ptr;
393162e2749eSChris Mason 
39322c90e5d6SChris Mason 	path = btrfs_alloc_path();
3933db5b493aSTsutomu Itoh 	if (!path)
3934db5b493aSTsutomu Itoh 		return -ENOMEM;
39352c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
393662e2749eSChris Mason 	if (!ret) {
39375f39d397SChris Mason 		leaf = path->nodes[0];
39385f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
39395f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
39405f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
394162e2749eSChris Mason 	}
39422c90e5d6SChris Mason 	btrfs_free_path(path);
3943aa5d6bedSChris Mason 	return ret;
3944be0e5c09SChris Mason }
3945be0e5c09SChris Mason 
394674123bd7SChris Mason /*
39475de08d7dSChris Mason  * delete the pointer from a given node.
394874123bd7SChris Mason  *
3949d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
3950d352ac68SChris Mason  * empty a node.
395174123bd7SChris Mason  */
3952afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
3953afe5fea7STsutomu Itoh 		    int level, int slot)
3954be0e5c09SChris Mason {
39555f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
39567518a238SChris Mason 	u32 nritems;
3957f3ea38daSJan Schmidt 	int ret;
3958be0e5c09SChris Mason 
39595f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
3960be0e5c09SChris Mason 	if (slot != nritems - 1) {
3961bf1d3425SDavid Sterba 		if (level) {
3962f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
3963f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
3964bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
3965bf1d3425SDavid Sterba 		}
39665f39d397SChris Mason 		memmove_extent_buffer(parent,
39675f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
39685f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
3969d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
3970d6025579SChris Mason 			      (nritems - slot - 1));
397157ba86c0SChris Mason 	} else if (level) {
3972f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
3973f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REMOVE, GFP_NOFS);
397457ba86c0SChris Mason 		BUG_ON(ret < 0);
3975be0e5c09SChris Mason 	}
3976f3ea38daSJan Schmidt 
39777518a238SChris Mason 	nritems--;
39785f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
39797518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
39805f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
3981eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
39825f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
3983bb803951SChris Mason 	} else if (slot == 0) {
39845f39d397SChris Mason 		struct btrfs_disk_key disk_key;
39855f39d397SChris Mason 
39865f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
3987b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
3988be0e5c09SChris Mason 	}
3989d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
3990be0e5c09SChris Mason }
3991be0e5c09SChris Mason 
399274123bd7SChris Mason /*
3993323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
39945d4f98a2SYan Zheng  * path->nodes[1].
3995323ac95bSChris Mason  *
3996323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
3997323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
3998323ac95bSChris Mason  *
3999323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4000323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4001323ac95bSChris Mason  */
4002143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4003323ac95bSChris Mason 				    struct btrfs_root *root,
40045d4f98a2SYan Zheng 				    struct btrfs_path *path,
40055d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4006323ac95bSChris Mason {
40075d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4008afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4009323ac95bSChris Mason 
40104d081c41SChris Mason 	/*
40114d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
40124d081c41SChris Mason 	 * aren't holding any locks when we call it
40134d081c41SChris Mason 	 */
40144d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
40154d081c41SChris Mason 
4016f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4017f0486c68SYan, Zheng 
401867439dadSDavid Sterba 	atomic_inc(&leaf->refs);
40195581a51aSJan Schmidt 	btrfs_free_tree_block(trans, root, leaf, 0, 1);
40203083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4021323ac95bSChris Mason }
4022323ac95bSChris Mason /*
402374123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
402474123bd7SChris Mason  * the leaf, remove it from the tree
402574123bd7SChris Mason  */
402685e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
402785e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4028be0e5c09SChris Mason {
40290b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
40305f39d397SChris Mason 	struct extent_buffer *leaf;
40315f39d397SChris Mason 	struct btrfs_item *item;
4032ce0eac2aSAlexandru Moise 	u32 last_off;
4033ce0eac2aSAlexandru Moise 	u32 dsize = 0;
4034aa5d6bedSChris Mason 	int ret = 0;
4035aa5d6bedSChris Mason 	int wret;
403685e21bacSChris Mason 	int i;
40377518a238SChris Mason 	u32 nritems;
4038be0e5c09SChris Mason 
40395f39d397SChris Mason 	leaf = path->nodes[0];
404085e21bacSChris Mason 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
404185e21bacSChris Mason 
404285e21bacSChris Mason 	for (i = 0; i < nr; i++)
404385e21bacSChris Mason 		dsize += btrfs_item_size_nr(leaf, slot + i);
404485e21bacSChris Mason 
40455f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4046be0e5c09SChris Mason 
404785e21bacSChris Mason 	if (slot + nr != nritems) {
40488f881e8cSDavid Sterba 		int data_end = leaf_data_end(leaf);
4049c82f823cSDavid Sterba 		struct btrfs_map_token token;
40505f39d397SChris Mason 
40513d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4052d6025579SChris Mason 			      data_end + dsize,
40533d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
405485e21bacSChris Mason 			      last_off - data_end);
40555f39d397SChris Mason 
4056c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
405785e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
40585f39d397SChris Mason 			u32 ioff;
4059db94535dSChris Mason 
4060dd3cc16bSRoss Kirk 			item = btrfs_item_nr(i);
4061cc4c13d5SDavid Sterba 			ioff = btrfs_token_item_offset(&token, item);
4062cc4c13d5SDavid Sterba 			btrfs_set_token_item_offset(&token, item, ioff + dsize);
40630783fcfcSChris Mason 		}
4064db94535dSChris Mason 
40655f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
406685e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
40670783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
406885e21bacSChris Mason 			      (nritems - slot - nr));
4069be0e5c09SChris Mason 	}
407085e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
407185e21bacSChris Mason 	nritems -= nr;
40725f39d397SChris Mason 
407374123bd7SChris Mason 	/* delete the leaf if we've emptied it */
40747518a238SChris Mason 	if (nritems == 0) {
40755f39d397SChris Mason 		if (leaf == root->node) {
40765f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
40779a8dd150SChris Mason 		} else {
40786a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4079143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
40809a8dd150SChris Mason 		}
4081be0e5c09SChris Mason 	} else {
40827518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4083aa5d6bedSChris Mason 		if (slot == 0) {
40845f39d397SChris Mason 			struct btrfs_disk_key disk_key;
40855f39d397SChris Mason 
40865f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4087b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4088aa5d6bedSChris Mason 		}
4089aa5d6bedSChris Mason 
409074123bd7SChris Mason 		/* delete the leaf if it is mostly empty */
40910b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
4092be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4093be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4094be0e5c09SChris Mason 			 * for possible call to del_ptr below
4095be0e5c09SChris Mason 			 */
40964920c9acSChris Mason 			slot = path->slots[1];
409767439dadSDavid Sterba 			atomic_inc(&leaf->refs);
40985f39d397SChris Mason 
409999d8f83cSChris Mason 			wret = push_leaf_left(trans, root, path, 1, 1,
410099d8f83cSChris Mason 					      1, (u32)-1);
410154aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4102aa5d6bedSChris Mason 				ret = wret;
41035f39d397SChris Mason 
41045f39d397SChris Mason 			if (path->nodes[0] == leaf &&
41055f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
410699d8f83cSChris Mason 				wret = push_leaf_right(trans, root, path, 1,
410799d8f83cSChris Mason 						       1, 1, 0);
410854aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4109aa5d6bedSChris Mason 					ret = wret;
4110aa5d6bedSChris Mason 			}
41115f39d397SChris Mason 
41125f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4113323ac95bSChris Mason 				path->slots[1] = slot;
4114143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
41155f39d397SChris Mason 				free_extent_buffer(leaf);
4116143bede5SJeff Mahoney 				ret = 0;
41175de08d7dSChris Mason 			} else {
4118925baeddSChris Mason 				/* if we're still in the path, make sure
4119925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4120925baeddSChris Mason 				 * push_leaf functions must have already
4121925baeddSChris Mason 				 * dirtied this buffer
4122925baeddSChris Mason 				 */
4123925baeddSChris Mason 				if (path->nodes[0] == leaf)
41245f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
41255f39d397SChris Mason 				free_extent_buffer(leaf);
4126be0e5c09SChris Mason 			}
4127d5719762SChris Mason 		} else {
41285f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4129be0e5c09SChris Mason 		}
41309a8dd150SChris Mason 	}
4131aa5d6bedSChris Mason 	return ret;
41329a8dd150SChris Mason }
41339a8dd150SChris Mason 
413497571fd0SChris Mason /*
4135925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
41367bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
41377bb86316SChris Mason  * returns < 0 on io errors.
4138d352ac68SChris Mason  *
4139d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4140d352ac68SChris Mason  * time you call it.
41417bb86316SChris Mason  */
414216e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
41437bb86316SChris Mason {
4144925baeddSChris Mason 	struct btrfs_key key;
4145925baeddSChris Mason 	struct btrfs_disk_key found_key;
4146925baeddSChris Mason 	int ret;
41477bb86316SChris Mason 
4148925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4149925baeddSChris Mason 
4150e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
4151925baeddSChris Mason 		key.offset--;
4152e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
4153925baeddSChris Mason 		key.type--;
4154e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4155e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
4156925baeddSChris Mason 		key.objectid--;
4157e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
4158e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4159e8b0d724SFilipe David Borba Manana 	} else {
41607bb86316SChris Mason 		return 1;
4161e8b0d724SFilipe David Borba Manana 	}
41627bb86316SChris Mason 
4163b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4164925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4165925baeddSChris Mason 	if (ret < 0)
4166925baeddSChris Mason 		return ret;
4167925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4168925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4169337c6f68SFilipe Manana 	/*
4170337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
4171337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
4172337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
4173337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
4174337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
4175337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
4176337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
4177337c6f68SFilipe Manana 	 * the previous key we computed above.
4178337c6f68SFilipe Manana 	 */
4179337c6f68SFilipe Manana 	if (ret <= 0)
41807bb86316SChris Mason 		return 0;
4181925baeddSChris Mason 	return 1;
41827bb86316SChris Mason }
41837bb86316SChris Mason 
41843f157a2fSChris Mason /*
41853f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4186de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4187de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
41883f157a2fSChris Mason  *
41893f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
41903f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
41913f157a2fSChris Mason  * key and get a writable path.
41923f157a2fSChris Mason  *
41933f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
41943f157a2fSChris Mason  * of the tree.
41953f157a2fSChris Mason  *
4196d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4197d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4198d352ac68SChris Mason  * skipped over (without reading them).
4199d352ac68SChris Mason  *
42003f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
42013f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
42023f157a2fSChris Mason  */
42033f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4204de78b51aSEric Sandeen 			 struct btrfs_path *path,
42053f157a2fSChris Mason 			 u64 min_trans)
42063f157a2fSChris Mason {
42073f157a2fSChris Mason 	struct extent_buffer *cur;
42083f157a2fSChris Mason 	struct btrfs_key found_key;
42093f157a2fSChris Mason 	int slot;
42109652480bSYan 	int sret;
42113f157a2fSChris Mason 	u32 nritems;
42123f157a2fSChris Mason 	int level;
42133f157a2fSChris Mason 	int ret = 1;
4214f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
42153f157a2fSChris Mason 
4216f98de9b9SFilipe Manana 	path->keep_locks = 1;
42173f157a2fSChris Mason again:
4218bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
42193f157a2fSChris Mason 	level = btrfs_header_level(cur);
4220e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
42213f157a2fSChris Mason 	path->nodes[level] = cur;
4222bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
42233f157a2fSChris Mason 
42243f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
42253f157a2fSChris Mason 		ret = 1;
42263f157a2fSChris Mason 		goto out;
42273f157a2fSChris Mason 	}
42283f157a2fSChris Mason 	while (1) {
42293f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
42303f157a2fSChris Mason 		level = btrfs_header_level(cur);
4231e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
4232cbca7d59SFilipe Manana 		if (sret < 0) {
4233cbca7d59SFilipe Manana 			ret = sret;
4234cbca7d59SFilipe Manana 			goto out;
4235cbca7d59SFilipe Manana 		}
42363f157a2fSChris Mason 
4237323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4238323ac95bSChris Mason 		if (level == path->lowest_level) {
4239e02119d5SChris Mason 			if (slot >= nritems)
4240e02119d5SChris Mason 				goto find_next_key;
42413f157a2fSChris Mason 			ret = 0;
42423f157a2fSChris Mason 			path->slots[level] = slot;
42433f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
42443f157a2fSChris Mason 			goto out;
42453f157a2fSChris Mason 		}
42469652480bSYan 		if (sret && slot > 0)
42479652480bSYan 			slot--;
42483f157a2fSChris Mason 		/*
4249de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4250260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
42513f157a2fSChris Mason 		 */
42523f157a2fSChris Mason 		while (slot < nritems) {
42533f157a2fSChris Mason 			u64 gen;
4254e02119d5SChris Mason 
42553f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
42563f157a2fSChris Mason 			if (gen < min_trans) {
42573f157a2fSChris Mason 				slot++;
42583f157a2fSChris Mason 				continue;
42593f157a2fSChris Mason 			}
42603f157a2fSChris Mason 			break;
42613f157a2fSChris Mason 		}
4262e02119d5SChris Mason find_next_key:
42633f157a2fSChris Mason 		/*
42643f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
42653f157a2fSChris Mason 		 * and find another one
42663f157a2fSChris Mason 		 */
42673f157a2fSChris Mason 		if (slot >= nritems) {
4268e02119d5SChris Mason 			path->slots[level] = slot;
4269e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4270de78b51aSEric Sandeen 						  min_trans);
4271e02119d5SChris Mason 			if (sret == 0) {
4272b3b4aa74SDavid Sterba 				btrfs_release_path(path);
42733f157a2fSChris Mason 				goto again;
42743f157a2fSChris Mason 			} else {
42753f157a2fSChris Mason 				goto out;
42763f157a2fSChris Mason 			}
42773f157a2fSChris Mason 		}
42783f157a2fSChris Mason 		/* save our key for returning back */
42793f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
42803f157a2fSChris Mason 		path->slots[level] = slot;
42813f157a2fSChris Mason 		if (level == path->lowest_level) {
42823f157a2fSChris Mason 			ret = 0;
42833f157a2fSChris Mason 			goto out;
42843f157a2fSChris Mason 		}
42854b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4286fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4287fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4288fb770ae4SLiu Bo 			goto out;
4289fb770ae4SLiu Bo 		}
42903f157a2fSChris Mason 
4291bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4292b4ce94deSChris Mason 
4293bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
42943f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4295f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
42963f157a2fSChris Mason 	}
42973f157a2fSChris Mason out:
4298f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4299f98de9b9SFilipe Manana 	if (ret == 0) {
4300f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4301f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4302f98de9b9SFilipe Manana 	}
43033f157a2fSChris Mason 	return ret;
43043f157a2fSChris Mason }
43053f157a2fSChris Mason 
43063f157a2fSChris Mason /*
43073f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
43083f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4309de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
43103f157a2fSChris Mason  *
43113f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
43123f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
43133f157a2fSChris Mason  *
43143f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
43153f157a2fSChris Mason  * calling this function.
43163f157a2fSChris Mason  */
4317e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4318de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4319e7a84565SChris Mason {
4320e7a84565SChris Mason 	int slot;
4321e7a84565SChris Mason 	struct extent_buffer *c;
4322e7a84565SChris Mason 
43236a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4324e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4325e7a84565SChris Mason 		if (!path->nodes[level])
4326e7a84565SChris Mason 			return 1;
4327e7a84565SChris Mason 
4328e7a84565SChris Mason 		slot = path->slots[level] + 1;
4329e7a84565SChris Mason 		c = path->nodes[level];
43303f157a2fSChris Mason next:
4331e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
433233c66f43SYan Zheng 			int ret;
433333c66f43SYan Zheng 			int orig_lowest;
433433c66f43SYan Zheng 			struct btrfs_key cur_key;
433533c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
433633c66f43SYan Zheng 			    !path->nodes[level + 1])
4337e7a84565SChris Mason 				return 1;
433833c66f43SYan Zheng 
43396a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
434033c66f43SYan Zheng 				level++;
4341e7a84565SChris Mason 				continue;
4342e7a84565SChris Mason 			}
434333c66f43SYan Zheng 
434433c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
434533c66f43SYan Zheng 			if (level == 0)
434633c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
434733c66f43SYan Zheng 			else
434833c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
434933c66f43SYan Zheng 
435033c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4351b3b4aa74SDavid Sterba 			btrfs_release_path(path);
435233c66f43SYan Zheng 			path->lowest_level = level;
435333c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
435433c66f43SYan Zheng 						0, 0);
435533c66f43SYan Zheng 			path->lowest_level = orig_lowest;
435633c66f43SYan Zheng 			if (ret < 0)
435733c66f43SYan Zheng 				return ret;
435833c66f43SYan Zheng 
435933c66f43SYan Zheng 			c = path->nodes[level];
436033c66f43SYan Zheng 			slot = path->slots[level];
436133c66f43SYan Zheng 			if (ret == 0)
436233c66f43SYan Zheng 				slot++;
436333c66f43SYan Zheng 			goto next;
436433c66f43SYan Zheng 		}
436533c66f43SYan Zheng 
4366e7a84565SChris Mason 		if (level == 0)
4367e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
43683f157a2fSChris Mason 		else {
43693f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
43703f157a2fSChris Mason 
43713f157a2fSChris Mason 			if (gen < min_trans) {
43723f157a2fSChris Mason 				slot++;
43733f157a2fSChris Mason 				goto next;
43743f157a2fSChris Mason 			}
4375e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
43763f157a2fSChris Mason 		}
4377e7a84565SChris Mason 		return 0;
4378e7a84565SChris Mason 	}
4379e7a84565SChris Mason 	return 1;
4380e7a84565SChris Mason }
4381e7a84565SChris Mason 
43823d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
43833d7806ecSJan Schmidt 			u64 time_seq)
43843d7806ecSJan Schmidt {
4385d97e63b6SChris Mason 	int slot;
43868e73f275SChris Mason 	int level;
43875f39d397SChris Mason 	struct extent_buffer *c;
43888e73f275SChris Mason 	struct extent_buffer *next;
4389925baeddSChris Mason 	struct btrfs_key key;
4390925baeddSChris Mason 	u32 nritems;
4391925baeddSChris Mason 	int ret;
43920e46318dSJosef Bacik 	int i;
4393925baeddSChris Mason 
4394925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4395d397712bSChris Mason 	if (nritems == 0)
4396925baeddSChris Mason 		return 1;
4397925baeddSChris Mason 
43988e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
43998e73f275SChris Mason again:
44008e73f275SChris Mason 	level = 1;
44018e73f275SChris Mason 	next = NULL;
4402b3b4aa74SDavid Sterba 	btrfs_release_path(path);
44038e73f275SChris Mason 
4404a2135011SChris Mason 	path->keep_locks = 1;
44058e73f275SChris Mason 
44063d7806ecSJan Schmidt 	if (time_seq)
44073d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
44083d7806ecSJan Schmidt 	else
4409925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4410925baeddSChris Mason 	path->keep_locks = 0;
4411925baeddSChris Mason 
4412925baeddSChris Mason 	if (ret < 0)
4413925baeddSChris Mason 		return ret;
4414925baeddSChris Mason 
4415a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4416168fd7d2SChris Mason 	/*
4417168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4418168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4419168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4420168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4421168fd7d2SChris Mason 	 */
4422a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4423e457afecSYan Zheng 		if (ret == 0)
4424168fd7d2SChris Mason 			path->slots[0]++;
44258e73f275SChris Mason 		ret = 0;
4426925baeddSChris Mason 		goto done;
4427925baeddSChris Mason 	}
44280b43e04fSLiu Bo 	/*
44290b43e04fSLiu Bo 	 * So the above check misses one case:
44300b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
44310b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
44320b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
44330b43e04fSLiu Bo 	 *
44340b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
44350b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
44360b43e04fSLiu Bo 	 *
44370b43e04fSLiu Bo 	 * And a bit more explanation about this check,
44380b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
44390b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
44400b43e04fSLiu Bo 	 * bigger one.
44410b43e04fSLiu Bo 	 */
44420b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
44430b43e04fSLiu Bo 		ret = 0;
44440b43e04fSLiu Bo 		goto done;
44450b43e04fSLiu Bo 	}
4446d97e63b6SChris Mason 
4447234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
44488e73f275SChris Mason 		if (!path->nodes[level]) {
44498e73f275SChris Mason 			ret = 1;
44508e73f275SChris Mason 			goto done;
44518e73f275SChris Mason 		}
44525f39d397SChris Mason 
4453d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4454d97e63b6SChris Mason 		c = path->nodes[level];
44555f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4456d97e63b6SChris Mason 			level++;
44578e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
44588e73f275SChris Mason 				ret = 1;
44598e73f275SChris Mason 				goto done;
44608e73f275SChris Mason 			}
4461d97e63b6SChris Mason 			continue;
4462d97e63b6SChris Mason 		}
44635f39d397SChris Mason 
44640e46318dSJosef Bacik 
44650e46318dSJosef Bacik 		/*
44660e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
44670e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
44680e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
44690e46318dSJosef Bacik 		 */
44700e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
44710e46318dSJosef Bacik 			if (path->locks[level]) {
44720e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
44730e46318dSJosef Bacik 				path->locks[i] = 0;
44740e46318dSJosef Bacik 			}
44750e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
44760e46318dSJosef Bacik 			path->nodes[i] = NULL;
4477925baeddSChris Mason 		}
44785f39d397SChris Mason 
44798e73f275SChris Mason 		next = c;
4480d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4481cda79c54SDavid Sterba 					    slot, &key);
44828e73f275SChris Mason 		if (ret == -EAGAIN)
44838e73f275SChris Mason 			goto again;
44845f39d397SChris Mason 
448576a05b35SChris Mason 		if (ret < 0) {
4486b3b4aa74SDavid Sterba 			btrfs_release_path(path);
448776a05b35SChris Mason 			goto done;
448876a05b35SChris Mason 		}
448976a05b35SChris Mason 
44905cd57b2cSChris Mason 		if (!path->skip_locking) {
4491bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4492d42244a0SJan Schmidt 			if (!ret && time_seq) {
4493d42244a0SJan Schmidt 				/*
4494d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4495d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4496d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4497d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4498d42244a0SJan Schmidt 				 * on our lock and cycle.
4499d42244a0SJan Schmidt 				 */
4500cf538830SJan Schmidt 				free_extent_buffer(next);
4501d42244a0SJan Schmidt 				btrfs_release_path(path);
4502d42244a0SJan Schmidt 				cond_resched();
4503d42244a0SJan Schmidt 				goto again;
4504d42244a0SJan Schmidt 			}
45050e46318dSJosef Bacik 			if (!ret)
45060e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4507bd681513SChris Mason 		}
4508d97e63b6SChris Mason 		break;
4509d97e63b6SChris Mason 	}
4510d97e63b6SChris Mason 	path->slots[level] = slot;
4511d97e63b6SChris Mason 	while (1) {
4512d97e63b6SChris Mason 		level--;
4513d97e63b6SChris Mason 		path->nodes[level] = next;
4514d97e63b6SChris Mason 		path->slots[level] = 0;
4515a74a4b97SChris Mason 		if (!path->skip_locking)
4516ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4517d97e63b6SChris Mason 		if (!level)
4518d97e63b6SChris Mason 			break;
4519b4ce94deSChris Mason 
4520d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4521cda79c54SDavid Sterba 					    0, &key);
45228e73f275SChris Mason 		if (ret == -EAGAIN)
45238e73f275SChris Mason 			goto again;
45248e73f275SChris Mason 
452576a05b35SChris Mason 		if (ret < 0) {
4526b3b4aa74SDavid Sterba 			btrfs_release_path(path);
452776a05b35SChris Mason 			goto done;
452876a05b35SChris Mason 		}
452976a05b35SChris Mason 
4530ffeb03cfSJosef Bacik 		if (!path->skip_locking)
45310e46318dSJosef Bacik 			btrfs_tree_read_lock(next);
4532d97e63b6SChris Mason 	}
45338e73f275SChris Mason 	ret = 0;
4534925baeddSChris Mason done:
4535f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
45368e73f275SChris Mason 
45378e73f275SChris Mason 	return ret;
4538d97e63b6SChris Mason }
45390b86a832SChris Mason 
45403f157a2fSChris Mason /*
45413f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
45423f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
45433f157a2fSChris Mason  *
45443f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
45453f157a2fSChris Mason  */
45460b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
45470b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
45480b86a832SChris Mason 			int type)
45490b86a832SChris Mason {
45500b86a832SChris Mason 	struct btrfs_key found_key;
45510b86a832SChris Mason 	struct extent_buffer *leaf;
4552e02119d5SChris Mason 	u32 nritems;
45530b86a832SChris Mason 	int ret;
45540b86a832SChris Mason 
45550b86a832SChris Mason 	while (1) {
45560b86a832SChris Mason 		if (path->slots[0] == 0) {
45570b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
45580b86a832SChris Mason 			if (ret != 0)
45590b86a832SChris Mason 				return ret;
45600b86a832SChris Mason 		} else {
45610b86a832SChris Mason 			path->slots[0]--;
45620b86a832SChris Mason 		}
45630b86a832SChris Mason 		leaf = path->nodes[0];
4564e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
4565e02119d5SChris Mason 		if (nritems == 0)
4566e02119d5SChris Mason 			return 1;
4567e02119d5SChris Mason 		if (path->slots[0] == nritems)
4568e02119d5SChris Mason 			path->slots[0]--;
4569e02119d5SChris Mason 
45700b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4571e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
4572e02119d5SChris Mason 			break;
45730a4eefbbSYan Zheng 		if (found_key.type == type)
45740a4eefbbSYan Zheng 			return 0;
4575e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
4576e02119d5SChris Mason 		    found_key.type < type)
4577e02119d5SChris Mason 			break;
45780b86a832SChris Mason 	}
45790b86a832SChris Mason 	return 1;
45800b86a832SChris Mason }
4581ade2e0b3SWang Shilong 
4582ade2e0b3SWang Shilong /*
4583ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
4584ade2e0b3SWang Shilong  * min objecitd.
4585ade2e0b3SWang Shilong  *
4586ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4587ade2e0b3SWang Shilong  */
4588ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
4589ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
4590ade2e0b3SWang Shilong {
4591ade2e0b3SWang Shilong 	struct btrfs_key found_key;
4592ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
4593ade2e0b3SWang Shilong 	u32 nritems;
4594ade2e0b3SWang Shilong 	int ret;
4595ade2e0b3SWang Shilong 
4596ade2e0b3SWang Shilong 	while (1) {
4597ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
4598ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
4599ade2e0b3SWang Shilong 			if (ret != 0)
4600ade2e0b3SWang Shilong 				return ret;
4601ade2e0b3SWang Shilong 		} else {
4602ade2e0b3SWang Shilong 			path->slots[0]--;
4603ade2e0b3SWang Shilong 		}
4604ade2e0b3SWang Shilong 		leaf = path->nodes[0];
4605ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
4606ade2e0b3SWang Shilong 		if (nritems == 0)
4607ade2e0b3SWang Shilong 			return 1;
4608ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
4609ade2e0b3SWang Shilong 			path->slots[0]--;
4610ade2e0b3SWang Shilong 
4611ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4612ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
4613ade2e0b3SWang Shilong 			break;
4614ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4615ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
4616ade2e0b3SWang Shilong 			return 0;
4617ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
4618ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
4619ade2e0b3SWang Shilong 			break;
4620ade2e0b3SWang Shilong 	}
4621ade2e0b3SWang Shilong 	return 1;
4622ade2e0b3SWang Shilong }
4623