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