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