xref: /openbmc/linux/fs/btrfs/backref.c (revision 56f5c19920d09bbf91efcf80e6ba301923400f4c)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
2a542ad1bSJan Schmidt /*
3a542ad1bSJan Schmidt  * Copyright (C) 2011 STRATO.  All rights reserved.
4a542ad1bSJan Schmidt  */
5a542ad1bSJan Schmidt 
6f54de068SDavid Sterba #include <linux/mm.h>
7afce772eSLu Fengqi #include <linux/rbtree.h>
800142756SJeff Mahoney #include <trace/events/btrfs.h>
9a542ad1bSJan Schmidt #include "ctree.h"
10a542ad1bSJan Schmidt #include "disk-io.h"
11a542ad1bSJan Schmidt #include "backref.h"
128da6d581SJan Schmidt #include "ulist.h"
138da6d581SJan Schmidt #include "transaction.h"
148da6d581SJan Schmidt #include "delayed-ref.h"
15b916a59aSJan Schmidt #include "locking.h"
161b60d2ecSQu Wenruo #include "misc.h"
17f3a84ccdSFilipe Manana #include "tree-mod-log.h"
18a542ad1bSJan Schmidt 
19dc046b10SJosef Bacik /* Just an arbitrary number so we can be sure this happened */
20dc046b10SJosef Bacik #define BACKREF_FOUND_SHARED 6
21dc046b10SJosef Bacik 
22976b1908SJan Schmidt struct extent_inode_elem {
23976b1908SJan Schmidt 	u64 inum;
24976b1908SJan Schmidt 	u64 offset;
25976b1908SJan Schmidt 	struct extent_inode_elem *next;
26976b1908SJan Schmidt };
27976b1908SJan Schmidt 
2873980becSJeff Mahoney static int check_extent_in_eb(const struct btrfs_key *key,
2973980becSJeff Mahoney 			      const struct extent_buffer *eb,
3073980becSJeff Mahoney 			      const struct btrfs_file_extent_item *fi,
31976b1908SJan Schmidt 			      u64 extent_item_pos,
32c995ab3cSZygo Blaxell 			      struct extent_inode_elem **eie,
33c995ab3cSZygo Blaxell 			      bool ignore_offset)
34976b1908SJan Schmidt {
358ca15e05SJosef Bacik 	u64 offset = 0;
368ca15e05SJosef Bacik 	struct extent_inode_elem *e;
378ca15e05SJosef Bacik 
38c995ab3cSZygo Blaxell 	if (!ignore_offset &&
39c995ab3cSZygo Blaxell 	    !btrfs_file_extent_compression(eb, fi) &&
408ca15e05SJosef Bacik 	    !btrfs_file_extent_encryption(eb, fi) &&
418ca15e05SJosef Bacik 	    !btrfs_file_extent_other_encoding(eb, fi)) {
42976b1908SJan Schmidt 		u64 data_offset;
43976b1908SJan Schmidt 		u64 data_len;
44976b1908SJan Schmidt 
45976b1908SJan Schmidt 		data_offset = btrfs_file_extent_offset(eb, fi);
46976b1908SJan Schmidt 		data_len = btrfs_file_extent_num_bytes(eb, fi);
47976b1908SJan Schmidt 
48976b1908SJan Schmidt 		if (extent_item_pos < data_offset ||
49976b1908SJan Schmidt 		    extent_item_pos >= data_offset + data_len)
50976b1908SJan Schmidt 			return 1;
518ca15e05SJosef Bacik 		offset = extent_item_pos - data_offset;
528ca15e05SJosef Bacik 	}
53976b1908SJan Schmidt 
54976b1908SJan Schmidt 	e = kmalloc(sizeof(*e), GFP_NOFS);
55976b1908SJan Schmidt 	if (!e)
56976b1908SJan Schmidt 		return -ENOMEM;
57976b1908SJan Schmidt 
58976b1908SJan Schmidt 	e->next = *eie;
59976b1908SJan Schmidt 	e->inum = key->objectid;
608ca15e05SJosef Bacik 	e->offset = key->offset + offset;
61976b1908SJan Schmidt 	*eie = e;
62976b1908SJan Schmidt 
63976b1908SJan Schmidt 	return 0;
64976b1908SJan Schmidt }
65976b1908SJan Schmidt 
66f05c4746SWang Shilong static void free_inode_elem_list(struct extent_inode_elem *eie)
67f05c4746SWang Shilong {
68f05c4746SWang Shilong 	struct extent_inode_elem *eie_next;
69f05c4746SWang Shilong 
70f05c4746SWang Shilong 	for (; eie; eie = eie_next) {
71f05c4746SWang Shilong 		eie_next = eie->next;
72f05c4746SWang Shilong 		kfree(eie);
73f05c4746SWang Shilong 	}
74f05c4746SWang Shilong }
75f05c4746SWang Shilong 
7673980becSJeff Mahoney static int find_extent_in_eb(const struct extent_buffer *eb,
7773980becSJeff Mahoney 			     u64 wanted_disk_byte, u64 extent_item_pos,
78c995ab3cSZygo Blaxell 			     struct extent_inode_elem **eie,
79c995ab3cSZygo Blaxell 			     bool ignore_offset)
80976b1908SJan Schmidt {
81976b1908SJan Schmidt 	u64 disk_byte;
82976b1908SJan Schmidt 	struct btrfs_key key;
83976b1908SJan Schmidt 	struct btrfs_file_extent_item *fi;
84976b1908SJan Schmidt 	int slot;
85976b1908SJan Schmidt 	int nritems;
86976b1908SJan Schmidt 	int extent_type;
87976b1908SJan Schmidt 	int ret;
88976b1908SJan Schmidt 
89976b1908SJan Schmidt 	/*
90976b1908SJan Schmidt 	 * from the shared data ref, we only have the leaf but we need
91976b1908SJan Schmidt 	 * the key. thus, we must look into all items and see that we
92976b1908SJan Schmidt 	 * find one (some) with a reference to our extent item.
93976b1908SJan Schmidt 	 */
94976b1908SJan Schmidt 	nritems = btrfs_header_nritems(eb);
95976b1908SJan Schmidt 	for (slot = 0; slot < nritems; ++slot) {
96976b1908SJan Schmidt 		btrfs_item_key_to_cpu(eb, &key, slot);
97976b1908SJan Schmidt 		if (key.type != BTRFS_EXTENT_DATA_KEY)
98976b1908SJan Schmidt 			continue;
99976b1908SJan Schmidt 		fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
100976b1908SJan Schmidt 		extent_type = btrfs_file_extent_type(eb, fi);
101976b1908SJan Schmidt 		if (extent_type == BTRFS_FILE_EXTENT_INLINE)
102976b1908SJan Schmidt 			continue;
103976b1908SJan Schmidt 		/* don't skip BTRFS_FILE_EXTENT_PREALLOC, we can handle that */
104976b1908SJan Schmidt 		disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
105976b1908SJan Schmidt 		if (disk_byte != wanted_disk_byte)
106976b1908SJan Schmidt 			continue;
107976b1908SJan Schmidt 
108c995ab3cSZygo Blaxell 		ret = check_extent_in_eb(&key, eb, fi, extent_item_pos, eie, ignore_offset);
109976b1908SJan Schmidt 		if (ret < 0)
110976b1908SJan Schmidt 			return ret;
111976b1908SJan Schmidt 	}
112976b1908SJan Schmidt 
113976b1908SJan Schmidt 	return 0;
114976b1908SJan Schmidt }
115976b1908SJan Schmidt 
11686d5f994SEdmund Nadolski struct preftree {
117ecf160b4SLiu Bo 	struct rb_root_cached root;
1186c336b21SJeff Mahoney 	unsigned int count;
11986d5f994SEdmund Nadolski };
12086d5f994SEdmund Nadolski 
121ecf160b4SLiu Bo #define PREFTREE_INIT	{ .root = RB_ROOT_CACHED, .count = 0 }
12286d5f994SEdmund Nadolski 
12386d5f994SEdmund Nadolski struct preftrees {
12486d5f994SEdmund Nadolski 	struct preftree direct;    /* BTRFS_SHARED_[DATA|BLOCK]_REF_KEY */
12586d5f994SEdmund Nadolski 	struct preftree indirect;  /* BTRFS_[TREE_BLOCK|EXTENT_DATA]_REF_KEY */
12686d5f994SEdmund Nadolski 	struct preftree indirect_missing_keys;
12786d5f994SEdmund Nadolski };
12886d5f994SEdmund Nadolski 
1293ec4d323SEdmund Nadolski /*
1303ec4d323SEdmund Nadolski  * Checks for a shared extent during backref search.
1313ec4d323SEdmund Nadolski  *
1323ec4d323SEdmund Nadolski  * The share_count tracks prelim_refs (direct and indirect) having a
1333ec4d323SEdmund Nadolski  * ref->count >0:
1343ec4d323SEdmund Nadolski  *  - incremented when a ref->count transitions to >0
1353ec4d323SEdmund Nadolski  *  - decremented when a ref->count transitions to <1
1363ec4d323SEdmund Nadolski  */
1373ec4d323SEdmund Nadolski struct share_check {
1383ec4d323SEdmund Nadolski 	u64 root_objectid;
1393ec4d323SEdmund Nadolski 	u64 inum;
1403ec4d323SEdmund Nadolski 	int share_count;
1414fc7b572SFilipe Manana 	bool have_delayed_delete_refs;
1423ec4d323SEdmund Nadolski };
1433ec4d323SEdmund Nadolski 
1443ec4d323SEdmund Nadolski static inline int extent_is_shared(struct share_check *sc)
1453ec4d323SEdmund Nadolski {
1463ec4d323SEdmund Nadolski 	return (sc && sc->share_count > 1) ? BACKREF_FOUND_SHARED : 0;
1473ec4d323SEdmund Nadolski }
1483ec4d323SEdmund Nadolski 
149b9e9a6cbSWang Shilong static struct kmem_cache *btrfs_prelim_ref_cache;
150b9e9a6cbSWang Shilong 
151b9e9a6cbSWang Shilong int __init btrfs_prelim_ref_init(void)
152b9e9a6cbSWang Shilong {
153b9e9a6cbSWang Shilong 	btrfs_prelim_ref_cache = kmem_cache_create("btrfs_prelim_ref",
154e0c476b1SJeff Mahoney 					sizeof(struct prelim_ref),
155b9e9a6cbSWang Shilong 					0,
156fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
157b9e9a6cbSWang Shilong 					NULL);
158b9e9a6cbSWang Shilong 	if (!btrfs_prelim_ref_cache)
159b9e9a6cbSWang Shilong 		return -ENOMEM;
160b9e9a6cbSWang Shilong 	return 0;
161b9e9a6cbSWang Shilong }
162b9e9a6cbSWang Shilong 
163e67c718bSDavid Sterba void __cold btrfs_prelim_ref_exit(void)
164b9e9a6cbSWang Shilong {
165b9e9a6cbSWang Shilong 	kmem_cache_destroy(btrfs_prelim_ref_cache);
166b9e9a6cbSWang Shilong }
167b9e9a6cbSWang Shilong 
16886d5f994SEdmund Nadolski static void free_pref(struct prelim_ref *ref)
16986d5f994SEdmund Nadolski {
17086d5f994SEdmund Nadolski 	kmem_cache_free(btrfs_prelim_ref_cache, ref);
17186d5f994SEdmund Nadolski }
17286d5f994SEdmund Nadolski 
17386d5f994SEdmund Nadolski /*
17486d5f994SEdmund Nadolski  * Return 0 when both refs are for the same block (and can be merged).
17586d5f994SEdmund Nadolski  * A -1 return indicates ref1 is a 'lower' block than ref2, while 1
17686d5f994SEdmund Nadolski  * indicates a 'higher' block.
17786d5f994SEdmund Nadolski  */
17886d5f994SEdmund Nadolski static int prelim_ref_compare(struct prelim_ref *ref1,
17986d5f994SEdmund Nadolski 			      struct prelim_ref *ref2)
18086d5f994SEdmund Nadolski {
18186d5f994SEdmund Nadolski 	if (ref1->level < ref2->level)
18286d5f994SEdmund Nadolski 		return -1;
18386d5f994SEdmund Nadolski 	if (ref1->level > ref2->level)
18486d5f994SEdmund Nadolski 		return 1;
18586d5f994SEdmund Nadolski 	if (ref1->root_id < ref2->root_id)
18686d5f994SEdmund Nadolski 		return -1;
18786d5f994SEdmund Nadolski 	if (ref1->root_id > ref2->root_id)
18886d5f994SEdmund Nadolski 		return 1;
18986d5f994SEdmund Nadolski 	if (ref1->key_for_search.type < ref2->key_for_search.type)
19086d5f994SEdmund Nadolski 		return -1;
19186d5f994SEdmund Nadolski 	if (ref1->key_for_search.type > ref2->key_for_search.type)
19286d5f994SEdmund Nadolski 		return 1;
19386d5f994SEdmund Nadolski 	if (ref1->key_for_search.objectid < ref2->key_for_search.objectid)
19486d5f994SEdmund Nadolski 		return -1;
19586d5f994SEdmund Nadolski 	if (ref1->key_for_search.objectid > ref2->key_for_search.objectid)
19686d5f994SEdmund Nadolski 		return 1;
19786d5f994SEdmund Nadolski 	if (ref1->key_for_search.offset < ref2->key_for_search.offset)
19886d5f994SEdmund Nadolski 		return -1;
19986d5f994SEdmund Nadolski 	if (ref1->key_for_search.offset > ref2->key_for_search.offset)
20086d5f994SEdmund Nadolski 		return 1;
20186d5f994SEdmund Nadolski 	if (ref1->parent < ref2->parent)
20286d5f994SEdmund Nadolski 		return -1;
20386d5f994SEdmund Nadolski 	if (ref1->parent > ref2->parent)
20486d5f994SEdmund Nadolski 		return 1;
20586d5f994SEdmund Nadolski 
20686d5f994SEdmund Nadolski 	return 0;
20786d5f994SEdmund Nadolski }
20886d5f994SEdmund Nadolski 
209ccc8dc75SColin Ian King static void update_share_count(struct share_check *sc, int oldcount,
210ccc8dc75SColin Ian King 			       int newcount)
2113ec4d323SEdmund Nadolski {
2123ec4d323SEdmund Nadolski 	if ((!sc) || (oldcount == 0 && newcount < 1))
2133ec4d323SEdmund Nadolski 		return;
2143ec4d323SEdmund Nadolski 
2153ec4d323SEdmund Nadolski 	if (oldcount > 0 && newcount < 1)
2163ec4d323SEdmund Nadolski 		sc->share_count--;
2173ec4d323SEdmund Nadolski 	else if (oldcount < 1 && newcount > 0)
2183ec4d323SEdmund Nadolski 		sc->share_count++;
2193ec4d323SEdmund Nadolski }
2203ec4d323SEdmund Nadolski 
22186d5f994SEdmund Nadolski /*
22286d5f994SEdmund Nadolski  * Add @newref to the @root rbtree, merging identical refs.
22386d5f994SEdmund Nadolski  *
2243ec4d323SEdmund Nadolski  * Callers should assume that newref has been freed after calling.
22586d5f994SEdmund Nadolski  */
22600142756SJeff Mahoney static void prelim_ref_insert(const struct btrfs_fs_info *fs_info,
22700142756SJeff Mahoney 			      struct preftree *preftree,
2283ec4d323SEdmund Nadolski 			      struct prelim_ref *newref,
2293ec4d323SEdmund Nadolski 			      struct share_check *sc)
23086d5f994SEdmund Nadolski {
231ecf160b4SLiu Bo 	struct rb_root_cached *root;
23286d5f994SEdmund Nadolski 	struct rb_node **p;
23386d5f994SEdmund Nadolski 	struct rb_node *parent = NULL;
23486d5f994SEdmund Nadolski 	struct prelim_ref *ref;
23586d5f994SEdmund Nadolski 	int result;
236ecf160b4SLiu Bo 	bool leftmost = true;
23786d5f994SEdmund Nadolski 
23886d5f994SEdmund Nadolski 	root = &preftree->root;
239ecf160b4SLiu Bo 	p = &root->rb_root.rb_node;
24086d5f994SEdmund Nadolski 
24186d5f994SEdmund Nadolski 	while (*p) {
24286d5f994SEdmund Nadolski 		parent = *p;
24386d5f994SEdmund Nadolski 		ref = rb_entry(parent, struct prelim_ref, rbnode);
24486d5f994SEdmund Nadolski 		result = prelim_ref_compare(ref, newref);
24586d5f994SEdmund Nadolski 		if (result < 0) {
24686d5f994SEdmund Nadolski 			p = &(*p)->rb_left;
24786d5f994SEdmund Nadolski 		} else if (result > 0) {
24886d5f994SEdmund Nadolski 			p = &(*p)->rb_right;
249ecf160b4SLiu Bo 			leftmost = false;
25086d5f994SEdmund Nadolski 		} else {
25186d5f994SEdmund Nadolski 			/* Identical refs, merge them and free @newref */
25286d5f994SEdmund Nadolski 			struct extent_inode_elem *eie = ref->inode_list;
25386d5f994SEdmund Nadolski 
25486d5f994SEdmund Nadolski 			while (eie && eie->next)
25586d5f994SEdmund Nadolski 				eie = eie->next;
25686d5f994SEdmund Nadolski 
25786d5f994SEdmund Nadolski 			if (!eie)
25886d5f994SEdmund Nadolski 				ref->inode_list = newref->inode_list;
25986d5f994SEdmund Nadolski 			else
26086d5f994SEdmund Nadolski 				eie->next = newref->inode_list;
26100142756SJeff Mahoney 			trace_btrfs_prelim_ref_merge(fs_info, ref, newref,
26200142756SJeff Mahoney 						     preftree->count);
2633ec4d323SEdmund Nadolski 			/*
2643ec4d323SEdmund Nadolski 			 * A delayed ref can have newref->count < 0.
2653ec4d323SEdmund Nadolski 			 * The ref->count is updated to follow any
2663ec4d323SEdmund Nadolski 			 * BTRFS_[ADD|DROP]_DELAYED_REF actions.
2673ec4d323SEdmund Nadolski 			 */
2683ec4d323SEdmund Nadolski 			update_share_count(sc, ref->count,
2693ec4d323SEdmund Nadolski 					   ref->count + newref->count);
27086d5f994SEdmund Nadolski 			ref->count += newref->count;
27186d5f994SEdmund Nadolski 			free_pref(newref);
27286d5f994SEdmund Nadolski 			return;
27386d5f994SEdmund Nadolski 		}
27486d5f994SEdmund Nadolski 	}
27586d5f994SEdmund Nadolski 
2763ec4d323SEdmund Nadolski 	update_share_count(sc, 0, newref->count);
2776c336b21SJeff Mahoney 	preftree->count++;
27800142756SJeff Mahoney 	trace_btrfs_prelim_ref_insert(fs_info, newref, NULL, preftree->count);
27986d5f994SEdmund Nadolski 	rb_link_node(&newref->rbnode, parent, p);
280ecf160b4SLiu Bo 	rb_insert_color_cached(&newref->rbnode, root, leftmost);
28186d5f994SEdmund Nadolski }
28286d5f994SEdmund Nadolski 
28386d5f994SEdmund Nadolski /*
28486d5f994SEdmund Nadolski  * Release the entire tree.  We don't care about internal consistency so
28586d5f994SEdmund Nadolski  * just free everything and then reset the tree root.
28686d5f994SEdmund Nadolski  */
28786d5f994SEdmund Nadolski static void prelim_release(struct preftree *preftree)
28886d5f994SEdmund Nadolski {
28986d5f994SEdmund Nadolski 	struct prelim_ref *ref, *next_ref;
29086d5f994SEdmund Nadolski 
291ecf160b4SLiu Bo 	rbtree_postorder_for_each_entry_safe(ref, next_ref,
29292876eecSFilipe Manana 					     &preftree->root.rb_root, rbnode) {
29392876eecSFilipe Manana 		free_inode_elem_list(ref->inode_list);
29486d5f994SEdmund Nadolski 		free_pref(ref);
29592876eecSFilipe Manana 	}
29686d5f994SEdmund Nadolski 
297ecf160b4SLiu Bo 	preftree->root = RB_ROOT_CACHED;
2986c336b21SJeff Mahoney 	preftree->count = 0;
29986d5f994SEdmund Nadolski }
30086d5f994SEdmund Nadolski 
301d5c88b73SJan Schmidt /*
302d5c88b73SJan Schmidt  * the rules for all callers of this function are:
303d5c88b73SJan Schmidt  * - obtaining the parent is the goal
304d5c88b73SJan Schmidt  * - if you add a key, you must know that it is a correct key
305d5c88b73SJan Schmidt  * - if you cannot add the parent or a correct key, then we will look into the
306d5c88b73SJan Schmidt  *   block later to set a correct key
307d5c88b73SJan Schmidt  *
308d5c88b73SJan Schmidt  * delayed refs
309d5c88b73SJan Schmidt  * ============
310d5c88b73SJan Schmidt  *        backref type | shared | indirect | shared | indirect
311d5c88b73SJan Schmidt  * information         |   tree |     tree |   data |     data
312d5c88b73SJan Schmidt  * --------------------+--------+----------+--------+----------
313d5c88b73SJan Schmidt  *      parent logical |    y   |     -    |    -   |     -
314d5c88b73SJan Schmidt  *      key to resolve |    -   |     y    |    y   |     y
315d5c88b73SJan Schmidt  *  tree block logical |    -   |     -    |    -   |     -
316d5c88b73SJan Schmidt  *  root for resolving |    y   |     y    |    y   |     y
317d5c88b73SJan Schmidt  *
318d5c88b73SJan Schmidt  * - column 1:       we've the parent -> done
319d5c88b73SJan Schmidt  * - column 2, 3, 4: we use the key to find the parent
320d5c88b73SJan Schmidt  *
321d5c88b73SJan Schmidt  * on disk refs (inline or keyed)
322d5c88b73SJan Schmidt  * ==============================
323d5c88b73SJan Schmidt  *        backref type | shared | indirect | shared | indirect
324d5c88b73SJan Schmidt  * information         |   tree |     tree |   data |     data
325d5c88b73SJan Schmidt  * --------------------+--------+----------+--------+----------
326d5c88b73SJan Schmidt  *      parent logical |    y   |     -    |    y   |     -
327d5c88b73SJan Schmidt  *      key to resolve |    -   |     -    |    -   |     y
328d5c88b73SJan Schmidt  *  tree block logical |    y   |     y    |    y   |     y
329d5c88b73SJan Schmidt  *  root for resolving |    -   |     y    |    y   |     y
330d5c88b73SJan Schmidt  *
331d5c88b73SJan Schmidt  * - column 1, 3: we've the parent -> done
332d5c88b73SJan Schmidt  * - column 2:    we take the first key from the block to find the parent
333e0c476b1SJeff Mahoney  *                (see add_missing_keys)
334d5c88b73SJan Schmidt  * - column 4:    we use the key to find the parent
335d5c88b73SJan Schmidt  *
336d5c88b73SJan Schmidt  * additional information that's available but not required to find the parent
337d5c88b73SJan Schmidt  * block might help in merging entries to gain some speed.
338d5c88b73SJan Schmidt  */
33900142756SJeff Mahoney static int add_prelim_ref(const struct btrfs_fs_info *fs_info,
34000142756SJeff Mahoney 			  struct preftree *preftree, u64 root_id,
341e0c476b1SJeff Mahoney 			  const struct btrfs_key *key, int level, u64 parent,
3423ec4d323SEdmund Nadolski 			  u64 wanted_disk_byte, int count,
3433ec4d323SEdmund Nadolski 			  struct share_check *sc, gfp_t gfp_mask)
3448da6d581SJan Schmidt {
345e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
3468da6d581SJan Schmidt 
34748ec4736SLiu Bo 	if (root_id == BTRFS_DATA_RELOC_TREE_OBJECTID)
34848ec4736SLiu Bo 		return 0;
34948ec4736SLiu Bo 
350b9e9a6cbSWang Shilong 	ref = kmem_cache_alloc(btrfs_prelim_ref_cache, gfp_mask);
3518da6d581SJan Schmidt 	if (!ref)
3528da6d581SJan Schmidt 		return -ENOMEM;
3538da6d581SJan Schmidt 
3548da6d581SJan Schmidt 	ref->root_id = root_id;
3557ac8b88eSethanwu 	if (key)
356d5c88b73SJan Schmidt 		ref->key_for_search = *key;
3577ac8b88eSethanwu 	else
358d5c88b73SJan Schmidt 		memset(&ref->key_for_search, 0, sizeof(ref->key_for_search));
3598da6d581SJan Schmidt 
3603301958bSJan Schmidt 	ref->inode_list = NULL;
3618da6d581SJan Schmidt 	ref->level = level;
3628da6d581SJan Schmidt 	ref->count = count;
3638da6d581SJan Schmidt 	ref->parent = parent;
3648da6d581SJan Schmidt 	ref->wanted_disk_byte = wanted_disk_byte;
3653ec4d323SEdmund Nadolski 	prelim_ref_insert(fs_info, preftree, ref, sc);
3663ec4d323SEdmund Nadolski 	return extent_is_shared(sc);
3678da6d581SJan Schmidt }
3688da6d581SJan Schmidt 
36986d5f994SEdmund Nadolski /* direct refs use root == 0, key == NULL */
37000142756SJeff Mahoney static int add_direct_ref(const struct btrfs_fs_info *fs_info,
37100142756SJeff Mahoney 			  struct preftrees *preftrees, int level, u64 parent,
3723ec4d323SEdmund Nadolski 			  u64 wanted_disk_byte, int count,
3733ec4d323SEdmund Nadolski 			  struct share_check *sc, gfp_t gfp_mask)
37486d5f994SEdmund Nadolski {
37500142756SJeff Mahoney 	return add_prelim_ref(fs_info, &preftrees->direct, 0, NULL, level,
3763ec4d323SEdmund Nadolski 			      parent, wanted_disk_byte, count, sc, gfp_mask);
37786d5f994SEdmund Nadolski }
37886d5f994SEdmund Nadolski 
37986d5f994SEdmund Nadolski /* indirect refs use parent == 0 */
38000142756SJeff Mahoney static int add_indirect_ref(const struct btrfs_fs_info *fs_info,
38100142756SJeff Mahoney 			    struct preftrees *preftrees, u64 root_id,
38286d5f994SEdmund Nadolski 			    const struct btrfs_key *key, int level,
3833ec4d323SEdmund Nadolski 			    u64 wanted_disk_byte, int count,
3843ec4d323SEdmund Nadolski 			    struct share_check *sc, gfp_t gfp_mask)
38586d5f994SEdmund Nadolski {
38686d5f994SEdmund Nadolski 	struct preftree *tree = &preftrees->indirect;
38786d5f994SEdmund Nadolski 
38886d5f994SEdmund Nadolski 	if (!key)
38986d5f994SEdmund Nadolski 		tree = &preftrees->indirect_missing_keys;
39000142756SJeff Mahoney 	return add_prelim_ref(fs_info, tree, root_id, key, level, 0,
3913ec4d323SEdmund Nadolski 			      wanted_disk_byte, count, sc, gfp_mask);
39286d5f994SEdmund Nadolski }
39386d5f994SEdmund Nadolski 
394ed58f2e6Sethanwu static int is_shared_data_backref(struct preftrees *preftrees, u64 bytenr)
395ed58f2e6Sethanwu {
396ed58f2e6Sethanwu 	struct rb_node **p = &preftrees->direct.root.rb_root.rb_node;
397ed58f2e6Sethanwu 	struct rb_node *parent = NULL;
398ed58f2e6Sethanwu 	struct prelim_ref *ref = NULL;
3999c6c723fSArnd Bergmann 	struct prelim_ref target = {};
400ed58f2e6Sethanwu 	int result;
401ed58f2e6Sethanwu 
402ed58f2e6Sethanwu 	target.parent = bytenr;
403ed58f2e6Sethanwu 
404ed58f2e6Sethanwu 	while (*p) {
405ed58f2e6Sethanwu 		parent = *p;
406ed58f2e6Sethanwu 		ref = rb_entry(parent, struct prelim_ref, rbnode);
407ed58f2e6Sethanwu 		result = prelim_ref_compare(ref, &target);
408ed58f2e6Sethanwu 
409ed58f2e6Sethanwu 		if (result < 0)
410ed58f2e6Sethanwu 			p = &(*p)->rb_left;
411ed58f2e6Sethanwu 		else if (result > 0)
412ed58f2e6Sethanwu 			p = &(*p)->rb_right;
413ed58f2e6Sethanwu 		else
414ed58f2e6Sethanwu 			return 1;
415ed58f2e6Sethanwu 	}
416ed58f2e6Sethanwu 	return 0;
417ed58f2e6Sethanwu }
418ed58f2e6Sethanwu 
4198da6d581SJan Schmidt static int add_all_parents(struct btrfs_root *root, struct btrfs_path *path,
420ed58f2e6Sethanwu 			   struct ulist *parents,
421ed58f2e6Sethanwu 			   struct preftrees *preftrees, struct prelim_ref *ref,
42244853868SJosef Bacik 			   int level, u64 time_seq, const u64 *extent_item_pos,
423b25b0b87Sethanwu 			   bool ignore_offset)
4248da6d581SJan Schmidt {
42569bca40dSAlexander Block 	int ret = 0;
42669bca40dSAlexander Block 	int slot;
42769bca40dSAlexander Block 	struct extent_buffer *eb;
42869bca40dSAlexander Block 	struct btrfs_key key;
4297ef81ac8SJosef Bacik 	struct btrfs_key *key_for_search = &ref->key_for_search;
4308da6d581SJan Schmidt 	struct btrfs_file_extent_item *fi;
431ed8c4913SJosef Bacik 	struct extent_inode_elem *eie = NULL, *old = NULL;
4328da6d581SJan Schmidt 	u64 disk_byte;
4337ef81ac8SJosef Bacik 	u64 wanted_disk_byte = ref->wanted_disk_byte;
4347ef81ac8SJosef Bacik 	u64 count = 0;
4357ac8b88eSethanwu 	u64 data_offset;
4368da6d581SJan Schmidt 
43769bca40dSAlexander Block 	if (level != 0) {
43869bca40dSAlexander Block 		eb = path->nodes[level];
43969bca40dSAlexander Block 		ret = ulist_add(parents, eb->start, 0, GFP_NOFS);
4403301958bSJan Schmidt 		if (ret < 0)
4413301958bSJan Schmidt 			return ret;
4428da6d581SJan Schmidt 		return 0;
44369bca40dSAlexander Block 	}
4448da6d581SJan Schmidt 
4458da6d581SJan Schmidt 	/*
446ed58f2e6Sethanwu 	 * 1. We normally enter this function with the path already pointing to
44769bca40dSAlexander Block 	 *    the first item to check. But sometimes, we may enter it with
448ed58f2e6Sethanwu 	 *    slot == nritems.
449ed58f2e6Sethanwu 	 * 2. We are searching for normal backref but bytenr of this leaf
450ed58f2e6Sethanwu 	 *    matches shared data backref
451cfc0eed0Sethanwu 	 * 3. The leaf owner is not equal to the root we are searching
452cfc0eed0Sethanwu 	 *
453ed58f2e6Sethanwu 	 * For these cases, go to the next leaf before we continue.
4548da6d581SJan Schmidt 	 */
455ed58f2e6Sethanwu 	eb = path->nodes[0];
456ed58f2e6Sethanwu 	if (path->slots[0] >= btrfs_header_nritems(eb) ||
457cfc0eed0Sethanwu 	    is_shared_data_backref(preftrees, eb->start) ||
458cfc0eed0Sethanwu 	    ref->root_id != btrfs_header_owner(eb)) {
459f3a84ccdSFilipe Manana 		if (time_seq == BTRFS_SEQ_LAST)
46021633fc6SQu Wenruo 			ret = btrfs_next_leaf(root, path);
46121633fc6SQu Wenruo 		else
4623d7806ecSJan Schmidt 			ret = btrfs_next_old_leaf(root, path, time_seq);
46321633fc6SQu Wenruo 	}
4648da6d581SJan Schmidt 
465b25b0b87Sethanwu 	while (!ret && count < ref->count) {
4668da6d581SJan Schmidt 		eb = path->nodes[0];
46769bca40dSAlexander Block 		slot = path->slots[0];
46869bca40dSAlexander Block 
46969bca40dSAlexander Block 		btrfs_item_key_to_cpu(eb, &key, slot);
47069bca40dSAlexander Block 
47169bca40dSAlexander Block 		if (key.objectid != key_for_search->objectid ||
47269bca40dSAlexander Block 		    key.type != BTRFS_EXTENT_DATA_KEY)
47369bca40dSAlexander Block 			break;
47469bca40dSAlexander Block 
475ed58f2e6Sethanwu 		/*
476ed58f2e6Sethanwu 		 * We are searching for normal backref but bytenr of this leaf
477cfc0eed0Sethanwu 		 * matches shared data backref, OR
478cfc0eed0Sethanwu 		 * the leaf owner is not equal to the root we are searching for
479ed58f2e6Sethanwu 		 */
480cfc0eed0Sethanwu 		if (slot == 0 &&
481cfc0eed0Sethanwu 		    (is_shared_data_backref(preftrees, eb->start) ||
482cfc0eed0Sethanwu 		     ref->root_id != btrfs_header_owner(eb))) {
483f3a84ccdSFilipe Manana 			if (time_seq == BTRFS_SEQ_LAST)
484ed58f2e6Sethanwu 				ret = btrfs_next_leaf(root, path);
485ed58f2e6Sethanwu 			else
486ed58f2e6Sethanwu 				ret = btrfs_next_old_leaf(root, path, time_seq);
487ed58f2e6Sethanwu 			continue;
488ed58f2e6Sethanwu 		}
48969bca40dSAlexander Block 		fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
4908da6d581SJan Schmidt 		disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
4917ac8b88eSethanwu 		data_offset = btrfs_file_extent_offset(eb, fi);
49269bca40dSAlexander Block 
49369bca40dSAlexander Block 		if (disk_byte == wanted_disk_byte) {
49469bca40dSAlexander Block 			eie = NULL;
495ed8c4913SJosef Bacik 			old = NULL;
4967ac8b88eSethanwu 			if (ref->key_for_search.offset == key.offset - data_offset)
4977ef81ac8SJosef Bacik 				count++;
4987ac8b88eSethanwu 			else
4997ac8b88eSethanwu 				goto next;
50069bca40dSAlexander Block 			if (extent_item_pos) {
50169bca40dSAlexander Block 				ret = check_extent_in_eb(&key, eb, fi,
50269bca40dSAlexander Block 						*extent_item_pos,
503c995ab3cSZygo Blaxell 						&eie, ignore_offset);
50469bca40dSAlexander Block 				if (ret < 0)
50569bca40dSAlexander Block 					break;
5068da6d581SJan Schmidt 			}
507ed8c4913SJosef Bacik 			if (ret > 0)
508ed8c4913SJosef Bacik 				goto next;
5094eb1f66dSTakashi Iwai 			ret = ulist_add_merge_ptr(parents, eb->start,
5104eb1f66dSTakashi Iwai 						  eie, (void **)&old, GFP_NOFS);
51169bca40dSAlexander Block 			if (ret < 0)
51269bca40dSAlexander Block 				break;
513ed8c4913SJosef Bacik 			if (!ret && extent_item_pos) {
514ed8c4913SJosef Bacik 				while (old->next)
515ed8c4913SJosef Bacik 					old = old->next;
516ed8c4913SJosef Bacik 				old->next = eie;
51769bca40dSAlexander Block 			}
518f05c4746SWang Shilong 			eie = NULL;
51969bca40dSAlexander Block 		}
520ed8c4913SJosef Bacik next:
521f3a84ccdSFilipe Manana 		if (time_seq == BTRFS_SEQ_LAST)
52221633fc6SQu Wenruo 			ret = btrfs_next_item(root, path);
52321633fc6SQu Wenruo 		else
52469bca40dSAlexander Block 			ret = btrfs_next_old_item(root, path, time_seq);
5258da6d581SJan Schmidt 	}
5268da6d581SJan Schmidt 
52769bca40dSAlexander Block 	if (ret > 0)
52869bca40dSAlexander Block 		ret = 0;
529f05c4746SWang Shilong 	else if (ret < 0)
530f05c4746SWang Shilong 		free_inode_elem_list(eie);
53169bca40dSAlexander Block 	return ret;
5328da6d581SJan Schmidt }
5338da6d581SJan Schmidt 
5348da6d581SJan Schmidt /*
5358da6d581SJan Schmidt  * resolve an indirect backref in the form (root_id, key, level)
5368da6d581SJan Schmidt  * to a logical address
5378da6d581SJan Schmidt  */
538e0c476b1SJeff Mahoney static int resolve_indirect_ref(struct btrfs_fs_info *fs_info,
539da61d31aSJosef Bacik 				struct btrfs_path *path, u64 time_seq,
540ed58f2e6Sethanwu 				struct preftrees *preftrees,
541e0c476b1SJeff Mahoney 				struct prelim_ref *ref, struct ulist *parents,
542b25b0b87Sethanwu 				const u64 *extent_item_pos, bool ignore_offset)
5438da6d581SJan Schmidt {
5448da6d581SJan Schmidt 	struct btrfs_root *root;
5458da6d581SJan Schmidt 	struct extent_buffer *eb;
5468da6d581SJan Schmidt 	int ret = 0;
5478da6d581SJan Schmidt 	int root_level;
5488da6d581SJan Schmidt 	int level = ref->level;
5497ac8b88eSethanwu 	struct btrfs_key search_key = ref->key_for_search;
5508da6d581SJan Schmidt 
55149d11beaSJosef Bacik 	/*
55249d11beaSJosef Bacik 	 * If we're search_commit_root we could possibly be holding locks on
55349d11beaSJosef Bacik 	 * other tree nodes.  This happens when qgroups does backref walks when
55449d11beaSJosef Bacik 	 * adding new delayed refs.  To deal with this we need to look in cache
55549d11beaSJosef Bacik 	 * for the root, and if we don't find it then we need to search the
55649d11beaSJosef Bacik 	 * tree_root's commit root, thus the btrfs_get_fs_root_commit_root usage
55749d11beaSJosef Bacik 	 * here.
55849d11beaSJosef Bacik 	 */
55949d11beaSJosef Bacik 	if (path->search_commit_root)
56049d11beaSJosef Bacik 		root = btrfs_get_fs_root_commit_root(fs_info, path, ref->root_id);
56149d11beaSJosef Bacik 	else
56256e9357aSDavid Sterba 		root = btrfs_get_fs_root(fs_info, ref->root_id, false);
5638da6d581SJan Schmidt 	if (IS_ERR(root)) {
5648da6d581SJan Schmidt 		ret = PTR_ERR(root);
5659326f76fSJosef Bacik 		goto out_free;
5669326f76fSJosef Bacik 	}
5679326f76fSJosef Bacik 
56839dba873SJosef Bacik 	if (!path->search_commit_root &&
56939dba873SJosef Bacik 	    test_bit(BTRFS_ROOT_DELETING, &root->state)) {
57039dba873SJosef Bacik 		ret = -ENOENT;
57139dba873SJosef Bacik 		goto out;
57239dba873SJosef Bacik 	}
57339dba873SJosef Bacik 
574f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(fs_info)) {
575d9ee522bSJosef Bacik 		ret = -ENOENT;
576d9ee522bSJosef Bacik 		goto out;
577d9ee522bSJosef Bacik 	}
578d9ee522bSJosef Bacik 
5799e351cc8SJosef Bacik 	if (path->search_commit_root)
5809e351cc8SJosef Bacik 		root_level = btrfs_header_level(root->commit_root);
581f3a84ccdSFilipe Manana 	else if (time_seq == BTRFS_SEQ_LAST)
58221633fc6SQu Wenruo 		root_level = btrfs_header_level(root->node);
5839e351cc8SJosef Bacik 	else
5845b6602e7SJan Schmidt 		root_level = btrfs_old_root_level(root, time_seq);
5858da6d581SJan Schmidt 
586c75e8394SJosef Bacik 	if (root_level + 1 == level)
5878da6d581SJan Schmidt 		goto out;
5888da6d581SJan Schmidt 
5897ac8b88eSethanwu 	/*
5907ac8b88eSethanwu 	 * We can often find data backrefs with an offset that is too large
5917ac8b88eSethanwu 	 * (>= LLONG_MAX, maximum allowed file offset) due to underflows when
5927ac8b88eSethanwu 	 * subtracting a file's offset with the data offset of its
5937ac8b88eSethanwu 	 * corresponding extent data item. This can happen for example in the
5947ac8b88eSethanwu 	 * clone ioctl.
5957ac8b88eSethanwu 	 *
5967ac8b88eSethanwu 	 * So if we detect such case we set the search key's offset to zero to
5977ac8b88eSethanwu 	 * make sure we will find the matching file extent item at
5987ac8b88eSethanwu 	 * add_all_parents(), otherwise we will miss it because the offset
5997ac8b88eSethanwu 	 * taken form the backref is much larger then the offset of the file
6007ac8b88eSethanwu 	 * extent item. This can make us scan a very large number of file
6017ac8b88eSethanwu 	 * extent items, but at least it will not make us miss any.
6027ac8b88eSethanwu 	 *
6037ac8b88eSethanwu 	 * This is an ugly workaround for a behaviour that should have never
6047ac8b88eSethanwu 	 * existed, but it does and a fix for the clone ioctl would touch a lot
6057ac8b88eSethanwu 	 * of places, cause backwards incompatibility and would not fix the
6067ac8b88eSethanwu 	 * problem for extents cloned with older kernels.
6077ac8b88eSethanwu 	 */
6087ac8b88eSethanwu 	if (search_key.type == BTRFS_EXTENT_DATA_KEY &&
6097ac8b88eSethanwu 	    search_key.offset >= LLONG_MAX)
6107ac8b88eSethanwu 		search_key.offset = 0;
6118da6d581SJan Schmidt 	path->lowest_level = level;
612f3a84ccdSFilipe Manana 	if (time_seq == BTRFS_SEQ_LAST)
6137ac8b88eSethanwu 		ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
61421633fc6SQu Wenruo 	else
6157ac8b88eSethanwu 		ret = btrfs_search_old_slot(root, &search_key, path, time_seq);
616538f72cdSWang Shilong 
617ab8d0fc4SJeff Mahoney 	btrfs_debug(fs_info,
618ab8d0fc4SJeff Mahoney 		"search slot in root %llu (level %d, ref count %d) returned %d for key (%llu %u %llu)",
619c1c9ff7cSGeert Uytterhoeven 		 ref->root_id, level, ref->count, ret,
620c1c9ff7cSGeert Uytterhoeven 		 ref->key_for_search.objectid, ref->key_for_search.type,
621c1c9ff7cSGeert Uytterhoeven 		 ref->key_for_search.offset);
6228da6d581SJan Schmidt 	if (ret < 0)
6238da6d581SJan Schmidt 		goto out;
6248da6d581SJan Schmidt 
6258da6d581SJan Schmidt 	eb = path->nodes[level];
6269345457fSJan Schmidt 	while (!eb) {
627fae7f21cSDulshani Gunawardhana 		if (WARN_ON(!level)) {
6288da6d581SJan Schmidt 			ret = 1;
6298da6d581SJan Schmidt 			goto out;
6308da6d581SJan Schmidt 		}
6319345457fSJan Schmidt 		level--;
6329345457fSJan Schmidt 		eb = path->nodes[level];
6339345457fSJan Schmidt 	}
6348da6d581SJan Schmidt 
635ed58f2e6Sethanwu 	ret = add_all_parents(root, path, parents, preftrees, ref, level,
636b25b0b87Sethanwu 			      time_seq, extent_item_pos, ignore_offset);
6378da6d581SJan Schmidt out:
63800246528SJosef Bacik 	btrfs_put_root(root);
6399326f76fSJosef Bacik out_free:
640da61d31aSJosef Bacik 	path->lowest_level = 0;
641da61d31aSJosef Bacik 	btrfs_release_path(path);
6428da6d581SJan Schmidt 	return ret;
6438da6d581SJan Schmidt }
6448da6d581SJan Schmidt 
6454dae077aSJeff Mahoney static struct extent_inode_elem *
6464dae077aSJeff Mahoney unode_aux_to_inode_list(struct ulist_node *node)
6474dae077aSJeff Mahoney {
6484dae077aSJeff Mahoney 	if (!node)
6494dae077aSJeff Mahoney 		return NULL;
6504dae077aSJeff Mahoney 	return (struct extent_inode_elem *)(uintptr_t)node->aux;
6514dae077aSJeff Mahoney }
6524dae077aSJeff Mahoney 
6535614dc3aSFilipe Manana static void free_leaf_list(struct ulist *ulist)
6545614dc3aSFilipe Manana {
6555614dc3aSFilipe Manana 	struct ulist_node *node;
6565614dc3aSFilipe Manana 	struct ulist_iterator uiter;
6575614dc3aSFilipe Manana 
6585614dc3aSFilipe Manana 	ULIST_ITER_INIT(&uiter);
6595614dc3aSFilipe Manana 	while ((node = ulist_next(ulist, &uiter)))
6605614dc3aSFilipe Manana 		free_inode_elem_list(unode_aux_to_inode_list(node));
6615614dc3aSFilipe Manana 
6625614dc3aSFilipe Manana 	ulist_free(ulist);
6635614dc3aSFilipe Manana }
6645614dc3aSFilipe Manana 
6658da6d581SJan Schmidt /*
66652042d8eSAndrea Gelmini  * We maintain three separate rbtrees: one for direct refs, one for
66786d5f994SEdmund Nadolski  * indirect refs which have a key, and one for indirect refs which do not
66886d5f994SEdmund Nadolski  * have a key. Each tree does merge on insertion.
66986d5f994SEdmund Nadolski  *
67086d5f994SEdmund Nadolski  * Once all of the references are located, we iterate over the tree of
67186d5f994SEdmund Nadolski  * indirect refs with missing keys. An appropriate key is located and
67286d5f994SEdmund Nadolski  * the ref is moved onto the tree for indirect refs. After all missing
67386d5f994SEdmund Nadolski  * keys are thus located, we iterate over the indirect ref tree, resolve
67486d5f994SEdmund Nadolski  * each reference, and then insert the resolved reference onto the
67586d5f994SEdmund Nadolski  * direct tree (merging there too).
67686d5f994SEdmund Nadolski  *
67786d5f994SEdmund Nadolski  * New backrefs (i.e., for parent nodes) are added to the appropriate
67886d5f994SEdmund Nadolski  * rbtree as they are encountered. The new backrefs are subsequently
67986d5f994SEdmund Nadolski  * resolved as above.
6808da6d581SJan Schmidt  */
681e0c476b1SJeff Mahoney static int resolve_indirect_refs(struct btrfs_fs_info *fs_info,
682da61d31aSJosef Bacik 				 struct btrfs_path *path, u64 time_seq,
68386d5f994SEdmund Nadolski 				 struct preftrees *preftrees,
684b25b0b87Sethanwu 				 const u64 *extent_item_pos,
685c995ab3cSZygo Blaxell 				 struct share_check *sc, bool ignore_offset)
6868da6d581SJan Schmidt {
6878da6d581SJan Schmidt 	int err;
6888da6d581SJan Schmidt 	int ret = 0;
6898da6d581SJan Schmidt 	struct ulist *parents;
6908da6d581SJan Schmidt 	struct ulist_node *node;
691cd1b413cSJan Schmidt 	struct ulist_iterator uiter;
69286d5f994SEdmund Nadolski 	struct rb_node *rnode;
6938da6d581SJan Schmidt 
6948da6d581SJan Schmidt 	parents = ulist_alloc(GFP_NOFS);
6958da6d581SJan Schmidt 	if (!parents)
6968da6d581SJan Schmidt 		return -ENOMEM;
6978da6d581SJan Schmidt 
6988da6d581SJan Schmidt 	/*
69986d5f994SEdmund Nadolski 	 * We could trade memory usage for performance here by iterating
70086d5f994SEdmund Nadolski 	 * the tree, allocating new refs for each insertion, and then
70186d5f994SEdmund Nadolski 	 * freeing the entire indirect tree when we're done.  In some test
70286d5f994SEdmund Nadolski 	 * cases, the tree can grow quite large (~200k objects).
7038da6d581SJan Schmidt 	 */
704ecf160b4SLiu Bo 	while ((rnode = rb_first_cached(&preftrees->indirect.root))) {
70586d5f994SEdmund Nadolski 		struct prelim_ref *ref;
70686d5f994SEdmund Nadolski 
70786d5f994SEdmund Nadolski 		ref = rb_entry(rnode, struct prelim_ref, rbnode);
70886d5f994SEdmund Nadolski 		if (WARN(ref->parent,
70986d5f994SEdmund Nadolski 			 "BUG: direct ref found in indirect tree")) {
71086d5f994SEdmund Nadolski 			ret = -EINVAL;
71186d5f994SEdmund Nadolski 			goto out;
71286d5f994SEdmund Nadolski 		}
71386d5f994SEdmund Nadolski 
714ecf160b4SLiu Bo 		rb_erase_cached(&ref->rbnode, &preftrees->indirect.root);
7156c336b21SJeff Mahoney 		preftrees->indirect.count--;
71686d5f994SEdmund Nadolski 
71786d5f994SEdmund Nadolski 		if (ref->count == 0) {
71886d5f994SEdmund Nadolski 			free_pref(ref);
7198da6d581SJan Schmidt 			continue;
72086d5f994SEdmund Nadolski 		}
72186d5f994SEdmund Nadolski 
722c9024219SFilipe Manana 		if (sc && ref->root_id != sc->root_objectid) {
72386d5f994SEdmund Nadolski 			free_pref(ref);
724dc046b10SJosef Bacik 			ret = BACKREF_FOUND_SHARED;
725dc046b10SJosef Bacik 			goto out;
726dc046b10SJosef Bacik 		}
727ed58f2e6Sethanwu 		err = resolve_indirect_ref(fs_info, path, time_seq, preftrees,
728ed58f2e6Sethanwu 					   ref, parents, extent_item_pos,
729b25b0b87Sethanwu 					   ignore_offset);
73095def2edSWang Shilong 		/*
73195def2edSWang Shilong 		 * we can only tolerate ENOENT,otherwise,we should catch error
73295def2edSWang Shilong 		 * and return directly.
73395def2edSWang Shilong 		 */
73495def2edSWang Shilong 		if (err == -ENOENT) {
7353ec4d323SEdmund Nadolski 			prelim_ref_insert(fs_info, &preftrees->direct, ref,
7363ec4d323SEdmund Nadolski 					  NULL);
7378da6d581SJan Schmidt 			continue;
73895def2edSWang Shilong 		} else if (err) {
73986d5f994SEdmund Nadolski 			free_pref(ref);
74095def2edSWang Shilong 			ret = err;
74195def2edSWang Shilong 			goto out;
74295def2edSWang Shilong 		}
7438da6d581SJan Schmidt 
7448da6d581SJan Schmidt 		/* we put the first parent into the ref at hand */
745cd1b413cSJan Schmidt 		ULIST_ITER_INIT(&uiter);
746cd1b413cSJan Schmidt 		node = ulist_next(parents, &uiter);
7478da6d581SJan Schmidt 		ref->parent = node ? node->val : 0;
7484dae077aSJeff Mahoney 		ref->inode_list = unode_aux_to_inode_list(node);
7498da6d581SJan Schmidt 
75086d5f994SEdmund Nadolski 		/* Add a prelim_ref(s) for any other parent(s). */
751cd1b413cSJan Schmidt 		while ((node = ulist_next(parents, &uiter))) {
75286d5f994SEdmund Nadolski 			struct prelim_ref *new_ref;
75386d5f994SEdmund Nadolski 
754b9e9a6cbSWang Shilong 			new_ref = kmem_cache_alloc(btrfs_prelim_ref_cache,
755b9e9a6cbSWang Shilong 						   GFP_NOFS);
7568da6d581SJan Schmidt 			if (!new_ref) {
75786d5f994SEdmund Nadolski 				free_pref(ref);
7588da6d581SJan Schmidt 				ret = -ENOMEM;
759e36902d4SWang Shilong 				goto out;
7608da6d581SJan Schmidt 			}
7618da6d581SJan Schmidt 			memcpy(new_ref, ref, sizeof(*ref));
7628da6d581SJan Schmidt 			new_ref->parent = node->val;
7634dae077aSJeff Mahoney 			new_ref->inode_list = unode_aux_to_inode_list(node);
7643ec4d323SEdmund Nadolski 			prelim_ref_insert(fs_info, &preftrees->direct,
7653ec4d323SEdmund Nadolski 					  new_ref, NULL);
7668da6d581SJan Schmidt 		}
76786d5f994SEdmund Nadolski 
7683ec4d323SEdmund Nadolski 		/*
76952042d8eSAndrea Gelmini 		 * Now it's a direct ref, put it in the direct tree. We must
7703ec4d323SEdmund Nadolski 		 * do this last because the ref could be merged/freed here.
7713ec4d323SEdmund Nadolski 		 */
7723ec4d323SEdmund Nadolski 		prelim_ref_insert(fs_info, &preftrees->direct, ref, NULL);
77386d5f994SEdmund Nadolski 
7748da6d581SJan Schmidt 		ulist_reinit(parents);
7759dd14fd6SEdmund Nadolski 		cond_resched();
7768da6d581SJan Schmidt 	}
777e36902d4SWang Shilong out:
7785614dc3aSFilipe Manana 	/*
7795614dc3aSFilipe Manana 	 * We may have inode lists attached to refs in the parents ulist, so we
7805614dc3aSFilipe Manana 	 * must free them before freeing the ulist and its refs.
7815614dc3aSFilipe Manana 	 */
7825614dc3aSFilipe Manana 	free_leaf_list(parents);
7838da6d581SJan Schmidt 	return ret;
7848da6d581SJan Schmidt }
7858da6d581SJan Schmidt 
786d5c88b73SJan Schmidt /*
787d5c88b73SJan Schmidt  * read tree blocks and add keys where required.
788d5c88b73SJan Schmidt  */
789e0c476b1SJeff Mahoney static int add_missing_keys(struct btrfs_fs_info *fs_info,
79038e3eebfSJosef Bacik 			    struct preftrees *preftrees, bool lock)
791d5c88b73SJan Schmidt {
792e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
793d5c88b73SJan Schmidt 	struct extent_buffer *eb;
79486d5f994SEdmund Nadolski 	struct preftree *tree = &preftrees->indirect_missing_keys;
79586d5f994SEdmund Nadolski 	struct rb_node *node;
796d5c88b73SJan Schmidt 
797ecf160b4SLiu Bo 	while ((node = rb_first_cached(&tree->root))) {
79886d5f994SEdmund Nadolski 		ref = rb_entry(node, struct prelim_ref, rbnode);
799ecf160b4SLiu Bo 		rb_erase_cached(node, &tree->root);
80086d5f994SEdmund Nadolski 
80186d5f994SEdmund Nadolski 		BUG_ON(ref->parent);	/* should not be a direct ref */
80286d5f994SEdmund Nadolski 		BUG_ON(ref->key_for_search.type);
803d5c88b73SJan Schmidt 		BUG_ON(!ref->wanted_disk_byte);
80486d5f994SEdmund Nadolski 
8051b7ec85eSJosef Bacik 		eb = read_tree_block(fs_info, ref->wanted_disk_byte,
8061b7ec85eSJosef Bacik 				     ref->root_id, 0, ref->level - 1, NULL);
80764c043deSLiu Bo 		if (IS_ERR(eb)) {
80886d5f994SEdmund Nadolski 			free_pref(ref);
80964c043deSLiu Bo 			return PTR_ERR(eb);
8104eb150d6SQu Wenruo 		}
8114eb150d6SQu Wenruo 		if (!extent_buffer_uptodate(eb)) {
81286d5f994SEdmund Nadolski 			free_pref(ref);
813416bc658SJosef Bacik 			free_extent_buffer(eb);
814416bc658SJosef Bacik 			return -EIO;
815416bc658SJosef Bacik 		}
8164eb150d6SQu Wenruo 
81738e3eebfSJosef Bacik 		if (lock)
818d5c88b73SJan Schmidt 			btrfs_tree_read_lock(eb);
819d5c88b73SJan Schmidt 		if (btrfs_header_level(eb) == 0)
820d5c88b73SJan Schmidt 			btrfs_item_key_to_cpu(eb, &ref->key_for_search, 0);
821d5c88b73SJan Schmidt 		else
822d5c88b73SJan Schmidt 			btrfs_node_key_to_cpu(eb, &ref->key_for_search, 0);
82338e3eebfSJosef Bacik 		if (lock)
824d5c88b73SJan Schmidt 			btrfs_tree_read_unlock(eb);
825d5c88b73SJan Schmidt 		free_extent_buffer(eb);
8263ec4d323SEdmund Nadolski 		prelim_ref_insert(fs_info, &preftrees->indirect, ref, NULL);
8279dd14fd6SEdmund Nadolski 		cond_resched();
828d5c88b73SJan Schmidt 	}
829d5c88b73SJan Schmidt 	return 0;
830d5c88b73SJan Schmidt }
831d5c88b73SJan Schmidt 
8328da6d581SJan Schmidt /*
8338da6d581SJan Schmidt  * add all currently queued delayed refs from this head whose seq nr is
8348da6d581SJan Schmidt  * smaller or equal that seq to the list
8358da6d581SJan Schmidt  */
83600142756SJeff Mahoney static int add_delayed_refs(const struct btrfs_fs_info *fs_info,
83700142756SJeff Mahoney 			    struct btrfs_delayed_ref_head *head, u64 seq,
838b25b0b87Sethanwu 			    struct preftrees *preftrees, struct share_check *sc)
8398da6d581SJan Schmidt {
840c6fc2454SQu Wenruo 	struct btrfs_delayed_ref_node *node;
841d5c88b73SJan Schmidt 	struct btrfs_key key;
8420e0adbcfSJosef Bacik 	struct rb_node *n;
84301747e92SEdmund Nadolski 	int count;
844b1375d64SJan Schmidt 	int ret = 0;
8458da6d581SJan Schmidt 
846d7df2c79SJosef Bacik 	spin_lock(&head->lock);
847e3d03965SLiu Bo 	for (n = rb_first_cached(&head->ref_tree); n; n = rb_next(n)) {
8480e0adbcfSJosef Bacik 		node = rb_entry(n, struct btrfs_delayed_ref_node,
8490e0adbcfSJosef Bacik 				ref_node);
8508da6d581SJan Schmidt 		if (node->seq > seq)
8518da6d581SJan Schmidt 			continue;
8528da6d581SJan Schmidt 
8538da6d581SJan Schmidt 		switch (node->action) {
8548da6d581SJan Schmidt 		case BTRFS_ADD_DELAYED_EXTENT:
8558da6d581SJan Schmidt 		case BTRFS_UPDATE_DELAYED_HEAD:
8568da6d581SJan Schmidt 			WARN_ON(1);
8578da6d581SJan Schmidt 			continue;
8588da6d581SJan Schmidt 		case BTRFS_ADD_DELAYED_REF:
85901747e92SEdmund Nadolski 			count = node->ref_mod;
8608da6d581SJan Schmidt 			break;
8618da6d581SJan Schmidt 		case BTRFS_DROP_DELAYED_REF:
86201747e92SEdmund Nadolski 			count = node->ref_mod * -1;
8638da6d581SJan Schmidt 			break;
8648da6d581SJan Schmidt 		default:
865290342f6SArnd Bergmann 			BUG();
8668da6d581SJan Schmidt 		}
8678da6d581SJan Schmidt 		switch (node->type) {
8688da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY: {
86986d5f994SEdmund Nadolski 			/* NORMAL INDIRECT METADATA backref */
8708da6d581SJan Schmidt 			struct btrfs_delayed_tree_ref *ref;
871943553efSFilipe Manana 			struct btrfs_key *key_ptr = NULL;
872943553efSFilipe Manana 
873943553efSFilipe Manana 			if (head->extent_op && head->extent_op->update_key) {
874943553efSFilipe Manana 				btrfs_disk_key_to_cpu(&key, &head->extent_op->key);
875943553efSFilipe Manana 				key_ptr = &key;
876943553efSFilipe Manana 			}
8778da6d581SJan Schmidt 
8788da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_tree_ref(node);
87900142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, ref->root,
880943553efSFilipe Manana 					       key_ptr, ref->level + 1,
88101747e92SEdmund Nadolski 					       node->bytenr, count, sc,
88201747e92SEdmund Nadolski 					       GFP_ATOMIC);
8838da6d581SJan Schmidt 			break;
8848da6d581SJan Schmidt 		}
8858da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY: {
88686d5f994SEdmund Nadolski 			/* SHARED DIRECT METADATA backref */
8878da6d581SJan Schmidt 			struct btrfs_delayed_tree_ref *ref;
8888da6d581SJan Schmidt 
8898da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_tree_ref(node);
89086d5f994SEdmund Nadolski 
89101747e92SEdmund Nadolski 			ret = add_direct_ref(fs_info, preftrees, ref->level + 1,
89201747e92SEdmund Nadolski 					     ref->parent, node->bytenr, count,
8933ec4d323SEdmund Nadolski 					     sc, GFP_ATOMIC);
8948da6d581SJan Schmidt 			break;
8958da6d581SJan Schmidt 		}
8968da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
89786d5f994SEdmund Nadolski 			/* NORMAL INDIRECT DATA backref */
8988da6d581SJan Schmidt 			struct btrfs_delayed_data_ref *ref;
8998da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_data_ref(node);
9008da6d581SJan Schmidt 
9018da6d581SJan Schmidt 			key.objectid = ref->objectid;
9028da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
9038da6d581SJan Schmidt 			key.offset = ref->offset;
904dc046b10SJosef Bacik 
905dc046b10SJosef Bacik 			/*
9064fc7b572SFilipe Manana 			 * If we have a share check context and a reference for
9074fc7b572SFilipe Manana 			 * another inode, we can't exit immediately. This is
9084fc7b572SFilipe Manana 			 * because even if this is a BTRFS_ADD_DELAYED_REF
9094fc7b572SFilipe Manana 			 * reference we may find next a BTRFS_DROP_DELAYED_REF
9104fc7b572SFilipe Manana 			 * which cancels out this ADD reference.
9114fc7b572SFilipe Manana 			 *
9124fc7b572SFilipe Manana 			 * If this is a DROP reference and there was no previous
9134fc7b572SFilipe Manana 			 * ADD reference, then we need to signal that when we
9144fc7b572SFilipe Manana 			 * process references from the extent tree (through
9154fc7b572SFilipe Manana 			 * add_inline_refs() and add_keyed_refs()), we should
9164fc7b572SFilipe Manana 			 * not exit early if we find a reference for another
9174fc7b572SFilipe Manana 			 * inode, because one of the delayed DROP references
9184fc7b572SFilipe Manana 			 * may cancel that reference in the extent tree.
919dc046b10SJosef Bacik 			 */
9204fc7b572SFilipe Manana 			if (sc && count < 0)
9214fc7b572SFilipe Manana 				sc->have_delayed_delete_refs = true;
922dc046b10SJosef Bacik 
92300142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, ref->root,
92401747e92SEdmund Nadolski 					       &key, 0, node->bytenr, count, sc,
92501747e92SEdmund Nadolski 					       GFP_ATOMIC);
9268da6d581SJan Schmidt 			break;
9278da6d581SJan Schmidt 		}
9288da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
92986d5f994SEdmund Nadolski 			/* SHARED DIRECT FULL backref */
9308da6d581SJan Schmidt 			struct btrfs_delayed_data_ref *ref;
9318da6d581SJan Schmidt 
9328da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_data_ref(node);
93386d5f994SEdmund Nadolski 
93401747e92SEdmund Nadolski 			ret = add_direct_ref(fs_info, preftrees, 0, ref->parent,
93501747e92SEdmund Nadolski 					     node->bytenr, count, sc,
93601747e92SEdmund Nadolski 					     GFP_ATOMIC);
9378da6d581SJan Schmidt 			break;
9388da6d581SJan Schmidt 		}
9398da6d581SJan Schmidt 		default:
9408da6d581SJan Schmidt 			WARN_ON(1);
9418da6d581SJan Schmidt 		}
9423ec4d323SEdmund Nadolski 		/*
9433ec4d323SEdmund Nadolski 		 * We must ignore BACKREF_FOUND_SHARED until all delayed
9443ec4d323SEdmund Nadolski 		 * refs have been checked.
9453ec4d323SEdmund Nadolski 		 */
9463ec4d323SEdmund Nadolski 		if (ret && (ret != BACKREF_FOUND_SHARED))
947d7df2c79SJosef Bacik 			break;
9488da6d581SJan Schmidt 	}
9493ec4d323SEdmund Nadolski 	if (!ret)
9503ec4d323SEdmund Nadolski 		ret = extent_is_shared(sc);
9514fc7b572SFilipe Manana 
952d7df2c79SJosef Bacik 	spin_unlock(&head->lock);
953d7df2c79SJosef Bacik 	return ret;
9548da6d581SJan Schmidt }
9558da6d581SJan Schmidt 
9568da6d581SJan Schmidt /*
9578da6d581SJan Schmidt  * add all inline backrefs for bytenr to the list
9583ec4d323SEdmund Nadolski  *
9593ec4d323SEdmund Nadolski  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
9608da6d581SJan Schmidt  */
96100142756SJeff Mahoney static int add_inline_refs(const struct btrfs_fs_info *fs_info,
96200142756SJeff Mahoney 			   struct btrfs_path *path, u64 bytenr,
96386d5f994SEdmund Nadolski 			   int *info_level, struct preftrees *preftrees,
964b25b0b87Sethanwu 			   struct share_check *sc)
9658da6d581SJan Schmidt {
966b1375d64SJan Schmidt 	int ret = 0;
9678da6d581SJan Schmidt 	int slot;
9688da6d581SJan Schmidt 	struct extent_buffer *leaf;
9698da6d581SJan Schmidt 	struct btrfs_key key;
970261c84b6SJosef Bacik 	struct btrfs_key found_key;
9718da6d581SJan Schmidt 	unsigned long ptr;
9728da6d581SJan Schmidt 	unsigned long end;
9738da6d581SJan Schmidt 	struct btrfs_extent_item *ei;
9748da6d581SJan Schmidt 	u64 flags;
9758da6d581SJan Schmidt 	u64 item_size;
9768da6d581SJan Schmidt 
9778da6d581SJan Schmidt 	/*
9788da6d581SJan Schmidt 	 * enumerate all inline refs
9798da6d581SJan Schmidt 	 */
9808da6d581SJan Schmidt 	leaf = path->nodes[0];
981dadcaf78SJan Schmidt 	slot = path->slots[0];
9828da6d581SJan Schmidt 
9833212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, slot);
9848da6d581SJan Schmidt 	BUG_ON(item_size < sizeof(*ei));
9858da6d581SJan Schmidt 
9868da6d581SJan Schmidt 	ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
9878da6d581SJan Schmidt 	flags = btrfs_extent_flags(leaf, ei);
988261c84b6SJosef Bacik 	btrfs_item_key_to_cpu(leaf, &found_key, slot);
9898da6d581SJan Schmidt 
9908da6d581SJan Schmidt 	ptr = (unsigned long)(ei + 1);
9918da6d581SJan Schmidt 	end = (unsigned long)ei + item_size;
9928da6d581SJan Schmidt 
993261c84b6SJosef Bacik 	if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
994261c84b6SJosef Bacik 	    flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
9958da6d581SJan Schmidt 		struct btrfs_tree_block_info *info;
9968da6d581SJan Schmidt 
9978da6d581SJan Schmidt 		info = (struct btrfs_tree_block_info *)ptr;
9988da6d581SJan Schmidt 		*info_level = btrfs_tree_block_level(leaf, info);
9998da6d581SJan Schmidt 		ptr += sizeof(struct btrfs_tree_block_info);
10008da6d581SJan Schmidt 		BUG_ON(ptr > end);
1001261c84b6SJosef Bacik 	} else if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
1002261c84b6SJosef Bacik 		*info_level = found_key.offset;
10038da6d581SJan Schmidt 	} else {
10048da6d581SJan Schmidt 		BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
10058da6d581SJan Schmidt 	}
10068da6d581SJan Schmidt 
10078da6d581SJan Schmidt 	while (ptr < end) {
10088da6d581SJan Schmidt 		struct btrfs_extent_inline_ref *iref;
10098da6d581SJan Schmidt 		u64 offset;
10108da6d581SJan Schmidt 		int type;
10118da6d581SJan Schmidt 
10128da6d581SJan Schmidt 		iref = (struct btrfs_extent_inline_ref *)ptr;
10133de28d57SLiu Bo 		type = btrfs_get_extent_inline_ref_type(leaf, iref,
10143de28d57SLiu Bo 							BTRFS_REF_TYPE_ANY);
10153de28d57SLiu Bo 		if (type == BTRFS_REF_TYPE_INVALID)
1016af431dcbSSu Yue 			return -EUCLEAN;
10173de28d57SLiu Bo 
10188da6d581SJan Schmidt 		offset = btrfs_extent_inline_ref_offset(leaf, iref);
10198da6d581SJan Schmidt 
10208da6d581SJan Schmidt 		switch (type) {
10218da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY:
102200142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees,
102300142756SJeff Mahoney 					     *info_level + 1, offset,
10243ec4d323SEdmund Nadolski 					     bytenr, 1, NULL, GFP_NOFS);
10258da6d581SJan Schmidt 			break;
10268da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
10278da6d581SJan Schmidt 			struct btrfs_shared_data_ref *sdref;
10288da6d581SJan Schmidt 			int count;
10298da6d581SJan Schmidt 
10308da6d581SJan Schmidt 			sdref = (struct btrfs_shared_data_ref *)(iref + 1);
10318da6d581SJan Schmidt 			count = btrfs_shared_data_ref_count(leaf, sdref);
103286d5f994SEdmund Nadolski 
103300142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees, 0, offset,
10343ec4d323SEdmund Nadolski 					     bytenr, count, sc, GFP_NOFS);
10358da6d581SJan Schmidt 			break;
10368da6d581SJan Schmidt 		}
10378da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY:
103800142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, offset,
103900142756SJeff Mahoney 					       NULL, *info_level + 1,
10403ec4d323SEdmund Nadolski 					       bytenr, 1, NULL, GFP_NOFS);
10418da6d581SJan Schmidt 			break;
10428da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
10438da6d581SJan Schmidt 			struct btrfs_extent_data_ref *dref;
10448da6d581SJan Schmidt 			int count;
10458da6d581SJan Schmidt 			u64 root;
10468da6d581SJan Schmidt 
10478da6d581SJan Schmidt 			dref = (struct btrfs_extent_data_ref *)(&iref->offset);
10488da6d581SJan Schmidt 			count = btrfs_extent_data_ref_count(leaf, dref);
10498da6d581SJan Schmidt 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
10508da6d581SJan Schmidt 								      dref);
10518da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
10528da6d581SJan Schmidt 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1053dc046b10SJosef Bacik 
1054a0a5472aSFilipe Manana 			if (sc && key.objectid != sc->inum &&
10554fc7b572SFilipe Manana 			    !sc->have_delayed_delete_refs) {
1056dc046b10SJosef Bacik 				ret = BACKREF_FOUND_SHARED;
1057dc046b10SJosef Bacik 				break;
1058dc046b10SJosef Bacik 			}
1059dc046b10SJosef Bacik 
10608da6d581SJan Schmidt 			root = btrfs_extent_data_ref_root(leaf, dref);
106186d5f994SEdmund Nadolski 
106200142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, root,
106300142756SJeff Mahoney 					       &key, 0, bytenr, count,
10643ec4d323SEdmund Nadolski 					       sc, GFP_NOFS);
10654fc7b572SFilipe Manana 
10668da6d581SJan Schmidt 			break;
10678da6d581SJan Schmidt 		}
10688da6d581SJan Schmidt 		default:
10698da6d581SJan Schmidt 			WARN_ON(1);
10708da6d581SJan Schmidt 		}
10711149ab6bSWang Shilong 		if (ret)
10721149ab6bSWang Shilong 			return ret;
10738da6d581SJan Schmidt 		ptr += btrfs_extent_inline_ref_size(type);
10748da6d581SJan Schmidt 	}
10758da6d581SJan Schmidt 
10768da6d581SJan Schmidt 	return 0;
10778da6d581SJan Schmidt }
10788da6d581SJan Schmidt 
10798da6d581SJan Schmidt /*
10808da6d581SJan Schmidt  * add all non-inline backrefs for bytenr to the list
10813ec4d323SEdmund Nadolski  *
10823ec4d323SEdmund Nadolski  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
10838da6d581SJan Schmidt  */
108498cc4222SJosef Bacik static int add_keyed_refs(struct btrfs_root *extent_root,
10858da6d581SJan Schmidt 			  struct btrfs_path *path, u64 bytenr,
108686d5f994SEdmund Nadolski 			  int info_level, struct preftrees *preftrees,
10873ec4d323SEdmund Nadolski 			  struct share_check *sc)
10888da6d581SJan Schmidt {
108998cc4222SJosef Bacik 	struct btrfs_fs_info *fs_info = extent_root->fs_info;
10908da6d581SJan Schmidt 	int ret;
10918da6d581SJan Schmidt 	int slot;
10928da6d581SJan Schmidt 	struct extent_buffer *leaf;
10938da6d581SJan Schmidt 	struct btrfs_key key;
10948da6d581SJan Schmidt 
10958da6d581SJan Schmidt 	while (1) {
10968da6d581SJan Schmidt 		ret = btrfs_next_item(extent_root, path);
10978da6d581SJan Schmidt 		if (ret < 0)
10988da6d581SJan Schmidt 			break;
10998da6d581SJan Schmidt 		if (ret) {
11008da6d581SJan Schmidt 			ret = 0;
11018da6d581SJan Schmidt 			break;
11028da6d581SJan Schmidt 		}
11038da6d581SJan Schmidt 
11048da6d581SJan Schmidt 		slot = path->slots[0];
11058da6d581SJan Schmidt 		leaf = path->nodes[0];
11068da6d581SJan Schmidt 		btrfs_item_key_to_cpu(leaf, &key, slot);
11078da6d581SJan Schmidt 
11088da6d581SJan Schmidt 		if (key.objectid != bytenr)
11098da6d581SJan Schmidt 			break;
11108da6d581SJan Schmidt 		if (key.type < BTRFS_TREE_BLOCK_REF_KEY)
11118da6d581SJan Schmidt 			continue;
11128da6d581SJan Schmidt 		if (key.type > BTRFS_SHARED_DATA_REF_KEY)
11138da6d581SJan Schmidt 			break;
11148da6d581SJan Schmidt 
11158da6d581SJan Schmidt 		switch (key.type) {
11168da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY:
111786d5f994SEdmund Nadolski 			/* SHARED DIRECT METADATA backref */
111800142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees,
111900142756SJeff Mahoney 					     info_level + 1, key.offset,
11203ec4d323SEdmund Nadolski 					     bytenr, 1, NULL, GFP_NOFS);
11218da6d581SJan Schmidt 			break;
11228da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
112386d5f994SEdmund Nadolski 			/* SHARED DIRECT FULL backref */
11248da6d581SJan Schmidt 			struct btrfs_shared_data_ref *sdref;
11258da6d581SJan Schmidt 			int count;
11268da6d581SJan Schmidt 
11278da6d581SJan Schmidt 			sdref = btrfs_item_ptr(leaf, slot,
11288da6d581SJan Schmidt 					      struct btrfs_shared_data_ref);
11298da6d581SJan Schmidt 			count = btrfs_shared_data_ref_count(leaf, sdref);
113000142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees, 0,
113100142756SJeff Mahoney 					     key.offset, bytenr, count,
11323ec4d323SEdmund Nadolski 					     sc, GFP_NOFS);
11338da6d581SJan Schmidt 			break;
11348da6d581SJan Schmidt 		}
11358da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY:
113686d5f994SEdmund Nadolski 			/* NORMAL INDIRECT METADATA backref */
113700142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, key.offset,
113800142756SJeff Mahoney 					       NULL, info_level + 1, bytenr,
11393ec4d323SEdmund Nadolski 					       1, NULL, GFP_NOFS);
11408da6d581SJan Schmidt 			break;
11418da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
114286d5f994SEdmund Nadolski 			/* NORMAL INDIRECT DATA backref */
11438da6d581SJan Schmidt 			struct btrfs_extent_data_ref *dref;
11448da6d581SJan Schmidt 			int count;
11458da6d581SJan Schmidt 			u64 root;
11468da6d581SJan Schmidt 
11478da6d581SJan Schmidt 			dref = btrfs_item_ptr(leaf, slot,
11488da6d581SJan Schmidt 					      struct btrfs_extent_data_ref);
11498da6d581SJan Schmidt 			count = btrfs_extent_data_ref_count(leaf, dref);
11508da6d581SJan Schmidt 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
11518da6d581SJan Schmidt 								      dref);
11528da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
11538da6d581SJan Schmidt 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1154dc046b10SJosef Bacik 
1155a0a5472aSFilipe Manana 			if (sc && key.objectid != sc->inum &&
11564fc7b572SFilipe Manana 			    !sc->have_delayed_delete_refs) {
1157dc046b10SJosef Bacik 				ret = BACKREF_FOUND_SHARED;
1158dc046b10SJosef Bacik 				break;
1159dc046b10SJosef Bacik 			}
1160dc046b10SJosef Bacik 
11618da6d581SJan Schmidt 			root = btrfs_extent_data_ref_root(leaf, dref);
116200142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, root,
116300142756SJeff Mahoney 					       &key, 0, bytenr, count,
11643ec4d323SEdmund Nadolski 					       sc, GFP_NOFS);
11658da6d581SJan Schmidt 			break;
11668da6d581SJan Schmidt 		}
11678da6d581SJan Schmidt 		default:
11688da6d581SJan Schmidt 			WARN_ON(1);
11698da6d581SJan Schmidt 		}
11701149ab6bSWang Shilong 		if (ret)
11711149ab6bSWang Shilong 			return ret;
11721149ab6bSWang Shilong 
11738da6d581SJan Schmidt 	}
11748da6d581SJan Schmidt 
11758da6d581SJan Schmidt 	return ret;
11768da6d581SJan Schmidt }
11778da6d581SJan Schmidt 
11788da6d581SJan Schmidt /*
11798da6d581SJan Schmidt  * this adds all existing backrefs (inline backrefs, backrefs and delayed
11808da6d581SJan Schmidt  * refs) for the given bytenr to the refs list, merges duplicates and resolves
11818da6d581SJan Schmidt  * indirect refs to their parent bytenr.
11828da6d581SJan Schmidt  * When roots are found, they're added to the roots list
11838da6d581SJan Schmidt  *
1184f3a84ccdSFilipe Manana  * If time_seq is set to BTRFS_SEQ_LAST, it will not search delayed_refs, and
1185f3a84ccdSFilipe Manana  * behave much like trans == NULL case, the difference only lies in it will not
118621633fc6SQu Wenruo  * commit root.
118721633fc6SQu Wenruo  * The special case is for qgroup to search roots in commit_transaction().
118821633fc6SQu Wenruo  *
11893ec4d323SEdmund Nadolski  * @sc - if !NULL, then immediately return BACKREF_FOUND_SHARED when a
11903ec4d323SEdmund Nadolski  * shared extent is detected.
11913ec4d323SEdmund Nadolski  *
11923ec4d323SEdmund Nadolski  * Otherwise this returns 0 for success and <0 for an error.
11933ec4d323SEdmund Nadolski  *
1194c995ab3cSZygo Blaxell  * If ignore_offset is set to false, only extent refs whose offsets match
1195c995ab3cSZygo Blaxell  * extent_item_pos are returned.  If true, every extent ref is returned
1196c995ab3cSZygo Blaxell  * and extent_item_pos is ignored.
1197c995ab3cSZygo Blaxell  *
11988da6d581SJan Schmidt  * FIXME some caching might speed things up
11998da6d581SJan Schmidt  */
12008da6d581SJan Schmidt static int find_parent_nodes(struct btrfs_trans_handle *trans,
12018da6d581SJan Schmidt 			     struct btrfs_fs_info *fs_info, u64 bytenr,
1202097b8a7cSJan Schmidt 			     u64 time_seq, struct ulist *refs,
1203dc046b10SJosef Bacik 			     struct ulist *roots, const u64 *extent_item_pos,
1204c995ab3cSZygo Blaxell 			     struct share_check *sc, bool ignore_offset)
12058da6d581SJan Schmidt {
120629cbcf40SJosef Bacik 	struct btrfs_root *root = btrfs_extent_root(fs_info, bytenr);
12078da6d581SJan Schmidt 	struct btrfs_key key;
12088da6d581SJan Schmidt 	struct btrfs_path *path;
12098da6d581SJan Schmidt 	struct btrfs_delayed_ref_root *delayed_refs = NULL;
1210d3b01064SLi Zefan 	struct btrfs_delayed_ref_head *head;
12118da6d581SJan Schmidt 	int info_level = 0;
12128da6d581SJan Schmidt 	int ret;
1213e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
121486d5f994SEdmund Nadolski 	struct rb_node *node;
1215f05c4746SWang Shilong 	struct extent_inode_elem *eie = NULL;
121686d5f994SEdmund Nadolski 	struct preftrees preftrees = {
121786d5f994SEdmund Nadolski 		.direct = PREFTREE_INIT,
121886d5f994SEdmund Nadolski 		.indirect = PREFTREE_INIT,
121986d5f994SEdmund Nadolski 		.indirect_missing_keys = PREFTREE_INIT
122086d5f994SEdmund Nadolski 	};
12218da6d581SJan Schmidt 
1222*56f5c199SFilipe Manana 	/* Roots ulist is not needed when using a sharedness check context. */
1223*56f5c199SFilipe Manana 	if (sc)
1224*56f5c199SFilipe Manana 		ASSERT(roots == NULL);
1225*56f5c199SFilipe Manana 
12268da6d581SJan Schmidt 	key.objectid = bytenr;
12278da6d581SJan Schmidt 	key.offset = (u64)-1;
1228261c84b6SJosef Bacik 	if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1229261c84b6SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
1230261c84b6SJosef Bacik 	else
1231261c84b6SJosef Bacik 		key.type = BTRFS_EXTENT_ITEM_KEY;
12328da6d581SJan Schmidt 
12338da6d581SJan Schmidt 	path = btrfs_alloc_path();
12348da6d581SJan Schmidt 	if (!path)
12358da6d581SJan Schmidt 		return -ENOMEM;
1236e84752d4SWang Shilong 	if (!trans) {
1237da61d31aSJosef Bacik 		path->search_commit_root = 1;
1238e84752d4SWang Shilong 		path->skip_locking = 1;
1239e84752d4SWang Shilong 	}
12408da6d581SJan Schmidt 
1241f3a84ccdSFilipe Manana 	if (time_seq == BTRFS_SEQ_LAST)
124221633fc6SQu Wenruo 		path->skip_locking = 1;
124321633fc6SQu Wenruo 
12448da6d581SJan Schmidt again:
1245d3b01064SLi Zefan 	head = NULL;
1246d3b01064SLi Zefan 
124798cc4222SJosef Bacik 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
12488da6d581SJan Schmidt 	if (ret < 0)
12498da6d581SJan Schmidt 		goto out;
1250fcba0120SJosef Bacik 	if (ret == 0) {
1251fcba0120SJosef Bacik 		/* This shouldn't happen, indicates a bug or fs corruption. */
1252fcba0120SJosef Bacik 		ASSERT(ret != 0);
1253fcba0120SJosef Bacik 		ret = -EUCLEAN;
1254fcba0120SJosef Bacik 		goto out;
1255fcba0120SJosef Bacik 	}
12568da6d581SJan Schmidt 
125721633fc6SQu Wenruo 	if (trans && likely(trans->type != __TRANS_DUMMY) &&
1258f3a84ccdSFilipe Manana 	    time_seq != BTRFS_SEQ_LAST) {
12598da6d581SJan Schmidt 		/*
12609665ebd5SJosef Bacik 		 * We have a specific time_seq we care about and trans which
12619665ebd5SJosef Bacik 		 * means we have the path lock, we need to grab the ref head and
12629665ebd5SJosef Bacik 		 * lock it so we have a consistent view of the refs at the given
12639665ebd5SJosef Bacik 		 * time.
12648da6d581SJan Schmidt 		 */
12658da6d581SJan Schmidt 		delayed_refs = &trans->transaction->delayed_refs;
12668da6d581SJan Schmidt 		spin_lock(&delayed_refs->lock);
1267f72ad18eSLiu Bo 		head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
12688da6d581SJan Schmidt 		if (head) {
12698da6d581SJan Schmidt 			if (!mutex_trylock(&head->mutex)) {
1270d278850eSJosef Bacik 				refcount_inc(&head->refs);
12718da6d581SJan Schmidt 				spin_unlock(&delayed_refs->lock);
12728da6d581SJan Schmidt 
12738da6d581SJan Schmidt 				btrfs_release_path(path);
12748da6d581SJan Schmidt 
12758da6d581SJan Schmidt 				/*
12768da6d581SJan Schmidt 				 * Mutex was contended, block until it's
12778da6d581SJan Schmidt 				 * released and try again
12788da6d581SJan Schmidt 				 */
12798da6d581SJan Schmidt 				mutex_lock(&head->mutex);
12808da6d581SJan Schmidt 				mutex_unlock(&head->mutex);
1281d278850eSJosef Bacik 				btrfs_put_delayed_ref_head(head);
12828da6d581SJan Schmidt 				goto again;
12838da6d581SJan Schmidt 			}
1284d7df2c79SJosef Bacik 			spin_unlock(&delayed_refs->lock);
128500142756SJeff Mahoney 			ret = add_delayed_refs(fs_info, head, time_seq,
1286b25b0b87Sethanwu 					       &preftrees, sc);
1287155725c9SJan Schmidt 			mutex_unlock(&head->mutex);
1288d7df2c79SJosef Bacik 			if (ret)
12898da6d581SJan Schmidt 				goto out;
1290d7df2c79SJosef Bacik 		} else {
12918da6d581SJan Schmidt 			spin_unlock(&delayed_refs->lock);
12927a3ae2f8SJan Schmidt 		}
1293d7df2c79SJosef Bacik 	}
12948da6d581SJan Schmidt 
12958da6d581SJan Schmidt 	if (path->slots[0]) {
12968da6d581SJan Schmidt 		struct extent_buffer *leaf;
12978da6d581SJan Schmidt 		int slot;
12988da6d581SJan Schmidt 
1299dadcaf78SJan Schmidt 		path->slots[0]--;
13008da6d581SJan Schmidt 		leaf = path->nodes[0];
1301dadcaf78SJan Schmidt 		slot = path->slots[0];
13028da6d581SJan Schmidt 		btrfs_item_key_to_cpu(leaf, &key, slot);
13038da6d581SJan Schmidt 		if (key.objectid == bytenr &&
1304261c84b6SJosef Bacik 		    (key.type == BTRFS_EXTENT_ITEM_KEY ||
1305261c84b6SJosef Bacik 		     key.type == BTRFS_METADATA_ITEM_KEY)) {
130600142756SJeff Mahoney 			ret = add_inline_refs(fs_info, path, bytenr,
1307b25b0b87Sethanwu 					      &info_level, &preftrees, sc);
13088da6d581SJan Schmidt 			if (ret)
13098da6d581SJan Schmidt 				goto out;
131098cc4222SJosef Bacik 			ret = add_keyed_refs(root, path, bytenr, info_level,
13113ec4d323SEdmund Nadolski 					     &preftrees, sc);
13128da6d581SJan Schmidt 			if (ret)
13138da6d581SJan Schmidt 				goto out;
13148da6d581SJan Schmidt 		}
13158da6d581SJan Schmidt 	}
131686d5f994SEdmund Nadolski 
1317*56f5c199SFilipe Manana 	/*
1318*56f5c199SFilipe Manana 	 * If we have a share context and we reached here, it means the extent
1319*56f5c199SFilipe Manana 	 * is not directly shared (no multiple reference items for it),
1320*56f5c199SFilipe Manana 	 * otherwise we would have exited earlier with a return value of
1321*56f5c199SFilipe Manana 	 * BACKREF_FOUND_SHARED after processing delayed references or while
1322*56f5c199SFilipe Manana 	 * processing inline or keyed references from the extent tree.
1323*56f5c199SFilipe Manana 	 * The extent may however be indirectly shared through shared subtrees
1324*56f5c199SFilipe Manana 	 * as a result from creating snapshots, so we determine below what is
1325*56f5c199SFilipe Manana 	 * its parent node, in case we are dealing with a metadata extent, or
1326*56f5c199SFilipe Manana 	 * what's the leaf (or leaves), from a fs tree, that has a file extent
1327*56f5c199SFilipe Manana 	 * item pointing to it in case we are dealing with a data extent.
1328*56f5c199SFilipe Manana 	 */
1329*56f5c199SFilipe Manana 	ASSERT(extent_is_shared(sc) == 0);
1330*56f5c199SFilipe Manana 
13318da6d581SJan Schmidt 	btrfs_release_path(path);
13328da6d581SJan Schmidt 
133338e3eebfSJosef Bacik 	ret = add_missing_keys(fs_info, &preftrees, path->skip_locking == 0);
1334d5c88b73SJan Schmidt 	if (ret)
1335d5c88b73SJan Schmidt 		goto out;
1336d5c88b73SJan Schmidt 
1337ecf160b4SLiu Bo 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect_missing_keys.root.rb_root));
13388da6d581SJan Schmidt 
133986d5f994SEdmund Nadolski 	ret = resolve_indirect_refs(fs_info, path, time_seq, &preftrees,
1340b25b0b87Sethanwu 				    extent_item_pos, sc, ignore_offset);
13418da6d581SJan Schmidt 	if (ret)
13428da6d581SJan Schmidt 		goto out;
13438da6d581SJan Schmidt 
1344ecf160b4SLiu Bo 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect.root.rb_root));
13458da6d581SJan Schmidt 
134686d5f994SEdmund Nadolski 	/*
134786d5f994SEdmund Nadolski 	 * This walks the tree of merged and resolved refs. Tree blocks are
134886d5f994SEdmund Nadolski 	 * read in as needed. Unique entries are added to the ulist, and
134986d5f994SEdmund Nadolski 	 * the list of found roots is updated.
135086d5f994SEdmund Nadolski 	 *
135186d5f994SEdmund Nadolski 	 * We release the entire tree in one go before returning.
135286d5f994SEdmund Nadolski 	 */
1353ecf160b4SLiu Bo 	node = rb_first_cached(&preftrees.direct.root);
135486d5f994SEdmund Nadolski 	while (node) {
135586d5f994SEdmund Nadolski 		ref = rb_entry(node, struct prelim_ref, rbnode);
135686d5f994SEdmund Nadolski 		node = rb_next(&ref->rbnode);
1357c8195a7bSZygo Blaxell 		/*
1358c8195a7bSZygo Blaxell 		 * ref->count < 0 can happen here if there are delayed
1359c8195a7bSZygo Blaxell 		 * refs with a node->action of BTRFS_DROP_DELAYED_REF.
1360c8195a7bSZygo Blaxell 		 * prelim_ref_insert() relies on this when merging
1361c8195a7bSZygo Blaxell 		 * identical refs to keep the overall count correct.
1362c8195a7bSZygo Blaxell 		 * prelim_ref_insert() will merge only those refs
1363c8195a7bSZygo Blaxell 		 * which compare identically.  Any refs having
1364c8195a7bSZygo Blaxell 		 * e.g. different offsets would not be merged,
1365c8195a7bSZygo Blaxell 		 * and would retain their original ref->count < 0.
1366c8195a7bSZygo Blaxell 		 */
136798cfee21SWang Shilong 		if (roots && ref->count && ref->root_id && ref->parent == 0) {
13688da6d581SJan Schmidt 			/* no parent == root of tree */
13698da6d581SJan Schmidt 			ret = ulist_add(roots, ref->root_id, 0, GFP_NOFS);
1370f1723939SWang Shilong 			if (ret < 0)
1371f1723939SWang Shilong 				goto out;
13728da6d581SJan Schmidt 		}
13738da6d581SJan Schmidt 		if (ref->count && ref->parent) {
13748a56457fSJosef Bacik 			if (extent_item_pos && !ref->inode_list &&
13758a56457fSJosef Bacik 			    ref->level == 0) {
1376976b1908SJan Schmidt 				struct extent_buffer *eb;
1377707e8a07SDavid Sterba 
1378581c1760SQu Wenruo 				eb = read_tree_block(fs_info, ref->parent, 0,
13791b7ec85eSJosef Bacik 						     0, ref->level, NULL);
138064c043deSLiu Bo 				if (IS_ERR(eb)) {
138164c043deSLiu Bo 					ret = PTR_ERR(eb);
138264c043deSLiu Bo 					goto out;
13834eb150d6SQu Wenruo 				}
13844eb150d6SQu Wenruo 				if (!extent_buffer_uptodate(eb)) {
1385416bc658SJosef Bacik 					free_extent_buffer(eb);
1386c16c2e2eSWang Shilong 					ret = -EIO;
1387c16c2e2eSWang Shilong 					goto out;
1388416bc658SJosef Bacik 				}
138938e3eebfSJosef Bacik 
1390ac5887c8SJosef Bacik 				if (!path->skip_locking)
13916f7ff6d7SFilipe Manana 					btrfs_tree_read_lock(eb);
1392976b1908SJan Schmidt 				ret = find_extent_in_eb(eb, bytenr,
1393c995ab3cSZygo Blaxell 							*extent_item_pos, &eie, ignore_offset);
139438e3eebfSJosef Bacik 				if (!path->skip_locking)
1395ac5887c8SJosef Bacik 					btrfs_tree_read_unlock(eb);
1396976b1908SJan Schmidt 				free_extent_buffer(eb);
1397f5929cd8SFilipe David Borba Manana 				if (ret < 0)
1398f5929cd8SFilipe David Borba Manana 					goto out;
1399f5929cd8SFilipe David Borba Manana 				ref->inode_list = eie;
140092876eecSFilipe Manana 				/*
140192876eecSFilipe Manana 				 * We transferred the list ownership to the ref,
140292876eecSFilipe Manana 				 * so set to NULL to avoid a double free in case
140392876eecSFilipe Manana 				 * an error happens after this.
140492876eecSFilipe Manana 				 */
140592876eecSFilipe Manana 				eie = NULL;
1406976b1908SJan Schmidt 			}
14074eb1f66dSTakashi Iwai 			ret = ulist_add_merge_ptr(refs, ref->parent,
14084eb1f66dSTakashi Iwai 						  ref->inode_list,
14094eb1f66dSTakashi Iwai 						  (void **)&eie, GFP_NOFS);
1410f1723939SWang Shilong 			if (ret < 0)
1411f1723939SWang Shilong 				goto out;
14123301958bSJan Schmidt 			if (!ret && extent_item_pos) {
14133301958bSJan Schmidt 				/*
14149f05c09dSJosef Bacik 				 * We've recorded that parent, so we must extend
14159f05c09dSJosef Bacik 				 * its inode list here.
14169f05c09dSJosef Bacik 				 *
14179f05c09dSJosef Bacik 				 * However if there was corruption we may not
14189f05c09dSJosef Bacik 				 * have found an eie, return an error in this
14199f05c09dSJosef Bacik 				 * case.
14203301958bSJan Schmidt 				 */
14219f05c09dSJosef Bacik 				ASSERT(eie);
14229f05c09dSJosef Bacik 				if (!eie) {
14239f05c09dSJosef Bacik 					ret = -EUCLEAN;
14249f05c09dSJosef Bacik 					goto out;
14259f05c09dSJosef Bacik 				}
14263301958bSJan Schmidt 				while (eie->next)
14273301958bSJan Schmidt 					eie = eie->next;
14283301958bSJan Schmidt 				eie->next = ref->inode_list;
14293301958bSJan Schmidt 			}
1430f05c4746SWang Shilong 			eie = NULL;
143192876eecSFilipe Manana 			/*
143292876eecSFilipe Manana 			 * We have transferred the inode list ownership from
143392876eecSFilipe Manana 			 * this ref to the ref we added to the 'refs' ulist.
143492876eecSFilipe Manana 			 * So set this ref's inode list to NULL to avoid
143592876eecSFilipe Manana 			 * use-after-free when our caller uses it or double
143692876eecSFilipe Manana 			 * frees in case an error happens before we return.
143792876eecSFilipe Manana 			 */
143892876eecSFilipe Manana 			ref->inode_list = NULL;
14398da6d581SJan Schmidt 		}
14409dd14fd6SEdmund Nadolski 		cond_resched();
14418da6d581SJan Schmidt 	}
14428da6d581SJan Schmidt 
14438da6d581SJan Schmidt out:
14448da6d581SJan Schmidt 	btrfs_free_path(path);
144586d5f994SEdmund Nadolski 
144686d5f994SEdmund Nadolski 	prelim_release(&preftrees.direct);
144786d5f994SEdmund Nadolski 	prelim_release(&preftrees.indirect);
144886d5f994SEdmund Nadolski 	prelim_release(&preftrees.indirect_missing_keys);
144986d5f994SEdmund Nadolski 
1450f05c4746SWang Shilong 	if (ret < 0)
1451f05c4746SWang Shilong 		free_inode_elem_list(eie);
14528da6d581SJan Schmidt 	return ret;
14538da6d581SJan Schmidt }
14548da6d581SJan Schmidt 
14558da6d581SJan Schmidt /*
14568da6d581SJan Schmidt  * Finds all leafs with a reference to the specified combination of bytenr and
14578da6d581SJan Schmidt  * offset. key_list_head will point to a list of corresponding keys (caller must
14588da6d581SJan Schmidt  * free each list element). The leafs will be stored in the leafs ulist, which
14598da6d581SJan Schmidt  * must be freed with ulist_free.
14608da6d581SJan Schmidt  *
14618da6d581SJan Schmidt  * returns 0 on success, <0 on error
14628da6d581SJan Schmidt  */
146319b546d7SQu Wenruo int btrfs_find_all_leafs(struct btrfs_trans_handle *trans,
14648da6d581SJan Schmidt 			 struct btrfs_fs_info *fs_info, u64 bytenr,
1465097b8a7cSJan Schmidt 			 u64 time_seq, struct ulist **leafs,
1466c995ab3cSZygo Blaxell 			 const u64 *extent_item_pos, bool ignore_offset)
14678da6d581SJan Schmidt {
14688da6d581SJan Schmidt 	int ret;
14698da6d581SJan Schmidt 
14708da6d581SJan Schmidt 	*leafs = ulist_alloc(GFP_NOFS);
147198cfee21SWang Shilong 	if (!*leafs)
14728da6d581SJan Schmidt 		return -ENOMEM;
14738da6d581SJan Schmidt 
1474afce772eSLu Fengqi 	ret = find_parent_nodes(trans, fs_info, bytenr, time_seq,
1475c995ab3cSZygo Blaxell 				*leafs, NULL, extent_item_pos, NULL, ignore_offset);
14768da6d581SJan Schmidt 	if (ret < 0 && ret != -ENOENT) {
1477976b1908SJan Schmidt 		free_leaf_list(*leafs);
14788da6d581SJan Schmidt 		return ret;
14798da6d581SJan Schmidt 	}
14808da6d581SJan Schmidt 
14818da6d581SJan Schmidt 	return 0;
14828da6d581SJan Schmidt }
14838da6d581SJan Schmidt 
14848da6d581SJan Schmidt /*
14858da6d581SJan Schmidt  * walk all backrefs for a given extent to find all roots that reference this
14868da6d581SJan Schmidt  * extent. Walking a backref means finding all extents that reference this
14878da6d581SJan Schmidt  * extent and in turn walk the backrefs of those, too. Naturally this is a
14888da6d581SJan Schmidt  * recursive process, but here it is implemented in an iterative fashion: We
14898da6d581SJan Schmidt  * find all referencing extents for the extent in question and put them on a
14908da6d581SJan Schmidt  * list. In turn, we find all referencing extents for those, further appending
14918da6d581SJan Schmidt  * to the list. The way we iterate the list allows adding more elements after
14928da6d581SJan Schmidt  * the current while iterating. The process stops when we reach the end of the
14938da6d581SJan Schmidt  * list. Found roots are added to the roots list.
14948da6d581SJan Schmidt  *
14958da6d581SJan Schmidt  * returns 0 on success, < 0 on error.
14968da6d581SJan Schmidt  */
1497e0c476b1SJeff Mahoney static int btrfs_find_all_roots_safe(struct btrfs_trans_handle *trans,
14988da6d581SJan Schmidt 				     struct btrfs_fs_info *fs_info, u64 bytenr,
1499c995ab3cSZygo Blaxell 				     u64 time_seq, struct ulist **roots,
1500c995ab3cSZygo Blaxell 				     bool ignore_offset)
15018da6d581SJan Schmidt {
15028da6d581SJan Schmidt 	struct ulist *tmp;
15038da6d581SJan Schmidt 	struct ulist_node *node = NULL;
1504cd1b413cSJan Schmidt 	struct ulist_iterator uiter;
15058da6d581SJan Schmidt 	int ret;
15068da6d581SJan Schmidt 
15078da6d581SJan Schmidt 	tmp = ulist_alloc(GFP_NOFS);
15088da6d581SJan Schmidt 	if (!tmp)
15098da6d581SJan Schmidt 		return -ENOMEM;
15108da6d581SJan Schmidt 	*roots = ulist_alloc(GFP_NOFS);
15118da6d581SJan Schmidt 	if (!*roots) {
15128da6d581SJan Schmidt 		ulist_free(tmp);
15138da6d581SJan Schmidt 		return -ENOMEM;
15148da6d581SJan Schmidt 	}
15158da6d581SJan Schmidt 
1516cd1b413cSJan Schmidt 	ULIST_ITER_INIT(&uiter);
15178da6d581SJan Schmidt 	while (1) {
1518afce772eSLu Fengqi 		ret = find_parent_nodes(trans, fs_info, bytenr, time_seq,
1519c995ab3cSZygo Blaxell 					tmp, *roots, NULL, NULL, ignore_offset);
15208da6d581SJan Schmidt 		if (ret < 0 && ret != -ENOENT) {
15218da6d581SJan Schmidt 			ulist_free(tmp);
15228da6d581SJan Schmidt 			ulist_free(*roots);
1523580c079bSFilipe Manana 			*roots = NULL;
15248da6d581SJan Schmidt 			return ret;
15258da6d581SJan Schmidt 		}
1526cd1b413cSJan Schmidt 		node = ulist_next(tmp, &uiter);
15278da6d581SJan Schmidt 		if (!node)
15288da6d581SJan Schmidt 			break;
15298da6d581SJan Schmidt 		bytenr = node->val;
1530bca1a290SWang Shilong 		cond_resched();
15318da6d581SJan Schmidt 	}
15328da6d581SJan Schmidt 
15338da6d581SJan Schmidt 	ulist_free(tmp);
15348da6d581SJan Schmidt 	return 0;
15358da6d581SJan Schmidt }
15368da6d581SJan Schmidt 
15379e351cc8SJosef Bacik int btrfs_find_all_roots(struct btrfs_trans_handle *trans,
15389e351cc8SJosef Bacik 			 struct btrfs_fs_info *fs_info, u64 bytenr,
1539c995ab3cSZygo Blaxell 			 u64 time_seq, struct ulist **roots,
1540c7bcbb21SFilipe Manana 			 bool skip_commit_root_sem)
15419e351cc8SJosef Bacik {
15429e351cc8SJosef Bacik 	int ret;
15439e351cc8SJosef Bacik 
15448949b9a1SFilipe Manana 	if (!trans && !skip_commit_root_sem)
15459e351cc8SJosef Bacik 		down_read(&fs_info->commit_root_sem);
1546e0c476b1SJeff Mahoney 	ret = btrfs_find_all_roots_safe(trans, fs_info, bytenr,
1547c7bcbb21SFilipe Manana 					time_seq, roots, false);
15488949b9a1SFilipe Manana 	if (!trans && !skip_commit_root_sem)
15499e351cc8SJosef Bacik 		up_read(&fs_info->commit_root_sem);
15509e351cc8SJosef Bacik 	return ret;
15519e351cc8SJosef Bacik }
15529e351cc8SJosef Bacik 
15538eedaddaSFilipe Manana /*
155412a824dcSFilipe Manana  * The caller has joined a transaction or is holding a read lock on the
155512a824dcSFilipe Manana  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
155612a824dcSFilipe Manana  * snapshot field changing while updating or checking the cache.
155712a824dcSFilipe Manana  */
155861dbb952SFilipe Manana static bool lookup_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
155912a824dcSFilipe Manana 					struct btrfs_root *root,
156012a824dcSFilipe Manana 					u64 bytenr, int level, bool *is_shared)
156112a824dcSFilipe Manana {
156212a824dcSFilipe Manana 	struct btrfs_backref_shared_cache_entry *entry;
156312a824dcSFilipe Manana 
156461dbb952SFilipe Manana 	if (!ctx->use_path_cache)
156563c84b46SFilipe Manana 		return false;
156663c84b46SFilipe Manana 
156712a824dcSFilipe Manana 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
156812a824dcSFilipe Manana 		return false;
156912a824dcSFilipe Manana 
157012a824dcSFilipe Manana 	/*
157112a824dcSFilipe Manana 	 * Level -1 is used for the data extent, which is not reliable to cache
157212a824dcSFilipe Manana 	 * because its reference count can increase or decrease without us
157312a824dcSFilipe Manana 	 * realizing. We cache results only for extent buffers that lead from
157412a824dcSFilipe Manana 	 * the root node down to the leaf with the file extent item.
157512a824dcSFilipe Manana 	 */
157612a824dcSFilipe Manana 	ASSERT(level >= 0);
157712a824dcSFilipe Manana 
157861dbb952SFilipe Manana 	entry = &ctx->path_cache_entries[level];
157912a824dcSFilipe Manana 
158012a824dcSFilipe Manana 	/* Unused cache entry or being used for some other extent buffer. */
158112a824dcSFilipe Manana 	if (entry->bytenr != bytenr)
158212a824dcSFilipe Manana 		return false;
158312a824dcSFilipe Manana 
158412a824dcSFilipe Manana 	/*
158512a824dcSFilipe Manana 	 * We cached a false result, but the last snapshot generation of the
158612a824dcSFilipe Manana 	 * root changed, so we now have a snapshot. Don't trust the result.
158712a824dcSFilipe Manana 	 */
158812a824dcSFilipe Manana 	if (!entry->is_shared &&
158912a824dcSFilipe Manana 	    entry->gen != btrfs_root_last_snapshot(&root->root_item))
159012a824dcSFilipe Manana 		return false;
159112a824dcSFilipe Manana 
159212a824dcSFilipe Manana 	/*
159312a824dcSFilipe Manana 	 * If we cached a true result and the last generation used for dropping
159412a824dcSFilipe Manana 	 * a root changed, we can not trust the result, because the dropped root
159512a824dcSFilipe Manana 	 * could be a snapshot sharing this extent buffer.
159612a824dcSFilipe Manana 	 */
159712a824dcSFilipe Manana 	if (entry->is_shared &&
159812a824dcSFilipe Manana 	    entry->gen != btrfs_get_last_root_drop_gen(root->fs_info))
159912a824dcSFilipe Manana 		return false;
160012a824dcSFilipe Manana 
160112a824dcSFilipe Manana 	*is_shared = entry->is_shared;
160296dbcc00SFilipe Manana 	/*
160396dbcc00SFilipe Manana 	 * If the node at this level is shared, than all nodes below are also
160496dbcc00SFilipe Manana 	 * shared. Currently some of the nodes below may be marked as not shared
160596dbcc00SFilipe Manana 	 * because we have just switched from one leaf to another, and switched
160696dbcc00SFilipe Manana 	 * also other nodes above the leaf and below the current level, so mark
160796dbcc00SFilipe Manana 	 * them as shared.
160896dbcc00SFilipe Manana 	 */
160996dbcc00SFilipe Manana 	if (*is_shared) {
161096dbcc00SFilipe Manana 		for (int i = 0; i < level; i++) {
161161dbb952SFilipe Manana 			ctx->path_cache_entries[i].is_shared = true;
161261dbb952SFilipe Manana 			ctx->path_cache_entries[i].gen = entry->gen;
161396dbcc00SFilipe Manana 		}
161496dbcc00SFilipe Manana 	}
161512a824dcSFilipe Manana 
161612a824dcSFilipe Manana 	return true;
161712a824dcSFilipe Manana }
161812a824dcSFilipe Manana 
161912a824dcSFilipe Manana /*
162012a824dcSFilipe Manana  * The caller has joined a transaction or is holding a read lock on the
162112a824dcSFilipe Manana  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
162212a824dcSFilipe Manana  * snapshot field changing while updating or checking the cache.
162312a824dcSFilipe Manana  */
162461dbb952SFilipe Manana static void store_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
162512a824dcSFilipe Manana 				       struct btrfs_root *root,
162612a824dcSFilipe Manana 				       u64 bytenr, int level, bool is_shared)
162712a824dcSFilipe Manana {
162812a824dcSFilipe Manana 	struct btrfs_backref_shared_cache_entry *entry;
162912a824dcSFilipe Manana 	u64 gen;
163012a824dcSFilipe Manana 
163161dbb952SFilipe Manana 	if (!ctx->use_path_cache)
163263c84b46SFilipe Manana 		return;
163363c84b46SFilipe Manana 
163412a824dcSFilipe Manana 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
163512a824dcSFilipe Manana 		return;
163612a824dcSFilipe Manana 
163712a824dcSFilipe Manana 	/*
163812a824dcSFilipe Manana 	 * Level -1 is used for the data extent, which is not reliable to cache
163912a824dcSFilipe Manana 	 * because its reference count can increase or decrease without us
164012a824dcSFilipe Manana 	 * realizing. We cache results only for extent buffers that lead from
164112a824dcSFilipe Manana 	 * the root node down to the leaf with the file extent item.
164212a824dcSFilipe Manana 	 */
164312a824dcSFilipe Manana 	ASSERT(level >= 0);
164412a824dcSFilipe Manana 
164512a824dcSFilipe Manana 	if (is_shared)
164612a824dcSFilipe Manana 		gen = btrfs_get_last_root_drop_gen(root->fs_info);
164712a824dcSFilipe Manana 	else
164812a824dcSFilipe Manana 		gen = btrfs_root_last_snapshot(&root->root_item);
164912a824dcSFilipe Manana 
165061dbb952SFilipe Manana 	entry = &ctx->path_cache_entries[level];
165112a824dcSFilipe Manana 	entry->bytenr = bytenr;
165212a824dcSFilipe Manana 	entry->is_shared = is_shared;
165312a824dcSFilipe Manana 	entry->gen = gen;
165412a824dcSFilipe Manana 
165512a824dcSFilipe Manana 	/*
165612a824dcSFilipe Manana 	 * If we found an extent buffer is shared, set the cache result for all
165712a824dcSFilipe Manana 	 * extent buffers below it to true. As nodes in the path are COWed,
165812a824dcSFilipe Manana 	 * their sharedness is moved to their children, and if a leaf is COWed,
165912a824dcSFilipe Manana 	 * then the sharedness of a data extent becomes direct, the refcount of
166012a824dcSFilipe Manana 	 * data extent is increased in the extent item at the extent tree.
166112a824dcSFilipe Manana 	 */
166212a824dcSFilipe Manana 	if (is_shared) {
166312a824dcSFilipe Manana 		for (int i = 0; i < level; i++) {
166461dbb952SFilipe Manana 			entry = &ctx->path_cache_entries[i];
166512a824dcSFilipe Manana 			entry->is_shared = is_shared;
166612a824dcSFilipe Manana 			entry->gen = gen;
166712a824dcSFilipe Manana 		}
166812a824dcSFilipe Manana 	}
166912a824dcSFilipe Manana }
167012a824dcSFilipe Manana 
167184a7949dSFilipe Manana struct btrfs_backref_share_check_ctx *btrfs_alloc_backref_share_check_ctx(void)
167284a7949dSFilipe Manana {
167384a7949dSFilipe Manana 	struct btrfs_backref_share_check_ctx *ctx;
167484a7949dSFilipe Manana 
167584a7949dSFilipe Manana 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
167684a7949dSFilipe Manana 	if (!ctx)
167784a7949dSFilipe Manana 		return NULL;
167884a7949dSFilipe Manana 
167984a7949dSFilipe Manana 	ulist_init(&ctx->refs);
168084a7949dSFilipe Manana 
168184a7949dSFilipe Manana 	return ctx;
168284a7949dSFilipe Manana }
168384a7949dSFilipe Manana 
168484a7949dSFilipe Manana void btrfs_free_backref_share_ctx(struct btrfs_backref_share_check_ctx *ctx)
168584a7949dSFilipe Manana {
168684a7949dSFilipe Manana 	if (!ctx)
168784a7949dSFilipe Manana 		return;
168884a7949dSFilipe Manana 
168984a7949dSFilipe Manana 	ulist_release(&ctx->refs);
169084a7949dSFilipe Manana 	kfree(ctx);
169184a7949dSFilipe Manana }
169284a7949dSFilipe Manana 
169312a824dcSFilipe Manana /*
16948eedaddaSFilipe Manana  * Check if a data extent is shared or not.
16956e353e3bSNikolay Borisov  *
1696ceb707daSFilipe Manana  * @inode:       The inode whose extent we are checking.
1697b8f164e3SFilipe Manana  * @bytenr:      Logical bytenr of the extent we are checking.
1698b8f164e3SFilipe Manana  * @extent_gen:  Generation of the extent (file extent item) or 0 if it is
1699b8f164e3SFilipe Manana  *               not known.
170061dbb952SFilipe Manana  * @ctx:         A backref sharedness check context.
17012c2ed5aaSMark Fasheh  *
17028eedaddaSFilipe Manana  * btrfs_is_data_extent_shared uses the backref walking code but will short
17032c2ed5aaSMark Fasheh  * circuit as soon as it finds a root or inode that doesn't match the
17042c2ed5aaSMark Fasheh  * one passed in. This provides a significant performance benefit for
17052c2ed5aaSMark Fasheh  * callers (such as fiemap) which want to know whether the extent is
17062c2ed5aaSMark Fasheh  * shared but do not need a ref count.
17072c2ed5aaSMark Fasheh  *
170803628cdbSFilipe Manana  * This attempts to attach to the running transaction in order to account for
170903628cdbSFilipe Manana  * delayed refs, but continues on even when no running transaction exists.
1710bb739cf0SEdmund Nadolski  *
17112c2ed5aaSMark Fasheh  * Return: 0 if extent is not shared, 1 if it is shared, < 0 on error.
17122c2ed5aaSMark Fasheh  */
1713ceb707daSFilipe Manana int btrfs_is_data_extent_shared(struct btrfs_inode *inode, u64 bytenr,
1714b8f164e3SFilipe Manana 				u64 extent_gen,
171561dbb952SFilipe Manana 				struct btrfs_backref_share_check_ctx *ctx)
1716dc046b10SJosef Bacik {
1717ceb707daSFilipe Manana 	struct btrfs_root *root = inode->root;
1718bb739cf0SEdmund Nadolski 	struct btrfs_fs_info *fs_info = root->fs_info;
1719bb739cf0SEdmund Nadolski 	struct btrfs_trans_handle *trans;
1720dc046b10SJosef Bacik 	struct ulist_iterator uiter;
1721dc046b10SJosef Bacik 	struct ulist_node *node;
1722f3a84ccdSFilipe Manana 	struct btrfs_seq_list elem = BTRFS_SEQ_LIST_INIT(elem);
1723dc046b10SJosef Bacik 	int ret = 0;
17243ec4d323SEdmund Nadolski 	struct share_check shared = {
17254fd786e6SMisono Tomohiro 		.root_objectid = root->root_key.objectid,
1726ceb707daSFilipe Manana 		.inum = btrfs_ino(inode),
17273ec4d323SEdmund Nadolski 		.share_count = 0,
17284fc7b572SFilipe Manana 		.have_delayed_delete_refs = false,
17293ec4d323SEdmund Nadolski 	};
173012a824dcSFilipe Manana 	int level;
1731dc046b10SJosef Bacik 
173284a7949dSFilipe Manana 	ulist_init(&ctx->refs);
1733dc046b10SJosef Bacik 
1734a6d155d2SFilipe Manana 	trans = btrfs_join_transaction_nostart(root);
1735bb739cf0SEdmund Nadolski 	if (IS_ERR(trans)) {
173603628cdbSFilipe Manana 		if (PTR_ERR(trans) != -ENOENT && PTR_ERR(trans) != -EROFS) {
173703628cdbSFilipe Manana 			ret = PTR_ERR(trans);
173803628cdbSFilipe Manana 			goto out;
173903628cdbSFilipe Manana 		}
1740bb739cf0SEdmund Nadolski 		trans = NULL;
1741dc046b10SJosef Bacik 		down_read(&fs_info->commit_root_sem);
1742bb739cf0SEdmund Nadolski 	} else {
1743bb739cf0SEdmund Nadolski 		btrfs_get_tree_mod_seq(fs_info, &elem);
1744bb739cf0SEdmund Nadolski 	}
1745bb739cf0SEdmund Nadolski 
174612a824dcSFilipe Manana 	/* -1 means we are in the bytenr of the data extent. */
174712a824dcSFilipe Manana 	level = -1;
1748dc046b10SJosef Bacik 	ULIST_ITER_INIT(&uiter);
174961dbb952SFilipe Manana 	ctx->use_path_cache = true;
1750dc046b10SJosef Bacik 	while (1) {
175112a824dcSFilipe Manana 		bool is_shared;
175212a824dcSFilipe Manana 		bool cached;
175312a824dcSFilipe Manana 
175484a7949dSFilipe Manana 		ret = find_parent_nodes(trans, fs_info, bytenr, elem.seq, &ctx->refs,
1755b6296858SFilipe Manana 					NULL, NULL, &shared, false);
1756dc046b10SJosef Bacik 		if (ret == BACKREF_FOUND_SHARED) {
17572c2ed5aaSMark Fasheh 			/* this is the only condition under which we return 1 */
1758dc046b10SJosef Bacik 			ret = 1;
175912a824dcSFilipe Manana 			if (level >= 0)
176061dbb952SFilipe Manana 				store_backref_shared_cache(ctx, root, bytenr,
176112a824dcSFilipe Manana 							   level, true);
1762dc046b10SJosef Bacik 			break;
1763dc046b10SJosef Bacik 		}
1764dc046b10SJosef Bacik 		if (ret < 0 && ret != -ENOENT)
1765dc046b10SJosef Bacik 			break;
17662c2ed5aaSMark Fasheh 		ret = 0;
1767b8f164e3SFilipe Manana 		/*
1768b8f164e3SFilipe Manana 		 * If our data extent is not shared through reflinks and it was
1769b8f164e3SFilipe Manana 		 * created in a generation after the last one used to create a
1770b8f164e3SFilipe Manana 		 * snapshot of the inode's root, then it can not be shared
1771b8f164e3SFilipe Manana 		 * indirectly through subtrees, as that can only happen with
1772b8f164e3SFilipe Manana 		 * snapshots. In this case bail out, no need to check for the
1773b8f164e3SFilipe Manana 		 * sharedness of extent buffers.
1774b8f164e3SFilipe Manana 		 */
1775b8f164e3SFilipe Manana 		if (level == -1 &&
1776b8f164e3SFilipe Manana 		    extent_gen > btrfs_root_last_snapshot(&root->root_item))
1777b8f164e3SFilipe Manana 			break;
1778b8f164e3SFilipe Manana 
177963c84b46SFilipe Manana 		/*
178063c84b46SFilipe Manana 		 * If our data extent was not directly shared (without multiple
178163c84b46SFilipe Manana 		 * reference items), than it might have a single reference item
178263c84b46SFilipe Manana 		 * with a count > 1 for the same offset, which means there are 2
178363c84b46SFilipe Manana 		 * (or more) file extent items that point to the data extent -
178463c84b46SFilipe Manana 		 * this happens when a file extent item needs to be split and
178563c84b46SFilipe Manana 		 * then one item gets moved to another leaf due to a b+tree leaf
178663c84b46SFilipe Manana 		 * split when inserting some item. In this case the file extent
178763c84b46SFilipe Manana 		 * items may be located in different leaves and therefore some
178863c84b46SFilipe Manana 		 * of the leaves may be referenced through shared subtrees while
178963c84b46SFilipe Manana 		 * others are not. Since our extent buffer cache only works for
179063c84b46SFilipe Manana 		 * a single path (by far the most common case and simpler to
179163c84b46SFilipe Manana 		 * deal with), we can not use it if we have multiple leaves
179263c84b46SFilipe Manana 		 * (which implies multiple paths).
179363c84b46SFilipe Manana 		 */
179484a7949dSFilipe Manana 		if (level == -1 && ctx->refs.nnodes > 1)
179561dbb952SFilipe Manana 			ctx->use_path_cache = false;
179663c84b46SFilipe Manana 
179712a824dcSFilipe Manana 		if (level >= 0)
179861dbb952SFilipe Manana 			store_backref_shared_cache(ctx, root, bytenr,
179912a824dcSFilipe Manana 						   level, false);
180084a7949dSFilipe Manana 		node = ulist_next(&ctx->refs, &uiter);
1801dc046b10SJosef Bacik 		if (!node)
1802dc046b10SJosef Bacik 			break;
1803dc046b10SJosef Bacik 		bytenr = node->val;
180412a824dcSFilipe Manana 		level++;
180561dbb952SFilipe Manana 		cached = lookup_backref_shared_cache(ctx, root, bytenr, level,
180612a824dcSFilipe Manana 						     &is_shared);
180712a824dcSFilipe Manana 		if (cached) {
180812a824dcSFilipe Manana 			ret = (is_shared ? 1 : 0);
180912a824dcSFilipe Manana 			break;
181012a824dcSFilipe Manana 		}
181118bf591bSEdmund Nadolski 		shared.share_count = 0;
18124fc7b572SFilipe Manana 		shared.have_delayed_delete_refs = false;
1813dc046b10SJosef Bacik 		cond_resched();
1814dc046b10SJosef Bacik 	}
1815bb739cf0SEdmund Nadolski 
1816bb739cf0SEdmund Nadolski 	if (trans) {
1817dc046b10SJosef Bacik 		btrfs_put_tree_mod_seq(fs_info, &elem);
1818bb739cf0SEdmund Nadolski 		btrfs_end_transaction(trans);
1819bb739cf0SEdmund Nadolski 	} else {
1820dc046b10SJosef Bacik 		up_read(&fs_info->commit_root_sem);
1821bb739cf0SEdmund Nadolski 	}
182203628cdbSFilipe Manana out:
182384a7949dSFilipe Manana 	ulist_release(&ctx->refs);
1824dc046b10SJosef Bacik 	return ret;
1825dc046b10SJosef Bacik }
1826dc046b10SJosef Bacik 
1827f186373fSMark Fasheh int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
1828f186373fSMark Fasheh 			  u64 start_off, struct btrfs_path *path,
1829f186373fSMark Fasheh 			  struct btrfs_inode_extref **ret_extref,
1830f186373fSMark Fasheh 			  u64 *found_off)
1831f186373fSMark Fasheh {
1832f186373fSMark Fasheh 	int ret, slot;
1833f186373fSMark Fasheh 	struct btrfs_key key;
1834f186373fSMark Fasheh 	struct btrfs_key found_key;
1835f186373fSMark Fasheh 	struct btrfs_inode_extref *extref;
183673980becSJeff Mahoney 	const struct extent_buffer *leaf;
1837f186373fSMark Fasheh 	unsigned long ptr;
1838f186373fSMark Fasheh 
1839f186373fSMark Fasheh 	key.objectid = inode_objectid;
1840962a298fSDavid Sterba 	key.type = BTRFS_INODE_EXTREF_KEY;
1841f186373fSMark Fasheh 	key.offset = start_off;
1842f186373fSMark Fasheh 
1843f186373fSMark Fasheh 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1844f186373fSMark Fasheh 	if (ret < 0)
1845f186373fSMark Fasheh 		return ret;
1846f186373fSMark Fasheh 
1847f186373fSMark Fasheh 	while (1) {
1848f186373fSMark Fasheh 		leaf = path->nodes[0];
1849f186373fSMark Fasheh 		slot = path->slots[0];
1850f186373fSMark Fasheh 		if (slot >= btrfs_header_nritems(leaf)) {
1851f186373fSMark Fasheh 			/*
1852f186373fSMark Fasheh 			 * If the item at offset is not found,
1853f186373fSMark Fasheh 			 * btrfs_search_slot will point us to the slot
1854f186373fSMark Fasheh 			 * where it should be inserted. In our case
1855f186373fSMark Fasheh 			 * that will be the slot directly before the
1856f186373fSMark Fasheh 			 * next INODE_REF_KEY_V2 item. In the case
1857f186373fSMark Fasheh 			 * that we're pointing to the last slot in a
1858f186373fSMark Fasheh 			 * leaf, we must move one leaf over.
1859f186373fSMark Fasheh 			 */
1860f186373fSMark Fasheh 			ret = btrfs_next_leaf(root, path);
1861f186373fSMark Fasheh 			if (ret) {
1862f186373fSMark Fasheh 				if (ret >= 1)
1863f186373fSMark Fasheh 					ret = -ENOENT;
1864f186373fSMark Fasheh 				break;
1865f186373fSMark Fasheh 			}
1866f186373fSMark Fasheh 			continue;
1867f186373fSMark Fasheh 		}
1868f186373fSMark Fasheh 
1869f186373fSMark Fasheh 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
1870f186373fSMark Fasheh 
1871f186373fSMark Fasheh 		/*
1872f186373fSMark Fasheh 		 * Check that we're still looking at an extended ref key for
1873f186373fSMark Fasheh 		 * this particular objectid. If we have different
1874f186373fSMark Fasheh 		 * objectid or type then there are no more to be found
1875f186373fSMark Fasheh 		 * in the tree and we can exit.
1876f186373fSMark Fasheh 		 */
1877f186373fSMark Fasheh 		ret = -ENOENT;
1878f186373fSMark Fasheh 		if (found_key.objectid != inode_objectid)
1879f186373fSMark Fasheh 			break;
1880962a298fSDavid Sterba 		if (found_key.type != BTRFS_INODE_EXTREF_KEY)
1881f186373fSMark Fasheh 			break;
1882f186373fSMark Fasheh 
1883f186373fSMark Fasheh 		ret = 0;
1884f186373fSMark Fasheh 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1885f186373fSMark Fasheh 		extref = (struct btrfs_inode_extref *)ptr;
1886f186373fSMark Fasheh 		*ret_extref = extref;
1887f186373fSMark Fasheh 		if (found_off)
1888f186373fSMark Fasheh 			*found_off = found_key.offset;
1889f186373fSMark Fasheh 		break;
1890f186373fSMark Fasheh 	}
1891f186373fSMark Fasheh 
1892f186373fSMark Fasheh 	return ret;
1893f186373fSMark Fasheh }
1894f186373fSMark Fasheh 
189548a3b636SEric Sandeen /*
189648a3b636SEric Sandeen  * this iterates to turn a name (from iref/extref) into a full filesystem path.
189748a3b636SEric Sandeen  * Elements of the path are separated by '/' and the path is guaranteed to be
189848a3b636SEric Sandeen  * 0-terminated. the path is only given within the current file system.
189948a3b636SEric Sandeen  * Therefore, it never starts with a '/'. the caller is responsible to provide
190048a3b636SEric Sandeen  * "size" bytes in "dest". the dest buffer will be filled backwards. finally,
190148a3b636SEric Sandeen  * the start point of the resulting string is returned. this pointer is within
190248a3b636SEric Sandeen  * dest, normally.
190348a3b636SEric Sandeen  * in case the path buffer would overflow, the pointer is decremented further
190448a3b636SEric Sandeen  * as if output was written to the buffer, though no more output is actually
190548a3b636SEric Sandeen  * generated. that way, the caller can determine how much space would be
190648a3b636SEric Sandeen  * required for the path to fit into the buffer. in that case, the returned
190748a3b636SEric Sandeen  * value will be smaller than dest. callers must check this!
190848a3b636SEric Sandeen  */
190996b5bd77SJan Schmidt char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
1910d24bec3aSMark Fasheh 			u32 name_len, unsigned long name_off,
1911a542ad1bSJan Schmidt 			struct extent_buffer *eb_in, u64 parent,
1912a542ad1bSJan Schmidt 			char *dest, u32 size)
1913a542ad1bSJan Schmidt {
1914a542ad1bSJan Schmidt 	int slot;
1915a542ad1bSJan Schmidt 	u64 next_inum;
1916a542ad1bSJan Schmidt 	int ret;
1917661bec6bSGabriel de Perthuis 	s64 bytes_left = ((s64)size) - 1;
1918a542ad1bSJan Schmidt 	struct extent_buffer *eb = eb_in;
1919a542ad1bSJan Schmidt 	struct btrfs_key found_key;
1920d24bec3aSMark Fasheh 	struct btrfs_inode_ref *iref;
1921a542ad1bSJan Schmidt 
1922a542ad1bSJan Schmidt 	if (bytes_left >= 0)
1923a542ad1bSJan Schmidt 		dest[bytes_left] = '\0';
1924a542ad1bSJan Schmidt 
1925a542ad1bSJan Schmidt 	while (1) {
1926d24bec3aSMark Fasheh 		bytes_left -= name_len;
1927a542ad1bSJan Schmidt 		if (bytes_left >= 0)
1928a542ad1bSJan Schmidt 			read_extent_buffer(eb, dest + bytes_left,
1929d24bec3aSMark Fasheh 					   name_off, name_len);
1930b916a59aSJan Schmidt 		if (eb != eb_in) {
19310c0fe3b0SFilipe Manana 			if (!path->skip_locking)
1932ac5887c8SJosef Bacik 				btrfs_tree_read_unlock(eb);
1933a542ad1bSJan Schmidt 			free_extent_buffer(eb);
1934b916a59aSJan Schmidt 		}
1935c234a24dSDavid Sterba 		ret = btrfs_find_item(fs_root, path, parent, 0,
1936c234a24dSDavid Sterba 				BTRFS_INODE_REF_KEY, &found_key);
19378f24b496SJan Schmidt 		if (ret > 0)
19388f24b496SJan Schmidt 			ret = -ENOENT;
1939a542ad1bSJan Schmidt 		if (ret)
1940a542ad1bSJan Schmidt 			break;
1941d24bec3aSMark Fasheh 
1942a542ad1bSJan Schmidt 		next_inum = found_key.offset;
1943a542ad1bSJan Schmidt 
1944a542ad1bSJan Schmidt 		/* regular exit ahead */
1945a542ad1bSJan Schmidt 		if (parent == next_inum)
1946a542ad1bSJan Schmidt 			break;
1947a542ad1bSJan Schmidt 
1948a542ad1bSJan Schmidt 		slot = path->slots[0];
1949a542ad1bSJan Schmidt 		eb = path->nodes[0];
1950a542ad1bSJan Schmidt 		/* make sure we can use eb after releasing the path */
1951b916a59aSJan Schmidt 		if (eb != eb_in) {
19520c0fe3b0SFilipe Manana 			path->nodes[0] = NULL;
19530c0fe3b0SFilipe Manana 			path->locks[0] = 0;
1954b916a59aSJan Schmidt 		}
1955a542ad1bSJan Schmidt 		btrfs_release_path(path);
1956a542ad1bSJan Schmidt 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1957d24bec3aSMark Fasheh 
1958d24bec3aSMark Fasheh 		name_len = btrfs_inode_ref_name_len(eb, iref);
1959d24bec3aSMark Fasheh 		name_off = (unsigned long)(iref + 1);
1960d24bec3aSMark Fasheh 
1961a542ad1bSJan Schmidt 		parent = next_inum;
1962a542ad1bSJan Schmidt 		--bytes_left;
1963a542ad1bSJan Schmidt 		if (bytes_left >= 0)
1964a542ad1bSJan Schmidt 			dest[bytes_left] = '/';
1965a542ad1bSJan Schmidt 	}
1966a542ad1bSJan Schmidt 
1967a542ad1bSJan Schmidt 	btrfs_release_path(path);
1968a542ad1bSJan Schmidt 
1969a542ad1bSJan Schmidt 	if (ret)
1970a542ad1bSJan Schmidt 		return ERR_PTR(ret);
1971a542ad1bSJan Schmidt 
1972a542ad1bSJan Schmidt 	return dest + bytes_left;
1973a542ad1bSJan Schmidt }
1974a542ad1bSJan Schmidt 
1975a542ad1bSJan Schmidt /*
1976a542ad1bSJan Schmidt  * this makes the path point to (logical EXTENT_ITEM *)
1977a542ad1bSJan Schmidt  * returns BTRFS_EXTENT_FLAG_DATA for data, BTRFS_EXTENT_FLAG_TREE_BLOCK for
1978a542ad1bSJan Schmidt  * tree blocks and <0 on error.
1979a542ad1bSJan Schmidt  */
1980a542ad1bSJan Schmidt int extent_from_logical(struct btrfs_fs_info *fs_info, u64 logical,
198169917e43SLiu Bo 			struct btrfs_path *path, struct btrfs_key *found_key,
198269917e43SLiu Bo 			u64 *flags_ret)
1983a542ad1bSJan Schmidt {
198429cbcf40SJosef Bacik 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, logical);
1985a542ad1bSJan Schmidt 	int ret;
1986a542ad1bSJan Schmidt 	u64 flags;
1987261c84b6SJosef Bacik 	u64 size = 0;
1988a542ad1bSJan Schmidt 	u32 item_size;
198973980becSJeff Mahoney 	const struct extent_buffer *eb;
1990a542ad1bSJan Schmidt 	struct btrfs_extent_item *ei;
1991a542ad1bSJan Schmidt 	struct btrfs_key key;
1992a542ad1bSJan Schmidt 
1993261c84b6SJosef Bacik 	if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1994261c84b6SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
1995261c84b6SJosef Bacik 	else
1996a542ad1bSJan Schmidt 		key.type = BTRFS_EXTENT_ITEM_KEY;
1997a542ad1bSJan Schmidt 	key.objectid = logical;
1998a542ad1bSJan Schmidt 	key.offset = (u64)-1;
1999a542ad1bSJan Schmidt 
200029cbcf40SJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2001a542ad1bSJan Schmidt 	if (ret < 0)
2002a542ad1bSJan Schmidt 		return ret;
2003a542ad1bSJan Schmidt 
200429cbcf40SJosef Bacik 	ret = btrfs_previous_extent_item(extent_root, path, 0);
2005850a8cdfSWang Shilong 	if (ret) {
2006850a8cdfSWang Shilong 		if (ret > 0)
2007580f0a67SJosef Bacik 			ret = -ENOENT;
2008580f0a67SJosef Bacik 		return ret;
2009580f0a67SJosef Bacik 	}
2010850a8cdfSWang Shilong 	btrfs_item_key_to_cpu(path->nodes[0], found_key, path->slots[0]);
2011261c84b6SJosef Bacik 	if (found_key->type == BTRFS_METADATA_ITEM_KEY)
2012da17066cSJeff Mahoney 		size = fs_info->nodesize;
2013261c84b6SJosef Bacik 	else if (found_key->type == BTRFS_EXTENT_ITEM_KEY)
2014261c84b6SJosef Bacik 		size = found_key->offset;
2015261c84b6SJosef Bacik 
2016580f0a67SJosef Bacik 	if (found_key->objectid > logical ||
2017261c84b6SJosef Bacik 	    found_key->objectid + size <= logical) {
2018ab8d0fc4SJeff Mahoney 		btrfs_debug(fs_info,
2019ab8d0fc4SJeff Mahoney 			"logical %llu is not within any extent", logical);
2020a542ad1bSJan Schmidt 		return -ENOENT;
20214692cf58SJan Schmidt 	}
2022a542ad1bSJan Schmidt 
2023a542ad1bSJan Schmidt 	eb = path->nodes[0];
20243212fa14SJosef Bacik 	item_size = btrfs_item_size(eb, path->slots[0]);
2025a542ad1bSJan Schmidt 	BUG_ON(item_size < sizeof(*ei));
2026a542ad1bSJan Schmidt 
2027a542ad1bSJan Schmidt 	ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
2028a542ad1bSJan Schmidt 	flags = btrfs_extent_flags(eb, ei);
2029a542ad1bSJan Schmidt 
2030ab8d0fc4SJeff Mahoney 	btrfs_debug(fs_info,
2031ab8d0fc4SJeff Mahoney 		"logical %llu is at position %llu within the extent (%llu EXTENT_ITEM %llu) flags %#llx size %u",
2032c1c9ff7cSGeert Uytterhoeven 		 logical, logical - found_key->objectid, found_key->objectid,
2033c1c9ff7cSGeert Uytterhoeven 		 found_key->offset, flags, item_size);
203469917e43SLiu Bo 
203569917e43SLiu Bo 	WARN_ON(!flags_ret);
203669917e43SLiu Bo 	if (flags_ret) {
2037a542ad1bSJan Schmidt 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
203869917e43SLiu Bo 			*flags_ret = BTRFS_EXTENT_FLAG_TREE_BLOCK;
203969917e43SLiu Bo 		else if (flags & BTRFS_EXTENT_FLAG_DATA)
204069917e43SLiu Bo 			*flags_ret = BTRFS_EXTENT_FLAG_DATA;
204169917e43SLiu Bo 		else
2042290342f6SArnd Bergmann 			BUG();
204369917e43SLiu Bo 		return 0;
204469917e43SLiu Bo 	}
2045a542ad1bSJan Schmidt 
2046a542ad1bSJan Schmidt 	return -EIO;
2047a542ad1bSJan Schmidt }
2048a542ad1bSJan Schmidt 
2049a542ad1bSJan Schmidt /*
2050a542ad1bSJan Schmidt  * helper function to iterate extent inline refs. ptr must point to a 0 value
2051a542ad1bSJan Schmidt  * for the first call and may be modified. it is used to track state.
2052a542ad1bSJan Schmidt  * if more refs exist, 0 is returned and the next call to
2053e0c476b1SJeff Mahoney  * get_extent_inline_ref must pass the modified ptr parameter to get the
2054a542ad1bSJan Schmidt  * next ref. after the last ref was processed, 1 is returned.
2055a542ad1bSJan Schmidt  * returns <0 on error
2056a542ad1bSJan Schmidt  */
2057e0c476b1SJeff Mahoney static int get_extent_inline_ref(unsigned long *ptr,
205873980becSJeff Mahoney 				 const struct extent_buffer *eb,
205973980becSJeff Mahoney 				 const struct btrfs_key *key,
206073980becSJeff Mahoney 				 const struct btrfs_extent_item *ei,
206173980becSJeff Mahoney 				 u32 item_size,
2062a542ad1bSJan Schmidt 				 struct btrfs_extent_inline_ref **out_eiref,
2063a542ad1bSJan Schmidt 				 int *out_type)
2064a542ad1bSJan Schmidt {
2065a542ad1bSJan Schmidt 	unsigned long end;
2066a542ad1bSJan Schmidt 	u64 flags;
2067a542ad1bSJan Schmidt 	struct btrfs_tree_block_info *info;
2068a542ad1bSJan Schmidt 
2069a542ad1bSJan Schmidt 	if (!*ptr) {
2070a542ad1bSJan Schmidt 		/* first call */
2071a542ad1bSJan Schmidt 		flags = btrfs_extent_flags(eb, ei);
2072a542ad1bSJan Schmidt 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
20736eda71d0SLiu Bo 			if (key->type == BTRFS_METADATA_ITEM_KEY) {
20746eda71d0SLiu Bo 				/* a skinny metadata extent */
20756eda71d0SLiu Bo 				*out_eiref =
20766eda71d0SLiu Bo 				     (struct btrfs_extent_inline_ref *)(ei + 1);
20776eda71d0SLiu Bo 			} else {
20786eda71d0SLiu Bo 				WARN_ON(key->type != BTRFS_EXTENT_ITEM_KEY);
2079a542ad1bSJan Schmidt 				info = (struct btrfs_tree_block_info *)(ei + 1);
2080a542ad1bSJan Schmidt 				*out_eiref =
2081a542ad1bSJan Schmidt 				   (struct btrfs_extent_inline_ref *)(info + 1);
20826eda71d0SLiu Bo 			}
2083a542ad1bSJan Schmidt 		} else {
2084a542ad1bSJan Schmidt 			*out_eiref = (struct btrfs_extent_inline_ref *)(ei + 1);
2085a542ad1bSJan Schmidt 		}
2086a542ad1bSJan Schmidt 		*ptr = (unsigned long)*out_eiref;
2087cd857dd6SLiu Bo 		if ((unsigned long)(*ptr) >= (unsigned long)ei + item_size)
2088a542ad1bSJan Schmidt 			return -ENOENT;
2089a542ad1bSJan Schmidt 	}
2090a542ad1bSJan Schmidt 
2091a542ad1bSJan Schmidt 	end = (unsigned long)ei + item_size;
20926eda71d0SLiu Bo 	*out_eiref = (struct btrfs_extent_inline_ref *)(*ptr);
20933de28d57SLiu Bo 	*out_type = btrfs_get_extent_inline_ref_type(eb, *out_eiref,
20943de28d57SLiu Bo 						     BTRFS_REF_TYPE_ANY);
20953de28d57SLiu Bo 	if (*out_type == BTRFS_REF_TYPE_INVALID)
2096af431dcbSSu Yue 		return -EUCLEAN;
2097a542ad1bSJan Schmidt 
2098a542ad1bSJan Schmidt 	*ptr += btrfs_extent_inline_ref_size(*out_type);
2099a542ad1bSJan Schmidt 	WARN_ON(*ptr > end);
2100a542ad1bSJan Schmidt 	if (*ptr == end)
2101a542ad1bSJan Schmidt 		return 1; /* last */
2102a542ad1bSJan Schmidt 
2103a542ad1bSJan Schmidt 	return 0;
2104a542ad1bSJan Schmidt }
2105a542ad1bSJan Schmidt 
2106a542ad1bSJan Schmidt /*
2107a542ad1bSJan Schmidt  * reads the tree block backref for an extent. tree level and root are returned
2108a542ad1bSJan Schmidt  * through out_level and out_root. ptr must point to a 0 value for the first
2109e0c476b1SJeff Mahoney  * call and may be modified (see get_extent_inline_ref comment).
2110a542ad1bSJan Schmidt  * returns 0 if data was provided, 1 if there was no more data to provide or
2111a542ad1bSJan Schmidt  * <0 on error.
2112a542ad1bSJan Schmidt  */
2113a542ad1bSJan Schmidt int tree_backref_for_extent(unsigned long *ptr, struct extent_buffer *eb,
21146eda71d0SLiu Bo 			    struct btrfs_key *key, struct btrfs_extent_item *ei,
21156eda71d0SLiu Bo 			    u32 item_size, u64 *out_root, u8 *out_level)
2116a542ad1bSJan Schmidt {
2117a542ad1bSJan Schmidt 	int ret;
2118a542ad1bSJan Schmidt 	int type;
2119a542ad1bSJan Schmidt 	struct btrfs_extent_inline_ref *eiref;
2120a542ad1bSJan Schmidt 
2121a542ad1bSJan Schmidt 	if (*ptr == (unsigned long)-1)
2122a542ad1bSJan Schmidt 		return 1;
2123a542ad1bSJan Schmidt 
2124a542ad1bSJan Schmidt 	while (1) {
2125e0c476b1SJeff Mahoney 		ret = get_extent_inline_ref(ptr, eb, key, ei, item_size,
2126a542ad1bSJan Schmidt 					      &eiref, &type);
2127a542ad1bSJan Schmidt 		if (ret < 0)
2128a542ad1bSJan Schmidt 			return ret;
2129a542ad1bSJan Schmidt 
2130a542ad1bSJan Schmidt 		if (type == BTRFS_TREE_BLOCK_REF_KEY ||
2131a542ad1bSJan Schmidt 		    type == BTRFS_SHARED_BLOCK_REF_KEY)
2132a542ad1bSJan Schmidt 			break;
2133a542ad1bSJan Schmidt 
2134a542ad1bSJan Schmidt 		if (ret == 1)
2135a542ad1bSJan Schmidt 			return 1;
2136a542ad1bSJan Schmidt 	}
2137a542ad1bSJan Schmidt 
2138a542ad1bSJan Schmidt 	/* we can treat both ref types equally here */
2139a542ad1bSJan Schmidt 	*out_root = btrfs_extent_inline_ref_offset(eb, eiref);
2140a1317f45SFilipe Manana 
2141a1317f45SFilipe Manana 	if (key->type == BTRFS_EXTENT_ITEM_KEY) {
2142a1317f45SFilipe Manana 		struct btrfs_tree_block_info *info;
2143a1317f45SFilipe Manana 
2144a1317f45SFilipe Manana 		info = (struct btrfs_tree_block_info *)(ei + 1);
2145a542ad1bSJan Schmidt 		*out_level = btrfs_tree_block_level(eb, info);
2146a1317f45SFilipe Manana 	} else {
2147a1317f45SFilipe Manana 		ASSERT(key->type == BTRFS_METADATA_ITEM_KEY);
2148a1317f45SFilipe Manana 		*out_level = (u8)key->offset;
2149a1317f45SFilipe Manana 	}
2150a542ad1bSJan Schmidt 
2151a542ad1bSJan Schmidt 	if (ret == 1)
2152a542ad1bSJan Schmidt 		*ptr = (unsigned long)-1;
2153a542ad1bSJan Schmidt 
2154a542ad1bSJan Schmidt 	return 0;
2155a542ad1bSJan Schmidt }
2156a542ad1bSJan Schmidt 
2157ab8d0fc4SJeff Mahoney static int iterate_leaf_refs(struct btrfs_fs_info *fs_info,
2158ab8d0fc4SJeff Mahoney 			     struct extent_inode_elem *inode_list,
2159976b1908SJan Schmidt 			     u64 root, u64 extent_item_objectid,
21604692cf58SJan Schmidt 			     iterate_extent_inodes_t *iterate, void *ctx)
2161a542ad1bSJan Schmidt {
2162976b1908SJan Schmidt 	struct extent_inode_elem *eie;
21634692cf58SJan Schmidt 	int ret = 0;
2164a542ad1bSJan Schmidt 
2165976b1908SJan Schmidt 	for (eie = inode_list; eie; eie = eie->next) {
2166ab8d0fc4SJeff Mahoney 		btrfs_debug(fs_info,
2167ab8d0fc4SJeff Mahoney 			    "ref for %llu resolved, key (%llu EXTEND_DATA %llu), root %llu",
2168ab8d0fc4SJeff Mahoney 			    extent_item_objectid, eie->inum,
2169ab8d0fc4SJeff Mahoney 			    eie->offset, root);
2170976b1908SJan Schmidt 		ret = iterate(eie->inum, eie->offset, root, ctx);
21714692cf58SJan Schmidt 		if (ret) {
2172ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_info,
2173ab8d0fc4SJeff Mahoney 				    "stopping iteration for %llu due to ret=%d",
2174976b1908SJan Schmidt 				    extent_item_objectid, ret);
2175a542ad1bSJan Schmidt 			break;
2176a542ad1bSJan Schmidt 		}
2177a542ad1bSJan Schmidt 	}
2178a542ad1bSJan Schmidt 
2179a542ad1bSJan Schmidt 	return ret;
2180a542ad1bSJan Schmidt }
2181a542ad1bSJan Schmidt 
2182a542ad1bSJan Schmidt /*
2183a542ad1bSJan Schmidt  * calls iterate() for every inode that references the extent identified by
21844692cf58SJan Schmidt  * the given parameters.
2185a542ad1bSJan Schmidt  * when the iterator function returns a non-zero value, iteration stops.
2186a542ad1bSJan Schmidt  */
2187a542ad1bSJan Schmidt int iterate_extent_inodes(struct btrfs_fs_info *fs_info,
21884692cf58SJan Schmidt 				u64 extent_item_objectid, u64 extent_item_pos,
21897a3ae2f8SJan Schmidt 				int search_commit_root,
2190c995ab3cSZygo Blaxell 				iterate_extent_inodes_t *iterate, void *ctx,
2191c995ab3cSZygo Blaxell 				bool ignore_offset)
2192a542ad1bSJan Schmidt {
2193a542ad1bSJan Schmidt 	int ret;
2194da61d31aSJosef Bacik 	struct btrfs_trans_handle *trans = NULL;
21957a3ae2f8SJan Schmidt 	struct ulist *refs = NULL;
21967a3ae2f8SJan Schmidt 	struct ulist *roots = NULL;
21974692cf58SJan Schmidt 	struct ulist_node *ref_node = NULL;
21984692cf58SJan Schmidt 	struct ulist_node *root_node = NULL;
2199f3a84ccdSFilipe Manana 	struct btrfs_seq_list seq_elem = BTRFS_SEQ_LIST_INIT(seq_elem);
2200cd1b413cSJan Schmidt 	struct ulist_iterator ref_uiter;
2201cd1b413cSJan Schmidt 	struct ulist_iterator root_uiter;
2202a542ad1bSJan Schmidt 
2203ab8d0fc4SJeff Mahoney 	btrfs_debug(fs_info, "resolving all inodes for extent %llu",
22044692cf58SJan Schmidt 			extent_item_objectid);
22054692cf58SJan Schmidt 
2206da61d31aSJosef Bacik 	if (!search_commit_root) {
220730a9da5dSJosef Bacik 		trans = btrfs_attach_transaction(fs_info->tree_root);
2208bfc61c36SFilipe Manana 		if (IS_ERR(trans)) {
2209bfc61c36SFilipe Manana 			if (PTR_ERR(trans) != -ENOENT &&
2210bfc61c36SFilipe Manana 			    PTR_ERR(trans) != -EROFS)
22117a3ae2f8SJan Schmidt 				return PTR_ERR(trans);
2212bfc61c36SFilipe Manana 			trans = NULL;
22137a3ae2f8SJan Schmidt 		}
2214bfc61c36SFilipe Manana 	}
2215bfc61c36SFilipe Manana 
2216bfc61c36SFilipe Manana 	if (trans)
2217f3a84ccdSFilipe Manana 		btrfs_get_tree_mod_seq(fs_info, &seq_elem);
2218bfc61c36SFilipe Manana 	else
2219bfc61c36SFilipe Manana 		down_read(&fs_info->commit_root_sem);
22204692cf58SJan Schmidt 
22214692cf58SJan Schmidt 	ret = btrfs_find_all_leafs(trans, fs_info, extent_item_objectid,
2222f3a84ccdSFilipe Manana 				   seq_elem.seq, &refs,
2223c995ab3cSZygo Blaxell 				   &extent_item_pos, ignore_offset);
22244692cf58SJan Schmidt 	if (ret)
22254692cf58SJan Schmidt 		goto out;
22264692cf58SJan Schmidt 
2227cd1b413cSJan Schmidt 	ULIST_ITER_INIT(&ref_uiter);
2228cd1b413cSJan Schmidt 	while (!ret && (ref_node = ulist_next(refs, &ref_uiter))) {
2229e0c476b1SJeff Mahoney 		ret = btrfs_find_all_roots_safe(trans, fs_info, ref_node->val,
2230f3a84ccdSFilipe Manana 						seq_elem.seq, &roots,
2231c995ab3cSZygo Blaxell 						ignore_offset);
22324692cf58SJan Schmidt 		if (ret)
2233a542ad1bSJan Schmidt 			break;
2234cd1b413cSJan Schmidt 		ULIST_ITER_INIT(&root_uiter);
2235cd1b413cSJan Schmidt 		while (!ret && (root_node = ulist_next(roots, &root_uiter))) {
2236ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_info,
2237ab8d0fc4SJeff Mahoney 				    "root %llu references leaf %llu, data list %#llx",
2238ab8d0fc4SJeff Mahoney 				    root_node->val, ref_node->val,
2239c1c9ff7cSGeert Uytterhoeven 				    ref_node->aux);
2240ab8d0fc4SJeff Mahoney 			ret = iterate_leaf_refs(fs_info,
2241ab8d0fc4SJeff Mahoney 						(struct extent_inode_elem *)
2242995e01b7SJan Schmidt 						(uintptr_t)ref_node->aux,
2243995e01b7SJan Schmidt 						root_node->val,
2244995e01b7SJan Schmidt 						extent_item_objectid,
2245a542ad1bSJan Schmidt 						iterate, ctx);
22464692cf58SJan Schmidt 		}
2247976b1908SJan Schmidt 		ulist_free(roots);
2248a542ad1bSJan Schmidt 	}
2249a542ad1bSJan Schmidt 
2250976b1908SJan Schmidt 	free_leaf_list(refs);
22514692cf58SJan Schmidt out:
2252bfc61c36SFilipe Manana 	if (trans) {
2253f3a84ccdSFilipe Manana 		btrfs_put_tree_mod_seq(fs_info, &seq_elem);
22543a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
22559e351cc8SJosef Bacik 	} else {
22569e351cc8SJosef Bacik 		up_read(&fs_info->commit_root_sem);
22577a3ae2f8SJan Schmidt 	}
22587a3ae2f8SJan Schmidt 
2259a542ad1bSJan Schmidt 	return ret;
2260a542ad1bSJan Schmidt }
2261a542ad1bSJan Schmidt 
2262e3059ec0SDavid Sterba static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
2263e3059ec0SDavid Sterba {
2264e3059ec0SDavid Sterba 	struct btrfs_data_container *inodes = ctx;
2265e3059ec0SDavid Sterba 	const size_t c = 3 * sizeof(u64);
2266e3059ec0SDavid Sterba 
2267e3059ec0SDavid Sterba 	if (inodes->bytes_left >= c) {
2268e3059ec0SDavid Sterba 		inodes->bytes_left -= c;
2269e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt] = inum;
2270e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt + 1] = offset;
2271e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt + 2] = root;
2272e3059ec0SDavid Sterba 		inodes->elem_cnt += 3;
2273e3059ec0SDavid Sterba 	} else {
2274e3059ec0SDavid Sterba 		inodes->bytes_missing += c - inodes->bytes_left;
2275e3059ec0SDavid Sterba 		inodes->bytes_left = 0;
2276e3059ec0SDavid Sterba 		inodes->elem_missed += 3;
2277e3059ec0SDavid Sterba 	}
2278e3059ec0SDavid Sterba 
2279e3059ec0SDavid Sterba 	return 0;
2280e3059ec0SDavid Sterba }
2281e3059ec0SDavid Sterba 
2282a542ad1bSJan Schmidt int iterate_inodes_from_logical(u64 logical, struct btrfs_fs_info *fs_info,
2283a542ad1bSJan Schmidt 				struct btrfs_path *path,
2284e3059ec0SDavid Sterba 				void *ctx, bool ignore_offset)
2285a542ad1bSJan Schmidt {
2286a542ad1bSJan Schmidt 	int ret;
22874692cf58SJan Schmidt 	u64 extent_item_pos;
228869917e43SLiu Bo 	u64 flags = 0;
2289a542ad1bSJan Schmidt 	struct btrfs_key found_key;
22907a3ae2f8SJan Schmidt 	int search_commit_root = path->search_commit_root;
2291a542ad1bSJan Schmidt 
229269917e43SLiu Bo 	ret = extent_from_logical(fs_info, logical, path, &found_key, &flags);
22934692cf58SJan Schmidt 	btrfs_release_path(path);
2294a542ad1bSJan Schmidt 	if (ret < 0)
2295a542ad1bSJan Schmidt 		return ret;
229669917e43SLiu Bo 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
22973627bf45SStefan Behrens 		return -EINVAL;
2298a542ad1bSJan Schmidt 
22994692cf58SJan Schmidt 	extent_item_pos = logical - found_key.objectid;
23007a3ae2f8SJan Schmidt 	ret = iterate_extent_inodes(fs_info, found_key.objectid,
23017a3ae2f8SJan Schmidt 					extent_item_pos, search_commit_root,
2302e3059ec0SDavid Sterba 					build_ino_list, ctx, ignore_offset);
2303a542ad1bSJan Schmidt 
2304a542ad1bSJan Schmidt 	return ret;
2305a542ad1bSJan Schmidt }
2306a542ad1bSJan Schmidt 
2307ad6240f6SDavid Sterba static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2308875d1daaSDavid Sterba 			 struct extent_buffer *eb, struct inode_fs_paths *ipath);
2309d24bec3aSMark Fasheh 
2310875d1daaSDavid Sterba static int iterate_inode_refs(u64 inum, struct inode_fs_paths *ipath)
2311a542ad1bSJan Schmidt {
2312aefc1eb1SJan Schmidt 	int ret = 0;
2313a542ad1bSJan Schmidt 	int slot;
2314a542ad1bSJan Schmidt 	u32 cur;
2315a542ad1bSJan Schmidt 	u32 len;
2316a542ad1bSJan Schmidt 	u32 name_len;
2317a542ad1bSJan Schmidt 	u64 parent = 0;
2318a542ad1bSJan Schmidt 	int found = 0;
2319875d1daaSDavid Sterba 	struct btrfs_root *fs_root = ipath->fs_root;
2320875d1daaSDavid Sterba 	struct btrfs_path *path = ipath->btrfs_path;
2321a542ad1bSJan Schmidt 	struct extent_buffer *eb;
2322a542ad1bSJan Schmidt 	struct btrfs_inode_ref *iref;
2323a542ad1bSJan Schmidt 	struct btrfs_key found_key;
2324a542ad1bSJan Schmidt 
2325aefc1eb1SJan Schmidt 	while (!ret) {
2326c234a24dSDavid Sterba 		ret = btrfs_find_item(fs_root, path, inum,
2327c234a24dSDavid Sterba 				parent ? parent + 1 : 0, BTRFS_INODE_REF_KEY,
2328a542ad1bSJan Schmidt 				&found_key);
2329c234a24dSDavid Sterba 
2330a542ad1bSJan Schmidt 		if (ret < 0)
2331a542ad1bSJan Schmidt 			break;
2332a542ad1bSJan Schmidt 		if (ret) {
2333a542ad1bSJan Schmidt 			ret = found ? 0 : -ENOENT;
2334a542ad1bSJan Schmidt 			break;
2335a542ad1bSJan Schmidt 		}
2336a542ad1bSJan Schmidt 		++found;
2337a542ad1bSJan Schmidt 
2338a542ad1bSJan Schmidt 		parent = found_key.offset;
2339a542ad1bSJan Schmidt 		slot = path->slots[0];
23403fe81ce2SFilipe David Borba Manana 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
23413fe81ce2SFilipe David Borba Manana 		if (!eb) {
23423fe81ce2SFilipe David Borba Manana 			ret = -ENOMEM;
23433fe81ce2SFilipe David Borba Manana 			break;
23443fe81ce2SFilipe David Borba Manana 		}
2345a542ad1bSJan Schmidt 		btrfs_release_path(path);
2346a542ad1bSJan Schmidt 
2347a542ad1bSJan Schmidt 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2348a542ad1bSJan Schmidt 
23493212fa14SJosef Bacik 		for (cur = 0; cur < btrfs_item_size(eb, slot); cur += len) {
2350a542ad1bSJan Schmidt 			name_len = btrfs_inode_ref_name_len(eb, iref);
2351a542ad1bSJan Schmidt 			/* path must be released before calling iterate()! */
2352ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_root->fs_info,
2353ab8d0fc4SJeff Mahoney 				"following ref at offset %u for inode %llu in tree %llu",
23544fd786e6SMisono Tomohiro 				cur, found_key.objectid,
23554fd786e6SMisono Tomohiro 				fs_root->root_key.objectid);
2356ad6240f6SDavid Sterba 			ret = inode_to_path(parent, name_len,
2357875d1daaSDavid Sterba 				      (unsigned long)(iref + 1), eb, ipath);
2358aefc1eb1SJan Schmidt 			if (ret)
2359a542ad1bSJan Schmidt 				break;
2360a542ad1bSJan Schmidt 			len = sizeof(*iref) + name_len;
2361a542ad1bSJan Schmidt 			iref = (struct btrfs_inode_ref *)((char *)iref + len);
2362a542ad1bSJan Schmidt 		}
2363a542ad1bSJan Schmidt 		free_extent_buffer(eb);
2364a542ad1bSJan Schmidt 	}
2365a542ad1bSJan Schmidt 
2366a542ad1bSJan Schmidt 	btrfs_release_path(path);
2367a542ad1bSJan Schmidt 
2368a542ad1bSJan Schmidt 	return ret;
2369a542ad1bSJan Schmidt }
2370a542ad1bSJan Schmidt 
2371875d1daaSDavid Sterba static int iterate_inode_extrefs(u64 inum, struct inode_fs_paths *ipath)
2372d24bec3aSMark Fasheh {
2373d24bec3aSMark Fasheh 	int ret;
2374d24bec3aSMark Fasheh 	int slot;
2375d24bec3aSMark Fasheh 	u64 offset = 0;
2376d24bec3aSMark Fasheh 	u64 parent;
2377d24bec3aSMark Fasheh 	int found = 0;
2378875d1daaSDavid Sterba 	struct btrfs_root *fs_root = ipath->fs_root;
2379875d1daaSDavid Sterba 	struct btrfs_path *path = ipath->btrfs_path;
2380d24bec3aSMark Fasheh 	struct extent_buffer *eb;
2381d24bec3aSMark Fasheh 	struct btrfs_inode_extref *extref;
2382d24bec3aSMark Fasheh 	u32 item_size;
2383d24bec3aSMark Fasheh 	u32 cur_offset;
2384d24bec3aSMark Fasheh 	unsigned long ptr;
2385d24bec3aSMark Fasheh 
2386d24bec3aSMark Fasheh 	while (1) {
2387d24bec3aSMark Fasheh 		ret = btrfs_find_one_extref(fs_root, inum, offset, path, &extref,
2388d24bec3aSMark Fasheh 					    &offset);
2389d24bec3aSMark Fasheh 		if (ret < 0)
2390d24bec3aSMark Fasheh 			break;
2391d24bec3aSMark Fasheh 		if (ret) {
2392d24bec3aSMark Fasheh 			ret = found ? 0 : -ENOENT;
2393d24bec3aSMark Fasheh 			break;
2394d24bec3aSMark Fasheh 		}
2395d24bec3aSMark Fasheh 		++found;
2396d24bec3aSMark Fasheh 
2397d24bec3aSMark Fasheh 		slot = path->slots[0];
23983fe81ce2SFilipe David Borba Manana 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
23993fe81ce2SFilipe David Borba Manana 		if (!eb) {
24003fe81ce2SFilipe David Borba Manana 			ret = -ENOMEM;
24013fe81ce2SFilipe David Borba Manana 			break;
24023fe81ce2SFilipe David Borba Manana 		}
2403d24bec3aSMark Fasheh 		btrfs_release_path(path);
2404d24bec3aSMark Fasheh 
24053212fa14SJosef Bacik 		item_size = btrfs_item_size(eb, slot);
24062849a854SChris Mason 		ptr = btrfs_item_ptr_offset(eb, slot);
2407d24bec3aSMark Fasheh 		cur_offset = 0;
2408d24bec3aSMark Fasheh 
2409d24bec3aSMark Fasheh 		while (cur_offset < item_size) {
2410d24bec3aSMark Fasheh 			u32 name_len;
2411d24bec3aSMark Fasheh 
2412d24bec3aSMark Fasheh 			extref = (struct btrfs_inode_extref *)(ptr + cur_offset);
2413d24bec3aSMark Fasheh 			parent = btrfs_inode_extref_parent(eb, extref);
2414d24bec3aSMark Fasheh 			name_len = btrfs_inode_extref_name_len(eb, extref);
2415ad6240f6SDavid Sterba 			ret = inode_to_path(parent, name_len,
2416875d1daaSDavid Sterba 				      (unsigned long)&extref->name, eb, ipath);
2417d24bec3aSMark Fasheh 			if (ret)
2418d24bec3aSMark Fasheh 				break;
2419d24bec3aSMark Fasheh 
24202849a854SChris Mason 			cur_offset += btrfs_inode_extref_name_len(eb, extref);
2421d24bec3aSMark Fasheh 			cur_offset += sizeof(*extref);
2422d24bec3aSMark Fasheh 		}
2423d24bec3aSMark Fasheh 		free_extent_buffer(eb);
2424d24bec3aSMark Fasheh 
2425d24bec3aSMark Fasheh 		offset++;
2426d24bec3aSMark Fasheh 	}
2427d24bec3aSMark Fasheh 
2428d24bec3aSMark Fasheh 	btrfs_release_path(path);
2429d24bec3aSMark Fasheh 
2430d24bec3aSMark Fasheh 	return ret;
2431d24bec3aSMark Fasheh }
2432d24bec3aSMark Fasheh 
2433a542ad1bSJan Schmidt /*
2434a542ad1bSJan Schmidt  * returns 0 if the path could be dumped (probably truncated)
2435a542ad1bSJan Schmidt  * returns <0 in case of an error
2436a542ad1bSJan Schmidt  */
2437d24bec3aSMark Fasheh static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2438875d1daaSDavid Sterba 			 struct extent_buffer *eb, struct inode_fs_paths *ipath)
2439a542ad1bSJan Schmidt {
2440a542ad1bSJan Schmidt 	char *fspath;
2441a542ad1bSJan Schmidt 	char *fspath_min;
2442a542ad1bSJan Schmidt 	int i = ipath->fspath->elem_cnt;
2443a542ad1bSJan Schmidt 	const int s_ptr = sizeof(char *);
2444a542ad1bSJan Schmidt 	u32 bytes_left;
2445a542ad1bSJan Schmidt 
2446a542ad1bSJan Schmidt 	bytes_left = ipath->fspath->bytes_left > s_ptr ?
2447a542ad1bSJan Schmidt 					ipath->fspath->bytes_left - s_ptr : 0;
2448a542ad1bSJan Schmidt 
2449740c3d22SChris Mason 	fspath_min = (char *)ipath->fspath->val + (i + 1) * s_ptr;
245096b5bd77SJan Schmidt 	fspath = btrfs_ref_to_path(ipath->fs_root, ipath->btrfs_path, name_len,
245196b5bd77SJan Schmidt 				   name_off, eb, inum, fspath_min, bytes_left);
2452a542ad1bSJan Schmidt 	if (IS_ERR(fspath))
2453a542ad1bSJan Schmidt 		return PTR_ERR(fspath);
2454a542ad1bSJan Schmidt 
2455a542ad1bSJan Schmidt 	if (fspath > fspath_min) {
2456745c4d8eSJeff Mahoney 		ipath->fspath->val[i] = (u64)(unsigned long)fspath;
2457a542ad1bSJan Schmidt 		++ipath->fspath->elem_cnt;
2458a542ad1bSJan Schmidt 		ipath->fspath->bytes_left = fspath - fspath_min;
2459a542ad1bSJan Schmidt 	} else {
2460a542ad1bSJan Schmidt 		++ipath->fspath->elem_missed;
2461a542ad1bSJan Schmidt 		ipath->fspath->bytes_missing += fspath_min - fspath;
2462a542ad1bSJan Schmidt 		ipath->fspath->bytes_left = 0;
2463a542ad1bSJan Schmidt 	}
2464a542ad1bSJan Schmidt 
2465a542ad1bSJan Schmidt 	return 0;
2466a542ad1bSJan Schmidt }
2467a542ad1bSJan Schmidt 
2468a542ad1bSJan Schmidt /*
2469a542ad1bSJan Schmidt  * this dumps all file system paths to the inode into the ipath struct, provided
2470a542ad1bSJan Schmidt  * is has been created large enough. each path is zero-terminated and accessed
2471740c3d22SChris Mason  * from ipath->fspath->val[i].
2472a542ad1bSJan Schmidt  * when it returns, there are ipath->fspath->elem_cnt number of paths available
2473740c3d22SChris Mason  * in ipath->fspath->val[]. when the allocated space wasn't sufficient, the
247401327610SNicholas D Steeves  * number of missed paths is recorded in ipath->fspath->elem_missed, otherwise,
2475a542ad1bSJan Schmidt  * it's zero. ipath->fspath->bytes_missing holds the number of bytes that would
2476a542ad1bSJan Schmidt  * have been needed to return all paths.
2477a542ad1bSJan Schmidt  */
2478a542ad1bSJan Schmidt int paths_from_inode(u64 inum, struct inode_fs_paths *ipath)
2479a542ad1bSJan Schmidt {
2480ad6240f6SDavid Sterba 	int ret;
2481ad6240f6SDavid Sterba 	int found_refs = 0;
2482ad6240f6SDavid Sterba 
2483875d1daaSDavid Sterba 	ret = iterate_inode_refs(inum, ipath);
2484ad6240f6SDavid Sterba 	if (!ret)
2485ad6240f6SDavid Sterba 		++found_refs;
2486ad6240f6SDavid Sterba 	else if (ret != -ENOENT)
2487ad6240f6SDavid Sterba 		return ret;
2488ad6240f6SDavid Sterba 
2489875d1daaSDavid Sterba 	ret = iterate_inode_extrefs(inum, ipath);
2490ad6240f6SDavid Sterba 	if (ret == -ENOENT && found_refs)
2491ad6240f6SDavid Sterba 		return 0;
2492ad6240f6SDavid Sterba 
2493ad6240f6SDavid Sterba 	return ret;
2494a542ad1bSJan Schmidt }
2495a542ad1bSJan Schmidt 
2496a542ad1bSJan Schmidt struct btrfs_data_container *init_data_container(u32 total_bytes)
2497a542ad1bSJan Schmidt {
2498a542ad1bSJan Schmidt 	struct btrfs_data_container *data;
2499a542ad1bSJan Schmidt 	size_t alloc_bytes;
2500a542ad1bSJan Schmidt 
2501a542ad1bSJan Schmidt 	alloc_bytes = max_t(size_t, total_bytes, sizeof(*data));
2502f54de068SDavid Sterba 	data = kvmalloc(alloc_bytes, GFP_KERNEL);
2503a542ad1bSJan Schmidt 	if (!data)
2504a542ad1bSJan Schmidt 		return ERR_PTR(-ENOMEM);
2505a542ad1bSJan Schmidt 
2506a542ad1bSJan Schmidt 	if (total_bytes >= sizeof(*data)) {
2507a542ad1bSJan Schmidt 		data->bytes_left = total_bytes - sizeof(*data);
2508a542ad1bSJan Schmidt 		data->bytes_missing = 0;
2509a542ad1bSJan Schmidt 	} else {
2510a542ad1bSJan Schmidt 		data->bytes_missing = sizeof(*data) - total_bytes;
2511a542ad1bSJan Schmidt 		data->bytes_left = 0;
2512a542ad1bSJan Schmidt 	}
2513a542ad1bSJan Schmidt 
2514a542ad1bSJan Schmidt 	data->elem_cnt = 0;
2515a542ad1bSJan Schmidt 	data->elem_missed = 0;
2516a542ad1bSJan Schmidt 
2517a542ad1bSJan Schmidt 	return data;
2518a542ad1bSJan Schmidt }
2519a542ad1bSJan Schmidt 
2520a542ad1bSJan Schmidt /*
2521a542ad1bSJan Schmidt  * allocates space to return multiple file system paths for an inode.
2522a542ad1bSJan Schmidt  * total_bytes to allocate are passed, note that space usable for actual path
2523a542ad1bSJan Schmidt  * information will be total_bytes - sizeof(struct inode_fs_paths).
2524a542ad1bSJan Schmidt  * the returned pointer must be freed with free_ipath() in the end.
2525a542ad1bSJan Schmidt  */
2526a542ad1bSJan Schmidt struct inode_fs_paths *init_ipath(s32 total_bytes, struct btrfs_root *fs_root,
2527a542ad1bSJan Schmidt 					struct btrfs_path *path)
2528a542ad1bSJan Schmidt {
2529a542ad1bSJan Schmidt 	struct inode_fs_paths *ifp;
2530a542ad1bSJan Schmidt 	struct btrfs_data_container *fspath;
2531a542ad1bSJan Schmidt 
2532a542ad1bSJan Schmidt 	fspath = init_data_container(total_bytes);
2533a542ad1bSJan Schmidt 	if (IS_ERR(fspath))
2534afc6961fSMisono Tomohiro 		return ERR_CAST(fspath);
2535a542ad1bSJan Schmidt 
2536f54de068SDavid Sterba 	ifp = kmalloc(sizeof(*ifp), GFP_KERNEL);
2537a542ad1bSJan Schmidt 	if (!ifp) {
2538f54de068SDavid Sterba 		kvfree(fspath);
2539a542ad1bSJan Schmidt 		return ERR_PTR(-ENOMEM);
2540a542ad1bSJan Schmidt 	}
2541a542ad1bSJan Schmidt 
2542a542ad1bSJan Schmidt 	ifp->btrfs_path = path;
2543a542ad1bSJan Schmidt 	ifp->fspath = fspath;
2544a542ad1bSJan Schmidt 	ifp->fs_root = fs_root;
2545a542ad1bSJan Schmidt 
2546a542ad1bSJan Schmidt 	return ifp;
2547a542ad1bSJan Schmidt }
2548a542ad1bSJan Schmidt 
2549a542ad1bSJan Schmidt void free_ipath(struct inode_fs_paths *ipath)
2550a542ad1bSJan Schmidt {
25514735fb28SJesper Juhl 	if (!ipath)
25524735fb28SJesper Juhl 		return;
2553f54de068SDavid Sterba 	kvfree(ipath->fspath);
2554a542ad1bSJan Schmidt 	kfree(ipath);
2555a542ad1bSJan Schmidt }
2556a37f232bSQu Wenruo 
2557a37f232bSQu Wenruo struct btrfs_backref_iter *btrfs_backref_iter_alloc(
2558a37f232bSQu Wenruo 		struct btrfs_fs_info *fs_info, gfp_t gfp_flag)
2559a37f232bSQu Wenruo {
2560a37f232bSQu Wenruo 	struct btrfs_backref_iter *ret;
2561a37f232bSQu Wenruo 
2562a37f232bSQu Wenruo 	ret = kzalloc(sizeof(*ret), gfp_flag);
2563a37f232bSQu Wenruo 	if (!ret)
2564a37f232bSQu Wenruo 		return NULL;
2565a37f232bSQu Wenruo 
2566a37f232bSQu Wenruo 	ret->path = btrfs_alloc_path();
2567c15c2ec0SBoleyn Su 	if (!ret->path) {
2568a37f232bSQu Wenruo 		kfree(ret);
2569a37f232bSQu Wenruo 		return NULL;
2570a37f232bSQu Wenruo 	}
2571a37f232bSQu Wenruo 
2572a37f232bSQu Wenruo 	/* Current backref iterator only supports iteration in commit root */
2573a37f232bSQu Wenruo 	ret->path->search_commit_root = 1;
2574a37f232bSQu Wenruo 	ret->path->skip_locking = 1;
2575a37f232bSQu Wenruo 	ret->fs_info = fs_info;
2576a37f232bSQu Wenruo 
2577a37f232bSQu Wenruo 	return ret;
2578a37f232bSQu Wenruo }
2579a37f232bSQu Wenruo 
2580a37f232bSQu Wenruo int btrfs_backref_iter_start(struct btrfs_backref_iter *iter, u64 bytenr)
2581a37f232bSQu Wenruo {
2582a37f232bSQu Wenruo 	struct btrfs_fs_info *fs_info = iter->fs_info;
258329cbcf40SJosef Bacik 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2584a37f232bSQu Wenruo 	struct btrfs_path *path = iter->path;
2585a37f232bSQu Wenruo 	struct btrfs_extent_item *ei;
2586a37f232bSQu Wenruo 	struct btrfs_key key;
2587a37f232bSQu Wenruo 	int ret;
2588a37f232bSQu Wenruo 
2589a37f232bSQu Wenruo 	key.objectid = bytenr;
2590a37f232bSQu Wenruo 	key.type = BTRFS_METADATA_ITEM_KEY;
2591a37f232bSQu Wenruo 	key.offset = (u64)-1;
2592a37f232bSQu Wenruo 	iter->bytenr = bytenr;
2593a37f232bSQu Wenruo 
259429cbcf40SJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2595a37f232bSQu Wenruo 	if (ret < 0)
2596a37f232bSQu Wenruo 		return ret;
2597a37f232bSQu Wenruo 	if (ret == 0) {
2598a37f232bSQu Wenruo 		ret = -EUCLEAN;
2599a37f232bSQu Wenruo 		goto release;
2600a37f232bSQu Wenruo 	}
2601a37f232bSQu Wenruo 	if (path->slots[0] == 0) {
2602a37f232bSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
2603a37f232bSQu Wenruo 		ret = -EUCLEAN;
2604a37f232bSQu Wenruo 		goto release;
2605a37f232bSQu Wenruo 	}
2606a37f232bSQu Wenruo 	path->slots[0]--;
2607a37f232bSQu Wenruo 
2608a37f232bSQu Wenruo 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2609a37f232bSQu Wenruo 	if ((key.type != BTRFS_EXTENT_ITEM_KEY &&
2610a37f232bSQu Wenruo 	     key.type != BTRFS_METADATA_ITEM_KEY) || key.objectid != bytenr) {
2611a37f232bSQu Wenruo 		ret = -ENOENT;
2612a37f232bSQu Wenruo 		goto release;
2613a37f232bSQu Wenruo 	}
2614a37f232bSQu Wenruo 	memcpy(&iter->cur_key, &key, sizeof(key));
2615a37f232bSQu Wenruo 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2616a37f232bSQu Wenruo 						    path->slots[0]);
2617a37f232bSQu Wenruo 	iter->end_ptr = (u32)(iter->item_ptr +
26183212fa14SJosef Bacik 			btrfs_item_size(path->nodes[0], path->slots[0]));
2619a37f232bSQu Wenruo 	ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
2620a37f232bSQu Wenruo 			    struct btrfs_extent_item);
2621a37f232bSQu Wenruo 
2622a37f232bSQu Wenruo 	/*
2623a37f232bSQu Wenruo 	 * Only support iteration on tree backref yet.
2624a37f232bSQu Wenruo 	 *
2625a37f232bSQu Wenruo 	 * This is an extra precaution for non skinny-metadata, where
2626a37f232bSQu Wenruo 	 * EXTENT_ITEM is also used for tree blocks, that we can only use
2627a37f232bSQu Wenruo 	 * extent flags to determine if it's a tree block.
2628a37f232bSQu Wenruo 	 */
2629a37f232bSQu Wenruo 	if (btrfs_extent_flags(path->nodes[0], ei) & BTRFS_EXTENT_FLAG_DATA) {
2630a37f232bSQu Wenruo 		ret = -ENOTSUPP;
2631a37f232bSQu Wenruo 		goto release;
2632a37f232bSQu Wenruo 	}
2633a37f232bSQu Wenruo 	iter->cur_ptr = (u32)(iter->item_ptr + sizeof(*ei));
2634a37f232bSQu Wenruo 
2635a37f232bSQu Wenruo 	/* If there is no inline backref, go search for keyed backref */
2636a37f232bSQu Wenruo 	if (iter->cur_ptr >= iter->end_ptr) {
263729cbcf40SJosef Bacik 		ret = btrfs_next_item(extent_root, path);
2638a37f232bSQu Wenruo 
2639a37f232bSQu Wenruo 		/* No inline nor keyed ref */
2640a37f232bSQu Wenruo 		if (ret > 0) {
2641a37f232bSQu Wenruo 			ret = -ENOENT;
2642a37f232bSQu Wenruo 			goto release;
2643a37f232bSQu Wenruo 		}
2644a37f232bSQu Wenruo 		if (ret < 0)
2645a37f232bSQu Wenruo 			goto release;
2646a37f232bSQu Wenruo 
2647a37f232bSQu Wenruo 		btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key,
2648a37f232bSQu Wenruo 				path->slots[0]);
2649a37f232bSQu Wenruo 		if (iter->cur_key.objectid != bytenr ||
2650a37f232bSQu Wenruo 		    (iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
2651a37f232bSQu Wenruo 		     iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY)) {
2652a37f232bSQu Wenruo 			ret = -ENOENT;
2653a37f232bSQu Wenruo 			goto release;
2654a37f232bSQu Wenruo 		}
2655a37f232bSQu Wenruo 		iter->cur_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2656a37f232bSQu Wenruo 							   path->slots[0]);
2657a37f232bSQu Wenruo 		iter->item_ptr = iter->cur_ptr;
26583212fa14SJosef Bacik 		iter->end_ptr = (u32)(iter->item_ptr + btrfs_item_size(
2659a37f232bSQu Wenruo 				      path->nodes[0], path->slots[0]));
2660a37f232bSQu Wenruo 	}
2661a37f232bSQu Wenruo 
2662a37f232bSQu Wenruo 	return 0;
2663a37f232bSQu Wenruo release:
2664a37f232bSQu Wenruo 	btrfs_backref_iter_release(iter);
2665a37f232bSQu Wenruo 	return ret;
2666a37f232bSQu Wenruo }
2667c39c2ddcSQu Wenruo 
2668c39c2ddcSQu Wenruo /*
2669c39c2ddcSQu Wenruo  * Go to the next backref item of current bytenr, can be either inlined or
2670c39c2ddcSQu Wenruo  * keyed.
2671c39c2ddcSQu Wenruo  *
2672c39c2ddcSQu Wenruo  * Caller needs to check whether it's inline ref or not by iter->cur_key.
2673c39c2ddcSQu Wenruo  *
2674c39c2ddcSQu Wenruo  * Return 0 if we get next backref without problem.
2675c39c2ddcSQu Wenruo  * Return >0 if there is no extra backref for this bytenr.
2676c39c2ddcSQu Wenruo  * Return <0 if there is something wrong happened.
2677c39c2ddcSQu Wenruo  */
2678c39c2ddcSQu Wenruo int btrfs_backref_iter_next(struct btrfs_backref_iter *iter)
2679c39c2ddcSQu Wenruo {
2680c39c2ddcSQu Wenruo 	struct extent_buffer *eb = btrfs_backref_get_eb(iter);
268129cbcf40SJosef Bacik 	struct btrfs_root *extent_root;
2682c39c2ddcSQu Wenruo 	struct btrfs_path *path = iter->path;
2683c39c2ddcSQu Wenruo 	struct btrfs_extent_inline_ref *iref;
2684c39c2ddcSQu Wenruo 	int ret;
2685c39c2ddcSQu Wenruo 	u32 size;
2686c39c2ddcSQu Wenruo 
2687c39c2ddcSQu Wenruo 	if (btrfs_backref_iter_is_inline_ref(iter)) {
2688c39c2ddcSQu Wenruo 		/* We're still inside the inline refs */
2689c39c2ddcSQu Wenruo 		ASSERT(iter->cur_ptr < iter->end_ptr);
2690c39c2ddcSQu Wenruo 
2691c39c2ddcSQu Wenruo 		if (btrfs_backref_has_tree_block_info(iter)) {
2692c39c2ddcSQu Wenruo 			/* First tree block info */
2693c39c2ddcSQu Wenruo 			size = sizeof(struct btrfs_tree_block_info);
2694c39c2ddcSQu Wenruo 		} else {
2695c39c2ddcSQu Wenruo 			/* Use inline ref type to determine the size */
2696c39c2ddcSQu Wenruo 			int type;
2697c39c2ddcSQu Wenruo 
2698c39c2ddcSQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
2699c39c2ddcSQu Wenruo 				((unsigned long)iter->cur_ptr);
2700c39c2ddcSQu Wenruo 			type = btrfs_extent_inline_ref_type(eb, iref);
2701c39c2ddcSQu Wenruo 
2702c39c2ddcSQu Wenruo 			size = btrfs_extent_inline_ref_size(type);
2703c39c2ddcSQu Wenruo 		}
2704c39c2ddcSQu Wenruo 		iter->cur_ptr += size;
2705c39c2ddcSQu Wenruo 		if (iter->cur_ptr < iter->end_ptr)
2706c39c2ddcSQu Wenruo 			return 0;
2707c39c2ddcSQu Wenruo 
2708c39c2ddcSQu Wenruo 		/* All inline items iterated, fall through */
2709c39c2ddcSQu Wenruo 	}
2710c39c2ddcSQu Wenruo 
2711c39c2ddcSQu Wenruo 	/* We're at keyed items, there is no inline item, go to the next one */
271229cbcf40SJosef Bacik 	extent_root = btrfs_extent_root(iter->fs_info, iter->bytenr);
271329cbcf40SJosef Bacik 	ret = btrfs_next_item(extent_root, iter->path);
2714c39c2ddcSQu Wenruo 	if (ret)
2715c39c2ddcSQu Wenruo 		return ret;
2716c39c2ddcSQu Wenruo 
2717c39c2ddcSQu Wenruo 	btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key, path->slots[0]);
2718c39c2ddcSQu Wenruo 	if (iter->cur_key.objectid != iter->bytenr ||
2719c39c2ddcSQu Wenruo 	    (iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
2720c39c2ddcSQu Wenruo 	     iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY))
2721c39c2ddcSQu Wenruo 		return 1;
2722c39c2ddcSQu Wenruo 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2723c39c2ddcSQu Wenruo 					path->slots[0]);
2724c39c2ddcSQu Wenruo 	iter->cur_ptr = iter->item_ptr;
27253212fa14SJosef Bacik 	iter->end_ptr = iter->item_ptr + (u32)btrfs_item_size(path->nodes[0],
2726c39c2ddcSQu Wenruo 						path->slots[0]);
2727c39c2ddcSQu Wenruo 	return 0;
2728c39c2ddcSQu Wenruo }
2729584fb121SQu Wenruo 
2730584fb121SQu Wenruo void btrfs_backref_init_cache(struct btrfs_fs_info *fs_info,
2731584fb121SQu Wenruo 			      struct btrfs_backref_cache *cache, int is_reloc)
2732584fb121SQu Wenruo {
2733584fb121SQu Wenruo 	int i;
2734584fb121SQu Wenruo 
2735584fb121SQu Wenruo 	cache->rb_root = RB_ROOT;
2736584fb121SQu Wenruo 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
2737584fb121SQu Wenruo 		INIT_LIST_HEAD(&cache->pending[i]);
2738584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->changed);
2739584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->detached);
2740584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->leaves);
2741584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->pending_edge);
2742584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->useless_node);
2743584fb121SQu Wenruo 	cache->fs_info = fs_info;
2744584fb121SQu Wenruo 	cache->is_reloc = is_reloc;
2745584fb121SQu Wenruo }
2746b1818dabSQu Wenruo 
2747b1818dabSQu Wenruo struct btrfs_backref_node *btrfs_backref_alloc_node(
2748b1818dabSQu Wenruo 		struct btrfs_backref_cache *cache, u64 bytenr, int level)
2749b1818dabSQu Wenruo {
2750b1818dabSQu Wenruo 	struct btrfs_backref_node *node;
2751b1818dabSQu Wenruo 
2752b1818dabSQu Wenruo 	ASSERT(level >= 0 && level < BTRFS_MAX_LEVEL);
2753b1818dabSQu Wenruo 	node = kzalloc(sizeof(*node), GFP_NOFS);
2754b1818dabSQu Wenruo 	if (!node)
2755b1818dabSQu Wenruo 		return node;
2756b1818dabSQu Wenruo 
2757b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->list);
2758b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->upper);
2759b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->lower);
2760b1818dabSQu Wenruo 	RB_CLEAR_NODE(&node->rb_node);
2761b1818dabSQu Wenruo 	cache->nr_nodes++;
2762b1818dabSQu Wenruo 	node->level = level;
2763b1818dabSQu Wenruo 	node->bytenr = bytenr;
2764b1818dabSQu Wenruo 
2765b1818dabSQu Wenruo 	return node;
2766b1818dabSQu Wenruo }
276747254d07SQu Wenruo 
276847254d07SQu Wenruo struct btrfs_backref_edge *btrfs_backref_alloc_edge(
276947254d07SQu Wenruo 		struct btrfs_backref_cache *cache)
277047254d07SQu Wenruo {
277147254d07SQu Wenruo 	struct btrfs_backref_edge *edge;
277247254d07SQu Wenruo 
277347254d07SQu Wenruo 	edge = kzalloc(sizeof(*edge), GFP_NOFS);
277447254d07SQu Wenruo 	if (edge)
277547254d07SQu Wenruo 		cache->nr_edges++;
277647254d07SQu Wenruo 	return edge;
277747254d07SQu Wenruo }
2778023acb07SQu Wenruo 
2779023acb07SQu Wenruo /*
2780023acb07SQu Wenruo  * Drop the backref node from cache, also cleaning up all its
2781023acb07SQu Wenruo  * upper edges and any uncached nodes in the path.
2782023acb07SQu Wenruo  *
2783023acb07SQu Wenruo  * This cleanup happens bottom up, thus the node should either
2784023acb07SQu Wenruo  * be the lowest node in the cache or a detached node.
2785023acb07SQu Wenruo  */
2786023acb07SQu Wenruo void btrfs_backref_cleanup_node(struct btrfs_backref_cache *cache,
2787023acb07SQu Wenruo 				struct btrfs_backref_node *node)
2788023acb07SQu Wenruo {
2789023acb07SQu Wenruo 	struct btrfs_backref_node *upper;
2790023acb07SQu Wenruo 	struct btrfs_backref_edge *edge;
2791023acb07SQu Wenruo 
2792023acb07SQu Wenruo 	if (!node)
2793023acb07SQu Wenruo 		return;
2794023acb07SQu Wenruo 
2795023acb07SQu Wenruo 	BUG_ON(!node->lowest && !node->detached);
2796023acb07SQu Wenruo 	while (!list_empty(&node->upper)) {
2797023acb07SQu Wenruo 		edge = list_entry(node->upper.next, struct btrfs_backref_edge,
2798023acb07SQu Wenruo 				  list[LOWER]);
2799023acb07SQu Wenruo 		upper = edge->node[UPPER];
2800023acb07SQu Wenruo 		list_del(&edge->list[LOWER]);
2801023acb07SQu Wenruo 		list_del(&edge->list[UPPER]);
2802023acb07SQu Wenruo 		btrfs_backref_free_edge(cache, edge);
2803023acb07SQu Wenruo 
2804023acb07SQu Wenruo 		/*
2805023acb07SQu Wenruo 		 * Add the node to leaf node list if no other child block
2806023acb07SQu Wenruo 		 * cached.
2807023acb07SQu Wenruo 		 */
2808023acb07SQu Wenruo 		if (list_empty(&upper->lower)) {
2809023acb07SQu Wenruo 			list_add_tail(&upper->lower, &cache->leaves);
2810023acb07SQu Wenruo 			upper->lowest = 1;
2811023acb07SQu Wenruo 		}
2812023acb07SQu Wenruo 	}
2813023acb07SQu Wenruo 
2814023acb07SQu Wenruo 	btrfs_backref_drop_node(cache, node);
2815023acb07SQu Wenruo }
281613fe1bdbSQu Wenruo 
281713fe1bdbSQu Wenruo /*
281813fe1bdbSQu Wenruo  * Release all nodes/edges from current cache
281913fe1bdbSQu Wenruo  */
282013fe1bdbSQu Wenruo void btrfs_backref_release_cache(struct btrfs_backref_cache *cache)
282113fe1bdbSQu Wenruo {
282213fe1bdbSQu Wenruo 	struct btrfs_backref_node *node;
282313fe1bdbSQu Wenruo 	int i;
282413fe1bdbSQu Wenruo 
282513fe1bdbSQu Wenruo 	while (!list_empty(&cache->detached)) {
282613fe1bdbSQu Wenruo 		node = list_entry(cache->detached.next,
282713fe1bdbSQu Wenruo 				  struct btrfs_backref_node, list);
282813fe1bdbSQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
282913fe1bdbSQu Wenruo 	}
283013fe1bdbSQu Wenruo 
283113fe1bdbSQu Wenruo 	while (!list_empty(&cache->leaves)) {
283213fe1bdbSQu Wenruo 		node = list_entry(cache->leaves.next,
283313fe1bdbSQu Wenruo 				  struct btrfs_backref_node, lower);
283413fe1bdbSQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
283513fe1bdbSQu Wenruo 	}
283613fe1bdbSQu Wenruo 
283713fe1bdbSQu Wenruo 	cache->last_trans = 0;
283813fe1bdbSQu Wenruo 
283913fe1bdbSQu Wenruo 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
284013fe1bdbSQu Wenruo 		ASSERT(list_empty(&cache->pending[i]));
284113fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->pending_edge));
284213fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->useless_node));
284313fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->changed));
284413fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->detached));
284513fe1bdbSQu Wenruo 	ASSERT(RB_EMPTY_ROOT(&cache->rb_root));
284613fe1bdbSQu Wenruo 	ASSERT(!cache->nr_nodes);
284713fe1bdbSQu Wenruo 	ASSERT(!cache->nr_edges);
284813fe1bdbSQu Wenruo }
28491b60d2ecSQu Wenruo 
28501b60d2ecSQu Wenruo /*
28511b60d2ecSQu Wenruo  * Handle direct tree backref
28521b60d2ecSQu Wenruo  *
28531b60d2ecSQu Wenruo  * Direct tree backref means, the backref item shows its parent bytenr
28541b60d2ecSQu Wenruo  * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
28551b60d2ecSQu Wenruo  *
28561b60d2ecSQu Wenruo  * @ref_key:	The converted backref key.
28571b60d2ecSQu Wenruo  *		For keyed backref, it's the item key.
28581b60d2ecSQu Wenruo  *		For inlined backref, objectid is the bytenr,
28591b60d2ecSQu Wenruo  *		type is btrfs_inline_ref_type, offset is
28601b60d2ecSQu Wenruo  *		btrfs_inline_ref_offset.
28611b60d2ecSQu Wenruo  */
28621b60d2ecSQu Wenruo static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
28631b60d2ecSQu Wenruo 				      struct btrfs_key *ref_key,
28641b60d2ecSQu Wenruo 				      struct btrfs_backref_node *cur)
28651b60d2ecSQu Wenruo {
28661b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
28671b60d2ecSQu Wenruo 	struct btrfs_backref_node *upper;
28681b60d2ecSQu Wenruo 	struct rb_node *rb_node;
28691b60d2ecSQu Wenruo 
28701b60d2ecSQu Wenruo 	ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
28711b60d2ecSQu Wenruo 
28721b60d2ecSQu Wenruo 	/* Only reloc root uses backref pointing to itself */
28731b60d2ecSQu Wenruo 	if (ref_key->objectid == ref_key->offset) {
28741b60d2ecSQu Wenruo 		struct btrfs_root *root;
28751b60d2ecSQu Wenruo 
28761b60d2ecSQu Wenruo 		cur->is_reloc_root = 1;
28771b60d2ecSQu Wenruo 		/* Only reloc backref cache cares about a specific root */
28781b60d2ecSQu Wenruo 		if (cache->is_reloc) {
28791b60d2ecSQu Wenruo 			root = find_reloc_root(cache->fs_info, cur->bytenr);
2880f78743fbSJosef Bacik 			if (!root)
28811b60d2ecSQu Wenruo 				return -ENOENT;
28821b60d2ecSQu Wenruo 			cur->root = root;
28831b60d2ecSQu Wenruo 		} else {
28841b60d2ecSQu Wenruo 			/*
28851b60d2ecSQu Wenruo 			 * For generic purpose backref cache, reloc root node
28861b60d2ecSQu Wenruo 			 * is useless.
28871b60d2ecSQu Wenruo 			 */
28881b60d2ecSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
28891b60d2ecSQu Wenruo 		}
28901b60d2ecSQu Wenruo 		return 0;
28911b60d2ecSQu Wenruo 	}
28921b60d2ecSQu Wenruo 
28931b60d2ecSQu Wenruo 	edge = btrfs_backref_alloc_edge(cache);
28941b60d2ecSQu Wenruo 	if (!edge)
28951b60d2ecSQu Wenruo 		return -ENOMEM;
28961b60d2ecSQu Wenruo 
28971b60d2ecSQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
28981b60d2ecSQu Wenruo 	if (!rb_node) {
28991b60d2ecSQu Wenruo 		/* Parent node not yet cached */
29001b60d2ecSQu Wenruo 		upper = btrfs_backref_alloc_node(cache, ref_key->offset,
29011b60d2ecSQu Wenruo 					   cur->level + 1);
29021b60d2ecSQu Wenruo 		if (!upper) {
29031b60d2ecSQu Wenruo 			btrfs_backref_free_edge(cache, edge);
29041b60d2ecSQu Wenruo 			return -ENOMEM;
29051b60d2ecSQu Wenruo 		}
29061b60d2ecSQu Wenruo 
29071b60d2ecSQu Wenruo 		/*
29081b60d2ecSQu Wenruo 		 *  Backrefs for the upper level block isn't cached, add the
29091b60d2ecSQu Wenruo 		 *  block to pending list
29101b60d2ecSQu Wenruo 		 */
29111b60d2ecSQu Wenruo 		list_add_tail(&edge->list[UPPER], &cache->pending_edge);
29121b60d2ecSQu Wenruo 	} else {
29131b60d2ecSQu Wenruo 		/* Parent node already cached */
29141b60d2ecSQu Wenruo 		upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
29151b60d2ecSQu Wenruo 		ASSERT(upper->checked);
29161b60d2ecSQu Wenruo 		INIT_LIST_HEAD(&edge->list[UPPER]);
29171b60d2ecSQu Wenruo 	}
29181b60d2ecSQu Wenruo 	btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
29191b60d2ecSQu Wenruo 	return 0;
29201b60d2ecSQu Wenruo }
29211b60d2ecSQu Wenruo 
29221b60d2ecSQu Wenruo /*
29231b60d2ecSQu Wenruo  * Handle indirect tree backref
29241b60d2ecSQu Wenruo  *
29251b60d2ecSQu Wenruo  * Indirect tree backref means, we only know which tree the node belongs to.
29261b60d2ecSQu Wenruo  * We still need to do a tree search to find out the parents. This is for
29271b60d2ecSQu Wenruo  * TREE_BLOCK_REF backref (keyed or inlined).
29281b60d2ecSQu Wenruo  *
29291b60d2ecSQu Wenruo  * @ref_key:	The same as @ref_key in  handle_direct_tree_backref()
29301b60d2ecSQu Wenruo  * @tree_key:	The first key of this tree block.
29311b60d2ecSQu Wenruo  * @path:	A clean (released) path, to avoid allocating path every time
29321b60d2ecSQu Wenruo  *		the function get called.
29331b60d2ecSQu Wenruo  */
29341b60d2ecSQu Wenruo static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
29351b60d2ecSQu Wenruo 					struct btrfs_path *path,
29361b60d2ecSQu Wenruo 					struct btrfs_key *ref_key,
29371b60d2ecSQu Wenruo 					struct btrfs_key *tree_key,
29381b60d2ecSQu Wenruo 					struct btrfs_backref_node *cur)
29391b60d2ecSQu Wenruo {
29401b60d2ecSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
29411b60d2ecSQu Wenruo 	struct btrfs_backref_node *upper;
29421b60d2ecSQu Wenruo 	struct btrfs_backref_node *lower;
29431b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
29441b60d2ecSQu Wenruo 	struct extent_buffer *eb;
29451b60d2ecSQu Wenruo 	struct btrfs_root *root;
29461b60d2ecSQu Wenruo 	struct rb_node *rb_node;
29471b60d2ecSQu Wenruo 	int level;
29481b60d2ecSQu Wenruo 	bool need_check = true;
29491b60d2ecSQu Wenruo 	int ret;
29501b60d2ecSQu Wenruo 
295156e9357aSDavid Sterba 	root = btrfs_get_fs_root(fs_info, ref_key->offset, false);
29521b60d2ecSQu Wenruo 	if (IS_ERR(root))
29531b60d2ecSQu Wenruo 		return PTR_ERR(root);
295492a7cc42SQu Wenruo 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
29551b60d2ecSQu Wenruo 		cur->cowonly = 1;
29561b60d2ecSQu Wenruo 
29571b60d2ecSQu Wenruo 	if (btrfs_root_level(&root->root_item) == cur->level) {
29581b60d2ecSQu Wenruo 		/* Tree root */
29591b60d2ecSQu Wenruo 		ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
2960876de781SQu Wenruo 		/*
2961876de781SQu Wenruo 		 * For reloc backref cache, we may ignore reloc root.  But for
2962876de781SQu Wenruo 		 * general purpose backref cache, we can't rely on
2963876de781SQu Wenruo 		 * btrfs_should_ignore_reloc_root() as it may conflict with
2964876de781SQu Wenruo 		 * current running relocation and lead to missing root.
2965876de781SQu Wenruo 		 *
2966876de781SQu Wenruo 		 * For general purpose backref cache, reloc root detection is
2967876de781SQu Wenruo 		 * completely relying on direct backref (key->offset is parent
2968876de781SQu Wenruo 		 * bytenr), thus only do such check for reloc cache.
2969876de781SQu Wenruo 		 */
2970876de781SQu Wenruo 		if (btrfs_should_ignore_reloc_root(root) && cache->is_reloc) {
29711b60d2ecSQu Wenruo 			btrfs_put_root(root);
29721b60d2ecSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
29731b60d2ecSQu Wenruo 		} else {
29741b60d2ecSQu Wenruo 			cur->root = root;
29751b60d2ecSQu Wenruo 		}
29761b60d2ecSQu Wenruo 		return 0;
29771b60d2ecSQu Wenruo 	}
29781b60d2ecSQu Wenruo 
29791b60d2ecSQu Wenruo 	level = cur->level + 1;
29801b60d2ecSQu Wenruo 
29811b60d2ecSQu Wenruo 	/* Search the tree to find parent blocks referring to the block */
29821b60d2ecSQu Wenruo 	path->search_commit_root = 1;
29831b60d2ecSQu Wenruo 	path->skip_locking = 1;
29841b60d2ecSQu Wenruo 	path->lowest_level = level;
29851b60d2ecSQu Wenruo 	ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
29861b60d2ecSQu Wenruo 	path->lowest_level = 0;
29871b60d2ecSQu Wenruo 	if (ret < 0) {
29881b60d2ecSQu Wenruo 		btrfs_put_root(root);
29891b60d2ecSQu Wenruo 		return ret;
29901b60d2ecSQu Wenruo 	}
29911b60d2ecSQu Wenruo 	if (ret > 0 && path->slots[level] > 0)
29921b60d2ecSQu Wenruo 		path->slots[level]--;
29931b60d2ecSQu Wenruo 
29941b60d2ecSQu Wenruo 	eb = path->nodes[level];
29951b60d2ecSQu Wenruo 	if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
29961b60d2ecSQu Wenruo 		btrfs_err(fs_info,
29971b60d2ecSQu Wenruo "couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
29981b60d2ecSQu Wenruo 			  cur->bytenr, level - 1, root->root_key.objectid,
29991b60d2ecSQu Wenruo 			  tree_key->objectid, tree_key->type, tree_key->offset);
30001b60d2ecSQu Wenruo 		btrfs_put_root(root);
30011b60d2ecSQu Wenruo 		ret = -ENOENT;
30021b60d2ecSQu Wenruo 		goto out;
30031b60d2ecSQu Wenruo 	}
30041b60d2ecSQu Wenruo 	lower = cur;
30051b60d2ecSQu Wenruo 
30061b60d2ecSQu Wenruo 	/* Add all nodes and edges in the path */
30071b60d2ecSQu Wenruo 	for (; level < BTRFS_MAX_LEVEL; level++) {
30081b60d2ecSQu Wenruo 		if (!path->nodes[level]) {
30091b60d2ecSQu Wenruo 			ASSERT(btrfs_root_bytenr(&root->root_item) ==
30101b60d2ecSQu Wenruo 			       lower->bytenr);
3011876de781SQu Wenruo 			/* Same as previous should_ignore_reloc_root() call */
3012876de781SQu Wenruo 			if (btrfs_should_ignore_reloc_root(root) &&
3013876de781SQu Wenruo 			    cache->is_reloc) {
30141b60d2ecSQu Wenruo 				btrfs_put_root(root);
30151b60d2ecSQu Wenruo 				list_add(&lower->list, &cache->useless_node);
30161b60d2ecSQu Wenruo 			} else {
30171b60d2ecSQu Wenruo 				lower->root = root;
30181b60d2ecSQu Wenruo 			}
30191b60d2ecSQu Wenruo 			break;
30201b60d2ecSQu Wenruo 		}
30211b60d2ecSQu Wenruo 
30221b60d2ecSQu Wenruo 		edge = btrfs_backref_alloc_edge(cache);
30231b60d2ecSQu Wenruo 		if (!edge) {
30241b60d2ecSQu Wenruo 			btrfs_put_root(root);
30251b60d2ecSQu Wenruo 			ret = -ENOMEM;
30261b60d2ecSQu Wenruo 			goto out;
30271b60d2ecSQu Wenruo 		}
30281b60d2ecSQu Wenruo 
30291b60d2ecSQu Wenruo 		eb = path->nodes[level];
30301b60d2ecSQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root, eb->start);
30311b60d2ecSQu Wenruo 		if (!rb_node) {
30321b60d2ecSQu Wenruo 			upper = btrfs_backref_alloc_node(cache, eb->start,
30331b60d2ecSQu Wenruo 							 lower->level + 1);
30341b60d2ecSQu Wenruo 			if (!upper) {
30351b60d2ecSQu Wenruo 				btrfs_put_root(root);
30361b60d2ecSQu Wenruo 				btrfs_backref_free_edge(cache, edge);
30371b60d2ecSQu Wenruo 				ret = -ENOMEM;
30381b60d2ecSQu Wenruo 				goto out;
30391b60d2ecSQu Wenruo 			}
30401b60d2ecSQu Wenruo 			upper->owner = btrfs_header_owner(eb);
304192a7cc42SQu Wenruo 			if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
30421b60d2ecSQu Wenruo 				upper->cowonly = 1;
30431b60d2ecSQu Wenruo 
30441b60d2ecSQu Wenruo 			/*
30451b60d2ecSQu Wenruo 			 * If we know the block isn't shared we can avoid
30461b60d2ecSQu Wenruo 			 * checking its backrefs.
30471b60d2ecSQu Wenruo 			 */
30481b60d2ecSQu Wenruo 			if (btrfs_block_can_be_shared(root, eb))
30491b60d2ecSQu Wenruo 				upper->checked = 0;
30501b60d2ecSQu Wenruo 			else
30511b60d2ecSQu Wenruo 				upper->checked = 1;
30521b60d2ecSQu Wenruo 
30531b60d2ecSQu Wenruo 			/*
30541b60d2ecSQu Wenruo 			 * Add the block to pending list if we need to check its
30551b60d2ecSQu Wenruo 			 * backrefs, we only do this once while walking up a
30561b60d2ecSQu Wenruo 			 * tree as we will catch anything else later on.
30571b60d2ecSQu Wenruo 			 */
30581b60d2ecSQu Wenruo 			if (!upper->checked && need_check) {
30591b60d2ecSQu Wenruo 				need_check = false;
30601b60d2ecSQu Wenruo 				list_add_tail(&edge->list[UPPER],
30611b60d2ecSQu Wenruo 					      &cache->pending_edge);
30621b60d2ecSQu Wenruo 			} else {
30631b60d2ecSQu Wenruo 				if (upper->checked)
30641b60d2ecSQu Wenruo 					need_check = true;
30651b60d2ecSQu Wenruo 				INIT_LIST_HEAD(&edge->list[UPPER]);
30661b60d2ecSQu Wenruo 			}
30671b60d2ecSQu Wenruo 		} else {
30681b60d2ecSQu Wenruo 			upper = rb_entry(rb_node, struct btrfs_backref_node,
30691b60d2ecSQu Wenruo 					 rb_node);
30701b60d2ecSQu Wenruo 			ASSERT(upper->checked);
30711b60d2ecSQu Wenruo 			INIT_LIST_HEAD(&edge->list[UPPER]);
30721b60d2ecSQu Wenruo 			if (!upper->owner)
30731b60d2ecSQu Wenruo 				upper->owner = btrfs_header_owner(eb);
30741b60d2ecSQu Wenruo 		}
30751b60d2ecSQu Wenruo 		btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
30761b60d2ecSQu Wenruo 
30771b60d2ecSQu Wenruo 		if (rb_node) {
30781b60d2ecSQu Wenruo 			btrfs_put_root(root);
30791b60d2ecSQu Wenruo 			break;
30801b60d2ecSQu Wenruo 		}
30811b60d2ecSQu Wenruo 		lower = upper;
30821b60d2ecSQu Wenruo 		upper = NULL;
30831b60d2ecSQu Wenruo 	}
30841b60d2ecSQu Wenruo out:
30851b60d2ecSQu Wenruo 	btrfs_release_path(path);
30861b60d2ecSQu Wenruo 	return ret;
30871b60d2ecSQu Wenruo }
30881b60d2ecSQu Wenruo 
30891b60d2ecSQu Wenruo /*
30901b60d2ecSQu Wenruo  * Add backref node @cur into @cache.
30911b60d2ecSQu Wenruo  *
30921b60d2ecSQu Wenruo  * NOTE: Even if the function returned 0, @cur is not yet cached as its upper
30931b60d2ecSQu Wenruo  *	 links aren't yet bi-directional. Needs to finish such links.
3094fc997ed0SQu Wenruo  *	 Use btrfs_backref_finish_upper_links() to finish such linkage.
30951b60d2ecSQu Wenruo  *
30961b60d2ecSQu Wenruo  * @path:	Released path for indirect tree backref lookup
30971b60d2ecSQu Wenruo  * @iter:	Released backref iter for extent tree search
30981b60d2ecSQu Wenruo  * @node_key:	The first key of the tree block
30991b60d2ecSQu Wenruo  */
31001b60d2ecSQu Wenruo int btrfs_backref_add_tree_node(struct btrfs_backref_cache *cache,
31011b60d2ecSQu Wenruo 				struct btrfs_path *path,
31021b60d2ecSQu Wenruo 				struct btrfs_backref_iter *iter,
31031b60d2ecSQu Wenruo 				struct btrfs_key *node_key,
31041b60d2ecSQu Wenruo 				struct btrfs_backref_node *cur)
31051b60d2ecSQu Wenruo {
31061b60d2ecSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
31071b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
31081b60d2ecSQu Wenruo 	struct btrfs_backref_node *exist;
31091b60d2ecSQu Wenruo 	int ret;
31101b60d2ecSQu Wenruo 
31111b60d2ecSQu Wenruo 	ret = btrfs_backref_iter_start(iter, cur->bytenr);
31121b60d2ecSQu Wenruo 	if (ret < 0)
31131b60d2ecSQu Wenruo 		return ret;
31141b60d2ecSQu Wenruo 	/*
31151b60d2ecSQu Wenruo 	 * We skip the first btrfs_tree_block_info, as we don't use the key
31161b60d2ecSQu Wenruo 	 * stored in it, but fetch it from the tree block
31171b60d2ecSQu Wenruo 	 */
31181b60d2ecSQu Wenruo 	if (btrfs_backref_has_tree_block_info(iter)) {
31191b60d2ecSQu Wenruo 		ret = btrfs_backref_iter_next(iter);
31201b60d2ecSQu Wenruo 		if (ret < 0)
31211b60d2ecSQu Wenruo 			goto out;
31221b60d2ecSQu Wenruo 		/* No extra backref? This means the tree block is corrupted */
31231b60d2ecSQu Wenruo 		if (ret > 0) {
31241b60d2ecSQu Wenruo 			ret = -EUCLEAN;
31251b60d2ecSQu Wenruo 			goto out;
31261b60d2ecSQu Wenruo 		}
31271b60d2ecSQu Wenruo 	}
31281b60d2ecSQu Wenruo 	WARN_ON(cur->checked);
31291b60d2ecSQu Wenruo 	if (!list_empty(&cur->upper)) {
31301b60d2ecSQu Wenruo 		/*
31311b60d2ecSQu Wenruo 		 * The backref was added previously when processing backref of
31321b60d2ecSQu Wenruo 		 * type BTRFS_TREE_BLOCK_REF_KEY
31331b60d2ecSQu Wenruo 		 */
31341b60d2ecSQu Wenruo 		ASSERT(list_is_singular(&cur->upper));
31351b60d2ecSQu Wenruo 		edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
31361b60d2ecSQu Wenruo 				  list[LOWER]);
31371b60d2ecSQu Wenruo 		ASSERT(list_empty(&edge->list[UPPER]));
31381b60d2ecSQu Wenruo 		exist = edge->node[UPPER];
31391b60d2ecSQu Wenruo 		/*
31401b60d2ecSQu Wenruo 		 * Add the upper level block to pending list if we need check
31411b60d2ecSQu Wenruo 		 * its backrefs
31421b60d2ecSQu Wenruo 		 */
31431b60d2ecSQu Wenruo 		if (!exist->checked)
31441b60d2ecSQu Wenruo 			list_add_tail(&edge->list[UPPER], &cache->pending_edge);
31451b60d2ecSQu Wenruo 	} else {
31461b60d2ecSQu Wenruo 		exist = NULL;
31471b60d2ecSQu Wenruo 	}
31481b60d2ecSQu Wenruo 
31491b60d2ecSQu Wenruo 	for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
31501b60d2ecSQu Wenruo 		struct extent_buffer *eb;
31511b60d2ecSQu Wenruo 		struct btrfs_key key;
31521b60d2ecSQu Wenruo 		int type;
31531b60d2ecSQu Wenruo 
31541b60d2ecSQu Wenruo 		cond_resched();
31551b60d2ecSQu Wenruo 		eb = btrfs_backref_get_eb(iter);
31561b60d2ecSQu Wenruo 
31571b60d2ecSQu Wenruo 		key.objectid = iter->bytenr;
31581b60d2ecSQu Wenruo 		if (btrfs_backref_iter_is_inline_ref(iter)) {
31591b60d2ecSQu Wenruo 			struct btrfs_extent_inline_ref *iref;
31601b60d2ecSQu Wenruo 
31611b60d2ecSQu Wenruo 			/* Update key for inline backref */
31621b60d2ecSQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
31631b60d2ecSQu Wenruo 				((unsigned long)iter->cur_ptr);
31641b60d2ecSQu Wenruo 			type = btrfs_get_extent_inline_ref_type(eb, iref,
31651b60d2ecSQu Wenruo 							BTRFS_REF_TYPE_BLOCK);
31661b60d2ecSQu Wenruo 			if (type == BTRFS_REF_TYPE_INVALID) {
31671b60d2ecSQu Wenruo 				ret = -EUCLEAN;
31681b60d2ecSQu Wenruo 				goto out;
31691b60d2ecSQu Wenruo 			}
31701b60d2ecSQu Wenruo 			key.type = type;
31711b60d2ecSQu Wenruo 			key.offset = btrfs_extent_inline_ref_offset(eb, iref);
31721b60d2ecSQu Wenruo 		} else {
31731b60d2ecSQu Wenruo 			key.type = iter->cur_key.type;
31741b60d2ecSQu Wenruo 			key.offset = iter->cur_key.offset;
31751b60d2ecSQu Wenruo 		}
31761b60d2ecSQu Wenruo 
31771b60d2ecSQu Wenruo 		/*
31781b60d2ecSQu Wenruo 		 * Parent node found and matches current inline ref, no need to
31791b60d2ecSQu Wenruo 		 * rebuild this node for this inline ref
31801b60d2ecSQu Wenruo 		 */
31811b60d2ecSQu Wenruo 		if (exist &&
31821b60d2ecSQu Wenruo 		    ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
31831b60d2ecSQu Wenruo 		      exist->owner == key.offset) ||
31841b60d2ecSQu Wenruo 		     (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
31851b60d2ecSQu Wenruo 		      exist->bytenr == key.offset))) {
31861b60d2ecSQu Wenruo 			exist = NULL;
31871b60d2ecSQu Wenruo 			continue;
31881b60d2ecSQu Wenruo 		}
31891b60d2ecSQu Wenruo 
31901b60d2ecSQu Wenruo 		/* SHARED_BLOCK_REF means key.offset is the parent bytenr */
31911b60d2ecSQu Wenruo 		if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
31921b60d2ecSQu Wenruo 			ret = handle_direct_tree_backref(cache, &key, cur);
31931b60d2ecSQu Wenruo 			if (ret < 0)
31941b60d2ecSQu Wenruo 				goto out;
31951b60d2ecSQu Wenruo 			continue;
31961b60d2ecSQu Wenruo 		} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
31971b60d2ecSQu Wenruo 			ret = -EINVAL;
31981b60d2ecSQu Wenruo 			btrfs_print_v0_err(fs_info);
31991b60d2ecSQu Wenruo 			btrfs_handle_fs_error(fs_info, ret, NULL);
32001b60d2ecSQu Wenruo 			goto out;
32011b60d2ecSQu Wenruo 		} else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
32021b60d2ecSQu Wenruo 			continue;
32031b60d2ecSQu Wenruo 		}
32041b60d2ecSQu Wenruo 
32051b60d2ecSQu Wenruo 		/*
32061b60d2ecSQu Wenruo 		 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
32071b60d2ecSQu Wenruo 		 * means the root objectid. We need to search the tree to get
32081b60d2ecSQu Wenruo 		 * its parent bytenr.
32091b60d2ecSQu Wenruo 		 */
32101b60d2ecSQu Wenruo 		ret = handle_indirect_tree_backref(cache, path, &key, node_key,
32111b60d2ecSQu Wenruo 						   cur);
32121b60d2ecSQu Wenruo 		if (ret < 0)
32131b60d2ecSQu Wenruo 			goto out;
32141b60d2ecSQu Wenruo 	}
32151b60d2ecSQu Wenruo 	ret = 0;
32161b60d2ecSQu Wenruo 	cur->checked = 1;
32171b60d2ecSQu Wenruo 	WARN_ON(exist);
32181b60d2ecSQu Wenruo out:
32191b60d2ecSQu Wenruo 	btrfs_backref_iter_release(iter);
32201b60d2ecSQu Wenruo 	return ret;
32211b60d2ecSQu Wenruo }
3222fc997ed0SQu Wenruo 
3223fc997ed0SQu Wenruo /*
3224fc997ed0SQu Wenruo  * Finish the upwards linkage created by btrfs_backref_add_tree_node()
3225fc997ed0SQu Wenruo  */
3226fc997ed0SQu Wenruo int btrfs_backref_finish_upper_links(struct btrfs_backref_cache *cache,
3227fc997ed0SQu Wenruo 				     struct btrfs_backref_node *start)
3228fc997ed0SQu Wenruo {
3229fc997ed0SQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
3230fc997ed0SQu Wenruo 	struct btrfs_backref_edge *edge;
3231fc997ed0SQu Wenruo 	struct rb_node *rb_node;
3232fc997ed0SQu Wenruo 	LIST_HEAD(pending_edge);
3233fc997ed0SQu Wenruo 
3234fc997ed0SQu Wenruo 	ASSERT(start->checked);
3235fc997ed0SQu Wenruo 
3236fc997ed0SQu Wenruo 	/* Insert this node to cache if it's not COW-only */
3237fc997ed0SQu Wenruo 	if (!start->cowonly) {
3238fc997ed0SQu Wenruo 		rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
3239fc997ed0SQu Wenruo 					   &start->rb_node);
3240fc997ed0SQu Wenruo 		if (rb_node)
3241fc997ed0SQu Wenruo 			btrfs_backref_panic(cache->fs_info, start->bytenr,
3242fc997ed0SQu Wenruo 					    -EEXIST);
3243fc997ed0SQu Wenruo 		list_add_tail(&start->lower, &cache->leaves);
3244fc997ed0SQu Wenruo 	}
3245fc997ed0SQu Wenruo 
3246fc997ed0SQu Wenruo 	/*
3247fc997ed0SQu Wenruo 	 * Use breadth first search to iterate all related edges.
3248fc997ed0SQu Wenruo 	 *
3249fc997ed0SQu Wenruo 	 * The starting points are all the edges of this node
3250fc997ed0SQu Wenruo 	 */
3251fc997ed0SQu Wenruo 	list_for_each_entry(edge, &start->upper, list[LOWER])
3252fc997ed0SQu Wenruo 		list_add_tail(&edge->list[UPPER], &pending_edge);
3253fc997ed0SQu Wenruo 
3254fc997ed0SQu Wenruo 	while (!list_empty(&pending_edge)) {
3255fc997ed0SQu Wenruo 		struct btrfs_backref_node *upper;
3256fc997ed0SQu Wenruo 		struct btrfs_backref_node *lower;
3257fc997ed0SQu Wenruo 
3258fc997ed0SQu Wenruo 		edge = list_first_entry(&pending_edge,
3259fc997ed0SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
3260fc997ed0SQu Wenruo 		list_del_init(&edge->list[UPPER]);
3261fc997ed0SQu Wenruo 		upper = edge->node[UPPER];
3262fc997ed0SQu Wenruo 		lower = edge->node[LOWER];
3263fc997ed0SQu Wenruo 
3264fc997ed0SQu Wenruo 		/* Parent is detached, no need to keep any edges */
3265fc997ed0SQu Wenruo 		if (upper->detached) {
3266fc997ed0SQu Wenruo 			list_del(&edge->list[LOWER]);
3267fc997ed0SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
3268fc997ed0SQu Wenruo 
3269fc997ed0SQu Wenruo 			/* Lower node is orphan, queue for cleanup */
3270fc997ed0SQu Wenruo 			if (list_empty(&lower->upper))
3271fc997ed0SQu Wenruo 				list_add(&lower->list, useless_node);
3272fc997ed0SQu Wenruo 			continue;
3273fc997ed0SQu Wenruo 		}
3274fc997ed0SQu Wenruo 
3275fc997ed0SQu Wenruo 		/*
3276fc997ed0SQu Wenruo 		 * All new nodes added in current build_backref_tree() haven't
3277fc997ed0SQu Wenruo 		 * been linked to the cache rb tree.
3278fc997ed0SQu Wenruo 		 * So if we have upper->rb_node populated, this means a cache
3279fc997ed0SQu Wenruo 		 * hit. We only need to link the edge, as @upper and all its
3280fc997ed0SQu Wenruo 		 * parents have already been linked.
3281fc997ed0SQu Wenruo 		 */
3282fc997ed0SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node)) {
3283fc997ed0SQu Wenruo 			if (upper->lowest) {
3284fc997ed0SQu Wenruo 				list_del_init(&upper->lower);
3285fc997ed0SQu Wenruo 				upper->lowest = 0;
3286fc997ed0SQu Wenruo 			}
3287fc997ed0SQu Wenruo 
3288fc997ed0SQu Wenruo 			list_add_tail(&edge->list[UPPER], &upper->lower);
3289fc997ed0SQu Wenruo 			continue;
3290fc997ed0SQu Wenruo 		}
3291fc997ed0SQu Wenruo 
3292fc997ed0SQu Wenruo 		/* Sanity check, we shouldn't have any unchecked nodes */
3293fc997ed0SQu Wenruo 		if (!upper->checked) {
3294fc997ed0SQu Wenruo 			ASSERT(0);
3295fc997ed0SQu Wenruo 			return -EUCLEAN;
3296fc997ed0SQu Wenruo 		}
3297fc997ed0SQu Wenruo 
3298fc997ed0SQu Wenruo 		/* Sanity check, COW-only node has non-COW-only parent */
3299fc997ed0SQu Wenruo 		if (start->cowonly != upper->cowonly) {
3300fc997ed0SQu Wenruo 			ASSERT(0);
3301fc997ed0SQu Wenruo 			return -EUCLEAN;
3302fc997ed0SQu Wenruo 		}
3303fc997ed0SQu Wenruo 
3304fc997ed0SQu Wenruo 		/* Only cache non-COW-only (subvolume trees) tree blocks */
3305fc997ed0SQu Wenruo 		if (!upper->cowonly) {
3306fc997ed0SQu Wenruo 			rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
3307fc997ed0SQu Wenruo 						   &upper->rb_node);
3308fc997ed0SQu Wenruo 			if (rb_node) {
3309fc997ed0SQu Wenruo 				btrfs_backref_panic(cache->fs_info,
3310fc997ed0SQu Wenruo 						upper->bytenr, -EEXIST);
3311fc997ed0SQu Wenruo 				return -EUCLEAN;
3312fc997ed0SQu Wenruo 			}
3313fc997ed0SQu Wenruo 		}
3314fc997ed0SQu Wenruo 
3315fc997ed0SQu Wenruo 		list_add_tail(&edge->list[UPPER], &upper->lower);
3316fc997ed0SQu Wenruo 
3317fc997ed0SQu Wenruo 		/*
3318fc997ed0SQu Wenruo 		 * Also queue all the parent edges of this uncached node
3319fc997ed0SQu Wenruo 		 * to finish the upper linkage
3320fc997ed0SQu Wenruo 		 */
3321fc997ed0SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
3322fc997ed0SQu Wenruo 			list_add_tail(&edge->list[UPPER], &pending_edge);
3323fc997ed0SQu Wenruo 	}
3324fc997ed0SQu Wenruo 	return 0;
3325fc997ed0SQu Wenruo }
33261b23ea18SQu Wenruo 
33271b23ea18SQu Wenruo void btrfs_backref_error_cleanup(struct btrfs_backref_cache *cache,
33281b23ea18SQu Wenruo 				 struct btrfs_backref_node *node)
33291b23ea18SQu Wenruo {
33301b23ea18SQu Wenruo 	struct btrfs_backref_node *lower;
33311b23ea18SQu Wenruo 	struct btrfs_backref_node *upper;
33321b23ea18SQu Wenruo 	struct btrfs_backref_edge *edge;
33331b23ea18SQu Wenruo 
33341b23ea18SQu Wenruo 	while (!list_empty(&cache->useless_node)) {
33351b23ea18SQu Wenruo 		lower = list_first_entry(&cache->useless_node,
33361b23ea18SQu Wenruo 				   struct btrfs_backref_node, list);
33371b23ea18SQu Wenruo 		list_del_init(&lower->list);
33381b23ea18SQu Wenruo 	}
33391b23ea18SQu Wenruo 	while (!list_empty(&cache->pending_edge)) {
33401b23ea18SQu Wenruo 		edge = list_first_entry(&cache->pending_edge,
33411b23ea18SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
33421b23ea18SQu Wenruo 		list_del(&edge->list[UPPER]);
33431b23ea18SQu Wenruo 		list_del(&edge->list[LOWER]);
33441b23ea18SQu Wenruo 		lower = edge->node[LOWER];
33451b23ea18SQu Wenruo 		upper = edge->node[UPPER];
33461b23ea18SQu Wenruo 		btrfs_backref_free_edge(cache, edge);
33471b23ea18SQu Wenruo 
33481b23ea18SQu Wenruo 		/*
33491b23ea18SQu Wenruo 		 * Lower is no longer linked to any upper backref nodes and
33501b23ea18SQu Wenruo 		 * isn't in the cache, we can free it ourselves.
33511b23ea18SQu Wenruo 		 */
33521b23ea18SQu Wenruo 		if (list_empty(&lower->upper) &&
33531b23ea18SQu Wenruo 		    RB_EMPTY_NODE(&lower->rb_node))
33541b23ea18SQu Wenruo 			list_add(&lower->list, &cache->useless_node);
33551b23ea18SQu Wenruo 
33561b23ea18SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node))
33571b23ea18SQu Wenruo 			continue;
33581b23ea18SQu Wenruo 
33591b23ea18SQu Wenruo 		/* Add this guy's upper edges to the list to process */
33601b23ea18SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
33611b23ea18SQu Wenruo 			list_add_tail(&edge->list[UPPER],
33621b23ea18SQu Wenruo 				      &cache->pending_edge);
33631b23ea18SQu Wenruo 		if (list_empty(&upper->upper))
33641b23ea18SQu Wenruo 			list_add(&upper->list, &cache->useless_node);
33651b23ea18SQu Wenruo 	}
33661b23ea18SQu Wenruo 
33671b23ea18SQu Wenruo 	while (!list_empty(&cache->useless_node)) {
33681b23ea18SQu Wenruo 		lower = list_first_entry(&cache->useless_node,
33691b23ea18SQu Wenruo 				   struct btrfs_backref_node, list);
33701b23ea18SQu Wenruo 		list_del_init(&lower->list);
33711b23ea18SQu Wenruo 		if (lower == node)
33721b23ea18SQu Wenruo 			node = NULL;
337349ecc679SJosef Bacik 		btrfs_backref_drop_node(cache, lower);
33741b23ea18SQu Wenruo 	}
33751b23ea18SQu Wenruo 
33761b23ea18SQu Wenruo 	btrfs_backref_cleanup_node(cache, node);
33771b23ea18SQu Wenruo 	ASSERT(list_empty(&cache->useless_node) &&
33781b23ea18SQu Wenruo 	       list_empty(&cache->pending_edge));
33791b23ea18SQu Wenruo }
3380