xref: /openbmc/linux/fs/btrfs/ctree.c (revision bdcdd86ca94b5e9faa18d6f4d3dda660ac5c887e)
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"
1988c602abSQu Wenruo #include "tree-checker.h"
209a8dd150SChris Mason 
21e089f05cSChris Mason static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
22e089f05cSChris Mason 		      *root, struct btrfs_path *path, int level);
23310712b2SOmar Sandoval static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
24310712b2SOmar Sandoval 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
25310712b2SOmar Sandoval 		      int data_size, int extend);
265f39d397SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
272ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
28971a1f66SChris Mason 			  struct extent_buffer *src, int empty);
295f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
305f39d397SChris Mason 			      struct extent_buffer *dst_buf,
315f39d397SChris Mason 			      struct extent_buffer *src_buf);
32afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
33afe5fea7STsutomu Itoh 		    int level, int slot);
34d97e63b6SChris Mason 
35af024ed2SJohannes Thumshirn static const struct btrfs_csums {
36af024ed2SJohannes Thumshirn 	u16		size;
3759a0fcdbSDavid Sterba 	const char	name[10];
3859a0fcdbSDavid Sterba 	const char	driver[12];
39af024ed2SJohannes Thumshirn } btrfs_csums[] = {
40af024ed2SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
413951e7f0SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
423831bf00SJohannes Thumshirn 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
43352ae07bSDavid Sterba 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
44352ae07bSDavid Sterba 				     .driver = "blake2b-256" },
45af024ed2SJohannes Thumshirn };
46af024ed2SJohannes Thumshirn 
47af024ed2SJohannes Thumshirn int btrfs_super_csum_size(const struct btrfs_super_block *s)
48af024ed2SJohannes Thumshirn {
49af024ed2SJohannes Thumshirn 	u16 t = btrfs_super_csum_type(s);
50af024ed2SJohannes Thumshirn 	/*
51af024ed2SJohannes Thumshirn 	 * csum type is validated at mount time
52af024ed2SJohannes Thumshirn 	 */
53af024ed2SJohannes Thumshirn 	return btrfs_csums[t].size;
54af024ed2SJohannes Thumshirn }
55af024ed2SJohannes Thumshirn 
56af024ed2SJohannes Thumshirn const char *btrfs_super_csum_name(u16 csum_type)
57af024ed2SJohannes Thumshirn {
58af024ed2SJohannes Thumshirn 	/* csum type is validated at mount time */
59af024ed2SJohannes Thumshirn 	return btrfs_csums[csum_type].name;
60af024ed2SJohannes Thumshirn }
61af024ed2SJohannes Thumshirn 
62b4e967beSDavid Sterba /*
63b4e967beSDavid Sterba  * Return driver name if defined, otherwise the name that's also a valid driver
64b4e967beSDavid Sterba  * name
65b4e967beSDavid Sterba  */
66b4e967beSDavid Sterba const char *btrfs_super_csum_driver(u16 csum_type)
67b4e967beSDavid Sterba {
68b4e967beSDavid Sterba 	/* csum type is validated at mount time */
6959a0fcdbSDavid Sterba 	return btrfs_csums[csum_type].driver[0] ?
7059a0fcdbSDavid Sterba 		btrfs_csums[csum_type].driver :
71b4e967beSDavid Sterba 		btrfs_csums[csum_type].name;
72b4e967beSDavid Sterba }
73b4e967beSDavid Sterba 
74604997b4SDavid Sterba size_t __attribute_const__ btrfs_get_num_csums(void)
75f7cea56cSDavid Sterba {
76f7cea56cSDavid Sterba 	return ARRAY_SIZE(btrfs_csums);
77f7cea56cSDavid Sterba }
78f7cea56cSDavid Sterba 
792c90e5d6SChris Mason struct btrfs_path *btrfs_alloc_path(void)
802c90e5d6SChris Mason {
81e2c89907SMasahiro Yamada 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
822c90e5d6SChris Mason }
832c90e5d6SChris Mason 
84d352ac68SChris Mason /* this also releases the path */
852c90e5d6SChris Mason void btrfs_free_path(struct btrfs_path *p)
862c90e5d6SChris Mason {
87ff175d57SJesper Juhl 	if (!p)
88ff175d57SJesper Juhl 		return;
89b3b4aa74SDavid Sterba 	btrfs_release_path(p);
902c90e5d6SChris Mason 	kmem_cache_free(btrfs_path_cachep, p);
912c90e5d6SChris Mason }
922c90e5d6SChris Mason 
93d352ac68SChris Mason /*
94d352ac68SChris Mason  * path release drops references on the extent buffers in the path
95d352ac68SChris Mason  * and it drops any locks held by this path
96d352ac68SChris Mason  *
97d352ac68SChris Mason  * It is safe to call this on paths that no locks or extent buffers held.
98d352ac68SChris Mason  */
99b3b4aa74SDavid Sterba noinline void btrfs_release_path(struct btrfs_path *p)
100eb60ceacSChris Mason {
101eb60ceacSChris Mason 	int i;
102a2135011SChris Mason 
103234b63a0SChris Mason 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
1043f157a2fSChris Mason 		p->slots[i] = 0;
105eb60ceacSChris Mason 		if (!p->nodes[i])
106925baeddSChris Mason 			continue;
107925baeddSChris Mason 		if (p->locks[i]) {
108bd681513SChris Mason 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
109925baeddSChris Mason 			p->locks[i] = 0;
110925baeddSChris Mason 		}
1115f39d397SChris Mason 		free_extent_buffer(p->nodes[i]);
1123f157a2fSChris Mason 		p->nodes[i] = NULL;
113eb60ceacSChris Mason 	}
114eb60ceacSChris Mason }
115eb60ceacSChris Mason 
116d352ac68SChris Mason /*
1178bb808c6SDavid Sterba  * We want the transaction abort to print stack trace only for errors where the
1188bb808c6SDavid Sterba  * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
1198bb808c6SDavid Sterba  * caused by external factors.
1208bb808c6SDavid Sterba  */
1218bb808c6SDavid Sterba bool __cold abort_should_print_stack(int errno)
1228bb808c6SDavid Sterba {
1238bb808c6SDavid Sterba 	switch (errno) {
1248bb808c6SDavid Sterba 	case -EIO:
1258bb808c6SDavid Sterba 	case -EROFS:
1268bb808c6SDavid Sterba 	case -ENOMEM:
1278bb808c6SDavid Sterba 		return false;
1288bb808c6SDavid Sterba 	}
1298bb808c6SDavid Sterba 	return true;
1308bb808c6SDavid Sterba }
1318bb808c6SDavid Sterba 
1328bb808c6SDavid Sterba /*
133d352ac68SChris Mason  * safely gets a reference on the root node of a tree.  A lock
134d352ac68SChris Mason  * is not taken, so a concurrent writer may put a different node
135d352ac68SChris Mason  * at the root of the tree.  See btrfs_lock_root_node for the
136d352ac68SChris Mason  * looping required.
137d352ac68SChris Mason  *
138d352ac68SChris Mason  * The extent buffer returned by this has a reference taken, so
139d352ac68SChris Mason  * it won't disappear.  It may stop being the root of the tree
140d352ac68SChris Mason  * at any time because there are no locks held.
141d352ac68SChris Mason  */
142925baeddSChris Mason struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
143925baeddSChris Mason {
144925baeddSChris Mason 	struct extent_buffer *eb;
145240f62c8SChris Mason 
1463083ee2eSJosef Bacik 	while (1) {
147240f62c8SChris Mason 		rcu_read_lock();
148240f62c8SChris Mason 		eb = rcu_dereference(root->node);
1493083ee2eSJosef Bacik 
1503083ee2eSJosef Bacik 		/*
1513083ee2eSJosef Bacik 		 * RCU really hurts here, we could free up the root node because
15201327610SNicholas D Steeves 		 * it was COWed but we may not get the new root node yet so do
1533083ee2eSJosef Bacik 		 * the inc_not_zero dance and if it doesn't work then
1543083ee2eSJosef Bacik 		 * synchronize_rcu and try again.
1553083ee2eSJosef Bacik 		 */
1563083ee2eSJosef Bacik 		if (atomic_inc_not_zero(&eb->refs)) {
157240f62c8SChris Mason 			rcu_read_unlock();
1583083ee2eSJosef Bacik 			break;
1593083ee2eSJosef Bacik 		}
1603083ee2eSJosef Bacik 		rcu_read_unlock();
1613083ee2eSJosef Bacik 		synchronize_rcu();
1623083ee2eSJosef Bacik 	}
163925baeddSChris Mason 	return eb;
164925baeddSChris Mason }
165925baeddSChris Mason 
16692a7cc42SQu Wenruo /*
16792a7cc42SQu Wenruo  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
16892a7cc42SQu Wenruo  * just get put onto a simple dirty list.  Transaction walks this list to make
16992a7cc42SQu Wenruo  * sure they get properly updated on disk.
170d352ac68SChris Mason  */
1710b86a832SChris Mason static void add_root_to_dirty_list(struct btrfs_root *root)
1720b86a832SChris Mason {
1730b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1740b246afaSJeff Mahoney 
175e7070be1SJosef Bacik 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
176e7070be1SJosef Bacik 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
177e7070be1SJosef Bacik 		return;
178e7070be1SJosef Bacik 
1790b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
180e7070be1SJosef Bacik 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
181e7070be1SJosef Bacik 		/* Want the extent tree to be the last on the list */
1824fd786e6SMisono Tomohiro 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
183e7070be1SJosef Bacik 			list_move_tail(&root->dirty_list,
1840b246afaSJeff Mahoney 				       &fs_info->dirty_cowonly_roots);
185e7070be1SJosef Bacik 		else
186e7070be1SJosef Bacik 			list_move(&root->dirty_list,
1870b246afaSJeff Mahoney 				  &fs_info->dirty_cowonly_roots);
1880b86a832SChris Mason 	}
1890b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1900b86a832SChris Mason }
1910b86a832SChris Mason 
192d352ac68SChris Mason /*
193d352ac68SChris Mason  * used by snapshot creation to make a copy of a root for a tree with
194d352ac68SChris Mason  * a given objectid.  The buffer with the new root node is returned in
195d352ac68SChris Mason  * cow_ret, and this func returns zero on success or a negative error code.
196d352ac68SChris Mason  */
197be20aa9dSChris Mason int btrfs_copy_root(struct btrfs_trans_handle *trans,
198be20aa9dSChris Mason 		      struct btrfs_root *root,
199be20aa9dSChris Mason 		      struct extent_buffer *buf,
200be20aa9dSChris Mason 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
201be20aa9dSChris Mason {
2020b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
203be20aa9dSChris Mason 	struct extent_buffer *cow;
204be20aa9dSChris Mason 	int ret = 0;
205be20aa9dSChris Mason 	int level;
2065d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
207be20aa9dSChris Mason 
20892a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2090b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
21092a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
21127cdeb70SMiao Xie 		trans->transid != root->last_trans);
212be20aa9dSChris Mason 
213be20aa9dSChris Mason 	level = btrfs_header_level(buf);
2145d4f98a2SYan Zheng 	if (level == 0)
2155d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
2165d4f98a2SYan Zheng 	else
2175d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
21831840ae1SZheng Yan 
2194d75f8a9SDavid Sterba 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
220cf6f34aaSJosef Bacik 				     &disk_key, level, buf->start, 0,
221cf6f34aaSJosef Bacik 				     BTRFS_NESTING_NEW_ROOT);
2225d4f98a2SYan Zheng 	if (IS_ERR(cow))
223be20aa9dSChris Mason 		return PTR_ERR(cow);
224be20aa9dSChris Mason 
22558e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
226be20aa9dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
227be20aa9dSChris Mason 	btrfs_set_header_generation(cow, trans->transid);
2285d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
2295d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
2305d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
2315d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
2325d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
2335d4f98a2SYan Zheng 	else
234be20aa9dSChris Mason 		btrfs_set_header_owner(cow, new_root_objectid);
235be20aa9dSChris Mason 
236de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
2372b82032cSYan Zheng 
238be20aa9dSChris Mason 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
2395d4f98a2SYan Zheng 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
240e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 1);
2415d4f98a2SYan Zheng 	else
242e339a6b0SJosef Bacik 		ret = btrfs_inc_ref(trans, root, cow, 0);
243867ed321SJosef Bacik 	if (ret) {
24472c9925fSFilipe Manana 		btrfs_tree_unlock(cow);
24572c9925fSFilipe Manana 		free_extent_buffer(cow);
246867ed321SJosef Bacik 		btrfs_abort_transaction(trans, ret);
247be20aa9dSChris Mason 		return ret;
248867ed321SJosef Bacik 	}
249be20aa9dSChris Mason 
250be20aa9dSChris Mason 	btrfs_mark_buffer_dirty(cow);
251be20aa9dSChris Mason 	*cow_ret = cow;
252be20aa9dSChris Mason 	return 0;
253be20aa9dSChris Mason }
254be20aa9dSChris Mason 
255d352ac68SChris Mason /*
2565d4f98a2SYan Zheng  * check if the tree block can be shared by multiple trees
2575d4f98a2SYan Zheng  */
2585d4f98a2SYan Zheng int btrfs_block_can_be_shared(struct btrfs_root *root,
2595d4f98a2SYan Zheng 			      struct extent_buffer *buf)
2605d4f98a2SYan Zheng {
2615d4f98a2SYan Zheng 	/*
26292a7cc42SQu Wenruo 	 * Tree blocks not in shareable trees and tree roots are never shared.
26392a7cc42SQu Wenruo 	 * If a block was allocated after the last snapshot and the block was
26492a7cc42SQu Wenruo 	 * not allocated by tree relocation, we know the block is not shared.
2655d4f98a2SYan Zheng 	 */
26692a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
2675d4f98a2SYan Zheng 	    buf != root->node && buf != root->commit_root &&
2685d4f98a2SYan Zheng 	    (btrfs_header_generation(buf) <=
2695d4f98a2SYan Zheng 	     btrfs_root_last_snapshot(&root->root_item) ||
2705d4f98a2SYan Zheng 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
2715d4f98a2SYan Zheng 		return 1;
272a79865c6SNikolay Borisov 
2735d4f98a2SYan Zheng 	return 0;
2745d4f98a2SYan Zheng }
2755d4f98a2SYan Zheng 
2765d4f98a2SYan Zheng static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
2775d4f98a2SYan Zheng 				       struct btrfs_root *root,
2785d4f98a2SYan Zheng 				       struct extent_buffer *buf,
279f0486c68SYan, Zheng 				       struct extent_buffer *cow,
280f0486c68SYan, Zheng 				       int *last_ref)
2815d4f98a2SYan Zheng {
2820b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2835d4f98a2SYan Zheng 	u64 refs;
2845d4f98a2SYan Zheng 	u64 owner;
2855d4f98a2SYan Zheng 	u64 flags;
2865d4f98a2SYan Zheng 	u64 new_flags = 0;
2875d4f98a2SYan Zheng 	int ret;
2885d4f98a2SYan Zheng 
2895d4f98a2SYan Zheng 	/*
2905d4f98a2SYan Zheng 	 * Backrefs update rules:
2915d4f98a2SYan Zheng 	 *
2925d4f98a2SYan Zheng 	 * Always use full backrefs for extent pointers in tree block
2935d4f98a2SYan Zheng 	 * allocated by tree relocation.
2945d4f98a2SYan Zheng 	 *
2955d4f98a2SYan Zheng 	 * If a shared tree block is no longer referenced by its owner
2965d4f98a2SYan Zheng 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
2975d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
2985d4f98a2SYan Zheng 	 *
2995d4f98a2SYan Zheng 	 * If a tree block is been relocating
3005d4f98a2SYan Zheng 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
3015d4f98a2SYan Zheng 	 * use full backrefs for extent pointers in tree block.
3025d4f98a2SYan Zheng 	 * The reason for this is some operations (such as drop tree)
3035d4f98a2SYan Zheng 	 * are only allowed for blocks use full backrefs.
3045d4f98a2SYan Zheng 	 */
3055d4f98a2SYan Zheng 
3065d4f98a2SYan Zheng 	if (btrfs_block_can_be_shared(root, buf)) {
3072ff7e61eSJeff Mahoney 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
3083173a18fSJosef Bacik 					       btrfs_header_level(buf), 1,
3093173a18fSJosef Bacik 					       &refs, &flags);
310be1a5564SMark Fasheh 		if (ret)
311be1a5564SMark Fasheh 			return ret;
312e5df9573SMark Fasheh 		if (refs == 0) {
313e5df9573SMark Fasheh 			ret = -EROFS;
3140b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
315e5df9573SMark Fasheh 			return ret;
316e5df9573SMark Fasheh 		}
3175d4f98a2SYan Zheng 	} else {
3185d4f98a2SYan Zheng 		refs = 1;
3195d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
3205d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
3215d4f98a2SYan Zheng 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
3225d4f98a2SYan Zheng 		else
3235d4f98a2SYan Zheng 			flags = 0;
3245d4f98a2SYan Zheng 	}
3255d4f98a2SYan Zheng 
3265d4f98a2SYan Zheng 	owner = btrfs_header_owner(buf);
3275d4f98a2SYan Zheng 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
3285d4f98a2SYan Zheng 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
3295d4f98a2SYan Zheng 
3305d4f98a2SYan Zheng 	if (refs > 1) {
3315d4f98a2SYan Zheng 		if ((owner == root->root_key.objectid ||
3325d4f98a2SYan Zheng 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
3335d4f98a2SYan Zheng 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
334e339a6b0SJosef Bacik 			ret = btrfs_inc_ref(trans, root, buf, 1);
335692826b2SJeff Mahoney 			if (ret)
336692826b2SJeff Mahoney 				return ret;
3375d4f98a2SYan Zheng 
3385d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3395d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID) {
340e339a6b0SJosef Bacik 				ret = btrfs_dec_ref(trans, root, buf, 0);
341692826b2SJeff Mahoney 				if (ret)
342692826b2SJeff Mahoney 					return ret;
343e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
344692826b2SJeff Mahoney 				if (ret)
345692826b2SJeff Mahoney 					return ret;
3465d4f98a2SYan Zheng 			}
3475d4f98a2SYan Zheng 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
3485d4f98a2SYan Zheng 		} else {
3495d4f98a2SYan Zheng 
3505d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3515d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
352e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3535d4f98a2SYan Zheng 			else
354e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
355692826b2SJeff Mahoney 			if (ret)
356692826b2SJeff Mahoney 				return ret;
3575d4f98a2SYan Zheng 		}
3585d4f98a2SYan Zheng 		if (new_flags != 0) {
359b1c79e09SJosef Bacik 			int level = btrfs_header_level(buf);
360b1c79e09SJosef Bacik 
36142c9d0b5SDavid Sterba 			ret = btrfs_set_disk_extent_flags(trans, buf,
3622fe6a5a1SDavid Sterba 							  new_flags, level);
363be1a5564SMark Fasheh 			if (ret)
364be1a5564SMark Fasheh 				return ret;
3655d4f98a2SYan Zheng 		}
3665d4f98a2SYan Zheng 	} else {
3675d4f98a2SYan Zheng 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
3685d4f98a2SYan Zheng 			if (root->root_key.objectid ==
3695d4f98a2SYan Zheng 			    BTRFS_TREE_RELOC_OBJECTID)
370e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 1);
3715d4f98a2SYan Zheng 			else
372e339a6b0SJosef Bacik 				ret = btrfs_inc_ref(trans, root, cow, 0);
373692826b2SJeff Mahoney 			if (ret)
374692826b2SJeff Mahoney 				return ret;
375e339a6b0SJosef Bacik 			ret = btrfs_dec_ref(trans, root, buf, 1);
376692826b2SJeff Mahoney 			if (ret)
377692826b2SJeff Mahoney 				return ret;
3785d4f98a2SYan Zheng 		}
3796a884d7dSDavid Sterba 		btrfs_clean_tree_block(buf);
380f0486c68SYan, Zheng 		*last_ref = 1;
3815d4f98a2SYan Zheng 	}
3825d4f98a2SYan Zheng 	return 0;
3835d4f98a2SYan Zheng }
3845d4f98a2SYan Zheng 
3855d4f98a2SYan Zheng /*
386d397712bSChris Mason  * does the dirty work in cow of a single block.  The parent block (if
387d397712bSChris Mason  * supplied) is updated to point to the new cow copy.  The new buffer is marked
388d397712bSChris Mason  * dirty and returned locked.  If you modify the block it needs to be marked
389d397712bSChris Mason  * dirty again.
390d352ac68SChris Mason  *
391d352ac68SChris Mason  * search_start -- an allocation hint for the new block
392d352ac68SChris Mason  *
393d397712bSChris Mason  * empty_size -- a hint that you plan on doing more cow.  This is the size in
394d397712bSChris Mason  * bytes the allocator should try to find free next to the block it returns.
395d397712bSChris Mason  * This is just a hint and may be ignored by the allocator.
396d352ac68SChris Mason  */
397d397712bSChris Mason static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
3985f39d397SChris Mason 			     struct btrfs_root *root,
3995f39d397SChris Mason 			     struct extent_buffer *buf,
4005f39d397SChris Mason 			     struct extent_buffer *parent, int parent_slot,
4015f39d397SChris Mason 			     struct extent_buffer **cow_ret,
4029631e4ccSJosef Bacik 			     u64 search_start, u64 empty_size,
4039631e4ccSJosef Bacik 			     enum btrfs_lock_nesting nest)
4046702ed49SChris Mason {
4050b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4065d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
4075f39d397SChris Mason 	struct extent_buffer *cow;
408be1a5564SMark Fasheh 	int level, ret;
409f0486c68SYan, Zheng 	int last_ref = 0;
410925baeddSChris Mason 	int unlock_orig = 0;
4110f5053ebSGoldwyn Rodrigues 	u64 parent_start = 0;
4126702ed49SChris Mason 
413925baeddSChris Mason 	if (*cow_ret == buf)
414925baeddSChris Mason 		unlock_orig = 1;
415925baeddSChris Mason 
41649d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(buf);
417925baeddSChris Mason 
41892a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
4190b246afaSJeff Mahoney 		trans->transid != fs_info->running_transaction->transid);
42092a7cc42SQu Wenruo 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
42127cdeb70SMiao Xie 		trans->transid != root->last_trans);
4225f39d397SChris Mason 
4237bb86316SChris Mason 	level = btrfs_header_level(buf);
42431840ae1SZheng Yan 
4255d4f98a2SYan Zheng 	if (level == 0)
4265d4f98a2SYan Zheng 		btrfs_item_key(buf, &disk_key, 0);
4275d4f98a2SYan Zheng 	else
4285d4f98a2SYan Zheng 		btrfs_node_key(buf, &disk_key, 0);
4295d4f98a2SYan Zheng 
4300f5053ebSGoldwyn Rodrigues 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
4315d4f98a2SYan Zheng 		parent_start = parent->start;
4325d4f98a2SYan Zheng 
43379bd3712SFilipe Manana 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
43479bd3712SFilipe Manana 				     root->root_key.objectid, &disk_key, level,
43579bd3712SFilipe Manana 				     search_start, empty_size, nest);
4366702ed49SChris Mason 	if (IS_ERR(cow))
4376702ed49SChris Mason 		return PTR_ERR(cow);
4386702ed49SChris Mason 
439b4ce94deSChris Mason 	/* cow is set to blocking by btrfs_init_new_buffer */
440b4ce94deSChris Mason 
44158e8012cSDavid Sterba 	copy_extent_buffer_full(cow, buf);
442db94535dSChris Mason 	btrfs_set_header_bytenr(cow, cow->start);
4435f39d397SChris Mason 	btrfs_set_header_generation(cow, trans->transid);
4445d4f98a2SYan Zheng 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
4455d4f98a2SYan Zheng 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
4465d4f98a2SYan Zheng 				     BTRFS_HEADER_FLAG_RELOC);
4475d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
4485d4f98a2SYan Zheng 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
4495d4f98a2SYan Zheng 	else
4505f39d397SChris Mason 		btrfs_set_header_owner(cow, root->root_key.objectid);
4516702ed49SChris Mason 
452de37aa51SNikolay Borisov 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
4532b82032cSYan Zheng 
454be1a5564SMark Fasheh 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
455b68dc2a9SMark Fasheh 	if (ret) {
456572c83acSJosef Bacik 		btrfs_tree_unlock(cow);
457572c83acSJosef Bacik 		free_extent_buffer(cow);
45866642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
459b68dc2a9SMark Fasheh 		return ret;
460b68dc2a9SMark Fasheh 	}
4611a40e23bSZheng Yan 
46292a7cc42SQu Wenruo 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
46383d4cfd4SJosef Bacik 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
46493314e3bSZhaolei 		if (ret) {
465572c83acSJosef Bacik 			btrfs_tree_unlock(cow);
466572c83acSJosef Bacik 			free_extent_buffer(cow);
46766642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
46883d4cfd4SJosef Bacik 			return ret;
46983d4cfd4SJosef Bacik 		}
47093314e3bSZhaolei 	}
4713fd0a558SYan, Zheng 
4726702ed49SChris Mason 	if (buf == root->node) {
473925baeddSChris Mason 		WARN_ON(parent && parent != buf);
4745d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4755d4f98a2SYan Zheng 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4765d4f98a2SYan Zheng 			parent_start = buf->start;
477925baeddSChris Mason 
47867439dadSDavid Sterba 		atomic_inc(&cow->refs);
479406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
480d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
481240f62c8SChris Mason 		rcu_assign_pointer(root->node, cow);
482925baeddSChris Mason 
4837a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
4847a163608SFilipe Manana 				      parent_start, last_ref);
4855f39d397SChris Mason 		free_extent_buffer(buf);
4860b86a832SChris Mason 		add_root_to_dirty_list(root);
4876702ed49SChris Mason 	} else {
4885d4f98a2SYan Zheng 		WARN_ON(trans->transid != btrfs_header_generation(parent));
489f3a84ccdSFilipe Manana 		btrfs_tree_mod_log_insert_key(parent, parent_slot,
490f3a84ccdSFilipe Manana 					      BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
4915f39d397SChris Mason 		btrfs_set_node_blockptr(parent, parent_slot,
492db94535dSChris Mason 					cow->start);
49374493f7aSChris Mason 		btrfs_set_node_ptr_generation(parent, parent_slot,
49474493f7aSChris Mason 					      trans->transid);
4956702ed49SChris Mason 		btrfs_mark_buffer_dirty(parent);
4965de865eeSFilipe David Borba Manana 		if (last_ref) {
497f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_free_eb(buf);
4985de865eeSFilipe David Borba Manana 			if (ret) {
499572c83acSJosef Bacik 				btrfs_tree_unlock(cow);
500572c83acSJosef Bacik 				free_extent_buffer(cow);
50166642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
5025de865eeSFilipe David Borba Manana 				return ret;
5035de865eeSFilipe David Borba Manana 			}
5045de865eeSFilipe David Borba Manana 		}
5057a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
5067a163608SFilipe Manana 				      parent_start, last_ref);
5076702ed49SChris Mason 	}
508925baeddSChris Mason 	if (unlock_orig)
509925baeddSChris Mason 		btrfs_tree_unlock(buf);
5103083ee2eSJosef Bacik 	free_extent_buffer_stale(buf);
5116702ed49SChris Mason 	btrfs_mark_buffer_dirty(cow);
5126702ed49SChris Mason 	*cow_ret = cow;
5136702ed49SChris Mason 	return 0;
5146702ed49SChris Mason }
5156702ed49SChris Mason 
5165d4f98a2SYan Zheng static inline int should_cow_block(struct btrfs_trans_handle *trans,
5175d4f98a2SYan Zheng 				   struct btrfs_root *root,
5185d4f98a2SYan Zheng 				   struct extent_buffer *buf)
5195d4f98a2SYan Zheng {
520f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(root->fs_info))
521faa2dbf0SJosef Bacik 		return 0;
522fccb84c9SDavid Sterba 
523d1980131SDavid Sterba 	/* Ensure we can see the FORCE_COW bit */
524d1980131SDavid Sterba 	smp_mb__before_atomic();
525f1ebcc74SLiu Bo 
526f1ebcc74SLiu Bo 	/*
527f1ebcc74SLiu Bo 	 * We do not need to cow a block if
528f1ebcc74SLiu Bo 	 * 1) this block is not created or changed in this transaction;
529f1ebcc74SLiu Bo 	 * 2) this block does not belong to TREE_RELOC tree;
530f1ebcc74SLiu Bo 	 * 3) the root is not forced COW.
531f1ebcc74SLiu Bo 	 *
532f1ebcc74SLiu Bo 	 * What is forced COW:
53301327610SNicholas D Steeves 	 *    when we create snapshot during committing the transaction,
53452042d8eSAndrea Gelmini 	 *    after we've finished copying src root, we must COW the shared
535f1ebcc74SLiu Bo 	 *    block to ensure the metadata consistency.
536f1ebcc74SLiu Bo 	 */
5375d4f98a2SYan Zheng 	if (btrfs_header_generation(buf) == trans->transid &&
5385d4f98a2SYan Zheng 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
5395d4f98a2SYan Zheng 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
540f1ebcc74SLiu Bo 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
54127cdeb70SMiao Xie 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
5425d4f98a2SYan Zheng 		return 0;
5435d4f98a2SYan Zheng 	return 1;
5445d4f98a2SYan Zheng }
5455d4f98a2SYan Zheng 
546d352ac68SChris Mason /*
547d352ac68SChris Mason  * cows a single block, see __btrfs_cow_block for the real work.
54801327610SNicholas D Steeves  * This version of it has extra checks so that a block isn't COWed more than
549d352ac68SChris Mason  * once per transaction, as long as it hasn't been written yet
550d352ac68SChris Mason  */
551d397712bSChris Mason noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
5525f39d397SChris Mason 		    struct btrfs_root *root, struct extent_buffer *buf,
5535f39d397SChris Mason 		    struct extent_buffer *parent, int parent_slot,
5549631e4ccSJosef Bacik 		    struct extent_buffer **cow_ret,
5559631e4ccSJosef Bacik 		    enum btrfs_lock_nesting nest)
55602217ed2SChris Mason {
5570b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5586702ed49SChris Mason 	u64 search_start;
559f510cfecSChris Mason 	int ret;
560dc17ff8fSChris Mason 
56183354f07SJosef Bacik 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
56283354f07SJosef Bacik 		btrfs_err(fs_info,
56383354f07SJosef Bacik 			"COW'ing blocks on a fs root that's being dropped");
56483354f07SJosef Bacik 
5650b246afaSJeff Mahoney 	if (trans->transaction != fs_info->running_transaction)
56631b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
567c1c9ff7cSGeert Uytterhoeven 		       trans->transid,
5680b246afaSJeff Mahoney 		       fs_info->running_transaction->transid);
56931b1a2bdSJulia Lawall 
5700b246afaSJeff Mahoney 	if (trans->transid != fs_info->generation)
57131b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
5720b246afaSJeff Mahoney 		       trans->transid, fs_info->generation);
573dc17ff8fSChris Mason 
5745d4f98a2SYan Zheng 	if (!should_cow_block(trans, root, buf)) {
57502217ed2SChris Mason 		*cow_ret = buf;
57602217ed2SChris Mason 		return 0;
57702217ed2SChris Mason 	}
578c487685dSChris Mason 
579ee22184bSByongho Lee 	search_start = buf->start & ~((u64)SZ_1G - 1);
580b4ce94deSChris Mason 
581f616f5cdSQu Wenruo 	/*
582f616f5cdSQu Wenruo 	 * Before CoWing this block for later modification, check if it's
583f616f5cdSQu Wenruo 	 * the subtree root and do the delayed subtree trace if needed.
584f616f5cdSQu Wenruo 	 *
585f616f5cdSQu Wenruo 	 * Also We don't care about the error, as it's handled internally.
586f616f5cdSQu Wenruo 	 */
587f616f5cdSQu Wenruo 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
588f510cfecSChris Mason 	ret = __btrfs_cow_block(trans, root, buf, parent,
5899631e4ccSJosef Bacik 				 parent_slot, cow_ret, search_start, 0, nest);
5901abe9b8aSliubo 
5911abe9b8aSliubo 	trace_btrfs_cow_block(root, buf, *cow_ret);
5921abe9b8aSliubo 
593f510cfecSChris Mason 	return ret;
5942c90e5d6SChris Mason }
595f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
5966702ed49SChris Mason 
597d352ac68SChris Mason /*
598d352ac68SChris Mason  * helper function for defrag to decide if two blocks pointed to by a
599d352ac68SChris Mason  * node are actually close by
600d352ac68SChris Mason  */
6016b80053dSChris Mason static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
6026702ed49SChris Mason {
6036b80053dSChris Mason 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
6046702ed49SChris Mason 		return 1;
6056b80053dSChris Mason 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
6066702ed49SChris Mason 		return 1;
60702217ed2SChris Mason 	return 0;
60802217ed2SChris Mason }
60902217ed2SChris Mason 
610ce6ef5abSDavid Sterba #ifdef __LITTLE_ENDIAN
611ce6ef5abSDavid Sterba 
612ce6ef5abSDavid Sterba /*
613ce6ef5abSDavid Sterba  * Compare two keys, on little-endian the disk order is same as CPU order and
614ce6ef5abSDavid Sterba  * we can avoid the conversion.
615ce6ef5abSDavid Sterba  */
616ce6ef5abSDavid Sterba static int comp_keys(const struct btrfs_disk_key *disk_key,
617ce6ef5abSDavid Sterba 		     const struct btrfs_key *k2)
618ce6ef5abSDavid Sterba {
619ce6ef5abSDavid Sterba 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
620ce6ef5abSDavid Sterba 
621ce6ef5abSDavid Sterba 	return btrfs_comp_cpu_keys(k1, k2);
622ce6ef5abSDavid Sterba }
623ce6ef5abSDavid Sterba 
624ce6ef5abSDavid Sterba #else
625ce6ef5abSDavid Sterba 
626081e9573SChris Mason /*
627081e9573SChris Mason  * compare two keys in a memcmp fashion
628081e9573SChris Mason  */
629310712b2SOmar Sandoval static int comp_keys(const struct btrfs_disk_key *disk,
630310712b2SOmar Sandoval 		     const struct btrfs_key *k2)
631081e9573SChris Mason {
632081e9573SChris Mason 	struct btrfs_key k1;
633081e9573SChris Mason 
634081e9573SChris Mason 	btrfs_disk_key_to_cpu(&k1, disk);
635081e9573SChris Mason 
63620736abaSDiego Calleja 	return btrfs_comp_cpu_keys(&k1, k2);
637081e9573SChris Mason }
638ce6ef5abSDavid Sterba #endif
639081e9573SChris Mason 
640f3465ca4SJosef Bacik /*
641f3465ca4SJosef Bacik  * same as comp_keys only with two btrfs_key's
642f3465ca4SJosef Bacik  */
643e1f60a65SDavid Sterba int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
644f3465ca4SJosef Bacik {
645f3465ca4SJosef Bacik 	if (k1->objectid > k2->objectid)
646f3465ca4SJosef Bacik 		return 1;
647f3465ca4SJosef Bacik 	if (k1->objectid < k2->objectid)
648f3465ca4SJosef Bacik 		return -1;
649f3465ca4SJosef Bacik 	if (k1->type > k2->type)
650f3465ca4SJosef Bacik 		return 1;
651f3465ca4SJosef Bacik 	if (k1->type < k2->type)
652f3465ca4SJosef Bacik 		return -1;
653f3465ca4SJosef Bacik 	if (k1->offset > k2->offset)
654f3465ca4SJosef Bacik 		return 1;
655f3465ca4SJosef Bacik 	if (k1->offset < k2->offset)
656f3465ca4SJosef Bacik 		return -1;
657f3465ca4SJosef Bacik 	return 0;
658f3465ca4SJosef Bacik }
659081e9573SChris Mason 
660d352ac68SChris Mason /*
661d352ac68SChris Mason  * this is used by the defrag code to go through all the
662d352ac68SChris Mason  * leaves pointed to by a node and reallocate them so that
663d352ac68SChris Mason  * disk order is close to key order
664d352ac68SChris Mason  */
6656702ed49SChris Mason int btrfs_realloc_node(struct btrfs_trans_handle *trans,
6665f39d397SChris Mason 		       struct btrfs_root *root, struct extent_buffer *parent,
667de78b51aSEric Sandeen 		       int start_slot, u64 *last_ret,
668a6b6e75eSChris Mason 		       struct btrfs_key *progress)
6696702ed49SChris Mason {
6700b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6716b80053dSChris Mason 	struct extent_buffer *cur;
6726702ed49SChris Mason 	u64 blocknr;
673e9d0b13bSChris Mason 	u64 search_start = *last_ret;
674e9d0b13bSChris Mason 	u64 last_block = 0;
6756702ed49SChris Mason 	u64 other;
6766702ed49SChris Mason 	u32 parent_nritems;
6776702ed49SChris Mason 	int end_slot;
6786702ed49SChris Mason 	int i;
6796702ed49SChris Mason 	int err = 0;
6806b80053dSChris Mason 	u32 blocksize;
681081e9573SChris Mason 	int progress_passed = 0;
682081e9573SChris Mason 	struct btrfs_disk_key disk_key;
6836702ed49SChris Mason 
6840b246afaSJeff Mahoney 	WARN_ON(trans->transaction != fs_info->running_transaction);
6850b246afaSJeff Mahoney 	WARN_ON(trans->transid != fs_info->generation);
68686479a04SChris Mason 
6876b80053dSChris Mason 	parent_nritems = btrfs_header_nritems(parent);
6880b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
6895dfe2be7SFilipe Manana 	end_slot = parent_nritems - 1;
6906702ed49SChris Mason 
6915dfe2be7SFilipe Manana 	if (parent_nritems <= 1)
6926702ed49SChris Mason 		return 0;
6936702ed49SChris Mason 
6945dfe2be7SFilipe Manana 	for (i = start_slot; i <= end_slot; i++) {
6956702ed49SChris Mason 		int close = 1;
696a6b6e75eSChris Mason 
697081e9573SChris Mason 		btrfs_node_key(parent, &disk_key, i);
698081e9573SChris Mason 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
699081e9573SChris Mason 			continue;
700081e9573SChris Mason 
701081e9573SChris Mason 		progress_passed = 1;
7026b80053dSChris Mason 		blocknr = btrfs_node_blockptr(parent, i);
703e9d0b13bSChris Mason 		if (last_block == 0)
704e9d0b13bSChris Mason 			last_block = blocknr;
7055708b959SChris Mason 
7066702ed49SChris Mason 		if (i > 0) {
7076b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i - 1);
7086b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
7096702ed49SChris Mason 		}
7105dfe2be7SFilipe Manana 		if (!close && i < end_slot) {
7116b80053dSChris Mason 			other = btrfs_node_blockptr(parent, i + 1);
7126b80053dSChris Mason 			close = close_blocks(blocknr, other, blocksize);
7136702ed49SChris Mason 		}
714e9d0b13bSChris Mason 		if (close) {
715e9d0b13bSChris Mason 			last_block = blocknr;
7166702ed49SChris Mason 			continue;
717e9d0b13bSChris Mason 		}
7186702ed49SChris Mason 
719206983b7SJosef Bacik 		cur = btrfs_read_node_slot(parent, i);
720206983b7SJosef Bacik 		if (IS_ERR(cur))
72164c043deSLiu Bo 			return PTR_ERR(cur);
722e9d0b13bSChris Mason 		if (search_start == 0)
7236b80053dSChris Mason 			search_start = last_block;
724e9d0b13bSChris Mason 
725e7a84565SChris Mason 		btrfs_tree_lock(cur);
7266b80053dSChris Mason 		err = __btrfs_cow_block(trans, root, cur, parent, i,
727e7a84565SChris Mason 					&cur, search_start,
7286b80053dSChris Mason 					min(16 * blocksize,
7299631e4ccSJosef Bacik 					    (end_slot - i) * blocksize),
7309631e4ccSJosef Bacik 					BTRFS_NESTING_COW);
731252c38f0SYan 		if (err) {
732e7a84565SChris Mason 			btrfs_tree_unlock(cur);
7336b80053dSChris Mason 			free_extent_buffer(cur);
7346702ed49SChris Mason 			break;
735252c38f0SYan 		}
736e7a84565SChris Mason 		search_start = cur->start;
737e7a84565SChris Mason 		last_block = cur->start;
738f2183bdeSChris Mason 		*last_ret = search_start;
739e7a84565SChris Mason 		btrfs_tree_unlock(cur);
740e7a84565SChris Mason 		free_extent_buffer(cur);
7416702ed49SChris Mason 	}
7426702ed49SChris Mason 	return err;
7436702ed49SChris Mason }
7446702ed49SChris Mason 
74574123bd7SChris Mason /*
746fb81212cSFilipe Manana  * Search for a key in the given extent_buffer.
7475f39d397SChris Mason  *
748fb81212cSFilipe Manana  * The lower boundary for the search is specified by the slot number @low. Use a
749fb81212cSFilipe Manana  * value of 0 to search over the whole extent buffer.
75074123bd7SChris Mason  *
751fb81212cSFilipe Manana  * The slot in the extent buffer is returned via @slot. If the key exists in the
752fb81212cSFilipe Manana  * extent buffer, then @slot will point to the slot where the key is, otherwise
753fb81212cSFilipe Manana  * it points to the slot where you would insert the key.
754fb81212cSFilipe Manana  *
755fb81212cSFilipe Manana  * Slot may point to the total number of items (i.e. one position beyond the last
756fb81212cSFilipe Manana  * key) if the key is bigger than the last key in the extent buffer.
75774123bd7SChris Mason  */
758fb81212cSFilipe Manana static noinline int generic_bin_search(struct extent_buffer *eb, int low,
75967d5e289SMarcos Paulo de Souza 				       const struct btrfs_key *key, int *slot)
760be0e5c09SChris Mason {
761fb81212cSFilipe Manana 	unsigned long p;
762fb81212cSFilipe Manana 	int item_size;
76367d5e289SMarcos Paulo de Souza 	int high = btrfs_header_nritems(eb);
764be0e5c09SChris Mason 	int ret;
7655cd17f34SDavid Sterba 	const int key_size = sizeof(struct btrfs_disk_key);
766be0e5c09SChris Mason 
7675e24e9afSLiu Bo 	if (low > high) {
7685e24e9afSLiu Bo 		btrfs_err(eb->fs_info,
7695e24e9afSLiu Bo 		 "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
7705e24e9afSLiu Bo 			  __func__, low, high, eb->start,
7715e24e9afSLiu Bo 			  btrfs_header_owner(eb), btrfs_header_level(eb));
7725e24e9afSLiu Bo 		return -EINVAL;
7735e24e9afSLiu Bo 	}
7745e24e9afSLiu Bo 
775fb81212cSFilipe Manana 	if (btrfs_header_level(eb) == 0) {
776fb81212cSFilipe Manana 		p = offsetof(struct btrfs_leaf, items);
777fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_item);
778fb81212cSFilipe Manana 	} else {
779fb81212cSFilipe Manana 		p = offsetof(struct btrfs_node, ptrs);
780fb81212cSFilipe Manana 		item_size = sizeof(struct btrfs_key_ptr);
781fb81212cSFilipe Manana 	}
782fb81212cSFilipe Manana 
783be0e5c09SChris Mason 	while (low < high) {
7845cd17f34SDavid Sterba 		unsigned long oip;
7855cd17f34SDavid Sterba 		unsigned long offset;
7865cd17f34SDavid Sterba 		struct btrfs_disk_key *tmp;
7875cd17f34SDavid Sterba 		struct btrfs_disk_key unaligned;
7885cd17f34SDavid Sterba 		int mid;
7895cd17f34SDavid Sterba 
790be0e5c09SChris Mason 		mid = (low + high) / 2;
7915f39d397SChris Mason 		offset = p + mid * item_size;
7925cd17f34SDavid Sterba 		oip = offset_in_page(offset);
7935f39d397SChris Mason 
7945cd17f34SDavid Sterba 		if (oip + key_size <= PAGE_SIZE) {
795884b07d0SQu Wenruo 			const unsigned long idx = get_eb_page_index(offset);
7965cd17f34SDavid Sterba 			char *kaddr = page_address(eb->pages[idx]);
797934d375bSChris Mason 
798884b07d0SQu Wenruo 			oip = get_eb_offset_in_page(eb, offset);
7995cd17f34SDavid Sterba 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
8005cd17f34SDavid Sterba 		} else {
8015cd17f34SDavid Sterba 			read_extent_buffer(eb, &unaligned, offset, key_size);
8025f39d397SChris Mason 			tmp = &unaligned;
803479965d6SChris Mason 		}
804479965d6SChris Mason 
805be0e5c09SChris Mason 		ret = comp_keys(tmp, key);
806be0e5c09SChris Mason 
807be0e5c09SChris Mason 		if (ret < 0)
808be0e5c09SChris Mason 			low = mid + 1;
809be0e5c09SChris Mason 		else if (ret > 0)
810be0e5c09SChris Mason 			high = mid;
811be0e5c09SChris Mason 		else {
812be0e5c09SChris Mason 			*slot = mid;
813be0e5c09SChris Mason 			return 0;
814be0e5c09SChris Mason 		}
815be0e5c09SChris Mason 	}
816be0e5c09SChris Mason 	*slot = low;
817be0e5c09SChris Mason 	return 1;
818be0e5c09SChris Mason }
819be0e5c09SChris Mason 
82097571fd0SChris Mason /*
821fb81212cSFilipe Manana  * Simple binary search on an extent buffer. Works for both leaves and nodes, and
822fb81212cSFilipe Manana  * always searches over the whole range of keys (slot 0 to slot 'nritems - 1').
82397571fd0SChris Mason  */
824a74b35ecSNikolay Borisov int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
825e3b83361SQu Wenruo 		     int *slot)
826be0e5c09SChris Mason {
827fb81212cSFilipe Manana 	return generic_bin_search(eb, 0, key, slot);
828be0e5c09SChris Mason }
829be0e5c09SChris Mason 
830f0486c68SYan, Zheng static void root_add_used(struct btrfs_root *root, u32 size)
831f0486c68SYan, Zheng {
832f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
833f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
834f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) + size);
835f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
836f0486c68SYan, Zheng }
837f0486c68SYan, Zheng 
838f0486c68SYan, Zheng static void root_sub_used(struct btrfs_root *root, u32 size)
839f0486c68SYan, Zheng {
840f0486c68SYan, Zheng 	spin_lock(&root->accounting_lock);
841f0486c68SYan, Zheng 	btrfs_set_root_used(&root->root_item,
842f0486c68SYan, Zheng 			    btrfs_root_used(&root->root_item) - size);
843f0486c68SYan, Zheng 	spin_unlock(&root->accounting_lock);
844f0486c68SYan, Zheng }
845f0486c68SYan, Zheng 
846d352ac68SChris Mason /* given a node and slot number, this reads the blocks it points to.  The
847d352ac68SChris Mason  * extent buffer is returned with a reference taken (but unlocked).
848d352ac68SChris Mason  */
8494b231ae4SDavid Sterba struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
8504b231ae4SDavid Sterba 					   int slot)
851bb803951SChris Mason {
852ca7a79adSChris Mason 	int level = btrfs_header_level(parent);
853416bc658SJosef Bacik 	struct extent_buffer *eb;
854581c1760SQu Wenruo 	struct btrfs_key first_key;
855416bc658SJosef Bacik 
856fb770ae4SLiu Bo 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
857fb770ae4SLiu Bo 		return ERR_PTR(-ENOENT);
858ca7a79adSChris Mason 
859ca7a79adSChris Mason 	BUG_ON(level == 0);
860ca7a79adSChris Mason 
861581c1760SQu Wenruo 	btrfs_node_key_to_cpu(parent, &first_key, slot);
862d0d20b0fSDavid Sterba 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
8631b7ec85eSJosef Bacik 			     btrfs_header_owner(parent),
864581c1760SQu Wenruo 			     btrfs_node_ptr_generation(parent, slot),
865581c1760SQu Wenruo 			     level - 1, &first_key);
8664eb150d6SQu Wenruo 	if (IS_ERR(eb))
8674eb150d6SQu Wenruo 		return eb;
8684eb150d6SQu Wenruo 	if (!extent_buffer_uptodate(eb)) {
869416bc658SJosef Bacik 		free_extent_buffer(eb);
8704eb150d6SQu Wenruo 		return ERR_PTR(-EIO);
871416bc658SJosef Bacik 	}
872416bc658SJosef Bacik 
873416bc658SJosef Bacik 	return eb;
874bb803951SChris Mason }
875bb803951SChris Mason 
876d352ac68SChris Mason /*
877d352ac68SChris Mason  * node level balancing, used to make sure nodes are in proper order for
878d352ac68SChris Mason  * item deletion.  We balance from the top down, so we have to make sure
879d352ac68SChris Mason  * that a deletion won't leave an node completely empty later on.
880d352ac68SChris Mason  */
881e02119d5SChris Mason static noinline int balance_level(struct btrfs_trans_handle *trans,
88298ed5174SChris Mason 			 struct btrfs_root *root,
88398ed5174SChris Mason 			 struct btrfs_path *path, int level)
884bb803951SChris Mason {
8850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8865f39d397SChris Mason 	struct extent_buffer *right = NULL;
8875f39d397SChris Mason 	struct extent_buffer *mid;
8885f39d397SChris Mason 	struct extent_buffer *left = NULL;
8895f39d397SChris Mason 	struct extent_buffer *parent = NULL;
890bb803951SChris Mason 	int ret = 0;
891bb803951SChris Mason 	int wret;
892bb803951SChris Mason 	int pslot;
893bb803951SChris Mason 	int orig_slot = path->slots[level];
89479f95c82SChris Mason 	u64 orig_ptr;
895bb803951SChris Mason 
89698e6b1ebSLiu Bo 	ASSERT(level > 0);
897bb803951SChris Mason 
8985f39d397SChris Mason 	mid = path->nodes[level];
899b4ce94deSChris Mason 
900ac5887c8SJosef Bacik 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
9017bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
9027bb86316SChris Mason 
9031d4f8a0cSChris Mason 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
90479f95c82SChris Mason 
905a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
9065f39d397SChris Mason 		parent = path->nodes[level + 1];
907bb803951SChris Mason 		pslot = path->slots[level + 1];
908a05a9bb1SLi Zefan 	}
909bb803951SChris Mason 
91040689478SChris Mason 	/*
91140689478SChris Mason 	 * deal with the case where there is only one pointer in the root
91240689478SChris Mason 	 * by promoting the node below to a root
91340689478SChris Mason 	 */
9145f39d397SChris Mason 	if (!parent) {
9155f39d397SChris Mason 		struct extent_buffer *child;
916bb803951SChris Mason 
9175f39d397SChris Mason 		if (btrfs_header_nritems(mid) != 1)
918bb803951SChris Mason 			return 0;
919bb803951SChris Mason 
920bb803951SChris Mason 		/* promote the child to a root */
9214b231ae4SDavid Sterba 		child = btrfs_read_node_slot(mid, 0);
922fb770ae4SLiu Bo 		if (IS_ERR(child)) {
923fb770ae4SLiu Bo 			ret = PTR_ERR(child);
9240b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
925305a26afSMark Fasheh 			goto enospc;
926305a26afSMark Fasheh 		}
927305a26afSMark Fasheh 
928925baeddSChris Mason 		btrfs_tree_lock(child);
9299631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
9309631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
931f0486c68SYan, Zheng 		if (ret) {
932f0486c68SYan, Zheng 			btrfs_tree_unlock(child);
933f0486c68SYan, Zheng 			free_extent_buffer(child);
934f0486c68SYan, Zheng 			goto enospc;
935f0486c68SYan, Zheng 		}
9362f375ab9SYan 
937406808abSFilipe Manana 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
938d9d19a01SDavid Sterba 		BUG_ON(ret < 0);
939240f62c8SChris Mason 		rcu_assign_pointer(root->node, child);
940925baeddSChris Mason 
9410b86a832SChris Mason 		add_root_to_dirty_list(root);
942925baeddSChris Mason 		btrfs_tree_unlock(child);
943b4ce94deSChris Mason 
944925baeddSChris Mason 		path->locks[level] = 0;
945bb803951SChris Mason 		path->nodes[level] = NULL;
9466a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
947925baeddSChris Mason 		btrfs_tree_unlock(mid);
948bb803951SChris Mason 		/* once for the path */
9495f39d397SChris Mason 		free_extent_buffer(mid);
950f0486c68SYan, Zheng 
951f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
9527a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
953bb803951SChris Mason 		/* once for the root ptr */
9543083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
955f0486c68SYan, Zheng 		return 0;
956bb803951SChris Mason 	}
9575f39d397SChris Mason 	if (btrfs_header_nritems(mid) >
9580b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
959bb803951SChris Mason 		return 0;
960bb803951SChris Mason 
9614b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
962fb770ae4SLiu Bo 	if (IS_ERR(left))
963fb770ae4SLiu Bo 		left = NULL;
964fb770ae4SLiu Bo 
9655f39d397SChris Mason 	if (left) {
966bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
9675f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, left,
9689631e4ccSJosef Bacik 				       parent, pslot - 1, &left,
969bf59a5a2SJosef Bacik 				       BTRFS_NESTING_LEFT_COW);
97054aa1f4dSChris Mason 		if (wret) {
97154aa1f4dSChris Mason 			ret = wret;
97254aa1f4dSChris Mason 			goto enospc;
97354aa1f4dSChris Mason 		}
9742cc58cf2SChris Mason 	}
975fb770ae4SLiu Bo 
9764b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
977fb770ae4SLiu Bo 	if (IS_ERR(right))
978fb770ae4SLiu Bo 		right = NULL;
979fb770ae4SLiu Bo 
9805f39d397SChris Mason 	if (right) {
981bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
9825f39d397SChris Mason 		wret = btrfs_cow_block(trans, root, right,
9839631e4ccSJosef Bacik 				       parent, pslot + 1, &right,
984bf59a5a2SJosef Bacik 				       BTRFS_NESTING_RIGHT_COW);
9852cc58cf2SChris Mason 		if (wret) {
9862cc58cf2SChris Mason 			ret = wret;
9872cc58cf2SChris Mason 			goto enospc;
9882cc58cf2SChris Mason 		}
9892cc58cf2SChris Mason 	}
9902cc58cf2SChris Mason 
9912cc58cf2SChris Mason 	/* first, try to make some room in the middle buffer */
9925f39d397SChris Mason 	if (left) {
9935f39d397SChris Mason 		orig_slot += btrfs_header_nritems(left);
994d30a668fSDavid Sterba 		wret = push_node_left(trans, left, mid, 1);
99579f95c82SChris Mason 		if (wret < 0)
99679f95c82SChris Mason 			ret = wret;
997bb803951SChris Mason 	}
99879f95c82SChris Mason 
99979f95c82SChris Mason 	/*
100079f95c82SChris Mason 	 * then try to empty the right most buffer into the middle
100179f95c82SChris Mason 	 */
10025f39d397SChris Mason 	if (right) {
1003d30a668fSDavid Sterba 		wret = push_node_left(trans, mid, right, 1);
100454aa1f4dSChris Mason 		if (wret < 0 && wret != -ENOSPC)
100579f95c82SChris Mason 			ret = wret;
10065f39d397SChris Mason 		if (btrfs_header_nritems(right) == 0) {
10076a884d7dSDavid Sterba 			btrfs_clean_tree_block(right);
1008925baeddSChris Mason 			btrfs_tree_unlock(right);
1009afe5fea7STsutomu Itoh 			del_ptr(root, path, level + 1, pslot + 1);
1010f0486c68SYan, Zheng 			root_sub_used(root, right->len);
10117a163608SFilipe Manana 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
10127a163608SFilipe Manana 					      0, 1);
10133083ee2eSJosef Bacik 			free_extent_buffer_stale(right);
1014f0486c68SYan, Zheng 			right = NULL;
1015bb803951SChris Mason 		} else {
10165f39d397SChris Mason 			struct btrfs_disk_key right_key;
10175f39d397SChris Mason 			btrfs_node_key(right, &right_key, 0);
1018f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1019f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
10200e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
10215f39d397SChris Mason 			btrfs_set_node_key(parent, &right_key, pslot + 1);
10225f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
1023bb803951SChris Mason 		}
1024bb803951SChris Mason 	}
10255f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 1) {
102679f95c82SChris Mason 		/*
102779f95c82SChris Mason 		 * we're not allowed to leave a node with one item in the
102879f95c82SChris Mason 		 * tree during a delete.  A deletion from lower in the tree
102979f95c82SChris Mason 		 * could try to delete the only pointer in this node.
103079f95c82SChris Mason 		 * So, pull some keys from the left.
103179f95c82SChris Mason 		 * There has to be a left pointer at this point because
103279f95c82SChris Mason 		 * otherwise we would have pulled some pointers from the
103379f95c82SChris Mason 		 * right
103479f95c82SChris Mason 		 */
1035305a26afSMark Fasheh 		if (!left) {
1036305a26afSMark Fasheh 			ret = -EROFS;
10370b246afaSJeff Mahoney 			btrfs_handle_fs_error(fs_info, ret, NULL);
1038305a26afSMark Fasheh 			goto enospc;
1039305a26afSMark Fasheh 		}
104055d32ed8SDavid Sterba 		wret = balance_node_right(trans, mid, left);
104154aa1f4dSChris Mason 		if (wret < 0) {
104279f95c82SChris Mason 			ret = wret;
104354aa1f4dSChris Mason 			goto enospc;
104454aa1f4dSChris Mason 		}
1045bce4eae9SChris Mason 		if (wret == 1) {
1046d30a668fSDavid Sterba 			wret = push_node_left(trans, left, mid, 1);
1047bce4eae9SChris Mason 			if (wret < 0)
1048bce4eae9SChris Mason 				ret = wret;
1049bce4eae9SChris Mason 		}
105079f95c82SChris Mason 		BUG_ON(wret == 1);
105179f95c82SChris Mason 	}
10525f39d397SChris Mason 	if (btrfs_header_nritems(mid) == 0) {
10536a884d7dSDavid Sterba 		btrfs_clean_tree_block(mid);
1054925baeddSChris Mason 		btrfs_tree_unlock(mid);
1055afe5fea7STsutomu Itoh 		del_ptr(root, path, level + 1, pslot);
1056f0486c68SYan, Zheng 		root_sub_used(root, mid->len);
10577a163608SFilipe Manana 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
10583083ee2eSJosef Bacik 		free_extent_buffer_stale(mid);
1059f0486c68SYan, Zheng 		mid = NULL;
106079f95c82SChris Mason 	} else {
106179f95c82SChris Mason 		/* update the parent key to reflect our changes */
10625f39d397SChris Mason 		struct btrfs_disk_key mid_key;
10635f39d397SChris Mason 		btrfs_node_key(mid, &mid_key, 0);
1064f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1065f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
10660e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
10675f39d397SChris Mason 		btrfs_set_node_key(parent, &mid_key, pslot);
10685f39d397SChris Mason 		btrfs_mark_buffer_dirty(parent);
106979f95c82SChris Mason 	}
1070bb803951SChris Mason 
107179f95c82SChris Mason 	/* update the path */
10725f39d397SChris Mason 	if (left) {
10735f39d397SChris Mason 		if (btrfs_header_nritems(left) > orig_slot) {
107467439dadSDavid Sterba 			atomic_inc(&left->refs);
1075925baeddSChris Mason 			/* left was locked after cow */
10765f39d397SChris Mason 			path->nodes[level] = left;
1077bb803951SChris Mason 			path->slots[level + 1] -= 1;
1078bb803951SChris Mason 			path->slots[level] = orig_slot;
1079925baeddSChris Mason 			if (mid) {
1080925baeddSChris Mason 				btrfs_tree_unlock(mid);
10815f39d397SChris Mason 				free_extent_buffer(mid);
1082925baeddSChris Mason 			}
1083bb803951SChris Mason 		} else {
10845f39d397SChris Mason 			orig_slot -= btrfs_header_nritems(left);
1085bb803951SChris Mason 			path->slots[level] = orig_slot;
1086bb803951SChris Mason 		}
1087bb803951SChris Mason 	}
108879f95c82SChris Mason 	/* double check we haven't messed things up */
1089e20d96d6SChris Mason 	if (orig_ptr !=
10905f39d397SChris Mason 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
109179f95c82SChris Mason 		BUG();
109254aa1f4dSChris Mason enospc:
1093925baeddSChris Mason 	if (right) {
1094925baeddSChris Mason 		btrfs_tree_unlock(right);
10955f39d397SChris Mason 		free_extent_buffer(right);
1096925baeddSChris Mason 	}
1097925baeddSChris Mason 	if (left) {
1098925baeddSChris Mason 		if (path->nodes[level] != left)
1099925baeddSChris Mason 			btrfs_tree_unlock(left);
11005f39d397SChris Mason 		free_extent_buffer(left);
1101925baeddSChris Mason 	}
1102bb803951SChris Mason 	return ret;
1103bb803951SChris Mason }
1104bb803951SChris Mason 
1105d352ac68SChris Mason /* Node balancing for insertion.  Here we only split or push nodes around
1106d352ac68SChris Mason  * when they are completely full.  This is also done top down, so we
1107d352ac68SChris Mason  * have to be pessimistic.
1108d352ac68SChris Mason  */
1109d397712bSChris Mason static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1110e66f709bSChris Mason 					  struct btrfs_root *root,
1111e66f709bSChris Mason 					  struct btrfs_path *path, int level)
1112e66f709bSChris Mason {
11130b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11145f39d397SChris Mason 	struct extent_buffer *right = NULL;
11155f39d397SChris Mason 	struct extent_buffer *mid;
11165f39d397SChris Mason 	struct extent_buffer *left = NULL;
11175f39d397SChris Mason 	struct extent_buffer *parent = NULL;
1118e66f709bSChris Mason 	int ret = 0;
1119e66f709bSChris Mason 	int wret;
1120e66f709bSChris Mason 	int pslot;
1121e66f709bSChris Mason 	int orig_slot = path->slots[level];
1122e66f709bSChris Mason 
1123e66f709bSChris Mason 	if (level == 0)
1124e66f709bSChris Mason 		return 1;
1125e66f709bSChris Mason 
11265f39d397SChris Mason 	mid = path->nodes[level];
11277bb86316SChris Mason 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1128e66f709bSChris Mason 
1129a05a9bb1SLi Zefan 	if (level < BTRFS_MAX_LEVEL - 1) {
11305f39d397SChris Mason 		parent = path->nodes[level + 1];
1131e66f709bSChris Mason 		pslot = path->slots[level + 1];
1132a05a9bb1SLi Zefan 	}
1133e66f709bSChris Mason 
11345f39d397SChris Mason 	if (!parent)
1135e66f709bSChris Mason 		return 1;
1136e66f709bSChris Mason 
11374b231ae4SDavid Sterba 	left = btrfs_read_node_slot(parent, pslot - 1);
1138fb770ae4SLiu Bo 	if (IS_ERR(left))
1139fb770ae4SLiu Bo 		left = NULL;
1140e66f709bSChris Mason 
1141e66f709bSChris Mason 	/* first, try to make some room in the middle buffer */
11425f39d397SChris Mason 	if (left) {
1143e66f709bSChris Mason 		u32 left_nr;
1144925baeddSChris Mason 
1145bf77467aSJosef Bacik 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1146b4ce94deSChris Mason 
11475f39d397SChris Mason 		left_nr = btrfs_header_nritems(left);
11480b246afaSJeff Mahoney 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
114933ade1f8SChris Mason 			wret = 1;
115033ade1f8SChris Mason 		} else {
11515f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, left, parent,
11529631e4ccSJosef Bacik 					      pslot - 1, &left,
1153bf59a5a2SJosef Bacik 					      BTRFS_NESTING_LEFT_COW);
115454aa1f4dSChris Mason 			if (ret)
115554aa1f4dSChris Mason 				wret = 1;
115654aa1f4dSChris Mason 			else {
1157d30a668fSDavid Sterba 				wret = push_node_left(trans, left, mid, 0);
115854aa1f4dSChris Mason 			}
115933ade1f8SChris Mason 		}
1160e66f709bSChris Mason 		if (wret < 0)
1161e66f709bSChris Mason 			ret = wret;
1162e66f709bSChris Mason 		if (wret == 0) {
11635f39d397SChris Mason 			struct btrfs_disk_key disk_key;
1164e66f709bSChris Mason 			orig_slot += left_nr;
11655f39d397SChris Mason 			btrfs_node_key(mid, &disk_key, 0);
1166f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1167f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
11680e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
11695f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot);
11705f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
11715f39d397SChris Mason 			if (btrfs_header_nritems(left) > orig_slot) {
11725f39d397SChris Mason 				path->nodes[level] = left;
1173e66f709bSChris Mason 				path->slots[level + 1] -= 1;
1174e66f709bSChris Mason 				path->slots[level] = orig_slot;
1175925baeddSChris Mason 				btrfs_tree_unlock(mid);
11765f39d397SChris Mason 				free_extent_buffer(mid);
1177e66f709bSChris Mason 			} else {
1178e66f709bSChris Mason 				orig_slot -=
11795f39d397SChris Mason 					btrfs_header_nritems(left);
1180e66f709bSChris Mason 				path->slots[level] = orig_slot;
1181925baeddSChris Mason 				btrfs_tree_unlock(left);
11825f39d397SChris Mason 				free_extent_buffer(left);
1183e66f709bSChris Mason 			}
1184e66f709bSChris Mason 			return 0;
1185e66f709bSChris Mason 		}
1186925baeddSChris Mason 		btrfs_tree_unlock(left);
11875f39d397SChris Mason 		free_extent_buffer(left);
1188e66f709bSChris Mason 	}
11894b231ae4SDavid Sterba 	right = btrfs_read_node_slot(parent, pslot + 1);
1190fb770ae4SLiu Bo 	if (IS_ERR(right))
1191fb770ae4SLiu Bo 		right = NULL;
1192e66f709bSChris Mason 
1193e66f709bSChris Mason 	/*
1194e66f709bSChris Mason 	 * then try to empty the right most buffer into the middle
1195e66f709bSChris Mason 	 */
11965f39d397SChris Mason 	if (right) {
119733ade1f8SChris Mason 		u32 right_nr;
1198b4ce94deSChris Mason 
1199bf77467aSJosef Bacik 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1200b4ce94deSChris Mason 
12015f39d397SChris Mason 		right_nr = btrfs_header_nritems(right);
12020b246afaSJeff Mahoney 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
120333ade1f8SChris Mason 			wret = 1;
120433ade1f8SChris Mason 		} else {
12055f39d397SChris Mason 			ret = btrfs_cow_block(trans, root, right,
12065f39d397SChris Mason 					      parent, pslot + 1,
1207bf59a5a2SJosef Bacik 					      &right, BTRFS_NESTING_RIGHT_COW);
120854aa1f4dSChris Mason 			if (ret)
120954aa1f4dSChris Mason 				wret = 1;
121054aa1f4dSChris Mason 			else {
121155d32ed8SDavid Sterba 				wret = balance_node_right(trans, right, mid);
121233ade1f8SChris Mason 			}
121354aa1f4dSChris Mason 		}
1214e66f709bSChris Mason 		if (wret < 0)
1215e66f709bSChris Mason 			ret = wret;
1216e66f709bSChris Mason 		if (wret == 0) {
12175f39d397SChris Mason 			struct btrfs_disk_key disk_key;
12185f39d397SChris Mason 
12195f39d397SChris Mason 			btrfs_node_key(right, &disk_key, 0);
1220f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1221f3a84ccdSFilipe Manana 					BTRFS_MOD_LOG_KEY_REPLACE, GFP_NOFS);
12220e82bcfeSDavid Sterba 			BUG_ON(ret < 0);
12235f39d397SChris Mason 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
12245f39d397SChris Mason 			btrfs_mark_buffer_dirty(parent);
12255f39d397SChris Mason 
12265f39d397SChris Mason 			if (btrfs_header_nritems(mid) <= orig_slot) {
12275f39d397SChris Mason 				path->nodes[level] = right;
1228e66f709bSChris Mason 				path->slots[level + 1] += 1;
1229e66f709bSChris Mason 				path->slots[level] = orig_slot -
12305f39d397SChris Mason 					btrfs_header_nritems(mid);
1231925baeddSChris Mason 				btrfs_tree_unlock(mid);
12325f39d397SChris Mason 				free_extent_buffer(mid);
1233e66f709bSChris Mason 			} else {
1234925baeddSChris Mason 				btrfs_tree_unlock(right);
12355f39d397SChris Mason 				free_extent_buffer(right);
1236e66f709bSChris Mason 			}
1237e66f709bSChris Mason 			return 0;
1238e66f709bSChris Mason 		}
1239925baeddSChris Mason 		btrfs_tree_unlock(right);
12405f39d397SChris Mason 		free_extent_buffer(right);
1241e66f709bSChris Mason 	}
1242e66f709bSChris Mason 	return 1;
1243e66f709bSChris Mason }
1244e66f709bSChris Mason 
124574123bd7SChris Mason /*
1246d352ac68SChris Mason  * readahead one full node of leaves, finding things that are close
1247d352ac68SChris Mason  * to the block in 'slot', and triggering ra on them.
12483c69faecSChris Mason  */
12492ff7e61eSJeff Mahoney static void reada_for_search(struct btrfs_fs_info *fs_info,
1250e02119d5SChris Mason 			     struct btrfs_path *path,
125101f46658SChris Mason 			     int level, int slot, u64 objectid)
12523c69faecSChris Mason {
12535f39d397SChris Mason 	struct extent_buffer *node;
125401f46658SChris Mason 	struct btrfs_disk_key disk_key;
12553c69faecSChris Mason 	u32 nritems;
12563c69faecSChris Mason 	u64 search;
1257a7175319SChris Mason 	u64 target;
12586b80053dSChris Mason 	u64 nread = 0;
1259ace75066SFilipe Manana 	u64 nread_max;
12606b80053dSChris Mason 	u32 nr;
12616b80053dSChris Mason 	u32 blocksize;
12626b80053dSChris Mason 	u32 nscan = 0;
1263db94535dSChris Mason 
1264ace75066SFilipe Manana 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
12653c69faecSChris Mason 		return;
12663c69faecSChris Mason 
12676702ed49SChris Mason 	if (!path->nodes[level])
12686702ed49SChris Mason 		return;
12696702ed49SChris Mason 
12705f39d397SChris Mason 	node = path->nodes[level];
1271925baeddSChris Mason 
1272ace75066SFilipe Manana 	/*
1273ace75066SFilipe Manana 	 * Since the time between visiting leaves is much shorter than the time
1274ace75066SFilipe Manana 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1275ace75066SFilipe Manana 	 * much IO at once (possibly random).
1276ace75066SFilipe Manana 	 */
1277ace75066SFilipe Manana 	if (path->reada == READA_FORWARD_ALWAYS) {
1278ace75066SFilipe Manana 		if (level > 1)
1279ace75066SFilipe Manana 			nread_max = node->fs_info->nodesize;
1280ace75066SFilipe Manana 		else
1281ace75066SFilipe Manana 			nread_max = SZ_128K;
1282ace75066SFilipe Manana 	} else {
1283ace75066SFilipe Manana 		nread_max = SZ_64K;
1284ace75066SFilipe Manana 	}
1285ace75066SFilipe Manana 
12863c69faecSChris Mason 	search = btrfs_node_blockptr(node, slot);
12870b246afaSJeff Mahoney 	blocksize = fs_info->nodesize;
1288069a2e37SFilipe Manana 	if (path->reada != READA_FORWARD_ALWAYS) {
1289069a2e37SFilipe Manana 		struct extent_buffer *eb;
1290069a2e37SFilipe Manana 
12910b246afaSJeff Mahoney 		eb = find_extent_buffer(fs_info, search);
12925f39d397SChris Mason 		if (eb) {
12935f39d397SChris Mason 			free_extent_buffer(eb);
12943c69faecSChris Mason 			return;
12953c69faecSChris Mason 		}
1296069a2e37SFilipe Manana 	}
12973c69faecSChris Mason 
1298a7175319SChris Mason 	target = search;
12996b80053dSChris Mason 
13005f39d397SChris Mason 	nritems = btrfs_header_nritems(node);
13016b80053dSChris Mason 	nr = slot;
130225b8b936SJosef Bacik 
13033c69faecSChris Mason 	while (1) {
1304e4058b54SDavid Sterba 		if (path->reada == READA_BACK) {
13056b80053dSChris Mason 			if (nr == 0)
13063c69faecSChris Mason 				break;
13076b80053dSChris Mason 			nr--;
1308ace75066SFilipe Manana 		} else if (path->reada == READA_FORWARD ||
1309ace75066SFilipe Manana 			   path->reada == READA_FORWARD_ALWAYS) {
13106b80053dSChris Mason 			nr++;
13116b80053dSChris Mason 			if (nr >= nritems)
13126b80053dSChris Mason 				break;
13133c69faecSChris Mason 		}
1314e4058b54SDavid Sterba 		if (path->reada == READA_BACK && objectid) {
131501f46658SChris Mason 			btrfs_node_key(node, &disk_key, nr);
131601f46658SChris Mason 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
131701f46658SChris Mason 				break;
131801f46658SChris Mason 		}
13196b80053dSChris Mason 		search = btrfs_node_blockptr(node, nr);
1320ace75066SFilipe Manana 		if (path->reada == READA_FORWARD_ALWAYS ||
1321ace75066SFilipe Manana 		    (search <= target && target - search <= 65536) ||
1322a7175319SChris Mason 		    (search > target && search - target <= 65536)) {
1323bfb484d9SJosef Bacik 			btrfs_readahead_node_child(node, nr);
13246b80053dSChris Mason 			nread += blocksize;
13253c69faecSChris Mason 		}
13266b80053dSChris Mason 		nscan++;
1327ace75066SFilipe Manana 		if (nread > nread_max || nscan > 32)
13286b80053dSChris Mason 			break;
13293c69faecSChris Mason 	}
13303c69faecSChris Mason }
1331925baeddSChris Mason 
1332bfb484d9SJosef Bacik static noinline void reada_for_balance(struct btrfs_path *path, int level)
1333b4ce94deSChris Mason {
1334bfb484d9SJosef Bacik 	struct extent_buffer *parent;
1335b4ce94deSChris Mason 	int slot;
1336b4ce94deSChris Mason 	int nritems;
1337b4ce94deSChris Mason 
13388c594ea8SChris Mason 	parent = path->nodes[level + 1];
1339b4ce94deSChris Mason 	if (!parent)
13400b08851fSJosef Bacik 		return;
1341b4ce94deSChris Mason 
1342b4ce94deSChris Mason 	nritems = btrfs_header_nritems(parent);
13438c594ea8SChris Mason 	slot = path->slots[level + 1];
1344b4ce94deSChris Mason 
1345bfb484d9SJosef Bacik 	if (slot > 0)
1346bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot - 1);
1347bfb484d9SJosef Bacik 	if (slot + 1 < nritems)
1348bfb484d9SJosef Bacik 		btrfs_readahead_node_child(parent, slot + 1);
1349b4ce94deSChris Mason }
1350b4ce94deSChris Mason 
1351b4ce94deSChris Mason 
1352b4ce94deSChris Mason /*
1353d397712bSChris Mason  * when we walk down the tree, it is usually safe to unlock the higher layers
1354d397712bSChris Mason  * in the tree.  The exceptions are when our path goes through slot 0, because
1355d397712bSChris Mason  * operations on the tree might require changing key pointers higher up in the
1356d397712bSChris Mason  * tree.
1357d352ac68SChris Mason  *
1358d397712bSChris Mason  * callers might also have set path->keep_locks, which tells this code to keep
1359d397712bSChris Mason  * the lock if the path points to the last slot in the block.  This is part of
1360d397712bSChris Mason  * walking through the tree, and selecting the next slot in the higher block.
1361d352ac68SChris Mason  *
1362d397712bSChris Mason  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1363d397712bSChris Mason  * if lowest_unlock is 1, level 0 won't be unlocked
1364d352ac68SChris Mason  */
1365e02119d5SChris Mason static noinline void unlock_up(struct btrfs_path *path, int level,
1366f7c79f30SChris Mason 			       int lowest_unlock, int min_write_lock_level,
1367f7c79f30SChris Mason 			       int *write_lock_level)
1368925baeddSChris Mason {
1369925baeddSChris Mason 	int i;
1370925baeddSChris Mason 	int skip_level = level;
1371c1227996SNikolay Borisov 	bool check_skip = true;
1372925baeddSChris Mason 
1373925baeddSChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1374925baeddSChris Mason 		if (!path->nodes[i])
1375925baeddSChris Mason 			break;
1376925baeddSChris Mason 		if (!path->locks[i])
1377925baeddSChris Mason 			break;
1378c1227996SNikolay Borisov 
1379c1227996SNikolay Borisov 		if (check_skip) {
1380c1227996SNikolay Borisov 			if (path->slots[i] == 0) {
1381925baeddSChris Mason 				skip_level = i + 1;
1382925baeddSChris Mason 				continue;
1383925baeddSChris Mason 			}
1384c1227996SNikolay Borisov 
1385c1227996SNikolay Borisov 			if (path->keep_locks) {
1386925baeddSChris Mason 				u32 nritems;
1387c1227996SNikolay Borisov 
1388c1227996SNikolay Borisov 				nritems = btrfs_header_nritems(path->nodes[i]);
1389051e1b9fSChris Mason 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1390925baeddSChris Mason 					skip_level = i + 1;
1391925baeddSChris Mason 					continue;
1392925baeddSChris Mason 				}
1393925baeddSChris Mason 			}
1394c1227996SNikolay Borisov 		}
1395051e1b9fSChris Mason 
1396d80bb3f9SLiu Bo 		if (i >= lowest_unlock && i > skip_level) {
1397c1227996SNikolay Borisov 			check_skip = false;
1398c1227996SNikolay Borisov 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1399925baeddSChris Mason 			path->locks[i] = 0;
1400f7c79f30SChris Mason 			if (write_lock_level &&
1401f7c79f30SChris Mason 			    i > min_write_lock_level &&
1402f7c79f30SChris Mason 			    i <= *write_lock_level) {
1403f7c79f30SChris Mason 				*write_lock_level = i - 1;
1404f7c79f30SChris Mason 			}
1405925baeddSChris Mason 		}
1406925baeddSChris Mason 	}
1407925baeddSChris Mason }
1408925baeddSChris Mason 
14093c69faecSChris Mason /*
1410376a21d7SFilipe Manana  * Helper function for btrfs_search_slot() and other functions that do a search
1411376a21d7SFilipe Manana  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1412376a21d7SFilipe Manana  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1413376a21d7SFilipe Manana  * its pages from disk.
1414c8c42864SChris Mason  *
1415376a21d7SFilipe Manana  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1416376a21d7SFilipe Manana  * whole btree search, starting again from the current root node.
1417c8c42864SChris Mason  */
1418c8c42864SChris Mason static int
1419d07b8528SLiu Bo read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1420c8c42864SChris Mason 		      struct extent_buffer **eb_ret, int level, int slot,
1421cda79c54SDavid Sterba 		      const struct btrfs_key *key)
1422c8c42864SChris Mason {
14230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1424c8c42864SChris Mason 	u64 blocknr;
1425c8c42864SChris Mason 	u64 gen;
1426c8c42864SChris Mason 	struct extent_buffer *tmp;
1427581c1760SQu Wenruo 	struct btrfs_key first_key;
142876a05b35SChris Mason 	int ret;
1429581c1760SQu Wenruo 	int parent_level;
1430b246666eSFilipe Manana 	bool unlock_up;
1431c8c42864SChris Mason 
1432b246666eSFilipe Manana 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1433213ff4b7SNikolay Borisov 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1434213ff4b7SNikolay Borisov 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1435213ff4b7SNikolay Borisov 	parent_level = btrfs_header_level(*eb_ret);
1436213ff4b7SNikolay Borisov 	btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
1437c8c42864SChris Mason 
1438b246666eSFilipe Manana 	/*
1439b246666eSFilipe Manana 	 * If we need to read an extent buffer from disk and we are holding locks
1440b246666eSFilipe Manana 	 * on upper level nodes, we unlock all the upper nodes before reading the
1441b246666eSFilipe Manana 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1442b246666eSFilipe Manana 	 * restart the search. We don't release the lock on the current level
1443b246666eSFilipe Manana 	 * because we need to walk this node to figure out which blocks to read.
1444b246666eSFilipe Manana 	 */
14450b246afaSJeff Mahoney 	tmp = find_extent_buffer(fs_info, blocknr);
1446cb44921aSChris Mason 	if (tmp) {
1447ace75066SFilipe Manana 		if (p->reada == READA_FORWARD_ALWAYS)
1448ace75066SFilipe Manana 			reada_for_search(fs_info, p, level, slot, key->objectid);
1449ace75066SFilipe Manana 
1450b9fab919SChris Mason 		/* first we do an atomic uptodate check */
1451b9fab919SChris Mason 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1452448de471SQu Wenruo 			/*
1453448de471SQu Wenruo 			 * Do extra check for first_key, eb can be stale due to
1454448de471SQu Wenruo 			 * being cached, read from scrub, or have multiple
1455448de471SQu Wenruo 			 * parents (shared tree blocks).
1456448de471SQu Wenruo 			 */
1457e064d5e9SDavid Sterba 			if (btrfs_verify_level_key(tmp,
1458448de471SQu Wenruo 					parent_level - 1, &first_key, gen)) {
1459448de471SQu Wenruo 				free_extent_buffer(tmp);
1460448de471SQu Wenruo 				return -EUCLEAN;
1461448de471SQu Wenruo 			}
1462c8c42864SChris Mason 			*eb_ret = tmp;
1463c8c42864SChris Mason 			return 0;
1464c8c42864SChris Mason 		}
1465bdf7c00eSJosef Bacik 
1466857bc13fSJosef Bacik 		if (p->nowait) {
1467857bc13fSJosef Bacik 			free_extent_buffer(tmp);
1468857bc13fSJosef Bacik 			return -EAGAIN;
1469857bc13fSJosef Bacik 		}
1470857bc13fSJosef Bacik 
1471b246666eSFilipe Manana 		if (unlock_up)
1472b246666eSFilipe Manana 			btrfs_unlock_up_safe(p, level + 1);
1473b246666eSFilipe Manana 
1474b9fab919SChris Mason 		/* now we're allowed to do a blocking uptodate check */
14756a2e9dc4SFilipe Manana 		ret = btrfs_read_extent_buffer(tmp, gen, parent_level - 1, &first_key);
14769a4ffa1bSQu Wenruo 		if (ret) {
1477cb44921aSChris Mason 			free_extent_buffer(tmp);
1478b3b4aa74SDavid Sterba 			btrfs_release_path(p);
1479cb44921aSChris Mason 			return -EIO;
1480cb44921aSChris Mason 		}
148188c602abSQu Wenruo 		if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
148288c602abSQu Wenruo 			free_extent_buffer(tmp);
148388c602abSQu Wenruo 			btrfs_release_path(p);
148488c602abSQu Wenruo 			return -EUCLEAN;
148588c602abSQu Wenruo 		}
1486b246666eSFilipe Manana 
1487b246666eSFilipe Manana 		if (unlock_up)
1488b246666eSFilipe Manana 			ret = -EAGAIN;
1489b246666eSFilipe Manana 
1490b246666eSFilipe Manana 		goto out;
1491857bc13fSJosef Bacik 	} else if (p->nowait) {
1492857bc13fSJosef Bacik 		return -EAGAIN;
14939a4ffa1bSQu Wenruo 	}
1494c8c42864SChris Mason 
1495b246666eSFilipe Manana 	if (unlock_up) {
14968c594ea8SChris Mason 		btrfs_unlock_up_safe(p, level + 1);
14974bb59055SFilipe Manana 		ret = -EAGAIN;
14984bb59055SFilipe Manana 	} else {
14994bb59055SFilipe Manana 		ret = 0;
15004bb59055SFilipe Manana 	}
15018c594ea8SChris Mason 
1502e4058b54SDavid Sterba 	if (p->reada != READA_NONE)
15032ff7e61eSJeff Mahoney 		reada_for_search(fs_info, p, level, slot, key->objectid);
1504c8c42864SChris Mason 
15051b7ec85eSJosef Bacik 	tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
15061b7ec85eSJosef Bacik 			      gen, parent_level - 1, &first_key);
15074eb150d6SQu Wenruo 	if (IS_ERR(tmp)) {
15084eb150d6SQu Wenruo 		btrfs_release_path(p);
15094eb150d6SQu Wenruo 		return PTR_ERR(tmp);
15104eb150d6SQu Wenruo 	}
151176a05b35SChris Mason 	/*
151276a05b35SChris Mason 	 * If the read above didn't mark this buffer up to date,
151376a05b35SChris Mason 	 * it will never end up being up to date.  Set ret to EIO now
151476a05b35SChris Mason 	 * and give up so that our caller doesn't loop forever
151576a05b35SChris Mason 	 * on our EAGAINs.
151676a05b35SChris Mason 	 */
1517e6a1d6fdSLiu Bo 	if (!extent_buffer_uptodate(tmp))
151876a05b35SChris Mason 		ret = -EIO;
151902a3307aSLiu Bo 
1520b246666eSFilipe Manana out:
15214bb59055SFilipe Manana 	if (ret == 0) {
15224bb59055SFilipe Manana 		*eb_ret = tmp;
15234bb59055SFilipe Manana 	} else {
15244bb59055SFilipe Manana 		free_extent_buffer(tmp);
152502a3307aSLiu Bo 		btrfs_release_path(p);
15264bb59055SFilipe Manana 	}
15274bb59055SFilipe Manana 
152876a05b35SChris Mason 	return ret;
1529c8c42864SChris Mason }
1530c8c42864SChris Mason 
1531c8c42864SChris Mason /*
1532c8c42864SChris Mason  * helper function for btrfs_search_slot.  This does all of the checks
1533c8c42864SChris Mason  * for node-level blocks and does any balancing required based on
1534c8c42864SChris Mason  * the ins_len.
1535c8c42864SChris Mason  *
1536c8c42864SChris Mason  * If no extra work was required, zero is returned.  If we had to
1537c8c42864SChris Mason  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1538c8c42864SChris Mason  * start over
1539c8c42864SChris Mason  */
1540c8c42864SChris Mason static int
1541c8c42864SChris Mason setup_nodes_for_search(struct btrfs_trans_handle *trans,
1542c8c42864SChris Mason 		       struct btrfs_root *root, struct btrfs_path *p,
1543bd681513SChris Mason 		       struct extent_buffer *b, int level, int ins_len,
1544bd681513SChris Mason 		       int *write_lock_level)
1545c8c42864SChris Mason {
15460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
154795b982deSNikolay Borisov 	int ret = 0;
15480b246afaSJeff Mahoney 
1549c8c42864SChris Mason 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
15500b246afaSJeff Mahoney 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1551c8c42864SChris Mason 
1552bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1553bd681513SChris Mason 			*write_lock_level = level + 1;
1554bd681513SChris Mason 			btrfs_release_path(p);
155595b982deSNikolay Borisov 			return -EAGAIN;
1556bd681513SChris Mason 		}
1557bd681513SChris Mason 
1558bfb484d9SJosef Bacik 		reada_for_balance(p, level);
155995b982deSNikolay Borisov 		ret = split_node(trans, root, p, level);
1560c8c42864SChris Mason 
1561c8c42864SChris Mason 		b = p->nodes[level];
1562c8c42864SChris Mason 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
15630b246afaSJeff Mahoney 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1564c8c42864SChris Mason 
1565bd681513SChris Mason 		if (*write_lock_level < level + 1) {
1566bd681513SChris Mason 			*write_lock_level = level + 1;
1567bd681513SChris Mason 			btrfs_release_path(p);
156895b982deSNikolay Borisov 			return -EAGAIN;
1569bd681513SChris Mason 		}
1570bd681513SChris Mason 
1571bfb484d9SJosef Bacik 		reada_for_balance(p, level);
157295b982deSNikolay Borisov 		ret = balance_level(trans, root, p, level);
157395b982deSNikolay Borisov 		if (ret)
157495b982deSNikolay Borisov 			return ret;
1575c8c42864SChris Mason 
1576c8c42864SChris Mason 		b = p->nodes[level];
1577c8c42864SChris Mason 		if (!b) {
1578b3b4aa74SDavid Sterba 			btrfs_release_path(p);
157995b982deSNikolay Borisov 			return -EAGAIN;
1580c8c42864SChris Mason 		}
1581c8c42864SChris Mason 		BUG_ON(btrfs_header_nritems(b) == 1);
1582c8c42864SChris Mason 	}
1583c8c42864SChris Mason 	return ret;
1584c8c42864SChris Mason }
1585c8c42864SChris Mason 
1586381cf658SDavid Sterba int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1587e33d5c3dSKelley Nielsen 		u64 iobjectid, u64 ioff, u8 key_type,
1588e33d5c3dSKelley Nielsen 		struct btrfs_key *found_key)
1589e33d5c3dSKelley Nielsen {
1590e33d5c3dSKelley Nielsen 	int ret;
1591e33d5c3dSKelley Nielsen 	struct btrfs_key key;
1592e33d5c3dSKelley Nielsen 	struct extent_buffer *eb;
1593381cf658SDavid Sterba 
1594381cf658SDavid Sterba 	ASSERT(path);
15951d4c08e0SDavid Sterba 	ASSERT(found_key);
1596e33d5c3dSKelley Nielsen 
1597e33d5c3dSKelley Nielsen 	key.type = key_type;
1598e33d5c3dSKelley Nielsen 	key.objectid = iobjectid;
1599e33d5c3dSKelley Nielsen 	key.offset = ioff;
1600e33d5c3dSKelley Nielsen 
1601e33d5c3dSKelley Nielsen 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
16021d4c08e0SDavid Sterba 	if (ret < 0)
1603e33d5c3dSKelley Nielsen 		return ret;
1604e33d5c3dSKelley Nielsen 
1605e33d5c3dSKelley Nielsen 	eb = path->nodes[0];
1606e33d5c3dSKelley Nielsen 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1607e33d5c3dSKelley Nielsen 		ret = btrfs_next_leaf(fs_root, path);
1608e33d5c3dSKelley Nielsen 		if (ret)
1609e33d5c3dSKelley Nielsen 			return ret;
1610e33d5c3dSKelley Nielsen 		eb = path->nodes[0];
1611e33d5c3dSKelley Nielsen 	}
1612e33d5c3dSKelley Nielsen 
1613e33d5c3dSKelley Nielsen 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1614e33d5c3dSKelley Nielsen 	if (found_key->type != key.type ||
1615e33d5c3dSKelley Nielsen 			found_key->objectid != key.objectid)
1616e33d5c3dSKelley Nielsen 		return 1;
1617e33d5c3dSKelley Nielsen 
1618e33d5c3dSKelley Nielsen 	return 0;
1619e33d5c3dSKelley Nielsen }
1620e33d5c3dSKelley Nielsen 
16211fc28d8eSLiu Bo static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
16221fc28d8eSLiu Bo 							struct btrfs_path *p,
16231fc28d8eSLiu Bo 							int write_lock_level)
16241fc28d8eSLiu Bo {
16251fc28d8eSLiu Bo 	struct extent_buffer *b;
1626120de408SJosef Bacik 	int root_lock = 0;
16271fc28d8eSLiu Bo 	int level = 0;
16281fc28d8eSLiu Bo 
16291fc28d8eSLiu Bo 	if (p->search_commit_root) {
16301fc28d8eSLiu Bo 		b = root->commit_root;
163167439dadSDavid Sterba 		atomic_inc(&b->refs);
16321fc28d8eSLiu Bo 		level = btrfs_header_level(b);
1633f9ddfd05SLiu Bo 		/*
1634f9ddfd05SLiu Bo 		 * Ensure that all callers have set skip_locking when
1635f9ddfd05SLiu Bo 		 * p->search_commit_root = 1.
1636f9ddfd05SLiu Bo 		 */
1637f9ddfd05SLiu Bo 		ASSERT(p->skip_locking == 1);
16381fc28d8eSLiu Bo 
16391fc28d8eSLiu Bo 		goto out;
16401fc28d8eSLiu Bo 	}
16411fc28d8eSLiu Bo 
16421fc28d8eSLiu Bo 	if (p->skip_locking) {
16431fc28d8eSLiu Bo 		b = btrfs_root_node(root);
16441fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16451fc28d8eSLiu Bo 		goto out;
16461fc28d8eSLiu Bo 	}
16471fc28d8eSLiu Bo 
1648120de408SJosef Bacik 	/* We try very hard to do read locks on the root */
1649120de408SJosef Bacik 	root_lock = BTRFS_READ_LOCK;
1650120de408SJosef Bacik 
16511fc28d8eSLiu Bo 	/*
1652662c653bSLiu Bo 	 * If the level is set to maximum, we can skip trying to get the read
1653662c653bSLiu Bo 	 * lock.
1654662c653bSLiu Bo 	 */
1655662c653bSLiu Bo 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1656662c653bSLiu Bo 		/*
1657662c653bSLiu Bo 		 * We don't know the level of the root node until we actually
1658662c653bSLiu Bo 		 * have it read locked
16591fc28d8eSLiu Bo 		 */
1660857bc13fSJosef Bacik 		if (p->nowait) {
1661857bc13fSJosef Bacik 			b = btrfs_try_read_lock_root_node(root);
1662857bc13fSJosef Bacik 			if (IS_ERR(b))
1663857bc13fSJosef Bacik 				return b;
1664857bc13fSJosef Bacik 		} else {
16651bb96598SJosef Bacik 			b = btrfs_read_lock_root_node(root);
1666857bc13fSJosef Bacik 		}
16671fc28d8eSLiu Bo 		level = btrfs_header_level(b);
16681fc28d8eSLiu Bo 		if (level > write_lock_level)
16691fc28d8eSLiu Bo 			goto out;
16701fc28d8eSLiu Bo 
1671662c653bSLiu Bo 		/* Whoops, must trade for write lock */
16721fc28d8eSLiu Bo 		btrfs_tree_read_unlock(b);
16731fc28d8eSLiu Bo 		free_extent_buffer(b);
1674662c653bSLiu Bo 	}
1675662c653bSLiu Bo 
16761fc28d8eSLiu Bo 	b = btrfs_lock_root_node(root);
16771fc28d8eSLiu Bo 	root_lock = BTRFS_WRITE_LOCK;
16781fc28d8eSLiu Bo 
16791fc28d8eSLiu Bo 	/* The level might have changed, check again */
16801fc28d8eSLiu Bo 	level = btrfs_header_level(b);
16811fc28d8eSLiu Bo 
16821fc28d8eSLiu Bo out:
1683120de408SJosef Bacik 	/*
1684120de408SJosef Bacik 	 * The root may have failed to write out at some point, and thus is no
1685120de408SJosef Bacik 	 * longer valid, return an error in this case.
1686120de408SJosef Bacik 	 */
1687120de408SJosef Bacik 	if (!extent_buffer_uptodate(b)) {
1688120de408SJosef Bacik 		if (root_lock)
1689120de408SJosef Bacik 			btrfs_tree_unlock_rw(b, root_lock);
1690120de408SJosef Bacik 		free_extent_buffer(b);
1691120de408SJosef Bacik 		return ERR_PTR(-EIO);
1692120de408SJosef Bacik 	}
1693120de408SJosef Bacik 
16941fc28d8eSLiu Bo 	p->nodes[level] = b;
16951fc28d8eSLiu Bo 	if (!p->skip_locking)
16961fc28d8eSLiu Bo 		p->locks[level] = root_lock;
16971fc28d8eSLiu Bo 	/*
16981fc28d8eSLiu Bo 	 * Callers are responsible for dropping b's references.
16991fc28d8eSLiu Bo 	 */
17001fc28d8eSLiu Bo 	return b;
17011fc28d8eSLiu Bo }
17021fc28d8eSLiu Bo 
1703d96b3424SFilipe Manana /*
1704d96b3424SFilipe Manana  * Replace the extent buffer at the lowest level of the path with a cloned
1705d96b3424SFilipe Manana  * version. The purpose is to be able to use it safely, after releasing the
1706d96b3424SFilipe Manana  * commit root semaphore, even if relocation is happening in parallel, the
1707d96b3424SFilipe Manana  * transaction used for relocation is committed and the extent buffer is
1708d96b3424SFilipe Manana  * reallocated in the next transaction.
1709d96b3424SFilipe Manana  *
1710d96b3424SFilipe Manana  * This is used in a context where the caller does not prevent transaction
1711d96b3424SFilipe Manana  * commits from happening, either by holding a transaction handle or holding
1712d96b3424SFilipe Manana  * some lock, while it's doing searches through a commit root.
1713d96b3424SFilipe Manana  * At the moment it's only used for send operations.
1714d96b3424SFilipe Manana  */
1715d96b3424SFilipe Manana static int finish_need_commit_sem_search(struct btrfs_path *path)
1716d96b3424SFilipe Manana {
1717d96b3424SFilipe Manana 	const int i = path->lowest_level;
1718d96b3424SFilipe Manana 	const int slot = path->slots[i];
1719d96b3424SFilipe Manana 	struct extent_buffer *lowest = path->nodes[i];
1720d96b3424SFilipe Manana 	struct extent_buffer *clone;
1721d96b3424SFilipe Manana 
1722d96b3424SFilipe Manana 	ASSERT(path->need_commit_sem);
1723d96b3424SFilipe Manana 
1724d96b3424SFilipe Manana 	if (!lowest)
1725d96b3424SFilipe Manana 		return 0;
1726d96b3424SFilipe Manana 
1727d96b3424SFilipe Manana 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1728d96b3424SFilipe Manana 
1729d96b3424SFilipe Manana 	clone = btrfs_clone_extent_buffer(lowest);
1730d96b3424SFilipe Manana 	if (!clone)
1731d96b3424SFilipe Manana 		return -ENOMEM;
1732d96b3424SFilipe Manana 
1733d96b3424SFilipe Manana 	btrfs_release_path(path);
1734d96b3424SFilipe Manana 	path->nodes[i] = clone;
1735d96b3424SFilipe Manana 	path->slots[i] = slot;
1736d96b3424SFilipe Manana 
1737d96b3424SFilipe Manana 	return 0;
1738d96b3424SFilipe Manana }
17391fc28d8eSLiu Bo 
1740e2e58d0fSFilipe Manana static inline int search_for_key_slot(struct extent_buffer *eb,
1741e2e58d0fSFilipe Manana 				      int search_low_slot,
1742e2e58d0fSFilipe Manana 				      const struct btrfs_key *key,
1743e2e58d0fSFilipe Manana 				      int prev_cmp,
1744e2e58d0fSFilipe Manana 				      int *slot)
1745e2e58d0fSFilipe Manana {
1746e2e58d0fSFilipe Manana 	/*
1747e2e58d0fSFilipe Manana 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1748e2e58d0fSFilipe Manana 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1749e2e58d0fSFilipe Manana 	 * always be at slot 0 on lower levels, since each key pointer
1750e2e58d0fSFilipe Manana 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1751e2e58d0fSFilipe Manana 	 * subtree it points to. Thus we can skip searching lower levels.
1752e2e58d0fSFilipe Manana 	 */
1753e2e58d0fSFilipe Manana 	if (prev_cmp == 0) {
1754e2e58d0fSFilipe Manana 		*slot = 0;
1755e2e58d0fSFilipe Manana 		return 0;
1756e2e58d0fSFilipe Manana 	}
1757e2e58d0fSFilipe Manana 
1758e2e58d0fSFilipe Manana 	return generic_bin_search(eb, search_low_slot, key, slot);
1759e2e58d0fSFilipe Manana }
1760e2e58d0fSFilipe Manana 
1761109324cfSFilipe Manana static int search_leaf(struct btrfs_trans_handle *trans,
1762109324cfSFilipe Manana 		       struct btrfs_root *root,
1763109324cfSFilipe Manana 		       const struct btrfs_key *key,
1764109324cfSFilipe Manana 		       struct btrfs_path *path,
1765109324cfSFilipe Manana 		       int ins_len,
1766109324cfSFilipe Manana 		       int prev_cmp)
1767109324cfSFilipe Manana {
1768109324cfSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
1769109324cfSFilipe Manana 	int leaf_free_space = -1;
1770109324cfSFilipe Manana 	int search_low_slot = 0;
1771109324cfSFilipe Manana 	int ret;
1772109324cfSFilipe Manana 	bool do_bin_search = true;
1773109324cfSFilipe Manana 
1774109324cfSFilipe Manana 	/*
1775109324cfSFilipe Manana 	 * If we are doing an insertion, the leaf has enough free space and the
1776109324cfSFilipe Manana 	 * destination slot for the key is not slot 0, then we can unlock our
1777109324cfSFilipe Manana 	 * write lock on the parent, and any other upper nodes, before doing the
1778109324cfSFilipe Manana 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1779109324cfSFilipe Manana 	 * tasks to lock the parent and any other upper nodes.
1780109324cfSFilipe Manana 	 */
1781109324cfSFilipe Manana 	if (ins_len > 0) {
1782109324cfSFilipe Manana 		/*
1783109324cfSFilipe Manana 		 * Cache the leaf free space, since we will need it later and it
1784109324cfSFilipe Manana 		 * will not change until then.
1785109324cfSFilipe Manana 		 */
1786109324cfSFilipe Manana 		leaf_free_space = btrfs_leaf_free_space(leaf);
1787109324cfSFilipe Manana 
1788109324cfSFilipe Manana 		/*
1789109324cfSFilipe Manana 		 * !path->locks[1] means we have a single node tree, the leaf is
1790109324cfSFilipe Manana 		 * the root of the tree.
1791109324cfSFilipe Manana 		 */
1792109324cfSFilipe Manana 		if (path->locks[1] && leaf_free_space >= ins_len) {
1793109324cfSFilipe Manana 			struct btrfs_disk_key first_key;
1794109324cfSFilipe Manana 
1795109324cfSFilipe Manana 			ASSERT(btrfs_header_nritems(leaf) > 0);
1796109324cfSFilipe Manana 			btrfs_item_key(leaf, &first_key, 0);
1797109324cfSFilipe Manana 
1798109324cfSFilipe Manana 			/*
1799109324cfSFilipe Manana 			 * Doing the extra comparison with the first key is cheap,
1800109324cfSFilipe Manana 			 * taking into account that the first key is very likely
1801109324cfSFilipe Manana 			 * already in a cache line because it immediately follows
1802109324cfSFilipe Manana 			 * the extent buffer's header and we have recently accessed
1803109324cfSFilipe Manana 			 * the header's level field.
1804109324cfSFilipe Manana 			 */
1805109324cfSFilipe Manana 			ret = comp_keys(&first_key, key);
1806109324cfSFilipe Manana 			if (ret < 0) {
1807109324cfSFilipe Manana 				/*
1808109324cfSFilipe Manana 				 * The first key is smaller than the key we want
1809109324cfSFilipe Manana 				 * to insert, so we are safe to unlock all upper
1810109324cfSFilipe Manana 				 * nodes and we have to do the binary search.
1811109324cfSFilipe Manana 				 *
1812109324cfSFilipe Manana 				 * We do use btrfs_unlock_up_safe() and not
1813109324cfSFilipe Manana 				 * unlock_up() because the later does not unlock
1814109324cfSFilipe Manana 				 * nodes with a slot of 0 - we can safely unlock
1815109324cfSFilipe Manana 				 * any node even if its slot is 0 since in this
1816109324cfSFilipe Manana 				 * case the key does not end up at slot 0 of the
1817109324cfSFilipe Manana 				 * leaf and there's no need to split the leaf.
1818109324cfSFilipe Manana 				 */
1819109324cfSFilipe Manana 				btrfs_unlock_up_safe(path, 1);
1820109324cfSFilipe Manana 				search_low_slot = 1;
1821109324cfSFilipe Manana 			} else {
1822109324cfSFilipe Manana 				/*
1823109324cfSFilipe Manana 				 * The first key is >= then the key we want to
1824109324cfSFilipe Manana 				 * insert, so we can skip the binary search as
1825109324cfSFilipe Manana 				 * the target key will be at slot 0.
1826109324cfSFilipe Manana 				 *
1827109324cfSFilipe Manana 				 * We can not unlock upper nodes when the key is
1828109324cfSFilipe Manana 				 * less than the first key, because we will need
1829109324cfSFilipe Manana 				 * to update the key at slot 0 of the parent node
1830109324cfSFilipe Manana 				 * and possibly of other upper nodes too.
1831109324cfSFilipe Manana 				 * If the key matches the first key, then we can
1832109324cfSFilipe Manana 				 * unlock all the upper nodes, using
1833109324cfSFilipe Manana 				 * btrfs_unlock_up_safe() instead of unlock_up()
1834109324cfSFilipe Manana 				 * as stated above.
1835109324cfSFilipe Manana 				 */
1836109324cfSFilipe Manana 				if (ret == 0)
1837109324cfSFilipe Manana 					btrfs_unlock_up_safe(path, 1);
1838109324cfSFilipe Manana 				/*
1839109324cfSFilipe Manana 				 * ret is already 0 or 1, matching the result of
1840109324cfSFilipe Manana 				 * a btrfs_bin_search() call, so there is no need
1841109324cfSFilipe Manana 				 * to adjust it.
1842109324cfSFilipe Manana 				 */
1843109324cfSFilipe Manana 				do_bin_search = false;
1844109324cfSFilipe Manana 				path->slots[0] = 0;
1845109324cfSFilipe Manana 			}
1846109324cfSFilipe Manana 		}
1847109324cfSFilipe Manana 	}
1848109324cfSFilipe Manana 
1849109324cfSFilipe Manana 	if (do_bin_search) {
1850109324cfSFilipe Manana 		ret = search_for_key_slot(leaf, search_low_slot, key,
1851109324cfSFilipe Manana 					  prev_cmp, &path->slots[0]);
1852109324cfSFilipe Manana 		if (ret < 0)
1853109324cfSFilipe Manana 			return ret;
1854109324cfSFilipe Manana 	}
1855109324cfSFilipe Manana 
1856109324cfSFilipe Manana 	if (ins_len > 0) {
1857109324cfSFilipe Manana 		/*
1858109324cfSFilipe Manana 		 * Item key already exists. In this case, if we are allowed to
1859109324cfSFilipe Manana 		 * insert the item (for example, in dir_item case, item key
1860109324cfSFilipe Manana 		 * collision is allowed), it will be merged with the original
1861109324cfSFilipe Manana 		 * item. Only the item size grows, no new btrfs item will be
1862109324cfSFilipe Manana 		 * added. If search_for_extension is not set, ins_len already
1863109324cfSFilipe Manana 		 * accounts the size btrfs_item, deduct it here so leaf space
1864109324cfSFilipe Manana 		 * check will be correct.
1865109324cfSFilipe Manana 		 */
1866109324cfSFilipe Manana 		if (ret == 0 && !path->search_for_extension) {
1867109324cfSFilipe Manana 			ASSERT(ins_len >= sizeof(struct btrfs_item));
1868109324cfSFilipe Manana 			ins_len -= sizeof(struct btrfs_item);
1869109324cfSFilipe Manana 		}
1870109324cfSFilipe Manana 
1871109324cfSFilipe Manana 		ASSERT(leaf_free_space >= 0);
1872109324cfSFilipe Manana 
1873109324cfSFilipe Manana 		if (leaf_free_space < ins_len) {
1874109324cfSFilipe Manana 			int err;
1875109324cfSFilipe Manana 
1876109324cfSFilipe Manana 			err = split_leaf(trans, root, key, path, ins_len,
1877109324cfSFilipe Manana 					 (ret == 0));
1878bb8e9a60SFilipe Manana 			ASSERT(err <= 0);
1879bb8e9a60SFilipe Manana 			if (WARN_ON(err > 0))
1880bb8e9a60SFilipe Manana 				err = -EUCLEAN;
1881109324cfSFilipe Manana 			if (err)
1882109324cfSFilipe Manana 				ret = err;
1883109324cfSFilipe Manana 		}
1884109324cfSFilipe Manana 	}
1885109324cfSFilipe Manana 
1886109324cfSFilipe Manana 	return ret;
1887109324cfSFilipe Manana }
1888109324cfSFilipe Manana 
1889c8c42864SChris Mason /*
18904271eceaSNikolay Borisov  * btrfs_search_slot - look for a key in a tree and perform necessary
18914271eceaSNikolay Borisov  * modifications to preserve tree invariants.
189274123bd7SChris Mason  *
18934271eceaSNikolay Borisov  * @trans:	Handle of transaction, used when modifying the tree
18944271eceaSNikolay Borisov  * @p:		Holds all btree nodes along the search path
18954271eceaSNikolay Borisov  * @root:	The root node of the tree
18964271eceaSNikolay Borisov  * @key:	The key we are looking for
18979a664971Sethanwu  * @ins_len:	Indicates purpose of search:
18989a664971Sethanwu  *              >0  for inserts it's size of item inserted (*)
18999a664971Sethanwu  *              <0  for deletions
19009a664971Sethanwu  *               0  for plain searches, not modifying the tree
19019a664971Sethanwu  *
19029a664971Sethanwu  *              (*) If size of item inserted doesn't include
19039a664971Sethanwu  *              sizeof(struct btrfs_item), then p->search_for_extension must
19049a664971Sethanwu  *              be set.
19054271eceaSNikolay Borisov  * @cow:	boolean should CoW operations be performed. Must always be 1
19064271eceaSNikolay Borisov  *		when modifying the tree.
190797571fd0SChris Mason  *
19084271eceaSNikolay Borisov  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
19094271eceaSNikolay Borisov  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
19104271eceaSNikolay Borisov  *
19114271eceaSNikolay Borisov  * If @key is found, 0 is returned and you can find the item in the leaf level
19124271eceaSNikolay Borisov  * of the path (level 0)
19134271eceaSNikolay Borisov  *
19144271eceaSNikolay Borisov  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
19154271eceaSNikolay Borisov  * points to the slot where it should be inserted
19164271eceaSNikolay Borisov  *
19174271eceaSNikolay Borisov  * If an error is encountered while searching the tree a negative error number
19184271eceaSNikolay Borisov  * is returned
191974123bd7SChris Mason  */
1920310712b2SOmar Sandoval int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1921310712b2SOmar Sandoval 		      const struct btrfs_key *key, struct btrfs_path *p,
1922310712b2SOmar Sandoval 		      int ins_len, int cow)
1923be0e5c09SChris Mason {
1924d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
19255f39d397SChris Mason 	struct extent_buffer *b;
1926be0e5c09SChris Mason 	int slot;
1927be0e5c09SChris Mason 	int ret;
192833c66f43SYan Zheng 	int err;
1929be0e5c09SChris Mason 	int level;
1930925baeddSChris Mason 	int lowest_unlock = 1;
1931bd681513SChris Mason 	/* everything at write_lock_level or lower must be write locked */
1932bd681513SChris Mason 	int write_lock_level = 0;
19339f3a7427SChris Mason 	u8 lowest_level = 0;
1934f7c79f30SChris Mason 	int min_write_lock_level;
1935d7396f07SFilipe David Borba Manana 	int prev_cmp;
19369f3a7427SChris Mason 
19376702ed49SChris Mason 	lowest_level = p->lowest_level;
1938323ac95bSChris Mason 	WARN_ON(lowest_level && ins_len > 0);
193922b0ebdaSChris Mason 	WARN_ON(p->nodes[0] != NULL);
1940eb653de1SFilipe David Borba Manana 	BUG_ON(!cow && ins_len);
194125179201SJosef Bacik 
1942857bc13fSJosef Bacik 	/*
1943857bc13fSJosef Bacik 	 * For now only allow nowait for read only operations.  There's no
1944857bc13fSJosef Bacik 	 * strict reason why we can't, we just only need it for reads so it's
1945857bc13fSJosef Bacik 	 * only implemented for reads.
1946857bc13fSJosef Bacik 	 */
1947857bc13fSJosef Bacik 	ASSERT(!p->nowait || !cow);
1948857bc13fSJosef Bacik 
1949bd681513SChris Mason 	if (ins_len < 0) {
1950925baeddSChris Mason 		lowest_unlock = 2;
195165b51a00SChris Mason 
1952bd681513SChris Mason 		/* when we are removing items, we might have to go up to level
1953bd681513SChris Mason 		 * two as we update tree pointers  Make sure we keep write
1954bd681513SChris Mason 		 * for those levels as well
1955bd681513SChris Mason 		 */
1956bd681513SChris Mason 		write_lock_level = 2;
1957bd681513SChris Mason 	} else if (ins_len > 0) {
1958bd681513SChris Mason 		/*
1959bd681513SChris Mason 		 * for inserting items, make sure we have a write lock on
1960bd681513SChris Mason 		 * level 1 so we can update keys
1961bd681513SChris Mason 		 */
1962bd681513SChris Mason 		write_lock_level = 1;
1963bd681513SChris Mason 	}
1964bd681513SChris Mason 
1965bd681513SChris Mason 	if (!cow)
1966bd681513SChris Mason 		write_lock_level = -1;
1967bd681513SChris Mason 
196809a2a8f9SJosef Bacik 	if (cow && (p->keep_locks || p->lowest_level))
1969bd681513SChris Mason 		write_lock_level = BTRFS_MAX_LEVEL;
1970bd681513SChris Mason 
1971f7c79f30SChris Mason 	min_write_lock_level = write_lock_level;
1972f7c79f30SChris Mason 
1973d96b3424SFilipe Manana 	if (p->need_commit_sem) {
1974d96b3424SFilipe Manana 		ASSERT(p->search_commit_root);
1975857bc13fSJosef Bacik 		if (p->nowait) {
1976857bc13fSJosef Bacik 			if (!down_read_trylock(&fs_info->commit_root_sem))
1977857bc13fSJosef Bacik 				return -EAGAIN;
1978857bc13fSJosef Bacik 		} else {
1979d96b3424SFilipe Manana 			down_read(&fs_info->commit_root_sem);
1980d96b3424SFilipe Manana 		}
1981857bc13fSJosef Bacik 	}
1982d96b3424SFilipe Manana 
1983bb803951SChris Mason again:
1984d7396f07SFilipe David Borba Manana 	prev_cmp = -1;
19851fc28d8eSLiu Bo 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
1986be6821f8SFilipe Manana 	if (IS_ERR(b)) {
1987be6821f8SFilipe Manana 		ret = PTR_ERR(b);
1988be6821f8SFilipe Manana 		goto done;
1989be6821f8SFilipe Manana 	}
1990925baeddSChris Mason 
1991eb60ceacSChris Mason 	while (b) {
1992f624d976SQu Wenruo 		int dec = 0;
1993f624d976SQu Wenruo 
19945f39d397SChris Mason 		level = btrfs_header_level(b);
199565b51a00SChris Mason 
199602217ed2SChris Mason 		if (cow) {
19979ea2c7c9SNikolay Borisov 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
19989ea2c7c9SNikolay Borisov 
1999c8c42864SChris Mason 			/*
2000c8c42864SChris Mason 			 * if we don't really need to cow this block
2001c8c42864SChris Mason 			 * then we don't want to set the path blocking,
2002c8c42864SChris Mason 			 * so we test it here
2003c8c42864SChris Mason 			 */
20045963ffcaSJosef Bacik 			if (!should_cow_block(trans, root, b))
200565b51a00SChris Mason 				goto cow_done;
20065d4f98a2SYan Zheng 
2007bd681513SChris Mason 			/*
2008bd681513SChris Mason 			 * must have write locks on this node and the
2009bd681513SChris Mason 			 * parent
2010bd681513SChris Mason 			 */
20115124e00eSJosef Bacik 			if (level > write_lock_level ||
20125124e00eSJosef Bacik 			    (level + 1 > write_lock_level &&
20135124e00eSJosef Bacik 			    level + 1 < BTRFS_MAX_LEVEL &&
20145124e00eSJosef Bacik 			    p->nodes[level + 1])) {
2015bd681513SChris Mason 				write_lock_level = level + 1;
2016bd681513SChris Mason 				btrfs_release_path(p);
2017bd681513SChris Mason 				goto again;
2018bd681513SChris Mason 			}
2019bd681513SChris Mason 
20209ea2c7c9SNikolay Borisov 			if (last_level)
20219ea2c7c9SNikolay Borisov 				err = btrfs_cow_block(trans, root, b, NULL, 0,
20229631e4ccSJosef Bacik 						      &b,
20239631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
20249ea2c7c9SNikolay Borisov 			else
202533c66f43SYan Zheng 				err = btrfs_cow_block(trans, root, b,
2026e20d96d6SChris Mason 						      p->nodes[level + 1],
20279631e4ccSJosef Bacik 						      p->slots[level + 1], &b,
20289631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
202933c66f43SYan Zheng 			if (err) {
203033c66f43SYan Zheng 				ret = err;
203165b51a00SChris Mason 				goto done;
203254aa1f4dSChris Mason 			}
203302217ed2SChris Mason 		}
203465b51a00SChris Mason cow_done:
2035eb60ceacSChris Mason 		p->nodes[level] = b;
2036b4ce94deSChris Mason 
2037b4ce94deSChris Mason 		/*
2038b4ce94deSChris Mason 		 * we have a lock on b and as long as we aren't changing
2039b4ce94deSChris Mason 		 * the tree, there is no way to for the items in b to change.
2040b4ce94deSChris Mason 		 * It is safe to drop the lock on our parent before we
2041b4ce94deSChris Mason 		 * go through the expensive btree search on b.
2042b4ce94deSChris Mason 		 *
2043eb653de1SFilipe David Borba Manana 		 * If we're inserting or deleting (ins_len != 0), then we might
2044eb653de1SFilipe David Borba Manana 		 * be changing slot zero, which may require changing the parent.
2045eb653de1SFilipe David Borba Manana 		 * So, we can't drop the lock until after we know which slot
2046eb653de1SFilipe David Borba Manana 		 * we're operating on.
2047b4ce94deSChris Mason 		 */
2048eb653de1SFilipe David Borba Manana 		if (!ins_len && !p->keep_locks) {
2049eb653de1SFilipe David Borba Manana 			int u = level + 1;
2050eb653de1SFilipe David Borba Manana 
2051eb653de1SFilipe David Borba Manana 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2052eb653de1SFilipe David Borba Manana 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2053eb653de1SFilipe David Borba Manana 				p->locks[u] = 0;
2054eb653de1SFilipe David Borba Manana 			}
2055eb653de1SFilipe David Borba Manana 		}
2056b4ce94deSChris Mason 
2057e2e58d0fSFilipe Manana 		if (level == 0) {
2058109324cfSFilipe Manana 			if (ins_len > 0)
2059e5e1c174SFilipe Manana 				ASSERT(write_lock_level >= 1);
2060bd681513SChris Mason 
2061109324cfSFilipe Manana 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2062459931ecSChris Mason 			if (!p->search_for_split)
2063f7c79f30SChris Mason 				unlock_up(p, level, lowest_unlock,
20644b6f8e96SLiu Bo 					  min_write_lock_level, NULL);
206565b51a00SChris Mason 			goto done;
206665b51a00SChris Mason 		}
2067e2e58d0fSFilipe Manana 
2068e2e58d0fSFilipe Manana 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2069e2e58d0fSFilipe Manana 		if (ret < 0)
2070e2e58d0fSFilipe Manana 			goto done;
2071e2e58d0fSFilipe Manana 		prev_cmp = ret;
2072e2e58d0fSFilipe Manana 
2073f624d976SQu Wenruo 		if (ret && slot > 0) {
2074f624d976SQu Wenruo 			dec = 1;
2075f624d976SQu Wenruo 			slot--;
2076f624d976SQu Wenruo 		}
2077f624d976SQu Wenruo 		p->slots[level] = slot;
2078f624d976SQu Wenruo 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2079f624d976SQu Wenruo 					     &write_lock_level);
2080f624d976SQu Wenruo 		if (err == -EAGAIN)
2081f624d976SQu Wenruo 			goto again;
2082f624d976SQu Wenruo 		if (err) {
2083f624d976SQu Wenruo 			ret = err;
2084f624d976SQu Wenruo 			goto done;
2085f624d976SQu Wenruo 		}
2086f624d976SQu Wenruo 		b = p->nodes[level];
2087f624d976SQu Wenruo 		slot = p->slots[level];
2088f624d976SQu Wenruo 
2089f624d976SQu Wenruo 		/*
2090f624d976SQu Wenruo 		 * Slot 0 is special, if we change the key we have to update
2091f624d976SQu Wenruo 		 * the parent pointer which means we must have a write lock on
2092f624d976SQu Wenruo 		 * the parent
2093f624d976SQu Wenruo 		 */
2094f624d976SQu Wenruo 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2095f624d976SQu Wenruo 			write_lock_level = level + 1;
2096f624d976SQu Wenruo 			btrfs_release_path(p);
2097f624d976SQu Wenruo 			goto again;
2098f624d976SQu Wenruo 		}
2099f624d976SQu Wenruo 
2100f624d976SQu Wenruo 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2101f624d976SQu Wenruo 			  &write_lock_level);
2102f624d976SQu Wenruo 
2103f624d976SQu Wenruo 		if (level == lowest_level) {
2104f624d976SQu Wenruo 			if (dec)
2105f624d976SQu Wenruo 				p->slots[level]++;
2106f624d976SQu Wenruo 			goto done;
2107f624d976SQu Wenruo 		}
2108f624d976SQu Wenruo 
2109f624d976SQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
2110f624d976SQu Wenruo 		if (err == -EAGAIN)
2111f624d976SQu Wenruo 			goto again;
2112f624d976SQu Wenruo 		if (err) {
2113f624d976SQu Wenruo 			ret = err;
2114f624d976SQu Wenruo 			goto done;
2115f624d976SQu Wenruo 		}
2116f624d976SQu Wenruo 
2117f624d976SQu Wenruo 		if (!p->skip_locking) {
2118f624d976SQu Wenruo 			level = btrfs_header_level(b);
2119b40130b2SJosef Bacik 
2120b40130b2SJosef Bacik 			btrfs_maybe_reset_lockdep_class(root, b);
2121b40130b2SJosef Bacik 
2122f624d976SQu Wenruo 			if (level <= write_lock_level) {
2123f624d976SQu Wenruo 				btrfs_tree_lock(b);
2124f624d976SQu Wenruo 				p->locks[level] = BTRFS_WRITE_LOCK;
2125f624d976SQu Wenruo 			} else {
2126857bc13fSJosef Bacik 				if (p->nowait) {
2127857bc13fSJosef Bacik 					if (!btrfs_try_tree_read_lock(b)) {
2128857bc13fSJosef Bacik 						free_extent_buffer(b);
2129857bc13fSJosef Bacik 						ret = -EAGAIN;
2130857bc13fSJosef Bacik 						goto done;
2131857bc13fSJosef Bacik 					}
2132857bc13fSJosef Bacik 				} else {
2133fe596ca3SJosef Bacik 					btrfs_tree_read_lock(b);
2134857bc13fSJosef Bacik 				}
2135f624d976SQu Wenruo 				p->locks[level] = BTRFS_READ_LOCK;
2136f624d976SQu Wenruo 			}
2137f624d976SQu Wenruo 			p->nodes[level] = b;
2138f624d976SQu Wenruo 		}
213965b51a00SChris Mason 	}
214065b51a00SChris Mason 	ret = 1;
214165b51a00SChris Mason done:
21425f5bc6b1SFilipe Manana 	if (ret < 0 && !p->skip_release_on_error)
2143b3b4aa74SDavid Sterba 		btrfs_release_path(p);
2144d96b3424SFilipe Manana 
2145d96b3424SFilipe Manana 	if (p->need_commit_sem) {
2146d96b3424SFilipe Manana 		int ret2;
2147d96b3424SFilipe Manana 
2148d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(p);
2149d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
2150d96b3424SFilipe Manana 		if (ret2)
2151d96b3424SFilipe Manana 			ret = ret2;
2152d96b3424SFilipe Manana 	}
2153d96b3424SFilipe Manana 
2154be0e5c09SChris Mason 	return ret;
2155be0e5c09SChris Mason }
2156f75e2b79SJosef Bacik ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2157be0e5c09SChris Mason 
215874123bd7SChris Mason /*
21595d9e75c4SJan Schmidt  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
21605d9e75c4SJan Schmidt  * current state of the tree together with the operations recorded in the tree
21615d9e75c4SJan Schmidt  * modification log to search for the key in a previous version of this tree, as
21625d9e75c4SJan Schmidt  * denoted by the time_seq parameter.
21635d9e75c4SJan Schmidt  *
21645d9e75c4SJan Schmidt  * Naturally, there is no support for insert, delete or cow operations.
21655d9e75c4SJan Schmidt  *
21665d9e75c4SJan Schmidt  * The resulting path and return value will be set up as if we called
21675d9e75c4SJan Schmidt  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
21685d9e75c4SJan Schmidt  */
2169310712b2SOmar Sandoval int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
21705d9e75c4SJan Schmidt 			  struct btrfs_path *p, u64 time_seq)
21715d9e75c4SJan Schmidt {
21720b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
21735d9e75c4SJan Schmidt 	struct extent_buffer *b;
21745d9e75c4SJan Schmidt 	int slot;
21755d9e75c4SJan Schmidt 	int ret;
21765d9e75c4SJan Schmidt 	int err;
21775d9e75c4SJan Schmidt 	int level;
21785d9e75c4SJan Schmidt 	int lowest_unlock = 1;
21795d9e75c4SJan Schmidt 	u8 lowest_level = 0;
21805d9e75c4SJan Schmidt 
21815d9e75c4SJan Schmidt 	lowest_level = p->lowest_level;
21825d9e75c4SJan Schmidt 	WARN_ON(p->nodes[0] != NULL);
2183c922b016SStefan Roesch 	ASSERT(!p->nowait);
21845d9e75c4SJan Schmidt 
21855d9e75c4SJan Schmidt 	if (p->search_commit_root) {
21865d9e75c4SJan Schmidt 		BUG_ON(time_seq);
21875d9e75c4SJan Schmidt 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
21885d9e75c4SJan Schmidt 	}
21895d9e75c4SJan Schmidt 
21905d9e75c4SJan Schmidt again:
2191f3a84ccdSFilipe Manana 	b = btrfs_get_old_root(root, time_seq);
2192315bed43SNikolay Borisov 	if (!b) {
2193315bed43SNikolay Borisov 		ret = -EIO;
2194315bed43SNikolay Borisov 		goto done;
2195315bed43SNikolay Borisov 	}
21965d9e75c4SJan Schmidt 	level = btrfs_header_level(b);
21975d9e75c4SJan Schmidt 	p->locks[level] = BTRFS_READ_LOCK;
21985d9e75c4SJan Schmidt 
21995d9e75c4SJan Schmidt 	while (b) {
2200abe9339dSQu Wenruo 		int dec = 0;
2201abe9339dSQu Wenruo 
22025d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
22035d9e75c4SJan Schmidt 		p->nodes[level] = b;
22045d9e75c4SJan Schmidt 
22055d9e75c4SJan Schmidt 		/*
22065d9e75c4SJan Schmidt 		 * we have a lock on b and as long as we aren't changing
22075d9e75c4SJan Schmidt 		 * the tree, there is no way to for the items in b to change.
22085d9e75c4SJan Schmidt 		 * It is safe to drop the lock on our parent before we
22095d9e75c4SJan Schmidt 		 * go through the expensive btree search on b.
22105d9e75c4SJan Schmidt 		 */
22115d9e75c4SJan Schmidt 		btrfs_unlock_up_safe(p, level + 1);
22125d9e75c4SJan Schmidt 
2213995e9a16SNikolay Borisov 		ret = btrfs_bin_search(b, key, &slot);
2214cbca7d59SFilipe Manana 		if (ret < 0)
2215cbca7d59SFilipe Manana 			goto done;
22165d9e75c4SJan Schmidt 
2217abe9339dSQu Wenruo 		if (level == 0) {
2218abe9339dSQu Wenruo 			p->slots[level] = slot;
2219abe9339dSQu Wenruo 			unlock_up(p, level, lowest_unlock, 0, NULL);
2220abe9339dSQu Wenruo 			goto done;
2221abe9339dSQu Wenruo 		}
2222abe9339dSQu Wenruo 
22235d9e75c4SJan Schmidt 		if (ret && slot > 0) {
22245d9e75c4SJan Schmidt 			dec = 1;
2225abe9339dSQu Wenruo 			slot--;
22265d9e75c4SJan Schmidt 		}
22275d9e75c4SJan Schmidt 		p->slots[level] = slot;
22285d9e75c4SJan Schmidt 		unlock_up(p, level, lowest_unlock, 0, NULL);
22295d9e75c4SJan Schmidt 
22305d9e75c4SJan Schmidt 		if (level == lowest_level) {
22315d9e75c4SJan Schmidt 			if (dec)
22325d9e75c4SJan Schmidt 				p->slots[level]++;
22335d9e75c4SJan Schmidt 			goto done;
22345d9e75c4SJan Schmidt 		}
22355d9e75c4SJan Schmidt 
2236abe9339dSQu Wenruo 		err = read_block_for_search(root, p, &b, level, slot, key);
22375d9e75c4SJan Schmidt 		if (err == -EAGAIN)
22385d9e75c4SJan Schmidt 			goto again;
22395d9e75c4SJan Schmidt 		if (err) {
22405d9e75c4SJan Schmidt 			ret = err;
22415d9e75c4SJan Schmidt 			goto done;
22425d9e75c4SJan Schmidt 		}
22435d9e75c4SJan Schmidt 
22445d9e75c4SJan Schmidt 		level = btrfs_header_level(b);
22455d9e75c4SJan Schmidt 		btrfs_tree_read_lock(b);
2246f3a84ccdSFilipe Manana 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2247db7f3436SJosef Bacik 		if (!b) {
2248db7f3436SJosef Bacik 			ret = -ENOMEM;
2249db7f3436SJosef Bacik 			goto done;
2250db7f3436SJosef Bacik 		}
22515d9e75c4SJan Schmidt 		p->locks[level] = BTRFS_READ_LOCK;
22525d9e75c4SJan Schmidt 		p->nodes[level] = b;
22535d9e75c4SJan Schmidt 	}
22545d9e75c4SJan Schmidt 	ret = 1;
22555d9e75c4SJan Schmidt done:
22565d9e75c4SJan Schmidt 	if (ret < 0)
22575d9e75c4SJan Schmidt 		btrfs_release_path(p);
22585d9e75c4SJan Schmidt 
22595d9e75c4SJan Schmidt 	return ret;
22605d9e75c4SJan Schmidt }
22615d9e75c4SJan Schmidt 
22625d9e75c4SJan Schmidt /*
22632f38b3e1SArne Jansen  * helper to use instead of search slot if no exact match is needed but
22642f38b3e1SArne Jansen  * instead the next or previous item should be returned.
22652f38b3e1SArne Jansen  * When find_higher is true, the next higher item is returned, the next lower
22662f38b3e1SArne Jansen  * otherwise.
22672f38b3e1SArne Jansen  * When return_any and find_higher are both true, and no higher item is found,
22682f38b3e1SArne Jansen  * return the next lower instead.
22692f38b3e1SArne Jansen  * When return_any is true and find_higher is false, and no lower item is found,
22702f38b3e1SArne Jansen  * return the next higher instead.
22712f38b3e1SArne Jansen  * It returns 0 if any item is found, 1 if none is found (tree empty), and
22722f38b3e1SArne Jansen  * < 0 on error
22732f38b3e1SArne Jansen  */
22742f38b3e1SArne Jansen int btrfs_search_slot_for_read(struct btrfs_root *root,
2275310712b2SOmar Sandoval 			       const struct btrfs_key *key,
2276310712b2SOmar Sandoval 			       struct btrfs_path *p, int find_higher,
2277310712b2SOmar Sandoval 			       int return_any)
22782f38b3e1SArne Jansen {
22792f38b3e1SArne Jansen 	int ret;
22802f38b3e1SArne Jansen 	struct extent_buffer *leaf;
22812f38b3e1SArne Jansen 
22822f38b3e1SArne Jansen again:
22832f38b3e1SArne Jansen 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
22842f38b3e1SArne Jansen 	if (ret <= 0)
22852f38b3e1SArne Jansen 		return ret;
22862f38b3e1SArne Jansen 	/*
22872f38b3e1SArne Jansen 	 * a return value of 1 means the path is at the position where the
22882f38b3e1SArne Jansen 	 * item should be inserted. Normally this is the next bigger item,
22892f38b3e1SArne Jansen 	 * but in case the previous item is the last in a leaf, path points
22902f38b3e1SArne Jansen 	 * to the first free slot in the previous leaf, i.e. at an invalid
22912f38b3e1SArne Jansen 	 * item.
22922f38b3e1SArne Jansen 	 */
22932f38b3e1SArne Jansen 	leaf = p->nodes[0];
22942f38b3e1SArne Jansen 
22952f38b3e1SArne Jansen 	if (find_higher) {
22962f38b3e1SArne Jansen 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
22972f38b3e1SArne Jansen 			ret = btrfs_next_leaf(root, p);
22982f38b3e1SArne Jansen 			if (ret <= 0)
22992f38b3e1SArne Jansen 				return ret;
23002f38b3e1SArne Jansen 			if (!return_any)
23012f38b3e1SArne Jansen 				return 1;
23022f38b3e1SArne Jansen 			/*
23032f38b3e1SArne Jansen 			 * no higher item found, return the next
23042f38b3e1SArne Jansen 			 * lower instead
23052f38b3e1SArne Jansen 			 */
23062f38b3e1SArne Jansen 			return_any = 0;
23072f38b3e1SArne Jansen 			find_higher = 0;
23082f38b3e1SArne Jansen 			btrfs_release_path(p);
23092f38b3e1SArne Jansen 			goto again;
23102f38b3e1SArne Jansen 		}
23112f38b3e1SArne Jansen 	} else {
23122f38b3e1SArne Jansen 		if (p->slots[0] == 0) {
23132f38b3e1SArne Jansen 			ret = btrfs_prev_leaf(root, p);
2314e6793769SArne Jansen 			if (ret < 0)
23152f38b3e1SArne Jansen 				return ret;
2316e6793769SArne Jansen 			if (!ret) {
231723c6bf6aSFilipe David Borba Manana 				leaf = p->nodes[0];
231823c6bf6aSFilipe David Borba Manana 				if (p->slots[0] == btrfs_header_nritems(leaf))
231923c6bf6aSFilipe David Borba Manana 					p->slots[0]--;
2320e6793769SArne Jansen 				return 0;
2321e6793769SArne Jansen 			}
23222f38b3e1SArne Jansen 			if (!return_any)
23232f38b3e1SArne Jansen 				return 1;
23242f38b3e1SArne Jansen 			/*
23252f38b3e1SArne Jansen 			 * no lower item found, return the next
23262f38b3e1SArne Jansen 			 * higher instead
23272f38b3e1SArne Jansen 			 */
23282f38b3e1SArne Jansen 			return_any = 0;
23292f38b3e1SArne Jansen 			find_higher = 1;
23302f38b3e1SArne Jansen 			btrfs_release_path(p);
23312f38b3e1SArne Jansen 			goto again;
2332e6793769SArne Jansen 		} else {
23332f38b3e1SArne Jansen 			--p->slots[0];
23342f38b3e1SArne Jansen 		}
23352f38b3e1SArne Jansen 	}
23362f38b3e1SArne Jansen 	return 0;
23372f38b3e1SArne Jansen }
23382f38b3e1SArne Jansen 
23392f38b3e1SArne Jansen /*
23400ff40a91SMarcos Paulo de Souza  * Execute search and call btrfs_previous_item to traverse backwards if the item
23410ff40a91SMarcos Paulo de Souza  * was not found.
23420ff40a91SMarcos Paulo de Souza  *
23430ff40a91SMarcos Paulo de Souza  * Return 0 if found, 1 if not found and < 0 if error.
23440ff40a91SMarcos Paulo de Souza  */
23450ff40a91SMarcos Paulo de Souza int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
23460ff40a91SMarcos Paulo de Souza 			   struct btrfs_path *path)
23470ff40a91SMarcos Paulo de Souza {
23480ff40a91SMarcos Paulo de Souza 	int ret;
23490ff40a91SMarcos Paulo de Souza 
23500ff40a91SMarcos Paulo de Souza 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
23510ff40a91SMarcos Paulo de Souza 	if (ret > 0)
23520ff40a91SMarcos Paulo de Souza 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
23530ff40a91SMarcos Paulo de Souza 
23540ff40a91SMarcos Paulo de Souza 	if (ret == 0)
23550ff40a91SMarcos Paulo de Souza 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
23560ff40a91SMarcos Paulo de Souza 
23570ff40a91SMarcos Paulo de Souza 	return ret;
23580ff40a91SMarcos Paulo de Souza }
23590ff40a91SMarcos Paulo de Souza 
236062142be3SGabriel Niebler /**
236162142be3SGabriel Niebler  * Search for a valid slot for the given path.
236262142be3SGabriel Niebler  *
236362142be3SGabriel Niebler  * @root:	The root node of the tree.
236462142be3SGabriel Niebler  * @key:	Will contain a valid item if found.
236562142be3SGabriel Niebler  * @path:	The starting point to validate the slot.
236662142be3SGabriel Niebler  *
236762142be3SGabriel Niebler  * Return: 0  if the item is valid
236862142be3SGabriel Niebler  *         1  if not found
236962142be3SGabriel Niebler  *         <0 if error.
237062142be3SGabriel Niebler  */
237162142be3SGabriel Niebler int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
237262142be3SGabriel Niebler 			      struct btrfs_path *path)
237362142be3SGabriel Niebler {
237462142be3SGabriel Niebler 	while (1) {
237562142be3SGabriel Niebler 		int ret;
237662142be3SGabriel Niebler 		const int slot = path->slots[0];
237762142be3SGabriel Niebler 		const struct extent_buffer *leaf = path->nodes[0];
237862142be3SGabriel Niebler 
237962142be3SGabriel Niebler 		/* This is where we start walking the path. */
238062142be3SGabriel Niebler 		if (slot >= btrfs_header_nritems(leaf)) {
238162142be3SGabriel Niebler 			/*
238262142be3SGabriel Niebler 			 * If we've reached the last slot in this leaf we need
238362142be3SGabriel Niebler 			 * to go to the next leaf and reset the path.
238462142be3SGabriel Niebler 			 */
238562142be3SGabriel Niebler 			ret = btrfs_next_leaf(root, path);
238662142be3SGabriel Niebler 			if (ret)
238762142be3SGabriel Niebler 				return ret;
238862142be3SGabriel Niebler 			continue;
238962142be3SGabriel Niebler 		}
239062142be3SGabriel Niebler 		/* Store the found, valid item in @key. */
239162142be3SGabriel Niebler 		btrfs_item_key_to_cpu(leaf, key, slot);
239262142be3SGabriel Niebler 		break;
239362142be3SGabriel Niebler 	}
239462142be3SGabriel Niebler 	return 0;
239562142be3SGabriel Niebler }
239662142be3SGabriel Niebler 
23970ff40a91SMarcos Paulo de Souza /*
239874123bd7SChris Mason  * adjust the pointers going up the tree, starting at level
239974123bd7SChris Mason  * making sure the right key of each node is points to 'key'.
240074123bd7SChris Mason  * This is used after shifting pointers to the left, so it stops
240174123bd7SChris Mason  * fixing up pointers when a given leaf/node is not in slot 0 of the
240274123bd7SChris Mason  * higher levels
2403aa5d6bedSChris Mason  *
240474123bd7SChris Mason  */
2405b167fa91SNikolay Borisov static void fixup_low_keys(struct btrfs_path *path,
24065f39d397SChris Mason 			   struct btrfs_disk_key *key, int level)
2407be0e5c09SChris Mason {
2408be0e5c09SChris Mason 	int i;
24095f39d397SChris Mason 	struct extent_buffer *t;
24100e82bcfeSDavid Sterba 	int ret;
24115f39d397SChris Mason 
2412234b63a0SChris Mason 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2413be0e5c09SChris Mason 		int tslot = path->slots[i];
24140e82bcfeSDavid Sterba 
2415eb60ceacSChris Mason 		if (!path->nodes[i])
2416be0e5c09SChris Mason 			break;
24175f39d397SChris Mason 		t = path->nodes[i];
2418f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
2419f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REPLACE, GFP_ATOMIC);
24200e82bcfeSDavid Sterba 		BUG_ON(ret < 0);
24215f39d397SChris Mason 		btrfs_set_node_key(t, key, tslot);
2422d6025579SChris Mason 		btrfs_mark_buffer_dirty(path->nodes[i]);
2423be0e5c09SChris Mason 		if (tslot != 0)
2424be0e5c09SChris Mason 			break;
2425be0e5c09SChris Mason 	}
2426be0e5c09SChris Mason }
2427be0e5c09SChris Mason 
242874123bd7SChris Mason /*
242931840ae1SZheng Yan  * update item key.
243031840ae1SZheng Yan  *
243131840ae1SZheng Yan  * This function isn't completely safe. It's the caller's responsibility
243231840ae1SZheng Yan  * that the new key won't break the order
243331840ae1SZheng Yan  */
2434b7a0365eSDaniel Dressler void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2435b7a0365eSDaniel Dressler 			     struct btrfs_path *path,
2436310712b2SOmar Sandoval 			     const struct btrfs_key *new_key)
243731840ae1SZheng Yan {
243831840ae1SZheng Yan 	struct btrfs_disk_key disk_key;
243931840ae1SZheng Yan 	struct extent_buffer *eb;
244031840ae1SZheng Yan 	int slot;
244131840ae1SZheng Yan 
244231840ae1SZheng Yan 	eb = path->nodes[0];
244331840ae1SZheng Yan 	slot = path->slots[0];
244431840ae1SZheng Yan 	if (slot > 0) {
244531840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot - 1);
24467c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
24477c15d410SQu Wenruo 			btrfs_crit(fs_info,
24487c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
24497c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
24507c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
24517c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
24527c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
24537c15d410SQu Wenruo 				   new_key->offset);
24547c15d410SQu Wenruo 			btrfs_print_leaf(eb);
24557c15d410SQu Wenruo 			BUG();
24567c15d410SQu Wenruo 		}
245731840ae1SZheng Yan 	}
245831840ae1SZheng Yan 	if (slot < btrfs_header_nritems(eb) - 1) {
245931840ae1SZheng Yan 		btrfs_item_key(eb, &disk_key, slot + 1);
24607c15d410SQu Wenruo 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
24617c15d410SQu Wenruo 			btrfs_crit(fs_info,
24627c15d410SQu Wenruo 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
24637c15d410SQu Wenruo 				   slot, btrfs_disk_key_objectid(&disk_key),
24647c15d410SQu Wenruo 				   btrfs_disk_key_type(&disk_key),
24657c15d410SQu Wenruo 				   btrfs_disk_key_offset(&disk_key),
24667c15d410SQu Wenruo 				   new_key->objectid, new_key->type,
24677c15d410SQu Wenruo 				   new_key->offset);
24687c15d410SQu Wenruo 			btrfs_print_leaf(eb);
24697c15d410SQu Wenruo 			BUG();
24707c15d410SQu Wenruo 		}
247131840ae1SZheng Yan 	}
247231840ae1SZheng Yan 
247331840ae1SZheng Yan 	btrfs_cpu_key_to_disk(&disk_key, new_key);
247431840ae1SZheng Yan 	btrfs_set_item_key(eb, &disk_key, slot);
247531840ae1SZheng Yan 	btrfs_mark_buffer_dirty(eb);
247631840ae1SZheng Yan 	if (slot == 0)
2477b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
247831840ae1SZheng Yan }
247931840ae1SZheng Yan 
248031840ae1SZheng Yan /*
2481d16c702fSQu Wenruo  * Check key order of two sibling extent buffers.
2482d16c702fSQu Wenruo  *
2483d16c702fSQu Wenruo  * Return true if something is wrong.
2484d16c702fSQu Wenruo  * Return false if everything is fine.
2485d16c702fSQu Wenruo  *
2486d16c702fSQu Wenruo  * Tree-checker only works inside one tree block, thus the following
2487d16c702fSQu Wenruo  * corruption can not be detected by tree-checker:
2488d16c702fSQu Wenruo  *
2489d16c702fSQu Wenruo  * Leaf @left			| Leaf @right
2490d16c702fSQu Wenruo  * --------------------------------------------------------------
2491d16c702fSQu Wenruo  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2492d16c702fSQu Wenruo  *
2493d16c702fSQu Wenruo  * Key f6 in leaf @left itself is valid, but not valid when the next
2494d16c702fSQu Wenruo  * key in leaf @right is 7.
2495d16c702fSQu Wenruo  * This can only be checked at tree block merge time.
2496d16c702fSQu Wenruo  * And since tree checker has ensured all key order in each tree block
2497d16c702fSQu Wenruo  * is correct, we only need to bother the last key of @left and the first
2498d16c702fSQu Wenruo  * key of @right.
2499d16c702fSQu Wenruo  */
2500d16c702fSQu Wenruo static bool check_sibling_keys(struct extent_buffer *left,
2501d16c702fSQu Wenruo 			       struct extent_buffer *right)
2502d16c702fSQu Wenruo {
2503d16c702fSQu Wenruo 	struct btrfs_key left_last;
2504d16c702fSQu Wenruo 	struct btrfs_key right_first;
2505d16c702fSQu Wenruo 	int level = btrfs_header_level(left);
2506d16c702fSQu Wenruo 	int nr_left = btrfs_header_nritems(left);
2507d16c702fSQu Wenruo 	int nr_right = btrfs_header_nritems(right);
2508d16c702fSQu Wenruo 
2509d16c702fSQu Wenruo 	/* No key to check in one of the tree blocks */
2510d16c702fSQu Wenruo 	if (!nr_left || !nr_right)
2511d16c702fSQu Wenruo 		return false;
2512d16c702fSQu Wenruo 
2513d16c702fSQu Wenruo 	if (level) {
2514d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2515d16c702fSQu Wenruo 		btrfs_node_key_to_cpu(right, &right_first, 0);
2516d16c702fSQu Wenruo 	} else {
2517d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2518d16c702fSQu Wenruo 		btrfs_item_key_to_cpu(right, &right_first, 0);
2519d16c702fSQu Wenruo 	}
2520d16c702fSQu Wenruo 
2521d16c702fSQu Wenruo 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2522d16c702fSQu Wenruo 		btrfs_crit(left->fs_info,
2523d16c702fSQu Wenruo "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2524d16c702fSQu Wenruo 			   left_last.objectid, left_last.type,
2525d16c702fSQu Wenruo 			   left_last.offset, right_first.objectid,
2526d16c702fSQu Wenruo 			   right_first.type, right_first.offset);
2527d16c702fSQu Wenruo 		return true;
2528d16c702fSQu Wenruo 	}
2529d16c702fSQu Wenruo 	return false;
2530d16c702fSQu Wenruo }
2531d16c702fSQu Wenruo 
2532d16c702fSQu Wenruo /*
253374123bd7SChris Mason  * try to push data from one node into the next node left in the
253479f95c82SChris Mason  * tree.
2535aa5d6bedSChris Mason  *
2536aa5d6bedSChris Mason  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2537aa5d6bedSChris Mason  * error, and > 0 if there was no room in the left hand block.
253874123bd7SChris Mason  */
253998ed5174SChris Mason static int push_node_left(struct btrfs_trans_handle *trans,
25402ff7e61eSJeff Mahoney 			  struct extent_buffer *dst,
2541971a1f66SChris Mason 			  struct extent_buffer *src, int empty)
2542be0e5c09SChris Mason {
2543d30a668fSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
2544be0e5c09SChris Mason 	int push_items = 0;
2545bb803951SChris Mason 	int src_nritems;
2546bb803951SChris Mason 	int dst_nritems;
2547aa5d6bedSChris Mason 	int ret = 0;
2548be0e5c09SChris Mason 
25495f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
25505f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
25510b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
25527bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
25537bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
255454aa1f4dSChris Mason 
2555bce4eae9SChris Mason 	if (!empty && src_nritems <= 8)
2556971a1f66SChris Mason 		return 1;
2557971a1f66SChris Mason 
2558d397712bSChris Mason 	if (push_items <= 0)
2559be0e5c09SChris Mason 		return 1;
2560be0e5c09SChris Mason 
2561bce4eae9SChris Mason 	if (empty) {
2562971a1f66SChris Mason 		push_items = min(src_nritems, push_items);
2563bce4eae9SChris Mason 		if (push_items < src_nritems) {
2564bce4eae9SChris Mason 			/* leave at least 8 pointers in the node if
2565bce4eae9SChris Mason 			 * we aren't going to empty it
2566bce4eae9SChris Mason 			 */
2567bce4eae9SChris Mason 			if (src_nritems - push_items < 8) {
2568bce4eae9SChris Mason 				if (push_items <= 8)
2569bce4eae9SChris Mason 					return 1;
2570bce4eae9SChris Mason 				push_items -= 8;
2571bce4eae9SChris Mason 			}
2572bce4eae9SChris Mason 		}
2573bce4eae9SChris Mason 	} else
2574bce4eae9SChris Mason 		push_items = min(src_nritems - 8, push_items);
257579f95c82SChris Mason 
2576d16c702fSQu Wenruo 	/* dst is the left eb, src is the middle eb */
2577d16c702fSQu Wenruo 	if (check_sibling_keys(dst, src)) {
2578d16c702fSQu Wenruo 		ret = -EUCLEAN;
2579d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2580d16c702fSQu Wenruo 		return ret;
2581d16c702fSQu Wenruo 	}
2582f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
25835de865eeSFilipe David Borba Manana 	if (ret) {
258466642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
25855de865eeSFilipe David Borba Manana 		return ret;
25865de865eeSFilipe David Borba Manana 	}
25875f39d397SChris Mason 	copy_extent_buffer(dst, src,
25885f39d397SChris Mason 			   btrfs_node_key_ptr_offset(dst_nritems),
25895f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
2590123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
25915f39d397SChris Mason 
2592bb803951SChris Mason 	if (push_items < src_nritems) {
259357911b8bSJan Schmidt 		/*
2594f3a84ccdSFilipe Manana 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2595f3a84ccdSFilipe Manana 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
259657911b8bSJan Schmidt 		 */
25975f39d397SChris Mason 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
25985f39d397SChris Mason 				      btrfs_node_key_ptr_offset(push_items),
2599e2fa7227SChris Mason 				      (src_nritems - push_items) *
2600123abc88SChris Mason 				      sizeof(struct btrfs_key_ptr));
2601bb803951SChris Mason 	}
26025f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
26035f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
26045f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
26055f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
260631840ae1SZheng Yan 
2607bb803951SChris Mason 	return ret;
2608be0e5c09SChris Mason }
2609be0e5c09SChris Mason 
261097571fd0SChris Mason /*
261179f95c82SChris Mason  * try to push data from one node into the next node right in the
261279f95c82SChris Mason  * tree.
261379f95c82SChris Mason  *
261479f95c82SChris Mason  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
261579f95c82SChris Mason  * error, and > 0 if there was no room in the right hand block.
261679f95c82SChris Mason  *
261779f95c82SChris Mason  * this will  only push up to 1/2 the contents of the left node over
261879f95c82SChris Mason  */
26195f39d397SChris Mason static int balance_node_right(struct btrfs_trans_handle *trans,
26205f39d397SChris Mason 			      struct extent_buffer *dst,
26215f39d397SChris Mason 			      struct extent_buffer *src)
262279f95c82SChris Mason {
262355d32ed8SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
262479f95c82SChris Mason 	int push_items = 0;
262579f95c82SChris Mason 	int max_push;
262679f95c82SChris Mason 	int src_nritems;
262779f95c82SChris Mason 	int dst_nritems;
262879f95c82SChris Mason 	int ret = 0;
262979f95c82SChris Mason 
26307bb86316SChris Mason 	WARN_ON(btrfs_header_generation(src) != trans->transid);
26317bb86316SChris Mason 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
26327bb86316SChris Mason 
26335f39d397SChris Mason 	src_nritems = btrfs_header_nritems(src);
26345f39d397SChris Mason 	dst_nritems = btrfs_header_nritems(dst);
26350b246afaSJeff Mahoney 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2636d397712bSChris Mason 	if (push_items <= 0)
263779f95c82SChris Mason 		return 1;
2638bce4eae9SChris Mason 
2639d397712bSChris Mason 	if (src_nritems < 4)
2640bce4eae9SChris Mason 		return 1;
264179f95c82SChris Mason 
264279f95c82SChris Mason 	max_push = src_nritems / 2 + 1;
264379f95c82SChris Mason 	/* don't try to empty the node */
2644d397712bSChris Mason 	if (max_push >= src_nritems)
264579f95c82SChris Mason 		return 1;
2646252c38f0SYan 
264779f95c82SChris Mason 	if (max_push < push_items)
264879f95c82SChris Mason 		push_items = max_push;
264979f95c82SChris Mason 
2650d16c702fSQu Wenruo 	/* dst is the right eb, src is the middle eb */
2651d16c702fSQu Wenruo 	if (check_sibling_keys(src, dst)) {
2652d16c702fSQu Wenruo 		ret = -EUCLEAN;
2653d16c702fSQu Wenruo 		btrfs_abort_transaction(trans, ret);
2654d16c702fSQu Wenruo 		return ret;
2655d16c702fSQu Wenruo 	}
2656f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2657bf1d3425SDavid Sterba 	BUG_ON(ret < 0);
26585f39d397SChris Mason 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
26595f39d397SChris Mason 				      btrfs_node_key_ptr_offset(0),
26605f39d397SChris Mason 				      (dst_nritems) *
26615f39d397SChris Mason 				      sizeof(struct btrfs_key_ptr));
2662d6025579SChris Mason 
2663f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2664ed874f0dSDavid Sterba 					 push_items);
26655de865eeSFilipe David Borba Manana 	if (ret) {
266666642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
26675de865eeSFilipe David Borba Manana 		return ret;
26685de865eeSFilipe David Borba Manana 	}
26695f39d397SChris Mason 	copy_extent_buffer(dst, src,
26705f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
26715f39d397SChris Mason 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2672123abc88SChris Mason 			   push_items * sizeof(struct btrfs_key_ptr));
267379f95c82SChris Mason 
26745f39d397SChris Mason 	btrfs_set_header_nritems(src, src_nritems - push_items);
26755f39d397SChris Mason 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
267679f95c82SChris Mason 
26775f39d397SChris Mason 	btrfs_mark_buffer_dirty(src);
26785f39d397SChris Mason 	btrfs_mark_buffer_dirty(dst);
267931840ae1SZheng Yan 
268079f95c82SChris Mason 	return ret;
268179f95c82SChris Mason }
268279f95c82SChris Mason 
268379f95c82SChris Mason /*
268497571fd0SChris Mason  * helper function to insert a new root level in the tree.
268597571fd0SChris Mason  * A new node is allocated, and a single item is inserted to
268697571fd0SChris Mason  * point to the existing root
2687aa5d6bedSChris Mason  *
2688aa5d6bedSChris Mason  * returns zero on success or < 0 on failure.
268997571fd0SChris Mason  */
2690d397712bSChris Mason static noinline int insert_new_root(struct btrfs_trans_handle *trans,
26915f39d397SChris Mason 			   struct btrfs_root *root,
2692fdd99c72SLiu Bo 			   struct btrfs_path *path, int level)
269374123bd7SChris Mason {
26940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
26957bb86316SChris Mason 	u64 lower_gen;
26965f39d397SChris Mason 	struct extent_buffer *lower;
26975f39d397SChris Mason 	struct extent_buffer *c;
2698925baeddSChris Mason 	struct extent_buffer *old;
26995f39d397SChris Mason 	struct btrfs_disk_key lower_key;
2700d9d19a01SDavid Sterba 	int ret;
27015c680ed6SChris Mason 
27025c680ed6SChris Mason 	BUG_ON(path->nodes[level]);
27035c680ed6SChris Mason 	BUG_ON(path->nodes[level-1] != root->node);
27045c680ed6SChris Mason 
27057bb86316SChris Mason 	lower = path->nodes[level-1];
27067bb86316SChris Mason 	if (level == 1)
27077bb86316SChris Mason 		btrfs_item_key(lower, &lower_key, 0);
27087bb86316SChris Mason 	else
27097bb86316SChris Mason 		btrfs_node_key(lower, &lower_key, 0);
27107bb86316SChris Mason 
271179bd3712SFilipe Manana 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
271279bd3712SFilipe Manana 				   &lower_key, level, root->node->start, 0,
2713cf6f34aaSJosef Bacik 				   BTRFS_NESTING_NEW_ROOT);
27145f39d397SChris Mason 	if (IS_ERR(c))
27155f39d397SChris Mason 		return PTR_ERR(c);
2716925baeddSChris Mason 
27170b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2718f0486c68SYan, Zheng 
27195f39d397SChris Mason 	btrfs_set_header_nritems(c, 1);
27205f39d397SChris Mason 	btrfs_set_node_key(c, &lower_key, 0);
2721db94535dSChris Mason 	btrfs_set_node_blockptr(c, 0, lower->start);
27227bb86316SChris Mason 	lower_gen = btrfs_header_generation(lower);
272331840ae1SZheng Yan 	WARN_ON(lower_gen != trans->transid);
27247bb86316SChris Mason 
27257bb86316SChris Mason 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
27265f39d397SChris Mason 
27275f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
2728d5719762SChris Mason 
2729925baeddSChris Mason 	old = root->node;
2730406808abSFilipe Manana 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2731d9d19a01SDavid Sterba 	BUG_ON(ret < 0);
2732240f62c8SChris Mason 	rcu_assign_pointer(root->node, c);
2733925baeddSChris Mason 
2734925baeddSChris Mason 	/* the super has an extra ref to root->node */
2735925baeddSChris Mason 	free_extent_buffer(old);
2736925baeddSChris Mason 
27370b86a832SChris Mason 	add_root_to_dirty_list(root);
273867439dadSDavid Sterba 	atomic_inc(&c->refs);
27395f39d397SChris Mason 	path->nodes[level] = c;
2740ac5887c8SJosef Bacik 	path->locks[level] = BTRFS_WRITE_LOCK;
274174123bd7SChris Mason 	path->slots[level] = 0;
274274123bd7SChris Mason 	return 0;
274374123bd7SChris Mason }
27445c680ed6SChris Mason 
27455c680ed6SChris Mason /*
27465c680ed6SChris Mason  * worker function to insert a single pointer in a node.
27475c680ed6SChris Mason  * the node should have enough room for the pointer already
274897571fd0SChris Mason  *
27495c680ed6SChris Mason  * slot and level indicate where you want the key to go, and
27505c680ed6SChris Mason  * blocknr is the block the key points to.
27515c680ed6SChris Mason  */
2752143bede5SJeff Mahoney static void insert_ptr(struct btrfs_trans_handle *trans,
27536ad3cf6dSDavid Sterba 		       struct btrfs_path *path,
2754143bede5SJeff Mahoney 		       struct btrfs_disk_key *key, u64 bytenr,
2755c3e06965SJan Schmidt 		       int slot, int level)
27565c680ed6SChris Mason {
27575f39d397SChris Mason 	struct extent_buffer *lower;
27585c680ed6SChris Mason 	int nritems;
2759f3ea38daSJan Schmidt 	int ret;
27605c680ed6SChris Mason 
27615c680ed6SChris Mason 	BUG_ON(!path->nodes[level]);
276249d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[level]);
27635f39d397SChris Mason 	lower = path->nodes[level];
27645f39d397SChris Mason 	nritems = btrfs_header_nritems(lower);
2765c293498bSStoyan Gaydarov 	BUG_ON(slot > nritems);
27666ad3cf6dSDavid Sterba 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
276774123bd7SChris Mason 	if (slot != nritems) {
2768bf1d3425SDavid Sterba 		if (level) {
2769f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2770f3a84ccdSFilipe Manana 					slot, nritems - slot);
2771bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
2772bf1d3425SDavid Sterba 		}
27735f39d397SChris Mason 		memmove_extent_buffer(lower,
27745f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
27755f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
2776123abc88SChris Mason 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
277774123bd7SChris Mason 	}
2778c3e06965SJan Schmidt 	if (level) {
2779f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
2780f3a84ccdSFilipe Manana 					    BTRFS_MOD_LOG_KEY_ADD, GFP_NOFS);
2781f3ea38daSJan Schmidt 		BUG_ON(ret < 0);
2782f3ea38daSJan Schmidt 	}
27835f39d397SChris Mason 	btrfs_set_node_key(lower, key, slot);
2784db94535dSChris Mason 	btrfs_set_node_blockptr(lower, slot, bytenr);
278574493f7aSChris Mason 	WARN_ON(trans->transid == 0);
278674493f7aSChris Mason 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
27875f39d397SChris Mason 	btrfs_set_header_nritems(lower, nritems + 1);
27885f39d397SChris Mason 	btrfs_mark_buffer_dirty(lower);
278974123bd7SChris Mason }
279074123bd7SChris Mason 
279197571fd0SChris Mason /*
279297571fd0SChris Mason  * split the node at the specified level in path in two.
279397571fd0SChris Mason  * The path is corrected to point to the appropriate node after the split
279497571fd0SChris Mason  *
279597571fd0SChris Mason  * Before splitting this tries to make some room in the node by pushing
279697571fd0SChris Mason  * left and right, if either one works, it returns right away.
2797aa5d6bedSChris Mason  *
2798aa5d6bedSChris Mason  * returns 0 on success and < 0 on failure
279997571fd0SChris Mason  */
2800e02119d5SChris Mason static noinline int split_node(struct btrfs_trans_handle *trans,
2801e02119d5SChris Mason 			       struct btrfs_root *root,
2802e02119d5SChris Mason 			       struct btrfs_path *path, int level)
2803be0e5c09SChris Mason {
28040b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
28055f39d397SChris Mason 	struct extent_buffer *c;
28065f39d397SChris Mason 	struct extent_buffer *split;
28075f39d397SChris Mason 	struct btrfs_disk_key disk_key;
2808be0e5c09SChris Mason 	int mid;
28095c680ed6SChris Mason 	int ret;
28107518a238SChris Mason 	u32 c_nritems;
2811be0e5c09SChris Mason 
28125f39d397SChris Mason 	c = path->nodes[level];
28137bb86316SChris Mason 	WARN_ON(btrfs_header_generation(c) != trans->transid);
28145f39d397SChris Mason 	if (c == root->node) {
2815d9abbf1cSJan Schmidt 		/*
281690f8d62eSJan Schmidt 		 * trying to split the root, lets make a new one
281790f8d62eSJan Schmidt 		 *
2818fdd99c72SLiu Bo 		 * tree mod log: We don't log_removal old root in
281990f8d62eSJan Schmidt 		 * insert_new_root, because that root buffer will be kept as a
282090f8d62eSJan Schmidt 		 * normal node. We are going to log removal of half of the
2821f3a84ccdSFilipe Manana 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2822f3a84ccdSFilipe Manana 		 * holding a tree lock on the buffer, which is why we cannot
2823f3a84ccdSFilipe Manana 		 * race with other tree_mod_log users.
2824d9abbf1cSJan Schmidt 		 */
2825fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, level + 1);
28265c680ed6SChris Mason 		if (ret)
28275c680ed6SChris Mason 			return ret;
2828b3612421SChris Mason 	} else {
2829e66f709bSChris Mason 		ret = push_nodes_for_insert(trans, root, path, level);
28305f39d397SChris Mason 		c = path->nodes[level];
28315f39d397SChris Mason 		if (!ret && btrfs_header_nritems(c) <
28320b246afaSJeff Mahoney 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2833e66f709bSChris Mason 			return 0;
283454aa1f4dSChris Mason 		if (ret < 0)
283554aa1f4dSChris Mason 			return ret;
28365c680ed6SChris Mason 	}
2837e66f709bSChris Mason 
28385f39d397SChris Mason 	c_nritems = btrfs_header_nritems(c);
28395d4f98a2SYan Zheng 	mid = (c_nritems + 1) / 2;
28405d4f98a2SYan Zheng 	btrfs_node_key(c, &disk_key, mid);
28417bb86316SChris Mason 
284279bd3712SFilipe Manana 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
284379bd3712SFilipe Manana 				       &disk_key, level, c->start, 0,
284479bd3712SFilipe Manana 				       BTRFS_NESTING_SPLIT);
28455f39d397SChris Mason 	if (IS_ERR(split))
28465f39d397SChris Mason 		return PTR_ERR(split);
284754aa1f4dSChris Mason 
28480b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
2849bc877d28SNikolay Borisov 	ASSERT(btrfs_header_level(c) == level);
28505f39d397SChris Mason 
2851f3a84ccdSFilipe Manana 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
28525de865eeSFilipe David Borba Manana 	if (ret) {
285366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
28545de865eeSFilipe David Borba Manana 		return ret;
28555de865eeSFilipe David Borba Manana 	}
28565f39d397SChris Mason 	copy_extent_buffer(split, c,
28575f39d397SChris Mason 			   btrfs_node_key_ptr_offset(0),
28585f39d397SChris Mason 			   btrfs_node_key_ptr_offset(mid),
2859123abc88SChris Mason 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
28605f39d397SChris Mason 	btrfs_set_header_nritems(split, c_nritems - mid);
28615f39d397SChris Mason 	btrfs_set_header_nritems(c, mid);
2862aa5d6bedSChris Mason 
28635f39d397SChris Mason 	btrfs_mark_buffer_dirty(c);
28645f39d397SChris Mason 	btrfs_mark_buffer_dirty(split);
28655f39d397SChris Mason 
28666ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, split->start,
2867c3e06965SJan Schmidt 		   path->slots[level + 1] + 1, level + 1);
2868aa5d6bedSChris Mason 
28695de08d7dSChris Mason 	if (path->slots[level] >= mid) {
28705c680ed6SChris Mason 		path->slots[level] -= mid;
2871925baeddSChris Mason 		btrfs_tree_unlock(c);
28725f39d397SChris Mason 		free_extent_buffer(c);
28735f39d397SChris Mason 		path->nodes[level] = split;
28745c680ed6SChris Mason 		path->slots[level + 1] += 1;
2875eb60ceacSChris Mason 	} else {
2876925baeddSChris Mason 		btrfs_tree_unlock(split);
28775f39d397SChris Mason 		free_extent_buffer(split);
2878be0e5c09SChris Mason 	}
2879d5286a92SNikolay Borisov 	return 0;
2880be0e5c09SChris Mason }
2881be0e5c09SChris Mason 
288274123bd7SChris Mason /*
288374123bd7SChris Mason  * how many bytes are required to store the items in a leaf.  start
288474123bd7SChris Mason  * and nr indicate which items in the leaf to check.  This totals up the
288574123bd7SChris Mason  * space used both by the item structs and the item data
288674123bd7SChris Mason  */
28875f39d397SChris Mason static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2888be0e5c09SChris Mason {
2889be0e5c09SChris Mason 	int data_len;
28905f39d397SChris Mason 	int nritems = btrfs_header_nritems(l);
2891d4dbff95SChris Mason 	int end = min(nritems, start + nr) - 1;
2892be0e5c09SChris Mason 
2893be0e5c09SChris Mason 	if (!nr)
2894be0e5c09SChris Mason 		return 0;
28953212fa14SJosef Bacik 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
28963212fa14SJosef Bacik 	data_len = data_len - btrfs_item_offset(l, end);
28970783fcfcSChris Mason 	data_len += sizeof(struct btrfs_item) * nr;
2898d4dbff95SChris Mason 	WARN_ON(data_len < 0);
2899be0e5c09SChris Mason 	return data_len;
2900be0e5c09SChris Mason }
2901be0e5c09SChris Mason 
290274123bd7SChris Mason /*
2903d4dbff95SChris Mason  * The space between the end of the leaf items and
2904d4dbff95SChris Mason  * the start of the leaf data.  IOW, how much room
2905d4dbff95SChris Mason  * the leaf has left for both items and data
2906d4dbff95SChris Mason  */
2907e902baacSDavid Sterba noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
2908d4dbff95SChris Mason {
2909e902baacSDavid Sterba 	struct btrfs_fs_info *fs_info = leaf->fs_info;
29105f39d397SChris Mason 	int nritems = btrfs_header_nritems(leaf);
29115f39d397SChris Mason 	int ret;
29120b246afaSJeff Mahoney 
29130b246afaSJeff Mahoney 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
29145f39d397SChris Mason 	if (ret < 0) {
29150b246afaSJeff Mahoney 		btrfs_crit(fs_info,
2916efe120a0SFrank Holton 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
2917da17066cSJeff Mahoney 			   ret,
29180b246afaSJeff Mahoney 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
29195f39d397SChris Mason 			   leaf_space_used(leaf, 0, nritems), nritems);
29205f39d397SChris Mason 	}
29215f39d397SChris Mason 	return ret;
2922d4dbff95SChris Mason }
2923d4dbff95SChris Mason 
292499d8f83cSChris Mason /*
292599d8f83cSChris Mason  * min slot controls the lowest index we're willing to push to the
292699d8f83cSChris Mason  * right.  We'll push up to and including min_slot, but no lower
292799d8f83cSChris Mason  */
2928f72f0010SDavid Sterba static noinline int __push_leaf_right(struct btrfs_path *path,
292944871b1bSChris Mason 				      int data_size, int empty,
293044871b1bSChris Mason 				      struct extent_buffer *right,
293199d8f83cSChris Mason 				      int free_space, u32 left_nritems,
293299d8f83cSChris Mason 				      u32 min_slot)
293300ec4c51SChris Mason {
2934f72f0010SDavid Sterba 	struct btrfs_fs_info *fs_info = right->fs_info;
29355f39d397SChris Mason 	struct extent_buffer *left = path->nodes[0];
293644871b1bSChris Mason 	struct extent_buffer *upper = path->nodes[1];
2937cfed81a0SChris Mason 	struct btrfs_map_token token;
29385f39d397SChris Mason 	struct btrfs_disk_key disk_key;
293900ec4c51SChris Mason 	int slot;
294034a38218SChris Mason 	u32 i;
294100ec4c51SChris Mason 	int push_space = 0;
294200ec4c51SChris Mason 	int push_items = 0;
294334a38218SChris Mason 	u32 nr;
29447518a238SChris Mason 	u32 right_nritems;
29455f39d397SChris Mason 	u32 data_end;
2946db94535dSChris Mason 	u32 this_item_size;
294700ec4c51SChris Mason 
294834a38218SChris Mason 	if (empty)
294934a38218SChris Mason 		nr = 0;
295034a38218SChris Mason 	else
295199d8f83cSChris Mason 		nr = max_t(u32, 1, min_slot);
295234a38218SChris Mason 
295331840ae1SZheng Yan 	if (path->slots[0] >= left_nritems)
295487b29b20SYan Zheng 		push_space += data_size;
295531840ae1SZheng Yan 
295644871b1bSChris Mason 	slot = path->slots[1];
295734a38218SChris Mason 	i = left_nritems - 1;
295834a38218SChris Mason 	while (i >= nr) {
295931840ae1SZheng Yan 		if (!empty && push_items > 0) {
296031840ae1SZheng Yan 			if (path->slots[0] > i)
296131840ae1SZheng Yan 				break;
296231840ae1SZheng Yan 			if (path->slots[0] == i) {
2963e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(left);
2964e902baacSDavid Sterba 
296531840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
296631840ae1SZheng Yan 					break;
296731840ae1SZheng Yan 			}
296831840ae1SZheng Yan 		}
296931840ae1SZheng Yan 
297000ec4c51SChris Mason 		if (path->slots[0] == i)
297187b29b20SYan Zheng 			push_space += data_size;
2972db94535dSChris Mason 
29733212fa14SJosef Bacik 		this_item_size = btrfs_item_size(left, i);
297474794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) +
297574794207SJosef Bacik 		    push_space > free_space)
297600ec4c51SChris Mason 			break;
297731840ae1SZheng Yan 
297800ec4c51SChris Mason 		push_items++;
297974794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
298034a38218SChris Mason 		if (i == 0)
298134a38218SChris Mason 			break;
298234a38218SChris Mason 		i--;
2983db94535dSChris Mason 	}
29845f39d397SChris Mason 
2985925baeddSChris Mason 	if (push_items == 0)
2986925baeddSChris Mason 		goto out_unlock;
29875f39d397SChris Mason 
29886c1500f2SJulia Lawall 	WARN_ON(!empty && push_items == left_nritems);
29895f39d397SChris Mason 
299000ec4c51SChris Mason 	/* push left to right */
29915f39d397SChris Mason 	right_nritems = btrfs_header_nritems(right);
299234a38218SChris Mason 
2993dc2e724eSJosef Bacik 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
29948f881e8cSDavid Sterba 	push_space -= leaf_data_end(left);
29955f39d397SChris Mason 
299600ec4c51SChris Mason 	/* make room in the right data area */
29978f881e8cSDavid Sterba 	data_end = leaf_data_end(right);
29985f39d397SChris Mason 	memmove_extent_buffer(right,
29993d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
30003d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
30010b246afaSJeff Mahoney 			      BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
30025f39d397SChris Mason 
300300ec4c51SChris Mason 	/* copy from the left data area */
30043d9ec8c4SNikolay Borisov 	copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
30050b246afaSJeff Mahoney 		     BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
30068f881e8cSDavid Sterba 		     BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
3007d6025579SChris Mason 		     push_space);
30085f39d397SChris Mason 
30095f39d397SChris Mason 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
30105f39d397SChris Mason 			      btrfs_item_nr_offset(0),
30110783fcfcSChris Mason 			      right_nritems * sizeof(struct btrfs_item));
30125f39d397SChris Mason 
301300ec4c51SChris Mason 	/* copy the items from left to right */
30145f39d397SChris Mason 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
30155f39d397SChris Mason 		   btrfs_item_nr_offset(left_nritems - push_items),
30160783fcfcSChris Mason 		   push_items * sizeof(struct btrfs_item));
301700ec4c51SChris Mason 
301800ec4c51SChris Mason 	/* update the item pointers */
3019c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
30207518a238SChris Mason 	right_nritems += push_items;
30215f39d397SChris Mason 	btrfs_set_header_nritems(right, right_nritems);
30220b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
30237518a238SChris Mason 	for (i = 0; i < right_nritems; i++) {
30243212fa14SJosef Bacik 		push_space -= btrfs_token_item_size(&token, i);
30253212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3026db94535dSChris Mason 	}
3027db94535dSChris Mason 
30287518a238SChris Mason 	left_nritems -= push_items;
30295f39d397SChris Mason 	btrfs_set_header_nritems(left, left_nritems);
303000ec4c51SChris Mason 
303134a38218SChris Mason 	if (left_nritems)
30325f39d397SChris Mason 		btrfs_mark_buffer_dirty(left);
3033f0486c68SYan, Zheng 	else
30346a884d7dSDavid Sterba 		btrfs_clean_tree_block(left);
3035f0486c68SYan, Zheng 
30365f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
3037a429e513SChris Mason 
30385f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
30395f39d397SChris Mason 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3040d6025579SChris Mason 	btrfs_mark_buffer_dirty(upper);
304102217ed2SChris Mason 
304200ec4c51SChris Mason 	/* then fixup the leaf pointer in the path */
30437518a238SChris Mason 	if (path->slots[0] >= left_nritems) {
30447518a238SChris Mason 		path->slots[0] -= left_nritems;
3045925baeddSChris Mason 		if (btrfs_header_nritems(path->nodes[0]) == 0)
30466a884d7dSDavid Sterba 			btrfs_clean_tree_block(path->nodes[0]);
3047925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
30485f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
30495f39d397SChris Mason 		path->nodes[0] = right;
305000ec4c51SChris Mason 		path->slots[1] += 1;
305100ec4c51SChris Mason 	} else {
3052925baeddSChris Mason 		btrfs_tree_unlock(right);
30535f39d397SChris Mason 		free_extent_buffer(right);
305400ec4c51SChris Mason 	}
305500ec4c51SChris Mason 	return 0;
3056925baeddSChris Mason 
3057925baeddSChris Mason out_unlock:
3058925baeddSChris Mason 	btrfs_tree_unlock(right);
3059925baeddSChris Mason 	free_extent_buffer(right);
3060925baeddSChris Mason 	return 1;
306100ec4c51SChris Mason }
3062925baeddSChris Mason 
306300ec4c51SChris Mason /*
306444871b1bSChris Mason  * push some data in the path leaf to the right, trying to free up at
306574123bd7SChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
306644871b1bSChris Mason  *
306744871b1bSChris Mason  * returns 1 if the push failed because the other node didn't have enough
306844871b1bSChris Mason  * room, 0 if everything worked out and < 0 if there were major errors.
306999d8f83cSChris Mason  *
307099d8f83cSChris Mason  * this will push starting from min_slot to the end of the leaf.  It won't
307199d8f83cSChris Mason  * push any slot lower than min_slot
307274123bd7SChris Mason  */
307344871b1bSChris Mason static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
307499d8f83cSChris Mason 			   *root, struct btrfs_path *path,
307599d8f83cSChris Mason 			   int min_data_size, int data_size,
307699d8f83cSChris Mason 			   int empty, u32 min_slot)
3077be0e5c09SChris Mason {
307844871b1bSChris Mason 	struct extent_buffer *left = path->nodes[0];
307944871b1bSChris Mason 	struct extent_buffer *right;
308044871b1bSChris Mason 	struct extent_buffer *upper;
308144871b1bSChris Mason 	int slot;
308244871b1bSChris Mason 	int free_space;
308344871b1bSChris Mason 	u32 left_nritems;
308444871b1bSChris Mason 	int ret;
308544871b1bSChris Mason 
308644871b1bSChris Mason 	if (!path->nodes[1])
308744871b1bSChris Mason 		return 1;
308844871b1bSChris Mason 
308944871b1bSChris Mason 	slot = path->slots[1];
309044871b1bSChris Mason 	upper = path->nodes[1];
309144871b1bSChris Mason 	if (slot >= btrfs_header_nritems(upper) - 1)
309244871b1bSChris Mason 		return 1;
309344871b1bSChris Mason 
309449d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
309544871b1bSChris Mason 
30964b231ae4SDavid Sterba 	right = btrfs_read_node_slot(upper, slot + 1);
3097fb770ae4SLiu Bo 	/*
3098fb770ae4SLiu Bo 	 * slot + 1 is not valid or we fail to read the right node,
3099fb770ae4SLiu Bo 	 * no big deal, just return.
3100fb770ae4SLiu Bo 	 */
3101fb770ae4SLiu Bo 	if (IS_ERR(right))
310291ca338dSTsutomu Itoh 		return 1;
310391ca338dSTsutomu Itoh 
3104bf77467aSJosef Bacik 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
310544871b1bSChris Mason 
3106e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(right);
310744871b1bSChris Mason 	if (free_space < data_size)
310844871b1bSChris Mason 		goto out_unlock;
310944871b1bSChris Mason 
311044871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, right, upper,
3111bf59a5a2SJosef Bacik 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
311244871b1bSChris Mason 	if (ret)
311344871b1bSChris Mason 		goto out_unlock;
311444871b1bSChris Mason 
311544871b1bSChris Mason 	left_nritems = btrfs_header_nritems(left);
311644871b1bSChris Mason 	if (left_nritems == 0)
311744871b1bSChris Mason 		goto out_unlock;
311844871b1bSChris Mason 
3119d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3120d16c702fSQu Wenruo 		ret = -EUCLEAN;
3121d16c702fSQu Wenruo 		btrfs_tree_unlock(right);
3122d16c702fSQu Wenruo 		free_extent_buffer(right);
3123d16c702fSQu Wenruo 		return ret;
3124d16c702fSQu Wenruo 	}
31252ef1fed2SFilipe David Borba Manana 	if (path->slots[0] == left_nritems && !empty) {
31262ef1fed2SFilipe David Borba Manana 		/* Key greater than all keys in the leaf, right neighbor has
31272ef1fed2SFilipe David Borba Manana 		 * enough room for it and we're not emptying our leaf to delete
31282ef1fed2SFilipe David Borba Manana 		 * it, therefore use right neighbor to insert the new item and
312952042d8eSAndrea Gelmini 		 * no need to touch/dirty our left leaf. */
31302ef1fed2SFilipe David Borba Manana 		btrfs_tree_unlock(left);
31312ef1fed2SFilipe David Borba Manana 		free_extent_buffer(left);
31322ef1fed2SFilipe David Borba Manana 		path->nodes[0] = right;
31332ef1fed2SFilipe David Borba Manana 		path->slots[0] = 0;
31342ef1fed2SFilipe David Borba Manana 		path->slots[1]++;
31352ef1fed2SFilipe David Borba Manana 		return 0;
31362ef1fed2SFilipe David Borba Manana 	}
31372ef1fed2SFilipe David Borba Manana 
3138f72f0010SDavid Sterba 	return __push_leaf_right(path, min_data_size, empty,
313999d8f83cSChris Mason 				right, free_space, left_nritems, min_slot);
314044871b1bSChris Mason out_unlock:
314144871b1bSChris Mason 	btrfs_tree_unlock(right);
314244871b1bSChris Mason 	free_extent_buffer(right);
314344871b1bSChris Mason 	return 1;
314444871b1bSChris Mason }
314544871b1bSChris Mason 
314644871b1bSChris Mason /*
314744871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
314844871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
314999d8f83cSChris Mason  *
315099d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
315199d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
315299d8f83cSChris Mason  * items
315344871b1bSChris Mason  */
31548087c193SDavid Sterba static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
315544871b1bSChris Mason 				     int empty, struct extent_buffer *left,
315699d8f83cSChris Mason 				     int free_space, u32 right_nritems,
315799d8f83cSChris Mason 				     u32 max_slot)
315844871b1bSChris Mason {
31598087c193SDavid Sterba 	struct btrfs_fs_info *fs_info = left->fs_info;
31605f39d397SChris Mason 	struct btrfs_disk_key disk_key;
31615f39d397SChris Mason 	struct extent_buffer *right = path->nodes[0];
3162be0e5c09SChris Mason 	int i;
3163be0e5c09SChris Mason 	int push_space = 0;
3164be0e5c09SChris Mason 	int push_items = 0;
31657518a238SChris Mason 	u32 old_left_nritems;
316634a38218SChris Mason 	u32 nr;
3167aa5d6bedSChris Mason 	int ret = 0;
3168db94535dSChris Mason 	u32 this_item_size;
3169db94535dSChris Mason 	u32 old_left_item_size;
3170cfed81a0SChris Mason 	struct btrfs_map_token token;
3171cfed81a0SChris Mason 
317234a38218SChris Mason 	if (empty)
317399d8f83cSChris Mason 		nr = min(right_nritems, max_slot);
317434a38218SChris Mason 	else
317599d8f83cSChris Mason 		nr = min(right_nritems - 1, max_slot);
317634a38218SChris Mason 
317734a38218SChris Mason 	for (i = 0; i < nr; i++) {
317831840ae1SZheng Yan 		if (!empty && push_items > 0) {
317931840ae1SZheng Yan 			if (path->slots[0] < i)
318031840ae1SZheng Yan 				break;
318131840ae1SZheng Yan 			if (path->slots[0] == i) {
3182e902baacSDavid Sterba 				int space = btrfs_leaf_free_space(right);
3183e902baacSDavid Sterba 
318431840ae1SZheng Yan 				if (space + push_space * 2 > free_space)
318531840ae1SZheng Yan 					break;
318631840ae1SZheng Yan 			}
318731840ae1SZheng Yan 		}
318831840ae1SZheng Yan 
3189be0e5c09SChris Mason 		if (path->slots[0] == i)
319087b29b20SYan Zheng 			push_space += data_size;
3191db94535dSChris Mason 
31923212fa14SJosef Bacik 		this_item_size = btrfs_item_size(right, i);
319374794207SJosef Bacik 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
319474794207SJosef Bacik 		    free_space)
3195be0e5c09SChris Mason 			break;
3196db94535dSChris Mason 
3197be0e5c09SChris Mason 		push_items++;
319874794207SJosef Bacik 		push_space += this_item_size + sizeof(struct btrfs_item);
3199be0e5c09SChris Mason 	}
3200db94535dSChris Mason 
3201be0e5c09SChris Mason 	if (push_items == 0) {
3202925baeddSChris Mason 		ret = 1;
3203925baeddSChris Mason 		goto out;
3204be0e5c09SChris Mason 	}
3205fae7f21cSDulshani Gunawardhana 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
32065f39d397SChris Mason 
3207be0e5c09SChris Mason 	/* push data from right to left */
32085f39d397SChris Mason 	copy_extent_buffer(left, right,
32095f39d397SChris Mason 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
32105f39d397SChris Mason 			   btrfs_item_nr_offset(0),
32115f39d397SChris Mason 			   push_items * sizeof(struct btrfs_item));
32125f39d397SChris Mason 
32130b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
32143212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1);
32155f39d397SChris Mason 
32163d9ec8c4SNikolay Borisov 	copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
32178f881e8cSDavid Sterba 		     leaf_data_end(left) - push_space,
32183d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET +
32193212fa14SJosef Bacik 		     btrfs_item_offset(right, push_items - 1),
3220be0e5c09SChris Mason 		     push_space);
32215f39d397SChris Mason 	old_left_nritems = btrfs_header_nritems(left);
322287b29b20SYan Zheng 	BUG_ON(old_left_nritems <= 0);
3223eb60ceacSChris Mason 
3224c82f823cSDavid Sterba 	btrfs_init_map_token(&token, left);
32253212fa14SJosef Bacik 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3226be0e5c09SChris Mason 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
32275f39d397SChris Mason 		u32 ioff;
3228db94535dSChris Mason 
32293212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
32303212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i,
3231cc4c13d5SDavid Sterba 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3232be0e5c09SChris Mason 	}
32335f39d397SChris Mason 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3234be0e5c09SChris Mason 
3235be0e5c09SChris Mason 	/* fixup right node */
323631b1a2bdSJulia Lawall 	if (push_items > right_nritems)
323731b1a2bdSJulia Lawall 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3238d397712bSChris Mason 		       right_nritems);
323934a38218SChris Mason 
324034a38218SChris Mason 	if (push_items < right_nritems) {
32413212fa14SJosef Bacik 		push_space = btrfs_item_offset(right, push_items - 1) -
32428f881e8cSDavid Sterba 						  leaf_data_end(right);
32433d9ec8c4SNikolay Borisov 		memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
32440b246afaSJeff Mahoney 				      BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
32453d9ec8c4SNikolay Borisov 				      BTRFS_LEAF_DATA_OFFSET +
32468f881e8cSDavid Sterba 				      leaf_data_end(right), push_space);
32475f39d397SChris Mason 
32485f39d397SChris Mason 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
32495f39d397SChris Mason 			      btrfs_item_nr_offset(push_items),
32505f39d397SChris Mason 			     (btrfs_header_nritems(right) - push_items) *
32510783fcfcSChris Mason 			     sizeof(struct btrfs_item));
325234a38218SChris Mason 	}
3253c82f823cSDavid Sterba 
3254c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
3255eef1c494SYan 	right_nritems -= push_items;
3256eef1c494SYan 	btrfs_set_header_nritems(right, right_nritems);
32570b246afaSJeff Mahoney 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
32585f39d397SChris Mason 	for (i = 0; i < right_nritems; i++) {
32593212fa14SJosef Bacik 		push_space = push_space - btrfs_token_item_size(&token, i);
32603212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, push_space);
3261db94535dSChris Mason 	}
3262eb60ceacSChris Mason 
32635f39d397SChris Mason 	btrfs_mark_buffer_dirty(left);
326434a38218SChris Mason 	if (right_nritems)
32655f39d397SChris Mason 		btrfs_mark_buffer_dirty(right);
3266f0486c68SYan, Zheng 	else
32676a884d7dSDavid Sterba 		btrfs_clean_tree_block(right);
3268098f59c2SChris Mason 
32695f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
3270b167fa91SNikolay Borisov 	fixup_low_keys(path, &disk_key, 1);
3271be0e5c09SChris Mason 
3272be0e5c09SChris Mason 	/* then fixup the leaf pointer in the path */
3273be0e5c09SChris Mason 	if (path->slots[0] < push_items) {
3274be0e5c09SChris Mason 		path->slots[0] += old_left_nritems;
3275925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
32765f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
32775f39d397SChris Mason 		path->nodes[0] = left;
3278be0e5c09SChris Mason 		path->slots[1] -= 1;
3279be0e5c09SChris Mason 	} else {
3280925baeddSChris Mason 		btrfs_tree_unlock(left);
32815f39d397SChris Mason 		free_extent_buffer(left);
3282be0e5c09SChris Mason 		path->slots[0] -= push_items;
3283be0e5c09SChris Mason 	}
3284eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
3285aa5d6bedSChris Mason 	return ret;
3286925baeddSChris Mason out:
3287925baeddSChris Mason 	btrfs_tree_unlock(left);
3288925baeddSChris Mason 	free_extent_buffer(left);
3289925baeddSChris Mason 	return ret;
3290be0e5c09SChris Mason }
3291be0e5c09SChris Mason 
329274123bd7SChris Mason /*
329344871b1bSChris Mason  * push some data in the path leaf to the left, trying to free up at
329444871b1bSChris Mason  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
329599d8f83cSChris Mason  *
329699d8f83cSChris Mason  * max_slot can put a limit on how far into the leaf we'll push items.  The
329799d8f83cSChris Mason  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
329899d8f83cSChris Mason  * items
329944871b1bSChris Mason  */
330044871b1bSChris Mason static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
330199d8f83cSChris Mason 			  *root, struct btrfs_path *path, int min_data_size,
330299d8f83cSChris Mason 			  int data_size, int empty, u32 max_slot)
330344871b1bSChris Mason {
330444871b1bSChris Mason 	struct extent_buffer *right = path->nodes[0];
330544871b1bSChris Mason 	struct extent_buffer *left;
330644871b1bSChris Mason 	int slot;
330744871b1bSChris Mason 	int free_space;
330844871b1bSChris Mason 	u32 right_nritems;
330944871b1bSChris Mason 	int ret = 0;
331044871b1bSChris Mason 
331144871b1bSChris Mason 	slot = path->slots[1];
331244871b1bSChris Mason 	if (slot == 0)
331344871b1bSChris Mason 		return 1;
331444871b1bSChris Mason 	if (!path->nodes[1])
331544871b1bSChris Mason 		return 1;
331644871b1bSChris Mason 
331744871b1bSChris Mason 	right_nritems = btrfs_header_nritems(right);
331844871b1bSChris Mason 	if (right_nritems == 0)
331944871b1bSChris Mason 		return 1;
332044871b1bSChris Mason 
332149d0c642SFilipe Manana 	btrfs_assert_tree_write_locked(path->nodes[1]);
332244871b1bSChris Mason 
33234b231ae4SDavid Sterba 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3324fb770ae4SLiu Bo 	/*
3325fb770ae4SLiu Bo 	 * slot - 1 is not valid or we fail to read the left node,
3326fb770ae4SLiu Bo 	 * no big deal, just return.
3327fb770ae4SLiu Bo 	 */
3328fb770ae4SLiu Bo 	if (IS_ERR(left))
332991ca338dSTsutomu Itoh 		return 1;
333091ca338dSTsutomu Itoh 
3331bf77467aSJosef Bacik 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
333244871b1bSChris Mason 
3333e902baacSDavid Sterba 	free_space = btrfs_leaf_free_space(left);
333444871b1bSChris Mason 	if (free_space < data_size) {
333544871b1bSChris Mason 		ret = 1;
333644871b1bSChris Mason 		goto out;
333744871b1bSChris Mason 	}
333844871b1bSChris Mason 
333944871b1bSChris Mason 	ret = btrfs_cow_block(trans, root, left,
33409631e4ccSJosef Bacik 			      path->nodes[1], slot - 1, &left,
3341bf59a5a2SJosef Bacik 			      BTRFS_NESTING_LEFT_COW);
334244871b1bSChris Mason 	if (ret) {
334344871b1bSChris Mason 		/* we hit -ENOSPC, but it isn't fatal here */
334479787eaaSJeff Mahoney 		if (ret == -ENOSPC)
334544871b1bSChris Mason 			ret = 1;
334644871b1bSChris Mason 		goto out;
334744871b1bSChris Mason 	}
334844871b1bSChris Mason 
3349d16c702fSQu Wenruo 	if (check_sibling_keys(left, right)) {
3350d16c702fSQu Wenruo 		ret = -EUCLEAN;
3351d16c702fSQu Wenruo 		goto out;
3352d16c702fSQu Wenruo 	}
33538087c193SDavid Sterba 	return __push_leaf_left(path, min_data_size,
335499d8f83cSChris Mason 			       empty, left, free_space, right_nritems,
335599d8f83cSChris Mason 			       max_slot);
335644871b1bSChris Mason out:
335744871b1bSChris Mason 	btrfs_tree_unlock(left);
335844871b1bSChris Mason 	free_extent_buffer(left);
335944871b1bSChris Mason 	return ret;
336044871b1bSChris Mason }
336144871b1bSChris Mason 
336244871b1bSChris Mason /*
336374123bd7SChris Mason  * split the path's leaf in two, making sure there is at least data_size
336474123bd7SChris Mason  * available for the resulting leaf level of the path.
336574123bd7SChris Mason  */
3366143bede5SJeff Mahoney static noinline void copy_for_split(struct btrfs_trans_handle *trans,
336744871b1bSChris Mason 				    struct btrfs_path *path,
336844871b1bSChris Mason 				    struct extent_buffer *l,
336944871b1bSChris Mason 				    struct extent_buffer *right,
337044871b1bSChris Mason 				    int slot, int mid, int nritems)
3371be0e5c09SChris Mason {
337294f94ad9SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
3373be0e5c09SChris Mason 	int data_copy_size;
3374be0e5c09SChris Mason 	int rt_data_off;
3375be0e5c09SChris Mason 	int i;
3376d4dbff95SChris Mason 	struct btrfs_disk_key disk_key;
3377cfed81a0SChris Mason 	struct btrfs_map_token token;
3378cfed81a0SChris Mason 
33795f39d397SChris Mason 	nritems = nritems - mid;
33805f39d397SChris Mason 	btrfs_set_header_nritems(right, nritems);
3381dc2e724eSJosef Bacik 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
33825f39d397SChris Mason 
33835f39d397SChris Mason 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
33845f39d397SChris Mason 			   btrfs_item_nr_offset(mid),
33855f39d397SChris Mason 			   nritems * sizeof(struct btrfs_item));
33865f39d397SChris Mason 
33875f39d397SChris Mason 	copy_extent_buffer(right, l,
33883d9ec8c4SNikolay Borisov 		     BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
33893d9ec8c4SNikolay Borisov 		     data_copy_size, BTRFS_LEAF_DATA_OFFSET +
33908f881e8cSDavid Sterba 		     leaf_data_end(l), data_copy_size);
339174123bd7SChris Mason 
3392dc2e724eSJosef Bacik 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
33935f39d397SChris Mason 
3394c82f823cSDavid Sterba 	btrfs_init_map_token(&token, right);
33955f39d397SChris Mason 	for (i = 0; i < nritems; i++) {
3396db94535dSChris Mason 		u32 ioff;
3397db94535dSChris Mason 
33983212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
33993212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
34000783fcfcSChris Mason 	}
340174123bd7SChris Mason 
34025f39d397SChris Mason 	btrfs_set_header_nritems(l, mid);
34035f39d397SChris Mason 	btrfs_item_key(right, &disk_key, 0);
34046ad3cf6dSDavid Sterba 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
34055f39d397SChris Mason 
34065f39d397SChris Mason 	btrfs_mark_buffer_dirty(right);
34075f39d397SChris Mason 	btrfs_mark_buffer_dirty(l);
3408eb60ceacSChris Mason 	BUG_ON(path->slots[0] != slot);
34095f39d397SChris Mason 
3410be0e5c09SChris Mason 	if (mid <= slot) {
3411925baeddSChris Mason 		btrfs_tree_unlock(path->nodes[0]);
34125f39d397SChris Mason 		free_extent_buffer(path->nodes[0]);
34135f39d397SChris Mason 		path->nodes[0] = right;
3414be0e5c09SChris Mason 		path->slots[0] -= mid;
3415be0e5c09SChris Mason 		path->slots[1] += 1;
3416925baeddSChris Mason 	} else {
3417925baeddSChris Mason 		btrfs_tree_unlock(right);
34185f39d397SChris Mason 		free_extent_buffer(right);
3419925baeddSChris Mason 	}
34205f39d397SChris Mason 
3421eb60ceacSChris Mason 	BUG_ON(path->slots[0] < 0);
342244871b1bSChris Mason }
342344871b1bSChris Mason 
342444871b1bSChris Mason /*
342599d8f83cSChris Mason  * double splits happen when we need to insert a big item in the middle
342699d8f83cSChris Mason  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
342799d8f83cSChris Mason  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
342899d8f83cSChris Mason  *          A                 B                 C
342999d8f83cSChris Mason  *
343099d8f83cSChris Mason  * We avoid this by trying to push the items on either side of our target
343199d8f83cSChris Mason  * into the adjacent leaves.  If all goes well we can avoid the double split
343299d8f83cSChris Mason  * completely.
343399d8f83cSChris Mason  */
343499d8f83cSChris Mason static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
343599d8f83cSChris Mason 					  struct btrfs_root *root,
343699d8f83cSChris Mason 					  struct btrfs_path *path,
343799d8f83cSChris Mason 					  int data_size)
343899d8f83cSChris Mason {
343999d8f83cSChris Mason 	int ret;
344099d8f83cSChris Mason 	int progress = 0;
344199d8f83cSChris Mason 	int slot;
344299d8f83cSChris Mason 	u32 nritems;
34435a4267caSFilipe David Borba Manana 	int space_needed = data_size;
344499d8f83cSChris Mason 
344599d8f83cSChris Mason 	slot = path->slots[0];
34465a4267caSFilipe David Borba Manana 	if (slot < btrfs_header_nritems(path->nodes[0]))
3447e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
344899d8f83cSChris Mason 
344999d8f83cSChris Mason 	/*
345099d8f83cSChris Mason 	 * try to push all the items after our slot into the
345199d8f83cSChris Mason 	 * right leaf
345299d8f83cSChris Mason 	 */
34535a4267caSFilipe David Borba Manana 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
345499d8f83cSChris Mason 	if (ret < 0)
345599d8f83cSChris Mason 		return ret;
345699d8f83cSChris Mason 
345799d8f83cSChris Mason 	if (ret == 0)
345899d8f83cSChris Mason 		progress++;
345999d8f83cSChris Mason 
346099d8f83cSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
346199d8f83cSChris Mason 	/*
346299d8f83cSChris Mason 	 * our goal is to get our slot at the start or end of a leaf.  If
346399d8f83cSChris Mason 	 * we've done so we're done
346499d8f83cSChris Mason 	 */
346599d8f83cSChris Mason 	if (path->slots[0] == 0 || path->slots[0] == nritems)
346699d8f83cSChris Mason 		return 0;
346799d8f83cSChris Mason 
3468e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
346999d8f83cSChris Mason 		return 0;
347099d8f83cSChris Mason 
347199d8f83cSChris Mason 	/* try to push all the items before our slot into the next leaf */
347299d8f83cSChris Mason 	slot = path->slots[0];
3473263d3995SFilipe Manana 	space_needed = data_size;
3474263d3995SFilipe Manana 	if (slot > 0)
3475e902baacSDavid Sterba 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
34765a4267caSFilipe David Borba Manana 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
347799d8f83cSChris Mason 	if (ret < 0)
347899d8f83cSChris Mason 		return ret;
347999d8f83cSChris Mason 
348099d8f83cSChris Mason 	if (ret == 0)
348199d8f83cSChris Mason 		progress++;
348299d8f83cSChris Mason 
348399d8f83cSChris Mason 	if (progress)
348499d8f83cSChris Mason 		return 0;
348599d8f83cSChris Mason 	return 1;
348699d8f83cSChris Mason }
348799d8f83cSChris Mason 
348899d8f83cSChris Mason /*
348944871b1bSChris Mason  * split the path's leaf in two, making sure there is at least data_size
349044871b1bSChris Mason  * available for the resulting leaf level of the path.
349144871b1bSChris Mason  *
349244871b1bSChris Mason  * returns 0 if all went well and < 0 on failure.
349344871b1bSChris Mason  */
349444871b1bSChris Mason static noinline int split_leaf(struct btrfs_trans_handle *trans,
349544871b1bSChris Mason 			       struct btrfs_root *root,
3496310712b2SOmar Sandoval 			       const struct btrfs_key *ins_key,
349744871b1bSChris Mason 			       struct btrfs_path *path, int data_size,
349844871b1bSChris Mason 			       int extend)
349944871b1bSChris Mason {
35005d4f98a2SYan Zheng 	struct btrfs_disk_key disk_key;
350144871b1bSChris Mason 	struct extent_buffer *l;
350244871b1bSChris Mason 	u32 nritems;
350344871b1bSChris Mason 	int mid;
350444871b1bSChris Mason 	int slot;
350544871b1bSChris Mason 	struct extent_buffer *right;
3506b7a0365eSDaniel Dressler 	struct btrfs_fs_info *fs_info = root->fs_info;
350744871b1bSChris Mason 	int ret = 0;
350844871b1bSChris Mason 	int wret;
35095d4f98a2SYan Zheng 	int split;
351044871b1bSChris Mason 	int num_doubles = 0;
351199d8f83cSChris Mason 	int tried_avoid_double = 0;
351244871b1bSChris Mason 
3513a5719521SYan, Zheng 	l = path->nodes[0];
3514a5719521SYan, Zheng 	slot = path->slots[0];
35153212fa14SJosef Bacik 	if (extend && data_size + btrfs_item_size(l, slot) +
35160b246afaSJeff Mahoney 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3517a5719521SYan, Zheng 		return -EOVERFLOW;
3518a5719521SYan, Zheng 
351944871b1bSChris Mason 	/* first try to make some room by pushing left and right */
352033157e05SLiu Bo 	if (data_size && path->nodes[1]) {
35215a4267caSFilipe David Borba Manana 		int space_needed = data_size;
35225a4267caSFilipe David Borba Manana 
35235a4267caSFilipe David Borba Manana 		if (slot < btrfs_header_nritems(l))
3524e902baacSDavid Sterba 			space_needed -= btrfs_leaf_free_space(l);
35255a4267caSFilipe David Borba Manana 
35265a4267caSFilipe David Borba Manana 		wret = push_leaf_right(trans, root, path, space_needed,
35275a4267caSFilipe David Borba Manana 				       space_needed, 0, 0);
352844871b1bSChris Mason 		if (wret < 0)
352944871b1bSChris Mason 			return wret;
353044871b1bSChris Mason 		if (wret) {
3531263d3995SFilipe Manana 			space_needed = data_size;
3532263d3995SFilipe Manana 			if (slot > 0)
3533e902baacSDavid Sterba 				space_needed -= btrfs_leaf_free_space(l);
35345a4267caSFilipe David Borba Manana 			wret = push_leaf_left(trans, root, path, space_needed,
35355a4267caSFilipe David Borba Manana 					      space_needed, 0, (u32)-1);
353644871b1bSChris Mason 			if (wret < 0)
353744871b1bSChris Mason 				return wret;
353844871b1bSChris Mason 		}
353944871b1bSChris Mason 		l = path->nodes[0];
354044871b1bSChris Mason 
354144871b1bSChris Mason 		/* did the pushes work? */
3542e902baacSDavid Sterba 		if (btrfs_leaf_free_space(l) >= data_size)
354344871b1bSChris Mason 			return 0;
354444871b1bSChris Mason 	}
354544871b1bSChris Mason 
354644871b1bSChris Mason 	if (!path->nodes[1]) {
3547fdd99c72SLiu Bo 		ret = insert_new_root(trans, root, path, 1);
354844871b1bSChris Mason 		if (ret)
354944871b1bSChris Mason 			return ret;
355044871b1bSChris Mason 	}
355144871b1bSChris Mason again:
35525d4f98a2SYan Zheng 	split = 1;
355344871b1bSChris Mason 	l = path->nodes[0];
355444871b1bSChris Mason 	slot = path->slots[0];
355544871b1bSChris Mason 	nritems = btrfs_header_nritems(l);
355644871b1bSChris Mason 	mid = (nritems + 1) / 2;
355744871b1bSChris Mason 
35585d4f98a2SYan Zheng 	if (mid <= slot) {
35595d4f98a2SYan Zheng 		if (nritems == 1 ||
35605d4f98a2SYan Zheng 		    leaf_space_used(l, mid, nritems - mid) + data_size >
35610b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
35625d4f98a2SYan Zheng 			if (slot >= nritems) {
35635d4f98a2SYan Zheng 				split = 0;
35645d4f98a2SYan Zheng 			} else {
35655d4f98a2SYan Zheng 				mid = slot;
35665d4f98a2SYan Zheng 				if (mid != nritems &&
35675d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
35680b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
356999d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
357099d8f83cSChris Mason 						goto push_for_double;
35715d4f98a2SYan Zheng 					split = 2;
35725d4f98a2SYan Zheng 				}
35735d4f98a2SYan Zheng 			}
35745d4f98a2SYan Zheng 		}
35755d4f98a2SYan Zheng 	} else {
35765d4f98a2SYan Zheng 		if (leaf_space_used(l, 0, mid) + data_size >
35770b246afaSJeff Mahoney 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
35785d4f98a2SYan Zheng 			if (!extend && data_size && slot == 0) {
35795d4f98a2SYan Zheng 				split = 0;
35805d4f98a2SYan Zheng 			} else if ((extend || !data_size) && slot == 0) {
35815d4f98a2SYan Zheng 				mid = 1;
35825d4f98a2SYan Zheng 			} else {
35835d4f98a2SYan Zheng 				mid = slot;
35845d4f98a2SYan Zheng 				if (mid != nritems &&
35855d4f98a2SYan Zheng 				    leaf_space_used(l, mid, nritems - mid) +
35860b246afaSJeff Mahoney 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
358799d8f83cSChris Mason 					if (data_size && !tried_avoid_double)
358899d8f83cSChris Mason 						goto push_for_double;
35895d4f98a2SYan Zheng 					split = 2;
35905d4f98a2SYan Zheng 				}
35915d4f98a2SYan Zheng 			}
35925d4f98a2SYan Zheng 		}
35935d4f98a2SYan Zheng 	}
35945d4f98a2SYan Zheng 
35955d4f98a2SYan Zheng 	if (split == 0)
35965d4f98a2SYan Zheng 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
35975d4f98a2SYan Zheng 	else
35985d4f98a2SYan Zheng 		btrfs_item_key(l, &disk_key, mid);
35995d4f98a2SYan Zheng 
3600ca9d473aSJosef Bacik 	/*
3601ca9d473aSJosef Bacik 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3602ca9d473aSJosef Bacik 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3603ca9d473aSJosef Bacik 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3604ca9d473aSJosef Bacik 	 * out.  In the future we could add a
3605ca9d473aSJosef Bacik 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3606ca9d473aSJosef Bacik 	 * use BTRFS_NESTING_NEW_ROOT.
3607ca9d473aSJosef Bacik 	 */
360879bd3712SFilipe Manana 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
360979bd3712SFilipe Manana 				       &disk_key, 0, l->start, 0,
361079bd3712SFilipe Manana 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3611ca9d473aSJosef Bacik 				       BTRFS_NESTING_SPLIT);
3612f0486c68SYan, Zheng 	if (IS_ERR(right))
361344871b1bSChris Mason 		return PTR_ERR(right);
3614f0486c68SYan, Zheng 
36150b246afaSJeff Mahoney 	root_add_used(root, fs_info->nodesize);
361644871b1bSChris Mason 
36175d4f98a2SYan Zheng 	if (split == 0) {
361844871b1bSChris Mason 		if (mid <= slot) {
361944871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
36206ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
36212ff7e61eSJeff Mahoney 				   right->start, path->slots[1] + 1, 1);
362244871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
362344871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
362444871b1bSChris Mason 			path->nodes[0] = right;
362544871b1bSChris Mason 			path->slots[0] = 0;
362644871b1bSChris Mason 			path->slots[1] += 1;
362744871b1bSChris Mason 		} else {
362844871b1bSChris Mason 			btrfs_set_header_nritems(right, 0);
36296ad3cf6dSDavid Sterba 			insert_ptr(trans, path, &disk_key,
36302ff7e61eSJeff Mahoney 				   right->start, path->slots[1], 1);
363144871b1bSChris Mason 			btrfs_tree_unlock(path->nodes[0]);
363244871b1bSChris Mason 			free_extent_buffer(path->nodes[0]);
363344871b1bSChris Mason 			path->nodes[0] = right;
363444871b1bSChris Mason 			path->slots[0] = 0;
3635143bede5SJeff Mahoney 			if (path->slots[1] == 0)
3636b167fa91SNikolay Borisov 				fixup_low_keys(path, &disk_key, 1);
36375d4f98a2SYan Zheng 		}
3638196e0249SLiu Bo 		/*
3639196e0249SLiu Bo 		 * We create a new leaf 'right' for the required ins_len and
3640196e0249SLiu Bo 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3641196e0249SLiu Bo 		 * the content of ins_len to 'right'.
3642196e0249SLiu Bo 		 */
364344871b1bSChris Mason 		return ret;
364444871b1bSChris Mason 	}
364544871b1bSChris Mason 
364694f94ad9SDavid Sterba 	copy_for_split(trans, path, l, right, slot, mid, nritems);
364744871b1bSChris Mason 
36485d4f98a2SYan Zheng 	if (split == 2) {
3649cc0c5538SChris Mason 		BUG_ON(num_doubles != 0);
3650cc0c5538SChris Mason 		num_doubles++;
3651cc0c5538SChris Mason 		goto again;
36523326d1b0SChris Mason 	}
365344871b1bSChris Mason 
3654143bede5SJeff Mahoney 	return 0;
365599d8f83cSChris Mason 
365699d8f83cSChris Mason push_for_double:
365799d8f83cSChris Mason 	push_for_double_split(trans, root, path, data_size);
365899d8f83cSChris Mason 	tried_avoid_double = 1;
3659e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
366099d8f83cSChris Mason 		return 0;
366199d8f83cSChris Mason 	goto again;
3662be0e5c09SChris Mason }
3663be0e5c09SChris Mason 
3664ad48fd75SYan, Zheng static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3665ad48fd75SYan, Zheng 					 struct btrfs_root *root,
3666ad48fd75SYan, Zheng 					 struct btrfs_path *path, int ins_len)
3667ad48fd75SYan, Zheng {
3668ad48fd75SYan, Zheng 	struct btrfs_key key;
3669ad48fd75SYan, Zheng 	struct extent_buffer *leaf;
3670ad48fd75SYan, Zheng 	struct btrfs_file_extent_item *fi;
3671ad48fd75SYan, Zheng 	u64 extent_len = 0;
3672ad48fd75SYan, Zheng 	u32 item_size;
3673ad48fd75SYan, Zheng 	int ret;
3674ad48fd75SYan, Zheng 
3675ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3676ad48fd75SYan, Zheng 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3677ad48fd75SYan, Zheng 
3678ad48fd75SYan, Zheng 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3679ad48fd75SYan, Zheng 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3680ad48fd75SYan, Zheng 
3681e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3682ad48fd75SYan, Zheng 		return 0;
3683ad48fd75SYan, Zheng 
36843212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3685ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3686ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3687ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3688ad48fd75SYan, Zheng 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3689ad48fd75SYan, Zheng 	}
3690b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3691ad48fd75SYan, Zheng 
3692ad48fd75SYan, Zheng 	path->keep_locks = 1;
3693ad48fd75SYan, Zheng 	path->search_for_split = 1;
3694ad48fd75SYan, Zheng 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3695ad48fd75SYan, Zheng 	path->search_for_split = 0;
3696a8df6fe6SFilipe Manana 	if (ret > 0)
3697a8df6fe6SFilipe Manana 		ret = -EAGAIN;
3698ad48fd75SYan, Zheng 	if (ret < 0)
3699ad48fd75SYan, Zheng 		goto err;
3700ad48fd75SYan, Zheng 
3701ad48fd75SYan, Zheng 	ret = -EAGAIN;
3702ad48fd75SYan, Zheng 	leaf = path->nodes[0];
3703a8df6fe6SFilipe Manana 	/* if our item isn't there, return now */
37043212fa14SJosef Bacik 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3705ad48fd75SYan, Zheng 		goto err;
3706ad48fd75SYan, Zheng 
3707109f6aefSChris Mason 	/* the leaf has  changed, it now has room.  return now */
3708e902baacSDavid Sterba 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3709109f6aefSChris Mason 		goto err;
3710109f6aefSChris Mason 
3711ad48fd75SYan, Zheng 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3712ad48fd75SYan, Zheng 		fi = btrfs_item_ptr(leaf, path->slots[0],
3713ad48fd75SYan, Zheng 				    struct btrfs_file_extent_item);
3714ad48fd75SYan, Zheng 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3715ad48fd75SYan, Zheng 			goto err;
3716ad48fd75SYan, Zheng 	}
3717ad48fd75SYan, Zheng 
3718ad48fd75SYan, Zheng 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3719f0486c68SYan, Zheng 	if (ret)
3720f0486c68SYan, Zheng 		goto err;
3721ad48fd75SYan, Zheng 
3722ad48fd75SYan, Zheng 	path->keep_locks = 0;
3723ad48fd75SYan, Zheng 	btrfs_unlock_up_safe(path, 1);
3724ad48fd75SYan, Zheng 	return 0;
3725ad48fd75SYan, Zheng err:
3726ad48fd75SYan, Zheng 	path->keep_locks = 0;
3727ad48fd75SYan, Zheng 	return ret;
3728ad48fd75SYan, Zheng }
3729ad48fd75SYan, Zheng 
373025263cd7SDavid Sterba static noinline int split_item(struct btrfs_path *path,
3731310712b2SOmar Sandoval 			       const struct btrfs_key *new_key,
3732459931ecSChris Mason 			       unsigned long split_offset)
3733459931ecSChris Mason {
3734459931ecSChris Mason 	struct extent_buffer *leaf;
3735c91666b1SJosef Bacik 	int orig_slot, slot;
3736ad48fd75SYan, Zheng 	char *buf;
3737459931ecSChris Mason 	u32 nritems;
3738ad48fd75SYan, Zheng 	u32 item_size;
3739459931ecSChris Mason 	u32 orig_offset;
3740459931ecSChris Mason 	struct btrfs_disk_key disk_key;
3741459931ecSChris Mason 
3742459931ecSChris Mason 	leaf = path->nodes[0];
3743e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3744b9473439SChris Mason 
3745c91666b1SJosef Bacik 	orig_slot = path->slots[0];
37463212fa14SJosef Bacik 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
37473212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
3748459931ecSChris Mason 
3749459931ecSChris Mason 	buf = kmalloc(item_size, GFP_NOFS);
3750ad48fd75SYan, Zheng 	if (!buf)
3751ad48fd75SYan, Zheng 		return -ENOMEM;
3752ad48fd75SYan, Zheng 
3753459931ecSChris Mason 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3754459931ecSChris Mason 			    path->slots[0]), item_size);
3755ad48fd75SYan, Zheng 
3756459931ecSChris Mason 	slot = path->slots[0] + 1;
3757459931ecSChris Mason 	nritems = btrfs_header_nritems(leaf);
3758459931ecSChris Mason 	if (slot != nritems) {
3759459931ecSChris Mason 		/* shift the items */
3760459931ecSChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3761459931ecSChris Mason 				btrfs_item_nr_offset(slot),
3762459931ecSChris Mason 				(nritems - slot) * sizeof(struct btrfs_item));
3763459931ecSChris Mason 	}
3764459931ecSChris Mason 
3765459931ecSChris Mason 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3766459931ecSChris Mason 	btrfs_set_item_key(leaf, &disk_key, slot);
3767459931ecSChris Mason 
37683212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, slot, orig_offset);
37693212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3770459931ecSChris Mason 
37713212fa14SJosef Bacik 	btrfs_set_item_offset(leaf, orig_slot,
3772459931ecSChris Mason 				 orig_offset + item_size - split_offset);
37733212fa14SJosef Bacik 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3774459931ecSChris Mason 
3775459931ecSChris Mason 	btrfs_set_header_nritems(leaf, nritems + 1);
3776459931ecSChris Mason 
3777459931ecSChris Mason 	/* write the data for the start of the original item */
3778459931ecSChris Mason 	write_extent_buffer(leaf, buf,
3779459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3780459931ecSChris Mason 			    split_offset);
3781459931ecSChris Mason 
3782459931ecSChris Mason 	/* write the data for the new item */
3783459931ecSChris Mason 	write_extent_buffer(leaf, buf + split_offset,
3784459931ecSChris Mason 			    btrfs_item_ptr_offset(leaf, slot),
3785459931ecSChris Mason 			    item_size - split_offset);
3786459931ecSChris Mason 	btrfs_mark_buffer_dirty(leaf);
3787459931ecSChris Mason 
3788e902baacSDavid Sterba 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3789459931ecSChris Mason 	kfree(buf);
3790ad48fd75SYan, Zheng 	return 0;
3791ad48fd75SYan, Zheng }
3792ad48fd75SYan, Zheng 
3793ad48fd75SYan, Zheng /*
3794ad48fd75SYan, Zheng  * This function splits a single item into two items,
3795ad48fd75SYan, Zheng  * giving 'new_key' to the new item and splitting the
3796ad48fd75SYan, Zheng  * old one at split_offset (from the start of the item).
3797ad48fd75SYan, Zheng  *
3798ad48fd75SYan, Zheng  * The path may be released by this operation.  After
3799ad48fd75SYan, Zheng  * the split, the path is pointing to the old item.  The
3800ad48fd75SYan, Zheng  * new item is going to be in the same node as the old one.
3801ad48fd75SYan, Zheng  *
3802ad48fd75SYan, Zheng  * Note, the item being split must be smaller enough to live alone on
3803ad48fd75SYan, Zheng  * a tree block with room for one extra struct btrfs_item
3804ad48fd75SYan, Zheng  *
3805ad48fd75SYan, Zheng  * This allows us to split the item in place, keeping a lock on the
3806ad48fd75SYan, Zheng  * leaf the entire time.
3807ad48fd75SYan, Zheng  */
3808ad48fd75SYan, Zheng int btrfs_split_item(struct btrfs_trans_handle *trans,
3809ad48fd75SYan, Zheng 		     struct btrfs_root *root,
3810ad48fd75SYan, Zheng 		     struct btrfs_path *path,
3811310712b2SOmar Sandoval 		     const struct btrfs_key *new_key,
3812ad48fd75SYan, Zheng 		     unsigned long split_offset)
3813ad48fd75SYan, Zheng {
3814ad48fd75SYan, Zheng 	int ret;
3815ad48fd75SYan, Zheng 	ret = setup_leaf_for_split(trans, root, path,
3816ad48fd75SYan, Zheng 				   sizeof(struct btrfs_item));
3817ad48fd75SYan, Zheng 	if (ret)
3818459931ecSChris Mason 		return ret;
3819ad48fd75SYan, Zheng 
382025263cd7SDavid Sterba 	ret = split_item(path, new_key, split_offset);
3821ad48fd75SYan, Zheng 	return ret;
3822ad48fd75SYan, Zheng }
3823ad48fd75SYan, Zheng 
3824ad48fd75SYan, Zheng /*
3825d352ac68SChris Mason  * make the item pointed to by the path smaller.  new_size indicates
3826d352ac68SChris Mason  * how small to make it, and from_end tells us if we just chop bytes
3827d352ac68SChris Mason  * off the end of the item or if we shift the item to chop bytes off
3828d352ac68SChris Mason  * the front.
3829d352ac68SChris Mason  */
383078ac4f9eSDavid Sterba void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3831b18c6685SChris Mason {
3832b18c6685SChris Mason 	int slot;
38335f39d397SChris Mason 	struct extent_buffer *leaf;
3834b18c6685SChris Mason 	u32 nritems;
3835b18c6685SChris Mason 	unsigned int data_end;
3836b18c6685SChris Mason 	unsigned int old_data_start;
3837b18c6685SChris Mason 	unsigned int old_size;
3838b18c6685SChris Mason 	unsigned int size_diff;
3839b18c6685SChris Mason 	int i;
3840cfed81a0SChris Mason 	struct btrfs_map_token token;
3841cfed81a0SChris Mason 
38425f39d397SChris Mason 	leaf = path->nodes[0];
3843179e29e4SChris Mason 	slot = path->slots[0];
3844179e29e4SChris Mason 
38453212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
3846179e29e4SChris Mason 	if (old_size == new_size)
3847143bede5SJeff Mahoney 		return;
3848b18c6685SChris Mason 
38495f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
38508f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
3851b18c6685SChris Mason 
38523212fa14SJosef Bacik 	old_data_start = btrfs_item_offset(leaf, slot);
3853179e29e4SChris Mason 
3854b18c6685SChris Mason 	size_diff = old_size - new_size;
3855b18c6685SChris Mason 
3856b18c6685SChris Mason 	BUG_ON(slot < 0);
3857b18c6685SChris Mason 	BUG_ON(slot >= nritems);
3858b18c6685SChris Mason 
3859b18c6685SChris Mason 	/*
3860b18c6685SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3861b18c6685SChris Mason 	 */
3862b18c6685SChris Mason 	/* first correct the data pointers */
3863c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
3864b18c6685SChris Mason 	for (i = slot; i < nritems; i++) {
38655f39d397SChris Mason 		u32 ioff;
3866db94535dSChris Mason 
38673212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
38683212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3869b18c6685SChris Mason 	}
3870db94535dSChris Mason 
3871b18c6685SChris Mason 	/* shift the data */
3872179e29e4SChris Mason 	if (from_end) {
38733d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
38743d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3875b18c6685SChris Mason 			      data_end, old_data_start + new_size - data_end);
3876179e29e4SChris Mason 	} else {
3877179e29e4SChris Mason 		struct btrfs_disk_key disk_key;
3878179e29e4SChris Mason 		u64 offset;
3879179e29e4SChris Mason 
3880179e29e4SChris Mason 		btrfs_item_key(leaf, &disk_key, slot);
3881179e29e4SChris Mason 
3882179e29e4SChris Mason 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3883179e29e4SChris Mason 			unsigned long ptr;
3884179e29e4SChris Mason 			struct btrfs_file_extent_item *fi;
3885179e29e4SChris Mason 
3886179e29e4SChris Mason 			fi = btrfs_item_ptr(leaf, slot,
3887179e29e4SChris Mason 					    struct btrfs_file_extent_item);
3888179e29e4SChris Mason 			fi = (struct btrfs_file_extent_item *)(
3889179e29e4SChris Mason 			     (unsigned long)fi - size_diff);
3890179e29e4SChris Mason 
3891179e29e4SChris Mason 			if (btrfs_file_extent_type(leaf, fi) ==
3892179e29e4SChris Mason 			    BTRFS_FILE_EXTENT_INLINE) {
3893179e29e4SChris Mason 				ptr = btrfs_item_ptr_offset(leaf, slot);
3894179e29e4SChris Mason 				memmove_extent_buffer(leaf, ptr,
3895179e29e4SChris Mason 				      (unsigned long)fi,
38967ec20afbSDavid Sterba 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
3897179e29e4SChris Mason 			}
3898179e29e4SChris Mason 		}
3899179e29e4SChris Mason 
39003d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
39013d9ec8c4SNikolay Borisov 			      data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
3902179e29e4SChris Mason 			      data_end, old_data_start - data_end);
3903179e29e4SChris Mason 
3904179e29e4SChris Mason 		offset = btrfs_disk_key_offset(&disk_key);
3905179e29e4SChris Mason 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3906179e29e4SChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot);
3907179e29e4SChris Mason 		if (slot == 0)
3908b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
3909179e29e4SChris Mason 	}
39105f39d397SChris Mason 
39113212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, new_size);
39125f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
3913b18c6685SChris Mason 
3914e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3915a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3916b18c6685SChris Mason 		BUG();
39175f39d397SChris Mason 	}
3918b18c6685SChris Mason }
3919b18c6685SChris Mason 
3920d352ac68SChris Mason /*
39218f69dbd2SStefan Behrens  * make the item pointed to by the path bigger, data_size is the added size.
3922d352ac68SChris Mason  */
3923c71dd880SDavid Sterba void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
39246567e837SChris Mason {
39256567e837SChris Mason 	int slot;
39265f39d397SChris Mason 	struct extent_buffer *leaf;
39276567e837SChris Mason 	u32 nritems;
39286567e837SChris Mason 	unsigned int data_end;
39296567e837SChris Mason 	unsigned int old_data;
39306567e837SChris Mason 	unsigned int old_size;
39316567e837SChris Mason 	int i;
3932cfed81a0SChris Mason 	struct btrfs_map_token token;
3933cfed81a0SChris Mason 
39345f39d397SChris Mason 	leaf = path->nodes[0];
39356567e837SChris Mason 
39365f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
39378f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
39386567e837SChris Mason 
3939e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < data_size) {
3940a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39416567e837SChris Mason 		BUG();
39425f39d397SChris Mason 	}
39436567e837SChris Mason 	slot = path->slots[0];
3944dc2e724eSJosef Bacik 	old_data = btrfs_item_data_end(leaf, slot);
39456567e837SChris Mason 
39466567e837SChris Mason 	BUG_ON(slot < 0);
39473326d1b0SChris Mason 	if (slot >= nritems) {
3948a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
3949c71dd880SDavid Sterba 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
3950d397712bSChris Mason 			   slot, nritems);
3951290342f6SArnd Bergmann 		BUG();
39523326d1b0SChris Mason 	}
39536567e837SChris Mason 
39546567e837SChris Mason 	/*
39556567e837SChris Mason 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
39566567e837SChris Mason 	 */
39576567e837SChris Mason 	/* first correct the data pointers */
3958c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
39596567e837SChris Mason 	for (i = slot; i < nritems; i++) {
39605f39d397SChris Mason 		u32 ioff;
3961db94535dSChris Mason 
39623212fa14SJosef Bacik 		ioff = btrfs_token_item_offset(&token, i);
39633212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
39646567e837SChris Mason 	}
39655f39d397SChris Mason 
39666567e837SChris Mason 	/* shift the data */
39673d9ec8c4SNikolay Borisov 	memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
39683d9ec8c4SNikolay Borisov 		      data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
39696567e837SChris Mason 		      data_end, old_data - data_end);
39705f39d397SChris Mason 
39716567e837SChris Mason 	data_end = old_data;
39723212fa14SJosef Bacik 	old_size = btrfs_item_size(leaf, slot);
39733212fa14SJosef Bacik 	btrfs_set_item_size(leaf, slot, old_size + data_size);
39745f39d397SChris Mason 	btrfs_mark_buffer_dirty(leaf);
39756567e837SChris Mason 
3976e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
3977a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
39786567e837SChris Mason 		BUG();
39795f39d397SChris Mason 	}
39806567e837SChris Mason }
39816567e837SChris Mason 
3982da9ffb24SNikolay Borisov /**
3983da9ffb24SNikolay Borisov  * setup_items_for_insert - Helper called before inserting one or more items
3984da9ffb24SNikolay Borisov  * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
3985da9ffb24SNikolay Borisov  * in a function that doesn't call btrfs_search_slot
3986da9ffb24SNikolay Borisov  *
3987da9ffb24SNikolay Borisov  * @root:	root we are inserting items to
3988da9ffb24SNikolay Borisov  * @path:	points to the leaf/slot where we are going to insert new items
3989b7ef5f3aSFilipe Manana  * @batch:      information about the batch of items to insert
399074123bd7SChris Mason  */
3991f0641656SFilipe Manana static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
3992b7ef5f3aSFilipe Manana 				   const struct btrfs_item_batch *batch)
3993be0e5c09SChris Mason {
39940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
39959c58309dSChris Mason 	int i;
39967518a238SChris Mason 	u32 nritems;
3997be0e5c09SChris Mason 	unsigned int data_end;
3998e2fa7227SChris Mason 	struct btrfs_disk_key disk_key;
399944871b1bSChris Mason 	struct extent_buffer *leaf;
400044871b1bSChris Mason 	int slot;
4001cfed81a0SChris Mason 	struct btrfs_map_token token;
4002fc0d82e1SNikolay Borisov 	u32 total_size;
4003fc0d82e1SNikolay Borisov 
4004b7ef5f3aSFilipe Manana 	/*
4005b7ef5f3aSFilipe Manana 	 * Before anything else, update keys in the parent and other ancestors
4006b7ef5f3aSFilipe Manana 	 * if needed, then release the write locks on them, so that other tasks
4007b7ef5f3aSFilipe Manana 	 * can use them while we modify the leaf.
4008b7ef5f3aSFilipe Manana 	 */
400924cdc847SFilipe Manana 	if (path->slots[0] == 0) {
4010b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4011b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, 1);
401224cdc847SFilipe Manana 	}
401324cdc847SFilipe Manana 	btrfs_unlock_up_safe(path, 1);
401424cdc847SFilipe Manana 
40155f39d397SChris Mason 	leaf = path->nodes[0];
401644871b1bSChris Mason 	slot = path->slots[0];
401774123bd7SChris Mason 
40185f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
40198f881e8cSDavid Sterba 	data_end = leaf_data_end(leaf);
4020b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4021eb60ceacSChris Mason 
4022e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < total_size) {
4023a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
40240b246afaSJeff Mahoney 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4025e902baacSDavid Sterba 			   total_size, btrfs_leaf_free_space(leaf));
4026be0e5c09SChris Mason 		BUG();
4027d4dbff95SChris Mason 	}
40285f39d397SChris Mason 
4029c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
4030be0e5c09SChris Mason 	if (slot != nritems) {
4031dc2e724eSJosef Bacik 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4032be0e5c09SChris Mason 
40335f39d397SChris Mason 		if (old_data < data_end) {
4034a4f78750SDavid Sterba 			btrfs_print_leaf(leaf);
40357269ddd2SNikolay Borisov 			btrfs_crit(fs_info,
40367269ddd2SNikolay Borisov 		"item at slot %d with data offset %u beyond data end of leaf %u",
40375f39d397SChris Mason 				   slot, old_data, data_end);
4038290342f6SArnd Bergmann 			BUG();
40395f39d397SChris Mason 		}
4040be0e5c09SChris Mason 		/*
4041be0e5c09SChris Mason 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4042be0e5c09SChris Mason 		 */
4043be0e5c09SChris Mason 		/* first correct the data pointers */
40440783fcfcSChris Mason 		for (i = slot; i < nritems; i++) {
40455f39d397SChris Mason 			u32 ioff;
4046db94535dSChris Mason 
40473212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
40483212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i,
4049b7ef5f3aSFilipe Manana 						       ioff - batch->total_data_size);
40500783fcfcSChris Mason 		}
4051be0e5c09SChris Mason 		/* shift the items */
4052b7ef5f3aSFilipe Manana 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + batch->nr),
40535f39d397SChris Mason 			      btrfs_item_nr_offset(slot),
40540783fcfcSChris Mason 			      (nritems - slot) * sizeof(struct btrfs_item));
4055be0e5c09SChris Mason 
4056be0e5c09SChris Mason 		/* shift the data */
40573d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4058b7ef5f3aSFilipe Manana 				      data_end - batch->total_data_size,
4059b7ef5f3aSFilipe Manana 				      BTRFS_LEAF_DATA_OFFSET + data_end,
4060b7ef5f3aSFilipe Manana 				      old_data - data_end);
4061be0e5c09SChris Mason 		data_end = old_data;
4062be0e5c09SChris Mason 	}
40635f39d397SChris Mason 
406462e2749eSChris Mason 	/* setup the item for the new data */
4065b7ef5f3aSFilipe Manana 	for (i = 0; i < batch->nr; i++) {
4066b7ef5f3aSFilipe Manana 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
40679c58309dSChris Mason 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4068b7ef5f3aSFilipe Manana 		data_end -= batch->data_sizes[i];
40693212fa14SJosef Bacik 		btrfs_set_token_item_offset(&token, slot + i, data_end);
40703212fa14SJosef Bacik 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
40719c58309dSChris Mason 	}
407244871b1bSChris Mason 
4073b7ef5f3aSFilipe Manana 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4074b9473439SChris Mason 	btrfs_mark_buffer_dirty(leaf);
4075aa5d6bedSChris Mason 
4076e902baacSDavid Sterba 	if (btrfs_leaf_free_space(leaf) < 0) {
4077a4f78750SDavid Sterba 		btrfs_print_leaf(leaf);
4078be0e5c09SChris Mason 		BUG();
40795f39d397SChris Mason 	}
408044871b1bSChris Mason }
408144871b1bSChris Mason 
408244871b1bSChris Mason /*
4083f0641656SFilipe Manana  * Insert a new item into a leaf.
4084f0641656SFilipe Manana  *
4085f0641656SFilipe Manana  * @root:      The root of the btree.
4086f0641656SFilipe Manana  * @path:      A path pointing to the target leaf and slot.
4087f0641656SFilipe Manana  * @key:       The key of the new item.
4088f0641656SFilipe Manana  * @data_size: The size of the data associated with the new key.
4089f0641656SFilipe Manana  */
4090f0641656SFilipe Manana void btrfs_setup_item_for_insert(struct btrfs_root *root,
4091f0641656SFilipe Manana 				 struct btrfs_path *path,
4092f0641656SFilipe Manana 				 const struct btrfs_key *key,
4093f0641656SFilipe Manana 				 u32 data_size)
4094f0641656SFilipe Manana {
4095f0641656SFilipe Manana 	struct btrfs_item_batch batch;
4096f0641656SFilipe Manana 
4097f0641656SFilipe Manana 	batch.keys = key;
4098f0641656SFilipe Manana 	batch.data_sizes = &data_size;
4099f0641656SFilipe Manana 	batch.total_data_size = data_size;
4100f0641656SFilipe Manana 	batch.nr = 1;
4101f0641656SFilipe Manana 
4102f0641656SFilipe Manana 	setup_items_for_insert(root, path, &batch);
4103f0641656SFilipe Manana }
4104f0641656SFilipe Manana 
4105f0641656SFilipe Manana /*
410644871b1bSChris Mason  * Given a key and some data, insert items into the tree.
410744871b1bSChris Mason  * This does all the path init required, making room in the tree if needed.
410844871b1bSChris Mason  */
410944871b1bSChris Mason int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
411044871b1bSChris Mason 			    struct btrfs_root *root,
411144871b1bSChris Mason 			    struct btrfs_path *path,
4112b7ef5f3aSFilipe Manana 			    const struct btrfs_item_batch *batch)
411344871b1bSChris Mason {
411444871b1bSChris Mason 	int ret = 0;
411544871b1bSChris Mason 	int slot;
4116b7ef5f3aSFilipe Manana 	u32 total_size;
411744871b1bSChris Mason 
4118b7ef5f3aSFilipe Manana 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4119b7ef5f3aSFilipe Manana 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
412044871b1bSChris Mason 	if (ret == 0)
412144871b1bSChris Mason 		return -EEXIST;
412244871b1bSChris Mason 	if (ret < 0)
4123143bede5SJeff Mahoney 		return ret;
412444871b1bSChris Mason 
412544871b1bSChris Mason 	slot = path->slots[0];
412644871b1bSChris Mason 	BUG_ON(slot < 0);
412744871b1bSChris Mason 
4128b7ef5f3aSFilipe Manana 	setup_items_for_insert(root, path, batch);
4129143bede5SJeff Mahoney 	return 0;
413062e2749eSChris Mason }
413162e2749eSChris Mason 
413262e2749eSChris Mason /*
413362e2749eSChris Mason  * Given a key and some data, insert an item into the tree.
413462e2749eSChris Mason  * This does all the path init required, making room in the tree if needed.
413562e2749eSChris Mason  */
4136310712b2SOmar Sandoval int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4137310712b2SOmar Sandoval 		      const struct btrfs_key *cpu_key, void *data,
4138310712b2SOmar Sandoval 		      u32 data_size)
413962e2749eSChris Mason {
414062e2749eSChris Mason 	int ret = 0;
41412c90e5d6SChris Mason 	struct btrfs_path *path;
41425f39d397SChris Mason 	struct extent_buffer *leaf;
41435f39d397SChris Mason 	unsigned long ptr;
414462e2749eSChris Mason 
41452c90e5d6SChris Mason 	path = btrfs_alloc_path();
4146db5b493aSTsutomu Itoh 	if (!path)
4147db5b493aSTsutomu Itoh 		return -ENOMEM;
41482c90e5d6SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
414962e2749eSChris Mason 	if (!ret) {
41505f39d397SChris Mason 		leaf = path->nodes[0];
41515f39d397SChris Mason 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
41525f39d397SChris Mason 		write_extent_buffer(leaf, data, ptr, data_size);
41535f39d397SChris Mason 		btrfs_mark_buffer_dirty(leaf);
415462e2749eSChris Mason 	}
41552c90e5d6SChris Mason 	btrfs_free_path(path);
4156aa5d6bedSChris Mason 	return ret;
4157be0e5c09SChris Mason }
4158be0e5c09SChris Mason 
415974123bd7SChris Mason /*
4160f0641656SFilipe Manana  * This function duplicates an item, giving 'new_key' to the new item.
4161f0641656SFilipe Manana  * It guarantees both items live in the same tree leaf and the new item is
4162f0641656SFilipe Manana  * contiguous with the original item.
4163f0641656SFilipe Manana  *
4164f0641656SFilipe Manana  * This allows us to split a file extent in place, keeping a lock on the leaf
4165f0641656SFilipe Manana  * the entire time.
4166f0641656SFilipe Manana  */
4167f0641656SFilipe Manana int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4168f0641656SFilipe Manana 			 struct btrfs_root *root,
4169f0641656SFilipe Manana 			 struct btrfs_path *path,
4170f0641656SFilipe Manana 			 const struct btrfs_key *new_key)
4171f0641656SFilipe Manana {
4172f0641656SFilipe Manana 	struct extent_buffer *leaf;
4173f0641656SFilipe Manana 	int ret;
4174f0641656SFilipe Manana 	u32 item_size;
4175f0641656SFilipe Manana 
4176f0641656SFilipe Manana 	leaf = path->nodes[0];
41773212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, path->slots[0]);
4178f0641656SFilipe Manana 	ret = setup_leaf_for_split(trans, root, path,
4179f0641656SFilipe Manana 				   item_size + sizeof(struct btrfs_item));
4180f0641656SFilipe Manana 	if (ret)
4181f0641656SFilipe Manana 		return ret;
4182f0641656SFilipe Manana 
4183f0641656SFilipe Manana 	path->slots[0]++;
4184f0641656SFilipe Manana 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4185f0641656SFilipe Manana 	leaf = path->nodes[0];
4186f0641656SFilipe Manana 	memcpy_extent_buffer(leaf,
4187f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4188f0641656SFilipe Manana 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4189f0641656SFilipe Manana 			     item_size);
4190f0641656SFilipe Manana 	return 0;
4191f0641656SFilipe Manana }
4192f0641656SFilipe Manana 
4193f0641656SFilipe Manana /*
41945de08d7dSChris Mason  * delete the pointer from a given node.
419574123bd7SChris Mason  *
4196d352ac68SChris Mason  * the tree should have been previously balanced so the deletion does not
4197d352ac68SChris Mason  * empty a node.
419874123bd7SChris Mason  */
4199afe5fea7STsutomu Itoh static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4200afe5fea7STsutomu Itoh 		    int level, int slot)
4201be0e5c09SChris Mason {
42025f39d397SChris Mason 	struct extent_buffer *parent = path->nodes[level];
42037518a238SChris Mason 	u32 nritems;
4204f3ea38daSJan Schmidt 	int ret;
4205be0e5c09SChris Mason 
42065f39d397SChris Mason 	nritems = btrfs_header_nritems(parent);
4207be0e5c09SChris Mason 	if (slot != nritems - 1) {
4208bf1d3425SDavid Sterba 		if (level) {
4209f3a84ccdSFilipe Manana 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4210f3a84ccdSFilipe Manana 					slot + 1, nritems - slot - 1);
4211bf1d3425SDavid Sterba 			BUG_ON(ret < 0);
4212bf1d3425SDavid Sterba 		}
42135f39d397SChris Mason 		memmove_extent_buffer(parent,
42145f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot),
42155f39d397SChris Mason 			      btrfs_node_key_ptr_offset(slot + 1),
4216d6025579SChris Mason 			      sizeof(struct btrfs_key_ptr) *
4217d6025579SChris Mason 			      (nritems - slot - 1));
421857ba86c0SChris Mason 	} else if (level) {
4219f3a84ccdSFilipe Manana 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
4220f3a84ccdSFilipe Manana 				BTRFS_MOD_LOG_KEY_REMOVE, GFP_NOFS);
422157ba86c0SChris Mason 		BUG_ON(ret < 0);
4222be0e5c09SChris Mason 	}
4223f3ea38daSJan Schmidt 
42247518a238SChris Mason 	nritems--;
42255f39d397SChris Mason 	btrfs_set_header_nritems(parent, nritems);
42267518a238SChris Mason 	if (nritems == 0 && parent == root->node) {
42275f39d397SChris Mason 		BUG_ON(btrfs_header_level(root->node) != 1);
4228eb60ceacSChris Mason 		/* just turn the root into a leaf and break */
42295f39d397SChris Mason 		btrfs_set_header_level(root->node, 0);
4230bb803951SChris Mason 	} else if (slot == 0) {
42315f39d397SChris Mason 		struct btrfs_disk_key disk_key;
42325f39d397SChris Mason 
42335f39d397SChris Mason 		btrfs_node_key(parent, &disk_key, 0);
4234b167fa91SNikolay Borisov 		fixup_low_keys(path, &disk_key, level + 1);
4235be0e5c09SChris Mason 	}
4236d6025579SChris Mason 	btrfs_mark_buffer_dirty(parent);
4237be0e5c09SChris Mason }
4238be0e5c09SChris Mason 
423974123bd7SChris Mason /*
4240323ac95bSChris Mason  * a helper function to delete the leaf pointed to by path->slots[1] and
42415d4f98a2SYan Zheng  * path->nodes[1].
4242323ac95bSChris Mason  *
4243323ac95bSChris Mason  * This deletes the pointer in path->nodes[1] and frees the leaf
4244323ac95bSChris Mason  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4245323ac95bSChris Mason  *
4246323ac95bSChris Mason  * The path must have already been setup for deleting the leaf, including
4247323ac95bSChris Mason  * all the proper balancing.  path->nodes[1] must be locked.
4248323ac95bSChris Mason  */
4249143bede5SJeff Mahoney static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4250323ac95bSChris Mason 				    struct btrfs_root *root,
42515d4f98a2SYan Zheng 				    struct btrfs_path *path,
42525d4f98a2SYan Zheng 				    struct extent_buffer *leaf)
4253323ac95bSChris Mason {
42545d4f98a2SYan Zheng 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4255afe5fea7STsutomu Itoh 	del_ptr(root, path, 1, path->slots[1]);
4256323ac95bSChris Mason 
42574d081c41SChris Mason 	/*
42584d081c41SChris Mason 	 * btrfs_free_extent is expensive, we want to make sure we
42594d081c41SChris Mason 	 * aren't holding any locks when we call it
42604d081c41SChris Mason 	 */
42614d081c41SChris Mason 	btrfs_unlock_up_safe(path, 0);
42624d081c41SChris Mason 
4263f0486c68SYan, Zheng 	root_sub_used(root, leaf->len);
4264f0486c68SYan, Zheng 
426567439dadSDavid Sterba 	atomic_inc(&leaf->refs);
42667a163608SFilipe Manana 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
42673083ee2eSJosef Bacik 	free_extent_buffer_stale(leaf);
4268323ac95bSChris Mason }
4269323ac95bSChris Mason /*
427074123bd7SChris Mason  * delete the item at the leaf level in path.  If that empties
427174123bd7SChris Mason  * the leaf, remove it from the tree
427274123bd7SChris Mason  */
427385e21bacSChris Mason int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
427485e21bacSChris Mason 		    struct btrfs_path *path, int slot, int nr)
4275be0e5c09SChris Mason {
42760b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
42775f39d397SChris Mason 	struct extent_buffer *leaf;
4278aa5d6bedSChris Mason 	int ret = 0;
4279aa5d6bedSChris Mason 	int wret;
42807518a238SChris Mason 	u32 nritems;
4281be0e5c09SChris Mason 
42825f39d397SChris Mason 	leaf = path->nodes[0];
42835f39d397SChris Mason 	nritems = btrfs_header_nritems(leaf);
4284be0e5c09SChris Mason 
428585e21bacSChris Mason 	if (slot + nr != nritems) {
42860cae23b6SFilipe Manana 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
42870cae23b6SFilipe Manana 		const int data_end = leaf_data_end(leaf);
4288c82f823cSDavid Sterba 		struct btrfs_map_token token;
42890cae23b6SFilipe Manana 		u32 dsize = 0;
42900cae23b6SFilipe Manana 		int i;
42910cae23b6SFilipe Manana 
42920cae23b6SFilipe Manana 		for (i = 0; i < nr; i++)
42930cae23b6SFilipe Manana 			dsize += btrfs_item_size(leaf, slot + i);
42945f39d397SChris Mason 
42953d9ec8c4SNikolay Borisov 		memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4296d6025579SChris Mason 			      data_end + dsize,
42973d9ec8c4SNikolay Borisov 			      BTRFS_LEAF_DATA_OFFSET + data_end,
429885e21bacSChris Mason 			      last_off - data_end);
42995f39d397SChris Mason 
4300c82f823cSDavid Sterba 		btrfs_init_map_token(&token, leaf);
430185e21bacSChris Mason 		for (i = slot + nr; i < nritems; i++) {
43025f39d397SChris Mason 			u32 ioff;
4303db94535dSChris Mason 
43043212fa14SJosef Bacik 			ioff = btrfs_token_item_offset(&token, i);
43053212fa14SJosef Bacik 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
43060783fcfcSChris Mason 		}
4307db94535dSChris Mason 
43085f39d397SChris Mason 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
430985e21bacSChris Mason 			      btrfs_item_nr_offset(slot + nr),
43100783fcfcSChris Mason 			      sizeof(struct btrfs_item) *
431185e21bacSChris Mason 			      (nritems - slot - nr));
4312be0e5c09SChris Mason 	}
431385e21bacSChris Mason 	btrfs_set_header_nritems(leaf, nritems - nr);
431485e21bacSChris Mason 	nritems -= nr;
43155f39d397SChris Mason 
431674123bd7SChris Mason 	/* delete the leaf if we've emptied it */
43177518a238SChris Mason 	if (nritems == 0) {
43185f39d397SChris Mason 		if (leaf == root->node) {
43195f39d397SChris Mason 			btrfs_set_header_level(leaf, 0);
43209a8dd150SChris Mason 		} else {
43216a884d7dSDavid Sterba 			btrfs_clean_tree_block(leaf);
4322143bede5SJeff Mahoney 			btrfs_del_leaf(trans, root, path, leaf);
43239a8dd150SChris Mason 		}
4324be0e5c09SChris Mason 	} else {
43257518a238SChris Mason 		int used = leaf_space_used(leaf, 0, nritems);
4326aa5d6bedSChris Mason 		if (slot == 0) {
43275f39d397SChris Mason 			struct btrfs_disk_key disk_key;
43285f39d397SChris Mason 
43295f39d397SChris Mason 			btrfs_item_key(leaf, &disk_key, 0);
4330b167fa91SNikolay Borisov 			fixup_low_keys(path, &disk_key, 1);
4331aa5d6bedSChris Mason 		}
4332aa5d6bedSChris Mason 
43337c4063d1SFilipe Manana 		/*
43347c4063d1SFilipe Manana 		 * Try to delete the leaf if it is mostly empty. We do this by
43357c4063d1SFilipe Manana 		 * trying to move all its items into its left and right neighbours.
43367c4063d1SFilipe Manana 		 * If we can't move all the items, then we don't delete it - it's
43377c4063d1SFilipe Manana 		 * not ideal, but future insertions might fill the leaf with more
43387c4063d1SFilipe Manana 		 * items, or items from other leaves might be moved later into our
43397c4063d1SFilipe Manana 		 * leaf due to deletions on those leaves.
43407c4063d1SFilipe Manana 		 */
43410b246afaSJeff Mahoney 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
43427c4063d1SFilipe Manana 			u32 min_push_space;
43437c4063d1SFilipe Manana 
4344be0e5c09SChris Mason 			/* push_leaf_left fixes the path.
4345be0e5c09SChris Mason 			 * make sure the path still points to our leaf
4346be0e5c09SChris Mason 			 * for possible call to del_ptr below
4347be0e5c09SChris Mason 			 */
43484920c9acSChris Mason 			slot = path->slots[1];
434967439dadSDavid Sterba 			atomic_inc(&leaf->refs);
43507c4063d1SFilipe Manana 			/*
43517c4063d1SFilipe Manana 			 * We want to be able to at least push one item to the
43527c4063d1SFilipe Manana 			 * left neighbour leaf, and that's the first item.
43537c4063d1SFilipe Manana 			 */
43547c4063d1SFilipe Manana 			min_push_space = sizeof(struct btrfs_item) +
43557c4063d1SFilipe Manana 				btrfs_item_size(leaf, 0);
43567c4063d1SFilipe Manana 			wret = push_leaf_left(trans, root, path, 0,
43577c4063d1SFilipe Manana 					      min_push_space, 1, (u32)-1);
435854aa1f4dSChris Mason 			if (wret < 0 && wret != -ENOSPC)
4359aa5d6bedSChris Mason 				ret = wret;
43605f39d397SChris Mason 
43615f39d397SChris Mason 			if (path->nodes[0] == leaf &&
43625f39d397SChris Mason 			    btrfs_header_nritems(leaf)) {
43637c4063d1SFilipe Manana 				/*
43647c4063d1SFilipe Manana 				 * If we were not able to push all items from our
43657c4063d1SFilipe Manana 				 * leaf to its left neighbour, then attempt to
43667c4063d1SFilipe Manana 				 * either push all the remaining items to the
43677c4063d1SFilipe Manana 				 * right neighbour or none. There's no advantage
43687c4063d1SFilipe Manana 				 * in pushing only some items, instead of all, as
43697c4063d1SFilipe Manana 				 * it's pointless to end up with a leaf having
43707c4063d1SFilipe Manana 				 * too few items while the neighbours can be full
43717c4063d1SFilipe Manana 				 * or nearly full.
43727c4063d1SFilipe Manana 				 */
43737c4063d1SFilipe Manana 				nritems = btrfs_header_nritems(leaf);
43747c4063d1SFilipe Manana 				min_push_space = leaf_space_used(leaf, 0, nritems);
43757c4063d1SFilipe Manana 				wret = push_leaf_right(trans, root, path, 0,
43767c4063d1SFilipe Manana 						       min_push_space, 1, 0);
437754aa1f4dSChris Mason 				if (wret < 0 && wret != -ENOSPC)
4378aa5d6bedSChris Mason 					ret = wret;
4379aa5d6bedSChris Mason 			}
43805f39d397SChris Mason 
43815f39d397SChris Mason 			if (btrfs_header_nritems(leaf) == 0) {
4382323ac95bSChris Mason 				path->slots[1] = slot;
4383143bede5SJeff Mahoney 				btrfs_del_leaf(trans, root, path, leaf);
43845f39d397SChris Mason 				free_extent_buffer(leaf);
4385143bede5SJeff Mahoney 				ret = 0;
43865de08d7dSChris Mason 			} else {
4387925baeddSChris Mason 				/* if we're still in the path, make sure
4388925baeddSChris Mason 				 * we're dirty.  Otherwise, one of the
4389925baeddSChris Mason 				 * push_leaf functions must have already
4390925baeddSChris Mason 				 * dirtied this buffer
4391925baeddSChris Mason 				 */
4392925baeddSChris Mason 				if (path->nodes[0] == leaf)
43935f39d397SChris Mason 					btrfs_mark_buffer_dirty(leaf);
43945f39d397SChris Mason 				free_extent_buffer(leaf);
4395be0e5c09SChris Mason 			}
4396d5719762SChris Mason 		} else {
43975f39d397SChris Mason 			btrfs_mark_buffer_dirty(leaf);
4398be0e5c09SChris Mason 		}
43999a8dd150SChris Mason 	}
4400aa5d6bedSChris Mason 	return ret;
44019a8dd150SChris Mason }
44029a8dd150SChris Mason 
440397571fd0SChris Mason /*
4404925baeddSChris Mason  * search the tree again to find a leaf with lesser keys
44057bb86316SChris Mason  * returns 0 if it found something or 1 if there are no lesser leaves.
44067bb86316SChris Mason  * returns < 0 on io errors.
4407d352ac68SChris Mason  *
4408d352ac68SChris Mason  * This may release the path, and so you may lose any locks held at the
4409d352ac68SChris Mason  * time you call it.
44107bb86316SChris Mason  */
441116e7549fSJosef Bacik int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
44127bb86316SChris Mason {
4413925baeddSChris Mason 	struct btrfs_key key;
4414925baeddSChris Mason 	struct btrfs_disk_key found_key;
4415925baeddSChris Mason 	int ret;
44167bb86316SChris Mason 
4417925baeddSChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4418925baeddSChris Mason 
4419e8b0d724SFilipe David Borba Manana 	if (key.offset > 0) {
4420925baeddSChris Mason 		key.offset--;
4421e8b0d724SFilipe David Borba Manana 	} else if (key.type > 0) {
4422925baeddSChris Mason 		key.type--;
4423e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4424e8b0d724SFilipe David Borba Manana 	} else if (key.objectid > 0) {
4425925baeddSChris Mason 		key.objectid--;
4426e8b0d724SFilipe David Borba Manana 		key.type = (u8)-1;
4427e8b0d724SFilipe David Borba Manana 		key.offset = (u64)-1;
4428e8b0d724SFilipe David Borba Manana 	} else {
44297bb86316SChris Mason 		return 1;
4430e8b0d724SFilipe David Borba Manana 	}
44317bb86316SChris Mason 
4432b3b4aa74SDavid Sterba 	btrfs_release_path(path);
4433925baeddSChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4434925baeddSChris Mason 	if (ret < 0)
4435925baeddSChris Mason 		return ret;
4436925baeddSChris Mason 	btrfs_item_key(path->nodes[0], &found_key, 0);
4437925baeddSChris Mason 	ret = comp_keys(&found_key, &key);
4438337c6f68SFilipe Manana 	/*
4439337c6f68SFilipe Manana 	 * We might have had an item with the previous key in the tree right
4440337c6f68SFilipe Manana 	 * before we released our path. And after we released our path, that
4441337c6f68SFilipe Manana 	 * item might have been pushed to the first slot (0) of the leaf we
4442337c6f68SFilipe Manana 	 * were holding due to a tree balance. Alternatively, an item with the
4443337c6f68SFilipe Manana 	 * previous key can exist as the only element of a leaf (big fat item).
4444337c6f68SFilipe Manana 	 * Therefore account for these 2 cases, so that our callers (like
4445337c6f68SFilipe Manana 	 * btrfs_previous_item) don't miss an existing item with a key matching
4446337c6f68SFilipe Manana 	 * the previous key we computed above.
4447337c6f68SFilipe Manana 	 */
4448337c6f68SFilipe Manana 	if (ret <= 0)
44497bb86316SChris Mason 		return 0;
4450925baeddSChris Mason 	return 1;
44517bb86316SChris Mason }
44527bb86316SChris Mason 
44533f157a2fSChris Mason /*
44543f157a2fSChris Mason  * A helper function to walk down the tree starting at min_key, and looking
4455de78b51aSEric Sandeen  * for nodes or leaves that are have a minimum transaction id.
4456de78b51aSEric Sandeen  * This is used by the btree defrag code, and tree logging
44573f157a2fSChris Mason  *
44583f157a2fSChris Mason  * This does not cow, but it does stuff the starting key it finds back
44593f157a2fSChris Mason  * into min_key, so you can call btrfs_search_slot with cow=1 on the
44603f157a2fSChris Mason  * key and get a writable path.
44613f157a2fSChris Mason  *
44623f157a2fSChris Mason  * This honors path->lowest_level to prevent descent past a given level
44633f157a2fSChris Mason  * of the tree.
44643f157a2fSChris Mason  *
4465d352ac68SChris Mason  * min_trans indicates the oldest transaction that you are interested
4466d352ac68SChris Mason  * in walking through.  Any nodes or leaves older than min_trans are
4467d352ac68SChris Mason  * skipped over (without reading them).
4468d352ac68SChris Mason  *
44693f157a2fSChris Mason  * returns zero if something useful was found, < 0 on error and 1 if there
44703f157a2fSChris Mason  * was nothing in the tree that matched the search criteria.
44713f157a2fSChris Mason  */
44723f157a2fSChris Mason int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4473de78b51aSEric Sandeen 			 struct btrfs_path *path,
44743f157a2fSChris Mason 			 u64 min_trans)
44753f157a2fSChris Mason {
44763f157a2fSChris Mason 	struct extent_buffer *cur;
44773f157a2fSChris Mason 	struct btrfs_key found_key;
44783f157a2fSChris Mason 	int slot;
44799652480bSYan 	int sret;
44803f157a2fSChris Mason 	u32 nritems;
44813f157a2fSChris Mason 	int level;
44823f157a2fSChris Mason 	int ret = 1;
4483f98de9b9SFilipe Manana 	int keep_locks = path->keep_locks;
44843f157a2fSChris Mason 
4485c922b016SStefan Roesch 	ASSERT(!path->nowait);
4486f98de9b9SFilipe Manana 	path->keep_locks = 1;
44873f157a2fSChris Mason again:
4488bd681513SChris Mason 	cur = btrfs_read_lock_root_node(root);
44893f157a2fSChris Mason 	level = btrfs_header_level(cur);
4490e02119d5SChris Mason 	WARN_ON(path->nodes[level]);
44913f157a2fSChris Mason 	path->nodes[level] = cur;
4492bd681513SChris Mason 	path->locks[level] = BTRFS_READ_LOCK;
44933f157a2fSChris Mason 
44943f157a2fSChris Mason 	if (btrfs_header_generation(cur) < min_trans) {
44953f157a2fSChris Mason 		ret = 1;
44963f157a2fSChris Mason 		goto out;
44973f157a2fSChris Mason 	}
44983f157a2fSChris Mason 	while (1) {
44993f157a2fSChris Mason 		nritems = btrfs_header_nritems(cur);
45003f157a2fSChris Mason 		level = btrfs_header_level(cur);
4501e3b83361SQu Wenruo 		sret = btrfs_bin_search(cur, min_key, &slot);
4502cbca7d59SFilipe Manana 		if (sret < 0) {
4503cbca7d59SFilipe Manana 			ret = sret;
4504cbca7d59SFilipe Manana 			goto out;
4505cbca7d59SFilipe Manana 		}
45063f157a2fSChris Mason 
4507323ac95bSChris Mason 		/* at the lowest level, we're done, setup the path and exit */
4508323ac95bSChris Mason 		if (level == path->lowest_level) {
4509e02119d5SChris Mason 			if (slot >= nritems)
4510e02119d5SChris Mason 				goto find_next_key;
45113f157a2fSChris Mason 			ret = 0;
45123f157a2fSChris Mason 			path->slots[level] = slot;
45133f157a2fSChris Mason 			btrfs_item_key_to_cpu(cur, &found_key, slot);
45143f157a2fSChris Mason 			goto out;
45153f157a2fSChris Mason 		}
45169652480bSYan 		if (sret && slot > 0)
45179652480bSYan 			slot--;
45183f157a2fSChris Mason 		/*
4519de78b51aSEric Sandeen 		 * check this node pointer against the min_trans parameters.
4520260db43cSRandy Dunlap 		 * If it is too old, skip to the next one.
45213f157a2fSChris Mason 		 */
45223f157a2fSChris Mason 		while (slot < nritems) {
45233f157a2fSChris Mason 			u64 gen;
4524e02119d5SChris Mason 
45253f157a2fSChris Mason 			gen = btrfs_node_ptr_generation(cur, slot);
45263f157a2fSChris Mason 			if (gen < min_trans) {
45273f157a2fSChris Mason 				slot++;
45283f157a2fSChris Mason 				continue;
45293f157a2fSChris Mason 			}
45303f157a2fSChris Mason 			break;
45313f157a2fSChris Mason 		}
4532e02119d5SChris Mason find_next_key:
45333f157a2fSChris Mason 		/*
45343f157a2fSChris Mason 		 * we didn't find a candidate key in this node, walk forward
45353f157a2fSChris Mason 		 * and find another one
45363f157a2fSChris Mason 		 */
45373f157a2fSChris Mason 		if (slot >= nritems) {
4538e02119d5SChris Mason 			path->slots[level] = slot;
4539e02119d5SChris Mason 			sret = btrfs_find_next_key(root, path, min_key, level,
4540de78b51aSEric Sandeen 						  min_trans);
4541e02119d5SChris Mason 			if (sret == 0) {
4542b3b4aa74SDavid Sterba 				btrfs_release_path(path);
45433f157a2fSChris Mason 				goto again;
45443f157a2fSChris Mason 			} else {
45453f157a2fSChris Mason 				goto out;
45463f157a2fSChris Mason 			}
45473f157a2fSChris Mason 		}
45483f157a2fSChris Mason 		/* save our key for returning back */
45493f157a2fSChris Mason 		btrfs_node_key_to_cpu(cur, &found_key, slot);
45503f157a2fSChris Mason 		path->slots[level] = slot;
45513f157a2fSChris Mason 		if (level == path->lowest_level) {
45523f157a2fSChris Mason 			ret = 0;
45533f157a2fSChris Mason 			goto out;
45543f157a2fSChris Mason 		}
45554b231ae4SDavid Sterba 		cur = btrfs_read_node_slot(cur, slot);
4556fb770ae4SLiu Bo 		if (IS_ERR(cur)) {
4557fb770ae4SLiu Bo 			ret = PTR_ERR(cur);
4558fb770ae4SLiu Bo 			goto out;
4559fb770ae4SLiu Bo 		}
45603f157a2fSChris Mason 
4561bd681513SChris Mason 		btrfs_tree_read_lock(cur);
4562b4ce94deSChris Mason 
4563bd681513SChris Mason 		path->locks[level - 1] = BTRFS_READ_LOCK;
45643f157a2fSChris Mason 		path->nodes[level - 1] = cur;
4565f7c79f30SChris Mason 		unlock_up(path, level, 1, 0, NULL);
45663f157a2fSChris Mason 	}
45673f157a2fSChris Mason out:
4568f98de9b9SFilipe Manana 	path->keep_locks = keep_locks;
4569f98de9b9SFilipe Manana 	if (ret == 0) {
4570f98de9b9SFilipe Manana 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4571f98de9b9SFilipe Manana 		memcpy(min_key, &found_key, sizeof(found_key));
4572f98de9b9SFilipe Manana 	}
45733f157a2fSChris Mason 	return ret;
45743f157a2fSChris Mason }
45753f157a2fSChris Mason 
45763f157a2fSChris Mason /*
45773f157a2fSChris Mason  * this is similar to btrfs_next_leaf, but does not try to preserve
45783f157a2fSChris Mason  * and fixup the path.  It looks for and returns the next key in the
4579de78b51aSEric Sandeen  * tree based on the current path and the min_trans parameters.
45803f157a2fSChris Mason  *
45813f157a2fSChris Mason  * 0 is returned if another key is found, < 0 if there are any errors
45823f157a2fSChris Mason  * and 1 is returned if there are no higher keys in the tree
45833f157a2fSChris Mason  *
45843f157a2fSChris Mason  * path->keep_locks should be set to 1 on the search made before
45853f157a2fSChris Mason  * calling this function.
45863f157a2fSChris Mason  */
4587e7a84565SChris Mason int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4588de78b51aSEric Sandeen 			struct btrfs_key *key, int level, u64 min_trans)
4589e7a84565SChris Mason {
4590e7a84565SChris Mason 	int slot;
4591e7a84565SChris Mason 	struct extent_buffer *c;
4592e7a84565SChris Mason 
45936a9fb468SJosef Bacik 	WARN_ON(!path->keep_locks && !path->skip_locking);
4594e7a84565SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
4595e7a84565SChris Mason 		if (!path->nodes[level])
4596e7a84565SChris Mason 			return 1;
4597e7a84565SChris Mason 
4598e7a84565SChris Mason 		slot = path->slots[level] + 1;
4599e7a84565SChris Mason 		c = path->nodes[level];
46003f157a2fSChris Mason next:
4601e7a84565SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
460233c66f43SYan Zheng 			int ret;
460333c66f43SYan Zheng 			int orig_lowest;
460433c66f43SYan Zheng 			struct btrfs_key cur_key;
460533c66f43SYan Zheng 			if (level + 1 >= BTRFS_MAX_LEVEL ||
460633c66f43SYan Zheng 			    !path->nodes[level + 1])
4607e7a84565SChris Mason 				return 1;
460833c66f43SYan Zheng 
46096a9fb468SJosef Bacik 			if (path->locks[level + 1] || path->skip_locking) {
461033c66f43SYan Zheng 				level++;
4611e7a84565SChris Mason 				continue;
4612e7a84565SChris Mason 			}
461333c66f43SYan Zheng 
461433c66f43SYan Zheng 			slot = btrfs_header_nritems(c) - 1;
461533c66f43SYan Zheng 			if (level == 0)
461633c66f43SYan Zheng 				btrfs_item_key_to_cpu(c, &cur_key, slot);
461733c66f43SYan Zheng 			else
461833c66f43SYan Zheng 				btrfs_node_key_to_cpu(c, &cur_key, slot);
461933c66f43SYan Zheng 
462033c66f43SYan Zheng 			orig_lowest = path->lowest_level;
4621b3b4aa74SDavid Sterba 			btrfs_release_path(path);
462233c66f43SYan Zheng 			path->lowest_level = level;
462333c66f43SYan Zheng 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
462433c66f43SYan Zheng 						0, 0);
462533c66f43SYan Zheng 			path->lowest_level = orig_lowest;
462633c66f43SYan Zheng 			if (ret < 0)
462733c66f43SYan Zheng 				return ret;
462833c66f43SYan Zheng 
462933c66f43SYan Zheng 			c = path->nodes[level];
463033c66f43SYan Zheng 			slot = path->slots[level];
463133c66f43SYan Zheng 			if (ret == 0)
463233c66f43SYan Zheng 				slot++;
463333c66f43SYan Zheng 			goto next;
463433c66f43SYan Zheng 		}
463533c66f43SYan Zheng 
4636e7a84565SChris Mason 		if (level == 0)
4637e7a84565SChris Mason 			btrfs_item_key_to_cpu(c, key, slot);
46383f157a2fSChris Mason 		else {
46393f157a2fSChris Mason 			u64 gen = btrfs_node_ptr_generation(c, slot);
46403f157a2fSChris Mason 
46413f157a2fSChris Mason 			if (gen < min_trans) {
46423f157a2fSChris Mason 				slot++;
46433f157a2fSChris Mason 				goto next;
46443f157a2fSChris Mason 			}
4645e7a84565SChris Mason 			btrfs_node_key_to_cpu(c, key, slot);
46463f157a2fSChris Mason 		}
4647e7a84565SChris Mason 		return 0;
4648e7a84565SChris Mason 	}
4649e7a84565SChris Mason 	return 1;
4650e7a84565SChris Mason }
4651e7a84565SChris Mason 
46523d7806ecSJan Schmidt int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
46533d7806ecSJan Schmidt 			u64 time_seq)
46543d7806ecSJan Schmidt {
4655d97e63b6SChris Mason 	int slot;
46568e73f275SChris Mason 	int level;
46575f39d397SChris Mason 	struct extent_buffer *c;
46588e73f275SChris Mason 	struct extent_buffer *next;
4659d96b3424SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
4660925baeddSChris Mason 	struct btrfs_key key;
4661d96b3424SFilipe Manana 	bool need_commit_sem = false;
4662925baeddSChris Mason 	u32 nritems;
4663925baeddSChris Mason 	int ret;
46640e46318dSJosef Bacik 	int i;
4665925baeddSChris Mason 
4666*bdcdd86cSFilipe Manana 	/*
4667*bdcdd86cSFilipe Manana 	 * The nowait semantics are used only for write paths, where we don't
4668*bdcdd86cSFilipe Manana 	 * use the tree mod log and sequence numbers.
4669*bdcdd86cSFilipe Manana 	 */
4670*bdcdd86cSFilipe Manana 	if (time_seq)
4671c922b016SStefan Roesch 		ASSERT(!path->nowait);
4672c922b016SStefan Roesch 
4673925baeddSChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4674d397712bSChris Mason 	if (nritems == 0)
4675925baeddSChris Mason 		return 1;
4676925baeddSChris Mason 
46778e73f275SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
46788e73f275SChris Mason again:
46798e73f275SChris Mason 	level = 1;
46808e73f275SChris Mason 	next = NULL;
4681b3b4aa74SDavid Sterba 	btrfs_release_path(path);
46828e73f275SChris Mason 
4683a2135011SChris Mason 	path->keep_locks = 1;
46848e73f275SChris Mason 
4685d96b3424SFilipe Manana 	if (time_seq) {
46863d7806ecSJan Schmidt 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4687d96b3424SFilipe Manana 	} else {
4688d96b3424SFilipe Manana 		if (path->need_commit_sem) {
4689d96b3424SFilipe Manana 			path->need_commit_sem = 0;
4690d96b3424SFilipe Manana 			need_commit_sem = true;
4691*bdcdd86cSFilipe Manana 			if (path->nowait) {
4692*bdcdd86cSFilipe Manana 				if (!down_read_trylock(&fs_info->commit_root_sem)) {
4693*bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4694*bdcdd86cSFilipe Manana 					goto done;
4695*bdcdd86cSFilipe Manana 				}
4696*bdcdd86cSFilipe Manana 			} else {
4697d96b3424SFilipe Manana 				down_read(&fs_info->commit_root_sem);
4698d96b3424SFilipe Manana 			}
4699*bdcdd86cSFilipe Manana 		}
4700925baeddSChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4701d96b3424SFilipe Manana 	}
4702925baeddSChris Mason 	path->keep_locks = 0;
4703925baeddSChris Mason 
4704925baeddSChris Mason 	if (ret < 0)
4705d96b3424SFilipe Manana 		goto done;
4706925baeddSChris Mason 
4707a2135011SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
4708168fd7d2SChris Mason 	/*
4709168fd7d2SChris Mason 	 * by releasing the path above we dropped all our locks.  A balance
4710168fd7d2SChris Mason 	 * could have added more items next to the key that used to be
4711168fd7d2SChris Mason 	 * at the very end of the block.  So, check again here and
4712168fd7d2SChris Mason 	 * advance the path if there are now more items available.
4713168fd7d2SChris Mason 	 */
4714a2135011SChris Mason 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4715e457afecSYan Zheng 		if (ret == 0)
4716168fd7d2SChris Mason 			path->slots[0]++;
47178e73f275SChris Mason 		ret = 0;
4718925baeddSChris Mason 		goto done;
4719925baeddSChris Mason 	}
47200b43e04fSLiu Bo 	/*
47210b43e04fSLiu Bo 	 * So the above check misses one case:
47220b43e04fSLiu Bo 	 * - after releasing the path above, someone has removed the item that
47230b43e04fSLiu Bo 	 *   used to be at the very end of the block, and balance between leafs
47240b43e04fSLiu Bo 	 *   gets another one with bigger key.offset to replace it.
47250b43e04fSLiu Bo 	 *
47260b43e04fSLiu Bo 	 * This one should be returned as well, or we can get leaf corruption
47270b43e04fSLiu Bo 	 * later(esp. in __btrfs_drop_extents()).
47280b43e04fSLiu Bo 	 *
47290b43e04fSLiu Bo 	 * And a bit more explanation about this check,
47300b43e04fSLiu Bo 	 * with ret > 0, the key isn't found, the path points to the slot
47310b43e04fSLiu Bo 	 * where it should be inserted, so the path->slots[0] item must be the
47320b43e04fSLiu Bo 	 * bigger one.
47330b43e04fSLiu Bo 	 */
47340b43e04fSLiu Bo 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
47350b43e04fSLiu Bo 		ret = 0;
47360b43e04fSLiu Bo 		goto done;
47370b43e04fSLiu Bo 	}
4738d97e63b6SChris Mason 
4739234b63a0SChris Mason 	while (level < BTRFS_MAX_LEVEL) {
47408e73f275SChris Mason 		if (!path->nodes[level]) {
47418e73f275SChris Mason 			ret = 1;
47428e73f275SChris Mason 			goto done;
47438e73f275SChris Mason 		}
47445f39d397SChris Mason 
4745d97e63b6SChris Mason 		slot = path->slots[level] + 1;
4746d97e63b6SChris Mason 		c = path->nodes[level];
47475f39d397SChris Mason 		if (slot >= btrfs_header_nritems(c)) {
4748d97e63b6SChris Mason 			level++;
47498e73f275SChris Mason 			if (level == BTRFS_MAX_LEVEL) {
47508e73f275SChris Mason 				ret = 1;
47518e73f275SChris Mason 				goto done;
47528e73f275SChris Mason 			}
4753d97e63b6SChris Mason 			continue;
4754d97e63b6SChris Mason 		}
47555f39d397SChris Mason 
47560e46318dSJosef Bacik 
47570e46318dSJosef Bacik 		/*
47580e46318dSJosef Bacik 		 * Our current level is where we're going to start from, and to
47590e46318dSJosef Bacik 		 * make sure lockdep doesn't complain we need to drop our locks
47600e46318dSJosef Bacik 		 * and nodes from 0 to our current level.
47610e46318dSJosef Bacik 		 */
47620e46318dSJosef Bacik 		for (i = 0; i < level; i++) {
47630e46318dSJosef Bacik 			if (path->locks[level]) {
47640e46318dSJosef Bacik 				btrfs_tree_read_unlock(path->nodes[i]);
47650e46318dSJosef Bacik 				path->locks[i] = 0;
47660e46318dSJosef Bacik 			}
47670e46318dSJosef Bacik 			free_extent_buffer(path->nodes[i]);
47680e46318dSJosef Bacik 			path->nodes[i] = NULL;
4769925baeddSChris Mason 		}
47705f39d397SChris Mason 
47718e73f275SChris Mason 		next = c;
4772d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4773cda79c54SDavid Sterba 					    slot, &key);
4774*bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
47758e73f275SChris Mason 			goto again;
47765f39d397SChris Mason 
477776a05b35SChris Mason 		if (ret < 0) {
4778b3b4aa74SDavid Sterba 			btrfs_release_path(path);
477976a05b35SChris Mason 			goto done;
478076a05b35SChris Mason 		}
478176a05b35SChris Mason 
47825cd57b2cSChris Mason 		if (!path->skip_locking) {
4783bd681513SChris Mason 			ret = btrfs_try_tree_read_lock(next);
4784*bdcdd86cSFilipe Manana 			if (!ret && path->nowait) {
4785*bdcdd86cSFilipe Manana 				ret = -EAGAIN;
4786*bdcdd86cSFilipe Manana 				goto done;
4787*bdcdd86cSFilipe Manana 			}
4788d42244a0SJan Schmidt 			if (!ret && time_seq) {
4789d42244a0SJan Schmidt 				/*
4790d42244a0SJan Schmidt 				 * If we don't get the lock, we may be racing
4791d42244a0SJan Schmidt 				 * with push_leaf_left, holding that lock while
4792d42244a0SJan Schmidt 				 * itself waiting for the leaf we've currently
4793d42244a0SJan Schmidt 				 * locked. To solve this situation, we give up
4794d42244a0SJan Schmidt 				 * on our lock and cycle.
4795d42244a0SJan Schmidt 				 */
4796cf538830SJan Schmidt 				free_extent_buffer(next);
4797d42244a0SJan Schmidt 				btrfs_release_path(path);
4798d42244a0SJan Schmidt 				cond_resched();
4799d42244a0SJan Schmidt 				goto again;
4800d42244a0SJan Schmidt 			}
48010e46318dSJosef Bacik 			if (!ret)
48020e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4803bd681513SChris Mason 		}
4804d97e63b6SChris Mason 		break;
4805d97e63b6SChris Mason 	}
4806d97e63b6SChris Mason 	path->slots[level] = slot;
4807d97e63b6SChris Mason 	while (1) {
4808d97e63b6SChris Mason 		level--;
4809d97e63b6SChris Mason 		path->nodes[level] = next;
4810d97e63b6SChris Mason 		path->slots[level] = 0;
4811a74a4b97SChris Mason 		if (!path->skip_locking)
4812ffeb03cfSJosef Bacik 			path->locks[level] = BTRFS_READ_LOCK;
4813d97e63b6SChris Mason 		if (!level)
4814d97e63b6SChris Mason 			break;
4815b4ce94deSChris Mason 
4816d07b8528SLiu Bo 		ret = read_block_for_search(root, path, &next, level,
4817cda79c54SDavid Sterba 					    0, &key);
4818*bdcdd86cSFilipe Manana 		if (ret == -EAGAIN && !path->nowait)
48198e73f275SChris Mason 			goto again;
48208e73f275SChris Mason 
482176a05b35SChris Mason 		if (ret < 0) {
4822b3b4aa74SDavid Sterba 			btrfs_release_path(path);
482376a05b35SChris Mason 			goto done;
482476a05b35SChris Mason 		}
482576a05b35SChris Mason 
4826*bdcdd86cSFilipe Manana 		if (!path->skip_locking) {
4827*bdcdd86cSFilipe Manana 			if (path->nowait) {
4828*bdcdd86cSFilipe Manana 				if (!btrfs_try_tree_read_lock(next)) {
4829*bdcdd86cSFilipe Manana 					ret = -EAGAIN;
4830*bdcdd86cSFilipe Manana 					goto done;
4831*bdcdd86cSFilipe Manana 				}
4832*bdcdd86cSFilipe Manana 			} else {
48330e46318dSJosef Bacik 				btrfs_tree_read_lock(next);
4834d97e63b6SChris Mason 			}
4835*bdcdd86cSFilipe Manana 		}
4836*bdcdd86cSFilipe Manana 	}
48378e73f275SChris Mason 	ret = 0;
4838925baeddSChris Mason done:
4839f7c79f30SChris Mason 	unlock_up(path, 0, 1, 0, NULL);
4840d96b3424SFilipe Manana 	if (need_commit_sem) {
4841d96b3424SFilipe Manana 		int ret2;
4842d96b3424SFilipe Manana 
4843d96b3424SFilipe Manana 		path->need_commit_sem = 1;
4844d96b3424SFilipe Manana 		ret2 = finish_need_commit_sem_search(path);
4845d96b3424SFilipe Manana 		up_read(&fs_info->commit_root_sem);
4846d96b3424SFilipe Manana 		if (ret2)
4847d96b3424SFilipe Manana 			ret = ret2;
4848d96b3424SFilipe Manana 	}
48498e73f275SChris Mason 
48508e73f275SChris Mason 	return ret;
4851d97e63b6SChris Mason }
48520b86a832SChris Mason 
48533f157a2fSChris Mason /*
48543f157a2fSChris Mason  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
48553f157a2fSChris Mason  * searching until it gets past min_objectid or finds an item of 'type'
48563f157a2fSChris Mason  *
48573f157a2fSChris Mason  * returns 0 if something is found, 1 if nothing was found and < 0 on error
48583f157a2fSChris Mason  */
48590b86a832SChris Mason int btrfs_previous_item(struct btrfs_root *root,
48600b86a832SChris Mason 			struct btrfs_path *path, u64 min_objectid,
48610b86a832SChris Mason 			int type)
48620b86a832SChris Mason {
48630b86a832SChris Mason 	struct btrfs_key found_key;
48640b86a832SChris Mason 	struct extent_buffer *leaf;
4865e02119d5SChris Mason 	u32 nritems;
48660b86a832SChris Mason 	int ret;
48670b86a832SChris Mason 
48680b86a832SChris Mason 	while (1) {
48690b86a832SChris Mason 		if (path->slots[0] == 0) {
48700b86a832SChris Mason 			ret = btrfs_prev_leaf(root, path);
48710b86a832SChris Mason 			if (ret != 0)
48720b86a832SChris Mason 				return ret;
48730b86a832SChris Mason 		} else {
48740b86a832SChris Mason 			path->slots[0]--;
48750b86a832SChris Mason 		}
48760b86a832SChris Mason 		leaf = path->nodes[0];
4877e02119d5SChris Mason 		nritems = btrfs_header_nritems(leaf);
4878e02119d5SChris Mason 		if (nritems == 0)
4879e02119d5SChris Mason 			return 1;
4880e02119d5SChris Mason 		if (path->slots[0] == nritems)
4881e02119d5SChris Mason 			path->slots[0]--;
4882e02119d5SChris Mason 
48830b86a832SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4884e02119d5SChris Mason 		if (found_key.objectid < min_objectid)
4885e02119d5SChris Mason 			break;
48860a4eefbbSYan Zheng 		if (found_key.type == type)
48870a4eefbbSYan Zheng 			return 0;
4888e02119d5SChris Mason 		if (found_key.objectid == min_objectid &&
4889e02119d5SChris Mason 		    found_key.type < type)
4890e02119d5SChris Mason 			break;
48910b86a832SChris Mason 	}
48920b86a832SChris Mason 	return 1;
48930b86a832SChris Mason }
4894ade2e0b3SWang Shilong 
4895ade2e0b3SWang Shilong /*
4896ade2e0b3SWang Shilong  * search in extent tree to find a previous Metadata/Data extent item with
4897ade2e0b3SWang Shilong  * min objecitd.
4898ade2e0b3SWang Shilong  *
4899ade2e0b3SWang Shilong  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4900ade2e0b3SWang Shilong  */
4901ade2e0b3SWang Shilong int btrfs_previous_extent_item(struct btrfs_root *root,
4902ade2e0b3SWang Shilong 			struct btrfs_path *path, u64 min_objectid)
4903ade2e0b3SWang Shilong {
4904ade2e0b3SWang Shilong 	struct btrfs_key found_key;
4905ade2e0b3SWang Shilong 	struct extent_buffer *leaf;
4906ade2e0b3SWang Shilong 	u32 nritems;
4907ade2e0b3SWang Shilong 	int ret;
4908ade2e0b3SWang Shilong 
4909ade2e0b3SWang Shilong 	while (1) {
4910ade2e0b3SWang Shilong 		if (path->slots[0] == 0) {
4911ade2e0b3SWang Shilong 			ret = btrfs_prev_leaf(root, path);
4912ade2e0b3SWang Shilong 			if (ret != 0)
4913ade2e0b3SWang Shilong 				return ret;
4914ade2e0b3SWang Shilong 		} else {
4915ade2e0b3SWang Shilong 			path->slots[0]--;
4916ade2e0b3SWang Shilong 		}
4917ade2e0b3SWang Shilong 		leaf = path->nodes[0];
4918ade2e0b3SWang Shilong 		nritems = btrfs_header_nritems(leaf);
4919ade2e0b3SWang Shilong 		if (nritems == 0)
4920ade2e0b3SWang Shilong 			return 1;
4921ade2e0b3SWang Shilong 		if (path->slots[0] == nritems)
4922ade2e0b3SWang Shilong 			path->slots[0]--;
4923ade2e0b3SWang Shilong 
4924ade2e0b3SWang Shilong 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4925ade2e0b3SWang Shilong 		if (found_key.objectid < min_objectid)
4926ade2e0b3SWang Shilong 			break;
4927ade2e0b3SWang Shilong 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4928ade2e0b3SWang Shilong 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
4929ade2e0b3SWang Shilong 			return 0;
4930ade2e0b3SWang Shilong 		if (found_key.objectid == min_objectid &&
4931ade2e0b3SWang Shilong 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
4932ade2e0b3SWang Shilong 			break;
4933ade2e0b3SWang Shilong 	}
4934ade2e0b3SWang Shilong 	return 1;
4935ade2e0b3SWang Shilong }
4936