xref: /openbmc/linux/fs/btrfs/backref.c (revision 66d04209e5a8d3fc47900de6bd0c319790a52b3e)
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"
18c7f13d42SJosef Bacik #include "fs.h"
1907e81dc9SJosef Bacik #include "accessors.h"
20a0231804SJosef Bacik #include "extent-tree.h"
2167707479SJosef Bacik #include "relocation.h"
22a542ad1bSJan Schmidt 
23877c1476SFilipe Manana /* Just arbitrary numbers so we can be sure one of these happened. */
24dc046b10SJosef Bacik #define BACKREF_FOUND_SHARED     6
25877c1476SFilipe Manana #define BACKREF_FOUND_NOT_SHARED 7
26dc046b10SJosef Bacik 
27976b1908SJan Schmidt struct extent_inode_elem {
28976b1908SJan Schmidt 	u64 inum;
29976b1908SJan Schmidt 	u64 offset;
30c7499a64SFilipe Manana 	u64 num_bytes;
31976b1908SJan Schmidt 	struct extent_inode_elem *next;
32976b1908SJan Schmidt };
33976b1908SJan Schmidt 
3473980becSJeff Mahoney static int check_extent_in_eb(const struct btrfs_key *key,
3573980becSJeff Mahoney 			      const struct extent_buffer *eb,
3673980becSJeff Mahoney 			      const struct btrfs_file_extent_item *fi,
37976b1908SJan Schmidt 			      u64 extent_item_pos,
386ce6ba53SFilipe Manana 			      struct extent_inode_elem **eie)
39976b1908SJan Schmidt {
40c7499a64SFilipe Manana 	const u64 data_len = btrfs_file_extent_num_bytes(eb, fi);
418ca15e05SJosef Bacik 	u64 offset = 0;
428ca15e05SJosef Bacik 	struct extent_inode_elem *e;
438ca15e05SJosef Bacik 
446ce6ba53SFilipe Manana 	if (!btrfs_file_extent_compression(eb, fi) &&
458ca15e05SJosef Bacik 	    !btrfs_file_extent_encryption(eb, fi) &&
468ca15e05SJosef Bacik 	    !btrfs_file_extent_other_encoding(eb, fi)) {
47976b1908SJan Schmidt 		u64 data_offset;
48976b1908SJan Schmidt 
49976b1908SJan Schmidt 		data_offset = btrfs_file_extent_offset(eb, fi);
50976b1908SJan Schmidt 
51976b1908SJan Schmidt 		if (extent_item_pos < data_offset ||
52976b1908SJan Schmidt 		    extent_item_pos >= data_offset + data_len)
53976b1908SJan Schmidt 			return 1;
548ca15e05SJosef Bacik 		offset = extent_item_pos - data_offset;
558ca15e05SJosef Bacik 	}
56976b1908SJan Schmidt 
57976b1908SJan Schmidt 	e = kmalloc(sizeof(*e), GFP_NOFS);
58976b1908SJan Schmidt 	if (!e)
59976b1908SJan Schmidt 		return -ENOMEM;
60976b1908SJan Schmidt 
61976b1908SJan Schmidt 	e->next = *eie;
62976b1908SJan Schmidt 	e->inum = key->objectid;
638ca15e05SJosef Bacik 	e->offset = key->offset + offset;
64c7499a64SFilipe Manana 	e->num_bytes = data_len;
65976b1908SJan Schmidt 	*eie = e;
66976b1908SJan Schmidt 
67976b1908SJan Schmidt 	return 0;
68976b1908SJan Schmidt }
69976b1908SJan Schmidt 
70f05c4746SWang Shilong static void free_inode_elem_list(struct extent_inode_elem *eie)
71f05c4746SWang Shilong {
72f05c4746SWang Shilong 	struct extent_inode_elem *eie_next;
73f05c4746SWang Shilong 
74f05c4746SWang Shilong 	for (; eie; eie = eie_next) {
75f05c4746SWang Shilong 		eie_next = eie->next;
76f05c4746SWang Shilong 		kfree(eie);
77f05c4746SWang Shilong 	}
78f05c4746SWang Shilong }
79f05c4746SWang Shilong 
8073980becSJeff Mahoney static int find_extent_in_eb(const struct extent_buffer *eb,
8173980becSJeff Mahoney 			     u64 wanted_disk_byte, u64 extent_item_pos,
826ce6ba53SFilipe Manana 			     struct extent_inode_elem **eie)
83976b1908SJan Schmidt {
84976b1908SJan Schmidt 	u64 disk_byte;
85976b1908SJan Schmidt 	struct btrfs_key key;
86976b1908SJan Schmidt 	struct btrfs_file_extent_item *fi;
87976b1908SJan Schmidt 	int slot;
88976b1908SJan Schmidt 	int nritems;
89976b1908SJan Schmidt 	int extent_type;
90976b1908SJan Schmidt 	int ret;
91976b1908SJan Schmidt 
92976b1908SJan Schmidt 	/*
93976b1908SJan Schmidt 	 * from the shared data ref, we only have the leaf but we need
94976b1908SJan Schmidt 	 * the key. thus, we must look into all items and see that we
95976b1908SJan Schmidt 	 * find one (some) with a reference to our extent item.
96976b1908SJan Schmidt 	 */
97976b1908SJan Schmidt 	nritems = btrfs_header_nritems(eb);
98976b1908SJan Schmidt 	for (slot = 0; slot < nritems; ++slot) {
99976b1908SJan Schmidt 		btrfs_item_key_to_cpu(eb, &key, slot);
100976b1908SJan Schmidt 		if (key.type != BTRFS_EXTENT_DATA_KEY)
101976b1908SJan Schmidt 			continue;
102976b1908SJan Schmidt 		fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
103976b1908SJan Schmidt 		extent_type = btrfs_file_extent_type(eb, fi);
104976b1908SJan Schmidt 		if (extent_type == BTRFS_FILE_EXTENT_INLINE)
105976b1908SJan Schmidt 			continue;
106976b1908SJan Schmidt 		/* don't skip BTRFS_FILE_EXTENT_PREALLOC, we can handle that */
107976b1908SJan Schmidt 		disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
108976b1908SJan Schmidt 		if (disk_byte != wanted_disk_byte)
109976b1908SJan Schmidt 			continue;
110976b1908SJan Schmidt 
1116ce6ba53SFilipe Manana 		ret = check_extent_in_eb(&key, eb, fi, extent_item_pos, eie);
112976b1908SJan Schmidt 		if (ret < 0)
113976b1908SJan Schmidt 			return ret;
114976b1908SJan Schmidt 	}
115976b1908SJan Schmidt 
116976b1908SJan Schmidt 	return 0;
117976b1908SJan Schmidt }
118976b1908SJan Schmidt 
11986d5f994SEdmund Nadolski struct preftree {
120ecf160b4SLiu Bo 	struct rb_root_cached root;
1216c336b21SJeff Mahoney 	unsigned int count;
12286d5f994SEdmund Nadolski };
12386d5f994SEdmund Nadolski 
124ecf160b4SLiu Bo #define PREFTREE_INIT	{ .root = RB_ROOT_CACHED, .count = 0 }
12586d5f994SEdmund Nadolski 
12686d5f994SEdmund Nadolski struct preftrees {
12786d5f994SEdmund Nadolski 	struct preftree direct;    /* BTRFS_SHARED_[DATA|BLOCK]_REF_KEY */
12886d5f994SEdmund Nadolski 	struct preftree indirect;  /* BTRFS_[TREE_BLOCK|EXTENT_DATA]_REF_KEY */
12986d5f994SEdmund Nadolski 	struct preftree indirect_missing_keys;
13086d5f994SEdmund Nadolski };
13186d5f994SEdmund Nadolski 
1323ec4d323SEdmund Nadolski /*
1333ec4d323SEdmund Nadolski  * Checks for a shared extent during backref search.
1343ec4d323SEdmund Nadolski  *
1353ec4d323SEdmund Nadolski  * The share_count tracks prelim_refs (direct and indirect) having a
1363ec4d323SEdmund Nadolski  * ref->count >0:
1373ec4d323SEdmund Nadolski  *  - incremented when a ref->count transitions to >0
1383ec4d323SEdmund Nadolski  *  - decremented when a ref->count transitions to <1
1393ec4d323SEdmund Nadolski  */
1403ec4d323SEdmund Nadolski struct share_check {
141877c1476SFilipe Manana 	struct btrfs_backref_share_check_ctx *ctx;
142877c1476SFilipe Manana 	struct btrfs_root *root;
1433ec4d323SEdmund Nadolski 	u64 inum;
14473e339e6SFilipe Manana 	u64 data_bytenr;
1456976201fSFilipe Manana 	u64 data_extent_gen;
14673e339e6SFilipe Manana 	/*
14773e339e6SFilipe Manana 	 * Counts number of inodes that refer to an extent (different inodes in
14873e339e6SFilipe Manana 	 * the same root or different roots) that we could find. The sharedness
14973e339e6SFilipe Manana 	 * check typically stops once this counter gets greater than 1, so it
15073e339e6SFilipe Manana 	 * may not reflect the total number of inodes.
15173e339e6SFilipe Manana 	 */
1523ec4d323SEdmund Nadolski 	int share_count;
15373e339e6SFilipe Manana 	/*
15473e339e6SFilipe Manana 	 * The number of times we found our inode refers to the data extent we
15573e339e6SFilipe Manana 	 * are determining the sharedness. In other words, how many file extent
15673e339e6SFilipe Manana 	 * items we could find for our inode that point to our target data
15773e339e6SFilipe Manana 	 * extent. The value we get here after finishing the extent sharedness
15873e339e6SFilipe Manana 	 * check may be smaller than reality, but if it ends up being greater
15973e339e6SFilipe Manana 	 * than 1, then we know for sure the inode has multiple file extent
16073e339e6SFilipe Manana 	 * items that point to our inode, and we can safely assume it's useful
16173e339e6SFilipe Manana 	 * to cache the sharedness check result.
16273e339e6SFilipe Manana 	 */
16373e339e6SFilipe Manana 	int self_ref_count;
1644fc7b572SFilipe Manana 	bool have_delayed_delete_refs;
1653ec4d323SEdmund Nadolski };
1663ec4d323SEdmund Nadolski 
1673ec4d323SEdmund Nadolski static inline int extent_is_shared(struct share_check *sc)
1683ec4d323SEdmund Nadolski {
1693ec4d323SEdmund Nadolski 	return (sc && sc->share_count > 1) ? BACKREF_FOUND_SHARED : 0;
1703ec4d323SEdmund Nadolski }
1713ec4d323SEdmund Nadolski 
172b9e9a6cbSWang Shilong static struct kmem_cache *btrfs_prelim_ref_cache;
173b9e9a6cbSWang Shilong 
174b9e9a6cbSWang Shilong int __init btrfs_prelim_ref_init(void)
175b9e9a6cbSWang Shilong {
176b9e9a6cbSWang Shilong 	btrfs_prelim_ref_cache = kmem_cache_create("btrfs_prelim_ref",
177e0c476b1SJeff Mahoney 					sizeof(struct prelim_ref),
178b9e9a6cbSWang Shilong 					0,
179fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
180b9e9a6cbSWang Shilong 					NULL);
181b9e9a6cbSWang Shilong 	if (!btrfs_prelim_ref_cache)
182b9e9a6cbSWang Shilong 		return -ENOMEM;
183b9e9a6cbSWang Shilong 	return 0;
184b9e9a6cbSWang Shilong }
185b9e9a6cbSWang Shilong 
186e67c718bSDavid Sterba void __cold btrfs_prelim_ref_exit(void)
187b9e9a6cbSWang Shilong {
188b9e9a6cbSWang Shilong 	kmem_cache_destroy(btrfs_prelim_ref_cache);
189b9e9a6cbSWang Shilong }
190b9e9a6cbSWang Shilong 
19186d5f994SEdmund Nadolski static void free_pref(struct prelim_ref *ref)
19286d5f994SEdmund Nadolski {
19386d5f994SEdmund Nadolski 	kmem_cache_free(btrfs_prelim_ref_cache, ref);
19486d5f994SEdmund Nadolski }
19586d5f994SEdmund Nadolski 
19686d5f994SEdmund Nadolski /*
19786d5f994SEdmund Nadolski  * Return 0 when both refs are for the same block (and can be merged).
19886d5f994SEdmund Nadolski  * A -1 return indicates ref1 is a 'lower' block than ref2, while 1
19986d5f994SEdmund Nadolski  * indicates a 'higher' block.
20086d5f994SEdmund Nadolski  */
20186d5f994SEdmund Nadolski static int prelim_ref_compare(struct prelim_ref *ref1,
20286d5f994SEdmund Nadolski 			      struct prelim_ref *ref2)
20386d5f994SEdmund Nadolski {
20486d5f994SEdmund Nadolski 	if (ref1->level < ref2->level)
20586d5f994SEdmund Nadolski 		return -1;
20686d5f994SEdmund Nadolski 	if (ref1->level > ref2->level)
20786d5f994SEdmund Nadolski 		return 1;
20886d5f994SEdmund Nadolski 	if (ref1->root_id < ref2->root_id)
20986d5f994SEdmund Nadolski 		return -1;
21086d5f994SEdmund Nadolski 	if (ref1->root_id > ref2->root_id)
21186d5f994SEdmund Nadolski 		return 1;
21286d5f994SEdmund Nadolski 	if (ref1->key_for_search.type < ref2->key_for_search.type)
21386d5f994SEdmund Nadolski 		return -1;
21486d5f994SEdmund Nadolski 	if (ref1->key_for_search.type > ref2->key_for_search.type)
21586d5f994SEdmund Nadolski 		return 1;
21686d5f994SEdmund Nadolski 	if (ref1->key_for_search.objectid < ref2->key_for_search.objectid)
21786d5f994SEdmund Nadolski 		return -1;
21886d5f994SEdmund Nadolski 	if (ref1->key_for_search.objectid > ref2->key_for_search.objectid)
21986d5f994SEdmund Nadolski 		return 1;
22086d5f994SEdmund Nadolski 	if (ref1->key_for_search.offset < ref2->key_for_search.offset)
22186d5f994SEdmund Nadolski 		return -1;
22286d5f994SEdmund Nadolski 	if (ref1->key_for_search.offset > ref2->key_for_search.offset)
22386d5f994SEdmund Nadolski 		return 1;
22486d5f994SEdmund Nadolski 	if (ref1->parent < ref2->parent)
22586d5f994SEdmund Nadolski 		return -1;
22686d5f994SEdmund Nadolski 	if (ref1->parent > ref2->parent)
22786d5f994SEdmund Nadolski 		return 1;
22886d5f994SEdmund Nadolski 
22986d5f994SEdmund Nadolski 	return 0;
23086d5f994SEdmund Nadolski }
23186d5f994SEdmund Nadolski 
232ccc8dc75SColin Ian King static void update_share_count(struct share_check *sc, int oldcount,
23373e339e6SFilipe Manana 			       int newcount, struct prelim_ref *newref)
2343ec4d323SEdmund Nadolski {
2353ec4d323SEdmund Nadolski 	if ((!sc) || (oldcount == 0 && newcount < 1))
2363ec4d323SEdmund Nadolski 		return;
2373ec4d323SEdmund Nadolski 
2383ec4d323SEdmund Nadolski 	if (oldcount > 0 && newcount < 1)
2393ec4d323SEdmund Nadolski 		sc->share_count--;
2403ec4d323SEdmund Nadolski 	else if (oldcount < 1 && newcount > 0)
2413ec4d323SEdmund Nadolski 		sc->share_count++;
24273e339e6SFilipe Manana 
243877c1476SFilipe Manana 	if (newref->root_id == sc->root->root_key.objectid &&
24473e339e6SFilipe Manana 	    newref->wanted_disk_byte == sc->data_bytenr &&
24573e339e6SFilipe Manana 	    newref->key_for_search.objectid == sc->inum)
24673e339e6SFilipe Manana 		sc->self_ref_count += newref->count;
2473ec4d323SEdmund Nadolski }
2483ec4d323SEdmund Nadolski 
24986d5f994SEdmund Nadolski /*
25086d5f994SEdmund Nadolski  * Add @newref to the @root rbtree, merging identical refs.
25186d5f994SEdmund Nadolski  *
2523ec4d323SEdmund Nadolski  * Callers should assume that newref has been freed after calling.
25386d5f994SEdmund Nadolski  */
25400142756SJeff Mahoney static void prelim_ref_insert(const struct btrfs_fs_info *fs_info,
25500142756SJeff Mahoney 			      struct preftree *preftree,
2563ec4d323SEdmund Nadolski 			      struct prelim_ref *newref,
2573ec4d323SEdmund Nadolski 			      struct share_check *sc)
25886d5f994SEdmund Nadolski {
259ecf160b4SLiu Bo 	struct rb_root_cached *root;
26086d5f994SEdmund Nadolski 	struct rb_node **p;
26186d5f994SEdmund Nadolski 	struct rb_node *parent = NULL;
26286d5f994SEdmund Nadolski 	struct prelim_ref *ref;
26386d5f994SEdmund Nadolski 	int result;
264ecf160b4SLiu Bo 	bool leftmost = true;
26586d5f994SEdmund Nadolski 
26686d5f994SEdmund Nadolski 	root = &preftree->root;
267ecf160b4SLiu Bo 	p = &root->rb_root.rb_node;
26886d5f994SEdmund Nadolski 
26986d5f994SEdmund Nadolski 	while (*p) {
27086d5f994SEdmund Nadolski 		parent = *p;
27186d5f994SEdmund Nadolski 		ref = rb_entry(parent, struct prelim_ref, rbnode);
27286d5f994SEdmund Nadolski 		result = prelim_ref_compare(ref, newref);
27386d5f994SEdmund Nadolski 		if (result < 0) {
27486d5f994SEdmund Nadolski 			p = &(*p)->rb_left;
27586d5f994SEdmund Nadolski 		} else if (result > 0) {
27686d5f994SEdmund Nadolski 			p = &(*p)->rb_right;
277ecf160b4SLiu Bo 			leftmost = false;
27886d5f994SEdmund Nadolski 		} else {
27986d5f994SEdmund Nadolski 			/* Identical refs, merge them and free @newref */
28086d5f994SEdmund Nadolski 			struct extent_inode_elem *eie = ref->inode_list;
28186d5f994SEdmund Nadolski 
28286d5f994SEdmund Nadolski 			while (eie && eie->next)
28386d5f994SEdmund Nadolski 				eie = eie->next;
28486d5f994SEdmund Nadolski 
28586d5f994SEdmund Nadolski 			if (!eie)
28686d5f994SEdmund Nadolski 				ref->inode_list = newref->inode_list;
28786d5f994SEdmund Nadolski 			else
28886d5f994SEdmund Nadolski 				eie->next = newref->inode_list;
28900142756SJeff Mahoney 			trace_btrfs_prelim_ref_merge(fs_info, ref, newref,
29000142756SJeff Mahoney 						     preftree->count);
2913ec4d323SEdmund Nadolski 			/*
2923ec4d323SEdmund Nadolski 			 * A delayed ref can have newref->count < 0.
2933ec4d323SEdmund Nadolski 			 * The ref->count is updated to follow any
2943ec4d323SEdmund Nadolski 			 * BTRFS_[ADD|DROP]_DELAYED_REF actions.
2953ec4d323SEdmund Nadolski 			 */
2963ec4d323SEdmund Nadolski 			update_share_count(sc, ref->count,
29773e339e6SFilipe Manana 					   ref->count + newref->count, newref);
29886d5f994SEdmund Nadolski 			ref->count += newref->count;
29986d5f994SEdmund Nadolski 			free_pref(newref);
30086d5f994SEdmund Nadolski 			return;
30186d5f994SEdmund Nadolski 		}
30286d5f994SEdmund Nadolski 	}
30386d5f994SEdmund Nadolski 
30473e339e6SFilipe Manana 	update_share_count(sc, 0, newref->count, newref);
3056c336b21SJeff Mahoney 	preftree->count++;
30600142756SJeff Mahoney 	trace_btrfs_prelim_ref_insert(fs_info, newref, NULL, preftree->count);
30786d5f994SEdmund Nadolski 	rb_link_node(&newref->rbnode, parent, p);
308ecf160b4SLiu Bo 	rb_insert_color_cached(&newref->rbnode, root, leftmost);
30986d5f994SEdmund Nadolski }
31086d5f994SEdmund Nadolski 
31186d5f994SEdmund Nadolski /*
31286d5f994SEdmund Nadolski  * Release the entire tree.  We don't care about internal consistency so
31386d5f994SEdmund Nadolski  * just free everything and then reset the tree root.
31486d5f994SEdmund Nadolski  */
31586d5f994SEdmund Nadolski static void prelim_release(struct preftree *preftree)
31686d5f994SEdmund Nadolski {
31786d5f994SEdmund Nadolski 	struct prelim_ref *ref, *next_ref;
31886d5f994SEdmund Nadolski 
319ecf160b4SLiu Bo 	rbtree_postorder_for_each_entry_safe(ref, next_ref,
32092876eecSFilipe Manana 					     &preftree->root.rb_root, rbnode) {
32192876eecSFilipe Manana 		free_inode_elem_list(ref->inode_list);
32286d5f994SEdmund Nadolski 		free_pref(ref);
32392876eecSFilipe Manana 	}
32486d5f994SEdmund Nadolski 
325ecf160b4SLiu Bo 	preftree->root = RB_ROOT_CACHED;
3266c336b21SJeff Mahoney 	preftree->count = 0;
32786d5f994SEdmund Nadolski }
32886d5f994SEdmund Nadolski 
329d5c88b73SJan Schmidt /*
330d5c88b73SJan Schmidt  * the rules for all callers of this function are:
331d5c88b73SJan Schmidt  * - obtaining the parent is the goal
332d5c88b73SJan Schmidt  * - if you add a key, you must know that it is a correct key
333d5c88b73SJan Schmidt  * - if you cannot add the parent or a correct key, then we will look into the
334d5c88b73SJan Schmidt  *   block later to set a correct key
335d5c88b73SJan Schmidt  *
336d5c88b73SJan Schmidt  * delayed refs
337d5c88b73SJan Schmidt  * ============
338d5c88b73SJan Schmidt  *        backref type | shared | indirect | shared | indirect
339d5c88b73SJan Schmidt  * information         |   tree |     tree |   data |     data
340d5c88b73SJan Schmidt  * --------------------+--------+----------+--------+----------
341d5c88b73SJan Schmidt  *      parent logical |    y   |     -    |    -   |     -
342d5c88b73SJan Schmidt  *      key to resolve |    -   |     y    |    y   |     y
343d5c88b73SJan Schmidt  *  tree block logical |    -   |     -    |    -   |     -
344d5c88b73SJan Schmidt  *  root for resolving |    y   |     y    |    y   |     y
345d5c88b73SJan Schmidt  *
346d5c88b73SJan Schmidt  * - column 1:       we've the parent -> done
347d5c88b73SJan Schmidt  * - column 2, 3, 4: we use the key to find the parent
348d5c88b73SJan Schmidt  *
349d5c88b73SJan Schmidt  * on disk refs (inline or keyed)
350d5c88b73SJan Schmidt  * ==============================
351d5c88b73SJan Schmidt  *        backref type | shared | indirect | shared | indirect
352d5c88b73SJan Schmidt  * information         |   tree |     tree |   data |     data
353d5c88b73SJan Schmidt  * --------------------+--------+----------+--------+----------
354d5c88b73SJan Schmidt  *      parent logical |    y   |     -    |    y   |     -
355d5c88b73SJan Schmidt  *      key to resolve |    -   |     -    |    -   |     y
356d5c88b73SJan Schmidt  *  tree block logical |    y   |     y    |    y   |     y
357d5c88b73SJan Schmidt  *  root for resolving |    -   |     y    |    y   |     y
358d5c88b73SJan Schmidt  *
359d5c88b73SJan Schmidt  * - column 1, 3: we've the parent -> done
360d5c88b73SJan Schmidt  * - column 2:    we take the first key from the block to find the parent
361e0c476b1SJeff Mahoney  *                (see add_missing_keys)
362d5c88b73SJan Schmidt  * - column 4:    we use the key to find the parent
363d5c88b73SJan Schmidt  *
364d5c88b73SJan Schmidt  * additional information that's available but not required to find the parent
365d5c88b73SJan Schmidt  * block might help in merging entries to gain some speed.
366d5c88b73SJan Schmidt  */
36700142756SJeff Mahoney static int add_prelim_ref(const struct btrfs_fs_info *fs_info,
36800142756SJeff Mahoney 			  struct preftree *preftree, u64 root_id,
369e0c476b1SJeff Mahoney 			  const struct btrfs_key *key, int level, u64 parent,
3703ec4d323SEdmund Nadolski 			  u64 wanted_disk_byte, int count,
3713ec4d323SEdmund Nadolski 			  struct share_check *sc, gfp_t gfp_mask)
3728da6d581SJan Schmidt {
373e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
3748da6d581SJan Schmidt 
37548ec4736SLiu Bo 	if (root_id == BTRFS_DATA_RELOC_TREE_OBJECTID)
37648ec4736SLiu Bo 		return 0;
37748ec4736SLiu Bo 
378b9e9a6cbSWang Shilong 	ref = kmem_cache_alloc(btrfs_prelim_ref_cache, gfp_mask);
3798da6d581SJan Schmidt 	if (!ref)
3808da6d581SJan Schmidt 		return -ENOMEM;
3818da6d581SJan Schmidt 
3828da6d581SJan Schmidt 	ref->root_id = root_id;
3837ac8b88eSethanwu 	if (key)
384d5c88b73SJan Schmidt 		ref->key_for_search = *key;
3857ac8b88eSethanwu 	else
386d5c88b73SJan Schmidt 		memset(&ref->key_for_search, 0, sizeof(ref->key_for_search));
3878da6d581SJan Schmidt 
3883301958bSJan Schmidt 	ref->inode_list = NULL;
3898da6d581SJan Schmidt 	ref->level = level;
3908da6d581SJan Schmidt 	ref->count = count;
3918da6d581SJan Schmidt 	ref->parent = parent;
3928da6d581SJan Schmidt 	ref->wanted_disk_byte = wanted_disk_byte;
3933ec4d323SEdmund Nadolski 	prelim_ref_insert(fs_info, preftree, ref, sc);
3943ec4d323SEdmund Nadolski 	return extent_is_shared(sc);
3958da6d581SJan Schmidt }
3968da6d581SJan Schmidt 
39786d5f994SEdmund Nadolski /* direct refs use root == 0, key == NULL */
39800142756SJeff Mahoney static int add_direct_ref(const struct btrfs_fs_info *fs_info,
39900142756SJeff Mahoney 			  struct preftrees *preftrees, int level, u64 parent,
4003ec4d323SEdmund Nadolski 			  u64 wanted_disk_byte, int count,
4013ec4d323SEdmund Nadolski 			  struct share_check *sc, gfp_t gfp_mask)
40286d5f994SEdmund Nadolski {
40300142756SJeff Mahoney 	return add_prelim_ref(fs_info, &preftrees->direct, 0, NULL, level,
4043ec4d323SEdmund Nadolski 			      parent, wanted_disk_byte, count, sc, gfp_mask);
40586d5f994SEdmund Nadolski }
40686d5f994SEdmund Nadolski 
40786d5f994SEdmund Nadolski /* indirect refs use parent == 0 */
40800142756SJeff Mahoney static int add_indirect_ref(const struct btrfs_fs_info *fs_info,
40900142756SJeff Mahoney 			    struct preftrees *preftrees, u64 root_id,
41086d5f994SEdmund Nadolski 			    const struct btrfs_key *key, int level,
4113ec4d323SEdmund Nadolski 			    u64 wanted_disk_byte, int count,
4123ec4d323SEdmund Nadolski 			    struct share_check *sc, gfp_t gfp_mask)
41386d5f994SEdmund Nadolski {
41486d5f994SEdmund Nadolski 	struct preftree *tree = &preftrees->indirect;
41586d5f994SEdmund Nadolski 
41686d5f994SEdmund Nadolski 	if (!key)
41786d5f994SEdmund Nadolski 		tree = &preftrees->indirect_missing_keys;
41800142756SJeff Mahoney 	return add_prelim_ref(fs_info, tree, root_id, key, level, 0,
4193ec4d323SEdmund Nadolski 			      wanted_disk_byte, count, sc, gfp_mask);
42086d5f994SEdmund Nadolski }
42186d5f994SEdmund Nadolski 
422ed58f2e6Sethanwu static int is_shared_data_backref(struct preftrees *preftrees, u64 bytenr)
423ed58f2e6Sethanwu {
424ed58f2e6Sethanwu 	struct rb_node **p = &preftrees->direct.root.rb_root.rb_node;
425ed58f2e6Sethanwu 	struct rb_node *parent = NULL;
426ed58f2e6Sethanwu 	struct prelim_ref *ref = NULL;
4279c6c723fSArnd Bergmann 	struct prelim_ref target = {};
428ed58f2e6Sethanwu 	int result;
429ed58f2e6Sethanwu 
430ed58f2e6Sethanwu 	target.parent = bytenr;
431ed58f2e6Sethanwu 
432ed58f2e6Sethanwu 	while (*p) {
433ed58f2e6Sethanwu 		parent = *p;
434ed58f2e6Sethanwu 		ref = rb_entry(parent, struct prelim_ref, rbnode);
435ed58f2e6Sethanwu 		result = prelim_ref_compare(ref, &target);
436ed58f2e6Sethanwu 
437ed58f2e6Sethanwu 		if (result < 0)
438ed58f2e6Sethanwu 			p = &(*p)->rb_left;
439ed58f2e6Sethanwu 		else if (result > 0)
440ed58f2e6Sethanwu 			p = &(*p)->rb_right;
441ed58f2e6Sethanwu 		else
442ed58f2e6Sethanwu 			return 1;
443ed58f2e6Sethanwu 	}
444ed58f2e6Sethanwu 	return 0;
445ed58f2e6Sethanwu }
446ed58f2e6Sethanwu 
447a2c8d27eSFilipe Manana static int add_all_parents(struct btrfs_backref_walk_ctx *ctx,
448a2c8d27eSFilipe Manana 			   struct btrfs_root *root, struct btrfs_path *path,
449ed58f2e6Sethanwu 			   struct ulist *parents,
450ed58f2e6Sethanwu 			   struct preftrees *preftrees, struct prelim_ref *ref,
451a2c8d27eSFilipe Manana 			   int level)
4528da6d581SJan Schmidt {
45369bca40dSAlexander Block 	int ret = 0;
45469bca40dSAlexander Block 	int slot;
45569bca40dSAlexander Block 	struct extent_buffer *eb;
45669bca40dSAlexander Block 	struct btrfs_key key;
4577ef81ac8SJosef Bacik 	struct btrfs_key *key_for_search = &ref->key_for_search;
4588da6d581SJan Schmidt 	struct btrfs_file_extent_item *fi;
459ed8c4913SJosef Bacik 	struct extent_inode_elem *eie = NULL, *old = NULL;
4608da6d581SJan Schmidt 	u64 disk_byte;
4617ef81ac8SJosef Bacik 	u64 wanted_disk_byte = ref->wanted_disk_byte;
4627ef81ac8SJosef Bacik 	u64 count = 0;
4637ac8b88eSethanwu 	u64 data_offset;
4648da6d581SJan Schmidt 
46569bca40dSAlexander Block 	if (level != 0) {
46669bca40dSAlexander Block 		eb = path->nodes[level];
46769bca40dSAlexander Block 		ret = ulist_add(parents, eb->start, 0, GFP_NOFS);
4683301958bSJan Schmidt 		if (ret < 0)
4693301958bSJan Schmidt 			return ret;
4708da6d581SJan Schmidt 		return 0;
47169bca40dSAlexander Block 	}
4728da6d581SJan Schmidt 
4738da6d581SJan Schmidt 	/*
474ed58f2e6Sethanwu 	 * 1. We normally enter this function with the path already pointing to
47569bca40dSAlexander Block 	 *    the first item to check. But sometimes, we may enter it with
476ed58f2e6Sethanwu 	 *    slot == nritems.
477ed58f2e6Sethanwu 	 * 2. We are searching for normal backref but bytenr of this leaf
478ed58f2e6Sethanwu 	 *    matches shared data backref
479cfc0eed0Sethanwu 	 * 3. The leaf owner is not equal to the root we are searching
480cfc0eed0Sethanwu 	 *
481ed58f2e6Sethanwu 	 * For these cases, go to the next leaf before we continue.
4828da6d581SJan Schmidt 	 */
483ed58f2e6Sethanwu 	eb = path->nodes[0];
484ed58f2e6Sethanwu 	if (path->slots[0] >= btrfs_header_nritems(eb) ||
485cfc0eed0Sethanwu 	    is_shared_data_backref(preftrees, eb->start) ||
486cfc0eed0Sethanwu 	    ref->root_id != btrfs_header_owner(eb)) {
487a2c8d27eSFilipe Manana 		if (ctx->time_seq == BTRFS_SEQ_LAST)
48821633fc6SQu Wenruo 			ret = btrfs_next_leaf(root, path);
48921633fc6SQu Wenruo 		else
490a2c8d27eSFilipe Manana 			ret = btrfs_next_old_leaf(root, path, ctx->time_seq);
49121633fc6SQu Wenruo 	}
4928da6d581SJan Schmidt 
493b25b0b87Sethanwu 	while (!ret && count < ref->count) {
4948da6d581SJan Schmidt 		eb = path->nodes[0];
49569bca40dSAlexander Block 		slot = path->slots[0];
49669bca40dSAlexander Block 
49769bca40dSAlexander Block 		btrfs_item_key_to_cpu(eb, &key, slot);
49869bca40dSAlexander Block 
49969bca40dSAlexander Block 		if (key.objectid != key_for_search->objectid ||
50069bca40dSAlexander Block 		    key.type != BTRFS_EXTENT_DATA_KEY)
50169bca40dSAlexander Block 			break;
50269bca40dSAlexander Block 
503ed58f2e6Sethanwu 		/*
504ed58f2e6Sethanwu 		 * We are searching for normal backref but bytenr of this leaf
505cfc0eed0Sethanwu 		 * matches shared data backref, OR
506cfc0eed0Sethanwu 		 * the leaf owner is not equal to the root we are searching for
507ed58f2e6Sethanwu 		 */
508cfc0eed0Sethanwu 		if (slot == 0 &&
509cfc0eed0Sethanwu 		    (is_shared_data_backref(preftrees, eb->start) ||
510cfc0eed0Sethanwu 		     ref->root_id != btrfs_header_owner(eb))) {
511a2c8d27eSFilipe Manana 			if (ctx->time_seq == BTRFS_SEQ_LAST)
512ed58f2e6Sethanwu 				ret = btrfs_next_leaf(root, path);
513ed58f2e6Sethanwu 			else
514a2c8d27eSFilipe Manana 				ret = btrfs_next_old_leaf(root, path, ctx->time_seq);
515ed58f2e6Sethanwu 			continue;
516ed58f2e6Sethanwu 		}
51769bca40dSAlexander Block 		fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5188da6d581SJan Schmidt 		disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
5197ac8b88eSethanwu 		data_offset = btrfs_file_extent_offset(eb, fi);
52069bca40dSAlexander Block 
52169bca40dSAlexander Block 		if (disk_byte == wanted_disk_byte) {
52269bca40dSAlexander Block 			eie = NULL;
523ed8c4913SJosef Bacik 			old = NULL;
5247ac8b88eSethanwu 			if (ref->key_for_search.offset == key.offset - data_offset)
5257ef81ac8SJosef Bacik 				count++;
5267ac8b88eSethanwu 			else
5277ac8b88eSethanwu 				goto next;
528a2c8d27eSFilipe Manana 			if (!ctx->ignore_extent_item_pos) {
52969bca40dSAlexander Block 				ret = check_extent_in_eb(&key, eb, fi,
530a2c8d27eSFilipe Manana 							 ctx->extent_item_pos, &eie);
53169bca40dSAlexander Block 				if (ret < 0)
53269bca40dSAlexander Block 					break;
5338da6d581SJan Schmidt 			}
534ed8c4913SJosef Bacik 			if (ret > 0)
535ed8c4913SJosef Bacik 				goto next;
5364eb1f66dSTakashi Iwai 			ret = ulist_add_merge_ptr(parents, eb->start,
5374eb1f66dSTakashi Iwai 						  eie, (void **)&old, GFP_NOFS);
53869bca40dSAlexander Block 			if (ret < 0)
53969bca40dSAlexander Block 				break;
540a2c8d27eSFilipe Manana 			if (!ret && !ctx->ignore_extent_item_pos) {
541ed8c4913SJosef Bacik 				while (old->next)
542ed8c4913SJosef Bacik 					old = old->next;
543ed8c4913SJosef Bacik 				old->next = eie;
54469bca40dSAlexander Block 			}
545f05c4746SWang Shilong 			eie = NULL;
54669bca40dSAlexander Block 		}
547ed8c4913SJosef Bacik next:
548a2c8d27eSFilipe Manana 		if (ctx->time_seq == BTRFS_SEQ_LAST)
54921633fc6SQu Wenruo 			ret = btrfs_next_item(root, path);
55021633fc6SQu Wenruo 		else
551a2c8d27eSFilipe Manana 			ret = btrfs_next_old_item(root, path, ctx->time_seq);
5528da6d581SJan Schmidt 	}
5538da6d581SJan Schmidt 
55469bca40dSAlexander Block 	if (ret > 0)
55569bca40dSAlexander Block 		ret = 0;
556f05c4746SWang Shilong 	else if (ret < 0)
557f05c4746SWang Shilong 		free_inode_elem_list(eie);
55869bca40dSAlexander Block 	return ret;
5598da6d581SJan Schmidt }
5608da6d581SJan Schmidt 
5618da6d581SJan Schmidt /*
5628da6d581SJan Schmidt  * resolve an indirect backref in the form (root_id, key, level)
5638da6d581SJan Schmidt  * to a logical address
5648da6d581SJan Schmidt  */
565a2c8d27eSFilipe Manana static int resolve_indirect_ref(struct btrfs_backref_walk_ctx *ctx,
566a2c8d27eSFilipe Manana 				struct btrfs_path *path,
567ed58f2e6Sethanwu 				struct preftrees *preftrees,
568a2c8d27eSFilipe Manana 				struct prelim_ref *ref, struct ulist *parents)
5698da6d581SJan Schmidt {
5708da6d581SJan Schmidt 	struct btrfs_root *root;
5718da6d581SJan Schmidt 	struct extent_buffer *eb;
5728da6d581SJan Schmidt 	int ret = 0;
5738da6d581SJan Schmidt 	int root_level;
5748da6d581SJan Schmidt 	int level = ref->level;
5757ac8b88eSethanwu 	struct btrfs_key search_key = ref->key_for_search;
5768da6d581SJan Schmidt 
57749d11beaSJosef Bacik 	/*
57849d11beaSJosef Bacik 	 * If we're search_commit_root we could possibly be holding locks on
57949d11beaSJosef Bacik 	 * other tree nodes.  This happens when qgroups does backref walks when
58049d11beaSJosef Bacik 	 * adding new delayed refs.  To deal with this we need to look in cache
58149d11beaSJosef Bacik 	 * for the root, and if we don't find it then we need to search the
58249d11beaSJosef Bacik 	 * tree_root's commit root, thus the btrfs_get_fs_root_commit_root usage
58349d11beaSJosef Bacik 	 * here.
58449d11beaSJosef Bacik 	 */
58549d11beaSJosef Bacik 	if (path->search_commit_root)
586a2c8d27eSFilipe Manana 		root = btrfs_get_fs_root_commit_root(ctx->fs_info, path, ref->root_id);
58749d11beaSJosef Bacik 	else
588a2c8d27eSFilipe Manana 		root = btrfs_get_fs_root(ctx->fs_info, ref->root_id, false);
5898da6d581SJan Schmidt 	if (IS_ERR(root)) {
5908da6d581SJan Schmidt 		ret = PTR_ERR(root);
5919326f76fSJosef Bacik 		goto out_free;
5929326f76fSJosef Bacik 	}
5939326f76fSJosef Bacik 
59439dba873SJosef Bacik 	if (!path->search_commit_root &&
59539dba873SJosef Bacik 	    test_bit(BTRFS_ROOT_DELETING, &root->state)) {
59639dba873SJosef Bacik 		ret = -ENOENT;
59739dba873SJosef Bacik 		goto out;
59839dba873SJosef Bacik 	}
59939dba873SJosef Bacik 
600a2c8d27eSFilipe Manana 	if (btrfs_is_testing(ctx->fs_info)) {
601d9ee522bSJosef Bacik 		ret = -ENOENT;
602d9ee522bSJosef Bacik 		goto out;
603d9ee522bSJosef Bacik 	}
604d9ee522bSJosef Bacik 
6059e351cc8SJosef Bacik 	if (path->search_commit_root)
6069e351cc8SJosef Bacik 		root_level = btrfs_header_level(root->commit_root);
607a2c8d27eSFilipe Manana 	else if (ctx->time_seq == BTRFS_SEQ_LAST)
60821633fc6SQu Wenruo 		root_level = btrfs_header_level(root->node);
6099e351cc8SJosef Bacik 	else
610a2c8d27eSFilipe Manana 		root_level = btrfs_old_root_level(root, ctx->time_seq);
6118da6d581SJan Schmidt 
612c75e8394SJosef Bacik 	if (root_level + 1 == level)
6138da6d581SJan Schmidt 		goto out;
6148da6d581SJan Schmidt 
6157ac8b88eSethanwu 	/*
6167ac8b88eSethanwu 	 * We can often find data backrefs with an offset that is too large
6177ac8b88eSethanwu 	 * (>= LLONG_MAX, maximum allowed file offset) due to underflows when
6187ac8b88eSethanwu 	 * subtracting a file's offset with the data offset of its
6197ac8b88eSethanwu 	 * corresponding extent data item. This can happen for example in the
6207ac8b88eSethanwu 	 * clone ioctl.
6217ac8b88eSethanwu 	 *
6227ac8b88eSethanwu 	 * So if we detect such case we set the search key's offset to zero to
6237ac8b88eSethanwu 	 * make sure we will find the matching file extent item at
6247ac8b88eSethanwu 	 * add_all_parents(), otherwise we will miss it because the offset
6257ac8b88eSethanwu 	 * taken form the backref is much larger then the offset of the file
6267ac8b88eSethanwu 	 * extent item. This can make us scan a very large number of file
6277ac8b88eSethanwu 	 * extent items, but at least it will not make us miss any.
6287ac8b88eSethanwu 	 *
6297ac8b88eSethanwu 	 * This is an ugly workaround for a behaviour that should have never
6307ac8b88eSethanwu 	 * existed, but it does and a fix for the clone ioctl would touch a lot
6317ac8b88eSethanwu 	 * of places, cause backwards incompatibility and would not fix the
6327ac8b88eSethanwu 	 * problem for extents cloned with older kernels.
6337ac8b88eSethanwu 	 */
6347ac8b88eSethanwu 	if (search_key.type == BTRFS_EXTENT_DATA_KEY &&
6357ac8b88eSethanwu 	    search_key.offset >= LLONG_MAX)
6367ac8b88eSethanwu 		search_key.offset = 0;
6378da6d581SJan Schmidt 	path->lowest_level = level;
638a2c8d27eSFilipe Manana 	if (ctx->time_seq == BTRFS_SEQ_LAST)
6397ac8b88eSethanwu 		ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
64021633fc6SQu Wenruo 	else
641a2c8d27eSFilipe Manana 		ret = btrfs_search_old_slot(root, &search_key, path, ctx->time_seq);
642538f72cdSWang Shilong 
643a2c8d27eSFilipe Manana 	btrfs_debug(ctx->fs_info,
644ab8d0fc4SJeff Mahoney 		"search slot in root %llu (level %d, ref count %d) returned %d for key (%llu %u %llu)",
645c1c9ff7cSGeert Uytterhoeven 		 ref->root_id, level, ref->count, ret,
646c1c9ff7cSGeert Uytterhoeven 		 ref->key_for_search.objectid, ref->key_for_search.type,
647c1c9ff7cSGeert Uytterhoeven 		 ref->key_for_search.offset);
6488da6d581SJan Schmidt 	if (ret < 0)
6498da6d581SJan Schmidt 		goto out;
6508da6d581SJan Schmidt 
6518da6d581SJan Schmidt 	eb = path->nodes[level];
6529345457fSJan Schmidt 	while (!eb) {
653fae7f21cSDulshani Gunawardhana 		if (WARN_ON(!level)) {
6548da6d581SJan Schmidt 			ret = 1;
6558da6d581SJan Schmidt 			goto out;
6568da6d581SJan Schmidt 		}
6579345457fSJan Schmidt 		level--;
6589345457fSJan Schmidt 		eb = path->nodes[level];
6599345457fSJan Schmidt 	}
6608da6d581SJan Schmidt 
661a2c8d27eSFilipe Manana 	ret = add_all_parents(ctx, root, path, parents, preftrees, ref, level);
6628da6d581SJan Schmidt out:
66300246528SJosef Bacik 	btrfs_put_root(root);
6649326f76fSJosef Bacik out_free:
665da61d31aSJosef Bacik 	path->lowest_level = 0;
666da61d31aSJosef Bacik 	btrfs_release_path(path);
6678da6d581SJan Schmidt 	return ret;
6688da6d581SJan Schmidt }
6698da6d581SJan Schmidt 
6704dae077aSJeff Mahoney static struct extent_inode_elem *
6714dae077aSJeff Mahoney unode_aux_to_inode_list(struct ulist_node *node)
6724dae077aSJeff Mahoney {
6734dae077aSJeff Mahoney 	if (!node)
6744dae077aSJeff Mahoney 		return NULL;
6754dae077aSJeff Mahoney 	return (struct extent_inode_elem *)(uintptr_t)node->aux;
6764dae077aSJeff Mahoney }
6774dae077aSJeff Mahoney 
6785614dc3aSFilipe Manana static void free_leaf_list(struct ulist *ulist)
6795614dc3aSFilipe Manana {
6805614dc3aSFilipe Manana 	struct ulist_node *node;
6815614dc3aSFilipe Manana 	struct ulist_iterator uiter;
6825614dc3aSFilipe Manana 
6835614dc3aSFilipe Manana 	ULIST_ITER_INIT(&uiter);
6845614dc3aSFilipe Manana 	while ((node = ulist_next(ulist, &uiter)))
6855614dc3aSFilipe Manana 		free_inode_elem_list(unode_aux_to_inode_list(node));
6865614dc3aSFilipe Manana 
6875614dc3aSFilipe Manana 	ulist_free(ulist);
6885614dc3aSFilipe Manana }
6895614dc3aSFilipe Manana 
6908da6d581SJan Schmidt /*
69152042d8eSAndrea Gelmini  * We maintain three separate rbtrees: one for direct refs, one for
69286d5f994SEdmund Nadolski  * indirect refs which have a key, and one for indirect refs which do not
69386d5f994SEdmund Nadolski  * have a key. Each tree does merge on insertion.
69486d5f994SEdmund Nadolski  *
69586d5f994SEdmund Nadolski  * Once all of the references are located, we iterate over the tree of
69686d5f994SEdmund Nadolski  * indirect refs with missing keys. An appropriate key is located and
69786d5f994SEdmund Nadolski  * the ref is moved onto the tree for indirect refs. After all missing
69886d5f994SEdmund Nadolski  * keys are thus located, we iterate over the indirect ref tree, resolve
69986d5f994SEdmund Nadolski  * each reference, and then insert the resolved reference onto the
70086d5f994SEdmund Nadolski  * direct tree (merging there too).
70186d5f994SEdmund Nadolski  *
70286d5f994SEdmund Nadolski  * New backrefs (i.e., for parent nodes) are added to the appropriate
70386d5f994SEdmund Nadolski  * rbtree as they are encountered. The new backrefs are subsequently
70486d5f994SEdmund Nadolski  * resolved as above.
7058da6d581SJan Schmidt  */
706a2c8d27eSFilipe Manana static int resolve_indirect_refs(struct btrfs_backref_walk_ctx *ctx,
707a2c8d27eSFilipe Manana 				 struct btrfs_path *path,
70886d5f994SEdmund Nadolski 				 struct preftrees *preftrees,
7096ce6ba53SFilipe Manana 				 struct share_check *sc)
7108da6d581SJan Schmidt {
7118da6d581SJan Schmidt 	int err;
7128da6d581SJan Schmidt 	int ret = 0;
7138da6d581SJan Schmidt 	struct ulist *parents;
7148da6d581SJan Schmidt 	struct ulist_node *node;
715cd1b413cSJan Schmidt 	struct ulist_iterator uiter;
71686d5f994SEdmund Nadolski 	struct rb_node *rnode;
7178da6d581SJan Schmidt 
7188da6d581SJan Schmidt 	parents = ulist_alloc(GFP_NOFS);
7198da6d581SJan Schmidt 	if (!parents)
7208da6d581SJan Schmidt 		return -ENOMEM;
7218da6d581SJan Schmidt 
7228da6d581SJan Schmidt 	/*
72386d5f994SEdmund Nadolski 	 * We could trade memory usage for performance here by iterating
72486d5f994SEdmund Nadolski 	 * the tree, allocating new refs for each insertion, and then
72586d5f994SEdmund Nadolski 	 * freeing the entire indirect tree when we're done.  In some test
72686d5f994SEdmund Nadolski 	 * cases, the tree can grow quite large (~200k objects).
7278da6d581SJan Schmidt 	 */
728ecf160b4SLiu Bo 	while ((rnode = rb_first_cached(&preftrees->indirect.root))) {
72986d5f994SEdmund Nadolski 		struct prelim_ref *ref;
73086d5f994SEdmund Nadolski 
73186d5f994SEdmund Nadolski 		ref = rb_entry(rnode, struct prelim_ref, rbnode);
73286d5f994SEdmund Nadolski 		if (WARN(ref->parent,
73386d5f994SEdmund Nadolski 			 "BUG: direct ref found in indirect tree")) {
73486d5f994SEdmund Nadolski 			ret = -EINVAL;
73586d5f994SEdmund Nadolski 			goto out;
73686d5f994SEdmund Nadolski 		}
73786d5f994SEdmund Nadolski 
738ecf160b4SLiu Bo 		rb_erase_cached(&ref->rbnode, &preftrees->indirect.root);
7396c336b21SJeff Mahoney 		preftrees->indirect.count--;
74086d5f994SEdmund Nadolski 
74186d5f994SEdmund Nadolski 		if (ref->count == 0) {
74286d5f994SEdmund Nadolski 			free_pref(ref);
7438da6d581SJan Schmidt 			continue;
74486d5f994SEdmund Nadolski 		}
74586d5f994SEdmund Nadolski 
746877c1476SFilipe Manana 		if (sc && ref->root_id != sc->root->root_key.objectid) {
74786d5f994SEdmund Nadolski 			free_pref(ref);
748dc046b10SJosef Bacik 			ret = BACKREF_FOUND_SHARED;
749dc046b10SJosef Bacik 			goto out;
750dc046b10SJosef Bacik 		}
751a2c8d27eSFilipe Manana 		err = resolve_indirect_ref(ctx, path, preftrees, ref, parents);
75295def2edSWang Shilong 		/*
75395def2edSWang Shilong 		 * we can only tolerate ENOENT,otherwise,we should catch error
75495def2edSWang Shilong 		 * and return directly.
75595def2edSWang Shilong 		 */
75695def2edSWang Shilong 		if (err == -ENOENT) {
757a2c8d27eSFilipe Manana 			prelim_ref_insert(ctx->fs_info, &preftrees->direct, ref,
7583ec4d323SEdmund Nadolski 					  NULL);
7598da6d581SJan Schmidt 			continue;
76095def2edSWang Shilong 		} else if (err) {
76186d5f994SEdmund Nadolski 			free_pref(ref);
76295def2edSWang Shilong 			ret = err;
76395def2edSWang Shilong 			goto out;
76495def2edSWang Shilong 		}
7658da6d581SJan Schmidt 
7668da6d581SJan Schmidt 		/* we put the first parent into the ref at hand */
767cd1b413cSJan Schmidt 		ULIST_ITER_INIT(&uiter);
768cd1b413cSJan Schmidt 		node = ulist_next(parents, &uiter);
7698da6d581SJan Schmidt 		ref->parent = node ? node->val : 0;
7704dae077aSJeff Mahoney 		ref->inode_list = unode_aux_to_inode_list(node);
7718da6d581SJan Schmidt 
77286d5f994SEdmund Nadolski 		/* Add a prelim_ref(s) for any other parent(s). */
773cd1b413cSJan Schmidt 		while ((node = ulist_next(parents, &uiter))) {
77486d5f994SEdmund Nadolski 			struct prelim_ref *new_ref;
77586d5f994SEdmund Nadolski 
776b9e9a6cbSWang Shilong 			new_ref = kmem_cache_alloc(btrfs_prelim_ref_cache,
777b9e9a6cbSWang Shilong 						   GFP_NOFS);
7788da6d581SJan Schmidt 			if (!new_ref) {
77986d5f994SEdmund Nadolski 				free_pref(ref);
7808da6d581SJan Schmidt 				ret = -ENOMEM;
781e36902d4SWang Shilong 				goto out;
7828da6d581SJan Schmidt 			}
7838da6d581SJan Schmidt 			memcpy(new_ref, ref, sizeof(*ref));
7848da6d581SJan Schmidt 			new_ref->parent = node->val;
7854dae077aSJeff Mahoney 			new_ref->inode_list = unode_aux_to_inode_list(node);
786a2c8d27eSFilipe Manana 			prelim_ref_insert(ctx->fs_info, &preftrees->direct,
7873ec4d323SEdmund Nadolski 					  new_ref, NULL);
7888da6d581SJan Schmidt 		}
78986d5f994SEdmund Nadolski 
7903ec4d323SEdmund Nadolski 		/*
79152042d8eSAndrea Gelmini 		 * Now it's a direct ref, put it in the direct tree. We must
7923ec4d323SEdmund Nadolski 		 * do this last because the ref could be merged/freed here.
7933ec4d323SEdmund Nadolski 		 */
794a2c8d27eSFilipe Manana 		prelim_ref_insert(ctx->fs_info, &preftrees->direct, ref, NULL);
79586d5f994SEdmund Nadolski 
7968da6d581SJan Schmidt 		ulist_reinit(parents);
7979dd14fd6SEdmund Nadolski 		cond_resched();
7988da6d581SJan Schmidt 	}
799e36902d4SWang Shilong out:
8005614dc3aSFilipe Manana 	/*
8015614dc3aSFilipe Manana 	 * We may have inode lists attached to refs in the parents ulist, so we
8025614dc3aSFilipe Manana 	 * must free them before freeing the ulist and its refs.
8035614dc3aSFilipe Manana 	 */
8045614dc3aSFilipe Manana 	free_leaf_list(parents);
8058da6d581SJan Schmidt 	return ret;
8068da6d581SJan Schmidt }
8078da6d581SJan Schmidt 
808d5c88b73SJan Schmidt /*
809d5c88b73SJan Schmidt  * read tree blocks and add keys where required.
810d5c88b73SJan Schmidt  */
811e0c476b1SJeff Mahoney static int add_missing_keys(struct btrfs_fs_info *fs_info,
81238e3eebfSJosef Bacik 			    struct preftrees *preftrees, bool lock)
813d5c88b73SJan Schmidt {
814e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
815d5c88b73SJan Schmidt 	struct extent_buffer *eb;
81686d5f994SEdmund Nadolski 	struct preftree *tree = &preftrees->indirect_missing_keys;
81786d5f994SEdmund Nadolski 	struct rb_node *node;
818d5c88b73SJan Schmidt 
819ecf160b4SLiu Bo 	while ((node = rb_first_cached(&tree->root))) {
82086d5f994SEdmund Nadolski 		ref = rb_entry(node, struct prelim_ref, rbnode);
821ecf160b4SLiu Bo 		rb_erase_cached(node, &tree->root);
82286d5f994SEdmund Nadolski 
82386d5f994SEdmund Nadolski 		BUG_ON(ref->parent);	/* should not be a direct ref */
82486d5f994SEdmund Nadolski 		BUG_ON(ref->key_for_search.type);
825d5c88b73SJan Schmidt 		BUG_ON(!ref->wanted_disk_byte);
82686d5f994SEdmund Nadolski 
8271b7ec85eSJosef Bacik 		eb = read_tree_block(fs_info, ref->wanted_disk_byte,
8281b7ec85eSJosef Bacik 				     ref->root_id, 0, ref->level - 1, NULL);
82964c043deSLiu Bo 		if (IS_ERR(eb)) {
83086d5f994SEdmund Nadolski 			free_pref(ref);
83164c043deSLiu Bo 			return PTR_ERR(eb);
8324eb150d6SQu Wenruo 		}
8334eb150d6SQu Wenruo 		if (!extent_buffer_uptodate(eb)) {
83486d5f994SEdmund Nadolski 			free_pref(ref);
835416bc658SJosef Bacik 			free_extent_buffer(eb);
836416bc658SJosef Bacik 			return -EIO;
837416bc658SJosef Bacik 		}
8384eb150d6SQu Wenruo 
83938e3eebfSJosef Bacik 		if (lock)
840d5c88b73SJan Schmidt 			btrfs_tree_read_lock(eb);
841d5c88b73SJan Schmidt 		if (btrfs_header_level(eb) == 0)
842d5c88b73SJan Schmidt 			btrfs_item_key_to_cpu(eb, &ref->key_for_search, 0);
843d5c88b73SJan Schmidt 		else
844d5c88b73SJan Schmidt 			btrfs_node_key_to_cpu(eb, &ref->key_for_search, 0);
84538e3eebfSJosef Bacik 		if (lock)
846d5c88b73SJan Schmidt 			btrfs_tree_read_unlock(eb);
847d5c88b73SJan Schmidt 		free_extent_buffer(eb);
8483ec4d323SEdmund Nadolski 		prelim_ref_insert(fs_info, &preftrees->indirect, ref, NULL);
8499dd14fd6SEdmund Nadolski 		cond_resched();
850d5c88b73SJan Schmidt 	}
851d5c88b73SJan Schmidt 	return 0;
852d5c88b73SJan Schmidt }
853d5c88b73SJan Schmidt 
8548da6d581SJan Schmidt /*
8558da6d581SJan Schmidt  * add all currently queued delayed refs from this head whose seq nr is
8568da6d581SJan Schmidt  * smaller or equal that seq to the list
8578da6d581SJan Schmidt  */
85800142756SJeff Mahoney static int add_delayed_refs(const struct btrfs_fs_info *fs_info,
85900142756SJeff Mahoney 			    struct btrfs_delayed_ref_head *head, u64 seq,
860b25b0b87Sethanwu 			    struct preftrees *preftrees, struct share_check *sc)
8618da6d581SJan Schmidt {
862c6fc2454SQu Wenruo 	struct btrfs_delayed_ref_node *node;
863d5c88b73SJan Schmidt 	struct btrfs_key key;
8640e0adbcfSJosef Bacik 	struct rb_node *n;
86501747e92SEdmund Nadolski 	int count;
866b1375d64SJan Schmidt 	int ret = 0;
8678da6d581SJan Schmidt 
868d7df2c79SJosef Bacik 	spin_lock(&head->lock);
869e3d03965SLiu Bo 	for (n = rb_first_cached(&head->ref_tree); n; n = rb_next(n)) {
8700e0adbcfSJosef Bacik 		node = rb_entry(n, struct btrfs_delayed_ref_node,
8710e0adbcfSJosef Bacik 				ref_node);
8728da6d581SJan Schmidt 		if (node->seq > seq)
8738da6d581SJan Schmidt 			continue;
8748da6d581SJan Schmidt 
8758da6d581SJan Schmidt 		switch (node->action) {
8768da6d581SJan Schmidt 		case BTRFS_ADD_DELAYED_EXTENT:
8778da6d581SJan Schmidt 		case BTRFS_UPDATE_DELAYED_HEAD:
8788da6d581SJan Schmidt 			WARN_ON(1);
8798da6d581SJan Schmidt 			continue;
8808da6d581SJan Schmidt 		case BTRFS_ADD_DELAYED_REF:
88101747e92SEdmund Nadolski 			count = node->ref_mod;
8828da6d581SJan Schmidt 			break;
8838da6d581SJan Schmidt 		case BTRFS_DROP_DELAYED_REF:
88401747e92SEdmund Nadolski 			count = node->ref_mod * -1;
8858da6d581SJan Schmidt 			break;
8868da6d581SJan Schmidt 		default:
887290342f6SArnd Bergmann 			BUG();
8888da6d581SJan Schmidt 		}
8898da6d581SJan Schmidt 		switch (node->type) {
8908da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY: {
89186d5f994SEdmund Nadolski 			/* NORMAL INDIRECT METADATA backref */
8928da6d581SJan Schmidt 			struct btrfs_delayed_tree_ref *ref;
893943553efSFilipe Manana 			struct btrfs_key *key_ptr = NULL;
894943553efSFilipe Manana 
895943553efSFilipe Manana 			if (head->extent_op && head->extent_op->update_key) {
896943553efSFilipe Manana 				btrfs_disk_key_to_cpu(&key, &head->extent_op->key);
897943553efSFilipe Manana 				key_ptr = &key;
898943553efSFilipe Manana 			}
8998da6d581SJan Schmidt 
9008da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_tree_ref(node);
90100142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, ref->root,
902943553efSFilipe Manana 					       key_ptr, ref->level + 1,
90301747e92SEdmund Nadolski 					       node->bytenr, count, sc,
90401747e92SEdmund Nadolski 					       GFP_ATOMIC);
9058da6d581SJan Schmidt 			break;
9068da6d581SJan Schmidt 		}
9078da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY: {
90886d5f994SEdmund Nadolski 			/* SHARED DIRECT METADATA backref */
9098da6d581SJan Schmidt 			struct btrfs_delayed_tree_ref *ref;
9108da6d581SJan Schmidt 
9118da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_tree_ref(node);
91286d5f994SEdmund Nadolski 
91301747e92SEdmund Nadolski 			ret = add_direct_ref(fs_info, preftrees, ref->level + 1,
91401747e92SEdmund Nadolski 					     ref->parent, node->bytenr, count,
9153ec4d323SEdmund Nadolski 					     sc, GFP_ATOMIC);
9168da6d581SJan Schmidt 			break;
9178da6d581SJan Schmidt 		}
9188da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
91986d5f994SEdmund Nadolski 			/* NORMAL INDIRECT DATA backref */
9208da6d581SJan Schmidt 			struct btrfs_delayed_data_ref *ref;
9218da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_data_ref(node);
9228da6d581SJan Schmidt 
9238da6d581SJan Schmidt 			key.objectid = ref->objectid;
9248da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
9258da6d581SJan Schmidt 			key.offset = ref->offset;
926dc046b10SJosef Bacik 
927dc046b10SJosef Bacik 			/*
9284fc7b572SFilipe Manana 			 * If we have a share check context and a reference for
9294fc7b572SFilipe Manana 			 * another inode, we can't exit immediately. This is
9304fc7b572SFilipe Manana 			 * because even if this is a BTRFS_ADD_DELAYED_REF
9314fc7b572SFilipe Manana 			 * reference we may find next a BTRFS_DROP_DELAYED_REF
9324fc7b572SFilipe Manana 			 * which cancels out this ADD reference.
9334fc7b572SFilipe Manana 			 *
9344fc7b572SFilipe Manana 			 * If this is a DROP reference and there was no previous
9354fc7b572SFilipe Manana 			 * ADD reference, then we need to signal that when we
9364fc7b572SFilipe Manana 			 * process references from the extent tree (through
9374fc7b572SFilipe Manana 			 * add_inline_refs() and add_keyed_refs()), we should
9384fc7b572SFilipe Manana 			 * not exit early if we find a reference for another
9394fc7b572SFilipe Manana 			 * inode, because one of the delayed DROP references
9404fc7b572SFilipe Manana 			 * may cancel that reference in the extent tree.
941dc046b10SJosef Bacik 			 */
9424fc7b572SFilipe Manana 			if (sc && count < 0)
9434fc7b572SFilipe Manana 				sc->have_delayed_delete_refs = true;
944dc046b10SJosef Bacik 
94500142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, ref->root,
94601747e92SEdmund Nadolski 					       &key, 0, node->bytenr, count, sc,
94701747e92SEdmund Nadolski 					       GFP_ATOMIC);
9488da6d581SJan Schmidt 			break;
9498da6d581SJan Schmidt 		}
9508da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
95186d5f994SEdmund Nadolski 			/* SHARED DIRECT FULL backref */
9528da6d581SJan Schmidt 			struct btrfs_delayed_data_ref *ref;
9538da6d581SJan Schmidt 
9548da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_data_ref(node);
95586d5f994SEdmund Nadolski 
95601747e92SEdmund Nadolski 			ret = add_direct_ref(fs_info, preftrees, 0, ref->parent,
95701747e92SEdmund Nadolski 					     node->bytenr, count, sc,
95801747e92SEdmund Nadolski 					     GFP_ATOMIC);
9598da6d581SJan Schmidt 			break;
9608da6d581SJan Schmidt 		}
9618da6d581SJan Schmidt 		default:
9628da6d581SJan Schmidt 			WARN_ON(1);
9638da6d581SJan Schmidt 		}
9643ec4d323SEdmund Nadolski 		/*
9653ec4d323SEdmund Nadolski 		 * We must ignore BACKREF_FOUND_SHARED until all delayed
9663ec4d323SEdmund Nadolski 		 * refs have been checked.
9673ec4d323SEdmund Nadolski 		 */
9683ec4d323SEdmund Nadolski 		if (ret && (ret != BACKREF_FOUND_SHARED))
969d7df2c79SJosef Bacik 			break;
9708da6d581SJan Schmidt 	}
9713ec4d323SEdmund Nadolski 	if (!ret)
9723ec4d323SEdmund Nadolski 		ret = extent_is_shared(sc);
9734fc7b572SFilipe Manana 
974d7df2c79SJosef Bacik 	spin_unlock(&head->lock);
975d7df2c79SJosef Bacik 	return ret;
9768da6d581SJan Schmidt }
9778da6d581SJan Schmidt 
9788da6d581SJan Schmidt /*
9798da6d581SJan Schmidt  * add all inline backrefs for bytenr to the list
9803ec4d323SEdmund Nadolski  *
9813ec4d323SEdmund Nadolski  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
9828da6d581SJan Schmidt  */
98300142756SJeff Mahoney static int add_inline_refs(const struct btrfs_fs_info *fs_info,
98400142756SJeff Mahoney 			   struct btrfs_path *path, u64 bytenr,
98586d5f994SEdmund Nadolski 			   int *info_level, struct preftrees *preftrees,
986b25b0b87Sethanwu 			   struct share_check *sc)
9878da6d581SJan Schmidt {
988b1375d64SJan Schmidt 	int ret = 0;
9898da6d581SJan Schmidt 	int slot;
9908da6d581SJan Schmidt 	struct extent_buffer *leaf;
9918da6d581SJan Schmidt 	struct btrfs_key key;
992261c84b6SJosef Bacik 	struct btrfs_key found_key;
9938da6d581SJan Schmidt 	unsigned long ptr;
9948da6d581SJan Schmidt 	unsigned long end;
9958da6d581SJan Schmidt 	struct btrfs_extent_item *ei;
9968da6d581SJan Schmidt 	u64 flags;
9978da6d581SJan Schmidt 	u64 item_size;
9988da6d581SJan Schmidt 
9998da6d581SJan Schmidt 	/*
10008da6d581SJan Schmidt 	 * enumerate all inline refs
10018da6d581SJan Schmidt 	 */
10028da6d581SJan Schmidt 	leaf = path->nodes[0];
1003dadcaf78SJan Schmidt 	slot = path->slots[0];
10048da6d581SJan Schmidt 
10053212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, slot);
10068da6d581SJan Schmidt 	BUG_ON(item_size < sizeof(*ei));
10078da6d581SJan Schmidt 
10088da6d581SJan Schmidt 	ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
10098da6d581SJan Schmidt 	flags = btrfs_extent_flags(leaf, ei);
1010261c84b6SJosef Bacik 	btrfs_item_key_to_cpu(leaf, &found_key, slot);
10118da6d581SJan Schmidt 
10128da6d581SJan Schmidt 	ptr = (unsigned long)(ei + 1);
10138da6d581SJan Schmidt 	end = (unsigned long)ei + item_size;
10148da6d581SJan Schmidt 
1015261c84b6SJosef Bacik 	if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
1016261c84b6SJosef Bacik 	    flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
10178da6d581SJan Schmidt 		struct btrfs_tree_block_info *info;
10188da6d581SJan Schmidt 
10198da6d581SJan Schmidt 		info = (struct btrfs_tree_block_info *)ptr;
10208da6d581SJan Schmidt 		*info_level = btrfs_tree_block_level(leaf, info);
10218da6d581SJan Schmidt 		ptr += sizeof(struct btrfs_tree_block_info);
10228da6d581SJan Schmidt 		BUG_ON(ptr > end);
1023261c84b6SJosef Bacik 	} else if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
1024261c84b6SJosef Bacik 		*info_level = found_key.offset;
10258da6d581SJan Schmidt 	} else {
10268da6d581SJan Schmidt 		BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
10278da6d581SJan Schmidt 	}
10288da6d581SJan Schmidt 
10298da6d581SJan Schmidt 	while (ptr < end) {
10308da6d581SJan Schmidt 		struct btrfs_extent_inline_ref *iref;
10318da6d581SJan Schmidt 		u64 offset;
10328da6d581SJan Schmidt 		int type;
10338da6d581SJan Schmidt 
10348da6d581SJan Schmidt 		iref = (struct btrfs_extent_inline_ref *)ptr;
10353de28d57SLiu Bo 		type = btrfs_get_extent_inline_ref_type(leaf, iref,
10363de28d57SLiu Bo 							BTRFS_REF_TYPE_ANY);
10373de28d57SLiu Bo 		if (type == BTRFS_REF_TYPE_INVALID)
1038af431dcbSSu Yue 			return -EUCLEAN;
10393de28d57SLiu Bo 
10408da6d581SJan Schmidt 		offset = btrfs_extent_inline_ref_offset(leaf, iref);
10418da6d581SJan Schmidt 
10428da6d581SJan Schmidt 		switch (type) {
10438da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY:
104400142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees,
104500142756SJeff Mahoney 					     *info_level + 1, offset,
10463ec4d323SEdmund Nadolski 					     bytenr, 1, NULL, GFP_NOFS);
10478da6d581SJan Schmidt 			break;
10488da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
10498da6d581SJan Schmidt 			struct btrfs_shared_data_ref *sdref;
10508da6d581SJan Schmidt 			int count;
10518da6d581SJan Schmidt 
10528da6d581SJan Schmidt 			sdref = (struct btrfs_shared_data_ref *)(iref + 1);
10538da6d581SJan Schmidt 			count = btrfs_shared_data_ref_count(leaf, sdref);
105486d5f994SEdmund Nadolski 
105500142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees, 0, offset,
10563ec4d323SEdmund Nadolski 					     bytenr, count, sc, GFP_NOFS);
10578da6d581SJan Schmidt 			break;
10588da6d581SJan Schmidt 		}
10598da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY:
106000142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, offset,
106100142756SJeff Mahoney 					       NULL, *info_level + 1,
10623ec4d323SEdmund Nadolski 					       bytenr, 1, NULL, GFP_NOFS);
10638da6d581SJan Schmidt 			break;
10648da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
10658da6d581SJan Schmidt 			struct btrfs_extent_data_ref *dref;
10668da6d581SJan Schmidt 			int count;
10678da6d581SJan Schmidt 			u64 root;
10688da6d581SJan Schmidt 
10698da6d581SJan Schmidt 			dref = (struct btrfs_extent_data_ref *)(&iref->offset);
10708da6d581SJan Schmidt 			count = btrfs_extent_data_ref_count(leaf, dref);
10718da6d581SJan Schmidt 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
10728da6d581SJan Schmidt 								      dref);
10738da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
10748da6d581SJan Schmidt 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1075dc046b10SJosef Bacik 
1076a0a5472aSFilipe Manana 			if (sc && key.objectid != sc->inum &&
10774fc7b572SFilipe Manana 			    !sc->have_delayed_delete_refs) {
1078dc046b10SJosef Bacik 				ret = BACKREF_FOUND_SHARED;
1079dc046b10SJosef Bacik 				break;
1080dc046b10SJosef Bacik 			}
1081dc046b10SJosef Bacik 
10828da6d581SJan Schmidt 			root = btrfs_extent_data_ref_root(leaf, dref);
108386d5f994SEdmund Nadolski 
108400142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, root,
108500142756SJeff Mahoney 					       &key, 0, bytenr, count,
10863ec4d323SEdmund Nadolski 					       sc, GFP_NOFS);
10874fc7b572SFilipe Manana 
10888da6d581SJan Schmidt 			break;
10898da6d581SJan Schmidt 		}
10908da6d581SJan Schmidt 		default:
10918da6d581SJan Schmidt 			WARN_ON(1);
10928da6d581SJan Schmidt 		}
10931149ab6bSWang Shilong 		if (ret)
10941149ab6bSWang Shilong 			return ret;
10958da6d581SJan Schmidt 		ptr += btrfs_extent_inline_ref_size(type);
10968da6d581SJan Schmidt 	}
10978da6d581SJan Schmidt 
10988da6d581SJan Schmidt 	return 0;
10998da6d581SJan Schmidt }
11008da6d581SJan Schmidt 
11018da6d581SJan Schmidt /*
11028da6d581SJan Schmidt  * add all non-inline backrefs for bytenr to the list
11033ec4d323SEdmund Nadolski  *
11043ec4d323SEdmund Nadolski  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
11058da6d581SJan Schmidt  */
110698cc4222SJosef Bacik static int add_keyed_refs(struct btrfs_root *extent_root,
11078da6d581SJan Schmidt 			  struct btrfs_path *path, u64 bytenr,
110886d5f994SEdmund Nadolski 			  int info_level, struct preftrees *preftrees,
11093ec4d323SEdmund Nadolski 			  struct share_check *sc)
11108da6d581SJan Schmidt {
111198cc4222SJosef Bacik 	struct btrfs_fs_info *fs_info = extent_root->fs_info;
11128da6d581SJan Schmidt 	int ret;
11138da6d581SJan Schmidt 	int slot;
11148da6d581SJan Schmidt 	struct extent_buffer *leaf;
11158da6d581SJan Schmidt 	struct btrfs_key key;
11168da6d581SJan Schmidt 
11178da6d581SJan Schmidt 	while (1) {
11188da6d581SJan Schmidt 		ret = btrfs_next_item(extent_root, path);
11198da6d581SJan Schmidt 		if (ret < 0)
11208da6d581SJan Schmidt 			break;
11218da6d581SJan Schmidt 		if (ret) {
11228da6d581SJan Schmidt 			ret = 0;
11238da6d581SJan Schmidt 			break;
11248da6d581SJan Schmidt 		}
11258da6d581SJan Schmidt 
11268da6d581SJan Schmidt 		slot = path->slots[0];
11278da6d581SJan Schmidt 		leaf = path->nodes[0];
11288da6d581SJan Schmidt 		btrfs_item_key_to_cpu(leaf, &key, slot);
11298da6d581SJan Schmidt 
11308da6d581SJan Schmidt 		if (key.objectid != bytenr)
11318da6d581SJan Schmidt 			break;
11328da6d581SJan Schmidt 		if (key.type < BTRFS_TREE_BLOCK_REF_KEY)
11338da6d581SJan Schmidt 			continue;
11348da6d581SJan Schmidt 		if (key.type > BTRFS_SHARED_DATA_REF_KEY)
11358da6d581SJan Schmidt 			break;
11368da6d581SJan Schmidt 
11378da6d581SJan Schmidt 		switch (key.type) {
11388da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY:
113986d5f994SEdmund Nadolski 			/* SHARED DIRECT METADATA backref */
114000142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees,
114100142756SJeff Mahoney 					     info_level + 1, key.offset,
11423ec4d323SEdmund Nadolski 					     bytenr, 1, NULL, GFP_NOFS);
11438da6d581SJan Schmidt 			break;
11448da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
114586d5f994SEdmund Nadolski 			/* SHARED DIRECT FULL backref */
11468da6d581SJan Schmidt 			struct btrfs_shared_data_ref *sdref;
11478da6d581SJan Schmidt 			int count;
11488da6d581SJan Schmidt 
11498da6d581SJan Schmidt 			sdref = btrfs_item_ptr(leaf, slot,
11508da6d581SJan Schmidt 					      struct btrfs_shared_data_ref);
11518da6d581SJan Schmidt 			count = btrfs_shared_data_ref_count(leaf, sdref);
115200142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees, 0,
115300142756SJeff Mahoney 					     key.offset, bytenr, count,
11543ec4d323SEdmund Nadolski 					     sc, GFP_NOFS);
11558da6d581SJan Schmidt 			break;
11568da6d581SJan Schmidt 		}
11578da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY:
115886d5f994SEdmund Nadolski 			/* NORMAL INDIRECT METADATA backref */
115900142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, key.offset,
116000142756SJeff Mahoney 					       NULL, info_level + 1, bytenr,
11613ec4d323SEdmund Nadolski 					       1, NULL, GFP_NOFS);
11628da6d581SJan Schmidt 			break;
11638da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
116486d5f994SEdmund Nadolski 			/* NORMAL INDIRECT DATA backref */
11658da6d581SJan Schmidt 			struct btrfs_extent_data_ref *dref;
11668da6d581SJan Schmidt 			int count;
11678da6d581SJan Schmidt 			u64 root;
11688da6d581SJan Schmidt 
11698da6d581SJan Schmidt 			dref = btrfs_item_ptr(leaf, slot,
11708da6d581SJan Schmidt 					      struct btrfs_extent_data_ref);
11718da6d581SJan Schmidt 			count = btrfs_extent_data_ref_count(leaf, dref);
11728da6d581SJan Schmidt 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
11738da6d581SJan Schmidt 								      dref);
11748da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
11758da6d581SJan Schmidt 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1176dc046b10SJosef Bacik 
1177a0a5472aSFilipe Manana 			if (sc && key.objectid != sc->inum &&
11784fc7b572SFilipe Manana 			    !sc->have_delayed_delete_refs) {
1179dc046b10SJosef Bacik 				ret = BACKREF_FOUND_SHARED;
1180dc046b10SJosef Bacik 				break;
1181dc046b10SJosef Bacik 			}
1182dc046b10SJosef Bacik 
11838da6d581SJan Schmidt 			root = btrfs_extent_data_ref_root(leaf, dref);
118400142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, root,
118500142756SJeff Mahoney 					       &key, 0, bytenr, count,
11863ec4d323SEdmund Nadolski 					       sc, GFP_NOFS);
11878da6d581SJan Schmidt 			break;
11888da6d581SJan Schmidt 		}
11898da6d581SJan Schmidt 		default:
11908da6d581SJan Schmidt 			WARN_ON(1);
11918da6d581SJan Schmidt 		}
11921149ab6bSWang Shilong 		if (ret)
11931149ab6bSWang Shilong 			return ret;
11941149ab6bSWang Shilong 
11958da6d581SJan Schmidt 	}
11968da6d581SJan Schmidt 
11978da6d581SJan Schmidt 	return ret;
11988da6d581SJan Schmidt }
11998da6d581SJan Schmidt 
12008da6d581SJan Schmidt /*
1201583f4ac5SFilipe Manana  * The caller has joined a transaction or is holding a read lock on the
1202583f4ac5SFilipe Manana  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1203583f4ac5SFilipe Manana  * snapshot field changing while updating or checking the cache.
1204583f4ac5SFilipe Manana  */
1205583f4ac5SFilipe Manana static bool lookup_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1206583f4ac5SFilipe Manana 					struct btrfs_root *root,
1207583f4ac5SFilipe Manana 					u64 bytenr, int level, bool *is_shared)
1208583f4ac5SFilipe Manana {
1209583f4ac5SFilipe Manana 	struct btrfs_backref_shared_cache_entry *entry;
1210583f4ac5SFilipe Manana 
1211583f4ac5SFilipe Manana 	if (!ctx->use_path_cache)
1212583f4ac5SFilipe Manana 		return false;
1213583f4ac5SFilipe Manana 
1214583f4ac5SFilipe Manana 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1215583f4ac5SFilipe Manana 		return false;
1216583f4ac5SFilipe Manana 
1217583f4ac5SFilipe Manana 	/*
1218583f4ac5SFilipe Manana 	 * Level -1 is used for the data extent, which is not reliable to cache
1219583f4ac5SFilipe Manana 	 * because its reference count can increase or decrease without us
1220583f4ac5SFilipe Manana 	 * realizing. We cache results only for extent buffers that lead from
1221583f4ac5SFilipe Manana 	 * the root node down to the leaf with the file extent item.
1222583f4ac5SFilipe Manana 	 */
1223583f4ac5SFilipe Manana 	ASSERT(level >= 0);
1224583f4ac5SFilipe Manana 
1225583f4ac5SFilipe Manana 	entry = &ctx->path_cache_entries[level];
1226583f4ac5SFilipe Manana 
1227583f4ac5SFilipe Manana 	/* Unused cache entry or being used for some other extent buffer. */
1228583f4ac5SFilipe Manana 	if (entry->bytenr != bytenr)
1229583f4ac5SFilipe Manana 		return false;
1230583f4ac5SFilipe Manana 
1231583f4ac5SFilipe Manana 	/*
1232583f4ac5SFilipe Manana 	 * We cached a false result, but the last snapshot generation of the
1233583f4ac5SFilipe Manana 	 * root changed, so we now have a snapshot. Don't trust the result.
1234583f4ac5SFilipe Manana 	 */
1235583f4ac5SFilipe Manana 	if (!entry->is_shared &&
1236583f4ac5SFilipe Manana 	    entry->gen != btrfs_root_last_snapshot(&root->root_item))
1237583f4ac5SFilipe Manana 		return false;
1238583f4ac5SFilipe Manana 
1239583f4ac5SFilipe Manana 	/*
1240583f4ac5SFilipe Manana 	 * If we cached a true result and the last generation used for dropping
1241583f4ac5SFilipe Manana 	 * a root changed, we can not trust the result, because the dropped root
1242583f4ac5SFilipe Manana 	 * could be a snapshot sharing this extent buffer.
1243583f4ac5SFilipe Manana 	 */
1244583f4ac5SFilipe Manana 	if (entry->is_shared &&
1245583f4ac5SFilipe Manana 	    entry->gen != btrfs_get_last_root_drop_gen(root->fs_info))
1246583f4ac5SFilipe Manana 		return false;
1247583f4ac5SFilipe Manana 
1248583f4ac5SFilipe Manana 	*is_shared = entry->is_shared;
1249583f4ac5SFilipe Manana 	/*
1250583f4ac5SFilipe Manana 	 * If the node at this level is shared, than all nodes below are also
1251583f4ac5SFilipe Manana 	 * shared. Currently some of the nodes below may be marked as not shared
1252583f4ac5SFilipe Manana 	 * because we have just switched from one leaf to another, and switched
1253583f4ac5SFilipe Manana 	 * also other nodes above the leaf and below the current level, so mark
1254583f4ac5SFilipe Manana 	 * them as shared.
1255583f4ac5SFilipe Manana 	 */
1256583f4ac5SFilipe Manana 	if (*is_shared) {
1257583f4ac5SFilipe Manana 		for (int i = 0; i < level; i++) {
1258583f4ac5SFilipe Manana 			ctx->path_cache_entries[i].is_shared = true;
1259583f4ac5SFilipe Manana 			ctx->path_cache_entries[i].gen = entry->gen;
1260583f4ac5SFilipe Manana 		}
1261583f4ac5SFilipe Manana 	}
1262583f4ac5SFilipe Manana 
1263583f4ac5SFilipe Manana 	return true;
1264583f4ac5SFilipe Manana }
1265583f4ac5SFilipe Manana 
1266583f4ac5SFilipe Manana /*
1267583f4ac5SFilipe Manana  * The caller has joined a transaction or is holding a read lock on the
1268583f4ac5SFilipe Manana  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1269583f4ac5SFilipe Manana  * snapshot field changing while updating or checking the cache.
1270583f4ac5SFilipe Manana  */
1271583f4ac5SFilipe Manana static void store_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1272583f4ac5SFilipe Manana 				       struct btrfs_root *root,
1273583f4ac5SFilipe Manana 				       u64 bytenr, int level, bool is_shared)
1274583f4ac5SFilipe Manana {
1275583f4ac5SFilipe Manana 	struct btrfs_backref_shared_cache_entry *entry;
1276583f4ac5SFilipe Manana 	u64 gen;
1277583f4ac5SFilipe Manana 
1278583f4ac5SFilipe Manana 	if (!ctx->use_path_cache)
1279583f4ac5SFilipe Manana 		return;
1280583f4ac5SFilipe Manana 
1281583f4ac5SFilipe Manana 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1282583f4ac5SFilipe Manana 		return;
1283583f4ac5SFilipe Manana 
1284583f4ac5SFilipe Manana 	/*
1285583f4ac5SFilipe Manana 	 * Level -1 is used for the data extent, which is not reliable to cache
1286583f4ac5SFilipe Manana 	 * because its reference count can increase or decrease without us
1287583f4ac5SFilipe Manana 	 * realizing. We cache results only for extent buffers that lead from
1288583f4ac5SFilipe Manana 	 * the root node down to the leaf with the file extent item.
1289583f4ac5SFilipe Manana 	 */
1290583f4ac5SFilipe Manana 	ASSERT(level >= 0);
1291583f4ac5SFilipe Manana 
1292583f4ac5SFilipe Manana 	if (is_shared)
1293583f4ac5SFilipe Manana 		gen = btrfs_get_last_root_drop_gen(root->fs_info);
1294583f4ac5SFilipe Manana 	else
1295583f4ac5SFilipe Manana 		gen = btrfs_root_last_snapshot(&root->root_item);
1296583f4ac5SFilipe Manana 
1297583f4ac5SFilipe Manana 	entry = &ctx->path_cache_entries[level];
1298583f4ac5SFilipe Manana 	entry->bytenr = bytenr;
1299583f4ac5SFilipe Manana 	entry->is_shared = is_shared;
1300583f4ac5SFilipe Manana 	entry->gen = gen;
1301583f4ac5SFilipe Manana 
1302583f4ac5SFilipe Manana 	/*
1303583f4ac5SFilipe Manana 	 * If we found an extent buffer is shared, set the cache result for all
1304583f4ac5SFilipe Manana 	 * extent buffers below it to true. As nodes in the path are COWed,
1305583f4ac5SFilipe Manana 	 * their sharedness is moved to their children, and if a leaf is COWed,
1306583f4ac5SFilipe Manana 	 * then the sharedness of a data extent becomes direct, the refcount of
1307583f4ac5SFilipe Manana 	 * data extent is increased in the extent item at the extent tree.
1308583f4ac5SFilipe Manana 	 */
1309583f4ac5SFilipe Manana 	if (is_shared) {
1310583f4ac5SFilipe Manana 		for (int i = 0; i < level; i++) {
1311583f4ac5SFilipe Manana 			entry = &ctx->path_cache_entries[i];
1312583f4ac5SFilipe Manana 			entry->is_shared = is_shared;
1313583f4ac5SFilipe Manana 			entry->gen = gen;
1314583f4ac5SFilipe Manana 		}
1315583f4ac5SFilipe Manana 	}
1316583f4ac5SFilipe Manana }
1317583f4ac5SFilipe Manana 
1318583f4ac5SFilipe Manana /*
13198da6d581SJan Schmidt  * this adds all existing backrefs (inline backrefs, backrefs and delayed
13208da6d581SJan Schmidt  * refs) for the given bytenr to the refs list, merges duplicates and resolves
13218da6d581SJan Schmidt  * indirect refs to their parent bytenr.
13228da6d581SJan Schmidt  * When roots are found, they're added to the roots list
13238da6d581SJan Schmidt  *
1324a2c8d27eSFilipe Manana  * @ctx:     Backref walking context object, must be not NULL.
1325a2c8d27eSFilipe Manana  * @sc:      If !NULL, then immediately return BACKREF_FOUND_SHARED when a
13263ec4d323SEdmund Nadolski  *           shared extent is detected.
13273ec4d323SEdmund Nadolski  *
13283ec4d323SEdmund Nadolski  * Otherwise this returns 0 for success and <0 for an error.
13293ec4d323SEdmund Nadolski  *
13308da6d581SJan Schmidt  * FIXME some caching might speed things up
13318da6d581SJan Schmidt  */
1332a2c8d27eSFilipe Manana static int find_parent_nodes(struct btrfs_backref_walk_ctx *ctx,
13336ce6ba53SFilipe Manana 			     struct share_check *sc)
13348da6d581SJan Schmidt {
1335a2c8d27eSFilipe Manana 	struct btrfs_root *root = btrfs_extent_root(ctx->fs_info, ctx->bytenr);
13368da6d581SJan Schmidt 	struct btrfs_key key;
13378da6d581SJan Schmidt 	struct btrfs_path *path;
13388da6d581SJan Schmidt 	struct btrfs_delayed_ref_root *delayed_refs = NULL;
1339d3b01064SLi Zefan 	struct btrfs_delayed_ref_head *head;
13408da6d581SJan Schmidt 	int info_level = 0;
13418da6d581SJan Schmidt 	int ret;
1342e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
134386d5f994SEdmund Nadolski 	struct rb_node *node;
1344f05c4746SWang Shilong 	struct extent_inode_elem *eie = NULL;
134586d5f994SEdmund Nadolski 	struct preftrees preftrees = {
134686d5f994SEdmund Nadolski 		.direct = PREFTREE_INIT,
134786d5f994SEdmund Nadolski 		.indirect = PREFTREE_INIT,
134886d5f994SEdmund Nadolski 		.indirect_missing_keys = PREFTREE_INIT
134986d5f994SEdmund Nadolski 	};
13508da6d581SJan Schmidt 
135156f5c199SFilipe Manana 	/* Roots ulist is not needed when using a sharedness check context. */
135256f5c199SFilipe Manana 	if (sc)
1353a2c8d27eSFilipe Manana 		ASSERT(ctx->roots == NULL);
135456f5c199SFilipe Manana 
1355a2c8d27eSFilipe Manana 	key.objectid = ctx->bytenr;
13568da6d581SJan Schmidt 	key.offset = (u64)-1;
1357a2c8d27eSFilipe Manana 	if (btrfs_fs_incompat(ctx->fs_info, SKINNY_METADATA))
1358261c84b6SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
1359261c84b6SJosef Bacik 	else
1360261c84b6SJosef Bacik 		key.type = BTRFS_EXTENT_ITEM_KEY;
13618da6d581SJan Schmidt 
13628da6d581SJan Schmidt 	path = btrfs_alloc_path();
13638da6d581SJan Schmidt 	if (!path)
13648da6d581SJan Schmidt 		return -ENOMEM;
1365a2c8d27eSFilipe Manana 	if (!ctx->trans) {
1366da61d31aSJosef Bacik 		path->search_commit_root = 1;
1367e84752d4SWang Shilong 		path->skip_locking = 1;
1368e84752d4SWang Shilong 	}
13698da6d581SJan Schmidt 
1370a2c8d27eSFilipe Manana 	if (ctx->time_seq == BTRFS_SEQ_LAST)
137121633fc6SQu Wenruo 		path->skip_locking = 1;
137221633fc6SQu Wenruo 
13738da6d581SJan Schmidt again:
1374d3b01064SLi Zefan 	head = NULL;
1375d3b01064SLi Zefan 
137698cc4222SJosef Bacik 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
13778da6d581SJan Schmidt 	if (ret < 0)
13788da6d581SJan Schmidt 		goto out;
1379fcba0120SJosef Bacik 	if (ret == 0) {
1380fcba0120SJosef Bacik 		/* This shouldn't happen, indicates a bug or fs corruption. */
1381fcba0120SJosef Bacik 		ASSERT(ret != 0);
1382fcba0120SJosef Bacik 		ret = -EUCLEAN;
1383fcba0120SJosef Bacik 		goto out;
1384fcba0120SJosef Bacik 	}
13858da6d581SJan Schmidt 
1386a2c8d27eSFilipe Manana 	if (ctx->trans && likely(ctx->trans->type != __TRANS_DUMMY) &&
1387a2c8d27eSFilipe Manana 	    ctx->time_seq != BTRFS_SEQ_LAST) {
13888da6d581SJan Schmidt 		/*
13899665ebd5SJosef Bacik 		 * We have a specific time_seq we care about and trans which
13909665ebd5SJosef Bacik 		 * means we have the path lock, we need to grab the ref head and
13919665ebd5SJosef Bacik 		 * lock it so we have a consistent view of the refs at the given
13929665ebd5SJosef Bacik 		 * time.
13938da6d581SJan Schmidt 		 */
1394a2c8d27eSFilipe Manana 		delayed_refs = &ctx->trans->transaction->delayed_refs;
13958da6d581SJan Schmidt 		spin_lock(&delayed_refs->lock);
1396a2c8d27eSFilipe Manana 		head = btrfs_find_delayed_ref_head(delayed_refs, ctx->bytenr);
13978da6d581SJan Schmidt 		if (head) {
13988da6d581SJan Schmidt 			if (!mutex_trylock(&head->mutex)) {
1399d278850eSJosef Bacik 				refcount_inc(&head->refs);
14008da6d581SJan Schmidt 				spin_unlock(&delayed_refs->lock);
14018da6d581SJan Schmidt 
14028da6d581SJan Schmidt 				btrfs_release_path(path);
14038da6d581SJan Schmidt 
14048da6d581SJan Schmidt 				/*
14058da6d581SJan Schmidt 				 * Mutex was contended, block until it's
14068da6d581SJan Schmidt 				 * released and try again
14078da6d581SJan Schmidt 				 */
14088da6d581SJan Schmidt 				mutex_lock(&head->mutex);
14098da6d581SJan Schmidt 				mutex_unlock(&head->mutex);
1410d278850eSJosef Bacik 				btrfs_put_delayed_ref_head(head);
14118da6d581SJan Schmidt 				goto again;
14128da6d581SJan Schmidt 			}
1413d7df2c79SJosef Bacik 			spin_unlock(&delayed_refs->lock);
1414a2c8d27eSFilipe Manana 			ret = add_delayed_refs(ctx->fs_info, head, ctx->time_seq,
1415b25b0b87Sethanwu 					       &preftrees, sc);
1416155725c9SJan Schmidt 			mutex_unlock(&head->mutex);
1417d7df2c79SJosef Bacik 			if (ret)
14188da6d581SJan Schmidt 				goto out;
1419d7df2c79SJosef Bacik 		} else {
14208da6d581SJan Schmidt 			spin_unlock(&delayed_refs->lock);
14217a3ae2f8SJan Schmidt 		}
1422d7df2c79SJosef Bacik 	}
14238da6d581SJan Schmidt 
14248da6d581SJan Schmidt 	if (path->slots[0]) {
14258da6d581SJan Schmidt 		struct extent_buffer *leaf;
14268da6d581SJan Schmidt 		int slot;
14278da6d581SJan Schmidt 
1428dadcaf78SJan Schmidt 		path->slots[0]--;
14298da6d581SJan Schmidt 		leaf = path->nodes[0];
1430dadcaf78SJan Schmidt 		slot = path->slots[0];
14318da6d581SJan Schmidt 		btrfs_item_key_to_cpu(leaf, &key, slot);
1432a2c8d27eSFilipe Manana 		if (key.objectid == ctx->bytenr &&
1433261c84b6SJosef Bacik 		    (key.type == BTRFS_EXTENT_ITEM_KEY ||
1434261c84b6SJosef Bacik 		     key.type == BTRFS_METADATA_ITEM_KEY)) {
1435a2c8d27eSFilipe Manana 			ret = add_inline_refs(ctx->fs_info, path, ctx->bytenr,
1436b25b0b87Sethanwu 					      &info_level, &preftrees, sc);
14378da6d581SJan Schmidt 			if (ret)
14388da6d581SJan Schmidt 				goto out;
1439a2c8d27eSFilipe Manana 			ret = add_keyed_refs(root, path, ctx->bytenr, info_level,
14403ec4d323SEdmund Nadolski 					     &preftrees, sc);
14418da6d581SJan Schmidt 			if (ret)
14428da6d581SJan Schmidt 				goto out;
14438da6d581SJan Schmidt 		}
14448da6d581SJan Schmidt 	}
144586d5f994SEdmund Nadolski 
144656f5c199SFilipe Manana 	/*
144756f5c199SFilipe Manana 	 * If we have a share context and we reached here, it means the extent
144856f5c199SFilipe Manana 	 * is not directly shared (no multiple reference items for it),
144956f5c199SFilipe Manana 	 * otherwise we would have exited earlier with a return value of
145056f5c199SFilipe Manana 	 * BACKREF_FOUND_SHARED after processing delayed references or while
145156f5c199SFilipe Manana 	 * processing inline or keyed references from the extent tree.
145256f5c199SFilipe Manana 	 * The extent may however be indirectly shared through shared subtrees
145356f5c199SFilipe Manana 	 * as a result from creating snapshots, so we determine below what is
145456f5c199SFilipe Manana 	 * its parent node, in case we are dealing with a metadata extent, or
145556f5c199SFilipe Manana 	 * what's the leaf (or leaves), from a fs tree, that has a file extent
145656f5c199SFilipe Manana 	 * item pointing to it in case we are dealing with a data extent.
145756f5c199SFilipe Manana 	 */
145856f5c199SFilipe Manana 	ASSERT(extent_is_shared(sc) == 0);
145956f5c199SFilipe Manana 
1460877c1476SFilipe Manana 	/*
1461877c1476SFilipe Manana 	 * If we are here for a data extent and we have a share_check structure
1462877c1476SFilipe Manana 	 * it means the data extent is not directly shared (does not have
1463877c1476SFilipe Manana 	 * multiple reference items), so we have to check if a path in the fs
1464877c1476SFilipe Manana 	 * tree (going from the root node down to the leaf that has the file
1465877c1476SFilipe Manana 	 * extent item pointing to the data extent) is shared, that is, if any
1466877c1476SFilipe Manana 	 * of the extent buffers in the path is referenced by other trees.
1467877c1476SFilipe Manana 	 */
1468a2c8d27eSFilipe Manana 	if (sc && ctx->bytenr == sc->data_bytenr) {
1469877c1476SFilipe Manana 		/*
14706976201fSFilipe Manana 		 * If our data extent is from a generation more recent than the
14716976201fSFilipe Manana 		 * last generation used to snapshot the root, then we know that
14726976201fSFilipe Manana 		 * it can not be shared through subtrees, so we can skip
14736976201fSFilipe Manana 		 * resolving indirect references, there's no point in
14746976201fSFilipe Manana 		 * determining the extent buffers for the path from the fs tree
14756976201fSFilipe Manana 		 * root node down to the leaf that has the file extent item that
14766976201fSFilipe Manana 		 * points to the data extent.
14776976201fSFilipe Manana 		 */
14786976201fSFilipe Manana 		if (sc->data_extent_gen >
14796976201fSFilipe Manana 		    btrfs_root_last_snapshot(&sc->root->root_item)) {
14806976201fSFilipe Manana 			ret = BACKREF_FOUND_NOT_SHARED;
14816976201fSFilipe Manana 			goto out;
14826976201fSFilipe Manana 		}
14836976201fSFilipe Manana 
14846976201fSFilipe Manana 		/*
1485877c1476SFilipe Manana 		 * If we are only determining if a data extent is shared or not
1486877c1476SFilipe Manana 		 * and the corresponding file extent item is located in the same
1487877c1476SFilipe Manana 		 * leaf as the previous file extent item, we can skip resolving
1488877c1476SFilipe Manana 		 * indirect references for a data extent, since the fs tree path
1489877c1476SFilipe Manana 		 * is the same (same leaf, so same path). We skip as long as the
1490877c1476SFilipe Manana 		 * cached result for the leaf is valid and only if there's only
1491877c1476SFilipe Manana 		 * one file extent item pointing to the data extent, because in
1492877c1476SFilipe Manana 		 * the case of multiple file extent items, they may be located
1493877c1476SFilipe Manana 		 * in different leaves and therefore we have multiple paths.
1494877c1476SFilipe Manana 		 */
1495877c1476SFilipe Manana 		if (sc->ctx->curr_leaf_bytenr == sc->ctx->prev_leaf_bytenr &&
1496877c1476SFilipe Manana 		    sc->self_ref_count == 1) {
1497877c1476SFilipe Manana 			bool cached;
1498877c1476SFilipe Manana 			bool is_shared;
1499877c1476SFilipe Manana 
1500877c1476SFilipe Manana 			cached = lookup_backref_shared_cache(sc->ctx, sc->root,
1501877c1476SFilipe Manana 						     sc->ctx->curr_leaf_bytenr,
1502877c1476SFilipe Manana 						     0, &is_shared);
1503877c1476SFilipe Manana 			if (cached) {
1504877c1476SFilipe Manana 				if (is_shared)
1505877c1476SFilipe Manana 					ret = BACKREF_FOUND_SHARED;
1506877c1476SFilipe Manana 				else
1507877c1476SFilipe Manana 					ret = BACKREF_FOUND_NOT_SHARED;
1508877c1476SFilipe Manana 				goto out;
1509877c1476SFilipe Manana 			}
1510877c1476SFilipe Manana 		}
1511877c1476SFilipe Manana 	}
1512877c1476SFilipe Manana 
15138da6d581SJan Schmidt 	btrfs_release_path(path);
15148da6d581SJan Schmidt 
1515a2c8d27eSFilipe Manana 	ret = add_missing_keys(ctx->fs_info, &preftrees, path->skip_locking == 0);
1516d5c88b73SJan Schmidt 	if (ret)
1517d5c88b73SJan Schmidt 		goto out;
1518d5c88b73SJan Schmidt 
1519ecf160b4SLiu Bo 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect_missing_keys.root.rb_root));
15208da6d581SJan Schmidt 
1521a2c8d27eSFilipe Manana 	ret = resolve_indirect_refs(ctx, path, &preftrees, sc);
15228da6d581SJan Schmidt 	if (ret)
15238da6d581SJan Schmidt 		goto out;
15248da6d581SJan Schmidt 
1525ecf160b4SLiu Bo 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect.root.rb_root));
15268da6d581SJan Schmidt 
152786d5f994SEdmund Nadolski 	/*
152886d5f994SEdmund Nadolski 	 * This walks the tree of merged and resolved refs. Tree blocks are
152986d5f994SEdmund Nadolski 	 * read in as needed. Unique entries are added to the ulist, and
153086d5f994SEdmund Nadolski 	 * the list of found roots is updated.
153186d5f994SEdmund Nadolski 	 *
153286d5f994SEdmund Nadolski 	 * We release the entire tree in one go before returning.
153386d5f994SEdmund Nadolski 	 */
1534ecf160b4SLiu Bo 	node = rb_first_cached(&preftrees.direct.root);
153586d5f994SEdmund Nadolski 	while (node) {
153686d5f994SEdmund Nadolski 		ref = rb_entry(node, struct prelim_ref, rbnode);
153786d5f994SEdmund Nadolski 		node = rb_next(&ref->rbnode);
1538c8195a7bSZygo Blaxell 		/*
1539c8195a7bSZygo Blaxell 		 * ref->count < 0 can happen here if there are delayed
1540c8195a7bSZygo Blaxell 		 * refs with a node->action of BTRFS_DROP_DELAYED_REF.
1541c8195a7bSZygo Blaxell 		 * prelim_ref_insert() relies on this when merging
1542c8195a7bSZygo Blaxell 		 * identical refs to keep the overall count correct.
1543c8195a7bSZygo Blaxell 		 * prelim_ref_insert() will merge only those refs
1544c8195a7bSZygo Blaxell 		 * which compare identically.  Any refs having
1545c8195a7bSZygo Blaxell 		 * e.g. different offsets would not be merged,
1546c8195a7bSZygo Blaxell 		 * and would retain their original ref->count < 0.
1547c8195a7bSZygo Blaxell 		 */
1548a2c8d27eSFilipe Manana 		if (ctx->roots && ref->count && ref->root_id && ref->parent == 0) {
15498da6d581SJan Schmidt 			/* no parent == root of tree */
1550a2c8d27eSFilipe Manana 			ret = ulist_add(ctx->roots, ref->root_id, 0, GFP_NOFS);
1551f1723939SWang Shilong 			if (ret < 0)
1552f1723939SWang Shilong 				goto out;
15538da6d581SJan Schmidt 		}
15548da6d581SJan Schmidt 		if (ref->count && ref->parent) {
1555a2c8d27eSFilipe Manana 			if (!ctx->ignore_extent_item_pos && !ref->inode_list &&
1556a2c8d27eSFilipe Manana 			    ref->level == 0) {
1557976b1908SJan Schmidt 				struct extent_buffer *eb;
1558707e8a07SDavid Sterba 
1559a2c8d27eSFilipe Manana 				eb = read_tree_block(ctx->fs_info, ref->parent, 0,
15601b7ec85eSJosef Bacik 						     0, ref->level, NULL);
156164c043deSLiu Bo 				if (IS_ERR(eb)) {
156264c043deSLiu Bo 					ret = PTR_ERR(eb);
156364c043deSLiu Bo 					goto out;
15644eb150d6SQu Wenruo 				}
15654eb150d6SQu Wenruo 				if (!extent_buffer_uptodate(eb)) {
1566416bc658SJosef Bacik 					free_extent_buffer(eb);
1567c16c2e2eSWang Shilong 					ret = -EIO;
1568c16c2e2eSWang Shilong 					goto out;
1569416bc658SJosef Bacik 				}
157038e3eebfSJosef Bacik 
1571ac5887c8SJosef Bacik 				if (!path->skip_locking)
15726f7ff6d7SFilipe Manana 					btrfs_tree_read_lock(eb);
1573a2c8d27eSFilipe Manana 				ret = find_extent_in_eb(eb, ctx->bytenr,
1574a2c8d27eSFilipe Manana 							ctx->extent_item_pos, &eie);
157538e3eebfSJosef Bacik 				if (!path->skip_locking)
1576ac5887c8SJosef Bacik 					btrfs_tree_read_unlock(eb);
1577976b1908SJan Schmidt 				free_extent_buffer(eb);
1578f5929cd8SFilipe David Borba Manana 				if (ret < 0)
1579f5929cd8SFilipe David Borba Manana 					goto out;
1580f5929cd8SFilipe David Borba Manana 				ref->inode_list = eie;
158192876eecSFilipe Manana 				/*
158292876eecSFilipe Manana 				 * We transferred the list ownership to the ref,
158392876eecSFilipe Manana 				 * so set to NULL to avoid a double free in case
158492876eecSFilipe Manana 				 * an error happens after this.
158592876eecSFilipe Manana 				 */
158692876eecSFilipe Manana 				eie = NULL;
1587976b1908SJan Schmidt 			}
1588a2c8d27eSFilipe Manana 			ret = ulist_add_merge_ptr(ctx->refs, ref->parent,
15894eb1f66dSTakashi Iwai 						  ref->inode_list,
15904eb1f66dSTakashi Iwai 						  (void **)&eie, GFP_NOFS);
1591f1723939SWang Shilong 			if (ret < 0)
1592f1723939SWang Shilong 				goto out;
1593a2c8d27eSFilipe Manana 			if (!ret && !ctx->ignore_extent_item_pos) {
15943301958bSJan Schmidt 				/*
15959f05c09dSJosef Bacik 				 * We've recorded that parent, so we must extend
15969f05c09dSJosef Bacik 				 * its inode list here.
15979f05c09dSJosef Bacik 				 *
15989f05c09dSJosef Bacik 				 * However if there was corruption we may not
15999f05c09dSJosef Bacik 				 * have found an eie, return an error in this
16009f05c09dSJosef Bacik 				 * case.
16013301958bSJan Schmidt 				 */
16029f05c09dSJosef Bacik 				ASSERT(eie);
16039f05c09dSJosef Bacik 				if (!eie) {
16049f05c09dSJosef Bacik 					ret = -EUCLEAN;
16059f05c09dSJosef Bacik 					goto out;
16069f05c09dSJosef Bacik 				}
16073301958bSJan Schmidt 				while (eie->next)
16083301958bSJan Schmidt 					eie = eie->next;
16093301958bSJan Schmidt 				eie->next = ref->inode_list;
16103301958bSJan Schmidt 			}
1611f05c4746SWang Shilong 			eie = NULL;
161292876eecSFilipe Manana 			/*
161392876eecSFilipe Manana 			 * We have transferred the inode list ownership from
161492876eecSFilipe Manana 			 * this ref to the ref we added to the 'refs' ulist.
161592876eecSFilipe Manana 			 * So set this ref's inode list to NULL to avoid
161692876eecSFilipe Manana 			 * use-after-free when our caller uses it or double
161792876eecSFilipe Manana 			 * frees in case an error happens before we return.
161892876eecSFilipe Manana 			 */
161992876eecSFilipe Manana 			ref->inode_list = NULL;
16208da6d581SJan Schmidt 		}
16219dd14fd6SEdmund Nadolski 		cond_resched();
16228da6d581SJan Schmidt 	}
16238da6d581SJan Schmidt 
16248da6d581SJan Schmidt out:
16258da6d581SJan Schmidt 	btrfs_free_path(path);
162686d5f994SEdmund Nadolski 
162786d5f994SEdmund Nadolski 	prelim_release(&preftrees.direct);
162886d5f994SEdmund Nadolski 	prelim_release(&preftrees.indirect);
162986d5f994SEdmund Nadolski 	prelim_release(&preftrees.indirect_missing_keys);
163086d5f994SEdmund Nadolski 
1631f05c4746SWang Shilong 	if (ret < 0)
1632f05c4746SWang Shilong 		free_inode_elem_list(eie);
16338da6d581SJan Schmidt 	return ret;
16348da6d581SJan Schmidt }
16358da6d581SJan Schmidt 
16368da6d581SJan Schmidt /*
1637a2c8d27eSFilipe Manana  * Finds all leaves with a reference to the specified combination of
1638a2c8d27eSFilipe Manana  * @ctx->bytenr and @ctx->extent_item_pos. The bytenr of the found leaves are
1639a2c8d27eSFilipe Manana  * added to the ulist at @ctx->refs, and that ulist is allocated by this
1640a2c8d27eSFilipe Manana  * function. The caller should free the ulist with free_leaf_list() if
1641a2c8d27eSFilipe Manana  * @ctx->ignore_extent_item_pos is false, otherwise a fimple ulist_free() is
1642a2c8d27eSFilipe Manana  * enough.
16438da6d581SJan Schmidt  *
1644a2c8d27eSFilipe Manana  * Returns 0 on success and < 0 on error. On error @ctx->refs is not allocated.
16458da6d581SJan Schmidt  */
1646a2c8d27eSFilipe Manana int btrfs_find_all_leafs(struct btrfs_backref_walk_ctx *ctx)
16478da6d581SJan Schmidt {
16488da6d581SJan Schmidt 	int ret;
16498da6d581SJan Schmidt 
1650a2c8d27eSFilipe Manana 	ASSERT(ctx->refs == NULL);
1651a2c8d27eSFilipe Manana 
1652a2c8d27eSFilipe Manana 	ctx->refs = ulist_alloc(GFP_NOFS);
1653a2c8d27eSFilipe Manana 	if (!ctx->refs)
16548da6d581SJan Schmidt 		return -ENOMEM;
16558da6d581SJan Schmidt 
1656a2c8d27eSFilipe Manana 	ret = find_parent_nodes(ctx, NULL);
16578da6d581SJan Schmidt 	if (ret < 0 && ret != -ENOENT) {
1658a2c8d27eSFilipe Manana 		free_leaf_list(ctx->refs);
1659a2c8d27eSFilipe Manana 		ctx->refs = NULL;
16608da6d581SJan Schmidt 		return ret;
16618da6d581SJan Schmidt 	}
16628da6d581SJan Schmidt 
16638da6d581SJan Schmidt 	return 0;
16648da6d581SJan Schmidt }
16658da6d581SJan Schmidt 
16668da6d581SJan Schmidt /*
1667a2c8d27eSFilipe Manana  * Walk all backrefs for a given extent to find all roots that reference this
16688da6d581SJan Schmidt  * extent. Walking a backref means finding all extents that reference this
16698da6d581SJan Schmidt  * extent and in turn walk the backrefs of those, too. Naturally this is a
16708da6d581SJan Schmidt  * recursive process, but here it is implemented in an iterative fashion: We
16718da6d581SJan Schmidt  * find all referencing extents for the extent in question and put them on a
16728da6d581SJan Schmidt  * list. In turn, we find all referencing extents for those, further appending
16738da6d581SJan Schmidt  * to the list. The way we iterate the list allows adding more elements after
16748da6d581SJan Schmidt  * the current while iterating. The process stops when we reach the end of the
1675a2c8d27eSFilipe Manana  * list.
16768da6d581SJan Schmidt  *
16771baea6f1SFilipe Manana  * Found roots are added to @ctx->roots, which is allocated by this function if
16781baea6f1SFilipe Manana  * it points to NULL, in which case the caller is responsible for freeing it
16791baea6f1SFilipe Manana  * after it's not needed anymore.
16801baea6f1SFilipe Manana  * This function requires @ctx->refs to be NULL, as it uses it for allocating a
16811baea6f1SFilipe Manana  * ulist to do temporary work, and frees it before returning.
1682a2c8d27eSFilipe Manana  *
16831baea6f1SFilipe Manana  * Returns 0 on success, < 0 on error.
16848da6d581SJan Schmidt  */
1685a2c8d27eSFilipe Manana static int btrfs_find_all_roots_safe(struct btrfs_backref_walk_ctx *ctx)
16868da6d581SJan Schmidt {
1687a2c8d27eSFilipe Manana 	const u64 orig_bytenr = ctx->bytenr;
1688a2c8d27eSFilipe Manana 	const bool orig_ignore_extent_item_pos = ctx->ignore_extent_item_pos;
16891baea6f1SFilipe Manana 	bool roots_ulist_allocated = false;
1690cd1b413cSJan Schmidt 	struct ulist_iterator uiter;
1691a2c8d27eSFilipe Manana 	int ret = 0;
16928da6d581SJan Schmidt 
1693a2c8d27eSFilipe Manana 	ASSERT(ctx->refs == NULL);
1694a2c8d27eSFilipe Manana 
1695a2c8d27eSFilipe Manana 	ctx->refs = ulist_alloc(GFP_NOFS);
1696a2c8d27eSFilipe Manana 	if (!ctx->refs)
16978da6d581SJan Schmidt 		return -ENOMEM;
1698a2c8d27eSFilipe Manana 
16991baea6f1SFilipe Manana 	if (!ctx->roots) {
1700a2c8d27eSFilipe Manana 		ctx->roots = ulist_alloc(GFP_NOFS);
1701a2c8d27eSFilipe Manana 		if (!ctx->roots) {
1702a2c8d27eSFilipe Manana 			ulist_free(ctx->refs);
1703a2c8d27eSFilipe Manana 			ctx->refs = NULL;
17048da6d581SJan Schmidt 			return -ENOMEM;
17058da6d581SJan Schmidt 		}
17061baea6f1SFilipe Manana 		roots_ulist_allocated = true;
17071baea6f1SFilipe Manana 	}
17088da6d581SJan Schmidt 
1709a2c8d27eSFilipe Manana 	ctx->ignore_extent_item_pos = true;
1710a2c8d27eSFilipe Manana 
1711cd1b413cSJan Schmidt 	ULIST_ITER_INIT(&uiter);
17128da6d581SJan Schmidt 	while (1) {
1713a2c8d27eSFilipe Manana 		struct ulist_node *node;
1714a2c8d27eSFilipe Manana 
1715a2c8d27eSFilipe Manana 		ret = find_parent_nodes(ctx, NULL);
17168da6d581SJan Schmidt 		if (ret < 0 && ret != -ENOENT) {
17171baea6f1SFilipe Manana 			if (roots_ulist_allocated) {
1718a2c8d27eSFilipe Manana 				ulist_free(ctx->roots);
1719a2c8d27eSFilipe Manana 				ctx->roots = NULL;
17201baea6f1SFilipe Manana 			}
1721a2c8d27eSFilipe Manana 			break;
17228da6d581SJan Schmidt 		}
1723a2c8d27eSFilipe Manana 		ret = 0;
1724a2c8d27eSFilipe Manana 		node = ulist_next(ctx->refs, &uiter);
17258da6d581SJan Schmidt 		if (!node)
17268da6d581SJan Schmidt 			break;
1727a2c8d27eSFilipe Manana 		ctx->bytenr = node->val;
1728bca1a290SWang Shilong 		cond_resched();
17298da6d581SJan Schmidt 	}
17308da6d581SJan Schmidt 
1731a2c8d27eSFilipe Manana 	ulist_free(ctx->refs);
1732a2c8d27eSFilipe Manana 	ctx->refs = NULL;
1733a2c8d27eSFilipe Manana 	ctx->bytenr = orig_bytenr;
1734a2c8d27eSFilipe Manana 	ctx->ignore_extent_item_pos = orig_ignore_extent_item_pos;
1735a2c8d27eSFilipe Manana 
1736a2c8d27eSFilipe Manana 	return ret;
17378da6d581SJan Schmidt }
17388da6d581SJan Schmidt 
1739a2c8d27eSFilipe Manana int btrfs_find_all_roots(struct btrfs_backref_walk_ctx *ctx,
1740c7bcbb21SFilipe Manana 			 bool skip_commit_root_sem)
17419e351cc8SJosef Bacik {
17429e351cc8SJosef Bacik 	int ret;
17439e351cc8SJosef Bacik 
1744a2c8d27eSFilipe Manana 	if (!ctx->trans && !skip_commit_root_sem)
1745a2c8d27eSFilipe Manana 		down_read(&ctx->fs_info->commit_root_sem);
1746a2c8d27eSFilipe Manana 	ret = btrfs_find_all_roots_safe(ctx);
1747a2c8d27eSFilipe Manana 	if (!ctx->trans && !skip_commit_root_sem)
1748a2c8d27eSFilipe Manana 		up_read(&ctx->fs_info->commit_root_sem);
17499e351cc8SJosef Bacik 	return ret;
17509e351cc8SJosef Bacik }
17519e351cc8SJosef Bacik 
175284a7949dSFilipe Manana struct btrfs_backref_share_check_ctx *btrfs_alloc_backref_share_check_ctx(void)
175384a7949dSFilipe Manana {
175484a7949dSFilipe Manana 	struct btrfs_backref_share_check_ctx *ctx;
175584a7949dSFilipe Manana 
175684a7949dSFilipe Manana 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
175784a7949dSFilipe Manana 	if (!ctx)
175884a7949dSFilipe Manana 		return NULL;
175984a7949dSFilipe Manana 
176084a7949dSFilipe Manana 	ulist_init(&ctx->refs);
176184a7949dSFilipe Manana 
176284a7949dSFilipe Manana 	return ctx;
176384a7949dSFilipe Manana }
176484a7949dSFilipe Manana 
176584a7949dSFilipe Manana void btrfs_free_backref_share_ctx(struct btrfs_backref_share_check_ctx *ctx)
176684a7949dSFilipe Manana {
176784a7949dSFilipe Manana 	if (!ctx)
176884a7949dSFilipe Manana 		return;
176984a7949dSFilipe Manana 
177084a7949dSFilipe Manana 	ulist_release(&ctx->refs);
177184a7949dSFilipe Manana 	kfree(ctx);
177284a7949dSFilipe Manana }
177384a7949dSFilipe Manana 
177412a824dcSFilipe Manana /*
17758eedaddaSFilipe Manana  * Check if a data extent is shared or not.
17766e353e3bSNikolay Borisov  *
1777ceb707daSFilipe Manana  * @inode:       The inode whose extent we are checking.
1778b8f164e3SFilipe Manana  * @bytenr:      Logical bytenr of the extent we are checking.
1779b8f164e3SFilipe Manana  * @extent_gen:  Generation of the extent (file extent item) or 0 if it is
1780b8f164e3SFilipe Manana  *               not known.
178161dbb952SFilipe Manana  * @ctx:         A backref sharedness check context.
17822c2ed5aaSMark Fasheh  *
17838eedaddaSFilipe Manana  * btrfs_is_data_extent_shared uses the backref walking code but will short
17842c2ed5aaSMark Fasheh  * circuit as soon as it finds a root or inode that doesn't match the
17852c2ed5aaSMark Fasheh  * one passed in. This provides a significant performance benefit for
17862c2ed5aaSMark Fasheh  * callers (such as fiemap) which want to know whether the extent is
17872c2ed5aaSMark Fasheh  * shared but do not need a ref count.
17882c2ed5aaSMark Fasheh  *
178903628cdbSFilipe Manana  * This attempts to attach to the running transaction in order to account for
179003628cdbSFilipe Manana  * delayed refs, but continues on even when no running transaction exists.
1791bb739cf0SEdmund Nadolski  *
17922c2ed5aaSMark Fasheh  * Return: 0 if extent is not shared, 1 if it is shared, < 0 on error.
17932c2ed5aaSMark Fasheh  */
1794ceb707daSFilipe Manana int btrfs_is_data_extent_shared(struct btrfs_inode *inode, u64 bytenr,
1795b8f164e3SFilipe Manana 				u64 extent_gen,
179661dbb952SFilipe Manana 				struct btrfs_backref_share_check_ctx *ctx)
1797dc046b10SJosef Bacik {
1798a2c8d27eSFilipe Manana 	struct btrfs_backref_walk_ctx walk_ctx = { 0 };
1799ceb707daSFilipe Manana 	struct btrfs_root *root = inode->root;
1800bb739cf0SEdmund Nadolski 	struct btrfs_fs_info *fs_info = root->fs_info;
1801bb739cf0SEdmund Nadolski 	struct btrfs_trans_handle *trans;
1802dc046b10SJosef Bacik 	struct ulist_iterator uiter;
1803dc046b10SJosef Bacik 	struct ulist_node *node;
1804f3a84ccdSFilipe Manana 	struct btrfs_seq_list elem = BTRFS_SEQ_LIST_INIT(elem);
1805dc046b10SJosef Bacik 	int ret = 0;
18063ec4d323SEdmund Nadolski 	struct share_check shared = {
1807877c1476SFilipe Manana 		.ctx = ctx,
1808877c1476SFilipe Manana 		.root = root,
1809ceb707daSFilipe Manana 		.inum = btrfs_ino(inode),
181073e339e6SFilipe Manana 		.data_bytenr = bytenr,
18116976201fSFilipe Manana 		.data_extent_gen = extent_gen,
18123ec4d323SEdmund Nadolski 		.share_count = 0,
181373e339e6SFilipe Manana 		.self_ref_count = 0,
18144fc7b572SFilipe Manana 		.have_delayed_delete_refs = false,
18153ec4d323SEdmund Nadolski 	};
181612a824dcSFilipe Manana 	int level;
1817dc046b10SJosef Bacik 
181873e339e6SFilipe Manana 	for (int i = 0; i < BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE; i++) {
181973e339e6SFilipe Manana 		if (ctx->prev_extents_cache[i].bytenr == bytenr)
182073e339e6SFilipe Manana 			return ctx->prev_extents_cache[i].is_shared;
182173e339e6SFilipe Manana 	}
182273e339e6SFilipe Manana 
182384a7949dSFilipe Manana 	ulist_init(&ctx->refs);
1824dc046b10SJosef Bacik 
1825a6d155d2SFilipe Manana 	trans = btrfs_join_transaction_nostart(root);
1826bb739cf0SEdmund Nadolski 	if (IS_ERR(trans)) {
182703628cdbSFilipe Manana 		if (PTR_ERR(trans) != -ENOENT && PTR_ERR(trans) != -EROFS) {
182803628cdbSFilipe Manana 			ret = PTR_ERR(trans);
182903628cdbSFilipe Manana 			goto out;
183003628cdbSFilipe Manana 		}
1831bb739cf0SEdmund Nadolski 		trans = NULL;
1832dc046b10SJosef Bacik 		down_read(&fs_info->commit_root_sem);
1833bb739cf0SEdmund Nadolski 	} else {
1834bb739cf0SEdmund Nadolski 		btrfs_get_tree_mod_seq(fs_info, &elem);
1835a2c8d27eSFilipe Manana 		walk_ctx.time_seq = elem.seq;
1836bb739cf0SEdmund Nadolski 	}
1837bb739cf0SEdmund Nadolski 
1838a2c8d27eSFilipe Manana 	walk_ctx.ignore_extent_item_pos = true;
1839a2c8d27eSFilipe Manana 	walk_ctx.trans = trans;
1840a2c8d27eSFilipe Manana 	walk_ctx.fs_info = fs_info;
1841a2c8d27eSFilipe Manana 	walk_ctx.refs = &ctx->refs;
1842a2c8d27eSFilipe Manana 
184312a824dcSFilipe Manana 	/* -1 means we are in the bytenr of the data extent. */
184412a824dcSFilipe Manana 	level = -1;
1845dc046b10SJosef Bacik 	ULIST_ITER_INIT(&uiter);
184661dbb952SFilipe Manana 	ctx->use_path_cache = true;
1847dc046b10SJosef Bacik 	while (1) {
184812a824dcSFilipe Manana 		bool is_shared;
184912a824dcSFilipe Manana 		bool cached;
185012a824dcSFilipe Manana 
1851a2c8d27eSFilipe Manana 		walk_ctx.bytenr = bytenr;
1852a2c8d27eSFilipe Manana 		ret = find_parent_nodes(&walk_ctx, &shared);
1853877c1476SFilipe Manana 		if (ret == BACKREF_FOUND_SHARED ||
1854877c1476SFilipe Manana 		    ret == BACKREF_FOUND_NOT_SHARED) {
1855877c1476SFilipe Manana 			/* If shared must return 1, otherwise return 0. */
1856877c1476SFilipe Manana 			ret = (ret == BACKREF_FOUND_SHARED) ? 1 : 0;
185712a824dcSFilipe Manana 			if (level >= 0)
185861dbb952SFilipe Manana 				store_backref_shared_cache(ctx, root, bytenr,
1859877c1476SFilipe Manana 							   level, ret == 1);
1860dc046b10SJosef Bacik 			break;
1861dc046b10SJosef Bacik 		}
1862dc046b10SJosef Bacik 		if (ret < 0 && ret != -ENOENT)
1863dc046b10SJosef Bacik 			break;
18642c2ed5aaSMark Fasheh 		ret = 0;
1865b8f164e3SFilipe Manana 
186663c84b46SFilipe Manana 		/*
186763c84b46SFilipe Manana 		 * If our data extent was not directly shared (without multiple
186863c84b46SFilipe Manana 		 * reference items), than it might have a single reference item
186963c84b46SFilipe Manana 		 * with a count > 1 for the same offset, which means there are 2
187063c84b46SFilipe Manana 		 * (or more) file extent items that point to the data extent -
187163c84b46SFilipe Manana 		 * this happens when a file extent item needs to be split and
187263c84b46SFilipe Manana 		 * then one item gets moved to another leaf due to a b+tree leaf
187363c84b46SFilipe Manana 		 * split when inserting some item. In this case the file extent
187463c84b46SFilipe Manana 		 * items may be located in different leaves and therefore some
187563c84b46SFilipe Manana 		 * of the leaves may be referenced through shared subtrees while
187663c84b46SFilipe Manana 		 * others are not. Since our extent buffer cache only works for
187763c84b46SFilipe Manana 		 * a single path (by far the most common case and simpler to
187863c84b46SFilipe Manana 		 * deal with), we can not use it if we have multiple leaves
187963c84b46SFilipe Manana 		 * (which implies multiple paths).
188063c84b46SFilipe Manana 		 */
188184a7949dSFilipe Manana 		if (level == -1 && ctx->refs.nnodes > 1)
188261dbb952SFilipe Manana 			ctx->use_path_cache = false;
188363c84b46SFilipe Manana 
188412a824dcSFilipe Manana 		if (level >= 0)
188561dbb952SFilipe Manana 			store_backref_shared_cache(ctx, root, bytenr,
188612a824dcSFilipe Manana 						   level, false);
188784a7949dSFilipe Manana 		node = ulist_next(&ctx->refs, &uiter);
1888dc046b10SJosef Bacik 		if (!node)
1889dc046b10SJosef Bacik 			break;
1890dc046b10SJosef Bacik 		bytenr = node->val;
189112a824dcSFilipe Manana 		level++;
189261dbb952SFilipe Manana 		cached = lookup_backref_shared_cache(ctx, root, bytenr, level,
189312a824dcSFilipe Manana 						     &is_shared);
189412a824dcSFilipe Manana 		if (cached) {
189512a824dcSFilipe Manana 			ret = (is_shared ? 1 : 0);
189612a824dcSFilipe Manana 			break;
189712a824dcSFilipe Manana 		}
189818bf591bSEdmund Nadolski 		shared.share_count = 0;
18994fc7b572SFilipe Manana 		shared.have_delayed_delete_refs = false;
1900dc046b10SJosef Bacik 		cond_resched();
1901dc046b10SJosef Bacik 	}
1902bb739cf0SEdmund Nadolski 
190373e339e6SFilipe Manana 	/*
190473e339e6SFilipe Manana 	 * Cache the sharedness result for the data extent if we know our inode
190573e339e6SFilipe Manana 	 * has more than 1 file extent item that refers to the data extent.
190673e339e6SFilipe Manana 	 */
190773e339e6SFilipe Manana 	if (ret >= 0 && shared.self_ref_count > 1) {
190873e339e6SFilipe Manana 		int slot = ctx->prev_extents_cache_slot;
190973e339e6SFilipe Manana 
191073e339e6SFilipe Manana 		ctx->prev_extents_cache[slot].bytenr = shared.data_bytenr;
191173e339e6SFilipe Manana 		ctx->prev_extents_cache[slot].is_shared = (ret == 1);
191273e339e6SFilipe Manana 
191373e339e6SFilipe Manana 		slot = (slot + 1) % BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE;
191473e339e6SFilipe Manana 		ctx->prev_extents_cache_slot = slot;
191573e339e6SFilipe Manana 	}
191673e339e6SFilipe Manana 
1917bb739cf0SEdmund Nadolski 	if (trans) {
1918dc046b10SJosef Bacik 		btrfs_put_tree_mod_seq(fs_info, &elem);
1919bb739cf0SEdmund Nadolski 		btrfs_end_transaction(trans);
1920bb739cf0SEdmund Nadolski 	} else {
1921dc046b10SJosef Bacik 		up_read(&fs_info->commit_root_sem);
1922bb739cf0SEdmund Nadolski 	}
192303628cdbSFilipe Manana out:
192484a7949dSFilipe Manana 	ulist_release(&ctx->refs);
1925877c1476SFilipe Manana 	ctx->prev_leaf_bytenr = ctx->curr_leaf_bytenr;
1926877c1476SFilipe Manana 
1927dc046b10SJosef Bacik 	return ret;
1928dc046b10SJosef Bacik }
1929dc046b10SJosef Bacik 
1930f186373fSMark Fasheh int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
1931f186373fSMark Fasheh 			  u64 start_off, struct btrfs_path *path,
1932f186373fSMark Fasheh 			  struct btrfs_inode_extref **ret_extref,
1933f186373fSMark Fasheh 			  u64 *found_off)
1934f186373fSMark Fasheh {
1935f186373fSMark Fasheh 	int ret, slot;
1936f186373fSMark Fasheh 	struct btrfs_key key;
1937f186373fSMark Fasheh 	struct btrfs_key found_key;
1938f186373fSMark Fasheh 	struct btrfs_inode_extref *extref;
193973980becSJeff Mahoney 	const struct extent_buffer *leaf;
1940f186373fSMark Fasheh 	unsigned long ptr;
1941f186373fSMark Fasheh 
1942f186373fSMark Fasheh 	key.objectid = inode_objectid;
1943962a298fSDavid Sterba 	key.type = BTRFS_INODE_EXTREF_KEY;
1944f186373fSMark Fasheh 	key.offset = start_off;
1945f186373fSMark Fasheh 
1946f186373fSMark Fasheh 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1947f186373fSMark Fasheh 	if (ret < 0)
1948f186373fSMark Fasheh 		return ret;
1949f186373fSMark Fasheh 
1950f186373fSMark Fasheh 	while (1) {
1951f186373fSMark Fasheh 		leaf = path->nodes[0];
1952f186373fSMark Fasheh 		slot = path->slots[0];
1953f186373fSMark Fasheh 		if (slot >= btrfs_header_nritems(leaf)) {
1954f186373fSMark Fasheh 			/*
1955f186373fSMark Fasheh 			 * If the item at offset is not found,
1956f186373fSMark Fasheh 			 * btrfs_search_slot will point us to the slot
1957f186373fSMark Fasheh 			 * where it should be inserted. In our case
1958f186373fSMark Fasheh 			 * that will be the slot directly before the
1959f186373fSMark Fasheh 			 * next INODE_REF_KEY_V2 item. In the case
1960f186373fSMark Fasheh 			 * that we're pointing to the last slot in a
1961f186373fSMark Fasheh 			 * leaf, we must move one leaf over.
1962f186373fSMark Fasheh 			 */
1963f186373fSMark Fasheh 			ret = btrfs_next_leaf(root, path);
1964f186373fSMark Fasheh 			if (ret) {
1965f186373fSMark Fasheh 				if (ret >= 1)
1966f186373fSMark Fasheh 					ret = -ENOENT;
1967f186373fSMark Fasheh 				break;
1968f186373fSMark Fasheh 			}
1969f186373fSMark Fasheh 			continue;
1970f186373fSMark Fasheh 		}
1971f186373fSMark Fasheh 
1972f186373fSMark Fasheh 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
1973f186373fSMark Fasheh 
1974f186373fSMark Fasheh 		/*
1975f186373fSMark Fasheh 		 * Check that we're still looking at an extended ref key for
1976f186373fSMark Fasheh 		 * this particular objectid. If we have different
1977f186373fSMark Fasheh 		 * objectid or type then there are no more to be found
1978f186373fSMark Fasheh 		 * in the tree and we can exit.
1979f186373fSMark Fasheh 		 */
1980f186373fSMark Fasheh 		ret = -ENOENT;
1981f186373fSMark Fasheh 		if (found_key.objectid != inode_objectid)
1982f186373fSMark Fasheh 			break;
1983962a298fSDavid Sterba 		if (found_key.type != BTRFS_INODE_EXTREF_KEY)
1984f186373fSMark Fasheh 			break;
1985f186373fSMark Fasheh 
1986f186373fSMark Fasheh 		ret = 0;
1987f186373fSMark Fasheh 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1988f186373fSMark Fasheh 		extref = (struct btrfs_inode_extref *)ptr;
1989f186373fSMark Fasheh 		*ret_extref = extref;
1990f186373fSMark Fasheh 		if (found_off)
1991f186373fSMark Fasheh 			*found_off = found_key.offset;
1992f186373fSMark Fasheh 		break;
1993f186373fSMark Fasheh 	}
1994f186373fSMark Fasheh 
1995f186373fSMark Fasheh 	return ret;
1996f186373fSMark Fasheh }
1997f186373fSMark Fasheh 
199848a3b636SEric Sandeen /*
199948a3b636SEric Sandeen  * this iterates to turn a name (from iref/extref) into a full filesystem path.
200048a3b636SEric Sandeen  * Elements of the path are separated by '/' and the path is guaranteed to be
200148a3b636SEric Sandeen  * 0-terminated. the path is only given within the current file system.
200248a3b636SEric Sandeen  * Therefore, it never starts with a '/'. the caller is responsible to provide
200348a3b636SEric Sandeen  * "size" bytes in "dest". the dest buffer will be filled backwards. finally,
200448a3b636SEric Sandeen  * the start point of the resulting string is returned. this pointer is within
200548a3b636SEric Sandeen  * dest, normally.
200648a3b636SEric Sandeen  * in case the path buffer would overflow, the pointer is decremented further
200748a3b636SEric Sandeen  * as if output was written to the buffer, though no more output is actually
200848a3b636SEric Sandeen  * generated. that way, the caller can determine how much space would be
200948a3b636SEric Sandeen  * required for the path to fit into the buffer. in that case, the returned
201048a3b636SEric Sandeen  * value will be smaller than dest. callers must check this!
201148a3b636SEric Sandeen  */
201296b5bd77SJan Schmidt char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
2013d24bec3aSMark Fasheh 			u32 name_len, unsigned long name_off,
2014a542ad1bSJan Schmidt 			struct extent_buffer *eb_in, u64 parent,
2015a542ad1bSJan Schmidt 			char *dest, u32 size)
2016a542ad1bSJan Schmidt {
2017a542ad1bSJan Schmidt 	int slot;
2018a542ad1bSJan Schmidt 	u64 next_inum;
2019a542ad1bSJan Schmidt 	int ret;
2020661bec6bSGabriel de Perthuis 	s64 bytes_left = ((s64)size) - 1;
2021a542ad1bSJan Schmidt 	struct extent_buffer *eb = eb_in;
2022a542ad1bSJan Schmidt 	struct btrfs_key found_key;
2023d24bec3aSMark Fasheh 	struct btrfs_inode_ref *iref;
2024a542ad1bSJan Schmidt 
2025a542ad1bSJan Schmidt 	if (bytes_left >= 0)
2026a542ad1bSJan Schmidt 		dest[bytes_left] = '\0';
2027a542ad1bSJan Schmidt 
2028a542ad1bSJan Schmidt 	while (1) {
2029d24bec3aSMark Fasheh 		bytes_left -= name_len;
2030a542ad1bSJan Schmidt 		if (bytes_left >= 0)
2031a542ad1bSJan Schmidt 			read_extent_buffer(eb, dest + bytes_left,
2032d24bec3aSMark Fasheh 					   name_off, name_len);
2033b916a59aSJan Schmidt 		if (eb != eb_in) {
20340c0fe3b0SFilipe Manana 			if (!path->skip_locking)
2035ac5887c8SJosef Bacik 				btrfs_tree_read_unlock(eb);
2036a542ad1bSJan Schmidt 			free_extent_buffer(eb);
2037b916a59aSJan Schmidt 		}
2038c234a24dSDavid Sterba 		ret = btrfs_find_item(fs_root, path, parent, 0,
2039c234a24dSDavid Sterba 				BTRFS_INODE_REF_KEY, &found_key);
20408f24b496SJan Schmidt 		if (ret > 0)
20418f24b496SJan Schmidt 			ret = -ENOENT;
2042a542ad1bSJan Schmidt 		if (ret)
2043a542ad1bSJan Schmidt 			break;
2044d24bec3aSMark Fasheh 
2045a542ad1bSJan Schmidt 		next_inum = found_key.offset;
2046a542ad1bSJan Schmidt 
2047a542ad1bSJan Schmidt 		/* regular exit ahead */
2048a542ad1bSJan Schmidt 		if (parent == next_inum)
2049a542ad1bSJan Schmidt 			break;
2050a542ad1bSJan Schmidt 
2051a542ad1bSJan Schmidt 		slot = path->slots[0];
2052a542ad1bSJan Schmidt 		eb = path->nodes[0];
2053a542ad1bSJan Schmidt 		/* make sure we can use eb after releasing the path */
2054b916a59aSJan Schmidt 		if (eb != eb_in) {
20550c0fe3b0SFilipe Manana 			path->nodes[0] = NULL;
20560c0fe3b0SFilipe Manana 			path->locks[0] = 0;
2057b916a59aSJan Schmidt 		}
2058a542ad1bSJan Schmidt 		btrfs_release_path(path);
2059a542ad1bSJan Schmidt 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2060d24bec3aSMark Fasheh 
2061d24bec3aSMark Fasheh 		name_len = btrfs_inode_ref_name_len(eb, iref);
2062d24bec3aSMark Fasheh 		name_off = (unsigned long)(iref + 1);
2063d24bec3aSMark Fasheh 
2064a542ad1bSJan Schmidt 		parent = next_inum;
2065a542ad1bSJan Schmidt 		--bytes_left;
2066a542ad1bSJan Schmidt 		if (bytes_left >= 0)
2067a542ad1bSJan Schmidt 			dest[bytes_left] = '/';
2068a542ad1bSJan Schmidt 	}
2069a542ad1bSJan Schmidt 
2070a542ad1bSJan Schmidt 	btrfs_release_path(path);
2071a542ad1bSJan Schmidt 
2072a542ad1bSJan Schmidt 	if (ret)
2073a542ad1bSJan Schmidt 		return ERR_PTR(ret);
2074a542ad1bSJan Schmidt 
2075a542ad1bSJan Schmidt 	return dest + bytes_left;
2076a542ad1bSJan Schmidt }
2077a542ad1bSJan Schmidt 
2078a542ad1bSJan Schmidt /*
2079a542ad1bSJan Schmidt  * this makes the path point to (logical EXTENT_ITEM *)
2080a542ad1bSJan Schmidt  * returns BTRFS_EXTENT_FLAG_DATA for data, BTRFS_EXTENT_FLAG_TREE_BLOCK for
2081a542ad1bSJan Schmidt  * tree blocks and <0 on error.
2082a542ad1bSJan Schmidt  */
2083a542ad1bSJan Schmidt int extent_from_logical(struct btrfs_fs_info *fs_info, u64 logical,
208469917e43SLiu Bo 			struct btrfs_path *path, struct btrfs_key *found_key,
208569917e43SLiu Bo 			u64 *flags_ret)
2086a542ad1bSJan Schmidt {
208729cbcf40SJosef Bacik 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, logical);
2088a542ad1bSJan Schmidt 	int ret;
2089a542ad1bSJan Schmidt 	u64 flags;
2090261c84b6SJosef Bacik 	u64 size = 0;
2091a542ad1bSJan Schmidt 	u32 item_size;
209273980becSJeff Mahoney 	const struct extent_buffer *eb;
2093a542ad1bSJan Schmidt 	struct btrfs_extent_item *ei;
2094a542ad1bSJan Schmidt 	struct btrfs_key key;
2095a542ad1bSJan Schmidt 
2096261c84b6SJosef Bacik 	if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2097261c84b6SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
2098261c84b6SJosef Bacik 	else
2099a542ad1bSJan Schmidt 		key.type = BTRFS_EXTENT_ITEM_KEY;
2100a542ad1bSJan Schmidt 	key.objectid = logical;
2101a542ad1bSJan Schmidt 	key.offset = (u64)-1;
2102a542ad1bSJan Schmidt 
210329cbcf40SJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2104a542ad1bSJan Schmidt 	if (ret < 0)
2105a542ad1bSJan Schmidt 		return ret;
2106a542ad1bSJan Schmidt 
210729cbcf40SJosef Bacik 	ret = btrfs_previous_extent_item(extent_root, path, 0);
2108850a8cdfSWang Shilong 	if (ret) {
2109850a8cdfSWang Shilong 		if (ret > 0)
2110580f0a67SJosef Bacik 			ret = -ENOENT;
2111580f0a67SJosef Bacik 		return ret;
2112580f0a67SJosef Bacik 	}
2113850a8cdfSWang Shilong 	btrfs_item_key_to_cpu(path->nodes[0], found_key, path->slots[0]);
2114261c84b6SJosef Bacik 	if (found_key->type == BTRFS_METADATA_ITEM_KEY)
2115da17066cSJeff Mahoney 		size = fs_info->nodesize;
2116261c84b6SJosef Bacik 	else if (found_key->type == BTRFS_EXTENT_ITEM_KEY)
2117261c84b6SJosef Bacik 		size = found_key->offset;
2118261c84b6SJosef Bacik 
2119580f0a67SJosef Bacik 	if (found_key->objectid > logical ||
2120261c84b6SJosef Bacik 	    found_key->objectid + size <= logical) {
2121ab8d0fc4SJeff Mahoney 		btrfs_debug(fs_info,
2122ab8d0fc4SJeff Mahoney 			"logical %llu is not within any extent", logical);
2123a542ad1bSJan Schmidt 		return -ENOENT;
21244692cf58SJan Schmidt 	}
2125a542ad1bSJan Schmidt 
2126a542ad1bSJan Schmidt 	eb = path->nodes[0];
21273212fa14SJosef Bacik 	item_size = btrfs_item_size(eb, path->slots[0]);
2128a542ad1bSJan Schmidt 	BUG_ON(item_size < sizeof(*ei));
2129a542ad1bSJan Schmidt 
2130a542ad1bSJan Schmidt 	ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
2131a542ad1bSJan Schmidt 	flags = btrfs_extent_flags(eb, ei);
2132a542ad1bSJan Schmidt 
2133ab8d0fc4SJeff Mahoney 	btrfs_debug(fs_info,
2134ab8d0fc4SJeff Mahoney 		"logical %llu is at position %llu within the extent (%llu EXTENT_ITEM %llu) flags %#llx size %u",
2135c1c9ff7cSGeert Uytterhoeven 		 logical, logical - found_key->objectid, found_key->objectid,
2136c1c9ff7cSGeert Uytterhoeven 		 found_key->offset, flags, item_size);
213769917e43SLiu Bo 
213869917e43SLiu Bo 	WARN_ON(!flags_ret);
213969917e43SLiu Bo 	if (flags_ret) {
2140a542ad1bSJan Schmidt 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
214169917e43SLiu Bo 			*flags_ret = BTRFS_EXTENT_FLAG_TREE_BLOCK;
214269917e43SLiu Bo 		else if (flags & BTRFS_EXTENT_FLAG_DATA)
214369917e43SLiu Bo 			*flags_ret = BTRFS_EXTENT_FLAG_DATA;
214469917e43SLiu Bo 		else
2145290342f6SArnd Bergmann 			BUG();
214669917e43SLiu Bo 		return 0;
214769917e43SLiu Bo 	}
2148a542ad1bSJan Schmidt 
2149a542ad1bSJan Schmidt 	return -EIO;
2150a542ad1bSJan Schmidt }
2151a542ad1bSJan Schmidt 
2152a542ad1bSJan Schmidt /*
2153a542ad1bSJan Schmidt  * helper function to iterate extent inline refs. ptr must point to a 0 value
2154a542ad1bSJan Schmidt  * for the first call and may be modified. it is used to track state.
2155a542ad1bSJan Schmidt  * if more refs exist, 0 is returned and the next call to
2156e0c476b1SJeff Mahoney  * get_extent_inline_ref must pass the modified ptr parameter to get the
2157a542ad1bSJan Schmidt  * next ref. after the last ref was processed, 1 is returned.
2158a542ad1bSJan Schmidt  * returns <0 on error
2159a542ad1bSJan Schmidt  */
2160e0c476b1SJeff Mahoney static int get_extent_inline_ref(unsigned long *ptr,
216173980becSJeff Mahoney 				 const struct extent_buffer *eb,
216273980becSJeff Mahoney 				 const struct btrfs_key *key,
216373980becSJeff Mahoney 				 const struct btrfs_extent_item *ei,
216473980becSJeff Mahoney 				 u32 item_size,
2165a542ad1bSJan Schmidt 				 struct btrfs_extent_inline_ref **out_eiref,
2166a542ad1bSJan Schmidt 				 int *out_type)
2167a542ad1bSJan Schmidt {
2168a542ad1bSJan Schmidt 	unsigned long end;
2169a542ad1bSJan Schmidt 	u64 flags;
2170a542ad1bSJan Schmidt 	struct btrfs_tree_block_info *info;
2171a542ad1bSJan Schmidt 
2172a542ad1bSJan Schmidt 	if (!*ptr) {
2173a542ad1bSJan Schmidt 		/* first call */
2174a542ad1bSJan Schmidt 		flags = btrfs_extent_flags(eb, ei);
2175a542ad1bSJan Schmidt 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
21766eda71d0SLiu Bo 			if (key->type == BTRFS_METADATA_ITEM_KEY) {
21776eda71d0SLiu Bo 				/* a skinny metadata extent */
21786eda71d0SLiu Bo 				*out_eiref =
21796eda71d0SLiu Bo 				     (struct btrfs_extent_inline_ref *)(ei + 1);
21806eda71d0SLiu Bo 			} else {
21816eda71d0SLiu Bo 				WARN_ON(key->type != BTRFS_EXTENT_ITEM_KEY);
2182a542ad1bSJan Schmidt 				info = (struct btrfs_tree_block_info *)(ei + 1);
2183a542ad1bSJan Schmidt 				*out_eiref =
2184a542ad1bSJan Schmidt 				   (struct btrfs_extent_inline_ref *)(info + 1);
21856eda71d0SLiu Bo 			}
2186a542ad1bSJan Schmidt 		} else {
2187a542ad1bSJan Schmidt 			*out_eiref = (struct btrfs_extent_inline_ref *)(ei + 1);
2188a542ad1bSJan Schmidt 		}
2189a542ad1bSJan Schmidt 		*ptr = (unsigned long)*out_eiref;
2190cd857dd6SLiu Bo 		if ((unsigned long)(*ptr) >= (unsigned long)ei + item_size)
2191a542ad1bSJan Schmidt 			return -ENOENT;
2192a542ad1bSJan Schmidt 	}
2193a542ad1bSJan Schmidt 
2194a542ad1bSJan Schmidt 	end = (unsigned long)ei + item_size;
21956eda71d0SLiu Bo 	*out_eiref = (struct btrfs_extent_inline_ref *)(*ptr);
21963de28d57SLiu Bo 	*out_type = btrfs_get_extent_inline_ref_type(eb, *out_eiref,
21973de28d57SLiu Bo 						     BTRFS_REF_TYPE_ANY);
21983de28d57SLiu Bo 	if (*out_type == BTRFS_REF_TYPE_INVALID)
2199af431dcbSSu Yue 		return -EUCLEAN;
2200a542ad1bSJan Schmidt 
2201a542ad1bSJan Schmidt 	*ptr += btrfs_extent_inline_ref_size(*out_type);
2202a542ad1bSJan Schmidt 	WARN_ON(*ptr > end);
2203a542ad1bSJan Schmidt 	if (*ptr == end)
2204a542ad1bSJan Schmidt 		return 1; /* last */
2205a542ad1bSJan Schmidt 
2206a542ad1bSJan Schmidt 	return 0;
2207a542ad1bSJan Schmidt }
2208a542ad1bSJan Schmidt 
2209a542ad1bSJan Schmidt /*
2210a542ad1bSJan Schmidt  * reads the tree block backref for an extent. tree level and root are returned
2211a542ad1bSJan Schmidt  * through out_level and out_root. ptr must point to a 0 value for the first
2212e0c476b1SJeff Mahoney  * call and may be modified (see get_extent_inline_ref comment).
2213a542ad1bSJan Schmidt  * returns 0 if data was provided, 1 if there was no more data to provide or
2214a542ad1bSJan Schmidt  * <0 on error.
2215a542ad1bSJan Schmidt  */
2216a542ad1bSJan Schmidt int tree_backref_for_extent(unsigned long *ptr, struct extent_buffer *eb,
22176eda71d0SLiu Bo 			    struct btrfs_key *key, struct btrfs_extent_item *ei,
22186eda71d0SLiu Bo 			    u32 item_size, u64 *out_root, u8 *out_level)
2219a542ad1bSJan Schmidt {
2220a542ad1bSJan Schmidt 	int ret;
2221a542ad1bSJan Schmidt 	int type;
2222a542ad1bSJan Schmidt 	struct btrfs_extent_inline_ref *eiref;
2223a542ad1bSJan Schmidt 
2224a542ad1bSJan Schmidt 	if (*ptr == (unsigned long)-1)
2225a542ad1bSJan Schmidt 		return 1;
2226a542ad1bSJan Schmidt 
2227a542ad1bSJan Schmidt 	while (1) {
2228e0c476b1SJeff Mahoney 		ret = get_extent_inline_ref(ptr, eb, key, ei, item_size,
2229a542ad1bSJan Schmidt 					      &eiref, &type);
2230a542ad1bSJan Schmidt 		if (ret < 0)
2231a542ad1bSJan Schmidt 			return ret;
2232a542ad1bSJan Schmidt 
2233a542ad1bSJan Schmidt 		if (type == BTRFS_TREE_BLOCK_REF_KEY ||
2234a542ad1bSJan Schmidt 		    type == BTRFS_SHARED_BLOCK_REF_KEY)
2235a542ad1bSJan Schmidt 			break;
2236a542ad1bSJan Schmidt 
2237a542ad1bSJan Schmidt 		if (ret == 1)
2238a542ad1bSJan Schmidt 			return 1;
2239a542ad1bSJan Schmidt 	}
2240a542ad1bSJan Schmidt 
2241a542ad1bSJan Schmidt 	/* we can treat both ref types equally here */
2242a542ad1bSJan Schmidt 	*out_root = btrfs_extent_inline_ref_offset(eb, eiref);
2243a1317f45SFilipe Manana 
2244a1317f45SFilipe Manana 	if (key->type == BTRFS_EXTENT_ITEM_KEY) {
2245a1317f45SFilipe Manana 		struct btrfs_tree_block_info *info;
2246a1317f45SFilipe Manana 
2247a1317f45SFilipe Manana 		info = (struct btrfs_tree_block_info *)(ei + 1);
2248a542ad1bSJan Schmidt 		*out_level = btrfs_tree_block_level(eb, info);
2249a1317f45SFilipe Manana 	} else {
2250a1317f45SFilipe Manana 		ASSERT(key->type == BTRFS_METADATA_ITEM_KEY);
2251a1317f45SFilipe Manana 		*out_level = (u8)key->offset;
2252a1317f45SFilipe Manana 	}
2253a542ad1bSJan Schmidt 
2254a542ad1bSJan Schmidt 	if (ret == 1)
2255a542ad1bSJan Schmidt 		*ptr = (unsigned long)-1;
2256a542ad1bSJan Schmidt 
2257a542ad1bSJan Schmidt 	return 0;
2258a542ad1bSJan Schmidt }
2259a542ad1bSJan Schmidt 
2260ab8d0fc4SJeff Mahoney static int iterate_leaf_refs(struct btrfs_fs_info *fs_info,
2261ab8d0fc4SJeff Mahoney 			     struct extent_inode_elem *inode_list,
2262976b1908SJan Schmidt 			     u64 root, u64 extent_item_objectid,
22634692cf58SJan Schmidt 			     iterate_extent_inodes_t *iterate, void *ctx)
2264a542ad1bSJan Schmidt {
2265976b1908SJan Schmidt 	struct extent_inode_elem *eie;
22664692cf58SJan Schmidt 	int ret = 0;
2267a542ad1bSJan Schmidt 
2268976b1908SJan Schmidt 	for (eie = inode_list; eie; eie = eie->next) {
2269ab8d0fc4SJeff Mahoney 		btrfs_debug(fs_info,
2270ab8d0fc4SJeff Mahoney 			    "ref for %llu resolved, key (%llu EXTEND_DATA %llu), root %llu",
2271ab8d0fc4SJeff Mahoney 			    extent_item_objectid, eie->inum,
2272ab8d0fc4SJeff Mahoney 			    eie->offset, root);
2273c7499a64SFilipe Manana 		ret = iterate(eie->inum, eie->offset, eie->num_bytes, root, ctx);
22744692cf58SJan Schmidt 		if (ret) {
2275ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_info,
2276ab8d0fc4SJeff Mahoney 				    "stopping iteration for %llu due to ret=%d",
2277976b1908SJan Schmidt 				    extent_item_objectid, ret);
2278a542ad1bSJan Schmidt 			break;
2279a542ad1bSJan Schmidt 		}
2280a542ad1bSJan Schmidt 	}
2281a542ad1bSJan Schmidt 
2282a542ad1bSJan Schmidt 	return ret;
2283a542ad1bSJan Schmidt }
2284a542ad1bSJan Schmidt 
2285a542ad1bSJan Schmidt /*
2286a542ad1bSJan Schmidt  * calls iterate() for every inode that references the extent identified by
22874692cf58SJan Schmidt  * the given parameters.
2288a542ad1bSJan Schmidt  * when the iterator function returns a non-zero value, iteration stops.
2289a542ad1bSJan Schmidt  */
2290a2c8d27eSFilipe Manana int iterate_extent_inodes(struct btrfs_backref_walk_ctx *ctx,
2291a2c8d27eSFilipe Manana 			  bool search_commit_root,
2292a2c8d27eSFilipe Manana 			  iterate_extent_inodes_t *iterate, void *user_ctx)
2293a542ad1bSJan Schmidt {
2294a542ad1bSJan Schmidt 	int ret;
2295a2c8d27eSFilipe Manana 	struct ulist *refs;
2296a2c8d27eSFilipe Manana 	struct ulist_node *ref_node;
2297f3a84ccdSFilipe Manana 	struct btrfs_seq_list seq_elem = BTRFS_SEQ_LIST_INIT(seq_elem);
2298cd1b413cSJan Schmidt 	struct ulist_iterator ref_uiter;
2299a542ad1bSJan Schmidt 
2300a2c8d27eSFilipe Manana 	btrfs_debug(ctx->fs_info, "resolving all inodes for extent %llu",
2301a2c8d27eSFilipe Manana 		    ctx->bytenr);
2302a2c8d27eSFilipe Manana 
2303a2c8d27eSFilipe Manana 	ASSERT(ctx->trans == NULL);
23041baea6f1SFilipe Manana 	ASSERT(ctx->roots == NULL);
23051baea6f1SFilipe Manana 
2306da61d31aSJosef Bacik 	if (!search_commit_root) {
2307a2c8d27eSFilipe Manana 		struct btrfs_trans_handle *trans;
2308a2c8d27eSFilipe Manana 
2309a2c8d27eSFilipe Manana 		trans = btrfs_attach_transaction(ctx->fs_info->tree_root);
2310bfc61c36SFilipe Manana 		if (IS_ERR(trans)) {
2311bfc61c36SFilipe Manana 			if (PTR_ERR(trans) != -ENOENT &&
2312*66d04209SFilipe Manana 			    PTR_ERR(trans) != -EROFS)
23137a3ae2f8SJan Schmidt 				return PTR_ERR(trans);
2314bfc61c36SFilipe Manana 			trans = NULL;
23157a3ae2f8SJan Schmidt 		}
2316a2c8d27eSFilipe Manana 		ctx->trans = trans;
2317bfc61c36SFilipe Manana 	}
2318bfc61c36SFilipe Manana 
2319a2c8d27eSFilipe Manana 	if (ctx->trans) {
2320a2c8d27eSFilipe Manana 		btrfs_get_tree_mod_seq(ctx->fs_info, &seq_elem);
2321a2c8d27eSFilipe Manana 		ctx->time_seq = seq_elem.seq;
2322a2c8d27eSFilipe Manana 	} else {
2323a2c8d27eSFilipe Manana 		down_read(&ctx->fs_info->commit_root_sem);
2324a2c8d27eSFilipe Manana 	}
23254692cf58SJan Schmidt 
2326a2c8d27eSFilipe Manana 	ret = btrfs_find_all_leafs(ctx);
23274692cf58SJan Schmidt 	if (ret)
23284692cf58SJan Schmidt 		goto out;
2329a2c8d27eSFilipe Manana 	refs = ctx->refs;
2330a2c8d27eSFilipe Manana 	ctx->refs = NULL;
23314692cf58SJan Schmidt 
2332cd1b413cSJan Schmidt 	ULIST_ITER_INIT(&ref_uiter);
2333cd1b413cSJan Schmidt 	while (!ret && (ref_node = ulist_next(refs, &ref_uiter))) {
2334*66d04209SFilipe Manana 		const u64 leaf_bytenr = ref_node->val;
2335a2c8d27eSFilipe Manana 		struct ulist_node *root_node;
2336a2c8d27eSFilipe Manana 		struct ulist_iterator root_uiter;
2337*66d04209SFilipe Manana 		struct extent_inode_elem *inode_list;
2338a2c8d27eSFilipe Manana 
2339*66d04209SFilipe Manana 		inode_list = (struct extent_inode_elem *)(uintptr_t)ref_node->aux;
2340*66d04209SFilipe Manana 
2341*66d04209SFilipe Manana 		if (ctx->cache_lookup) {
2342*66d04209SFilipe Manana 			const u64 *root_ids;
2343*66d04209SFilipe Manana 			int root_count;
2344*66d04209SFilipe Manana 			bool cached;
2345*66d04209SFilipe Manana 
2346*66d04209SFilipe Manana 			cached = ctx->cache_lookup(leaf_bytenr, ctx->user_ctx,
2347*66d04209SFilipe Manana 						   &root_ids, &root_count);
2348*66d04209SFilipe Manana 			if (cached) {
2349*66d04209SFilipe Manana 				for (int i = 0; i < root_count; i++) {
2350*66d04209SFilipe Manana 					ret = iterate_leaf_refs(ctx->fs_info,
2351*66d04209SFilipe Manana 								inode_list,
2352*66d04209SFilipe Manana 								root_ids[i],
2353*66d04209SFilipe Manana 								leaf_bytenr,
2354*66d04209SFilipe Manana 								iterate,
2355*66d04209SFilipe Manana 								user_ctx);
2356*66d04209SFilipe Manana 					if (ret)
2357*66d04209SFilipe Manana 						break;
2358*66d04209SFilipe Manana 				}
2359*66d04209SFilipe Manana 				continue;
2360*66d04209SFilipe Manana 			}
2361*66d04209SFilipe Manana 		}
2362*66d04209SFilipe Manana 
2363*66d04209SFilipe Manana 		if (!ctx->roots) {
2364*66d04209SFilipe Manana 			ctx->roots = ulist_alloc(GFP_NOFS);
2365*66d04209SFilipe Manana 			if (!ctx->roots) {
2366*66d04209SFilipe Manana 				ret = -ENOMEM;
2367*66d04209SFilipe Manana 				break;
2368*66d04209SFilipe Manana 			}
2369*66d04209SFilipe Manana 		}
2370*66d04209SFilipe Manana 
2371*66d04209SFilipe Manana 		ctx->bytenr = leaf_bytenr;
2372a2c8d27eSFilipe Manana 		ret = btrfs_find_all_roots_safe(ctx);
23734692cf58SJan Schmidt 		if (ret)
2374a542ad1bSJan Schmidt 			break;
2375a2c8d27eSFilipe Manana 
2376*66d04209SFilipe Manana 		if (ctx->cache_store)
2377*66d04209SFilipe Manana 			ctx->cache_store(leaf_bytenr, ctx->roots, ctx->user_ctx);
2378*66d04209SFilipe Manana 
2379cd1b413cSJan Schmidt 		ULIST_ITER_INIT(&root_uiter);
2380a2c8d27eSFilipe Manana 		while (!ret && (root_node = ulist_next(ctx->roots, &root_uiter))) {
2381a2c8d27eSFilipe Manana 			btrfs_debug(ctx->fs_info,
2382ab8d0fc4SJeff Mahoney 				    "root %llu references leaf %llu, data list %#llx",
2383ab8d0fc4SJeff Mahoney 				    root_node->val, ref_node->val,
2384c1c9ff7cSGeert Uytterhoeven 				    ref_node->aux);
2385*66d04209SFilipe Manana 			ret = iterate_leaf_refs(ctx->fs_info, inode_list,
2386a2c8d27eSFilipe Manana 						root_node->val, ctx->bytenr,
2387a2c8d27eSFilipe Manana 						iterate, user_ctx);
23884692cf58SJan Schmidt 		}
23891baea6f1SFilipe Manana 		ulist_reinit(ctx->roots);
2390a542ad1bSJan Schmidt 	}
2391a542ad1bSJan Schmidt 
2392976b1908SJan Schmidt 	free_leaf_list(refs);
23934692cf58SJan Schmidt out:
2394a2c8d27eSFilipe Manana 	if (ctx->trans) {
2395a2c8d27eSFilipe Manana 		btrfs_put_tree_mod_seq(ctx->fs_info, &seq_elem);
2396a2c8d27eSFilipe Manana 		btrfs_end_transaction(ctx->trans);
2397a2c8d27eSFilipe Manana 		ctx->trans = NULL;
23989e351cc8SJosef Bacik 	} else {
2399a2c8d27eSFilipe Manana 		up_read(&ctx->fs_info->commit_root_sem);
24007a3ae2f8SJan Schmidt 	}
24017a3ae2f8SJan Schmidt 
24021baea6f1SFilipe Manana 	ulist_free(ctx->roots);
24031baea6f1SFilipe Manana 	ctx->roots = NULL;
24041baea6f1SFilipe Manana 
2405a542ad1bSJan Schmidt 	return ret;
2406a542ad1bSJan Schmidt }
2407a542ad1bSJan Schmidt 
2408c7499a64SFilipe Manana static int build_ino_list(u64 inum, u64 offset, u64 num_bytes, u64 root, void *ctx)
2409e3059ec0SDavid Sterba {
2410e3059ec0SDavid Sterba 	struct btrfs_data_container *inodes = ctx;
2411e3059ec0SDavid Sterba 	const size_t c = 3 * sizeof(u64);
2412e3059ec0SDavid Sterba 
2413e3059ec0SDavid Sterba 	if (inodes->bytes_left >= c) {
2414e3059ec0SDavid Sterba 		inodes->bytes_left -= c;
2415e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt] = inum;
2416e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt + 1] = offset;
2417e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt + 2] = root;
2418e3059ec0SDavid Sterba 		inodes->elem_cnt += 3;
2419e3059ec0SDavid Sterba 	} else {
2420e3059ec0SDavid Sterba 		inodes->bytes_missing += c - inodes->bytes_left;
2421e3059ec0SDavid Sterba 		inodes->bytes_left = 0;
2422e3059ec0SDavid Sterba 		inodes->elem_missed += 3;
2423e3059ec0SDavid Sterba 	}
2424e3059ec0SDavid Sterba 
2425e3059ec0SDavid Sterba 	return 0;
2426e3059ec0SDavid Sterba }
2427e3059ec0SDavid Sterba 
2428a542ad1bSJan Schmidt int iterate_inodes_from_logical(u64 logical, struct btrfs_fs_info *fs_info,
2429a542ad1bSJan Schmidt 				struct btrfs_path *path,
2430e3059ec0SDavid Sterba 				void *ctx, bool ignore_offset)
2431a542ad1bSJan Schmidt {
2432a2c8d27eSFilipe Manana 	struct btrfs_backref_walk_ctx walk_ctx = { 0 };
2433a542ad1bSJan Schmidt 	int ret;
243469917e43SLiu Bo 	u64 flags = 0;
2435a542ad1bSJan Schmidt 	struct btrfs_key found_key;
24367a3ae2f8SJan Schmidt 	int search_commit_root = path->search_commit_root;
2437a542ad1bSJan Schmidt 
243869917e43SLiu Bo 	ret = extent_from_logical(fs_info, logical, path, &found_key, &flags);
24394692cf58SJan Schmidt 	btrfs_release_path(path);
2440a542ad1bSJan Schmidt 	if (ret < 0)
2441a542ad1bSJan Schmidt 		return ret;
244269917e43SLiu Bo 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
24433627bf45SStefan Behrens 		return -EINVAL;
2444a542ad1bSJan Schmidt 
2445a2c8d27eSFilipe Manana 	walk_ctx.bytenr = found_key.objectid;
24466ce6ba53SFilipe Manana 	if (ignore_offset)
2447a2c8d27eSFilipe Manana 		walk_ctx.ignore_extent_item_pos = true;
24486ce6ba53SFilipe Manana 	else
2449a2c8d27eSFilipe Manana 		walk_ctx.extent_item_pos = logical - found_key.objectid;
2450a2c8d27eSFilipe Manana 	walk_ctx.fs_info = fs_info;
24516ce6ba53SFilipe Manana 
2452a2c8d27eSFilipe Manana 	return iterate_extent_inodes(&walk_ctx, search_commit_root,
24536ce6ba53SFilipe Manana 				     build_ino_list, ctx);
2454a542ad1bSJan Schmidt }
2455a542ad1bSJan Schmidt 
2456ad6240f6SDavid Sterba static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2457875d1daaSDavid Sterba 			 struct extent_buffer *eb, struct inode_fs_paths *ipath);
2458d24bec3aSMark Fasheh 
2459875d1daaSDavid Sterba static int iterate_inode_refs(u64 inum, struct inode_fs_paths *ipath)
2460a542ad1bSJan Schmidt {
2461aefc1eb1SJan Schmidt 	int ret = 0;
2462a542ad1bSJan Schmidt 	int slot;
2463a542ad1bSJan Schmidt 	u32 cur;
2464a542ad1bSJan Schmidt 	u32 len;
2465a542ad1bSJan Schmidt 	u32 name_len;
2466a542ad1bSJan Schmidt 	u64 parent = 0;
2467a542ad1bSJan Schmidt 	int found = 0;
2468875d1daaSDavid Sterba 	struct btrfs_root *fs_root = ipath->fs_root;
2469875d1daaSDavid Sterba 	struct btrfs_path *path = ipath->btrfs_path;
2470a542ad1bSJan Schmidt 	struct extent_buffer *eb;
2471a542ad1bSJan Schmidt 	struct btrfs_inode_ref *iref;
2472a542ad1bSJan Schmidt 	struct btrfs_key found_key;
2473a542ad1bSJan Schmidt 
2474aefc1eb1SJan Schmidt 	while (!ret) {
2475c234a24dSDavid Sterba 		ret = btrfs_find_item(fs_root, path, inum,
2476c234a24dSDavid Sterba 				parent ? parent + 1 : 0, BTRFS_INODE_REF_KEY,
2477a542ad1bSJan Schmidt 				&found_key);
2478c234a24dSDavid Sterba 
2479a542ad1bSJan Schmidt 		if (ret < 0)
2480a542ad1bSJan Schmidt 			break;
2481a542ad1bSJan Schmidt 		if (ret) {
2482a542ad1bSJan Schmidt 			ret = found ? 0 : -ENOENT;
2483a542ad1bSJan Schmidt 			break;
2484a542ad1bSJan Schmidt 		}
2485a542ad1bSJan Schmidt 		++found;
2486a542ad1bSJan Schmidt 
2487a542ad1bSJan Schmidt 		parent = found_key.offset;
2488a542ad1bSJan Schmidt 		slot = path->slots[0];
24893fe81ce2SFilipe David Borba Manana 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
24903fe81ce2SFilipe David Borba Manana 		if (!eb) {
24913fe81ce2SFilipe David Borba Manana 			ret = -ENOMEM;
24923fe81ce2SFilipe David Borba Manana 			break;
24933fe81ce2SFilipe David Borba Manana 		}
2494a542ad1bSJan Schmidt 		btrfs_release_path(path);
2495a542ad1bSJan Schmidt 
2496a542ad1bSJan Schmidt 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2497a542ad1bSJan Schmidt 
24983212fa14SJosef Bacik 		for (cur = 0; cur < btrfs_item_size(eb, slot); cur += len) {
2499a542ad1bSJan Schmidt 			name_len = btrfs_inode_ref_name_len(eb, iref);
2500a542ad1bSJan Schmidt 			/* path must be released before calling iterate()! */
2501ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_root->fs_info,
2502ab8d0fc4SJeff Mahoney 				"following ref at offset %u for inode %llu in tree %llu",
25034fd786e6SMisono Tomohiro 				cur, found_key.objectid,
25044fd786e6SMisono Tomohiro 				fs_root->root_key.objectid);
2505ad6240f6SDavid Sterba 			ret = inode_to_path(parent, name_len,
2506875d1daaSDavid Sterba 				      (unsigned long)(iref + 1), eb, ipath);
2507aefc1eb1SJan Schmidt 			if (ret)
2508a542ad1bSJan Schmidt 				break;
2509a542ad1bSJan Schmidt 			len = sizeof(*iref) + name_len;
2510a542ad1bSJan Schmidt 			iref = (struct btrfs_inode_ref *)((char *)iref + len);
2511a542ad1bSJan Schmidt 		}
2512a542ad1bSJan Schmidt 		free_extent_buffer(eb);
2513a542ad1bSJan Schmidt 	}
2514a542ad1bSJan Schmidt 
2515a542ad1bSJan Schmidt 	btrfs_release_path(path);
2516a542ad1bSJan Schmidt 
2517a542ad1bSJan Schmidt 	return ret;
2518a542ad1bSJan Schmidt }
2519a542ad1bSJan Schmidt 
2520875d1daaSDavid Sterba static int iterate_inode_extrefs(u64 inum, struct inode_fs_paths *ipath)
2521d24bec3aSMark Fasheh {
2522d24bec3aSMark Fasheh 	int ret;
2523d24bec3aSMark Fasheh 	int slot;
2524d24bec3aSMark Fasheh 	u64 offset = 0;
2525d24bec3aSMark Fasheh 	u64 parent;
2526d24bec3aSMark Fasheh 	int found = 0;
2527875d1daaSDavid Sterba 	struct btrfs_root *fs_root = ipath->fs_root;
2528875d1daaSDavid Sterba 	struct btrfs_path *path = ipath->btrfs_path;
2529d24bec3aSMark Fasheh 	struct extent_buffer *eb;
2530d24bec3aSMark Fasheh 	struct btrfs_inode_extref *extref;
2531d24bec3aSMark Fasheh 	u32 item_size;
2532d24bec3aSMark Fasheh 	u32 cur_offset;
2533d24bec3aSMark Fasheh 	unsigned long ptr;
2534d24bec3aSMark Fasheh 
2535d24bec3aSMark Fasheh 	while (1) {
2536d24bec3aSMark Fasheh 		ret = btrfs_find_one_extref(fs_root, inum, offset, path, &extref,
2537d24bec3aSMark Fasheh 					    &offset);
2538d24bec3aSMark Fasheh 		if (ret < 0)
2539d24bec3aSMark Fasheh 			break;
2540d24bec3aSMark Fasheh 		if (ret) {
2541d24bec3aSMark Fasheh 			ret = found ? 0 : -ENOENT;
2542d24bec3aSMark Fasheh 			break;
2543d24bec3aSMark Fasheh 		}
2544d24bec3aSMark Fasheh 		++found;
2545d24bec3aSMark Fasheh 
2546d24bec3aSMark Fasheh 		slot = path->slots[0];
25473fe81ce2SFilipe David Borba Manana 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
25483fe81ce2SFilipe David Borba Manana 		if (!eb) {
25493fe81ce2SFilipe David Borba Manana 			ret = -ENOMEM;
25503fe81ce2SFilipe David Borba Manana 			break;
25513fe81ce2SFilipe David Borba Manana 		}
2552d24bec3aSMark Fasheh 		btrfs_release_path(path);
2553d24bec3aSMark Fasheh 
25543212fa14SJosef Bacik 		item_size = btrfs_item_size(eb, slot);
25552849a854SChris Mason 		ptr = btrfs_item_ptr_offset(eb, slot);
2556d24bec3aSMark Fasheh 		cur_offset = 0;
2557d24bec3aSMark Fasheh 
2558d24bec3aSMark Fasheh 		while (cur_offset < item_size) {
2559d24bec3aSMark Fasheh 			u32 name_len;
2560d24bec3aSMark Fasheh 
2561d24bec3aSMark Fasheh 			extref = (struct btrfs_inode_extref *)(ptr + cur_offset);
2562d24bec3aSMark Fasheh 			parent = btrfs_inode_extref_parent(eb, extref);
2563d24bec3aSMark Fasheh 			name_len = btrfs_inode_extref_name_len(eb, extref);
2564ad6240f6SDavid Sterba 			ret = inode_to_path(parent, name_len,
2565875d1daaSDavid Sterba 				      (unsigned long)&extref->name, eb, ipath);
2566d24bec3aSMark Fasheh 			if (ret)
2567d24bec3aSMark Fasheh 				break;
2568d24bec3aSMark Fasheh 
25692849a854SChris Mason 			cur_offset += btrfs_inode_extref_name_len(eb, extref);
2570d24bec3aSMark Fasheh 			cur_offset += sizeof(*extref);
2571d24bec3aSMark Fasheh 		}
2572d24bec3aSMark Fasheh 		free_extent_buffer(eb);
2573d24bec3aSMark Fasheh 
2574d24bec3aSMark Fasheh 		offset++;
2575d24bec3aSMark Fasheh 	}
2576d24bec3aSMark Fasheh 
2577d24bec3aSMark Fasheh 	btrfs_release_path(path);
2578d24bec3aSMark Fasheh 
2579d24bec3aSMark Fasheh 	return ret;
2580d24bec3aSMark Fasheh }
2581d24bec3aSMark Fasheh 
2582a542ad1bSJan Schmidt /*
2583a542ad1bSJan Schmidt  * returns 0 if the path could be dumped (probably truncated)
2584a542ad1bSJan Schmidt  * returns <0 in case of an error
2585a542ad1bSJan Schmidt  */
2586d24bec3aSMark Fasheh static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2587875d1daaSDavid Sterba 			 struct extent_buffer *eb, struct inode_fs_paths *ipath)
2588a542ad1bSJan Schmidt {
2589a542ad1bSJan Schmidt 	char *fspath;
2590a542ad1bSJan Schmidt 	char *fspath_min;
2591a542ad1bSJan Schmidt 	int i = ipath->fspath->elem_cnt;
2592a542ad1bSJan Schmidt 	const int s_ptr = sizeof(char *);
2593a542ad1bSJan Schmidt 	u32 bytes_left;
2594a542ad1bSJan Schmidt 
2595a542ad1bSJan Schmidt 	bytes_left = ipath->fspath->bytes_left > s_ptr ?
2596a542ad1bSJan Schmidt 					ipath->fspath->bytes_left - s_ptr : 0;
2597a542ad1bSJan Schmidt 
2598740c3d22SChris Mason 	fspath_min = (char *)ipath->fspath->val + (i + 1) * s_ptr;
259996b5bd77SJan Schmidt 	fspath = btrfs_ref_to_path(ipath->fs_root, ipath->btrfs_path, name_len,
260096b5bd77SJan Schmidt 				   name_off, eb, inum, fspath_min, bytes_left);
2601a542ad1bSJan Schmidt 	if (IS_ERR(fspath))
2602a542ad1bSJan Schmidt 		return PTR_ERR(fspath);
2603a542ad1bSJan Schmidt 
2604a542ad1bSJan Schmidt 	if (fspath > fspath_min) {
2605745c4d8eSJeff Mahoney 		ipath->fspath->val[i] = (u64)(unsigned long)fspath;
2606a542ad1bSJan Schmidt 		++ipath->fspath->elem_cnt;
2607a542ad1bSJan Schmidt 		ipath->fspath->bytes_left = fspath - fspath_min;
2608a542ad1bSJan Schmidt 	} else {
2609a542ad1bSJan Schmidt 		++ipath->fspath->elem_missed;
2610a542ad1bSJan Schmidt 		ipath->fspath->bytes_missing += fspath_min - fspath;
2611a542ad1bSJan Schmidt 		ipath->fspath->bytes_left = 0;
2612a542ad1bSJan Schmidt 	}
2613a542ad1bSJan Schmidt 
2614a542ad1bSJan Schmidt 	return 0;
2615a542ad1bSJan Schmidt }
2616a542ad1bSJan Schmidt 
2617a542ad1bSJan Schmidt /*
2618a542ad1bSJan Schmidt  * this dumps all file system paths to the inode into the ipath struct, provided
2619a542ad1bSJan Schmidt  * is has been created large enough. each path is zero-terminated and accessed
2620740c3d22SChris Mason  * from ipath->fspath->val[i].
2621a542ad1bSJan Schmidt  * when it returns, there are ipath->fspath->elem_cnt number of paths available
2622740c3d22SChris Mason  * in ipath->fspath->val[]. when the allocated space wasn't sufficient, the
262301327610SNicholas D Steeves  * number of missed paths is recorded in ipath->fspath->elem_missed, otherwise,
2624a542ad1bSJan Schmidt  * it's zero. ipath->fspath->bytes_missing holds the number of bytes that would
2625a542ad1bSJan Schmidt  * have been needed to return all paths.
2626a542ad1bSJan Schmidt  */
2627a542ad1bSJan Schmidt int paths_from_inode(u64 inum, struct inode_fs_paths *ipath)
2628a542ad1bSJan Schmidt {
2629ad6240f6SDavid Sterba 	int ret;
2630ad6240f6SDavid Sterba 	int found_refs = 0;
2631ad6240f6SDavid Sterba 
2632875d1daaSDavid Sterba 	ret = iterate_inode_refs(inum, ipath);
2633ad6240f6SDavid Sterba 	if (!ret)
2634ad6240f6SDavid Sterba 		++found_refs;
2635ad6240f6SDavid Sterba 	else if (ret != -ENOENT)
2636ad6240f6SDavid Sterba 		return ret;
2637ad6240f6SDavid Sterba 
2638875d1daaSDavid Sterba 	ret = iterate_inode_extrefs(inum, ipath);
2639ad6240f6SDavid Sterba 	if (ret == -ENOENT && found_refs)
2640ad6240f6SDavid Sterba 		return 0;
2641ad6240f6SDavid Sterba 
2642ad6240f6SDavid Sterba 	return ret;
2643a542ad1bSJan Schmidt }
2644a542ad1bSJan Schmidt 
2645a542ad1bSJan Schmidt struct btrfs_data_container *init_data_container(u32 total_bytes)
2646a542ad1bSJan Schmidt {
2647a542ad1bSJan Schmidt 	struct btrfs_data_container *data;
2648a542ad1bSJan Schmidt 	size_t alloc_bytes;
2649a542ad1bSJan Schmidt 
2650a542ad1bSJan Schmidt 	alloc_bytes = max_t(size_t, total_bytes, sizeof(*data));
2651f54de068SDavid Sterba 	data = kvmalloc(alloc_bytes, GFP_KERNEL);
2652a542ad1bSJan Schmidt 	if (!data)
2653a542ad1bSJan Schmidt 		return ERR_PTR(-ENOMEM);
2654a542ad1bSJan Schmidt 
2655a542ad1bSJan Schmidt 	if (total_bytes >= sizeof(*data)) {
2656a542ad1bSJan Schmidt 		data->bytes_left = total_bytes - sizeof(*data);
2657a542ad1bSJan Schmidt 		data->bytes_missing = 0;
2658a542ad1bSJan Schmidt 	} else {
2659a542ad1bSJan Schmidt 		data->bytes_missing = sizeof(*data) - total_bytes;
2660a542ad1bSJan Schmidt 		data->bytes_left = 0;
2661a542ad1bSJan Schmidt 	}
2662a542ad1bSJan Schmidt 
2663a542ad1bSJan Schmidt 	data->elem_cnt = 0;
2664a542ad1bSJan Schmidt 	data->elem_missed = 0;
2665a542ad1bSJan Schmidt 
2666a542ad1bSJan Schmidt 	return data;
2667a542ad1bSJan Schmidt }
2668a542ad1bSJan Schmidt 
2669a542ad1bSJan Schmidt /*
2670a542ad1bSJan Schmidt  * allocates space to return multiple file system paths for an inode.
2671a542ad1bSJan Schmidt  * total_bytes to allocate are passed, note that space usable for actual path
2672a542ad1bSJan Schmidt  * information will be total_bytes - sizeof(struct inode_fs_paths).
2673a542ad1bSJan Schmidt  * the returned pointer must be freed with free_ipath() in the end.
2674a542ad1bSJan Schmidt  */
2675a542ad1bSJan Schmidt struct inode_fs_paths *init_ipath(s32 total_bytes, struct btrfs_root *fs_root,
2676a542ad1bSJan Schmidt 					struct btrfs_path *path)
2677a542ad1bSJan Schmidt {
2678a542ad1bSJan Schmidt 	struct inode_fs_paths *ifp;
2679a542ad1bSJan Schmidt 	struct btrfs_data_container *fspath;
2680a542ad1bSJan Schmidt 
2681a542ad1bSJan Schmidt 	fspath = init_data_container(total_bytes);
2682a542ad1bSJan Schmidt 	if (IS_ERR(fspath))
2683afc6961fSMisono Tomohiro 		return ERR_CAST(fspath);
2684a542ad1bSJan Schmidt 
2685f54de068SDavid Sterba 	ifp = kmalloc(sizeof(*ifp), GFP_KERNEL);
2686a542ad1bSJan Schmidt 	if (!ifp) {
2687f54de068SDavid Sterba 		kvfree(fspath);
2688a542ad1bSJan Schmidt 		return ERR_PTR(-ENOMEM);
2689a542ad1bSJan Schmidt 	}
2690a542ad1bSJan Schmidt 
2691a542ad1bSJan Schmidt 	ifp->btrfs_path = path;
2692a542ad1bSJan Schmidt 	ifp->fspath = fspath;
2693a542ad1bSJan Schmidt 	ifp->fs_root = fs_root;
2694a542ad1bSJan Schmidt 
2695a542ad1bSJan Schmidt 	return ifp;
2696a542ad1bSJan Schmidt }
2697a542ad1bSJan Schmidt 
2698a542ad1bSJan Schmidt void free_ipath(struct inode_fs_paths *ipath)
2699a542ad1bSJan Schmidt {
27004735fb28SJesper Juhl 	if (!ipath)
27014735fb28SJesper Juhl 		return;
2702f54de068SDavid Sterba 	kvfree(ipath->fspath);
2703a542ad1bSJan Schmidt 	kfree(ipath);
2704a542ad1bSJan Schmidt }
2705a37f232bSQu Wenruo 
2706d68194b2SDavid Sterba struct btrfs_backref_iter *btrfs_backref_iter_alloc(struct btrfs_fs_info *fs_info)
2707a37f232bSQu Wenruo {
2708a37f232bSQu Wenruo 	struct btrfs_backref_iter *ret;
2709a37f232bSQu Wenruo 
2710d68194b2SDavid Sterba 	ret = kzalloc(sizeof(*ret), GFP_NOFS);
2711a37f232bSQu Wenruo 	if (!ret)
2712a37f232bSQu Wenruo 		return NULL;
2713a37f232bSQu Wenruo 
2714a37f232bSQu Wenruo 	ret->path = btrfs_alloc_path();
2715c15c2ec0SBoleyn Su 	if (!ret->path) {
2716a37f232bSQu Wenruo 		kfree(ret);
2717a37f232bSQu Wenruo 		return NULL;
2718a37f232bSQu Wenruo 	}
2719a37f232bSQu Wenruo 
2720a37f232bSQu Wenruo 	/* Current backref iterator only supports iteration in commit root */
2721a37f232bSQu Wenruo 	ret->path->search_commit_root = 1;
2722a37f232bSQu Wenruo 	ret->path->skip_locking = 1;
2723a37f232bSQu Wenruo 	ret->fs_info = fs_info;
2724a37f232bSQu Wenruo 
2725a37f232bSQu Wenruo 	return ret;
2726a37f232bSQu Wenruo }
2727a37f232bSQu Wenruo 
2728a37f232bSQu Wenruo int btrfs_backref_iter_start(struct btrfs_backref_iter *iter, u64 bytenr)
2729a37f232bSQu Wenruo {
2730a37f232bSQu Wenruo 	struct btrfs_fs_info *fs_info = iter->fs_info;
273129cbcf40SJosef Bacik 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2732a37f232bSQu Wenruo 	struct btrfs_path *path = iter->path;
2733a37f232bSQu Wenruo 	struct btrfs_extent_item *ei;
2734a37f232bSQu Wenruo 	struct btrfs_key key;
2735a37f232bSQu Wenruo 	int ret;
2736a37f232bSQu Wenruo 
2737a37f232bSQu Wenruo 	key.objectid = bytenr;
2738a37f232bSQu Wenruo 	key.type = BTRFS_METADATA_ITEM_KEY;
2739a37f232bSQu Wenruo 	key.offset = (u64)-1;
2740a37f232bSQu Wenruo 	iter->bytenr = bytenr;
2741a37f232bSQu Wenruo 
274229cbcf40SJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2743a37f232bSQu Wenruo 	if (ret < 0)
2744a37f232bSQu Wenruo 		return ret;
2745a37f232bSQu Wenruo 	if (ret == 0) {
2746a37f232bSQu Wenruo 		ret = -EUCLEAN;
2747a37f232bSQu Wenruo 		goto release;
2748a37f232bSQu Wenruo 	}
2749a37f232bSQu Wenruo 	if (path->slots[0] == 0) {
2750a37f232bSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
2751a37f232bSQu Wenruo 		ret = -EUCLEAN;
2752a37f232bSQu Wenruo 		goto release;
2753a37f232bSQu Wenruo 	}
2754a37f232bSQu Wenruo 	path->slots[0]--;
2755a37f232bSQu Wenruo 
2756a37f232bSQu Wenruo 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2757a37f232bSQu Wenruo 	if ((key.type != BTRFS_EXTENT_ITEM_KEY &&
2758a37f232bSQu Wenruo 	     key.type != BTRFS_METADATA_ITEM_KEY) || key.objectid != bytenr) {
2759a37f232bSQu Wenruo 		ret = -ENOENT;
2760a37f232bSQu Wenruo 		goto release;
2761a37f232bSQu Wenruo 	}
2762a37f232bSQu Wenruo 	memcpy(&iter->cur_key, &key, sizeof(key));
2763a37f232bSQu Wenruo 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2764a37f232bSQu Wenruo 						    path->slots[0]);
2765a37f232bSQu Wenruo 	iter->end_ptr = (u32)(iter->item_ptr +
27663212fa14SJosef Bacik 			btrfs_item_size(path->nodes[0], path->slots[0]));
2767a37f232bSQu Wenruo 	ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
2768a37f232bSQu Wenruo 			    struct btrfs_extent_item);
2769a37f232bSQu Wenruo 
2770a37f232bSQu Wenruo 	/*
2771a37f232bSQu Wenruo 	 * Only support iteration on tree backref yet.
2772a37f232bSQu Wenruo 	 *
2773a37f232bSQu Wenruo 	 * This is an extra precaution for non skinny-metadata, where
2774a37f232bSQu Wenruo 	 * EXTENT_ITEM is also used for tree blocks, that we can only use
2775a37f232bSQu Wenruo 	 * extent flags to determine if it's a tree block.
2776a37f232bSQu Wenruo 	 */
2777a37f232bSQu Wenruo 	if (btrfs_extent_flags(path->nodes[0], ei) & BTRFS_EXTENT_FLAG_DATA) {
2778a37f232bSQu Wenruo 		ret = -ENOTSUPP;
2779a37f232bSQu Wenruo 		goto release;
2780a37f232bSQu Wenruo 	}
2781a37f232bSQu Wenruo 	iter->cur_ptr = (u32)(iter->item_ptr + sizeof(*ei));
2782a37f232bSQu Wenruo 
2783a37f232bSQu Wenruo 	/* If there is no inline backref, go search for keyed backref */
2784a37f232bSQu Wenruo 	if (iter->cur_ptr >= iter->end_ptr) {
278529cbcf40SJosef Bacik 		ret = btrfs_next_item(extent_root, path);
2786a37f232bSQu Wenruo 
2787a37f232bSQu Wenruo 		/* No inline nor keyed ref */
2788a37f232bSQu Wenruo 		if (ret > 0) {
2789a37f232bSQu Wenruo 			ret = -ENOENT;
2790a37f232bSQu Wenruo 			goto release;
2791a37f232bSQu Wenruo 		}
2792a37f232bSQu Wenruo 		if (ret < 0)
2793a37f232bSQu Wenruo 			goto release;
2794a37f232bSQu Wenruo 
2795a37f232bSQu Wenruo 		btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key,
2796a37f232bSQu Wenruo 				path->slots[0]);
2797a37f232bSQu Wenruo 		if (iter->cur_key.objectid != bytenr ||
2798a37f232bSQu Wenruo 		    (iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
2799a37f232bSQu Wenruo 		     iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY)) {
2800a37f232bSQu Wenruo 			ret = -ENOENT;
2801a37f232bSQu Wenruo 			goto release;
2802a37f232bSQu Wenruo 		}
2803a37f232bSQu Wenruo 		iter->cur_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2804a37f232bSQu Wenruo 							   path->slots[0]);
2805a37f232bSQu Wenruo 		iter->item_ptr = iter->cur_ptr;
28063212fa14SJosef Bacik 		iter->end_ptr = (u32)(iter->item_ptr + btrfs_item_size(
2807a37f232bSQu Wenruo 				      path->nodes[0], path->slots[0]));
2808a37f232bSQu Wenruo 	}
2809a37f232bSQu Wenruo 
2810a37f232bSQu Wenruo 	return 0;
2811a37f232bSQu Wenruo release:
2812a37f232bSQu Wenruo 	btrfs_backref_iter_release(iter);
2813a37f232bSQu Wenruo 	return ret;
2814a37f232bSQu Wenruo }
2815c39c2ddcSQu Wenruo 
2816c39c2ddcSQu Wenruo /*
2817c39c2ddcSQu Wenruo  * Go to the next backref item of current bytenr, can be either inlined or
2818c39c2ddcSQu Wenruo  * keyed.
2819c39c2ddcSQu Wenruo  *
2820c39c2ddcSQu Wenruo  * Caller needs to check whether it's inline ref or not by iter->cur_key.
2821c39c2ddcSQu Wenruo  *
2822c39c2ddcSQu Wenruo  * Return 0 if we get next backref without problem.
2823c39c2ddcSQu Wenruo  * Return >0 if there is no extra backref for this bytenr.
2824c39c2ddcSQu Wenruo  * Return <0 if there is something wrong happened.
2825c39c2ddcSQu Wenruo  */
2826c39c2ddcSQu Wenruo int btrfs_backref_iter_next(struct btrfs_backref_iter *iter)
2827c39c2ddcSQu Wenruo {
2828c39c2ddcSQu Wenruo 	struct extent_buffer *eb = btrfs_backref_get_eb(iter);
282929cbcf40SJosef Bacik 	struct btrfs_root *extent_root;
2830c39c2ddcSQu Wenruo 	struct btrfs_path *path = iter->path;
2831c39c2ddcSQu Wenruo 	struct btrfs_extent_inline_ref *iref;
2832c39c2ddcSQu Wenruo 	int ret;
2833c39c2ddcSQu Wenruo 	u32 size;
2834c39c2ddcSQu Wenruo 
2835c39c2ddcSQu Wenruo 	if (btrfs_backref_iter_is_inline_ref(iter)) {
2836c39c2ddcSQu Wenruo 		/* We're still inside the inline refs */
2837c39c2ddcSQu Wenruo 		ASSERT(iter->cur_ptr < iter->end_ptr);
2838c39c2ddcSQu Wenruo 
2839c39c2ddcSQu Wenruo 		if (btrfs_backref_has_tree_block_info(iter)) {
2840c39c2ddcSQu Wenruo 			/* First tree block info */
2841c39c2ddcSQu Wenruo 			size = sizeof(struct btrfs_tree_block_info);
2842c39c2ddcSQu Wenruo 		} else {
2843c39c2ddcSQu Wenruo 			/* Use inline ref type to determine the size */
2844c39c2ddcSQu Wenruo 			int type;
2845c39c2ddcSQu Wenruo 
2846c39c2ddcSQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
2847c39c2ddcSQu Wenruo 				((unsigned long)iter->cur_ptr);
2848c39c2ddcSQu Wenruo 			type = btrfs_extent_inline_ref_type(eb, iref);
2849c39c2ddcSQu Wenruo 
2850c39c2ddcSQu Wenruo 			size = btrfs_extent_inline_ref_size(type);
2851c39c2ddcSQu Wenruo 		}
2852c39c2ddcSQu Wenruo 		iter->cur_ptr += size;
2853c39c2ddcSQu Wenruo 		if (iter->cur_ptr < iter->end_ptr)
2854c39c2ddcSQu Wenruo 			return 0;
2855c39c2ddcSQu Wenruo 
2856c39c2ddcSQu Wenruo 		/* All inline items iterated, fall through */
2857c39c2ddcSQu Wenruo 	}
2858c39c2ddcSQu Wenruo 
2859c39c2ddcSQu Wenruo 	/* We're at keyed items, there is no inline item, go to the next one */
286029cbcf40SJosef Bacik 	extent_root = btrfs_extent_root(iter->fs_info, iter->bytenr);
286129cbcf40SJosef Bacik 	ret = btrfs_next_item(extent_root, iter->path);
2862c39c2ddcSQu Wenruo 	if (ret)
2863c39c2ddcSQu Wenruo 		return ret;
2864c39c2ddcSQu Wenruo 
2865c39c2ddcSQu Wenruo 	btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key, path->slots[0]);
2866c39c2ddcSQu Wenruo 	if (iter->cur_key.objectid != iter->bytenr ||
2867c39c2ddcSQu Wenruo 	    (iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
2868c39c2ddcSQu Wenruo 	     iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY))
2869c39c2ddcSQu Wenruo 		return 1;
2870c39c2ddcSQu Wenruo 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2871c39c2ddcSQu Wenruo 					path->slots[0]);
2872c39c2ddcSQu Wenruo 	iter->cur_ptr = iter->item_ptr;
28733212fa14SJosef Bacik 	iter->end_ptr = iter->item_ptr + (u32)btrfs_item_size(path->nodes[0],
2874c39c2ddcSQu Wenruo 						path->slots[0]);
2875c39c2ddcSQu Wenruo 	return 0;
2876c39c2ddcSQu Wenruo }
2877584fb121SQu Wenruo 
2878584fb121SQu Wenruo void btrfs_backref_init_cache(struct btrfs_fs_info *fs_info,
2879584fb121SQu Wenruo 			      struct btrfs_backref_cache *cache, int is_reloc)
2880584fb121SQu Wenruo {
2881584fb121SQu Wenruo 	int i;
2882584fb121SQu Wenruo 
2883584fb121SQu Wenruo 	cache->rb_root = RB_ROOT;
2884584fb121SQu Wenruo 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
2885584fb121SQu Wenruo 		INIT_LIST_HEAD(&cache->pending[i]);
2886584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->changed);
2887584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->detached);
2888584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->leaves);
2889584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->pending_edge);
2890584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->useless_node);
2891584fb121SQu Wenruo 	cache->fs_info = fs_info;
2892584fb121SQu Wenruo 	cache->is_reloc = is_reloc;
2893584fb121SQu Wenruo }
2894b1818dabSQu Wenruo 
2895b1818dabSQu Wenruo struct btrfs_backref_node *btrfs_backref_alloc_node(
2896b1818dabSQu Wenruo 		struct btrfs_backref_cache *cache, u64 bytenr, int level)
2897b1818dabSQu Wenruo {
2898b1818dabSQu Wenruo 	struct btrfs_backref_node *node;
2899b1818dabSQu Wenruo 
2900b1818dabSQu Wenruo 	ASSERT(level >= 0 && level < BTRFS_MAX_LEVEL);
2901b1818dabSQu Wenruo 	node = kzalloc(sizeof(*node), GFP_NOFS);
2902b1818dabSQu Wenruo 	if (!node)
2903b1818dabSQu Wenruo 		return node;
2904b1818dabSQu Wenruo 
2905b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->list);
2906b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->upper);
2907b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->lower);
2908b1818dabSQu Wenruo 	RB_CLEAR_NODE(&node->rb_node);
2909b1818dabSQu Wenruo 	cache->nr_nodes++;
2910b1818dabSQu Wenruo 	node->level = level;
2911b1818dabSQu Wenruo 	node->bytenr = bytenr;
2912b1818dabSQu Wenruo 
2913b1818dabSQu Wenruo 	return node;
2914b1818dabSQu Wenruo }
291547254d07SQu Wenruo 
291647254d07SQu Wenruo struct btrfs_backref_edge *btrfs_backref_alloc_edge(
291747254d07SQu Wenruo 		struct btrfs_backref_cache *cache)
291847254d07SQu Wenruo {
291947254d07SQu Wenruo 	struct btrfs_backref_edge *edge;
292047254d07SQu Wenruo 
292147254d07SQu Wenruo 	edge = kzalloc(sizeof(*edge), GFP_NOFS);
292247254d07SQu Wenruo 	if (edge)
292347254d07SQu Wenruo 		cache->nr_edges++;
292447254d07SQu Wenruo 	return edge;
292547254d07SQu Wenruo }
2926023acb07SQu Wenruo 
2927023acb07SQu Wenruo /*
2928023acb07SQu Wenruo  * Drop the backref node from cache, also cleaning up all its
2929023acb07SQu Wenruo  * upper edges and any uncached nodes in the path.
2930023acb07SQu Wenruo  *
2931023acb07SQu Wenruo  * This cleanup happens bottom up, thus the node should either
2932023acb07SQu Wenruo  * be the lowest node in the cache or a detached node.
2933023acb07SQu Wenruo  */
2934023acb07SQu Wenruo void btrfs_backref_cleanup_node(struct btrfs_backref_cache *cache,
2935023acb07SQu Wenruo 				struct btrfs_backref_node *node)
2936023acb07SQu Wenruo {
2937023acb07SQu Wenruo 	struct btrfs_backref_node *upper;
2938023acb07SQu Wenruo 	struct btrfs_backref_edge *edge;
2939023acb07SQu Wenruo 
2940023acb07SQu Wenruo 	if (!node)
2941023acb07SQu Wenruo 		return;
2942023acb07SQu Wenruo 
2943023acb07SQu Wenruo 	BUG_ON(!node->lowest && !node->detached);
2944023acb07SQu Wenruo 	while (!list_empty(&node->upper)) {
2945023acb07SQu Wenruo 		edge = list_entry(node->upper.next, struct btrfs_backref_edge,
2946023acb07SQu Wenruo 				  list[LOWER]);
2947023acb07SQu Wenruo 		upper = edge->node[UPPER];
2948023acb07SQu Wenruo 		list_del(&edge->list[LOWER]);
2949023acb07SQu Wenruo 		list_del(&edge->list[UPPER]);
2950023acb07SQu Wenruo 		btrfs_backref_free_edge(cache, edge);
2951023acb07SQu Wenruo 
2952023acb07SQu Wenruo 		/*
2953023acb07SQu Wenruo 		 * Add the node to leaf node list if no other child block
2954023acb07SQu Wenruo 		 * cached.
2955023acb07SQu Wenruo 		 */
2956023acb07SQu Wenruo 		if (list_empty(&upper->lower)) {
2957023acb07SQu Wenruo 			list_add_tail(&upper->lower, &cache->leaves);
2958023acb07SQu Wenruo 			upper->lowest = 1;
2959023acb07SQu Wenruo 		}
2960023acb07SQu Wenruo 	}
2961023acb07SQu Wenruo 
2962023acb07SQu Wenruo 	btrfs_backref_drop_node(cache, node);
2963023acb07SQu Wenruo }
296413fe1bdbSQu Wenruo 
296513fe1bdbSQu Wenruo /*
296613fe1bdbSQu Wenruo  * Release all nodes/edges from current cache
296713fe1bdbSQu Wenruo  */
296813fe1bdbSQu Wenruo void btrfs_backref_release_cache(struct btrfs_backref_cache *cache)
296913fe1bdbSQu Wenruo {
297013fe1bdbSQu Wenruo 	struct btrfs_backref_node *node;
297113fe1bdbSQu Wenruo 	int i;
297213fe1bdbSQu Wenruo 
297313fe1bdbSQu Wenruo 	while (!list_empty(&cache->detached)) {
297413fe1bdbSQu Wenruo 		node = list_entry(cache->detached.next,
297513fe1bdbSQu Wenruo 				  struct btrfs_backref_node, list);
297613fe1bdbSQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
297713fe1bdbSQu Wenruo 	}
297813fe1bdbSQu Wenruo 
297913fe1bdbSQu Wenruo 	while (!list_empty(&cache->leaves)) {
298013fe1bdbSQu Wenruo 		node = list_entry(cache->leaves.next,
298113fe1bdbSQu Wenruo 				  struct btrfs_backref_node, lower);
298213fe1bdbSQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
298313fe1bdbSQu Wenruo 	}
298413fe1bdbSQu Wenruo 
298513fe1bdbSQu Wenruo 	cache->last_trans = 0;
298613fe1bdbSQu Wenruo 
298713fe1bdbSQu Wenruo 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
298813fe1bdbSQu Wenruo 		ASSERT(list_empty(&cache->pending[i]));
298913fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->pending_edge));
299013fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->useless_node));
299113fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->changed));
299213fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->detached));
299313fe1bdbSQu Wenruo 	ASSERT(RB_EMPTY_ROOT(&cache->rb_root));
299413fe1bdbSQu Wenruo 	ASSERT(!cache->nr_nodes);
299513fe1bdbSQu Wenruo 	ASSERT(!cache->nr_edges);
299613fe1bdbSQu Wenruo }
29971b60d2ecSQu Wenruo 
29981b60d2ecSQu Wenruo /*
29991b60d2ecSQu Wenruo  * Handle direct tree backref
30001b60d2ecSQu Wenruo  *
30011b60d2ecSQu Wenruo  * Direct tree backref means, the backref item shows its parent bytenr
30021b60d2ecSQu Wenruo  * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
30031b60d2ecSQu Wenruo  *
30041b60d2ecSQu Wenruo  * @ref_key:	The converted backref key.
30051b60d2ecSQu Wenruo  *		For keyed backref, it's the item key.
30061b60d2ecSQu Wenruo  *		For inlined backref, objectid is the bytenr,
30071b60d2ecSQu Wenruo  *		type is btrfs_inline_ref_type, offset is
30081b60d2ecSQu Wenruo  *		btrfs_inline_ref_offset.
30091b60d2ecSQu Wenruo  */
30101b60d2ecSQu Wenruo static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
30111b60d2ecSQu Wenruo 				      struct btrfs_key *ref_key,
30121b60d2ecSQu Wenruo 				      struct btrfs_backref_node *cur)
30131b60d2ecSQu Wenruo {
30141b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
30151b60d2ecSQu Wenruo 	struct btrfs_backref_node *upper;
30161b60d2ecSQu Wenruo 	struct rb_node *rb_node;
30171b60d2ecSQu Wenruo 
30181b60d2ecSQu Wenruo 	ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
30191b60d2ecSQu Wenruo 
30201b60d2ecSQu Wenruo 	/* Only reloc root uses backref pointing to itself */
30211b60d2ecSQu Wenruo 	if (ref_key->objectid == ref_key->offset) {
30221b60d2ecSQu Wenruo 		struct btrfs_root *root;
30231b60d2ecSQu Wenruo 
30241b60d2ecSQu Wenruo 		cur->is_reloc_root = 1;
30251b60d2ecSQu Wenruo 		/* Only reloc backref cache cares about a specific root */
30261b60d2ecSQu Wenruo 		if (cache->is_reloc) {
30271b60d2ecSQu Wenruo 			root = find_reloc_root(cache->fs_info, cur->bytenr);
3028f78743fbSJosef Bacik 			if (!root)
30291b60d2ecSQu Wenruo 				return -ENOENT;
30301b60d2ecSQu Wenruo 			cur->root = root;
30311b60d2ecSQu Wenruo 		} else {
30321b60d2ecSQu Wenruo 			/*
30331b60d2ecSQu Wenruo 			 * For generic purpose backref cache, reloc root node
30341b60d2ecSQu Wenruo 			 * is useless.
30351b60d2ecSQu Wenruo 			 */
30361b60d2ecSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
30371b60d2ecSQu Wenruo 		}
30381b60d2ecSQu Wenruo 		return 0;
30391b60d2ecSQu Wenruo 	}
30401b60d2ecSQu Wenruo 
30411b60d2ecSQu Wenruo 	edge = btrfs_backref_alloc_edge(cache);
30421b60d2ecSQu Wenruo 	if (!edge)
30431b60d2ecSQu Wenruo 		return -ENOMEM;
30441b60d2ecSQu Wenruo 
30451b60d2ecSQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
30461b60d2ecSQu Wenruo 	if (!rb_node) {
30471b60d2ecSQu Wenruo 		/* Parent node not yet cached */
30481b60d2ecSQu Wenruo 		upper = btrfs_backref_alloc_node(cache, ref_key->offset,
30491b60d2ecSQu Wenruo 					   cur->level + 1);
30501b60d2ecSQu Wenruo 		if (!upper) {
30511b60d2ecSQu Wenruo 			btrfs_backref_free_edge(cache, edge);
30521b60d2ecSQu Wenruo 			return -ENOMEM;
30531b60d2ecSQu Wenruo 		}
30541b60d2ecSQu Wenruo 
30551b60d2ecSQu Wenruo 		/*
30561b60d2ecSQu Wenruo 		 *  Backrefs for the upper level block isn't cached, add the
30571b60d2ecSQu Wenruo 		 *  block to pending list
30581b60d2ecSQu Wenruo 		 */
30591b60d2ecSQu Wenruo 		list_add_tail(&edge->list[UPPER], &cache->pending_edge);
30601b60d2ecSQu Wenruo 	} else {
30611b60d2ecSQu Wenruo 		/* Parent node already cached */
30621b60d2ecSQu Wenruo 		upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
30631b60d2ecSQu Wenruo 		ASSERT(upper->checked);
30641b60d2ecSQu Wenruo 		INIT_LIST_HEAD(&edge->list[UPPER]);
30651b60d2ecSQu Wenruo 	}
30661b60d2ecSQu Wenruo 	btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
30671b60d2ecSQu Wenruo 	return 0;
30681b60d2ecSQu Wenruo }
30691b60d2ecSQu Wenruo 
30701b60d2ecSQu Wenruo /*
30711b60d2ecSQu Wenruo  * Handle indirect tree backref
30721b60d2ecSQu Wenruo  *
30731b60d2ecSQu Wenruo  * Indirect tree backref means, we only know which tree the node belongs to.
30741b60d2ecSQu Wenruo  * We still need to do a tree search to find out the parents. This is for
30751b60d2ecSQu Wenruo  * TREE_BLOCK_REF backref (keyed or inlined).
30761b60d2ecSQu Wenruo  *
30771b60d2ecSQu Wenruo  * @ref_key:	The same as @ref_key in  handle_direct_tree_backref()
30781b60d2ecSQu Wenruo  * @tree_key:	The first key of this tree block.
30791b60d2ecSQu Wenruo  * @path:	A clean (released) path, to avoid allocating path every time
30801b60d2ecSQu Wenruo  *		the function get called.
30811b60d2ecSQu Wenruo  */
30821b60d2ecSQu Wenruo static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
30831b60d2ecSQu Wenruo 					struct btrfs_path *path,
30841b60d2ecSQu Wenruo 					struct btrfs_key *ref_key,
30851b60d2ecSQu Wenruo 					struct btrfs_key *tree_key,
30861b60d2ecSQu Wenruo 					struct btrfs_backref_node *cur)
30871b60d2ecSQu Wenruo {
30881b60d2ecSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
30891b60d2ecSQu Wenruo 	struct btrfs_backref_node *upper;
30901b60d2ecSQu Wenruo 	struct btrfs_backref_node *lower;
30911b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
30921b60d2ecSQu Wenruo 	struct extent_buffer *eb;
30931b60d2ecSQu Wenruo 	struct btrfs_root *root;
30941b60d2ecSQu Wenruo 	struct rb_node *rb_node;
30951b60d2ecSQu Wenruo 	int level;
30961b60d2ecSQu Wenruo 	bool need_check = true;
30971b60d2ecSQu Wenruo 	int ret;
30981b60d2ecSQu Wenruo 
309956e9357aSDavid Sterba 	root = btrfs_get_fs_root(fs_info, ref_key->offset, false);
31001b60d2ecSQu Wenruo 	if (IS_ERR(root))
31011b60d2ecSQu Wenruo 		return PTR_ERR(root);
310292a7cc42SQu Wenruo 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
31031b60d2ecSQu Wenruo 		cur->cowonly = 1;
31041b60d2ecSQu Wenruo 
31051b60d2ecSQu Wenruo 	if (btrfs_root_level(&root->root_item) == cur->level) {
31061b60d2ecSQu Wenruo 		/* Tree root */
31071b60d2ecSQu Wenruo 		ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
3108876de781SQu Wenruo 		/*
3109876de781SQu Wenruo 		 * For reloc backref cache, we may ignore reloc root.  But for
3110876de781SQu Wenruo 		 * general purpose backref cache, we can't rely on
3111876de781SQu Wenruo 		 * btrfs_should_ignore_reloc_root() as it may conflict with
3112876de781SQu Wenruo 		 * current running relocation and lead to missing root.
3113876de781SQu Wenruo 		 *
3114876de781SQu Wenruo 		 * For general purpose backref cache, reloc root detection is
3115876de781SQu Wenruo 		 * completely relying on direct backref (key->offset is parent
3116876de781SQu Wenruo 		 * bytenr), thus only do such check for reloc cache.
3117876de781SQu Wenruo 		 */
3118876de781SQu Wenruo 		if (btrfs_should_ignore_reloc_root(root) && cache->is_reloc) {
31191b60d2ecSQu Wenruo 			btrfs_put_root(root);
31201b60d2ecSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
31211b60d2ecSQu Wenruo 		} else {
31221b60d2ecSQu Wenruo 			cur->root = root;
31231b60d2ecSQu Wenruo 		}
31241b60d2ecSQu Wenruo 		return 0;
31251b60d2ecSQu Wenruo 	}
31261b60d2ecSQu Wenruo 
31271b60d2ecSQu Wenruo 	level = cur->level + 1;
31281b60d2ecSQu Wenruo 
31291b60d2ecSQu Wenruo 	/* Search the tree to find parent blocks referring to the block */
31301b60d2ecSQu Wenruo 	path->search_commit_root = 1;
31311b60d2ecSQu Wenruo 	path->skip_locking = 1;
31321b60d2ecSQu Wenruo 	path->lowest_level = level;
31331b60d2ecSQu Wenruo 	ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
31341b60d2ecSQu Wenruo 	path->lowest_level = 0;
31351b60d2ecSQu Wenruo 	if (ret < 0) {
31361b60d2ecSQu Wenruo 		btrfs_put_root(root);
31371b60d2ecSQu Wenruo 		return ret;
31381b60d2ecSQu Wenruo 	}
31391b60d2ecSQu Wenruo 	if (ret > 0 && path->slots[level] > 0)
31401b60d2ecSQu Wenruo 		path->slots[level]--;
31411b60d2ecSQu Wenruo 
31421b60d2ecSQu Wenruo 	eb = path->nodes[level];
31431b60d2ecSQu Wenruo 	if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
31441b60d2ecSQu Wenruo 		btrfs_err(fs_info,
31451b60d2ecSQu Wenruo "couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
31461b60d2ecSQu Wenruo 			  cur->bytenr, level - 1, root->root_key.objectid,
31471b60d2ecSQu Wenruo 			  tree_key->objectid, tree_key->type, tree_key->offset);
31481b60d2ecSQu Wenruo 		btrfs_put_root(root);
31491b60d2ecSQu Wenruo 		ret = -ENOENT;
31501b60d2ecSQu Wenruo 		goto out;
31511b60d2ecSQu Wenruo 	}
31521b60d2ecSQu Wenruo 	lower = cur;
31531b60d2ecSQu Wenruo 
31541b60d2ecSQu Wenruo 	/* Add all nodes and edges in the path */
31551b60d2ecSQu Wenruo 	for (; level < BTRFS_MAX_LEVEL; level++) {
31561b60d2ecSQu Wenruo 		if (!path->nodes[level]) {
31571b60d2ecSQu Wenruo 			ASSERT(btrfs_root_bytenr(&root->root_item) ==
31581b60d2ecSQu Wenruo 			       lower->bytenr);
3159876de781SQu Wenruo 			/* Same as previous should_ignore_reloc_root() call */
3160876de781SQu Wenruo 			if (btrfs_should_ignore_reloc_root(root) &&
3161876de781SQu Wenruo 			    cache->is_reloc) {
31621b60d2ecSQu Wenruo 				btrfs_put_root(root);
31631b60d2ecSQu Wenruo 				list_add(&lower->list, &cache->useless_node);
31641b60d2ecSQu Wenruo 			} else {
31651b60d2ecSQu Wenruo 				lower->root = root;
31661b60d2ecSQu Wenruo 			}
31671b60d2ecSQu Wenruo 			break;
31681b60d2ecSQu Wenruo 		}
31691b60d2ecSQu Wenruo 
31701b60d2ecSQu Wenruo 		edge = btrfs_backref_alloc_edge(cache);
31711b60d2ecSQu Wenruo 		if (!edge) {
31721b60d2ecSQu Wenruo 			btrfs_put_root(root);
31731b60d2ecSQu Wenruo 			ret = -ENOMEM;
31741b60d2ecSQu Wenruo 			goto out;
31751b60d2ecSQu Wenruo 		}
31761b60d2ecSQu Wenruo 
31771b60d2ecSQu Wenruo 		eb = path->nodes[level];
31781b60d2ecSQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root, eb->start);
31791b60d2ecSQu Wenruo 		if (!rb_node) {
31801b60d2ecSQu Wenruo 			upper = btrfs_backref_alloc_node(cache, eb->start,
31811b60d2ecSQu Wenruo 							 lower->level + 1);
31821b60d2ecSQu Wenruo 			if (!upper) {
31831b60d2ecSQu Wenruo 				btrfs_put_root(root);
31841b60d2ecSQu Wenruo 				btrfs_backref_free_edge(cache, edge);
31851b60d2ecSQu Wenruo 				ret = -ENOMEM;
31861b60d2ecSQu Wenruo 				goto out;
31871b60d2ecSQu Wenruo 			}
31881b60d2ecSQu Wenruo 			upper->owner = btrfs_header_owner(eb);
318992a7cc42SQu Wenruo 			if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
31901b60d2ecSQu Wenruo 				upper->cowonly = 1;
31911b60d2ecSQu Wenruo 
31921b60d2ecSQu Wenruo 			/*
31931b60d2ecSQu Wenruo 			 * If we know the block isn't shared we can avoid
31941b60d2ecSQu Wenruo 			 * checking its backrefs.
31951b60d2ecSQu Wenruo 			 */
31961b60d2ecSQu Wenruo 			if (btrfs_block_can_be_shared(root, eb))
31971b60d2ecSQu Wenruo 				upper->checked = 0;
31981b60d2ecSQu Wenruo 			else
31991b60d2ecSQu Wenruo 				upper->checked = 1;
32001b60d2ecSQu Wenruo 
32011b60d2ecSQu Wenruo 			/*
32021b60d2ecSQu Wenruo 			 * Add the block to pending list if we need to check its
32031b60d2ecSQu Wenruo 			 * backrefs, we only do this once while walking up a
32041b60d2ecSQu Wenruo 			 * tree as we will catch anything else later on.
32051b60d2ecSQu Wenruo 			 */
32061b60d2ecSQu Wenruo 			if (!upper->checked && need_check) {
32071b60d2ecSQu Wenruo 				need_check = false;
32081b60d2ecSQu Wenruo 				list_add_tail(&edge->list[UPPER],
32091b60d2ecSQu Wenruo 					      &cache->pending_edge);
32101b60d2ecSQu Wenruo 			} else {
32111b60d2ecSQu Wenruo 				if (upper->checked)
32121b60d2ecSQu Wenruo 					need_check = true;
32131b60d2ecSQu Wenruo 				INIT_LIST_HEAD(&edge->list[UPPER]);
32141b60d2ecSQu Wenruo 			}
32151b60d2ecSQu Wenruo 		} else {
32161b60d2ecSQu Wenruo 			upper = rb_entry(rb_node, struct btrfs_backref_node,
32171b60d2ecSQu Wenruo 					 rb_node);
32181b60d2ecSQu Wenruo 			ASSERT(upper->checked);
32191b60d2ecSQu Wenruo 			INIT_LIST_HEAD(&edge->list[UPPER]);
32201b60d2ecSQu Wenruo 			if (!upper->owner)
32211b60d2ecSQu Wenruo 				upper->owner = btrfs_header_owner(eb);
32221b60d2ecSQu Wenruo 		}
32231b60d2ecSQu Wenruo 		btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
32241b60d2ecSQu Wenruo 
32251b60d2ecSQu Wenruo 		if (rb_node) {
32261b60d2ecSQu Wenruo 			btrfs_put_root(root);
32271b60d2ecSQu Wenruo 			break;
32281b60d2ecSQu Wenruo 		}
32291b60d2ecSQu Wenruo 		lower = upper;
32301b60d2ecSQu Wenruo 		upper = NULL;
32311b60d2ecSQu Wenruo 	}
32321b60d2ecSQu Wenruo out:
32331b60d2ecSQu Wenruo 	btrfs_release_path(path);
32341b60d2ecSQu Wenruo 	return ret;
32351b60d2ecSQu Wenruo }
32361b60d2ecSQu Wenruo 
32371b60d2ecSQu Wenruo /*
32381b60d2ecSQu Wenruo  * Add backref node @cur into @cache.
32391b60d2ecSQu Wenruo  *
32401b60d2ecSQu Wenruo  * NOTE: Even if the function returned 0, @cur is not yet cached as its upper
32411b60d2ecSQu Wenruo  *	 links aren't yet bi-directional. Needs to finish such links.
3242fc997ed0SQu Wenruo  *	 Use btrfs_backref_finish_upper_links() to finish such linkage.
32431b60d2ecSQu Wenruo  *
32441b60d2ecSQu Wenruo  * @path:	Released path for indirect tree backref lookup
32451b60d2ecSQu Wenruo  * @iter:	Released backref iter for extent tree search
32461b60d2ecSQu Wenruo  * @node_key:	The first key of the tree block
32471b60d2ecSQu Wenruo  */
32481b60d2ecSQu Wenruo int btrfs_backref_add_tree_node(struct btrfs_backref_cache *cache,
32491b60d2ecSQu Wenruo 				struct btrfs_path *path,
32501b60d2ecSQu Wenruo 				struct btrfs_backref_iter *iter,
32511b60d2ecSQu Wenruo 				struct btrfs_key *node_key,
32521b60d2ecSQu Wenruo 				struct btrfs_backref_node *cur)
32531b60d2ecSQu Wenruo {
32541b60d2ecSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
32551b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
32561b60d2ecSQu Wenruo 	struct btrfs_backref_node *exist;
32571b60d2ecSQu Wenruo 	int ret;
32581b60d2ecSQu Wenruo 
32591b60d2ecSQu Wenruo 	ret = btrfs_backref_iter_start(iter, cur->bytenr);
32601b60d2ecSQu Wenruo 	if (ret < 0)
32611b60d2ecSQu Wenruo 		return ret;
32621b60d2ecSQu Wenruo 	/*
32631b60d2ecSQu Wenruo 	 * We skip the first btrfs_tree_block_info, as we don't use the key
32641b60d2ecSQu Wenruo 	 * stored in it, but fetch it from the tree block
32651b60d2ecSQu Wenruo 	 */
32661b60d2ecSQu Wenruo 	if (btrfs_backref_has_tree_block_info(iter)) {
32671b60d2ecSQu Wenruo 		ret = btrfs_backref_iter_next(iter);
32681b60d2ecSQu Wenruo 		if (ret < 0)
32691b60d2ecSQu Wenruo 			goto out;
32701b60d2ecSQu Wenruo 		/* No extra backref? This means the tree block is corrupted */
32711b60d2ecSQu Wenruo 		if (ret > 0) {
32721b60d2ecSQu Wenruo 			ret = -EUCLEAN;
32731b60d2ecSQu Wenruo 			goto out;
32741b60d2ecSQu Wenruo 		}
32751b60d2ecSQu Wenruo 	}
32761b60d2ecSQu Wenruo 	WARN_ON(cur->checked);
32771b60d2ecSQu Wenruo 	if (!list_empty(&cur->upper)) {
32781b60d2ecSQu Wenruo 		/*
32791b60d2ecSQu Wenruo 		 * The backref was added previously when processing backref of
32801b60d2ecSQu Wenruo 		 * type BTRFS_TREE_BLOCK_REF_KEY
32811b60d2ecSQu Wenruo 		 */
32821b60d2ecSQu Wenruo 		ASSERT(list_is_singular(&cur->upper));
32831b60d2ecSQu Wenruo 		edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
32841b60d2ecSQu Wenruo 				  list[LOWER]);
32851b60d2ecSQu Wenruo 		ASSERT(list_empty(&edge->list[UPPER]));
32861b60d2ecSQu Wenruo 		exist = edge->node[UPPER];
32871b60d2ecSQu Wenruo 		/*
32881b60d2ecSQu Wenruo 		 * Add the upper level block to pending list if we need check
32891b60d2ecSQu Wenruo 		 * its backrefs
32901b60d2ecSQu Wenruo 		 */
32911b60d2ecSQu Wenruo 		if (!exist->checked)
32921b60d2ecSQu Wenruo 			list_add_tail(&edge->list[UPPER], &cache->pending_edge);
32931b60d2ecSQu Wenruo 	} else {
32941b60d2ecSQu Wenruo 		exist = NULL;
32951b60d2ecSQu Wenruo 	}
32961b60d2ecSQu Wenruo 
32971b60d2ecSQu Wenruo 	for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
32981b60d2ecSQu Wenruo 		struct extent_buffer *eb;
32991b60d2ecSQu Wenruo 		struct btrfs_key key;
33001b60d2ecSQu Wenruo 		int type;
33011b60d2ecSQu Wenruo 
33021b60d2ecSQu Wenruo 		cond_resched();
33031b60d2ecSQu Wenruo 		eb = btrfs_backref_get_eb(iter);
33041b60d2ecSQu Wenruo 
33051b60d2ecSQu Wenruo 		key.objectid = iter->bytenr;
33061b60d2ecSQu Wenruo 		if (btrfs_backref_iter_is_inline_ref(iter)) {
33071b60d2ecSQu Wenruo 			struct btrfs_extent_inline_ref *iref;
33081b60d2ecSQu Wenruo 
33091b60d2ecSQu Wenruo 			/* Update key for inline backref */
33101b60d2ecSQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
33111b60d2ecSQu Wenruo 				((unsigned long)iter->cur_ptr);
33121b60d2ecSQu Wenruo 			type = btrfs_get_extent_inline_ref_type(eb, iref,
33131b60d2ecSQu Wenruo 							BTRFS_REF_TYPE_BLOCK);
33141b60d2ecSQu Wenruo 			if (type == BTRFS_REF_TYPE_INVALID) {
33151b60d2ecSQu Wenruo 				ret = -EUCLEAN;
33161b60d2ecSQu Wenruo 				goto out;
33171b60d2ecSQu Wenruo 			}
33181b60d2ecSQu Wenruo 			key.type = type;
33191b60d2ecSQu Wenruo 			key.offset = btrfs_extent_inline_ref_offset(eb, iref);
33201b60d2ecSQu Wenruo 		} else {
33211b60d2ecSQu Wenruo 			key.type = iter->cur_key.type;
33221b60d2ecSQu Wenruo 			key.offset = iter->cur_key.offset;
33231b60d2ecSQu Wenruo 		}
33241b60d2ecSQu Wenruo 
33251b60d2ecSQu Wenruo 		/*
33261b60d2ecSQu Wenruo 		 * Parent node found and matches current inline ref, no need to
33271b60d2ecSQu Wenruo 		 * rebuild this node for this inline ref
33281b60d2ecSQu Wenruo 		 */
33291b60d2ecSQu Wenruo 		if (exist &&
33301b60d2ecSQu Wenruo 		    ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
33311b60d2ecSQu Wenruo 		      exist->owner == key.offset) ||
33321b60d2ecSQu Wenruo 		     (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
33331b60d2ecSQu Wenruo 		      exist->bytenr == key.offset))) {
33341b60d2ecSQu Wenruo 			exist = NULL;
33351b60d2ecSQu Wenruo 			continue;
33361b60d2ecSQu Wenruo 		}
33371b60d2ecSQu Wenruo 
33381b60d2ecSQu Wenruo 		/* SHARED_BLOCK_REF means key.offset is the parent bytenr */
33391b60d2ecSQu Wenruo 		if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
33401b60d2ecSQu Wenruo 			ret = handle_direct_tree_backref(cache, &key, cur);
33411b60d2ecSQu Wenruo 			if (ret < 0)
33421b60d2ecSQu Wenruo 				goto out;
33431b60d2ecSQu Wenruo 			continue;
33441b60d2ecSQu Wenruo 		} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
33451b60d2ecSQu Wenruo 			ret = -EINVAL;
33461b60d2ecSQu Wenruo 			btrfs_print_v0_err(fs_info);
33471b60d2ecSQu Wenruo 			btrfs_handle_fs_error(fs_info, ret, NULL);
33481b60d2ecSQu Wenruo 			goto out;
33491b60d2ecSQu Wenruo 		} else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
33501b60d2ecSQu Wenruo 			continue;
33511b60d2ecSQu Wenruo 		}
33521b60d2ecSQu Wenruo 
33531b60d2ecSQu Wenruo 		/*
33541b60d2ecSQu Wenruo 		 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
33551b60d2ecSQu Wenruo 		 * means the root objectid. We need to search the tree to get
33561b60d2ecSQu Wenruo 		 * its parent bytenr.
33571b60d2ecSQu Wenruo 		 */
33581b60d2ecSQu Wenruo 		ret = handle_indirect_tree_backref(cache, path, &key, node_key,
33591b60d2ecSQu Wenruo 						   cur);
33601b60d2ecSQu Wenruo 		if (ret < 0)
33611b60d2ecSQu Wenruo 			goto out;
33621b60d2ecSQu Wenruo 	}
33631b60d2ecSQu Wenruo 	ret = 0;
33641b60d2ecSQu Wenruo 	cur->checked = 1;
33651b60d2ecSQu Wenruo 	WARN_ON(exist);
33661b60d2ecSQu Wenruo out:
33671b60d2ecSQu Wenruo 	btrfs_backref_iter_release(iter);
33681b60d2ecSQu Wenruo 	return ret;
33691b60d2ecSQu Wenruo }
3370fc997ed0SQu Wenruo 
3371fc997ed0SQu Wenruo /*
3372fc997ed0SQu Wenruo  * Finish the upwards linkage created by btrfs_backref_add_tree_node()
3373fc997ed0SQu Wenruo  */
3374fc997ed0SQu Wenruo int btrfs_backref_finish_upper_links(struct btrfs_backref_cache *cache,
3375fc997ed0SQu Wenruo 				     struct btrfs_backref_node *start)
3376fc997ed0SQu Wenruo {
3377fc997ed0SQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
3378fc997ed0SQu Wenruo 	struct btrfs_backref_edge *edge;
3379fc997ed0SQu Wenruo 	struct rb_node *rb_node;
3380fc997ed0SQu Wenruo 	LIST_HEAD(pending_edge);
3381fc997ed0SQu Wenruo 
3382fc997ed0SQu Wenruo 	ASSERT(start->checked);
3383fc997ed0SQu Wenruo 
3384fc997ed0SQu Wenruo 	/* Insert this node to cache if it's not COW-only */
3385fc997ed0SQu Wenruo 	if (!start->cowonly) {
3386fc997ed0SQu Wenruo 		rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
3387fc997ed0SQu Wenruo 					   &start->rb_node);
3388fc997ed0SQu Wenruo 		if (rb_node)
3389fc997ed0SQu Wenruo 			btrfs_backref_panic(cache->fs_info, start->bytenr,
3390fc997ed0SQu Wenruo 					    -EEXIST);
3391fc997ed0SQu Wenruo 		list_add_tail(&start->lower, &cache->leaves);
3392fc997ed0SQu Wenruo 	}
3393fc997ed0SQu Wenruo 
3394fc997ed0SQu Wenruo 	/*
3395fc997ed0SQu Wenruo 	 * Use breadth first search to iterate all related edges.
3396fc997ed0SQu Wenruo 	 *
3397fc997ed0SQu Wenruo 	 * The starting points are all the edges of this node
3398fc997ed0SQu Wenruo 	 */
3399fc997ed0SQu Wenruo 	list_for_each_entry(edge, &start->upper, list[LOWER])
3400fc997ed0SQu Wenruo 		list_add_tail(&edge->list[UPPER], &pending_edge);
3401fc997ed0SQu Wenruo 
3402fc997ed0SQu Wenruo 	while (!list_empty(&pending_edge)) {
3403fc997ed0SQu Wenruo 		struct btrfs_backref_node *upper;
3404fc997ed0SQu Wenruo 		struct btrfs_backref_node *lower;
3405fc997ed0SQu Wenruo 
3406fc997ed0SQu Wenruo 		edge = list_first_entry(&pending_edge,
3407fc997ed0SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
3408fc997ed0SQu Wenruo 		list_del_init(&edge->list[UPPER]);
3409fc997ed0SQu Wenruo 		upper = edge->node[UPPER];
3410fc997ed0SQu Wenruo 		lower = edge->node[LOWER];
3411fc997ed0SQu Wenruo 
3412fc997ed0SQu Wenruo 		/* Parent is detached, no need to keep any edges */
3413fc997ed0SQu Wenruo 		if (upper->detached) {
3414fc997ed0SQu Wenruo 			list_del(&edge->list[LOWER]);
3415fc997ed0SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
3416fc997ed0SQu Wenruo 
3417fc997ed0SQu Wenruo 			/* Lower node is orphan, queue for cleanup */
3418fc997ed0SQu Wenruo 			if (list_empty(&lower->upper))
3419fc997ed0SQu Wenruo 				list_add(&lower->list, useless_node);
3420fc997ed0SQu Wenruo 			continue;
3421fc997ed0SQu Wenruo 		}
3422fc997ed0SQu Wenruo 
3423fc997ed0SQu Wenruo 		/*
3424fc997ed0SQu Wenruo 		 * All new nodes added in current build_backref_tree() haven't
3425fc997ed0SQu Wenruo 		 * been linked to the cache rb tree.
3426fc997ed0SQu Wenruo 		 * So if we have upper->rb_node populated, this means a cache
3427fc997ed0SQu Wenruo 		 * hit. We only need to link the edge, as @upper and all its
3428fc997ed0SQu Wenruo 		 * parents have already been linked.
3429fc997ed0SQu Wenruo 		 */
3430fc997ed0SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node)) {
3431fc997ed0SQu Wenruo 			if (upper->lowest) {
3432fc997ed0SQu Wenruo 				list_del_init(&upper->lower);
3433fc997ed0SQu Wenruo 				upper->lowest = 0;
3434fc997ed0SQu Wenruo 			}
3435fc997ed0SQu Wenruo 
3436fc997ed0SQu Wenruo 			list_add_tail(&edge->list[UPPER], &upper->lower);
3437fc997ed0SQu Wenruo 			continue;
3438fc997ed0SQu Wenruo 		}
3439fc997ed0SQu Wenruo 
3440fc997ed0SQu Wenruo 		/* Sanity check, we shouldn't have any unchecked nodes */
3441fc997ed0SQu Wenruo 		if (!upper->checked) {
3442fc997ed0SQu Wenruo 			ASSERT(0);
3443fc997ed0SQu Wenruo 			return -EUCLEAN;
3444fc997ed0SQu Wenruo 		}
3445fc997ed0SQu Wenruo 
3446fc997ed0SQu Wenruo 		/* Sanity check, COW-only node has non-COW-only parent */
3447fc997ed0SQu Wenruo 		if (start->cowonly != upper->cowonly) {
3448fc997ed0SQu Wenruo 			ASSERT(0);
3449fc997ed0SQu Wenruo 			return -EUCLEAN;
3450fc997ed0SQu Wenruo 		}
3451fc997ed0SQu Wenruo 
3452fc997ed0SQu Wenruo 		/* Only cache non-COW-only (subvolume trees) tree blocks */
3453fc997ed0SQu Wenruo 		if (!upper->cowonly) {
3454fc997ed0SQu Wenruo 			rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
3455fc997ed0SQu Wenruo 						   &upper->rb_node);
3456fc997ed0SQu Wenruo 			if (rb_node) {
3457fc997ed0SQu Wenruo 				btrfs_backref_panic(cache->fs_info,
3458fc997ed0SQu Wenruo 						upper->bytenr, -EEXIST);
3459fc997ed0SQu Wenruo 				return -EUCLEAN;
3460fc997ed0SQu Wenruo 			}
3461fc997ed0SQu Wenruo 		}
3462fc997ed0SQu Wenruo 
3463fc997ed0SQu Wenruo 		list_add_tail(&edge->list[UPPER], &upper->lower);
3464fc997ed0SQu Wenruo 
3465fc997ed0SQu Wenruo 		/*
3466fc997ed0SQu Wenruo 		 * Also queue all the parent edges of this uncached node
3467fc997ed0SQu Wenruo 		 * to finish the upper linkage
3468fc997ed0SQu Wenruo 		 */
3469fc997ed0SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
3470fc997ed0SQu Wenruo 			list_add_tail(&edge->list[UPPER], &pending_edge);
3471fc997ed0SQu Wenruo 	}
3472fc997ed0SQu Wenruo 	return 0;
3473fc997ed0SQu Wenruo }
34741b23ea18SQu Wenruo 
34751b23ea18SQu Wenruo void btrfs_backref_error_cleanup(struct btrfs_backref_cache *cache,
34761b23ea18SQu Wenruo 				 struct btrfs_backref_node *node)
34771b23ea18SQu Wenruo {
34781b23ea18SQu Wenruo 	struct btrfs_backref_node *lower;
34791b23ea18SQu Wenruo 	struct btrfs_backref_node *upper;
34801b23ea18SQu Wenruo 	struct btrfs_backref_edge *edge;
34811b23ea18SQu Wenruo 
34821b23ea18SQu Wenruo 	while (!list_empty(&cache->useless_node)) {
34831b23ea18SQu Wenruo 		lower = list_first_entry(&cache->useless_node,
34841b23ea18SQu Wenruo 				   struct btrfs_backref_node, list);
34851b23ea18SQu Wenruo 		list_del_init(&lower->list);
34861b23ea18SQu Wenruo 	}
34871b23ea18SQu Wenruo 	while (!list_empty(&cache->pending_edge)) {
34881b23ea18SQu Wenruo 		edge = list_first_entry(&cache->pending_edge,
34891b23ea18SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
34901b23ea18SQu Wenruo 		list_del(&edge->list[UPPER]);
34911b23ea18SQu Wenruo 		list_del(&edge->list[LOWER]);
34921b23ea18SQu Wenruo 		lower = edge->node[LOWER];
34931b23ea18SQu Wenruo 		upper = edge->node[UPPER];
34941b23ea18SQu Wenruo 		btrfs_backref_free_edge(cache, edge);
34951b23ea18SQu Wenruo 
34961b23ea18SQu Wenruo 		/*
34971b23ea18SQu Wenruo 		 * Lower is no longer linked to any upper backref nodes and
34981b23ea18SQu Wenruo 		 * isn't in the cache, we can free it ourselves.
34991b23ea18SQu Wenruo 		 */
35001b23ea18SQu Wenruo 		if (list_empty(&lower->upper) &&
35011b23ea18SQu Wenruo 		    RB_EMPTY_NODE(&lower->rb_node))
35021b23ea18SQu Wenruo 			list_add(&lower->list, &cache->useless_node);
35031b23ea18SQu Wenruo 
35041b23ea18SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node))
35051b23ea18SQu Wenruo 			continue;
35061b23ea18SQu Wenruo 
35071b23ea18SQu Wenruo 		/* Add this guy's upper edges to the list to process */
35081b23ea18SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
35091b23ea18SQu Wenruo 			list_add_tail(&edge->list[UPPER],
35101b23ea18SQu Wenruo 				      &cache->pending_edge);
35111b23ea18SQu Wenruo 		if (list_empty(&upper->upper))
35121b23ea18SQu Wenruo 			list_add(&upper->list, &cache->useless_node);
35131b23ea18SQu Wenruo 	}
35141b23ea18SQu Wenruo 
35151b23ea18SQu Wenruo 	while (!list_empty(&cache->useless_node)) {
35161b23ea18SQu Wenruo 		lower = list_first_entry(&cache->useless_node,
35171b23ea18SQu Wenruo 				   struct btrfs_backref_node, list);
35181b23ea18SQu Wenruo 		list_del_init(&lower->list);
35191b23ea18SQu Wenruo 		if (lower == node)
35201b23ea18SQu Wenruo 			node = NULL;
352149ecc679SJosef Bacik 		btrfs_backref_drop_node(cache, lower);
35221b23ea18SQu Wenruo 	}
35231b23ea18SQu Wenruo 
35241b23ea18SQu Wenruo 	btrfs_backref_cleanup_node(cache, node);
35251b23ea18SQu Wenruo 	ASSERT(list_empty(&cache->useless_node) &&
35261b23ea18SQu Wenruo 	       list_empty(&cache->pending_edge));
35271b23ea18SQu Wenruo }
3528