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