xref: /openbmc/linux/fs/btrfs/ctree.c (revision 0cae23b66a5f42b8071f42757f13d87c90d3600b)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
26cbd5570SChris Mason /*
3d352ac68SChris Mason  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
46cbd5570SChris Mason  */
56cbd5570SChris Mason 
6a6b6e75eSChris Mason #include <linux/sched.h>
75a0e3ad6STejun Heo #include <linux/slab.h>
8bd989ba3SJan Schmidt #include <linux/rbtree.h>
9adf02123SDavid Sterba #include <linux/mm.h>
10e41d12f5SChristoph Hellwig #include <linux/error-injection.h>
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 
39949d0c642SFilipe Manana 	btrfs_assert_tree_write_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 
4667a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
4677a163608SFilipe Manana 				      parent_start, 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 		}
4887a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
4897a163608SFilipe Manana 				      parent_start, 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 /*
729fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
7305f39d397SChris Mason  *
731fb81212cSFilipe Manana  * The lower boundary for the search is specified by the slot number @low. Use a
732fb81212cSFilipe Manana  * value of 0 to search over the whole extent buffer.
73374123bd7SChris Mason  *
734fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
735fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
736fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
737fb81212cSFilipe Manana  *
738fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
739fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
74074123bd7SChris Mason  */
741fb81212cSFilipe Manana static noinline int generic_bin_search(struct extent_buffer *eb, int low,
74267d5e289SMarcos Paulo de Souza 				       const struct btrfs_key *key, int *slot)
743be0e5c09SChris Mason {
744fb81212cSFilipe Manana 	unsigned long p;
745fb81212cSFilipe Manana 	int item_size;
74667d5e289SMarcos Paulo de Souza 	int high = btrfs_header_nritems(eb);
747be0e5c09SChris Mason 	int ret;
7485cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
749be0e5c09SChris Mason 
7505e24e9afSLiu Bo 	if (low > high) {
7515e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
7525e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
7535e24e9afSLiu Bo 			  __func__, low, high, eb->start,
7545e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
7555e24e9afSLiu Bo 		return -EINVAL;
7565e24e9afSLiu Bo 	}
7575e24e9afSLiu Bo 
758fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
759fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
760fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
761fb81212cSFilipe Manana 	} else {
762fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
763fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
764fb81212cSFilipe Manana 	}
765fb81212cSFilipe Manana 
766be0e5c09SChris Mason 	while (low < high) {
7675cd17f34SDavid Sterba 		unsigned long oip;
7685cd17f34SDavid Sterba 		unsigned long offset;
7695cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
7705cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
7715cd17f34SDavid Sterba 		int mid;
7725cd17f34SDavid Sterba 
773be0e5c09SChris Mason 		mid = (low + high) / 2;
7745f39d397SChris Mason 		offset = p + mid * item_size;
7755cd17f34SDavid Sterba 		oip = offset_in_page(offset);
7765f39d397SChris Mason 
7775cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
778884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
7795cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
780934d375bSChris Mason 
781884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
7825cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
7835cd17f34SDavid Sterba 		} else {
7845cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
7855f39d397SChris Mason 			tmp = &unaligned;
786479965d6SChris Mason 		}
787479965d6SChris Mason 
788be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
789be0e5c09SChris Mason 
790be0e5c09SChris Mason 		if (ret < 0)
791be0e5c09SChris Mason 			low = mid + 1;
792be0e5c09SChris Mason 		else if (ret > 0)
793be0e5c09SChris Mason 			high = mid;
794be0e5c09SChris Mason 		else {
795be0e5c09SChris Mason 			*slot = mid;
796be0e5c09SChris Mason 			return 0;
797be0e5c09SChris Mason 		}
798be0e5c09SChris Mason 	}
799be0e5c09SChris Mason 	*slot = low;
800be0e5c09SChris Mason 	return 1;
801be0e5c09SChris Mason }
802be0e5c09SChris Mason 
80397571fd0SChris Mason /*
804fb81212cSFilipe Manana  * Simple binary search on an extent buffer. Works for both leaves and nodes, and
805fb81212cSFilipe Manana  * always searches over the whole range of keys (slot 0 to slot 'nritems - 1').
80697571fd0SChris Mason  */
807a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
808e3b83361SQu Wenruo 		     int *slot)
809be0e5c09SChris Mason {
810fb81212cSFilipe Manana 	return generic_bin_search(eb, 0, key, slot);
811be0e5c09SChris Mason }
812be0e5c09SChris Mason 
813f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
814f0486c68SYan, Zheng {
815f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
816f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
817f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
818f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
819f0486c68SYan, Zheng }
820f0486c68SYan, Zheng 
821f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
822f0486c68SYan, Zheng {
823f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
824f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
825f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
826f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
827f0486c68SYan, Zheng }
828f0486c68SYan, Zheng 
829d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
830d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
831d352ac68SChris Mason  */
8324b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
8334b231ae4SDavid Sterba 					   int slot)
834bb803951SChris Mason {
835ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
836416bc658SJosef Bacik 	struct extent_buffer *eb;
837581c1760SQu Wenruo 	struct btrfs_key first_key;
838416bc658SJosef Bacik 
839fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
840fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
841ca7a79adSChris Mason 
842ca7a79adSChris Mason 	BUG_ON(level == 0);
843ca7a79adSChris Mason 
844581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
845d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
8461b7ec85eSJosef Bacik 			     btrfs_header_owner(parent),
847581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
848581c1760SQu Wenruo 			     level - 1, &first_key);
849fb770ae4SLiu Bo 	if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
850416bc658SJosef Bacik 		free_extent_buffer(eb);
851fb770ae4SLiu Bo 		eb = ERR_PTR(-EIO);
852416bc658SJosef Bacik 	}
853416bc658SJosef Bacik 
854416bc658SJosef Bacik 	return eb;
855bb803951SChris Mason }
856bb803951SChris Mason 
857d352ac68SChris Mason /*
858d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
859d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
860d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
861d352ac68SChris Mason  */
862e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
86398ed5174SChris Mason 			 struct btrfs_root *root,
86498ed5174SChris Mason 			 struct btrfs_path *path, int level)
865bb803951SChris Mason {
8660b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8675f39d397SChris Mason 	struct extent_buffer *right = NULL;
8685f39d397SChris Mason 	struct extent_buffer *mid;
8695f39d397SChris Mason 	struct extent_buffer *left = NULL;
8705f39d397SChris Mason 	struct extent_buffer *parent = NULL;
871bb803951SChris Mason 	int ret = 0;
872bb803951SChris Mason 	int wret;
873bb803951SChris Mason 	int pslot;
874bb803951SChris Mason 	int orig_slot = path->slots[level];
87579f95c82SChris Mason 	u64 orig_ptr;
876bb803951SChris Mason 
87798e6b1ebSLiu Bo 	ASSERT(level > 0);
878bb803951SChris Mason 
8795f39d397SChris Mason 	mid = path->nodes[level];
880b4ce94deSChris Mason 
881ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
8827bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
8837bb86316SChris Mason 
8841d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
88579f95c82SChris Mason 
886a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
8875f39d397SChris Mason 		parent = path->nodes[level + 1];
888bb803951SChris Mason 		pslot = path->slots[level + 1];
889a05a9bb1SLi Zefan 	}
890bb803951SChris Mason 
89140689478SChris Mason 	/*
89240689478SChris Mason 	 * deal with the case where there is only one pointer in the root
89340689478SChris Mason 	 * by promoting the node below to a root
89440689478SChris Mason 	 */
8955f39d397SChris Mason 	if (!parent) {
8965f39d397SChris Mason 		struct extent_buffer *child;
897bb803951SChris Mason 
8985f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
899bb803951SChris Mason 			return 0;
900bb803951SChris Mason 
901bb803951SChris Mason 		/* promote the child to a root */
9024b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
903fb770ae4SLiu Bo 		if (IS_ERR(child)) {
904fb770ae4SLiu Bo 			ret = PTR_ERR(child);
9050b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
906305a26afSMark Fasheh 			goto enospc;
907305a26afSMark Fasheh 		}
908305a26afSMark Fasheh 
909925baeddSChris Mason 		btrfs_tree_lock(child);
9109631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
9119631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
912f0486c68SYan, Zheng 		if (ret) {
913f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
914f0486c68SYan, Zheng 			free_extent_buffer(child);
915f0486c68SYan, Zheng 			goto enospc;
916f0486c68SYan, Zheng 		}
9172f375ab9SYan 
918406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
919d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
920240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
921925baeddSChris Mason 
9220b86a832SChris Mason 		add_root_to_dirty_list(root);
923925baeddSChris Mason 		btrfs_tree_unlock(child);
924b4ce94deSChris Mason 
925925baeddSChris Mason 		path->locks[level] = 0;
926bb803951SChris Mason 		path->nodes[level] = NULL;
9276a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
928925baeddSChris Mason 		btrfs_tree_unlock(mid);
929bb803951SChris Mason 		/* once for the path */
9305f39d397SChris Mason 		free_extent_buffer(mid);
931f0486c68SYan, Zheng 
932f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
9337a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
934bb803951SChris Mason 		/* once for the root ptr */
9353083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
936f0486c68SYan, Zheng 		return 0;
937bb803951SChris Mason 	}
9385f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
9390b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
940bb803951SChris Mason 		return 0;
941bb803951SChris Mason 
9424b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
943fb770ae4SLiu Bo 	if (IS_ERR(left))
944fb770ae4SLiu Bo 		left = NULL;
945fb770ae4SLiu Bo 
9465f39d397SChris Mason 	if (left) {
947bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
9485f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
9499631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
950bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
95154aa1f4dSChris Mason 		if (wret) {
95254aa1f4dSChris Mason 			ret = wret;
95354aa1f4dSChris Mason 			goto enospc;
95454aa1f4dSChris Mason 		}
9552cc58cf2SChris Mason 	}
956fb770ae4SLiu Bo 
9574b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
958fb770ae4SLiu Bo 	if (IS_ERR(right))
959fb770ae4SLiu Bo 		right = NULL;
960fb770ae4SLiu Bo 
9615f39d397SChris Mason 	if (right) {
962bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
9635f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
9649631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
965bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
9662cc58cf2SChris Mason 		if (wret) {
9672cc58cf2SChris Mason 			ret = wret;
9682cc58cf2SChris Mason 			goto enospc;
9692cc58cf2SChris Mason 		}
9702cc58cf2SChris Mason 	}
9712cc58cf2SChris Mason 
9722cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
9735f39d397SChris Mason 	if (left) {
9745f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
975d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
97679f95c82SChris Mason 		if (wret < 0)
97779f95c82SChris Mason 			ret = wret;
978bb803951SChris Mason 	}
97979f95c82SChris Mason 
98079f95c82SChris Mason 	/*
98179f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
98279f95c82SChris Mason 	 */
9835f39d397SChris Mason 	if (right) {
984d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
98554aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
98679f95c82SChris Mason 			ret = wret;
9875f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
9886a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
989925baeddSChris Mason 			btrfs_tree_unlock(right);
990afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
991f0486c68SYan, Zheng 			root_sub_used(root, right->len);
9927a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
9937a163608SFilipe Manana 					      0, 1);
9943083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
995f0486c68SYan, Zheng 			right = NULL;
996bb803951SChris Mason 		} else {
9975f39d397SChris Mason 			struct btrfs_disk_key right_key;
9985f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
999f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1000f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
10010e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
10025f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
10035f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1004bb803951SChris Mason 		}
1005bb803951SChris Mason 	}
10065f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
100779f95c82SChris Mason 		/*
100879f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
100979f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
101079f95c82SChris Mason 		 * could try to delete the only pointer in this node.
101179f95c82SChris Mason 		 * So, pull some keys from the left.
101279f95c82SChris Mason 		 * There has to be a left pointer at this point because
101379f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
101479f95c82SChris Mason 		 * right
101579f95c82SChris Mason 		 */
1016305a26afSMark Fasheh 		if (!left) {
1017305a26afSMark Fasheh 			ret = -EROFS;
10180b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1019305a26afSMark Fasheh 			goto enospc;
1020305a26afSMark Fasheh 		}
102155d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
102254aa1f4dSChris Mason 		if (wret < 0) {
102379f95c82SChris Mason 			ret = wret;
102454aa1f4dSChris Mason 			goto enospc;
102554aa1f4dSChris Mason 		}
1026bce4eae9SChris Mason 		if (wret == 1) {
1027d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1028bce4eae9SChris Mason 			if (wret < 0)
1029bce4eae9SChris Mason 				ret = wret;
1030bce4eae9SChris Mason 		}
103179f95c82SChris Mason 		BUG_ON(wret == 1);
103279f95c82SChris Mason 	}
10335f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
10346a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1035925baeddSChris Mason 		btrfs_tree_unlock(mid);
1036afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1037f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10387a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
10393083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1040f0486c68SYan, Zheng 		mid = NULL;
104179f95c82SChris Mason 	} else {
104279f95c82SChris Mason 		/* update the parent key to reflect our changes */
10435f39d397SChris Mason 		struct btrfs_disk_key mid_key;
10445f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1045f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1046f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
10470e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
10485f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
10495f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
105079f95c82SChris Mason 	}
1051bb803951SChris Mason 
105279f95c82SChris Mason 	/* update the path */
10535f39d397SChris Mason 	if (left) {
10545f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
105567439dadSDavid Sterba 			atomic_inc(&left->refs);
1056925baeddSChris Mason 			/* left was locked after cow */
10575f39d397SChris Mason 			path->nodes[level] = left;
1058bb803951SChris Mason 			path->slots[level + 1] -= 1;
1059bb803951SChris Mason 			path->slots[level] = orig_slot;
1060925baeddSChris Mason 			if (mid) {
1061925baeddSChris Mason 				btrfs_tree_unlock(mid);
10625f39d397SChris Mason 				free_extent_buffer(mid);
1063925baeddSChris Mason 			}
1064bb803951SChris Mason 		} else {
10655f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1066bb803951SChris Mason 			path->slots[level] = orig_slot;
1067bb803951SChris Mason 		}
1068bb803951SChris Mason 	}
106979f95c82SChris Mason 	/* double check we haven't messed things up */
1070e20d96d6SChris Mason 	if (orig_ptr !=
10715f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
107279f95c82SChris Mason 		BUG();
107354aa1f4dSChris Mason enospc:
1074925baeddSChris Mason 	if (right) {
1075925baeddSChris Mason 		btrfs_tree_unlock(right);
10765f39d397SChris Mason 		free_extent_buffer(right);
1077925baeddSChris Mason 	}
1078925baeddSChris Mason 	if (left) {
1079925baeddSChris Mason 		if (path->nodes[level] != left)
1080925baeddSChris Mason 			btrfs_tree_unlock(left);
10815f39d397SChris Mason 		free_extent_buffer(left);
1082925baeddSChris Mason 	}
1083bb803951SChris Mason 	return ret;
1084bb803951SChris Mason }
1085bb803951SChris Mason 
1086d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1087d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1088d352ac68SChris Mason  * have to be pessimistic.
1089d352ac68SChris Mason  */
1090d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1091e66f709bSChris Mason 					  struct btrfs_root *root,
1092e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1093e66f709bSChris Mason {
10940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10955f39d397SChris Mason 	struct extent_buffer *right = NULL;
10965f39d397SChris Mason 	struct extent_buffer *mid;
10975f39d397SChris Mason 	struct extent_buffer *left = NULL;
10985f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1099e66f709bSChris Mason 	int ret = 0;
1100e66f709bSChris Mason 	int wret;
1101e66f709bSChris Mason 	int pslot;
1102e66f709bSChris Mason 	int orig_slot = path->slots[level];
1103e66f709bSChris Mason 
1104e66f709bSChris Mason 	if (level == 0)
1105e66f709bSChris Mason 		return 1;
1106e66f709bSChris Mason 
11075f39d397SChris Mason 	mid = path->nodes[level];
11087bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1109e66f709bSChris Mason 
1110a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
11115f39d397SChris Mason 		parent = path->nodes[level + 1];
1112e66f709bSChris Mason 		pslot = path->slots[level + 1];
1113a05a9bb1SLi Zefan 	}
1114e66f709bSChris Mason 
11155f39d397SChris Mason 	if (!parent)
1116e66f709bSChris Mason 		return 1;
1117e66f709bSChris Mason 
11184b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1119fb770ae4SLiu Bo 	if (IS_ERR(left))
1120fb770ae4SLiu Bo 		left = NULL;
1121e66f709bSChris Mason 
1122e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
11235f39d397SChris Mason 	if (left) {
1124e66f709bSChris Mason 		u32 left_nr;
1125925baeddSChris Mason 
1126bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1127b4ce94deSChris Mason 
11285f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
11290b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
113033ade1f8SChris Mason 			wret = 1;
113133ade1f8SChris Mason 		} else {
11325f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
11339631e4ccSJosef Bacik 					      pslot - 1, &left,
1134bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
113554aa1f4dSChris Mason 			if (ret)
113654aa1f4dSChris Mason 				wret = 1;
113754aa1f4dSChris Mason 			else {
1138d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
113954aa1f4dSChris Mason 			}
114033ade1f8SChris Mason 		}
1141e66f709bSChris Mason 		if (wret < 0)
1142e66f709bSChris Mason 			ret = wret;
1143e66f709bSChris Mason 		if (wret == 0) {
11445f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1145e66f709bSChris Mason 			orig_slot += left_nr;
11465f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1147f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1148f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
11490e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11505f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
11515f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
11525f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
11535f39d397SChris Mason 				path->nodes[level] = left;
1154e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1155e66f709bSChris Mason 				path->slots[level] = orig_slot;
1156925baeddSChris Mason 				btrfs_tree_unlock(mid);
11575f39d397SChris Mason 				free_extent_buffer(mid);
1158e66f709bSChris Mason 			} else {
1159e66f709bSChris Mason 				orig_slot -=
11605f39d397SChris Mason 					btrfs_header_nritems(left);
1161e66f709bSChris Mason 				path->slots[level] = orig_slot;
1162925baeddSChris Mason 				btrfs_tree_unlock(left);
11635f39d397SChris Mason 				free_extent_buffer(left);
1164e66f709bSChris Mason 			}
1165e66f709bSChris Mason 			return 0;
1166e66f709bSChris Mason 		}
1167925baeddSChris Mason 		btrfs_tree_unlock(left);
11685f39d397SChris Mason 		free_extent_buffer(left);
1169e66f709bSChris Mason 	}
11704b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1171fb770ae4SLiu Bo 	if (IS_ERR(right))
1172fb770ae4SLiu Bo 		right = NULL;
1173e66f709bSChris Mason 
1174e66f709bSChris Mason 	/*
1175e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1176e66f709bSChris Mason 	 */
11775f39d397SChris Mason 	if (right) {
117833ade1f8SChris Mason 		u32 right_nr;
1179b4ce94deSChris Mason 
1180bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1181b4ce94deSChris Mason 
11825f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
11830b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
118433ade1f8SChris Mason 			wret = 1;
118533ade1f8SChris Mason 		} else {
11865f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
11875f39d397SChris Mason 					      parent, pslot + 1,
1188bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
118954aa1f4dSChris Mason 			if (ret)
119054aa1f4dSChris Mason 				wret = 1;
119154aa1f4dSChris Mason 			else {
119255d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
119333ade1f8SChris Mason 			}
119454aa1f4dSChris Mason 		}
1195e66f709bSChris Mason 		if (wret < 0)
1196e66f709bSChris Mason 			ret = wret;
1197e66f709bSChris Mason 		if (wret == 0) {
11985f39d397SChris Mason 			struct btrfs_disk_key disk_key;
11995f39d397SChris Mason 
12005f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1201f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1202f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
12030e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
12045f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
12055f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12065f39d397SChris Mason 
12075f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
12085f39d397SChris Mason 				path->nodes[level] = right;
1209e66f709bSChris Mason 				path->slots[level + 1] += 1;
1210e66f709bSChris Mason 				path->slots[level] = orig_slot -
12115f39d397SChris Mason 					btrfs_header_nritems(mid);
1212925baeddSChris Mason 				btrfs_tree_unlock(mid);
12135f39d397SChris Mason 				free_extent_buffer(mid);
1214e66f709bSChris Mason 			} else {
1215925baeddSChris Mason 				btrfs_tree_unlock(right);
12165f39d397SChris Mason 				free_extent_buffer(right);
1217e66f709bSChris Mason 			}
1218e66f709bSChris Mason 			return 0;
1219e66f709bSChris Mason 		}
1220925baeddSChris Mason 		btrfs_tree_unlock(right);
12215f39d397SChris Mason 		free_extent_buffer(right);
1222e66f709bSChris Mason 	}
1223e66f709bSChris Mason 	return 1;
1224e66f709bSChris Mason }
1225e66f709bSChris Mason 
122674123bd7SChris Mason /*
1227d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1228d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
12293c69faecSChris Mason  */
12302ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1231e02119d5SChris Mason 			     struct btrfs_path *path,
123201f46658SChris Mason 			     int level, int slot, u64 objectid)
12333c69faecSChris Mason {
12345f39d397SChris Mason 	struct extent_buffer *node;
123501f46658SChris Mason 	struct btrfs_disk_key disk_key;
12363c69faecSChris Mason 	u32 nritems;
12373c69faecSChris Mason 	u64 search;
1238a7175319SChris Mason 	u64 target;
12396b80053dSChris Mason 	u64 nread = 0;
1240ace75066SFilipe Manana 	u64 nread_max;
12416b80053dSChris Mason 	u32 nr;
12426b80053dSChris Mason 	u32 blocksize;
12436b80053dSChris Mason 	u32 nscan = 0;
1244db94535dSChris Mason 
1245ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
12463c69faecSChris Mason 		return;
12473c69faecSChris Mason 
12486702ed49SChris Mason 	if (!path->nodes[level])
12496702ed49SChris Mason 		return;
12506702ed49SChris Mason 
12515f39d397SChris Mason 	node = path->nodes[level];
1252925baeddSChris Mason 
1253ace75066SFilipe Manana 	/*
1254ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1255ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1256ace75066SFilipe Manana 	 * much IO at once (possibly random).
1257ace75066SFilipe Manana 	 */
1258ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1259ace75066SFilipe Manana 		if (level > 1)
1260ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1261ace75066SFilipe Manana 		else
1262ace75066SFilipe Manana 			nread_max = SZ_128K;
1263ace75066SFilipe Manana 	} else {
1264ace75066SFilipe Manana 		nread_max = SZ_64K;
1265ace75066SFilipe Manana 	}
1266ace75066SFilipe Manana 
12673c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
12680b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1269069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1270069a2e37SFilipe Manana 		struct extent_buffer *eb;
1271069a2e37SFilipe Manana 
12720b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
12735f39d397SChris Mason 		if (eb) {
12745f39d397SChris Mason 			free_extent_buffer(eb);
12753c69faecSChris Mason 			return;
12763c69faecSChris Mason 		}
1277069a2e37SFilipe Manana 	}
12783c69faecSChris Mason 
1279a7175319SChris Mason 	target = search;
12806b80053dSChris Mason 
12815f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
12826b80053dSChris Mason 	nr = slot;
128325b8b936SJosef Bacik 
12843c69faecSChris Mason 	while (1) {
1285e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
12866b80053dSChris Mason 			if (nr == 0)
12873c69faecSChris Mason 				break;
12886b80053dSChris Mason 			nr--;
1289ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1290ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
12916b80053dSChris Mason 			nr++;
12926b80053dSChris Mason 			if (nr >= nritems)
12936b80053dSChris Mason 				break;
12943c69faecSChris Mason 		}
1295e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
129601f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
129701f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
129801f46658SChris Mason 				break;
129901f46658SChris Mason 		}
13006b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1301ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1302ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1303a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1304bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
13056b80053dSChris Mason 			nread += blocksize;
13063c69faecSChris Mason 		}
13076b80053dSChris Mason 		nscan++;
1308ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
13096b80053dSChris Mason 			break;
13103c69faecSChris Mason 	}
13113c69faecSChris Mason }
1312925baeddSChris Mason 
1313bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1314b4ce94deSChris Mason {
1315bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1316b4ce94deSChris Mason 	int slot;
1317b4ce94deSChris Mason 	int nritems;
1318b4ce94deSChris Mason 
13198c594ea8SChris Mason 	parent = path->nodes[level + 1];
1320b4ce94deSChris Mason 	if (!parent)
13210b08851fSJosef Bacik 		return;
1322b4ce94deSChris Mason 
1323b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
13248c594ea8SChris Mason 	slot = path->slots[level + 1];
1325b4ce94deSChris Mason 
1326bfb484d9SJosef Bacik 	if (slot > 0)
1327bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1328bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1329bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1330b4ce94deSChris Mason }
1331b4ce94deSChris Mason 
1332b4ce94deSChris Mason 
1333b4ce94deSChris Mason /*
1334d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1335d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1336d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1337d397712bSChris Mason  * tree.
1338d352ac68SChris Mason  *
1339d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1340d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1341d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1342d352ac68SChris Mason  *
1343d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1344d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1345d352ac68SChris Mason  */
1346e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1347f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1348f7c79f30SChris Mason 			       int *write_lock_level)
1349925baeddSChris Mason {
1350925baeddSChris Mason 	int i;
1351925baeddSChris Mason 	int skip_level = level;
1352c1227996SNikolay Borisov 	bool check_skip = true;
1353925baeddSChris Mason 
1354925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1355925baeddSChris Mason 		if (!path->nodes[i])
1356925baeddSChris Mason 			break;
1357925baeddSChris Mason 		if (!path->locks[i])
1358925baeddSChris Mason 			break;
1359c1227996SNikolay Borisov 
1360c1227996SNikolay Borisov 		if (check_skip) {
1361c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1362925baeddSChris Mason 				skip_level = i + 1;
1363925baeddSChris Mason 				continue;
1364925baeddSChris Mason 			}
1365c1227996SNikolay Borisov 
1366c1227996SNikolay Borisov 			if (path->keep_locks) {
1367925baeddSChris Mason 				u32 nritems;
1368c1227996SNikolay Borisov 
1369c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1370051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1371925baeddSChris Mason 					skip_level = i + 1;
1372925baeddSChris Mason 					continue;
1373925baeddSChris Mason 				}
1374925baeddSChris Mason 			}
1375c1227996SNikolay Borisov 		}
1376051e1b9fSChris Mason 
1377d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1378c1227996SNikolay Borisov 			check_skip = false;
1379c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1380925baeddSChris Mason 			path->locks[i] = 0;
1381f7c79f30SChris Mason 			if (write_lock_level &&
1382f7c79f30SChris Mason 			    i > min_write_lock_level &&
1383f7c79f30SChris Mason 			    i <= *write_lock_level) {
1384f7c79f30SChris Mason 				*write_lock_level = i - 1;
1385f7c79f30SChris Mason 			}
1386925baeddSChris Mason 		}
1387925baeddSChris Mason 	}
1388925baeddSChris Mason }
1389925baeddSChris Mason 
13903c69faecSChris Mason /*
1391c8c42864SChris Mason  * helper function for btrfs_search_slot.  The goal is to find a block
1392c8c42864SChris Mason  * in cache without setting the path to blocking.  If we find the block
1393c8c42864SChris Mason  * we return zero and the path is unchanged.
1394c8c42864SChris Mason  *
1395c8c42864SChris Mason  * If we can't find the block, we set the path blocking and do some
1396c8c42864SChris Mason  * reada.  -EAGAIN is returned and the search must be repeated.
1397c8c42864SChris Mason  */
1398c8c42864SChris Mason static int
1399d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1400c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1401cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1402c8c42864SChris Mason {
14030b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1404c8c42864SChris Mason 	u64 blocknr;
1405c8c42864SChris Mason 	u64 gen;
1406c8c42864SChris Mason 	struct extent_buffer *tmp;
1407581c1760SQu Wenruo 	struct btrfs_key first_key;
140876a05b35SChris Mason 	int ret;
1409581c1760SQu Wenruo 	int parent_level;
1410c8c42864SChris Mason 
1411213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1412213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1413213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1414213ff4b7SNikolay Borisov 	btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
1415c8c42864SChris Mason 
14160b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1417cb44921aSChris Mason 	if (tmp) {
1418ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1419ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1420ace75066SFilipe Manana 
1421b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1422b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1423448de471SQu Wenruo 			/*
1424448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1425448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1426448de471SQu Wenruo 			 * parents (shared tree blocks).
1427448de471SQu Wenruo 			 */
1428e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1429448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
1430448de471SQu Wenruo 				free_extent_buffer(tmp);
1431448de471SQu Wenruo 				return -EUCLEAN;
1432448de471SQu Wenruo 			}
1433c8c42864SChris Mason 			*eb_ret = tmp;
1434c8c42864SChris Mason 			return 0;
1435c8c42864SChris Mason 		}
1436bdf7c00eSJosef Bacik 
1437b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
1438581c1760SQu Wenruo 		ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
1439bdf7c00eSJosef Bacik 		if (!ret) {
1440cb44921aSChris Mason 			*eb_ret = tmp;
1441cb44921aSChris Mason 			return 0;
1442cb44921aSChris Mason 		}
1443cb44921aSChris Mason 		free_extent_buffer(tmp);
1444b3b4aa74SDavid Sterba 		btrfs_release_path(p);
1445cb44921aSChris Mason 		return -EIO;
1446cb44921aSChris Mason 	}
1447c8c42864SChris Mason 
1448c8c42864SChris Mason 	/*
1449c8c42864SChris Mason 	 * reduce lock contention at high levels
1450c8c42864SChris Mason 	 * of the btree by dropping locks before
145176a05b35SChris Mason 	 * we read.  Don't release the lock on the current
145276a05b35SChris Mason 	 * level because we need to walk this node to figure
145376a05b35SChris Mason 	 * out which blocks to read.
1454c8c42864SChris Mason 	 */
14558c594ea8SChris Mason 	btrfs_unlock_up_safe(p, level + 1);
14568c594ea8SChris Mason 
1457e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
14582ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1459c8c42864SChris Mason 
146076a05b35SChris Mason 	ret = -EAGAIN;
14611b7ec85eSJosef Bacik 	tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
14621b7ec85eSJosef Bacik 			      gen, parent_level - 1, &first_key);
146364c043deSLiu Bo 	if (!IS_ERR(tmp)) {
146476a05b35SChris Mason 		/*
146576a05b35SChris Mason 		 * If the read above didn't mark this buffer up to date,
146676a05b35SChris Mason 		 * it will never end up being up to date.  Set ret to EIO now
146776a05b35SChris Mason 		 * and give up so that our caller doesn't loop forever
146876a05b35SChris Mason 		 * on our EAGAINs.
146976a05b35SChris Mason 		 */
1470e6a1d6fdSLiu Bo 		if (!extent_buffer_uptodate(tmp))
147176a05b35SChris Mason 			ret = -EIO;
1472c8c42864SChris Mason 		free_extent_buffer(tmp);
1473c871b0f2SLiu Bo 	} else {
1474c871b0f2SLiu Bo 		ret = PTR_ERR(tmp);
147576a05b35SChris Mason 	}
147602a3307aSLiu Bo 
147702a3307aSLiu Bo 	btrfs_release_path(p);
147876a05b35SChris Mason 	return ret;
1479c8c42864SChris Mason }
1480c8c42864SChris Mason 
1481c8c42864SChris Mason /*
1482c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1483c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1484c8c42864SChris Mason  * the ins_len.
1485c8c42864SChris Mason  *
1486c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1487c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1488c8c42864SChris Mason  * start over
1489c8c42864SChris Mason  */
1490c8c42864SChris Mason static int
1491c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1492c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1493bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1494bd681513SChris Mason 		       int *write_lock_level)
1495c8c42864SChris Mason {
14960b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
149795b982deSNikolay Borisov 	int ret = 0;
14980b246afaSJeff Mahoney 
1499c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
15000b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1501c8c42864SChris Mason 
1502bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1503bd681513SChris Mason 			*write_lock_level = level + 1;
1504bd681513SChris Mason 			btrfs_release_path(p);
150595b982deSNikolay Borisov 			return -EAGAIN;
1506bd681513SChris Mason 		}
1507bd681513SChris Mason 
1508bfb484d9SJosef Bacik 		reada_for_balance(p, level);
150995b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1510c8c42864SChris Mason 
1511c8c42864SChris Mason 		b = p->nodes[level];
1512c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
15130b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1514c8c42864SChris Mason 
1515bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1516bd681513SChris Mason 			*write_lock_level = level + 1;
1517bd681513SChris Mason 			btrfs_release_path(p);
151895b982deSNikolay Borisov 			return -EAGAIN;
1519bd681513SChris Mason 		}
1520bd681513SChris Mason 
1521bfb484d9SJosef Bacik 		reada_for_balance(p, level);
152295b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
152395b982deSNikolay Borisov 		if (ret)
152495b982deSNikolay Borisov 			return ret;
1525c8c42864SChris Mason 
1526c8c42864SChris Mason 		b = p->nodes[level];
1527c8c42864SChris Mason 		if (!b) {
1528b3b4aa74SDavid Sterba 			btrfs_release_path(p);
152995b982deSNikolay Borisov 			return -EAGAIN;
1530c8c42864SChris Mason 		}
1531c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1532c8c42864SChris Mason 	}
1533c8c42864SChris Mason 	return ret;
1534c8c42864SChris Mason }
1535c8c42864SChris Mason 
1536381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1537e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1538e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1539e33d5c3dSKelley Nielsen {
1540e33d5c3dSKelley Nielsen 	int ret;
1541e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1542e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1543381cf658SDavid Sterba 
1544381cf658SDavid Sterba 	ASSERT(path);
15451d4c08e0SDavid Sterba 	ASSERT(found_key);
1546e33d5c3dSKelley Nielsen 
1547e33d5c3dSKelley Nielsen 	key.type = key_type;
1548e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1549e33d5c3dSKelley Nielsen 	key.offset = ioff;
1550e33d5c3dSKelley Nielsen 
1551e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
15521d4c08e0SDavid Sterba 	if (ret < 0)
1553e33d5c3dSKelley Nielsen 		return ret;
1554e33d5c3dSKelley Nielsen 
1555e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1556e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1557e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1558e33d5c3dSKelley Nielsen 		if (ret)
1559e33d5c3dSKelley Nielsen 			return ret;
1560e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1561e33d5c3dSKelley Nielsen 	}
1562e33d5c3dSKelley Nielsen 
1563e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1564e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1565e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1566e33d5c3dSKelley Nielsen 		return 1;
1567e33d5c3dSKelley Nielsen 
1568e33d5c3dSKelley Nielsen 	return 0;
1569e33d5c3dSKelley Nielsen }
1570e33d5c3dSKelley Nielsen 
15711fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
15721fc28d8eSLiu Bo 							struct btrfs_path *p,
15731fc28d8eSLiu Bo 							int write_lock_level)
15741fc28d8eSLiu Bo {
15751fc28d8eSLiu Bo 	struct extent_buffer *b;
1576120de408SJosef Bacik 	int root_lock = 0;
15771fc28d8eSLiu Bo 	int level = 0;
15781fc28d8eSLiu Bo 
15791fc28d8eSLiu Bo 	if (p->search_commit_root) {
15801fc28d8eSLiu Bo 		b = root->commit_root;
158167439dadSDavid Sterba 		atomic_inc(&b->refs);
15821fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1583f9ddfd05SLiu Bo 		/*
1584f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1585f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1586f9ddfd05SLiu Bo 		 */
1587f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
15881fc28d8eSLiu Bo 
15891fc28d8eSLiu Bo 		goto out;
15901fc28d8eSLiu Bo 	}
15911fc28d8eSLiu Bo 
15921fc28d8eSLiu Bo 	if (p->skip_locking) {
15931fc28d8eSLiu Bo 		b = btrfs_root_node(root);
15941fc28d8eSLiu Bo 		level = btrfs_header_level(b);
15951fc28d8eSLiu Bo 		goto out;
15961fc28d8eSLiu Bo 	}
15971fc28d8eSLiu Bo 
1598120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1599120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1600120de408SJosef Bacik 
16011fc28d8eSLiu Bo 	/*
1602662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1603662c653bSLiu Bo 	 * lock.
1604662c653bSLiu Bo 	 */
1605662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1606662c653bSLiu Bo 		/*
1607662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1608662c653bSLiu Bo 		 * have it read locked
16091fc28d8eSLiu Bo 		 */
16101bb96598SJosef Bacik 		b = btrfs_read_lock_root_node(root);
16111fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16121fc28d8eSLiu Bo 		if (level > write_lock_level)
16131fc28d8eSLiu Bo 			goto out;
16141fc28d8eSLiu Bo 
1615662c653bSLiu Bo 		/* Whoops, must trade for write lock */
16161fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
16171fc28d8eSLiu Bo 		free_extent_buffer(b);
1618662c653bSLiu Bo 	}
1619662c653bSLiu Bo 
16201fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
16211fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
16221fc28d8eSLiu Bo 
16231fc28d8eSLiu Bo 	/* The level might have changed, check again */
16241fc28d8eSLiu Bo 	level = btrfs_header_level(b);
16251fc28d8eSLiu Bo 
16261fc28d8eSLiu Bo out:
1627120de408SJosef Bacik 	/*
1628120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1629120de408SJosef Bacik 	 * longer valid, return an error in this case.
1630120de408SJosef Bacik 	 */
1631120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1632120de408SJosef Bacik 		if (root_lock)
1633120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1634120de408SJosef Bacik 		free_extent_buffer(b);
1635120de408SJosef Bacik 		return ERR_PTR(-EIO);
1636120de408SJosef Bacik 	}
1637120de408SJosef Bacik 
16381fc28d8eSLiu Bo 	p->nodes[level] = b;
16391fc28d8eSLiu Bo 	if (!p->skip_locking)
16401fc28d8eSLiu Bo 		p->locks[level] = root_lock;
16411fc28d8eSLiu Bo 	/*
16421fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
16431fc28d8eSLiu Bo 	 */
16441fc28d8eSLiu Bo 	return b;
16451fc28d8eSLiu Bo }
16461fc28d8eSLiu Bo 
1647d96b3424SFilipe Manana /*
1648d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1649d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1650d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1651d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1652d96b3424SFilipe Manana  * reallocated in the next transaction.
1653d96b3424SFilipe Manana  *
1654d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1655d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1656d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1657d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1658d96b3424SFilipe Manana  */
1659d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1660d96b3424SFilipe Manana {
1661d96b3424SFilipe Manana 	const int i = path->lowest_level;
1662d96b3424SFilipe Manana 	const int slot = path->slots[i];
1663d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1664d96b3424SFilipe Manana 	struct extent_buffer *clone;
1665d96b3424SFilipe Manana 
1666d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1667d96b3424SFilipe Manana 
1668d96b3424SFilipe Manana 	if (!lowest)
1669d96b3424SFilipe Manana 		return 0;
1670d96b3424SFilipe Manana 
1671d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1672d96b3424SFilipe Manana 
1673d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1674d96b3424SFilipe Manana 	if (!clone)
1675d96b3424SFilipe Manana 		return -ENOMEM;
1676d96b3424SFilipe Manana 
1677d96b3424SFilipe Manana 	btrfs_release_path(path);
1678d96b3424SFilipe Manana 	path->nodes[i] = clone;
1679d96b3424SFilipe Manana 	path->slots[i] = slot;
1680d96b3424SFilipe Manana 
1681d96b3424SFilipe Manana 	return 0;
1682d96b3424SFilipe Manana }
16831fc28d8eSLiu Bo 
1684e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1685e2e58d0fSFilipe Manana 				      int search_low_slot,
1686e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1687e2e58d0fSFilipe Manana 				      int prev_cmp,
1688e2e58d0fSFilipe Manana 				      int *slot)
1689e2e58d0fSFilipe Manana {
1690e2e58d0fSFilipe Manana 	/*
1691e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1692e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1693e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1694e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1695e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1696e2e58d0fSFilipe Manana 	 */
1697e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1698e2e58d0fSFilipe Manana 		*slot = 0;
1699e2e58d0fSFilipe Manana 		return 0;
1700e2e58d0fSFilipe Manana 	}
1701e2e58d0fSFilipe Manana 
1702e2e58d0fSFilipe Manana 	return generic_bin_search(eb, search_low_slot, key, slot);
1703e2e58d0fSFilipe Manana }
1704e2e58d0fSFilipe Manana 
1705109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1706109324cfSFilipe Manana 		       struct btrfs_root *root,
1707109324cfSFilipe Manana 		       const struct btrfs_key *key,
1708109324cfSFilipe Manana 		       struct btrfs_path *path,
1709109324cfSFilipe Manana 		       int ins_len,
1710109324cfSFilipe Manana 		       int prev_cmp)
1711109324cfSFilipe Manana {
1712109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
1713109324cfSFilipe Manana 	int leaf_free_space = -1;
1714109324cfSFilipe Manana 	int search_low_slot = 0;
1715109324cfSFilipe Manana 	int ret;
1716109324cfSFilipe Manana 	bool do_bin_search = true;
1717109324cfSFilipe Manana 
1718109324cfSFilipe Manana 	/*
1719109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
1720109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
1721109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
1722109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1723109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
1724109324cfSFilipe Manana 	 */
1725109324cfSFilipe Manana 	if (ins_len > 0) {
1726109324cfSFilipe Manana 		/*
1727109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
1728109324cfSFilipe Manana 		 * will not change until then.
1729109324cfSFilipe Manana 		 */
1730109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
1731109324cfSFilipe Manana 
1732109324cfSFilipe Manana 		/*
1733109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
1734109324cfSFilipe Manana 		 * the root of the tree.
1735109324cfSFilipe Manana 		 */
1736109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
1737109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
1738109324cfSFilipe Manana 
1739109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
1740109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
1741109324cfSFilipe Manana 
1742109324cfSFilipe Manana 			/*
1743109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
1744109324cfSFilipe Manana 			 * taking into account that the first key is very likely
1745109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
1746109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
1747109324cfSFilipe Manana 			 * the header's level field.
1748109324cfSFilipe Manana 			 */
1749109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
1750109324cfSFilipe Manana 			if (ret < 0) {
1751109324cfSFilipe Manana 				/*
1752109324cfSFilipe Manana 				 * The first key is smaller than the key we want
1753109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
1754109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
1755109324cfSFilipe Manana 				 *
1756109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
1757109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
1758109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
1759109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
1760109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
1761109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
1762109324cfSFilipe Manana 				 */
1763109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
1764109324cfSFilipe Manana 				search_low_slot = 1;
1765109324cfSFilipe Manana 			} else {
1766109324cfSFilipe Manana 				/*
1767109324cfSFilipe Manana 				 * The first key is >= then the key we want to
1768109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
1769109324cfSFilipe Manana 				 * the target key will be at slot 0.
1770109324cfSFilipe Manana 				 *
1771109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
1772109324cfSFilipe Manana 				 * less than the first key, because we will need
1773109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
1774109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
1775109324cfSFilipe Manana 				 * If the key matches the first key, then we can
1776109324cfSFilipe Manana 				 * unlock all the upper nodes, using
1777109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
1778109324cfSFilipe Manana 				 * as stated above.
1779109324cfSFilipe Manana 				 */
1780109324cfSFilipe Manana 				if (ret == 0)
1781109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
1782109324cfSFilipe Manana 				/*
1783109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
1784109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
1785109324cfSFilipe Manana 				 * to adjust it.
1786109324cfSFilipe Manana 				 */
1787109324cfSFilipe Manana 				do_bin_search = false;
1788109324cfSFilipe Manana 				path->slots[0] = 0;
1789109324cfSFilipe Manana 			}
1790109324cfSFilipe Manana 		}
1791109324cfSFilipe Manana 	}
1792109324cfSFilipe Manana 
1793109324cfSFilipe Manana 	if (do_bin_search) {
1794109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
1795109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
1796109324cfSFilipe Manana 		if (ret < 0)
1797109324cfSFilipe Manana 			return ret;
1798109324cfSFilipe Manana 	}
1799109324cfSFilipe Manana 
1800109324cfSFilipe Manana 	if (ins_len > 0) {
1801109324cfSFilipe Manana 		/*
1802109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
1803109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
1804109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
1805109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
1806109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
1807109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
1808109324cfSFilipe Manana 		 * check will be correct.
1809109324cfSFilipe Manana 		 */
1810109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
1811109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
1812109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
1813109324cfSFilipe Manana 		}
1814109324cfSFilipe Manana 
1815109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
1816109324cfSFilipe Manana 
1817109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
1818109324cfSFilipe Manana 			int err;
1819109324cfSFilipe Manana 
1820109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
1821109324cfSFilipe Manana 					 (ret == 0));
1822bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
1823bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
1824bb8e9a60SFilipe Manana 				err = -EUCLEAN;
1825109324cfSFilipe Manana 			if (err)
1826109324cfSFilipe Manana 				ret = err;
1827109324cfSFilipe Manana 		}
1828109324cfSFilipe Manana 	}
1829109324cfSFilipe Manana 
1830109324cfSFilipe Manana 	return ret;
1831109324cfSFilipe Manana }
1832109324cfSFilipe Manana 
1833c8c42864SChris Mason /*
18344271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
18354271eceaSNikolay Borisov  * modifications to preserve tree invariants.
183674123bd7SChris Mason  *
18374271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
18384271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
18394271eceaSNikolay Borisov  * @root:	The root node of the tree
18404271eceaSNikolay Borisov  * @key:	The key we are looking for
18419a664971Sethanwu  * @ins_len:	Indicates purpose of search:
18429a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
18439a664971Sethanwu  *              <0  for deletions
18449a664971Sethanwu  *               0  for plain searches, not modifying the tree
18459a664971Sethanwu  *
18469a664971Sethanwu  *              (*) If size of item inserted doesn't include
18479a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
18489a664971Sethanwu  *              be set.
18494271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
18504271eceaSNikolay Borisov  *		when modifying the tree.
185197571fd0SChris Mason  *
18524271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
18534271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
18544271eceaSNikolay Borisov  *
18554271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
18564271eceaSNikolay Borisov  * of the path (level 0)
18574271eceaSNikolay Borisov  *
18584271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
18594271eceaSNikolay Borisov  * points to the slot where it should be inserted
18604271eceaSNikolay Borisov  *
18614271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
18624271eceaSNikolay Borisov  * is returned
186374123bd7SChris Mason  */
1864310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1865310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
1866310712b2SOmar Sandoval 		      int ins_len, int cow)
1867be0e5c09SChris Mason {
1868d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
18695f39d397SChris Mason 	struct extent_buffer *b;
1870be0e5c09SChris Mason 	int slot;
1871be0e5c09SChris Mason 	int ret;
187233c66f43SYan Zheng 	int err;
1873be0e5c09SChris Mason 	int level;
1874925baeddSChris Mason 	int lowest_unlock = 1;
1875bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
1876bd681513SChris Mason 	int write_lock_level = 0;
18779f3a7427SChris Mason 	u8 lowest_level = 0;
1878f7c79f30SChris Mason 	int min_write_lock_level;
1879d7396f07SFilipe David Borba Manana 	int prev_cmp;
18809f3a7427SChris Mason 
18816702ed49SChris Mason 	lowest_level = p->lowest_level;
1882323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
188322b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
1884eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
188525179201SJosef Bacik 
1886bd681513SChris Mason 	if (ins_len < 0) {
1887925baeddSChris Mason 		lowest_unlock = 2;
188865b51a00SChris Mason 
1889bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
1890bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
1891bd681513SChris Mason 		 * for those levels as well
1892bd681513SChris Mason 		 */
1893bd681513SChris Mason 		write_lock_level = 2;
1894bd681513SChris Mason 	} else if (ins_len > 0) {
1895bd681513SChris Mason 		/*
1896bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
1897bd681513SChris Mason 		 * level 1 so we can update keys
1898bd681513SChris Mason 		 */
1899bd681513SChris Mason 		write_lock_level = 1;
1900bd681513SChris Mason 	}
1901bd681513SChris Mason 
1902bd681513SChris Mason 	if (!cow)
1903bd681513SChris Mason 		write_lock_level = -1;
1904bd681513SChris Mason 
190509a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
1906bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
1907bd681513SChris Mason 
1908f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
1909f7c79f30SChris Mason 
1910d96b3424SFilipe Manana 	if (p->need_commit_sem) {
1911d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
1912d96b3424SFilipe Manana 		down_read(&fs_info->commit_root_sem);
1913d96b3424SFilipe Manana 	}
1914d96b3424SFilipe Manana 
1915bb803951SChris Mason again:
1916d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
19171fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
1918be6821f8SFilipe Manana 	if (IS_ERR(b)) {
1919be6821f8SFilipe Manana 		ret = PTR_ERR(b);
1920be6821f8SFilipe Manana 		goto done;
1921be6821f8SFilipe Manana 	}
1922925baeddSChris Mason 
1923eb60ceacSChris Mason 	while (b) {
1924f624d976SQu Wenruo 		int dec = 0;
1925f624d976SQu Wenruo 
19265f39d397SChris Mason 		level = btrfs_header_level(b);
192765b51a00SChris Mason 
192802217ed2SChris Mason 		if (cow) {
19299ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
19309ea2c7c9SNikolay Borisov 
1931c8c42864SChris Mason 			/*
1932c8c42864SChris Mason 			 * if we don't really need to cow this block
1933c8c42864SChris Mason 			 * then we don't want to set the path blocking,
1934c8c42864SChris Mason 			 * so we test it here
1935c8c42864SChris Mason 			 */
19365963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
193765b51a00SChris Mason 				goto cow_done;
19385d4f98a2SYan Zheng 
1939bd681513SChris Mason 			/*
1940bd681513SChris Mason 			 * must have write locks on this node and the
1941bd681513SChris Mason 			 * parent
1942bd681513SChris Mason 			 */
19435124e00eSJosef Bacik 			if (level > write_lock_level ||
19445124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
19455124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
19465124e00eSJosef Bacik 			    p->nodes[level + 1])) {
1947bd681513SChris Mason 				write_lock_level = level + 1;
1948bd681513SChris Mason 				btrfs_release_path(p);
1949bd681513SChris Mason 				goto again;
1950bd681513SChris Mason 			}
1951bd681513SChris Mason 
19529ea2c7c9SNikolay Borisov 			if (last_level)
19539ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
19549631e4ccSJosef Bacik 						      &b,
19559631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
19569ea2c7c9SNikolay Borisov 			else
195733c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
1958e20d96d6SChris Mason 						      p->nodes[level + 1],
19599631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
19609631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
196133c66f43SYan Zheng 			if (err) {
196233c66f43SYan Zheng 				ret = err;
196365b51a00SChris Mason 				goto done;
196454aa1f4dSChris Mason 			}
196502217ed2SChris Mason 		}
196665b51a00SChris Mason cow_done:
1967eb60ceacSChris Mason 		p->nodes[level] = b;
1968b4ce94deSChris Mason 
1969b4ce94deSChris Mason 		/*
1970b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
1971b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
1972b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
1973b4ce94deSChris Mason 		 * go through the expensive btree search on b.
1974b4ce94deSChris Mason 		 *
1975eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
1976eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
1977eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
1978eb653de1SFilipe David Borba Manana 		 * we're operating on.
1979b4ce94deSChris Mason 		 */
1980eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
1981eb653de1SFilipe David Borba Manana 			int u = level + 1;
1982eb653de1SFilipe David Borba Manana 
1983eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
1984eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
1985eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
1986eb653de1SFilipe David Borba Manana 			}
1987eb653de1SFilipe David Borba Manana 		}
1988b4ce94deSChris Mason 
1989e2e58d0fSFilipe Manana 		if (level == 0) {
1990109324cfSFilipe Manana 			if (ins_len > 0)
1991e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
1992bd681513SChris Mason 
1993109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
1994459931ecSChris Mason 			if (!p->search_for_split)
1995f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
19964b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
199765b51a00SChris Mason 			goto done;
199865b51a00SChris Mason 		}
1999e2e58d0fSFilipe Manana 
2000e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2001e2e58d0fSFilipe Manana 		if (ret < 0)
2002e2e58d0fSFilipe Manana 			goto done;
2003e2e58d0fSFilipe Manana 		prev_cmp = ret;
2004e2e58d0fSFilipe Manana 
2005f624d976SQu Wenruo 		if (ret && slot > 0) {
2006f624d976SQu Wenruo 			dec = 1;
2007f624d976SQu Wenruo 			slot--;
2008f624d976SQu Wenruo 		}
2009f624d976SQu Wenruo 		p->slots[level] = slot;
2010f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2011f624d976SQu Wenruo 					     &write_lock_level);
2012f624d976SQu Wenruo 		if (err == -EAGAIN)
2013f624d976SQu Wenruo 			goto again;
2014f624d976SQu Wenruo 		if (err) {
2015f624d976SQu Wenruo 			ret = err;
2016f624d976SQu Wenruo 			goto done;
2017f624d976SQu Wenruo 		}
2018f624d976SQu Wenruo 		b = p->nodes[level];
2019f624d976SQu Wenruo 		slot = p->slots[level];
2020f624d976SQu Wenruo 
2021f624d976SQu Wenruo 		/*
2022f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2023f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2024f624d976SQu Wenruo 		 * the parent
2025f624d976SQu Wenruo 		 */
2026f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2027f624d976SQu Wenruo 			write_lock_level = level + 1;
2028f624d976SQu Wenruo 			btrfs_release_path(p);
2029f624d976SQu Wenruo 			goto again;
2030f624d976SQu Wenruo 		}
2031f624d976SQu Wenruo 
2032f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2033f624d976SQu Wenruo 			  &write_lock_level);
2034f624d976SQu Wenruo 
2035f624d976SQu Wenruo 		if (level == lowest_level) {
2036f624d976SQu Wenruo 			if (dec)
2037f624d976SQu Wenruo 				p->slots[level]++;
2038f624d976SQu Wenruo 			goto done;
2039f624d976SQu Wenruo 		}
2040f624d976SQu Wenruo 
2041f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2042f624d976SQu Wenruo 		if (err == -EAGAIN)
2043f624d976SQu Wenruo 			goto again;
2044f624d976SQu Wenruo 		if (err) {
2045f624d976SQu Wenruo 			ret = err;
2046f624d976SQu Wenruo 			goto done;
2047f624d976SQu Wenruo 		}
2048f624d976SQu Wenruo 
2049f624d976SQu Wenruo 		if (!p->skip_locking) {
2050f624d976SQu Wenruo 			level = btrfs_header_level(b);
2051f624d976SQu Wenruo 			if (level <= write_lock_level) {
2052f624d976SQu Wenruo 				btrfs_tree_lock(b);
2053f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2054f624d976SQu Wenruo 			} else {
2055fe596ca3SJosef Bacik 				btrfs_tree_read_lock(b);
2056f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2057f624d976SQu Wenruo 			}
2058f624d976SQu Wenruo 			p->nodes[level] = b;
2059f624d976SQu Wenruo 		}
206065b51a00SChris Mason 	}
206165b51a00SChris Mason 	ret = 1;
206265b51a00SChris Mason done:
20635f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2064b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2065d96b3424SFilipe Manana 
2066d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2067d96b3424SFilipe Manana 		int ret2;
2068d96b3424SFilipe Manana 
2069d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2070d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2071d96b3424SFilipe Manana 		if (ret2)
2072d96b3424SFilipe Manana 			ret = ret2;
2073d96b3424SFilipe Manana 	}
2074d96b3424SFilipe Manana 
2075be0e5c09SChris Mason 	return ret;
2076be0e5c09SChris Mason }
2077f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2078be0e5c09SChris Mason 
207974123bd7SChris Mason /*
20805d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
20815d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
20825d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
20835d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
20845d9e75c4SJan Schmidt  *
20855d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
20865d9e75c4SJan Schmidt  *
20875d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
20885d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
20895d9e75c4SJan Schmidt  */
2090310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
20915d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
20925d9e75c4SJan Schmidt {
20930b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
20945d9e75c4SJan Schmidt 	struct extent_buffer *b;
20955d9e75c4SJan Schmidt 	int slot;
20965d9e75c4SJan Schmidt 	int ret;
20975d9e75c4SJan Schmidt 	int err;
20985d9e75c4SJan Schmidt 	int level;
20995d9e75c4SJan Schmidt 	int lowest_unlock = 1;
21005d9e75c4SJan Schmidt 	u8 lowest_level = 0;
21015d9e75c4SJan Schmidt 
21025d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
21035d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
21045d9e75c4SJan Schmidt 
21055d9e75c4SJan Schmidt 	if (p->search_commit_root) {
21065d9e75c4SJan Schmidt 		BUG_ON(time_seq);
21075d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
21085d9e75c4SJan Schmidt 	}
21095d9e75c4SJan Schmidt 
21105d9e75c4SJan Schmidt again:
2111f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2112315bed43SNikolay Borisov 	if (!b) {
2113315bed43SNikolay Borisov 		ret = -EIO;
2114315bed43SNikolay Borisov 		goto done;
2115315bed43SNikolay Borisov 	}
21165d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
21175d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
21185d9e75c4SJan Schmidt 
21195d9e75c4SJan Schmidt 	while (b) {
2120abe9339dSQu Wenruo 		int dec = 0;
2121abe9339dSQu Wenruo 
21225d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
21235d9e75c4SJan Schmidt 		p->nodes[level] = b;
21245d9e75c4SJan Schmidt 
21255d9e75c4SJan Schmidt 		/*
21265d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
21275d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
21285d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
21295d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
21305d9e75c4SJan Schmidt 		 */
21315d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
21325d9e75c4SJan Schmidt 
2133995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
2134cbca7d59SFilipe Manana 		if (ret < 0)
2135cbca7d59SFilipe Manana 			goto done;
21365d9e75c4SJan Schmidt 
2137abe9339dSQu Wenruo 		if (level == 0) {
2138abe9339dSQu Wenruo 			p->slots[level] = slot;
2139abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2140abe9339dSQu Wenruo 			goto done;
2141abe9339dSQu Wenruo 		}
2142abe9339dSQu Wenruo 
21435d9e75c4SJan Schmidt 		if (ret && slot > 0) {
21445d9e75c4SJan Schmidt 			dec = 1;
2145abe9339dSQu Wenruo 			slot--;
21465d9e75c4SJan Schmidt 		}
21475d9e75c4SJan Schmidt 		p->slots[level] = slot;
21485d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
21495d9e75c4SJan Schmidt 
21505d9e75c4SJan Schmidt 		if (level == lowest_level) {
21515d9e75c4SJan Schmidt 			if (dec)
21525d9e75c4SJan Schmidt 				p->slots[level]++;
21535d9e75c4SJan Schmidt 			goto done;
21545d9e75c4SJan Schmidt 		}
21555d9e75c4SJan Schmidt 
2156abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
21575d9e75c4SJan Schmidt 		if (err == -EAGAIN)
21585d9e75c4SJan Schmidt 			goto again;
21595d9e75c4SJan Schmidt 		if (err) {
21605d9e75c4SJan Schmidt 			ret = err;
21615d9e75c4SJan Schmidt 			goto done;
21625d9e75c4SJan Schmidt 		}
21635d9e75c4SJan Schmidt 
21645d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
21655d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2166f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2167db7f3436SJosef Bacik 		if (!b) {
2168db7f3436SJosef Bacik 			ret = -ENOMEM;
2169db7f3436SJosef Bacik 			goto done;
2170db7f3436SJosef Bacik 		}
21715d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
21725d9e75c4SJan Schmidt 		p->nodes[level] = b;
21735d9e75c4SJan Schmidt 	}
21745d9e75c4SJan Schmidt 	ret = 1;
21755d9e75c4SJan Schmidt done:
21765d9e75c4SJan Schmidt 	if (ret < 0)
21775d9e75c4SJan Schmidt 		btrfs_release_path(p);
21785d9e75c4SJan Schmidt 
21795d9e75c4SJan Schmidt 	return ret;
21805d9e75c4SJan Schmidt }
21815d9e75c4SJan Schmidt 
21825d9e75c4SJan Schmidt /*
21832f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
21842f38b3e1SArne Jansen  * instead the next or previous item should be returned.
21852f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
21862f38b3e1SArne Jansen  * otherwise.
21872f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
21882f38b3e1SArne Jansen  * return the next lower instead.
21892f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
21902f38b3e1SArne Jansen  * return the next higher instead.
21912f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
21922f38b3e1SArne Jansen  * < 0 on error
21932f38b3e1SArne Jansen  */
21942f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2195310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2196310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2197310712b2SOmar Sandoval 			       int return_any)
21982f38b3e1SArne Jansen {
21992f38b3e1SArne Jansen 	int ret;
22002f38b3e1SArne Jansen 	struct extent_buffer *leaf;
22012f38b3e1SArne Jansen 
22022f38b3e1SArne Jansen again:
22032f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
22042f38b3e1SArne Jansen 	if (ret <= 0)
22052f38b3e1SArne Jansen 		return ret;
22062f38b3e1SArne Jansen 	/*
22072f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
22082f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
22092f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
22102f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
22112f38b3e1SArne Jansen 	 * item.
22122f38b3e1SArne Jansen 	 */
22132f38b3e1SArne Jansen 	leaf = p->nodes[0];
22142f38b3e1SArne Jansen 
22152f38b3e1SArne Jansen 	if (find_higher) {
22162f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
22172f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
22182f38b3e1SArne Jansen 			if (ret <= 0)
22192f38b3e1SArne Jansen 				return ret;
22202f38b3e1SArne Jansen 			if (!return_any)
22212f38b3e1SArne Jansen 				return 1;
22222f38b3e1SArne Jansen 			/*
22232f38b3e1SArne Jansen 			 * no higher item found, return the next
22242f38b3e1SArne Jansen 			 * lower instead
22252f38b3e1SArne Jansen 			 */
22262f38b3e1SArne Jansen 			return_any = 0;
22272f38b3e1SArne Jansen 			find_higher = 0;
22282f38b3e1SArne Jansen 			btrfs_release_path(p);
22292f38b3e1SArne Jansen 			goto again;
22302f38b3e1SArne Jansen 		}
22312f38b3e1SArne Jansen 	} else {
22322f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
22332f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2234e6793769SArne Jansen 			if (ret < 0)
22352f38b3e1SArne Jansen 				return ret;
2236e6793769SArne Jansen 			if (!ret) {
223723c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
223823c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
223923c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2240e6793769SArne Jansen 				return 0;
2241e6793769SArne Jansen 			}
22422f38b3e1SArne Jansen 			if (!return_any)
22432f38b3e1SArne Jansen 				return 1;
22442f38b3e1SArne Jansen 			/*
22452f38b3e1SArne Jansen 			 * no lower item found, return the next
22462f38b3e1SArne Jansen 			 * higher instead
22472f38b3e1SArne Jansen 			 */
22482f38b3e1SArne Jansen 			return_any = 0;
22492f38b3e1SArne Jansen 			find_higher = 1;
22502f38b3e1SArne Jansen 			btrfs_release_path(p);
22512f38b3e1SArne Jansen 			goto again;
2252e6793769SArne Jansen 		} else {
22532f38b3e1SArne Jansen 			--p->slots[0];
22542f38b3e1SArne Jansen 		}
22552f38b3e1SArne Jansen 	}
22562f38b3e1SArne Jansen 	return 0;
22572f38b3e1SArne Jansen }
22582f38b3e1SArne Jansen 
22592f38b3e1SArne Jansen /*
22600ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
22610ff40a91SMarcos Paulo de Souza  * was not found.
22620ff40a91SMarcos Paulo de Souza  *
22630ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
22640ff40a91SMarcos Paulo de Souza  */
22650ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
22660ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
22670ff40a91SMarcos Paulo de Souza {
22680ff40a91SMarcos Paulo de Souza 	int ret;
22690ff40a91SMarcos Paulo de Souza 
22700ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
22710ff40a91SMarcos Paulo de Souza 	if (ret > 0)
22720ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
22730ff40a91SMarcos Paulo de Souza 
22740ff40a91SMarcos Paulo de Souza 	if (ret == 0)
22750ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
22760ff40a91SMarcos Paulo de Souza 
22770ff40a91SMarcos Paulo de Souza 	return ret;
22780ff40a91SMarcos Paulo de Souza }
22790ff40a91SMarcos Paulo de Souza 
22800ff40a91SMarcos Paulo de Souza /*
228174123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
228274123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
228374123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
228474123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
228574123bd7SChris Mason  * higher levels
2286aa5d6bedSChris Mason  *
228774123bd7SChris Mason  */
2288b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
22895f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2290be0e5c09SChris Mason {
2291be0e5c09SChris Mason 	int i;
22925f39d397SChris Mason 	struct extent_buffer *t;
22930e82bcfeSDavid Sterba 	int ret;
22945f39d397SChris Mason 
2295234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2296be0e5c09SChris Mason 		int tslot = path->slots[i];
22970e82bcfeSDavid Sterba 
2298eb60ceacSChris Mason 		if (!path->nodes[i])
2299be0e5c09SChris Mason 			break;
23005f39d397SChris Mason 		t = path->nodes[i];
2301f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
2302f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REPLACE, GFP_ATOMIC);
23030e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
23045f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2305d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2306be0e5c09SChris Mason 		if (tslot != 0)
2307be0e5c09SChris Mason 			break;
2308be0e5c09SChris Mason 	}
2309be0e5c09SChris Mason }
2310be0e5c09SChris Mason 
231174123bd7SChris Mason /*
231231840ae1SZheng Yan  * update item key.
231331840ae1SZheng Yan  *
231431840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
231531840ae1SZheng Yan  * that the new key won't break the order
231631840ae1SZheng Yan  */
2317b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2318b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2319310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
232031840ae1SZheng Yan {
232131840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
232231840ae1SZheng Yan 	struct extent_buffer *eb;
232331840ae1SZheng Yan 	int slot;
232431840ae1SZheng Yan 
232531840ae1SZheng Yan 	eb = path->nodes[0];
232631840ae1SZheng Yan 	slot = path->slots[0];
232731840ae1SZheng Yan 	if (slot > 0) {
232831840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
23297c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
23307c15d410SQu Wenruo 			btrfs_crit(fs_info,
23317c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
23327c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
23337c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
23347c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
23357c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
23367c15d410SQu Wenruo 				   new_key->offset);
23377c15d410SQu Wenruo 			btrfs_print_leaf(eb);
23387c15d410SQu Wenruo 			BUG();
23397c15d410SQu Wenruo 		}
234031840ae1SZheng Yan 	}
234131840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
234231840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
23437c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
23447c15d410SQu Wenruo 			btrfs_crit(fs_info,
23457c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
23467c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
23477c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
23487c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
23497c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
23507c15d410SQu Wenruo 				   new_key->offset);
23517c15d410SQu Wenruo 			btrfs_print_leaf(eb);
23527c15d410SQu Wenruo 			BUG();
23537c15d410SQu Wenruo 		}
235431840ae1SZheng Yan 	}
235531840ae1SZheng Yan 
235631840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
235731840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
235831840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
235931840ae1SZheng Yan 	if (slot == 0)
2360b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
236131840ae1SZheng Yan }
236231840ae1SZheng Yan 
236331840ae1SZheng Yan /*
2364d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2365d16c702fSQu Wenruo  *
2366d16c702fSQu Wenruo  * Return true if something is wrong.
2367d16c702fSQu Wenruo  * Return false if everything is fine.
2368d16c702fSQu Wenruo  *
2369d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2370d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2371d16c702fSQu Wenruo  *
2372d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2373d16c702fSQu Wenruo  * --------------------------------------------------------------
2374d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2375d16c702fSQu Wenruo  *
2376d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2377d16c702fSQu Wenruo  * key in leaf @right is 7.
2378d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2379d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2380d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2381d16c702fSQu Wenruo  * key of @right.
2382d16c702fSQu Wenruo  */
2383d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2384d16c702fSQu Wenruo 			       struct extent_buffer *right)
2385d16c702fSQu Wenruo {
2386d16c702fSQu Wenruo 	struct btrfs_key left_last;
2387d16c702fSQu Wenruo 	struct btrfs_key right_first;
2388d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2389d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2390d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2391d16c702fSQu Wenruo 
2392d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2393d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2394d16c702fSQu Wenruo 		return false;
2395d16c702fSQu Wenruo 
2396d16c702fSQu Wenruo 	if (level) {
2397d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2398d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2399d16c702fSQu Wenruo 	} else {
2400d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2401d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2402d16c702fSQu Wenruo 	}
2403d16c702fSQu Wenruo 
2404d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2405d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2406d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2407d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2408d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2409d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2410d16c702fSQu Wenruo 		return true;
2411d16c702fSQu Wenruo 	}
2412d16c702fSQu Wenruo 	return false;
2413d16c702fSQu Wenruo }
2414d16c702fSQu Wenruo 
2415d16c702fSQu Wenruo /*
241674123bd7SChris Mason  * try to push data from one node into the next node left in the
241779f95c82SChris Mason  * tree.
2418aa5d6bedSChris Mason  *
2419aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2420aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
242174123bd7SChris Mason  */
242298ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
24232ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2424971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2425be0e5c09SChris Mason {
2426d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2427be0e5c09SChris Mason 	int push_items = 0;
2428bb803951SChris Mason 	int src_nritems;
2429bb803951SChris Mason 	int dst_nritems;
2430aa5d6bedSChris Mason 	int ret = 0;
2431be0e5c09SChris Mason 
24325f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
24335f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
24340b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
24357bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
24367bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
243754aa1f4dSChris Mason 
2438bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2439971a1f66SChris Mason 		return 1;
2440971a1f66SChris Mason 
2441d397712bSChris Mason 	if (push_items <= 0)
2442be0e5c09SChris Mason 		return 1;
2443be0e5c09SChris Mason 
2444bce4eae9SChris Mason 	if (empty) {
2445971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2446bce4eae9SChris Mason 		if (push_items < src_nritems) {
2447bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2448bce4eae9SChris Mason 			 * we aren't going to empty it
2449bce4eae9SChris Mason 			 */
2450bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2451bce4eae9SChris Mason 				if (push_items <= 8)
2452bce4eae9SChris Mason 					return 1;
2453bce4eae9SChris Mason 				push_items -= 8;
2454bce4eae9SChris Mason 			}
2455bce4eae9SChris Mason 		}
2456bce4eae9SChris Mason 	} else
2457bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
245879f95c82SChris Mason 
2459d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2460d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2461d16c702fSQu Wenruo 		ret = -EUCLEAN;
2462d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2463d16c702fSQu Wenruo 		return ret;
2464d16c702fSQu Wenruo 	}
2465f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
24665de865eeSFilipe David Borba Manana 	if (ret) {
246766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
24685de865eeSFilipe David Borba Manana 		return ret;
24695de865eeSFilipe David Borba Manana 	}
24705f39d397SChris Mason 	copy_extent_buffer(dst, src,
24715f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
24725f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2473123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
24745f39d397SChris Mason 
2475bb803951SChris Mason 	if (push_items < src_nritems) {
247657911b8bSJan Schmidt 		/*
2477f3a84ccdSFilipe Manana 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2478f3a84ccdSFilipe Manana 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
247957911b8bSJan Schmidt 		 */
24805f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
24815f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2482e2fa7227SChris Mason 				      (src_nritems - push_items) *
2483123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2484bb803951SChris Mason 	}
24855f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
24865f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
24875f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
24885f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
248931840ae1SZheng Yan 
2490bb803951SChris Mason 	return ret;
2491be0e5c09SChris Mason }
2492be0e5c09SChris Mason 
249397571fd0SChris Mason /*
249479f95c82SChris Mason  * try to push data from one node into the next node right in the
249579f95c82SChris Mason  * tree.
249679f95c82SChris Mason  *
249779f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
249879f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
249979f95c82SChris Mason  *
250079f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
250179f95c82SChris Mason  */
25025f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
25035f39d397SChris Mason 			      struct extent_buffer *dst,
25045f39d397SChris Mason 			      struct extent_buffer *src)
250579f95c82SChris Mason {
250655d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
250779f95c82SChris Mason 	int push_items = 0;
250879f95c82SChris Mason 	int max_push;
250979f95c82SChris Mason 	int src_nritems;
251079f95c82SChris Mason 	int dst_nritems;
251179f95c82SChris Mason 	int ret = 0;
251279f95c82SChris Mason 
25137bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
25147bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
25157bb86316SChris Mason 
25165f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
25175f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
25180b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2519d397712bSChris Mason 	if (push_items <= 0)
252079f95c82SChris Mason 		return 1;
2521bce4eae9SChris Mason 
2522d397712bSChris Mason 	if (src_nritems < 4)
2523bce4eae9SChris Mason 		return 1;
252479f95c82SChris Mason 
252579f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
252679f95c82SChris Mason 	/* don't try to empty the node */
2527d397712bSChris Mason 	if (max_push >= src_nritems)
252879f95c82SChris Mason 		return 1;
2529252c38f0SYan 
253079f95c82SChris Mason 	if (max_push < push_items)
253179f95c82SChris Mason 		push_items = max_push;
253279f95c82SChris Mason 
2533d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2534d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2535d16c702fSQu Wenruo 		ret = -EUCLEAN;
2536d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2537d16c702fSQu Wenruo 		return ret;
2538d16c702fSQu Wenruo 	}
2539f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2540bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
25415f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
25425f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
25435f39d397SChris Mason 				      (dst_nritems) *
25445f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2545d6025579SChris Mason 
2546f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2547ed874f0dSDavid Sterba 					 push_items);
25485de865eeSFilipe David Borba Manana 	if (ret) {
254966642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
25505de865eeSFilipe David Borba Manana 		return ret;
25515de865eeSFilipe David Borba Manana 	}
25525f39d397SChris Mason 	copy_extent_buffer(dst, src,
25535f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
25545f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2555123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
255679f95c82SChris Mason 
25575f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
25585f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
255979f95c82SChris Mason 
25605f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
25615f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
256231840ae1SZheng Yan 
256379f95c82SChris Mason 	return ret;
256479f95c82SChris Mason }
256579f95c82SChris Mason 
256679f95c82SChris Mason /*
256797571fd0SChris Mason  * helper function to insert a new root level in the tree.
256897571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
256997571fd0SChris Mason  * point to the existing root
2570aa5d6bedSChris Mason  *
2571aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
257297571fd0SChris Mason  */
2573d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
25745f39d397SChris Mason 			   struct btrfs_root *root,
2575fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
257674123bd7SChris Mason {
25770b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
25787bb86316SChris Mason 	u64 lower_gen;
25795f39d397SChris Mason 	struct extent_buffer *lower;
25805f39d397SChris Mason 	struct extent_buffer *c;
2581925baeddSChris Mason 	struct extent_buffer *old;
25825f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2583d9d19a01SDavid Sterba 	int ret;
25845c680ed6SChris Mason 
25855c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
25865c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
25875c680ed6SChris Mason 
25887bb86316SChris Mason 	lower = path->nodes[level-1];
25897bb86316SChris Mason 	if (level == 1)
25907bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
25917bb86316SChris Mason 	else
25927bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
25937bb86316SChris Mason 
259479bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
259579bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2596cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
25975f39d397SChris Mason 	if (IS_ERR(c))
25985f39d397SChris Mason 		return PTR_ERR(c);
2599925baeddSChris Mason 
26000b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2601f0486c68SYan, Zheng 
26025f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
26035f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2604db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
26057bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
260631840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
26077bb86316SChris Mason 
26087bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
26095f39d397SChris Mason 
26105f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2611d5719762SChris Mason 
2612925baeddSChris Mason 	old = root->node;
2613406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2614d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2615240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2616925baeddSChris Mason 
2617925baeddSChris Mason 	/* the super has an extra ref to root->node */
2618925baeddSChris Mason 	free_extent_buffer(old);
2619925baeddSChris Mason 
26200b86a832SChris Mason 	add_root_to_dirty_list(root);
262167439dadSDavid Sterba 	atomic_inc(&c->refs);
26225f39d397SChris Mason 	path->nodes[level] = c;
2623ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
262474123bd7SChris Mason 	path->slots[level] = 0;
262574123bd7SChris Mason 	return 0;
262674123bd7SChris Mason }
26275c680ed6SChris Mason 
26285c680ed6SChris Mason /*
26295c680ed6SChris Mason  * worker function to insert a single pointer in a node.
26305c680ed6SChris Mason  * the node should have enough room for the pointer already
263197571fd0SChris Mason  *
26325c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
26335c680ed6SChris Mason  * blocknr is the block the key points to.
26345c680ed6SChris Mason  */
2635143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
26366ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2637143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2638c3e06965SJan Schmidt 		       int slot, int level)
26395c680ed6SChris Mason {
26405f39d397SChris Mason 	struct extent_buffer *lower;
26415c680ed6SChris Mason 	int nritems;
2642f3ea38daSJan Schmidt 	int ret;
26435c680ed6SChris Mason 
26445c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
264549d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
26465f39d397SChris Mason 	lower = path->nodes[level];
26475f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2648c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
26496ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
265074123bd7SChris Mason 	if (slot != nritems) {
2651bf1d3425SDavid Sterba 		if (level) {
2652f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2653f3a84ccdSFilipe Manana 					slot, nritems - slot);
2654bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2655bf1d3425SDavid Sterba 		}
26565f39d397SChris Mason 		memmove_extent_buffer(lower,
26575f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
26585f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
2659123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
266074123bd7SChris Mason 	}
2661c3e06965SJan Schmidt 	if (level) {
2662f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
2663f3a84ccdSFilipe Manana 					    BTRFS_MOD_LOG_KEY_ADD, GFP_NOFS);
2664f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2665f3ea38daSJan Schmidt 	}
26665f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2667db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
266874493f7aSChris Mason 	WARN_ON(trans->transid == 0);
266974493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
26705f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
26715f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
267274123bd7SChris Mason }
267374123bd7SChris Mason 
267497571fd0SChris Mason /*
267597571fd0SChris Mason  * split the node at the specified level in path in two.
267697571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
267797571fd0SChris Mason  *
267897571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
267997571fd0SChris Mason  * left and right, if either one works, it returns right away.
2680aa5d6bedSChris Mason  *
2681aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
268297571fd0SChris Mason  */
2683e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
2684e02119d5SChris Mason 			       struct btrfs_root *root,
2685e02119d5SChris Mason 			       struct btrfs_path *path, int level)
2686be0e5c09SChris Mason {
26870b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
26885f39d397SChris Mason 	struct extent_buffer *c;
26895f39d397SChris Mason 	struct extent_buffer *split;
26905f39d397SChris Mason 	struct btrfs_disk_key disk_key;
2691be0e5c09SChris Mason 	int mid;
26925c680ed6SChris Mason 	int ret;
26937518a238SChris Mason 	u32 c_nritems;
2694be0e5c09SChris Mason 
26955f39d397SChris Mason 	c = path->nodes[level];
26967bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
26975f39d397SChris Mason 	if (c == root->node) {
2698d9abbf1cSJan Schmidt 		/*
269990f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
270090f8d62eSJan Schmidt 		 *
2701fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
270290f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
270390f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
2704f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2705f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
2706f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
2707d9abbf1cSJan Schmidt 		 */
2708fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
27095c680ed6SChris Mason 		if (ret)
27105c680ed6SChris Mason 			return ret;
2711b3612421SChris Mason 	} else {
2712e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
27135f39d397SChris Mason 		c = path->nodes[level];
27145f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
27150b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2716e66f709bSChris Mason 			return 0;
271754aa1f4dSChris Mason 		if (ret < 0)
271854aa1f4dSChris Mason 			return ret;
27195c680ed6SChris Mason 	}
2720e66f709bSChris Mason 
27215f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
27225d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
27235d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
27247bb86316SChris Mason 
272579bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
272679bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
272779bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
27285f39d397SChris Mason 	if (IS_ERR(split))
27295f39d397SChris Mason 		return PTR_ERR(split);
273054aa1f4dSChris Mason 
27310b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2732bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
27335f39d397SChris Mason 
2734f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
27355de865eeSFilipe David Borba Manana 	if (ret) {
273666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
27375de865eeSFilipe David Borba Manana 		return ret;
27385de865eeSFilipe David Borba Manana 	}
27395f39d397SChris Mason 	copy_extent_buffer(split, c,
27405f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
27415f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
2742123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
27435f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
27445f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
2745aa5d6bedSChris Mason 
27465f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
27475f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
27485f39d397SChris Mason 
27496ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
2750c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
2751aa5d6bedSChris Mason 
27525de08d7dSChris Mason 	if (path->slots[level] >= mid) {
27535c680ed6SChris Mason 		path->slots[level] -= mid;
2754925baeddSChris Mason 		btrfs_tree_unlock(c);
27555f39d397SChris Mason 		free_extent_buffer(c);
27565f39d397SChris Mason 		path->nodes[level] = split;
27575c680ed6SChris Mason 		path->slots[level + 1] += 1;
2758eb60ceacSChris Mason 	} else {
2759925baeddSChris Mason 		btrfs_tree_unlock(split);
27605f39d397SChris Mason 		free_extent_buffer(split);
2761be0e5c09SChris Mason 	}
2762d5286a92SNikolay Borisov 	return 0;
2763be0e5c09SChris Mason }
2764be0e5c09SChris Mason 
276574123bd7SChris Mason /*
276674123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
276774123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
276874123bd7SChris Mason  * space used both by the item structs and the item data
276974123bd7SChris Mason  */
27705f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2771be0e5c09SChris Mason {
2772be0e5c09SChris Mason 	int data_len;
27735f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
2774d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
2775be0e5c09SChris Mason 
2776be0e5c09SChris Mason 	if (!nr)
2777be0e5c09SChris Mason 		return 0;
27783212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
27793212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
27800783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
2781d4dbff95SChris Mason 	WARN_ON(data_len < 0);
2782be0e5c09SChris Mason 	return data_len;
2783be0e5c09SChris Mason }
2784be0e5c09SChris Mason 
278574123bd7SChris Mason /*
2786d4dbff95SChris Mason  * The space between the end of the leaf items and
2787d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
2788d4dbff95SChris Mason  * the leaf has left for both items and data
2789d4dbff95SChris Mason  */
2790e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
2791d4dbff95SChris Mason {
2792e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
27935f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
27945f39d397SChris Mason 	int ret;
27950b246afaSJeff Mahoney 
27960b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
27975f39d397SChris Mason 	if (ret < 0) {
27980b246afaSJeff Mahoney 		btrfs_crit(fs_info,
2799efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2800da17066cSJeff Mahoney 			   ret,
28010b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
28025f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
28035f39d397SChris Mason 	}
28045f39d397SChris Mason 	return ret;
2805d4dbff95SChris Mason }
2806d4dbff95SChris Mason 
280799d8f83cSChris Mason /*
280899d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
280999d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
281099d8f83cSChris Mason  */
2811f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
281244871b1bSChris Mason 				      int data_size, int empty,
281344871b1bSChris Mason 				      struct extent_buffer *right,
281499d8f83cSChris Mason 				      int free_space, u32 left_nritems,
281599d8f83cSChris Mason 				      u32 min_slot)
281600ec4c51SChris Mason {
2817f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
28185f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
281944871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
2820cfed81a0SChris Mason 	struct btrfs_map_token token;
28215f39d397SChris Mason 	struct btrfs_disk_key disk_key;
282200ec4c51SChris Mason 	int slot;
282334a38218SChris Mason 	u32 i;
282400ec4c51SChris Mason 	int push_space = 0;
282500ec4c51SChris Mason 	int push_items = 0;
282634a38218SChris Mason 	u32 nr;
28277518a238SChris Mason 	u32 right_nritems;
28285f39d397SChris Mason 	u32 data_end;
2829db94535dSChris Mason 	u32 this_item_size;
283000ec4c51SChris Mason 
283134a38218SChris Mason 	if (empty)
283234a38218SChris Mason 		nr = 0;
283334a38218SChris Mason 	else
283499d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
283534a38218SChris Mason 
283631840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
283787b29b20SYan Zheng 		push_space += data_size;
283831840ae1SZheng Yan 
283944871b1bSChris Mason 	slot = path->slots[1];
284034a38218SChris Mason 	i = left_nritems - 1;
284134a38218SChris Mason 	while (i >= nr) {
284231840ae1SZheng Yan 		if (!empty && push_items > 0) {
284331840ae1SZheng Yan 			if (path->slots[0] > i)
284431840ae1SZheng Yan 				break;
284531840ae1SZheng Yan 			if (path->slots[0] == i) {
2846e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
2847e902baacSDavid Sterba 
284831840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
284931840ae1SZheng Yan 					break;
285031840ae1SZheng Yan 			}
285131840ae1SZheng Yan 		}
285231840ae1SZheng Yan 
285300ec4c51SChris Mason 		if (path->slots[0] == i)
285487b29b20SYan Zheng 			push_space += data_size;
2855db94535dSChris Mason 
28563212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
285774794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
285874794207SJosef Bacik 		    push_space > free_space)
285900ec4c51SChris Mason 			break;
286031840ae1SZheng Yan 
286100ec4c51SChris Mason 		push_items++;
286274794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
286334a38218SChris Mason 		if (i == 0)
286434a38218SChris Mason 			break;
286534a38218SChris Mason 		i--;
2866db94535dSChris Mason 	}
28675f39d397SChris Mason 
2868925baeddSChris Mason 	if (push_items == 0)
2869925baeddSChris Mason 		goto out_unlock;
28705f39d397SChris Mason 
28716c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
28725f39d397SChris Mason 
287300ec4c51SChris Mason 	/* push left to right */
28745f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
287534a38218SChris Mason 
2876dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
28778f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
28785f39d397SChris Mason 
287900ec4c51SChris Mason 	/* make room in the right data area */
28808f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
28815f39d397SChris Mason 	memmove_extent_buffer(right,
28823d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
28833d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
28840b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
28855f39d397SChris Mason 
288600ec4c51SChris Mason 	/* copy from the left data area */
28873d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
28880b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
28898f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
2890d6025579SChris Mason 		     push_space);
28915f39d397SChris Mason 
28925f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
28935f39d397SChris Mason 			      btrfs_item_nr_offset(0),
28940783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
28955f39d397SChris Mason 
289600ec4c51SChris Mason 	/* copy the items from left to right */
28975f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
28985f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
28990783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
290000ec4c51SChris Mason 
290100ec4c51SChris Mason 	/* update the item pointers */
2902c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
29037518a238SChris Mason 	right_nritems += push_items;
29045f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
29050b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
29067518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
29073212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
29083212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
2909db94535dSChris Mason 	}
2910db94535dSChris Mason 
29117518a238SChris Mason 	left_nritems -= push_items;
29125f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
291300ec4c51SChris Mason 
291434a38218SChris Mason 	if (left_nritems)
29155f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
2916f0486c68SYan, Zheng 	else
29176a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
2918f0486c68SYan, Zheng 
29195f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
2920a429e513SChris Mason 
29215f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
29225f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
2923d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
292402217ed2SChris Mason 
292500ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
29267518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
29277518a238SChris Mason 		path->slots[0] -= left_nritems;
2928925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
29296a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
2930925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
29315f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
29325f39d397SChris Mason 		path->nodes[0] = right;
293300ec4c51SChris Mason 		path->slots[1] += 1;
293400ec4c51SChris Mason 	} else {
2935925baeddSChris Mason 		btrfs_tree_unlock(right);
29365f39d397SChris Mason 		free_extent_buffer(right);
293700ec4c51SChris Mason 	}
293800ec4c51SChris Mason 	return 0;
2939925baeddSChris Mason 
2940925baeddSChris Mason out_unlock:
2941925baeddSChris Mason 	btrfs_tree_unlock(right);
2942925baeddSChris Mason 	free_extent_buffer(right);
2943925baeddSChris Mason 	return 1;
294400ec4c51SChris Mason }
2945925baeddSChris Mason 
294600ec4c51SChris Mason /*
294744871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
294874123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
294944871b1bSChris Mason  *
295044871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
295144871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
295299d8f83cSChris Mason  *
295399d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
295499d8f83cSChris Mason  * push any slot lower than min_slot
295574123bd7SChris Mason  */
295644871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
295799d8f83cSChris Mason 			   *root, struct btrfs_path *path,
295899d8f83cSChris Mason 			   int min_data_size, int data_size,
295999d8f83cSChris Mason 			   int empty, u32 min_slot)
2960be0e5c09SChris Mason {
296144871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
296244871b1bSChris Mason 	struct extent_buffer *right;
296344871b1bSChris Mason 	struct extent_buffer *upper;
296444871b1bSChris Mason 	int slot;
296544871b1bSChris Mason 	int free_space;
296644871b1bSChris Mason 	u32 left_nritems;
296744871b1bSChris Mason 	int ret;
296844871b1bSChris Mason 
296944871b1bSChris Mason 	if (!path->nodes[1])
297044871b1bSChris Mason 		return 1;
297144871b1bSChris Mason 
297244871b1bSChris Mason 	slot = path->slots[1];
297344871b1bSChris Mason 	upper = path->nodes[1];
297444871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
297544871b1bSChris Mason 		return 1;
297644871b1bSChris Mason 
297749d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
297844871b1bSChris Mason 
29794b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
2980fb770ae4SLiu Bo 	/*
2981fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
2982fb770ae4SLiu Bo 	 * no big deal, just return.
2983fb770ae4SLiu Bo 	 */
2984fb770ae4SLiu Bo 	if (IS_ERR(right))
298591ca338dSTsutomu Itoh 		return 1;
298691ca338dSTsutomu Itoh 
2987bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
298844871b1bSChris Mason 
2989e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
299044871b1bSChris Mason 	if (free_space < data_size)
299144871b1bSChris Mason 		goto out_unlock;
299244871b1bSChris Mason 
299344871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
2994bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
299544871b1bSChris Mason 	if (ret)
299644871b1bSChris Mason 		goto out_unlock;
299744871b1bSChris Mason 
299844871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
299944871b1bSChris Mason 	if (left_nritems == 0)
300044871b1bSChris Mason 		goto out_unlock;
300144871b1bSChris Mason 
3002d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3003d16c702fSQu Wenruo 		ret = -EUCLEAN;
3004d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3005d16c702fSQu Wenruo 		free_extent_buffer(right);
3006d16c702fSQu Wenruo 		return ret;
3007d16c702fSQu Wenruo 	}
30082ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
30092ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
30102ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
30112ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
301252042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
30132ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
30142ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
30152ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
30162ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
30172ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
30182ef1fed2SFilipe David Borba Manana 		return 0;
30192ef1fed2SFilipe David Borba Manana 	}
30202ef1fed2SFilipe David Borba Manana 
3021f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
302299d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
302344871b1bSChris Mason out_unlock:
302444871b1bSChris Mason 	btrfs_tree_unlock(right);
302544871b1bSChris Mason 	free_extent_buffer(right);
302644871b1bSChris Mason 	return 1;
302744871b1bSChris Mason }
302844871b1bSChris Mason 
302944871b1bSChris Mason /*
303044871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
303144871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
303299d8f83cSChris Mason  *
303399d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
303499d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
303599d8f83cSChris Mason  * items
303644871b1bSChris Mason  */
30378087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
303844871b1bSChris Mason 				     int empty, struct extent_buffer *left,
303999d8f83cSChris Mason 				     int free_space, u32 right_nritems,
304099d8f83cSChris Mason 				     u32 max_slot)
304144871b1bSChris Mason {
30428087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
30435f39d397SChris Mason 	struct btrfs_disk_key disk_key;
30445f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3045be0e5c09SChris Mason 	int i;
3046be0e5c09SChris Mason 	int push_space = 0;
3047be0e5c09SChris Mason 	int push_items = 0;
30487518a238SChris Mason 	u32 old_left_nritems;
304934a38218SChris Mason 	u32 nr;
3050aa5d6bedSChris Mason 	int ret = 0;
3051db94535dSChris Mason 	u32 this_item_size;
3052db94535dSChris Mason 	u32 old_left_item_size;
3053cfed81a0SChris Mason 	struct btrfs_map_token token;
3054cfed81a0SChris Mason 
305534a38218SChris Mason 	if (empty)
305699d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
305734a38218SChris Mason 	else
305899d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
305934a38218SChris Mason 
306034a38218SChris Mason 	for (i = 0; i < nr; i++) {
306131840ae1SZheng Yan 		if (!empty && push_items > 0) {
306231840ae1SZheng Yan 			if (path->slots[0] < i)
306331840ae1SZheng Yan 				break;
306431840ae1SZheng Yan 			if (path->slots[0] == i) {
3065e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3066e902baacSDavid Sterba 
306731840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
306831840ae1SZheng Yan 					break;
306931840ae1SZheng Yan 			}
307031840ae1SZheng Yan 		}
307131840ae1SZheng Yan 
3072be0e5c09SChris Mason 		if (path->slots[0] == i)
307387b29b20SYan Zheng 			push_space += data_size;
3074db94535dSChris Mason 
30753212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
307674794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
307774794207SJosef Bacik 		    free_space)
3078be0e5c09SChris Mason 			break;
3079db94535dSChris Mason 
3080be0e5c09SChris Mason 		push_items++;
308174794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3082be0e5c09SChris Mason 	}
3083db94535dSChris Mason 
3084be0e5c09SChris Mason 	if (push_items == 0) {
3085925baeddSChris Mason 		ret = 1;
3086925baeddSChris Mason 		goto out;
3087be0e5c09SChris Mason 	}
3088fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
30895f39d397SChris Mason 
3090be0e5c09SChris Mason 	/* push data from right to left */
30915f39d397SChris Mason 	copy_extent_buffer(left, right,
30925f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
30935f39d397SChris Mason 			   btrfs_item_nr_offset(0),
30945f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
30955f39d397SChris Mason 
30960b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
30973212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
30985f39d397SChris Mason 
30993d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
31008f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
31013d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
31023212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1),
3103be0e5c09SChris Mason 		     push_space);
31045f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
310587b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3106eb60ceacSChris Mason 
3107c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
31083212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3109be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
31105f39d397SChris Mason 		u32 ioff;
3111db94535dSChris Mason 
31123212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
31133212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3114cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3115be0e5c09SChris Mason 	}
31165f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3117be0e5c09SChris Mason 
3118be0e5c09SChris Mason 	/* fixup right node */
311931b1a2bdSJulia Lawall 	if (push_items > right_nritems)
312031b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3121d397712bSChris Mason 		       right_nritems);
312234a38218SChris Mason 
312334a38218SChris Mason 	if (push_items < right_nritems) {
31243212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
31258f881e8cSDavid Sterba 						  leaf_data_end(right);
31263d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
31270b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
31283d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
31298f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
31305f39d397SChris Mason 
31315f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
31325f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
31335f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
31340783fcfcSChris Mason 			     sizeof(struct btrfs_item));
313534a38218SChris Mason 	}
3136c82f823cSDavid Sterba 
3137c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3138eef1c494SYan 	right_nritems -= push_items;
3139eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
31400b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
31415f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
31423212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
31433212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3144db94535dSChris Mason 	}
3145eb60ceacSChris Mason 
31465f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
314734a38218SChris Mason 	if (right_nritems)
31485f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3149f0486c68SYan, Zheng 	else
31506a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3151098f59c2SChris Mason 
31525f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3153b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3154be0e5c09SChris Mason 
3155be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3156be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3157be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3158925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
31595f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
31605f39d397SChris Mason 		path->nodes[0] = left;
3161be0e5c09SChris Mason 		path->slots[1] -= 1;
3162be0e5c09SChris Mason 	} else {
3163925baeddSChris Mason 		btrfs_tree_unlock(left);
31645f39d397SChris Mason 		free_extent_buffer(left);
3165be0e5c09SChris Mason 		path->slots[0] -= push_items;
3166be0e5c09SChris Mason 	}
3167eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3168aa5d6bedSChris Mason 	return ret;
3169925baeddSChris Mason out:
3170925baeddSChris Mason 	btrfs_tree_unlock(left);
3171925baeddSChris Mason 	free_extent_buffer(left);
3172925baeddSChris Mason 	return ret;
3173be0e5c09SChris Mason }
3174be0e5c09SChris Mason 
317574123bd7SChris Mason /*
317644871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
317744871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
317899d8f83cSChris Mason  *
317999d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
318099d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
318199d8f83cSChris Mason  * items
318244871b1bSChris Mason  */
318344871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
318499d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
318599d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
318644871b1bSChris Mason {
318744871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
318844871b1bSChris Mason 	struct extent_buffer *left;
318944871b1bSChris Mason 	int slot;
319044871b1bSChris Mason 	int free_space;
319144871b1bSChris Mason 	u32 right_nritems;
319244871b1bSChris Mason 	int ret = 0;
319344871b1bSChris Mason 
319444871b1bSChris Mason 	slot = path->slots[1];
319544871b1bSChris Mason 	if (slot == 0)
319644871b1bSChris Mason 		return 1;
319744871b1bSChris Mason 	if (!path->nodes[1])
319844871b1bSChris Mason 		return 1;
319944871b1bSChris Mason 
320044871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
320144871b1bSChris Mason 	if (right_nritems == 0)
320244871b1bSChris Mason 		return 1;
320344871b1bSChris Mason 
320449d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
320544871b1bSChris Mason 
32064b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3207fb770ae4SLiu Bo 	/*
3208fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3209fb770ae4SLiu Bo 	 * no big deal, just return.
3210fb770ae4SLiu Bo 	 */
3211fb770ae4SLiu Bo 	if (IS_ERR(left))
321291ca338dSTsutomu Itoh 		return 1;
321391ca338dSTsutomu Itoh 
3214bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
321544871b1bSChris Mason 
3216e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
321744871b1bSChris Mason 	if (free_space < data_size) {
321844871b1bSChris Mason 		ret = 1;
321944871b1bSChris Mason 		goto out;
322044871b1bSChris Mason 	}
322144871b1bSChris Mason 
322244871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
32239631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3224bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
322544871b1bSChris Mason 	if (ret) {
322644871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
322779787eaaSJeff Mahoney 		if (ret == -ENOSPC)
322844871b1bSChris Mason 			ret = 1;
322944871b1bSChris Mason 		goto out;
323044871b1bSChris Mason 	}
323144871b1bSChris Mason 
3232d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3233d16c702fSQu Wenruo 		ret = -EUCLEAN;
3234d16c702fSQu Wenruo 		goto out;
3235d16c702fSQu Wenruo 	}
32368087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
323799d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
323899d8f83cSChris Mason 			       max_slot);
323944871b1bSChris Mason out:
324044871b1bSChris Mason 	btrfs_tree_unlock(left);
324144871b1bSChris Mason 	free_extent_buffer(left);
324244871b1bSChris Mason 	return ret;
324344871b1bSChris Mason }
324444871b1bSChris Mason 
324544871b1bSChris Mason /*
324674123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
324774123bd7SChris Mason  * available for the resulting leaf level of the path.
324874123bd7SChris Mason  */
3249143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
325044871b1bSChris Mason 				    struct btrfs_path *path,
325144871b1bSChris Mason 				    struct extent_buffer *l,
325244871b1bSChris Mason 				    struct extent_buffer *right,
325344871b1bSChris Mason 				    int slot, int mid, int nritems)
3254be0e5c09SChris Mason {
325594f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3256be0e5c09SChris Mason 	int data_copy_size;
3257be0e5c09SChris Mason 	int rt_data_off;
3258be0e5c09SChris Mason 	int i;
3259d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3260cfed81a0SChris Mason 	struct btrfs_map_token token;
3261cfed81a0SChris Mason 
32625f39d397SChris Mason 	nritems = nritems - mid;
32635f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3264dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
32655f39d397SChris Mason 
32665f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
32675f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
32685f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
32695f39d397SChris Mason 
32705f39d397SChris Mason 	copy_extent_buffer(right, l,
32713d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
32723d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
32738f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
327474123bd7SChris Mason 
3275dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
32765f39d397SChris Mason 
3277c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
32785f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3279db94535dSChris Mason 		u32 ioff;
3280db94535dSChris Mason 
32813212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
32823212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
32830783fcfcSChris Mason 	}
328474123bd7SChris Mason 
32855f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
32865f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
32876ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
32885f39d397SChris Mason 
32895f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
32905f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3291eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
32925f39d397SChris Mason 
3293be0e5c09SChris Mason 	if (mid <= slot) {
3294925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32955f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32965f39d397SChris Mason 		path->nodes[0] = right;
3297be0e5c09SChris Mason 		path->slots[0] -= mid;
3298be0e5c09SChris Mason 		path->slots[1] += 1;
3299925baeddSChris Mason 	} else {
3300925baeddSChris Mason 		btrfs_tree_unlock(right);
33015f39d397SChris Mason 		free_extent_buffer(right);
3302925baeddSChris Mason 	}
33035f39d397SChris Mason 
3304eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
330544871b1bSChris Mason }
330644871b1bSChris Mason 
330744871b1bSChris Mason /*
330899d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
330999d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
331099d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
331199d8f83cSChris Mason  *          A                 B                 C
331299d8f83cSChris Mason  *
331399d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
331499d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
331599d8f83cSChris Mason  * completely.
331699d8f83cSChris Mason  */
331799d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
331899d8f83cSChris Mason 					  struct btrfs_root *root,
331999d8f83cSChris Mason 					  struct btrfs_path *path,
332099d8f83cSChris Mason 					  int data_size)
332199d8f83cSChris Mason {
332299d8f83cSChris Mason 	int ret;
332399d8f83cSChris Mason 	int progress = 0;
332499d8f83cSChris Mason 	int slot;
332599d8f83cSChris Mason 	u32 nritems;
33265a4267caSFilipe David Borba Manana 	int space_needed = data_size;
332799d8f83cSChris Mason 
332899d8f83cSChris Mason 	slot = path->slots[0];
33295a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3330e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
333199d8f83cSChris Mason 
333299d8f83cSChris Mason 	/*
333399d8f83cSChris Mason 	 * try to push all the items after our slot into the
333499d8f83cSChris Mason 	 * right leaf
333599d8f83cSChris Mason 	 */
33365a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
333799d8f83cSChris Mason 	if (ret < 0)
333899d8f83cSChris Mason 		return ret;
333999d8f83cSChris Mason 
334099d8f83cSChris Mason 	if (ret == 0)
334199d8f83cSChris Mason 		progress++;
334299d8f83cSChris Mason 
334399d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
334499d8f83cSChris Mason 	/*
334599d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
334699d8f83cSChris Mason 	 * we've done so we're done
334799d8f83cSChris Mason 	 */
334899d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
334999d8f83cSChris Mason 		return 0;
335099d8f83cSChris Mason 
3351e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
335299d8f83cSChris Mason 		return 0;
335399d8f83cSChris Mason 
335499d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
335599d8f83cSChris Mason 	slot = path->slots[0];
3356263d3995SFilipe Manana 	space_needed = data_size;
3357263d3995SFilipe Manana 	if (slot > 0)
3358e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
33595a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
336099d8f83cSChris Mason 	if (ret < 0)
336199d8f83cSChris Mason 		return ret;
336299d8f83cSChris Mason 
336399d8f83cSChris Mason 	if (ret == 0)
336499d8f83cSChris Mason 		progress++;
336599d8f83cSChris Mason 
336699d8f83cSChris Mason 	if (progress)
336799d8f83cSChris Mason 		return 0;
336899d8f83cSChris Mason 	return 1;
336999d8f83cSChris Mason }
337099d8f83cSChris Mason 
337199d8f83cSChris Mason /*
337244871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
337344871b1bSChris Mason  * available for the resulting leaf level of the path.
337444871b1bSChris Mason  *
337544871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
337644871b1bSChris Mason  */
337744871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
337844871b1bSChris Mason 			       struct btrfs_root *root,
3379310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
338044871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
338144871b1bSChris Mason 			       int extend)
338244871b1bSChris Mason {
33835d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
338444871b1bSChris Mason 	struct extent_buffer *l;
338544871b1bSChris Mason 	u32 nritems;
338644871b1bSChris Mason 	int mid;
338744871b1bSChris Mason 	int slot;
338844871b1bSChris Mason 	struct extent_buffer *right;
3389b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
339044871b1bSChris Mason 	int ret = 0;
339144871b1bSChris Mason 	int wret;
33925d4f98a2SYan Zheng 	int split;
339344871b1bSChris Mason 	int num_doubles = 0;
339499d8f83cSChris Mason 	int tried_avoid_double = 0;
339544871b1bSChris Mason 
3396a5719521SYan, Zheng 	l = path->nodes[0];
3397a5719521SYan, Zheng 	slot = path->slots[0];
33983212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
33990b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3400a5719521SYan, Zheng 		return -EOVERFLOW;
3401a5719521SYan, Zheng 
340244871b1bSChris Mason 	/* first try to make some room by pushing left and right */
340333157e05SLiu Bo 	if (data_size && path->nodes[1]) {
34045a4267caSFilipe David Borba Manana 		int space_needed = data_size;
34055a4267caSFilipe David Borba Manana 
34065a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3407e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
34085a4267caSFilipe David Borba Manana 
34095a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
34105a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
341144871b1bSChris Mason 		if (wret < 0)
341244871b1bSChris Mason 			return wret;
341344871b1bSChris Mason 		if (wret) {
3414263d3995SFilipe Manana 			space_needed = data_size;
3415263d3995SFilipe Manana 			if (slot > 0)
3416e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
34175a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
34185a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
341944871b1bSChris Mason 			if (wret < 0)
342044871b1bSChris Mason 				return wret;
342144871b1bSChris Mason 		}
342244871b1bSChris Mason 		l = path->nodes[0];
342344871b1bSChris Mason 
342444871b1bSChris Mason 		/* did the pushes work? */
3425e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
342644871b1bSChris Mason 			return 0;
342744871b1bSChris Mason 	}
342844871b1bSChris Mason 
342944871b1bSChris Mason 	if (!path->nodes[1]) {
3430fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
343144871b1bSChris Mason 		if (ret)
343244871b1bSChris Mason 			return ret;
343344871b1bSChris Mason 	}
343444871b1bSChris Mason again:
34355d4f98a2SYan Zheng 	split = 1;
343644871b1bSChris Mason 	l = path->nodes[0];
343744871b1bSChris Mason 	slot = path->slots[0];
343844871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
343944871b1bSChris Mason 	mid = (nritems + 1) / 2;
344044871b1bSChris Mason 
34415d4f98a2SYan Zheng 	if (mid <= slot) {
34425d4f98a2SYan Zheng 		if (nritems == 1 ||
34435d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
34440b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
34455d4f98a2SYan Zheng 			if (slot >= nritems) {
34465d4f98a2SYan Zheng 				split = 0;
34475d4f98a2SYan Zheng 			} else {
34485d4f98a2SYan Zheng 				mid = slot;
34495d4f98a2SYan Zheng 				if (mid != nritems &&
34505d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
34510b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
345299d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
345399d8f83cSChris Mason 						goto push_for_double;
34545d4f98a2SYan Zheng 					split = 2;
34555d4f98a2SYan Zheng 				}
34565d4f98a2SYan Zheng 			}
34575d4f98a2SYan Zheng 		}
34585d4f98a2SYan Zheng 	} else {
34595d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
34600b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
34615d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
34625d4f98a2SYan Zheng 				split = 0;
34635d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
34645d4f98a2SYan Zheng 				mid = 1;
34655d4f98a2SYan Zheng 			} else {
34665d4f98a2SYan Zheng 				mid = slot;
34675d4f98a2SYan Zheng 				if (mid != nritems &&
34685d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
34690b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
347099d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
347199d8f83cSChris Mason 						goto push_for_double;
34725d4f98a2SYan Zheng 					split = 2;
34735d4f98a2SYan Zheng 				}
34745d4f98a2SYan Zheng 			}
34755d4f98a2SYan Zheng 		}
34765d4f98a2SYan Zheng 	}
34775d4f98a2SYan Zheng 
34785d4f98a2SYan Zheng 	if (split == 0)
34795d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
34805d4f98a2SYan Zheng 	else
34815d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
34825d4f98a2SYan Zheng 
3483ca9d473aSJosef Bacik 	/*
3484ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3485ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3486ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3487ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3488ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3489ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3490ca9d473aSJosef Bacik 	 */
349179bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
349279bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
349379bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3494ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3495f0486c68SYan, Zheng 	if (IS_ERR(right))
349644871b1bSChris Mason 		return PTR_ERR(right);
3497f0486c68SYan, Zheng 
34980b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
349944871b1bSChris Mason 
35005d4f98a2SYan Zheng 	if (split == 0) {
350144871b1bSChris Mason 		if (mid <= slot) {
350244871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
35036ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
35042ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
350544871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
350644871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
350744871b1bSChris Mason 			path->nodes[0] = right;
350844871b1bSChris Mason 			path->slots[0] = 0;
350944871b1bSChris Mason 			path->slots[1] += 1;
351044871b1bSChris Mason 		} else {
351144871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
35126ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
35132ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
351444871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
351544871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
351644871b1bSChris Mason 			path->nodes[0] = right;
351744871b1bSChris Mason 			path->slots[0] = 0;
3518143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3519b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
35205d4f98a2SYan Zheng 		}
3521196e0249SLiu Bo 		/*
3522196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3523196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3524196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3525196e0249SLiu Bo 		 */
352644871b1bSChris Mason 		return ret;
352744871b1bSChris Mason 	}
352844871b1bSChris Mason 
352994f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
353044871b1bSChris Mason 
35315d4f98a2SYan Zheng 	if (split == 2) {
3532cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3533cc0c5538SChris Mason 		num_doubles++;
3534cc0c5538SChris Mason 		goto again;
35353326d1b0SChris Mason 	}
353644871b1bSChris Mason 
3537143bede5SJeff Mahoney 	return 0;
353899d8f83cSChris Mason 
353999d8f83cSChris Mason push_for_double:
354099d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
354199d8f83cSChris Mason 	tried_avoid_double = 1;
3542e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
354399d8f83cSChris Mason 		return 0;
354499d8f83cSChris Mason 	goto again;
3545be0e5c09SChris Mason }
3546be0e5c09SChris Mason 
3547ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3548ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3549ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3550ad48fd75SYan, Zheng {
3551ad48fd75SYan, Zheng 	struct btrfs_key key;
3552ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3553ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3554ad48fd75SYan, Zheng 	u64 extent_len = 0;
3555ad48fd75SYan, Zheng 	u32 item_size;
3556ad48fd75SYan, Zheng 	int ret;
3557ad48fd75SYan, Zheng 
3558ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3559ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3560ad48fd75SYan, Zheng 
3561ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3562ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3563ad48fd75SYan, Zheng 
3564e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3565ad48fd75SYan, Zheng 		return 0;
3566ad48fd75SYan, Zheng 
35673212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3568ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3569ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3570ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3571ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3572ad48fd75SYan, Zheng 	}
3573b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3574ad48fd75SYan, Zheng 
3575ad48fd75SYan, Zheng 	path->keep_locks = 1;
3576ad48fd75SYan, Zheng 	path->search_for_split = 1;
3577ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3578ad48fd75SYan, Zheng 	path->search_for_split = 0;
3579a8df6fe6SFilipe Manana 	if (ret > 0)
3580a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3581ad48fd75SYan, Zheng 	if (ret < 0)
3582ad48fd75SYan, Zheng 		goto err;
3583ad48fd75SYan, Zheng 
3584ad48fd75SYan, Zheng 	ret = -EAGAIN;
3585ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3586a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
35873212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3588ad48fd75SYan, Zheng 		goto err;
3589ad48fd75SYan, Zheng 
3590109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3591e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3592109f6aefSChris Mason 		goto err;
3593109f6aefSChris Mason 
3594ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3595ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3596ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3597ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3598ad48fd75SYan, Zheng 			goto err;
3599ad48fd75SYan, Zheng 	}
3600ad48fd75SYan, Zheng 
3601ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3602f0486c68SYan, Zheng 	if (ret)
3603f0486c68SYan, Zheng 		goto err;
3604ad48fd75SYan, Zheng 
3605ad48fd75SYan, Zheng 	path->keep_locks = 0;
3606ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3607ad48fd75SYan, Zheng 	return 0;
3608ad48fd75SYan, Zheng err:
3609ad48fd75SYan, Zheng 	path->keep_locks = 0;
3610ad48fd75SYan, Zheng 	return ret;
3611ad48fd75SYan, Zheng }
3612ad48fd75SYan, Zheng 
361325263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3614310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3615459931ecSChris Mason 			       unsigned long split_offset)
3616459931ecSChris Mason {
3617459931ecSChris Mason 	struct extent_buffer *leaf;
3618c91666b1SJosef Bacik 	int orig_slot, slot;
3619ad48fd75SYan, Zheng 	char *buf;
3620459931ecSChris Mason 	u32 nritems;
3621ad48fd75SYan, Zheng 	u32 item_size;
3622459931ecSChris Mason 	u32 orig_offset;
3623459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3624459931ecSChris Mason 
3625459931ecSChris Mason 	leaf = path->nodes[0];
3626e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3627b9473439SChris Mason 
3628c91666b1SJosef Bacik 	orig_slot = path->slots[0];
36293212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
36303212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3631459931ecSChris Mason 
3632459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3633ad48fd75SYan, Zheng 	if (!buf)
3634ad48fd75SYan, Zheng 		return -ENOMEM;
3635ad48fd75SYan, Zheng 
3636459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3637459931ecSChris Mason 			    path->slots[0]), item_size);
3638ad48fd75SYan, Zheng 
3639459931ecSChris Mason 	slot = path->slots[0] + 1;
3640459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3641459931ecSChris Mason 	if (slot != nritems) {
3642459931ecSChris Mason 		/* shift the items */
3643459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3644459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3645459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3646459931ecSChris Mason 	}
3647459931ecSChris Mason 
3648459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3649459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3650459931ecSChris Mason 
36513212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
36523212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3653459931ecSChris Mason 
36543212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
3655459931ecSChris Mason 				 orig_offset + item_size - split_offset);
36563212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3657459931ecSChris Mason 
3658459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3659459931ecSChris Mason 
3660459931ecSChris Mason 	/* write the data for the start of the original item */
3661459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3662459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3663459931ecSChris Mason 			    split_offset);
3664459931ecSChris Mason 
3665459931ecSChris Mason 	/* write the data for the new item */
3666459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3667459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3668459931ecSChris Mason 			    item_size - split_offset);
3669459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3670459931ecSChris Mason 
3671e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3672459931ecSChris Mason 	kfree(buf);
3673ad48fd75SYan, Zheng 	return 0;
3674ad48fd75SYan, Zheng }
3675ad48fd75SYan, Zheng 
3676ad48fd75SYan, Zheng /*
3677ad48fd75SYan, Zheng  * This function splits a single item into two items,
3678ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3679ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3680ad48fd75SYan, Zheng  *
3681ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3682ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3683ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3684ad48fd75SYan, Zheng  *
3685ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3686ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3687ad48fd75SYan, Zheng  *
3688ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3689ad48fd75SYan, Zheng  * leaf the entire time.
3690ad48fd75SYan, Zheng  */
3691ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3692ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3693ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3694310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3695ad48fd75SYan, Zheng 		     unsigned long split_offset)
3696ad48fd75SYan, Zheng {
3697ad48fd75SYan, Zheng 	int ret;
3698ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3699ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3700ad48fd75SYan, Zheng 	if (ret)
3701459931ecSChris Mason 		return ret;
3702ad48fd75SYan, Zheng 
370325263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3704ad48fd75SYan, Zheng 	return ret;
3705ad48fd75SYan, Zheng }
3706ad48fd75SYan, Zheng 
3707ad48fd75SYan, Zheng /*
3708d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
3709d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
3710d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
3711d352ac68SChris Mason  * the front.
3712d352ac68SChris Mason  */
371378ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3714b18c6685SChris Mason {
3715b18c6685SChris Mason 	int slot;
37165f39d397SChris Mason 	struct extent_buffer *leaf;
3717b18c6685SChris Mason 	u32 nritems;
3718b18c6685SChris Mason 	unsigned int data_end;
3719b18c6685SChris Mason 	unsigned int old_data_start;
3720b18c6685SChris Mason 	unsigned int old_size;
3721b18c6685SChris Mason 	unsigned int size_diff;
3722b18c6685SChris Mason 	int i;
3723cfed81a0SChris Mason 	struct btrfs_map_token token;
3724cfed81a0SChris Mason 
37255f39d397SChris Mason 	leaf = path->nodes[0];
3726179e29e4SChris Mason 	slot = path->slots[0];
3727179e29e4SChris Mason 
37283212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
3729179e29e4SChris Mason 	if (old_size == new_size)
3730143bede5SJeff Mahoney 		return;
3731b18c6685SChris Mason 
37325f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
37338f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3734b18c6685SChris Mason 
37353212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
3736179e29e4SChris Mason 
3737b18c6685SChris Mason 	size_diff = old_size - new_size;
3738b18c6685SChris Mason 
3739b18c6685SChris Mason 	BUG_ON(slot < 0);
3740b18c6685SChris Mason 	BUG_ON(slot >= nritems);
3741b18c6685SChris Mason 
3742b18c6685SChris Mason 	/*
3743b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3744b18c6685SChris Mason 	 */
3745b18c6685SChris Mason 	/* first correct the data pointers */
3746c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3747b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
37485f39d397SChris Mason 		u32 ioff;
3749db94535dSChris Mason 
37503212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
37513212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3752b18c6685SChris Mason 	}
3753db94535dSChris Mason 
3754b18c6685SChris Mason 	/* shift the data */
3755179e29e4SChris Mason 	if (from_end) {
37563d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
37573d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3758b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
3759179e29e4SChris Mason 	} else {
3760179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
3761179e29e4SChris Mason 		u64 offset;
3762179e29e4SChris Mason 
3763179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
3764179e29e4SChris Mason 
3765179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3766179e29e4SChris Mason 			unsigned long ptr;
3767179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
3768179e29e4SChris Mason 
3769179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
3770179e29e4SChris Mason 					    struct btrfs_file_extent_item);
3771179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
3772179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
3773179e29e4SChris Mason 
3774179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
3775179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
3776179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
3777179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
3778179e29e4SChris Mason 				      (unsigned long)fi,
37797ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
3780179e29e4SChris Mason 			}
3781179e29e4SChris Mason 		}
3782179e29e4SChris Mason 
37833d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
37843d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3785179e29e4SChris Mason 			      data_end, old_data_start - data_end);
3786179e29e4SChris Mason 
3787179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
3788179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3789179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
3790179e29e4SChris Mason 		if (slot == 0)
3791b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
3792179e29e4SChris Mason 	}
37935f39d397SChris Mason 
37943212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
37955f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3796b18c6685SChris Mason 
3797e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3798a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3799b18c6685SChris Mason 		BUG();
38005f39d397SChris Mason 	}
3801b18c6685SChris Mason }
3802b18c6685SChris Mason 
3803d352ac68SChris Mason /*
38048f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
3805d352ac68SChris Mason  */
3806c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
38076567e837SChris Mason {
38086567e837SChris Mason 	int slot;
38095f39d397SChris Mason 	struct extent_buffer *leaf;
38106567e837SChris Mason 	u32 nritems;
38116567e837SChris Mason 	unsigned int data_end;
38126567e837SChris Mason 	unsigned int old_data;
38136567e837SChris Mason 	unsigned int old_size;
38146567e837SChris Mason 	int i;
3815cfed81a0SChris Mason 	struct btrfs_map_token token;
3816cfed81a0SChris Mason 
38175f39d397SChris Mason 	leaf = path->nodes[0];
38186567e837SChris Mason 
38195f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
38208f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
38216567e837SChris Mason 
3822e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
3823a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
38246567e837SChris Mason 		BUG();
38255f39d397SChris Mason 	}
38266567e837SChris Mason 	slot = path->slots[0];
3827dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
38286567e837SChris Mason 
38296567e837SChris Mason 	BUG_ON(slot < 0);
38303326d1b0SChris Mason 	if (slot >= nritems) {
3831a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3832c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
3833d397712bSChris Mason 			   slot, nritems);
3834290342f6SArnd Bergmann 		BUG();
38353326d1b0SChris Mason 	}
38366567e837SChris Mason 
38376567e837SChris Mason 	/*
38386567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
38396567e837SChris Mason 	 */
38406567e837SChris Mason 	/* first correct the data pointers */
3841c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
38426567e837SChris Mason 	for (i = slot; i < nritems; i++) {
38435f39d397SChris Mason 		u32 ioff;
3844db94535dSChris Mason 
38453212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
38463212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
38476567e837SChris Mason 	}
38485f39d397SChris Mason 
38496567e837SChris Mason 	/* shift the data */
38503d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
38513d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
38526567e837SChris Mason 		      data_end, old_data - data_end);
38535f39d397SChris Mason 
38546567e837SChris Mason 	data_end = old_data;
38553212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
38563212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
38575f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
38586567e837SChris Mason 
3859e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3860a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
38616567e837SChris Mason 		BUG();
38625f39d397SChris Mason 	}
38636567e837SChris Mason }
38646567e837SChris Mason 
3865da9ffb24SNikolay Borisov /**
3866da9ffb24SNikolay Borisov  * setup_items_for_insert - Helper called before inserting one or more items
3867da9ffb24SNikolay Borisov  * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
3868da9ffb24SNikolay Borisov  * in a function that doesn't call btrfs_search_slot
3869da9ffb24SNikolay Borisov  *
3870da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
3871da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
3872b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
387374123bd7SChris Mason  */
3874f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
3875b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
3876be0e5c09SChris Mason {
38770b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
38789c58309dSChris Mason 	int i;
38797518a238SChris Mason 	u32 nritems;
3880be0e5c09SChris Mason 	unsigned int data_end;
3881e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
388244871b1bSChris Mason 	struct extent_buffer *leaf;
388344871b1bSChris Mason 	int slot;
3884cfed81a0SChris Mason 	struct btrfs_map_token token;
3885fc0d82e1SNikolay Borisov 	u32 total_size;
3886fc0d82e1SNikolay Borisov 
3887b7ef5f3aSFilipe Manana 	/*
3888b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
3889b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
3890b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
3891b7ef5f3aSFilipe Manana 	 */
389224cdc847SFilipe Manana 	if (path->slots[0] == 0) {
3893b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
3894b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
389524cdc847SFilipe Manana 	}
389624cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
389724cdc847SFilipe Manana 
38985f39d397SChris Mason 	leaf = path->nodes[0];
389944871b1bSChris Mason 	slot = path->slots[0];
390074123bd7SChris Mason 
39015f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
39028f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3903b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
3904eb60ceacSChris Mason 
3905e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
3906a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39070b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
3908e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
3909be0e5c09SChris Mason 		BUG();
3910d4dbff95SChris Mason 	}
39115f39d397SChris Mason 
3912c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3913be0e5c09SChris Mason 	if (slot != nritems) {
3914dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
3915be0e5c09SChris Mason 
39165f39d397SChris Mason 		if (old_data < data_end) {
3917a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
39187269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
39197269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
39205f39d397SChris Mason 				   slot, old_data, data_end);
3921290342f6SArnd Bergmann 			BUG();
39225f39d397SChris Mason 		}
3923be0e5c09SChris Mason 		/*
3924be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3925be0e5c09SChris Mason 		 */
3926be0e5c09SChris Mason 		/* first correct the data pointers */
39270783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
39285f39d397SChris Mason 			u32 ioff;
3929db94535dSChris Mason 
39303212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
39313212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
3932b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
39330783fcfcSChris Mason 		}
3934be0e5c09SChris Mason 		/* shift the items */
3935b7ef5f3aSFilipe Manana 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + batch->nr),
39365f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
39370783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
3938be0e5c09SChris Mason 
3939be0e5c09SChris Mason 		/* shift the data */
39403d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
3941b7ef5f3aSFilipe Manana 				      data_end - batch->total_data_size,
3942b7ef5f3aSFilipe Manana 				      BTRFS_LEAF_DATA_OFFSET + data_end,
3943b7ef5f3aSFilipe Manana 				      old_data - data_end);
3944be0e5c09SChris Mason 		data_end = old_data;
3945be0e5c09SChris Mason 	}
39465f39d397SChris Mason 
394762e2749eSChris Mason 	/* setup the item for the new data */
3948b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
3949b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
39509c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
3951b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
39523212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
39533212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
39549c58309dSChris Mason 	}
395544871b1bSChris Mason 
3956b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
3957b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3958aa5d6bedSChris Mason 
3959e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3960a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3961be0e5c09SChris Mason 		BUG();
39625f39d397SChris Mason 	}
396344871b1bSChris Mason }
396444871b1bSChris Mason 
396544871b1bSChris Mason /*
3966f0641656SFilipe Manana  * Insert a new item into a leaf.
3967f0641656SFilipe Manana  *
3968f0641656SFilipe Manana  * @root:      The root of the btree.
3969f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
3970f0641656SFilipe Manana  * @key:       The key of the new item.
3971f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
3972f0641656SFilipe Manana  */
3973f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
3974f0641656SFilipe Manana 				 struct btrfs_path *path,
3975f0641656SFilipe Manana 				 const struct btrfs_key *key,
3976f0641656SFilipe Manana 				 u32 data_size)
3977f0641656SFilipe Manana {
3978f0641656SFilipe Manana 	struct btrfs_item_batch batch;
3979f0641656SFilipe Manana 
3980f0641656SFilipe Manana 	batch.keys = key;
3981f0641656SFilipe Manana 	batch.data_sizes = &data_size;
3982f0641656SFilipe Manana 	batch.total_data_size = data_size;
3983f0641656SFilipe Manana 	batch.nr = 1;
3984f0641656SFilipe Manana 
3985f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
3986f0641656SFilipe Manana }
3987f0641656SFilipe Manana 
3988f0641656SFilipe Manana /*
398944871b1bSChris Mason  * Given a key and some data, insert items into the tree.
399044871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
399144871b1bSChris Mason  */
399244871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
399344871b1bSChris Mason 			    struct btrfs_root *root,
399444871b1bSChris Mason 			    struct btrfs_path *path,
3995b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
399644871b1bSChris Mason {
399744871b1bSChris Mason 	int ret = 0;
399844871b1bSChris Mason 	int slot;
3999b7ef5f3aSFilipe Manana 	u32 total_size;
400044871b1bSChris Mason 
4001b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4002b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
400344871b1bSChris Mason 	if (ret == 0)
400444871b1bSChris Mason 		return -EEXIST;
400544871b1bSChris Mason 	if (ret < 0)
4006143bede5SJeff Mahoney 		return ret;
400744871b1bSChris Mason 
400844871b1bSChris Mason 	slot = path->slots[0];
400944871b1bSChris Mason 	BUG_ON(slot < 0);
401044871b1bSChris Mason 
4011b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4012143bede5SJeff Mahoney 	return 0;
401362e2749eSChris Mason }
401462e2749eSChris Mason 
401562e2749eSChris Mason /*
401662e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
401762e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
401862e2749eSChris Mason  */
4019310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4020310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4021310712b2SOmar Sandoval 		      u32 data_size)
402262e2749eSChris Mason {
402362e2749eSChris Mason 	int ret = 0;
40242c90e5d6SChris Mason 	struct btrfs_path *path;
40255f39d397SChris Mason 	struct extent_buffer *leaf;
40265f39d397SChris Mason 	unsigned long ptr;
402762e2749eSChris Mason 
40282c90e5d6SChris Mason 	path = btrfs_alloc_path();
4029db5b493aSTsutomu Itoh 	if (!path)
4030db5b493aSTsutomu Itoh 		return -ENOMEM;
40312c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
403262e2749eSChris Mason 	if (!ret) {
40335f39d397SChris Mason 		leaf = path->nodes[0];
40345f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
40355f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
40365f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
403762e2749eSChris Mason 	}
40382c90e5d6SChris Mason 	btrfs_free_path(path);
4039aa5d6bedSChris Mason 	return ret;
4040be0e5c09SChris Mason }
4041be0e5c09SChris Mason 
404274123bd7SChris Mason /*
4043f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4044f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4045f0641656SFilipe Manana  * contiguous with the original item.
4046f0641656SFilipe Manana  *
4047f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4048f0641656SFilipe Manana  * the entire time.
4049f0641656SFilipe Manana  */
4050f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4051f0641656SFilipe Manana 			 struct btrfs_root *root,
4052f0641656SFilipe Manana 			 struct btrfs_path *path,
4053f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4054f0641656SFilipe Manana {
4055f0641656SFilipe Manana 	struct extent_buffer *leaf;
4056f0641656SFilipe Manana 	int ret;
4057f0641656SFilipe Manana 	u32 item_size;
4058f0641656SFilipe Manana 
4059f0641656SFilipe Manana 	leaf = path->nodes[0];
40603212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4061f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4062f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4063f0641656SFilipe Manana 	if (ret)
4064f0641656SFilipe Manana 		return ret;
4065f0641656SFilipe Manana 
4066f0641656SFilipe Manana 	path->slots[0]++;
4067f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4068f0641656SFilipe Manana 	leaf = path->nodes[0];
4069f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4070f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4071f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4072f0641656SFilipe Manana 			     item_size);
4073f0641656SFilipe Manana 	return 0;
4074f0641656SFilipe Manana }
4075f0641656SFilipe Manana 
4076f0641656SFilipe Manana /*
40775de08d7dSChris Mason  * delete the pointer from a given node.
407874123bd7SChris Mason  *
4079d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4080d352ac68SChris Mason  * empty a node.
408174123bd7SChris Mason  */
4082afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4083afe5fea7STsutomu Itoh 		    int level, int slot)
4084be0e5c09SChris Mason {
40855f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
40867518a238SChris Mason 	u32 nritems;
4087f3ea38daSJan Schmidt 	int ret;
4088be0e5c09SChris Mason 
40895f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4090be0e5c09SChris Mason 	if (slot != nritems - 1) {
4091bf1d3425SDavid Sterba 		if (level) {
4092f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4093f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4094bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4095bf1d3425SDavid Sterba 		}
40965f39d397SChris Mason 		memmove_extent_buffer(parent,
40975f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
40985f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4099d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4100d6025579SChris Mason 			      (nritems - slot - 1));
410157ba86c0SChris Mason 	} else if (level) {
4102f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
4103f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REMOVE, GFP_NOFS);
410457ba86c0SChris Mason 		BUG_ON(ret < 0);
4105be0e5c09SChris Mason 	}
4106f3ea38daSJan Schmidt 
41077518a238SChris Mason 	nritems--;
41085f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
41097518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
41105f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4111eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
41125f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4113bb803951SChris Mason 	} else if (slot == 0) {
41145f39d397SChris Mason 		struct btrfs_disk_key disk_key;
41155f39d397SChris Mason 
41165f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4117b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4118be0e5c09SChris Mason 	}
4119d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4120be0e5c09SChris Mason }
4121be0e5c09SChris Mason 
412274123bd7SChris Mason /*
4123323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
41245d4f98a2SYan Zheng  * path->nodes[1].
4125323ac95bSChris Mason  *
4126323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4127323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4128323ac95bSChris Mason  *
4129323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4130323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4131323ac95bSChris Mason  */
4132143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4133323ac95bSChris Mason 				    struct btrfs_root *root,
41345d4f98a2SYan Zheng 				    struct btrfs_path *path,
41355d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4136323ac95bSChris Mason {
41375d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4138afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4139323ac95bSChris Mason 
41404d081c41SChris Mason 	/*
41414d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
41424d081c41SChris Mason 	 * aren't holding any locks when we call it
41434d081c41SChris Mason 	 */
41444d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
41454d081c41SChris Mason 
4146f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4147f0486c68SYan, Zheng 
414867439dadSDavid Sterba 	atomic_inc(&leaf->refs);
41497a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
41503083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4151323ac95bSChris Mason }
4152323ac95bSChris Mason /*
415374123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
415474123bd7SChris Mason  * the leaf, remove it from the tree
415574123bd7SChris Mason  */
415685e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
415785e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4158be0e5c09SChris Mason {
41590b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
41605f39d397SChris Mason 	struct extent_buffer *leaf;
4161aa5d6bedSChris Mason 	int ret = 0;
4162aa5d6bedSChris Mason 	int wret;
41637518a238SChris Mason 	u32 nritems;
4164be0e5c09SChris Mason 
41655f39d397SChris Mason 	leaf = path->nodes[0];
41665f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4167be0e5c09SChris Mason 
416885e21bacSChris Mason 	if (slot + nr != nritems) {
4169*0cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
4170*0cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4171c82f823cSDavid Sterba 		struct btrfs_map_token token;
4172*0cae23b6SFilipe Manana 		u32 dsize = 0;
4173*0cae23b6SFilipe Manana 		int i;
4174*0cae23b6SFilipe Manana 
4175*0cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
4176*0cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
41775f39d397SChris Mason 
41783d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4179d6025579SChris Mason 			      data_end + dsize,
41803d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
418185e21bacSChris Mason 			      last_off - data_end);
41825f39d397SChris Mason 
4183c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
418485e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
41855f39d397SChris Mason 			u32 ioff;
4186db94535dSChris Mason 
41873212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
41883212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
41890783fcfcSChris Mason 		}
4190db94535dSChris Mason 
41915f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
419285e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
41930783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
419485e21bacSChris Mason 			      (nritems - slot - nr));
4195be0e5c09SChris Mason 	}
419685e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
419785e21bacSChris Mason 	nritems -= nr;
41985f39d397SChris Mason 
419974123bd7SChris Mason 	/* delete the leaf if we've emptied it */
42007518a238SChris Mason 	if (nritems == 0) {
42015f39d397SChris Mason 		if (leaf == root->node) {
42025f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
42039a8dd150SChris Mason 		} else {
42046a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4205143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
42069a8dd150SChris Mason 		}
4207be0e5c09SChris Mason 	} else {
42087518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4209aa5d6bedSChris Mason 		if (slot == 0) {
42105f39d397SChris Mason 			struct btrfs_disk_key disk_key;
42115f39d397SChris Mason 
42125f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4213b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4214aa5d6bedSChris Mason 		}
4215aa5d6bedSChris Mason 
42167c4063d1SFilipe Manana 		/*
42177c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
42187c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
42197c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
42207c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
42217c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
42227c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
42237c4063d1SFilipe Manana 		 */
42240b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
42257c4063d1SFilipe Manana 			u32 min_push_space;
42267c4063d1SFilipe Manana 
4227be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4228be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4229be0e5c09SChris Mason 			 * for possible call to del_ptr below
4230be0e5c09SChris Mason 			 */
42314920c9acSChris Mason 			slot = path->slots[1];
423267439dadSDavid Sterba 			atomic_inc(&leaf->refs);
42337c4063d1SFilipe Manana 			/*
42347c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
42357c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
42367c4063d1SFilipe Manana 			 */
42377c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
42387c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
42397c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
42407c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
424154aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4242aa5d6bedSChris Mason 				ret = wret;
42435f39d397SChris Mason 
42445f39d397SChris Mason 			if (path->nodes[0] == leaf &&
42455f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
42467c4063d1SFilipe Manana 				/*
42477c4063d1SFilipe Manana 				 * If we were not able to push all items from our
42487c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
42497c4063d1SFilipe Manana 				 * either push all the remaining items to the
42507c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
42517c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
42527c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
42537c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
42547c4063d1SFilipe Manana 				 * or nearly full.
42557c4063d1SFilipe Manana 				 */
42567c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
42577c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
42587c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
42597c4063d1SFilipe Manana 						       min_push_space, 1, 0);
426054aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4261aa5d6bedSChris Mason 					ret = wret;
4262aa5d6bedSChris Mason 			}
42635f39d397SChris Mason 
42645f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4265323ac95bSChris Mason 				path->slots[1] = slot;
4266143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
42675f39d397SChris Mason 				free_extent_buffer(leaf);
4268143bede5SJeff Mahoney 				ret = 0;
42695de08d7dSChris Mason 			} else {
4270925baeddSChris Mason 				/* if we're still in the path, make sure
4271925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4272925baeddSChris Mason 				 * push_leaf functions must have already
4273925baeddSChris Mason 				 * dirtied this buffer
4274925baeddSChris Mason 				 */
4275925baeddSChris Mason 				if (path->nodes[0] == leaf)
42765f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
42775f39d397SChris Mason 				free_extent_buffer(leaf);
4278be0e5c09SChris Mason 			}
4279d5719762SChris Mason 		} else {
42805f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4281be0e5c09SChris Mason 		}
42829a8dd150SChris Mason 	}
4283aa5d6bedSChris Mason 	return ret;
42849a8dd150SChris Mason }
42859a8dd150SChris Mason 
428697571fd0SChris Mason /*
4287925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
42887bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
42897bb86316SChris Mason  * returns < 0 on io errors.
4290d352ac68SChris Mason  *
4291d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4292d352ac68SChris Mason  * time you call it.
42937bb86316SChris Mason  */
429416e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
42957bb86316SChris Mason {
4296925baeddSChris Mason 	struct btrfs_key key;
4297925baeddSChris Mason 	struct btrfs_disk_key found_key;
4298925baeddSChris Mason 	int ret;
42997bb86316SChris Mason 
4300925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4301925baeddSChris Mason 
4302e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
4303925baeddSChris Mason 		key.offset--;
4304e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
4305925baeddSChris Mason 		key.type--;
4306e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4307e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
4308925baeddSChris Mason 		key.objectid--;
4309e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
4310e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4311e8b0d724SFilipe David Borba Manana 	} else {
43127bb86316SChris Mason 		return 1;
4313e8b0d724SFilipe David Borba Manana 	}
43147bb86316SChris Mason 
4315b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4316925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4317925baeddSChris Mason 	if (ret < 0)
4318925baeddSChris Mason 		return ret;
4319925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4320925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4321337c6f68SFilipe Manana 	/*
4322337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
4323337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
4324337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
4325337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
4326337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
4327337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
4328337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
4329337c6f68SFilipe Manana 	 * the previous key we computed above.
4330337c6f68SFilipe Manana 	 */
4331337c6f68SFilipe Manana 	if (ret <= 0)
43327bb86316SChris Mason 		return 0;
4333925baeddSChris Mason 	return 1;
43347bb86316SChris Mason }
43357bb86316SChris Mason 
43363f157a2fSChris Mason /*
43373f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4338de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4339de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
43403f157a2fSChris Mason  *
43413f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
43423f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
43433f157a2fSChris Mason  * key and get a writable path.
43443f157a2fSChris Mason  *
43453f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
43463f157a2fSChris Mason  * of the tree.
43473f157a2fSChris Mason  *
4348d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4349d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4350d352ac68SChris Mason  * skipped over (without reading them).
4351d352ac68SChris Mason  *
43523f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
43533f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
43543f157a2fSChris Mason  */
43553f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4356de78b51aSEric Sandeen 			 struct btrfs_path *path,
43573f157a2fSChris Mason 			 u64 min_trans)
43583f157a2fSChris Mason {
43593f157a2fSChris Mason 	struct extent_buffer *cur;
43603f157a2fSChris Mason 	struct btrfs_key found_key;
43613f157a2fSChris Mason 	int slot;
43629652480bSYan 	int sret;
43633f157a2fSChris Mason 	u32 nritems;
43643f157a2fSChris Mason 	int level;
43653f157a2fSChris Mason 	int ret = 1;
4366f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
43673f157a2fSChris Mason 
4368f98de9b9SFilipe Manana 	path->keep_locks = 1;
43693f157a2fSChris Mason again:
4370bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
43713f157a2fSChris Mason 	level = btrfs_header_level(cur);
4372e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
43733f157a2fSChris Mason 	path->nodes[level] = cur;
4374bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
43753f157a2fSChris Mason 
43763f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
43773f157a2fSChris Mason 		ret = 1;
43783f157a2fSChris Mason 		goto out;
43793f157a2fSChris Mason 	}
43803f157a2fSChris Mason 	while (1) {
43813f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
43823f157a2fSChris Mason 		level = btrfs_header_level(cur);
4383e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
4384cbca7d59SFilipe Manana 		if (sret < 0) {
4385cbca7d59SFilipe Manana 			ret = sret;
4386cbca7d59SFilipe Manana 			goto out;
4387cbca7d59SFilipe Manana 		}
43883f157a2fSChris Mason 
4389323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4390323ac95bSChris Mason 		if (level == path->lowest_level) {
4391e02119d5SChris Mason 			if (slot >= nritems)
4392e02119d5SChris Mason 				goto find_next_key;
43933f157a2fSChris Mason 			ret = 0;
43943f157a2fSChris Mason 			path->slots[level] = slot;
43953f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
43963f157a2fSChris Mason 			goto out;
43973f157a2fSChris Mason 		}
43989652480bSYan 		if (sret && slot > 0)
43999652480bSYan 			slot--;
44003f157a2fSChris Mason 		/*
4401de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4402260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
44033f157a2fSChris Mason 		 */
44043f157a2fSChris Mason 		while (slot < nritems) {
44053f157a2fSChris Mason 			u64 gen;
4406e02119d5SChris Mason 
44073f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
44083f157a2fSChris Mason 			if (gen < min_trans) {
44093f157a2fSChris Mason 				slot++;
44103f157a2fSChris Mason 				continue;
44113f157a2fSChris Mason 			}
44123f157a2fSChris Mason 			break;
44133f157a2fSChris Mason 		}
4414e02119d5SChris Mason find_next_key:
44153f157a2fSChris Mason 		/*
44163f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
44173f157a2fSChris Mason 		 * and find another one
44183f157a2fSChris Mason 		 */
44193f157a2fSChris Mason 		if (slot >= nritems) {
4420e02119d5SChris Mason 			path->slots[level] = slot;
4421e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4422de78b51aSEric Sandeen 						  min_trans);
4423e02119d5SChris Mason 			if (sret == 0) {
4424b3b4aa74SDavid Sterba 				btrfs_release_path(path);
44253f157a2fSChris Mason 				goto again;
44263f157a2fSChris Mason 			} else {
44273f157a2fSChris Mason 				goto out;
44283f157a2fSChris Mason 			}
44293f157a2fSChris Mason 		}
44303f157a2fSChris Mason 		/* save our key for returning back */
44313f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
44323f157a2fSChris Mason 		path->slots[level] = slot;
44333f157a2fSChris Mason 		if (level == path->lowest_level) {
44343f157a2fSChris Mason 			ret = 0;
44353f157a2fSChris Mason 			goto out;
44363f157a2fSChris Mason 		}
44374b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4438fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4439fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4440fb770ae4SLiu Bo 			goto out;
4441fb770ae4SLiu Bo 		}
44423f157a2fSChris Mason 
4443bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4444b4ce94deSChris Mason 
4445bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
44463f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4447f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
44483f157a2fSChris Mason 	}
44493f157a2fSChris Mason out:
4450f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4451f98de9b9SFilipe Manana 	if (ret == 0) {
4452f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4453f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4454f98de9b9SFilipe Manana 	}
44553f157a2fSChris Mason 	return ret;
44563f157a2fSChris Mason }
44573f157a2fSChris Mason 
44583f157a2fSChris Mason /*
44593f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
44603f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4461de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
44623f157a2fSChris Mason  *
44633f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
44643f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
44653f157a2fSChris Mason  *
44663f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
44673f157a2fSChris Mason  * calling this function.
44683f157a2fSChris Mason  */
4469e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4470de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4471e7a84565SChris Mason {
4472e7a84565SChris Mason 	int slot;
4473e7a84565SChris Mason 	struct extent_buffer *c;
4474e7a84565SChris Mason 
44756a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4476e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4477e7a84565SChris Mason 		if (!path->nodes[level])
4478e7a84565SChris Mason 			return 1;
4479e7a84565SChris Mason 
4480e7a84565SChris Mason 		slot = path->slots[level] + 1;
4481e7a84565SChris Mason 		c = path->nodes[level];
44823f157a2fSChris Mason next:
4483e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
448433c66f43SYan Zheng 			int ret;
448533c66f43SYan Zheng 			int orig_lowest;
448633c66f43SYan Zheng 			struct btrfs_key cur_key;
448733c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
448833c66f43SYan Zheng 			    !path->nodes[level + 1])
4489e7a84565SChris Mason 				return 1;
449033c66f43SYan Zheng 
44916a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
449233c66f43SYan Zheng 				level++;
4493e7a84565SChris Mason 				continue;
4494e7a84565SChris Mason 			}
449533c66f43SYan Zheng 
449633c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
449733c66f43SYan Zheng 			if (level == 0)
449833c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
449933c66f43SYan Zheng 			else
450033c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
450133c66f43SYan Zheng 
450233c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4503b3b4aa74SDavid Sterba 			btrfs_release_path(path);
450433c66f43SYan Zheng 			path->lowest_level = level;
450533c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
450633c66f43SYan Zheng 						0, 0);
450733c66f43SYan Zheng 			path->lowest_level = orig_lowest;
450833c66f43SYan Zheng 			if (ret < 0)
450933c66f43SYan Zheng 				return ret;
451033c66f43SYan Zheng 
451133c66f43SYan Zheng 			c = path->nodes[level];
451233c66f43SYan Zheng 			slot = path->slots[level];
451333c66f43SYan Zheng 			if (ret == 0)
451433c66f43SYan Zheng 				slot++;
451533c66f43SYan Zheng 			goto next;
451633c66f43SYan Zheng 		}
451733c66f43SYan Zheng 
4518e7a84565SChris Mason 		if (level == 0)
4519e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
45203f157a2fSChris Mason 		else {
45213f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
45223f157a2fSChris Mason 
45233f157a2fSChris Mason 			if (gen < min_trans) {
45243f157a2fSChris Mason 				slot++;
45253f157a2fSChris Mason 				goto next;
45263f157a2fSChris Mason 			}
4527e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
45283f157a2fSChris Mason 		}
4529e7a84565SChris Mason 		return 0;
4530e7a84565SChris Mason 	}
4531e7a84565SChris Mason 	return 1;
4532e7a84565SChris Mason }
4533e7a84565SChris Mason 
45343d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
45353d7806ecSJan Schmidt 			u64 time_seq)
45363d7806ecSJan Schmidt {
4537d97e63b6SChris Mason 	int slot;
45388e73f275SChris Mason 	int level;
45395f39d397SChris Mason 	struct extent_buffer *c;
45408e73f275SChris Mason 	struct extent_buffer *next;
4541d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4542925baeddSChris Mason 	struct btrfs_key key;
4543d96b3424SFilipe Manana 	bool need_commit_sem = false;
4544925baeddSChris Mason 	u32 nritems;
4545925baeddSChris Mason 	int ret;
45460e46318dSJosef Bacik 	int i;
4547925baeddSChris Mason 
4548925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4549d397712bSChris Mason 	if (nritems == 0)
4550925baeddSChris Mason 		return 1;
4551925baeddSChris Mason 
45528e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
45538e73f275SChris Mason again:
45548e73f275SChris Mason 	level = 1;
45558e73f275SChris Mason 	next = NULL;
4556b3b4aa74SDavid Sterba 	btrfs_release_path(path);
45578e73f275SChris Mason 
4558a2135011SChris Mason 	path->keep_locks = 1;
45598e73f275SChris Mason 
4560d96b3424SFilipe Manana 	if (time_seq) {
45613d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4562d96b3424SFilipe Manana 	} else {
4563d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4564d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4565d96b3424SFilipe Manana 			need_commit_sem = true;
4566d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
4567d96b3424SFilipe Manana 		}
4568925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4569d96b3424SFilipe Manana 	}
4570925baeddSChris Mason 	path->keep_locks = 0;
4571925baeddSChris Mason 
4572925baeddSChris Mason 	if (ret < 0)
4573d96b3424SFilipe Manana 		goto done;
4574925baeddSChris Mason 
4575a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4576168fd7d2SChris Mason 	/*
4577168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4578168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4579168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4580168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4581168fd7d2SChris Mason 	 */
4582a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4583e457afecSYan Zheng 		if (ret == 0)
4584168fd7d2SChris Mason 			path->slots[0]++;
45858e73f275SChris Mason 		ret = 0;
4586925baeddSChris Mason 		goto done;
4587925baeddSChris Mason 	}
45880b43e04fSLiu Bo 	/*
45890b43e04fSLiu Bo 	 * So the above check misses one case:
45900b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
45910b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
45920b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
45930b43e04fSLiu Bo 	 *
45940b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
45950b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
45960b43e04fSLiu Bo 	 *
45970b43e04fSLiu Bo 	 * And a bit more explanation about this check,
45980b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
45990b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
46000b43e04fSLiu Bo 	 * bigger one.
46010b43e04fSLiu Bo 	 */
46020b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
46030b43e04fSLiu Bo 		ret = 0;
46040b43e04fSLiu Bo 		goto done;
46050b43e04fSLiu Bo 	}
4606d97e63b6SChris Mason 
4607234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
46088e73f275SChris Mason 		if (!path->nodes[level]) {
46098e73f275SChris Mason 			ret = 1;
46108e73f275SChris Mason 			goto done;
46118e73f275SChris Mason 		}
46125f39d397SChris Mason 
4613d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4614d97e63b6SChris Mason 		c = path->nodes[level];
46155f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4616d97e63b6SChris Mason 			level++;
46178e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
46188e73f275SChris Mason 				ret = 1;
46198e73f275SChris Mason 				goto done;
46208e73f275SChris Mason 			}
4621d97e63b6SChris Mason 			continue;
4622d97e63b6SChris Mason 		}
46235f39d397SChris Mason 
46240e46318dSJosef Bacik 
46250e46318dSJosef Bacik 		/*
46260e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
46270e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
46280e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
46290e46318dSJosef Bacik 		 */
46300e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
46310e46318dSJosef Bacik 			if (path->locks[level]) {
46320e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
46330e46318dSJosef Bacik 				path->locks[i] = 0;
46340e46318dSJosef Bacik 			}
46350e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
46360e46318dSJosef Bacik 			path->nodes[i] = NULL;
4637925baeddSChris Mason 		}
46385f39d397SChris Mason 
46398e73f275SChris Mason 		next = c;
4640d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4641cda79c54SDavid Sterba 					    slot, &key);
46428e73f275SChris Mason 		if (ret == -EAGAIN)
46438e73f275SChris Mason 			goto again;
46445f39d397SChris Mason 
464576a05b35SChris Mason 		if (ret < 0) {
4646b3b4aa74SDavid Sterba 			btrfs_release_path(path);
464776a05b35SChris Mason 			goto done;
464876a05b35SChris Mason 		}
464976a05b35SChris Mason 
46505cd57b2cSChris Mason 		if (!path->skip_locking) {
4651bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4652d42244a0SJan Schmidt 			if (!ret && time_seq) {
4653d42244a0SJan Schmidt 				/*
4654d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4655d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4656d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4657d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4658d42244a0SJan Schmidt 				 * on our lock and cycle.
4659d42244a0SJan Schmidt 				 */
4660cf538830SJan Schmidt 				free_extent_buffer(next);
4661d42244a0SJan Schmidt 				btrfs_release_path(path);
4662d42244a0SJan Schmidt 				cond_resched();
4663d42244a0SJan Schmidt 				goto again;
4664d42244a0SJan Schmidt 			}
46650e46318dSJosef Bacik 			if (!ret)
46660e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4667bd681513SChris Mason 		}
4668d97e63b6SChris Mason 		break;
4669d97e63b6SChris Mason 	}
4670d97e63b6SChris Mason 	path->slots[level] = slot;
4671d97e63b6SChris Mason 	while (1) {
4672d97e63b6SChris Mason 		level--;
4673d97e63b6SChris Mason 		path->nodes[level] = next;
4674d97e63b6SChris Mason 		path->slots[level] = 0;
4675a74a4b97SChris Mason 		if (!path->skip_locking)
4676ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4677d97e63b6SChris Mason 		if (!level)
4678d97e63b6SChris Mason 			break;
4679b4ce94deSChris Mason 
4680d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4681cda79c54SDavid Sterba 					    0, &key);
46828e73f275SChris Mason 		if (ret == -EAGAIN)
46838e73f275SChris Mason 			goto again;
46848e73f275SChris Mason 
468576a05b35SChris Mason 		if (ret < 0) {
4686b3b4aa74SDavid Sterba 			btrfs_release_path(path);
468776a05b35SChris Mason 			goto done;
468876a05b35SChris Mason 		}
468976a05b35SChris Mason 
4690ffeb03cfSJosef Bacik 		if (!path->skip_locking)
46910e46318dSJosef Bacik 			btrfs_tree_read_lock(next);
4692d97e63b6SChris Mason 	}
46938e73f275SChris Mason 	ret = 0;
4694925baeddSChris Mason done:
4695f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
4696d96b3424SFilipe Manana 	if (need_commit_sem) {
4697d96b3424SFilipe Manana 		int ret2;
4698d96b3424SFilipe Manana 
4699d96b3424SFilipe Manana 		path->need_commit_sem = 1;
4700d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
4701d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
4702d96b3424SFilipe Manana 		if (ret2)
4703d96b3424SFilipe Manana 			ret = ret2;
4704d96b3424SFilipe Manana 	}
47058e73f275SChris Mason 
47068e73f275SChris Mason 	return ret;
4707d97e63b6SChris Mason }
47080b86a832SChris Mason 
47093f157a2fSChris Mason /*
47103f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
47113f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
47123f157a2fSChris Mason  *
47133f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
47143f157a2fSChris Mason  */
47150b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
47160b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
47170b86a832SChris Mason 			int type)
47180b86a832SChris Mason {
47190b86a832SChris Mason 	struct btrfs_key found_key;
47200b86a832SChris Mason 	struct extent_buffer *leaf;
4721e02119d5SChris Mason 	u32 nritems;
47220b86a832SChris Mason 	int ret;
47230b86a832SChris Mason 
47240b86a832SChris Mason 	while (1) {
47250b86a832SChris Mason 		if (path->slots[0] == 0) {
47260b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
47270b86a832SChris Mason 			if (ret != 0)
47280b86a832SChris Mason 				return ret;
47290b86a832SChris Mason 		} else {
47300b86a832SChris Mason 			path->slots[0]--;
47310b86a832SChris Mason 		}
47320b86a832SChris Mason 		leaf = path->nodes[0];
4733e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
4734e02119d5SChris Mason 		if (nritems == 0)
4735e02119d5SChris Mason 			return 1;
4736e02119d5SChris Mason 		if (path->slots[0] == nritems)
4737e02119d5SChris Mason 			path->slots[0]--;
4738e02119d5SChris Mason 
47390b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4740e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
4741e02119d5SChris Mason 			break;
47420a4eefbbSYan Zheng 		if (found_key.type == type)
47430a4eefbbSYan Zheng 			return 0;
4744e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
4745e02119d5SChris Mason 		    found_key.type < type)
4746e02119d5SChris Mason 			break;
47470b86a832SChris Mason 	}
47480b86a832SChris Mason 	return 1;
47490b86a832SChris Mason }
4750ade2e0b3SWang Shilong 
4751ade2e0b3SWang Shilong /*
4752ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
4753ade2e0b3SWang Shilong  * min objecitd.
4754ade2e0b3SWang Shilong  *
4755ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4756ade2e0b3SWang Shilong  */
4757ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
4758ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
4759ade2e0b3SWang Shilong {
4760ade2e0b3SWang Shilong 	struct btrfs_key found_key;
4761ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
4762ade2e0b3SWang Shilong 	u32 nritems;
4763ade2e0b3SWang Shilong 	int ret;
4764ade2e0b3SWang Shilong 
4765ade2e0b3SWang Shilong 	while (1) {
4766ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
4767ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
4768ade2e0b3SWang Shilong 			if (ret != 0)
4769ade2e0b3SWang Shilong 				return ret;
4770ade2e0b3SWang Shilong 		} else {
4771ade2e0b3SWang Shilong 			path->slots[0]--;
4772ade2e0b3SWang Shilong 		}
4773ade2e0b3SWang Shilong 		leaf = path->nodes[0];
4774ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
4775ade2e0b3SWang Shilong 		if (nritems == 0)
4776ade2e0b3SWang Shilong 			return 1;
4777ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
4778ade2e0b3SWang Shilong 			path->slots[0]--;
4779ade2e0b3SWang Shilong 
4780ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4781ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
4782ade2e0b3SWang Shilong 			break;
4783ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4784ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
4785ade2e0b3SWang Shilong 			return 0;
4786ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
4787ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
4788ade2e0b3SWang Shilong 			break;
4789ade2e0b3SWang Shilong 	}
4790ade2e0b3SWang Shilong 	return 1;
4791ade2e0b3SWang Shilong }
4792