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