xref: /linux/fs/btrfs/ctree.c (revision 122333d6bd229af279cdb35d1b874b71b3b9ccfb)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/sched.h>
7 #include <linux/slab.h>
8 #include <linux/rbtree.h>
9 #include <linux/mm.h>
10 #include <linux/error-injection.h>
11 #include "messages.h"
12 #include "ctree.h"
13 #include "disk-io.h"
14 #include "transaction.h"
15 #include "print-tree.h"
16 #include "locking.h"
17 #include "volumes.h"
18 #include "qgroup.h"
19 #include "tree-mod-log.h"
20 #include "tree-checker.h"
21 #include "fs.h"
22 #include "accessors.h"
23 #include "extent-tree.h"
24 #include "relocation.h"
25 #include "file-item.h"
26 
27 static struct kmem_cache *btrfs_path_cachep;
28 
29 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
30 		      *root, struct btrfs_path *path, int level);
31 static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
32 		      const struct btrfs_key *ins_key, struct btrfs_path *path,
33 		      int data_size, int extend);
34 static int push_node_left(struct btrfs_trans_handle *trans,
35 			  struct extent_buffer *dst,
36 			  struct extent_buffer *src, int empty);
37 static int balance_node_right(struct btrfs_trans_handle *trans,
38 			      struct extent_buffer *dst_buf,
39 			      struct extent_buffer *src_buf);
40 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
41 		    int level, int slot);
42 
43 static const struct btrfs_csums {
44 	u16		size;
45 	const char	name[10];
46 	const char	driver[12];
47 } btrfs_csums[] = {
48 	[BTRFS_CSUM_TYPE_CRC32] = { .size = 4, .name = "crc32c" },
49 	[BTRFS_CSUM_TYPE_XXHASH] = { .size = 8, .name = "xxhash64" },
50 	[BTRFS_CSUM_TYPE_SHA256] = { .size = 32, .name = "sha256" },
51 	[BTRFS_CSUM_TYPE_BLAKE2] = { .size = 32, .name = "blake2b",
52 				     .driver = "blake2b-256" },
53 };
54 
55 /*
56  * The leaf data grows from end-to-front in the node.  this returns the address
57  * of the start of the last item, which is the stop of the leaf data stack.
58  */
59 static unsigned int leaf_data_end(const struct extent_buffer *leaf)
60 {
61 	u32 nr = btrfs_header_nritems(leaf);
62 
63 	if (nr == 0)
64 		return BTRFS_LEAF_DATA_SIZE(leaf->fs_info);
65 	return btrfs_item_offset(leaf, nr - 1);
66 }
67 
68 /*
69  * Move data in a @leaf (using memmove, safe for overlapping ranges).
70  *
71  * @leaf:	leaf that we're doing a memmove on
72  * @dst_offset:	item data offset we're moving to
73  * @src_offset:	item data offset were' moving from
74  * @len:	length of the data we're moving
75  *
76  * Wrapper around memmove_extent_buffer() that takes into account the header on
77  * the leaf.  The btrfs_item offset's start directly after the header, so we
78  * have to adjust any offsets to account for the header in the leaf.  This
79  * handles that math to simplify the callers.
80  */
81 static inline void memmove_leaf_data(const struct extent_buffer *leaf,
82 				     unsigned long dst_offset,
83 				     unsigned long src_offset,
84 				     unsigned long len)
85 {
86 	memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, 0) + dst_offset,
87 			      btrfs_item_nr_offset(leaf, 0) + src_offset, len);
88 }
89 
90 /*
91  * Copy item data from @src into @dst at the given @offset.
92  *
93  * @dst:	destination leaf that we're copying into
94  * @src:	source leaf that we're copying from
95  * @dst_offset:	item data offset we're copying to
96  * @src_offset:	item data offset were' copying from
97  * @len:	length of the data we're copying
98  *
99  * Wrapper around copy_extent_buffer() that takes into account the header on
100  * the leaf.  The btrfs_item offset's start directly after the header, so we
101  * have to adjust any offsets to account for the header in the leaf.  This
102  * handles that math to simplify the callers.
103  */
104 static inline void copy_leaf_data(const struct extent_buffer *dst,
105 				  const struct extent_buffer *src,
106 				  unsigned long dst_offset,
107 				  unsigned long src_offset, unsigned long len)
108 {
109 	copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, 0) + dst_offset,
110 			   btrfs_item_nr_offset(src, 0) + src_offset, len);
111 }
112 
113 /*
114  * Move items in a @leaf (using memmove).
115  *
116  * @dst:	destination leaf for the items
117  * @dst_item:	the item nr we're copying into
118  * @src_item:	the item nr we're copying from
119  * @nr_items:	the number of items to copy
120  *
121  * Wrapper around memmove_extent_buffer() that does the math to get the
122  * appropriate offsets into the leaf from the item numbers.
123  */
124 static inline void memmove_leaf_items(const struct extent_buffer *leaf,
125 				      int dst_item, int src_item, int nr_items)
126 {
127 	memmove_extent_buffer(leaf, btrfs_item_nr_offset(leaf, dst_item),
128 			      btrfs_item_nr_offset(leaf, src_item),
129 			      nr_items * sizeof(struct btrfs_item));
130 }
131 
132 /*
133  * Copy items from @src into @dst at the given @offset.
134  *
135  * @dst:	destination leaf for the items
136  * @src:	source leaf for the items
137  * @dst_item:	the item nr we're copying into
138  * @src_item:	the item nr we're copying from
139  * @nr_items:	the number of items to copy
140  *
141  * Wrapper around copy_extent_buffer() that does the math to get the
142  * appropriate offsets into the leaf from the item numbers.
143  */
144 static inline void copy_leaf_items(const struct extent_buffer *dst,
145 				   const struct extent_buffer *src,
146 				   int dst_item, int src_item, int nr_items)
147 {
148 	copy_extent_buffer(dst, src, btrfs_item_nr_offset(dst, dst_item),
149 			      btrfs_item_nr_offset(src, src_item),
150 			      nr_items * sizeof(struct btrfs_item));
151 }
152 
153 int btrfs_super_csum_size(const struct btrfs_super_block *s)
154 {
155 	u16 t = btrfs_super_csum_type(s);
156 	/*
157 	 * csum type is validated at mount time
158 	 */
159 	return btrfs_csums[t].size;
160 }
161 
162 const char *btrfs_super_csum_name(u16 csum_type)
163 {
164 	/* csum type is validated at mount time */
165 	return btrfs_csums[csum_type].name;
166 }
167 
168 /*
169  * Return driver name if defined, otherwise the name that's also a valid driver
170  * name
171  */
172 const char *btrfs_super_csum_driver(u16 csum_type)
173 {
174 	/* csum type is validated at mount time */
175 	return btrfs_csums[csum_type].driver[0] ?
176 		btrfs_csums[csum_type].driver :
177 		btrfs_csums[csum_type].name;
178 }
179 
180 size_t __attribute_const__ btrfs_get_num_csums(void)
181 {
182 	return ARRAY_SIZE(btrfs_csums);
183 }
184 
185 struct btrfs_path *btrfs_alloc_path(void)
186 {
187 	might_sleep();
188 
189 	return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
190 }
191 
192 /* this also releases the path */
193 void btrfs_free_path(struct btrfs_path *p)
194 {
195 	if (!p)
196 		return;
197 	btrfs_release_path(p);
198 	kmem_cache_free(btrfs_path_cachep, p);
199 }
200 
201 /*
202  * path release drops references on the extent buffers in the path
203  * and it drops any locks held by this path
204  *
205  * It is safe to call this on paths that no locks or extent buffers held.
206  */
207 noinline void btrfs_release_path(struct btrfs_path *p)
208 {
209 	int i;
210 
211 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
212 		p->slots[i] = 0;
213 		if (!p->nodes[i])
214 			continue;
215 		if (p->locks[i]) {
216 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
217 			p->locks[i] = 0;
218 		}
219 		free_extent_buffer(p->nodes[i]);
220 		p->nodes[i] = NULL;
221 	}
222 }
223 
224 /*
225  * We want the transaction abort to print stack trace only for errors where the
226  * cause could be a bug, eg. due to ENOSPC, and not for common errors that are
227  * caused by external factors.
228  */
229 bool __cold abort_should_print_stack(int errno)
230 {
231 	switch (errno) {
232 	case -EIO:
233 	case -EROFS:
234 	case -ENOMEM:
235 		return false;
236 	}
237 	return true;
238 }
239 
240 /*
241  * safely gets a reference on the root node of a tree.  A lock
242  * is not taken, so a concurrent writer may put a different node
243  * at the root of the tree.  See btrfs_lock_root_node for the
244  * looping required.
245  *
246  * The extent buffer returned by this has a reference taken, so
247  * it won't disappear.  It may stop being the root of the tree
248  * at any time because there are no locks held.
249  */
250 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
251 {
252 	struct extent_buffer *eb;
253 
254 	while (1) {
255 		rcu_read_lock();
256 		eb = rcu_dereference(root->node);
257 
258 		/*
259 		 * RCU really hurts here, we could free up the root node because
260 		 * it was COWed but we may not get the new root node yet so do
261 		 * the inc_not_zero dance and if it doesn't work then
262 		 * synchronize_rcu and try again.
263 		 */
264 		if (atomic_inc_not_zero(&eb->refs)) {
265 			rcu_read_unlock();
266 			break;
267 		}
268 		rcu_read_unlock();
269 		synchronize_rcu();
270 	}
271 	return eb;
272 }
273 
274 /*
275  * Cowonly root (not-shareable trees, everything not subvolume or reloc roots),
276  * just get put onto a simple dirty list.  Transaction walks this list to make
277  * sure they get properly updated on disk.
278  */
279 static void add_root_to_dirty_list(struct btrfs_root *root)
280 {
281 	struct btrfs_fs_info *fs_info = root->fs_info;
282 
283 	if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
284 	    !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
285 		return;
286 
287 	spin_lock(&fs_info->trans_lock);
288 	if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
289 		/* Want the extent tree to be the last on the list */
290 		if (root->root_key.objectid == BTRFS_EXTENT_TREE_OBJECTID)
291 			list_move_tail(&root->dirty_list,
292 				       &fs_info->dirty_cowonly_roots);
293 		else
294 			list_move(&root->dirty_list,
295 				  &fs_info->dirty_cowonly_roots);
296 	}
297 	spin_unlock(&fs_info->trans_lock);
298 }
299 
300 /*
301  * used by snapshot creation to make a copy of a root for a tree with
302  * a given objectid.  The buffer with the new root node is returned in
303  * cow_ret, and this func returns zero on success or a negative error code.
304  */
305 int btrfs_copy_root(struct btrfs_trans_handle *trans,
306 		      struct btrfs_root *root,
307 		      struct extent_buffer *buf,
308 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
309 {
310 	struct btrfs_fs_info *fs_info = root->fs_info;
311 	struct extent_buffer *cow;
312 	int ret = 0;
313 	int level;
314 	struct btrfs_disk_key disk_key;
315 
316 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
317 		trans->transid != fs_info->running_transaction->transid);
318 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
319 		trans->transid != root->last_trans);
320 
321 	level = btrfs_header_level(buf);
322 	if (level == 0)
323 		btrfs_item_key(buf, &disk_key, 0);
324 	else
325 		btrfs_node_key(buf, &disk_key, 0);
326 
327 	cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
328 				     &disk_key, level, buf->start, 0,
329 				     BTRFS_NESTING_NEW_ROOT);
330 	if (IS_ERR(cow))
331 		return PTR_ERR(cow);
332 
333 	copy_extent_buffer_full(cow, buf);
334 	btrfs_set_header_bytenr(cow, cow->start);
335 	btrfs_set_header_generation(cow, trans->transid);
336 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
337 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
338 				     BTRFS_HEADER_FLAG_RELOC);
339 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
340 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
341 	else
342 		btrfs_set_header_owner(cow, new_root_objectid);
343 
344 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
345 
346 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
347 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
348 		ret = btrfs_inc_ref(trans, root, cow, 1);
349 	else
350 		ret = btrfs_inc_ref(trans, root, cow, 0);
351 	if (ret) {
352 		btrfs_tree_unlock(cow);
353 		free_extent_buffer(cow);
354 		btrfs_abort_transaction(trans, ret);
355 		return ret;
356 	}
357 
358 	btrfs_mark_buffer_dirty(cow);
359 	*cow_ret = cow;
360 	return 0;
361 }
362 
363 /*
364  * check if the tree block can be shared by multiple trees
365  */
366 int btrfs_block_can_be_shared(struct btrfs_root *root,
367 			      struct extent_buffer *buf)
368 {
369 	/*
370 	 * Tree blocks not in shareable trees and tree roots are never shared.
371 	 * If a block was allocated after the last snapshot and the block was
372 	 * not allocated by tree relocation, we know the block is not shared.
373 	 */
374 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
375 	    buf != root->node && buf != root->commit_root &&
376 	    (btrfs_header_generation(buf) <=
377 	     btrfs_root_last_snapshot(&root->root_item) ||
378 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
379 		return 1;
380 
381 	return 0;
382 }
383 
384 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
385 				       struct btrfs_root *root,
386 				       struct extent_buffer *buf,
387 				       struct extent_buffer *cow,
388 				       int *last_ref)
389 {
390 	struct btrfs_fs_info *fs_info = root->fs_info;
391 	u64 refs;
392 	u64 owner;
393 	u64 flags;
394 	u64 new_flags = 0;
395 	int ret;
396 
397 	/*
398 	 * Backrefs update rules:
399 	 *
400 	 * Always use full backrefs for extent pointers in tree block
401 	 * allocated by tree relocation.
402 	 *
403 	 * If a shared tree block is no longer referenced by its owner
404 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
405 	 * use full backrefs for extent pointers in tree block.
406 	 *
407 	 * If a tree block is been relocating
408 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
409 	 * use full backrefs for extent pointers in tree block.
410 	 * The reason for this is some operations (such as drop tree)
411 	 * are only allowed for blocks use full backrefs.
412 	 */
413 
414 	if (btrfs_block_can_be_shared(root, buf)) {
415 		ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
416 					       btrfs_header_level(buf), 1,
417 					       &refs, &flags);
418 		if (ret)
419 			return ret;
420 		if (refs == 0) {
421 			ret = -EROFS;
422 			btrfs_handle_fs_error(fs_info, ret, NULL);
423 			return ret;
424 		}
425 	} else {
426 		refs = 1;
427 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
428 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
429 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
430 		else
431 			flags = 0;
432 	}
433 
434 	owner = btrfs_header_owner(buf);
435 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
436 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
437 
438 	if (refs > 1) {
439 		if ((owner == root->root_key.objectid ||
440 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
441 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
442 			ret = btrfs_inc_ref(trans, root, buf, 1);
443 			if (ret)
444 				return ret;
445 
446 			if (root->root_key.objectid ==
447 			    BTRFS_TREE_RELOC_OBJECTID) {
448 				ret = btrfs_dec_ref(trans, root, buf, 0);
449 				if (ret)
450 					return ret;
451 				ret = btrfs_inc_ref(trans, root, cow, 1);
452 				if (ret)
453 					return ret;
454 			}
455 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
456 		} else {
457 
458 			if (root->root_key.objectid ==
459 			    BTRFS_TREE_RELOC_OBJECTID)
460 				ret = btrfs_inc_ref(trans, root, cow, 1);
461 			else
462 				ret = btrfs_inc_ref(trans, root, cow, 0);
463 			if (ret)
464 				return ret;
465 		}
466 		if (new_flags != 0) {
467 			int level = btrfs_header_level(buf);
468 
469 			ret = btrfs_set_disk_extent_flags(trans, buf,
470 							  new_flags, level);
471 			if (ret)
472 				return ret;
473 		}
474 	} else {
475 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
476 			if (root->root_key.objectid ==
477 			    BTRFS_TREE_RELOC_OBJECTID)
478 				ret = btrfs_inc_ref(trans, root, cow, 1);
479 			else
480 				ret = btrfs_inc_ref(trans, root, cow, 0);
481 			if (ret)
482 				return ret;
483 			ret = btrfs_dec_ref(trans, root, buf, 1);
484 			if (ret)
485 				return ret;
486 		}
487 		btrfs_clear_buffer_dirty(trans, buf);
488 		*last_ref = 1;
489 	}
490 	return 0;
491 }
492 
493 /*
494  * does the dirty work in cow of a single block.  The parent block (if
495  * supplied) is updated to point to the new cow copy.  The new buffer is marked
496  * dirty and returned locked.  If you modify the block it needs to be marked
497  * dirty again.
498  *
499  * search_start -- an allocation hint for the new block
500  *
501  * empty_size -- a hint that you plan on doing more cow.  This is the size in
502  * bytes the allocator should try to find free next to the block it returns.
503  * This is just a hint and may be ignored by the allocator.
504  */
505 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
506 			     struct btrfs_root *root,
507 			     struct extent_buffer *buf,
508 			     struct extent_buffer *parent, int parent_slot,
509 			     struct extent_buffer **cow_ret,
510 			     u64 search_start, u64 empty_size,
511 			     enum btrfs_lock_nesting nest)
512 {
513 	struct btrfs_fs_info *fs_info = root->fs_info;
514 	struct btrfs_disk_key disk_key;
515 	struct extent_buffer *cow;
516 	int level, ret;
517 	int last_ref = 0;
518 	int unlock_orig = 0;
519 	u64 parent_start = 0;
520 
521 	if (*cow_ret == buf)
522 		unlock_orig = 1;
523 
524 	btrfs_assert_tree_write_locked(buf);
525 
526 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
527 		trans->transid != fs_info->running_transaction->transid);
528 	WARN_ON(test_bit(BTRFS_ROOT_SHAREABLE, &root->state) &&
529 		trans->transid != root->last_trans);
530 
531 	level = btrfs_header_level(buf);
532 
533 	if (level == 0)
534 		btrfs_item_key(buf, &disk_key, 0);
535 	else
536 		btrfs_node_key(buf, &disk_key, 0);
537 
538 	if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
539 		parent_start = parent->start;
540 
541 	cow = btrfs_alloc_tree_block(trans, root, parent_start,
542 				     root->root_key.objectid, &disk_key, level,
543 				     search_start, empty_size, nest);
544 	if (IS_ERR(cow))
545 		return PTR_ERR(cow);
546 
547 	/* cow is set to blocking by btrfs_init_new_buffer */
548 
549 	copy_extent_buffer_full(cow, buf);
550 	btrfs_set_header_bytenr(cow, cow->start);
551 	btrfs_set_header_generation(cow, trans->transid);
552 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
553 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
554 				     BTRFS_HEADER_FLAG_RELOC);
555 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
556 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
557 	else
558 		btrfs_set_header_owner(cow, root->root_key.objectid);
559 
560 	write_extent_buffer_fsid(cow, fs_info->fs_devices->metadata_uuid);
561 
562 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
563 	if (ret) {
564 		btrfs_tree_unlock(cow);
565 		free_extent_buffer(cow);
566 		btrfs_abort_transaction(trans, ret);
567 		return ret;
568 	}
569 
570 	if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
571 		ret = btrfs_reloc_cow_block(trans, root, buf, cow);
572 		if (ret) {
573 			btrfs_tree_unlock(cow);
574 			free_extent_buffer(cow);
575 			btrfs_abort_transaction(trans, ret);
576 			return ret;
577 		}
578 	}
579 
580 	if (buf == root->node) {
581 		WARN_ON(parent && parent != buf);
582 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
583 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
584 			parent_start = buf->start;
585 
586 		atomic_inc(&cow->refs);
587 		ret = btrfs_tree_mod_log_insert_root(root->node, cow, true);
588 		BUG_ON(ret < 0);
589 		rcu_assign_pointer(root->node, cow);
590 
591 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
592 				      parent_start, last_ref);
593 		free_extent_buffer(buf);
594 		add_root_to_dirty_list(root);
595 	} else {
596 		WARN_ON(trans->transid != btrfs_header_generation(parent));
597 		btrfs_tree_mod_log_insert_key(parent, parent_slot,
598 					      BTRFS_MOD_LOG_KEY_REPLACE);
599 		btrfs_set_node_blockptr(parent, parent_slot,
600 					cow->start);
601 		btrfs_set_node_ptr_generation(parent, parent_slot,
602 					      trans->transid);
603 		btrfs_mark_buffer_dirty(parent);
604 		if (last_ref) {
605 			ret = btrfs_tree_mod_log_free_eb(buf);
606 			if (ret) {
607 				btrfs_tree_unlock(cow);
608 				free_extent_buffer(cow);
609 				btrfs_abort_transaction(trans, ret);
610 				return ret;
611 			}
612 		}
613 		btrfs_free_tree_block(trans, btrfs_root_id(root), buf,
614 				      parent_start, last_ref);
615 	}
616 	if (unlock_orig)
617 		btrfs_tree_unlock(buf);
618 	free_extent_buffer_stale(buf);
619 	btrfs_mark_buffer_dirty(cow);
620 	*cow_ret = cow;
621 	return 0;
622 }
623 
624 static inline int should_cow_block(struct btrfs_trans_handle *trans,
625 				   struct btrfs_root *root,
626 				   struct extent_buffer *buf)
627 {
628 	if (btrfs_is_testing(root->fs_info))
629 		return 0;
630 
631 	/* Ensure we can see the FORCE_COW bit */
632 	smp_mb__before_atomic();
633 
634 	/*
635 	 * We do not need to cow a block if
636 	 * 1) this block is not created or changed in this transaction;
637 	 * 2) this block does not belong to TREE_RELOC tree;
638 	 * 3) the root is not forced COW.
639 	 *
640 	 * What is forced COW:
641 	 *    when we create snapshot during committing the transaction,
642 	 *    after we've finished copying src root, we must COW the shared
643 	 *    block to ensure the metadata consistency.
644 	 */
645 	if (btrfs_header_generation(buf) == trans->transid &&
646 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
647 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
648 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
649 	    !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
650 		return 0;
651 	return 1;
652 }
653 
654 /*
655  * cows a single block, see __btrfs_cow_block for the real work.
656  * This version of it has extra checks so that a block isn't COWed more than
657  * once per transaction, as long as it hasn't been written yet
658  */
659 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
660 		    struct btrfs_root *root, struct extent_buffer *buf,
661 		    struct extent_buffer *parent, int parent_slot,
662 		    struct extent_buffer **cow_ret,
663 		    enum btrfs_lock_nesting nest)
664 {
665 	struct btrfs_fs_info *fs_info = root->fs_info;
666 	u64 search_start;
667 	int ret;
668 
669 	if (test_bit(BTRFS_ROOT_DELETING, &root->state))
670 		btrfs_err(fs_info,
671 			"COW'ing blocks on a fs root that's being dropped");
672 
673 	if (trans->transaction != fs_info->running_transaction)
674 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
675 		       trans->transid,
676 		       fs_info->running_transaction->transid);
677 
678 	if (trans->transid != fs_info->generation)
679 		WARN(1, KERN_CRIT "trans %llu running %llu\n",
680 		       trans->transid, fs_info->generation);
681 
682 	if (!should_cow_block(trans, root, buf)) {
683 		*cow_ret = buf;
684 		return 0;
685 	}
686 
687 	search_start = buf->start & ~((u64)SZ_1G - 1);
688 
689 	/*
690 	 * Before CoWing this block for later modification, check if it's
691 	 * the subtree root and do the delayed subtree trace if needed.
692 	 *
693 	 * Also We don't care about the error, as it's handled internally.
694 	 */
695 	btrfs_qgroup_trace_subtree_after_cow(trans, root, buf);
696 	ret = __btrfs_cow_block(trans, root, buf, parent,
697 				 parent_slot, cow_ret, search_start, 0, nest);
698 
699 	trace_btrfs_cow_block(root, buf, *cow_ret);
700 
701 	return ret;
702 }
703 ALLOW_ERROR_INJECTION(btrfs_cow_block, ERRNO);
704 
705 /*
706  * helper function for defrag to decide if two blocks pointed to by a
707  * node are actually close by
708  */
709 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
710 {
711 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
712 		return 1;
713 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
714 		return 1;
715 	return 0;
716 }
717 
718 #ifdef __LITTLE_ENDIAN
719 
720 /*
721  * Compare two keys, on little-endian the disk order is same as CPU order and
722  * we can avoid the conversion.
723  */
724 static int comp_keys(const struct btrfs_disk_key *disk_key,
725 		     const struct btrfs_key *k2)
726 {
727 	const struct btrfs_key *k1 = (const struct btrfs_key *)disk_key;
728 
729 	return btrfs_comp_cpu_keys(k1, k2);
730 }
731 
732 #else
733 
734 /*
735  * compare two keys in a memcmp fashion
736  */
737 static int comp_keys(const struct btrfs_disk_key *disk,
738 		     const struct btrfs_key *k2)
739 {
740 	struct btrfs_key k1;
741 
742 	btrfs_disk_key_to_cpu(&k1, disk);
743 
744 	return btrfs_comp_cpu_keys(&k1, k2);
745 }
746 #endif
747 
748 /*
749  * same as comp_keys only with two btrfs_key's
750  */
751 int __pure btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
752 {
753 	if (k1->objectid > k2->objectid)
754 		return 1;
755 	if (k1->objectid < k2->objectid)
756 		return -1;
757 	if (k1->type > k2->type)
758 		return 1;
759 	if (k1->type < k2->type)
760 		return -1;
761 	if (k1->offset > k2->offset)
762 		return 1;
763 	if (k1->offset < k2->offset)
764 		return -1;
765 	return 0;
766 }
767 
768 /*
769  * this is used by the defrag code to go through all the
770  * leaves pointed to by a node and reallocate them so that
771  * disk order is close to key order
772  */
773 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
774 		       struct btrfs_root *root, struct extent_buffer *parent,
775 		       int start_slot, u64 *last_ret,
776 		       struct btrfs_key *progress)
777 {
778 	struct btrfs_fs_info *fs_info = root->fs_info;
779 	struct extent_buffer *cur;
780 	u64 blocknr;
781 	u64 search_start = *last_ret;
782 	u64 last_block = 0;
783 	u64 other;
784 	u32 parent_nritems;
785 	int end_slot;
786 	int i;
787 	int err = 0;
788 	u32 blocksize;
789 	int progress_passed = 0;
790 	struct btrfs_disk_key disk_key;
791 
792 	WARN_ON(trans->transaction != fs_info->running_transaction);
793 	WARN_ON(trans->transid != fs_info->generation);
794 
795 	parent_nritems = btrfs_header_nritems(parent);
796 	blocksize = fs_info->nodesize;
797 	end_slot = parent_nritems - 1;
798 
799 	if (parent_nritems <= 1)
800 		return 0;
801 
802 	for (i = start_slot; i <= end_slot; i++) {
803 		int close = 1;
804 
805 		btrfs_node_key(parent, &disk_key, i);
806 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
807 			continue;
808 
809 		progress_passed = 1;
810 		blocknr = btrfs_node_blockptr(parent, i);
811 		if (last_block == 0)
812 			last_block = blocknr;
813 
814 		if (i > 0) {
815 			other = btrfs_node_blockptr(parent, i - 1);
816 			close = close_blocks(blocknr, other, blocksize);
817 		}
818 		if (!close && i < end_slot) {
819 			other = btrfs_node_blockptr(parent, i + 1);
820 			close = close_blocks(blocknr, other, blocksize);
821 		}
822 		if (close) {
823 			last_block = blocknr;
824 			continue;
825 		}
826 
827 		cur = btrfs_read_node_slot(parent, i);
828 		if (IS_ERR(cur))
829 			return PTR_ERR(cur);
830 		if (search_start == 0)
831 			search_start = last_block;
832 
833 		btrfs_tree_lock(cur);
834 		err = __btrfs_cow_block(trans, root, cur, parent, i,
835 					&cur, search_start,
836 					min(16 * blocksize,
837 					    (end_slot - i) * blocksize),
838 					BTRFS_NESTING_COW);
839 		if (err) {
840 			btrfs_tree_unlock(cur);
841 			free_extent_buffer(cur);
842 			break;
843 		}
844 		search_start = cur->start;
845 		last_block = cur->start;
846 		*last_ret = search_start;
847 		btrfs_tree_unlock(cur);
848 		free_extent_buffer(cur);
849 	}
850 	return err;
851 }
852 
853 /*
854  * Search for a key in the given extent_buffer.
855  *
856  * The lower boundary for the search is specified by the slot number @first_slot.
857  * Use a value of 0 to search over the whole extent buffer. Works for both
858  * leaves and nodes.
859  *
860  * The slot in the extent buffer is returned via @slot. If the key exists in the
861  * extent buffer, then @slot will point to the slot where the key is, otherwise
862  * it points to the slot where you would insert the key.
863  *
864  * Slot may point to the total number of items (i.e. one position beyond the last
865  * key) if the key is bigger than the last key in the extent buffer.
866  */
867 int btrfs_bin_search(struct extent_buffer *eb, int first_slot,
868 		     const struct btrfs_key *key, int *slot)
869 {
870 	unsigned long p;
871 	int item_size;
872 	/*
873 	 * Use unsigned types for the low and high slots, so that we get a more
874 	 * efficient division in the search loop below.
875 	 */
876 	u32 low = first_slot;
877 	u32 high = btrfs_header_nritems(eb);
878 	int ret;
879 	const int key_size = sizeof(struct btrfs_disk_key);
880 
881 	if (unlikely(low > high)) {
882 		btrfs_err(eb->fs_info,
883 		 "%s: low (%u) > high (%u) eb %llu owner %llu level %d",
884 			  __func__, low, high, eb->start,
885 			  btrfs_header_owner(eb), btrfs_header_level(eb));
886 		return -EINVAL;
887 	}
888 
889 	if (btrfs_header_level(eb) == 0) {
890 		p = offsetof(struct btrfs_leaf, items);
891 		item_size = sizeof(struct btrfs_item);
892 	} else {
893 		p = offsetof(struct btrfs_node, ptrs);
894 		item_size = sizeof(struct btrfs_key_ptr);
895 	}
896 
897 	while (low < high) {
898 		unsigned long oip;
899 		unsigned long offset;
900 		struct btrfs_disk_key *tmp;
901 		struct btrfs_disk_key unaligned;
902 		int mid;
903 
904 		mid = (low + high) / 2;
905 		offset = p + mid * item_size;
906 		oip = offset_in_page(offset);
907 
908 		if (oip + key_size <= PAGE_SIZE) {
909 			const unsigned long idx = get_eb_page_index(offset);
910 			char *kaddr = page_address(eb->pages[idx]);
911 
912 			oip = get_eb_offset_in_page(eb, offset);
913 			tmp = (struct btrfs_disk_key *)(kaddr + oip);
914 		} else {
915 			read_extent_buffer(eb, &unaligned, offset, key_size);
916 			tmp = &unaligned;
917 		}
918 
919 		ret = comp_keys(tmp, key);
920 
921 		if (ret < 0)
922 			low = mid + 1;
923 		else if (ret > 0)
924 			high = mid;
925 		else {
926 			*slot = mid;
927 			return 0;
928 		}
929 	}
930 	*slot = low;
931 	return 1;
932 }
933 
934 static void root_add_used(struct btrfs_root *root, u32 size)
935 {
936 	spin_lock(&root->accounting_lock);
937 	btrfs_set_root_used(&root->root_item,
938 			    btrfs_root_used(&root->root_item) + size);
939 	spin_unlock(&root->accounting_lock);
940 }
941 
942 static void root_sub_used(struct btrfs_root *root, u32 size)
943 {
944 	spin_lock(&root->accounting_lock);
945 	btrfs_set_root_used(&root->root_item,
946 			    btrfs_root_used(&root->root_item) - size);
947 	spin_unlock(&root->accounting_lock);
948 }
949 
950 /* given a node and slot number, this reads the blocks it points to.  The
951  * extent buffer is returned with a reference taken (but unlocked).
952  */
953 struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
954 					   int slot)
955 {
956 	int level = btrfs_header_level(parent);
957 	struct btrfs_tree_parent_check check = { 0 };
958 	struct extent_buffer *eb;
959 
960 	if (slot < 0 || slot >= btrfs_header_nritems(parent))
961 		return ERR_PTR(-ENOENT);
962 
963 	ASSERT(level);
964 
965 	check.level = level - 1;
966 	check.transid = btrfs_node_ptr_generation(parent, slot);
967 	check.owner_root = btrfs_header_owner(parent);
968 	check.has_first_key = true;
969 	btrfs_node_key_to_cpu(parent, &check.first_key, slot);
970 
971 	eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
972 			     &check);
973 	if (IS_ERR(eb))
974 		return eb;
975 	if (!extent_buffer_uptodate(eb)) {
976 		free_extent_buffer(eb);
977 		return ERR_PTR(-EIO);
978 	}
979 
980 	return eb;
981 }
982 
983 /*
984  * node level balancing, used to make sure nodes are in proper order for
985  * item deletion.  We balance from the top down, so we have to make sure
986  * that a deletion won't leave an node completely empty later on.
987  */
988 static noinline int balance_level(struct btrfs_trans_handle *trans,
989 			 struct btrfs_root *root,
990 			 struct btrfs_path *path, int level)
991 {
992 	struct btrfs_fs_info *fs_info = root->fs_info;
993 	struct extent_buffer *right = NULL;
994 	struct extent_buffer *mid;
995 	struct extent_buffer *left = NULL;
996 	struct extent_buffer *parent = NULL;
997 	int ret = 0;
998 	int wret;
999 	int pslot;
1000 	int orig_slot = path->slots[level];
1001 	u64 orig_ptr;
1002 
1003 	ASSERT(level > 0);
1004 
1005 	mid = path->nodes[level];
1006 
1007 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
1008 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1009 
1010 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
1011 
1012 	if (level < BTRFS_MAX_LEVEL - 1) {
1013 		parent = path->nodes[level + 1];
1014 		pslot = path->slots[level + 1];
1015 	}
1016 
1017 	/*
1018 	 * deal with the case where there is only one pointer in the root
1019 	 * by promoting the node below to a root
1020 	 */
1021 	if (!parent) {
1022 		struct extent_buffer *child;
1023 
1024 		if (btrfs_header_nritems(mid) != 1)
1025 			return 0;
1026 
1027 		/* promote the child to a root */
1028 		child = btrfs_read_node_slot(mid, 0);
1029 		if (IS_ERR(child)) {
1030 			ret = PTR_ERR(child);
1031 			btrfs_handle_fs_error(fs_info, ret, NULL);
1032 			goto enospc;
1033 		}
1034 
1035 		btrfs_tree_lock(child);
1036 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
1037 				      BTRFS_NESTING_COW);
1038 		if (ret) {
1039 			btrfs_tree_unlock(child);
1040 			free_extent_buffer(child);
1041 			goto enospc;
1042 		}
1043 
1044 		ret = btrfs_tree_mod_log_insert_root(root->node, child, true);
1045 		BUG_ON(ret < 0);
1046 		rcu_assign_pointer(root->node, child);
1047 
1048 		add_root_to_dirty_list(root);
1049 		btrfs_tree_unlock(child);
1050 
1051 		path->locks[level] = 0;
1052 		path->nodes[level] = NULL;
1053 		btrfs_clear_buffer_dirty(trans, mid);
1054 		btrfs_tree_unlock(mid);
1055 		/* once for the path */
1056 		free_extent_buffer(mid);
1057 
1058 		root_sub_used(root, mid->len);
1059 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1060 		/* once for the root ptr */
1061 		free_extent_buffer_stale(mid);
1062 		return 0;
1063 	}
1064 	if (btrfs_header_nritems(mid) >
1065 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1066 		return 0;
1067 
1068 	if (pslot) {
1069 		left = btrfs_read_node_slot(parent, pslot - 1);
1070 		if (IS_ERR(left)) {
1071 			ret = PTR_ERR(left);
1072 			left = NULL;
1073 			goto enospc;
1074 		}
1075 
1076 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1077 		wret = btrfs_cow_block(trans, root, left,
1078 				       parent, pslot - 1, &left,
1079 				       BTRFS_NESTING_LEFT_COW);
1080 		if (wret) {
1081 			ret = wret;
1082 			goto enospc;
1083 		}
1084 	}
1085 
1086 	if (pslot + 1 < btrfs_header_nritems(parent)) {
1087 		right = btrfs_read_node_slot(parent, pslot + 1);
1088 		if (IS_ERR(right)) {
1089 			ret = PTR_ERR(right);
1090 			right = NULL;
1091 			goto enospc;
1092 		}
1093 
1094 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1095 		wret = btrfs_cow_block(trans, root, right,
1096 				       parent, pslot + 1, &right,
1097 				       BTRFS_NESTING_RIGHT_COW);
1098 		if (wret) {
1099 			ret = wret;
1100 			goto enospc;
1101 		}
1102 	}
1103 
1104 	/* first, try to make some room in the middle buffer */
1105 	if (left) {
1106 		orig_slot += btrfs_header_nritems(left);
1107 		wret = push_node_left(trans, left, mid, 1);
1108 		if (wret < 0)
1109 			ret = wret;
1110 	}
1111 
1112 	/*
1113 	 * then try to empty the right most buffer into the middle
1114 	 */
1115 	if (right) {
1116 		wret = push_node_left(trans, mid, right, 1);
1117 		if (wret < 0 && wret != -ENOSPC)
1118 			ret = wret;
1119 		if (btrfs_header_nritems(right) == 0) {
1120 			btrfs_clear_buffer_dirty(trans, right);
1121 			btrfs_tree_unlock(right);
1122 			del_ptr(root, path, level + 1, pslot + 1);
1123 			root_sub_used(root, right->len);
1124 			btrfs_free_tree_block(trans, btrfs_root_id(root), right,
1125 					      0, 1);
1126 			free_extent_buffer_stale(right);
1127 			right = NULL;
1128 		} else {
1129 			struct btrfs_disk_key right_key;
1130 			btrfs_node_key(right, &right_key, 0);
1131 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1132 					BTRFS_MOD_LOG_KEY_REPLACE);
1133 			BUG_ON(ret < 0);
1134 			btrfs_set_node_key(parent, &right_key, pslot + 1);
1135 			btrfs_mark_buffer_dirty(parent);
1136 		}
1137 	}
1138 	if (btrfs_header_nritems(mid) == 1) {
1139 		/*
1140 		 * we're not allowed to leave a node with one item in the
1141 		 * tree during a delete.  A deletion from lower in the tree
1142 		 * could try to delete the only pointer in this node.
1143 		 * So, pull some keys from the left.
1144 		 * There has to be a left pointer at this point because
1145 		 * otherwise we would have pulled some pointers from the
1146 		 * right
1147 		 */
1148 		if (!left) {
1149 			ret = -EROFS;
1150 			btrfs_handle_fs_error(fs_info, ret, NULL);
1151 			goto enospc;
1152 		}
1153 		wret = balance_node_right(trans, mid, left);
1154 		if (wret < 0) {
1155 			ret = wret;
1156 			goto enospc;
1157 		}
1158 		if (wret == 1) {
1159 			wret = push_node_left(trans, left, mid, 1);
1160 			if (wret < 0)
1161 				ret = wret;
1162 		}
1163 		BUG_ON(wret == 1);
1164 	}
1165 	if (btrfs_header_nritems(mid) == 0) {
1166 		btrfs_clear_buffer_dirty(trans, mid);
1167 		btrfs_tree_unlock(mid);
1168 		del_ptr(root, path, level + 1, pslot);
1169 		root_sub_used(root, mid->len);
1170 		btrfs_free_tree_block(trans, btrfs_root_id(root), mid, 0, 1);
1171 		free_extent_buffer_stale(mid);
1172 		mid = NULL;
1173 	} else {
1174 		/* update the parent key to reflect our changes */
1175 		struct btrfs_disk_key mid_key;
1176 		btrfs_node_key(mid, &mid_key, 0);
1177 		ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1178 						    BTRFS_MOD_LOG_KEY_REPLACE);
1179 		BUG_ON(ret < 0);
1180 		btrfs_set_node_key(parent, &mid_key, pslot);
1181 		btrfs_mark_buffer_dirty(parent);
1182 	}
1183 
1184 	/* update the path */
1185 	if (left) {
1186 		if (btrfs_header_nritems(left) > orig_slot) {
1187 			atomic_inc(&left->refs);
1188 			/* left was locked after cow */
1189 			path->nodes[level] = left;
1190 			path->slots[level + 1] -= 1;
1191 			path->slots[level] = orig_slot;
1192 			if (mid) {
1193 				btrfs_tree_unlock(mid);
1194 				free_extent_buffer(mid);
1195 			}
1196 		} else {
1197 			orig_slot -= btrfs_header_nritems(left);
1198 			path->slots[level] = orig_slot;
1199 		}
1200 	}
1201 	/* double check we haven't messed things up */
1202 	if (orig_ptr !=
1203 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
1204 		BUG();
1205 enospc:
1206 	if (right) {
1207 		btrfs_tree_unlock(right);
1208 		free_extent_buffer(right);
1209 	}
1210 	if (left) {
1211 		if (path->nodes[level] != left)
1212 			btrfs_tree_unlock(left);
1213 		free_extent_buffer(left);
1214 	}
1215 	return ret;
1216 }
1217 
1218 /* Node balancing for insertion.  Here we only split or push nodes around
1219  * when they are completely full.  This is also done top down, so we
1220  * have to be pessimistic.
1221  */
1222 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1223 					  struct btrfs_root *root,
1224 					  struct btrfs_path *path, int level)
1225 {
1226 	struct btrfs_fs_info *fs_info = root->fs_info;
1227 	struct extent_buffer *right = NULL;
1228 	struct extent_buffer *mid;
1229 	struct extent_buffer *left = NULL;
1230 	struct extent_buffer *parent = NULL;
1231 	int ret = 0;
1232 	int wret;
1233 	int pslot;
1234 	int orig_slot = path->slots[level];
1235 
1236 	if (level == 0)
1237 		return 1;
1238 
1239 	mid = path->nodes[level];
1240 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1241 
1242 	if (level < BTRFS_MAX_LEVEL - 1) {
1243 		parent = path->nodes[level + 1];
1244 		pslot = path->slots[level + 1];
1245 	}
1246 
1247 	if (!parent)
1248 		return 1;
1249 
1250 	/* first, try to make some room in the middle buffer */
1251 	if (pslot) {
1252 		u32 left_nr;
1253 
1254 		left = btrfs_read_node_slot(parent, pslot - 1);
1255 		if (IS_ERR(left))
1256 			return PTR_ERR(left);
1257 
1258 		__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
1259 
1260 		left_nr = btrfs_header_nritems(left);
1261 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
1262 			wret = 1;
1263 		} else {
1264 			ret = btrfs_cow_block(trans, root, left, parent,
1265 					      pslot - 1, &left,
1266 					      BTRFS_NESTING_LEFT_COW);
1267 			if (ret)
1268 				wret = 1;
1269 			else {
1270 				wret = push_node_left(trans, left, mid, 0);
1271 			}
1272 		}
1273 		if (wret < 0)
1274 			ret = wret;
1275 		if (wret == 0) {
1276 			struct btrfs_disk_key disk_key;
1277 			orig_slot += left_nr;
1278 			btrfs_node_key(mid, &disk_key, 0);
1279 			ret = btrfs_tree_mod_log_insert_key(parent, pslot,
1280 					BTRFS_MOD_LOG_KEY_REPLACE);
1281 			BUG_ON(ret < 0);
1282 			btrfs_set_node_key(parent, &disk_key, pslot);
1283 			btrfs_mark_buffer_dirty(parent);
1284 			if (btrfs_header_nritems(left) > orig_slot) {
1285 				path->nodes[level] = left;
1286 				path->slots[level + 1] -= 1;
1287 				path->slots[level] = orig_slot;
1288 				btrfs_tree_unlock(mid);
1289 				free_extent_buffer(mid);
1290 			} else {
1291 				orig_slot -=
1292 					btrfs_header_nritems(left);
1293 				path->slots[level] = orig_slot;
1294 				btrfs_tree_unlock(left);
1295 				free_extent_buffer(left);
1296 			}
1297 			return 0;
1298 		}
1299 		btrfs_tree_unlock(left);
1300 		free_extent_buffer(left);
1301 	}
1302 
1303 	/*
1304 	 * then try to empty the right most buffer into the middle
1305 	 */
1306 	if (pslot + 1 < btrfs_header_nritems(parent)) {
1307 		u32 right_nr;
1308 
1309 		right = btrfs_read_node_slot(parent, pslot + 1);
1310 		if (IS_ERR(right))
1311 			return PTR_ERR(right);
1312 
1313 		__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
1314 
1315 		right_nr = btrfs_header_nritems(right);
1316 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
1317 			wret = 1;
1318 		} else {
1319 			ret = btrfs_cow_block(trans, root, right,
1320 					      parent, pslot + 1,
1321 					      &right, BTRFS_NESTING_RIGHT_COW);
1322 			if (ret)
1323 				wret = 1;
1324 			else {
1325 				wret = balance_node_right(trans, right, mid);
1326 			}
1327 		}
1328 		if (wret < 0)
1329 			ret = wret;
1330 		if (wret == 0) {
1331 			struct btrfs_disk_key disk_key;
1332 
1333 			btrfs_node_key(right, &disk_key, 0);
1334 			ret = btrfs_tree_mod_log_insert_key(parent, pslot + 1,
1335 					BTRFS_MOD_LOG_KEY_REPLACE);
1336 			BUG_ON(ret < 0);
1337 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
1338 			btrfs_mark_buffer_dirty(parent);
1339 
1340 			if (btrfs_header_nritems(mid) <= orig_slot) {
1341 				path->nodes[level] = right;
1342 				path->slots[level + 1] += 1;
1343 				path->slots[level] = orig_slot -
1344 					btrfs_header_nritems(mid);
1345 				btrfs_tree_unlock(mid);
1346 				free_extent_buffer(mid);
1347 			} else {
1348 				btrfs_tree_unlock(right);
1349 				free_extent_buffer(right);
1350 			}
1351 			return 0;
1352 		}
1353 		btrfs_tree_unlock(right);
1354 		free_extent_buffer(right);
1355 	}
1356 	return 1;
1357 }
1358 
1359 /*
1360  * readahead one full node of leaves, finding things that are close
1361  * to the block in 'slot', and triggering ra on them.
1362  */
1363 static void reada_for_search(struct btrfs_fs_info *fs_info,
1364 			     struct btrfs_path *path,
1365 			     int level, int slot, u64 objectid)
1366 {
1367 	struct extent_buffer *node;
1368 	struct btrfs_disk_key disk_key;
1369 	u32 nritems;
1370 	u64 search;
1371 	u64 target;
1372 	u64 nread = 0;
1373 	u64 nread_max;
1374 	u32 nr;
1375 	u32 blocksize;
1376 	u32 nscan = 0;
1377 
1378 	if (level != 1 && path->reada != READA_FORWARD_ALWAYS)
1379 		return;
1380 
1381 	if (!path->nodes[level])
1382 		return;
1383 
1384 	node = path->nodes[level];
1385 
1386 	/*
1387 	 * Since the time between visiting leaves is much shorter than the time
1388 	 * between visiting nodes, limit read ahead of nodes to 1, to avoid too
1389 	 * much IO at once (possibly random).
1390 	 */
1391 	if (path->reada == READA_FORWARD_ALWAYS) {
1392 		if (level > 1)
1393 			nread_max = node->fs_info->nodesize;
1394 		else
1395 			nread_max = SZ_128K;
1396 	} else {
1397 		nread_max = SZ_64K;
1398 	}
1399 
1400 	search = btrfs_node_blockptr(node, slot);
1401 	blocksize = fs_info->nodesize;
1402 	if (path->reada != READA_FORWARD_ALWAYS) {
1403 		struct extent_buffer *eb;
1404 
1405 		eb = find_extent_buffer(fs_info, search);
1406 		if (eb) {
1407 			free_extent_buffer(eb);
1408 			return;
1409 		}
1410 	}
1411 
1412 	target = search;
1413 
1414 	nritems = btrfs_header_nritems(node);
1415 	nr = slot;
1416 
1417 	while (1) {
1418 		if (path->reada == READA_BACK) {
1419 			if (nr == 0)
1420 				break;
1421 			nr--;
1422 		} else if (path->reada == READA_FORWARD ||
1423 			   path->reada == READA_FORWARD_ALWAYS) {
1424 			nr++;
1425 			if (nr >= nritems)
1426 				break;
1427 		}
1428 		if (path->reada == READA_BACK && objectid) {
1429 			btrfs_node_key(node, &disk_key, nr);
1430 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
1431 				break;
1432 		}
1433 		search = btrfs_node_blockptr(node, nr);
1434 		if (path->reada == READA_FORWARD_ALWAYS ||
1435 		    (search <= target && target - search <= 65536) ||
1436 		    (search > target && search - target <= 65536)) {
1437 			btrfs_readahead_node_child(node, nr);
1438 			nread += blocksize;
1439 		}
1440 		nscan++;
1441 		if (nread > nread_max || nscan > 32)
1442 			break;
1443 	}
1444 }
1445 
1446 static noinline void reada_for_balance(struct btrfs_path *path, int level)
1447 {
1448 	struct extent_buffer *parent;
1449 	int slot;
1450 	int nritems;
1451 
1452 	parent = path->nodes[level + 1];
1453 	if (!parent)
1454 		return;
1455 
1456 	nritems = btrfs_header_nritems(parent);
1457 	slot = path->slots[level + 1];
1458 
1459 	if (slot > 0)
1460 		btrfs_readahead_node_child(parent, slot - 1);
1461 	if (slot + 1 < nritems)
1462 		btrfs_readahead_node_child(parent, slot + 1);
1463 }
1464 
1465 
1466 /*
1467  * when we walk down the tree, it is usually safe to unlock the higher layers
1468  * in the tree.  The exceptions are when our path goes through slot 0, because
1469  * operations on the tree might require changing key pointers higher up in the
1470  * tree.
1471  *
1472  * callers might also have set path->keep_locks, which tells this code to keep
1473  * the lock if the path points to the last slot in the block.  This is part of
1474  * walking through the tree, and selecting the next slot in the higher block.
1475  *
1476  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1477  * if lowest_unlock is 1, level 0 won't be unlocked
1478  */
1479 static noinline void unlock_up(struct btrfs_path *path, int level,
1480 			       int lowest_unlock, int min_write_lock_level,
1481 			       int *write_lock_level)
1482 {
1483 	int i;
1484 	int skip_level = level;
1485 	bool check_skip = true;
1486 
1487 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1488 		if (!path->nodes[i])
1489 			break;
1490 		if (!path->locks[i])
1491 			break;
1492 
1493 		if (check_skip) {
1494 			if (path->slots[i] == 0) {
1495 				skip_level = i + 1;
1496 				continue;
1497 			}
1498 
1499 			if (path->keep_locks) {
1500 				u32 nritems;
1501 
1502 				nritems = btrfs_header_nritems(path->nodes[i]);
1503 				if (nritems < 1 || path->slots[i] >= nritems - 1) {
1504 					skip_level = i + 1;
1505 					continue;
1506 				}
1507 			}
1508 		}
1509 
1510 		if (i >= lowest_unlock && i > skip_level) {
1511 			check_skip = false;
1512 			btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1513 			path->locks[i] = 0;
1514 			if (write_lock_level &&
1515 			    i > min_write_lock_level &&
1516 			    i <= *write_lock_level) {
1517 				*write_lock_level = i - 1;
1518 			}
1519 		}
1520 	}
1521 }
1522 
1523 /*
1524  * Helper function for btrfs_search_slot() and other functions that do a search
1525  * on a btree. The goal is to find a tree block in the cache (the radix tree at
1526  * fs_info->buffer_radix), but if we can't find it, or it's not up to date, read
1527  * its pages from disk.
1528  *
1529  * Returns -EAGAIN, with the path unlocked, if the caller needs to repeat the
1530  * whole btree search, starting again from the current root node.
1531  */
1532 static int
1533 read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
1534 		      struct extent_buffer **eb_ret, int level, int slot,
1535 		      const struct btrfs_key *key)
1536 {
1537 	struct btrfs_fs_info *fs_info = root->fs_info;
1538 	struct btrfs_tree_parent_check check = { 0 };
1539 	u64 blocknr;
1540 	u64 gen;
1541 	struct extent_buffer *tmp;
1542 	int ret;
1543 	int parent_level;
1544 	bool unlock_up;
1545 
1546 	unlock_up = ((level + 1 < BTRFS_MAX_LEVEL) && p->locks[level + 1]);
1547 	blocknr = btrfs_node_blockptr(*eb_ret, slot);
1548 	gen = btrfs_node_ptr_generation(*eb_ret, slot);
1549 	parent_level = btrfs_header_level(*eb_ret);
1550 	btrfs_node_key_to_cpu(*eb_ret, &check.first_key, slot);
1551 	check.has_first_key = true;
1552 	check.level = parent_level - 1;
1553 	check.transid = gen;
1554 	check.owner_root = root->root_key.objectid;
1555 
1556 	/*
1557 	 * If we need to read an extent buffer from disk and we are holding locks
1558 	 * on upper level nodes, we unlock all the upper nodes before reading the
1559 	 * extent buffer, and then return -EAGAIN to the caller as it needs to
1560 	 * restart the search. We don't release the lock on the current level
1561 	 * because we need to walk this node to figure out which blocks to read.
1562 	 */
1563 	tmp = find_extent_buffer(fs_info, blocknr);
1564 	if (tmp) {
1565 		if (p->reada == READA_FORWARD_ALWAYS)
1566 			reada_for_search(fs_info, p, level, slot, key->objectid);
1567 
1568 		/* first we do an atomic uptodate check */
1569 		if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1570 			/*
1571 			 * Do extra check for first_key, eb can be stale due to
1572 			 * being cached, read from scrub, or have multiple
1573 			 * parents (shared tree blocks).
1574 			 */
1575 			if (btrfs_verify_level_key(tmp,
1576 					parent_level - 1, &check.first_key, gen)) {
1577 				free_extent_buffer(tmp);
1578 				return -EUCLEAN;
1579 			}
1580 			*eb_ret = tmp;
1581 			return 0;
1582 		}
1583 
1584 		if (p->nowait) {
1585 			free_extent_buffer(tmp);
1586 			return -EAGAIN;
1587 		}
1588 
1589 		if (unlock_up)
1590 			btrfs_unlock_up_safe(p, level + 1);
1591 
1592 		/* now we're allowed to do a blocking uptodate check */
1593 		ret = btrfs_read_extent_buffer(tmp, &check);
1594 		if (ret) {
1595 			free_extent_buffer(tmp);
1596 			btrfs_release_path(p);
1597 			return -EIO;
1598 		}
1599 		if (btrfs_check_eb_owner(tmp, root->root_key.objectid)) {
1600 			free_extent_buffer(tmp);
1601 			btrfs_release_path(p);
1602 			return -EUCLEAN;
1603 		}
1604 
1605 		if (unlock_up)
1606 			ret = -EAGAIN;
1607 
1608 		goto out;
1609 	} else if (p->nowait) {
1610 		return -EAGAIN;
1611 	}
1612 
1613 	if (unlock_up) {
1614 		btrfs_unlock_up_safe(p, level + 1);
1615 		ret = -EAGAIN;
1616 	} else {
1617 		ret = 0;
1618 	}
1619 
1620 	if (p->reada != READA_NONE)
1621 		reada_for_search(fs_info, p, level, slot, key->objectid);
1622 
1623 	tmp = read_tree_block(fs_info, blocknr, &check);
1624 	if (IS_ERR(tmp)) {
1625 		btrfs_release_path(p);
1626 		return PTR_ERR(tmp);
1627 	}
1628 	/*
1629 	 * If the read above didn't mark this buffer up to date,
1630 	 * it will never end up being up to date.  Set ret to EIO now
1631 	 * and give up so that our caller doesn't loop forever
1632 	 * on our EAGAINs.
1633 	 */
1634 	if (!extent_buffer_uptodate(tmp))
1635 		ret = -EIO;
1636 
1637 out:
1638 	if (ret == 0) {
1639 		*eb_ret = tmp;
1640 	} else {
1641 		free_extent_buffer(tmp);
1642 		btrfs_release_path(p);
1643 	}
1644 
1645 	return ret;
1646 }
1647 
1648 /*
1649  * helper function for btrfs_search_slot.  This does all of the checks
1650  * for node-level blocks and does any balancing required based on
1651  * the ins_len.
1652  *
1653  * If no extra work was required, zero is returned.  If we had to
1654  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1655  * start over
1656  */
1657 static int
1658 setup_nodes_for_search(struct btrfs_trans_handle *trans,
1659 		       struct btrfs_root *root, struct btrfs_path *p,
1660 		       struct extent_buffer *b, int level, int ins_len,
1661 		       int *write_lock_level)
1662 {
1663 	struct btrfs_fs_info *fs_info = root->fs_info;
1664 	int ret = 0;
1665 
1666 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
1667 	    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
1668 
1669 		if (*write_lock_level < level + 1) {
1670 			*write_lock_level = level + 1;
1671 			btrfs_release_path(p);
1672 			return -EAGAIN;
1673 		}
1674 
1675 		reada_for_balance(p, level);
1676 		ret = split_node(trans, root, p, level);
1677 
1678 		b = p->nodes[level];
1679 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
1680 		   BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
1681 
1682 		if (*write_lock_level < level + 1) {
1683 			*write_lock_level = level + 1;
1684 			btrfs_release_path(p);
1685 			return -EAGAIN;
1686 		}
1687 
1688 		reada_for_balance(p, level);
1689 		ret = balance_level(trans, root, p, level);
1690 		if (ret)
1691 			return ret;
1692 
1693 		b = p->nodes[level];
1694 		if (!b) {
1695 			btrfs_release_path(p);
1696 			return -EAGAIN;
1697 		}
1698 		BUG_ON(btrfs_header_nritems(b) == 1);
1699 	}
1700 	return ret;
1701 }
1702 
1703 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
1704 		u64 iobjectid, u64 ioff, u8 key_type,
1705 		struct btrfs_key *found_key)
1706 {
1707 	int ret;
1708 	struct btrfs_key key;
1709 	struct extent_buffer *eb;
1710 
1711 	ASSERT(path);
1712 	ASSERT(found_key);
1713 
1714 	key.type = key_type;
1715 	key.objectid = iobjectid;
1716 	key.offset = ioff;
1717 
1718 	ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
1719 	if (ret < 0)
1720 		return ret;
1721 
1722 	eb = path->nodes[0];
1723 	if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
1724 		ret = btrfs_next_leaf(fs_root, path);
1725 		if (ret)
1726 			return ret;
1727 		eb = path->nodes[0];
1728 	}
1729 
1730 	btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
1731 	if (found_key->type != key.type ||
1732 			found_key->objectid != key.objectid)
1733 		return 1;
1734 
1735 	return 0;
1736 }
1737 
1738 static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
1739 							struct btrfs_path *p,
1740 							int write_lock_level)
1741 {
1742 	struct extent_buffer *b;
1743 	int root_lock = 0;
1744 	int level = 0;
1745 
1746 	if (p->search_commit_root) {
1747 		b = root->commit_root;
1748 		atomic_inc(&b->refs);
1749 		level = btrfs_header_level(b);
1750 		/*
1751 		 * Ensure that all callers have set skip_locking when
1752 		 * p->search_commit_root = 1.
1753 		 */
1754 		ASSERT(p->skip_locking == 1);
1755 
1756 		goto out;
1757 	}
1758 
1759 	if (p->skip_locking) {
1760 		b = btrfs_root_node(root);
1761 		level = btrfs_header_level(b);
1762 		goto out;
1763 	}
1764 
1765 	/* We try very hard to do read locks on the root */
1766 	root_lock = BTRFS_READ_LOCK;
1767 
1768 	/*
1769 	 * If the level is set to maximum, we can skip trying to get the read
1770 	 * lock.
1771 	 */
1772 	if (write_lock_level < BTRFS_MAX_LEVEL) {
1773 		/*
1774 		 * We don't know the level of the root node until we actually
1775 		 * have it read locked
1776 		 */
1777 		if (p->nowait) {
1778 			b = btrfs_try_read_lock_root_node(root);
1779 			if (IS_ERR(b))
1780 				return b;
1781 		} else {
1782 			b = btrfs_read_lock_root_node(root);
1783 		}
1784 		level = btrfs_header_level(b);
1785 		if (level > write_lock_level)
1786 			goto out;
1787 
1788 		/* Whoops, must trade for write lock */
1789 		btrfs_tree_read_unlock(b);
1790 		free_extent_buffer(b);
1791 	}
1792 
1793 	b = btrfs_lock_root_node(root);
1794 	root_lock = BTRFS_WRITE_LOCK;
1795 
1796 	/* The level might have changed, check again */
1797 	level = btrfs_header_level(b);
1798 
1799 out:
1800 	/*
1801 	 * The root may have failed to write out at some point, and thus is no
1802 	 * longer valid, return an error in this case.
1803 	 */
1804 	if (!extent_buffer_uptodate(b)) {
1805 		if (root_lock)
1806 			btrfs_tree_unlock_rw(b, root_lock);
1807 		free_extent_buffer(b);
1808 		return ERR_PTR(-EIO);
1809 	}
1810 
1811 	p->nodes[level] = b;
1812 	if (!p->skip_locking)
1813 		p->locks[level] = root_lock;
1814 	/*
1815 	 * Callers are responsible for dropping b's references.
1816 	 */
1817 	return b;
1818 }
1819 
1820 /*
1821  * Replace the extent buffer at the lowest level of the path with a cloned
1822  * version. The purpose is to be able to use it safely, after releasing the
1823  * commit root semaphore, even if relocation is happening in parallel, the
1824  * transaction used for relocation is committed and the extent buffer is
1825  * reallocated in the next transaction.
1826  *
1827  * This is used in a context where the caller does not prevent transaction
1828  * commits from happening, either by holding a transaction handle or holding
1829  * some lock, while it's doing searches through a commit root.
1830  * At the moment it's only used for send operations.
1831  */
1832 static int finish_need_commit_sem_search(struct btrfs_path *path)
1833 {
1834 	const int i = path->lowest_level;
1835 	const int slot = path->slots[i];
1836 	struct extent_buffer *lowest = path->nodes[i];
1837 	struct extent_buffer *clone;
1838 
1839 	ASSERT(path->need_commit_sem);
1840 
1841 	if (!lowest)
1842 		return 0;
1843 
1844 	lockdep_assert_held_read(&lowest->fs_info->commit_root_sem);
1845 
1846 	clone = btrfs_clone_extent_buffer(lowest);
1847 	if (!clone)
1848 		return -ENOMEM;
1849 
1850 	btrfs_release_path(path);
1851 	path->nodes[i] = clone;
1852 	path->slots[i] = slot;
1853 
1854 	return 0;
1855 }
1856 
1857 static inline int search_for_key_slot(struct extent_buffer *eb,
1858 				      int search_low_slot,
1859 				      const struct btrfs_key *key,
1860 				      int prev_cmp,
1861 				      int *slot)
1862 {
1863 	/*
1864 	 * If a previous call to btrfs_bin_search() on a parent node returned an
1865 	 * exact match (prev_cmp == 0), we can safely assume the target key will
1866 	 * always be at slot 0 on lower levels, since each key pointer
1867 	 * (struct btrfs_key_ptr) refers to the lowest key accessible from the
1868 	 * subtree it points to. Thus we can skip searching lower levels.
1869 	 */
1870 	if (prev_cmp == 0) {
1871 		*slot = 0;
1872 		return 0;
1873 	}
1874 
1875 	return btrfs_bin_search(eb, search_low_slot, key, slot);
1876 }
1877 
1878 static int search_leaf(struct btrfs_trans_handle *trans,
1879 		       struct btrfs_root *root,
1880 		       const struct btrfs_key *key,
1881 		       struct btrfs_path *path,
1882 		       int ins_len,
1883 		       int prev_cmp)
1884 {
1885 	struct extent_buffer *leaf = path->nodes[0];
1886 	int leaf_free_space = -1;
1887 	int search_low_slot = 0;
1888 	int ret;
1889 	bool do_bin_search = true;
1890 
1891 	/*
1892 	 * If we are doing an insertion, the leaf has enough free space and the
1893 	 * destination slot for the key is not slot 0, then we can unlock our
1894 	 * write lock on the parent, and any other upper nodes, before doing the
1895 	 * binary search on the leaf (with search_for_key_slot()), allowing other
1896 	 * tasks to lock the parent and any other upper nodes.
1897 	 */
1898 	if (ins_len > 0) {
1899 		/*
1900 		 * Cache the leaf free space, since we will need it later and it
1901 		 * will not change until then.
1902 		 */
1903 		leaf_free_space = btrfs_leaf_free_space(leaf);
1904 
1905 		/*
1906 		 * !path->locks[1] means we have a single node tree, the leaf is
1907 		 * the root of the tree.
1908 		 */
1909 		if (path->locks[1] && leaf_free_space >= ins_len) {
1910 			struct btrfs_disk_key first_key;
1911 
1912 			ASSERT(btrfs_header_nritems(leaf) > 0);
1913 			btrfs_item_key(leaf, &first_key, 0);
1914 
1915 			/*
1916 			 * Doing the extra comparison with the first key is cheap,
1917 			 * taking into account that the first key is very likely
1918 			 * already in a cache line because it immediately follows
1919 			 * the extent buffer's header and we have recently accessed
1920 			 * the header's level field.
1921 			 */
1922 			ret = comp_keys(&first_key, key);
1923 			if (ret < 0) {
1924 				/*
1925 				 * The first key is smaller than the key we want
1926 				 * to insert, so we are safe to unlock all upper
1927 				 * nodes and we have to do the binary search.
1928 				 *
1929 				 * We do use btrfs_unlock_up_safe() and not
1930 				 * unlock_up() because the later does not unlock
1931 				 * nodes with a slot of 0 - we can safely unlock
1932 				 * any node even if its slot is 0 since in this
1933 				 * case the key does not end up at slot 0 of the
1934 				 * leaf and there's no need to split the leaf.
1935 				 */
1936 				btrfs_unlock_up_safe(path, 1);
1937 				search_low_slot = 1;
1938 			} else {
1939 				/*
1940 				 * The first key is >= then the key we want to
1941 				 * insert, so we can skip the binary search as
1942 				 * the target key will be at slot 0.
1943 				 *
1944 				 * We can not unlock upper nodes when the key is
1945 				 * less than the first key, because we will need
1946 				 * to update the key at slot 0 of the parent node
1947 				 * and possibly of other upper nodes too.
1948 				 * If the key matches the first key, then we can
1949 				 * unlock all the upper nodes, using
1950 				 * btrfs_unlock_up_safe() instead of unlock_up()
1951 				 * as stated above.
1952 				 */
1953 				if (ret == 0)
1954 					btrfs_unlock_up_safe(path, 1);
1955 				/*
1956 				 * ret is already 0 or 1, matching the result of
1957 				 * a btrfs_bin_search() call, so there is no need
1958 				 * to adjust it.
1959 				 */
1960 				do_bin_search = false;
1961 				path->slots[0] = 0;
1962 			}
1963 		}
1964 	}
1965 
1966 	if (do_bin_search) {
1967 		ret = search_for_key_slot(leaf, search_low_slot, key,
1968 					  prev_cmp, &path->slots[0]);
1969 		if (ret < 0)
1970 			return ret;
1971 	}
1972 
1973 	if (ins_len > 0) {
1974 		/*
1975 		 * Item key already exists. In this case, if we are allowed to
1976 		 * insert the item (for example, in dir_item case, item key
1977 		 * collision is allowed), it will be merged with the original
1978 		 * item. Only the item size grows, no new btrfs item will be
1979 		 * added. If search_for_extension is not set, ins_len already
1980 		 * accounts the size btrfs_item, deduct it here so leaf space
1981 		 * check will be correct.
1982 		 */
1983 		if (ret == 0 && !path->search_for_extension) {
1984 			ASSERT(ins_len >= sizeof(struct btrfs_item));
1985 			ins_len -= sizeof(struct btrfs_item);
1986 		}
1987 
1988 		ASSERT(leaf_free_space >= 0);
1989 
1990 		if (leaf_free_space < ins_len) {
1991 			int err;
1992 
1993 			err = split_leaf(trans, root, key, path, ins_len,
1994 					 (ret == 0));
1995 			ASSERT(err <= 0);
1996 			if (WARN_ON(err > 0))
1997 				err = -EUCLEAN;
1998 			if (err)
1999 				ret = err;
2000 		}
2001 	}
2002 
2003 	return ret;
2004 }
2005 
2006 /*
2007  * btrfs_search_slot - look for a key in a tree and perform necessary
2008  * modifications to preserve tree invariants.
2009  *
2010  * @trans:	Handle of transaction, used when modifying the tree
2011  * @p:		Holds all btree nodes along the search path
2012  * @root:	The root node of the tree
2013  * @key:	The key we are looking for
2014  * @ins_len:	Indicates purpose of search:
2015  *              >0  for inserts it's size of item inserted (*)
2016  *              <0  for deletions
2017  *               0  for plain searches, not modifying the tree
2018  *
2019  *              (*) If size of item inserted doesn't include
2020  *              sizeof(struct btrfs_item), then p->search_for_extension must
2021  *              be set.
2022  * @cow:	boolean should CoW operations be performed. Must always be 1
2023  *		when modifying the tree.
2024  *
2025  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
2026  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
2027  *
2028  * If @key is found, 0 is returned and you can find the item in the leaf level
2029  * of the path (level 0)
2030  *
2031  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
2032  * points to the slot where it should be inserted
2033  *
2034  * If an error is encountered while searching the tree a negative error number
2035  * is returned
2036  */
2037 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2038 		      const struct btrfs_key *key, struct btrfs_path *p,
2039 		      int ins_len, int cow)
2040 {
2041 	struct btrfs_fs_info *fs_info = root->fs_info;
2042 	struct extent_buffer *b;
2043 	int slot;
2044 	int ret;
2045 	int err;
2046 	int level;
2047 	int lowest_unlock = 1;
2048 	/* everything at write_lock_level or lower must be write locked */
2049 	int write_lock_level = 0;
2050 	u8 lowest_level = 0;
2051 	int min_write_lock_level;
2052 	int prev_cmp;
2053 
2054 	might_sleep();
2055 
2056 	lowest_level = p->lowest_level;
2057 	WARN_ON(lowest_level && ins_len > 0);
2058 	WARN_ON(p->nodes[0] != NULL);
2059 	BUG_ON(!cow && ins_len);
2060 
2061 	/*
2062 	 * For now only allow nowait for read only operations.  There's no
2063 	 * strict reason why we can't, we just only need it for reads so it's
2064 	 * only implemented for reads.
2065 	 */
2066 	ASSERT(!p->nowait || !cow);
2067 
2068 	if (ins_len < 0) {
2069 		lowest_unlock = 2;
2070 
2071 		/* when we are removing items, we might have to go up to level
2072 		 * two as we update tree pointers  Make sure we keep write
2073 		 * for those levels as well
2074 		 */
2075 		write_lock_level = 2;
2076 	} else if (ins_len > 0) {
2077 		/*
2078 		 * for inserting items, make sure we have a write lock on
2079 		 * level 1 so we can update keys
2080 		 */
2081 		write_lock_level = 1;
2082 	}
2083 
2084 	if (!cow)
2085 		write_lock_level = -1;
2086 
2087 	if (cow && (p->keep_locks || p->lowest_level))
2088 		write_lock_level = BTRFS_MAX_LEVEL;
2089 
2090 	min_write_lock_level = write_lock_level;
2091 
2092 	if (p->need_commit_sem) {
2093 		ASSERT(p->search_commit_root);
2094 		if (p->nowait) {
2095 			if (!down_read_trylock(&fs_info->commit_root_sem))
2096 				return -EAGAIN;
2097 		} else {
2098 			down_read(&fs_info->commit_root_sem);
2099 		}
2100 	}
2101 
2102 again:
2103 	prev_cmp = -1;
2104 	b = btrfs_search_slot_get_root(root, p, write_lock_level);
2105 	if (IS_ERR(b)) {
2106 		ret = PTR_ERR(b);
2107 		goto done;
2108 	}
2109 
2110 	while (b) {
2111 		int dec = 0;
2112 
2113 		level = btrfs_header_level(b);
2114 
2115 		if (cow) {
2116 			bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2117 
2118 			/*
2119 			 * if we don't really need to cow this block
2120 			 * then we don't want to set the path blocking,
2121 			 * so we test it here
2122 			 */
2123 			if (!should_cow_block(trans, root, b))
2124 				goto cow_done;
2125 
2126 			/*
2127 			 * must have write locks on this node and the
2128 			 * parent
2129 			 */
2130 			if (level > write_lock_level ||
2131 			    (level + 1 > write_lock_level &&
2132 			    level + 1 < BTRFS_MAX_LEVEL &&
2133 			    p->nodes[level + 1])) {
2134 				write_lock_level = level + 1;
2135 				btrfs_release_path(p);
2136 				goto again;
2137 			}
2138 
2139 			if (last_level)
2140 				err = btrfs_cow_block(trans, root, b, NULL, 0,
2141 						      &b,
2142 						      BTRFS_NESTING_COW);
2143 			else
2144 				err = btrfs_cow_block(trans, root, b,
2145 						      p->nodes[level + 1],
2146 						      p->slots[level + 1], &b,
2147 						      BTRFS_NESTING_COW);
2148 			if (err) {
2149 				ret = err;
2150 				goto done;
2151 			}
2152 		}
2153 cow_done:
2154 		p->nodes[level] = b;
2155 
2156 		/*
2157 		 * we have a lock on b and as long as we aren't changing
2158 		 * the tree, there is no way to for the items in b to change.
2159 		 * It is safe to drop the lock on our parent before we
2160 		 * go through the expensive btree search on b.
2161 		 *
2162 		 * If we're inserting or deleting (ins_len != 0), then we might
2163 		 * be changing slot zero, which may require changing the parent.
2164 		 * So, we can't drop the lock until after we know which slot
2165 		 * we're operating on.
2166 		 */
2167 		if (!ins_len && !p->keep_locks) {
2168 			int u = level + 1;
2169 
2170 			if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2171 				btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2172 				p->locks[u] = 0;
2173 			}
2174 		}
2175 
2176 		if (level == 0) {
2177 			if (ins_len > 0)
2178 				ASSERT(write_lock_level >= 1);
2179 
2180 			ret = search_leaf(trans, root, key, p, ins_len, prev_cmp);
2181 			if (!p->search_for_split)
2182 				unlock_up(p, level, lowest_unlock,
2183 					  min_write_lock_level, NULL);
2184 			goto done;
2185 		}
2186 
2187 		ret = search_for_key_slot(b, 0, key, prev_cmp, &slot);
2188 		if (ret < 0)
2189 			goto done;
2190 		prev_cmp = ret;
2191 
2192 		if (ret && slot > 0) {
2193 			dec = 1;
2194 			slot--;
2195 		}
2196 		p->slots[level] = slot;
2197 		err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2198 					     &write_lock_level);
2199 		if (err == -EAGAIN)
2200 			goto again;
2201 		if (err) {
2202 			ret = err;
2203 			goto done;
2204 		}
2205 		b = p->nodes[level];
2206 		slot = p->slots[level];
2207 
2208 		/*
2209 		 * Slot 0 is special, if we change the key we have to update
2210 		 * the parent pointer which means we must have a write lock on
2211 		 * the parent
2212 		 */
2213 		if (slot == 0 && ins_len && write_lock_level < level + 1) {
2214 			write_lock_level = level + 1;
2215 			btrfs_release_path(p);
2216 			goto again;
2217 		}
2218 
2219 		unlock_up(p, level, lowest_unlock, min_write_lock_level,
2220 			  &write_lock_level);
2221 
2222 		if (level == lowest_level) {
2223 			if (dec)
2224 				p->slots[level]++;
2225 			goto done;
2226 		}
2227 
2228 		err = read_block_for_search(root, p, &b, level, slot, key);
2229 		if (err == -EAGAIN)
2230 			goto again;
2231 		if (err) {
2232 			ret = err;
2233 			goto done;
2234 		}
2235 
2236 		if (!p->skip_locking) {
2237 			level = btrfs_header_level(b);
2238 
2239 			btrfs_maybe_reset_lockdep_class(root, b);
2240 
2241 			if (level <= write_lock_level) {
2242 				btrfs_tree_lock(b);
2243 				p->locks[level] = BTRFS_WRITE_LOCK;
2244 			} else {
2245 				if (p->nowait) {
2246 					if (!btrfs_try_tree_read_lock(b)) {
2247 						free_extent_buffer(b);
2248 						ret = -EAGAIN;
2249 						goto done;
2250 					}
2251 				} else {
2252 					btrfs_tree_read_lock(b);
2253 				}
2254 				p->locks[level] = BTRFS_READ_LOCK;
2255 			}
2256 			p->nodes[level] = b;
2257 		}
2258 	}
2259 	ret = 1;
2260 done:
2261 	if (ret < 0 && !p->skip_release_on_error)
2262 		btrfs_release_path(p);
2263 
2264 	if (p->need_commit_sem) {
2265 		int ret2;
2266 
2267 		ret2 = finish_need_commit_sem_search(p);
2268 		up_read(&fs_info->commit_root_sem);
2269 		if (ret2)
2270 			ret = ret2;
2271 	}
2272 
2273 	return ret;
2274 }
2275 ALLOW_ERROR_INJECTION(btrfs_search_slot, ERRNO);
2276 
2277 /*
2278  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2279  * current state of the tree together with the operations recorded in the tree
2280  * modification log to search for the key in a previous version of this tree, as
2281  * denoted by the time_seq parameter.
2282  *
2283  * Naturally, there is no support for insert, delete or cow operations.
2284  *
2285  * The resulting path and return value will be set up as if we called
2286  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2287  */
2288 int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
2289 			  struct btrfs_path *p, u64 time_seq)
2290 {
2291 	struct btrfs_fs_info *fs_info = root->fs_info;
2292 	struct extent_buffer *b;
2293 	int slot;
2294 	int ret;
2295 	int err;
2296 	int level;
2297 	int lowest_unlock = 1;
2298 	u8 lowest_level = 0;
2299 
2300 	lowest_level = p->lowest_level;
2301 	WARN_ON(p->nodes[0] != NULL);
2302 	ASSERT(!p->nowait);
2303 
2304 	if (p->search_commit_root) {
2305 		BUG_ON(time_seq);
2306 		return btrfs_search_slot(NULL, root, key, p, 0, 0);
2307 	}
2308 
2309 again:
2310 	b = btrfs_get_old_root(root, time_seq);
2311 	if (!b) {
2312 		ret = -EIO;
2313 		goto done;
2314 	}
2315 	level = btrfs_header_level(b);
2316 	p->locks[level] = BTRFS_READ_LOCK;
2317 
2318 	while (b) {
2319 		int dec = 0;
2320 
2321 		level = btrfs_header_level(b);
2322 		p->nodes[level] = b;
2323 
2324 		/*
2325 		 * we have a lock on b and as long as we aren't changing
2326 		 * the tree, there is no way to for the items in b to change.
2327 		 * It is safe to drop the lock on our parent before we
2328 		 * go through the expensive btree search on b.
2329 		 */
2330 		btrfs_unlock_up_safe(p, level + 1);
2331 
2332 		ret = btrfs_bin_search(b, 0, key, &slot);
2333 		if (ret < 0)
2334 			goto done;
2335 
2336 		if (level == 0) {
2337 			p->slots[level] = slot;
2338 			unlock_up(p, level, lowest_unlock, 0, NULL);
2339 			goto done;
2340 		}
2341 
2342 		if (ret && slot > 0) {
2343 			dec = 1;
2344 			slot--;
2345 		}
2346 		p->slots[level] = slot;
2347 		unlock_up(p, level, lowest_unlock, 0, NULL);
2348 
2349 		if (level == lowest_level) {
2350 			if (dec)
2351 				p->slots[level]++;
2352 			goto done;
2353 		}
2354 
2355 		err = read_block_for_search(root, p, &b, level, slot, key);
2356 		if (err == -EAGAIN)
2357 			goto again;
2358 		if (err) {
2359 			ret = err;
2360 			goto done;
2361 		}
2362 
2363 		level = btrfs_header_level(b);
2364 		btrfs_tree_read_lock(b);
2365 		b = btrfs_tree_mod_log_rewind(fs_info, p, b, time_seq);
2366 		if (!b) {
2367 			ret = -ENOMEM;
2368 			goto done;
2369 		}
2370 		p->locks[level] = BTRFS_READ_LOCK;
2371 		p->nodes[level] = b;
2372 	}
2373 	ret = 1;
2374 done:
2375 	if (ret < 0)
2376 		btrfs_release_path(p);
2377 
2378 	return ret;
2379 }
2380 
2381 /*
2382  * helper to use instead of search slot if no exact match is needed but
2383  * instead the next or previous item should be returned.
2384  * When find_higher is true, the next higher item is returned, the next lower
2385  * otherwise.
2386  * When return_any and find_higher are both true, and no higher item is found,
2387  * return the next lower instead.
2388  * When return_any is true and find_higher is false, and no lower item is found,
2389  * return the next higher instead.
2390  * It returns 0 if any item is found, 1 if none is found (tree empty), and
2391  * < 0 on error
2392  */
2393 int btrfs_search_slot_for_read(struct btrfs_root *root,
2394 			       const struct btrfs_key *key,
2395 			       struct btrfs_path *p, int find_higher,
2396 			       int return_any)
2397 {
2398 	int ret;
2399 	struct extent_buffer *leaf;
2400 
2401 again:
2402 	ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
2403 	if (ret <= 0)
2404 		return ret;
2405 	/*
2406 	 * a return value of 1 means the path is at the position where the
2407 	 * item should be inserted. Normally this is the next bigger item,
2408 	 * but in case the previous item is the last in a leaf, path points
2409 	 * to the first free slot in the previous leaf, i.e. at an invalid
2410 	 * item.
2411 	 */
2412 	leaf = p->nodes[0];
2413 
2414 	if (find_higher) {
2415 		if (p->slots[0] >= btrfs_header_nritems(leaf)) {
2416 			ret = btrfs_next_leaf(root, p);
2417 			if (ret <= 0)
2418 				return ret;
2419 			if (!return_any)
2420 				return 1;
2421 			/*
2422 			 * no higher item found, return the next
2423 			 * lower instead
2424 			 */
2425 			return_any = 0;
2426 			find_higher = 0;
2427 			btrfs_release_path(p);
2428 			goto again;
2429 		}
2430 	} else {
2431 		if (p->slots[0] == 0) {
2432 			ret = btrfs_prev_leaf(root, p);
2433 			if (ret < 0)
2434 				return ret;
2435 			if (!ret) {
2436 				leaf = p->nodes[0];
2437 				if (p->slots[0] == btrfs_header_nritems(leaf))
2438 					p->slots[0]--;
2439 				return 0;
2440 			}
2441 			if (!return_any)
2442 				return 1;
2443 			/*
2444 			 * no lower item found, return the next
2445 			 * higher instead
2446 			 */
2447 			return_any = 0;
2448 			find_higher = 1;
2449 			btrfs_release_path(p);
2450 			goto again;
2451 		} else {
2452 			--p->slots[0];
2453 		}
2454 	}
2455 	return 0;
2456 }
2457 
2458 /*
2459  * Execute search and call btrfs_previous_item to traverse backwards if the item
2460  * was not found.
2461  *
2462  * Return 0 if found, 1 if not found and < 0 if error.
2463  */
2464 int btrfs_search_backwards(struct btrfs_root *root, struct btrfs_key *key,
2465 			   struct btrfs_path *path)
2466 {
2467 	int ret;
2468 
2469 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
2470 	if (ret > 0)
2471 		ret = btrfs_previous_item(root, path, key->objectid, key->type);
2472 
2473 	if (ret == 0)
2474 		btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
2475 
2476 	return ret;
2477 }
2478 
2479 /*
2480  * Search for a valid slot for the given path.
2481  *
2482  * @root:	The root node of the tree.
2483  * @key:	Will contain a valid item if found.
2484  * @path:	The starting point to validate the slot.
2485  *
2486  * Return: 0  if the item is valid
2487  *         1  if not found
2488  *         <0 if error.
2489  */
2490 int btrfs_get_next_valid_item(struct btrfs_root *root, struct btrfs_key *key,
2491 			      struct btrfs_path *path)
2492 {
2493 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2494 		int ret;
2495 
2496 		ret = btrfs_next_leaf(root, path);
2497 		if (ret)
2498 			return ret;
2499 	}
2500 
2501 	btrfs_item_key_to_cpu(path->nodes[0], key, path->slots[0]);
2502 	return 0;
2503 }
2504 
2505 /*
2506  * adjust the pointers going up the tree, starting at level
2507  * making sure the right key of each node is points to 'key'.
2508  * This is used after shifting pointers to the left, so it stops
2509  * fixing up pointers when a given leaf/node is not in slot 0 of the
2510  * higher levels
2511  *
2512  */
2513 static void fixup_low_keys(struct btrfs_path *path,
2514 			   struct btrfs_disk_key *key, int level)
2515 {
2516 	int i;
2517 	struct extent_buffer *t;
2518 	int ret;
2519 
2520 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2521 		int tslot = path->slots[i];
2522 
2523 		if (!path->nodes[i])
2524 			break;
2525 		t = path->nodes[i];
2526 		ret = btrfs_tree_mod_log_insert_key(t, tslot,
2527 						    BTRFS_MOD_LOG_KEY_REPLACE);
2528 		BUG_ON(ret < 0);
2529 		btrfs_set_node_key(t, key, tslot);
2530 		btrfs_mark_buffer_dirty(path->nodes[i]);
2531 		if (tslot != 0)
2532 			break;
2533 	}
2534 }
2535 
2536 /*
2537  * update item key.
2538  *
2539  * This function isn't completely safe. It's the caller's responsibility
2540  * that the new key won't break the order
2541  */
2542 void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
2543 			     struct btrfs_path *path,
2544 			     const struct btrfs_key *new_key)
2545 {
2546 	struct btrfs_disk_key disk_key;
2547 	struct extent_buffer *eb;
2548 	int slot;
2549 
2550 	eb = path->nodes[0];
2551 	slot = path->slots[0];
2552 	if (slot > 0) {
2553 		btrfs_item_key(eb, &disk_key, slot - 1);
2554 		if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
2555 			btrfs_crit(fs_info,
2556 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2557 				   slot, btrfs_disk_key_objectid(&disk_key),
2558 				   btrfs_disk_key_type(&disk_key),
2559 				   btrfs_disk_key_offset(&disk_key),
2560 				   new_key->objectid, new_key->type,
2561 				   new_key->offset);
2562 			btrfs_print_leaf(eb);
2563 			BUG();
2564 		}
2565 	}
2566 	if (slot < btrfs_header_nritems(eb) - 1) {
2567 		btrfs_item_key(eb, &disk_key, slot + 1);
2568 		if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
2569 			btrfs_crit(fs_info,
2570 		"slot %u key (%llu %u %llu) new key (%llu %u %llu)",
2571 				   slot, btrfs_disk_key_objectid(&disk_key),
2572 				   btrfs_disk_key_type(&disk_key),
2573 				   btrfs_disk_key_offset(&disk_key),
2574 				   new_key->objectid, new_key->type,
2575 				   new_key->offset);
2576 			btrfs_print_leaf(eb);
2577 			BUG();
2578 		}
2579 	}
2580 
2581 	btrfs_cpu_key_to_disk(&disk_key, new_key);
2582 	btrfs_set_item_key(eb, &disk_key, slot);
2583 	btrfs_mark_buffer_dirty(eb);
2584 	if (slot == 0)
2585 		fixup_low_keys(path, &disk_key, 1);
2586 }
2587 
2588 /*
2589  * Check key order of two sibling extent buffers.
2590  *
2591  * Return true if something is wrong.
2592  * Return false if everything is fine.
2593  *
2594  * Tree-checker only works inside one tree block, thus the following
2595  * corruption can not be detected by tree-checker:
2596  *
2597  * Leaf @left			| Leaf @right
2598  * --------------------------------------------------------------
2599  * | 1 | 2 | 3 | 4 | 5 | f6 |   | 7 | 8 |
2600  *
2601  * Key f6 in leaf @left itself is valid, but not valid when the next
2602  * key in leaf @right is 7.
2603  * This can only be checked at tree block merge time.
2604  * And since tree checker has ensured all key order in each tree block
2605  * is correct, we only need to bother the last key of @left and the first
2606  * key of @right.
2607  */
2608 static bool check_sibling_keys(struct extent_buffer *left,
2609 			       struct extent_buffer *right)
2610 {
2611 	struct btrfs_key left_last;
2612 	struct btrfs_key right_first;
2613 	int level = btrfs_header_level(left);
2614 	int nr_left = btrfs_header_nritems(left);
2615 	int nr_right = btrfs_header_nritems(right);
2616 
2617 	/* No key to check in one of the tree blocks */
2618 	if (!nr_left || !nr_right)
2619 		return false;
2620 
2621 	if (level) {
2622 		btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
2623 		btrfs_node_key_to_cpu(right, &right_first, 0);
2624 	} else {
2625 		btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
2626 		btrfs_item_key_to_cpu(right, &right_first, 0);
2627 	}
2628 
2629 	if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
2630 		btrfs_crit(left->fs_info, "left extent buffer:");
2631 		btrfs_print_tree(left, false);
2632 		btrfs_crit(left->fs_info, "right extent buffer:");
2633 		btrfs_print_tree(right, false);
2634 		btrfs_crit(left->fs_info,
2635 "bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
2636 			   left_last.objectid, left_last.type,
2637 			   left_last.offset, right_first.objectid,
2638 			   right_first.type, right_first.offset);
2639 		return true;
2640 	}
2641 	return false;
2642 }
2643 
2644 /*
2645  * try to push data from one node into the next node left in the
2646  * tree.
2647  *
2648  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2649  * error, and > 0 if there was no room in the left hand block.
2650  */
2651 static int push_node_left(struct btrfs_trans_handle *trans,
2652 			  struct extent_buffer *dst,
2653 			  struct extent_buffer *src, int empty)
2654 {
2655 	struct btrfs_fs_info *fs_info = trans->fs_info;
2656 	int push_items = 0;
2657 	int src_nritems;
2658 	int dst_nritems;
2659 	int ret = 0;
2660 
2661 	src_nritems = btrfs_header_nritems(src);
2662 	dst_nritems = btrfs_header_nritems(dst);
2663 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2664 	WARN_ON(btrfs_header_generation(src) != trans->transid);
2665 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
2666 
2667 	if (!empty && src_nritems <= 8)
2668 		return 1;
2669 
2670 	if (push_items <= 0)
2671 		return 1;
2672 
2673 	if (empty) {
2674 		push_items = min(src_nritems, push_items);
2675 		if (push_items < src_nritems) {
2676 			/* leave at least 8 pointers in the node if
2677 			 * we aren't going to empty it
2678 			 */
2679 			if (src_nritems - push_items < 8) {
2680 				if (push_items <= 8)
2681 					return 1;
2682 				push_items -= 8;
2683 			}
2684 		}
2685 	} else
2686 		push_items = min(src_nritems - 8, push_items);
2687 
2688 	/* dst is the left eb, src is the middle eb */
2689 	if (check_sibling_keys(dst, src)) {
2690 		ret = -EUCLEAN;
2691 		btrfs_abort_transaction(trans, ret);
2692 		return ret;
2693 	}
2694 	ret = btrfs_tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
2695 	if (ret) {
2696 		btrfs_abort_transaction(trans, ret);
2697 		return ret;
2698 	}
2699 	copy_extent_buffer(dst, src,
2700 			   btrfs_node_key_ptr_offset(dst, dst_nritems),
2701 			   btrfs_node_key_ptr_offset(src, 0),
2702 			   push_items * sizeof(struct btrfs_key_ptr));
2703 
2704 	if (push_items < src_nritems) {
2705 		/*
2706 		 * Don't call btrfs_tree_mod_log_insert_move() here, key removal
2707 		 * was already fully logged by btrfs_tree_mod_log_eb_copy() above.
2708 		 */
2709 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(src, 0),
2710 				      btrfs_node_key_ptr_offset(src, push_items),
2711 				      (src_nritems - push_items) *
2712 				      sizeof(struct btrfs_key_ptr));
2713 	}
2714 	btrfs_set_header_nritems(src, src_nritems - push_items);
2715 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
2716 	btrfs_mark_buffer_dirty(src);
2717 	btrfs_mark_buffer_dirty(dst);
2718 
2719 	return ret;
2720 }
2721 
2722 /*
2723  * try to push data from one node into the next node right in the
2724  * tree.
2725  *
2726  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
2727  * error, and > 0 if there was no room in the right hand block.
2728  *
2729  * this will  only push up to 1/2 the contents of the left node over
2730  */
2731 static int balance_node_right(struct btrfs_trans_handle *trans,
2732 			      struct extent_buffer *dst,
2733 			      struct extent_buffer *src)
2734 {
2735 	struct btrfs_fs_info *fs_info = trans->fs_info;
2736 	int push_items = 0;
2737 	int max_push;
2738 	int src_nritems;
2739 	int dst_nritems;
2740 	int ret = 0;
2741 
2742 	WARN_ON(btrfs_header_generation(src) != trans->transid);
2743 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
2744 
2745 	src_nritems = btrfs_header_nritems(src);
2746 	dst_nritems = btrfs_header_nritems(dst);
2747 	push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
2748 	if (push_items <= 0)
2749 		return 1;
2750 
2751 	if (src_nritems < 4)
2752 		return 1;
2753 
2754 	max_push = src_nritems / 2 + 1;
2755 	/* don't try to empty the node */
2756 	if (max_push >= src_nritems)
2757 		return 1;
2758 
2759 	if (max_push < push_items)
2760 		push_items = max_push;
2761 
2762 	/* dst is the right eb, src is the middle eb */
2763 	if (check_sibling_keys(src, dst)) {
2764 		ret = -EUCLEAN;
2765 		btrfs_abort_transaction(trans, ret);
2766 		return ret;
2767 	}
2768 	ret = btrfs_tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
2769 	BUG_ON(ret < 0);
2770 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(dst, push_items),
2771 				      btrfs_node_key_ptr_offset(dst, 0),
2772 				      (dst_nritems) *
2773 				      sizeof(struct btrfs_key_ptr));
2774 
2775 	ret = btrfs_tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
2776 					 push_items);
2777 	if (ret) {
2778 		btrfs_abort_transaction(trans, ret);
2779 		return ret;
2780 	}
2781 	copy_extent_buffer(dst, src,
2782 			   btrfs_node_key_ptr_offset(dst, 0),
2783 			   btrfs_node_key_ptr_offset(src, src_nritems - push_items),
2784 			   push_items * sizeof(struct btrfs_key_ptr));
2785 
2786 	btrfs_set_header_nritems(src, src_nritems - push_items);
2787 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
2788 
2789 	btrfs_mark_buffer_dirty(src);
2790 	btrfs_mark_buffer_dirty(dst);
2791 
2792 	return ret;
2793 }
2794 
2795 /*
2796  * helper function to insert a new root level in the tree.
2797  * A new node is allocated, and a single item is inserted to
2798  * point to the existing root
2799  *
2800  * returns zero on success or < 0 on failure.
2801  */
2802 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
2803 			   struct btrfs_root *root,
2804 			   struct btrfs_path *path, int level)
2805 {
2806 	struct btrfs_fs_info *fs_info = root->fs_info;
2807 	u64 lower_gen;
2808 	struct extent_buffer *lower;
2809 	struct extent_buffer *c;
2810 	struct extent_buffer *old;
2811 	struct btrfs_disk_key lower_key;
2812 	int ret;
2813 
2814 	BUG_ON(path->nodes[level]);
2815 	BUG_ON(path->nodes[level-1] != root->node);
2816 
2817 	lower = path->nodes[level-1];
2818 	if (level == 1)
2819 		btrfs_item_key(lower, &lower_key, 0);
2820 	else
2821 		btrfs_node_key(lower, &lower_key, 0);
2822 
2823 	c = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
2824 				   &lower_key, level, root->node->start, 0,
2825 				   BTRFS_NESTING_NEW_ROOT);
2826 	if (IS_ERR(c))
2827 		return PTR_ERR(c);
2828 
2829 	root_add_used(root, fs_info->nodesize);
2830 
2831 	btrfs_set_header_nritems(c, 1);
2832 	btrfs_set_node_key(c, &lower_key, 0);
2833 	btrfs_set_node_blockptr(c, 0, lower->start);
2834 	lower_gen = btrfs_header_generation(lower);
2835 	WARN_ON(lower_gen != trans->transid);
2836 
2837 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
2838 
2839 	btrfs_mark_buffer_dirty(c);
2840 
2841 	old = root->node;
2842 	ret = btrfs_tree_mod_log_insert_root(root->node, c, false);
2843 	BUG_ON(ret < 0);
2844 	rcu_assign_pointer(root->node, c);
2845 
2846 	/* the super has an extra ref to root->node */
2847 	free_extent_buffer(old);
2848 
2849 	add_root_to_dirty_list(root);
2850 	atomic_inc(&c->refs);
2851 	path->nodes[level] = c;
2852 	path->locks[level] = BTRFS_WRITE_LOCK;
2853 	path->slots[level] = 0;
2854 	return 0;
2855 }
2856 
2857 /*
2858  * worker function to insert a single pointer in a node.
2859  * the node should have enough room for the pointer already
2860  *
2861  * slot and level indicate where you want the key to go, and
2862  * blocknr is the block the key points to.
2863  */
2864 static void insert_ptr(struct btrfs_trans_handle *trans,
2865 		       struct btrfs_path *path,
2866 		       struct btrfs_disk_key *key, u64 bytenr,
2867 		       int slot, int level)
2868 {
2869 	struct extent_buffer *lower;
2870 	int nritems;
2871 	int ret;
2872 
2873 	BUG_ON(!path->nodes[level]);
2874 	btrfs_assert_tree_write_locked(path->nodes[level]);
2875 	lower = path->nodes[level];
2876 	nritems = btrfs_header_nritems(lower);
2877 	BUG_ON(slot > nritems);
2878 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
2879 	if (slot != nritems) {
2880 		if (level) {
2881 			ret = btrfs_tree_mod_log_insert_move(lower, slot + 1,
2882 					slot, nritems - slot);
2883 			BUG_ON(ret < 0);
2884 		}
2885 		memmove_extent_buffer(lower,
2886 			      btrfs_node_key_ptr_offset(lower, slot + 1),
2887 			      btrfs_node_key_ptr_offset(lower, slot),
2888 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
2889 	}
2890 	if (level) {
2891 		ret = btrfs_tree_mod_log_insert_key(lower, slot,
2892 						    BTRFS_MOD_LOG_KEY_ADD);
2893 		BUG_ON(ret < 0);
2894 	}
2895 	btrfs_set_node_key(lower, key, slot);
2896 	btrfs_set_node_blockptr(lower, slot, bytenr);
2897 	WARN_ON(trans->transid == 0);
2898 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
2899 	btrfs_set_header_nritems(lower, nritems + 1);
2900 	btrfs_mark_buffer_dirty(lower);
2901 }
2902 
2903 /*
2904  * split the node at the specified level in path in two.
2905  * The path is corrected to point to the appropriate node after the split
2906  *
2907  * Before splitting this tries to make some room in the node by pushing
2908  * left and right, if either one works, it returns right away.
2909  *
2910  * returns 0 on success and < 0 on failure
2911  */
2912 static noinline int split_node(struct btrfs_trans_handle *trans,
2913 			       struct btrfs_root *root,
2914 			       struct btrfs_path *path, int level)
2915 {
2916 	struct btrfs_fs_info *fs_info = root->fs_info;
2917 	struct extent_buffer *c;
2918 	struct extent_buffer *split;
2919 	struct btrfs_disk_key disk_key;
2920 	int mid;
2921 	int ret;
2922 	u32 c_nritems;
2923 
2924 	c = path->nodes[level];
2925 	WARN_ON(btrfs_header_generation(c) != trans->transid);
2926 	if (c == root->node) {
2927 		/*
2928 		 * trying to split the root, lets make a new one
2929 		 *
2930 		 * tree mod log: We don't log_removal old root in
2931 		 * insert_new_root, because that root buffer will be kept as a
2932 		 * normal node. We are going to log removal of half of the
2933 		 * elements below with btrfs_tree_mod_log_eb_copy(). We're
2934 		 * holding a tree lock on the buffer, which is why we cannot
2935 		 * race with other tree_mod_log users.
2936 		 */
2937 		ret = insert_new_root(trans, root, path, level + 1);
2938 		if (ret)
2939 			return ret;
2940 	} else {
2941 		ret = push_nodes_for_insert(trans, root, path, level);
2942 		c = path->nodes[level];
2943 		if (!ret && btrfs_header_nritems(c) <
2944 		    BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
2945 			return 0;
2946 		if (ret < 0)
2947 			return ret;
2948 	}
2949 
2950 	c_nritems = btrfs_header_nritems(c);
2951 	mid = (c_nritems + 1) / 2;
2952 	btrfs_node_key(c, &disk_key, mid);
2953 
2954 	split = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
2955 				       &disk_key, level, c->start, 0,
2956 				       BTRFS_NESTING_SPLIT);
2957 	if (IS_ERR(split))
2958 		return PTR_ERR(split);
2959 
2960 	root_add_used(root, fs_info->nodesize);
2961 	ASSERT(btrfs_header_level(c) == level);
2962 
2963 	ret = btrfs_tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
2964 	if (ret) {
2965 		btrfs_abort_transaction(trans, ret);
2966 		return ret;
2967 	}
2968 	copy_extent_buffer(split, c,
2969 			   btrfs_node_key_ptr_offset(split, 0),
2970 			   btrfs_node_key_ptr_offset(c, mid),
2971 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
2972 	btrfs_set_header_nritems(split, c_nritems - mid);
2973 	btrfs_set_header_nritems(c, mid);
2974 
2975 	btrfs_mark_buffer_dirty(c);
2976 	btrfs_mark_buffer_dirty(split);
2977 
2978 	insert_ptr(trans, path, &disk_key, split->start,
2979 		   path->slots[level + 1] + 1, level + 1);
2980 
2981 	if (path->slots[level] >= mid) {
2982 		path->slots[level] -= mid;
2983 		btrfs_tree_unlock(c);
2984 		free_extent_buffer(c);
2985 		path->nodes[level] = split;
2986 		path->slots[level + 1] += 1;
2987 	} else {
2988 		btrfs_tree_unlock(split);
2989 		free_extent_buffer(split);
2990 	}
2991 	return 0;
2992 }
2993 
2994 /*
2995  * how many bytes are required to store the items in a leaf.  start
2996  * and nr indicate which items in the leaf to check.  This totals up the
2997  * space used both by the item structs and the item data
2998  */
2999 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
3000 {
3001 	int data_len;
3002 	int nritems = btrfs_header_nritems(l);
3003 	int end = min(nritems, start + nr) - 1;
3004 
3005 	if (!nr)
3006 		return 0;
3007 	data_len = btrfs_item_offset(l, start) + btrfs_item_size(l, start);
3008 	data_len = data_len - btrfs_item_offset(l, end);
3009 	data_len += sizeof(struct btrfs_item) * nr;
3010 	WARN_ON(data_len < 0);
3011 	return data_len;
3012 }
3013 
3014 /*
3015  * The space between the end of the leaf items and
3016  * the start of the leaf data.  IOW, how much room
3017  * the leaf has left for both items and data
3018  */
3019 noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
3020 {
3021 	struct btrfs_fs_info *fs_info = leaf->fs_info;
3022 	int nritems = btrfs_header_nritems(leaf);
3023 	int ret;
3024 
3025 	ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
3026 	if (ret < 0) {
3027 		btrfs_crit(fs_info,
3028 			   "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3029 			   ret,
3030 			   (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
3031 			   leaf_space_used(leaf, 0, nritems), nritems);
3032 	}
3033 	return ret;
3034 }
3035 
3036 /*
3037  * min slot controls the lowest index we're willing to push to the
3038  * right.  We'll push up to and including min_slot, but no lower
3039  */
3040 static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
3041 				      struct btrfs_path *path,
3042 				      int data_size, int empty,
3043 				      struct extent_buffer *right,
3044 				      int free_space, u32 left_nritems,
3045 				      u32 min_slot)
3046 {
3047 	struct btrfs_fs_info *fs_info = right->fs_info;
3048 	struct extent_buffer *left = path->nodes[0];
3049 	struct extent_buffer *upper = path->nodes[1];
3050 	struct btrfs_map_token token;
3051 	struct btrfs_disk_key disk_key;
3052 	int slot;
3053 	u32 i;
3054 	int push_space = 0;
3055 	int push_items = 0;
3056 	u32 nr;
3057 	u32 right_nritems;
3058 	u32 data_end;
3059 	u32 this_item_size;
3060 
3061 	if (empty)
3062 		nr = 0;
3063 	else
3064 		nr = max_t(u32, 1, min_slot);
3065 
3066 	if (path->slots[0] >= left_nritems)
3067 		push_space += data_size;
3068 
3069 	slot = path->slots[1];
3070 	i = left_nritems - 1;
3071 	while (i >= nr) {
3072 		if (!empty && push_items > 0) {
3073 			if (path->slots[0] > i)
3074 				break;
3075 			if (path->slots[0] == i) {
3076 				int space = btrfs_leaf_free_space(left);
3077 
3078 				if (space + push_space * 2 > free_space)
3079 					break;
3080 			}
3081 		}
3082 
3083 		if (path->slots[0] == i)
3084 			push_space += data_size;
3085 
3086 		this_item_size = btrfs_item_size(left, i);
3087 		if (this_item_size + sizeof(struct btrfs_item) +
3088 		    push_space > free_space)
3089 			break;
3090 
3091 		push_items++;
3092 		push_space += this_item_size + sizeof(struct btrfs_item);
3093 		if (i == 0)
3094 			break;
3095 		i--;
3096 	}
3097 
3098 	if (push_items == 0)
3099 		goto out_unlock;
3100 
3101 	WARN_ON(!empty && push_items == left_nritems);
3102 
3103 	/* push left to right */
3104 	right_nritems = btrfs_header_nritems(right);
3105 
3106 	push_space = btrfs_item_data_end(left, left_nritems - push_items);
3107 	push_space -= leaf_data_end(left);
3108 
3109 	/* make room in the right data area */
3110 	data_end = leaf_data_end(right);
3111 	memmove_leaf_data(right, data_end - push_space, data_end,
3112 			  BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
3113 
3114 	/* copy from the left data area */
3115 	copy_leaf_data(right, left, BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3116 		       leaf_data_end(left), push_space);
3117 
3118 	memmove_leaf_items(right, push_items, 0, right_nritems);
3119 
3120 	/* copy the items from left to right */
3121 	copy_leaf_items(right, left, 0, left_nritems - push_items, push_items);
3122 
3123 	/* update the item pointers */
3124 	btrfs_init_map_token(&token, right);
3125 	right_nritems += push_items;
3126 	btrfs_set_header_nritems(right, right_nritems);
3127 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3128 	for (i = 0; i < right_nritems; i++) {
3129 		push_space -= btrfs_token_item_size(&token, i);
3130 		btrfs_set_token_item_offset(&token, i, push_space);
3131 	}
3132 
3133 	left_nritems -= push_items;
3134 	btrfs_set_header_nritems(left, left_nritems);
3135 
3136 	if (left_nritems)
3137 		btrfs_mark_buffer_dirty(left);
3138 	else
3139 		btrfs_clear_buffer_dirty(trans, left);
3140 
3141 	btrfs_mark_buffer_dirty(right);
3142 
3143 	btrfs_item_key(right, &disk_key, 0);
3144 	btrfs_set_node_key(upper, &disk_key, slot + 1);
3145 	btrfs_mark_buffer_dirty(upper);
3146 
3147 	/* then fixup the leaf pointer in the path */
3148 	if (path->slots[0] >= left_nritems) {
3149 		path->slots[0] -= left_nritems;
3150 		if (btrfs_header_nritems(path->nodes[0]) == 0)
3151 			btrfs_clear_buffer_dirty(trans, path->nodes[0]);
3152 		btrfs_tree_unlock(path->nodes[0]);
3153 		free_extent_buffer(path->nodes[0]);
3154 		path->nodes[0] = right;
3155 		path->slots[1] += 1;
3156 	} else {
3157 		btrfs_tree_unlock(right);
3158 		free_extent_buffer(right);
3159 	}
3160 	return 0;
3161 
3162 out_unlock:
3163 	btrfs_tree_unlock(right);
3164 	free_extent_buffer(right);
3165 	return 1;
3166 }
3167 
3168 /*
3169  * push some data in the path leaf to the right, trying to free up at
3170  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
3171  *
3172  * returns 1 if the push failed because the other node didn't have enough
3173  * room, 0 if everything worked out and < 0 if there were major errors.
3174  *
3175  * this will push starting from min_slot to the end of the leaf.  It won't
3176  * push any slot lower than min_slot
3177  */
3178 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
3179 			   *root, struct btrfs_path *path,
3180 			   int min_data_size, int data_size,
3181 			   int empty, u32 min_slot)
3182 {
3183 	struct extent_buffer *left = path->nodes[0];
3184 	struct extent_buffer *right;
3185 	struct extent_buffer *upper;
3186 	int slot;
3187 	int free_space;
3188 	u32 left_nritems;
3189 	int ret;
3190 
3191 	if (!path->nodes[1])
3192 		return 1;
3193 
3194 	slot = path->slots[1];
3195 	upper = path->nodes[1];
3196 	if (slot >= btrfs_header_nritems(upper) - 1)
3197 		return 1;
3198 
3199 	btrfs_assert_tree_write_locked(path->nodes[1]);
3200 
3201 	right = btrfs_read_node_slot(upper, slot + 1);
3202 	if (IS_ERR(right))
3203 		return PTR_ERR(right);
3204 
3205 	__btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
3206 
3207 	free_space = btrfs_leaf_free_space(right);
3208 	if (free_space < data_size)
3209 		goto out_unlock;
3210 
3211 	ret = btrfs_cow_block(trans, root, right, upper,
3212 			      slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
3213 	if (ret)
3214 		goto out_unlock;
3215 
3216 	left_nritems = btrfs_header_nritems(left);
3217 	if (left_nritems == 0)
3218 		goto out_unlock;
3219 
3220 	if (check_sibling_keys(left, right)) {
3221 		ret = -EUCLEAN;
3222 		btrfs_abort_transaction(trans, ret);
3223 		btrfs_tree_unlock(right);
3224 		free_extent_buffer(right);
3225 		return ret;
3226 	}
3227 	if (path->slots[0] == left_nritems && !empty) {
3228 		/* Key greater than all keys in the leaf, right neighbor has
3229 		 * enough room for it and we're not emptying our leaf to delete
3230 		 * it, therefore use right neighbor to insert the new item and
3231 		 * no need to touch/dirty our left leaf. */
3232 		btrfs_tree_unlock(left);
3233 		free_extent_buffer(left);
3234 		path->nodes[0] = right;
3235 		path->slots[0] = 0;
3236 		path->slots[1]++;
3237 		return 0;
3238 	}
3239 
3240 	return __push_leaf_right(trans, path, min_data_size, empty, right,
3241 				 free_space, left_nritems, min_slot);
3242 out_unlock:
3243 	btrfs_tree_unlock(right);
3244 	free_extent_buffer(right);
3245 	return 1;
3246 }
3247 
3248 /*
3249  * push some data in the path leaf to the left, trying to free up at
3250  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
3251  *
3252  * max_slot can put a limit on how far into the leaf we'll push items.  The
3253  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
3254  * items
3255  */
3256 static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
3257 				     struct btrfs_path *path, int data_size,
3258 				     int empty, struct extent_buffer *left,
3259 				     int free_space, u32 right_nritems,
3260 				     u32 max_slot)
3261 {
3262 	struct btrfs_fs_info *fs_info = left->fs_info;
3263 	struct btrfs_disk_key disk_key;
3264 	struct extent_buffer *right = path->nodes[0];
3265 	int i;
3266 	int push_space = 0;
3267 	int push_items = 0;
3268 	u32 old_left_nritems;
3269 	u32 nr;
3270 	int ret = 0;
3271 	u32 this_item_size;
3272 	u32 old_left_item_size;
3273 	struct btrfs_map_token token;
3274 
3275 	if (empty)
3276 		nr = min(right_nritems, max_slot);
3277 	else
3278 		nr = min(right_nritems - 1, max_slot);
3279 
3280 	for (i = 0; i < nr; i++) {
3281 		if (!empty && push_items > 0) {
3282 			if (path->slots[0] < i)
3283 				break;
3284 			if (path->slots[0] == i) {
3285 				int space = btrfs_leaf_free_space(right);
3286 
3287 				if (space + push_space * 2 > free_space)
3288 					break;
3289 			}
3290 		}
3291 
3292 		if (path->slots[0] == i)
3293 			push_space += data_size;
3294 
3295 		this_item_size = btrfs_item_size(right, i);
3296 		if (this_item_size + sizeof(struct btrfs_item) + push_space >
3297 		    free_space)
3298 			break;
3299 
3300 		push_items++;
3301 		push_space += this_item_size + sizeof(struct btrfs_item);
3302 	}
3303 
3304 	if (push_items == 0) {
3305 		ret = 1;
3306 		goto out;
3307 	}
3308 	WARN_ON(!empty && push_items == btrfs_header_nritems(right));
3309 
3310 	/* push data from right to left */
3311 	copy_leaf_items(left, right, btrfs_header_nritems(left), 0, push_items);
3312 
3313 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
3314 		     btrfs_item_offset(right, push_items - 1);
3315 
3316 	copy_leaf_data(left, right, leaf_data_end(left) - push_space,
3317 		       btrfs_item_offset(right, push_items - 1), push_space);
3318 	old_left_nritems = btrfs_header_nritems(left);
3319 	BUG_ON(old_left_nritems <= 0);
3320 
3321 	btrfs_init_map_token(&token, left);
3322 	old_left_item_size = btrfs_item_offset(left, old_left_nritems - 1);
3323 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
3324 		u32 ioff;
3325 
3326 		ioff = btrfs_token_item_offset(&token, i);
3327 		btrfs_set_token_item_offset(&token, i,
3328 		      ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
3329 	}
3330 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
3331 
3332 	/* fixup right node */
3333 	if (push_items > right_nritems)
3334 		WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
3335 		       right_nritems);
3336 
3337 	if (push_items < right_nritems) {
3338 		push_space = btrfs_item_offset(right, push_items - 1) -
3339 						  leaf_data_end(right);
3340 		memmove_leaf_data(right,
3341 				  BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3342 				  leaf_data_end(right), push_space);
3343 
3344 		memmove_leaf_items(right, 0, push_items,
3345 				   btrfs_header_nritems(right) - push_items);
3346 	}
3347 
3348 	btrfs_init_map_token(&token, right);
3349 	right_nritems -= push_items;
3350 	btrfs_set_header_nritems(right, right_nritems);
3351 	push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
3352 	for (i = 0; i < right_nritems; i++) {
3353 		push_space = push_space - btrfs_token_item_size(&token, i);
3354 		btrfs_set_token_item_offset(&token, i, push_space);
3355 	}
3356 
3357 	btrfs_mark_buffer_dirty(left);
3358 	if (right_nritems)
3359 		btrfs_mark_buffer_dirty(right);
3360 	else
3361 		btrfs_clear_buffer_dirty(trans, right);
3362 
3363 	btrfs_item_key(right, &disk_key, 0);
3364 	fixup_low_keys(path, &disk_key, 1);
3365 
3366 	/* then fixup the leaf pointer in the path */
3367 	if (path->slots[0] < push_items) {
3368 		path->slots[0] += old_left_nritems;
3369 		btrfs_tree_unlock(path->nodes[0]);
3370 		free_extent_buffer(path->nodes[0]);
3371 		path->nodes[0] = left;
3372 		path->slots[1] -= 1;
3373 	} else {
3374 		btrfs_tree_unlock(left);
3375 		free_extent_buffer(left);
3376 		path->slots[0] -= push_items;
3377 	}
3378 	BUG_ON(path->slots[0] < 0);
3379 	return ret;
3380 out:
3381 	btrfs_tree_unlock(left);
3382 	free_extent_buffer(left);
3383 	return ret;
3384 }
3385 
3386 /*
3387  * push some data in the path leaf to the left, trying to free up at
3388  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
3389  *
3390  * max_slot can put a limit on how far into the leaf we'll push items.  The
3391  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
3392  * items
3393  */
3394 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
3395 			  *root, struct btrfs_path *path, int min_data_size,
3396 			  int data_size, int empty, u32 max_slot)
3397 {
3398 	struct extent_buffer *right = path->nodes[0];
3399 	struct extent_buffer *left;
3400 	int slot;
3401 	int free_space;
3402 	u32 right_nritems;
3403 	int ret = 0;
3404 
3405 	slot = path->slots[1];
3406 	if (slot == 0)
3407 		return 1;
3408 	if (!path->nodes[1])
3409 		return 1;
3410 
3411 	right_nritems = btrfs_header_nritems(right);
3412 	if (right_nritems == 0)
3413 		return 1;
3414 
3415 	btrfs_assert_tree_write_locked(path->nodes[1]);
3416 
3417 	left = btrfs_read_node_slot(path->nodes[1], slot - 1);
3418 	if (IS_ERR(left))
3419 		return PTR_ERR(left);
3420 
3421 	__btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
3422 
3423 	free_space = btrfs_leaf_free_space(left);
3424 	if (free_space < data_size) {
3425 		ret = 1;
3426 		goto out;
3427 	}
3428 
3429 	ret = btrfs_cow_block(trans, root, left,
3430 			      path->nodes[1], slot - 1, &left,
3431 			      BTRFS_NESTING_LEFT_COW);
3432 	if (ret) {
3433 		/* we hit -ENOSPC, but it isn't fatal here */
3434 		if (ret == -ENOSPC)
3435 			ret = 1;
3436 		goto out;
3437 	}
3438 
3439 	if (check_sibling_keys(left, right)) {
3440 		ret = -EUCLEAN;
3441 		btrfs_abort_transaction(trans, ret);
3442 		goto out;
3443 	}
3444 	return __push_leaf_left(trans, path, min_data_size, empty, left,
3445 				free_space, right_nritems, max_slot);
3446 out:
3447 	btrfs_tree_unlock(left);
3448 	free_extent_buffer(left);
3449 	return ret;
3450 }
3451 
3452 /*
3453  * split the path's leaf in two, making sure there is at least data_size
3454  * available for the resulting leaf level of the path.
3455  */
3456 static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3457 				    struct btrfs_path *path,
3458 				    struct extent_buffer *l,
3459 				    struct extent_buffer *right,
3460 				    int slot, int mid, int nritems)
3461 {
3462 	struct btrfs_fs_info *fs_info = trans->fs_info;
3463 	int data_copy_size;
3464 	int rt_data_off;
3465 	int i;
3466 	struct btrfs_disk_key disk_key;
3467 	struct btrfs_map_token token;
3468 
3469 	nritems = nritems - mid;
3470 	btrfs_set_header_nritems(right, nritems);
3471 	data_copy_size = btrfs_item_data_end(l, mid) - leaf_data_end(l);
3472 
3473 	copy_leaf_items(right, l, 0, mid, nritems);
3474 
3475 	copy_leaf_data(right, l, BTRFS_LEAF_DATA_SIZE(fs_info) - data_copy_size,
3476 		       leaf_data_end(l), data_copy_size);
3477 
3478 	rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_data_end(l, mid);
3479 
3480 	btrfs_init_map_token(&token, right);
3481 	for (i = 0; i < nritems; i++) {
3482 		u32 ioff;
3483 
3484 		ioff = btrfs_token_item_offset(&token, i);
3485 		btrfs_set_token_item_offset(&token, i, ioff + rt_data_off);
3486 	}
3487 
3488 	btrfs_set_header_nritems(l, mid);
3489 	btrfs_item_key(right, &disk_key, 0);
3490 	insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
3491 
3492 	btrfs_mark_buffer_dirty(right);
3493 	btrfs_mark_buffer_dirty(l);
3494 	BUG_ON(path->slots[0] != slot);
3495 
3496 	if (mid <= slot) {
3497 		btrfs_tree_unlock(path->nodes[0]);
3498 		free_extent_buffer(path->nodes[0]);
3499 		path->nodes[0] = right;
3500 		path->slots[0] -= mid;
3501 		path->slots[1] += 1;
3502 	} else {
3503 		btrfs_tree_unlock(right);
3504 		free_extent_buffer(right);
3505 	}
3506 
3507 	BUG_ON(path->slots[0] < 0);
3508 }
3509 
3510 /*
3511  * double splits happen when we need to insert a big item in the middle
3512  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
3513  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
3514  *          A                 B                 C
3515  *
3516  * We avoid this by trying to push the items on either side of our target
3517  * into the adjacent leaves.  If all goes well we can avoid the double split
3518  * completely.
3519  */
3520 static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
3521 					  struct btrfs_root *root,
3522 					  struct btrfs_path *path,
3523 					  int data_size)
3524 {
3525 	int ret;
3526 	int progress = 0;
3527 	int slot;
3528 	u32 nritems;
3529 	int space_needed = data_size;
3530 
3531 	slot = path->slots[0];
3532 	if (slot < btrfs_header_nritems(path->nodes[0]))
3533 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
3534 
3535 	/*
3536 	 * try to push all the items after our slot into the
3537 	 * right leaf
3538 	 */
3539 	ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
3540 	if (ret < 0)
3541 		return ret;
3542 
3543 	if (ret == 0)
3544 		progress++;
3545 
3546 	nritems = btrfs_header_nritems(path->nodes[0]);
3547 	/*
3548 	 * our goal is to get our slot at the start or end of a leaf.  If
3549 	 * we've done so we're done
3550 	 */
3551 	if (path->slots[0] == 0 || path->slots[0] == nritems)
3552 		return 0;
3553 
3554 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
3555 		return 0;
3556 
3557 	/* try to push all the items before our slot into the next leaf */
3558 	slot = path->slots[0];
3559 	space_needed = data_size;
3560 	if (slot > 0)
3561 		space_needed -= btrfs_leaf_free_space(path->nodes[0]);
3562 	ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
3563 	if (ret < 0)
3564 		return ret;
3565 
3566 	if (ret == 0)
3567 		progress++;
3568 
3569 	if (progress)
3570 		return 0;
3571 	return 1;
3572 }
3573 
3574 /*
3575  * split the path's leaf in two, making sure there is at least data_size
3576  * available for the resulting leaf level of the path.
3577  *
3578  * returns 0 if all went well and < 0 on failure.
3579  */
3580 static noinline int split_leaf(struct btrfs_trans_handle *trans,
3581 			       struct btrfs_root *root,
3582 			       const struct btrfs_key *ins_key,
3583 			       struct btrfs_path *path, int data_size,
3584 			       int extend)
3585 {
3586 	struct btrfs_disk_key disk_key;
3587 	struct extent_buffer *l;
3588 	u32 nritems;
3589 	int mid;
3590 	int slot;
3591 	struct extent_buffer *right;
3592 	struct btrfs_fs_info *fs_info = root->fs_info;
3593 	int ret = 0;
3594 	int wret;
3595 	int split;
3596 	int num_doubles = 0;
3597 	int tried_avoid_double = 0;
3598 
3599 	l = path->nodes[0];
3600 	slot = path->slots[0];
3601 	if (extend && data_size + btrfs_item_size(l, slot) +
3602 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
3603 		return -EOVERFLOW;
3604 
3605 	/* first try to make some room by pushing left and right */
3606 	if (data_size && path->nodes[1]) {
3607 		int space_needed = data_size;
3608 
3609 		if (slot < btrfs_header_nritems(l))
3610 			space_needed -= btrfs_leaf_free_space(l);
3611 
3612 		wret = push_leaf_right(trans, root, path, space_needed,
3613 				       space_needed, 0, 0);
3614 		if (wret < 0)
3615 			return wret;
3616 		if (wret) {
3617 			space_needed = data_size;
3618 			if (slot > 0)
3619 				space_needed -= btrfs_leaf_free_space(l);
3620 			wret = push_leaf_left(trans, root, path, space_needed,
3621 					      space_needed, 0, (u32)-1);
3622 			if (wret < 0)
3623 				return wret;
3624 		}
3625 		l = path->nodes[0];
3626 
3627 		/* did the pushes work? */
3628 		if (btrfs_leaf_free_space(l) >= data_size)
3629 			return 0;
3630 	}
3631 
3632 	if (!path->nodes[1]) {
3633 		ret = insert_new_root(trans, root, path, 1);
3634 		if (ret)
3635 			return ret;
3636 	}
3637 again:
3638 	split = 1;
3639 	l = path->nodes[0];
3640 	slot = path->slots[0];
3641 	nritems = btrfs_header_nritems(l);
3642 	mid = (nritems + 1) / 2;
3643 
3644 	if (mid <= slot) {
3645 		if (nritems == 1 ||
3646 		    leaf_space_used(l, mid, nritems - mid) + data_size >
3647 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
3648 			if (slot >= nritems) {
3649 				split = 0;
3650 			} else {
3651 				mid = slot;
3652 				if (mid != nritems &&
3653 				    leaf_space_used(l, mid, nritems - mid) +
3654 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
3655 					if (data_size && !tried_avoid_double)
3656 						goto push_for_double;
3657 					split = 2;
3658 				}
3659 			}
3660 		}
3661 	} else {
3662 		if (leaf_space_used(l, 0, mid) + data_size >
3663 			BTRFS_LEAF_DATA_SIZE(fs_info)) {
3664 			if (!extend && data_size && slot == 0) {
3665 				split = 0;
3666 			} else if ((extend || !data_size) && slot == 0) {
3667 				mid = 1;
3668 			} else {
3669 				mid = slot;
3670 				if (mid != nritems &&
3671 				    leaf_space_used(l, mid, nritems - mid) +
3672 				    data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
3673 					if (data_size && !tried_avoid_double)
3674 						goto push_for_double;
3675 					split = 2;
3676 				}
3677 			}
3678 		}
3679 	}
3680 
3681 	if (split == 0)
3682 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
3683 	else
3684 		btrfs_item_key(l, &disk_key, mid);
3685 
3686 	/*
3687 	 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
3688 	 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
3689 	 * subclasses, which is 8 at the time of this patch, and we've maxed it
3690 	 * out.  In the future we could add a
3691 	 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
3692 	 * use BTRFS_NESTING_NEW_ROOT.
3693 	 */
3694 	right = btrfs_alloc_tree_block(trans, root, 0, root->root_key.objectid,
3695 				       &disk_key, 0, l->start, 0,
3696 				       num_doubles ? BTRFS_NESTING_NEW_ROOT :
3697 				       BTRFS_NESTING_SPLIT);
3698 	if (IS_ERR(right))
3699 		return PTR_ERR(right);
3700 
3701 	root_add_used(root, fs_info->nodesize);
3702 
3703 	if (split == 0) {
3704 		if (mid <= slot) {
3705 			btrfs_set_header_nritems(right, 0);
3706 			insert_ptr(trans, path, &disk_key,
3707 				   right->start, path->slots[1] + 1, 1);
3708 			btrfs_tree_unlock(path->nodes[0]);
3709 			free_extent_buffer(path->nodes[0]);
3710 			path->nodes[0] = right;
3711 			path->slots[0] = 0;
3712 			path->slots[1] += 1;
3713 		} else {
3714 			btrfs_set_header_nritems(right, 0);
3715 			insert_ptr(trans, path, &disk_key,
3716 				   right->start, path->slots[1], 1);
3717 			btrfs_tree_unlock(path->nodes[0]);
3718 			free_extent_buffer(path->nodes[0]);
3719 			path->nodes[0] = right;
3720 			path->slots[0] = 0;
3721 			if (path->slots[1] == 0)
3722 				fixup_low_keys(path, &disk_key, 1);
3723 		}
3724 		/*
3725 		 * We create a new leaf 'right' for the required ins_len and
3726 		 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
3727 		 * the content of ins_len to 'right'.
3728 		 */
3729 		return ret;
3730 	}
3731 
3732 	copy_for_split(trans, path, l, right, slot, mid, nritems);
3733 
3734 	if (split == 2) {
3735 		BUG_ON(num_doubles != 0);
3736 		num_doubles++;
3737 		goto again;
3738 	}
3739 
3740 	return 0;
3741 
3742 push_for_double:
3743 	push_for_double_split(trans, root, path, data_size);
3744 	tried_avoid_double = 1;
3745 	if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
3746 		return 0;
3747 	goto again;
3748 }
3749 
3750 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3751 					 struct btrfs_root *root,
3752 					 struct btrfs_path *path, int ins_len)
3753 {
3754 	struct btrfs_key key;
3755 	struct extent_buffer *leaf;
3756 	struct btrfs_file_extent_item *fi;
3757 	u64 extent_len = 0;
3758 	u32 item_size;
3759 	int ret;
3760 
3761 	leaf = path->nodes[0];
3762 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3763 
3764 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3765 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3766 
3767 	if (btrfs_leaf_free_space(leaf) >= ins_len)
3768 		return 0;
3769 
3770 	item_size = btrfs_item_size(leaf, path->slots[0]);
3771 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3772 		fi = btrfs_item_ptr(leaf, path->slots[0],
3773 				    struct btrfs_file_extent_item);
3774 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3775 	}
3776 	btrfs_release_path(path);
3777 
3778 	path->keep_locks = 1;
3779 	path->search_for_split = 1;
3780 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3781 	path->search_for_split = 0;
3782 	if (ret > 0)
3783 		ret = -EAGAIN;
3784 	if (ret < 0)
3785 		goto err;
3786 
3787 	ret = -EAGAIN;
3788 	leaf = path->nodes[0];
3789 	/* if our item isn't there, return now */
3790 	if (item_size != btrfs_item_size(leaf, path->slots[0]))
3791 		goto err;
3792 
3793 	/* the leaf has  changed, it now has room.  return now */
3794 	if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
3795 		goto err;
3796 
3797 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3798 		fi = btrfs_item_ptr(leaf, path->slots[0],
3799 				    struct btrfs_file_extent_item);
3800 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3801 			goto err;
3802 	}
3803 
3804 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3805 	if (ret)
3806 		goto err;
3807 
3808 	path->keep_locks = 0;
3809 	btrfs_unlock_up_safe(path, 1);
3810 	return 0;
3811 err:
3812 	path->keep_locks = 0;
3813 	return ret;
3814 }
3815 
3816 static noinline int split_item(struct btrfs_path *path,
3817 			       const struct btrfs_key *new_key,
3818 			       unsigned long split_offset)
3819 {
3820 	struct extent_buffer *leaf;
3821 	int orig_slot, slot;
3822 	char *buf;
3823 	u32 nritems;
3824 	u32 item_size;
3825 	u32 orig_offset;
3826 	struct btrfs_disk_key disk_key;
3827 
3828 	leaf = path->nodes[0];
3829 	BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
3830 
3831 	orig_slot = path->slots[0];
3832 	orig_offset = btrfs_item_offset(leaf, path->slots[0]);
3833 	item_size = btrfs_item_size(leaf, path->slots[0]);
3834 
3835 	buf = kmalloc(item_size, GFP_NOFS);
3836 	if (!buf)
3837 		return -ENOMEM;
3838 
3839 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3840 			    path->slots[0]), item_size);
3841 
3842 	slot = path->slots[0] + 1;
3843 	nritems = btrfs_header_nritems(leaf);
3844 	if (slot != nritems) {
3845 		/* shift the items */
3846 		memmove_leaf_items(leaf, slot + 1, slot, nritems - slot);
3847 	}
3848 
3849 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3850 	btrfs_set_item_key(leaf, &disk_key, slot);
3851 
3852 	btrfs_set_item_offset(leaf, slot, orig_offset);
3853 	btrfs_set_item_size(leaf, slot, item_size - split_offset);
3854 
3855 	btrfs_set_item_offset(leaf, orig_slot,
3856 				 orig_offset + item_size - split_offset);
3857 	btrfs_set_item_size(leaf, orig_slot, split_offset);
3858 
3859 	btrfs_set_header_nritems(leaf, nritems + 1);
3860 
3861 	/* write the data for the start of the original item */
3862 	write_extent_buffer(leaf, buf,
3863 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3864 			    split_offset);
3865 
3866 	/* write the data for the new item */
3867 	write_extent_buffer(leaf, buf + split_offset,
3868 			    btrfs_item_ptr_offset(leaf, slot),
3869 			    item_size - split_offset);
3870 	btrfs_mark_buffer_dirty(leaf);
3871 
3872 	BUG_ON(btrfs_leaf_free_space(leaf) < 0);
3873 	kfree(buf);
3874 	return 0;
3875 }
3876 
3877 /*
3878  * This function splits a single item into two items,
3879  * giving 'new_key' to the new item and splitting the
3880  * old one at split_offset (from the start of the item).
3881  *
3882  * The path may be released by this operation.  After
3883  * the split, the path is pointing to the old item.  The
3884  * new item is going to be in the same node as the old one.
3885  *
3886  * Note, the item being split must be smaller enough to live alone on
3887  * a tree block with room for one extra struct btrfs_item
3888  *
3889  * This allows us to split the item in place, keeping a lock on the
3890  * leaf the entire time.
3891  */
3892 int btrfs_split_item(struct btrfs_trans_handle *trans,
3893 		     struct btrfs_root *root,
3894 		     struct btrfs_path *path,
3895 		     const struct btrfs_key *new_key,
3896 		     unsigned long split_offset)
3897 {
3898 	int ret;
3899 	ret = setup_leaf_for_split(trans, root, path,
3900 				   sizeof(struct btrfs_item));
3901 	if (ret)
3902 		return ret;
3903 
3904 	ret = split_item(path, new_key, split_offset);
3905 	return ret;
3906 }
3907 
3908 /*
3909  * make the item pointed to by the path smaller.  new_size indicates
3910  * how small to make it, and from_end tells us if we just chop bytes
3911  * off the end of the item or if we shift the item to chop bytes off
3912  * the front.
3913  */
3914 void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
3915 {
3916 	int slot;
3917 	struct extent_buffer *leaf;
3918 	u32 nritems;
3919 	unsigned int data_end;
3920 	unsigned int old_data_start;
3921 	unsigned int old_size;
3922 	unsigned int size_diff;
3923 	int i;
3924 	struct btrfs_map_token token;
3925 
3926 	leaf = path->nodes[0];
3927 	slot = path->slots[0];
3928 
3929 	old_size = btrfs_item_size(leaf, slot);
3930 	if (old_size == new_size)
3931 		return;
3932 
3933 	nritems = btrfs_header_nritems(leaf);
3934 	data_end = leaf_data_end(leaf);
3935 
3936 	old_data_start = btrfs_item_offset(leaf, slot);
3937 
3938 	size_diff = old_size - new_size;
3939 
3940 	BUG_ON(slot < 0);
3941 	BUG_ON(slot >= nritems);
3942 
3943 	/*
3944 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3945 	 */
3946 	/* first correct the data pointers */
3947 	btrfs_init_map_token(&token, leaf);
3948 	for (i = slot; i < nritems; i++) {
3949 		u32 ioff;
3950 
3951 		ioff = btrfs_token_item_offset(&token, i);
3952 		btrfs_set_token_item_offset(&token, i, ioff + size_diff);
3953 	}
3954 
3955 	/* shift the data */
3956 	if (from_end) {
3957 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
3958 				  old_data_start + new_size - data_end);
3959 	} else {
3960 		struct btrfs_disk_key disk_key;
3961 		u64 offset;
3962 
3963 		btrfs_item_key(leaf, &disk_key, slot);
3964 
3965 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3966 			unsigned long ptr;
3967 			struct btrfs_file_extent_item *fi;
3968 
3969 			fi = btrfs_item_ptr(leaf, slot,
3970 					    struct btrfs_file_extent_item);
3971 			fi = (struct btrfs_file_extent_item *)(
3972 			     (unsigned long)fi - size_diff);
3973 
3974 			if (btrfs_file_extent_type(leaf, fi) ==
3975 			    BTRFS_FILE_EXTENT_INLINE) {
3976 				ptr = btrfs_item_ptr_offset(leaf, slot);
3977 				memmove_extent_buffer(leaf, ptr,
3978 				      (unsigned long)fi,
3979 				      BTRFS_FILE_EXTENT_INLINE_DATA_START);
3980 			}
3981 		}
3982 
3983 		memmove_leaf_data(leaf, data_end + size_diff, data_end,
3984 				  old_data_start - data_end);
3985 
3986 		offset = btrfs_disk_key_offset(&disk_key);
3987 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3988 		btrfs_set_item_key(leaf, &disk_key, slot);
3989 		if (slot == 0)
3990 			fixup_low_keys(path, &disk_key, 1);
3991 	}
3992 
3993 	btrfs_set_item_size(leaf, slot, new_size);
3994 	btrfs_mark_buffer_dirty(leaf);
3995 
3996 	if (btrfs_leaf_free_space(leaf) < 0) {
3997 		btrfs_print_leaf(leaf);
3998 		BUG();
3999 	}
4000 }
4001 
4002 /*
4003  * make the item pointed to by the path bigger, data_size is the added size.
4004  */
4005 void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
4006 {
4007 	int slot;
4008 	struct extent_buffer *leaf;
4009 	u32 nritems;
4010 	unsigned int data_end;
4011 	unsigned int old_data;
4012 	unsigned int old_size;
4013 	int i;
4014 	struct btrfs_map_token token;
4015 
4016 	leaf = path->nodes[0];
4017 
4018 	nritems = btrfs_header_nritems(leaf);
4019 	data_end = leaf_data_end(leaf);
4020 
4021 	if (btrfs_leaf_free_space(leaf) < data_size) {
4022 		btrfs_print_leaf(leaf);
4023 		BUG();
4024 	}
4025 	slot = path->slots[0];
4026 	old_data = btrfs_item_data_end(leaf, slot);
4027 
4028 	BUG_ON(slot < 0);
4029 	if (slot >= nritems) {
4030 		btrfs_print_leaf(leaf);
4031 		btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
4032 			   slot, nritems);
4033 		BUG();
4034 	}
4035 
4036 	/*
4037 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4038 	 */
4039 	/* first correct the data pointers */
4040 	btrfs_init_map_token(&token, leaf);
4041 	for (i = slot; i < nritems; i++) {
4042 		u32 ioff;
4043 
4044 		ioff = btrfs_token_item_offset(&token, i);
4045 		btrfs_set_token_item_offset(&token, i, ioff - data_size);
4046 	}
4047 
4048 	/* shift the data */
4049 	memmove_leaf_data(leaf, data_end - data_size, data_end,
4050 			  old_data - data_end);
4051 
4052 	data_end = old_data;
4053 	old_size = btrfs_item_size(leaf, slot);
4054 	btrfs_set_item_size(leaf, slot, old_size + data_size);
4055 	btrfs_mark_buffer_dirty(leaf);
4056 
4057 	if (btrfs_leaf_free_space(leaf) < 0) {
4058 		btrfs_print_leaf(leaf);
4059 		BUG();
4060 	}
4061 }
4062 
4063 /*
4064  * Make space in the node before inserting one or more items.
4065  *
4066  * @root:	root we are inserting items to
4067  * @path:	points to the leaf/slot where we are going to insert new items
4068  * @batch:      information about the batch of items to insert
4069  *
4070  * Main purpose is to save stack depth by doing the bulk of the work in a
4071  * function that doesn't call btrfs_search_slot
4072  */
4073 static void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
4074 				   const struct btrfs_item_batch *batch)
4075 {
4076 	struct btrfs_fs_info *fs_info = root->fs_info;
4077 	int i;
4078 	u32 nritems;
4079 	unsigned int data_end;
4080 	struct btrfs_disk_key disk_key;
4081 	struct extent_buffer *leaf;
4082 	int slot;
4083 	struct btrfs_map_token token;
4084 	u32 total_size;
4085 
4086 	/*
4087 	 * Before anything else, update keys in the parent and other ancestors
4088 	 * if needed, then release the write locks on them, so that other tasks
4089 	 * can use them while we modify the leaf.
4090 	 */
4091 	if (path->slots[0] == 0) {
4092 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[0]);
4093 		fixup_low_keys(path, &disk_key, 1);
4094 	}
4095 	btrfs_unlock_up_safe(path, 1);
4096 
4097 	leaf = path->nodes[0];
4098 	slot = path->slots[0];
4099 
4100 	nritems = btrfs_header_nritems(leaf);
4101 	data_end = leaf_data_end(leaf);
4102 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4103 
4104 	if (btrfs_leaf_free_space(leaf) < total_size) {
4105 		btrfs_print_leaf(leaf);
4106 		btrfs_crit(fs_info, "not enough freespace need %u have %d",
4107 			   total_size, btrfs_leaf_free_space(leaf));
4108 		BUG();
4109 	}
4110 
4111 	btrfs_init_map_token(&token, leaf);
4112 	if (slot != nritems) {
4113 		unsigned int old_data = btrfs_item_data_end(leaf, slot);
4114 
4115 		if (old_data < data_end) {
4116 			btrfs_print_leaf(leaf);
4117 			btrfs_crit(fs_info,
4118 		"item at slot %d with data offset %u beyond data end of leaf %u",
4119 				   slot, old_data, data_end);
4120 			BUG();
4121 		}
4122 		/*
4123 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4124 		 */
4125 		/* first correct the data pointers */
4126 		for (i = slot; i < nritems; i++) {
4127 			u32 ioff;
4128 
4129 			ioff = btrfs_token_item_offset(&token, i);
4130 			btrfs_set_token_item_offset(&token, i,
4131 						       ioff - batch->total_data_size);
4132 		}
4133 		/* shift the items */
4134 		memmove_leaf_items(leaf, slot + batch->nr, slot, nritems - slot);
4135 
4136 		/* shift the data */
4137 		memmove_leaf_data(leaf, data_end - batch->total_data_size,
4138 				  data_end, old_data - data_end);
4139 		data_end = old_data;
4140 	}
4141 
4142 	/* setup the item for the new data */
4143 	for (i = 0; i < batch->nr; i++) {
4144 		btrfs_cpu_key_to_disk(&disk_key, &batch->keys[i]);
4145 		btrfs_set_item_key(leaf, &disk_key, slot + i);
4146 		data_end -= batch->data_sizes[i];
4147 		btrfs_set_token_item_offset(&token, slot + i, data_end);
4148 		btrfs_set_token_item_size(&token, slot + i, batch->data_sizes[i]);
4149 	}
4150 
4151 	btrfs_set_header_nritems(leaf, nritems + batch->nr);
4152 	btrfs_mark_buffer_dirty(leaf);
4153 
4154 	if (btrfs_leaf_free_space(leaf) < 0) {
4155 		btrfs_print_leaf(leaf);
4156 		BUG();
4157 	}
4158 }
4159 
4160 /*
4161  * Insert a new item into a leaf.
4162  *
4163  * @root:      The root of the btree.
4164  * @path:      A path pointing to the target leaf and slot.
4165  * @key:       The key of the new item.
4166  * @data_size: The size of the data associated with the new key.
4167  */
4168 void btrfs_setup_item_for_insert(struct btrfs_root *root,
4169 				 struct btrfs_path *path,
4170 				 const struct btrfs_key *key,
4171 				 u32 data_size)
4172 {
4173 	struct btrfs_item_batch batch;
4174 
4175 	batch.keys = key;
4176 	batch.data_sizes = &data_size;
4177 	batch.total_data_size = data_size;
4178 	batch.nr = 1;
4179 
4180 	setup_items_for_insert(root, path, &batch);
4181 }
4182 
4183 /*
4184  * Given a key and some data, insert items into the tree.
4185  * This does all the path init required, making room in the tree if needed.
4186  */
4187 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4188 			    struct btrfs_root *root,
4189 			    struct btrfs_path *path,
4190 			    const struct btrfs_item_batch *batch)
4191 {
4192 	int ret = 0;
4193 	int slot;
4194 	u32 total_size;
4195 
4196 	total_size = batch->total_data_size + (batch->nr * sizeof(struct btrfs_item));
4197 	ret = btrfs_search_slot(trans, root, &batch->keys[0], path, total_size, 1);
4198 	if (ret == 0)
4199 		return -EEXIST;
4200 	if (ret < 0)
4201 		return ret;
4202 
4203 	slot = path->slots[0];
4204 	BUG_ON(slot < 0);
4205 
4206 	setup_items_for_insert(root, path, batch);
4207 	return 0;
4208 }
4209 
4210 /*
4211  * Given a key and some data, insert an item into the tree.
4212  * This does all the path init required, making room in the tree if needed.
4213  */
4214 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4215 		      const struct btrfs_key *cpu_key, void *data,
4216 		      u32 data_size)
4217 {
4218 	int ret = 0;
4219 	struct btrfs_path *path;
4220 	struct extent_buffer *leaf;
4221 	unsigned long ptr;
4222 
4223 	path = btrfs_alloc_path();
4224 	if (!path)
4225 		return -ENOMEM;
4226 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
4227 	if (!ret) {
4228 		leaf = path->nodes[0];
4229 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4230 		write_extent_buffer(leaf, data, ptr, data_size);
4231 		btrfs_mark_buffer_dirty(leaf);
4232 	}
4233 	btrfs_free_path(path);
4234 	return ret;
4235 }
4236 
4237 /*
4238  * This function duplicates an item, giving 'new_key' to the new item.
4239  * It guarantees both items live in the same tree leaf and the new item is
4240  * contiguous with the original item.
4241  *
4242  * This allows us to split a file extent in place, keeping a lock on the leaf
4243  * the entire time.
4244  */
4245 int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4246 			 struct btrfs_root *root,
4247 			 struct btrfs_path *path,
4248 			 const struct btrfs_key *new_key)
4249 {
4250 	struct extent_buffer *leaf;
4251 	int ret;
4252 	u32 item_size;
4253 
4254 	leaf = path->nodes[0];
4255 	item_size = btrfs_item_size(leaf, path->slots[0]);
4256 	ret = setup_leaf_for_split(trans, root, path,
4257 				   item_size + sizeof(struct btrfs_item));
4258 	if (ret)
4259 		return ret;
4260 
4261 	path->slots[0]++;
4262 	btrfs_setup_item_for_insert(root, path, new_key, item_size);
4263 	leaf = path->nodes[0];
4264 	memcpy_extent_buffer(leaf,
4265 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
4266 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4267 			     item_size);
4268 	return 0;
4269 }
4270 
4271 /*
4272  * delete the pointer from a given node.
4273  *
4274  * the tree should have been previously balanced so the deletion does not
4275  * empty a node.
4276  */
4277 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4278 		    int level, int slot)
4279 {
4280 	struct extent_buffer *parent = path->nodes[level];
4281 	u32 nritems;
4282 	int ret;
4283 
4284 	nritems = btrfs_header_nritems(parent);
4285 	if (slot != nritems - 1) {
4286 		if (level) {
4287 			ret = btrfs_tree_mod_log_insert_move(parent, slot,
4288 					slot + 1, nritems - slot - 1);
4289 			BUG_ON(ret < 0);
4290 		}
4291 		memmove_extent_buffer(parent,
4292 			      btrfs_node_key_ptr_offset(parent, slot),
4293 			      btrfs_node_key_ptr_offset(parent, slot + 1),
4294 			      sizeof(struct btrfs_key_ptr) *
4295 			      (nritems - slot - 1));
4296 	} else if (level) {
4297 		ret = btrfs_tree_mod_log_insert_key(parent, slot,
4298 						    BTRFS_MOD_LOG_KEY_REMOVE);
4299 		BUG_ON(ret < 0);
4300 	}
4301 
4302 	nritems--;
4303 	btrfs_set_header_nritems(parent, nritems);
4304 	if (nritems == 0 && parent == root->node) {
4305 		BUG_ON(btrfs_header_level(root->node) != 1);
4306 		/* just turn the root into a leaf and break */
4307 		btrfs_set_header_level(root->node, 0);
4308 	} else if (slot == 0) {
4309 		struct btrfs_disk_key disk_key;
4310 
4311 		btrfs_node_key(parent, &disk_key, 0);
4312 		fixup_low_keys(path, &disk_key, level + 1);
4313 	}
4314 	btrfs_mark_buffer_dirty(parent);
4315 }
4316 
4317 /*
4318  * a helper function to delete the leaf pointed to by path->slots[1] and
4319  * path->nodes[1].
4320  *
4321  * This deletes the pointer in path->nodes[1] and frees the leaf
4322  * block extent.  zero is returned if it all worked out, < 0 otherwise.
4323  *
4324  * The path must have already been setup for deleting the leaf, including
4325  * all the proper balancing.  path->nodes[1] must be locked.
4326  */
4327 static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4328 				    struct btrfs_root *root,
4329 				    struct btrfs_path *path,
4330 				    struct extent_buffer *leaf)
4331 {
4332 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
4333 	del_ptr(root, path, 1, path->slots[1]);
4334 
4335 	/*
4336 	 * btrfs_free_extent is expensive, we want to make sure we
4337 	 * aren't holding any locks when we call it
4338 	 */
4339 	btrfs_unlock_up_safe(path, 0);
4340 
4341 	root_sub_used(root, leaf->len);
4342 
4343 	atomic_inc(&leaf->refs);
4344 	btrfs_free_tree_block(trans, btrfs_root_id(root), leaf, 0, 1);
4345 	free_extent_buffer_stale(leaf);
4346 }
4347 /*
4348  * delete the item at the leaf level in path.  If that empties
4349  * the leaf, remove it from the tree
4350  */
4351 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4352 		    struct btrfs_path *path, int slot, int nr)
4353 {
4354 	struct btrfs_fs_info *fs_info = root->fs_info;
4355 	struct extent_buffer *leaf;
4356 	int ret = 0;
4357 	int wret;
4358 	u32 nritems;
4359 
4360 	leaf = path->nodes[0];
4361 	nritems = btrfs_header_nritems(leaf);
4362 
4363 	if (slot + nr != nritems) {
4364 		const u32 last_off = btrfs_item_offset(leaf, slot + nr - 1);
4365 		const int data_end = leaf_data_end(leaf);
4366 		struct btrfs_map_token token;
4367 		u32 dsize = 0;
4368 		int i;
4369 
4370 		for (i = 0; i < nr; i++)
4371 			dsize += btrfs_item_size(leaf, slot + i);
4372 
4373 		memmove_leaf_data(leaf, data_end + dsize, data_end,
4374 				  last_off - data_end);
4375 
4376 		btrfs_init_map_token(&token, leaf);
4377 		for (i = slot + nr; i < nritems; i++) {
4378 			u32 ioff;
4379 
4380 			ioff = btrfs_token_item_offset(&token, i);
4381 			btrfs_set_token_item_offset(&token, i, ioff + dsize);
4382 		}
4383 
4384 		memmove_leaf_items(leaf, slot, slot + nr, nritems - slot - nr);
4385 	}
4386 	btrfs_set_header_nritems(leaf, nritems - nr);
4387 	nritems -= nr;
4388 
4389 	/* delete the leaf if we've emptied it */
4390 	if (nritems == 0) {
4391 		if (leaf == root->node) {
4392 			btrfs_set_header_level(leaf, 0);
4393 		} else {
4394 			btrfs_clear_buffer_dirty(trans, leaf);
4395 			btrfs_del_leaf(trans, root, path, leaf);
4396 		}
4397 	} else {
4398 		int used = leaf_space_used(leaf, 0, nritems);
4399 		if (slot == 0) {
4400 			struct btrfs_disk_key disk_key;
4401 
4402 			btrfs_item_key(leaf, &disk_key, 0);
4403 			fixup_low_keys(path, &disk_key, 1);
4404 		}
4405 
4406 		/*
4407 		 * Try to delete the leaf if it is mostly empty. We do this by
4408 		 * trying to move all its items into its left and right neighbours.
4409 		 * If we can't move all the items, then we don't delete it - it's
4410 		 * not ideal, but future insertions might fill the leaf with more
4411 		 * items, or items from other leaves might be moved later into our
4412 		 * leaf due to deletions on those leaves.
4413 		 */
4414 		if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
4415 			u32 min_push_space;
4416 
4417 			/* push_leaf_left fixes the path.
4418 			 * make sure the path still points to our leaf
4419 			 * for possible call to del_ptr below
4420 			 */
4421 			slot = path->slots[1];
4422 			atomic_inc(&leaf->refs);
4423 			/*
4424 			 * We want to be able to at least push one item to the
4425 			 * left neighbour leaf, and that's the first item.
4426 			 */
4427 			min_push_space = sizeof(struct btrfs_item) +
4428 				btrfs_item_size(leaf, 0);
4429 			wret = push_leaf_left(trans, root, path, 0,
4430 					      min_push_space, 1, (u32)-1);
4431 			if (wret < 0 && wret != -ENOSPC)
4432 				ret = wret;
4433 
4434 			if (path->nodes[0] == leaf &&
4435 			    btrfs_header_nritems(leaf)) {
4436 				/*
4437 				 * If we were not able to push all items from our
4438 				 * leaf to its left neighbour, then attempt to
4439 				 * either push all the remaining items to the
4440 				 * right neighbour or none. There's no advantage
4441 				 * in pushing only some items, instead of all, as
4442 				 * it's pointless to end up with a leaf having
4443 				 * too few items while the neighbours can be full
4444 				 * or nearly full.
4445 				 */
4446 				nritems = btrfs_header_nritems(leaf);
4447 				min_push_space = leaf_space_used(leaf, 0, nritems);
4448 				wret = push_leaf_right(trans, root, path, 0,
4449 						       min_push_space, 1, 0);
4450 				if (wret < 0 && wret != -ENOSPC)
4451 					ret = wret;
4452 			}
4453 
4454 			if (btrfs_header_nritems(leaf) == 0) {
4455 				path->slots[1] = slot;
4456 				btrfs_del_leaf(trans, root, path, leaf);
4457 				free_extent_buffer(leaf);
4458 				ret = 0;
4459 			} else {
4460 				/* if we're still in the path, make sure
4461 				 * we're dirty.  Otherwise, one of the
4462 				 * push_leaf functions must have already
4463 				 * dirtied this buffer
4464 				 */
4465 				if (path->nodes[0] == leaf)
4466 					btrfs_mark_buffer_dirty(leaf);
4467 				free_extent_buffer(leaf);
4468 			}
4469 		} else {
4470 			btrfs_mark_buffer_dirty(leaf);
4471 		}
4472 	}
4473 	return ret;
4474 }
4475 
4476 /*
4477  * search the tree again to find a leaf with lesser keys
4478  * returns 0 if it found something or 1 if there are no lesser leaves.
4479  * returns < 0 on io errors.
4480  *
4481  * This may release the path, and so you may lose any locks held at the
4482  * time you call it.
4483  */
4484 int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
4485 {
4486 	struct btrfs_key key;
4487 	struct btrfs_key orig_key;
4488 	struct btrfs_disk_key found_key;
4489 	int ret;
4490 
4491 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
4492 	orig_key = key;
4493 
4494 	if (key.offset > 0) {
4495 		key.offset--;
4496 	} else if (key.type > 0) {
4497 		key.type--;
4498 		key.offset = (u64)-1;
4499 	} else if (key.objectid > 0) {
4500 		key.objectid--;
4501 		key.type = (u8)-1;
4502 		key.offset = (u64)-1;
4503 	} else {
4504 		return 1;
4505 	}
4506 
4507 	btrfs_release_path(path);
4508 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4509 	if (ret <= 0)
4510 		return ret;
4511 
4512 	/*
4513 	 * Previous key not found. Even if we were at slot 0 of the leaf we had
4514 	 * before releasing the path and calling btrfs_search_slot(), we now may
4515 	 * be in a slot pointing to the same original key - this can happen if
4516 	 * after we released the path, one of more items were moved from a
4517 	 * sibling leaf into the front of the leaf we had due to an insertion
4518 	 * (see push_leaf_right()).
4519 	 * If we hit this case and our slot is > 0 and just decrement the slot
4520 	 * so that the caller does not process the same key again, which may or
4521 	 * may not break the caller, depending on its logic.
4522 	 */
4523 	if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
4524 		btrfs_item_key(path->nodes[0], &found_key, path->slots[0]);
4525 		ret = comp_keys(&found_key, &orig_key);
4526 		if (ret == 0) {
4527 			if (path->slots[0] > 0) {
4528 				path->slots[0]--;
4529 				return 0;
4530 			}
4531 			/*
4532 			 * At slot 0, same key as before, it means orig_key is
4533 			 * the lowest, leftmost, key in the tree. We're done.
4534 			 */
4535 			return 1;
4536 		}
4537 	}
4538 
4539 	btrfs_item_key(path->nodes[0], &found_key, 0);
4540 	ret = comp_keys(&found_key, &key);
4541 	/*
4542 	 * We might have had an item with the previous key in the tree right
4543 	 * before we released our path. And after we released our path, that
4544 	 * item might have been pushed to the first slot (0) of the leaf we
4545 	 * were holding due to a tree balance. Alternatively, an item with the
4546 	 * previous key can exist as the only element of a leaf (big fat item).
4547 	 * Therefore account for these 2 cases, so that our callers (like
4548 	 * btrfs_previous_item) don't miss an existing item with a key matching
4549 	 * the previous key we computed above.
4550 	 */
4551 	if (ret <= 0)
4552 		return 0;
4553 	return 1;
4554 }
4555 
4556 /*
4557  * A helper function to walk down the tree starting at min_key, and looking
4558  * for nodes or leaves that are have a minimum transaction id.
4559  * This is used by the btree defrag code, and tree logging
4560  *
4561  * This does not cow, but it does stuff the starting key it finds back
4562  * into min_key, so you can call btrfs_search_slot with cow=1 on the
4563  * key and get a writable path.
4564  *
4565  * This honors path->lowest_level to prevent descent past a given level
4566  * of the tree.
4567  *
4568  * min_trans indicates the oldest transaction that you are interested
4569  * in walking through.  Any nodes or leaves older than min_trans are
4570  * skipped over (without reading them).
4571  *
4572  * returns zero if something useful was found, < 0 on error and 1 if there
4573  * was nothing in the tree that matched the search criteria.
4574  */
4575 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
4576 			 struct btrfs_path *path,
4577 			 u64 min_trans)
4578 {
4579 	struct extent_buffer *cur;
4580 	struct btrfs_key found_key;
4581 	int slot;
4582 	int sret;
4583 	u32 nritems;
4584 	int level;
4585 	int ret = 1;
4586 	int keep_locks = path->keep_locks;
4587 
4588 	ASSERT(!path->nowait);
4589 	path->keep_locks = 1;
4590 again:
4591 	cur = btrfs_read_lock_root_node(root);
4592 	level = btrfs_header_level(cur);
4593 	WARN_ON(path->nodes[level]);
4594 	path->nodes[level] = cur;
4595 	path->locks[level] = BTRFS_READ_LOCK;
4596 
4597 	if (btrfs_header_generation(cur) < min_trans) {
4598 		ret = 1;
4599 		goto out;
4600 	}
4601 	while (1) {
4602 		nritems = btrfs_header_nritems(cur);
4603 		level = btrfs_header_level(cur);
4604 		sret = btrfs_bin_search(cur, 0, min_key, &slot);
4605 		if (sret < 0) {
4606 			ret = sret;
4607 			goto out;
4608 		}
4609 
4610 		/* at the lowest level, we're done, setup the path and exit */
4611 		if (level == path->lowest_level) {
4612 			if (slot >= nritems)
4613 				goto find_next_key;
4614 			ret = 0;
4615 			path->slots[level] = slot;
4616 			btrfs_item_key_to_cpu(cur, &found_key, slot);
4617 			goto out;
4618 		}
4619 		if (sret && slot > 0)
4620 			slot--;
4621 		/*
4622 		 * check this node pointer against the min_trans parameters.
4623 		 * If it is too old, skip to the next one.
4624 		 */
4625 		while (slot < nritems) {
4626 			u64 gen;
4627 
4628 			gen = btrfs_node_ptr_generation(cur, slot);
4629 			if (gen < min_trans) {
4630 				slot++;
4631 				continue;
4632 			}
4633 			break;
4634 		}
4635 find_next_key:
4636 		/*
4637 		 * we didn't find a candidate key in this node, walk forward
4638 		 * and find another one
4639 		 */
4640 		if (slot >= nritems) {
4641 			path->slots[level] = slot;
4642 			sret = btrfs_find_next_key(root, path, min_key, level,
4643 						  min_trans);
4644 			if (sret == 0) {
4645 				btrfs_release_path(path);
4646 				goto again;
4647 			} else {
4648 				goto out;
4649 			}
4650 		}
4651 		/* save our key for returning back */
4652 		btrfs_node_key_to_cpu(cur, &found_key, slot);
4653 		path->slots[level] = slot;
4654 		if (level == path->lowest_level) {
4655 			ret = 0;
4656 			goto out;
4657 		}
4658 		cur = btrfs_read_node_slot(cur, slot);
4659 		if (IS_ERR(cur)) {
4660 			ret = PTR_ERR(cur);
4661 			goto out;
4662 		}
4663 
4664 		btrfs_tree_read_lock(cur);
4665 
4666 		path->locks[level - 1] = BTRFS_READ_LOCK;
4667 		path->nodes[level - 1] = cur;
4668 		unlock_up(path, level, 1, 0, NULL);
4669 	}
4670 out:
4671 	path->keep_locks = keep_locks;
4672 	if (ret == 0) {
4673 		btrfs_unlock_up_safe(path, path->lowest_level + 1);
4674 		memcpy(min_key, &found_key, sizeof(found_key));
4675 	}
4676 	return ret;
4677 }
4678 
4679 /*
4680  * this is similar to btrfs_next_leaf, but does not try to preserve
4681  * and fixup the path.  It looks for and returns the next key in the
4682  * tree based on the current path and the min_trans parameters.
4683  *
4684  * 0 is returned if another key is found, < 0 if there are any errors
4685  * and 1 is returned if there are no higher keys in the tree
4686  *
4687  * path->keep_locks should be set to 1 on the search made before
4688  * calling this function.
4689  */
4690 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4691 			struct btrfs_key *key, int level, u64 min_trans)
4692 {
4693 	int slot;
4694 	struct extent_buffer *c;
4695 
4696 	WARN_ON(!path->keep_locks && !path->skip_locking);
4697 	while (level < BTRFS_MAX_LEVEL) {
4698 		if (!path->nodes[level])
4699 			return 1;
4700 
4701 		slot = path->slots[level] + 1;
4702 		c = path->nodes[level];
4703 next:
4704 		if (slot >= btrfs_header_nritems(c)) {
4705 			int ret;
4706 			int orig_lowest;
4707 			struct btrfs_key cur_key;
4708 			if (level + 1 >= BTRFS_MAX_LEVEL ||
4709 			    !path->nodes[level + 1])
4710 				return 1;
4711 
4712 			if (path->locks[level + 1] || path->skip_locking) {
4713 				level++;
4714 				continue;
4715 			}
4716 
4717 			slot = btrfs_header_nritems(c) - 1;
4718 			if (level == 0)
4719 				btrfs_item_key_to_cpu(c, &cur_key, slot);
4720 			else
4721 				btrfs_node_key_to_cpu(c, &cur_key, slot);
4722 
4723 			orig_lowest = path->lowest_level;
4724 			btrfs_release_path(path);
4725 			path->lowest_level = level;
4726 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
4727 						0, 0);
4728 			path->lowest_level = orig_lowest;
4729 			if (ret < 0)
4730 				return ret;
4731 
4732 			c = path->nodes[level];
4733 			slot = path->slots[level];
4734 			if (ret == 0)
4735 				slot++;
4736 			goto next;
4737 		}
4738 
4739 		if (level == 0)
4740 			btrfs_item_key_to_cpu(c, key, slot);
4741 		else {
4742 			u64 gen = btrfs_node_ptr_generation(c, slot);
4743 
4744 			if (gen < min_trans) {
4745 				slot++;
4746 				goto next;
4747 			}
4748 			btrfs_node_key_to_cpu(c, key, slot);
4749 		}
4750 		return 0;
4751 	}
4752 	return 1;
4753 }
4754 
4755 int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
4756 			u64 time_seq)
4757 {
4758 	int slot;
4759 	int level;
4760 	struct extent_buffer *c;
4761 	struct extent_buffer *next;
4762 	struct btrfs_fs_info *fs_info = root->fs_info;
4763 	struct btrfs_key key;
4764 	bool need_commit_sem = false;
4765 	u32 nritems;
4766 	int ret;
4767 	int i;
4768 
4769 	/*
4770 	 * The nowait semantics are used only for write paths, where we don't
4771 	 * use the tree mod log and sequence numbers.
4772 	 */
4773 	if (time_seq)
4774 		ASSERT(!path->nowait);
4775 
4776 	nritems = btrfs_header_nritems(path->nodes[0]);
4777 	if (nritems == 0)
4778 		return 1;
4779 
4780 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
4781 again:
4782 	level = 1;
4783 	next = NULL;
4784 	btrfs_release_path(path);
4785 
4786 	path->keep_locks = 1;
4787 
4788 	if (time_seq) {
4789 		ret = btrfs_search_old_slot(root, &key, path, time_seq);
4790 	} else {
4791 		if (path->need_commit_sem) {
4792 			path->need_commit_sem = 0;
4793 			need_commit_sem = true;
4794 			if (path->nowait) {
4795 				if (!down_read_trylock(&fs_info->commit_root_sem)) {
4796 					ret = -EAGAIN;
4797 					goto done;
4798 				}
4799 			} else {
4800 				down_read(&fs_info->commit_root_sem);
4801 			}
4802 		}
4803 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4804 	}
4805 	path->keep_locks = 0;
4806 
4807 	if (ret < 0)
4808 		goto done;
4809 
4810 	nritems = btrfs_header_nritems(path->nodes[0]);
4811 	/*
4812 	 * by releasing the path above we dropped all our locks.  A balance
4813 	 * could have added more items next to the key that used to be
4814 	 * at the very end of the block.  So, check again here and
4815 	 * advance the path if there are now more items available.
4816 	 */
4817 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4818 		if (ret == 0)
4819 			path->slots[0]++;
4820 		ret = 0;
4821 		goto done;
4822 	}
4823 	/*
4824 	 * So the above check misses one case:
4825 	 * - after releasing the path above, someone has removed the item that
4826 	 *   used to be at the very end of the block, and balance between leafs
4827 	 *   gets another one with bigger key.offset to replace it.
4828 	 *
4829 	 * This one should be returned as well, or we can get leaf corruption
4830 	 * later(esp. in __btrfs_drop_extents()).
4831 	 *
4832 	 * And a bit more explanation about this check,
4833 	 * with ret > 0, the key isn't found, the path points to the slot
4834 	 * where it should be inserted, so the path->slots[0] item must be the
4835 	 * bigger one.
4836 	 */
4837 	if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
4838 		ret = 0;
4839 		goto done;
4840 	}
4841 
4842 	while (level < BTRFS_MAX_LEVEL) {
4843 		if (!path->nodes[level]) {
4844 			ret = 1;
4845 			goto done;
4846 		}
4847 
4848 		slot = path->slots[level] + 1;
4849 		c = path->nodes[level];
4850 		if (slot >= btrfs_header_nritems(c)) {
4851 			level++;
4852 			if (level == BTRFS_MAX_LEVEL) {
4853 				ret = 1;
4854 				goto done;
4855 			}
4856 			continue;
4857 		}
4858 
4859 
4860 		/*
4861 		 * Our current level is where we're going to start from, and to
4862 		 * make sure lockdep doesn't complain we need to drop our locks
4863 		 * and nodes from 0 to our current level.
4864 		 */
4865 		for (i = 0; i < level; i++) {
4866 			if (path->locks[level]) {
4867 				btrfs_tree_read_unlock(path->nodes[i]);
4868 				path->locks[i] = 0;
4869 			}
4870 			free_extent_buffer(path->nodes[i]);
4871 			path->nodes[i] = NULL;
4872 		}
4873 
4874 		next = c;
4875 		ret = read_block_for_search(root, path, &next, level,
4876 					    slot, &key);
4877 		if (ret == -EAGAIN && !path->nowait)
4878 			goto again;
4879 
4880 		if (ret < 0) {
4881 			btrfs_release_path(path);
4882 			goto done;
4883 		}
4884 
4885 		if (!path->skip_locking) {
4886 			ret = btrfs_try_tree_read_lock(next);
4887 			if (!ret && path->nowait) {
4888 				ret = -EAGAIN;
4889 				goto done;
4890 			}
4891 			if (!ret && time_seq) {
4892 				/*
4893 				 * If we don't get the lock, we may be racing
4894 				 * with push_leaf_left, holding that lock while
4895 				 * itself waiting for the leaf we've currently
4896 				 * locked. To solve this situation, we give up
4897 				 * on our lock and cycle.
4898 				 */
4899 				free_extent_buffer(next);
4900 				btrfs_release_path(path);
4901 				cond_resched();
4902 				goto again;
4903 			}
4904 			if (!ret)
4905 				btrfs_tree_read_lock(next);
4906 		}
4907 		break;
4908 	}
4909 	path->slots[level] = slot;
4910 	while (1) {
4911 		level--;
4912 		path->nodes[level] = next;
4913 		path->slots[level] = 0;
4914 		if (!path->skip_locking)
4915 			path->locks[level] = BTRFS_READ_LOCK;
4916 		if (!level)
4917 			break;
4918 
4919 		ret = read_block_for_search(root, path, &next, level,
4920 					    0, &key);
4921 		if (ret == -EAGAIN && !path->nowait)
4922 			goto again;
4923 
4924 		if (ret < 0) {
4925 			btrfs_release_path(path);
4926 			goto done;
4927 		}
4928 
4929 		if (!path->skip_locking) {
4930 			if (path->nowait) {
4931 				if (!btrfs_try_tree_read_lock(next)) {
4932 					ret = -EAGAIN;
4933 					goto done;
4934 				}
4935 			} else {
4936 				btrfs_tree_read_lock(next);
4937 			}
4938 		}
4939 	}
4940 	ret = 0;
4941 done:
4942 	unlock_up(path, 0, 1, 0, NULL);
4943 	if (need_commit_sem) {
4944 		int ret2;
4945 
4946 		path->need_commit_sem = 1;
4947 		ret2 = finish_need_commit_sem_search(path);
4948 		up_read(&fs_info->commit_root_sem);
4949 		if (ret2)
4950 			ret = ret2;
4951 	}
4952 
4953 	return ret;
4954 }
4955 
4956 int btrfs_next_old_item(struct btrfs_root *root, struct btrfs_path *path, u64 time_seq)
4957 {
4958 	path->slots[0]++;
4959 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
4960 		return btrfs_next_old_leaf(root, path, time_seq);
4961 	return 0;
4962 }
4963 
4964 /*
4965  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
4966  * searching until it gets past min_objectid or finds an item of 'type'
4967  *
4968  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4969  */
4970 int btrfs_previous_item(struct btrfs_root *root,
4971 			struct btrfs_path *path, u64 min_objectid,
4972 			int type)
4973 {
4974 	struct btrfs_key found_key;
4975 	struct extent_buffer *leaf;
4976 	u32 nritems;
4977 	int ret;
4978 
4979 	while (1) {
4980 		if (path->slots[0] == 0) {
4981 			ret = btrfs_prev_leaf(root, path);
4982 			if (ret != 0)
4983 				return ret;
4984 		} else {
4985 			path->slots[0]--;
4986 		}
4987 		leaf = path->nodes[0];
4988 		nritems = btrfs_header_nritems(leaf);
4989 		if (nritems == 0)
4990 			return 1;
4991 		if (path->slots[0] == nritems)
4992 			path->slots[0]--;
4993 
4994 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4995 		if (found_key.objectid < min_objectid)
4996 			break;
4997 		if (found_key.type == type)
4998 			return 0;
4999 		if (found_key.objectid == min_objectid &&
5000 		    found_key.type < type)
5001 			break;
5002 	}
5003 	return 1;
5004 }
5005 
5006 /*
5007  * search in extent tree to find a previous Metadata/Data extent item with
5008  * min objecitd.
5009  *
5010  * returns 0 if something is found, 1 if nothing was found and < 0 on error
5011  */
5012 int btrfs_previous_extent_item(struct btrfs_root *root,
5013 			struct btrfs_path *path, u64 min_objectid)
5014 {
5015 	struct btrfs_key found_key;
5016 	struct extent_buffer *leaf;
5017 	u32 nritems;
5018 	int ret;
5019 
5020 	while (1) {
5021 		if (path->slots[0] == 0) {
5022 			ret = btrfs_prev_leaf(root, path);
5023 			if (ret != 0)
5024 				return ret;
5025 		} else {
5026 			path->slots[0]--;
5027 		}
5028 		leaf = path->nodes[0];
5029 		nritems = btrfs_header_nritems(leaf);
5030 		if (nritems == 0)
5031 			return 1;
5032 		if (path->slots[0] == nritems)
5033 			path->slots[0]--;
5034 
5035 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5036 		if (found_key.objectid < min_objectid)
5037 			break;
5038 		if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5039 		    found_key.type == BTRFS_METADATA_ITEM_KEY)
5040 			return 0;
5041 		if (found_key.objectid == min_objectid &&
5042 		    found_key.type < BTRFS_EXTENT_ITEM_KEY)
5043 			break;
5044 	}
5045 	return 1;
5046 }
5047 
5048 int __init btrfs_ctree_init(void)
5049 {
5050 	btrfs_path_cachep = kmem_cache_create("btrfs_path",
5051 			sizeof(struct btrfs_path), 0,
5052 			SLAB_MEM_SPREAD, NULL);
5053 	if (!btrfs_path_cachep)
5054 		return -ENOMEM;
5055 	return 0;
5056 }
5057 
5058 void __cold btrfs_ctree_exit(void)
5059 {
5060 	kmem_cache_destroy(btrfs_path_cachep);
5061 }
5062