xref: /openbmc/linux/fs/btrfs/backref.c (revision 88ffb665c894b1929b30b09e05506ff359d9fb89)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2011 STRATO.  All rights reserved.
4  */
5 
6 #include <linux/mm.h>
7 #include <linux/rbtree.h>
8 #include <trace/events/btrfs.h>
9 #include "ctree.h"
10 #include "disk-io.h"
11 #include "backref.h"
12 #include "ulist.h"
13 #include "transaction.h"
14 #include "delayed-ref.h"
15 #include "locking.h"
16 #include "misc.h"
17 #include "tree-mod-log.h"
18 #include "fs.h"
19 #include "accessors.h"
20 #include "extent-tree.h"
21 #include "relocation.h"
22 
23 /* Just arbitrary numbers so we can be sure one of these happened. */
24 #define BACKREF_FOUND_SHARED     6
25 #define BACKREF_FOUND_NOT_SHARED 7
26 
27 struct extent_inode_elem {
28 	u64 inum;
29 	u64 offset;
30 	u64 num_bytes;
31 	struct extent_inode_elem *next;
32 };
33 
34 static int check_extent_in_eb(struct btrfs_backref_walk_ctx *ctx,
35 			      const struct btrfs_key *key,
36 			      const struct extent_buffer *eb,
37 			      const struct btrfs_file_extent_item *fi,
38 			      struct extent_inode_elem **eie)
39 {
40 	const u64 data_len = btrfs_file_extent_num_bytes(eb, fi);
41 	u64 offset = key->offset;
42 	struct extent_inode_elem *e;
43 	const u64 *root_ids;
44 	int root_count;
45 	bool cached;
46 
47 	if (!btrfs_file_extent_compression(eb, fi) &&
48 	    !btrfs_file_extent_encryption(eb, fi) &&
49 	    !btrfs_file_extent_other_encoding(eb, fi)) {
50 		u64 data_offset;
51 
52 		data_offset = btrfs_file_extent_offset(eb, fi);
53 
54 		if (ctx->extent_item_pos < data_offset ||
55 		    ctx->extent_item_pos >= data_offset + data_len)
56 			return 1;
57 		offset += ctx->extent_item_pos - data_offset;
58 	}
59 
60 	if (!ctx->indirect_ref_iterator || !ctx->cache_lookup)
61 		goto add_inode_elem;
62 
63 	cached = ctx->cache_lookup(eb->start, ctx->user_ctx, &root_ids,
64 				   &root_count);
65 	if (!cached)
66 		goto add_inode_elem;
67 
68 	for (int i = 0; i < root_count; i++) {
69 		int ret;
70 
71 		ret = ctx->indirect_ref_iterator(key->objectid, offset,
72 						 data_len, root_ids[i],
73 						 ctx->user_ctx);
74 		if (ret)
75 			return ret;
76 	}
77 
78 add_inode_elem:
79 	e = kmalloc(sizeof(*e), GFP_NOFS);
80 	if (!e)
81 		return -ENOMEM;
82 
83 	e->next = *eie;
84 	e->inum = key->objectid;
85 	e->offset = offset;
86 	e->num_bytes = data_len;
87 	*eie = e;
88 
89 	return 0;
90 }
91 
92 static void free_inode_elem_list(struct extent_inode_elem *eie)
93 {
94 	struct extent_inode_elem *eie_next;
95 
96 	for (; eie; eie = eie_next) {
97 		eie_next = eie->next;
98 		kfree(eie);
99 	}
100 }
101 
102 static int find_extent_in_eb(struct btrfs_backref_walk_ctx *ctx,
103 			     const struct extent_buffer *eb,
104 			     struct extent_inode_elem **eie)
105 {
106 	u64 disk_byte;
107 	struct btrfs_key key;
108 	struct btrfs_file_extent_item *fi;
109 	int slot;
110 	int nritems;
111 	int extent_type;
112 	int ret;
113 
114 	/*
115 	 * from the shared data ref, we only have the leaf but we need
116 	 * the key. thus, we must look into all items and see that we
117 	 * find one (some) with a reference to our extent item.
118 	 */
119 	nritems = btrfs_header_nritems(eb);
120 	for (slot = 0; slot < nritems; ++slot) {
121 		btrfs_item_key_to_cpu(eb, &key, slot);
122 		if (key.type != BTRFS_EXTENT_DATA_KEY)
123 			continue;
124 		fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
125 		extent_type = btrfs_file_extent_type(eb, fi);
126 		if (extent_type == BTRFS_FILE_EXTENT_INLINE)
127 			continue;
128 		/* don't skip BTRFS_FILE_EXTENT_PREALLOC, we can handle that */
129 		disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
130 		if (disk_byte != ctx->bytenr)
131 			continue;
132 
133 		ret = check_extent_in_eb(ctx, &key, eb, fi, eie);
134 		if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
135 			return ret;
136 	}
137 
138 	return 0;
139 }
140 
141 struct preftree {
142 	struct rb_root_cached root;
143 	unsigned int count;
144 };
145 
146 #define PREFTREE_INIT	{ .root = RB_ROOT_CACHED, .count = 0 }
147 
148 struct preftrees {
149 	struct preftree direct;    /* BTRFS_SHARED_[DATA|BLOCK]_REF_KEY */
150 	struct preftree indirect;  /* BTRFS_[TREE_BLOCK|EXTENT_DATA]_REF_KEY */
151 	struct preftree indirect_missing_keys;
152 };
153 
154 /*
155  * Checks for a shared extent during backref search.
156  *
157  * The share_count tracks prelim_refs (direct and indirect) having a
158  * ref->count >0:
159  *  - incremented when a ref->count transitions to >0
160  *  - decremented when a ref->count transitions to <1
161  */
162 struct share_check {
163 	struct btrfs_backref_share_check_ctx *ctx;
164 	struct btrfs_root *root;
165 	u64 inum;
166 	u64 data_bytenr;
167 	u64 data_extent_gen;
168 	/*
169 	 * Counts number of inodes that refer to an extent (different inodes in
170 	 * the same root or different roots) that we could find. The sharedness
171 	 * check typically stops once this counter gets greater than 1, so it
172 	 * may not reflect the total number of inodes.
173 	 */
174 	int share_count;
175 	/*
176 	 * The number of times we found our inode refers to the data extent we
177 	 * are determining the sharedness. In other words, how many file extent
178 	 * items we could find for our inode that point to our target data
179 	 * extent. The value we get here after finishing the extent sharedness
180 	 * check may be smaller than reality, but if it ends up being greater
181 	 * than 1, then we know for sure the inode has multiple file extent
182 	 * items that point to our inode, and we can safely assume it's useful
183 	 * to cache the sharedness check result.
184 	 */
185 	int self_ref_count;
186 	bool have_delayed_delete_refs;
187 };
188 
189 static inline int extent_is_shared(struct share_check *sc)
190 {
191 	return (sc && sc->share_count > 1) ? BACKREF_FOUND_SHARED : 0;
192 }
193 
194 static struct kmem_cache *btrfs_prelim_ref_cache;
195 
196 int __init btrfs_prelim_ref_init(void)
197 {
198 	btrfs_prelim_ref_cache = kmem_cache_create("btrfs_prelim_ref",
199 					sizeof(struct prelim_ref),
200 					0,
201 					SLAB_MEM_SPREAD,
202 					NULL);
203 	if (!btrfs_prelim_ref_cache)
204 		return -ENOMEM;
205 	return 0;
206 }
207 
208 void __cold btrfs_prelim_ref_exit(void)
209 {
210 	kmem_cache_destroy(btrfs_prelim_ref_cache);
211 }
212 
213 static void free_pref(struct prelim_ref *ref)
214 {
215 	kmem_cache_free(btrfs_prelim_ref_cache, ref);
216 }
217 
218 /*
219  * Return 0 when both refs are for the same block (and can be merged).
220  * A -1 return indicates ref1 is a 'lower' block than ref2, while 1
221  * indicates a 'higher' block.
222  */
223 static int prelim_ref_compare(struct prelim_ref *ref1,
224 			      struct prelim_ref *ref2)
225 {
226 	if (ref1->level < ref2->level)
227 		return -1;
228 	if (ref1->level > ref2->level)
229 		return 1;
230 	if (ref1->root_id < ref2->root_id)
231 		return -1;
232 	if (ref1->root_id > ref2->root_id)
233 		return 1;
234 	if (ref1->key_for_search.type < ref2->key_for_search.type)
235 		return -1;
236 	if (ref1->key_for_search.type > ref2->key_for_search.type)
237 		return 1;
238 	if (ref1->key_for_search.objectid < ref2->key_for_search.objectid)
239 		return -1;
240 	if (ref1->key_for_search.objectid > ref2->key_for_search.objectid)
241 		return 1;
242 	if (ref1->key_for_search.offset < ref2->key_for_search.offset)
243 		return -1;
244 	if (ref1->key_for_search.offset > ref2->key_for_search.offset)
245 		return 1;
246 	if (ref1->parent < ref2->parent)
247 		return -1;
248 	if (ref1->parent > ref2->parent)
249 		return 1;
250 
251 	return 0;
252 }
253 
254 static void update_share_count(struct share_check *sc, int oldcount,
255 			       int newcount, struct prelim_ref *newref)
256 {
257 	if ((!sc) || (oldcount == 0 && newcount < 1))
258 		return;
259 
260 	if (oldcount > 0 && newcount < 1)
261 		sc->share_count--;
262 	else if (oldcount < 1 && newcount > 0)
263 		sc->share_count++;
264 
265 	if (newref->root_id == sc->root->root_key.objectid &&
266 	    newref->wanted_disk_byte == sc->data_bytenr &&
267 	    newref->key_for_search.objectid == sc->inum)
268 		sc->self_ref_count += newref->count;
269 }
270 
271 /*
272  * Add @newref to the @root rbtree, merging identical refs.
273  *
274  * Callers should assume that newref has been freed after calling.
275  */
276 static void prelim_ref_insert(const struct btrfs_fs_info *fs_info,
277 			      struct preftree *preftree,
278 			      struct prelim_ref *newref,
279 			      struct share_check *sc)
280 {
281 	struct rb_root_cached *root;
282 	struct rb_node **p;
283 	struct rb_node *parent = NULL;
284 	struct prelim_ref *ref;
285 	int result;
286 	bool leftmost = true;
287 
288 	root = &preftree->root;
289 	p = &root->rb_root.rb_node;
290 
291 	while (*p) {
292 		parent = *p;
293 		ref = rb_entry(parent, struct prelim_ref, rbnode);
294 		result = prelim_ref_compare(ref, newref);
295 		if (result < 0) {
296 			p = &(*p)->rb_left;
297 		} else if (result > 0) {
298 			p = &(*p)->rb_right;
299 			leftmost = false;
300 		} else {
301 			/* Identical refs, merge them and free @newref */
302 			struct extent_inode_elem *eie = ref->inode_list;
303 
304 			while (eie && eie->next)
305 				eie = eie->next;
306 
307 			if (!eie)
308 				ref->inode_list = newref->inode_list;
309 			else
310 				eie->next = newref->inode_list;
311 			trace_btrfs_prelim_ref_merge(fs_info, ref, newref,
312 						     preftree->count);
313 			/*
314 			 * A delayed ref can have newref->count < 0.
315 			 * The ref->count is updated to follow any
316 			 * BTRFS_[ADD|DROP]_DELAYED_REF actions.
317 			 */
318 			update_share_count(sc, ref->count,
319 					   ref->count + newref->count, newref);
320 			ref->count += newref->count;
321 			free_pref(newref);
322 			return;
323 		}
324 	}
325 
326 	update_share_count(sc, 0, newref->count, newref);
327 	preftree->count++;
328 	trace_btrfs_prelim_ref_insert(fs_info, newref, NULL, preftree->count);
329 	rb_link_node(&newref->rbnode, parent, p);
330 	rb_insert_color_cached(&newref->rbnode, root, leftmost);
331 }
332 
333 /*
334  * Release the entire tree.  We don't care about internal consistency so
335  * just free everything and then reset the tree root.
336  */
337 static void prelim_release(struct preftree *preftree)
338 {
339 	struct prelim_ref *ref, *next_ref;
340 
341 	rbtree_postorder_for_each_entry_safe(ref, next_ref,
342 					     &preftree->root.rb_root, rbnode) {
343 		free_inode_elem_list(ref->inode_list);
344 		free_pref(ref);
345 	}
346 
347 	preftree->root = RB_ROOT_CACHED;
348 	preftree->count = 0;
349 }
350 
351 /*
352  * the rules for all callers of this function are:
353  * - obtaining the parent is the goal
354  * - if you add a key, you must know that it is a correct key
355  * - if you cannot add the parent or a correct key, then we will look into the
356  *   block later to set a correct key
357  *
358  * delayed refs
359  * ============
360  *        backref type | shared | indirect | shared | indirect
361  * information         |   tree |     tree |   data |     data
362  * --------------------+--------+----------+--------+----------
363  *      parent logical |    y   |     -    |    -   |     -
364  *      key to resolve |    -   |     y    |    y   |     y
365  *  tree block logical |    -   |     -    |    -   |     -
366  *  root for resolving |    y   |     y    |    y   |     y
367  *
368  * - column 1:       we've the parent -> done
369  * - column 2, 3, 4: we use the key to find the parent
370  *
371  * on disk refs (inline or keyed)
372  * ==============================
373  *        backref type | shared | indirect | shared | indirect
374  * information         |   tree |     tree |   data |     data
375  * --------------------+--------+----------+--------+----------
376  *      parent logical |    y   |     -    |    y   |     -
377  *      key to resolve |    -   |     -    |    -   |     y
378  *  tree block logical |    y   |     y    |    y   |     y
379  *  root for resolving |    -   |     y    |    y   |     y
380  *
381  * - column 1, 3: we've the parent -> done
382  * - column 2:    we take the first key from the block to find the parent
383  *                (see add_missing_keys)
384  * - column 4:    we use the key to find the parent
385  *
386  * additional information that's available but not required to find the parent
387  * block might help in merging entries to gain some speed.
388  */
389 static int add_prelim_ref(const struct btrfs_fs_info *fs_info,
390 			  struct preftree *preftree, u64 root_id,
391 			  const struct btrfs_key *key, int level, u64 parent,
392 			  u64 wanted_disk_byte, int count,
393 			  struct share_check *sc, gfp_t gfp_mask)
394 {
395 	struct prelim_ref *ref;
396 
397 	if (root_id == BTRFS_DATA_RELOC_TREE_OBJECTID)
398 		return 0;
399 
400 	ref = kmem_cache_alloc(btrfs_prelim_ref_cache, gfp_mask);
401 	if (!ref)
402 		return -ENOMEM;
403 
404 	ref->root_id = root_id;
405 	if (key)
406 		ref->key_for_search = *key;
407 	else
408 		memset(&ref->key_for_search, 0, sizeof(ref->key_for_search));
409 
410 	ref->inode_list = NULL;
411 	ref->level = level;
412 	ref->count = count;
413 	ref->parent = parent;
414 	ref->wanted_disk_byte = wanted_disk_byte;
415 	prelim_ref_insert(fs_info, preftree, ref, sc);
416 	return extent_is_shared(sc);
417 }
418 
419 /* direct refs use root == 0, key == NULL */
420 static int add_direct_ref(const struct btrfs_fs_info *fs_info,
421 			  struct preftrees *preftrees, int level, u64 parent,
422 			  u64 wanted_disk_byte, int count,
423 			  struct share_check *sc, gfp_t gfp_mask)
424 {
425 	return add_prelim_ref(fs_info, &preftrees->direct, 0, NULL, level,
426 			      parent, wanted_disk_byte, count, sc, gfp_mask);
427 }
428 
429 /* indirect refs use parent == 0 */
430 static int add_indirect_ref(const struct btrfs_fs_info *fs_info,
431 			    struct preftrees *preftrees, u64 root_id,
432 			    const struct btrfs_key *key, int level,
433 			    u64 wanted_disk_byte, int count,
434 			    struct share_check *sc, gfp_t gfp_mask)
435 {
436 	struct preftree *tree = &preftrees->indirect;
437 
438 	if (!key)
439 		tree = &preftrees->indirect_missing_keys;
440 	return add_prelim_ref(fs_info, tree, root_id, key, level, 0,
441 			      wanted_disk_byte, count, sc, gfp_mask);
442 }
443 
444 static int is_shared_data_backref(struct preftrees *preftrees, u64 bytenr)
445 {
446 	struct rb_node **p = &preftrees->direct.root.rb_root.rb_node;
447 	struct rb_node *parent = NULL;
448 	struct prelim_ref *ref = NULL;
449 	struct prelim_ref target = {};
450 	int result;
451 
452 	target.parent = bytenr;
453 
454 	while (*p) {
455 		parent = *p;
456 		ref = rb_entry(parent, struct prelim_ref, rbnode);
457 		result = prelim_ref_compare(ref, &target);
458 
459 		if (result < 0)
460 			p = &(*p)->rb_left;
461 		else if (result > 0)
462 			p = &(*p)->rb_right;
463 		else
464 			return 1;
465 	}
466 	return 0;
467 }
468 
469 static int add_all_parents(struct btrfs_backref_walk_ctx *ctx,
470 			   struct btrfs_root *root, struct btrfs_path *path,
471 			   struct ulist *parents,
472 			   struct preftrees *preftrees, struct prelim_ref *ref,
473 			   int level)
474 {
475 	int ret = 0;
476 	int slot;
477 	struct extent_buffer *eb;
478 	struct btrfs_key key;
479 	struct btrfs_key *key_for_search = &ref->key_for_search;
480 	struct btrfs_file_extent_item *fi;
481 	struct extent_inode_elem *eie = NULL, *old = NULL;
482 	u64 disk_byte;
483 	u64 wanted_disk_byte = ref->wanted_disk_byte;
484 	u64 count = 0;
485 	u64 data_offset;
486 
487 	if (level != 0) {
488 		eb = path->nodes[level];
489 		ret = ulist_add(parents, eb->start, 0, GFP_NOFS);
490 		if (ret < 0)
491 			return ret;
492 		return 0;
493 	}
494 
495 	/*
496 	 * 1. We normally enter this function with the path already pointing to
497 	 *    the first item to check. But sometimes, we may enter it with
498 	 *    slot == nritems.
499 	 * 2. We are searching for normal backref but bytenr of this leaf
500 	 *    matches shared data backref
501 	 * 3. The leaf owner is not equal to the root we are searching
502 	 *
503 	 * For these cases, go to the next leaf before we continue.
504 	 */
505 	eb = path->nodes[0];
506 	if (path->slots[0] >= btrfs_header_nritems(eb) ||
507 	    is_shared_data_backref(preftrees, eb->start) ||
508 	    ref->root_id != btrfs_header_owner(eb)) {
509 		if (ctx->time_seq == BTRFS_SEQ_LAST)
510 			ret = btrfs_next_leaf(root, path);
511 		else
512 			ret = btrfs_next_old_leaf(root, path, ctx->time_seq);
513 	}
514 
515 	while (!ret && count < ref->count) {
516 		eb = path->nodes[0];
517 		slot = path->slots[0];
518 
519 		btrfs_item_key_to_cpu(eb, &key, slot);
520 
521 		if (key.objectid != key_for_search->objectid ||
522 		    key.type != BTRFS_EXTENT_DATA_KEY)
523 			break;
524 
525 		/*
526 		 * We are searching for normal backref but bytenr of this leaf
527 		 * matches shared data backref, OR
528 		 * the leaf owner is not equal to the root we are searching for
529 		 */
530 		if (slot == 0 &&
531 		    (is_shared_data_backref(preftrees, eb->start) ||
532 		     ref->root_id != btrfs_header_owner(eb))) {
533 			if (ctx->time_seq == BTRFS_SEQ_LAST)
534 				ret = btrfs_next_leaf(root, path);
535 			else
536 				ret = btrfs_next_old_leaf(root, path, ctx->time_seq);
537 			continue;
538 		}
539 		fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
540 		disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
541 		data_offset = btrfs_file_extent_offset(eb, fi);
542 
543 		if (disk_byte == wanted_disk_byte) {
544 			eie = NULL;
545 			old = NULL;
546 			if (ref->key_for_search.offset == key.offset - data_offset)
547 				count++;
548 			else
549 				goto next;
550 			if (!ctx->ignore_extent_item_pos) {
551 				ret = check_extent_in_eb(ctx, &key, eb, fi, &eie);
552 				if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
553 				    ret < 0)
554 					break;
555 			}
556 			if (ret > 0)
557 				goto next;
558 			ret = ulist_add_merge_ptr(parents, eb->start,
559 						  eie, (void **)&old, GFP_NOFS);
560 			if (ret < 0)
561 				break;
562 			if (!ret && !ctx->ignore_extent_item_pos) {
563 				while (old->next)
564 					old = old->next;
565 				old->next = eie;
566 			}
567 			eie = NULL;
568 		}
569 next:
570 		if (ctx->time_seq == BTRFS_SEQ_LAST)
571 			ret = btrfs_next_item(root, path);
572 		else
573 			ret = btrfs_next_old_item(root, path, ctx->time_seq);
574 	}
575 
576 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
577 		free_inode_elem_list(eie);
578 	else if (ret > 0)
579 		ret = 0;
580 
581 	return ret;
582 }
583 
584 /*
585  * resolve an indirect backref in the form (root_id, key, level)
586  * to a logical address
587  */
588 static int resolve_indirect_ref(struct btrfs_backref_walk_ctx *ctx,
589 				struct btrfs_path *path,
590 				struct preftrees *preftrees,
591 				struct prelim_ref *ref, struct ulist *parents)
592 {
593 	struct btrfs_root *root;
594 	struct extent_buffer *eb;
595 	int ret = 0;
596 	int root_level;
597 	int level = ref->level;
598 	struct btrfs_key search_key = ref->key_for_search;
599 
600 	/*
601 	 * If we're search_commit_root we could possibly be holding locks on
602 	 * other tree nodes.  This happens when qgroups does backref walks when
603 	 * adding new delayed refs.  To deal with this we need to look in cache
604 	 * for the root, and if we don't find it then we need to search the
605 	 * tree_root's commit root, thus the btrfs_get_fs_root_commit_root usage
606 	 * here.
607 	 */
608 	if (path->search_commit_root)
609 		root = btrfs_get_fs_root_commit_root(ctx->fs_info, path, ref->root_id);
610 	else
611 		root = btrfs_get_fs_root(ctx->fs_info, ref->root_id, false);
612 	if (IS_ERR(root)) {
613 		ret = PTR_ERR(root);
614 		goto out_free;
615 	}
616 
617 	if (!path->search_commit_root &&
618 	    test_bit(BTRFS_ROOT_DELETING, &root->state)) {
619 		ret = -ENOENT;
620 		goto out;
621 	}
622 
623 	if (btrfs_is_testing(ctx->fs_info)) {
624 		ret = -ENOENT;
625 		goto out;
626 	}
627 
628 	if (path->search_commit_root)
629 		root_level = btrfs_header_level(root->commit_root);
630 	else if (ctx->time_seq == BTRFS_SEQ_LAST)
631 		root_level = btrfs_header_level(root->node);
632 	else
633 		root_level = btrfs_old_root_level(root, ctx->time_seq);
634 
635 	if (root_level + 1 == level)
636 		goto out;
637 
638 	/*
639 	 * We can often find data backrefs with an offset that is too large
640 	 * (>= LLONG_MAX, maximum allowed file offset) due to underflows when
641 	 * subtracting a file's offset with the data offset of its
642 	 * corresponding extent data item. This can happen for example in the
643 	 * clone ioctl.
644 	 *
645 	 * So if we detect such case we set the search key's offset to zero to
646 	 * make sure we will find the matching file extent item at
647 	 * add_all_parents(), otherwise we will miss it because the offset
648 	 * taken form the backref is much larger then the offset of the file
649 	 * extent item. This can make us scan a very large number of file
650 	 * extent items, but at least it will not make us miss any.
651 	 *
652 	 * This is an ugly workaround for a behaviour that should have never
653 	 * existed, but it does and a fix for the clone ioctl would touch a lot
654 	 * of places, cause backwards incompatibility and would not fix the
655 	 * problem for extents cloned with older kernels.
656 	 */
657 	if (search_key.type == BTRFS_EXTENT_DATA_KEY &&
658 	    search_key.offset >= LLONG_MAX)
659 		search_key.offset = 0;
660 	path->lowest_level = level;
661 	if (ctx->time_seq == BTRFS_SEQ_LAST)
662 		ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
663 	else
664 		ret = btrfs_search_old_slot(root, &search_key, path, ctx->time_seq);
665 
666 	btrfs_debug(ctx->fs_info,
667 		"search slot in root %llu (level %d, ref count %d) returned %d for key (%llu %u %llu)",
668 		 ref->root_id, level, ref->count, ret,
669 		 ref->key_for_search.objectid, ref->key_for_search.type,
670 		 ref->key_for_search.offset);
671 	if (ret < 0)
672 		goto out;
673 
674 	eb = path->nodes[level];
675 	while (!eb) {
676 		if (WARN_ON(!level)) {
677 			ret = 1;
678 			goto out;
679 		}
680 		level--;
681 		eb = path->nodes[level];
682 	}
683 
684 	ret = add_all_parents(ctx, root, path, parents, preftrees, ref, level);
685 out:
686 	btrfs_put_root(root);
687 out_free:
688 	path->lowest_level = 0;
689 	btrfs_release_path(path);
690 	return ret;
691 }
692 
693 static struct extent_inode_elem *
694 unode_aux_to_inode_list(struct ulist_node *node)
695 {
696 	if (!node)
697 		return NULL;
698 	return (struct extent_inode_elem *)(uintptr_t)node->aux;
699 }
700 
701 static void free_leaf_list(struct ulist *ulist)
702 {
703 	struct ulist_node *node;
704 	struct ulist_iterator uiter;
705 
706 	ULIST_ITER_INIT(&uiter);
707 	while ((node = ulist_next(ulist, &uiter)))
708 		free_inode_elem_list(unode_aux_to_inode_list(node));
709 
710 	ulist_free(ulist);
711 }
712 
713 /*
714  * We maintain three separate rbtrees: one for direct refs, one for
715  * indirect refs which have a key, and one for indirect refs which do not
716  * have a key. Each tree does merge on insertion.
717  *
718  * Once all of the references are located, we iterate over the tree of
719  * indirect refs with missing keys. An appropriate key is located and
720  * the ref is moved onto the tree for indirect refs. After all missing
721  * keys are thus located, we iterate over the indirect ref tree, resolve
722  * each reference, and then insert the resolved reference onto the
723  * direct tree (merging there too).
724  *
725  * New backrefs (i.e., for parent nodes) are added to the appropriate
726  * rbtree as they are encountered. The new backrefs are subsequently
727  * resolved as above.
728  */
729 static int resolve_indirect_refs(struct btrfs_backref_walk_ctx *ctx,
730 				 struct btrfs_path *path,
731 				 struct preftrees *preftrees,
732 				 struct share_check *sc)
733 {
734 	int err;
735 	int ret = 0;
736 	struct ulist *parents;
737 	struct ulist_node *node;
738 	struct ulist_iterator uiter;
739 	struct rb_node *rnode;
740 
741 	parents = ulist_alloc(GFP_NOFS);
742 	if (!parents)
743 		return -ENOMEM;
744 
745 	/*
746 	 * We could trade memory usage for performance here by iterating
747 	 * the tree, allocating new refs for each insertion, and then
748 	 * freeing the entire indirect tree when we're done.  In some test
749 	 * cases, the tree can grow quite large (~200k objects).
750 	 */
751 	while ((rnode = rb_first_cached(&preftrees->indirect.root))) {
752 		struct prelim_ref *ref;
753 
754 		ref = rb_entry(rnode, struct prelim_ref, rbnode);
755 		if (WARN(ref->parent,
756 			 "BUG: direct ref found in indirect tree")) {
757 			ret = -EINVAL;
758 			goto out;
759 		}
760 
761 		rb_erase_cached(&ref->rbnode, &preftrees->indirect.root);
762 		preftrees->indirect.count--;
763 
764 		if (ref->count == 0) {
765 			free_pref(ref);
766 			continue;
767 		}
768 
769 		if (sc && ref->root_id != sc->root->root_key.objectid) {
770 			free_pref(ref);
771 			ret = BACKREF_FOUND_SHARED;
772 			goto out;
773 		}
774 		err = resolve_indirect_ref(ctx, path, preftrees, ref, parents);
775 		/*
776 		 * we can only tolerate ENOENT,otherwise,we should catch error
777 		 * and return directly.
778 		 */
779 		if (err == -ENOENT) {
780 			prelim_ref_insert(ctx->fs_info, &preftrees->direct, ref,
781 					  NULL);
782 			continue;
783 		} else if (err) {
784 			free_pref(ref);
785 			ret = err;
786 			goto out;
787 		}
788 
789 		/* we put the first parent into the ref at hand */
790 		ULIST_ITER_INIT(&uiter);
791 		node = ulist_next(parents, &uiter);
792 		ref->parent = node ? node->val : 0;
793 		ref->inode_list = unode_aux_to_inode_list(node);
794 
795 		/* Add a prelim_ref(s) for any other parent(s). */
796 		while ((node = ulist_next(parents, &uiter))) {
797 			struct prelim_ref *new_ref;
798 
799 			new_ref = kmem_cache_alloc(btrfs_prelim_ref_cache,
800 						   GFP_NOFS);
801 			if (!new_ref) {
802 				free_pref(ref);
803 				ret = -ENOMEM;
804 				goto out;
805 			}
806 			memcpy(new_ref, ref, sizeof(*ref));
807 			new_ref->parent = node->val;
808 			new_ref->inode_list = unode_aux_to_inode_list(node);
809 			prelim_ref_insert(ctx->fs_info, &preftrees->direct,
810 					  new_ref, NULL);
811 		}
812 
813 		/*
814 		 * Now it's a direct ref, put it in the direct tree. We must
815 		 * do this last because the ref could be merged/freed here.
816 		 */
817 		prelim_ref_insert(ctx->fs_info, &preftrees->direct, ref, NULL);
818 
819 		ulist_reinit(parents);
820 		cond_resched();
821 	}
822 out:
823 	/*
824 	 * We may have inode lists attached to refs in the parents ulist, so we
825 	 * must free them before freeing the ulist and its refs.
826 	 */
827 	free_leaf_list(parents);
828 	return ret;
829 }
830 
831 /*
832  * read tree blocks and add keys where required.
833  */
834 static int add_missing_keys(struct btrfs_fs_info *fs_info,
835 			    struct preftrees *preftrees, bool lock)
836 {
837 	struct prelim_ref *ref;
838 	struct extent_buffer *eb;
839 	struct preftree *tree = &preftrees->indirect_missing_keys;
840 	struct rb_node *node;
841 
842 	while ((node = rb_first_cached(&tree->root))) {
843 		ref = rb_entry(node, struct prelim_ref, rbnode);
844 		rb_erase_cached(node, &tree->root);
845 
846 		BUG_ON(ref->parent);	/* should not be a direct ref */
847 		BUG_ON(ref->key_for_search.type);
848 		BUG_ON(!ref->wanted_disk_byte);
849 
850 		eb = read_tree_block(fs_info, ref->wanted_disk_byte,
851 				     ref->root_id, 0, ref->level - 1, NULL);
852 		if (IS_ERR(eb)) {
853 			free_pref(ref);
854 			return PTR_ERR(eb);
855 		}
856 		if (!extent_buffer_uptodate(eb)) {
857 			free_pref(ref);
858 			free_extent_buffer(eb);
859 			return -EIO;
860 		}
861 
862 		if (lock)
863 			btrfs_tree_read_lock(eb);
864 		if (btrfs_header_level(eb) == 0)
865 			btrfs_item_key_to_cpu(eb, &ref->key_for_search, 0);
866 		else
867 			btrfs_node_key_to_cpu(eb, &ref->key_for_search, 0);
868 		if (lock)
869 			btrfs_tree_read_unlock(eb);
870 		free_extent_buffer(eb);
871 		prelim_ref_insert(fs_info, &preftrees->indirect, ref, NULL);
872 		cond_resched();
873 	}
874 	return 0;
875 }
876 
877 /*
878  * add all currently queued delayed refs from this head whose seq nr is
879  * smaller or equal that seq to the list
880  */
881 static int add_delayed_refs(const struct btrfs_fs_info *fs_info,
882 			    struct btrfs_delayed_ref_head *head, u64 seq,
883 			    struct preftrees *preftrees, struct share_check *sc)
884 {
885 	struct btrfs_delayed_ref_node *node;
886 	struct btrfs_key key;
887 	struct rb_node *n;
888 	int count;
889 	int ret = 0;
890 
891 	spin_lock(&head->lock);
892 	for (n = rb_first_cached(&head->ref_tree); n; n = rb_next(n)) {
893 		node = rb_entry(n, struct btrfs_delayed_ref_node,
894 				ref_node);
895 		if (node->seq > seq)
896 			continue;
897 
898 		switch (node->action) {
899 		case BTRFS_ADD_DELAYED_EXTENT:
900 		case BTRFS_UPDATE_DELAYED_HEAD:
901 			WARN_ON(1);
902 			continue;
903 		case BTRFS_ADD_DELAYED_REF:
904 			count = node->ref_mod;
905 			break;
906 		case BTRFS_DROP_DELAYED_REF:
907 			count = node->ref_mod * -1;
908 			break;
909 		default:
910 			BUG();
911 		}
912 		switch (node->type) {
913 		case BTRFS_TREE_BLOCK_REF_KEY: {
914 			/* NORMAL INDIRECT METADATA backref */
915 			struct btrfs_delayed_tree_ref *ref;
916 			struct btrfs_key *key_ptr = NULL;
917 
918 			if (head->extent_op && head->extent_op->update_key) {
919 				btrfs_disk_key_to_cpu(&key, &head->extent_op->key);
920 				key_ptr = &key;
921 			}
922 
923 			ref = btrfs_delayed_node_to_tree_ref(node);
924 			ret = add_indirect_ref(fs_info, preftrees, ref->root,
925 					       key_ptr, ref->level + 1,
926 					       node->bytenr, count, sc,
927 					       GFP_ATOMIC);
928 			break;
929 		}
930 		case BTRFS_SHARED_BLOCK_REF_KEY: {
931 			/* SHARED DIRECT METADATA backref */
932 			struct btrfs_delayed_tree_ref *ref;
933 
934 			ref = btrfs_delayed_node_to_tree_ref(node);
935 
936 			ret = add_direct_ref(fs_info, preftrees, ref->level + 1,
937 					     ref->parent, node->bytenr, count,
938 					     sc, GFP_ATOMIC);
939 			break;
940 		}
941 		case BTRFS_EXTENT_DATA_REF_KEY: {
942 			/* NORMAL INDIRECT DATA backref */
943 			struct btrfs_delayed_data_ref *ref;
944 			ref = btrfs_delayed_node_to_data_ref(node);
945 
946 			key.objectid = ref->objectid;
947 			key.type = BTRFS_EXTENT_DATA_KEY;
948 			key.offset = ref->offset;
949 
950 			/*
951 			 * If we have a share check context and a reference for
952 			 * another inode, we can't exit immediately. This is
953 			 * because even if this is a BTRFS_ADD_DELAYED_REF
954 			 * reference we may find next a BTRFS_DROP_DELAYED_REF
955 			 * which cancels out this ADD reference.
956 			 *
957 			 * If this is a DROP reference and there was no previous
958 			 * ADD reference, then we need to signal that when we
959 			 * process references from the extent tree (through
960 			 * add_inline_refs() and add_keyed_refs()), we should
961 			 * not exit early if we find a reference for another
962 			 * inode, because one of the delayed DROP references
963 			 * may cancel that reference in the extent tree.
964 			 */
965 			if (sc && count < 0)
966 				sc->have_delayed_delete_refs = true;
967 
968 			ret = add_indirect_ref(fs_info, preftrees, ref->root,
969 					       &key, 0, node->bytenr, count, sc,
970 					       GFP_ATOMIC);
971 			break;
972 		}
973 		case BTRFS_SHARED_DATA_REF_KEY: {
974 			/* SHARED DIRECT FULL backref */
975 			struct btrfs_delayed_data_ref *ref;
976 
977 			ref = btrfs_delayed_node_to_data_ref(node);
978 
979 			ret = add_direct_ref(fs_info, preftrees, 0, ref->parent,
980 					     node->bytenr, count, sc,
981 					     GFP_ATOMIC);
982 			break;
983 		}
984 		default:
985 			WARN_ON(1);
986 		}
987 		/*
988 		 * We must ignore BACKREF_FOUND_SHARED until all delayed
989 		 * refs have been checked.
990 		 */
991 		if (ret && (ret != BACKREF_FOUND_SHARED))
992 			break;
993 	}
994 	if (!ret)
995 		ret = extent_is_shared(sc);
996 
997 	spin_unlock(&head->lock);
998 	return ret;
999 }
1000 
1001 /*
1002  * add all inline backrefs for bytenr to the list
1003  *
1004  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
1005  */
1006 static int add_inline_refs(const struct btrfs_fs_info *fs_info,
1007 			   struct btrfs_path *path, u64 bytenr,
1008 			   int *info_level, struct preftrees *preftrees,
1009 			   struct share_check *sc)
1010 {
1011 	int ret = 0;
1012 	int slot;
1013 	struct extent_buffer *leaf;
1014 	struct btrfs_key key;
1015 	struct btrfs_key found_key;
1016 	unsigned long ptr;
1017 	unsigned long end;
1018 	struct btrfs_extent_item *ei;
1019 	u64 flags;
1020 	u64 item_size;
1021 
1022 	/*
1023 	 * enumerate all inline refs
1024 	 */
1025 	leaf = path->nodes[0];
1026 	slot = path->slots[0];
1027 
1028 	item_size = btrfs_item_size(leaf, slot);
1029 	BUG_ON(item_size < sizeof(*ei));
1030 
1031 	ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
1032 	flags = btrfs_extent_flags(leaf, ei);
1033 	btrfs_item_key_to_cpu(leaf, &found_key, slot);
1034 
1035 	ptr = (unsigned long)(ei + 1);
1036 	end = (unsigned long)ei + item_size;
1037 
1038 	if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
1039 	    flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1040 		struct btrfs_tree_block_info *info;
1041 
1042 		info = (struct btrfs_tree_block_info *)ptr;
1043 		*info_level = btrfs_tree_block_level(leaf, info);
1044 		ptr += sizeof(struct btrfs_tree_block_info);
1045 		BUG_ON(ptr > end);
1046 	} else if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
1047 		*info_level = found_key.offset;
1048 	} else {
1049 		BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
1050 	}
1051 
1052 	while (ptr < end) {
1053 		struct btrfs_extent_inline_ref *iref;
1054 		u64 offset;
1055 		int type;
1056 
1057 		iref = (struct btrfs_extent_inline_ref *)ptr;
1058 		type = btrfs_get_extent_inline_ref_type(leaf, iref,
1059 							BTRFS_REF_TYPE_ANY);
1060 		if (type == BTRFS_REF_TYPE_INVALID)
1061 			return -EUCLEAN;
1062 
1063 		offset = btrfs_extent_inline_ref_offset(leaf, iref);
1064 
1065 		switch (type) {
1066 		case BTRFS_SHARED_BLOCK_REF_KEY:
1067 			ret = add_direct_ref(fs_info, preftrees,
1068 					     *info_level + 1, offset,
1069 					     bytenr, 1, NULL, GFP_NOFS);
1070 			break;
1071 		case BTRFS_SHARED_DATA_REF_KEY: {
1072 			struct btrfs_shared_data_ref *sdref;
1073 			int count;
1074 
1075 			sdref = (struct btrfs_shared_data_ref *)(iref + 1);
1076 			count = btrfs_shared_data_ref_count(leaf, sdref);
1077 
1078 			ret = add_direct_ref(fs_info, preftrees, 0, offset,
1079 					     bytenr, count, sc, GFP_NOFS);
1080 			break;
1081 		}
1082 		case BTRFS_TREE_BLOCK_REF_KEY:
1083 			ret = add_indirect_ref(fs_info, preftrees, offset,
1084 					       NULL, *info_level + 1,
1085 					       bytenr, 1, NULL, GFP_NOFS);
1086 			break;
1087 		case BTRFS_EXTENT_DATA_REF_KEY: {
1088 			struct btrfs_extent_data_ref *dref;
1089 			int count;
1090 			u64 root;
1091 
1092 			dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1093 			count = btrfs_extent_data_ref_count(leaf, dref);
1094 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
1095 								      dref);
1096 			key.type = BTRFS_EXTENT_DATA_KEY;
1097 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1098 
1099 			if (sc && key.objectid != sc->inum &&
1100 			    !sc->have_delayed_delete_refs) {
1101 				ret = BACKREF_FOUND_SHARED;
1102 				break;
1103 			}
1104 
1105 			root = btrfs_extent_data_ref_root(leaf, dref);
1106 
1107 			ret = add_indirect_ref(fs_info, preftrees, root,
1108 					       &key, 0, bytenr, count,
1109 					       sc, GFP_NOFS);
1110 
1111 			break;
1112 		}
1113 		default:
1114 			WARN_ON(1);
1115 		}
1116 		if (ret)
1117 			return ret;
1118 		ptr += btrfs_extent_inline_ref_size(type);
1119 	}
1120 
1121 	return 0;
1122 }
1123 
1124 /*
1125  * add all non-inline backrefs for bytenr to the list
1126  *
1127  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
1128  */
1129 static int add_keyed_refs(struct btrfs_root *extent_root,
1130 			  struct btrfs_path *path, u64 bytenr,
1131 			  int info_level, struct preftrees *preftrees,
1132 			  struct share_check *sc)
1133 {
1134 	struct btrfs_fs_info *fs_info = extent_root->fs_info;
1135 	int ret;
1136 	int slot;
1137 	struct extent_buffer *leaf;
1138 	struct btrfs_key key;
1139 
1140 	while (1) {
1141 		ret = btrfs_next_item(extent_root, path);
1142 		if (ret < 0)
1143 			break;
1144 		if (ret) {
1145 			ret = 0;
1146 			break;
1147 		}
1148 
1149 		slot = path->slots[0];
1150 		leaf = path->nodes[0];
1151 		btrfs_item_key_to_cpu(leaf, &key, slot);
1152 
1153 		if (key.objectid != bytenr)
1154 			break;
1155 		if (key.type < BTRFS_TREE_BLOCK_REF_KEY)
1156 			continue;
1157 		if (key.type > BTRFS_SHARED_DATA_REF_KEY)
1158 			break;
1159 
1160 		switch (key.type) {
1161 		case BTRFS_SHARED_BLOCK_REF_KEY:
1162 			/* SHARED DIRECT METADATA backref */
1163 			ret = add_direct_ref(fs_info, preftrees,
1164 					     info_level + 1, key.offset,
1165 					     bytenr, 1, NULL, GFP_NOFS);
1166 			break;
1167 		case BTRFS_SHARED_DATA_REF_KEY: {
1168 			/* SHARED DIRECT FULL backref */
1169 			struct btrfs_shared_data_ref *sdref;
1170 			int count;
1171 
1172 			sdref = btrfs_item_ptr(leaf, slot,
1173 					      struct btrfs_shared_data_ref);
1174 			count = btrfs_shared_data_ref_count(leaf, sdref);
1175 			ret = add_direct_ref(fs_info, preftrees, 0,
1176 					     key.offset, bytenr, count,
1177 					     sc, GFP_NOFS);
1178 			break;
1179 		}
1180 		case BTRFS_TREE_BLOCK_REF_KEY:
1181 			/* NORMAL INDIRECT METADATA backref */
1182 			ret = add_indirect_ref(fs_info, preftrees, key.offset,
1183 					       NULL, info_level + 1, bytenr,
1184 					       1, NULL, GFP_NOFS);
1185 			break;
1186 		case BTRFS_EXTENT_DATA_REF_KEY: {
1187 			/* NORMAL INDIRECT DATA backref */
1188 			struct btrfs_extent_data_ref *dref;
1189 			int count;
1190 			u64 root;
1191 
1192 			dref = btrfs_item_ptr(leaf, slot,
1193 					      struct btrfs_extent_data_ref);
1194 			count = btrfs_extent_data_ref_count(leaf, dref);
1195 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
1196 								      dref);
1197 			key.type = BTRFS_EXTENT_DATA_KEY;
1198 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1199 
1200 			if (sc && key.objectid != sc->inum &&
1201 			    !sc->have_delayed_delete_refs) {
1202 				ret = BACKREF_FOUND_SHARED;
1203 				break;
1204 			}
1205 
1206 			root = btrfs_extent_data_ref_root(leaf, dref);
1207 			ret = add_indirect_ref(fs_info, preftrees, root,
1208 					       &key, 0, bytenr, count,
1209 					       sc, GFP_NOFS);
1210 			break;
1211 		}
1212 		default:
1213 			WARN_ON(1);
1214 		}
1215 		if (ret)
1216 			return ret;
1217 
1218 	}
1219 
1220 	return ret;
1221 }
1222 
1223 /*
1224  * The caller has joined a transaction or is holding a read lock on the
1225  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1226  * snapshot field changing while updating or checking the cache.
1227  */
1228 static bool lookup_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1229 					struct btrfs_root *root,
1230 					u64 bytenr, int level, bool *is_shared)
1231 {
1232 	struct btrfs_backref_shared_cache_entry *entry;
1233 
1234 	if (!ctx->use_path_cache)
1235 		return false;
1236 
1237 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1238 		return false;
1239 
1240 	/*
1241 	 * Level -1 is used for the data extent, which is not reliable to cache
1242 	 * because its reference count can increase or decrease without us
1243 	 * realizing. We cache results only for extent buffers that lead from
1244 	 * the root node down to the leaf with the file extent item.
1245 	 */
1246 	ASSERT(level >= 0);
1247 
1248 	entry = &ctx->path_cache_entries[level];
1249 
1250 	/* Unused cache entry or being used for some other extent buffer. */
1251 	if (entry->bytenr != bytenr)
1252 		return false;
1253 
1254 	/*
1255 	 * We cached a false result, but the last snapshot generation of the
1256 	 * root changed, so we now have a snapshot. Don't trust the result.
1257 	 */
1258 	if (!entry->is_shared &&
1259 	    entry->gen != btrfs_root_last_snapshot(&root->root_item))
1260 		return false;
1261 
1262 	/*
1263 	 * If we cached a true result and the last generation used for dropping
1264 	 * a root changed, we can not trust the result, because the dropped root
1265 	 * could be a snapshot sharing this extent buffer.
1266 	 */
1267 	if (entry->is_shared &&
1268 	    entry->gen != btrfs_get_last_root_drop_gen(root->fs_info))
1269 		return false;
1270 
1271 	*is_shared = entry->is_shared;
1272 	/*
1273 	 * If the node at this level is shared, than all nodes below are also
1274 	 * shared. Currently some of the nodes below may be marked as not shared
1275 	 * because we have just switched from one leaf to another, and switched
1276 	 * also other nodes above the leaf and below the current level, so mark
1277 	 * them as shared.
1278 	 */
1279 	if (*is_shared) {
1280 		for (int i = 0; i < level; i++) {
1281 			ctx->path_cache_entries[i].is_shared = true;
1282 			ctx->path_cache_entries[i].gen = entry->gen;
1283 		}
1284 	}
1285 
1286 	return true;
1287 }
1288 
1289 /*
1290  * The caller has joined a transaction or is holding a read lock on the
1291  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1292  * snapshot field changing while updating or checking the cache.
1293  */
1294 static void store_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1295 				       struct btrfs_root *root,
1296 				       u64 bytenr, int level, bool is_shared)
1297 {
1298 	struct btrfs_backref_shared_cache_entry *entry;
1299 	u64 gen;
1300 
1301 	if (!ctx->use_path_cache)
1302 		return;
1303 
1304 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1305 		return;
1306 
1307 	/*
1308 	 * Level -1 is used for the data extent, which is not reliable to cache
1309 	 * because its reference count can increase or decrease without us
1310 	 * realizing. We cache results only for extent buffers that lead from
1311 	 * the root node down to the leaf with the file extent item.
1312 	 */
1313 	ASSERT(level >= 0);
1314 
1315 	if (is_shared)
1316 		gen = btrfs_get_last_root_drop_gen(root->fs_info);
1317 	else
1318 		gen = btrfs_root_last_snapshot(&root->root_item);
1319 
1320 	entry = &ctx->path_cache_entries[level];
1321 	entry->bytenr = bytenr;
1322 	entry->is_shared = is_shared;
1323 	entry->gen = gen;
1324 
1325 	/*
1326 	 * If we found an extent buffer is shared, set the cache result for all
1327 	 * extent buffers below it to true. As nodes in the path are COWed,
1328 	 * their sharedness is moved to their children, and if a leaf is COWed,
1329 	 * then the sharedness of a data extent becomes direct, the refcount of
1330 	 * data extent is increased in the extent item at the extent tree.
1331 	 */
1332 	if (is_shared) {
1333 		for (int i = 0; i < level; i++) {
1334 			entry = &ctx->path_cache_entries[i];
1335 			entry->is_shared = is_shared;
1336 			entry->gen = gen;
1337 		}
1338 	}
1339 }
1340 
1341 /*
1342  * this adds all existing backrefs (inline backrefs, backrefs and delayed
1343  * refs) for the given bytenr to the refs list, merges duplicates and resolves
1344  * indirect refs to their parent bytenr.
1345  * When roots are found, they're added to the roots list
1346  *
1347  * @ctx:     Backref walking context object, must be not NULL.
1348  * @sc:      If !NULL, then immediately return BACKREF_FOUND_SHARED when a
1349  *           shared extent is detected.
1350  *
1351  * Otherwise this returns 0 for success and <0 for an error.
1352  *
1353  * FIXME some caching might speed things up
1354  */
1355 static int find_parent_nodes(struct btrfs_backref_walk_ctx *ctx,
1356 			     struct share_check *sc)
1357 {
1358 	struct btrfs_root *root = btrfs_extent_root(ctx->fs_info, ctx->bytenr);
1359 	struct btrfs_key key;
1360 	struct btrfs_path *path;
1361 	struct btrfs_delayed_ref_root *delayed_refs = NULL;
1362 	struct btrfs_delayed_ref_head *head;
1363 	int info_level = 0;
1364 	int ret;
1365 	struct prelim_ref *ref;
1366 	struct rb_node *node;
1367 	struct extent_inode_elem *eie = NULL;
1368 	struct preftrees preftrees = {
1369 		.direct = PREFTREE_INIT,
1370 		.indirect = PREFTREE_INIT,
1371 		.indirect_missing_keys = PREFTREE_INIT
1372 	};
1373 
1374 	/* Roots ulist is not needed when using a sharedness check context. */
1375 	if (sc)
1376 		ASSERT(ctx->roots == NULL);
1377 
1378 	key.objectid = ctx->bytenr;
1379 	key.offset = (u64)-1;
1380 	if (btrfs_fs_incompat(ctx->fs_info, SKINNY_METADATA))
1381 		key.type = BTRFS_METADATA_ITEM_KEY;
1382 	else
1383 		key.type = BTRFS_EXTENT_ITEM_KEY;
1384 
1385 	path = btrfs_alloc_path();
1386 	if (!path)
1387 		return -ENOMEM;
1388 	if (!ctx->trans) {
1389 		path->search_commit_root = 1;
1390 		path->skip_locking = 1;
1391 	}
1392 
1393 	if (ctx->time_seq == BTRFS_SEQ_LAST)
1394 		path->skip_locking = 1;
1395 
1396 again:
1397 	head = NULL;
1398 
1399 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1400 	if (ret < 0)
1401 		goto out;
1402 	if (ret == 0) {
1403 		/* This shouldn't happen, indicates a bug or fs corruption. */
1404 		ASSERT(ret != 0);
1405 		ret = -EUCLEAN;
1406 		goto out;
1407 	}
1408 
1409 	if (ctx->trans && likely(ctx->trans->type != __TRANS_DUMMY) &&
1410 	    ctx->time_seq != BTRFS_SEQ_LAST) {
1411 		/*
1412 		 * We have a specific time_seq we care about and trans which
1413 		 * means we have the path lock, we need to grab the ref head and
1414 		 * lock it so we have a consistent view of the refs at the given
1415 		 * time.
1416 		 */
1417 		delayed_refs = &ctx->trans->transaction->delayed_refs;
1418 		spin_lock(&delayed_refs->lock);
1419 		head = btrfs_find_delayed_ref_head(delayed_refs, ctx->bytenr);
1420 		if (head) {
1421 			if (!mutex_trylock(&head->mutex)) {
1422 				refcount_inc(&head->refs);
1423 				spin_unlock(&delayed_refs->lock);
1424 
1425 				btrfs_release_path(path);
1426 
1427 				/*
1428 				 * Mutex was contended, block until it's
1429 				 * released and try again
1430 				 */
1431 				mutex_lock(&head->mutex);
1432 				mutex_unlock(&head->mutex);
1433 				btrfs_put_delayed_ref_head(head);
1434 				goto again;
1435 			}
1436 			spin_unlock(&delayed_refs->lock);
1437 			ret = add_delayed_refs(ctx->fs_info, head, ctx->time_seq,
1438 					       &preftrees, sc);
1439 			mutex_unlock(&head->mutex);
1440 			if (ret)
1441 				goto out;
1442 		} else {
1443 			spin_unlock(&delayed_refs->lock);
1444 		}
1445 	}
1446 
1447 	if (path->slots[0]) {
1448 		struct extent_buffer *leaf;
1449 		int slot;
1450 
1451 		path->slots[0]--;
1452 		leaf = path->nodes[0];
1453 		slot = path->slots[0];
1454 		btrfs_item_key_to_cpu(leaf, &key, slot);
1455 		if (key.objectid == ctx->bytenr &&
1456 		    (key.type == BTRFS_EXTENT_ITEM_KEY ||
1457 		     key.type == BTRFS_METADATA_ITEM_KEY)) {
1458 			ret = add_inline_refs(ctx->fs_info, path, ctx->bytenr,
1459 					      &info_level, &preftrees, sc);
1460 			if (ret)
1461 				goto out;
1462 			ret = add_keyed_refs(root, path, ctx->bytenr, info_level,
1463 					     &preftrees, sc);
1464 			if (ret)
1465 				goto out;
1466 		}
1467 	}
1468 
1469 	/*
1470 	 * If we have a share context and we reached here, it means the extent
1471 	 * is not directly shared (no multiple reference items for it),
1472 	 * otherwise we would have exited earlier with a return value of
1473 	 * BACKREF_FOUND_SHARED after processing delayed references or while
1474 	 * processing inline or keyed references from the extent tree.
1475 	 * The extent may however be indirectly shared through shared subtrees
1476 	 * as a result from creating snapshots, so we determine below what is
1477 	 * its parent node, in case we are dealing with a metadata extent, or
1478 	 * what's the leaf (or leaves), from a fs tree, that has a file extent
1479 	 * item pointing to it in case we are dealing with a data extent.
1480 	 */
1481 	ASSERT(extent_is_shared(sc) == 0);
1482 
1483 	/*
1484 	 * If we are here for a data extent and we have a share_check structure
1485 	 * it means the data extent is not directly shared (does not have
1486 	 * multiple reference items), so we have to check if a path in the fs
1487 	 * tree (going from the root node down to the leaf that has the file
1488 	 * extent item pointing to the data extent) is shared, that is, if any
1489 	 * of the extent buffers in the path is referenced by other trees.
1490 	 */
1491 	if (sc && ctx->bytenr == sc->data_bytenr) {
1492 		/*
1493 		 * If our data extent is from a generation more recent than the
1494 		 * last generation used to snapshot the root, then we know that
1495 		 * it can not be shared through subtrees, so we can skip
1496 		 * resolving indirect references, there's no point in
1497 		 * determining the extent buffers for the path from the fs tree
1498 		 * root node down to the leaf that has the file extent item that
1499 		 * points to the data extent.
1500 		 */
1501 		if (sc->data_extent_gen >
1502 		    btrfs_root_last_snapshot(&sc->root->root_item)) {
1503 			ret = BACKREF_FOUND_NOT_SHARED;
1504 			goto out;
1505 		}
1506 
1507 		/*
1508 		 * If we are only determining if a data extent is shared or not
1509 		 * and the corresponding file extent item is located in the same
1510 		 * leaf as the previous file extent item, we can skip resolving
1511 		 * indirect references for a data extent, since the fs tree path
1512 		 * is the same (same leaf, so same path). We skip as long as the
1513 		 * cached result for the leaf is valid and only if there's only
1514 		 * one file extent item pointing to the data extent, because in
1515 		 * the case of multiple file extent items, they may be located
1516 		 * in different leaves and therefore we have multiple paths.
1517 		 */
1518 		if (sc->ctx->curr_leaf_bytenr == sc->ctx->prev_leaf_bytenr &&
1519 		    sc->self_ref_count == 1) {
1520 			bool cached;
1521 			bool is_shared;
1522 
1523 			cached = lookup_backref_shared_cache(sc->ctx, sc->root,
1524 						     sc->ctx->curr_leaf_bytenr,
1525 						     0, &is_shared);
1526 			if (cached) {
1527 				if (is_shared)
1528 					ret = BACKREF_FOUND_SHARED;
1529 				else
1530 					ret = BACKREF_FOUND_NOT_SHARED;
1531 				goto out;
1532 			}
1533 		}
1534 	}
1535 
1536 	btrfs_release_path(path);
1537 
1538 	ret = add_missing_keys(ctx->fs_info, &preftrees, path->skip_locking == 0);
1539 	if (ret)
1540 		goto out;
1541 
1542 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect_missing_keys.root.rb_root));
1543 
1544 	ret = resolve_indirect_refs(ctx, path, &preftrees, sc);
1545 	if (ret)
1546 		goto out;
1547 
1548 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect.root.rb_root));
1549 
1550 	/*
1551 	 * This walks the tree of merged and resolved refs. Tree blocks are
1552 	 * read in as needed. Unique entries are added to the ulist, and
1553 	 * the list of found roots is updated.
1554 	 *
1555 	 * We release the entire tree in one go before returning.
1556 	 */
1557 	node = rb_first_cached(&preftrees.direct.root);
1558 	while (node) {
1559 		ref = rb_entry(node, struct prelim_ref, rbnode);
1560 		node = rb_next(&ref->rbnode);
1561 		/*
1562 		 * ref->count < 0 can happen here if there are delayed
1563 		 * refs with a node->action of BTRFS_DROP_DELAYED_REF.
1564 		 * prelim_ref_insert() relies on this when merging
1565 		 * identical refs to keep the overall count correct.
1566 		 * prelim_ref_insert() will merge only those refs
1567 		 * which compare identically.  Any refs having
1568 		 * e.g. different offsets would not be merged,
1569 		 * and would retain their original ref->count < 0.
1570 		 */
1571 		if (ctx->roots && ref->count && ref->root_id && ref->parent == 0) {
1572 			/* no parent == root of tree */
1573 			ret = ulist_add(ctx->roots, ref->root_id, 0, GFP_NOFS);
1574 			if (ret < 0)
1575 				goto out;
1576 		}
1577 		if (ref->count && ref->parent) {
1578 			if (!ctx->ignore_extent_item_pos && !ref->inode_list &&
1579 			    ref->level == 0) {
1580 				struct extent_buffer *eb;
1581 
1582 				eb = read_tree_block(ctx->fs_info, ref->parent, 0,
1583 						     0, ref->level, NULL);
1584 				if (IS_ERR(eb)) {
1585 					ret = PTR_ERR(eb);
1586 					goto out;
1587 				}
1588 				if (!extent_buffer_uptodate(eb)) {
1589 					free_extent_buffer(eb);
1590 					ret = -EIO;
1591 					goto out;
1592 				}
1593 
1594 				if (!path->skip_locking)
1595 					btrfs_tree_read_lock(eb);
1596 				ret = find_extent_in_eb(ctx, eb, &eie);
1597 				if (!path->skip_locking)
1598 					btrfs_tree_read_unlock(eb);
1599 				free_extent_buffer(eb);
1600 				if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
1601 				    ret < 0)
1602 					goto out;
1603 				ref->inode_list = eie;
1604 				/*
1605 				 * We transferred the list ownership to the ref,
1606 				 * so set to NULL to avoid a double free in case
1607 				 * an error happens after this.
1608 				 */
1609 				eie = NULL;
1610 			}
1611 			ret = ulist_add_merge_ptr(ctx->refs, ref->parent,
1612 						  ref->inode_list,
1613 						  (void **)&eie, GFP_NOFS);
1614 			if (ret < 0)
1615 				goto out;
1616 			if (!ret && !ctx->ignore_extent_item_pos) {
1617 				/*
1618 				 * We've recorded that parent, so we must extend
1619 				 * its inode list here.
1620 				 *
1621 				 * However if there was corruption we may not
1622 				 * have found an eie, return an error in this
1623 				 * case.
1624 				 */
1625 				ASSERT(eie);
1626 				if (!eie) {
1627 					ret = -EUCLEAN;
1628 					goto out;
1629 				}
1630 				while (eie->next)
1631 					eie = eie->next;
1632 				eie->next = ref->inode_list;
1633 			}
1634 			eie = NULL;
1635 			/*
1636 			 * We have transferred the inode list ownership from
1637 			 * this ref to the ref we added to the 'refs' ulist.
1638 			 * So set this ref's inode list to NULL to avoid
1639 			 * use-after-free when our caller uses it or double
1640 			 * frees in case an error happens before we return.
1641 			 */
1642 			ref->inode_list = NULL;
1643 		}
1644 		cond_resched();
1645 	}
1646 
1647 out:
1648 	btrfs_free_path(path);
1649 
1650 	prelim_release(&preftrees.direct);
1651 	prelim_release(&preftrees.indirect);
1652 	prelim_release(&preftrees.indirect_missing_keys);
1653 
1654 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
1655 		free_inode_elem_list(eie);
1656 	return ret;
1657 }
1658 
1659 /*
1660  * Finds all leaves with a reference to the specified combination of
1661  * @ctx->bytenr and @ctx->extent_item_pos. The bytenr of the found leaves are
1662  * added to the ulist at @ctx->refs, and that ulist is allocated by this
1663  * function. The caller should free the ulist with free_leaf_list() if
1664  * @ctx->ignore_extent_item_pos is false, otherwise a fimple ulist_free() is
1665  * enough.
1666  *
1667  * Returns 0 on success and < 0 on error. On error @ctx->refs is not allocated.
1668  */
1669 int btrfs_find_all_leafs(struct btrfs_backref_walk_ctx *ctx)
1670 {
1671 	int ret;
1672 
1673 	ASSERT(ctx->refs == NULL);
1674 
1675 	ctx->refs = ulist_alloc(GFP_NOFS);
1676 	if (!ctx->refs)
1677 		return -ENOMEM;
1678 
1679 	ret = find_parent_nodes(ctx, NULL);
1680 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
1681 	    (ret < 0 && ret != -ENOENT)) {
1682 		free_leaf_list(ctx->refs);
1683 		ctx->refs = NULL;
1684 		return ret;
1685 	}
1686 
1687 	return 0;
1688 }
1689 
1690 /*
1691  * Walk all backrefs for a given extent to find all roots that reference this
1692  * extent. Walking a backref means finding all extents that reference this
1693  * extent and in turn walk the backrefs of those, too. Naturally this is a
1694  * recursive process, but here it is implemented in an iterative fashion: We
1695  * find all referencing extents for the extent in question and put them on a
1696  * list. In turn, we find all referencing extents for those, further appending
1697  * to the list. The way we iterate the list allows adding more elements after
1698  * the current while iterating. The process stops when we reach the end of the
1699  * list.
1700  *
1701  * Found roots are added to @ctx->roots, which is allocated by this function if
1702  * it points to NULL, in which case the caller is responsible for freeing it
1703  * after it's not needed anymore.
1704  * This function requires @ctx->refs to be NULL, as it uses it for allocating a
1705  * ulist to do temporary work, and frees it before returning.
1706  *
1707  * Returns 0 on success, < 0 on error.
1708  */
1709 static int btrfs_find_all_roots_safe(struct btrfs_backref_walk_ctx *ctx)
1710 {
1711 	const u64 orig_bytenr = ctx->bytenr;
1712 	const bool orig_ignore_extent_item_pos = ctx->ignore_extent_item_pos;
1713 	bool roots_ulist_allocated = false;
1714 	struct ulist_iterator uiter;
1715 	int ret = 0;
1716 
1717 	ASSERT(ctx->refs == NULL);
1718 
1719 	ctx->refs = ulist_alloc(GFP_NOFS);
1720 	if (!ctx->refs)
1721 		return -ENOMEM;
1722 
1723 	if (!ctx->roots) {
1724 		ctx->roots = ulist_alloc(GFP_NOFS);
1725 		if (!ctx->roots) {
1726 			ulist_free(ctx->refs);
1727 			ctx->refs = NULL;
1728 			return -ENOMEM;
1729 		}
1730 		roots_ulist_allocated = true;
1731 	}
1732 
1733 	ctx->ignore_extent_item_pos = true;
1734 
1735 	ULIST_ITER_INIT(&uiter);
1736 	while (1) {
1737 		struct ulist_node *node;
1738 
1739 		ret = find_parent_nodes(ctx, NULL);
1740 		if (ret < 0 && ret != -ENOENT) {
1741 			if (roots_ulist_allocated) {
1742 				ulist_free(ctx->roots);
1743 				ctx->roots = NULL;
1744 			}
1745 			break;
1746 		}
1747 		ret = 0;
1748 		node = ulist_next(ctx->refs, &uiter);
1749 		if (!node)
1750 			break;
1751 		ctx->bytenr = node->val;
1752 		cond_resched();
1753 	}
1754 
1755 	ulist_free(ctx->refs);
1756 	ctx->refs = NULL;
1757 	ctx->bytenr = orig_bytenr;
1758 	ctx->ignore_extent_item_pos = orig_ignore_extent_item_pos;
1759 
1760 	return ret;
1761 }
1762 
1763 int btrfs_find_all_roots(struct btrfs_backref_walk_ctx *ctx,
1764 			 bool skip_commit_root_sem)
1765 {
1766 	int ret;
1767 
1768 	if (!ctx->trans && !skip_commit_root_sem)
1769 		down_read(&ctx->fs_info->commit_root_sem);
1770 	ret = btrfs_find_all_roots_safe(ctx);
1771 	if (!ctx->trans && !skip_commit_root_sem)
1772 		up_read(&ctx->fs_info->commit_root_sem);
1773 	return ret;
1774 }
1775 
1776 struct btrfs_backref_share_check_ctx *btrfs_alloc_backref_share_check_ctx(void)
1777 {
1778 	struct btrfs_backref_share_check_ctx *ctx;
1779 
1780 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1781 	if (!ctx)
1782 		return NULL;
1783 
1784 	ulist_init(&ctx->refs);
1785 
1786 	return ctx;
1787 }
1788 
1789 void btrfs_free_backref_share_ctx(struct btrfs_backref_share_check_ctx *ctx)
1790 {
1791 	if (!ctx)
1792 		return;
1793 
1794 	ulist_release(&ctx->refs);
1795 	kfree(ctx);
1796 }
1797 
1798 /*
1799  * Check if a data extent is shared or not.
1800  *
1801  * @inode:       The inode whose extent we are checking.
1802  * @bytenr:      Logical bytenr of the extent we are checking.
1803  * @extent_gen:  Generation of the extent (file extent item) or 0 if it is
1804  *               not known.
1805  * @ctx:         A backref sharedness check context.
1806  *
1807  * btrfs_is_data_extent_shared uses the backref walking code but will short
1808  * circuit as soon as it finds a root or inode that doesn't match the
1809  * one passed in. This provides a significant performance benefit for
1810  * callers (such as fiemap) which want to know whether the extent is
1811  * shared but do not need a ref count.
1812  *
1813  * This attempts to attach to the running transaction in order to account for
1814  * delayed refs, but continues on even when no running transaction exists.
1815  *
1816  * Return: 0 if extent is not shared, 1 if it is shared, < 0 on error.
1817  */
1818 int btrfs_is_data_extent_shared(struct btrfs_inode *inode, u64 bytenr,
1819 				u64 extent_gen,
1820 				struct btrfs_backref_share_check_ctx *ctx)
1821 {
1822 	struct btrfs_backref_walk_ctx walk_ctx = { 0 };
1823 	struct btrfs_root *root = inode->root;
1824 	struct btrfs_fs_info *fs_info = root->fs_info;
1825 	struct btrfs_trans_handle *trans;
1826 	struct ulist_iterator uiter;
1827 	struct ulist_node *node;
1828 	struct btrfs_seq_list elem = BTRFS_SEQ_LIST_INIT(elem);
1829 	int ret = 0;
1830 	struct share_check shared = {
1831 		.ctx = ctx,
1832 		.root = root,
1833 		.inum = btrfs_ino(inode),
1834 		.data_bytenr = bytenr,
1835 		.data_extent_gen = extent_gen,
1836 		.share_count = 0,
1837 		.self_ref_count = 0,
1838 		.have_delayed_delete_refs = false,
1839 	};
1840 	int level;
1841 
1842 	for (int i = 0; i < BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE; i++) {
1843 		if (ctx->prev_extents_cache[i].bytenr == bytenr)
1844 			return ctx->prev_extents_cache[i].is_shared;
1845 	}
1846 
1847 	ulist_init(&ctx->refs);
1848 
1849 	trans = btrfs_join_transaction_nostart(root);
1850 	if (IS_ERR(trans)) {
1851 		if (PTR_ERR(trans) != -ENOENT && PTR_ERR(trans) != -EROFS) {
1852 			ret = PTR_ERR(trans);
1853 			goto out;
1854 		}
1855 		trans = NULL;
1856 		down_read(&fs_info->commit_root_sem);
1857 	} else {
1858 		btrfs_get_tree_mod_seq(fs_info, &elem);
1859 		walk_ctx.time_seq = elem.seq;
1860 	}
1861 
1862 	walk_ctx.ignore_extent_item_pos = true;
1863 	walk_ctx.trans = trans;
1864 	walk_ctx.fs_info = fs_info;
1865 	walk_ctx.refs = &ctx->refs;
1866 
1867 	/* -1 means we are in the bytenr of the data extent. */
1868 	level = -1;
1869 	ULIST_ITER_INIT(&uiter);
1870 	ctx->use_path_cache = true;
1871 	while (1) {
1872 		bool is_shared;
1873 		bool cached;
1874 
1875 		walk_ctx.bytenr = bytenr;
1876 		ret = find_parent_nodes(&walk_ctx, &shared);
1877 		if (ret == BACKREF_FOUND_SHARED ||
1878 		    ret == BACKREF_FOUND_NOT_SHARED) {
1879 			/* If shared must return 1, otherwise return 0. */
1880 			ret = (ret == BACKREF_FOUND_SHARED) ? 1 : 0;
1881 			if (level >= 0)
1882 				store_backref_shared_cache(ctx, root, bytenr,
1883 							   level, ret == 1);
1884 			break;
1885 		}
1886 		if (ret < 0 && ret != -ENOENT)
1887 			break;
1888 		ret = 0;
1889 
1890 		/*
1891 		 * If our data extent was not directly shared (without multiple
1892 		 * reference items), than it might have a single reference item
1893 		 * with a count > 1 for the same offset, which means there are 2
1894 		 * (or more) file extent items that point to the data extent -
1895 		 * this happens when a file extent item needs to be split and
1896 		 * then one item gets moved to another leaf due to a b+tree leaf
1897 		 * split when inserting some item. In this case the file extent
1898 		 * items may be located in different leaves and therefore some
1899 		 * of the leaves may be referenced through shared subtrees while
1900 		 * others are not. Since our extent buffer cache only works for
1901 		 * a single path (by far the most common case and simpler to
1902 		 * deal with), we can not use it if we have multiple leaves
1903 		 * (which implies multiple paths).
1904 		 */
1905 		if (level == -1 && ctx->refs.nnodes > 1)
1906 			ctx->use_path_cache = false;
1907 
1908 		if (level >= 0)
1909 			store_backref_shared_cache(ctx, root, bytenr,
1910 						   level, false);
1911 		node = ulist_next(&ctx->refs, &uiter);
1912 		if (!node)
1913 			break;
1914 		bytenr = node->val;
1915 		level++;
1916 		cached = lookup_backref_shared_cache(ctx, root, bytenr, level,
1917 						     &is_shared);
1918 		if (cached) {
1919 			ret = (is_shared ? 1 : 0);
1920 			break;
1921 		}
1922 		shared.share_count = 0;
1923 		shared.have_delayed_delete_refs = false;
1924 		cond_resched();
1925 	}
1926 
1927 	/*
1928 	 * Cache the sharedness result for the data extent if we know our inode
1929 	 * has more than 1 file extent item that refers to the data extent.
1930 	 */
1931 	if (ret >= 0 && shared.self_ref_count > 1) {
1932 		int slot = ctx->prev_extents_cache_slot;
1933 
1934 		ctx->prev_extents_cache[slot].bytenr = shared.data_bytenr;
1935 		ctx->prev_extents_cache[slot].is_shared = (ret == 1);
1936 
1937 		slot = (slot + 1) % BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE;
1938 		ctx->prev_extents_cache_slot = slot;
1939 	}
1940 
1941 	if (trans) {
1942 		btrfs_put_tree_mod_seq(fs_info, &elem);
1943 		btrfs_end_transaction(trans);
1944 	} else {
1945 		up_read(&fs_info->commit_root_sem);
1946 	}
1947 out:
1948 	ulist_release(&ctx->refs);
1949 	ctx->prev_leaf_bytenr = ctx->curr_leaf_bytenr;
1950 
1951 	return ret;
1952 }
1953 
1954 int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
1955 			  u64 start_off, struct btrfs_path *path,
1956 			  struct btrfs_inode_extref **ret_extref,
1957 			  u64 *found_off)
1958 {
1959 	int ret, slot;
1960 	struct btrfs_key key;
1961 	struct btrfs_key found_key;
1962 	struct btrfs_inode_extref *extref;
1963 	const struct extent_buffer *leaf;
1964 	unsigned long ptr;
1965 
1966 	key.objectid = inode_objectid;
1967 	key.type = BTRFS_INODE_EXTREF_KEY;
1968 	key.offset = start_off;
1969 
1970 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1971 	if (ret < 0)
1972 		return ret;
1973 
1974 	while (1) {
1975 		leaf = path->nodes[0];
1976 		slot = path->slots[0];
1977 		if (slot >= btrfs_header_nritems(leaf)) {
1978 			/*
1979 			 * If the item at offset is not found,
1980 			 * btrfs_search_slot will point us to the slot
1981 			 * where it should be inserted. In our case
1982 			 * that will be the slot directly before the
1983 			 * next INODE_REF_KEY_V2 item. In the case
1984 			 * that we're pointing to the last slot in a
1985 			 * leaf, we must move one leaf over.
1986 			 */
1987 			ret = btrfs_next_leaf(root, path);
1988 			if (ret) {
1989 				if (ret >= 1)
1990 					ret = -ENOENT;
1991 				break;
1992 			}
1993 			continue;
1994 		}
1995 
1996 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
1997 
1998 		/*
1999 		 * Check that we're still looking at an extended ref key for
2000 		 * this particular objectid. If we have different
2001 		 * objectid or type then there are no more to be found
2002 		 * in the tree and we can exit.
2003 		 */
2004 		ret = -ENOENT;
2005 		if (found_key.objectid != inode_objectid)
2006 			break;
2007 		if (found_key.type != BTRFS_INODE_EXTREF_KEY)
2008 			break;
2009 
2010 		ret = 0;
2011 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
2012 		extref = (struct btrfs_inode_extref *)ptr;
2013 		*ret_extref = extref;
2014 		if (found_off)
2015 			*found_off = found_key.offset;
2016 		break;
2017 	}
2018 
2019 	return ret;
2020 }
2021 
2022 /*
2023  * this iterates to turn a name (from iref/extref) into a full filesystem path.
2024  * Elements of the path are separated by '/' and the path is guaranteed to be
2025  * 0-terminated. the path is only given within the current file system.
2026  * Therefore, it never starts with a '/'. the caller is responsible to provide
2027  * "size" bytes in "dest". the dest buffer will be filled backwards. finally,
2028  * the start point of the resulting string is returned. this pointer is within
2029  * dest, normally.
2030  * in case the path buffer would overflow, the pointer is decremented further
2031  * as if output was written to the buffer, though no more output is actually
2032  * generated. that way, the caller can determine how much space would be
2033  * required for the path to fit into the buffer. in that case, the returned
2034  * value will be smaller than dest. callers must check this!
2035  */
2036 char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
2037 			u32 name_len, unsigned long name_off,
2038 			struct extent_buffer *eb_in, u64 parent,
2039 			char *dest, u32 size)
2040 {
2041 	int slot;
2042 	u64 next_inum;
2043 	int ret;
2044 	s64 bytes_left = ((s64)size) - 1;
2045 	struct extent_buffer *eb = eb_in;
2046 	struct btrfs_key found_key;
2047 	struct btrfs_inode_ref *iref;
2048 
2049 	if (bytes_left >= 0)
2050 		dest[bytes_left] = '\0';
2051 
2052 	while (1) {
2053 		bytes_left -= name_len;
2054 		if (bytes_left >= 0)
2055 			read_extent_buffer(eb, dest + bytes_left,
2056 					   name_off, name_len);
2057 		if (eb != eb_in) {
2058 			if (!path->skip_locking)
2059 				btrfs_tree_read_unlock(eb);
2060 			free_extent_buffer(eb);
2061 		}
2062 		ret = btrfs_find_item(fs_root, path, parent, 0,
2063 				BTRFS_INODE_REF_KEY, &found_key);
2064 		if (ret > 0)
2065 			ret = -ENOENT;
2066 		if (ret)
2067 			break;
2068 
2069 		next_inum = found_key.offset;
2070 
2071 		/* regular exit ahead */
2072 		if (parent == next_inum)
2073 			break;
2074 
2075 		slot = path->slots[0];
2076 		eb = path->nodes[0];
2077 		/* make sure we can use eb after releasing the path */
2078 		if (eb != eb_in) {
2079 			path->nodes[0] = NULL;
2080 			path->locks[0] = 0;
2081 		}
2082 		btrfs_release_path(path);
2083 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2084 
2085 		name_len = btrfs_inode_ref_name_len(eb, iref);
2086 		name_off = (unsigned long)(iref + 1);
2087 
2088 		parent = next_inum;
2089 		--bytes_left;
2090 		if (bytes_left >= 0)
2091 			dest[bytes_left] = '/';
2092 	}
2093 
2094 	btrfs_release_path(path);
2095 
2096 	if (ret)
2097 		return ERR_PTR(ret);
2098 
2099 	return dest + bytes_left;
2100 }
2101 
2102 /*
2103  * this makes the path point to (logical EXTENT_ITEM *)
2104  * returns BTRFS_EXTENT_FLAG_DATA for data, BTRFS_EXTENT_FLAG_TREE_BLOCK for
2105  * tree blocks and <0 on error.
2106  */
2107 int extent_from_logical(struct btrfs_fs_info *fs_info, u64 logical,
2108 			struct btrfs_path *path, struct btrfs_key *found_key,
2109 			u64 *flags_ret)
2110 {
2111 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, logical);
2112 	int ret;
2113 	u64 flags;
2114 	u64 size = 0;
2115 	u32 item_size;
2116 	const struct extent_buffer *eb;
2117 	struct btrfs_extent_item *ei;
2118 	struct btrfs_key key;
2119 
2120 	if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2121 		key.type = BTRFS_METADATA_ITEM_KEY;
2122 	else
2123 		key.type = BTRFS_EXTENT_ITEM_KEY;
2124 	key.objectid = logical;
2125 	key.offset = (u64)-1;
2126 
2127 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2128 	if (ret < 0)
2129 		return ret;
2130 
2131 	ret = btrfs_previous_extent_item(extent_root, path, 0);
2132 	if (ret) {
2133 		if (ret > 0)
2134 			ret = -ENOENT;
2135 		return ret;
2136 	}
2137 	btrfs_item_key_to_cpu(path->nodes[0], found_key, path->slots[0]);
2138 	if (found_key->type == BTRFS_METADATA_ITEM_KEY)
2139 		size = fs_info->nodesize;
2140 	else if (found_key->type == BTRFS_EXTENT_ITEM_KEY)
2141 		size = found_key->offset;
2142 
2143 	if (found_key->objectid > logical ||
2144 	    found_key->objectid + size <= logical) {
2145 		btrfs_debug(fs_info,
2146 			"logical %llu is not within any extent", logical);
2147 		return -ENOENT;
2148 	}
2149 
2150 	eb = path->nodes[0];
2151 	item_size = btrfs_item_size(eb, path->slots[0]);
2152 	BUG_ON(item_size < sizeof(*ei));
2153 
2154 	ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
2155 	flags = btrfs_extent_flags(eb, ei);
2156 
2157 	btrfs_debug(fs_info,
2158 		"logical %llu is at position %llu within the extent (%llu EXTENT_ITEM %llu) flags %#llx size %u",
2159 		 logical, logical - found_key->objectid, found_key->objectid,
2160 		 found_key->offset, flags, item_size);
2161 
2162 	WARN_ON(!flags_ret);
2163 	if (flags_ret) {
2164 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
2165 			*flags_ret = BTRFS_EXTENT_FLAG_TREE_BLOCK;
2166 		else if (flags & BTRFS_EXTENT_FLAG_DATA)
2167 			*flags_ret = BTRFS_EXTENT_FLAG_DATA;
2168 		else
2169 			BUG();
2170 		return 0;
2171 	}
2172 
2173 	return -EIO;
2174 }
2175 
2176 /*
2177  * helper function to iterate extent inline refs. ptr must point to a 0 value
2178  * for the first call and may be modified. it is used to track state.
2179  * if more refs exist, 0 is returned and the next call to
2180  * get_extent_inline_ref must pass the modified ptr parameter to get the
2181  * next ref. after the last ref was processed, 1 is returned.
2182  * returns <0 on error
2183  */
2184 static int get_extent_inline_ref(unsigned long *ptr,
2185 				 const struct extent_buffer *eb,
2186 				 const struct btrfs_key *key,
2187 				 const struct btrfs_extent_item *ei,
2188 				 u32 item_size,
2189 				 struct btrfs_extent_inline_ref **out_eiref,
2190 				 int *out_type)
2191 {
2192 	unsigned long end;
2193 	u64 flags;
2194 	struct btrfs_tree_block_info *info;
2195 
2196 	if (!*ptr) {
2197 		/* first call */
2198 		flags = btrfs_extent_flags(eb, ei);
2199 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
2200 			if (key->type == BTRFS_METADATA_ITEM_KEY) {
2201 				/* a skinny metadata extent */
2202 				*out_eiref =
2203 				     (struct btrfs_extent_inline_ref *)(ei + 1);
2204 			} else {
2205 				WARN_ON(key->type != BTRFS_EXTENT_ITEM_KEY);
2206 				info = (struct btrfs_tree_block_info *)(ei + 1);
2207 				*out_eiref =
2208 				   (struct btrfs_extent_inline_ref *)(info + 1);
2209 			}
2210 		} else {
2211 			*out_eiref = (struct btrfs_extent_inline_ref *)(ei + 1);
2212 		}
2213 		*ptr = (unsigned long)*out_eiref;
2214 		if ((unsigned long)(*ptr) >= (unsigned long)ei + item_size)
2215 			return -ENOENT;
2216 	}
2217 
2218 	end = (unsigned long)ei + item_size;
2219 	*out_eiref = (struct btrfs_extent_inline_ref *)(*ptr);
2220 	*out_type = btrfs_get_extent_inline_ref_type(eb, *out_eiref,
2221 						     BTRFS_REF_TYPE_ANY);
2222 	if (*out_type == BTRFS_REF_TYPE_INVALID)
2223 		return -EUCLEAN;
2224 
2225 	*ptr += btrfs_extent_inline_ref_size(*out_type);
2226 	WARN_ON(*ptr > end);
2227 	if (*ptr == end)
2228 		return 1; /* last */
2229 
2230 	return 0;
2231 }
2232 
2233 /*
2234  * reads the tree block backref for an extent. tree level and root are returned
2235  * through out_level and out_root. ptr must point to a 0 value for the first
2236  * call and may be modified (see get_extent_inline_ref comment).
2237  * returns 0 if data was provided, 1 if there was no more data to provide or
2238  * <0 on error.
2239  */
2240 int tree_backref_for_extent(unsigned long *ptr, struct extent_buffer *eb,
2241 			    struct btrfs_key *key, struct btrfs_extent_item *ei,
2242 			    u32 item_size, u64 *out_root, u8 *out_level)
2243 {
2244 	int ret;
2245 	int type;
2246 	struct btrfs_extent_inline_ref *eiref;
2247 
2248 	if (*ptr == (unsigned long)-1)
2249 		return 1;
2250 
2251 	while (1) {
2252 		ret = get_extent_inline_ref(ptr, eb, key, ei, item_size,
2253 					      &eiref, &type);
2254 		if (ret < 0)
2255 			return ret;
2256 
2257 		if (type == BTRFS_TREE_BLOCK_REF_KEY ||
2258 		    type == BTRFS_SHARED_BLOCK_REF_KEY)
2259 			break;
2260 
2261 		if (ret == 1)
2262 			return 1;
2263 	}
2264 
2265 	/* we can treat both ref types equally here */
2266 	*out_root = btrfs_extent_inline_ref_offset(eb, eiref);
2267 
2268 	if (key->type == BTRFS_EXTENT_ITEM_KEY) {
2269 		struct btrfs_tree_block_info *info;
2270 
2271 		info = (struct btrfs_tree_block_info *)(ei + 1);
2272 		*out_level = btrfs_tree_block_level(eb, info);
2273 	} else {
2274 		ASSERT(key->type == BTRFS_METADATA_ITEM_KEY);
2275 		*out_level = (u8)key->offset;
2276 	}
2277 
2278 	if (ret == 1)
2279 		*ptr = (unsigned long)-1;
2280 
2281 	return 0;
2282 }
2283 
2284 static int iterate_leaf_refs(struct btrfs_fs_info *fs_info,
2285 			     struct extent_inode_elem *inode_list,
2286 			     u64 root, u64 extent_item_objectid,
2287 			     iterate_extent_inodes_t *iterate, void *ctx)
2288 {
2289 	struct extent_inode_elem *eie;
2290 	int ret = 0;
2291 
2292 	for (eie = inode_list; eie; eie = eie->next) {
2293 		btrfs_debug(fs_info,
2294 			    "ref for %llu resolved, key (%llu EXTEND_DATA %llu), root %llu",
2295 			    extent_item_objectid, eie->inum,
2296 			    eie->offset, root);
2297 		ret = iterate(eie->inum, eie->offset, eie->num_bytes, root, ctx);
2298 		if (ret) {
2299 			btrfs_debug(fs_info,
2300 				    "stopping iteration for %llu due to ret=%d",
2301 				    extent_item_objectid, ret);
2302 			break;
2303 		}
2304 	}
2305 
2306 	return ret;
2307 }
2308 
2309 /*
2310  * calls iterate() for every inode that references the extent identified by
2311  * the given parameters.
2312  * when the iterator function returns a non-zero value, iteration stops.
2313  */
2314 int iterate_extent_inodes(struct btrfs_backref_walk_ctx *ctx,
2315 			  bool search_commit_root,
2316 			  iterate_extent_inodes_t *iterate, void *user_ctx)
2317 {
2318 	int ret;
2319 	struct ulist *refs;
2320 	struct ulist_node *ref_node;
2321 	struct btrfs_seq_list seq_elem = BTRFS_SEQ_LIST_INIT(seq_elem);
2322 	struct ulist_iterator ref_uiter;
2323 
2324 	btrfs_debug(ctx->fs_info, "resolving all inodes for extent %llu",
2325 		    ctx->bytenr);
2326 
2327 	ASSERT(ctx->trans == NULL);
2328 	ASSERT(ctx->roots == NULL);
2329 
2330 	if (!search_commit_root) {
2331 		struct btrfs_trans_handle *trans;
2332 
2333 		trans = btrfs_attach_transaction(ctx->fs_info->tree_root);
2334 		if (IS_ERR(trans)) {
2335 			if (PTR_ERR(trans) != -ENOENT &&
2336 			    PTR_ERR(trans) != -EROFS)
2337 				return PTR_ERR(trans);
2338 			trans = NULL;
2339 		}
2340 		ctx->trans = trans;
2341 	}
2342 
2343 	if (ctx->trans) {
2344 		btrfs_get_tree_mod_seq(ctx->fs_info, &seq_elem);
2345 		ctx->time_seq = seq_elem.seq;
2346 	} else {
2347 		down_read(&ctx->fs_info->commit_root_sem);
2348 	}
2349 
2350 	ret = btrfs_find_all_leafs(ctx);
2351 	if (ret)
2352 		goto out;
2353 	refs = ctx->refs;
2354 	ctx->refs = NULL;
2355 
2356 	ULIST_ITER_INIT(&ref_uiter);
2357 	while (!ret && (ref_node = ulist_next(refs, &ref_uiter))) {
2358 		const u64 leaf_bytenr = ref_node->val;
2359 		struct ulist_node *root_node;
2360 		struct ulist_iterator root_uiter;
2361 		struct extent_inode_elem *inode_list;
2362 
2363 		inode_list = (struct extent_inode_elem *)(uintptr_t)ref_node->aux;
2364 
2365 		if (ctx->cache_lookup) {
2366 			const u64 *root_ids;
2367 			int root_count;
2368 			bool cached;
2369 
2370 			cached = ctx->cache_lookup(leaf_bytenr, ctx->user_ctx,
2371 						   &root_ids, &root_count);
2372 			if (cached) {
2373 				for (int i = 0; i < root_count; i++) {
2374 					ret = iterate_leaf_refs(ctx->fs_info,
2375 								inode_list,
2376 								root_ids[i],
2377 								leaf_bytenr,
2378 								iterate,
2379 								user_ctx);
2380 					if (ret)
2381 						break;
2382 				}
2383 				continue;
2384 			}
2385 		}
2386 
2387 		if (!ctx->roots) {
2388 			ctx->roots = ulist_alloc(GFP_NOFS);
2389 			if (!ctx->roots) {
2390 				ret = -ENOMEM;
2391 				break;
2392 			}
2393 		}
2394 
2395 		ctx->bytenr = leaf_bytenr;
2396 		ret = btrfs_find_all_roots_safe(ctx);
2397 		if (ret)
2398 			break;
2399 
2400 		if (ctx->cache_store)
2401 			ctx->cache_store(leaf_bytenr, ctx->roots, ctx->user_ctx);
2402 
2403 		ULIST_ITER_INIT(&root_uiter);
2404 		while (!ret && (root_node = ulist_next(ctx->roots, &root_uiter))) {
2405 			btrfs_debug(ctx->fs_info,
2406 				    "root %llu references leaf %llu, data list %#llx",
2407 				    root_node->val, ref_node->val,
2408 				    ref_node->aux);
2409 			ret = iterate_leaf_refs(ctx->fs_info, inode_list,
2410 						root_node->val, ctx->bytenr,
2411 						iterate, user_ctx);
2412 		}
2413 		ulist_reinit(ctx->roots);
2414 	}
2415 
2416 	free_leaf_list(refs);
2417 out:
2418 	if (ctx->trans) {
2419 		btrfs_put_tree_mod_seq(ctx->fs_info, &seq_elem);
2420 		btrfs_end_transaction(ctx->trans);
2421 		ctx->trans = NULL;
2422 	} else {
2423 		up_read(&ctx->fs_info->commit_root_sem);
2424 	}
2425 
2426 	ulist_free(ctx->roots);
2427 	ctx->roots = NULL;
2428 
2429 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP)
2430 		ret = 0;
2431 
2432 	return ret;
2433 }
2434 
2435 static int build_ino_list(u64 inum, u64 offset, u64 num_bytes, u64 root, void *ctx)
2436 {
2437 	struct btrfs_data_container *inodes = ctx;
2438 	const size_t c = 3 * sizeof(u64);
2439 
2440 	if (inodes->bytes_left >= c) {
2441 		inodes->bytes_left -= c;
2442 		inodes->val[inodes->elem_cnt] = inum;
2443 		inodes->val[inodes->elem_cnt + 1] = offset;
2444 		inodes->val[inodes->elem_cnt + 2] = root;
2445 		inodes->elem_cnt += 3;
2446 	} else {
2447 		inodes->bytes_missing += c - inodes->bytes_left;
2448 		inodes->bytes_left = 0;
2449 		inodes->elem_missed += 3;
2450 	}
2451 
2452 	return 0;
2453 }
2454 
2455 int iterate_inodes_from_logical(u64 logical, struct btrfs_fs_info *fs_info,
2456 				struct btrfs_path *path,
2457 				void *ctx, bool ignore_offset)
2458 {
2459 	struct btrfs_backref_walk_ctx walk_ctx = { 0 };
2460 	int ret;
2461 	u64 flags = 0;
2462 	struct btrfs_key found_key;
2463 	int search_commit_root = path->search_commit_root;
2464 
2465 	ret = extent_from_logical(fs_info, logical, path, &found_key, &flags);
2466 	btrfs_release_path(path);
2467 	if (ret < 0)
2468 		return ret;
2469 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
2470 		return -EINVAL;
2471 
2472 	walk_ctx.bytenr = found_key.objectid;
2473 	if (ignore_offset)
2474 		walk_ctx.ignore_extent_item_pos = true;
2475 	else
2476 		walk_ctx.extent_item_pos = logical - found_key.objectid;
2477 	walk_ctx.fs_info = fs_info;
2478 
2479 	return iterate_extent_inodes(&walk_ctx, search_commit_root,
2480 				     build_ino_list, ctx);
2481 }
2482 
2483 static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2484 			 struct extent_buffer *eb, struct inode_fs_paths *ipath);
2485 
2486 static int iterate_inode_refs(u64 inum, struct inode_fs_paths *ipath)
2487 {
2488 	int ret = 0;
2489 	int slot;
2490 	u32 cur;
2491 	u32 len;
2492 	u32 name_len;
2493 	u64 parent = 0;
2494 	int found = 0;
2495 	struct btrfs_root *fs_root = ipath->fs_root;
2496 	struct btrfs_path *path = ipath->btrfs_path;
2497 	struct extent_buffer *eb;
2498 	struct btrfs_inode_ref *iref;
2499 	struct btrfs_key found_key;
2500 
2501 	while (!ret) {
2502 		ret = btrfs_find_item(fs_root, path, inum,
2503 				parent ? parent + 1 : 0, BTRFS_INODE_REF_KEY,
2504 				&found_key);
2505 
2506 		if (ret < 0)
2507 			break;
2508 		if (ret) {
2509 			ret = found ? 0 : -ENOENT;
2510 			break;
2511 		}
2512 		++found;
2513 
2514 		parent = found_key.offset;
2515 		slot = path->slots[0];
2516 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
2517 		if (!eb) {
2518 			ret = -ENOMEM;
2519 			break;
2520 		}
2521 		btrfs_release_path(path);
2522 
2523 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2524 
2525 		for (cur = 0; cur < btrfs_item_size(eb, slot); cur += len) {
2526 			name_len = btrfs_inode_ref_name_len(eb, iref);
2527 			/* path must be released before calling iterate()! */
2528 			btrfs_debug(fs_root->fs_info,
2529 				"following ref at offset %u for inode %llu in tree %llu",
2530 				cur, found_key.objectid,
2531 				fs_root->root_key.objectid);
2532 			ret = inode_to_path(parent, name_len,
2533 				      (unsigned long)(iref + 1), eb, ipath);
2534 			if (ret)
2535 				break;
2536 			len = sizeof(*iref) + name_len;
2537 			iref = (struct btrfs_inode_ref *)((char *)iref + len);
2538 		}
2539 		free_extent_buffer(eb);
2540 	}
2541 
2542 	btrfs_release_path(path);
2543 
2544 	return ret;
2545 }
2546 
2547 static int iterate_inode_extrefs(u64 inum, struct inode_fs_paths *ipath)
2548 {
2549 	int ret;
2550 	int slot;
2551 	u64 offset = 0;
2552 	u64 parent;
2553 	int found = 0;
2554 	struct btrfs_root *fs_root = ipath->fs_root;
2555 	struct btrfs_path *path = ipath->btrfs_path;
2556 	struct extent_buffer *eb;
2557 	struct btrfs_inode_extref *extref;
2558 	u32 item_size;
2559 	u32 cur_offset;
2560 	unsigned long ptr;
2561 
2562 	while (1) {
2563 		ret = btrfs_find_one_extref(fs_root, inum, offset, path, &extref,
2564 					    &offset);
2565 		if (ret < 0)
2566 			break;
2567 		if (ret) {
2568 			ret = found ? 0 : -ENOENT;
2569 			break;
2570 		}
2571 		++found;
2572 
2573 		slot = path->slots[0];
2574 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
2575 		if (!eb) {
2576 			ret = -ENOMEM;
2577 			break;
2578 		}
2579 		btrfs_release_path(path);
2580 
2581 		item_size = btrfs_item_size(eb, slot);
2582 		ptr = btrfs_item_ptr_offset(eb, slot);
2583 		cur_offset = 0;
2584 
2585 		while (cur_offset < item_size) {
2586 			u32 name_len;
2587 
2588 			extref = (struct btrfs_inode_extref *)(ptr + cur_offset);
2589 			parent = btrfs_inode_extref_parent(eb, extref);
2590 			name_len = btrfs_inode_extref_name_len(eb, extref);
2591 			ret = inode_to_path(parent, name_len,
2592 				      (unsigned long)&extref->name, eb, ipath);
2593 			if (ret)
2594 				break;
2595 
2596 			cur_offset += btrfs_inode_extref_name_len(eb, extref);
2597 			cur_offset += sizeof(*extref);
2598 		}
2599 		free_extent_buffer(eb);
2600 
2601 		offset++;
2602 	}
2603 
2604 	btrfs_release_path(path);
2605 
2606 	return ret;
2607 }
2608 
2609 /*
2610  * returns 0 if the path could be dumped (probably truncated)
2611  * returns <0 in case of an error
2612  */
2613 static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2614 			 struct extent_buffer *eb, struct inode_fs_paths *ipath)
2615 {
2616 	char *fspath;
2617 	char *fspath_min;
2618 	int i = ipath->fspath->elem_cnt;
2619 	const int s_ptr = sizeof(char *);
2620 	u32 bytes_left;
2621 
2622 	bytes_left = ipath->fspath->bytes_left > s_ptr ?
2623 					ipath->fspath->bytes_left - s_ptr : 0;
2624 
2625 	fspath_min = (char *)ipath->fspath->val + (i + 1) * s_ptr;
2626 	fspath = btrfs_ref_to_path(ipath->fs_root, ipath->btrfs_path, name_len,
2627 				   name_off, eb, inum, fspath_min, bytes_left);
2628 	if (IS_ERR(fspath))
2629 		return PTR_ERR(fspath);
2630 
2631 	if (fspath > fspath_min) {
2632 		ipath->fspath->val[i] = (u64)(unsigned long)fspath;
2633 		++ipath->fspath->elem_cnt;
2634 		ipath->fspath->bytes_left = fspath - fspath_min;
2635 	} else {
2636 		++ipath->fspath->elem_missed;
2637 		ipath->fspath->bytes_missing += fspath_min - fspath;
2638 		ipath->fspath->bytes_left = 0;
2639 	}
2640 
2641 	return 0;
2642 }
2643 
2644 /*
2645  * this dumps all file system paths to the inode into the ipath struct, provided
2646  * is has been created large enough. each path is zero-terminated and accessed
2647  * from ipath->fspath->val[i].
2648  * when it returns, there are ipath->fspath->elem_cnt number of paths available
2649  * in ipath->fspath->val[]. when the allocated space wasn't sufficient, the
2650  * number of missed paths is recorded in ipath->fspath->elem_missed, otherwise,
2651  * it's zero. ipath->fspath->bytes_missing holds the number of bytes that would
2652  * have been needed to return all paths.
2653  */
2654 int paths_from_inode(u64 inum, struct inode_fs_paths *ipath)
2655 {
2656 	int ret;
2657 	int found_refs = 0;
2658 
2659 	ret = iterate_inode_refs(inum, ipath);
2660 	if (!ret)
2661 		++found_refs;
2662 	else if (ret != -ENOENT)
2663 		return ret;
2664 
2665 	ret = iterate_inode_extrefs(inum, ipath);
2666 	if (ret == -ENOENT && found_refs)
2667 		return 0;
2668 
2669 	return ret;
2670 }
2671 
2672 struct btrfs_data_container *init_data_container(u32 total_bytes)
2673 {
2674 	struct btrfs_data_container *data;
2675 	size_t alloc_bytes;
2676 
2677 	alloc_bytes = max_t(size_t, total_bytes, sizeof(*data));
2678 	data = kvmalloc(alloc_bytes, GFP_KERNEL);
2679 	if (!data)
2680 		return ERR_PTR(-ENOMEM);
2681 
2682 	if (total_bytes >= sizeof(*data)) {
2683 		data->bytes_left = total_bytes - sizeof(*data);
2684 		data->bytes_missing = 0;
2685 	} else {
2686 		data->bytes_missing = sizeof(*data) - total_bytes;
2687 		data->bytes_left = 0;
2688 	}
2689 
2690 	data->elem_cnt = 0;
2691 	data->elem_missed = 0;
2692 
2693 	return data;
2694 }
2695 
2696 /*
2697  * allocates space to return multiple file system paths for an inode.
2698  * total_bytes to allocate are passed, note that space usable for actual path
2699  * information will be total_bytes - sizeof(struct inode_fs_paths).
2700  * the returned pointer must be freed with free_ipath() in the end.
2701  */
2702 struct inode_fs_paths *init_ipath(s32 total_bytes, struct btrfs_root *fs_root,
2703 					struct btrfs_path *path)
2704 {
2705 	struct inode_fs_paths *ifp;
2706 	struct btrfs_data_container *fspath;
2707 
2708 	fspath = init_data_container(total_bytes);
2709 	if (IS_ERR(fspath))
2710 		return ERR_CAST(fspath);
2711 
2712 	ifp = kmalloc(sizeof(*ifp), GFP_KERNEL);
2713 	if (!ifp) {
2714 		kvfree(fspath);
2715 		return ERR_PTR(-ENOMEM);
2716 	}
2717 
2718 	ifp->btrfs_path = path;
2719 	ifp->fspath = fspath;
2720 	ifp->fs_root = fs_root;
2721 
2722 	return ifp;
2723 }
2724 
2725 void free_ipath(struct inode_fs_paths *ipath)
2726 {
2727 	if (!ipath)
2728 		return;
2729 	kvfree(ipath->fspath);
2730 	kfree(ipath);
2731 }
2732 
2733 struct btrfs_backref_iter *btrfs_backref_iter_alloc(struct btrfs_fs_info *fs_info)
2734 {
2735 	struct btrfs_backref_iter *ret;
2736 
2737 	ret = kzalloc(sizeof(*ret), GFP_NOFS);
2738 	if (!ret)
2739 		return NULL;
2740 
2741 	ret->path = btrfs_alloc_path();
2742 	if (!ret->path) {
2743 		kfree(ret);
2744 		return NULL;
2745 	}
2746 
2747 	/* Current backref iterator only supports iteration in commit root */
2748 	ret->path->search_commit_root = 1;
2749 	ret->path->skip_locking = 1;
2750 	ret->fs_info = fs_info;
2751 
2752 	return ret;
2753 }
2754 
2755 int btrfs_backref_iter_start(struct btrfs_backref_iter *iter, u64 bytenr)
2756 {
2757 	struct btrfs_fs_info *fs_info = iter->fs_info;
2758 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2759 	struct btrfs_path *path = iter->path;
2760 	struct btrfs_extent_item *ei;
2761 	struct btrfs_key key;
2762 	int ret;
2763 
2764 	key.objectid = bytenr;
2765 	key.type = BTRFS_METADATA_ITEM_KEY;
2766 	key.offset = (u64)-1;
2767 	iter->bytenr = bytenr;
2768 
2769 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2770 	if (ret < 0)
2771 		return ret;
2772 	if (ret == 0) {
2773 		ret = -EUCLEAN;
2774 		goto release;
2775 	}
2776 	if (path->slots[0] == 0) {
2777 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
2778 		ret = -EUCLEAN;
2779 		goto release;
2780 	}
2781 	path->slots[0]--;
2782 
2783 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2784 	if ((key.type != BTRFS_EXTENT_ITEM_KEY &&
2785 	     key.type != BTRFS_METADATA_ITEM_KEY) || key.objectid != bytenr) {
2786 		ret = -ENOENT;
2787 		goto release;
2788 	}
2789 	memcpy(&iter->cur_key, &key, sizeof(key));
2790 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2791 						    path->slots[0]);
2792 	iter->end_ptr = (u32)(iter->item_ptr +
2793 			btrfs_item_size(path->nodes[0], path->slots[0]));
2794 	ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
2795 			    struct btrfs_extent_item);
2796 
2797 	/*
2798 	 * Only support iteration on tree backref yet.
2799 	 *
2800 	 * This is an extra precaution for non skinny-metadata, where
2801 	 * EXTENT_ITEM is also used for tree blocks, that we can only use
2802 	 * extent flags to determine if it's a tree block.
2803 	 */
2804 	if (btrfs_extent_flags(path->nodes[0], ei) & BTRFS_EXTENT_FLAG_DATA) {
2805 		ret = -ENOTSUPP;
2806 		goto release;
2807 	}
2808 	iter->cur_ptr = (u32)(iter->item_ptr + sizeof(*ei));
2809 
2810 	/* If there is no inline backref, go search for keyed backref */
2811 	if (iter->cur_ptr >= iter->end_ptr) {
2812 		ret = btrfs_next_item(extent_root, path);
2813 
2814 		/* No inline nor keyed ref */
2815 		if (ret > 0) {
2816 			ret = -ENOENT;
2817 			goto release;
2818 		}
2819 		if (ret < 0)
2820 			goto release;
2821 
2822 		btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key,
2823 				path->slots[0]);
2824 		if (iter->cur_key.objectid != bytenr ||
2825 		    (iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
2826 		     iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY)) {
2827 			ret = -ENOENT;
2828 			goto release;
2829 		}
2830 		iter->cur_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2831 							   path->slots[0]);
2832 		iter->item_ptr = iter->cur_ptr;
2833 		iter->end_ptr = (u32)(iter->item_ptr + btrfs_item_size(
2834 				      path->nodes[0], path->slots[0]));
2835 	}
2836 
2837 	return 0;
2838 release:
2839 	btrfs_backref_iter_release(iter);
2840 	return ret;
2841 }
2842 
2843 /*
2844  * Go to the next backref item of current bytenr, can be either inlined or
2845  * keyed.
2846  *
2847  * Caller needs to check whether it's inline ref or not by iter->cur_key.
2848  *
2849  * Return 0 if we get next backref without problem.
2850  * Return >0 if there is no extra backref for this bytenr.
2851  * Return <0 if there is something wrong happened.
2852  */
2853 int btrfs_backref_iter_next(struct btrfs_backref_iter *iter)
2854 {
2855 	struct extent_buffer *eb = btrfs_backref_get_eb(iter);
2856 	struct btrfs_root *extent_root;
2857 	struct btrfs_path *path = iter->path;
2858 	struct btrfs_extent_inline_ref *iref;
2859 	int ret;
2860 	u32 size;
2861 
2862 	if (btrfs_backref_iter_is_inline_ref(iter)) {
2863 		/* We're still inside the inline refs */
2864 		ASSERT(iter->cur_ptr < iter->end_ptr);
2865 
2866 		if (btrfs_backref_has_tree_block_info(iter)) {
2867 			/* First tree block info */
2868 			size = sizeof(struct btrfs_tree_block_info);
2869 		} else {
2870 			/* Use inline ref type to determine the size */
2871 			int type;
2872 
2873 			iref = (struct btrfs_extent_inline_ref *)
2874 				((unsigned long)iter->cur_ptr);
2875 			type = btrfs_extent_inline_ref_type(eb, iref);
2876 
2877 			size = btrfs_extent_inline_ref_size(type);
2878 		}
2879 		iter->cur_ptr += size;
2880 		if (iter->cur_ptr < iter->end_ptr)
2881 			return 0;
2882 
2883 		/* All inline items iterated, fall through */
2884 	}
2885 
2886 	/* We're at keyed items, there is no inline item, go to the next one */
2887 	extent_root = btrfs_extent_root(iter->fs_info, iter->bytenr);
2888 	ret = btrfs_next_item(extent_root, iter->path);
2889 	if (ret)
2890 		return ret;
2891 
2892 	btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key, path->slots[0]);
2893 	if (iter->cur_key.objectid != iter->bytenr ||
2894 	    (iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
2895 	     iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY))
2896 		return 1;
2897 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2898 					path->slots[0]);
2899 	iter->cur_ptr = iter->item_ptr;
2900 	iter->end_ptr = iter->item_ptr + (u32)btrfs_item_size(path->nodes[0],
2901 						path->slots[0]);
2902 	return 0;
2903 }
2904 
2905 void btrfs_backref_init_cache(struct btrfs_fs_info *fs_info,
2906 			      struct btrfs_backref_cache *cache, int is_reloc)
2907 {
2908 	int i;
2909 
2910 	cache->rb_root = RB_ROOT;
2911 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
2912 		INIT_LIST_HEAD(&cache->pending[i]);
2913 	INIT_LIST_HEAD(&cache->changed);
2914 	INIT_LIST_HEAD(&cache->detached);
2915 	INIT_LIST_HEAD(&cache->leaves);
2916 	INIT_LIST_HEAD(&cache->pending_edge);
2917 	INIT_LIST_HEAD(&cache->useless_node);
2918 	cache->fs_info = fs_info;
2919 	cache->is_reloc = is_reloc;
2920 }
2921 
2922 struct btrfs_backref_node *btrfs_backref_alloc_node(
2923 		struct btrfs_backref_cache *cache, u64 bytenr, int level)
2924 {
2925 	struct btrfs_backref_node *node;
2926 
2927 	ASSERT(level >= 0 && level < BTRFS_MAX_LEVEL);
2928 	node = kzalloc(sizeof(*node), GFP_NOFS);
2929 	if (!node)
2930 		return node;
2931 
2932 	INIT_LIST_HEAD(&node->list);
2933 	INIT_LIST_HEAD(&node->upper);
2934 	INIT_LIST_HEAD(&node->lower);
2935 	RB_CLEAR_NODE(&node->rb_node);
2936 	cache->nr_nodes++;
2937 	node->level = level;
2938 	node->bytenr = bytenr;
2939 
2940 	return node;
2941 }
2942 
2943 struct btrfs_backref_edge *btrfs_backref_alloc_edge(
2944 		struct btrfs_backref_cache *cache)
2945 {
2946 	struct btrfs_backref_edge *edge;
2947 
2948 	edge = kzalloc(sizeof(*edge), GFP_NOFS);
2949 	if (edge)
2950 		cache->nr_edges++;
2951 	return edge;
2952 }
2953 
2954 /*
2955  * Drop the backref node from cache, also cleaning up all its
2956  * upper edges and any uncached nodes in the path.
2957  *
2958  * This cleanup happens bottom up, thus the node should either
2959  * be the lowest node in the cache or a detached node.
2960  */
2961 void btrfs_backref_cleanup_node(struct btrfs_backref_cache *cache,
2962 				struct btrfs_backref_node *node)
2963 {
2964 	struct btrfs_backref_node *upper;
2965 	struct btrfs_backref_edge *edge;
2966 
2967 	if (!node)
2968 		return;
2969 
2970 	BUG_ON(!node->lowest && !node->detached);
2971 	while (!list_empty(&node->upper)) {
2972 		edge = list_entry(node->upper.next, struct btrfs_backref_edge,
2973 				  list[LOWER]);
2974 		upper = edge->node[UPPER];
2975 		list_del(&edge->list[LOWER]);
2976 		list_del(&edge->list[UPPER]);
2977 		btrfs_backref_free_edge(cache, edge);
2978 
2979 		/*
2980 		 * Add the node to leaf node list if no other child block
2981 		 * cached.
2982 		 */
2983 		if (list_empty(&upper->lower)) {
2984 			list_add_tail(&upper->lower, &cache->leaves);
2985 			upper->lowest = 1;
2986 		}
2987 	}
2988 
2989 	btrfs_backref_drop_node(cache, node);
2990 }
2991 
2992 /*
2993  * Release all nodes/edges from current cache
2994  */
2995 void btrfs_backref_release_cache(struct btrfs_backref_cache *cache)
2996 {
2997 	struct btrfs_backref_node *node;
2998 	int i;
2999 
3000 	while (!list_empty(&cache->detached)) {
3001 		node = list_entry(cache->detached.next,
3002 				  struct btrfs_backref_node, list);
3003 		btrfs_backref_cleanup_node(cache, node);
3004 	}
3005 
3006 	while (!list_empty(&cache->leaves)) {
3007 		node = list_entry(cache->leaves.next,
3008 				  struct btrfs_backref_node, lower);
3009 		btrfs_backref_cleanup_node(cache, node);
3010 	}
3011 
3012 	cache->last_trans = 0;
3013 
3014 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
3015 		ASSERT(list_empty(&cache->pending[i]));
3016 	ASSERT(list_empty(&cache->pending_edge));
3017 	ASSERT(list_empty(&cache->useless_node));
3018 	ASSERT(list_empty(&cache->changed));
3019 	ASSERT(list_empty(&cache->detached));
3020 	ASSERT(RB_EMPTY_ROOT(&cache->rb_root));
3021 	ASSERT(!cache->nr_nodes);
3022 	ASSERT(!cache->nr_edges);
3023 }
3024 
3025 /*
3026  * Handle direct tree backref
3027  *
3028  * Direct tree backref means, the backref item shows its parent bytenr
3029  * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
3030  *
3031  * @ref_key:	The converted backref key.
3032  *		For keyed backref, it's the item key.
3033  *		For inlined backref, objectid is the bytenr,
3034  *		type is btrfs_inline_ref_type, offset is
3035  *		btrfs_inline_ref_offset.
3036  */
3037 static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
3038 				      struct btrfs_key *ref_key,
3039 				      struct btrfs_backref_node *cur)
3040 {
3041 	struct btrfs_backref_edge *edge;
3042 	struct btrfs_backref_node *upper;
3043 	struct rb_node *rb_node;
3044 
3045 	ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
3046 
3047 	/* Only reloc root uses backref pointing to itself */
3048 	if (ref_key->objectid == ref_key->offset) {
3049 		struct btrfs_root *root;
3050 
3051 		cur->is_reloc_root = 1;
3052 		/* Only reloc backref cache cares about a specific root */
3053 		if (cache->is_reloc) {
3054 			root = find_reloc_root(cache->fs_info, cur->bytenr);
3055 			if (!root)
3056 				return -ENOENT;
3057 			cur->root = root;
3058 		} else {
3059 			/*
3060 			 * For generic purpose backref cache, reloc root node
3061 			 * is useless.
3062 			 */
3063 			list_add(&cur->list, &cache->useless_node);
3064 		}
3065 		return 0;
3066 	}
3067 
3068 	edge = btrfs_backref_alloc_edge(cache);
3069 	if (!edge)
3070 		return -ENOMEM;
3071 
3072 	rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
3073 	if (!rb_node) {
3074 		/* Parent node not yet cached */
3075 		upper = btrfs_backref_alloc_node(cache, ref_key->offset,
3076 					   cur->level + 1);
3077 		if (!upper) {
3078 			btrfs_backref_free_edge(cache, edge);
3079 			return -ENOMEM;
3080 		}
3081 
3082 		/*
3083 		 *  Backrefs for the upper level block isn't cached, add the
3084 		 *  block to pending list
3085 		 */
3086 		list_add_tail(&edge->list[UPPER], &cache->pending_edge);
3087 	} else {
3088 		/* Parent node already cached */
3089 		upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
3090 		ASSERT(upper->checked);
3091 		INIT_LIST_HEAD(&edge->list[UPPER]);
3092 	}
3093 	btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
3094 	return 0;
3095 }
3096 
3097 /*
3098  * Handle indirect tree backref
3099  *
3100  * Indirect tree backref means, we only know which tree the node belongs to.
3101  * We still need to do a tree search to find out the parents. This is for
3102  * TREE_BLOCK_REF backref (keyed or inlined).
3103  *
3104  * @ref_key:	The same as @ref_key in  handle_direct_tree_backref()
3105  * @tree_key:	The first key of this tree block.
3106  * @path:	A clean (released) path, to avoid allocating path every time
3107  *		the function get called.
3108  */
3109 static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
3110 					struct btrfs_path *path,
3111 					struct btrfs_key *ref_key,
3112 					struct btrfs_key *tree_key,
3113 					struct btrfs_backref_node *cur)
3114 {
3115 	struct btrfs_fs_info *fs_info = cache->fs_info;
3116 	struct btrfs_backref_node *upper;
3117 	struct btrfs_backref_node *lower;
3118 	struct btrfs_backref_edge *edge;
3119 	struct extent_buffer *eb;
3120 	struct btrfs_root *root;
3121 	struct rb_node *rb_node;
3122 	int level;
3123 	bool need_check = true;
3124 	int ret;
3125 
3126 	root = btrfs_get_fs_root(fs_info, ref_key->offset, false);
3127 	if (IS_ERR(root))
3128 		return PTR_ERR(root);
3129 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
3130 		cur->cowonly = 1;
3131 
3132 	if (btrfs_root_level(&root->root_item) == cur->level) {
3133 		/* Tree root */
3134 		ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
3135 		/*
3136 		 * For reloc backref cache, we may ignore reloc root.  But for
3137 		 * general purpose backref cache, we can't rely on
3138 		 * btrfs_should_ignore_reloc_root() as it may conflict with
3139 		 * current running relocation and lead to missing root.
3140 		 *
3141 		 * For general purpose backref cache, reloc root detection is
3142 		 * completely relying on direct backref (key->offset is parent
3143 		 * bytenr), thus only do such check for reloc cache.
3144 		 */
3145 		if (btrfs_should_ignore_reloc_root(root) && cache->is_reloc) {
3146 			btrfs_put_root(root);
3147 			list_add(&cur->list, &cache->useless_node);
3148 		} else {
3149 			cur->root = root;
3150 		}
3151 		return 0;
3152 	}
3153 
3154 	level = cur->level + 1;
3155 
3156 	/* Search the tree to find parent blocks referring to the block */
3157 	path->search_commit_root = 1;
3158 	path->skip_locking = 1;
3159 	path->lowest_level = level;
3160 	ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
3161 	path->lowest_level = 0;
3162 	if (ret < 0) {
3163 		btrfs_put_root(root);
3164 		return ret;
3165 	}
3166 	if (ret > 0 && path->slots[level] > 0)
3167 		path->slots[level]--;
3168 
3169 	eb = path->nodes[level];
3170 	if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
3171 		btrfs_err(fs_info,
3172 "couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
3173 			  cur->bytenr, level - 1, root->root_key.objectid,
3174 			  tree_key->objectid, tree_key->type, tree_key->offset);
3175 		btrfs_put_root(root);
3176 		ret = -ENOENT;
3177 		goto out;
3178 	}
3179 	lower = cur;
3180 
3181 	/* Add all nodes and edges in the path */
3182 	for (; level < BTRFS_MAX_LEVEL; level++) {
3183 		if (!path->nodes[level]) {
3184 			ASSERT(btrfs_root_bytenr(&root->root_item) ==
3185 			       lower->bytenr);
3186 			/* Same as previous should_ignore_reloc_root() call */
3187 			if (btrfs_should_ignore_reloc_root(root) &&
3188 			    cache->is_reloc) {
3189 				btrfs_put_root(root);
3190 				list_add(&lower->list, &cache->useless_node);
3191 			} else {
3192 				lower->root = root;
3193 			}
3194 			break;
3195 		}
3196 
3197 		edge = btrfs_backref_alloc_edge(cache);
3198 		if (!edge) {
3199 			btrfs_put_root(root);
3200 			ret = -ENOMEM;
3201 			goto out;
3202 		}
3203 
3204 		eb = path->nodes[level];
3205 		rb_node = rb_simple_search(&cache->rb_root, eb->start);
3206 		if (!rb_node) {
3207 			upper = btrfs_backref_alloc_node(cache, eb->start,
3208 							 lower->level + 1);
3209 			if (!upper) {
3210 				btrfs_put_root(root);
3211 				btrfs_backref_free_edge(cache, edge);
3212 				ret = -ENOMEM;
3213 				goto out;
3214 			}
3215 			upper->owner = btrfs_header_owner(eb);
3216 			if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
3217 				upper->cowonly = 1;
3218 
3219 			/*
3220 			 * If we know the block isn't shared we can avoid
3221 			 * checking its backrefs.
3222 			 */
3223 			if (btrfs_block_can_be_shared(root, eb))
3224 				upper->checked = 0;
3225 			else
3226 				upper->checked = 1;
3227 
3228 			/*
3229 			 * Add the block to pending list if we need to check its
3230 			 * backrefs, we only do this once while walking up a
3231 			 * tree as we will catch anything else later on.
3232 			 */
3233 			if (!upper->checked && need_check) {
3234 				need_check = false;
3235 				list_add_tail(&edge->list[UPPER],
3236 					      &cache->pending_edge);
3237 			} else {
3238 				if (upper->checked)
3239 					need_check = true;
3240 				INIT_LIST_HEAD(&edge->list[UPPER]);
3241 			}
3242 		} else {
3243 			upper = rb_entry(rb_node, struct btrfs_backref_node,
3244 					 rb_node);
3245 			ASSERT(upper->checked);
3246 			INIT_LIST_HEAD(&edge->list[UPPER]);
3247 			if (!upper->owner)
3248 				upper->owner = btrfs_header_owner(eb);
3249 		}
3250 		btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
3251 
3252 		if (rb_node) {
3253 			btrfs_put_root(root);
3254 			break;
3255 		}
3256 		lower = upper;
3257 		upper = NULL;
3258 	}
3259 out:
3260 	btrfs_release_path(path);
3261 	return ret;
3262 }
3263 
3264 /*
3265  * Add backref node @cur into @cache.
3266  *
3267  * NOTE: Even if the function returned 0, @cur is not yet cached as its upper
3268  *	 links aren't yet bi-directional. Needs to finish such links.
3269  *	 Use btrfs_backref_finish_upper_links() to finish such linkage.
3270  *
3271  * @path:	Released path for indirect tree backref lookup
3272  * @iter:	Released backref iter for extent tree search
3273  * @node_key:	The first key of the tree block
3274  */
3275 int btrfs_backref_add_tree_node(struct btrfs_backref_cache *cache,
3276 				struct btrfs_path *path,
3277 				struct btrfs_backref_iter *iter,
3278 				struct btrfs_key *node_key,
3279 				struct btrfs_backref_node *cur)
3280 {
3281 	struct btrfs_fs_info *fs_info = cache->fs_info;
3282 	struct btrfs_backref_edge *edge;
3283 	struct btrfs_backref_node *exist;
3284 	int ret;
3285 
3286 	ret = btrfs_backref_iter_start(iter, cur->bytenr);
3287 	if (ret < 0)
3288 		return ret;
3289 	/*
3290 	 * We skip the first btrfs_tree_block_info, as we don't use the key
3291 	 * stored in it, but fetch it from the tree block
3292 	 */
3293 	if (btrfs_backref_has_tree_block_info(iter)) {
3294 		ret = btrfs_backref_iter_next(iter);
3295 		if (ret < 0)
3296 			goto out;
3297 		/* No extra backref? This means the tree block is corrupted */
3298 		if (ret > 0) {
3299 			ret = -EUCLEAN;
3300 			goto out;
3301 		}
3302 	}
3303 	WARN_ON(cur->checked);
3304 	if (!list_empty(&cur->upper)) {
3305 		/*
3306 		 * The backref was added previously when processing backref of
3307 		 * type BTRFS_TREE_BLOCK_REF_KEY
3308 		 */
3309 		ASSERT(list_is_singular(&cur->upper));
3310 		edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
3311 				  list[LOWER]);
3312 		ASSERT(list_empty(&edge->list[UPPER]));
3313 		exist = edge->node[UPPER];
3314 		/*
3315 		 * Add the upper level block to pending list if we need check
3316 		 * its backrefs
3317 		 */
3318 		if (!exist->checked)
3319 			list_add_tail(&edge->list[UPPER], &cache->pending_edge);
3320 	} else {
3321 		exist = NULL;
3322 	}
3323 
3324 	for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
3325 		struct extent_buffer *eb;
3326 		struct btrfs_key key;
3327 		int type;
3328 
3329 		cond_resched();
3330 		eb = btrfs_backref_get_eb(iter);
3331 
3332 		key.objectid = iter->bytenr;
3333 		if (btrfs_backref_iter_is_inline_ref(iter)) {
3334 			struct btrfs_extent_inline_ref *iref;
3335 
3336 			/* Update key for inline backref */
3337 			iref = (struct btrfs_extent_inline_ref *)
3338 				((unsigned long)iter->cur_ptr);
3339 			type = btrfs_get_extent_inline_ref_type(eb, iref,
3340 							BTRFS_REF_TYPE_BLOCK);
3341 			if (type == BTRFS_REF_TYPE_INVALID) {
3342 				ret = -EUCLEAN;
3343 				goto out;
3344 			}
3345 			key.type = type;
3346 			key.offset = btrfs_extent_inline_ref_offset(eb, iref);
3347 		} else {
3348 			key.type = iter->cur_key.type;
3349 			key.offset = iter->cur_key.offset;
3350 		}
3351 
3352 		/*
3353 		 * Parent node found and matches current inline ref, no need to
3354 		 * rebuild this node for this inline ref
3355 		 */
3356 		if (exist &&
3357 		    ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
3358 		      exist->owner == key.offset) ||
3359 		     (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
3360 		      exist->bytenr == key.offset))) {
3361 			exist = NULL;
3362 			continue;
3363 		}
3364 
3365 		/* SHARED_BLOCK_REF means key.offset is the parent bytenr */
3366 		if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
3367 			ret = handle_direct_tree_backref(cache, &key, cur);
3368 			if (ret < 0)
3369 				goto out;
3370 			continue;
3371 		} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
3372 			ret = -EINVAL;
3373 			btrfs_print_v0_err(fs_info);
3374 			btrfs_handle_fs_error(fs_info, ret, NULL);
3375 			goto out;
3376 		} else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
3377 			continue;
3378 		}
3379 
3380 		/*
3381 		 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
3382 		 * means the root objectid. We need to search the tree to get
3383 		 * its parent bytenr.
3384 		 */
3385 		ret = handle_indirect_tree_backref(cache, path, &key, node_key,
3386 						   cur);
3387 		if (ret < 0)
3388 			goto out;
3389 	}
3390 	ret = 0;
3391 	cur->checked = 1;
3392 	WARN_ON(exist);
3393 out:
3394 	btrfs_backref_iter_release(iter);
3395 	return ret;
3396 }
3397 
3398 /*
3399  * Finish the upwards linkage created by btrfs_backref_add_tree_node()
3400  */
3401 int btrfs_backref_finish_upper_links(struct btrfs_backref_cache *cache,
3402 				     struct btrfs_backref_node *start)
3403 {
3404 	struct list_head *useless_node = &cache->useless_node;
3405 	struct btrfs_backref_edge *edge;
3406 	struct rb_node *rb_node;
3407 	LIST_HEAD(pending_edge);
3408 
3409 	ASSERT(start->checked);
3410 
3411 	/* Insert this node to cache if it's not COW-only */
3412 	if (!start->cowonly) {
3413 		rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
3414 					   &start->rb_node);
3415 		if (rb_node)
3416 			btrfs_backref_panic(cache->fs_info, start->bytenr,
3417 					    -EEXIST);
3418 		list_add_tail(&start->lower, &cache->leaves);
3419 	}
3420 
3421 	/*
3422 	 * Use breadth first search to iterate all related edges.
3423 	 *
3424 	 * The starting points are all the edges of this node
3425 	 */
3426 	list_for_each_entry(edge, &start->upper, list[LOWER])
3427 		list_add_tail(&edge->list[UPPER], &pending_edge);
3428 
3429 	while (!list_empty(&pending_edge)) {
3430 		struct btrfs_backref_node *upper;
3431 		struct btrfs_backref_node *lower;
3432 
3433 		edge = list_first_entry(&pending_edge,
3434 				struct btrfs_backref_edge, list[UPPER]);
3435 		list_del_init(&edge->list[UPPER]);
3436 		upper = edge->node[UPPER];
3437 		lower = edge->node[LOWER];
3438 
3439 		/* Parent is detached, no need to keep any edges */
3440 		if (upper->detached) {
3441 			list_del(&edge->list[LOWER]);
3442 			btrfs_backref_free_edge(cache, edge);
3443 
3444 			/* Lower node is orphan, queue for cleanup */
3445 			if (list_empty(&lower->upper))
3446 				list_add(&lower->list, useless_node);
3447 			continue;
3448 		}
3449 
3450 		/*
3451 		 * All new nodes added in current build_backref_tree() haven't
3452 		 * been linked to the cache rb tree.
3453 		 * So if we have upper->rb_node populated, this means a cache
3454 		 * hit. We only need to link the edge, as @upper and all its
3455 		 * parents have already been linked.
3456 		 */
3457 		if (!RB_EMPTY_NODE(&upper->rb_node)) {
3458 			if (upper->lowest) {
3459 				list_del_init(&upper->lower);
3460 				upper->lowest = 0;
3461 			}
3462 
3463 			list_add_tail(&edge->list[UPPER], &upper->lower);
3464 			continue;
3465 		}
3466 
3467 		/* Sanity check, we shouldn't have any unchecked nodes */
3468 		if (!upper->checked) {
3469 			ASSERT(0);
3470 			return -EUCLEAN;
3471 		}
3472 
3473 		/* Sanity check, COW-only node has non-COW-only parent */
3474 		if (start->cowonly != upper->cowonly) {
3475 			ASSERT(0);
3476 			return -EUCLEAN;
3477 		}
3478 
3479 		/* Only cache non-COW-only (subvolume trees) tree blocks */
3480 		if (!upper->cowonly) {
3481 			rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
3482 						   &upper->rb_node);
3483 			if (rb_node) {
3484 				btrfs_backref_panic(cache->fs_info,
3485 						upper->bytenr, -EEXIST);
3486 				return -EUCLEAN;
3487 			}
3488 		}
3489 
3490 		list_add_tail(&edge->list[UPPER], &upper->lower);
3491 
3492 		/*
3493 		 * Also queue all the parent edges of this uncached node
3494 		 * to finish the upper linkage
3495 		 */
3496 		list_for_each_entry(edge, &upper->upper, list[LOWER])
3497 			list_add_tail(&edge->list[UPPER], &pending_edge);
3498 	}
3499 	return 0;
3500 }
3501 
3502 void btrfs_backref_error_cleanup(struct btrfs_backref_cache *cache,
3503 				 struct btrfs_backref_node *node)
3504 {
3505 	struct btrfs_backref_node *lower;
3506 	struct btrfs_backref_node *upper;
3507 	struct btrfs_backref_edge *edge;
3508 
3509 	while (!list_empty(&cache->useless_node)) {
3510 		lower = list_first_entry(&cache->useless_node,
3511 				   struct btrfs_backref_node, list);
3512 		list_del_init(&lower->list);
3513 	}
3514 	while (!list_empty(&cache->pending_edge)) {
3515 		edge = list_first_entry(&cache->pending_edge,
3516 				struct btrfs_backref_edge, list[UPPER]);
3517 		list_del(&edge->list[UPPER]);
3518 		list_del(&edge->list[LOWER]);
3519 		lower = edge->node[LOWER];
3520 		upper = edge->node[UPPER];
3521 		btrfs_backref_free_edge(cache, edge);
3522 
3523 		/*
3524 		 * Lower is no longer linked to any upper backref nodes and
3525 		 * isn't in the cache, we can free it ourselves.
3526 		 */
3527 		if (list_empty(&lower->upper) &&
3528 		    RB_EMPTY_NODE(&lower->rb_node))
3529 			list_add(&lower->list, &cache->useless_node);
3530 
3531 		if (!RB_EMPTY_NODE(&upper->rb_node))
3532 			continue;
3533 
3534 		/* Add this guy's upper edges to the list to process */
3535 		list_for_each_entry(edge, &upper->upper, list[LOWER])
3536 			list_add_tail(&edge->list[UPPER],
3537 				      &cache->pending_edge);
3538 		if (list_empty(&upper->upper))
3539 			list_add(&upper->list, &cache->useless_node);
3540 	}
3541 
3542 	while (!list_empty(&cache->useless_node)) {
3543 		lower = list_first_entry(&cache->useless_node,
3544 				   struct btrfs_backref_node, list);
3545 		list_del_init(&lower->list);
3546 		if (lower == node)
3547 			node = NULL;
3548 		btrfs_backref_drop_node(cache, lower);
3549 	}
3550 
3551 	btrfs_backref_cleanup_node(cache, node);
3552 	ASSERT(list_empty(&cache->useless_node) &&
3553 	       list_empty(&cache->pending_edge));
3554 }
3555