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