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