xref: /openbmc/linux/fs/btrfs/backref.c (revision f73853c7168aef0e071c160979af05a148691e61)
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(struct btrfs_backref_walk_ctx *ctx,
1007 			   struct btrfs_path *path,
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 
1033 	if (ctx->check_extent_item) {
1034 		ret = ctx->check_extent_item(ctx->bytenr, ei, leaf, ctx->user_ctx);
1035 		if (ret)
1036 			return ret;
1037 	}
1038 
1039 	flags = btrfs_extent_flags(leaf, ei);
1040 	btrfs_item_key_to_cpu(leaf, &found_key, slot);
1041 
1042 	ptr = (unsigned long)(ei + 1);
1043 	end = (unsigned long)ei + item_size;
1044 
1045 	if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
1046 	    flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1047 		struct btrfs_tree_block_info *info;
1048 
1049 		info = (struct btrfs_tree_block_info *)ptr;
1050 		*info_level = btrfs_tree_block_level(leaf, info);
1051 		ptr += sizeof(struct btrfs_tree_block_info);
1052 		BUG_ON(ptr > end);
1053 	} else if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
1054 		*info_level = found_key.offset;
1055 	} else {
1056 		BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
1057 	}
1058 
1059 	while (ptr < end) {
1060 		struct btrfs_extent_inline_ref *iref;
1061 		u64 offset;
1062 		int type;
1063 
1064 		iref = (struct btrfs_extent_inline_ref *)ptr;
1065 		type = btrfs_get_extent_inline_ref_type(leaf, iref,
1066 							BTRFS_REF_TYPE_ANY);
1067 		if (type == BTRFS_REF_TYPE_INVALID)
1068 			return -EUCLEAN;
1069 
1070 		offset = btrfs_extent_inline_ref_offset(leaf, iref);
1071 
1072 		switch (type) {
1073 		case BTRFS_SHARED_BLOCK_REF_KEY:
1074 			ret = add_direct_ref(ctx->fs_info, preftrees,
1075 					     *info_level + 1, offset,
1076 					     ctx->bytenr, 1, NULL, GFP_NOFS);
1077 			break;
1078 		case BTRFS_SHARED_DATA_REF_KEY: {
1079 			struct btrfs_shared_data_ref *sdref;
1080 			int count;
1081 
1082 			sdref = (struct btrfs_shared_data_ref *)(iref + 1);
1083 			count = btrfs_shared_data_ref_count(leaf, sdref);
1084 
1085 			ret = add_direct_ref(ctx->fs_info, preftrees, 0, offset,
1086 					     ctx->bytenr, count, sc, GFP_NOFS);
1087 			break;
1088 		}
1089 		case BTRFS_TREE_BLOCK_REF_KEY:
1090 			ret = add_indirect_ref(ctx->fs_info, preftrees, offset,
1091 					       NULL, *info_level + 1,
1092 					       ctx->bytenr, 1, NULL, GFP_NOFS);
1093 			break;
1094 		case BTRFS_EXTENT_DATA_REF_KEY: {
1095 			struct btrfs_extent_data_ref *dref;
1096 			int count;
1097 			u64 root;
1098 
1099 			dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1100 			count = btrfs_extent_data_ref_count(leaf, dref);
1101 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
1102 								      dref);
1103 			key.type = BTRFS_EXTENT_DATA_KEY;
1104 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1105 
1106 			if (sc && key.objectid != sc->inum &&
1107 			    !sc->have_delayed_delete_refs) {
1108 				ret = BACKREF_FOUND_SHARED;
1109 				break;
1110 			}
1111 
1112 			root = btrfs_extent_data_ref_root(leaf, dref);
1113 
1114 			ret = add_indirect_ref(ctx->fs_info, preftrees, root,
1115 					       &key, 0, ctx->bytenr, count,
1116 					       sc, GFP_NOFS);
1117 
1118 			break;
1119 		}
1120 		default:
1121 			WARN_ON(1);
1122 		}
1123 		if (ret)
1124 			return ret;
1125 		ptr += btrfs_extent_inline_ref_size(type);
1126 	}
1127 
1128 	return 0;
1129 }
1130 
1131 /*
1132  * add all non-inline backrefs for bytenr to the list
1133  *
1134  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
1135  */
1136 static int add_keyed_refs(struct btrfs_root *extent_root,
1137 			  struct btrfs_path *path, u64 bytenr,
1138 			  int info_level, struct preftrees *preftrees,
1139 			  struct share_check *sc)
1140 {
1141 	struct btrfs_fs_info *fs_info = extent_root->fs_info;
1142 	int ret;
1143 	int slot;
1144 	struct extent_buffer *leaf;
1145 	struct btrfs_key key;
1146 
1147 	while (1) {
1148 		ret = btrfs_next_item(extent_root, path);
1149 		if (ret < 0)
1150 			break;
1151 		if (ret) {
1152 			ret = 0;
1153 			break;
1154 		}
1155 
1156 		slot = path->slots[0];
1157 		leaf = path->nodes[0];
1158 		btrfs_item_key_to_cpu(leaf, &key, slot);
1159 
1160 		if (key.objectid != bytenr)
1161 			break;
1162 		if (key.type < BTRFS_TREE_BLOCK_REF_KEY)
1163 			continue;
1164 		if (key.type > BTRFS_SHARED_DATA_REF_KEY)
1165 			break;
1166 
1167 		switch (key.type) {
1168 		case BTRFS_SHARED_BLOCK_REF_KEY:
1169 			/* SHARED DIRECT METADATA backref */
1170 			ret = add_direct_ref(fs_info, preftrees,
1171 					     info_level + 1, key.offset,
1172 					     bytenr, 1, NULL, GFP_NOFS);
1173 			break;
1174 		case BTRFS_SHARED_DATA_REF_KEY: {
1175 			/* SHARED DIRECT FULL backref */
1176 			struct btrfs_shared_data_ref *sdref;
1177 			int count;
1178 
1179 			sdref = btrfs_item_ptr(leaf, slot,
1180 					      struct btrfs_shared_data_ref);
1181 			count = btrfs_shared_data_ref_count(leaf, sdref);
1182 			ret = add_direct_ref(fs_info, preftrees, 0,
1183 					     key.offset, bytenr, count,
1184 					     sc, GFP_NOFS);
1185 			break;
1186 		}
1187 		case BTRFS_TREE_BLOCK_REF_KEY:
1188 			/* NORMAL INDIRECT METADATA backref */
1189 			ret = add_indirect_ref(fs_info, preftrees, key.offset,
1190 					       NULL, info_level + 1, bytenr,
1191 					       1, NULL, GFP_NOFS);
1192 			break;
1193 		case BTRFS_EXTENT_DATA_REF_KEY: {
1194 			/* NORMAL INDIRECT DATA backref */
1195 			struct btrfs_extent_data_ref *dref;
1196 			int count;
1197 			u64 root;
1198 
1199 			dref = btrfs_item_ptr(leaf, slot,
1200 					      struct btrfs_extent_data_ref);
1201 			count = btrfs_extent_data_ref_count(leaf, dref);
1202 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
1203 								      dref);
1204 			key.type = BTRFS_EXTENT_DATA_KEY;
1205 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1206 
1207 			if (sc && key.objectid != sc->inum &&
1208 			    !sc->have_delayed_delete_refs) {
1209 				ret = BACKREF_FOUND_SHARED;
1210 				break;
1211 			}
1212 
1213 			root = btrfs_extent_data_ref_root(leaf, dref);
1214 			ret = add_indirect_ref(fs_info, preftrees, root,
1215 					       &key, 0, bytenr, count,
1216 					       sc, GFP_NOFS);
1217 			break;
1218 		}
1219 		default:
1220 			WARN_ON(1);
1221 		}
1222 		if (ret)
1223 			return ret;
1224 
1225 	}
1226 
1227 	return ret;
1228 }
1229 
1230 /*
1231  * The caller has joined a transaction or is holding a read lock on the
1232  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1233  * snapshot field changing while updating or checking the cache.
1234  */
1235 static bool lookup_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1236 					struct btrfs_root *root,
1237 					u64 bytenr, int level, bool *is_shared)
1238 {
1239 	struct btrfs_backref_shared_cache_entry *entry;
1240 
1241 	if (!ctx->use_path_cache)
1242 		return false;
1243 
1244 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1245 		return false;
1246 
1247 	/*
1248 	 * Level -1 is used for the data extent, which is not reliable to cache
1249 	 * because its reference count can increase or decrease without us
1250 	 * realizing. We cache results only for extent buffers that lead from
1251 	 * the root node down to the leaf with the file extent item.
1252 	 */
1253 	ASSERT(level >= 0);
1254 
1255 	entry = &ctx->path_cache_entries[level];
1256 
1257 	/* Unused cache entry or being used for some other extent buffer. */
1258 	if (entry->bytenr != bytenr)
1259 		return false;
1260 
1261 	/*
1262 	 * We cached a false result, but the last snapshot generation of the
1263 	 * root changed, so we now have a snapshot. Don't trust the result.
1264 	 */
1265 	if (!entry->is_shared &&
1266 	    entry->gen != btrfs_root_last_snapshot(&root->root_item))
1267 		return false;
1268 
1269 	/*
1270 	 * If we cached a true result and the last generation used for dropping
1271 	 * a root changed, we can not trust the result, because the dropped root
1272 	 * could be a snapshot sharing this extent buffer.
1273 	 */
1274 	if (entry->is_shared &&
1275 	    entry->gen != btrfs_get_last_root_drop_gen(root->fs_info))
1276 		return false;
1277 
1278 	*is_shared = entry->is_shared;
1279 	/*
1280 	 * If the node at this level is shared, than all nodes below are also
1281 	 * shared. Currently some of the nodes below may be marked as not shared
1282 	 * because we have just switched from one leaf to another, and switched
1283 	 * also other nodes above the leaf and below the current level, so mark
1284 	 * them as shared.
1285 	 */
1286 	if (*is_shared) {
1287 		for (int i = 0; i < level; i++) {
1288 			ctx->path_cache_entries[i].is_shared = true;
1289 			ctx->path_cache_entries[i].gen = entry->gen;
1290 		}
1291 	}
1292 
1293 	return true;
1294 }
1295 
1296 /*
1297  * The caller has joined a transaction or is holding a read lock on the
1298  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1299  * snapshot field changing while updating or checking the cache.
1300  */
1301 static void store_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1302 				       struct btrfs_root *root,
1303 				       u64 bytenr, int level, bool is_shared)
1304 {
1305 	struct btrfs_backref_shared_cache_entry *entry;
1306 	u64 gen;
1307 
1308 	if (!ctx->use_path_cache)
1309 		return;
1310 
1311 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1312 		return;
1313 
1314 	/*
1315 	 * Level -1 is used for the data extent, which is not reliable to cache
1316 	 * because its reference count can increase or decrease without us
1317 	 * realizing. We cache results only for extent buffers that lead from
1318 	 * the root node down to the leaf with the file extent item.
1319 	 */
1320 	ASSERT(level >= 0);
1321 
1322 	if (is_shared)
1323 		gen = btrfs_get_last_root_drop_gen(root->fs_info);
1324 	else
1325 		gen = btrfs_root_last_snapshot(&root->root_item);
1326 
1327 	entry = &ctx->path_cache_entries[level];
1328 	entry->bytenr = bytenr;
1329 	entry->is_shared = is_shared;
1330 	entry->gen = gen;
1331 
1332 	/*
1333 	 * If we found an extent buffer is shared, set the cache result for all
1334 	 * extent buffers below it to true. As nodes in the path are COWed,
1335 	 * their sharedness is moved to their children, and if a leaf is COWed,
1336 	 * then the sharedness of a data extent becomes direct, the refcount of
1337 	 * data extent is increased in the extent item at the extent tree.
1338 	 */
1339 	if (is_shared) {
1340 		for (int i = 0; i < level; i++) {
1341 			entry = &ctx->path_cache_entries[i];
1342 			entry->is_shared = is_shared;
1343 			entry->gen = gen;
1344 		}
1345 	}
1346 }
1347 
1348 /*
1349  * this adds all existing backrefs (inline backrefs, backrefs and delayed
1350  * refs) for the given bytenr to the refs list, merges duplicates and resolves
1351  * indirect refs to their parent bytenr.
1352  * When roots are found, they're added to the roots list
1353  *
1354  * @ctx:     Backref walking context object, must be not NULL.
1355  * @sc:      If !NULL, then immediately return BACKREF_FOUND_SHARED when a
1356  *           shared extent is detected.
1357  *
1358  * Otherwise this returns 0 for success and <0 for an error.
1359  *
1360  * FIXME some caching might speed things up
1361  */
1362 static int find_parent_nodes(struct btrfs_backref_walk_ctx *ctx,
1363 			     struct share_check *sc)
1364 {
1365 	struct btrfs_root *root = btrfs_extent_root(ctx->fs_info, ctx->bytenr);
1366 	struct btrfs_key key;
1367 	struct btrfs_path *path;
1368 	struct btrfs_delayed_ref_root *delayed_refs = NULL;
1369 	struct btrfs_delayed_ref_head *head;
1370 	int info_level = 0;
1371 	int ret;
1372 	struct prelim_ref *ref;
1373 	struct rb_node *node;
1374 	struct extent_inode_elem *eie = NULL;
1375 	struct preftrees preftrees = {
1376 		.direct = PREFTREE_INIT,
1377 		.indirect = PREFTREE_INIT,
1378 		.indirect_missing_keys = PREFTREE_INIT
1379 	};
1380 
1381 	/* Roots ulist is not needed when using a sharedness check context. */
1382 	if (sc)
1383 		ASSERT(ctx->roots == NULL);
1384 
1385 	key.objectid = ctx->bytenr;
1386 	key.offset = (u64)-1;
1387 	if (btrfs_fs_incompat(ctx->fs_info, SKINNY_METADATA))
1388 		key.type = BTRFS_METADATA_ITEM_KEY;
1389 	else
1390 		key.type = BTRFS_EXTENT_ITEM_KEY;
1391 
1392 	path = btrfs_alloc_path();
1393 	if (!path)
1394 		return -ENOMEM;
1395 	if (!ctx->trans) {
1396 		path->search_commit_root = 1;
1397 		path->skip_locking = 1;
1398 	}
1399 
1400 	if (ctx->time_seq == BTRFS_SEQ_LAST)
1401 		path->skip_locking = 1;
1402 
1403 again:
1404 	head = NULL;
1405 
1406 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1407 	if (ret < 0)
1408 		goto out;
1409 	if (ret == 0) {
1410 		/* This shouldn't happen, indicates a bug or fs corruption. */
1411 		ASSERT(ret != 0);
1412 		ret = -EUCLEAN;
1413 		goto out;
1414 	}
1415 
1416 	if (ctx->trans && likely(ctx->trans->type != __TRANS_DUMMY) &&
1417 	    ctx->time_seq != BTRFS_SEQ_LAST) {
1418 		/*
1419 		 * We have a specific time_seq we care about and trans which
1420 		 * means we have the path lock, we need to grab the ref head and
1421 		 * lock it so we have a consistent view of the refs at the given
1422 		 * time.
1423 		 */
1424 		delayed_refs = &ctx->trans->transaction->delayed_refs;
1425 		spin_lock(&delayed_refs->lock);
1426 		head = btrfs_find_delayed_ref_head(delayed_refs, ctx->bytenr);
1427 		if (head) {
1428 			if (!mutex_trylock(&head->mutex)) {
1429 				refcount_inc(&head->refs);
1430 				spin_unlock(&delayed_refs->lock);
1431 
1432 				btrfs_release_path(path);
1433 
1434 				/*
1435 				 * Mutex was contended, block until it's
1436 				 * released and try again
1437 				 */
1438 				mutex_lock(&head->mutex);
1439 				mutex_unlock(&head->mutex);
1440 				btrfs_put_delayed_ref_head(head);
1441 				goto again;
1442 			}
1443 			spin_unlock(&delayed_refs->lock);
1444 			ret = add_delayed_refs(ctx->fs_info, head, ctx->time_seq,
1445 					       &preftrees, sc);
1446 			mutex_unlock(&head->mutex);
1447 			if (ret)
1448 				goto out;
1449 		} else {
1450 			spin_unlock(&delayed_refs->lock);
1451 		}
1452 	}
1453 
1454 	if (path->slots[0]) {
1455 		struct extent_buffer *leaf;
1456 		int slot;
1457 
1458 		path->slots[0]--;
1459 		leaf = path->nodes[0];
1460 		slot = path->slots[0];
1461 		btrfs_item_key_to_cpu(leaf, &key, slot);
1462 		if (key.objectid == ctx->bytenr &&
1463 		    (key.type == BTRFS_EXTENT_ITEM_KEY ||
1464 		     key.type == BTRFS_METADATA_ITEM_KEY)) {
1465 			ret = add_inline_refs(ctx, path, &info_level,
1466 					      &preftrees, sc);
1467 			if (ret)
1468 				goto out;
1469 			ret = add_keyed_refs(root, path, ctx->bytenr, info_level,
1470 					     &preftrees, sc);
1471 			if (ret)
1472 				goto out;
1473 		}
1474 	}
1475 
1476 	/*
1477 	 * If we have a share context and we reached here, it means the extent
1478 	 * is not directly shared (no multiple reference items for it),
1479 	 * otherwise we would have exited earlier with a return value of
1480 	 * BACKREF_FOUND_SHARED after processing delayed references or while
1481 	 * processing inline or keyed references from the extent tree.
1482 	 * The extent may however be indirectly shared through shared subtrees
1483 	 * as a result from creating snapshots, so we determine below what is
1484 	 * its parent node, in case we are dealing with a metadata extent, or
1485 	 * what's the leaf (or leaves), from a fs tree, that has a file extent
1486 	 * item pointing to it in case we are dealing with a data extent.
1487 	 */
1488 	ASSERT(extent_is_shared(sc) == 0);
1489 
1490 	/*
1491 	 * If we are here for a data extent and we have a share_check structure
1492 	 * it means the data extent is not directly shared (does not have
1493 	 * multiple reference items), so we have to check if a path in the fs
1494 	 * tree (going from the root node down to the leaf that has the file
1495 	 * extent item pointing to the data extent) is shared, that is, if any
1496 	 * of the extent buffers in the path is referenced by other trees.
1497 	 */
1498 	if (sc && ctx->bytenr == sc->data_bytenr) {
1499 		/*
1500 		 * If our data extent is from a generation more recent than the
1501 		 * last generation used to snapshot the root, then we know that
1502 		 * it can not be shared through subtrees, so we can skip
1503 		 * resolving indirect references, there's no point in
1504 		 * determining the extent buffers for the path from the fs tree
1505 		 * root node down to the leaf that has the file extent item that
1506 		 * points to the data extent.
1507 		 */
1508 		if (sc->data_extent_gen >
1509 		    btrfs_root_last_snapshot(&sc->root->root_item)) {
1510 			ret = BACKREF_FOUND_NOT_SHARED;
1511 			goto out;
1512 		}
1513 
1514 		/*
1515 		 * If we are only determining if a data extent is shared or not
1516 		 * and the corresponding file extent item is located in the same
1517 		 * leaf as the previous file extent item, we can skip resolving
1518 		 * indirect references for a data extent, since the fs tree path
1519 		 * is the same (same leaf, so same path). We skip as long as the
1520 		 * cached result for the leaf is valid and only if there's only
1521 		 * one file extent item pointing to the data extent, because in
1522 		 * the case of multiple file extent items, they may be located
1523 		 * in different leaves and therefore we have multiple paths.
1524 		 */
1525 		if (sc->ctx->curr_leaf_bytenr == sc->ctx->prev_leaf_bytenr &&
1526 		    sc->self_ref_count == 1) {
1527 			bool cached;
1528 			bool is_shared;
1529 
1530 			cached = lookup_backref_shared_cache(sc->ctx, sc->root,
1531 						     sc->ctx->curr_leaf_bytenr,
1532 						     0, &is_shared);
1533 			if (cached) {
1534 				if (is_shared)
1535 					ret = BACKREF_FOUND_SHARED;
1536 				else
1537 					ret = BACKREF_FOUND_NOT_SHARED;
1538 				goto out;
1539 			}
1540 		}
1541 	}
1542 
1543 	btrfs_release_path(path);
1544 
1545 	ret = add_missing_keys(ctx->fs_info, &preftrees, path->skip_locking == 0);
1546 	if (ret)
1547 		goto out;
1548 
1549 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect_missing_keys.root.rb_root));
1550 
1551 	ret = resolve_indirect_refs(ctx, path, &preftrees, sc);
1552 	if (ret)
1553 		goto out;
1554 
1555 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect.root.rb_root));
1556 
1557 	/*
1558 	 * This walks the tree of merged and resolved refs. Tree blocks are
1559 	 * read in as needed. Unique entries are added to the ulist, and
1560 	 * the list of found roots is updated.
1561 	 *
1562 	 * We release the entire tree in one go before returning.
1563 	 */
1564 	node = rb_first_cached(&preftrees.direct.root);
1565 	while (node) {
1566 		ref = rb_entry(node, struct prelim_ref, rbnode);
1567 		node = rb_next(&ref->rbnode);
1568 		/*
1569 		 * ref->count < 0 can happen here if there are delayed
1570 		 * refs with a node->action of BTRFS_DROP_DELAYED_REF.
1571 		 * prelim_ref_insert() relies on this when merging
1572 		 * identical refs to keep the overall count correct.
1573 		 * prelim_ref_insert() will merge only those refs
1574 		 * which compare identically.  Any refs having
1575 		 * e.g. different offsets would not be merged,
1576 		 * and would retain their original ref->count < 0.
1577 		 */
1578 		if (ctx->roots && ref->count && ref->root_id && ref->parent == 0) {
1579 			/* no parent == root of tree */
1580 			ret = ulist_add(ctx->roots, ref->root_id, 0, GFP_NOFS);
1581 			if (ret < 0)
1582 				goto out;
1583 		}
1584 		if (ref->count && ref->parent) {
1585 			if (!ctx->ignore_extent_item_pos && !ref->inode_list &&
1586 			    ref->level == 0) {
1587 				struct extent_buffer *eb;
1588 
1589 				eb = read_tree_block(ctx->fs_info, ref->parent, 0,
1590 						     0, ref->level, NULL);
1591 				if (IS_ERR(eb)) {
1592 					ret = PTR_ERR(eb);
1593 					goto out;
1594 				}
1595 				if (!extent_buffer_uptodate(eb)) {
1596 					free_extent_buffer(eb);
1597 					ret = -EIO;
1598 					goto out;
1599 				}
1600 
1601 				if (!path->skip_locking)
1602 					btrfs_tree_read_lock(eb);
1603 				ret = find_extent_in_eb(ctx, eb, &eie);
1604 				if (!path->skip_locking)
1605 					btrfs_tree_read_unlock(eb);
1606 				free_extent_buffer(eb);
1607 				if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
1608 				    ret < 0)
1609 					goto out;
1610 				ref->inode_list = eie;
1611 				/*
1612 				 * We transferred the list ownership to the ref,
1613 				 * so set to NULL to avoid a double free in case
1614 				 * an error happens after this.
1615 				 */
1616 				eie = NULL;
1617 			}
1618 			ret = ulist_add_merge_ptr(ctx->refs, ref->parent,
1619 						  ref->inode_list,
1620 						  (void **)&eie, GFP_NOFS);
1621 			if (ret < 0)
1622 				goto out;
1623 			if (!ret && !ctx->ignore_extent_item_pos) {
1624 				/*
1625 				 * We've recorded that parent, so we must extend
1626 				 * its inode list here.
1627 				 *
1628 				 * However if there was corruption we may not
1629 				 * have found an eie, return an error in this
1630 				 * case.
1631 				 */
1632 				ASSERT(eie);
1633 				if (!eie) {
1634 					ret = -EUCLEAN;
1635 					goto out;
1636 				}
1637 				while (eie->next)
1638 					eie = eie->next;
1639 				eie->next = ref->inode_list;
1640 			}
1641 			eie = NULL;
1642 			/*
1643 			 * We have transferred the inode list ownership from
1644 			 * this ref to the ref we added to the 'refs' ulist.
1645 			 * So set this ref's inode list to NULL to avoid
1646 			 * use-after-free when our caller uses it or double
1647 			 * frees in case an error happens before we return.
1648 			 */
1649 			ref->inode_list = NULL;
1650 		}
1651 		cond_resched();
1652 	}
1653 
1654 out:
1655 	btrfs_free_path(path);
1656 
1657 	prelim_release(&preftrees.direct);
1658 	prelim_release(&preftrees.indirect);
1659 	prelim_release(&preftrees.indirect_missing_keys);
1660 
1661 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
1662 		free_inode_elem_list(eie);
1663 	return ret;
1664 }
1665 
1666 /*
1667  * Finds all leaves with a reference to the specified combination of
1668  * @ctx->bytenr and @ctx->extent_item_pos. The bytenr of the found leaves are
1669  * added to the ulist at @ctx->refs, and that ulist is allocated by this
1670  * function. The caller should free the ulist with free_leaf_list() if
1671  * @ctx->ignore_extent_item_pos is false, otherwise a fimple ulist_free() is
1672  * enough.
1673  *
1674  * Returns 0 on success and < 0 on error. On error @ctx->refs is not allocated.
1675  */
1676 int btrfs_find_all_leafs(struct btrfs_backref_walk_ctx *ctx)
1677 {
1678 	int ret;
1679 
1680 	ASSERT(ctx->refs == NULL);
1681 
1682 	ctx->refs = ulist_alloc(GFP_NOFS);
1683 	if (!ctx->refs)
1684 		return -ENOMEM;
1685 
1686 	ret = find_parent_nodes(ctx, NULL);
1687 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
1688 	    (ret < 0 && ret != -ENOENT)) {
1689 		free_leaf_list(ctx->refs);
1690 		ctx->refs = NULL;
1691 		return ret;
1692 	}
1693 
1694 	return 0;
1695 }
1696 
1697 /*
1698  * Walk all backrefs for a given extent to find all roots that reference this
1699  * extent. Walking a backref means finding all extents that reference this
1700  * extent and in turn walk the backrefs of those, too. Naturally this is a
1701  * recursive process, but here it is implemented in an iterative fashion: We
1702  * find all referencing extents for the extent in question and put them on a
1703  * list. In turn, we find all referencing extents for those, further appending
1704  * to the list. The way we iterate the list allows adding more elements after
1705  * the current while iterating. The process stops when we reach the end of the
1706  * list.
1707  *
1708  * Found roots are added to @ctx->roots, which is allocated by this function if
1709  * it points to NULL, in which case the caller is responsible for freeing it
1710  * after it's not needed anymore.
1711  * This function requires @ctx->refs to be NULL, as it uses it for allocating a
1712  * ulist to do temporary work, and frees it before returning.
1713  *
1714  * Returns 0 on success, < 0 on error.
1715  */
1716 static int btrfs_find_all_roots_safe(struct btrfs_backref_walk_ctx *ctx)
1717 {
1718 	const u64 orig_bytenr = ctx->bytenr;
1719 	const bool orig_ignore_extent_item_pos = ctx->ignore_extent_item_pos;
1720 	bool roots_ulist_allocated = false;
1721 	struct ulist_iterator uiter;
1722 	int ret = 0;
1723 
1724 	ASSERT(ctx->refs == NULL);
1725 
1726 	ctx->refs = ulist_alloc(GFP_NOFS);
1727 	if (!ctx->refs)
1728 		return -ENOMEM;
1729 
1730 	if (!ctx->roots) {
1731 		ctx->roots = ulist_alloc(GFP_NOFS);
1732 		if (!ctx->roots) {
1733 			ulist_free(ctx->refs);
1734 			ctx->refs = NULL;
1735 			return -ENOMEM;
1736 		}
1737 		roots_ulist_allocated = true;
1738 	}
1739 
1740 	ctx->ignore_extent_item_pos = true;
1741 
1742 	ULIST_ITER_INIT(&uiter);
1743 	while (1) {
1744 		struct ulist_node *node;
1745 
1746 		ret = find_parent_nodes(ctx, NULL);
1747 		if (ret < 0 && ret != -ENOENT) {
1748 			if (roots_ulist_allocated) {
1749 				ulist_free(ctx->roots);
1750 				ctx->roots = NULL;
1751 			}
1752 			break;
1753 		}
1754 		ret = 0;
1755 		node = ulist_next(ctx->refs, &uiter);
1756 		if (!node)
1757 			break;
1758 		ctx->bytenr = node->val;
1759 		cond_resched();
1760 	}
1761 
1762 	ulist_free(ctx->refs);
1763 	ctx->refs = NULL;
1764 	ctx->bytenr = orig_bytenr;
1765 	ctx->ignore_extent_item_pos = orig_ignore_extent_item_pos;
1766 
1767 	return ret;
1768 }
1769 
1770 int btrfs_find_all_roots(struct btrfs_backref_walk_ctx *ctx,
1771 			 bool skip_commit_root_sem)
1772 {
1773 	int ret;
1774 
1775 	if (!ctx->trans && !skip_commit_root_sem)
1776 		down_read(&ctx->fs_info->commit_root_sem);
1777 	ret = btrfs_find_all_roots_safe(ctx);
1778 	if (!ctx->trans && !skip_commit_root_sem)
1779 		up_read(&ctx->fs_info->commit_root_sem);
1780 	return ret;
1781 }
1782 
1783 struct btrfs_backref_share_check_ctx *btrfs_alloc_backref_share_check_ctx(void)
1784 {
1785 	struct btrfs_backref_share_check_ctx *ctx;
1786 
1787 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1788 	if (!ctx)
1789 		return NULL;
1790 
1791 	ulist_init(&ctx->refs);
1792 
1793 	return ctx;
1794 }
1795 
1796 void btrfs_free_backref_share_ctx(struct btrfs_backref_share_check_ctx *ctx)
1797 {
1798 	if (!ctx)
1799 		return;
1800 
1801 	ulist_release(&ctx->refs);
1802 	kfree(ctx);
1803 }
1804 
1805 /*
1806  * Check if a data extent is shared or not.
1807  *
1808  * @inode:       The inode whose extent we are checking.
1809  * @bytenr:      Logical bytenr of the extent we are checking.
1810  * @extent_gen:  Generation of the extent (file extent item) or 0 if it is
1811  *               not known.
1812  * @ctx:         A backref sharedness check context.
1813  *
1814  * btrfs_is_data_extent_shared uses the backref walking code but will short
1815  * circuit as soon as it finds a root or inode that doesn't match the
1816  * one passed in. This provides a significant performance benefit for
1817  * callers (such as fiemap) which want to know whether the extent is
1818  * shared but do not need a ref count.
1819  *
1820  * This attempts to attach to the running transaction in order to account for
1821  * delayed refs, but continues on even when no running transaction exists.
1822  *
1823  * Return: 0 if extent is not shared, 1 if it is shared, < 0 on error.
1824  */
1825 int btrfs_is_data_extent_shared(struct btrfs_inode *inode, u64 bytenr,
1826 				u64 extent_gen,
1827 				struct btrfs_backref_share_check_ctx *ctx)
1828 {
1829 	struct btrfs_backref_walk_ctx walk_ctx = { 0 };
1830 	struct btrfs_root *root = inode->root;
1831 	struct btrfs_fs_info *fs_info = root->fs_info;
1832 	struct btrfs_trans_handle *trans;
1833 	struct ulist_iterator uiter;
1834 	struct ulist_node *node;
1835 	struct btrfs_seq_list elem = BTRFS_SEQ_LIST_INIT(elem);
1836 	int ret = 0;
1837 	struct share_check shared = {
1838 		.ctx = ctx,
1839 		.root = root,
1840 		.inum = btrfs_ino(inode),
1841 		.data_bytenr = bytenr,
1842 		.data_extent_gen = extent_gen,
1843 		.share_count = 0,
1844 		.self_ref_count = 0,
1845 		.have_delayed_delete_refs = false,
1846 	};
1847 	int level;
1848 
1849 	for (int i = 0; i < BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE; i++) {
1850 		if (ctx->prev_extents_cache[i].bytenr == bytenr)
1851 			return ctx->prev_extents_cache[i].is_shared;
1852 	}
1853 
1854 	ulist_init(&ctx->refs);
1855 
1856 	trans = btrfs_join_transaction_nostart(root);
1857 	if (IS_ERR(trans)) {
1858 		if (PTR_ERR(trans) != -ENOENT && PTR_ERR(trans) != -EROFS) {
1859 			ret = PTR_ERR(trans);
1860 			goto out;
1861 		}
1862 		trans = NULL;
1863 		down_read(&fs_info->commit_root_sem);
1864 	} else {
1865 		btrfs_get_tree_mod_seq(fs_info, &elem);
1866 		walk_ctx.time_seq = elem.seq;
1867 	}
1868 
1869 	walk_ctx.ignore_extent_item_pos = true;
1870 	walk_ctx.trans = trans;
1871 	walk_ctx.fs_info = fs_info;
1872 	walk_ctx.refs = &ctx->refs;
1873 
1874 	/* -1 means we are in the bytenr of the data extent. */
1875 	level = -1;
1876 	ULIST_ITER_INIT(&uiter);
1877 	ctx->use_path_cache = true;
1878 	while (1) {
1879 		bool is_shared;
1880 		bool cached;
1881 
1882 		walk_ctx.bytenr = bytenr;
1883 		ret = find_parent_nodes(&walk_ctx, &shared);
1884 		if (ret == BACKREF_FOUND_SHARED ||
1885 		    ret == BACKREF_FOUND_NOT_SHARED) {
1886 			/* If shared must return 1, otherwise return 0. */
1887 			ret = (ret == BACKREF_FOUND_SHARED) ? 1 : 0;
1888 			if (level >= 0)
1889 				store_backref_shared_cache(ctx, root, bytenr,
1890 							   level, ret == 1);
1891 			break;
1892 		}
1893 		if (ret < 0 && ret != -ENOENT)
1894 			break;
1895 		ret = 0;
1896 
1897 		/*
1898 		 * If our data extent was not directly shared (without multiple
1899 		 * reference items), than it might have a single reference item
1900 		 * with a count > 1 for the same offset, which means there are 2
1901 		 * (or more) file extent items that point to the data extent -
1902 		 * this happens when a file extent item needs to be split and
1903 		 * then one item gets moved to another leaf due to a b+tree leaf
1904 		 * split when inserting some item. In this case the file extent
1905 		 * items may be located in different leaves and therefore some
1906 		 * of the leaves may be referenced through shared subtrees while
1907 		 * others are not. Since our extent buffer cache only works for
1908 		 * a single path (by far the most common case and simpler to
1909 		 * deal with), we can not use it if we have multiple leaves
1910 		 * (which implies multiple paths).
1911 		 */
1912 		if (level == -1 && ctx->refs.nnodes > 1)
1913 			ctx->use_path_cache = false;
1914 
1915 		if (level >= 0)
1916 			store_backref_shared_cache(ctx, root, bytenr,
1917 						   level, false);
1918 		node = ulist_next(&ctx->refs, &uiter);
1919 		if (!node)
1920 			break;
1921 		bytenr = node->val;
1922 		level++;
1923 		cached = lookup_backref_shared_cache(ctx, root, bytenr, level,
1924 						     &is_shared);
1925 		if (cached) {
1926 			ret = (is_shared ? 1 : 0);
1927 			break;
1928 		}
1929 		shared.share_count = 0;
1930 		shared.have_delayed_delete_refs = false;
1931 		cond_resched();
1932 	}
1933 
1934 	/*
1935 	 * Cache the sharedness result for the data extent if we know our inode
1936 	 * has more than 1 file extent item that refers to the data extent.
1937 	 */
1938 	if (ret >= 0 && shared.self_ref_count > 1) {
1939 		int slot = ctx->prev_extents_cache_slot;
1940 
1941 		ctx->prev_extents_cache[slot].bytenr = shared.data_bytenr;
1942 		ctx->prev_extents_cache[slot].is_shared = (ret == 1);
1943 
1944 		slot = (slot + 1) % BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE;
1945 		ctx->prev_extents_cache_slot = slot;
1946 	}
1947 
1948 	if (trans) {
1949 		btrfs_put_tree_mod_seq(fs_info, &elem);
1950 		btrfs_end_transaction(trans);
1951 	} else {
1952 		up_read(&fs_info->commit_root_sem);
1953 	}
1954 out:
1955 	ulist_release(&ctx->refs);
1956 	ctx->prev_leaf_bytenr = ctx->curr_leaf_bytenr;
1957 
1958 	return ret;
1959 }
1960 
1961 int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
1962 			  u64 start_off, struct btrfs_path *path,
1963 			  struct btrfs_inode_extref **ret_extref,
1964 			  u64 *found_off)
1965 {
1966 	int ret, slot;
1967 	struct btrfs_key key;
1968 	struct btrfs_key found_key;
1969 	struct btrfs_inode_extref *extref;
1970 	const struct extent_buffer *leaf;
1971 	unsigned long ptr;
1972 
1973 	key.objectid = inode_objectid;
1974 	key.type = BTRFS_INODE_EXTREF_KEY;
1975 	key.offset = start_off;
1976 
1977 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1978 	if (ret < 0)
1979 		return ret;
1980 
1981 	while (1) {
1982 		leaf = path->nodes[0];
1983 		slot = path->slots[0];
1984 		if (slot >= btrfs_header_nritems(leaf)) {
1985 			/*
1986 			 * If the item at offset is not found,
1987 			 * btrfs_search_slot will point us to the slot
1988 			 * where it should be inserted. In our case
1989 			 * that will be the slot directly before the
1990 			 * next INODE_REF_KEY_V2 item. In the case
1991 			 * that we're pointing to the last slot in a
1992 			 * leaf, we must move one leaf over.
1993 			 */
1994 			ret = btrfs_next_leaf(root, path);
1995 			if (ret) {
1996 				if (ret >= 1)
1997 					ret = -ENOENT;
1998 				break;
1999 			}
2000 			continue;
2001 		}
2002 
2003 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
2004 
2005 		/*
2006 		 * Check that we're still looking at an extended ref key for
2007 		 * this particular objectid. If we have different
2008 		 * objectid or type then there are no more to be found
2009 		 * in the tree and we can exit.
2010 		 */
2011 		ret = -ENOENT;
2012 		if (found_key.objectid != inode_objectid)
2013 			break;
2014 		if (found_key.type != BTRFS_INODE_EXTREF_KEY)
2015 			break;
2016 
2017 		ret = 0;
2018 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
2019 		extref = (struct btrfs_inode_extref *)ptr;
2020 		*ret_extref = extref;
2021 		if (found_off)
2022 			*found_off = found_key.offset;
2023 		break;
2024 	}
2025 
2026 	return ret;
2027 }
2028 
2029 /*
2030  * this iterates to turn a name (from iref/extref) into a full filesystem path.
2031  * Elements of the path are separated by '/' and the path is guaranteed to be
2032  * 0-terminated. the path is only given within the current file system.
2033  * Therefore, it never starts with a '/'. the caller is responsible to provide
2034  * "size" bytes in "dest". the dest buffer will be filled backwards. finally,
2035  * the start point of the resulting string is returned. this pointer is within
2036  * dest, normally.
2037  * in case the path buffer would overflow, the pointer is decremented further
2038  * as if output was written to the buffer, though no more output is actually
2039  * generated. that way, the caller can determine how much space would be
2040  * required for the path to fit into the buffer. in that case, the returned
2041  * value will be smaller than dest. callers must check this!
2042  */
2043 char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
2044 			u32 name_len, unsigned long name_off,
2045 			struct extent_buffer *eb_in, u64 parent,
2046 			char *dest, u32 size)
2047 {
2048 	int slot;
2049 	u64 next_inum;
2050 	int ret;
2051 	s64 bytes_left = ((s64)size) - 1;
2052 	struct extent_buffer *eb = eb_in;
2053 	struct btrfs_key found_key;
2054 	struct btrfs_inode_ref *iref;
2055 
2056 	if (bytes_left >= 0)
2057 		dest[bytes_left] = '\0';
2058 
2059 	while (1) {
2060 		bytes_left -= name_len;
2061 		if (bytes_left >= 0)
2062 			read_extent_buffer(eb, dest + bytes_left,
2063 					   name_off, name_len);
2064 		if (eb != eb_in) {
2065 			if (!path->skip_locking)
2066 				btrfs_tree_read_unlock(eb);
2067 			free_extent_buffer(eb);
2068 		}
2069 		ret = btrfs_find_item(fs_root, path, parent, 0,
2070 				BTRFS_INODE_REF_KEY, &found_key);
2071 		if (ret > 0)
2072 			ret = -ENOENT;
2073 		if (ret)
2074 			break;
2075 
2076 		next_inum = found_key.offset;
2077 
2078 		/* regular exit ahead */
2079 		if (parent == next_inum)
2080 			break;
2081 
2082 		slot = path->slots[0];
2083 		eb = path->nodes[0];
2084 		/* make sure we can use eb after releasing the path */
2085 		if (eb != eb_in) {
2086 			path->nodes[0] = NULL;
2087 			path->locks[0] = 0;
2088 		}
2089 		btrfs_release_path(path);
2090 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2091 
2092 		name_len = btrfs_inode_ref_name_len(eb, iref);
2093 		name_off = (unsigned long)(iref + 1);
2094 
2095 		parent = next_inum;
2096 		--bytes_left;
2097 		if (bytes_left >= 0)
2098 			dest[bytes_left] = '/';
2099 	}
2100 
2101 	btrfs_release_path(path);
2102 
2103 	if (ret)
2104 		return ERR_PTR(ret);
2105 
2106 	return dest + bytes_left;
2107 }
2108 
2109 /*
2110  * this makes the path point to (logical EXTENT_ITEM *)
2111  * returns BTRFS_EXTENT_FLAG_DATA for data, BTRFS_EXTENT_FLAG_TREE_BLOCK for
2112  * tree blocks and <0 on error.
2113  */
2114 int extent_from_logical(struct btrfs_fs_info *fs_info, u64 logical,
2115 			struct btrfs_path *path, struct btrfs_key *found_key,
2116 			u64 *flags_ret)
2117 {
2118 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, logical);
2119 	int ret;
2120 	u64 flags;
2121 	u64 size = 0;
2122 	u32 item_size;
2123 	const struct extent_buffer *eb;
2124 	struct btrfs_extent_item *ei;
2125 	struct btrfs_key key;
2126 
2127 	if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2128 		key.type = BTRFS_METADATA_ITEM_KEY;
2129 	else
2130 		key.type = BTRFS_EXTENT_ITEM_KEY;
2131 	key.objectid = logical;
2132 	key.offset = (u64)-1;
2133 
2134 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2135 	if (ret < 0)
2136 		return ret;
2137 
2138 	ret = btrfs_previous_extent_item(extent_root, path, 0);
2139 	if (ret) {
2140 		if (ret > 0)
2141 			ret = -ENOENT;
2142 		return ret;
2143 	}
2144 	btrfs_item_key_to_cpu(path->nodes[0], found_key, path->slots[0]);
2145 	if (found_key->type == BTRFS_METADATA_ITEM_KEY)
2146 		size = fs_info->nodesize;
2147 	else if (found_key->type == BTRFS_EXTENT_ITEM_KEY)
2148 		size = found_key->offset;
2149 
2150 	if (found_key->objectid > logical ||
2151 	    found_key->objectid + size <= logical) {
2152 		btrfs_debug(fs_info,
2153 			"logical %llu is not within any extent", logical);
2154 		return -ENOENT;
2155 	}
2156 
2157 	eb = path->nodes[0];
2158 	item_size = btrfs_item_size(eb, path->slots[0]);
2159 	BUG_ON(item_size < sizeof(*ei));
2160 
2161 	ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
2162 	flags = btrfs_extent_flags(eb, ei);
2163 
2164 	btrfs_debug(fs_info,
2165 		"logical %llu is at position %llu within the extent (%llu EXTENT_ITEM %llu) flags %#llx size %u",
2166 		 logical, logical - found_key->objectid, found_key->objectid,
2167 		 found_key->offset, flags, item_size);
2168 
2169 	WARN_ON(!flags_ret);
2170 	if (flags_ret) {
2171 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
2172 			*flags_ret = BTRFS_EXTENT_FLAG_TREE_BLOCK;
2173 		else if (flags & BTRFS_EXTENT_FLAG_DATA)
2174 			*flags_ret = BTRFS_EXTENT_FLAG_DATA;
2175 		else
2176 			BUG();
2177 		return 0;
2178 	}
2179 
2180 	return -EIO;
2181 }
2182 
2183 /*
2184  * helper function to iterate extent inline refs. ptr must point to a 0 value
2185  * for the first call and may be modified. it is used to track state.
2186  * if more refs exist, 0 is returned and the next call to
2187  * get_extent_inline_ref must pass the modified ptr parameter to get the
2188  * next ref. after the last ref was processed, 1 is returned.
2189  * returns <0 on error
2190  */
2191 static int get_extent_inline_ref(unsigned long *ptr,
2192 				 const struct extent_buffer *eb,
2193 				 const struct btrfs_key *key,
2194 				 const struct btrfs_extent_item *ei,
2195 				 u32 item_size,
2196 				 struct btrfs_extent_inline_ref **out_eiref,
2197 				 int *out_type)
2198 {
2199 	unsigned long end;
2200 	u64 flags;
2201 	struct btrfs_tree_block_info *info;
2202 
2203 	if (!*ptr) {
2204 		/* first call */
2205 		flags = btrfs_extent_flags(eb, ei);
2206 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
2207 			if (key->type == BTRFS_METADATA_ITEM_KEY) {
2208 				/* a skinny metadata extent */
2209 				*out_eiref =
2210 				     (struct btrfs_extent_inline_ref *)(ei + 1);
2211 			} else {
2212 				WARN_ON(key->type != BTRFS_EXTENT_ITEM_KEY);
2213 				info = (struct btrfs_tree_block_info *)(ei + 1);
2214 				*out_eiref =
2215 				   (struct btrfs_extent_inline_ref *)(info + 1);
2216 			}
2217 		} else {
2218 			*out_eiref = (struct btrfs_extent_inline_ref *)(ei + 1);
2219 		}
2220 		*ptr = (unsigned long)*out_eiref;
2221 		if ((unsigned long)(*ptr) >= (unsigned long)ei + item_size)
2222 			return -ENOENT;
2223 	}
2224 
2225 	end = (unsigned long)ei + item_size;
2226 	*out_eiref = (struct btrfs_extent_inline_ref *)(*ptr);
2227 	*out_type = btrfs_get_extent_inline_ref_type(eb, *out_eiref,
2228 						     BTRFS_REF_TYPE_ANY);
2229 	if (*out_type == BTRFS_REF_TYPE_INVALID)
2230 		return -EUCLEAN;
2231 
2232 	*ptr += btrfs_extent_inline_ref_size(*out_type);
2233 	WARN_ON(*ptr > end);
2234 	if (*ptr == end)
2235 		return 1; /* last */
2236 
2237 	return 0;
2238 }
2239 
2240 /*
2241  * reads the tree block backref for an extent. tree level and root are returned
2242  * through out_level and out_root. ptr must point to a 0 value for the first
2243  * call and may be modified (see get_extent_inline_ref comment).
2244  * returns 0 if data was provided, 1 if there was no more data to provide or
2245  * <0 on error.
2246  */
2247 int tree_backref_for_extent(unsigned long *ptr, struct extent_buffer *eb,
2248 			    struct btrfs_key *key, struct btrfs_extent_item *ei,
2249 			    u32 item_size, u64 *out_root, u8 *out_level)
2250 {
2251 	int ret;
2252 	int type;
2253 	struct btrfs_extent_inline_ref *eiref;
2254 
2255 	if (*ptr == (unsigned long)-1)
2256 		return 1;
2257 
2258 	while (1) {
2259 		ret = get_extent_inline_ref(ptr, eb, key, ei, item_size,
2260 					      &eiref, &type);
2261 		if (ret < 0)
2262 			return ret;
2263 
2264 		if (type == BTRFS_TREE_BLOCK_REF_KEY ||
2265 		    type == BTRFS_SHARED_BLOCK_REF_KEY)
2266 			break;
2267 
2268 		if (ret == 1)
2269 			return 1;
2270 	}
2271 
2272 	/* we can treat both ref types equally here */
2273 	*out_root = btrfs_extent_inline_ref_offset(eb, eiref);
2274 
2275 	if (key->type == BTRFS_EXTENT_ITEM_KEY) {
2276 		struct btrfs_tree_block_info *info;
2277 
2278 		info = (struct btrfs_tree_block_info *)(ei + 1);
2279 		*out_level = btrfs_tree_block_level(eb, info);
2280 	} else {
2281 		ASSERT(key->type == BTRFS_METADATA_ITEM_KEY);
2282 		*out_level = (u8)key->offset;
2283 	}
2284 
2285 	if (ret == 1)
2286 		*ptr = (unsigned long)-1;
2287 
2288 	return 0;
2289 }
2290 
2291 static int iterate_leaf_refs(struct btrfs_fs_info *fs_info,
2292 			     struct extent_inode_elem *inode_list,
2293 			     u64 root, u64 extent_item_objectid,
2294 			     iterate_extent_inodes_t *iterate, void *ctx)
2295 {
2296 	struct extent_inode_elem *eie;
2297 	int ret = 0;
2298 
2299 	for (eie = inode_list; eie; eie = eie->next) {
2300 		btrfs_debug(fs_info,
2301 			    "ref for %llu resolved, key (%llu EXTEND_DATA %llu), root %llu",
2302 			    extent_item_objectid, eie->inum,
2303 			    eie->offset, root);
2304 		ret = iterate(eie->inum, eie->offset, eie->num_bytes, root, ctx);
2305 		if (ret) {
2306 			btrfs_debug(fs_info,
2307 				    "stopping iteration for %llu due to ret=%d",
2308 				    extent_item_objectid, ret);
2309 			break;
2310 		}
2311 	}
2312 
2313 	return ret;
2314 }
2315 
2316 /*
2317  * calls iterate() for every inode that references the extent identified by
2318  * the given parameters.
2319  * when the iterator function returns a non-zero value, iteration stops.
2320  */
2321 int iterate_extent_inodes(struct btrfs_backref_walk_ctx *ctx,
2322 			  bool search_commit_root,
2323 			  iterate_extent_inodes_t *iterate, void *user_ctx)
2324 {
2325 	int ret;
2326 	struct ulist *refs;
2327 	struct ulist_node *ref_node;
2328 	struct btrfs_seq_list seq_elem = BTRFS_SEQ_LIST_INIT(seq_elem);
2329 	struct ulist_iterator ref_uiter;
2330 
2331 	btrfs_debug(ctx->fs_info, "resolving all inodes for extent %llu",
2332 		    ctx->bytenr);
2333 
2334 	ASSERT(ctx->trans == NULL);
2335 	ASSERT(ctx->roots == NULL);
2336 
2337 	if (!search_commit_root) {
2338 		struct btrfs_trans_handle *trans;
2339 
2340 		trans = btrfs_attach_transaction(ctx->fs_info->tree_root);
2341 		if (IS_ERR(trans)) {
2342 			if (PTR_ERR(trans) != -ENOENT &&
2343 			    PTR_ERR(trans) != -EROFS)
2344 				return PTR_ERR(trans);
2345 			trans = NULL;
2346 		}
2347 		ctx->trans = trans;
2348 	}
2349 
2350 	if (ctx->trans) {
2351 		btrfs_get_tree_mod_seq(ctx->fs_info, &seq_elem);
2352 		ctx->time_seq = seq_elem.seq;
2353 	} else {
2354 		down_read(&ctx->fs_info->commit_root_sem);
2355 	}
2356 
2357 	ret = btrfs_find_all_leafs(ctx);
2358 	if (ret)
2359 		goto out;
2360 	refs = ctx->refs;
2361 	ctx->refs = NULL;
2362 
2363 	ULIST_ITER_INIT(&ref_uiter);
2364 	while (!ret && (ref_node = ulist_next(refs, &ref_uiter))) {
2365 		const u64 leaf_bytenr = ref_node->val;
2366 		struct ulist_node *root_node;
2367 		struct ulist_iterator root_uiter;
2368 		struct extent_inode_elem *inode_list;
2369 
2370 		inode_list = (struct extent_inode_elem *)(uintptr_t)ref_node->aux;
2371 
2372 		if (ctx->cache_lookup) {
2373 			const u64 *root_ids;
2374 			int root_count;
2375 			bool cached;
2376 
2377 			cached = ctx->cache_lookup(leaf_bytenr, ctx->user_ctx,
2378 						   &root_ids, &root_count);
2379 			if (cached) {
2380 				for (int i = 0; i < root_count; i++) {
2381 					ret = iterate_leaf_refs(ctx->fs_info,
2382 								inode_list,
2383 								root_ids[i],
2384 								leaf_bytenr,
2385 								iterate,
2386 								user_ctx);
2387 					if (ret)
2388 						break;
2389 				}
2390 				continue;
2391 			}
2392 		}
2393 
2394 		if (!ctx->roots) {
2395 			ctx->roots = ulist_alloc(GFP_NOFS);
2396 			if (!ctx->roots) {
2397 				ret = -ENOMEM;
2398 				break;
2399 			}
2400 		}
2401 
2402 		ctx->bytenr = leaf_bytenr;
2403 		ret = btrfs_find_all_roots_safe(ctx);
2404 		if (ret)
2405 			break;
2406 
2407 		if (ctx->cache_store)
2408 			ctx->cache_store(leaf_bytenr, ctx->roots, ctx->user_ctx);
2409 
2410 		ULIST_ITER_INIT(&root_uiter);
2411 		while (!ret && (root_node = ulist_next(ctx->roots, &root_uiter))) {
2412 			btrfs_debug(ctx->fs_info,
2413 				    "root %llu references leaf %llu, data list %#llx",
2414 				    root_node->val, ref_node->val,
2415 				    ref_node->aux);
2416 			ret = iterate_leaf_refs(ctx->fs_info, inode_list,
2417 						root_node->val, ctx->bytenr,
2418 						iterate, user_ctx);
2419 		}
2420 		ulist_reinit(ctx->roots);
2421 	}
2422 
2423 	free_leaf_list(refs);
2424 out:
2425 	if (ctx->trans) {
2426 		btrfs_put_tree_mod_seq(ctx->fs_info, &seq_elem);
2427 		btrfs_end_transaction(ctx->trans);
2428 		ctx->trans = NULL;
2429 	} else {
2430 		up_read(&ctx->fs_info->commit_root_sem);
2431 	}
2432 
2433 	ulist_free(ctx->roots);
2434 	ctx->roots = NULL;
2435 
2436 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP)
2437 		ret = 0;
2438 
2439 	return ret;
2440 }
2441 
2442 static int build_ino_list(u64 inum, u64 offset, u64 num_bytes, u64 root, void *ctx)
2443 {
2444 	struct btrfs_data_container *inodes = ctx;
2445 	const size_t c = 3 * sizeof(u64);
2446 
2447 	if (inodes->bytes_left >= c) {
2448 		inodes->bytes_left -= c;
2449 		inodes->val[inodes->elem_cnt] = inum;
2450 		inodes->val[inodes->elem_cnt + 1] = offset;
2451 		inodes->val[inodes->elem_cnt + 2] = root;
2452 		inodes->elem_cnt += 3;
2453 	} else {
2454 		inodes->bytes_missing += c - inodes->bytes_left;
2455 		inodes->bytes_left = 0;
2456 		inodes->elem_missed += 3;
2457 	}
2458 
2459 	return 0;
2460 }
2461 
2462 int iterate_inodes_from_logical(u64 logical, struct btrfs_fs_info *fs_info,
2463 				struct btrfs_path *path,
2464 				void *ctx, bool ignore_offset)
2465 {
2466 	struct btrfs_backref_walk_ctx walk_ctx = { 0 };
2467 	int ret;
2468 	u64 flags = 0;
2469 	struct btrfs_key found_key;
2470 	int search_commit_root = path->search_commit_root;
2471 
2472 	ret = extent_from_logical(fs_info, logical, path, &found_key, &flags);
2473 	btrfs_release_path(path);
2474 	if (ret < 0)
2475 		return ret;
2476 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
2477 		return -EINVAL;
2478 
2479 	walk_ctx.bytenr = found_key.objectid;
2480 	if (ignore_offset)
2481 		walk_ctx.ignore_extent_item_pos = true;
2482 	else
2483 		walk_ctx.extent_item_pos = logical - found_key.objectid;
2484 	walk_ctx.fs_info = fs_info;
2485 
2486 	return iterate_extent_inodes(&walk_ctx, search_commit_root,
2487 				     build_ino_list, ctx);
2488 }
2489 
2490 static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2491 			 struct extent_buffer *eb, struct inode_fs_paths *ipath);
2492 
2493 static int iterate_inode_refs(u64 inum, struct inode_fs_paths *ipath)
2494 {
2495 	int ret = 0;
2496 	int slot;
2497 	u32 cur;
2498 	u32 len;
2499 	u32 name_len;
2500 	u64 parent = 0;
2501 	int found = 0;
2502 	struct btrfs_root *fs_root = ipath->fs_root;
2503 	struct btrfs_path *path = ipath->btrfs_path;
2504 	struct extent_buffer *eb;
2505 	struct btrfs_inode_ref *iref;
2506 	struct btrfs_key found_key;
2507 
2508 	while (!ret) {
2509 		ret = btrfs_find_item(fs_root, path, inum,
2510 				parent ? parent + 1 : 0, BTRFS_INODE_REF_KEY,
2511 				&found_key);
2512 
2513 		if (ret < 0)
2514 			break;
2515 		if (ret) {
2516 			ret = found ? 0 : -ENOENT;
2517 			break;
2518 		}
2519 		++found;
2520 
2521 		parent = found_key.offset;
2522 		slot = path->slots[0];
2523 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
2524 		if (!eb) {
2525 			ret = -ENOMEM;
2526 			break;
2527 		}
2528 		btrfs_release_path(path);
2529 
2530 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2531 
2532 		for (cur = 0; cur < btrfs_item_size(eb, slot); cur += len) {
2533 			name_len = btrfs_inode_ref_name_len(eb, iref);
2534 			/* path must be released before calling iterate()! */
2535 			btrfs_debug(fs_root->fs_info,
2536 				"following ref at offset %u for inode %llu in tree %llu",
2537 				cur, found_key.objectid,
2538 				fs_root->root_key.objectid);
2539 			ret = inode_to_path(parent, name_len,
2540 				      (unsigned long)(iref + 1), eb, ipath);
2541 			if (ret)
2542 				break;
2543 			len = sizeof(*iref) + name_len;
2544 			iref = (struct btrfs_inode_ref *)((char *)iref + len);
2545 		}
2546 		free_extent_buffer(eb);
2547 	}
2548 
2549 	btrfs_release_path(path);
2550 
2551 	return ret;
2552 }
2553 
2554 static int iterate_inode_extrefs(u64 inum, struct inode_fs_paths *ipath)
2555 {
2556 	int ret;
2557 	int slot;
2558 	u64 offset = 0;
2559 	u64 parent;
2560 	int found = 0;
2561 	struct btrfs_root *fs_root = ipath->fs_root;
2562 	struct btrfs_path *path = ipath->btrfs_path;
2563 	struct extent_buffer *eb;
2564 	struct btrfs_inode_extref *extref;
2565 	u32 item_size;
2566 	u32 cur_offset;
2567 	unsigned long ptr;
2568 
2569 	while (1) {
2570 		ret = btrfs_find_one_extref(fs_root, inum, offset, path, &extref,
2571 					    &offset);
2572 		if (ret < 0)
2573 			break;
2574 		if (ret) {
2575 			ret = found ? 0 : -ENOENT;
2576 			break;
2577 		}
2578 		++found;
2579 
2580 		slot = path->slots[0];
2581 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
2582 		if (!eb) {
2583 			ret = -ENOMEM;
2584 			break;
2585 		}
2586 		btrfs_release_path(path);
2587 
2588 		item_size = btrfs_item_size(eb, slot);
2589 		ptr = btrfs_item_ptr_offset(eb, slot);
2590 		cur_offset = 0;
2591 
2592 		while (cur_offset < item_size) {
2593 			u32 name_len;
2594 
2595 			extref = (struct btrfs_inode_extref *)(ptr + cur_offset);
2596 			parent = btrfs_inode_extref_parent(eb, extref);
2597 			name_len = btrfs_inode_extref_name_len(eb, extref);
2598 			ret = inode_to_path(parent, name_len,
2599 				      (unsigned long)&extref->name, eb, ipath);
2600 			if (ret)
2601 				break;
2602 
2603 			cur_offset += btrfs_inode_extref_name_len(eb, extref);
2604 			cur_offset += sizeof(*extref);
2605 		}
2606 		free_extent_buffer(eb);
2607 
2608 		offset++;
2609 	}
2610 
2611 	btrfs_release_path(path);
2612 
2613 	return ret;
2614 }
2615 
2616 /*
2617  * returns 0 if the path could be dumped (probably truncated)
2618  * returns <0 in case of an error
2619  */
2620 static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2621 			 struct extent_buffer *eb, struct inode_fs_paths *ipath)
2622 {
2623 	char *fspath;
2624 	char *fspath_min;
2625 	int i = ipath->fspath->elem_cnt;
2626 	const int s_ptr = sizeof(char *);
2627 	u32 bytes_left;
2628 
2629 	bytes_left = ipath->fspath->bytes_left > s_ptr ?
2630 					ipath->fspath->bytes_left - s_ptr : 0;
2631 
2632 	fspath_min = (char *)ipath->fspath->val + (i + 1) * s_ptr;
2633 	fspath = btrfs_ref_to_path(ipath->fs_root, ipath->btrfs_path, name_len,
2634 				   name_off, eb, inum, fspath_min, bytes_left);
2635 	if (IS_ERR(fspath))
2636 		return PTR_ERR(fspath);
2637 
2638 	if (fspath > fspath_min) {
2639 		ipath->fspath->val[i] = (u64)(unsigned long)fspath;
2640 		++ipath->fspath->elem_cnt;
2641 		ipath->fspath->bytes_left = fspath - fspath_min;
2642 	} else {
2643 		++ipath->fspath->elem_missed;
2644 		ipath->fspath->bytes_missing += fspath_min - fspath;
2645 		ipath->fspath->bytes_left = 0;
2646 	}
2647 
2648 	return 0;
2649 }
2650 
2651 /*
2652  * this dumps all file system paths to the inode into the ipath struct, provided
2653  * is has been created large enough. each path is zero-terminated and accessed
2654  * from ipath->fspath->val[i].
2655  * when it returns, there are ipath->fspath->elem_cnt number of paths available
2656  * in ipath->fspath->val[]. when the allocated space wasn't sufficient, the
2657  * number of missed paths is recorded in ipath->fspath->elem_missed, otherwise,
2658  * it's zero. ipath->fspath->bytes_missing holds the number of bytes that would
2659  * have been needed to return all paths.
2660  */
2661 int paths_from_inode(u64 inum, struct inode_fs_paths *ipath)
2662 {
2663 	int ret;
2664 	int found_refs = 0;
2665 
2666 	ret = iterate_inode_refs(inum, ipath);
2667 	if (!ret)
2668 		++found_refs;
2669 	else if (ret != -ENOENT)
2670 		return ret;
2671 
2672 	ret = iterate_inode_extrefs(inum, ipath);
2673 	if (ret == -ENOENT && found_refs)
2674 		return 0;
2675 
2676 	return ret;
2677 }
2678 
2679 struct btrfs_data_container *init_data_container(u32 total_bytes)
2680 {
2681 	struct btrfs_data_container *data;
2682 	size_t alloc_bytes;
2683 
2684 	alloc_bytes = max_t(size_t, total_bytes, sizeof(*data));
2685 	data = kvmalloc(alloc_bytes, GFP_KERNEL);
2686 	if (!data)
2687 		return ERR_PTR(-ENOMEM);
2688 
2689 	if (total_bytes >= sizeof(*data)) {
2690 		data->bytes_left = total_bytes - sizeof(*data);
2691 		data->bytes_missing = 0;
2692 	} else {
2693 		data->bytes_missing = sizeof(*data) - total_bytes;
2694 		data->bytes_left = 0;
2695 	}
2696 
2697 	data->elem_cnt = 0;
2698 	data->elem_missed = 0;
2699 
2700 	return data;
2701 }
2702 
2703 /*
2704  * allocates space to return multiple file system paths for an inode.
2705  * total_bytes to allocate are passed, note that space usable for actual path
2706  * information will be total_bytes - sizeof(struct inode_fs_paths).
2707  * the returned pointer must be freed with free_ipath() in the end.
2708  */
2709 struct inode_fs_paths *init_ipath(s32 total_bytes, struct btrfs_root *fs_root,
2710 					struct btrfs_path *path)
2711 {
2712 	struct inode_fs_paths *ifp;
2713 	struct btrfs_data_container *fspath;
2714 
2715 	fspath = init_data_container(total_bytes);
2716 	if (IS_ERR(fspath))
2717 		return ERR_CAST(fspath);
2718 
2719 	ifp = kmalloc(sizeof(*ifp), GFP_KERNEL);
2720 	if (!ifp) {
2721 		kvfree(fspath);
2722 		return ERR_PTR(-ENOMEM);
2723 	}
2724 
2725 	ifp->btrfs_path = path;
2726 	ifp->fspath = fspath;
2727 	ifp->fs_root = fs_root;
2728 
2729 	return ifp;
2730 }
2731 
2732 void free_ipath(struct inode_fs_paths *ipath)
2733 {
2734 	if (!ipath)
2735 		return;
2736 	kvfree(ipath->fspath);
2737 	kfree(ipath);
2738 }
2739 
2740 struct btrfs_backref_iter *btrfs_backref_iter_alloc(struct btrfs_fs_info *fs_info)
2741 {
2742 	struct btrfs_backref_iter *ret;
2743 
2744 	ret = kzalloc(sizeof(*ret), GFP_NOFS);
2745 	if (!ret)
2746 		return NULL;
2747 
2748 	ret->path = btrfs_alloc_path();
2749 	if (!ret->path) {
2750 		kfree(ret);
2751 		return NULL;
2752 	}
2753 
2754 	/* Current backref iterator only supports iteration in commit root */
2755 	ret->path->search_commit_root = 1;
2756 	ret->path->skip_locking = 1;
2757 	ret->fs_info = fs_info;
2758 
2759 	return ret;
2760 }
2761 
2762 int btrfs_backref_iter_start(struct btrfs_backref_iter *iter, u64 bytenr)
2763 {
2764 	struct btrfs_fs_info *fs_info = iter->fs_info;
2765 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2766 	struct btrfs_path *path = iter->path;
2767 	struct btrfs_extent_item *ei;
2768 	struct btrfs_key key;
2769 	int ret;
2770 
2771 	key.objectid = bytenr;
2772 	key.type = BTRFS_METADATA_ITEM_KEY;
2773 	key.offset = (u64)-1;
2774 	iter->bytenr = bytenr;
2775 
2776 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2777 	if (ret < 0)
2778 		return ret;
2779 	if (ret == 0) {
2780 		ret = -EUCLEAN;
2781 		goto release;
2782 	}
2783 	if (path->slots[0] == 0) {
2784 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
2785 		ret = -EUCLEAN;
2786 		goto release;
2787 	}
2788 	path->slots[0]--;
2789 
2790 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2791 	if ((key.type != BTRFS_EXTENT_ITEM_KEY &&
2792 	     key.type != BTRFS_METADATA_ITEM_KEY) || key.objectid != bytenr) {
2793 		ret = -ENOENT;
2794 		goto release;
2795 	}
2796 	memcpy(&iter->cur_key, &key, sizeof(key));
2797 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2798 						    path->slots[0]);
2799 	iter->end_ptr = (u32)(iter->item_ptr +
2800 			btrfs_item_size(path->nodes[0], path->slots[0]));
2801 	ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
2802 			    struct btrfs_extent_item);
2803 
2804 	/*
2805 	 * Only support iteration on tree backref yet.
2806 	 *
2807 	 * This is an extra precaution for non skinny-metadata, where
2808 	 * EXTENT_ITEM is also used for tree blocks, that we can only use
2809 	 * extent flags to determine if it's a tree block.
2810 	 */
2811 	if (btrfs_extent_flags(path->nodes[0], ei) & BTRFS_EXTENT_FLAG_DATA) {
2812 		ret = -ENOTSUPP;
2813 		goto release;
2814 	}
2815 	iter->cur_ptr = (u32)(iter->item_ptr + sizeof(*ei));
2816 
2817 	/* If there is no inline backref, go search for keyed backref */
2818 	if (iter->cur_ptr >= iter->end_ptr) {
2819 		ret = btrfs_next_item(extent_root, path);
2820 
2821 		/* No inline nor keyed ref */
2822 		if (ret > 0) {
2823 			ret = -ENOENT;
2824 			goto release;
2825 		}
2826 		if (ret < 0)
2827 			goto release;
2828 
2829 		btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key,
2830 				path->slots[0]);
2831 		if (iter->cur_key.objectid != bytenr ||
2832 		    (iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
2833 		     iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY)) {
2834 			ret = -ENOENT;
2835 			goto release;
2836 		}
2837 		iter->cur_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2838 							   path->slots[0]);
2839 		iter->item_ptr = iter->cur_ptr;
2840 		iter->end_ptr = (u32)(iter->item_ptr + btrfs_item_size(
2841 				      path->nodes[0], path->slots[0]));
2842 	}
2843 
2844 	return 0;
2845 release:
2846 	btrfs_backref_iter_release(iter);
2847 	return ret;
2848 }
2849 
2850 /*
2851  * Go to the next backref item of current bytenr, can be either inlined or
2852  * keyed.
2853  *
2854  * Caller needs to check whether it's inline ref or not by iter->cur_key.
2855  *
2856  * Return 0 if we get next backref without problem.
2857  * Return >0 if there is no extra backref for this bytenr.
2858  * Return <0 if there is something wrong happened.
2859  */
2860 int btrfs_backref_iter_next(struct btrfs_backref_iter *iter)
2861 {
2862 	struct extent_buffer *eb = btrfs_backref_get_eb(iter);
2863 	struct btrfs_root *extent_root;
2864 	struct btrfs_path *path = iter->path;
2865 	struct btrfs_extent_inline_ref *iref;
2866 	int ret;
2867 	u32 size;
2868 
2869 	if (btrfs_backref_iter_is_inline_ref(iter)) {
2870 		/* We're still inside the inline refs */
2871 		ASSERT(iter->cur_ptr < iter->end_ptr);
2872 
2873 		if (btrfs_backref_has_tree_block_info(iter)) {
2874 			/* First tree block info */
2875 			size = sizeof(struct btrfs_tree_block_info);
2876 		} else {
2877 			/* Use inline ref type to determine the size */
2878 			int type;
2879 
2880 			iref = (struct btrfs_extent_inline_ref *)
2881 				((unsigned long)iter->cur_ptr);
2882 			type = btrfs_extent_inline_ref_type(eb, iref);
2883 
2884 			size = btrfs_extent_inline_ref_size(type);
2885 		}
2886 		iter->cur_ptr += size;
2887 		if (iter->cur_ptr < iter->end_ptr)
2888 			return 0;
2889 
2890 		/* All inline items iterated, fall through */
2891 	}
2892 
2893 	/* We're at keyed items, there is no inline item, go to the next one */
2894 	extent_root = btrfs_extent_root(iter->fs_info, iter->bytenr);
2895 	ret = btrfs_next_item(extent_root, iter->path);
2896 	if (ret)
2897 		return ret;
2898 
2899 	btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key, path->slots[0]);
2900 	if (iter->cur_key.objectid != iter->bytenr ||
2901 	    (iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
2902 	     iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY))
2903 		return 1;
2904 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2905 					path->slots[0]);
2906 	iter->cur_ptr = iter->item_ptr;
2907 	iter->end_ptr = iter->item_ptr + (u32)btrfs_item_size(path->nodes[0],
2908 						path->slots[0]);
2909 	return 0;
2910 }
2911 
2912 void btrfs_backref_init_cache(struct btrfs_fs_info *fs_info,
2913 			      struct btrfs_backref_cache *cache, int is_reloc)
2914 {
2915 	int i;
2916 
2917 	cache->rb_root = RB_ROOT;
2918 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
2919 		INIT_LIST_HEAD(&cache->pending[i]);
2920 	INIT_LIST_HEAD(&cache->changed);
2921 	INIT_LIST_HEAD(&cache->detached);
2922 	INIT_LIST_HEAD(&cache->leaves);
2923 	INIT_LIST_HEAD(&cache->pending_edge);
2924 	INIT_LIST_HEAD(&cache->useless_node);
2925 	cache->fs_info = fs_info;
2926 	cache->is_reloc = is_reloc;
2927 }
2928 
2929 struct btrfs_backref_node *btrfs_backref_alloc_node(
2930 		struct btrfs_backref_cache *cache, u64 bytenr, int level)
2931 {
2932 	struct btrfs_backref_node *node;
2933 
2934 	ASSERT(level >= 0 && level < BTRFS_MAX_LEVEL);
2935 	node = kzalloc(sizeof(*node), GFP_NOFS);
2936 	if (!node)
2937 		return node;
2938 
2939 	INIT_LIST_HEAD(&node->list);
2940 	INIT_LIST_HEAD(&node->upper);
2941 	INIT_LIST_HEAD(&node->lower);
2942 	RB_CLEAR_NODE(&node->rb_node);
2943 	cache->nr_nodes++;
2944 	node->level = level;
2945 	node->bytenr = bytenr;
2946 
2947 	return node;
2948 }
2949 
2950 struct btrfs_backref_edge *btrfs_backref_alloc_edge(
2951 		struct btrfs_backref_cache *cache)
2952 {
2953 	struct btrfs_backref_edge *edge;
2954 
2955 	edge = kzalloc(sizeof(*edge), GFP_NOFS);
2956 	if (edge)
2957 		cache->nr_edges++;
2958 	return edge;
2959 }
2960 
2961 /*
2962  * Drop the backref node from cache, also cleaning up all its
2963  * upper edges and any uncached nodes in the path.
2964  *
2965  * This cleanup happens bottom up, thus the node should either
2966  * be the lowest node in the cache or a detached node.
2967  */
2968 void btrfs_backref_cleanup_node(struct btrfs_backref_cache *cache,
2969 				struct btrfs_backref_node *node)
2970 {
2971 	struct btrfs_backref_node *upper;
2972 	struct btrfs_backref_edge *edge;
2973 
2974 	if (!node)
2975 		return;
2976 
2977 	BUG_ON(!node->lowest && !node->detached);
2978 	while (!list_empty(&node->upper)) {
2979 		edge = list_entry(node->upper.next, struct btrfs_backref_edge,
2980 				  list[LOWER]);
2981 		upper = edge->node[UPPER];
2982 		list_del(&edge->list[LOWER]);
2983 		list_del(&edge->list[UPPER]);
2984 		btrfs_backref_free_edge(cache, edge);
2985 
2986 		/*
2987 		 * Add the node to leaf node list if no other child block
2988 		 * cached.
2989 		 */
2990 		if (list_empty(&upper->lower)) {
2991 			list_add_tail(&upper->lower, &cache->leaves);
2992 			upper->lowest = 1;
2993 		}
2994 	}
2995 
2996 	btrfs_backref_drop_node(cache, node);
2997 }
2998 
2999 /*
3000  * Release all nodes/edges from current cache
3001  */
3002 void btrfs_backref_release_cache(struct btrfs_backref_cache *cache)
3003 {
3004 	struct btrfs_backref_node *node;
3005 	int i;
3006 
3007 	while (!list_empty(&cache->detached)) {
3008 		node = list_entry(cache->detached.next,
3009 				  struct btrfs_backref_node, list);
3010 		btrfs_backref_cleanup_node(cache, node);
3011 	}
3012 
3013 	while (!list_empty(&cache->leaves)) {
3014 		node = list_entry(cache->leaves.next,
3015 				  struct btrfs_backref_node, lower);
3016 		btrfs_backref_cleanup_node(cache, node);
3017 	}
3018 
3019 	cache->last_trans = 0;
3020 
3021 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
3022 		ASSERT(list_empty(&cache->pending[i]));
3023 	ASSERT(list_empty(&cache->pending_edge));
3024 	ASSERT(list_empty(&cache->useless_node));
3025 	ASSERT(list_empty(&cache->changed));
3026 	ASSERT(list_empty(&cache->detached));
3027 	ASSERT(RB_EMPTY_ROOT(&cache->rb_root));
3028 	ASSERT(!cache->nr_nodes);
3029 	ASSERT(!cache->nr_edges);
3030 }
3031 
3032 /*
3033  * Handle direct tree backref
3034  *
3035  * Direct tree backref means, the backref item shows its parent bytenr
3036  * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
3037  *
3038  * @ref_key:	The converted backref key.
3039  *		For keyed backref, it's the item key.
3040  *		For inlined backref, objectid is the bytenr,
3041  *		type is btrfs_inline_ref_type, offset is
3042  *		btrfs_inline_ref_offset.
3043  */
3044 static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
3045 				      struct btrfs_key *ref_key,
3046 				      struct btrfs_backref_node *cur)
3047 {
3048 	struct btrfs_backref_edge *edge;
3049 	struct btrfs_backref_node *upper;
3050 	struct rb_node *rb_node;
3051 
3052 	ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
3053 
3054 	/* Only reloc root uses backref pointing to itself */
3055 	if (ref_key->objectid == ref_key->offset) {
3056 		struct btrfs_root *root;
3057 
3058 		cur->is_reloc_root = 1;
3059 		/* Only reloc backref cache cares about a specific root */
3060 		if (cache->is_reloc) {
3061 			root = find_reloc_root(cache->fs_info, cur->bytenr);
3062 			if (!root)
3063 				return -ENOENT;
3064 			cur->root = root;
3065 		} else {
3066 			/*
3067 			 * For generic purpose backref cache, reloc root node
3068 			 * is useless.
3069 			 */
3070 			list_add(&cur->list, &cache->useless_node);
3071 		}
3072 		return 0;
3073 	}
3074 
3075 	edge = btrfs_backref_alloc_edge(cache);
3076 	if (!edge)
3077 		return -ENOMEM;
3078 
3079 	rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
3080 	if (!rb_node) {
3081 		/* Parent node not yet cached */
3082 		upper = btrfs_backref_alloc_node(cache, ref_key->offset,
3083 					   cur->level + 1);
3084 		if (!upper) {
3085 			btrfs_backref_free_edge(cache, edge);
3086 			return -ENOMEM;
3087 		}
3088 
3089 		/*
3090 		 *  Backrefs for the upper level block isn't cached, add the
3091 		 *  block to pending list
3092 		 */
3093 		list_add_tail(&edge->list[UPPER], &cache->pending_edge);
3094 	} else {
3095 		/* Parent node already cached */
3096 		upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
3097 		ASSERT(upper->checked);
3098 		INIT_LIST_HEAD(&edge->list[UPPER]);
3099 	}
3100 	btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
3101 	return 0;
3102 }
3103 
3104 /*
3105  * Handle indirect tree backref
3106  *
3107  * Indirect tree backref means, we only know which tree the node belongs to.
3108  * We still need to do a tree search to find out the parents. This is for
3109  * TREE_BLOCK_REF backref (keyed or inlined).
3110  *
3111  * @ref_key:	The same as @ref_key in  handle_direct_tree_backref()
3112  * @tree_key:	The first key of this tree block.
3113  * @path:	A clean (released) path, to avoid allocating path every time
3114  *		the function get called.
3115  */
3116 static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
3117 					struct btrfs_path *path,
3118 					struct btrfs_key *ref_key,
3119 					struct btrfs_key *tree_key,
3120 					struct btrfs_backref_node *cur)
3121 {
3122 	struct btrfs_fs_info *fs_info = cache->fs_info;
3123 	struct btrfs_backref_node *upper;
3124 	struct btrfs_backref_node *lower;
3125 	struct btrfs_backref_edge *edge;
3126 	struct extent_buffer *eb;
3127 	struct btrfs_root *root;
3128 	struct rb_node *rb_node;
3129 	int level;
3130 	bool need_check = true;
3131 	int ret;
3132 
3133 	root = btrfs_get_fs_root(fs_info, ref_key->offset, false);
3134 	if (IS_ERR(root))
3135 		return PTR_ERR(root);
3136 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
3137 		cur->cowonly = 1;
3138 
3139 	if (btrfs_root_level(&root->root_item) == cur->level) {
3140 		/* Tree root */
3141 		ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
3142 		/*
3143 		 * For reloc backref cache, we may ignore reloc root.  But for
3144 		 * general purpose backref cache, we can't rely on
3145 		 * btrfs_should_ignore_reloc_root() as it may conflict with
3146 		 * current running relocation and lead to missing root.
3147 		 *
3148 		 * For general purpose backref cache, reloc root detection is
3149 		 * completely relying on direct backref (key->offset is parent
3150 		 * bytenr), thus only do such check for reloc cache.
3151 		 */
3152 		if (btrfs_should_ignore_reloc_root(root) && cache->is_reloc) {
3153 			btrfs_put_root(root);
3154 			list_add(&cur->list, &cache->useless_node);
3155 		} else {
3156 			cur->root = root;
3157 		}
3158 		return 0;
3159 	}
3160 
3161 	level = cur->level + 1;
3162 
3163 	/* Search the tree to find parent blocks referring to the block */
3164 	path->search_commit_root = 1;
3165 	path->skip_locking = 1;
3166 	path->lowest_level = level;
3167 	ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
3168 	path->lowest_level = 0;
3169 	if (ret < 0) {
3170 		btrfs_put_root(root);
3171 		return ret;
3172 	}
3173 	if (ret > 0 && path->slots[level] > 0)
3174 		path->slots[level]--;
3175 
3176 	eb = path->nodes[level];
3177 	if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
3178 		btrfs_err(fs_info,
3179 "couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
3180 			  cur->bytenr, level - 1, root->root_key.objectid,
3181 			  tree_key->objectid, tree_key->type, tree_key->offset);
3182 		btrfs_put_root(root);
3183 		ret = -ENOENT;
3184 		goto out;
3185 	}
3186 	lower = cur;
3187 
3188 	/* Add all nodes and edges in the path */
3189 	for (; level < BTRFS_MAX_LEVEL; level++) {
3190 		if (!path->nodes[level]) {
3191 			ASSERT(btrfs_root_bytenr(&root->root_item) ==
3192 			       lower->bytenr);
3193 			/* Same as previous should_ignore_reloc_root() call */
3194 			if (btrfs_should_ignore_reloc_root(root) &&
3195 			    cache->is_reloc) {
3196 				btrfs_put_root(root);
3197 				list_add(&lower->list, &cache->useless_node);
3198 			} else {
3199 				lower->root = root;
3200 			}
3201 			break;
3202 		}
3203 
3204 		edge = btrfs_backref_alloc_edge(cache);
3205 		if (!edge) {
3206 			btrfs_put_root(root);
3207 			ret = -ENOMEM;
3208 			goto out;
3209 		}
3210 
3211 		eb = path->nodes[level];
3212 		rb_node = rb_simple_search(&cache->rb_root, eb->start);
3213 		if (!rb_node) {
3214 			upper = btrfs_backref_alloc_node(cache, eb->start,
3215 							 lower->level + 1);
3216 			if (!upper) {
3217 				btrfs_put_root(root);
3218 				btrfs_backref_free_edge(cache, edge);
3219 				ret = -ENOMEM;
3220 				goto out;
3221 			}
3222 			upper->owner = btrfs_header_owner(eb);
3223 			if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
3224 				upper->cowonly = 1;
3225 
3226 			/*
3227 			 * If we know the block isn't shared we can avoid
3228 			 * checking its backrefs.
3229 			 */
3230 			if (btrfs_block_can_be_shared(root, eb))
3231 				upper->checked = 0;
3232 			else
3233 				upper->checked = 1;
3234 
3235 			/*
3236 			 * Add the block to pending list if we need to check its
3237 			 * backrefs, we only do this once while walking up a
3238 			 * tree as we will catch anything else later on.
3239 			 */
3240 			if (!upper->checked && need_check) {
3241 				need_check = false;
3242 				list_add_tail(&edge->list[UPPER],
3243 					      &cache->pending_edge);
3244 			} else {
3245 				if (upper->checked)
3246 					need_check = true;
3247 				INIT_LIST_HEAD(&edge->list[UPPER]);
3248 			}
3249 		} else {
3250 			upper = rb_entry(rb_node, struct btrfs_backref_node,
3251 					 rb_node);
3252 			ASSERT(upper->checked);
3253 			INIT_LIST_HEAD(&edge->list[UPPER]);
3254 			if (!upper->owner)
3255 				upper->owner = btrfs_header_owner(eb);
3256 		}
3257 		btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
3258 
3259 		if (rb_node) {
3260 			btrfs_put_root(root);
3261 			break;
3262 		}
3263 		lower = upper;
3264 		upper = NULL;
3265 	}
3266 out:
3267 	btrfs_release_path(path);
3268 	return ret;
3269 }
3270 
3271 /*
3272  * Add backref node @cur into @cache.
3273  *
3274  * NOTE: Even if the function returned 0, @cur is not yet cached as its upper
3275  *	 links aren't yet bi-directional. Needs to finish such links.
3276  *	 Use btrfs_backref_finish_upper_links() to finish such linkage.
3277  *
3278  * @path:	Released path for indirect tree backref lookup
3279  * @iter:	Released backref iter for extent tree search
3280  * @node_key:	The first key of the tree block
3281  */
3282 int btrfs_backref_add_tree_node(struct btrfs_backref_cache *cache,
3283 				struct btrfs_path *path,
3284 				struct btrfs_backref_iter *iter,
3285 				struct btrfs_key *node_key,
3286 				struct btrfs_backref_node *cur)
3287 {
3288 	struct btrfs_fs_info *fs_info = cache->fs_info;
3289 	struct btrfs_backref_edge *edge;
3290 	struct btrfs_backref_node *exist;
3291 	int ret;
3292 
3293 	ret = btrfs_backref_iter_start(iter, cur->bytenr);
3294 	if (ret < 0)
3295 		return ret;
3296 	/*
3297 	 * We skip the first btrfs_tree_block_info, as we don't use the key
3298 	 * stored in it, but fetch it from the tree block
3299 	 */
3300 	if (btrfs_backref_has_tree_block_info(iter)) {
3301 		ret = btrfs_backref_iter_next(iter);
3302 		if (ret < 0)
3303 			goto out;
3304 		/* No extra backref? This means the tree block is corrupted */
3305 		if (ret > 0) {
3306 			ret = -EUCLEAN;
3307 			goto out;
3308 		}
3309 	}
3310 	WARN_ON(cur->checked);
3311 	if (!list_empty(&cur->upper)) {
3312 		/*
3313 		 * The backref was added previously when processing backref of
3314 		 * type BTRFS_TREE_BLOCK_REF_KEY
3315 		 */
3316 		ASSERT(list_is_singular(&cur->upper));
3317 		edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
3318 				  list[LOWER]);
3319 		ASSERT(list_empty(&edge->list[UPPER]));
3320 		exist = edge->node[UPPER];
3321 		/*
3322 		 * Add the upper level block to pending list if we need check
3323 		 * its backrefs
3324 		 */
3325 		if (!exist->checked)
3326 			list_add_tail(&edge->list[UPPER], &cache->pending_edge);
3327 	} else {
3328 		exist = NULL;
3329 	}
3330 
3331 	for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
3332 		struct extent_buffer *eb;
3333 		struct btrfs_key key;
3334 		int type;
3335 
3336 		cond_resched();
3337 		eb = btrfs_backref_get_eb(iter);
3338 
3339 		key.objectid = iter->bytenr;
3340 		if (btrfs_backref_iter_is_inline_ref(iter)) {
3341 			struct btrfs_extent_inline_ref *iref;
3342 
3343 			/* Update key for inline backref */
3344 			iref = (struct btrfs_extent_inline_ref *)
3345 				((unsigned long)iter->cur_ptr);
3346 			type = btrfs_get_extent_inline_ref_type(eb, iref,
3347 							BTRFS_REF_TYPE_BLOCK);
3348 			if (type == BTRFS_REF_TYPE_INVALID) {
3349 				ret = -EUCLEAN;
3350 				goto out;
3351 			}
3352 			key.type = type;
3353 			key.offset = btrfs_extent_inline_ref_offset(eb, iref);
3354 		} else {
3355 			key.type = iter->cur_key.type;
3356 			key.offset = iter->cur_key.offset;
3357 		}
3358 
3359 		/*
3360 		 * Parent node found and matches current inline ref, no need to
3361 		 * rebuild this node for this inline ref
3362 		 */
3363 		if (exist &&
3364 		    ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
3365 		      exist->owner == key.offset) ||
3366 		     (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
3367 		      exist->bytenr == key.offset))) {
3368 			exist = NULL;
3369 			continue;
3370 		}
3371 
3372 		/* SHARED_BLOCK_REF means key.offset is the parent bytenr */
3373 		if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
3374 			ret = handle_direct_tree_backref(cache, &key, cur);
3375 			if (ret < 0)
3376 				goto out;
3377 			continue;
3378 		} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
3379 			ret = -EINVAL;
3380 			btrfs_print_v0_err(fs_info);
3381 			btrfs_handle_fs_error(fs_info, ret, NULL);
3382 			goto out;
3383 		} else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
3384 			continue;
3385 		}
3386 
3387 		/*
3388 		 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
3389 		 * means the root objectid. We need to search the tree to get
3390 		 * its parent bytenr.
3391 		 */
3392 		ret = handle_indirect_tree_backref(cache, path, &key, node_key,
3393 						   cur);
3394 		if (ret < 0)
3395 			goto out;
3396 	}
3397 	ret = 0;
3398 	cur->checked = 1;
3399 	WARN_ON(exist);
3400 out:
3401 	btrfs_backref_iter_release(iter);
3402 	return ret;
3403 }
3404 
3405 /*
3406  * Finish the upwards linkage created by btrfs_backref_add_tree_node()
3407  */
3408 int btrfs_backref_finish_upper_links(struct btrfs_backref_cache *cache,
3409 				     struct btrfs_backref_node *start)
3410 {
3411 	struct list_head *useless_node = &cache->useless_node;
3412 	struct btrfs_backref_edge *edge;
3413 	struct rb_node *rb_node;
3414 	LIST_HEAD(pending_edge);
3415 
3416 	ASSERT(start->checked);
3417 
3418 	/* Insert this node to cache if it's not COW-only */
3419 	if (!start->cowonly) {
3420 		rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
3421 					   &start->rb_node);
3422 		if (rb_node)
3423 			btrfs_backref_panic(cache->fs_info, start->bytenr,
3424 					    -EEXIST);
3425 		list_add_tail(&start->lower, &cache->leaves);
3426 	}
3427 
3428 	/*
3429 	 * Use breadth first search to iterate all related edges.
3430 	 *
3431 	 * The starting points are all the edges of this node
3432 	 */
3433 	list_for_each_entry(edge, &start->upper, list[LOWER])
3434 		list_add_tail(&edge->list[UPPER], &pending_edge);
3435 
3436 	while (!list_empty(&pending_edge)) {
3437 		struct btrfs_backref_node *upper;
3438 		struct btrfs_backref_node *lower;
3439 
3440 		edge = list_first_entry(&pending_edge,
3441 				struct btrfs_backref_edge, list[UPPER]);
3442 		list_del_init(&edge->list[UPPER]);
3443 		upper = edge->node[UPPER];
3444 		lower = edge->node[LOWER];
3445 
3446 		/* Parent is detached, no need to keep any edges */
3447 		if (upper->detached) {
3448 			list_del(&edge->list[LOWER]);
3449 			btrfs_backref_free_edge(cache, edge);
3450 
3451 			/* Lower node is orphan, queue for cleanup */
3452 			if (list_empty(&lower->upper))
3453 				list_add(&lower->list, useless_node);
3454 			continue;
3455 		}
3456 
3457 		/*
3458 		 * All new nodes added in current build_backref_tree() haven't
3459 		 * been linked to the cache rb tree.
3460 		 * So if we have upper->rb_node populated, this means a cache
3461 		 * hit. We only need to link the edge, as @upper and all its
3462 		 * parents have already been linked.
3463 		 */
3464 		if (!RB_EMPTY_NODE(&upper->rb_node)) {
3465 			if (upper->lowest) {
3466 				list_del_init(&upper->lower);
3467 				upper->lowest = 0;
3468 			}
3469 
3470 			list_add_tail(&edge->list[UPPER], &upper->lower);
3471 			continue;
3472 		}
3473 
3474 		/* Sanity check, we shouldn't have any unchecked nodes */
3475 		if (!upper->checked) {
3476 			ASSERT(0);
3477 			return -EUCLEAN;
3478 		}
3479 
3480 		/* Sanity check, COW-only node has non-COW-only parent */
3481 		if (start->cowonly != upper->cowonly) {
3482 			ASSERT(0);
3483 			return -EUCLEAN;
3484 		}
3485 
3486 		/* Only cache non-COW-only (subvolume trees) tree blocks */
3487 		if (!upper->cowonly) {
3488 			rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
3489 						   &upper->rb_node);
3490 			if (rb_node) {
3491 				btrfs_backref_panic(cache->fs_info,
3492 						upper->bytenr, -EEXIST);
3493 				return -EUCLEAN;
3494 			}
3495 		}
3496 
3497 		list_add_tail(&edge->list[UPPER], &upper->lower);
3498 
3499 		/*
3500 		 * Also queue all the parent edges of this uncached node
3501 		 * to finish the upper linkage
3502 		 */
3503 		list_for_each_entry(edge, &upper->upper, list[LOWER])
3504 			list_add_tail(&edge->list[UPPER], &pending_edge);
3505 	}
3506 	return 0;
3507 }
3508 
3509 void btrfs_backref_error_cleanup(struct btrfs_backref_cache *cache,
3510 				 struct btrfs_backref_node *node)
3511 {
3512 	struct btrfs_backref_node *lower;
3513 	struct btrfs_backref_node *upper;
3514 	struct btrfs_backref_edge *edge;
3515 
3516 	while (!list_empty(&cache->useless_node)) {
3517 		lower = list_first_entry(&cache->useless_node,
3518 				   struct btrfs_backref_node, list);
3519 		list_del_init(&lower->list);
3520 	}
3521 	while (!list_empty(&cache->pending_edge)) {
3522 		edge = list_first_entry(&cache->pending_edge,
3523 				struct btrfs_backref_edge, list[UPPER]);
3524 		list_del(&edge->list[UPPER]);
3525 		list_del(&edge->list[LOWER]);
3526 		lower = edge->node[LOWER];
3527 		upper = edge->node[UPPER];
3528 		btrfs_backref_free_edge(cache, edge);
3529 
3530 		/*
3531 		 * Lower is no longer linked to any upper backref nodes and
3532 		 * isn't in the cache, we can free it ourselves.
3533 		 */
3534 		if (list_empty(&lower->upper) &&
3535 		    RB_EMPTY_NODE(&lower->rb_node))
3536 			list_add(&lower->list, &cache->useless_node);
3537 
3538 		if (!RB_EMPTY_NODE(&upper->rb_node))
3539 			continue;
3540 
3541 		/* Add this guy's upper edges to the list to process */
3542 		list_for_each_entry(edge, &upper->upper, list[LOWER])
3543 			list_add_tail(&edge->list[UPPER],
3544 				      &cache->pending_edge);
3545 		if (list_empty(&upper->upper))
3546 			list_add(&upper->list, &cache->useless_node);
3547 	}
3548 
3549 	while (!list_empty(&cache->useless_node)) {
3550 		lower = list_first_entry(&cache->useless_node,
3551 				   struct btrfs_backref_node, list);
3552 		list_del_init(&lower->list);
3553 		if (lower == node)
3554 			node = NULL;
3555 		btrfs_backref_drop_node(cache, lower);
3556 	}
3557 
3558 	btrfs_backref_cleanup_node(cache, node);
3559 	ASSERT(list_empty(&cache->useless_node) &&
3560 	       list_empty(&cache->pending_edge));
3561 }
3562