xref: /openbmc/linux/fs/btrfs/backref.c (revision 583f4ac56254c844cbbc9f23744e1f2efbf42fc7)
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;
14073e339e6SFilipe Manana 	u64 data_bytenr;
14173e339e6SFilipe Manana 	/*
14273e339e6SFilipe Manana 	 * Counts number of inodes that refer to an extent (different inodes in
14373e339e6SFilipe Manana 	 * the same root or different roots) that we could find. The sharedness
14473e339e6SFilipe Manana 	 * check typically stops once this counter gets greater than 1, so it
14573e339e6SFilipe Manana 	 * may not reflect the total number of inodes.
14673e339e6SFilipe Manana 	 */
1473ec4d323SEdmund Nadolski 	int share_count;
14873e339e6SFilipe Manana 	/*
14973e339e6SFilipe Manana 	 * The number of times we found our inode refers to the data extent we
15073e339e6SFilipe Manana 	 * are determining the sharedness. In other words, how many file extent
15173e339e6SFilipe Manana 	 * items we could find for our inode that point to our target data
15273e339e6SFilipe Manana 	 * extent. The value we get here after finishing the extent sharedness
15373e339e6SFilipe Manana 	 * check may be smaller than reality, but if it ends up being greater
15473e339e6SFilipe Manana 	 * than 1, then we know for sure the inode has multiple file extent
15573e339e6SFilipe Manana 	 * items that point to our inode, and we can safely assume it's useful
15673e339e6SFilipe Manana 	 * to cache the sharedness check result.
15773e339e6SFilipe Manana 	 */
15873e339e6SFilipe Manana 	int self_ref_count;
1594fc7b572SFilipe Manana 	bool have_delayed_delete_refs;
1603ec4d323SEdmund Nadolski };
1613ec4d323SEdmund Nadolski 
1623ec4d323SEdmund Nadolski static inline int extent_is_shared(struct share_check *sc)
1633ec4d323SEdmund Nadolski {
1643ec4d323SEdmund Nadolski 	return (sc && sc->share_count > 1) ? BACKREF_FOUND_SHARED : 0;
1653ec4d323SEdmund Nadolski }
1663ec4d323SEdmund Nadolski 
167b9e9a6cbSWang Shilong static struct kmem_cache *btrfs_prelim_ref_cache;
168b9e9a6cbSWang Shilong 
169b9e9a6cbSWang Shilong int __init btrfs_prelim_ref_init(void)
170b9e9a6cbSWang Shilong {
171b9e9a6cbSWang Shilong 	btrfs_prelim_ref_cache = kmem_cache_create("btrfs_prelim_ref",
172e0c476b1SJeff Mahoney 					sizeof(struct prelim_ref),
173b9e9a6cbSWang Shilong 					0,
174fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
175b9e9a6cbSWang Shilong 					NULL);
176b9e9a6cbSWang Shilong 	if (!btrfs_prelim_ref_cache)
177b9e9a6cbSWang Shilong 		return -ENOMEM;
178b9e9a6cbSWang Shilong 	return 0;
179b9e9a6cbSWang Shilong }
180b9e9a6cbSWang Shilong 
181e67c718bSDavid Sterba void __cold btrfs_prelim_ref_exit(void)
182b9e9a6cbSWang Shilong {
183b9e9a6cbSWang Shilong 	kmem_cache_destroy(btrfs_prelim_ref_cache);
184b9e9a6cbSWang Shilong }
185b9e9a6cbSWang Shilong 
18686d5f994SEdmund Nadolski static void free_pref(struct prelim_ref *ref)
18786d5f994SEdmund Nadolski {
18886d5f994SEdmund Nadolski 	kmem_cache_free(btrfs_prelim_ref_cache, ref);
18986d5f994SEdmund Nadolski }
19086d5f994SEdmund Nadolski 
19186d5f994SEdmund Nadolski /*
19286d5f994SEdmund Nadolski  * Return 0 when both refs are for the same block (and can be merged).
19386d5f994SEdmund Nadolski  * A -1 return indicates ref1 is a 'lower' block than ref2, while 1
19486d5f994SEdmund Nadolski  * indicates a 'higher' block.
19586d5f994SEdmund Nadolski  */
19686d5f994SEdmund Nadolski static int prelim_ref_compare(struct prelim_ref *ref1,
19786d5f994SEdmund Nadolski 			      struct prelim_ref *ref2)
19886d5f994SEdmund Nadolski {
19986d5f994SEdmund Nadolski 	if (ref1->level < ref2->level)
20086d5f994SEdmund Nadolski 		return -1;
20186d5f994SEdmund Nadolski 	if (ref1->level > ref2->level)
20286d5f994SEdmund Nadolski 		return 1;
20386d5f994SEdmund Nadolski 	if (ref1->root_id < ref2->root_id)
20486d5f994SEdmund Nadolski 		return -1;
20586d5f994SEdmund Nadolski 	if (ref1->root_id > ref2->root_id)
20686d5f994SEdmund Nadolski 		return 1;
20786d5f994SEdmund Nadolski 	if (ref1->key_for_search.type < ref2->key_for_search.type)
20886d5f994SEdmund Nadolski 		return -1;
20986d5f994SEdmund Nadolski 	if (ref1->key_for_search.type > ref2->key_for_search.type)
21086d5f994SEdmund Nadolski 		return 1;
21186d5f994SEdmund Nadolski 	if (ref1->key_for_search.objectid < ref2->key_for_search.objectid)
21286d5f994SEdmund Nadolski 		return -1;
21386d5f994SEdmund Nadolski 	if (ref1->key_for_search.objectid > ref2->key_for_search.objectid)
21486d5f994SEdmund Nadolski 		return 1;
21586d5f994SEdmund Nadolski 	if (ref1->key_for_search.offset < ref2->key_for_search.offset)
21686d5f994SEdmund Nadolski 		return -1;
21786d5f994SEdmund Nadolski 	if (ref1->key_for_search.offset > ref2->key_for_search.offset)
21886d5f994SEdmund Nadolski 		return 1;
21986d5f994SEdmund Nadolski 	if (ref1->parent < ref2->parent)
22086d5f994SEdmund Nadolski 		return -1;
22186d5f994SEdmund Nadolski 	if (ref1->parent > ref2->parent)
22286d5f994SEdmund Nadolski 		return 1;
22386d5f994SEdmund Nadolski 
22486d5f994SEdmund Nadolski 	return 0;
22586d5f994SEdmund Nadolski }
22686d5f994SEdmund Nadolski 
227ccc8dc75SColin Ian King static void update_share_count(struct share_check *sc, int oldcount,
22873e339e6SFilipe Manana 			       int newcount, struct prelim_ref *newref)
2293ec4d323SEdmund Nadolski {
2303ec4d323SEdmund Nadolski 	if ((!sc) || (oldcount == 0 && newcount < 1))
2313ec4d323SEdmund Nadolski 		return;
2323ec4d323SEdmund Nadolski 
2333ec4d323SEdmund Nadolski 	if (oldcount > 0 && newcount < 1)
2343ec4d323SEdmund Nadolski 		sc->share_count--;
2353ec4d323SEdmund Nadolski 	else if (oldcount < 1 && newcount > 0)
2363ec4d323SEdmund Nadolski 		sc->share_count++;
23773e339e6SFilipe Manana 
23873e339e6SFilipe Manana 	if (newref->root_id == sc->root_objectid &&
23973e339e6SFilipe Manana 	    newref->wanted_disk_byte == sc->data_bytenr &&
24073e339e6SFilipe Manana 	    newref->key_for_search.objectid == sc->inum)
24173e339e6SFilipe Manana 		sc->self_ref_count += newref->count;
2423ec4d323SEdmund Nadolski }
2433ec4d323SEdmund Nadolski 
24486d5f994SEdmund Nadolski /*
24586d5f994SEdmund Nadolski  * Add @newref to the @root rbtree, merging identical refs.
24686d5f994SEdmund Nadolski  *
2473ec4d323SEdmund Nadolski  * Callers should assume that newref has been freed after calling.
24886d5f994SEdmund Nadolski  */
24900142756SJeff Mahoney static void prelim_ref_insert(const struct btrfs_fs_info *fs_info,
25000142756SJeff Mahoney 			      struct preftree *preftree,
2513ec4d323SEdmund Nadolski 			      struct prelim_ref *newref,
2523ec4d323SEdmund Nadolski 			      struct share_check *sc)
25386d5f994SEdmund Nadolski {
254ecf160b4SLiu Bo 	struct rb_root_cached *root;
25586d5f994SEdmund Nadolski 	struct rb_node **p;
25686d5f994SEdmund Nadolski 	struct rb_node *parent = NULL;
25786d5f994SEdmund Nadolski 	struct prelim_ref *ref;
25886d5f994SEdmund Nadolski 	int result;
259ecf160b4SLiu Bo 	bool leftmost = true;
26086d5f994SEdmund Nadolski 
26186d5f994SEdmund Nadolski 	root = &preftree->root;
262ecf160b4SLiu Bo 	p = &root->rb_root.rb_node;
26386d5f994SEdmund Nadolski 
26486d5f994SEdmund Nadolski 	while (*p) {
26586d5f994SEdmund Nadolski 		parent = *p;
26686d5f994SEdmund Nadolski 		ref = rb_entry(parent, struct prelim_ref, rbnode);
26786d5f994SEdmund Nadolski 		result = prelim_ref_compare(ref, newref);
26886d5f994SEdmund Nadolski 		if (result < 0) {
26986d5f994SEdmund Nadolski 			p = &(*p)->rb_left;
27086d5f994SEdmund Nadolski 		} else if (result > 0) {
27186d5f994SEdmund Nadolski 			p = &(*p)->rb_right;
272ecf160b4SLiu Bo 			leftmost = false;
27386d5f994SEdmund Nadolski 		} else {
27486d5f994SEdmund Nadolski 			/* Identical refs, merge them and free @newref */
27586d5f994SEdmund Nadolski 			struct extent_inode_elem *eie = ref->inode_list;
27686d5f994SEdmund Nadolski 
27786d5f994SEdmund Nadolski 			while (eie && eie->next)
27886d5f994SEdmund Nadolski 				eie = eie->next;
27986d5f994SEdmund Nadolski 
28086d5f994SEdmund Nadolski 			if (!eie)
28186d5f994SEdmund Nadolski 				ref->inode_list = newref->inode_list;
28286d5f994SEdmund Nadolski 			else
28386d5f994SEdmund Nadolski 				eie->next = newref->inode_list;
28400142756SJeff Mahoney 			trace_btrfs_prelim_ref_merge(fs_info, ref, newref,
28500142756SJeff Mahoney 						     preftree->count);
2863ec4d323SEdmund Nadolski 			/*
2873ec4d323SEdmund Nadolski 			 * A delayed ref can have newref->count < 0.
2883ec4d323SEdmund Nadolski 			 * The ref->count is updated to follow any
2893ec4d323SEdmund Nadolski 			 * BTRFS_[ADD|DROP]_DELAYED_REF actions.
2903ec4d323SEdmund Nadolski 			 */
2913ec4d323SEdmund Nadolski 			update_share_count(sc, ref->count,
29273e339e6SFilipe Manana 					   ref->count + newref->count, newref);
29386d5f994SEdmund Nadolski 			ref->count += newref->count;
29486d5f994SEdmund Nadolski 			free_pref(newref);
29586d5f994SEdmund Nadolski 			return;
29686d5f994SEdmund Nadolski 		}
29786d5f994SEdmund Nadolski 	}
29886d5f994SEdmund Nadolski 
29973e339e6SFilipe Manana 	update_share_count(sc, 0, newref->count, newref);
3006c336b21SJeff Mahoney 	preftree->count++;
30100142756SJeff Mahoney 	trace_btrfs_prelim_ref_insert(fs_info, newref, NULL, preftree->count);
30286d5f994SEdmund Nadolski 	rb_link_node(&newref->rbnode, parent, p);
303ecf160b4SLiu Bo 	rb_insert_color_cached(&newref->rbnode, root, leftmost);
30486d5f994SEdmund Nadolski }
30586d5f994SEdmund Nadolski 
30686d5f994SEdmund Nadolski /*
30786d5f994SEdmund Nadolski  * Release the entire tree.  We don't care about internal consistency so
30886d5f994SEdmund Nadolski  * just free everything and then reset the tree root.
30986d5f994SEdmund Nadolski  */
31086d5f994SEdmund Nadolski static void prelim_release(struct preftree *preftree)
31186d5f994SEdmund Nadolski {
31286d5f994SEdmund Nadolski 	struct prelim_ref *ref, *next_ref;
31386d5f994SEdmund Nadolski 
314ecf160b4SLiu Bo 	rbtree_postorder_for_each_entry_safe(ref, next_ref,
31592876eecSFilipe Manana 					     &preftree->root.rb_root, rbnode) {
31692876eecSFilipe Manana 		free_inode_elem_list(ref->inode_list);
31786d5f994SEdmund Nadolski 		free_pref(ref);
31892876eecSFilipe Manana 	}
31986d5f994SEdmund Nadolski 
320ecf160b4SLiu Bo 	preftree->root = RB_ROOT_CACHED;
3216c336b21SJeff Mahoney 	preftree->count = 0;
32286d5f994SEdmund Nadolski }
32386d5f994SEdmund Nadolski 
324d5c88b73SJan Schmidt /*
325d5c88b73SJan Schmidt  * the rules for all callers of this function are:
326d5c88b73SJan Schmidt  * - obtaining the parent is the goal
327d5c88b73SJan Schmidt  * - if you add a key, you must know that it is a correct key
328d5c88b73SJan Schmidt  * - if you cannot add the parent or a correct key, then we will look into the
329d5c88b73SJan Schmidt  *   block later to set a correct key
330d5c88b73SJan Schmidt  *
331d5c88b73SJan Schmidt  * delayed refs
332d5c88b73SJan Schmidt  * ============
333d5c88b73SJan Schmidt  *        backref type | shared | indirect | shared | indirect
334d5c88b73SJan Schmidt  * information         |   tree |     tree |   data |     data
335d5c88b73SJan Schmidt  * --------------------+--------+----------+--------+----------
336d5c88b73SJan Schmidt  *      parent logical |    y   |     -    |    -   |     -
337d5c88b73SJan Schmidt  *      key to resolve |    -   |     y    |    y   |     y
338d5c88b73SJan Schmidt  *  tree block logical |    -   |     -    |    -   |     -
339d5c88b73SJan Schmidt  *  root for resolving |    y   |     y    |    y   |     y
340d5c88b73SJan Schmidt  *
341d5c88b73SJan Schmidt  * - column 1:       we've the parent -> done
342d5c88b73SJan Schmidt  * - column 2, 3, 4: we use the key to find the parent
343d5c88b73SJan Schmidt  *
344d5c88b73SJan Schmidt  * on disk refs (inline or keyed)
345d5c88b73SJan Schmidt  * ==============================
346d5c88b73SJan Schmidt  *        backref type | shared | indirect | shared | indirect
347d5c88b73SJan Schmidt  * information         |   tree |     tree |   data |     data
348d5c88b73SJan Schmidt  * --------------------+--------+----------+--------+----------
349d5c88b73SJan Schmidt  *      parent logical |    y   |     -    |    y   |     -
350d5c88b73SJan Schmidt  *      key to resolve |    -   |     -    |    -   |     y
351d5c88b73SJan Schmidt  *  tree block logical |    y   |     y    |    y   |     y
352d5c88b73SJan Schmidt  *  root for resolving |    -   |     y    |    y   |     y
353d5c88b73SJan Schmidt  *
354d5c88b73SJan Schmidt  * - column 1, 3: we've the parent -> done
355d5c88b73SJan Schmidt  * - column 2:    we take the first key from the block to find the parent
356e0c476b1SJeff Mahoney  *                (see add_missing_keys)
357d5c88b73SJan Schmidt  * - column 4:    we use the key to find the parent
358d5c88b73SJan Schmidt  *
359d5c88b73SJan Schmidt  * additional information that's available but not required to find the parent
360d5c88b73SJan Schmidt  * block might help in merging entries to gain some speed.
361d5c88b73SJan Schmidt  */
36200142756SJeff Mahoney static int add_prelim_ref(const struct btrfs_fs_info *fs_info,
36300142756SJeff Mahoney 			  struct preftree *preftree, u64 root_id,
364e0c476b1SJeff Mahoney 			  const struct btrfs_key *key, int level, u64 parent,
3653ec4d323SEdmund Nadolski 			  u64 wanted_disk_byte, int count,
3663ec4d323SEdmund Nadolski 			  struct share_check *sc, gfp_t gfp_mask)
3678da6d581SJan Schmidt {
368e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
3698da6d581SJan Schmidt 
37048ec4736SLiu Bo 	if (root_id == BTRFS_DATA_RELOC_TREE_OBJECTID)
37148ec4736SLiu Bo 		return 0;
37248ec4736SLiu Bo 
373b9e9a6cbSWang Shilong 	ref = kmem_cache_alloc(btrfs_prelim_ref_cache, gfp_mask);
3748da6d581SJan Schmidt 	if (!ref)
3758da6d581SJan Schmidt 		return -ENOMEM;
3768da6d581SJan Schmidt 
3778da6d581SJan Schmidt 	ref->root_id = root_id;
3787ac8b88eSethanwu 	if (key)
379d5c88b73SJan Schmidt 		ref->key_for_search = *key;
3807ac8b88eSethanwu 	else
381d5c88b73SJan Schmidt 		memset(&ref->key_for_search, 0, sizeof(ref->key_for_search));
3828da6d581SJan Schmidt 
3833301958bSJan Schmidt 	ref->inode_list = NULL;
3848da6d581SJan Schmidt 	ref->level = level;
3858da6d581SJan Schmidt 	ref->count = count;
3868da6d581SJan Schmidt 	ref->parent = parent;
3878da6d581SJan Schmidt 	ref->wanted_disk_byte = wanted_disk_byte;
3883ec4d323SEdmund Nadolski 	prelim_ref_insert(fs_info, preftree, ref, sc);
3893ec4d323SEdmund Nadolski 	return extent_is_shared(sc);
3908da6d581SJan Schmidt }
3918da6d581SJan Schmidt 
39286d5f994SEdmund Nadolski /* direct refs use root == 0, key == NULL */
39300142756SJeff Mahoney static int add_direct_ref(const struct btrfs_fs_info *fs_info,
39400142756SJeff Mahoney 			  struct preftrees *preftrees, int level, u64 parent,
3953ec4d323SEdmund Nadolski 			  u64 wanted_disk_byte, int count,
3963ec4d323SEdmund Nadolski 			  struct share_check *sc, gfp_t gfp_mask)
39786d5f994SEdmund Nadolski {
39800142756SJeff Mahoney 	return add_prelim_ref(fs_info, &preftrees->direct, 0, NULL, level,
3993ec4d323SEdmund Nadolski 			      parent, wanted_disk_byte, count, sc, gfp_mask);
40086d5f994SEdmund Nadolski }
40186d5f994SEdmund Nadolski 
40286d5f994SEdmund Nadolski /* indirect refs use parent == 0 */
40300142756SJeff Mahoney static int add_indirect_ref(const struct btrfs_fs_info *fs_info,
40400142756SJeff Mahoney 			    struct preftrees *preftrees, u64 root_id,
40586d5f994SEdmund Nadolski 			    const struct btrfs_key *key, int level,
4063ec4d323SEdmund Nadolski 			    u64 wanted_disk_byte, int count,
4073ec4d323SEdmund Nadolski 			    struct share_check *sc, gfp_t gfp_mask)
40886d5f994SEdmund Nadolski {
40986d5f994SEdmund Nadolski 	struct preftree *tree = &preftrees->indirect;
41086d5f994SEdmund Nadolski 
41186d5f994SEdmund Nadolski 	if (!key)
41286d5f994SEdmund Nadolski 		tree = &preftrees->indirect_missing_keys;
41300142756SJeff Mahoney 	return add_prelim_ref(fs_info, tree, root_id, key, level, 0,
4143ec4d323SEdmund Nadolski 			      wanted_disk_byte, count, sc, gfp_mask);
41586d5f994SEdmund Nadolski }
41686d5f994SEdmund Nadolski 
417ed58f2e6Sethanwu static int is_shared_data_backref(struct preftrees *preftrees, u64 bytenr)
418ed58f2e6Sethanwu {
419ed58f2e6Sethanwu 	struct rb_node **p = &preftrees->direct.root.rb_root.rb_node;
420ed58f2e6Sethanwu 	struct rb_node *parent = NULL;
421ed58f2e6Sethanwu 	struct prelim_ref *ref = NULL;
4229c6c723fSArnd Bergmann 	struct prelim_ref target = {};
423ed58f2e6Sethanwu 	int result;
424ed58f2e6Sethanwu 
425ed58f2e6Sethanwu 	target.parent = bytenr;
426ed58f2e6Sethanwu 
427ed58f2e6Sethanwu 	while (*p) {
428ed58f2e6Sethanwu 		parent = *p;
429ed58f2e6Sethanwu 		ref = rb_entry(parent, struct prelim_ref, rbnode);
430ed58f2e6Sethanwu 		result = prelim_ref_compare(ref, &target);
431ed58f2e6Sethanwu 
432ed58f2e6Sethanwu 		if (result < 0)
433ed58f2e6Sethanwu 			p = &(*p)->rb_left;
434ed58f2e6Sethanwu 		else if (result > 0)
435ed58f2e6Sethanwu 			p = &(*p)->rb_right;
436ed58f2e6Sethanwu 		else
437ed58f2e6Sethanwu 			return 1;
438ed58f2e6Sethanwu 	}
439ed58f2e6Sethanwu 	return 0;
440ed58f2e6Sethanwu }
441ed58f2e6Sethanwu 
4428da6d581SJan Schmidt static int add_all_parents(struct btrfs_root *root, struct btrfs_path *path,
443ed58f2e6Sethanwu 			   struct ulist *parents,
444ed58f2e6Sethanwu 			   struct preftrees *preftrees, struct prelim_ref *ref,
44544853868SJosef Bacik 			   int level, u64 time_seq, const u64 *extent_item_pos,
446b25b0b87Sethanwu 			   bool ignore_offset)
4478da6d581SJan Schmidt {
44869bca40dSAlexander Block 	int ret = 0;
44969bca40dSAlexander Block 	int slot;
45069bca40dSAlexander Block 	struct extent_buffer *eb;
45169bca40dSAlexander Block 	struct btrfs_key key;
4527ef81ac8SJosef Bacik 	struct btrfs_key *key_for_search = &ref->key_for_search;
4538da6d581SJan Schmidt 	struct btrfs_file_extent_item *fi;
454ed8c4913SJosef Bacik 	struct extent_inode_elem *eie = NULL, *old = NULL;
4558da6d581SJan Schmidt 	u64 disk_byte;
4567ef81ac8SJosef Bacik 	u64 wanted_disk_byte = ref->wanted_disk_byte;
4577ef81ac8SJosef Bacik 	u64 count = 0;
4587ac8b88eSethanwu 	u64 data_offset;
4598da6d581SJan Schmidt 
46069bca40dSAlexander Block 	if (level != 0) {
46169bca40dSAlexander Block 		eb = path->nodes[level];
46269bca40dSAlexander Block 		ret = ulist_add(parents, eb->start, 0, GFP_NOFS);
4633301958bSJan Schmidt 		if (ret < 0)
4643301958bSJan Schmidt 			return ret;
4658da6d581SJan Schmidt 		return 0;
46669bca40dSAlexander Block 	}
4678da6d581SJan Schmidt 
4688da6d581SJan Schmidt 	/*
469ed58f2e6Sethanwu 	 * 1. We normally enter this function with the path already pointing to
47069bca40dSAlexander Block 	 *    the first item to check. But sometimes, we may enter it with
471ed58f2e6Sethanwu 	 *    slot == nritems.
472ed58f2e6Sethanwu 	 * 2. We are searching for normal backref but bytenr of this leaf
473ed58f2e6Sethanwu 	 *    matches shared data backref
474cfc0eed0Sethanwu 	 * 3. The leaf owner is not equal to the root we are searching
475cfc0eed0Sethanwu 	 *
476ed58f2e6Sethanwu 	 * For these cases, go to the next leaf before we continue.
4778da6d581SJan Schmidt 	 */
478ed58f2e6Sethanwu 	eb = path->nodes[0];
479ed58f2e6Sethanwu 	if (path->slots[0] >= btrfs_header_nritems(eb) ||
480cfc0eed0Sethanwu 	    is_shared_data_backref(preftrees, eb->start) ||
481cfc0eed0Sethanwu 	    ref->root_id != btrfs_header_owner(eb)) {
482f3a84ccdSFilipe Manana 		if (time_seq == BTRFS_SEQ_LAST)
48321633fc6SQu Wenruo 			ret = btrfs_next_leaf(root, path);
48421633fc6SQu Wenruo 		else
4853d7806ecSJan Schmidt 			ret = btrfs_next_old_leaf(root, path, time_seq);
48621633fc6SQu Wenruo 	}
4878da6d581SJan Schmidt 
488b25b0b87Sethanwu 	while (!ret && count < ref->count) {
4898da6d581SJan Schmidt 		eb = path->nodes[0];
49069bca40dSAlexander Block 		slot = path->slots[0];
49169bca40dSAlexander Block 
49269bca40dSAlexander Block 		btrfs_item_key_to_cpu(eb, &key, slot);
49369bca40dSAlexander Block 
49469bca40dSAlexander Block 		if (key.objectid != key_for_search->objectid ||
49569bca40dSAlexander Block 		    key.type != BTRFS_EXTENT_DATA_KEY)
49669bca40dSAlexander Block 			break;
49769bca40dSAlexander Block 
498ed58f2e6Sethanwu 		/*
499ed58f2e6Sethanwu 		 * We are searching for normal backref but bytenr of this leaf
500cfc0eed0Sethanwu 		 * matches shared data backref, OR
501cfc0eed0Sethanwu 		 * the leaf owner is not equal to the root we are searching for
502ed58f2e6Sethanwu 		 */
503cfc0eed0Sethanwu 		if (slot == 0 &&
504cfc0eed0Sethanwu 		    (is_shared_data_backref(preftrees, eb->start) ||
505cfc0eed0Sethanwu 		     ref->root_id != btrfs_header_owner(eb))) {
506f3a84ccdSFilipe Manana 			if (time_seq == BTRFS_SEQ_LAST)
507ed58f2e6Sethanwu 				ret = btrfs_next_leaf(root, path);
508ed58f2e6Sethanwu 			else
509ed58f2e6Sethanwu 				ret = btrfs_next_old_leaf(root, path, time_seq);
510ed58f2e6Sethanwu 			continue;
511ed58f2e6Sethanwu 		}
51269bca40dSAlexander Block 		fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5138da6d581SJan Schmidt 		disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
5147ac8b88eSethanwu 		data_offset = btrfs_file_extent_offset(eb, fi);
51569bca40dSAlexander Block 
51669bca40dSAlexander Block 		if (disk_byte == wanted_disk_byte) {
51769bca40dSAlexander Block 			eie = NULL;
518ed8c4913SJosef Bacik 			old = NULL;
5197ac8b88eSethanwu 			if (ref->key_for_search.offset == key.offset - data_offset)
5207ef81ac8SJosef Bacik 				count++;
5217ac8b88eSethanwu 			else
5227ac8b88eSethanwu 				goto next;
52369bca40dSAlexander Block 			if (extent_item_pos) {
52469bca40dSAlexander Block 				ret = check_extent_in_eb(&key, eb, fi,
52569bca40dSAlexander Block 						*extent_item_pos,
526c995ab3cSZygo Blaxell 						&eie, ignore_offset);
52769bca40dSAlexander Block 				if (ret < 0)
52869bca40dSAlexander Block 					break;
5298da6d581SJan Schmidt 			}
530ed8c4913SJosef Bacik 			if (ret > 0)
531ed8c4913SJosef Bacik 				goto next;
5324eb1f66dSTakashi Iwai 			ret = ulist_add_merge_ptr(parents, eb->start,
5334eb1f66dSTakashi Iwai 						  eie, (void **)&old, GFP_NOFS);
53469bca40dSAlexander Block 			if (ret < 0)
53569bca40dSAlexander Block 				break;
536ed8c4913SJosef Bacik 			if (!ret && extent_item_pos) {
537ed8c4913SJosef Bacik 				while (old->next)
538ed8c4913SJosef Bacik 					old = old->next;
539ed8c4913SJosef Bacik 				old->next = eie;
54069bca40dSAlexander Block 			}
541f05c4746SWang Shilong 			eie = NULL;
54269bca40dSAlexander Block 		}
543ed8c4913SJosef Bacik next:
544f3a84ccdSFilipe Manana 		if (time_seq == BTRFS_SEQ_LAST)
54521633fc6SQu Wenruo 			ret = btrfs_next_item(root, path);
54621633fc6SQu Wenruo 		else
54769bca40dSAlexander Block 			ret = btrfs_next_old_item(root, path, time_seq);
5488da6d581SJan Schmidt 	}
5498da6d581SJan Schmidt 
55069bca40dSAlexander Block 	if (ret > 0)
55169bca40dSAlexander Block 		ret = 0;
552f05c4746SWang Shilong 	else if (ret < 0)
553f05c4746SWang Shilong 		free_inode_elem_list(eie);
55469bca40dSAlexander Block 	return ret;
5558da6d581SJan Schmidt }
5568da6d581SJan Schmidt 
5578da6d581SJan Schmidt /*
5588da6d581SJan Schmidt  * resolve an indirect backref in the form (root_id, key, level)
5598da6d581SJan Schmidt  * to a logical address
5608da6d581SJan Schmidt  */
561e0c476b1SJeff Mahoney static int resolve_indirect_ref(struct btrfs_fs_info *fs_info,
562da61d31aSJosef Bacik 				struct btrfs_path *path, u64 time_seq,
563ed58f2e6Sethanwu 				struct preftrees *preftrees,
564e0c476b1SJeff Mahoney 				struct prelim_ref *ref, struct ulist *parents,
565b25b0b87Sethanwu 				const u64 *extent_item_pos, bool ignore_offset)
5668da6d581SJan Schmidt {
5678da6d581SJan Schmidt 	struct btrfs_root *root;
5688da6d581SJan Schmidt 	struct extent_buffer *eb;
5698da6d581SJan Schmidt 	int ret = 0;
5708da6d581SJan Schmidt 	int root_level;
5718da6d581SJan Schmidt 	int level = ref->level;
5727ac8b88eSethanwu 	struct btrfs_key search_key = ref->key_for_search;
5738da6d581SJan Schmidt 
57449d11beaSJosef Bacik 	/*
57549d11beaSJosef Bacik 	 * If we're search_commit_root we could possibly be holding locks on
57649d11beaSJosef Bacik 	 * other tree nodes.  This happens when qgroups does backref walks when
57749d11beaSJosef Bacik 	 * adding new delayed refs.  To deal with this we need to look in cache
57849d11beaSJosef Bacik 	 * for the root, and if we don't find it then we need to search the
57949d11beaSJosef Bacik 	 * tree_root's commit root, thus the btrfs_get_fs_root_commit_root usage
58049d11beaSJosef Bacik 	 * here.
58149d11beaSJosef Bacik 	 */
58249d11beaSJosef Bacik 	if (path->search_commit_root)
58349d11beaSJosef Bacik 		root = btrfs_get_fs_root_commit_root(fs_info, path, ref->root_id);
58449d11beaSJosef Bacik 	else
58556e9357aSDavid Sterba 		root = btrfs_get_fs_root(fs_info, ref->root_id, false);
5868da6d581SJan Schmidt 	if (IS_ERR(root)) {
5878da6d581SJan Schmidt 		ret = PTR_ERR(root);
5889326f76fSJosef Bacik 		goto out_free;
5899326f76fSJosef Bacik 	}
5909326f76fSJosef Bacik 
59139dba873SJosef Bacik 	if (!path->search_commit_root &&
59239dba873SJosef Bacik 	    test_bit(BTRFS_ROOT_DELETING, &root->state)) {
59339dba873SJosef Bacik 		ret = -ENOENT;
59439dba873SJosef Bacik 		goto out;
59539dba873SJosef Bacik 	}
59639dba873SJosef Bacik 
597f5ee5c9aSJeff Mahoney 	if (btrfs_is_testing(fs_info)) {
598d9ee522bSJosef Bacik 		ret = -ENOENT;
599d9ee522bSJosef Bacik 		goto out;
600d9ee522bSJosef Bacik 	}
601d9ee522bSJosef Bacik 
6029e351cc8SJosef Bacik 	if (path->search_commit_root)
6039e351cc8SJosef Bacik 		root_level = btrfs_header_level(root->commit_root);
604f3a84ccdSFilipe Manana 	else if (time_seq == BTRFS_SEQ_LAST)
60521633fc6SQu Wenruo 		root_level = btrfs_header_level(root->node);
6069e351cc8SJosef Bacik 	else
6075b6602e7SJan Schmidt 		root_level = btrfs_old_root_level(root, time_seq);
6088da6d581SJan Schmidt 
609c75e8394SJosef Bacik 	if (root_level + 1 == level)
6108da6d581SJan Schmidt 		goto out;
6118da6d581SJan Schmidt 
6127ac8b88eSethanwu 	/*
6137ac8b88eSethanwu 	 * We can often find data backrefs with an offset that is too large
6147ac8b88eSethanwu 	 * (>= LLONG_MAX, maximum allowed file offset) due to underflows when
6157ac8b88eSethanwu 	 * subtracting a file's offset with the data offset of its
6167ac8b88eSethanwu 	 * corresponding extent data item. This can happen for example in the
6177ac8b88eSethanwu 	 * clone ioctl.
6187ac8b88eSethanwu 	 *
6197ac8b88eSethanwu 	 * So if we detect such case we set the search key's offset to zero to
6207ac8b88eSethanwu 	 * make sure we will find the matching file extent item at
6217ac8b88eSethanwu 	 * add_all_parents(), otherwise we will miss it because the offset
6227ac8b88eSethanwu 	 * taken form the backref is much larger then the offset of the file
6237ac8b88eSethanwu 	 * extent item. This can make us scan a very large number of file
6247ac8b88eSethanwu 	 * extent items, but at least it will not make us miss any.
6257ac8b88eSethanwu 	 *
6267ac8b88eSethanwu 	 * This is an ugly workaround for a behaviour that should have never
6277ac8b88eSethanwu 	 * existed, but it does and a fix for the clone ioctl would touch a lot
6287ac8b88eSethanwu 	 * of places, cause backwards incompatibility and would not fix the
6297ac8b88eSethanwu 	 * problem for extents cloned with older kernels.
6307ac8b88eSethanwu 	 */
6317ac8b88eSethanwu 	if (search_key.type == BTRFS_EXTENT_DATA_KEY &&
6327ac8b88eSethanwu 	    search_key.offset >= LLONG_MAX)
6337ac8b88eSethanwu 		search_key.offset = 0;
6348da6d581SJan Schmidt 	path->lowest_level = level;
635f3a84ccdSFilipe Manana 	if (time_seq == BTRFS_SEQ_LAST)
6367ac8b88eSethanwu 		ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
63721633fc6SQu Wenruo 	else
6387ac8b88eSethanwu 		ret = btrfs_search_old_slot(root, &search_key, path, time_seq);
639538f72cdSWang Shilong 
640ab8d0fc4SJeff Mahoney 	btrfs_debug(fs_info,
641ab8d0fc4SJeff Mahoney 		"search slot in root %llu (level %d, ref count %d) returned %d for key (%llu %u %llu)",
642c1c9ff7cSGeert Uytterhoeven 		 ref->root_id, level, ref->count, ret,
643c1c9ff7cSGeert Uytterhoeven 		 ref->key_for_search.objectid, ref->key_for_search.type,
644c1c9ff7cSGeert Uytterhoeven 		 ref->key_for_search.offset);
6458da6d581SJan Schmidt 	if (ret < 0)
6468da6d581SJan Schmidt 		goto out;
6478da6d581SJan Schmidt 
6488da6d581SJan Schmidt 	eb = path->nodes[level];
6499345457fSJan Schmidt 	while (!eb) {
650fae7f21cSDulshani Gunawardhana 		if (WARN_ON(!level)) {
6518da6d581SJan Schmidt 			ret = 1;
6528da6d581SJan Schmidt 			goto out;
6538da6d581SJan Schmidt 		}
6549345457fSJan Schmidt 		level--;
6559345457fSJan Schmidt 		eb = path->nodes[level];
6569345457fSJan Schmidt 	}
6578da6d581SJan Schmidt 
658ed58f2e6Sethanwu 	ret = add_all_parents(root, path, parents, preftrees, ref, level,
659b25b0b87Sethanwu 			      time_seq, extent_item_pos, ignore_offset);
6608da6d581SJan Schmidt out:
66100246528SJosef Bacik 	btrfs_put_root(root);
6629326f76fSJosef Bacik out_free:
663da61d31aSJosef Bacik 	path->lowest_level = 0;
664da61d31aSJosef Bacik 	btrfs_release_path(path);
6658da6d581SJan Schmidt 	return ret;
6668da6d581SJan Schmidt }
6678da6d581SJan Schmidt 
6684dae077aSJeff Mahoney static struct extent_inode_elem *
6694dae077aSJeff Mahoney unode_aux_to_inode_list(struct ulist_node *node)
6704dae077aSJeff Mahoney {
6714dae077aSJeff Mahoney 	if (!node)
6724dae077aSJeff Mahoney 		return NULL;
6734dae077aSJeff Mahoney 	return (struct extent_inode_elem *)(uintptr_t)node->aux;
6744dae077aSJeff Mahoney }
6754dae077aSJeff Mahoney 
6765614dc3aSFilipe Manana static void free_leaf_list(struct ulist *ulist)
6775614dc3aSFilipe Manana {
6785614dc3aSFilipe Manana 	struct ulist_node *node;
6795614dc3aSFilipe Manana 	struct ulist_iterator uiter;
6805614dc3aSFilipe Manana 
6815614dc3aSFilipe Manana 	ULIST_ITER_INIT(&uiter);
6825614dc3aSFilipe Manana 	while ((node = ulist_next(ulist, &uiter)))
6835614dc3aSFilipe Manana 		free_inode_elem_list(unode_aux_to_inode_list(node));
6845614dc3aSFilipe Manana 
6855614dc3aSFilipe Manana 	ulist_free(ulist);
6865614dc3aSFilipe Manana }
6875614dc3aSFilipe Manana 
6888da6d581SJan Schmidt /*
68952042d8eSAndrea Gelmini  * We maintain three separate rbtrees: one for direct refs, one for
69086d5f994SEdmund Nadolski  * indirect refs which have a key, and one for indirect refs which do not
69186d5f994SEdmund Nadolski  * have a key. Each tree does merge on insertion.
69286d5f994SEdmund Nadolski  *
69386d5f994SEdmund Nadolski  * Once all of the references are located, we iterate over the tree of
69486d5f994SEdmund Nadolski  * indirect refs with missing keys. An appropriate key is located and
69586d5f994SEdmund Nadolski  * the ref is moved onto the tree for indirect refs. After all missing
69686d5f994SEdmund Nadolski  * keys are thus located, we iterate over the indirect ref tree, resolve
69786d5f994SEdmund Nadolski  * each reference, and then insert the resolved reference onto the
69886d5f994SEdmund Nadolski  * direct tree (merging there too).
69986d5f994SEdmund Nadolski  *
70086d5f994SEdmund Nadolski  * New backrefs (i.e., for parent nodes) are added to the appropriate
70186d5f994SEdmund Nadolski  * rbtree as they are encountered. The new backrefs are subsequently
70286d5f994SEdmund Nadolski  * resolved as above.
7038da6d581SJan Schmidt  */
704e0c476b1SJeff Mahoney static int resolve_indirect_refs(struct btrfs_fs_info *fs_info,
705da61d31aSJosef Bacik 				 struct btrfs_path *path, u64 time_seq,
70686d5f994SEdmund Nadolski 				 struct preftrees *preftrees,
707b25b0b87Sethanwu 				 const u64 *extent_item_pos,
708c995ab3cSZygo Blaxell 				 struct share_check *sc, bool ignore_offset)
7098da6d581SJan Schmidt {
7108da6d581SJan Schmidt 	int err;
7118da6d581SJan Schmidt 	int ret = 0;
7128da6d581SJan Schmidt 	struct ulist *parents;
7138da6d581SJan Schmidt 	struct ulist_node *node;
714cd1b413cSJan Schmidt 	struct ulist_iterator uiter;
71586d5f994SEdmund Nadolski 	struct rb_node *rnode;
7168da6d581SJan Schmidt 
7178da6d581SJan Schmidt 	parents = ulist_alloc(GFP_NOFS);
7188da6d581SJan Schmidt 	if (!parents)
7198da6d581SJan Schmidt 		return -ENOMEM;
7208da6d581SJan Schmidt 
7218da6d581SJan Schmidt 	/*
72286d5f994SEdmund Nadolski 	 * We could trade memory usage for performance here by iterating
72386d5f994SEdmund Nadolski 	 * the tree, allocating new refs for each insertion, and then
72486d5f994SEdmund Nadolski 	 * freeing the entire indirect tree when we're done.  In some test
72586d5f994SEdmund Nadolski 	 * cases, the tree can grow quite large (~200k objects).
7268da6d581SJan Schmidt 	 */
727ecf160b4SLiu Bo 	while ((rnode = rb_first_cached(&preftrees->indirect.root))) {
72886d5f994SEdmund Nadolski 		struct prelim_ref *ref;
72986d5f994SEdmund Nadolski 
73086d5f994SEdmund Nadolski 		ref = rb_entry(rnode, struct prelim_ref, rbnode);
73186d5f994SEdmund Nadolski 		if (WARN(ref->parent,
73286d5f994SEdmund Nadolski 			 "BUG: direct ref found in indirect tree")) {
73386d5f994SEdmund Nadolski 			ret = -EINVAL;
73486d5f994SEdmund Nadolski 			goto out;
73586d5f994SEdmund Nadolski 		}
73686d5f994SEdmund Nadolski 
737ecf160b4SLiu Bo 		rb_erase_cached(&ref->rbnode, &preftrees->indirect.root);
7386c336b21SJeff Mahoney 		preftrees->indirect.count--;
73986d5f994SEdmund Nadolski 
74086d5f994SEdmund Nadolski 		if (ref->count == 0) {
74186d5f994SEdmund Nadolski 			free_pref(ref);
7428da6d581SJan Schmidt 			continue;
74386d5f994SEdmund Nadolski 		}
74486d5f994SEdmund Nadolski 
745c9024219SFilipe Manana 		if (sc && ref->root_id != sc->root_objectid) {
74686d5f994SEdmund Nadolski 			free_pref(ref);
747dc046b10SJosef Bacik 			ret = BACKREF_FOUND_SHARED;
748dc046b10SJosef Bacik 			goto out;
749dc046b10SJosef Bacik 		}
750ed58f2e6Sethanwu 		err = resolve_indirect_ref(fs_info, path, time_seq, preftrees,
751ed58f2e6Sethanwu 					   ref, parents, extent_item_pos,
752b25b0b87Sethanwu 					   ignore_offset);
75395def2edSWang Shilong 		/*
75495def2edSWang Shilong 		 * we can only tolerate ENOENT,otherwise,we should catch error
75595def2edSWang Shilong 		 * and return directly.
75695def2edSWang Shilong 		 */
75795def2edSWang Shilong 		if (err == -ENOENT) {
7583ec4d323SEdmund Nadolski 			prelim_ref_insert(fs_info, &preftrees->direct, ref,
7593ec4d323SEdmund Nadolski 					  NULL);
7608da6d581SJan Schmidt 			continue;
76195def2edSWang Shilong 		} else if (err) {
76286d5f994SEdmund Nadolski 			free_pref(ref);
76395def2edSWang Shilong 			ret = err;
76495def2edSWang Shilong 			goto out;
76595def2edSWang Shilong 		}
7668da6d581SJan Schmidt 
7678da6d581SJan Schmidt 		/* we put the first parent into the ref at hand */
768cd1b413cSJan Schmidt 		ULIST_ITER_INIT(&uiter);
769cd1b413cSJan Schmidt 		node = ulist_next(parents, &uiter);
7708da6d581SJan Schmidt 		ref->parent = node ? node->val : 0;
7714dae077aSJeff Mahoney 		ref->inode_list = unode_aux_to_inode_list(node);
7728da6d581SJan Schmidt 
77386d5f994SEdmund Nadolski 		/* Add a prelim_ref(s) for any other parent(s). */
774cd1b413cSJan Schmidt 		while ((node = ulist_next(parents, &uiter))) {
77586d5f994SEdmund Nadolski 			struct prelim_ref *new_ref;
77686d5f994SEdmund Nadolski 
777b9e9a6cbSWang Shilong 			new_ref = kmem_cache_alloc(btrfs_prelim_ref_cache,
778b9e9a6cbSWang Shilong 						   GFP_NOFS);
7798da6d581SJan Schmidt 			if (!new_ref) {
78086d5f994SEdmund Nadolski 				free_pref(ref);
7818da6d581SJan Schmidt 				ret = -ENOMEM;
782e36902d4SWang Shilong 				goto out;
7838da6d581SJan Schmidt 			}
7848da6d581SJan Schmidt 			memcpy(new_ref, ref, sizeof(*ref));
7858da6d581SJan Schmidt 			new_ref->parent = node->val;
7864dae077aSJeff Mahoney 			new_ref->inode_list = unode_aux_to_inode_list(node);
7873ec4d323SEdmund Nadolski 			prelim_ref_insert(fs_info, &preftrees->direct,
7883ec4d323SEdmund Nadolski 					  new_ref, NULL);
7898da6d581SJan Schmidt 		}
79086d5f994SEdmund Nadolski 
7913ec4d323SEdmund Nadolski 		/*
79252042d8eSAndrea Gelmini 		 * Now it's a direct ref, put it in the direct tree. We must
7933ec4d323SEdmund Nadolski 		 * do this last because the ref could be merged/freed here.
7943ec4d323SEdmund Nadolski 		 */
7953ec4d323SEdmund Nadolski 		prelim_ref_insert(fs_info, &preftrees->direct, ref, NULL);
79686d5f994SEdmund Nadolski 
7978da6d581SJan Schmidt 		ulist_reinit(parents);
7989dd14fd6SEdmund Nadolski 		cond_resched();
7998da6d581SJan Schmidt 	}
800e36902d4SWang Shilong out:
8015614dc3aSFilipe Manana 	/*
8025614dc3aSFilipe Manana 	 * We may have inode lists attached to refs in the parents ulist, so we
8035614dc3aSFilipe Manana 	 * must free them before freeing the ulist and its refs.
8045614dc3aSFilipe Manana 	 */
8055614dc3aSFilipe Manana 	free_leaf_list(parents);
8068da6d581SJan Schmidt 	return ret;
8078da6d581SJan Schmidt }
8088da6d581SJan Schmidt 
809d5c88b73SJan Schmidt /*
810d5c88b73SJan Schmidt  * read tree blocks and add keys where required.
811d5c88b73SJan Schmidt  */
812e0c476b1SJeff Mahoney static int add_missing_keys(struct btrfs_fs_info *fs_info,
81338e3eebfSJosef Bacik 			    struct preftrees *preftrees, bool lock)
814d5c88b73SJan Schmidt {
815e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
816d5c88b73SJan Schmidt 	struct extent_buffer *eb;
81786d5f994SEdmund Nadolski 	struct preftree *tree = &preftrees->indirect_missing_keys;
81886d5f994SEdmund Nadolski 	struct rb_node *node;
819d5c88b73SJan Schmidt 
820ecf160b4SLiu Bo 	while ((node = rb_first_cached(&tree->root))) {
82186d5f994SEdmund Nadolski 		ref = rb_entry(node, struct prelim_ref, rbnode);
822ecf160b4SLiu Bo 		rb_erase_cached(node, &tree->root);
82386d5f994SEdmund Nadolski 
82486d5f994SEdmund Nadolski 		BUG_ON(ref->parent);	/* should not be a direct ref */
82586d5f994SEdmund Nadolski 		BUG_ON(ref->key_for_search.type);
826d5c88b73SJan Schmidt 		BUG_ON(!ref->wanted_disk_byte);
82786d5f994SEdmund Nadolski 
8281b7ec85eSJosef Bacik 		eb = read_tree_block(fs_info, ref->wanted_disk_byte,
8291b7ec85eSJosef Bacik 				     ref->root_id, 0, ref->level - 1, NULL);
83064c043deSLiu Bo 		if (IS_ERR(eb)) {
83186d5f994SEdmund Nadolski 			free_pref(ref);
83264c043deSLiu Bo 			return PTR_ERR(eb);
8334eb150d6SQu Wenruo 		}
8344eb150d6SQu Wenruo 		if (!extent_buffer_uptodate(eb)) {
83586d5f994SEdmund Nadolski 			free_pref(ref);
836416bc658SJosef Bacik 			free_extent_buffer(eb);
837416bc658SJosef Bacik 			return -EIO;
838416bc658SJosef Bacik 		}
8394eb150d6SQu Wenruo 
84038e3eebfSJosef Bacik 		if (lock)
841d5c88b73SJan Schmidt 			btrfs_tree_read_lock(eb);
842d5c88b73SJan Schmidt 		if (btrfs_header_level(eb) == 0)
843d5c88b73SJan Schmidt 			btrfs_item_key_to_cpu(eb, &ref->key_for_search, 0);
844d5c88b73SJan Schmidt 		else
845d5c88b73SJan Schmidt 			btrfs_node_key_to_cpu(eb, &ref->key_for_search, 0);
84638e3eebfSJosef Bacik 		if (lock)
847d5c88b73SJan Schmidt 			btrfs_tree_read_unlock(eb);
848d5c88b73SJan Schmidt 		free_extent_buffer(eb);
8493ec4d323SEdmund Nadolski 		prelim_ref_insert(fs_info, &preftrees->indirect, ref, NULL);
8509dd14fd6SEdmund Nadolski 		cond_resched();
851d5c88b73SJan Schmidt 	}
852d5c88b73SJan Schmidt 	return 0;
853d5c88b73SJan Schmidt }
854d5c88b73SJan Schmidt 
8558da6d581SJan Schmidt /*
8568da6d581SJan Schmidt  * add all currently queued delayed refs from this head whose seq nr is
8578da6d581SJan Schmidt  * smaller or equal that seq to the list
8588da6d581SJan Schmidt  */
85900142756SJeff Mahoney static int add_delayed_refs(const struct btrfs_fs_info *fs_info,
86000142756SJeff Mahoney 			    struct btrfs_delayed_ref_head *head, u64 seq,
861b25b0b87Sethanwu 			    struct preftrees *preftrees, struct share_check *sc)
8628da6d581SJan Schmidt {
863c6fc2454SQu Wenruo 	struct btrfs_delayed_ref_node *node;
864d5c88b73SJan Schmidt 	struct btrfs_key key;
8650e0adbcfSJosef Bacik 	struct rb_node *n;
86601747e92SEdmund Nadolski 	int count;
867b1375d64SJan Schmidt 	int ret = 0;
8688da6d581SJan Schmidt 
869d7df2c79SJosef Bacik 	spin_lock(&head->lock);
870e3d03965SLiu Bo 	for (n = rb_first_cached(&head->ref_tree); n; n = rb_next(n)) {
8710e0adbcfSJosef Bacik 		node = rb_entry(n, struct btrfs_delayed_ref_node,
8720e0adbcfSJosef Bacik 				ref_node);
8738da6d581SJan Schmidt 		if (node->seq > seq)
8748da6d581SJan Schmidt 			continue;
8758da6d581SJan Schmidt 
8768da6d581SJan Schmidt 		switch (node->action) {
8778da6d581SJan Schmidt 		case BTRFS_ADD_DELAYED_EXTENT:
8788da6d581SJan Schmidt 		case BTRFS_UPDATE_DELAYED_HEAD:
8798da6d581SJan Schmidt 			WARN_ON(1);
8808da6d581SJan Schmidt 			continue;
8818da6d581SJan Schmidt 		case BTRFS_ADD_DELAYED_REF:
88201747e92SEdmund Nadolski 			count = node->ref_mod;
8838da6d581SJan Schmidt 			break;
8848da6d581SJan Schmidt 		case BTRFS_DROP_DELAYED_REF:
88501747e92SEdmund Nadolski 			count = node->ref_mod * -1;
8868da6d581SJan Schmidt 			break;
8878da6d581SJan Schmidt 		default:
888290342f6SArnd Bergmann 			BUG();
8898da6d581SJan Schmidt 		}
8908da6d581SJan Schmidt 		switch (node->type) {
8918da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY: {
89286d5f994SEdmund Nadolski 			/* NORMAL INDIRECT METADATA backref */
8938da6d581SJan Schmidt 			struct btrfs_delayed_tree_ref *ref;
894943553efSFilipe Manana 			struct btrfs_key *key_ptr = NULL;
895943553efSFilipe Manana 
896943553efSFilipe Manana 			if (head->extent_op && head->extent_op->update_key) {
897943553efSFilipe Manana 				btrfs_disk_key_to_cpu(&key, &head->extent_op->key);
898943553efSFilipe Manana 				key_ptr = &key;
899943553efSFilipe Manana 			}
9008da6d581SJan Schmidt 
9018da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_tree_ref(node);
90200142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, ref->root,
903943553efSFilipe Manana 					       key_ptr, ref->level + 1,
90401747e92SEdmund Nadolski 					       node->bytenr, count, sc,
90501747e92SEdmund Nadolski 					       GFP_ATOMIC);
9068da6d581SJan Schmidt 			break;
9078da6d581SJan Schmidt 		}
9088da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY: {
90986d5f994SEdmund Nadolski 			/* SHARED DIRECT METADATA backref */
9108da6d581SJan Schmidt 			struct btrfs_delayed_tree_ref *ref;
9118da6d581SJan Schmidt 
9128da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_tree_ref(node);
91386d5f994SEdmund Nadolski 
91401747e92SEdmund Nadolski 			ret = add_direct_ref(fs_info, preftrees, ref->level + 1,
91501747e92SEdmund Nadolski 					     ref->parent, node->bytenr, count,
9163ec4d323SEdmund Nadolski 					     sc, GFP_ATOMIC);
9178da6d581SJan Schmidt 			break;
9188da6d581SJan Schmidt 		}
9198da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
92086d5f994SEdmund Nadolski 			/* NORMAL INDIRECT DATA backref */
9218da6d581SJan Schmidt 			struct btrfs_delayed_data_ref *ref;
9228da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_data_ref(node);
9238da6d581SJan Schmidt 
9248da6d581SJan Schmidt 			key.objectid = ref->objectid;
9258da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
9268da6d581SJan Schmidt 			key.offset = ref->offset;
927dc046b10SJosef Bacik 
928dc046b10SJosef Bacik 			/*
9294fc7b572SFilipe Manana 			 * If we have a share check context and a reference for
9304fc7b572SFilipe Manana 			 * another inode, we can't exit immediately. This is
9314fc7b572SFilipe Manana 			 * because even if this is a BTRFS_ADD_DELAYED_REF
9324fc7b572SFilipe Manana 			 * reference we may find next a BTRFS_DROP_DELAYED_REF
9334fc7b572SFilipe Manana 			 * which cancels out this ADD reference.
9344fc7b572SFilipe Manana 			 *
9354fc7b572SFilipe Manana 			 * If this is a DROP reference and there was no previous
9364fc7b572SFilipe Manana 			 * ADD reference, then we need to signal that when we
9374fc7b572SFilipe Manana 			 * process references from the extent tree (through
9384fc7b572SFilipe Manana 			 * add_inline_refs() and add_keyed_refs()), we should
9394fc7b572SFilipe Manana 			 * not exit early if we find a reference for another
9404fc7b572SFilipe Manana 			 * inode, because one of the delayed DROP references
9414fc7b572SFilipe Manana 			 * may cancel that reference in the extent tree.
942dc046b10SJosef Bacik 			 */
9434fc7b572SFilipe Manana 			if (sc && count < 0)
9444fc7b572SFilipe Manana 				sc->have_delayed_delete_refs = true;
945dc046b10SJosef Bacik 
94600142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, ref->root,
94701747e92SEdmund Nadolski 					       &key, 0, node->bytenr, count, sc,
94801747e92SEdmund Nadolski 					       GFP_ATOMIC);
9498da6d581SJan Schmidt 			break;
9508da6d581SJan Schmidt 		}
9518da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
95286d5f994SEdmund Nadolski 			/* SHARED DIRECT FULL backref */
9538da6d581SJan Schmidt 			struct btrfs_delayed_data_ref *ref;
9548da6d581SJan Schmidt 
9558da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_data_ref(node);
95686d5f994SEdmund Nadolski 
95701747e92SEdmund Nadolski 			ret = add_direct_ref(fs_info, preftrees, 0, ref->parent,
95801747e92SEdmund Nadolski 					     node->bytenr, count, sc,
95901747e92SEdmund Nadolski 					     GFP_ATOMIC);
9608da6d581SJan Schmidt 			break;
9618da6d581SJan Schmidt 		}
9628da6d581SJan Schmidt 		default:
9638da6d581SJan Schmidt 			WARN_ON(1);
9648da6d581SJan Schmidt 		}
9653ec4d323SEdmund Nadolski 		/*
9663ec4d323SEdmund Nadolski 		 * We must ignore BACKREF_FOUND_SHARED until all delayed
9673ec4d323SEdmund Nadolski 		 * refs have been checked.
9683ec4d323SEdmund Nadolski 		 */
9693ec4d323SEdmund Nadolski 		if (ret && (ret != BACKREF_FOUND_SHARED))
970d7df2c79SJosef Bacik 			break;
9718da6d581SJan Schmidt 	}
9723ec4d323SEdmund Nadolski 	if (!ret)
9733ec4d323SEdmund Nadolski 		ret = extent_is_shared(sc);
9744fc7b572SFilipe Manana 
975d7df2c79SJosef Bacik 	spin_unlock(&head->lock);
976d7df2c79SJosef Bacik 	return ret;
9778da6d581SJan Schmidt }
9788da6d581SJan Schmidt 
9798da6d581SJan Schmidt /*
9808da6d581SJan Schmidt  * add all inline backrefs for bytenr to the list
9813ec4d323SEdmund Nadolski  *
9823ec4d323SEdmund Nadolski  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
9838da6d581SJan Schmidt  */
98400142756SJeff Mahoney static int add_inline_refs(const struct btrfs_fs_info *fs_info,
98500142756SJeff Mahoney 			   struct btrfs_path *path, u64 bytenr,
98686d5f994SEdmund Nadolski 			   int *info_level, struct preftrees *preftrees,
987b25b0b87Sethanwu 			   struct share_check *sc)
9888da6d581SJan Schmidt {
989b1375d64SJan Schmidt 	int ret = 0;
9908da6d581SJan Schmidt 	int slot;
9918da6d581SJan Schmidt 	struct extent_buffer *leaf;
9928da6d581SJan Schmidt 	struct btrfs_key key;
993261c84b6SJosef Bacik 	struct btrfs_key found_key;
9948da6d581SJan Schmidt 	unsigned long ptr;
9958da6d581SJan Schmidt 	unsigned long end;
9968da6d581SJan Schmidt 	struct btrfs_extent_item *ei;
9978da6d581SJan Schmidt 	u64 flags;
9988da6d581SJan Schmidt 	u64 item_size;
9998da6d581SJan Schmidt 
10008da6d581SJan Schmidt 	/*
10018da6d581SJan Schmidt 	 * enumerate all inline refs
10028da6d581SJan Schmidt 	 */
10038da6d581SJan Schmidt 	leaf = path->nodes[0];
1004dadcaf78SJan Schmidt 	slot = path->slots[0];
10058da6d581SJan Schmidt 
10063212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, slot);
10078da6d581SJan Schmidt 	BUG_ON(item_size < sizeof(*ei));
10088da6d581SJan Schmidt 
10098da6d581SJan Schmidt 	ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
10108da6d581SJan Schmidt 	flags = btrfs_extent_flags(leaf, ei);
1011261c84b6SJosef Bacik 	btrfs_item_key_to_cpu(leaf, &found_key, slot);
10128da6d581SJan Schmidt 
10138da6d581SJan Schmidt 	ptr = (unsigned long)(ei + 1);
10148da6d581SJan Schmidt 	end = (unsigned long)ei + item_size;
10158da6d581SJan Schmidt 
1016261c84b6SJosef Bacik 	if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
1017261c84b6SJosef Bacik 	    flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
10188da6d581SJan Schmidt 		struct btrfs_tree_block_info *info;
10198da6d581SJan Schmidt 
10208da6d581SJan Schmidt 		info = (struct btrfs_tree_block_info *)ptr;
10218da6d581SJan Schmidt 		*info_level = btrfs_tree_block_level(leaf, info);
10228da6d581SJan Schmidt 		ptr += sizeof(struct btrfs_tree_block_info);
10238da6d581SJan Schmidt 		BUG_ON(ptr > end);
1024261c84b6SJosef Bacik 	} else if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
1025261c84b6SJosef Bacik 		*info_level = found_key.offset;
10268da6d581SJan Schmidt 	} else {
10278da6d581SJan Schmidt 		BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
10288da6d581SJan Schmidt 	}
10298da6d581SJan Schmidt 
10308da6d581SJan Schmidt 	while (ptr < end) {
10318da6d581SJan Schmidt 		struct btrfs_extent_inline_ref *iref;
10328da6d581SJan Schmidt 		u64 offset;
10338da6d581SJan Schmidt 		int type;
10348da6d581SJan Schmidt 
10358da6d581SJan Schmidt 		iref = (struct btrfs_extent_inline_ref *)ptr;
10363de28d57SLiu Bo 		type = btrfs_get_extent_inline_ref_type(leaf, iref,
10373de28d57SLiu Bo 							BTRFS_REF_TYPE_ANY);
10383de28d57SLiu Bo 		if (type == BTRFS_REF_TYPE_INVALID)
1039af431dcbSSu Yue 			return -EUCLEAN;
10403de28d57SLiu Bo 
10418da6d581SJan Schmidt 		offset = btrfs_extent_inline_ref_offset(leaf, iref);
10428da6d581SJan Schmidt 
10438da6d581SJan Schmidt 		switch (type) {
10448da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY:
104500142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees,
104600142756SJeff Mahoney 					     *info_level + 1, offset,
10473ec4d323SEdmund Nadolski 					     bytenr, 1, NULL, GFP_NOFS);
10488da6d581SJan Schmidt 			break;
10498da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
10508da6d581SJan Schmidt 			struct btrfs_shared_data_ref *sdref;
10518da6d581SJan Schmidt 			int count;
10528da6d581SJan Schmidt 
10538da6d581SJan Schmidt 			sdref = (struct btrfs_shared_data_ref *)(iref + 1);
10548da6d581SJan Schmidt 			count = btrfs_shared_data_ref_count(leaf, sdref);
105586d5f994SEdmund Nadolski 
105600142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees, 0, offset,
10573ec4d323SEdmund Nadolski 					     bytenr, count, sc, GFP_NOFS);
10588da6d581SJan Schmidt 			break;
10598da6d581SJan Schmidt 		}
10608da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY:
106100142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, offset,
106200142756SJeff Mahoney 					       NULL, *info_level + 1,
10633ec4d323SEdmund Nadolski 					       bytenr, 1, NULL, GFP_NOFS);
10648da6d581SJan Schmidt 			break;
10658da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
10668da6d581SJan Schmidt 			struct btrfs_extent_data_ref *dref;
10678da6d581SJan Schmidt 			int count;
10688da6d581SJan Schmidt 			u64 root;
10698da6d581SJan Schmidt 
10708da6d581SJan Schmidt 			dref = (struct btrfs_extent_data_ref *)(&iref->offset);
10718da6d581SJan Schmidt 			count = btrfs_extent_data_ref_count(leaf, dref);
10728da6d581SJan Schmidt 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
10738da6d581SJan Schmidt 								      dref);
10748da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
10758da6d581SJan Schmidt 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1076dc046b10SJosef Bacik 
1077a0a5472aSFilipe Manana 			if (sc && key.objectid != sc->inum &&
10784fc7b572SFilipe Manana 			    !sc->have_delayed_delete_refs) {
1079dc046b10SJosef Bacik 				ret = BACKREF_FOUND_SHARED;
1080dc046b10SJosef Bacik 				break;
1081dc046b10SJosef Bacik 			}
1082dc046b10SJosef Bacik 
10838da6d581SJan Schmidt 			root = btrfs_extent_data_ref_root(leaf, dref);
108486d5f994SEdmund Nadolski 
108500142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, root,
108600142756SJeff Mahoney 					       &key, 0, bytenr, count,
10873ec4d323SEdmund Nadolski 					       sc, GFP_NOFS);
10884fc7b572SFilipe Manana 
10898da6d581SJan Schmidt 			break;
10908da6d581SJan Schmidt 		}
10918da6d581SJan Schmidt 		default:
10928da6d581SJan Schmidt 			WARN_ON(1);
10938da6d581SJan Schmidt 		}
10941149ab6bSWang Shilong 		if (ret)
10951149ab6bSWang Shilong 			return ret;
10968da6d581SJan Schmidt 		ptr += btrfs_extent_inline_ref_size(type);
10978da6d581SJan Schmidt 	}
10988da6d581SJan Schmidt 
10998da6d581SJan Schmidt 	return 0;
11008da6d581SJan Schmidt }
11018da6d581SJan Schmidt 
11028da6d581SJan Schmidt /*
11038da6d581SJan Schmidt  * add all non-inline backrefs for bytenr to the list
11043ec4d323SEdmund Nadolski  *
11053ec4d323SEdmund Nadolski  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
11068da6d581SJan Schmidt  */
110798cc4222SJosef Bacik static int add_keyed_refs(struct btrfs_root *extent_root,
11088da6d581SJan Schmidt 			  struct btrfs_path *path, u64 bytenr,
110986d5f994SEdmund Nadolski 			  int info_level, struct preftrees *preftrees,
11103ec4d323SEdmund Nadolski 			  struct share_check *sc)
11118da6d581SJan Schmidt {
111298cc4222SJosef Bacik 	struct btrfs_fs_info *fs_info = extent_root->fs_info;
11138da6d581SJan Schmidt 	int ret;
11148da6d581SJan Schmidt 	int slot;
11158da6d581SJan Schmidt 	struct extent_buffer *leaf;
11168da6d581SJan Schmidt 	struct btrfs_key key;
11178da6d581SJan Schmidt 
11188da6d581SJan Schmidt 	while (1) {
11198da6d581SJan Schmidt 		ret = btrfs_next_item(extent_root, path);
11208da6d581SJan Schmidt 		if (ret < 0)
11218da6d581SJan Schmidt 			break;
11228da6d581SJan Schmidt 		if (ret) {
11238da6d581SJan Schmidt 			ret = 0;
11248da6d581SJan Schmidt 			break;
11258da6d581SJan Schmidt 		}
11268da6d581SJan Schmidt 
11278da6d581SJan Schmidt 		slot = path->slots[0];
11288da6d581SJan Schmidt 		leaf = path->nodes[0];
11298da6d581SJan Schmidt 		btrfs_item_key_to_cpu(leaf, &key, slot);
11308da6d581SJan Schmidt 
11318da6d581SJan Schmidt 		if (key.objectid != bytenr)
11328da6d581SJan Schmidt 			break;
11338da6d581SJan Schmidt 		if (key.type < BTRFS_TREE_BLOCK_REF_KEY)
11348da6d581SJan Schmidt 			continue;
11358da6d581SJan Schmidt 		if (key.type > BTRFS_SHARED_DATA_REF_KEY)
11368da6d581SJan Schmidt 			break;
11378da6d581SJan Schmidt 
11388da6d581SJan Schmidt 		switch (key.type) {
11398da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY:
114086d5f994SEdmund Nadolski 			/* SHARED DIRECT METADATA backref */
114100142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees,
114200142756SJeff Mahoney 					     info_level + 1, key.offset,
11433ec4d323SEdmund Nadolski 					     bytenr, 1, NULL, GFP_NOFS);
11448da6d581SJan Schmidt 			break;
11458da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
114686d5f994SEdmund Nadolski 			/* SHARED DIRECT FULL backref */
11478da6d581SJan Schmidt 			struct btrfs_shared_data_ref *sdref;
11488da6d581SJan Schmidt 			int count;
11498da6d581SJan Schmidt 
11508da6d581SJan Schmidt 			sdref = btrfs_item_ptr(leaf, slot,
11518da6d581SJan Schmidt 					      struct btrfs_shared_data_ref);
11528da6d581SJan Schmidt 			count = btrfs_shared_data_ref_count(leaf, sdref);
115300142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees, 0,
115400142756SJeff Mahoney 					     key.offset, bytenr, count,
11553ec4d323SEdmund Nadolski 					     sc, GFP_NOFS);
11568da6d581SJan Schmidt 			break;
11578da6d581SJan Schmidt 		}
11588da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY:
115986d5f994SEdmund Nadolski 			/* NORMAL INDIRECT METADATA backref */
116000142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, key.offset,
116100142756SJeff Mahoney 					       NULL, info_level + 1, bytenr,
11623ec4d323SEdmund Nadolski 					       1, NULL, GFP_NOFS);
11638da6d581SJan Schmidt 			break;
11648da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
116586d5f994SEdmund Nadolski 			/* NORMAL INDIRECT DATA backref */
11668da6d581SJan Schmidt 			struct btrfs_extent_data_ref *dref;
11678da6d581SJan Schmidt 			int count;
11688da6d581SJan Schmidt 			u64 root;
11698da6d581SJan Schmidt 
11708da6d581SJan Schmidt 			dref = btrfs_item_ptr(leaf, slot,
11718da6d581SJan Schmidt 					      struct btrfs_extent_data_ref);
11728da6d581SJan Schmidt 			count = btrfs_extent_data_ref_count(leaf, dref);
11738da6d581SJan Schmidt 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
11748da6d581SJan Schmidt 								      dref);
11758da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
11768da6d581SJan Schmidt 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1177dc046b10SJosef Bacik 
1178a0a5472aSFilipe Manana 			if (sc && key.objectid != sc->inum &&
11794fc7b572SFilipe Manana 			    !sc->have_delayed_delete_refs) {
1180dc046b10SJosef Bacik 				ret = BACKREF_FOUND_SHARED;
1181dc046b10SJosef Bacik 				break;
1182dc046b10SJosef Bacik 			}
1183dc046b10SJosef Bacik 
11848da6d581SJan Schmidt 			root = btrfs_extent_data_ref_root(leaf, dref);
118500142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, root,
118600142756SJeff Mahoney 					       &key, 0, bytenr, count,
11873ec4d323SEdmund Nadolski 					       sc, GFP_NOFS);
11888da6d581SJan Schmidt 			break;
11898da6d581SJan Schmidt 		}
11908da6d581SJan Schmidt 		default:
11918da6d581SJan Schmidt 			WARN_ON(1);
11928da6d581SJan Schmidt 		}
11931149ab6bSWang Shilong 		if (ret)
11941149ab6bSWang Shilong 			return ret;
11951149ab6bSWang Shilong 
11968da6d581SJan Schmidt 	}
11978da6d581SJan Schmidt 
11988da6d581SJan Schmidt 	return ret;
11998da6d581SJan Schmidt }
12008da6d581SJan Schmidt 
12018da6d581SJan Schmidt /*
1202*583f4ac5SFilipe Manana  * The caller has joined a transaction or is holding a read lock on the
1203*583f4ac5SFilipe Manana  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1204*583f4ac5SFilipe Manana  * snapshot field changing while updating or checking the cache.
1205*583f4ac5SFilipe Manana  */
1206*583f4ac5SFilipe Manana static bool lookup_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1207*583f4ac5SFilipe Manana 					struct btrfs_root *root,
1208*583f4ac5SFilipe Manana 					u64 bytenr, int level, bool *is_shared)
1209*583f4ac5SFilipe Manana {
1210*583f4ac5SFilipe Manana 	struct btrfs_backref_shared_cache_entry *entry;
1211*583f4ac5SFilipe Manana 
1212*583f4ac5SFilipe Manana 	if (!ctx->use_path_cache)
1213*583f4ac5SFilipe Manana 		return false;
1214*583f4ac5SFilipe Manana 
1215*583f4ac5SFilipe Manana 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1216*583f4ac5SFilipe Manana 		return false;
1217*583f4ac5SFilipe Manana 
1218*583f4ac5SFilipe Manana 	/*
1219*583f4ac5SFilipe Manana 	 * Level -1 is used for the data extent, which is not reliable to cache
1220*583f4ac5SFilipe Manana 	 * because its reference count can increase or decrease without us
1221*583f4ac5SFilipe Manana 	 * realizing. We cache results only for extent buffers that lead from
1222*583f4ac5SFilipe Manana 	 * the root node down to the leaf with the file extent item.
1223*583f4ac5SFilipe Manana 	 */
1224*583f4ac5SFilipe Manana 	ASSERT(level >= 0);
1225*583f4ac5SFilipe Manana 
1226*583f4ac5SFilipe Manana 	entry = &ctx->path_cache_entries[level];
1227*583f4ac5SFilipe Manana 
1228*583f4ac5SFilipe Manana 	/* Unused cache entry or being used for some other extent buffer. */
1229*583f4ac5SFilipe Manana 	if (entry->bytenr != bytenr)
1230*583f4ac5SFilipe Manana 		return false;
1231*583f4ac5SFilipe Manana 
1232*583f4ac5SFilipe Manana 	/*
1233*583f4ac5SFilipe Manana 	 * We cached a false result, but the last snapshot generation of the
1234*583f4ac5SFilipe Manana 	 * root changed, so we now have a snapshot. Don't trust the result.
1235*583f4ac5SFilipe Manana 	 */
1236*583f4ac5SFilipe Manana 	if (!entry->is_shared &&
1237*583f4ac5SFilipe Manana 	    entry->gen != btrfs_root_last_snapshot(&root->root_item))
1238*583f4ac5SFilipe Manana 		return false;
1239*583f4ac5SFilipe Manana 
1240*583f4ac5SFilipe Manana 	/*
1241*583f4ac5SFilipe Manana 	 * If we cached a true result and the last generation used for dropping
1242*583f4ac5SFilipe Manana 	 * a root changed, we can not trust the result, because the dropped root
1243*583f4ac5SFilipe Manana 	 * could be a snapshot sharing this extent buffer.
1244*583f4ac5SFilipe Manana 	 */
1245*583f4ac5SFilipe Manana 	if (entry->is_shared &&
1246*583f4ac5SFilipe Manana 	    entry->gen != btrfs_get_last_root_drop_gen(root->fs_info))
1247*583f4ac5SFilipe Manana 		return false;
1248*583f4ac5SFilipe Manana 
1249*583f4ac5SFilipe Manana 	*is_shared = entry->is_shared;
1250*583f4ac5SFilipe Manana 	/*
1251*583f4ac5SFilipe Manana 	 * If the node at this level is shared, than all nodes below are also
1252*583f4ac5SFilipe Manana 	 * shared. Currently some of the nodes below may be marked as not shared
1253*583f4ac5SFilipe Manana 	 * because we have just switched from one leaf to another, and switched
1254*583f4ac5SFilipe Manana 	 * also other nodes above the leaf and below the current level, so mark
1255*583f4ac5SFilipe Manana 	 * them as shared.
1256*583f4ac5SFilipe Manana 	 */
1257*583f4ac5SFilipe Manana 	if (*is_shared) {
1258*583f4ac5SFilipe Manana 		for (int i = 0; i < level; i++) {
1259*583f4ac5SFilipe Manana 			ctx->path_cache_entries[i].is_shared = true;
1260*583f4ac5SFilipe Manana 			ctx->path_cache_entries[i].gen = entry->gen;
1261*583f4ac5SFilipe Manana 		}
1262*583f4ac5SFilipe Manana 	}
1263*583f4ac5SFilipe Manana 
1264*583f4ac5SFilipe Manana 	return true;
1265*583f4ac5SFilipe Manana }
1266*583f4ac5SFilipe Manana 
1267*583f4ac5SFilipe Manana /*
1268*583f4ac5SFilipe Manana  * The caller has joined a transaction or is holding a read lock on the
1269*583f4ac5SFilipe Manana  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1270*583f4ac5SFilipe Manana  * snapshot field changing while updating or checking the cache.
1271*583f4ac5SFilipe Manana  */
1272*583f4ac5SFilipe Manana static void store_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1273*583f4ac5SFilipe Manana 				       struct btrfs_root *root,
1274*583f4ac5SFilipe Manana 				       u64 bytenr, int level, bool is_shared)
1275*583f4ac5SFilipe Manana {
1276*583f4ac5SFilipe Manana 	struct btrfs_backref_shared_cache_entry *entry;
1277*583f4ac5SFilipe Manana 	u64 gen;
1278*583f4ac5SFilipe Manana 
1279*583f4ac5SFilipe Manana 	if (!ctx->use_path_cache)
1280*583f4ac5SFilipe Manana 		return;
1281*583f4ac5SFilipe Manana 
1282*583f4ac5SFilipe Manana 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1283*583f4ac5SFilipe Manana 		return;
1284*583f4ac5SFilipe Manana 
1285*583f4ac5SFilipe Manana 	/*
1286*583f4ac5SFilipe Manana 	 * Level -1 is used for the data extent, which is not reliable to cache
1287*583f4ac5SFilipe Manana 	 * because its reference count can increase or decrease without us
1288*583f4ac5SFilipe Manana 	 * realizing. We cache results only for extent buffers that lead from
1289*583f4ac5SFilipe Manana 	 * the root node down to the leaf with the file extent item.
1290*583f4ac5SFilipe Manana 	 */
1291*583f4ac5SFilipe Manana 	ASSERT(level >= 0);
1292*583f4ac5SFilipe Manana 
1293*583f4ac5SFilipe Manana 	if (is_shared)
1294*583f4ac5SFilipe Manana 		gen = btrfs_get_last_root_drop_gen(root->fs_info);
1295*583f4ac5SFilipe Manana 	else
1296*583f4ac5SFilipe Manana 		gen = btrfs_root_last_snapshot(&root->root_item);
1297*583f4ac5SFilipe Manana 
1298*583f4ac5SFilipe Manana 	entry = &ctx->path_cache_entries[level];
1299*583f4ac5SFilipe Manana 	entry->bytenr = bytenr;
1300*583f4ac5SFilipe Manana 	entry->is_shared = is_shared;
1301*583f4ac5SFilipe Manana 	entry->gen = gen;
1302*583f4ac5SFilipe Manana 
1303*583f4ac5SFilipe Manana 	/*
1304*583f4ac5SFilipe Manana 	 * If we found an extent buffer is shared, set the cache result for all
1305*583f4ac5SFilipe Manana 	 * extent buffers below it to true. As nodes in the path are COWed,
1306*583f4ac5SFilipe Manana 	 * their sharedness is moved to their children, and if a leaf is COWed,
1307*583f4ac5SFilipe Manana 	 * then the sharedness of a data extent becomes direct, the refcount of
1308*583f4ac5SFilipe Manana 	 * data extent is increased in the extent item at the extent tree.
1309*583f4ac5SFilipe Manana 	 */
1310*583f4ac5SFilipe Manana 	if (is_shared) {
1311*583f4ac5SFilipe Manana 		for (int i = 0; i < level; i++) {
1312*583f4ac5SFilipe Manana 			entry = &ctx->path_cache_entries[i];
1313*583f4ac5SFilipe Manana 			entry->is_shared = is_shared;
1314*583f4ac5SFilipe Manana 			entry->gen = gen;
1315*583f4ac5SFilipe Manana 		}
1316*583f4ac5SFilipe Manana 	}
1317*583f4ac5SFilipe Manana }
1318*583f4ac5SFilipe Manana 
1319*583f4ac5SFilipe Manana /*
13208da6d581SJan Schmidt  * this adds all existing backrefs (inline backrefs, backrefs and delayed
13218da6d581SJan Schmidt  * refs) for the given bytenr to the refs list, merges duplicates and resolves
13228da6d581SJan Schmidt  * indirect refs to their parent bytenr.
13238da6d581SJan Schmidt  * When roots are found, they're added to the roots list
13248da6d581SJan Schmidt  *
1325f3a84ccdSFilipe Manana  * If time_seq is set to BTRFS_SEQ_LAST, it will not search delayed_refs, and
1326f3a84ccdSFilipe Manana  * behave much like trans == NULL case, the difference only lies in it will not
132721633fc6SQu Wenruo  * commit root.
132821633fc6SQu Wenruo  * The special case is for qgroup to search roots in commit_transaction().
132921633fc6SQu Wenruo  *
13303ec4d323SEdmund Nadolski  * @sc - if !NULL, then immediately return BACKREF_FOUND_SHARED when a
13313ec4d323SEdmund Nadolski  * shared extent is detected.
13323ec4d323SEdmund Nadolski  *
13333ec4d323SEdmund Nadolski  * Otherwise this returns 0 for success and <0 for an error.
13343ec4d323SEdmund Nadolski  *
1335c995ab3cSZygo Blaxell  * If ignore_offset is set to false, only extent refs whose offsets match
1336c995ab3cSZygo Blaxell  * extent_item_pos are returned.  If true, every extent ref is returned
1337c995ab3cSZygo Blaxell  * and extent_item_pos is ignored.
1338c995ab3cSZygo Blaxell  *
13398da6d581SJan Schmidt  * FIXME some caching might speed things up
13408da6d581SJan Schmidt  */
13418da6d581SJan Schmidt static int find_parent_nodes(struct btrfs_trans_handle *trans,
13428da6d581SJan Schmidt 			     struct btrfs_fs_info *fs_info, u64 bytenr,
1343097b8a7cSJan Schmidt 			     u64 time_seq, struct ulist *refs,
1344dc046b10SJosef Bacik 			     struct ulist *roots, const u64 *extent_item_pos,
1345c995ab3cSZygo Blaxell 			     struct share_check *sc, bool ignore_offset)
13468da6d581SJan Schmidt {
134729cbcf40SJosef Bacik 	struct btrfs_root *root = btrfs_extent_root(fs_info, bytenr);
13488da6d581SJan Schmidt 	struct btrfs_key key;
13498da6d581SJan Schmidt 	struct btrfs_path *path;
13508da6d581SJan Schmidt 	struct btrfs_delayed_ref_root *delayed_refs = NULL;
1351d3b01064SLi Zefan 	struct btrfs_delayed_ref_head *head;
13528da6d581SJan Schmidt 	int info_level = 0;
13538da6d581SJan Schmidt 	int ret;
1354e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
135586d5f994SEdmund Nadolski 	struct rb_node *node;
1356f05c4746SWang Shilong 	struct extent_inode_elem *eie = NULL;
135786d5f994SEdmund Nadolski 	struct preftrees preftrees = {
135886d5f994SEdmund Nadolski 		.direct = PREFTREE_INIT,
135986d5f994SEdmund Nadolski 		.indirect = PREFTREE_INIT,
136086d5f994SEdmund Nadolski 		.indirect_missing_keys = PREFTREE_INIT
136186d5f994SEdmund Nadolski 	};
13628da6d581SJan Schmidt 
136356f5c199SFilipe Manana 	/* Roots ulist is not needed when using a sharedness check context. */
136456f5c199SFilipe Manana 	if (sc)
136556f5c199SFilipe Manana 		ASSERT(roots == NULL);
136656f5c199SFilipe Manana 
13678da6d581SJan Schmidt 	key.objectid = bytenr;
13688da6d581SJan Schmidt 	key.offset = (u64)-1;
1369261c84b6SJosef Bacik 	if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1370261c84b6SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
1371261c84b6SJosef Bacik 	else
1372261c84b6SJosef Bacik 		key.type = BTRFS_EXTENT_ITEM_KEY;
13738da6d581SJan Schmidt 
13748da6d581SJan Schmidt 	path = btrfs_alloc_path();
13758da6d581SJan Schmidt 	if (!path)
13768da6d581SJan Schmidt 		return -ENOMEM;
1377e84752d4SWang Shilong 	if (!trans) {
1378da61d31aSJosef Bacik 		path->search_commit_root = 1;
1379e84752d4SWang Shilong 		path->skip_locking = 1;
1380e84752d4SWang Shilong 	}
13818da6d581SJan Schmidt 
1382f3a84ccdSFilipe Manana 	if (time_seq == BTRFS_SEQ_LAST)
138321633fc6SQu Wenruo 		path->skip_locking = 1;
138421633fc6SQu Wenruo 
13858da6d581SJan Schmidt again:
1386d3b01064SLi Zefan 	head = NULL;
1387d3b01064SLi Zefan 
138898cc4222SJosef Bacik 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
13898da6d581SJan Schmidt 	if (ret < 0)
13908da6d581SJan Schmidt 		goto out;
1391fcba0120SJosef Bacik 	if (ret == 0) {
1392fcba0120SJosef Bacik 		/* This shouldn't happen, indicates a bug or fs corruption. */
1393fcba0120SJosef Bacik 		ASSERT(ret != 0);
1394fcba0120SJosef Bacik 		ret = -EUCLEAN;
1395fcba0120SJosef Bacik 		goto out;
1396fcba0120SJosef Bacik 	}
13978da6d581SJan Schmidt 
139821633fc6SQu Wenruo 	if (trans && likely(trans->type != __TRANS_DUMMY) &&
1399f3a84ccdSFilipe Manana 	    time_seq != BTRFS_SEQ_LAST) {
14008da6d581SJan Schmidt 		/*
14019665ebd5SJosef Bacik 		 * We have a specific time_seq we care about and trans which
14029665ebd5SJosef Bacik 		 * means we have the path lock, we need to grab the ref head and
14039665ebd5SJosef Bacik 		 * lock it so we have a consistent view of the refs at the given
14049665ebd5SJosef Bacik 		 * time.
14058da6d581SJan Schmidt 		 */
14068da6d581SJan Schmidt 		delayed_refs = &trans->transaction->delayed_refs;
14078da6d581SJan Schmidt 		spin_lock(&delayed_refs->lock);
1408f72ad18eSLiu Bo 		head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
14098da6d581SJan Schmidt 		if (head) {
14108da6d581SJan Schmidt 			if (!mutex_trylock(&head->mutex)) {
1411d278850eSJosef Bacik 				refcount_inc(&head->refs);
14128da6d581SJan Schmidt 				spin_unlock(&delayed_refs->lock);
14138da6d581SJan Schmidt 
14148da6d581SJan Schmidt 				btrfs_release_path(path);
14158da6d581SJan Schmidt 
14168da6d581SJan Schmidt 				/*
14178da6d581SJan Schmidt 				 * Mutex was contended, block until it's
14188da6d581SJan Schmidt 				 * released and try again
14198da6d581SJan Schmidt 				 */
14208da6d581SJan Schmidt 				mutex_lock(&head->mutex);
14218da6d581SJan Schmidt 				mutex_unlock(&head->mutex);
1422d278850eSJosef Bacik 				btrfs_put_delayed_ref_head(head);
14238da6d581SJan Schmidt 				goto again;
14248da6d581SJan Schmidt 			}
1425d7df2c79SJosef Bacik 			spin_unlock(&delayed_refs->lock);
142600142756SJeff Mahoney 			ret = add_delayed_refs(fs_info, head, time_seq,
1427b25b0b87Sethanwu 					       &preftrees, sc);
1428155725c9SJan Schmidt 			mutex_unlock(&head->mutex);
1429d7df2c79SJosef Bacik 			if (ret)
14308da6d581SJan Schmidt 				goto out;
1431d7df2c79SJosef Bacik 		} else {
14328da6d581SJan Schmidt 			spin_unlock(&delayed_refs->lock);
14337a3ae2f8SJan Schmidt 		}
1434d7df2c79SJosef Bacik 	}
14358da6d581SJan Schmidt 
14368da6d581SJan Schmidt 	if (path->slots[0]) {
14378da6d581SJan Schmidt 		struct extent_buffer *leaf;
14388da6d581SJan Schmidt 		int slot;
14398da6d581SJan Schmidt 
1440dadcaf78SJan Schmidt 		path->slots[0]--;
14418da6d581SJan Schmidt 		leaf = path->nodes[0];
1442dadcaf78SJan Schmidt 		slot = path->slots[0];
14438da6d581SJan Schmidt 		btrfs_item_key_to_cpu(leaf, &key, slot);
14448da6d581SJan Schmidt 		if (key.objectid == bytenr &&
1445261c84b6SJosef Bacik 		    (key.type == BTRFS_EXTENT_ITEM_KEY ||
1446261c84b6SJosef Bacik 		     key.type == BTRFS_METADATA_ITEM_KEY)) {
144700142756SJeff Mahoney 			ret = add_inline_refs(fs_info, path, bytenr,
1448b25b0b87Sethanwu 					      &info_level, &preftrees, sc);
14498da6d581SJan Schmidt 			if (ret)
14508da6d581SJan Schmidt 				goto out;
145198cc4222SJosef Bacik 			ret = add_keyed_refs(root, path, bytenr, info_level,
14523ec4d323SEdmund Nadolski 					     &preftrees, sc);
14538da6d581SJan Schmidt 			if (ret)
14548da6d581SJan Schmidt 				goto out;
14558da6d581SJan Schmidt 		}
14568da6d581SJan Schmidt 	}
145786d5f994SEdmund Nadolski 
145856f5c199SFilipe Manana 	/*
145956f5c199SFilipe Manana 	 * If we have a share context and we reached here, it means the extent
146056f5c199SFilipe Manana 	 * is not directly shared (no multiple reference items for it),
146156f5c199SFilipe Manana 	 * otherwise we would have exited earlier with a return value of
146256f5c199SFilipe Manana 	 * BACKREF_FOUND_SHARED after processing delayed references or while
146356f5c199SFilipe Manana 	 * processing inline or keyed references from the extent tree.
146456f5c199SFilipe Manana 	 * The extent may however be indirectly shared through shared subtrees
146556f5c199SFilipe Manana 	 * as a result from creating snapshots, so we determine below what is
146656f5c199SFilipe Manana 	 * its parent node, in case we are dealing with a metadata extent, or
146756f5c199SFilipe Manana 	 * what's the leaf (or leaves), from a fs tree, that has a file extent
146856f5c199SFilipe Manana 	 * item pointing to it in case we are dealing with a data extent.
146956f5c199SFilipe Manana 	 */
147056f5c199SFilipe Manana 	ASSERT(extent_is_shared(sc) == 0);
147156f5c199SFilipe Manana 
14728da6d581SJan Schmidt 	btrfs_release_path(path);
14738da6d581SJan Schmidt 
147438e3eebfSJosef Bacik 	ret = add_missing_keys(fs_info, &preftrees, path->skip_locking == 0);
1475d5c88b73SJan Schmidt 	if (ret)
1476d5c88b73SJan Schmidt 		goto out;
1477d5c88b73SJan Schmidt 
1478ecf160b4SLiu Bo 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect_missing_keys.root.rb_root));
14798da6d581SJan Schmidt 
148086d5f994SEdmund Nadolski 	ret = resolve_indirect_refs(fs_info, path, time_seq, &preftrees,
1481b25b0b87Sethanwu 				    extent_item_pos, sc, ignore_offset);
14828da6d581SJan Schmidt 	if (ret)
14838da6d581SJan Schmidt 		goto out;
14848da6d581SJan Schmidt 
1485ecf160b4SLiu Bo 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect.root.rb_root));
14868da6d581SJan Schmidt 
148786d5f994SEdmund Nadolski 	/*
148886d5f994SEdmund Nadolski 	 * This walks the tree of merged and resolved refs. Tree blocks are
148986d5f994SEdmund Nadolski 	 * read in as needed. Unique entries are added to the ulist, and
149086d5f994SEdmund Nadolski 	 * the list of found roots is updated.
149186d5f994SEdmund Nadolski 	 *
149286d5f994SEdmund Nadolski 	 * We release the entire tree in one go before returning.
149386d5f994SEdmund Nadolski 	 */
1494ecf160b4SLiu Bo 	node = rb_first_cached(&preftrees.direct.root);
149586d5f994SEdmund Nadolski 	while (node) {
149686d5f994SEdmund Nadolski 		ref = rb_entry(node, struct prelim_ref, rbnode);
149786d5f994SEdmund Nadolski 		node = rb_next(&ref->rbnode);
1498c8195a7bSZygo Blaxell 		/*
1499c8195a7bSZygo Blaxell 		 * ref->count < 0 can happen here if there are delayed
1500c8195a7bSZygo Blaxell 		 * refs with a node->action of BTRFS_DROP_DELAYED_REF.
1501c8195a7bSZygo Blaxell 		 * prelim_ref_insert() relies on this when merging
1502c8195a7bSZygo Blaxell 		 * identical refs to keep the overall count correct.
1503c8195a7bSZygo Blaxell 		 * prelim_ref_insert() will merge only those refs
1504c8195a7bSZygo Blaxell 		 * which compare identically.  Any refs having
1505c8195a7bSZygo Blaxell 		 * e.g. different offsets would not be merged,
1506c8195a7bSZygo Blaxell 		 * and would retain their original ref->count < 0.
1507c8195a7bSZygo Blaxell 		 */
150898cfee21SWang Shilong 		if (roots && ref->count && ref->root_id && ref->parent == 0) {
15098da6d581SJan Schmidt 			/* no parent == root of tree */
15108da6d581SJan Schmidt 			ret = ulist_add(roots, ref->root_id, 0, GFP_NOFS);
1511f1723939SWang Shilong 			if (ret < 0)
1512f1723939SWang Shilong 				goto out;
15138da6d581SJan Schmidt 		}
15148da6d581SJan Schmidt 		if (ref->count && ref->parent) {
15158a56457fSJosef Bacik 			if (extent_item_pos && !ref->inode_list &&
15168a56457fSJosef Bacik 			    ref->level == 0) {
1517976b1908SJan Schmidt 				struct extent_buffer *eb;
1518707e8a07SDavid Sterba 
1519581c1760SQu Wenruo 				eb = read_tree_block(fs_info, ref->parent, 0,
15201b7ec85eSJosef Bacik 						     0, ref->level, NULL);
152164c043deSLiu Bo 				if (IS_ERR(eb)) {
152264c043deSLiu Bo 					ret = PTR_ERR(eb);
152364c043deSLiu Bo 					goto out;
15244eb150d6SQu Wenruo 				}
15254eb150d6SQu Wenruo 				if (!extent_buffer_uptodate(eb)) {
1526416bc658SJosef Bacik 					free_extent_buffer(eb);
1527c16c2e2eSWang Shilong 					ret = -EIO;
1528c16c2e2eSWang Shilong 					goto out;
1529416bc658SJosef Bacik 				}
153038e3eebfSJosef Bacik 
1531ac5887c8SJosef Bacik 				if (!path->skip_locking)
15326f7ff6d7SFilipe Manana 					btrfs_tree_read_lock(eb);
1533976b1908SJan Schmidt 				ret = find_extent_in_eb(eb, bytenr,
1534c995ab3cSZygo Blaxell 							*extent_item_pos, &eie, ignore_offset);
153538e3eebfSJosef Bacik 				if (!path->skip_locking)
1536ac5887c8SJosef Bacik 					btrfs_tree_read_unlock(eb);
1537976b1908SJan Schmidt 				free_extent_buffer(eb);
1538f5929cd8SFilipe David Borba Manana 				if (ret < 0)
1539f5929cd8SFilipe David Borba Manana 					goto out;
1540f5929cd8SFilipe David Borba Manana 				ref->inode_list = eie;
154192876eecSFilipe Manana 				/*
154292876eecSFilipe Manana 				 * We transferred the list ownership to the ref,
154392876eecSFilipe Manana 				 * so set to NULL to avoid a double free in case
154492876eecSFilipe Manana 				 * an error happens after this.
154592876eecSFilipe Manana 				 */
154692876eecSFilipe Manana 				eie = NULL;
1547976b1908SJan Schmidt 			}
15484eb1f66dSTakashi Iwai 			ret = ulist_add_merge_ptr(refs, ref->parent,
15494eb1f66dSTakashi Iwai 						  ref->inode_list,
15504eb1f66dSTakashi Iwai 						  (void **)&eie, GFP_NOFS);
1551f1723939SWang Shilong 			if (ret < 0)
1552f1723939SWang Shilong 				goto out;
15533301958bSJan Schmidt 			if (!ret && extent_item_pos) {
15543301958bSJan Schmidt 				/*
15559f05c09dSJosef Bacik 				 * We've recorded that parent, so we must extend
15569f05c09dSJosef Bacik 				 * its inode list here.
15579f05c09dSJosef Bacik 				 *
15589f05c09dSJosef Bacik 				 * However if there was corruption we may not
15599f05c09dSJosef Bacik 				 * have found an eie, return an error in this
15609f05c09dSJosef Bacik 				 * case.
15613301958bSJan Schmidt 				 */
15629f05c09dSJosef Bacik 				ASSERT(eie);
15639f05c09dSJosef Bacik 				if (!eie) {
15649f05c09dSJosef Bacik 					ret = -EUCLEAN;
15659f05c09dSJosef Bacik 					goto out;
15669f05c09dSJosef Bacik 				}
15673301958bSJan Schmidt 				while (eie->next)
15683301958bSJan Schmidt 					eie = eie->next;
15693301958bSJan Schmidt 				eie->next = ref->inode_list;
15703301958bSJan Schmidt 			}
1571f05c4746SWang Shilong 			eie = NULL;
157292876eecSFilipe Manana 			/*
157392876eecSFilipe Manana 			 * We have transferred the inode list ownership from
157492876eecSFilipe Manana 			 * this ref to the ref we added to the 'refs' ulist.
157592876eecSFilipe Manana 			 * So set this ref's inode list to NULL to avoid
157692876eecSFilipe Manana 			 * use-after-free when our caller uses it or double
157792876eecSFilipe Manana 			 * frees in case an error happens before we return.
157892876eecSFilipe Manana 			 */
157992876eecSFilipe Manana 			ref->inode_list = NULL;
15808da6d581SJan Schmidt 		}
15819dd14fd6SEdmund Nadolski 		cond_resched();
15828da6d581SJan Schmidt 	}
15838da6d581SJan Schmidt 
15848da6d581SJan Schmidt out:
15858da6d581SJan Schmidt 	btrfs_free_path(path);
158686d5f994SEdmund Nadolski 
158786d5f994SEdmund Nadolski 	prelim_release(&preftrees.direct);
158886d5f994SEdmund Nadolski 	prelim_release(&preftrees.indirect);
158986d5f994SEdmund Nadolski 	prelim_release(&preftrees.indirect_missing_keys);
159086d5f994SEdmund Nadolski 
1591f05c4746SWang Shilong 	if (ret < 0)
1592f05c4746SWang Shilong 		free_inode_elem_list(eie);
15938da6d581SJan Schmidt 	return ret;
15948da6d581SJan Schmidt }
15958da6d581SJan Schmidt 
15968da6d581SJan Schmidt /*
15978da6d581SJan Schmidt  * Finds all leafs with a reference to the specified combination of bytenr and
15988da6d581SJan Schmidt  * offset. key_list_head will point to a list of corresponding keys (caller must
15998da6d581SJan Schmidt  * free each list element). The leafs will be stored in the leafs ulist, which
16008da6d581SJan Schmidt  * must be freed with ulist_free.
16018da6d581SJan Schmidt  *
16028da6d581SJan Schmidt  * returns 0 on success, <0 on error
16038da6d581SJan Schmidt  */
160419b546d7SQu Wenruo int btrfs_find_all_leafs(struct btrfs_trans_handle *trans,
16058da6d581SJan Schmidt 			 struct btrfs_fs_info *fs_info, u64 bytenr,
1606097b8a7cSJan Schmidt 			 u64 time_seq, struct ulist **leafs,
1607c995ab3cSZygo Blaxell 			 const u64 *extent_item_pos, bool ignore_offset)
16088da6d581SJan Schmidt {
16098da6d581SJan Schmidt 	int ret;
16108da6d581SJan Schmidt 
16118da6d581SJan Schmidt 	*leafs = ulist_alloc(GFP_NOFS);
161298cfee21SWang Shilong 	if (!*leafs)
16138da6d581SJan Schmidt 		return -ENOMEM;
16148da6d581SJan Schmidt 
1615afce772eSLu Fengqi 	ret = find_parent_nodes(trans, fs_info, bytenr, time_seq,
1616c995ab3cSZygo Blaxell 				*leafs, NULL, extent_item_pos, NULL, ignore_offset);
16178da6d581SJan Schmidt 	if (ret < 0 && ret != -ENOENT) {
1618976b1908SJan Schmidt 		free_leaf_list(*leafs);
16198da6d581SJan Schmidt 		return ret;
16208da6d581SJan Schmidt 	}
16218da6d581SJan Schmidt 
16228da6d581SJan Schmidt 	return 0;
16238da6d581SJan Schmidt }
16248da6d581SJan Schmidt 
16258da6d581SJan Schmidt /*
16268da6d581SJan Schmidt  * walk all backrefs for a given extent to find all roots that reference this
16278da6d581SJan Schmidt  * extent. Walking a backref means finding all extents that reference this
16288da6d581SJan Schmidt  * extent and in turn walk the backrefs of those, too. Naturally this is a
16298da6d581SJan Schmidt  * recursive process, but here it is implemented in an iterative fashion: We
16308da6d581SJan Schmidt  * find all referencing extents for the extent in question and put them on a
16318da6d581SJan Schmidt  * list. In turn, we find all referencing extents for those, further appending
16328da6d581SJan Schmidt  * to the list. The way we iterate the list allows adding more elements after
16338da6d581SJan Schmidt  * the current while iterating. The process stops when we reach the end of the
16348da6d581SJan Schmidt  * list. Found roots are added to the roots list.
16358da6d581SJan Schmidt  *
16368da6d581SJan Schmidt  * returns 0 on success, < 0 on error.
16378da6d581SJan Schmidt  */
1638e0c476b1SJeff Mahoney static int btrfs_find_all_roots_safe(struct btrfs_trans_handle *trans,
16398da6d581SJan Schmidt 				     struct btrfs_fs_info *fs_info, u64 bytenr,
1640c995ab3cSZygo Blaxell 				     u64 time_seq, struct ulist **roots,
1641c995ab3cSZygo Blaxell 				     bool ignore_offset)
16428da6d581SJan Schmidt {
16438da6d581SJan Schmidt 	struct ulist *tmp;
16448da6d581SJan Schmidt 	struct ulist_node *node = NULL;
1645cd1b413cSJan Schmidt 	struct ulist_iterator uiter;
16468da6d581SJan Schmidt 	int ret;
16478da6d581SJan Schmidt 
16488da6d581SJan Schmidt 	tmp = ulist_alloc(GFP_NOFS);
16498da6d581SJan Schmidt 	if (!tmp)
16508da6d581SJan Schmidt 		return -ENOMEM;
16518da6d581SJan Schmidt 	*roots = ulist_alloc(GFP_NOFS);
16528da6d581SJan Schmidt 	if (!*roots) {
16538da6d581SJan Schmidt 		ulist_free(tmp);
16548da6d581SJan Schmidt 		return -ENOMEM;
16558da6d581SJan Schmidt 	}
16568da6d581SJan Schmidt 
1657cd1b413cSJan Schmidt 	ULIST_ITER_INIT(&uiter);
16588da6d581SJan Schmidt 	while (1) {
1659afce772eSLu Fengqi 		ret = find_parent_nodes(trans, fs_info, bytenr, time_seq,
1660c995ab3cSZygo Blaxell 					tmp, *roots, NULL, NULL, ignore_offset);
16618da6d581SJan Schmidt 		if (ret < 0 && ret != -ENOENT) {
16628da6d581SJan Schmidt 			ulist_free(tmp);
16638da6d581SJan Schmidt 			ulist_free(*roots);
1664580c079bSFilipe Manana 			*roots = NULL;
16658da6d581SJan Schmidt 			return ret;
16668da6d581SJan Schmidt 		}
1667cd1b413cSJan Schmidt 		node = ulist_next(tmp, &uiter);
16688da6d581SJan Schmidt 		if (!node)
16698da6d581SJan Schmidt 			break;
16708da6d581SJan Schmidt 		bytenr = node->val;
1671bca1a290SWang Shilong 		cond_resched();
16728da6d581SJan Schmidt 	}
16738da6d581SJan Schmidt 
16748da6d581SJan Schmidt 	ulist_free(tmp);
16758da6d581SJan Schmidt 	return 0;
16768da6d581SJan Schmidt }
16778da6d581SJan Schmidt 
16789e351cc8SJosef Bacik int btrfs_find_all_roots(struct btrfs_trans_handle *trans,
16799e351cc8SJosef Bacik 			 struct btrfs_fs_info *fs_info, u64 bytenr,
1680c995ab3cSZygo Blaxell 			 u64 time_seq, struct ulist **roots,
1681c7bcbb21SFilipe Manana 			 bool skip_commit_root_sem)
16829e351cc8SJosef Bacik {
16839e351cc8SJosef Bacik 	int ret;
16849e351cc8SJosef Bacik 
16858949b9a1SFilipe Manana 	if (!trans && !skip_commit_root_sem)
16869e351cc8SJosef Bacik 		down_read(&fs_info->commit_root_sem);
1687e0c476b1SJeff Mahoney 	ret = btrfs_find_all_roots_safe(trans, fs_info, bytenr,
1688c7bcbb21SFilipe Manana 					time_seq, roots, false);
16898949b9a1SFilipe Manana 	if (!trans && !skip_commit_root_sem)
16909e351cc8SJosef Bacik 		up_read(&fs_info->commit_root_sem);
16919e351cc8SJosef Bacik 	return ret;
16929e351cc8SJosef Bacik }
16939e351cc8SJosef Bacik 
169484a7949dSFilipe Manana struct btrfs_backref_share_check_ctx *btrfs_alloc_backref_share_check_ctx(void)
169584a7949dSFilipe Manana {
169684a7949dSFilipe Manana 	struct btrfs_backref_share_check_ctx *ctx;
169784a7949dSFilipe Manana 
169884a7949dSFilipe Manana 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
169984a7949dSFilipe Manana 	if (!ctx)
170084a7949dSFilipe Manana 		return NULL;
170184a7949dSFilipe Manana 
170284a7949dSFilipe Manana 	ulist_init(&ctx->refs);
170384a7949dSFilipe Manana 
170484a7949dSFilipe Manana 	return ctx;
170584a7949dSFilipe Manana }
170684a7949dSFilipe Manana 
170784a7949dSFilipe Manana void btrfs_free_backref_share_ctx(struct btrfs_backref_share_check_ctx *ctx)
170884a7949dSFilipe Manana {
170984a7949dSFilipe Manana 	if (!ctx)
171084a7949dSFilipe Manana 		return;
171184a7949dSFilipe Manana 
171284a7949dSFilipe Manana 	ulist_release(&ctx->refs);
171384a7949dSFilipe Manana 	kfree(ctx);
171484a7949dSFilipe Manana }
171584a7949dSFilipe Manana 
171612a824dcSFilipe Manana /*
17178eedaddaSFilipe Manana  * Check if a data extent is shared or not.
17186e353e3bSNikolay Borisov  *
1719ceb707daSFilipe Manana  * @inode:       The inode whose extent we are checking.
1720b8f164e3SFilipe Manana  * @bytenr:      Logical bytenr of the extent we are checking.
1721b8f164e3SFilipe Manana  * @extent_gen:  Generation of the extent (file extent item) or 0 if it is
1722b8f164e3SFilipe Manana  *               not known.
172361dbb952SFilipe Manana  * @ctx:         A backref sharedness check context.
17242c2ed5aaSMark Fasheh  *
17258eedaddaSFilipe Manana  * btrfs_is_data_extent_shared uses the backref walking code but will short
17262c2ed5aaSMark Fasheh  * circuit as soon as it finds a root or inode that doesn't match the
17272c2ed5aaSMark Fasheh  * one passed in. This provides a significant performance benefit for
17282c2ed5aaSMark Fasheh  * callers (such as fiemap) which want to know whether the extent is
17292c2ed5aaSMark Fasheh  * shared but do not need a ref count.
17302c2ed5aaSMark Fasheh  *
173103628cdbSFilipe Manana  * This attempts to attach to the running transaction in order to account for
173203628cdbSFilipe Manana  * delayed refs, but continues on even when no running transaction exists.
1733bb739cf0SEdmund Nadolski  *
17342c2ed5aaSMark Fasheh  * Return: 0 if extent is not shared, 1 if it is shared, < 0 on error.
17352c2ed5aaSMark Fasheh  */
1736ceb707daSFilipe Manana int btrfs_is_data_extent_shared(struct btrfs_inode *inode, u64 bytenr,
1737b8f164e3SFilipe Manana 				u64 extent_gen,
173861dbb952SFilipe Manana 				struct btrfs_backref_share_check_ctx *ctx)
1739dc046b10SJosef Bacik {
1740ceb707daSFilipe Manana 	struct btrfs_root *root = inode->root;
1741bb739cf0SEdmund Nadolski 	struct btrfs_fs_info *fs_info = root->fs_info;
1742bb739cf0SEdmund Nadolski 	struct btrfs_trans_handle *trans;
1743dc046b10SJosef Bacik 	struct ulist_iterator uiter;
1744dc046b10SJosef Bacik 	struct ulist_node *node;
1745f3a84ccdSFilipe Manana 	struct btrfs_seq_list elem = BTRFS_SEQ_LIST_INIT(elem);
1746dc046b10SJosef Bacik 	int ret = 0;
17473ec4d323SEdmund Nadolski 	struct share_check shared = {
17484fd786e6SMisono Tomohiro 		.root_objectid = root->root_key.objectid,
1749ceb707daSFilipe Manana 		.inum = btrfs_ino(inode),
175073e339e6SFilipe Manana 		.data_bytenr = bytenr,
17513ec4d323SEdmund Nadolski 		.share_count = 0,
175273e339e6SFilipe Manana 		.self_ref_count = 0,
17534fc7b572SFilipe Manana 		.have_delayed_delete_refs = false,
17543ec4d323SEdmund Nadolski 	};
175512a824dcSFilipe Manana 	int level;
1756dc046b10SJosef Bacik 
175773e339e6SFilipe Manana 	for (int i = 0; i < BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE; i++) {
175873e339e6SFilipe Manana 		if (ctx->prev_extents_cache[i].bytenr == bytenr)
175973e339e6SFilipe Manana 			return ctx->prev_extents_cache[i].is_shared;
176073e339e6SFilipe Manana 	}
176173e339e6SFilipe Manana 
176284a7949dSFilipe Manana 	ulist_init(&ctx->refs);
1763dc046b10SJosef Bacik 
1764a6d155d2SFilipe Manana 	trans = btrfs_join_transaction_nostart(root);
1765bb739cf0SEdmund Nadolski 	if (IS_ERR(trans)) {
176603628cdbSFilipe Manana 		if (PTR_ERR(trans) != -ENOENT && PTR_ERR(trans) != -EROFS) {
176703628cdbSFilipe Manana 			ret = PTR_ERR(trans);
176803628cdbSFilipe Manana 			goto out;
176903628cdbSFilipe Manana 		}
1770bb739cf0SEdmund Nadolski 		trans = NULL;
1771dc046b10SJosef Bacik 		down_read(&fs_info->commit_root_sem);
1772bb739cf0SEdmund Nadolski 	} else {
1773bb739cf0SEdmund Nadolski 		btrfs_get_tree_mod_seq(fs_info, &elem);
1774bb739cf0SEdmund Nadolski 	}
1775bb739cf0SEdmund Nadolski 
177612a824dcSFilipe Manana 	/* -1 means we are in the bytenr of the data extent. */
177712a824dcSFilipe Manana 	level = -1;
1778dc046b10SJosef Bacik 	ULIST_ITER_INIT(&uiter);
177961dbb952SFilipe Manana 	ctx->use_path_cache = true;
1780dc046b10SJosef Bacik 	while (1) {
178112a824dcSFilipe Manana 		bool is_shared;
178212a824dcSFilipe Manana 		bool cached;
178312a824dcSFilipe Manana 
178484a7949dSFilipe Manana 		ret = find_parent_nodes(trans, fs_info, bytenr, elem.seq, &ctx->refs,
1785b6296858SFilipe Manana 					NULL, NULL, &shared, false);
1786dc046b10SJosef Bacik 		if (ret == BACKREF_FOUND_SHARED) {
17872c2ed5aaSMark Fasheh 			/* this is the only condition under which we return 1 */
1788dc046b10SJosef Bacik 			ret = 1;
178912a824dcSFilipe Manana 			if (level >= 0)
179061dbb952SFilipe Manana 				store_backref_shared_cache(ctx, root, bytenr,
179112a824dcSFilipe Manana 							   level, true);
1792dc046b10SJosef Bacik 			break;
1793dc046b10SJosef Bacik 		}
1794dc046b10SJosef Bacik 		if (ret < 0 && ret != -ENOENT)
1795dc046b10SJosef Bacik 			break;
17962c2ed5aaSMark Fasheh 		ret = 0;
1797b8f164e3SFilipe Manana 		/*
1798b8f164e3SFilipe Manana 		 * If our data extent is not shared through reflinks and it was
1799b8f164e3SFilipe Manana 		 * created in a generation after the last one used to create a
1800b8f164e3SFilipe Manana 		 * snapshot of the inode's root, then it can not be shared
1801b8f164e3SFilipe Manana 		 * indirectly through subtrees, as that can only happen with
1802b8f164e3SFilipe Manana 		 * snapshots. In this case bail out, no need to check for the
1803b8f164e3SFilipe Manana 		 * sharedness of extent buffers.
1804b8f164e3SFilipe Manana 		 */
1805b8f164e3SFilipe Manana 		if (level == -1 &&
1806b8f164e3SFilipe Manana 		    extent_gen > btrfs_root_last_snapshot(&root->root_item))
1807b8f164e3SFilipe Manana 			break;
1808b8f164e3SFilipe Manana 
180963c84b46SFilipe Manana 		/*
181063c84b46SFilipe Manana 		 * If our data extent was not directly shared (without multiple
181163c84b46SFilipe Manana 		 * reference items), than it might have a single reference item
181263c84b46SFilipe Manana 		 * with a count > 1 for the same offset, which means there are 2
181363c84b46SFilipe Manana 		 * (or more) file extent items that point to the data extent -
181463c84b46SFilipe Manana 		 * this happens when a file extent item needs to be split and
181563c84b46SFilipe Manana 		 * then one item gets moved to another leaf due to a b+tree leaf
181663c84b46SFilipe Manana 		 * split when inserting some item. In this case the file extent
181763c84b46SFilipe Manana 		 * items may be located in different leaves and therefore some
181863c84b46SFilipe Manana 		 * of the leaves may be referenced through shared subtrees while
181963c84b46SFilipe Manana 		 * others are not. Since our extent buffer cache only works for
182063c84b46SFilipe Manana 		 * a single path (by far the most common case and simpler to
182163c84b46SFilipe Manana 		 * deal with), we can not use it if we have multiple leaves
182263c84b46SFilipe Manana 		 * (which implies multiple paths).
182363c84b46SFilipe Manana 		 */
182484a7949dSFilipe Manana 		if (level == -1 && ctx->refs.nnodes > 1)
182561dbb952SFilipe Manana 			ctx->use_path_cache = false;
182663c84b46SFilipe Manana 
182712a824dcSFilipe Manana 		if (level >= 0)
182861dbb952SFilipe Manana 			store_backref_shared_cache(ctx, root, bytenr,
182912a824dcSFilipe Manana 						   level, false);
183084a7949dSFilipe Manana 		node = ulist_next(&ctx->refs, &uiter);
1831dc046b10SJosef Bacik 		if (!node)
1832dc046b10SJosef Bacik 			break;
1833dc046b10SJosef Bacik 		bytenr = node->val;
183412a824dcSFilipe Manana 		level++;
183561dbb952SFilipe Manana 		cached = lookup_backref_shared_cache(ctx, root, bytenr, level,
183612a824dcSFilipe Manana 						     &is_shared);
183712a824dcSFilipe Manana 		if (cached) {
183812a824dcSFilipe Manana 			ret = (is_shared ? 1 : 0);
183912a824dcSFilipe Manana 			break;
184012a824dcSFilipe Manana 		}
184118bf591bSEdmund Nadolski 		shared.share_count = 0;
18424fc7b572SFilipe Manana 		shared.have_delayed_delete_refs = false;
1843dc046b10SJosef Bacik 		cond_resched();
1844dc046b10SJosef Bacik 	}
1845bb739cf0SEdmund Nadolski 
184673e339e6SFilipe Manana 	/*
184773e339e6SFilipe Manana 	 * Cache the sharedness result for the data extent if we know our inode
184873e339e6SFilipe Manana 	 * has more than 1 file extent item that refers to the data extent.
184973e339e6SFilipe Manana 	 */
185073e339e6SFilipe Manana 	if (ret >= 0 && shared.self_ref_count > 1) {
185173e339e6SFilipe Manana 		int slot = ctx->prev_extents_cache_slot;
185273e339e6SFilipe Manana 
185373e339e6SFilipe Manana 		ctx->prev_extents_cache[slot].bytenr = shared.data_bytenr;
185473e339e6SFilipe Manana 		ctx->prev_extents_cache[slot].is_shared = (ret == 1);
185573e339e6SFilipe Manana 
185673e339e6SFilipe Manana 		slot = (slot + 1) % BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE;
185773e339e6SFilipe Manana 		ctx->prev_extents_cache_slot = slot;
185873e339e6SFilipe Manana 	}
185973e339e6SFilipe Manana 
1860bb739cf0SEdmund Nadolski 	if (trans) {
1861dc046b10SJosef Bacik 		btrfs_put_tree_mod_seq(fs_info, &elem);
1862bb739cf0SEdmund Nadolski 		btrfs_end_transaction(trans);
1863bb739cf0SEdmund Nadolski 	} else {
1864dc046b10SJosef Bacik 		up_read(&fs_info->commit_root_sem);
1865bb739cf0SEdmund Nadolski 	}
186603628cdbSFilipe Manana out:
186784a7949dSFilipe Manana 	ulist_release(&ctx->refs);
1868dc046b10SJosef Bacik 	return ret;
1869dc046b10SJosef Bacik }
1870dc046b10SJosef Bacik 
1871f186373fSMark Fasheh int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
1872f186373fSMark Fasheh 			  u64 start_off, struct btrfs_path *path,
1873f186373fSMark Fasheh 			  struct btrfs_inode_extref **ret_extref,
1874f186373fSMark Fasheh 			  u64 *found_off)
1875f186373fSMark Fasheh {
1876f186373fSMark Fasheh 	int ret, slot;
1877f186373fSMark Fasheh 	struct btrfs_key key;
1878f186373fSMark Fasheh 	struct btrfs_key found_key;
1879f186373fSMark Fasheh 	struct btrfs_inode_extref *extref;
188073980becSJeff Mahoney 	const struct extent_buffer *leaf;
1881f186373fSMark Fasheh 	unsigned long ptr;
1882f186373fSMark Fasheh 
1883f186373fSMark Fasheh 	key.objectid = inode_objectid;
1884962a298fSDavid Sterba 	key.type = BTRFS_INODE_EXTREF_KEY;
1885f186373fSMark Fasheh 	key.offset = start_off;
1886f186373fSMark Fasheh 
1887f186373fSMark Fasheh 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1888f186373fSMark Fasheh 	if (ret < 0)
1889f186373fSMark Fasheh 		return ret;
1890f186373fSMark Fasheh 
1891f186373fSMark Fasheh 	while (1) {
1892f186373fSMark Fasheh 		leaf = path->nodes[0];
1893f186373fSMark Fasheh 		slot = path->slots[0];
1894f186373fSMark Fasheh 		if (slot >= btrfs_header_nritems(leaf)) {
1895f186373fSMark Fasheh 			/*
1896f186373fSMark Fasheh 			 * If the item at offset is not found,
1897f186373fSMark Fasheh 			 * btrfs_search_slot will point us to the slot
1898f186373fSMark Fasheh 			 * where it should be inserted. In our case
1899f186373fSMark Fasheh 			 * that will be the slot directly before the
1900f186373fSMark Fasheh 			 * next INODE_REF_KEY_V2 item. In the case
1901f186373fSMark Fasheh 			 * that we're pointing to the last slot in a
1902f186373fSMark Fasheh 			 * leaf, we must move one leaf over.
1903f186373fSMark Fasheh 			 */
1904f186373fSMark Fasheh 			ret = btrfs_next_leaf(root, path);
1905f186373fSMark Fasheh 			if (ret) {
1906f186373fSMark Fasheh 				if (ret >= 1)
1907f186373fSMark Fasheh 					ret = -ENOENT;
1908f186373fSMark Fasheh 				break;
1909f186373fSMark Fasheh 			}
1910f186373fSMark Fasheh 			continue;
1911f186373fSMark Fasheh 		}
1912f186373fSMark Fasheh 
1913f186373fSMark Fasheh 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
1914f186373fSMark Fasheh 
1915f186373fSMark Fasheh 		/*
1916f186373fSMark Fasheh 		 * Check that we're still looking at an extended ref key for
1917f186373fSMark Fasheh 		 * this particular objectid. If we have different
1918f186373fSMark Fasheh 		 * objectid or type then there are no more to be found
1919f186373fSMark Fasheh 		 * in the tree and we can exit.
1920f186373fSMark Fasheh 		 */
1921f186373fSMark Fasheh 		ret = -ENOENT;
1922f186373fSMark Fasheh 		if (found_key.objectid != inode_objectid)
1923f186373fSMark Fasheh 			break;
1924962a298fSDavid Sterba 		if (found_key.type != BTRFS_INODE_EXTREF_KEY)
1925f186373fSMark Fasheh 			break;
1926f186373fSMark Fasheh 
1927f186373fSMark Fasheh 		ret = 0;
1928f186373fSMark Fasheh 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1929f186373fSMark Fasheh 		extref = (struct btrfs_inode_extref *)ptr;
1930f186373fSMark Fasheh 		*ret_extref = extref;
1931f186373fSMark Fasheh 		if (found_off)
1932f186373fSMark Fasheh 			*found_off = found_key.offset;
1933f186373fSMark Fasheh 		break;
1934f186373fSMark Fasheh 	}
1935f186373fSMark Fasheh 
1936f186373fSMark Fasheh 	return ret;
1937f186373fSMark Fasheh }
1938f186373fSMark Fasheh 
193948a3b636SEric Sandeen /*
194048a3b636SEric Sandeen  * this iterates to turn a name (from iref/extref) into a full filesystem path.
194148a3b636SEric Sandeen  * Elements of the path are separated by '/' and the path is guaranteed to be
194248a3b636SEric Sandeen  * 0-terminated. the path is only given within the current file system.
194348a3b636SEric Sandeen  * Therefore, it never starts with a '/'. the caller is responsible to provide
194448a3b636SEric Sandeen  * "size" bytes in "dest". the dest buffer will be filled backwards. finally,
194548a3b636SEric Sandeen  * the start point of the resulting string is returned. this pointer is within
194648a3b636SEric Sandeen  * dest, normally.
194748a3b636SEric Sandeen  * in case the path buffer would overflow, the pointer is decremented further
194848a3b636SEric Sandeen  * as if output was written to the buffer, though no more output is actually
194948a3b636SEric Sandeen  * generated. that way, the caller can determine how much space would be
195048a3b636SEric Sandeen  * required for the path to fit into the buffer. in that case, the returned
195148a3b636SEric Sandeen  * value will be smaller than dest. callers must check this!
195248a3b636SEric Sandeen  */
195396b5bd77SJan Schmidt char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
1954d24bec3aSMark Fasheh 			u32 name_len, unsigned long name_off,
1955a542ad1bSJan Schmidt 			struct extent_buffer *eb_in, u64 parent,
1956a542ad1bSJan Schmidt 			char *dest, u32 size)
1957a542ad1bSJan Schmidt {
1958a542ad1bSJan Schmidt 	int slot;
1959a542ad1bSJan Schmidt 	u64 next_inum;
1960a542ad1bSJan Schmidt 	int ret;
1961661bec6bSGabriel de Perthuis 	s64 bytes_left = ((s64)size) - 1;
1962a542ad1bSJan Schmidt 	struct extent_buffer *eb = eb_in;
1963a542ad1bSJan Schmidt 	struct btrfs_key found_key;
1964d24bec3aSMark Fasheh 	struct btrfs_inode_ref *iref;
1965a542ad1bSJan Schmidt 
1966a542ad1bSJan Schmidt 	if (bytes_left >= 0)
1967a542ad1bSJan Schmidt 		dest[bytes_left] = '\0';
1968a542ad1bSJan Schmidt 
1969a542ad1bSJan Schmidt 	while (1) {
1970d24bec3aSMark Fasheh 		bytes_left -= name_len;
1971a542ad1bSJan Schmidt 		if (bytes_left >= 0)
1972a542ad1bSJan Schmidt 			read_extent_buffer(eb, dest + bytes_left,
1973d24bec3aSMark Fasheh 					   name_off, name_len);
1974b916a59aSJan Schmidt 		if (eb != eb_in) {
19750c0fe3b0SFilipe Manana 			if (!path->skip_locking)
1976ac5887c8SJosef Bacik 				btrfs_tree_read_unlock(eb);
1977a542ad1bSJan Schmidt 			free_extent_buffer(eb);
1978b916a59aSJan Schmidt 		}
1979c234a24dSDavid Sterba 		ret = btrfs_find_item(fs_root, path, parent, 0,
1980c234a24dSDavid Sterba 				BTRFS_INODE_REF_KEY, &found_key);
19818f24b496SJan Schmidt 		if (ret > 0)
19828f24b496SJan Schmidt 			ret = -ENOENT;
1983a542ad1bSJan Schmidt 		if (ret)
1984a542ad1bSJan Schmidt 			break;
1985d24bec3aSMark Fasheh 
1986a542ad1bSJan Schmidt 		next_inum = found_key.offset;
1987a542ad1bSJan Schmidt 
1988a542ad1bSJan Schmidt 		/* regular exit ahead */
1989a542ad1bSJan Schmidt 		if (parent == next_inum)
1990a542ad1bSJan Schmidt 			break;
1991a542ad1bSJan Schmidt 
1992a542ad1bSJan Schmidt 		slot = path->slots[0];
1993a542ad1bSJan Schmidt 		eb = path->nodes[0];
1994a542ad1bSJan Schmidt 		/* make sure we can use eb after releasing the path */
1995b916a59aSJan Schmidt 		if (eb != eb_in) {
19960c0fe3b0SFilipe Manana 			path->nodes[0] = NULL;
19970c0fe3b0SFilipe Manana 			path->locks[0] = 0;
1998b916a59aSJan Schmidt 		}
1999a542ad1bSJan Schmidt 		btrfs_release_path(path);
2000a542ad1bSJan Schmidt 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2001d24bec3aSMark Fasheh 
2002d24bec3aSMark Fasheh 		name_len = btrfs_inode_ref_name_len(eb, iref);
2003d24bec3aSMark Fasheh 		name_off = (unsigned long)(iref + 1);
2004d24bec3aSMark Fasheh 
2005a542ad1bSJan Schmidt 		parent = next_inum;
2006a542ad1bSJan Schmidt 		--bytes_left;
2007a542ad1bSJan Schmidt 		if (bytes_left >= 0)
2008a542ad1bSJan Schmidt 			dest[bytes_left] = '/';
2009a542ad1bSJan Schmidt 	}
2010a542ad1bSJan Schmidt 
2011a542ad1bSJan Schmidt 	btrfs_release_path(path);
2012a542ad1bSJan Schmidt 
2013a542ad1bSJan Schmidt 	if (ret)
2014a542ad1bSJan Schmidt 		return ERR_PTR(ret);
2015a542ad1bSJan Schmidt 
2016a542ad1bSJan Schmidt 	return dest + bytes_left;
2017a542ad1bSJan Schmidt }
2018a542ad1bSJan Schmidt 
2019a542ad1bSJan Schmidt /*
2020a542ad1bSJan Schmidt  * this makes the path point to (logical EXTENT_ITEM *)
2021a542ad1bSJan Schmidt  * returns BTRFS_EXTENT_FLAG_DATA for data, BTRFS_EXTENT_FLAG_TREE_BLOCK for
2022a542ad1bSJan Schmidt  * tree blocks and <0 on error.
2023a542ad1bSJan Schmidt  */
2024a542ad1bSJan Schmidt int extent_from_logical(struct btrfs_fs_info *fs_info, u64 logical,
202569917e43SLiu Bo 			struct btrfs_path *path, struct btrfs_key *found_key,
202669917e43SLiu Bo 			u64 *flags_ret)
2027a542ad1bSJan Schmidt {
202829cbcf40SJosef Bacik 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, logical);
2029a542ad1bSJan Schmidt 	int ret;
2030a542ad1bSJan Schmidt 	u64 flags;
2031261c84b6SJosef Bacik 	u64 size = 0;
2032a542ad1bSJan Schmidt 	u32 item_size;
203373980becSJeff Mahoney 	const struct extent_buffer *eb;
2034a542ad1bSJan Schmidt 	struct btrfs_extent_item *ei;
2035a542ad1bSJan Schmidt 	struct btrfs_key key;
2036a542ad1bSJan Schmidt 
2037261c84b6SJosef Bacik 	if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2038261c84b6SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
2039261c84b6SJosef Bacik 	else
2040a542ad1bSJan Schmidt 		key.type = BTRFS_EXTENT_ITEM_KEY;
2041a542ad1bSJan Schmidt 	key.objectid = logical;
2042a542ad1bSJan Schmidt 	key.offset = (u64)-1;
2043a542ad1bSJan Schmidt 
204429cbcf40SJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2045a542ad1bSJan Schmidt 	if (ret < 0)
2046a542ad1bSJan Schmidt 		return ret;
2047a542ad1bSJan Schmidt 
204829cbcf40SJosef Bacik 	ret = btrfs_previous_extent_item(extent_root, path, 0);
2049850a8cdfSWang Shilong 	if (ret) {
2050850a8cdfSWang Shilong 		if (ret > 0)
2051580f0a67SJosef Bacik 			ret = -ENOENT;
2052580f0a67SJosef Bacik 		return ret;
2053580f0a67SJosef Bacik 	}
2054850a8cdfSWang Shilong 	btrfs_item_key_to_cpu(path->nodes[0], found_key, path->slots[0]);
2055261c84b6SJosef Bacik 	if (found_key->type == BTRFS_METADATA_ITEM_KEY)
2056da17066cSJeff Mahoney 		size = fs_info->nodesize;
2057261c84b6SJosef Bacik 	else if (found_key->type == BTRFS_EXTENT_ITEM_KEY)
2058261c84b6SJosef Bacik 		size = found_key->offset;
2059261c84b6SJosef Bacik 
2060580f0a67SJosef Bacik 	if (found_key->objectid > logical ||
2061261c84b6SJosef Bacik 	    found_key->objectid + size <= logical) {
2062ab8d0fc4SJeff Mahoney 		btrfs_debug(fs_info,
2063ab8d0fc4SJeff Mahoney 			"logical %llu is not within any extent", logical);
2064a542ad1bSJan Schmidt 		return -ENOENT;
20654692cf58SJan Schmidt 	}
2066a542ad1bSJan Schmidt 
2067a542ad1bSJan Schmidt 	eb = path->nodes[0];
20683212fa14SJosef Bacik 	item_size = btrfs_item_size(eb, path->slots[0]);
2069a542ad1bSJan Schmidt 	BUG_ON(item_size < sizeof(*ei));
2070a542ad1bSJan Schmidt 
2071a542ad1bSJan Schmidt 	ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
2072a542ad1bSJan Schmidt 	flags = btrfs_extent_flags(eb, ei);
2073a542ad1bSJan Schmidt 
2074ab8d0fc4SJeff Mahoney 	btrfs_debug(fs_info,
2075ab8d0fc4SJeff Mahoney 		"logical %llu is at position %llu within the extent (%llu EXTENT_ITEM %llu) flags %#llx size %u",
2076c1c9ff7cSGeert Uytterhoeven 		 logical, logical - found_key->objectid, found_key->objectid,
2077c1c9ff7cSGeert Uytterhoeven 		 found_key->offset, flags, item_size);
207869917e43SLiu Bo 
207969917e43SLiu Bo 	WARN_ON(!flags_ret);
208069917e43SLiu Bo 	if (flags_ret) {
2081a542ad1bSJan Schmidt 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
208269917e43SLiu Bo 			*flags_ret = BTRFS_EXTENT_FLAG_TREE_BLOCK;
208369917e43SLiu Bo 		else if (flags & BTRFS_EXTENT_FLAG_DATA)
208469917e43SLiu Bo 			*flags_ret = BTRFS_EXTENT_FLAG_DATA;
208569917e43SLiu Bo 		else
2086290342f6SArnd Bergmann 			BUG();
208769917e43SLiu Bo 		return 0;
208869917e43SLiu Bo 	}
2089a542ad1bSJan Schmidt 
2090a542ad1bSJan Schmidt 	return -EIO;
2091a542ad1bSJan Schmidt }
2092a542ad1bSJan Schmidt 
2093a542ad1bSJan Schmidt /*
2094a542ad1bSJan Schmidt  * helper function to iterate extent inline refs. ptr must point to a 0 value
2095a542ad1bSJan Schmidt  * for the first call and may be modified. it is used to track state.
2096a542ad1bSJan Schmidt  * if more refs exist, 0 is returned and the next call to
2097e0c476b1SJeff Mahoney  * get_extent_inline_ref must pass the modified ptr parameter to get the
2098a542ad1bSJan Schmidt  * next ref. after the last ref was processed, 1 is returned.
2099a542ad1bSJan Schmidt  * returns <0 on error
2100a542ad1bSJan Schmidt  */
2101e0c476b1SJeff Mahoney static int get_extent_inline_ref(unsigned long *ptr,
210273980becSJeff Mahoney 				 const struct extent_buffer *eb,
210373980becSJeff Mahoney 				 const struct btrfs_key *key,
210473980becSJeff Mahoney 				 const struct btrfs_extent_item *ei,
210573980becSJeff Mahoney 				 u32 item_size,
2106a542ad1bSJan Schmidt 				 struct btrfs_extent_inline_ref **out_eiref,
2107a542ad1bSJan Schmidt 				 int *out_type)
2108a542ad1bSJan Schmidt {
2109a542ad1bSJan Schmidt 	unsigned long end;
2110a542ad1bSJan Schmidt 	u64 flags;
2111a542ad1bSJan Schmidt 	struct btrfs_tree_block_info *info;
2112a542ad1bSJan Schmidt 
2113a542ad1bSJan Schmidt 	if (!*ptr) {
2114a542ad1bSJan Schmidt 		/* first call */
2115a542ad1bSJan Schmidt 		flags = btrfs_extent_flags(eb, ei);
2116a542ad1bSJan Schmidt 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
21176eda71d0SLiu Bo 			if (key->type == BTRFS_METADATA_ITEM_KEY) {
21186eda71d0SLiu Bo 				/* a skinny metadata extent */
21196eda71d0SLiu Bo 				*out_eiref =
21206eda71d0SLiu Bo 				     (struct btrfs_extent_inline_ref *)(ei + 1);
21216eda71d0SLiu Bo 			} else {
21226eda71d0SLiu Bo 				WARN_ON(key->type != BTRFS_EXTENT_ITEM_KEY);
2123a542ad1bSJan Schmidt 				info = (struct btrfs_tree_block_info *)(ei + 1);
2124a542ad1bSJan Schmidt 				*out_eiref =
2125a542ad1bSJan Schmidt 				   (struct btrfs_extent_inline_ref *)(info + 1);
21266eda71d0SLiu Bo 			}
2127a542ad1bSJan Schmidt 		} else {
2128a542ad1bSJan Schmidt 			*out_eiref = (struct btrfs_extent_inline_ref *)(ei + 1);
2129a542ad1bSJan Schmidt 		}
2130a542ad1bSJan Schmidt 		*ptr = (unsigned long)*out_eiref;
2131cd857dd6SLiu Bo 		if ((unsigned long)(*ptr) >= (unsigned long)ei + item_size)
2132a542ad1bSJan Schmidt 			return -ENOENT;
2133a542ad1bSJan Schmidt 	}
2134a542ad1bSJan Schmidt 
2135a542ad1bSJan Schmidt 	end = (unsigned long)ei + item_size;
21366eda71d0SLiu Bo 	*out_eiref = (struct btrfs_extent_inline_ref *)(*ptr);
21373de28d57SLiu Bo 	*out_type = btrfs_get_extent_inline_ref_type(eb, *out_eiref,
21383de28d57SLiu Bo 						     BTRFS_REF_TYPE_ANY);
21393de28d57SLiu Bo 	if (*out_type == BTRFS_REF_TYPE_INVALID)
2140af431dcbSSu Yue 		return -EUCLEAN;
2141a542ad1bSJan Schmidt 
2142a542ad1bSJan Schmidt 	*ptr += btrfs_extent_inline_ref_size(*out_type);
2143a542ad1bSJan Schmidt 	WARN_ON(*ptr > end);
2144a542ad1bSJan Schmidt 	if (*ptr == end)
2145a542ad1bSJan Schmidt 		return 1; /* last */
2146a542ad1bSJan Schmidt 
2147a542ad1bSJan Schmidt 	return 0;
2148a542ad1bSJan Schmidt }
2149a542ad1bSJan Schmidt 
2150a542ad1bSJan Schmidt /*
2151a542ad1bSJan Schmidt  * reads the tree block backref for an extent. tree level and root are returned
2152a542ad1bSJan Schmidt  * through out_level and out_root. ptr must point to a 0 value for the first
2153e0c476b1SJeff Mahoney  * call and may be modified (see get_extent_inline_ref comment).
2154a542ad1bSJan Schmidt  * returns 0 if data was provided, 1 if there was no more data to provide or
2155a542ad1bSJan Schmidt  * <0 on error.
2156a542ad1bSJan Schmidt  */
2157a542ad1bSJan Schmidt int tree_backref_for_extent(unsigned long *ptr, struct extent_buffer *eb,
21586eda71d0SLiu Bo 			    struct btrfs_key *key, struct btrfs_extent_item *ei,
21596eda71d0SLiu Bo 			    u32 item_size, u64 *out_root, u8 *out_level)
2160a542ad1bSJan Schmidt {
2161a542ad1bSJan Schmidt 	int ret;
2162a542ad1bSJan Schmidt 	int type;
2163a542ad1bSJan Schmidt 	struct btrfs_extent_inline_ref *eiref;
2164a542ad1bSJan Schmidt 
2165a542ad1bSJan Schmidt 	if (*ptr == (unsigned long)-1)
2166a542ad1bSJan Schmidt 		return 1;
2167a542ad1bSJan Schmidt 
2168a542ad1bSJan Schmidt 	while (1) {
2169e0c476b1SJeff Mahoney 		ret = get_extent_inline_ref(ptr, eb, key, ei, item_size,
2170a542ad1bSJan Schmidt 					      &eiref, &type);
2171a542ad1bSJan Schmidt 		if (ret < 0)
2172a542ad1bSJan Schmidt 			return ret;
2173a542ad1bSJan Schmidt 
2174a542ad1bSJan Schmidt 		if (type == BTRFS_TREE_BLOCK_REF_KEY ||
2175a542ad1bSJan Schmidt 		    type == BTRFS_SHARED_BLOCK_REF_KEY)
2176a542ad1bSJan Schmidt 			break;
2177a542ad1bSJan Schmidt 
2178a542ad1bSJan Schmidt 		if (ret == 1)
2179a542ad1bSJan Schmidt 			return 1;
2180a542ad1bSJan Schmidt 	}
2181a542ad1bSJan Schmidt 
2182a542ad1bSJan Schmidt 	/* we can treat both ref types equally here */
2183a542ad1bSJan Schmidt 	*out_root = btrfs_extent_inline_ref_offset(eb, eiref);
2184a1317f45SFilipe Manana 
2185a1317f45SFilipe Manana 	if (key->type == BTRFS_EXTENT_ITEM_KEY) {
2186a1317f45SFilipe Manana 		struct btrfs_tree_block_info *info;
2187a1317f45SFilipe Manana 
2188a1317f45SFilipe Manana 		info = (struct btrfs_tree_block_info *)(ei + 1);
2189a542ad1bSJan Schmidt 		*out_level = btrfs_tree_block_level(eb, info);
2190a1317f45SFilipe Manana 	} else {
2191a1317f45SFilipe Manana 		ASSERT(key->type == BTRFS_METADATA_ITEM_KEY);
2192a1317f45SFilipe Manana 		*out_level = (u8)key->offset;
2193a1317f45SFilipe Manana 	}
2194a542ad1bSJan Schmidt 
2195a542ad1bSJan Schmidt 	if (ret == 1)
2196a542ad1bSJan Schmidt 		*ptr = (unsigned long)-1;
2197a542ad1bSJan Schmidt 
2198a542ad1bSJan Schmidt 	return 0;
2199a542ad1bSJan Schmidt }
2200a542ad1bSJan Schmidt 
2201ab8d0fc4SJeff Mahoney static int iterate_leaf_refs(struct btrfs_fs_info *fs_info,
2202ab8d0fc4SJeff Mahoney 			     struct extent_inode_elem *inode_list,
2203976b1908SJan Schmidt 			     u64 root, u64 extent_item_objectid,
22044692cf58SJan Schmidt 			     iterate_extent_inodes_t *iterate, void *ctx)
2205a542ad1bSJan Schmidt {
2206976b1908SJan Schmidt 	struct extent_inode_elem *eie;
22074692cf58SJan Schmidt 	int ret = 0;
2208a542ad1bSJan Schmidt 
2209976b1908SJan Schmidt 	for (eie = inode_list; eie; eie = eie->next) {
2210ab8d0fc4SJeff Mahoney 		btrfs_debug(fs_info,
2211ab8d0fc4SJeff Mahoney 			    "ref for %llu resolved, key (%llu EXTEND_DATA %llu), root %llu",
2212ab8d0fc4SJeff Mahoney 			    extent_item_objectid, eie->inum,
2213ab8d0fc4SJeff Mahoney 			    eie->offset, root);
2214976b1908SJan Schmidt 		ret = iterate(eie->inum, eie->offset, root, ctx);
22154692cf58SJan Schmidt 		if (ret) {
2216ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_info,
2217ab8d0fc4SJeff Mahoney 				    "stopping iteration for %llu due to ret=%d",
2218976b1908SJan Schmidt 				    extent_item_objectid, ret);
2219a542ad1bSJan Schmidt 			break;
2220a542ad1bSJan Schmidt 		}
2221a542ad1bSJan Schmidt 	}
2222a542ad1bSJan Schmidt 
2223a542ad1bSJan Schmidt 	return ret;
2224a542ad1bSJan Schmidt }
2225a542ad1bSJan Schmidt 
2226a542ad1bSJan Schmidt /*
2227a542ad1bSJan Schmidt  * calls iterate() for every inode that references the extent identified by
22284692cf58SJan Schmidt  * the given parameters.
2229a542ad1bSJan Schmidt  * when the iterator function returns a non-zero value, iteration stops.
2230a542ad1bSJan Schmidt  */
2231a542ad1bSJan Schmidt int iterate_extent_inodes(struct btrfs_fs_info *fs_info,
22324692cf58SJan Schmidt 				u64 extent_item_objectid, u64 extent_item_pos,
22337a3ae2f8SJan Schmidt 				int search_commit_root,
2234c995ab3cSZygo Blaxell 				iterate_extent_inodes_t *iterate, void *ctx,
2235c995ab3cSZygo Blaxell 				bool ignore_offset)
2236a542ad1bSJan Schmidt {
2237a542ad1bSJan Schmidt 	int ret;
2238da61d31aSJosef Bacik 	struct btrfs_trans_handle *trans = NULL;
22397a3ae2f8SJan Schmidt 	struct ulist *refs = NULL;
22407a3ae2f8SJan Schmidt 	struct ulist *roots = NULL;
22414692cf58SJan Schmidt 	struct ulist_node *ref_node = NULL;
22424692cf58SJan Schmidt 	struct ulist_node *root_node = NULL;
2243f3a84ccdSFilipe Manana 	struct btrfs_seq_list seq_elem = BTRFS_SEQ_LIST_INIT(seq_elem);
2244cd1b413cSJan Schmidt 	struct ulist_iterator ref_uiter;
2245cd1b413cSJan Schmidt 	struct ulist_iterator root_uiter;
2246a542ad1bSJan Schmidt 
2247ab8d0fc4SJeff Mahoney 	btrfs_debug(fs_info, "resolving all inodes for extent %llu",
22484692cf58SJan Schmidt 			extent_item_objectid);
22494692cf58SJan Schmidt 
2250da61d31aSJosef Bacik 	if (!search_commit_root) {
225130a9da5dSJosef Bacik 		trans = btrfs_attach_transaction(fs_info->tree_root);
2252bfc61c36SFilipe Manana 		if (IS_ERR(trans)) {
2253bfc61c36SFilipe Manana 			if (PTR_ERR(trans) != -ENOENT &&
2254bfc61c36SFilipe Manana 			    PTR_ERR(trans) != -EROFS)
22557a3ae2f8SJan Schmidt 				return PTR_ERR(trans);
2256bfc61c36SFilipe Manana 			trans = NULL;
22577a3ae2f8SJan Schmidt 		}
2258bfc61c36SFilipe Manana 	}
2259bfc61c36SFilipe Manana 
2260bfc61c36SFilipe Manana 	if (trans)
2261f3a84ccdSFilipe Manana 		btrfs_get_tree_mod_seq(fs_info, &seq_elem);
2262bfc61c36SFilipe Manana 	else
2263bfc61c36SFilipe Manana 		down_read(&fs_info->commit_root_sem);
22644692cf58SJan Schmidt 
22654692cf58SJan Schmidt 	ret = btrfs_find_all_leafs(trans, fs_info, extent_item_objectid,
2266f3a84ccdSFilipe Manana 				   seq_elem.seq, &refs,
2267c995ab3cSZygo Blaxell 				   &extent_item_pos, ignore_offset);
22684692cf58SJan Schmidt 	if (ret)
22694692cf58SJan Schmidt 		goto out;
22704692cf58SJan Schmidt 
2271cd1b413cSJan Schmidt 	ULIST_ITER_INIT(&ref_uiter);
2272cd1b413cSJan Schmidt 	while (!ret && (ref_node = ulist_next(refs, &ref_uiter))) {
2273e0c476b1SJeff Mahoney 		ret = btrfs_find_all_roots_safe(trans, fs_info, ref_node->val,
2274f3a84ccdSFilipe Manana 						seq_elem.seq, &roots,
2275c995ab3cSZygo Blaxell 						ignore_offset);
22764692cf58SJan Schmidt 		if (ret)
2277a542ad1bSJan Schmidt 			break;
2278cd1b413cSJan Schmidt 		ULIST_ITER_INIT(&root_uiter);
2279cd1b413cSJan Schmidt 		while (!ret && (root_node = ulist_next(roots, &root_uiter))) {
2280ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_info,
2281ab8d0fc4SJeff Mahoney 				    "root %llu references leaf %llu, data list %#llx",
2282ab8d0fc4SJeff Mahoney 				    root_node->val, ref_node->val,
2283c1c9ff7cSGeert Uytterhoeven 				    ref_node->aux);
2284ab8d0fc4SJeff Mahoney 			ret = iterate_leaf_refs(fs_info,
2285ab8d0fc4SJeff Mahoney 						(struct extent_inode_elem *)
2286995e01b7SJan Schmidt 						(uintptr_t)ref_node->aux,
2287995e01b7SJan Schmidt 						root_node->val,
2288995e01b7SJan Schmidt 						extent_item_objectid,
2289a542ad1bSJan Schmidt 						iterate, ctx);
22904692cf58SJan Schmidt 		}
2291976b1908SJan Schmidt 		ulist_free(roots);
2292a542ad1bSJan Schmidt 	}
2293a542ad1bSJan Schmidt 
2294976b1908SJan Schmidt 	free_leaf_list(refs);
22954692cf58SJan Schmidt out:
2296bfc61c36SFilipe Manana 	if (trans) {
2297f3a84ccdSFilipe Manana 		btrfs_put_tree_mod_seq(fs_info, &seq_elem);
22983a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
22999e351cc8SJosef Bacik 	} else {
23009e351cc8SJosef Bacik 		up_read(&fs_info->commit_root_sem);
23017a3ae2f8SJan Schmidt 	}
23027a3ae2f8SJan Schmidt 
2303a542ad1bSJan Schmidt 	return ret;
2304a542ad1bSJan Schmidt }
2305a542ad1bSJan Schmidt 
2306e3059ec0SDavid Sterba static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
2307e3059ec0SDavid Sterba {
2308e3059ec0SDavid Sterba 	struct btrfs_data_container *inodes = ctx;
2309e3059ec0SDavid Sterba 	const size_t c = 3 * sizeof(u64);
2310e3059ec0SDavid Sterba 
2311e3059ec0SDavid Sterba 	if (inodes->bytes_left >= c) {
2312e3059ec0SDavid Sterba 		inodes->bytes_left -= c;
2313e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt] = inum;
2314e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt + 1] = offset;
2315e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt + 2] = root;
2316e3059ec0SDavid Sterba 		inodes->elem_cnt += 3;
2317e3059ec0SDavid Sterba 	} else {
2318e3059ec0SDavid Sterba 		inodes->bytes_missing += c - inodes->bytes_left;
2319e3059ec0SDavid Sterba 		inodes->bytes_left = 0;
2320e3059ec0SDavid Sterba 		inodes->elem_missed += 3;
2321e3059ec0SDavid Sterba 	}
2322e3059ec0SDavid Sterba 
2323e3059ec0SDavid Sterba 	return 0;
2324e3059ec0SDavid Sterba }
2325e3059ec0SDavid Sterba 
2326a542ad1bSJan Schmidt int iterate_inodes_from_logical(u64 logical, struct btrfs_fs_info *fs_info,
2327a542ad1bSJan Schmidt 				struct btrfs_path *path,
2328e3059ec0SDavid Sterba 				void *ctx, bool ignore_offset)
2329a542ad1bSJan Schmidt {
2330a542ad1bSJan Schmidt 	int ret;
23314692cf58SJan Schmidt 	u64 extent_item_pos;
233269917e43SLiu Bo 	u64 flags = 0;
2333a542ad1bSJan Schmidt 	struct btrfs_key found_key;
23347a3ae2f8SJan Schmidt 	int search_commit_root = path->search_commit_root;
2335a542ad1bSJan Schmidt 
233669917e43SLiu Bo 	ret = extent_from_logical(fs_info, logical, path, &found_key, &flags);
23374692cf58SJan Schmidt 	btrfs_release_path(path);
2338a542ad1bSJan Schmidt 	if (ret < 0)
2339a542ad1bSJan Schmidt 		return ret;
234069917e43SLiu Bo 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
23413627bf45SStefan Behrens 		return -EINVAL;
2342a542ad1bSJan Schmidt 
23434692cf58SJan Schmidt 	extent_item_pos = logical - found_key.objectid;
23447a3ae2f8SJan Schmidt 	ret = iterate_extent_inodes(fs_info, found_key.objectid,
23457a3ae2f8SJan Schmidt 					extent_item_pos, search_commit_root,
2346e3059ec0SDavid Sterba 					build_ino_list, ctx, ignore_offset);
2347a542ad1bSJan Schmidt 
2348a542ad1bSJan Schmidt 	return ret;
2349a542ad1bSJan Schmidt }
2350a542ad1bSJan Schmidt 
2351ad6240f6SDavid Sterba static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2352875d1daaSDavid Sterba 			 struct extent_buffer *eb, struct inode_fs_paths *ipath);
2353d24bec3aSMark Fasheh 
2354875d1daaSDavid Sterba static int iterate_inode_refs(u64 inum, struct inode_fs_paths *ipath)
2355a542ad1bSJan Schmidt {
2356aefc1eb1SJan Schmidt 	int ret = 0;
2357a542ad1bSJan Schmidt 	int slot;
2358a542ad1bSJan Schmidt 	u32 cur;
2359a542ad1bSJan Schmidt 	u32 len;
2360a542ad1bSJan Schmidt 	u32 name_len;
2361a542ad1bSJan Schmidt 	u64 parent = 0;
2362a542ad1bSJan Schmidt 	int found = 0;
2363875d1daaSDavid Sterba 	struct btrfs_root *fs_root = ipath->fs_root;
2364875d1daaSDavid Sterba 	struct btrfs_path *path = ipath->btrfs_path;
2365a542ad1bSJan Schmidt 	struct extent_buffer *eb;
2366a542ad1bSJan Schmidt 	struct btrfs_inode_ref *iref;
2367a542ad1bSJan Schmidt 	struct btrfs_key found_key;
2368a542ad1bSJan Schmidt 
2369aefc1eb1SJan Schmidt 	while (!ret) {
2370c234a24dSDavid Sterba 		ret = btrfs_find_item(fs_root, path, inum,
2371c234a24dSDavid Sterba 				parent ? parent + 1 : 0, BTRFS_INODE_REF_KEY,
2372a542ad1bSJan Schmidt 				&found_key);
2373c234a24dSDavid Sterba 
2374a542ad1bSJan Schmidt 		if (ret < 0)
2375a542ad1bSJan Schmidt 			break;
2376a542ad1bSJan Schmidt 		if (ret) {
2377a542ad1bSJan Schmidt 			ret = found ? 0 : -ENOENT;
2378a542ad1bSJan Schmidt 			break;
2379a542ad1bSJan Schmidt 		}
2380a542ad1bSJan Schmidt 		++found;
2381a542ad1bSJan Schmidt 
2382a542ad1bSJan Schmidt 		parent = found_key.offset;
2383a542ad1bSJan Schmidt 		slot = path->slots[0];
23843fe81ce2SFilipe David Borba Manana 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
23853fe81ce2SFilipe David Borba Manana 		if (!eb) {
23863fe81ce2SFilipe David Borba Manana 			ret = -ENOMEM;
23873fe81ce2SFilipe David Borba Manana 			break;
23883fe81ce2SFilipe David Borba Manana 		}
2389a542ad1bSJan Schmidt 		btrfs_release_path(path);
2390a542ad1bSJan Schmidt 
2391a542ad1bSJan Schmidt 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2392a542ad1bSJan Schmidt 
23933212fa14SJosef Bacik 		for (cur = 0; cur < btrfs_item_size(eb, slot); cur += len) {
2394a542ad1bSJan Schmidt 			name_len = btrfs_inode_ref_name_len(eb, iref);
2395a542ad1bSJan Schmidt 			/* path must be released before calling iterate()! */
2396ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_root->fs_info,
2397ab8d0fc4SJeff Mahoney 				"following ref at offset %u for inode %llu in tree %llu",
23984fd786e6SMisono Tomohiro 				cur, found_key.objectid,
23994fd786e6SMisono Tomohiro 				fs_root->root_key.objectid);
2400ad6240f6SDavid Sterba 			ret = inode_to_path(parent, name_len,
2401875d1daaSDavid Sterba 				      (unsigned long)(iref + 1), eb, ipath);
2402aefc1eb1SJan Schmidt 			if (ret)
2403a542ad1bSJan Schmidt 				break;
2404a542ad1bSJan Schmidt 			len = sizeof(*iref) + name_len;
2405a542ad1bSJan Schmidt 			iref = (struct btrfs_inode_ref *)((char *)iref + len);
2406a542ad1bSJan Schmidt 		}
2407a542ad1bSJan Schmidt 		free_extent_buffer(eb);
2408a542ad1bSJan Schmidt 	}
2409a542ad1bSJan Schmidt 
2410a542ad1bSJan Schmidt 	btrfs_release_path(path);
2411a542ad1bSJan Schmidt 
2412a542ad1bSJan Schmidt 	return ret;
2413a542ad1bSJan Schmidt }
2414a542ad1bSJan Schmidt 
2415875d1daaSDavid Sterba static int iterate_inode_extrefs(u64 inum, struct inode_fs_paths *ipath)
2416d24bec3aSMark Fasheh {
2417d24bec3aSMark Fasheh 	int ret;
2418d24bec3aSMark Fasheh 	int slot;
2419d24bec3aSMark Fasheh 	u64 offset = 0;
2420d24bec3aSMark Fasheh 	u64 parent;
2421d24bec3aSMark Fasheh 	int found = 0;
2422875d1daaSDavid Sterba 	struct btrfs_root *fs_root = ipath->fs_root;
2423875d1daaSDavid Sterba 	struct btrfs_path *path = ipath->btrfs_path;
2424d24bec3aSMark Fasheh 	struct extent_buffer *eb;
2425d24bec3aSMark Fasheh 	struct btrfs_inode_extref *extref;
2426d24bec3aSMark Fasheh 	u32 item_size;
2427d24bec3aSMark Fasheh 	u32 cur_offset;
2428d24bec3aSMark Fasheh 	unsigned long ptr;
2429d24bec3aSMark Fasheh 
2430d24bec3aSMark Fasheh 	while (1) {
2431d24bec3aSMark Fasheh 		ret = btrfs_find_one_extref(fs_root, inum, offset, path, &extref,
2432d24bec3aSMark Fasheh 					    &offset);
2433d24bec3aSMark Fasheh 		if (ret < 0)
2434d24bec3aSMark Fasheh 			break;
2435d24bec3aSMark Fasheh 		if (ret) {
2436d24bec3aSMark Fasheh 			ret = found ? 0 : -ENOENT;
2437d24bec3aSMark Fasheh 			break;
2438d24bec3aSMark Fasheh 		}
2439d24bec3aSMark Fasheh 		++found;
2440d24bec3aSMark Fasheh 
2441d24bec3aSMark Fasheh 		slot = path->slots[0];
24423fe81ce2SFilipe David Borba Manana 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
24433fe81ce2SFilipe David Borba Manana 		if (!eb) {
24443fe81ce2SFilipe David Borba Manana 			ret = -ENOMEM;
24453fe81ce2SFilipe David Borba Manana 			break;
24463fe81ce2SFilipe David Borba Manana 		}
2447d24bec3aSMark Fasheh 		btrfs_release_path(path);
2448d24bec3aSMark Fasheh 
24493212fa14SJosef Bacik 		item_size = btrfs_item_size(eb, slot);
24502849a854SChris Mason 		ptr = btrfs_item_ptr_offset(eb, slot);
2451d24bec3aSMark Fasheh 		cur_offset = 0;
2452d24bec3aSMark Fasheh 
2453d24bec3aSMark Fasheh 		while (cur_offset < item_size) {
2454d24bec3aSMark Fasheh 			u32 name_len;
2455d24bec3aSMark Fasheh 
2456d24bec3aSMark Fasheh 			extref = (struct btrfs_inode_extref *)(ptr + cur_offset);
2457d24bec3aSMark Fasheh 			parent = btrfs_inode_extref_parent(eb, extref);
2458d24bec3aSMark Fasheh 			name_len = btrfs_inode_extref_name_len(eb, extref);
2459ad6240f6SDavid Sterba 			ret = inode_to_path(parent, name_len,
2460875d1daaSDavid Sterba 				      (unsigned long)&extref->name, eb, ipath);
2461d24bec3aSMark Fasheh 			if (ret)
2462d24bec3aSMark Fasheh 				break;
2463d24bec3aSMark Fasheh 
24642849a854SChris Mason 			cur_offset += btrfs_inode_extref_name_len(eb, extref);
2465d24bec3aSMark Fasheh 			cur_offset += sizeof(*extref);
2466d24bec3aSMark Fasheh 		}
2467d24bec3aSMark Fasheh 		free_extent_buffer(eb);
2468d24bec3aSMark Fasheh 
2469d24bec3aSMark Fasheh 		offset++;
2470d24bec3aSMark Fasheh 	}
2471d24bec3aSMark Fasheh 
2472d24bec3aSMark Fasheh 	btrfs_release_path(path);
2473d24bec3aSMark Fasheh 
2474d24bec3aSMark Fasheh 	return ret;
2475d24bec3aSMark Fasheh }
2476d24bec3aSMark Fasheh 
2477a542ad1bSJan Schmidt /*
2478a542ad1bSJan Schmidt  * returns 0 if the path could be dumped (probably truncated)
2479a542ad1bSJan Schmidt  * returns <0 in case of an error
2480a542ad1bSJan Schmidt  */
2481d24bec3aSMark Fasheh static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2482875d1daaSDavid Sterba 			 struct extent_buffer *eb, struct inode_fs_paths *ipath)
2483a542ad1bSJan Schmidt {
2484a542ad1bSJan Schmidt 	char *fspath;
2485a542ad1bSJan Schmidt 	char *fspath_min;
2486a542ad1bSJan Schmidt 	int i = ipath->fspath->elem_cnt;
2487a542ad1bSJan Schmidt 	const int s_ptr = sizeof(char *);
2488a542ad1bSJan Schmidt 	u32 bytes_left;
2489a542ad1bSJan Schmidt 
2490a542ad1bSJan Schmidt 	bytes_left = ipath->fspath->bytes_left > s_ptr ?
2491a542ad1bSJan Schmidt 					ipath->fspath->bytes_left - s_ptr : 0;
2492a542ad1bSJan Schmidt 
2493740c3d22SChris Mason 	fspath_min = (char *)ipath->fspath->val + (i + 1) * s_ptr;
249496b5bd77SJan Schmidt 	fspath = btrfs_ref_to_path(ipath->fs_root, ipath->btrfs_path, name_len,
249596b5bd77SJan Schmidt 				   name_off, eb, inum, fspath_min, bytes_left);
2496a542ad1bSJan Schmidt 	if (IS_ERR(fspath))
2497a542ad1bSJan Schmidt 		return PTR_ERR(fspath);
2498a542ad1bSJan Schmidt 
2499a542ad1bSJan Schmidt 	if (fspath > fspath_min) {
2500745c4d8eSJeff Mahoney 		ipath->fspath->val[i] = (u64)(unsigned long)fspath;
2501a542ad1bSJan Schmidt 		++ipath->fspath->elem_cnt;
2502a542ad1bSJan Schmidt 		ipath->fspath->bytes_left = fspath - fspath_min;
2503a542ad1bSJan Schmidt 	} else {
2504a542ad1bSJan Schmidt 		++ipath->fspath->elem_missed;
2505a542ad1bSJan Schmidt 		ipath->fspath->bytes_missing += fspath_min - fspath;
2506a542ad1bSJan Schmidt 		ipath->fspath->bytes_left = 0;
2507a542ad1bSJan Schmidt 	}
2508a542ad1bSJan Schmidt 
2509a542ad1bSJan Schmidt 	return 0;
2510a542ad1bSJan Schmidt }
2511a542ad1bSJan Schmidt 
2512a542ad1bSJan Schmidt /*
2513a542ad1bSJan Schmidt  * this dumps all file system paths to the inode into the ipath struct, provided
2514a542ad1bSJan Schmidt  * is has been created large enough. each path is zero-terminated and accessed
2515740c3d22SChris Mason  * from ipath->fspath->val[i].
2516a542ad1bSJan Schmidt  * when it returns, there are ipath->fspath->elem_cnt number of paths available
2517740c3d22SChris Mason  * in ipath->fspath->val[]. when the allocated space wasn't sufficient, the
251801327610SNicholas D Steeves  * number of missed paths is recorded in ipath->fspath->elem_missed, otherwise,
2519a542ad1bSJan Schmidt  * it's zero. ipath->fspath->bytes_missing holds the number of bytes that would
2520a542ad1bSJan Schmidt  * have been needed to return all paths.
2521a542ad1bSJan Schmidt  */
2522a542ad1bSJan Schmidt int paths_from_inode(u64 inum, struct inode_fs_paths *ipath)
2523a542ad1bSJan Schmidt {
2524ad6240f6SDavid Sterba 	int ret;
2525ad6240f6SDavid Sterba 	int found_refs = 0;
2526ad6240f6SDavid Sterba 
2527875d1daaSDavid Sterba 	ret = iterate_inode_refs(inum, ipath);
2528ad6240f6SDavid Sterba 	if (!ret)
2529ad6240f6SDavid Sterba 		++found_refs;
2530ad6240f6SDavid Sterba 	else if (ret != -ENOENT)
2531ad6240f6SDavid Sterba 		return ret;
2532ad6240f6SDavid Sterba 
2533875d1daaSDavid Sterba 	ret = iterate_inode_extrefs(inum, ipath);
2534ad6240f6SDavid Sterba 	if (ret == -ENOENT && found_refs)
2535ad6240f6SDavid Sterba 		return 0;
2536ad6240f6SDavid Sterba 
2537ad6240f6SDavid Sterba 	return ret;
2538a542ad1bSJan Schmidt }
2539a542ad1bSJan Schmidt 
2540a542ad1bSJan Schmidt struct btrfs_data_container *init_data_container(u32 total_bytes)
2541a542ad1bSJan Schmidt {
2542a542ad1bSJan Schmidt 	struct btrfs_data_container *data;
2543a542ad1bSJan Schmidt 	size_t alloc_bytes;
2544a542ad1bSJan Schmidt 
2545a542ad1bSJan Schmidt 	alloc_bytes = max_t(size_t, total_bytes, sizeof(*data));
2546f54de068SDavid Sterba 	data = kvmalloc(alloc_bytes, GFP_KERNEL);
2547a542ad1bSJan Schmidt 	if (!data)
2548a542ad1bSJan Schmidt 		return ERR_PTR(-ENOMEM);
2549a542ad1bSJan Schmidt 
2550a542ad1bSJan Schmidt 	if (total_bytes >= sizeof(*data)) {
2551a542ad1bSJan Schmidt 		data->bytes_left = total_bytes - sizeof(*data);
2552a542ad1bSJan Schmidt 		data->bytes_missing = 0;
2553a542ad1bSJan Schmidt 	} else {
2554a542ad1bSJan Schmidt 		data->bytes_missing = sizeof(*data) - total_bytes;
2555a542ad1bSJan Schmidt 		data->bytes_left = 0;
2556a542ad1bSJan Schmidt 	}
2557a542ad1bSJan Schmidt 
2558a542ad1bSJan Schmidt 	data->elem_cnt = 0;
2559a542ad1bSJan Schmidt 	data->elem_missed = 0;
2560a542ad1bSJan Schmidt 
2561a542ad1bSJan Schmidt 	return data;
2562a542ad1bSJan Schmidt }
2563a542ad1bSJan Schmidt 
2564a542ad1bSJan Schmidt /*
2565a542ad1bSJan Schmidt  * allocates space to return multiple file system paths for an inode.
2566a542ad1bSJan Schmidt  * total_bytes to allocate are passed, note that space usable for actual path
2567a542ad1bSJan Schmidt  * information will be total_bytes - sizeof(struct inode_fs_paths).
2568a542ad1bSJan Schmidt  * the returned pointer must be freed with free_ipath() in the end.
2569a542ad1bSJan Schmidt  */
2570a542ad1bSJan Schmidt struct inode_fs_paths *init_ipath(s32 total_bytes, struct btrfs_root *fs_root,
2571a542ad1bSJan Schmidt 					struct btrfs_path *path)
2572a542ad1bSJan Schmidt {
2573a542ad1bSJan Schmidt 	struct inode_fs_paths *ifp;
2574a542ad1bSJan Schmidt 	struct btrfs_data_container *fspath;
2575a542ad1bSJan Schmidt 
2576a542ad1bSJan Schmidt 	fspath = init_data_container(total_bytes);
2577a542ad1bSJan Schmidt 	if (IS_ERR(fspath))
2578afc6961fSMisono Tomohiro 		return ERR_CAST(fspath);
2579a542ad1bSJan Schmidt 
2580f54de068SDavid Sterba 	ifp = kmalloc(sizeof(*ifp), GFP_KERNEL);
2581a542ad1bSJan Schmidt 	if (!ifp) {
2582f54de068SDavid Sterba 		kvfree(fspath);
2583a542ad1bSJan Schmidt 		return ERR_PTR(-ENOMEM);
2584a542ad1bSJan Schmidt 	}
2585a542ad1bSJan Schmidt 
2586a542ad1bSJan Schmidt 	ifp->btrfs_path = path;
2587a542ad1bSJan Schmidt 	ifp->fspath = fspath;
2588a542ad1bSJan Schmidt 	ifp->fs_root = fs_root;
2589a542ad1bSJan Schmidt 
2590a542ad1bSJan Schmidt 	return ifp;
2591a542ad1bSJan Schmidt }
2592a542ad1bSJan Schmidt 
2593a542ad1bSJan Schmidt void free_ipath(struct inode_fs_paths *ipath)
2594a542ad1bSJan Schmidt {
25954735fb28SJesper Juhl 	if (!ipath)
25964735fb28SJesper Juhl 		return;
2597f54de068SDavid Sterba 	kvfree(ipath->fspath);
2598a542ad1bSJan Schmidt 	kfree(ipath);
2599a542ad1bSJan Schmidt }
2600a37f232bSQu Wenruo 
2601a37f232bSQu Wenruo struct btrfs_backref_iter *btrfs_backref_iter_alloc(
2602a37f232bSQu Wenruo 		struct btrfs_fs_info *fs_info, gfp_t gfp_flag)
2603a37f232bSQu Wenruo {
2604a37f232bSQu Wenruo 	struct btrfs_backref_iter *ret;
2605a37f232bSQu Wenruo 
2606a37f232bSQu Wenruo 	ret = kzalloc(sizeof(*ret), gfp_flag);
2607a37f232bSQu Wenruo 	if (!ret)
2608a37f232bSQu Wenruo 		return NULL;
2609a37f232bSQu Wenruo 
2610a37f232bSQu Wenruo 	ret->path = btrfs_alloc_path();
2611c15c2ec0SBoleyn Su 	if (!ret->path) {
2612a37f232bSQu Wenruo 		kfree(ret);
2613a37f232bSQu Wenruo 		return NULL;
2614a37f232bSQu Wenruo 	}
2615a37f232bSQu Wenruo 
2616a37f232bSQu Wenruo 	/* Current backref iterator only supports iteration in commit root */
2617a37f232bSQu Wenruo 	ret->path->search_commit_root = 1;
2618a37f232bSQu Wenruo 	ret->path->skip_locking = 1;
2619a37f232bSQu Wenruo 	ret->fs_info = fs_info;
2620a37f232bSQu Wenruo 
2621a37f232bSQu Wenruo 	return ret;
2622a37f232bSQu Wenruo }
2623a37f232bSQu Wenruo 
2624a37f232bSQu Wenruo int btrfs_backref_iter_start(struct btrfs_backref_iter *iter, u64 bytenr)
2625a37f232bSQu Wenruo {
2626a37f232bSQu Wenruo 	struct btrfs_fs_info *fs_info = iter->fs_info;
262729cbcf40SJosef Bacik 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2628a37f232bSQu Wenruo 	struct btrfs_path *path = iter->path;
2629a37f232bSQu Wenruo 	struct btrfs_extent_item *ei;
2630a37f232bSQu Wenruo 	struct btrfs_key key;
2631a37f232bSQu Wenruo 	int ret;
2632a37f232bSQu Wenruo 
2633a37f232bSQu Wenruo 	key.objectid = bytenr;
2634a37f232bSQu Wenruo 	key.type = BTRFS_METADATA_ITEM_KEY;
2635a37f232bSQu Wenruo 	key.offset = (u64)-1;
2636a37f232bSQu Wenruo 	iter->bytenr = bytenr;
2637a37f232bSQu Wenruo 
263829cbcf40SJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2639a37f232bSQu Wenruo 	if (ret < 0)
2640a37f232bSQu Wenruo 		return ret;
2641a37f232bSQu Wenruo 	if (ret == 0) {
2642a37f232bSQu Wenruo 		ret = -EUCLEAN;
2643a37f232bSQu Wenruo 		goto release;
2644a37f232bSQu Wenruo 	}
2645a37f232bSQu Wenruo 	if (path->slots[0] == 0) {
2646a37f232bSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
2647a37f232bSQu Wenruo 		ret = -EUCLEAN;
2648a37f232bSQu Wenruo 		goto release;
2649a37f232bSQu Wenruo 	}
2650a37f232bSQu Wenruo 	path->slots[0]--;
2651a37f232bSQu Wenruo 
2652a37f232bSQu Wenruo 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2653a37f232bSQu Wenruo 	if ((key.type != BTRFS_EXTENT_ITEM_KEY &&
2654a37f232bSQu Wenruo 	     key.type != BTRFS_METADATA_ITEM_KEY) || key.objectid != bytenr) {
2655a37f232bSQu Wenruo 		ret = -ENOENT;
2656a37f232bSQu Wenruo 		goto release;
2657a37f232bSQu Wenruo 	}
2658a37f232bSQu Wenruo 	memcpy(&iter->cur_key, &key, sizeof(key));
2659a37f232bSQu Wenruo 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2660a37f232bSQu Wenruo 						    path->slots[0]);
2661a37f232bSQu Wenruo 	iter->end_ptr = (u32)(iter->item_ptr +
26623212fa14SJosef Bacik 			btrfs_item_size(path->nodes[0], path->slots[0]));
2663a37f232bSQu Wenruo 	ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
2664a37f232bSQu Wenruo 			    struct btrfs_extent_item);
2665a37f232bSQu Wenruo 
2666a37f232bSQu Wenruo 	/*
2667a37f232bSQu Wenruo 	 * Only support iteration on tree backref yet.
2668a37f232bSQu Wenruo 	 *
2669a37f232bSQu Wenruo 	 * This is an extra precaution for non skinny-metadata, where
2670a37f232bSQu Wenruo 	 * EXTENT_ITEM is also used for tree blocks, that we can only use
2671a37f232bSQu Wenruo 	 * extent flags to determine if it's a tree block.
2672a37f232bSQu Wenruo 	 */
2673a37f232bSQu Wenruo 	if (btrfs_extent_flags(path->nodes[0], ei) & BTRFS_EXTENT_FLAG_DATA) {
2674a37f232bSQu Wenruo 		ret = -ENOTSUPP;
2675a37f232bSQu Wenruo 		goto release;
2676a37f232bSQu Wenruo 	}
2677a37f232bSQu Wenruo 	iter->cur_ptr = (u32)(iter->item_ptr + sizeof(*ei));
2678a37f232bSQu Wenruo 
2679a37f232bSQu Wenruo 	/* If there is no inline backref, go search for keyed backref */
2680a37f232bSQu Wenruo 	if (iter->cur_ptr >= iter->end_ptr) {
268129cbcf40SJosef Bacik 		ret = btrfs_next_item(extent_root, path);
2682a37f232bSQu Wenruo 
2683a37f232bSQu Wenruo 		/* No inline nor keyed ref */
2684a37f232bSQu Wenruo 		if (ret > 0) {
2685a37f232bSQu Wenruo 			ret = -ENOENT;
2686a37f232bSQu Wenruo 			goto release;
2687a37f232bSQu Wenruo 		}
2688a37f232bSQu Wenruo 		if (ret < 0)
2689a37f232bSQu Wenruo 			goto release;
2690a37f232bSQu Wenruo 
2691a37f232bSQu Wenruo 		btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key,
2692a37f232bSQu Wenruo 				path->slots[0]);
2693a37f232bSQu Wenruo 		if (iter->cur_key.objectid != bytenr ||
2694a37f232bSQu Wenruo 		    (iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
2695a37f232bSQu Wenruo 		     iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY)) {
2696a37f232bSQu Wenruo 			ret = -ENOENT;
2697a37f232bSQu Wenruo 			goto release;
2698a37f232bSQu Wenruo 		}
2699a37f232bSQu Wenruo 		iter->cur_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2700a37f232bSQu Wenruo 							   path->slots[0]);
2701a37f232bSQu Wenruo 		iter->item_ptr = iter->cur_ptr;
27023212fa14SJosef Bacik 		iter->end_ptr = (u32)(iter->item_ptr + btrfs_item_size(
2703a37f232bSQu Wenruo 				      path->nodes[0], path->slots[0]));
2704a37f232bSQu Wenruo 	}
2705a37f232bSQu Wenruo 
2706a37f232bSQu Wenruo 	return 0;
2707a37f232bSQu Wenruo release:
2708a37f232bSQu Wenruo 	btrfs_backref_iter_release(iter);
2709a37f232bSQu Wenruo 	return ret;
2710a37f232bSQu Wenruo }
2711c39c2ddcSQu Wenruo 
2712c39c2ddcSQu Wenruo /*
2713c39c2ddcSQu Wenruo  * Go to the next backref item of current bytenr, can be either inlined or
2714c39c2ddcSQu Wenruo  * keyed.
2715c39c2ddcSQu Wenruo  *
2716c39c2ddcSQu Wenruo  * Caller needs to check whether it's inline ref or not by iter->cur_key.
2717c39c2ddcSQu Wenruo  *
2718c39c2ddcSQu Wenruo  * Return 0 if we get next backref without problem.
2719c39c2ddcSQu Wenruo  * Return >0 if there is no extra backref for this bytenr.
2720c39c2ddcSQu Wenruo  * Return <0 if there is something wrong happened.
2721c39c2ddcSQu Wenruo  */
2722c39c2ddcSQu Wenruo int btrfs_backref_iter_next(struct btrfs_backref_iter *iter)
2723c39c2ddcSQu Wenruo {
2724c39c2ddcSQu Wenruo 	struct extent_buffer *eb = btrfs_backref_get_eb(iter);
272529cbcf40SJosef Bacik 	struct btrfs_root *extent_root;
2726c39c2ddcSQu Wenruo 	struct btrfs_path *path = iter->path;
2727c39c2ddcSQu Wenruo 	struct btrfs_extent_inline_ref *iref;
2728c39c2ddcSQu Wenruo 	int ret;
2729c39c2ddcSQu Wenruo 	u32 size;
2730c39c2ddcSQu Wenruo 
2731c39c2ddcSQu Wenruo 	if (btrfs_backref_iter_is_inline_ref(iter)) {
2732c39c2ddcSQu Wenruo 		/* We're still inside the inline refs */
2733c39c2ddcSQu Wenruo 		ASSERT(iter->cur_ptr < iter->end_ptr);
2734c39c2ddcSQu Wenruo 
2735c39c2ddcSQu Wenruo 		if (btrfs_backref_has_tree_block_info(iter)) {
2736c39c2ddcSQu Wenruo 			/* First tree block info */
2737c39c2ddcSQu Wenruo 			size = sizeof(struct btrfs_tree_block_info);
2738c39c2ddcSQu Wenruo 		} else {
2739c39c2ddcSQu Wenruo 			/* Use inline ref type to determine the size */
2740c39c2ddcSQu Wenruo 			int type;
2741c39c2ddcSQu Wenruo 
2742c39c2ddcSQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
2743c39c2ddcSQu Wenruo 				((unsigned long)iter->cur_ptr);
2744c39c2ddcSQu Wenruo 			type = btrfs_extent_inline_ref_type(eb, iref);
2745c39c2ddcSQu Wenruo 
2746c39c2ddcSQu Wenruo 			size = btrfs_extent_inline_ref_size(type);
2747c39c2ddcSQu Wenruo 		}
2748c39c2ddcSQu Wenruo 		iter->cur_ptr += size;
2749c39c2ddcSQu Wenruo 		if (iter->cur_ptr < iter->end_ptr)
2750c39c2ddcSQu Wenruo 			return 0;
2751c39c2ddcSQu Wenruo 
2752c39c2ddcSQu Wenruo 		/* All inline items iterated, fall through */
2753c39c2ddcSQu Wenruo 	}
2754c39c2ddcSQu Wenruo 
2755c39c2ddcSQu Wenruo 	/* We're at keyed items, there is no inline item, go to the next one */
275629cbcf40SJosef Bacik 	extent_root = btrfs_extent_root(iter->fs_info, iter->bytenr);
275729cbcf40SJosef Bacik 	ret = btrfs_next_item(extent_root, iter->path);
2758c39c2ddcSQu Wenruo 	if (ret)
2759c39c2ddcSQu Wenruo 		return ret;
2760c39c2ddcSQu Wenruo 
2761c39c2ddcSQu Wenruo 	btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key, path->slots[0]);
2762c39c2ddcSQu Wenruo 	if (iter->cur_key.objectid != iter->bytenr ||
2763c39c2ddcSQu Wenruo 	    (iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
2764c39c2ddcSQu Wenruo 	     iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY))
2765c39c2ddcSQu Wenruo 		return 1;
2766c39c2ddcSQu Wenruo 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2767c39c2ddcSQu Wenruo 					path->slots[0]);
2768c39c2ddcSQu Wenruo 	iter->cur_ptr = iter->item_ptr;
27693212fa14SJosef Bacik 	iter->end_ptr = iter->item_ptr + (u32)btrfs_item_size(path->nodes[0],
2770c39c2ddcSQu Wenruo 						path->slots[0]);
2771c39c2ddcSQu Wenruo 	return 0;
2772c39c2ddcSQu Wenruo }
2773584fb121SQu Wenruo 
2774584fb121SQu Wenruo void btrfs_backref_init_cache(struct btrfs_fs_info *fs_info,
2775584fb121SQu Wenruo 			      struct btrfs_backref_cache *cache, int is_reloc)
2776584fb121SQu Wenruo {
2777584fb121SQu Wenruo 	int i;
2778584fb121SQu Wenruo 
2779584fb121SQu Wenruo 	cache->rb_root = RB_ROOT;
2780584fb121SQu Wenruo 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
2781584fb121SQu Wenruo 		INIT_LIST_HEAD(&cache->pending[i]);
2782584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->changed);
2783584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->detached);
2784584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->leaves);
2785584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->pending_edge);
2786584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->useless_node);
2787584fb121SQu Wenruo 	cache->fs_info = fs_info;
2788584fb121SQu Wenruo 	cache->is_reloc = is_reloc;
2789584fb121SQu Wenruo }
2790b1818dabSQu Wenruo 
2791b1818dabSQu Wenruo struct btrfs_backref_node *btrfs_backref_alloc_node(
2792b1818dabSQu Wenruo 		struct btrfs_backref_cache *cache, u64 bytenr, int level)
2793b1818dabSQu Wenruo {
2794b1818dabSQu Wenruo 	struct btrfs_backref_node *node;
2795b1818dabSQu Wenruo 
2796b1818dabSQu Wenruo 	ASSERT(level >= 0 && level < BTRFS_MAX_LEVEL);
2797b1818dabSQu Wenruo 	node = kzalloc(sizeof(*node), GFP_NOFS);
2798b1818dabSQu Wenruo 	if (!node)
2799b1818dabSQu Wenruo 		return node;
2800b1818dabSQu Wenruo 
2801b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->list);
2802b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->upper);
2803b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->lower);
2804b1818dabSQu Wenruo 	RB_CLEAR_NODE(&node->rb_node);
2805b1818dabSQu Wenruo 	cache->nr_nodes++;
2806b1818dabSQu Wenruo 	node->level = level;
2807b1818dabSQu Wenruo 	node->bytenr = bytenr;
2808b1818dabSQu Wenruo 
2809b1818dabSQu Wenruo 	return node;
2810b1818dabSQu Wenruo }
281147254d07SQu Wenruo 
281247254d07SQu Wenruo struct btrfs_backref_edge *btrfs_backref_alloc_edge(
281347254d07SQu Wenruo 		struct btrfs_backref_cache *cache)
281447254d07SQu Wenruo {
281547254d07SQu Wenruo 	struct btrfs_backref_edge *edge;
281647254d07SQu Wenruo 
281747254d07SQu Wenruo 	edge = kzalloc(sizeof(*edge), GFP_NOFS);
281847254d07SQu Wenruo 	if (edge)
281947254d07SQu Wenruo 		cache->nr_edges++;
282047254d07SQu Wenruo 	return edge;
282147254d07SQu Wenruo }
2822023acb07SQu Wenruo 
2823023acb07SQu Wenruo /*
2824023acb07SQu Wenruo  * Drop the backref node from cache, also cleaning up all its
2825023acb07SQu Wenruo  * upper edges and any uncached nodes in the path.
2826023acb07SQu Wenruo  *
2827023acb07SQu Wenruo  * This cleanup happens bottom up, thus the node should either
2828023acb07SQu Wenruo  * be the lowest node in the cache or a detached node.
2829023acb07SQu Wenruo  */
2830023acb07SQu Wenruo void btrfs_backref_cleanup_node(struct btrfs_backref_cache *cache,
2831023acb07SQu Wenruo 				struct btrfs_backref_node *node)
2832023acb07SQu Wenruo {
2833023acb07SQu Wenruo 	struct btrfs_backref_node *upper;
2834023acb07SQu Wenruo 	struct btrfs_backref_edge *edge;
2835023acb07SQu Wenruo 
2836023acb07SQu Wenruo 	if (!node)
2837023acb07SQu Wenruo 		return;
2838023acb07SQu Wenruo 
2839023acb07SQu Wenruo 	BUG_ON(!node->lowest && !node->detached);
2840023acb07SQu Wenruo 	while (!list_empty(&node->upper)) {
2841023acb07SQu Wenruo 		edge = list_entry(node->upper.next, struct btrfs_backref_edge,
2842023acb07SQu Wenruo 				  list[LOWER]);
2843023acb07SQu Wenruo 		upper = edge->node[UPPER];
2844023acb07SQu Wenruo 		list_del(&edge->list[LOWER]);
2845023acb07SQu Wenruo 		list_del(&edge->list[UPPER]);
2846023acb07SQu Wenruo 		btrfs_backref_free_edge(cache, edge);
2847023acb07SQu Wenruo 
2848023acb07SQu Wenruo 		/*
2849023acb07SQu Wenruo 		 * Add the node to leaf node list if no other child block
2850023acb07SQu Wenruo 		 * cached.
2851023acb07SQu Wenruo 		 */
2852023acb07SQu Wenruo 		if (list_empty(&upper->lower)) {
2853023acb07SQu Wenruo 			list_add_tail(&upper->lower, &cache->leaves);
2854023acb07SQu Wenruo 			upper->lowest = 1;
2855023acb07SQu Wenruo 		}
2856023acb07SQu Wenruo 	}
2857023acb07SQu Wenruo 
2858023acb07SQu Wenruo 	btrfs_backref_drop_node(cache, node);
2859023acb07SQu Wenruo }
286013fe1bdbSQu Wenruo 
286113fe1bdbSQu Wenruo /*
286213fe1bdbSQu Wenruo  * Release all nodes/edges from current cache
286313fe1bdbSQu Wenruo  */
286413fe1bdbSQu Wenruo void btrfs_backref_release_cache(struct btrfs_backref_cache *cache)
286513fe1bdbSQu Wenruo {
286613fe1bdbSQu Wenruo 	struct btrfs_backref_node *node;
286713fe1bdbSQu Wenruo 	int i;
286813fe1bdbSQu Wenruo 
286913fe1bdbSQu Wenruo 	while (!list_empty(&cache->detached)) {
287013fe1bdbSQu Wenruo 		node = list_entry(cache->detached.next,
287113fe1bdbSQu Wenruo 				  struct btrfs_backref_node, list);
287213fe1bdbSQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
287313fe1bdbSQu Wenruo 	}
287413fe1bdbSQu Wenruo 
287513fe1bdbSQu Wenruo 	while (!list_empty(&cache->leaves)) {
287613fe1bdbSQu Wenruo 		node = list_entry(cache->leaves.next,
287713fe1bdbSQu Wenruo 				  struct btrfs_backref_node, lower);
287813fe1bdbSQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
287913fe1bdbSQu Wenruo 	}
288013fe1bdbSQu Wenruo 
288113fe1bdbSQu Wenruo 	cache->last_trans = 0;
288213fe1bdbSQu Wenruo 
288313fe1bdbSQu Wenruo 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
288413fe1bdbSQu Wenruo 		ASSERT(list_empty(&cache->pending[i]));
288513fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->pending_edge));
288613fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->useless_node));
288713fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->changed));
288813fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->detached));
288913fe1bdbSQu Wenruo 	ASSERT(RB_EMPTY_ROOT(&cache->rb_root));
289013fe1bdbSQu Wenruo 	ASSERT(!cache->nr_nodes);
289113fe1bdbSQu Wenruo 	ASSERT(!cache->nr_edges);
289213fe1bdbSQu Wenruo }
28931b60d2ecSQu Wenruo 
28941b60d2ecSQu Wenruo /*
28951b60d2ecSQu Wenruo  * Handle direct tree backref
28961b60d2ecSQu Wenruo  *
28971b60d2ecSQu Wenruo  * Direct tree backref means, the backref item shows its parent bytenr
28981b60d2ecSQu Wenruo  * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
28991b60d2ecSQu Wenruo  *
29001b60d2ecSQu Wenruo  * @ref_key:	The converted backref key.
29011b60d2ecSQu Wenruo  *		For keyed backref, it's the item key.
29021b60d2ecSQu Wenruo  *		For inlined backref, objectid is the bytenr,
29031b60d2ecSQu Wenruo  *		type is btrfs_inline_ref_type, offset is
29041b60d2ecSQu Wenruo  *		btrfs_inline_ref_offset.
29051b60d2ecSQu Wenruo  */
29061b60d2ecSQu Wenruo static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
29071b60d2ecSQu Wenruo 				      struct btrfs_key *ref_key,
29081b60d2ecSQu Wenruo 				      struct btrfs_backref_node *cur)
29091b60d2ecSQu Wenruo {
29101b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
29111b60d2ecSQu Wenruo 	struct btrfs_backref_node *upper;
29121b60d2ecSQu Wenruo 	struct rb_node *rb_node;
29131b60d2ecSQu Wenruo 
29141b60d2ecSQu Wenruo 	ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
29151b60d2ecSQu Wenruo 
29161b60d2ecSQu Wenruo 	/* Only reloc root uses backref pointing to itself */
29171b60d2ecSQu Wenruo 	if (ref_key->objectid == ref_key->offset) {
29181b60d2ecSQu Wenruo 		struct btrfs_root *root;
29191b60d2ecSQu Wenruo 
29201b60d2ecSQu Wenruo 		cur->is_reloc_root = 1;
29211b60d2ecSQu Wenruo 		/* Only reloc backref cache cares about a specific root */
29221b60d2ecSQu Wenruo 		if (cache->is_reloc) {
29231b60d2ecSQu Wenruo 			root = find_reloc_root(cache->fs_info, cur->bytenr);
2924f78743fbSJosef Bacik 			if (!root)
29251b60d2ecSQu Wenruo 				return -ENOENT;
29261b60d2ecSQu Wenruo 			cur->root = root;
29271b60d2ecSQu Wenruo 		} else {
29281b60d2ecSQu Wenruo 			/*
29291b60d2ecSQu Wenruo 			 * For generic purpose backref cache, reloc root node
29301b60d2ecSQu Wenruo 			 * is useless.
29311b60d2ecSQu Wenruo 			 */
29321b60d2ecSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
29331b60d2ecSQu Wenruo 		}
29341b60d2ecSQu Wenruo 		return 0;
29351b60d2ecSQu Wenruo 	}
29361b60d2ecSQu Wenruo 
29371b60d2ecSQu Wenruo 	edge = btrfs_backref_alloc_edge(cache);
29381b60d2ecSQu Wenruo 	if (!edge)
29391b60d2ecSQu Wenruo 		return -ENOMEM;
29401b60d2ecSQu Wenruo 
29411b60d2ecSQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
29421b60d2ecSQu Wenruo 	if (!rb_node) {
29431b60d2ecSQu Wenruo 		/* Parent node not yet cached */
29441b60d2ecSQu Wenruo 		upper = btrfs_backref_alloc_node(cache, ref_key->offset,
29451b60d2ecSQu Wenruo 					   cur->level + 1);
29461b60d2ecSQu Wenruo 		if (!upper) {
29471b60d2ecSQu Wenruo 			btrfs_backref_free_edge(cache, edge);
29481b60d2ecSQu Wenruo 			return -ENOMEM;
29491b60d2ecSQu Wenruo 		}
29501b60d2ecSQu Wenruo 
29511b60d2ecSQu Wenruo 		/*
29521b60d2ecSQu Wenruo 		 *  Backrefs for the upper level block isn't cached, add the
29531b60d2ecSQu Wenruo 		 *  block to pending list
29541b60d2ecSQu Wenruo 		 */
29551b60d2ecSQu Wenruo 		list_add_tail(&edge->list[UPPER], &cache->pending_edge);
29561b60d2ecSQu Wenruo 	} else {
29571b60d2ecSQu Wenruo 		/* Parent node already cached */
29581b60d2ecSQu Wenruo 		upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
29591b60d2ecSQu Wenruo 		ASSERT(upper->checked);
29601b60d2ecSQu Wenruo 		INIT_LIST_HEAD(&edge->list[UPPER]);
29611b60d2ecSQu Wenruo 	}
29621b60d2ecSQu Wenruo 	btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
29631b60d2ecSQu Wenruo 	return 0;
29641b60d2ecSQu Wenruo }
29651b60d2ecSQu Wenruo 
29661b60d2ecSQu Wenruo /*
29671b60d2ecSQu Wenruo  * Handle indirect tree backref
29681b60d2ecSQu Wenruo  *
29691b60d2ecSQu Wenruo  * Indirect tree backref means, we only know which tree the node belongs to.
29701b60d2ecSQu Wenruo  * We still need to do a tree search to find out the parents. This is for
29711b60d2ecSQu Wenruo  * TREE_BLOCK_REF backref (keyed or inlined).
29721b60d2ecSQu Wenruo  *
29731b60d2ecSQu Wenruo  * @ref_key:	The same as @ref_key in  handle_direct_tree_backref()
29741b60d2ecSQu Wenruo  * @tree_key:	The first key of this tree block.
29751b60d2ecSQu Wenruo  * @path:	A clean (released) path, to avoid allocating path every time
29761b60d2ecSQu Wenruo  *		the function get called.
29771b60d2ecSQu Wenruo  */
29781b60d2ecSQu Wenruo static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
29791b60d2ecSQu Wenruo 					struct btrfs_path *path,
29801b60d2ecSQu Wenruo 					struct btrfs_key *ref_key,
29811b60d2ecSQu Wenruo 					struct btrfs_key *tree_key,
29821b60d2ecSQu Wenruo 					struct btrfs_backref_node *cur)
29831b60d2ecSQu Wenruo {
29841b60d2ecSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
29851b60d2ecSQu Wenruo 	struct btrfs_backref_node *upper;
29861b60d2ecSQu Wenruo 	struct btrfs_backref_node *lower;
29871b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
29881b60d2ecSQu Wenruo 	struct extent_buffer *eb;
29891b60d2ecSQu Wenruo 	struct btrfs_root *root;
29901b60d2ecSQu Wenruo 	struct rb_node *rb_node;
29911b60d2ecSQu Wenruo 	int level;
29921b60d2ecSQu Wenruo 	bool need_check = true;
29931b60d2ecSQu Wenruo 	int ret;
29941b60d2ecSQu Wenruo 
299556e9357aSDavid Sterba 	root = btrfs_get_fs_root(fs_info, ref_key->offset, false);
29961b60d2ecSQu Wenruo 	if (IS_ERR(root))
29971b60d2ecSQu Wenruo 		return PTR_ERR(root);
299892a7cc42SQu Wenruo 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
29991b60d2ecSQu Wenruo 		cur->cowonly = 1;
30001b60d2ecSQu Wenruo 
30011b60d2ecSQu Wenruo 	if (btrfs_root_level(&root->root_item) == cur->level) {
30021b60d2ecSQu Wenruo 		/* Tree root */
30031b60d2ecSQu Wenruo 		ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
3004876de781SQu Wenruo 		/*
3005876de781SQu Wenruo 		 * For reloc backref cache, we may ignore reloc root.  But for
3006876de781SQu Wenruo 		 * general purpose backref cache, we can't rely on
3007876de781SQu Wenruo 		 * btrfs_should_ignore_reloc_root() as it may conflict with
3008876de781SQu Wenruo 		 * current running relocation and lead to missing root.
3009876de781SQu Wenruo 		 *
3010876de781SQu Wenruo 		 * For general purpose backref cache, reloc root detection is
3011876de781SQu Wenruo 		 * completely relying on direct backref (key->offset is parent
3012876de781SQu Wenruo 		 * bytenr), thus only do such check for reloc cache.
3013876de781SQu Wenruo 		 */
3014876de781SQu Wenruo 		if (btrfs_should_ignore_reloc_root(root) && cache->is_reloc) {
30151b60d2ecSQu Wenruo 			btrfs_put_root(root);
30161b60d2ecSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
30171b60d2ecSQu Wenruo 		} else {
30181b60d2ecSQu Wenruo 			cur->root = root;
30191b60d2ecSQu Wenruo 		}
30201b60d2ecSQu Wenruo 		return 0;
30211b60d2ecSQu Wenruo 	}
30221b60d2ecSQu Wenruo 
30231b60d2ecSQu Wenruo 	level = cur->level + 1;
30241b60d2ecSQu Wenruo 
30251b60d2ecSQu Wenruo 	/* Search the tree to find parent blocks referring to the block */
30261b60d2ecSQu Wenruo 	path->search_commit_root = 1;
30271b60d2ecSQu Wenruo 	path->skip_locking = 1;
30281b60d2ecSQu Wenruo 	path->lowest_level = level;
30291b60d2ecSQu Wenruo 	ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
30301b60d2ecSQu Wenruo 	path->lowest_level = 0;
30311b60d2ecSQu Wenruo 	if (ret < 0) {
30321b60d2ecSQu Wenruo 		btrfs_put_root(root);
30331b60d2ecSQu Wenruo 		return ret;
30341b60d2ecSQu Wenruo 	}
30351b60d2ecSQu Wenruo 	if (ret > 0 && path->slots[level] > 0)
30361b60d2ecSQu Wenruo 		path->slots[level]--;
30371b60d2ecSQu Wenruo 
30381b60d2ecSQu Wenruo 	eb = path->nodes[level];
30391b60d2ecSQu Wenruo 	if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
30401b60d2ecSQu Wenruo 		btrfs_err(fs_info,
30411b60d2ecSQu Wenruo "couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
30421b60d2ecSQu Wenruo 			  cur->bytenr, level - 1, root->root_key.objectid,
30431b60d2ecSQu Wenruo 			  tree_key->objectid, tree_key->type, tree_key->offset);
30441b60d2ecSQu Wenruo 		btrfs_put_root(root);
30451b60d2ecSQu Wenruo 		ret = -ENOENT;
30461b60d2ecSQu Wenruo 		goto out;
30471b60d2ecSQu Wenruo 	}
30481b60d2ecSQu Wenruo 	lower = cur;
30491b60d2ecSQu Wenruo 
30501b60d2ecSQu Wenruo 	/* Add all nodes and edges in the path */
30511b60d2ecSQu Wenruo 	for (; level < BTRFS_MAX_LEVEL; level++) {
30521b60d2ecSQu Wenruo 		if (!path->nodes[level]) {
30531b60d2ecSQu Wenruo 			ASSERT(btrfs_root_bytenr(&root->root_item) ==
30541b60d2ecSQu Wenruo 			       lower->bytenr);
3055876de781SQu Wenruo 			/* Same as previous should_ignore_reloc_root() call */
3056876de781SQu Wenruo 			if (btrfs_should_ignore_reloc_root(root) &&
3057876de781SQu Wenruo 			    cache->is_reloc) {
30581b60d2ecSQu Wenruo 				btrfs_put_root(root);
30591b60d2ecSQu Wenruo 				list_add(&lower->list, &cache->useless_node);
30601b60d2ecSQu Wenruo 			} else {
30611b60d2ecSQu Wenruo 				lower->root = root;
30621b60d2ecSQu Wenruo 			}
30631b60d2ecSQu Wenruo 			break;
30641b60d2ecSQu Wenruo 		}
30651b60d2ecSQu Wenruo 
30661b60d2ecSQu Wenruo 		edge = btrfs_backref_alloc_edge(cache);
30671b60d2ecSQu Wenruo 		if (!edge) {
30681b60d2ecSQu Wenruo 			btrfs_put_root(root);
30691b60d2ecSQu Wenruo 			ret = -ENOMEM;
30701b60d2ecSQu Wenruo 			goto out;
30711b60d2ecSQu Wenruo 		}
30721b60d2ecSQu Wenruo 
30731b60d2ecSQu Wenruo 		eb = path->nodes[level];
30741b60d2ecSQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root, eb->start);
30751b60d2ecSQu Wenruo 		if (!rb_node) {
30761b60d2ecSQu Wenruo 			upper = btrfs_backref_alloc_node(cache, eb->start,
30771b60d2ecSQu Wenruo 							 lower->level + 1);
30781b60d2ecSQu Wenruo 			if (!upper) {
30791b60d2ecSQu Wenruo 				btrfs_put_root(root);
30801b60d2ecSQu Wenruo 				btrfs_backref_free_edge(cache, edge);
30811b60d2ecSQu Wenruo 				ret = -ENOMEM;
30821b60d2ecSQu Wenruo 				goto out;
30831b60d2ecSQu Wenruo 			}
30841b60d2ecSQu Wenruo 			upper->owner = btrfs_header_owner(eb);
308592a7cc42SQu Wenruo 			if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
30861b60d2ecSQu Wenruo 				upper->cowonly = 1;
30871b60d2ecSQu Wenruo 
30881b60d2ecSQu Wenruo 			/*
30891b60d2ecSQu Wenruo 			 * If we know the block isn't shared we can avoid
30901b60d2ecSQu Wenruo 			 * checking its backrefs.
30911b60d2ecSQu Wenruo 			 */
30921b60d2ecSQu Wenruo 			if (btrfs_block_can_be_shared(root, eb))
30931b60d2ecSQu Wenruo 				upper->checked = 0;
30941b60d2ecSQu Wenruo 			else
30951b60d2ecSQu Wenruo 				upper->checked = 1;
30961b60d2ecSQu Wenruo 
30971b60d2ecSQu Wenruo 			/*
30981b60d2ecSQu Wenruo 			 * Add the block to pending list if we need to check its
30991b60d2ecSQu Wenruo 			 * backrefs, we only do this once while walking up a
31001b60d2ecSQu Wenruo 			 * tree as we will catch anything else later on.
31011b60d2ecSQu Wenruo 			 */
31021b60d2ecSQu Wenruo 			if (!upper->checked && need_check) {
31031b60d2ecSQu Wenruo 				need_check = false;
31041b60d2ecSQu Wenruo 				list_add_tail(&edge->list[UPPER],
31051b60d2ecSQu Wenruo 					      &cache->pending_edge);
31061b60d2ecSQu Wenruo 			} else {
31071b60d2ecSQu Wenruo 				if (upper->checked)
31081b60d2ecSQu Wenruo 					need_check = true;
31091b60d2ecSQu Wenruo 				INIT_LIST_HEAD(&edge->list[UPPER]);
31101b60d2ecSQu Wenruo 			}
31111b60d2ecSQu Wenruo 		} else {
31121b60d2ecSQu Wenruo 			upper = rb_entry(rb_node, struct btrfs_backref_node,
31131b60d2ecSQu Wenruo 					 rb_node);
31141b60d2ecSQu Wenruo 			ASSERT(upper->checked);
31151b60d2ecSQu Wenruo 			INIT_LIST_HEAD(&edge->list[UPPER]);
31161b60d2ecSQu Wenruo 			if (!upper->owner)
31171b60d2ecSQu Wenruo 				upper->owner = btrfs_header_owner(eb);
31181b60d2ecSQu Wenruo 		}
31191b60d2ecSQu Wenruo 		btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
31201b60d2ecSQu Wenruo 
31211b60d2ecSQu Wenruo 		if (rb_node) {
31221b60d2ecSQu Wenruo 			btrfs_put_root(root);
31231b60d2ecSQu Wenruo 			break;
31241b60d2ecSQu Wenruo 		}
31251b60d2ecSQu Wenruo 		lower = upper;
31261b60d2ecSQu Wenruo 		upper = NULL;
31271b60d2ecSQu Wenruo 	}
31281b60d2ecSQu Wenruo out:
31291b60d2ecSQu Wenruo 	btrfs_release_path(path);
31301b60d2ecSQu Wenruo 	return ret;
31311b60d2ecSQu Wenruo }
31321b60d2ecSQu Wenruo 
31331b60d2ecSQu Wenruo /*
31341b60d2ecSQu Wenruo  * Add backref node @cur into @cache.
31351b60d2ecSQu Wenruo  *
31361b60d2ecSQu Wenruo  * NOTE: Even if the function returned 0, @cur is not yet cached as its upper
31371b60d2ecSQu Wenruo  *	 links aren't yet bi-directional. Needs to finish such links.
3138fc997ed0SQu Wenruo  *	 Use btrfs_backref_finish_upper_links() to finish such linkage.
31391b60d2ecSQu Wenruo  *
31401b60d2ecSQu Wenruo  * @path:	Released path for indirect tree backref lookup
31411b60d2ecSQu Wenruo  * @iter:	Released backref iter for extent tree search
31421b60d2ecSQu Wenruo  * @node_key:	The first key of the tree block
31431b60d2ecSQu Wenruo  */
31441b60d2ecSQu Wenruo int btrfs_backref_add_tree_node(struct btrfs_backref_cache *cache,
31451b60d2ecSQu Wenruo 				struct btrfs_path *path,
31461b60d2ecSQu Wenruo 				struct btrfs_backref_iter *iter,
31471b60d2ecSQu Wenruo 				struct btrfs_key *node_key,
31481b60d2ecSQu Wenruo 				struct btrfs_backref_node *cur)
31491b60d2ecSQu Wenruo {
31501b60d2ecSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
31511b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
31521b60d2ecSQu Wenruo 	struct btrfs_backref_node *exist;
31531b60d2ecSQu Wenruo 	int ret;
31541b60d2ecSQu Wenruo 
31551b60d2ecSQu Wenruo 	ret = btrfs_backref_iter_start(iter, cur->bytenr);
31561b60d2ecSQu Wenruo 	if (ret < 0)
31571b60d2ecSQu Wenruo 		return ret;
31581b60d2ecSQu Wenruo 	/*
31591b60d2ecSQu Wenruo 	 * We skip the first btrfs_tree_block_info, as we don't use the key
31601b60d2ecSQu Wenruo 	 * stored in it, but fetch it from the tree block
31611b60d2ecSQu Wenruo 	 */
31621b60d2ecSQu Wenruo 	if (btrfs_backref_has_tree_block_info(iter)) {
31631b60d2ecSQu Wenruo 		ret = btrfs_backref_iter_next(iter);
31641b60d2ecSQu Wenruo 		if (ret < 0)
31651b60d2ecSQu Wenruo 			goto out;
31661b60d2ecSQu Wenruo 		/* No extra backref? This means the tree block is corrupted */
31671b60d2ecSQu Wenruo 		if (ret > 0) {
31681b60d2ecSQu Wenruo 			ret = -EUCLEAN;
31691b60d2ecSQu Wenruo 			goto out;
31701b60d2ecSQu Wenruo 		}
31711b60d2ecSQu Wenruo 	}
31721b60d2ecSQu Wenruo 	WARN_ON(cur->checked);
31731b60d2ecSQu Wenruo 	if (!list_empty(&cur->upper)) {
31741b60d2ecSQu Wenruo 		/*
31751b60d2ecSQu Wenruo 		 * The backref was added previously when processing backref of
31761b60d2ecSQu Wenruo 		 * type BTRFS_TREE_BLOCK_REF_KEY
31771b60d2ecSQu Wenruo 		 */
31781b60d2ecSQu Wenruo 		ASSERT(list_is_singular(&cur->upper));
31791b60d2ecSQu Wenruo 		edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
31801b60d2ecSQu Wenruo 				  list[LOWER]);
31811b60d2ecSQu Wenruo 		ASSERT(list_empty(&edge->list[UPPER]));
31821b60d2ecSQu Wenruo 		exist = edge->node[UPPER];
31831b60d2ecSQu Wenruo 		/*
31841b60d2ecSQu Wenruo 		 * Add the upper level block to pending list if we need check
31851b60d2ecSQu Wenruo 		 * its backrefs
31861b60d2ecSQu Wenruo 		 */
31871b60d2ecSQu Wenruo 		if (!exist->checked)
31881b60d2ecSQu Wenruo 			list_add_tail(&edge->list[UPPER], &cache->pending_edge);
31891b60d2ecSQu Wenruo 	} else {
31901b60d2ecSQu Wenruo 		exist = NULL;
31911b60d2ecSQu Wenruo 	}
31921b60d2ecSQu Wenruo 
31931b60d2ecSQu Wenruo 	for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
31941b60d2ecSQu Wenruo 		struct extent_buffer *eb;
31951b60d2ecSQu Wenruo 		struct btrfs_key key;
31961b60d2ecSQu Wenruo 		int type;
31971b60d2ecSQu Wenruo 
31981b60d2ecSQu Wenruo 		cond_resched();
31991b60d2ecSQu Wenruo 		eb = btrfs_backref_get_eb(iter);
32001b60d2ecSQu Wenruo 
32011b60d2ecSQu Wenruo 		key.objectid = iter->bytenr;
32021b60d2ecSQu Wenruo 		if (btrfs_backref_iter_is_inline_ref(iter)) {
32031b60d2ecSQu Wenruo 			struct btrfs_extent_inline_ref *iref;
32041b60d2ecSQu Wenruo 
32051b60d2ecSQu Wenruo 			/* Update key for inline backref */
32061b60d2ecSQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
32071b60d2ecSQu Wenruo 				((unsigned long)iter->cur_ptr);
32081b60d2ecSQu Wenruo 			type = btrfs_get_extent_inline_ref_type(eb, iref,
32091b60d2ecSQu Wenruo 							BTRFS_REF_TYPE_BLOCK);
32101b60d2ecSQu Wenruo 			if (type == BTRFS_REF_TYPE_INVALID) {
32111b60d2ecSQu Wenruo 				ret = -EUCLEAN;
32121b60d2ecSQu Wenruo 				goto out;
32131b60d2ecSQu Wenruo 			}
32141b60d2ecSQu Wenruo 			key.type = type;
32151b60d2ecSQu Wenruo 			key.offset = btrfs_extent_inline_ref_offset(eb, iref);
32161b60d2ecSQu Wenruo 		} else {
32171b60d2ecSQu Wenruo 			key.type = iter->cur_key.type;
32181b60d2ecSQu Wenruo 			key.offset = iter->cur_key.offset;
32191b60d2ecSQu Wenruo 		}
32201b60d2ecSQu Wenruo 
32211b60d2ecSQu Wenruo 		/*
32221b60d2ecSQu Wenruo 		 * Parent node found and matches current inline ref, no need to
32231b60d2ecSQu Wenruo 		 * rebuild this node for this inline ref
32241b60d2ecSQu Wenruo 		 */
32251b60d2ecSQu Wenruo 		if (exist &&
32261b60d2ecSQu Wenruo 		    ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
32271b60d2ecSQu Wenruo 		      exist->owner == key.offset) ||
32281b60d2ecSQu Wenruo 		     (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
32291b60d2ecSQu Wenruo 		      exist->bytenr == key.offset))) {
32301b60d2ecSQu Wenruo 			exist = NULL;
32311b60d2ecSQu Wenruo 			continue;
32321b60d2ecSQu Wenruo 		}
32331b60d2ecSQu Wenruo 
32341b60d2ecSQu Wenruo 		/* SHARED_BLOCK_REF means key.offset is the parent bytenr */
32351b60d2ecSQu Wenruo 		if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
32361b60d2ecSQu Wenruo 			ret = handle_direct_tree_backref(cache, &key, cur);
32371b60d2ecSQu Wenruo 			if (ret < 0)
32381b60d2ecSQu Wenruo 				goto out;
32391b60d2ecSQu Wenruo 			continue;
32401b60d2ecSQu Wenruo 		} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
32411b60d2ecSQu Wenruo 			ret = -EINVAL;
32421b60d2ecSQu Wenruo 			btrfs_print_v0_err(fs_info);
32431b60d2ecSQu Wenruo 			btrfs_handle_fs_error(fs_info, ret, NULL);
32441b60d2ecSQu Wenruo 			goto out;
32451b60d2ecSQu Wenruo 		} else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
32461b60d2ecSQu Wenruo 			continue;
32471b60d2ecSQu Wenruo 		}
32481b60d2ecSQu Wenruo 
32491b60d2ecSQu Wenruo 		/*
32501b60d2ecSQu Wenruo 		 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
32511b60d2ecSQu Wenruo 		 * means the root objectid. We need to search the tree to get
32521b60d2ecSQu Wenruo 		 * its parent bytenr.
32531b60d2ecSQu Wenruo 		 */
32541b60d2ecSQu Wenruo 		ret = handle_indirect_tree_backref(cache, path, &key, node_key,
32551b60d2ecSQu Wenruo 						   cur);
32561b60d2ecSQu Wenruo 		if (ret < 0)
32571b60d2ecSQu Wenruo 			goto out;
32581b60d2ecSQu Wenruo 	}
32591b60d2ecSQu Wenruo 	ret = 0;
32601b60d2ecSQu Wenruo 	cur->checked = 1;
32611b60d2ecSQu Wenruo 	WARN_ON(exist);
32621b60d2ecSQu Wenruo out:
32631b60d2ecSQu Wenruo 	btrfs_backref_iter_release(iter);
32641b60d2ecSQu Wenruo 	return ret;
32651b60d2ecSQu Wenruo }
3266fc997ed0SQu Wenruo 
3267fc997ed0SQu Wenruo /*
3268fc997ed0SQu Wenruo  * Finish the upwards linkage created by btrfs_backref_add_tree_node()
3269fc997ed0SQu Wenruo  */
3270fc997ed0SQu Wenruo int btrfs_backref_finish_upper_links(struct btrfs_backref_cache *cache,
3271fc997ed0SQu Wenruo 				     struct btrfs_backref_node *start)
3272fc997ed0SQu Wenruo {
3273fc997ed0SQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
3274fc997ed0SQu Wenruo 	struct btrfs_backref_edge *edge;
3275fc997ed0SQu Wenruo 	struct rb_node *rb_node;
3276fc997ed0SQu Wenruo 	LIST_HEAD(pending_edge);
3277fc997ed0SQu Wenruo 
3278fc997ed0SQu Wenruo 	ASSERT(start->checked);
3279fc997ed0SQu Wenruo 
3280fc997ed0SQu Wenruo 	/* Insert this node to cache if it's not COW-only */
3281fc997ed0SQu Wenruo 	if (!start->cowonly) {
3282fc997ed0SQu Wenruo 		rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
3283fc997ed0SQu Wenruo 					   &start->rb_node);
3284fc997ed0SQu Wenruo 		if (rb_node)
3285fc997ed0SQu Wenruo 			btrfs_backref_panic(cache->fs_info, start->bytenr,
3286fc997ed0SQu Wenruo 					    -EEXIST);
3287fc997ed0SQu Wenruo 		list_add_tail(&start->lower, &cache->leaves);
3288fc997ed0SQu Wenruo 	}
3289fc997ed0SQu Wenruo 
3290fc997ed0SQu Wenruo 	/*
3291fc997ed0SQu Wenruo 	 * Use breadth first search to iterate all related edges.
3292fc997ed0SQu Wenruo 	 *
3293fc997ed0SQu Wenruo 	 * The starting points are all the edges of this node
3294fc997ed0SQu Wenruo 	 */
3295fc997ed0SQu Wenruo 	list_for_each_entry(edge, &start->upper, list[LOWER])
3296fc997ed0SQu Wenruo 		list_add_tail(&edge->list[UPPER], &pending_edge);
3297fc997ed0SQu Wenruo 
3298fc997ed0SQu Wenruo 	while (!list_empty(&pending_edge)) {
3299fc997ed0SQu Wenruo 		struct btrfs_backref_node *upper;
3300fc997ed0SQu Wenruo 		struct btrfs_backref_node *lower;
3301fc997ed0SQu Wenruo 
3302fc997ed0SQu Wenruo 		edge = list_first_entry(&pending_edge,
3303fc997ed0SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
3304fc997ed0SQu Wenruo 		list_del_init(&edge->list[UPPER]);
3305fc997ed0SQu Wenruo 		upper = edge->node[UPPER];
3306fc997ed0SQu Wenruo 		lower = edge->node[LOWER];
3307fc997ed0SQu Wenruo 
3308fc997ed0SQu Wenruo 		/* Parent is detached, no need to keep any edges */
3309fc997ed0SQu Wenruo 		if (upper->detached) {
3310fc997ed0SQu Wenruo 			list_del(&edge->list[LOWER]);
3311fc997ed0SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
3312fc997ed0SQu Wenruo 
3313fc997ed0SQu Wenruo 			/* Lower node is orphan, queue for cleanup */
3314fc997ed0SQu Wenruo 			if (list_empty(&lower->upper))
3315fc997ed0SQu Wenruo 				list_add(&lower->list, useless_node);
3316fc997ed0SQu Wenruo 			continue;
3317fc997ed0SQu Wenruo 		}
3318fc997ed0SQu Wenruo 
3319fc997ed0SQu Wenruo 		/*
3320fc997ed0SQu Wenruo 		 * All new nodes added in current build_backref_tree() haven't
3321fc997ed0SQu Wenruo 		 * been linked to the cache rb tree.
3322fc997ed0SQu Wenruo 		 * So if we have upper->rb_node populated, this means a cache
3323fc997ed0SQu Wenruo 		 * hit. We only need to link the edge, as @upper and all its
3324fc997ed0SQu Wenruo 		 * parents have already been linked.
3325fc997ed0SQu Wenruo 		 */
3326fc997ed0SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node)) {
3327fc997ed0SQu Wenruo 			if (upper->lowest) {
3328fc997ed0SQu Wenruo 				list_del_init(&upper->lower);
3329fc997ed0SQu Wenruo 				upper->lowest = 0;
3330fc997ed0SQu Wenruo 			}
3331fc997ed0SQu Wenruo 
3332fc997ed0SQu Wenruo 			list_add_tail(&edge->list[UPPER], &upper->lower);
3333fc997ed0SQu Wenruo 			continue;
3334fc997ed0SQu Wenruo 		}
3335fc997ed0SQu Wenruo 
3336fc997ed0SQu Wenruo 		/* Sanity check, we shouldn't have any unchecked nodes */
3337fc997ed0SQu Wenruo 		if (!upper->checked) {
3338fc997ed0SQu Wenruo 			ASSERT(0);
3339fc997ed0SQu Wenruo 			return -EUCLEAN;
3340fc997ed0SQu Wenruo 		}
3341fc997ed0SQu Wenruo 
3342fc997ed0SQu Wenruo 		/* Sanity check, COW-only node has non-COW-only parent */
3343fc997ed0SQu Wenruo 		if (start->cowonly != upper->cowonly) {
3344fc997ed0SQu Wenruo 			ASSERT(0);
3345fc997ed0SQu Wenruo 			return -EUCLEAN;
3346fc997ed0SQu Wenruo 		}
3347fc997ed0SQu Wenruo 
3348fc997ed0SQu Wenruo 		/* Only cache non-COW-only (subvolume trees) tree blocks */
3349fc997ed0SQu Wenruo 		if (!upper->cowonly) {
3350fc997ed0SQu Wenruo 			rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
3351fc997ed0SQu Wenruo 						   &upper->rb_node);
3352fc997ed0SQu Wenruo 			if (rb_node) {
3353fc997ed0SQu Wenruo 				btrfs_backref_panic(cache->fs_info,
3354fc997ed0SQu Wenruo 						upper->bytenr, -EEXIST);
3355fc997ed0SQu Wenruo 				return -EUCLEAN;
3356fc997ed0SQu Wenruo 			}
3357fc997ed0SQu Wenruo 		}
3358fc997ed0SQu Wenruo 
3359fc997ed0SQu Wenruo 		list_add_tail(&edge->list[UPPER], &upper->lower);
3360fc997ed0SQu Wenruo 
3361fc997ed0SQu Wenruo 		/*
3362fc997ed0SQu Wenruo 		 * Also queue all the parent edges of this uncached node
3363fc997ed0SQu Wenruo 		 * to finish the upper linkage
3364fc997ed0SQu Wenruo 		 */
3365fc997ed0SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
3366fc997ed0SQu Wenruo 			list_add_tail(&edge->list[UPPER], &pending_edge);
3367fc997ed0SQu Wenruo 	}
3368fc997ed0SQu Wenruo 	return 0;
3369fc997ed0SQu Wenruo }
33701b23ea18SQu Wenruo 
33711b23ea18SQu Wenruo void btrfs_backref_error_cleanup(struct btrfs_backref_cache *cache,
33721b23ea18SQu Wenruo 				 struct btrfs_backref_node *node)
33731b23ea18SQu Wenruo {
33741b23ea18SQu Wenruo 	struct btrfs_backref_node *lower;
33751b23ea18SQu Wenruo 	struct btrfs_backref_node *upper;
33761b23ea18SQu Wenruo 	struct btrfs_backref_edge *edge;
33771b23ea18SQu Wenruo 
33781b23ea18SQu Wenruo 	while (!list_empty(&cache->useless_node)) {
33791b23ea18SQu Wenruo 		lower = list_first_entry(&cache->useless_node,
33801b23ea18SQu Wenruo 				   struct btrfs_backref_node, list);
33811b23ea18SQu Wenruo 		list_del_init(&lower->list);
33821b23ea18SQu Wenruo 	}
33831b23ea18SQu Wenruo 	while (!list_empty(&cache->pending_edge)) {
33841b23ea18SQu Wenruo 		edge = list_first_entry(&cache->pending_edge,
33851b23ea18SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
33861b23ea18SQu Wenruo 		list_del(&edge->list[UPPER]);
33871b23ea18SQu Wenruo 		list_del(&edge->list[LOWER]);
33881b23ea18SQu Wenruo 		lower = edge->node[LOWER];
33891b23ea18SQu Wenruo 		upper = edge->node[UPPER];
33901b23ea18SQu Wenruo 		btrfs_backref_free_edge(cache, edge);
33911b23ea18SQu Wenruo 
33921b23ea18SQu Wenruo 		/*
33931b23ea18SQu Wenruo 		 * Lower is no longer linked to any upper backref nodes and
33941b23ea18SQu Wenruo 		 * isn't in the cache, we can free it ourselves.
33951b23ea18SQu Wenruo 		 */
33961b23ea18SQu Wenruo 		if (list_empty(&lower->upper) &&
33971b23ea18SQu Wenruo 		    RB_EMPTY_NODE(&lower->rb_node))
33981b23ea18SQu Wenruo 			list_add(&lower->list, &cache->useless_node);
33991b23ea18SQu Wenruo 
34001b23ea18SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node))
34011b23ea18SQu Wenruo 			continue;
34021b23ea18SQu Wenruo 
34031b23ea18SQu Wenruo 		/* Add this guy's upper edges to the list to process */
34041b23ea18SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
34051b23ea18SQu Wenruo 			list_add_tail(&edge->list[UPPER],
34061b23ea18SQu Wenruo 				      &cache->pending_edge);
34071b23ea18SQu Wenruo 		if (list_empty(&upper->upper))
34081b23ea18SQu Wenruo 			list_add(&upper->list, &cache->useless_node);
34091b23ea18SQu Wenruo 	}
34101b23ea18SQu Wenruo 
34111b23ea18SQu Wenruo 	while (!list_empty(&cache->useless_node)) {
34121b23ea18SQu Wenruo 		lower = list_first_entry(&cache->useless_node,
34131b23ea18SQu Wenruo 				   struct btrfs_backref_node, list);
34141b23ea18SQu Wenruo 		list_del_init(&lower->list);
34151b23ea18SQu Wenruo 		if (lower == node)
34161b23ea18SQu Wenruo 			node = NULL;
341749ecc679SJosef Bacik 		btrfs_backref_drop_node(cache, lower);
34181b23ea18SQu Wenruo 	}
34191b23ea18SQu Wenruo 
34201b23ea18SQu Wenruo 	btrfs_backref_cleanup_node(cache, node);
34211b23ea18SQu Wenruo 	ASSERT(list_empty(&cache->useless_node) &&
34221b23ea18SQu Wenruo 	       list_empty(&cache->pending_edge));
34231b23ea18SQu Wenruo }
3424