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