xref: /openbmc/linux/fs/btrfs/backref.c (revision adf0241868bd46c7be8012ef99cb88c7f47c16ce)
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 
3488ffb665SFilipe Manana static int check_extent_in_eb(struct btrfs_backref_walk_ctx *ctx,
3588ffb665SFilipe Manana 			      const struct btrfs_key *key,
3673980becSJeff Mahoney 			      const struct extent_buffer *eb,
3773980becSJeff Mahoney 			      const struct btrfs_file_extent_item *fi,
386ce6ba53SFilipe Manana 			      struct extent_inode_elem **eie)
39976b1908SJan Schmidt {
40c7499a64SFilipe Manana 	const u64 data_len = btrfs_file_extent_num_bytes(eb, fi);
4188ffb665SFilipe Manana 	u64 offset = key->offset;
428ca15e05SJosef Bacik 	struct extent_inode_elem *e;
4388ffb665SFilipe Manana 	const u64 *root_ids;
4488ffb665SFilipe Manana 	int root_count;
4588ffb665SFilipe Manana 	bool cached;
468ca15e05SJosef Bacik 
476ce6ba53SFilipe Manana 	if (!btrfs_file_extent_compression(eb, fi) &&
488ca15e05SJosef Bacik 	    !btrfs_file_extent_encryption(eb, fi) &&
498ca15e05SJosef Bacik 	    !btrfs_file_extent_other_encoding(eb, fi)) {
50976b1908SJan Schmidt 		u64 data_offset;
51976b1908SJan Schmidt 
52976b1908SJan Schmidt 		data_offset = btrfs_file_extent_offset(eb, fi);
53976b1908SJan Schmidt 
5488ffb665SFilipe Manana 		if (ctx->extent_item_pos < data_offset ||
5588ffb665SFilipe Manana 		    ctx->extent_item_pos >= data_offset + data_len)
56976b1908SJan Schmidt 			return 1;
5788ffb665SFilipe Manana 		offset += ctx->extent_item_pos - data_offset;
588ca15e05SJosef Bacik 	}
59976b1908SJan Schmidt 
6088ffb665SFilipe Manana 	if (!ctx->indirect_ref_iterator || !ctx->cache_lookup)
6188ffb665SFilipe Manana 		goto add_inode_elem;
6288ffb665SFilipe Manana 
6388ffb665SFilipe Manana 	cached = ctx->cache_lookup(eb->start, ctx->user_ctx, &root_ids,
6488ffb665SFilipe Manana 				   &root_count);
6588ffb665SFilipe Manana 	if (!cached)
6688ffb665SFilipe Manana 		goto add_inode_elem;
6788ffb665SFilipe Manana 
6888ffb665SFilipe Manana 	for (int i = 0; i < root_count; i++) {
6988ffb665SFilipe Manana 		int ret;
7088ffb665SFilipe Manana 
7188ffb665SFilipe Manana 		ret = ctx->indirect_ref_iterator(key->objectid, offset,
7288ffb665SFilipe Manana 						 data_len, root_ids[i],
7388ffb665SFilipe Manana 						 ctx->user_ctx);
7488ffb665SFilipe Manana 		if (ret)
7588ffb665SFilipe Manana 			return ret;
7688ffb665SFilipe Manana 	}
7788ffb665SFilipe Manana 
7888ffb665SFilipe Manana add_inode_elem:
79976b1908SJan Schmidt 	e = kmalloc(sizeof(*e), GFP_NOFS);
80976b1908SJan Schmidt 	if (!e)
81976b1908SJan Schmidt 		return -ENOMEM;
82976b1908SJan Schmidt 
83976b1908SJan Schmidt 	e->next = *eie;
84976b1908SJan Schmidt 	e->inum = key->objectid;
8588ffb665SFilipe Manana 	e->offset = offset;
86c7499a64SFilipe Manana 	e->num_bytes = data_len;
87976b1908SJan Schmidt 	*eie = e;
88976b1908SJan Schmidt 
89976b1908SJan Schmidt 	return 0;
90976b1908SJan Schmidt }
91976b1908SJan Schmidt 
92f05c4746SWang Shilong static void free_inode_elem_list(struct extent_inode_elem *eie)
93f05c4746SWang Shilong {
94f05c4746SWang Shilong 	struct extent_inode_elem *eie_next;
95f05c4746SWang Shilong 
96f05c4746SWang Shilong 	for (; eie; eie = eie_next) {
97f05c4746SWang Shilong 		eie_next = eie->next;
98f05c4746SWang Shilong 		kfree(eie);
99f05c4746SWang Shilong 	}
100f05c4746SWang Shilong }
101f05c4746SWang Shilong 
10288ffb665SFilipe Manana static int find_extent_in_eb(struct btrfs_backref_walk_ctx *ctx,
10388ffb665SFilipe Manana 			     const struct extent_buffer *eb,
1046ce6ba53SFilipe Manana 			     struct extent_inode_elem **eie)
105976b1908SJan Schmidt {
106976b1908SJan Schmidt 	u64 disk_byte;
107976b1908SJan Schmidt 	struct btrfs_key key;
108976b1908SJan Schmidt 	struct btrfs_file_extent_item *fi;
109976b1908SJan Schmidt 	int slot;
110976b1908SJan Schmidt 	int nritems;
111976b1908SJan Schmidt 	int extent_type;
112976b1908SJan Schmidt 	int ret;
113976b1908SJan Schmidt 
114976b1908SJan Schmidt 	/*
115976b1908SJan Schmidt 	 * from the shared data ref, we only have the leaf but we need
116976b1908SJan Schmidt 	 * the key. thus, we must look into all items and see that we
117976b1908SJan Schmidt 	 * find one (some) with a reference to our extent item.
118976b1908SJan Schmidt 	 */
119976b1908SJan Schmidt 	nritems = btrfs_header_nritems(eb);
120976b1908SJan Schmidt 	for (slot = 0; slot < nritems; ++slot) {
121976b1908SJan Schmidt 		btrfs_item_key_to_cpu(eb, &key, slot);
122976b1908SJan Schmidt 		if (key.type != BTRFS_EXTENT_DATA_KEY)
123976b1908SJan Schmidt 			continue;
124976b1908SJan Schmidt 		fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
125976b1908SJan Schmidt 		extent_type = btrfs_file_extent_type(eb, fi);
126976b1908SJan Schmidt 		if (extent_type == BTRFS_FILE_EXTENT_INLINE)
127976b1908SJan Schmidt 			continue;
128976b1908SJan Schmidt 		/* don't skip BTRFS_FILE_EXTENT_PREALLOC, we can handle that */
129976b1908SJan Schmidt 		disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
13088ffb665SFilipe Manana 		if (disk_byte != ctx->bytenr)
131976b1908SJan Schmidt 			continue;
132976b1908SJan Schmidt 
13388ffb665SFilipe Manana 		ret = check_extent_in_eb(ctx, &key, eb, fi, eie);
13488ffb665SFilipe Manana 		if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
135976b1908SJan Schmidt 			return ret;
136976b1908SJan Schmidt 	}
137976b1908SJan Schmidt 
138976b1908SJan Schmidt 	return 0;
139976b1908SJan Schmidt }
140976b1908SJan Schmidt 
14186d5f994SEdmund Nadolski struct preftree {
142ecf160b4SLiu Bo 	struct rb_root_cached root;
1436c336b21SJeff Mahoney 	unsigned int count;
14486d5f994SEdmund Nadolski };
14586d5f994SEdmund Nadolski 
146ecf160b4SLiu Bo #define PREFTREE_INIT	{ .root = RB_ROOT_CACHED, .count = 0 }
14786d5f994SEdmund Nadolski 
14886d5f994SEdmund Nadolski struct preftrees {
14986d5f994SEdmund Nadolski 	struct preftree direct;    /* BTRFS_SHARED_[DATA|BLOCK]_REF_KEY */
15086d5f994SEdmund Nadolski 	struct preftree indirect;  /* BTRFS_[TREE_BLOCK|EXTENT_DATA]_REF_KEY */
15186d5f994SEdmund Nadolski 	struct preftree indirect_missing_keys;
15286d5f994SEdmund Nadolski };
15386d5f994SEdmund Nadolski 
1543ec4d323SEdmund Nadolski /*
1553ec4d323SEdmund Nadolski  * Checks for a shared extent during backref search.
1563ec4d323SEdmund Nadolski  *
1573ec4d323SEdmund Nadolski  * The share_count tracks prelim_refs (direct and indirect) having a
1583ec4d323SEdmund Nadolski  * ref->count >0:
1593ec4d323SEdmund Nadolski  *  - incremented when a ref->count transitions to >0
1603ec4d323SEdmund Nadolski  *  - decremented when a ref->count transitions to <1
1613ec4d323SEdmund Nadolski  */
1623ec4d323SEdmund Nadolski struct share_check {
163877c1476SFilipe Manana 	struct btrfs_backref_share_check_ctx *ctx;
164877c1476SFilipe Manana 	struct btrfs_root *root;
1653ec4d323SEdmund Nadolski 	u64 inum;
16673e339e6SFilipe Manana 	u64 data_bytenr;
1676976201fSFilipe Manana 	u64 data_extent_gen;
16873e339e6SFilipe Manana 	/*
16973e339e6SFilipe Manana 	 * Counts number of inodes that refer to an extent (different inodes in
17073e339e6SFilipe Manana 	 * the same root or different roots) that we could find. The sharedness
17173e339e6SFilipe Manana 	 * check typically stops once this counter gets greater than 1, so it
17273e339e6SFilipe Manana 	 * may not reflect the total number of inodes.
17373e339e6SFilipe Manana 	 */
1743ec4d323SEdmund Nadolski 	int share_count;
17573e339e6SFilipe Manana 	/*
17673e339e6SFilipe Manana 	 * The number of times we found our inode refers to the data extent we
17773e339e6SFilipe Manana 	 * are determining the sharedness. In other words, how many file extent
17873e339e6SFilipe Manana 	 * items we could find for our inode that point to our target data
17973e339e6SFilipe Manana 	 * extent. The value we get here after finishing the extent sharedness
18073e339e6SFilipe Manana 	 * check may be smaller than reality, but if it ends up being greater
18173e339e6SFilipe Manana 	 * than 1, then we know for sure the inode has multiple file extent
18273e339e6SFilipe Manana 	 * items that point to our inode, and we can safely assume it's useful
18373e339e6SFilipe Manana 	 * to cache the sharedness check result.
18473e339e6SFilipe Manana 	 */
18573e339e6SFilipe Manana 	int self_ref_count;
1864fc7b572SFilipe Manana 	bool have_delayed_delete_refs;
1873ec4d323SEdmund Nadolski };
1883ec4d323SEdmund Nadolski 
1893ec4d323SEdmund Nadolski static inline int extent_is_shared(struct share_check *sc)
1903ec4d323SEdmund Nadolski {
1913ec4d323SEdmund Nadolski 	return (sc && sc->share_count > 1) ? BACKREF_FOUND_SHARED : 0;
1923ec4d323SEdmund Nadolski }
1933ec4d323SEdmund Nadolski 
194b9e9a6cbSWang Shilong static struct kmem_cache *btrfs_prelim_ref_cache;
195b9e9a6cbSWang Shilong 
196b9e9a6cbSWang Shilong int __init btrfs_prelim_ref_init(void)
197b9e9a6cbSWang Shilong {
198b9e9a6cbSWang Shilong 	btrfs_prelim_ref_cache = kmem_cache_create("btrfs_prelim_ref",
199e0c476b1SJeff Mahoney 					sizeof(struct prelim_ref),
200b9e9a6cbSWang Shilong 					0,
201fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
202b9e9a6cbSWang Shilong 					NULL);
203b9e9a6cbSWang Shilong 	if (!btrfs_prelim_ref_cache)
204b9e9a6cbSWang Shilong 		return -ENOMEM;
205b9e9a6cbSWang Shilong 	return 0;
206b9e9a6cbSWang Shilong }
207b9e9a6cbSWang Shilong 
208e67c718bSDavid Sterba void __cold btrfs_prelim_ref_exit(void)
209b9e9a6cbSWang Shilong {
210b9e9a6cbSWang Shilong 	kmem_cache_destroy(btrfs_prelim_ref_cache);
211b9e9a6cbSWang Shilong }
212b9e9a6cbSWang Shilong 
21386d5f994SEdmund Nadolski static void free_pref(struct prelim_ref *ref)
21486d5f994SEdmund Nadolski {
21586d5f994SEdmund Nadolski 	kmem_cache_free(btrfs_prelim_ref_cache, ref);
21686d5f994SEdmund Nadolski }
21786d5f994SEdmund Nadolski 
21886d5f994SEdmund Nadolski /*
21986d5f994SEdmund Nadolski  * Return 0 when both refs are for the same block (and can be merged).
22086d5f994SEdmund Nadolski  * A -1 return indicates ref1 is a 'lower' block than ref2, while 1
22186d5f994SEdmund Nadolski  * indicates a 'higher' block.
22286d5f994SEdmund Nadolski  */
22386d5f994SEdmund Nadolski static int prelim_ref_compare(struct prelim_ref *ref1,
22486d5f994SEdmund Nadolski 			      struct prelim_ref *ref2)
22586d5f994SEdmund Nadolski {
22686d5f994SEdmund Nadolski 	if (ref1->level < ref2->level)
22786d5f994SEdmund Nadolski 		return -1;
22886d5f994SEdmund Nadolski 	if (ref1->level > ref2->level)
22986d5f994SEdmund Nadolski 		return 1;
23086d5f994SEdmund Nadolski 	if (ref1->root_id < ref2->root_id)
23186d5f994SEdmund Nadolski 		return -1;
23286d5f994SEdmund Nadolski 	if (ref1->root_id > ref2->root_id)
23386d5f994SEdmund Nadolski 		return 1;
23486d5f994SEdmund Nadolski 	if (ref1->key_for_search.type < ref2->key_for_search.type)
23586d5f994SEdmund Nadolski 		return -1;
23686d5f994SEdmund Nadolski 	if (ref1->key_for_search.type > ref2->key_for_search.type)
23786d5f994SEdmund Nadolski 		return 1;
23886d5f994SEdmund Nadolski 	if (ref1->key_for_search.objectid < ref2->key_for_search.objectid)
23986d5f994SEdmund Nadolski 		return -1;
24086d5f994SEdmund Nadolski 	if (ref1->key_for_search.objectid > ref2->key_for_search.objectid)
24186d5f994SEdmund Nadolski 		return 1;
24286d5f994SEdmund Nadolski 	if (ref1->key_for_search.offset < ref2->key_for_search.offset)
24386d5f994SEdmund Nadolski 		return -1;
24486d5f994SEdmund Nadolski 	if (ref1->key_for_search.offset > ref2->key_for_search.offset)
24586d5f994SEdmund Nadolski 		return 1;
24686d5f994SEdmund Nadolski 	if (ref1->parent < ref2->parent)
24786d5f994SEdmund Nadolski 		return -1;
24886d5f994SEdmund Nadolski 	if (ref1->parent > ref2->parent)
24986d5f994SEdmund Nadolski 		return 1;
25086d5f994SEdmund Nadolski 
25186d5f994SEdmund Nadolski 	return 0;
25286d5f994SEdmund Nadolski }
25386d5f994SEdmund Nadolski 
254ccc8dc75SColin Ian King static void update_share_count(struct share_check *sc, int oldcount,
25573e339e6SFilipe Manana 			       int newcount, struct prelim_ref *newref)
2563ec4d323SEdmund Nadolski {
2573ec4d323SEdmund Nadolski 	if ((!sc) || (oldcount == 0 && newcount < 1))
2583ec4d323SEdmund Nadolski 		return;
2593ec4d323SEdmund Nadolski 
2603ec4d323SEdmund Nadolski 	if (oldcount > 0 && newcount < 1)
2613ec4d323SEdmund Nadolski 		sc->share_count--;
2623ec4d323SEdmund Nadolski 	else if (oldcount < 1 && newcount > 0)
2633ec4d323SEdmund Nadolski 		sc->share_count++;
26473e339e6SFilipe Manana 
265877c1476SFilipe Manana 	if (newref->root_id == sc->root->root_key.objectid &&
26673e339e6SFilipe Manana 	    newref->wanted_disk_byte == sc->data_bytenr &&
26773e339e6SFilipe Manana 	    newref->key_for_search.objectid == sc->inum)
26873e339e6SFilipe Manana 		sc->self_ref_count += newref->count;
2693ec4d323SEdmund Nadolski }
2703ec4d323SEdmund Nadolski 
27186d5f994SEdmund Nadolski /*
27286d5f994SEdmund Nadolski  * Add @newref to the @root rbtree, merging identical refs.
27386d5f994SEdmund Nadolski  *
2743ec4d323SEdmund Nadolski  * Callers should assume that newref has been freed after calling.
27586d5f994SEdmund Nadolski  */
27600142756SJeff Mahoney static void prelim_ref_insert(const struct btrfs_fs_info *fs_info,
27700142756SJeff Mahoney 			      struct preftree *preftree,
2783ec4d323SEdmund Nadolski 			      struct prelim_ref *newref,
2793ec4d323SEdmund Nadolski 			      struct share_check *sc)
28086d5f994SEdmund Nadolski {
281ecf160b4SLiu Bo 	struct rb_root_cached *root;
28286d5f994SEdmund Nadolski 	struct rb_node **p;
28386d5f994SEdmund Nadolski 	struct rb_node *parent = NULL;
28486d5f994SEdmund Nadolski 	struct prelim_ref *ref;
28586d5f994SEdmund Nadolski 	int result;
286ecf160b4SLiu Bo 	bool leftmost = true;
28786d5f994SEdmund Nadolski 
28886d5f994SEdmund Nadolski 	root = &preftree->root;
289ecf160b4SLiu Bo 	p = &root->rb_root.rb_node;
29086d5f994SEdmund Nadolski 
29186d5f994SEdmund Nadolski 	while (*p) {
29286d5f994SEdmund Nadolski 		parent = *p;
29386d5f994SEdmund Nadolski 		ref = rb_entry(parent, struct prelim_ref, rbnode);
29486d5f994SEdmund Nadolski 		result = prelim_ref_compare(ref, newref);
29586d5f994SEdmund Nadolski 		if (result < 0) {
29686d5f994SEdmund Nadolski 			p = &(*p)->rb_left;
29786d5f994SEdmund Nadolski 		} else if (result > 0) {
29886d5f994SEdmund Nadolski 			p = &(*p)->rb_right;
299ecf160b4SLiu Bo 			leftmost = false;
30086d5f994SEdmund Nadolski 		} else {
30186d5f994SEdmund Nadolski 			/* Identical refs, merge them and free @newref */
30286d5f994SEdmund Nadolski 			struct extent_inode_elem *eie = ref->inode_list;
30386d5f994SEdmund Nadolski 
30486d5f994SEdmund Nadolski 			while (eie && eie->next)
30586d5f994SEdmund Nadolski 				eie = eie->next;
30686d5f994SEdmund Nadolski 
30786d5f994SEdmund Nadolski 			if (!eie)
30886d5f994SEdmund Nadolski 				ref->inode_list = newref->inode_list;
30986d5f994SEdmund Nadolski 			else
31086d5f994SEdmund Nadolski 				eie->next = newref->inode_list;
31100142756SJeff Mahoney 			trace_btrfs_prelim_ref_merge(fs_info, ref, newref,
31200142756SJeff Mahoney 						     preftree->count);
3133ec4d323SEdmund Nadolski 			/*
3143ec4d323SEdmund Nadolski 			 * A delayed ref can have newref->count < 0.
3153ec4d323SEdmund Nadolski 			 * The ref->count is updated to follow any
3163ec4d323SEdmund Nadolski 			 * BTRFS_[ADD|DROP]_DELAYED_REF actions.
3173ec4d323SEdmund Nadolski 			 */
3183ec4d323SEdmund Nadolski 			update_share_count(sc, ref->count,
31973e339e6SFilipe Manana 					   ref->count + newref->count, newref);
32086d5f994SEdmund Nadolski 			ref->count += newref->count;
32186d5f994SEdmund Nadolski 			free_pref(newref);
32286d5f994SEdmund Nadolski 			return;
32386d5f994SEdmund Nadolski 		}
32486d5f994SEdmund Nadolski 	}
32586d5f994SEdmund Nadolski 
32673e339e6SFilipe Manana 	update_share_count(sc, 0, newref->count, newref);
3276c336b21SJeff Mahoney 	preftree->count++;
32800142756SJeff Mahoney 	trace_btrfs_prelim_ref_insert(fs_info, newref, NULL, preftree->count);
32986d5f994SEdmund Nadolski 	rb_link_node(&newref->rbnode, parent, p);
330ecf160b4SLiu Bo 	rb_insert_color_cached(&newref->rbnode, root, leftmost);
33186d5f994SEdmund Nadolski }
33286d5f994SEdmund Nadolski 
33386d5f994SEdmund Nadolski /*
33486d5f994SEdmund Nadolski  * Release the entire tree.  We don't care about internal consistency so
33586d5f994SEdmund Nadolski  * just free everything and then reset the tree root.
33686d5f994SEdmund Nadolski  */
33786d5f994SEdmund Nadolski static void prelim_release(struct preftree *preftree)
33886d5f994SEdmund Nadolski {
33986d5f994SEdmund Nadolski 	struct prelim_ref *ref, *next_ref;
34086d5f994SEdmund Nadolski 
341ecf160b4SLiu Bo 	rbtree_postorder_for_each_entry_safe(ref, next_ref,
34292876eecSFilipe Manana 					     &preftree->root.rb_root, rbnode) {
34392876eecSFilipe Manana 		free_inode_elem_list(ref->inode_list);
34486d5f994SEdmund Nadolski 		free_pref(ref);
34592876eecSFilipe Manana 	}
34686d5f994SEdmund Nadolski 
347ecf160b4SLiu Bo 	preftree->root = RB_ROOT_CACHED;
3486c336b21SJeff Mahoney 	preftree->count = 0;
34986d5f994SEdmund Nadolski }
35086d5f994SEdmund Nadolski 
351d5c88b73SJan Schmidt /*
352d5c88b73SJan Schmidt  * the rules for all callers of this function are:
353d5c88b73SJan Schmidt  * - obtaining the parent is the goal
354d5c88b73SJan Schmidt  * - if you add a key, you must know that it is a correct key
355d5c88b73SJan Schmidt  * - if you cannot add the parent or a correct key, then we will look into the
356d5c88b73SJan Schmidt  *   block later to set a correct key
357d5c88b73SJan Schmidt  *
358d5c88b73SJan Schmidt  * delayed refs
359d5c88b73SJan Schmidt  * ============
360d5c88b73SJan Schmidt  *        backref type | shared | indirect | shared | indirect
361d5c88b73SJan Schmidt  * information         |   tree |     tree |   data |     data
362d5c88b73SJan Schmidt  * --------------------+--------+----------+--------+----------
363d5c88b73SJan Schmidt  *      parent logical |    y   |     -    |    -   |     -
364d5c88b73SJan Schmidt  *      key to resolve |    -   |     y    |    y   |     y
365d5c88b73SJan Schmidt  *  tree block logical |    -   |     -    |    -   |     -
366d5c88b73SJan Schmidt  *  root for resolving |    y   |     y    |    y   |     y
367d5c88b73SJan Schmidt  *
368d5c88b73SJan Schmidt  * - column 1:       we've the parent -> done
369d5c88b73SJan Schmidt  * - column 2, 3, 4: we use the key to find the parent
370d5c88b73SJan Schmidt  *
371d5c88b73SJan Schmidt  * on disk refs (inline or keyed)
372d5c88b73SJan Schmidt  * ==============================
373d5c88b73SJan Schmidt  *        backref type | shared | indirect | shared | indirect
374d5c88b73SJan Schmidt  * information         |   tree |     tree |   data |     data
375d5c88b73SJan Schmidt  * --------------------+--------+----------+--------+----------
376d5c88b73SJan Schmidt  *      parent logical |    y   |     -    |    y   |     -
377d5c88b73SJan Schmidt  *      key to resolve |    -   |     -    |    -   |     y
378d5c88b73SJan Schmidt  *  tree block logical |    y   |     y    |    y   |     y
379d5c88b73SJan Schmidt  *  root for resolving |    -   |     y    |    y   |     y
380d5c88b73SJan Schmidt  *
381d5c88b73SJan Schmidt  * - column 1, 3: we've the parent -> done
382d5c88b73SJan Schmidt  * - column 2:    we take the first key from the block to find the parent
383e0c476b1SJeff Mahoney  *                (see add_missing_keys)
384d5c88b73SJan Schmidt  * - column 4:    we use the key to find the parent
385d5c88b73SJan Schmidt  *
386d5c88b73SJan Schmidt  * additional information that's available but not required to find the parent
387d5c88b73SJan Schmidt  * block might help in merging entries to gain some speed.
388d5c88b73SJan Schmidt  */
38900142756SJeff Mahoney static int add_prelim_ref(const struct btrfs_fs_info *fs_info,
39000142756SJeff Mahoney 			  struct preftree *preftree, u64 root_id,
391e0c476b1SJeff Mahoney 			  const struct btrfs_key *key, int level, u64 parent,
3923ec4d323SEdmund Nadolski 			  u64 wanted_disk_byte, int count,
3933ec4d323SEdmund Nadolski 			  struct share_check *sc, gfp_t gfp_mask)
3948da6d581SJan Schmidt {
395e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
3968da6d581SJan Schmidt 
39748ec4736SLiu Bo 	if (root_id == BTRFS_DATA_RELOC_TREE_OBJECTID)
39848ec4736SLiu Bo 		return 0;
39948ec4736SLiu Bo 
400b9e9a6cbSWang Shilong 	ref = kmem_cache_alloc(btrfs_prelim_ref_cache, gfp_mask);
4018da6d581SJan Schmidt 	if (!ref)
4028da6d581SJan Schmidt 		return -ENOMEM;
4038da6d581SJan Schmidt 
4048da6d581SJan Schmidt 	ref->root_id = root_id;
4057ac8b88eSethanwu 	if (key)
406d5c88b73SJan Schmidt 		ref->key_for_search = *key;
4077ac8b88eSethanwu 	else
408d5c88b73SJan Schmidt 		memset(&ref->key_for_search, 0, sizeof(ref->key_for_search));
4098da6d581SJan Schmidt 
4103301958bSJan Schmidt 	ref->inode_list = NULL;
4118da6d581SJan Schmidt 	ref->level = level;
4128da6d581SJan Schmidt 	ref->count = count;
4138da6d581SJan Schmidt 	ref->parent = parent;
4148da6d581SJan Schmidt 	ref->wanted_disk_byte = wanted_disk_byte;
4153ec4d323SEdmund Nadolski 	prelim_ref_insert(fs_info, preftree, ref, sc);
4163ec4d323SEdmund Nadolski 	return extent_is_shared(sc);
4178da6d581SJan Schmidt }
4188da6d581SJan Schmidt 
41986d5f994SEdmund Nadolski /* direct refs use root == 0, key == NULL */
42000142756SJeff Mahoney static int add_direct_ref(const struct btrfs_fs_info *fs_info,
42100142756SJeff Mahoney 			  struct preftrees *preftrees, int level, u64 parent,
4223ec4d323SEdmund Nadolski 			  u64 wanted_disk_byte, int count,
4233ec4d323SEdmund Nadolski 			  struct share_check *sc, gfp_t gfp_mask)
42486d5f994SEdmund Nadolski {
42500142756SJeff Mahoney 	return add_prelim_ref(fs_info, &preftrees->direct, 0, NULL, level,
4263ec4d323SEdmund Nadolski 			      parent, wanted_disk_byte, count, sc, gfp_mask);
42786d5f994SEdmund Nadolski }
42886d5f994SEdmund Nadolski 
42986d5f994SEdmund Nadolski /* indirect refs use parent == 0 */
43000142756SJeff Mahoney static int add_indirect_ref(const struct btrfs_fs_info *fs_info,
43100142756SJeff Mahoney 			    struct preftrees *preftrees, u64 root_id,
43286d5f994SEdmund Nadolski 			    const struct btrfs_key *key, int level,
4333ec4d323SEdmund Nadolski 			    u64 wanted_disk_byte, int count,
4343ec4d323SEdmund Nadolski 			    struct share_check *sc, gfp_t gfp_mask)
43586d5f994SEdmund Nadolski {
43686d5f994SEdmund Nadolski 	struct preftree *tree = &preftrees->indirect;
43786d5f994SEdmund Nadolski 
43886d5f994SEdmund Nadolski 	if (!key)
43986d5f994SEdmund Nadolski 		tree = &preftrees->indirect_missing_keys;
44000142756SJeff Mahoney 	return add_prelim_ref(fs_info, tree, root_id, key, level, 0,
4413ec4d323SEdmund Nadolski 			      wanted_disk_byte, count, sc, gfp_mask);
44286d5f994SEdmund Nadolski }
44386d5f994SEdmund Nadolski 
444ed58f2e6Sethanwu static int is_shared_data_backref(struct preftrees *preftrees, u64 bytenr)
445ed58f2e6Sethanwu {
446ed58f2e6Sethanwu 	struct rb_node **p = &preftrees->direct.root.rb_root.rb_node;
447ed58f2e6Sethanwu 	struct rb_node *parent = NULL;
448ed58f2e6Sethanwu 	struct prelim_ref *ref = NULL;
4499c6c723fSArnd Bergmann 	struct prelim_ref target = {};
450ed58f2e6Sethanwu 	int result;
451ed58f2e6Sethanwu 
452ed58f2e6Sethanwu 	target.parent = bytenr;
453ed58f2e6Sethanwu 
454ed58f2e6Sethanwu 	while (*p) {
455ed58f2e6Sethanwu 		parent = *p;
456ed58f2e6Sethanwu 		ref = rb_entry(parent, struct prelim_ref, rbnode);
457ed58f2e6Sethanwu 		result = prelim_ref_compare(ref, &target);
458ed58f2e6Sethanwu 
459ed58f2e6Sethanwu 		if (result < 0)
460ed58f2e6Sethanwu 			p = &(*p)->rb_left;
461ed58f2e6Sethanwu 		else if (result > 0)
462ed58f2e6Sethanwu 			p = &(*p)->rb_right;
463ed58f2e6Sethanwu 		else
464ed58f2e6Sethanwu 			return 1;
465ed58f2e6Sethanwu 	}
466ed58f2e6Sethanwu 	return 0;
467ed58f2e6Sethanwu }
468ed58f2e6Sethanwu 
469a2c8d27eSFilipe Manana static int add_all_parents(struct btrfs_backref_walk_ctx *ctx,
470a2c8d27eSFilipe Manana 			   struct btrfs_root *root, struct btrfs_path *path,
471ed58f2e6Sethanwu 			   struct ulist *parents,
472ed58f2e6Sethanwu 			   struct preftrees *preftrees, struct prelim_ref *ref,
473a2c8d27eSFilipe Manana 			   int level)
4748da6d581SJan Schmidt {
47569bca40dSAlexander Block 	int ret = 0;
47669bca40dSAlexander Block 	int slot;
47769bca40dSAlexander Block 	struct extent_buffer *eb;
47869bca40dSAlexander Block 	struct btrfs_key key;
4797ef81ac8SJosef Bacik 	struct btrfs_key *key_for_search = &ref->key_for_search;
4808da6d581SJan Schmidt 	struct btrfs_file_extent_item *fi;
481ed8c4913SJosef Bacik 	struct extent_inode_elem *eie = NULL, *old = NULL;
4828da6d581SJan Schmidt 	u64 disk_byte;
4837ef81ac8SJosef Bacik 	u64 wanted_disk_byte = ref->wanted_disk_byte;
4847ef81ac8SJosef Bacik 	u64 count = 0;
4857ac8b88eSethanwu 	u64 data_offset;
4868da6d581SJan Schmidt 
48769bca40dSAlexander Block 	if (level != 0) {
48869bca40dSAlexander Block 		eb = path->nodes[level];
48969bca40dSAlexander Block 		ret = ulist_add(parents, eb->start, 0, GFP_NOFS);
4903301958bSJan Schmidt 		if (ret < 0)
4913301958bSJan Schmidt 			return ret;
4928da6d581SJan Schmidt 		return 0;
49369bca40dSAlexander Block 	}
4948da6d581SJan Schmidt 
4958da6d581SJan Schmidt 	/*
496ed58f2e6Sethanwu 	 * 1. We normally enter this function with the path already pointing to
49769bca40dSAlexander Block 	 *    the first item to check. But sometimes, we may enter it with
498ed58f2e6Sethanwu 	 *    slot == nritems.
499ed58f2e6Sethanwu 	 * 2. We are searching for normal backref but bytenr of this leaf
500ed58f2e6Sethanwu 	 *    matches shared data backref
501cfc0eed0Sethanwu 	 * 3. The leaf owner is not equal to the root we are searching
502cfc0eed0Sethanwu 	 *
503ed58f2e6Sethanwu 	 * For these cases, go to the next leaf before we continue.
5048da6d581SJan Schmidt 	 */
505ed58f2e6Sethanwu 	eb = path->nodes[0];
506ed58f2e6Sethanwu 	if (path->slots[0] >= btrfs_header_nritems(eb) ||
507cfc0eed0Sethanwu 	    is_shared_data_backref(preftrees, eb->start) ||
508cfc0eed0Sethanwu 	    ref->root_id != btrfs_header_owner(eb)) {
509a2c8d27eSFilipe Manana 		if (ctx->time_seq == BTRFS_SEQ_LAST)
51021633fc6SQu Wenruo 			ret = btrfs_next_leaf(root, path);
51121633fc6SQu Wenruo 		else
512a2c8d27eSFilipe Manana 			ret = btrfs_next_old_leaf(root, path, ctx->time_seq);
51321633fc6SQu Wenruo 	}
5148da6d581SJan Schmidt 
515b25b0b87Sethanwu 	while (!ret && count < ref->count) {
5168da6d581SJan Schmidt 		eb = path->nodes[0];
51769bca40dSAlexander Block 		slot = path->slots[0];
51869bca40dSAlexander Block 
51969bca40dSAlexander Block 		btrfs_item_key_to_cpu(eb, &key, slot);
52069bca40dSAlexander Block 
52169bca40dSAlexander Block 		if (key.objectid != key_for_search->objectid ||
52269bca40dSAlexander Block 		    key.type != BTRFS_EXTENT_DATA_KEY)
52369bca40dSAlexander Block 			break;
52469bca40dSAlexander Block 
525ed58f2e6Sethanwu 		/*
526ed58f2e6Sethanwu 		 * We are searching for normal backref but bytenr of this leaf
527cfc0eed0Sethanwu 		 * matches shared data backref, OR
528cfc0eed0Sethanwu 		 * the leaf owner is not equal to the root we are searching for
529ed58f2e6Sethanwu 		 */
530cfc0eed0Sethanwu 		if (slot == 0 &&
531cfc0eed0Sethanwu 		    (is_shared_data_backref(preftrees, eb->start) ||
532cfc0eed0Sethanwu 		     ref->root_id != btrfs_header_owner(eb))) {
533a2c8d27eSFilipe Manana 			if (ctx->time_seq == BTRFS_SEQ_LAST)
534ed58f2e6Sethanwu 				ret = btrfs_next_leaf(root, path);
535ed58f2e6Sethanwu 			else
536a2c8d27eSFilipe Manana 				ret = btrfs_next_old_leaf(root, path, ctx->time_seq);
537ed58f2e6Sethanwu 			continue;
538ed58f2e6Sethanwu 		}
53969bca40dSAlexander Block 		fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5408da6d581SJan Schmidt 		disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
5417ac8b88eSethanwu 		data_offset = btrfs_file_extent_offset(eb, fi);
54269bca40dSAlexander Block 
54369bca40dSAlexander Block 		if (disk_byte == wanted_disk_byte) {
54469bca40dSAlexander Block 			eie = NULL;
545ed8c4913SJosef Bacik 			old = NULL;
5467ac8b88eSethanwu 			if (ref->key_for_search.offset == key.offset - data_offset)
5477ef81ac8SJosef Bacik 				count++;
5487ac8b88eSethanwu 			else
5497ac8b88eSethanwu 				goto next;
550a2c8d27eSFilipe Manana 			if (!ctx->ignore_extent_item_pos) {
55188ffb665SFilipe Manana 				ret = check_extent_in_eb(ctx, &key, eb, fi, &eie);
55288ffb665SFilipe Manana 				if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
55388ffb665SFilipe Manana 				    ret < 0)
55469bca40dSAlexander Block 					break;
5558da6d581SJan Schmidt 			}
556ed8c4913SJosef Bacik 			if (ret > 0)
557ed8c4913SJosef Bacik 				goto next;
5584eb1f66dSTakashi Iwai 			ret = ulist_add_merge_ptr(parents, eb->start,
5594eb1f66dSTakashi Iwai 						  eie, (void **)&old, GFP_NOFS);
56069bca40dSAlexander Block 			if (ret < 0)
56169bca40dSAlexander Block 				break;
562a2c8d27eSFilipe Manana 			if (!ret && !ctx->ignore_extent_item_pos) {
563ed8c4913SJosef Bacik 				while (old->next)
564ed8c4913SJosef Bacik 					old = old->next;
565ed8c4913SJosef Bacik 				old->next = eie;
56669bca40dSAlexander Block 			}
567f05c4746SWang Shilong 			eie = NULL;
56869bca40dSAlexander Block 		}
569ed8c4913SJosef Bacik next:
570a2c8d27eSFilipe Manana 		if (ctx->time_seq == BTRFS_SEQ_LAST)
57121633fc6SQu Wenruo 			ret = btrfs_next_item(root, path);
57221633fc6SQu Wenruo 		else
573a2c8d27eSFilipe Manana 			ret = btrfs_next_old_item(root, path, ctx->time_seq);
5748da6d581SJan Schmidt 	}
5758da6d581SJan Schmidt 
57688ffb665SFilipe Manana 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
577f05c4746SWang Shilong 		free_inode_elem_list(eie);
57888ffb665SFilipe Manana 	else if (ret > 0)
57988ffb665SFilipe Manana 		ret = 0;
58088ffb665SFilipe Manana 
58169bca40dSAlexander Block 	return ret;
5828da6d581SJan Schmidt }
5838da6d581SJan Schmidt 
5848da6d581SJan Schmidt /*
5858da6d581SJan Schmidt  * resolve an indirect backref in the form (root_id, key, level)
5868da6d581SJan Schmidt  * to a logical address
5878da6d581SJan Schmidt  */
588a2c8d27eSFilipe Manana static int resolve_indirect_ref(struct btrfs_backref_walk_ctx *ctx,
589a2c8d27eSFilipe Manana 				struct btrfs_path *path,
590ed58f2e6Sethanwu 				struct preftrees *preftrees,
591a2c8d27eSFilipe Manana 				struct prelim_ref *ref, struct ulist *parents)
5928da6d581SJan Schmidt {
5938da6d581SJan Schmidt 	struct btrfs_root *root;
5948da6d581SJan Schmidt 	struct extent_buffer *eb;
5958da6d581SJan Schmidt 	int ret = 0;
5968da6d581SJan Schmidt 	int root_level;
5978da6d581SJan Schmidt 	int level = ref->level;
5987ac8b88eSethanwu 	struct btrfs_key search_key = ref->key_for_search;
5998da6d581SJan Schmidt 
60049d11beaSJosef Bacik 	/*
60149d11beaSJosef Bacik 	 * If we're search_commit_root we could possibly be holding locks on
60249d11beaSJosef Bacik 	 * other tree nodes.  This happens when qgroups does backref walks when
60349d11beaSJosef Bacik 	 * adding new delayed refs.  To deal with this we need to look in cache
60449d11beaSJosef Bacik 	 * for the root, and if we don't find it then we need to search the
60549d11beaSJosef Bacik 	 * tree_root's commit root, thus the btrfs_get_fs_root_commit_root usage
60649d11beaSJosef Bacik 	 * here.
60749d11beaSJosef Bacik 	 */
60849d11beaSJosef Bacik 	if (path->search_commit_root)
609a2c8d27eSFilipe Manana 		root = btrfs_get_fs_root_commit_root(ctx->fs_info, path, ref->root_id);
61049d11beaSJosef Bacik 	else
611a2c8d27eSFilipe Manana 		root = btrfs_get_fs_root(ctx->fs_info, ref->root_id, false);
6128da6d581SJan Schmidt 	if (IS_ERR(root)) {
6138da6d581SJan Schmidt 		ret = PTR_ERR(root);
6149326f76fSJosef Bacik 		goto out_free;
6159326f76fSJosef Bacik 	}
6169326f76fSJosef Bacik 
61739dba873SJosef Bacik 	if (!path->search_commit_root &&
61839dba873SJosef Bacik 	    test_bit(BTRFS_ROOT_DELETING, &root->state)) {
61939dba873SJosef Bacik 		ret = -ENOENT;
62039dba873SJosef Bacik 		goto out;
62139dba873SJosef Bacik 	}
62239dba873SJosef Bacik 
623a2c8d27eSFilipe Manana 	if (btrfs_is_testing(ctx->fs_info)) {
624d9ee522bSJosef Bacik 		ret = -ENOENT;
625d9ee522bSJosef Bacik 		goto out;
626d9ee522bSJosef Bacik 	}
627d9ee522bSJosef Bacik 
6289e351cc8SJosef Bacik 	if (path->search_commit_root)
6299e351cc8SJosef Bacik 		root_level = btrfs_header_level(root->commit_root);
630a2c8d27eSFilipe Manana 	else if (ctx->time_seq == BTRFS_SEQ_LAST)
63121633fc6SQu Wenruo 		root_level = btrfs_header_level(root->node);
6329e351cc8SJosef Bacik 	else
633a2c8d27eSFilipe Manana 		root_level = btrfs_old_root_level(root, ctx->time_seq);
6348da6d581SJan Schmidt 
635c75e8394SJosef Bacik 	if (root_level + 1 == level)
6368da6d581SJan Schmidt 		goto out;
6378da6d581SJan Schmidt 
6387ac8b88eSethanwu 	/*
6397ac8b88eSethanwu 	 * We can often find data backrefs with an offset that is too large
6407ac8b88eSethanwu 	 * (>= LLONG_MAX, maximum allowed file offset) due to underflows when
6417ac8b88eSethanwu 	 * subtracting a file's offset with the data offset of its
6427ac8b88eSethanwu 	 * corresponding extent data item. This can happen for example in the
6437ac8b88eSethanwu 	 * clone ioctl.
6447ac8b88eSethanwu 	 *
6457ac8b88eSethanwu 	 * So if we detect such case we set the search key's offset to zero to
6467ac8b88eSethanwu 	 * make sure we will find the matching file extent item at
6477ac8b88eSethanwu 	 * add_all_parents(), otherwise we will miss it because the offset
6487ac8b88eSethanwu 	 * taken form the backref is much larger then the offset of the file
6497ac8b88eSethanwu 	 * extent item. This can make us scan a very large number of file
6507ac8b88eSethanwu 	 * extent items, but at least it will not make us miss any.
6517ac8b88eSethanwu 	 *
6527ac8b88eSethanwu 	 * This is an ugly workaround for a behaviour that should have never
6537ac8b88eSethanwu 	 * existed, but it does and a fix for the clone ioctl would touch a lot
6547ac8b88eSethanwu 	 * of places, cause backwards incompatibility and would not fix the
6557ac8b88eSethanwu 	 * problem for extents cloned with older kernels.
6567ac8b88eSethanwu 	 */
6577ac8b88eSethanwu 	if (search_key.type == BTRFS_EXTENT_DATA_KEY &&
6587ac8b88eSethanwu 	    search_key.offset >= LLONG_MAX)
6597ac8b88eSethanwu 		search_key.offset = 0;
6608da6d581SJan Schmidt 	path->lowest_level = level;
661a2c8d27eSFilipe Manana 	if (ctx->time_seq == BTRFS_SEQ_LAST)
6627ac8b88eSethanwu 		ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
66321633fc6SQu Wenruo 	else
664a2c8d27eSFilipe Manana 		ret = btrfs_search_old_slot(root, &search_key, path, ctx->time_seq);
665538f72cdSWang Shilong 
666a2c8d27eSFilipe Manana 	btrfs_debug(ctx->fs_info,
667ab8d0fc4SJeff Mahoney 		"search slot in root %llu (level %d, ref count %d) returned %d for key (%llu %u %llu)",
668c1c9ff7cSGeert Uytterhoeven 		 ref->root_id, level, ref->count, ret,
669c1c9ff7cSGeert Uytterhoeven 		 ref->key_for_search.objectid, ref->key_for_search.type,
670c1c9ff7cSGeert Uytterhoeven 		 ref->key_for_search.offset);
6718da6d581SJan Schmidt 	if (ret < 0)
6728da6d581SJan Schmidt 		goto out;
6738da6d581SJan Schmidt 
6748da6d581SJan Schmidt 	eb = path->nodes[level];
6759345457fSJan Schmidt 	while (!eb) {
676fae7f21cSDulshani Gunawardhana 		if (WARN_ON(!level)) {
6778da6d581SJan Schmidt 			ret = 1;
6788da6d581SJan Schmidt 			goto out;
6798da6d581SJan Schmidt 		}
6809345457fSJan Schmidt 		level--;
6819345457fSJan Schmidt 		eb = path->nodes[level];
6829345457fSJan Schmidt 	}
6838da6d581SJan Schmidt 
684a2c8d27eSFilipe Manana 	ret = add_all_parents(ctx, root, path, parents, preftrees, ref, level);
6858da6d581SJan Schmidt out:
68600246528SJosef Bacik 	btrfs_put_root(root);
6879326f76fSJosef Bacik out_free:
688da61d31aSJosef Bacik 	path->lowest_level = 0;
689da61d31aSJosef Bacik 	btrfs_release_path(path);
6908da6d581SJan Schmidt 	return ret;
6918da6d581SJan Schmidt }
6928da6d581SJan Schmidt 
6934dae077aSJeff Mahoney static struct extent_inode_elem *
6944dae077aSJeff Mahoney unode_aux_to_inode_list(struct ulist_node *node)
6954dae077aSJeff Mahoney {
6964dae077aSJeff Mahoney 	if (!node)
6974dae077aSJeff Mahoney 		return NULL;
6984dae077aSJeff Mahoney 	return (struct extent_inode_elem *)(uintptr_t)node->aux;
6994dae077aSJeff Mahoney }
7004dae077aSJeff Mahoney 
7015614dc3aSFilipe Manana static void free_leaf_list(struct ulist *ulist)
7025614dc3aSFilipe Manana {
7035614dc3aSFilipe Manana 	struct ulist_node *node;
7045614dc3aSFilipe Manana 	struct ulist_iterator uiter;
7055614dc3aSFilipe Manana 
7065614dc3aSFilipe Manana 	ULIST_ITER_INIT(&uiter);
7075614dc3aSFilipe Manana 	while ((node = ulist_next(ulist, &uiter)))
7085614dc3aSFilipe Manana 		free_inode_elem_list(unode_aux_to_inode_list(node));
7095614dc3aSFilipe Manana 
7105614dc3aSFilipe Manana 	ulist_free(ulist);
7115614dc3aSFilipe Manana }
7125614dc3aSFilipe Manana 
7138da6d581SJan Schmidt /*
71452042d8eSAndrea Gelmini  * We maintain three separate rbtrees: one for direct refs, one for
71586d5f994SEdmund Nadolski  * indirect refs which have a key, and one for indirect refs which do not
71686d5f994SEdmund Nadolski  * have a key. Each tree does merge on insertion.
71786d5f994SEdmund Nadolski  *
71886d5f994SEdmund Nadolski  * Once all of the references are located, we iterate over the tree of
71986d5f994SEdmund Nadolski  * indirect refs with missing keys. An appropriate key is located and
72086d5f994SEdmund Nadolski  * the ref is moved onto the tree for indirect refs. After all missing
72186d5f994SEdmund Nadolski  * keys are thus located, we iterate over the indirect ref tree, resolve
72286d5f994SEdmund Nadolski  * each reference, and then insert the resolved reference onto the
72386d5f994SEdmund Nadolski  * direct tree (merging there too).
72486d5f994SEdmund Nadolski  *
72586d5f994SEdmund Nadolski  * New backrefs (i.e., for parent nodes) are added to the appropriate
72686d5f994SEdmund Nadolski  * rbtree as they are encountered. The new backrefs are subsequently
72786d5f994SEdmund Nadolski  * resolved as above.
7288da6d581SJan Schmidt  */
729a2c8d27eSFilipe Manana static int resolve_indirect_refs(struct btrfs_backref_walk_ctx *ctx,
730a2c8d27eSFilipe Manana 				 struct btrfs_path *path,
73186d5f994SEdmund Nadolski 				 struct preftrees *preftrees,
7326ce6ba53SFilipe Manana 				 struct share_check *sc)
7338da6d581SJan Schmidt {
7348da6d581SJan Schmidt 	int err;
7358da6d581SJan Schmidt 	int ret = 0;
7368da6d581SJan Schmidt 	struct ulist *parents;
7378da6d581SJan Schmidt 	struct ulist_node *node;
738cd1b413cSJan Schmidt 	struct ulist_iterator uiter;
73986d5f994SEdmund Nadolski 	struct rb_node *rnode;
7408da6d581SJan Schmidt 
7418da6d581SJan Schmidt 	parents = ulist_alloc(GFP_NOFS);
7428da6d581SJan Schmidt 	if (!parents)
7438da6d581SJan Schmidt 		return -ENOMEM;
7448da6d581SJan Schmidt 
7458da6d581SJan Schmidt 	/*
74686d5f994SEdmund Nadolski 	 * We could trade memory usage for performance here by iterating
74786d5f994SEdmund Nadolski 	 * the tree, allocating new refs for each insertion, and then
74886d5f994SEdmund Nadolski 	 * freeing the entire indirect tree when we're done.  In some test
74986d5f994SEdmund Nadolski 	 * cases, the tree can grow quite large (~200k objects).
7508da6d581SJan Schmidt 	 */
751ecf160b4SLiu Bo 	while ((rnode = rb_first_cached(&preftrees->indirect.root))) {
75286d5f994SEdmund Nadolski 		struct prelim_ref *ref;
75386d5f994SEdmund Nadolski 
75486d5f994SEdmund Nadolski 		ref = rb_entry(rnode, struct prelim_ref, rbnode);
75586d5f994SEdmund Nadolski 		if (WARN(ref->parent,
75686d5f994SEdmund Nadolski 			 "BUG: direct ref found in indirect tree")) {
75786d5f994SEdmund Nadolski 			ret = -EINVAL;
75886d5f994SEdmund Nadolski 			goto out;
75986d5f994SEdmund Nadolski 		}
76086d5f994SEdmund Nadolski 
761ecf160b4SLiu Bo 		rb_erase_cached(&ref->rbnode, &preftrees->indirect.root);
7626c336b21SJeff Mahoney 		preftrees->indirect.count--;
76386d5f994SEdmund Nadolski 
76486d5f994SEdmund Nadolski 		if (ref->count == 0) {
76586d5f994SEdmund Nadolski 			free_pref(ref);
7668da6d581SJan Schmidt 			continue;
76786d5f994SEdmund Nadolski 		}
76886d5f994SEdmund Nadolski 
769877c1476SFilipe Manana 		if (sc && ref->root_id != sc->root->root_key.objectid) {
77086d5f994SEdmund Nadolski 			free_pref(ref);
771dc046b10SJosef Bacik 			ret = BACKREF_FOUND_SHARED;
772dc046b10SJosef Bacik 			goto out;
773dc046b10SJosef Bacik 		}
774a2c8d27eSFilipe Manana 		err = resolve_indirect_ref(ctx, path, preftrees, ref, parents);
77595def2edSWang Shilong 		/*
77695def2edSWang Shilong 		 * we can only tolerate ENOENT,otherwise,we should catch error
77795def2edSWang Shilong 		 * and return directly.
77895def2edSWang Shilong 		 */
77995def2edSWang Shilong 		if (err == -ENOENT) {
780a2c8d27eSFilipe Manana 			prelim_ref_insert(ctx->fs_info, &preftrees->direct, ref,
7813ec4d323SEdmund Nadolski 					  NULL);
7828da6d581SJan Schmidt 			continue;
78395def2edSWang Shilong 		} else if (err) {
78486d5f994SEdmund Nadolski 			free_pref(ref);
78595def2edSWang Shilong 			ret = err;
78695def2edSWang Shilong 			goto out;
78795def2edSWang Shilong 		}
7888da6d581SJan Schmidt 
7898da6d581SJan Schmidt 		/* we put the first parent into the ref at hand */
790cd1b413cSJan Schmidt 		ULIST_ITER_INIT(&uiter);
791cd1b413cSJan Schmidt 		node = ulist_next(parents, &uiter);
7928da6d581SJan Schmidt 		ref->parent = node ? node->val : 0;
7934dae077aSJeff Mahoney 		ref->inode_list = unode_aux_to_inode_list(node);
7948da6d581SJan Schmidt 
79586d5f994SEdmund Nadolski 		/* Add a prelim_ref(s) for any other parent(s). */
796cd1b413cSJan Schmidt 		while ((node = ulist_next(parents, &uiter))) {
79786d5f994SEdmund Nadolski 			struct prelim_ref *new_ref;
79886d5f994SEdmund Nadolski 
799b9e9a6cbSWang Shilong 			new_ref = kmem_cache_alloc(btrfs_prelim_ref_cache,
800b9e9a6cbSWang Shilong 						   GFP_NOFS);
8018da6d581SJan Schmidt 			if (!new_ref) {
80286d5f994SEdmund Nadolski 				free_pref(ref);
8038da6d581SJan Schmidt 				ret = -ENOMEM;
804e36902d4SWang Shilong 				goto out;
8058da6d581SJan Schmidt 			}
8068da6d581SJan Schmidt 			memcpy(new_ref, ref, sizeof(*ref));
8078da6d581SJan Schmidt 			new_ref->parent = node->val;
8084dae077aSJeff Mahoney 			new_ref->inode_list = unode_aux_to_inode_list(node);
809a2c8d27eSFilipe Manana 			prelim_ref_insert(ctx->fs_info, &preftrees->direct,
8103ec4d323SEdmund Nadolski 					  new_ref, NULL);
8118da6d581SJan Schmidt 		}
81286d5f994SEdmund Nadolski 
8133ec4d323SEdmund Nadolski 		/*
81452042d8eSAndrea Gelmini 		 * Now it's a direct ref, put it in the direct tree. We must
8153ec4d323SEdmund Nadolski 		 * do this last because the ref could be merged/freed here.
8163ec4d323SEdmund Nadolski 		 */
817a2c8d27eSFilipe Manana 		prelim_ref_insert(ctx->fs_info, &preftrees->direct, ref, NULL);
81886d5f994SEdmund Nadolski 
8198da6d581SJan Schmidt 		ulist_reinit(parents);
8209dd14fd6SEdmund Nadolski 		cond_resched();
8218da6d581SJan Schmidt 	}
822e36902d4SWang Shilong out:
8235614dc3aSFilipe Manana 	/*
8245614dc3aSFilipe Manana 	 * We may have inode lists attached to refs in the parents ulist, so we
8255614dc3aSFilipe Manana 	 * must free them before freeing the ulist and its refs.
8265614dc3aSFilipe Manana 	 */
8275614dc3aSFilipe Manana 	free_leaf_list(parents);
8288da6d581SJan Schmidt 	return ret;
8298da6d581SJan Schmidt }
8308da6d581SJan Schmidt 
831d5c88b73SJan Schmidt /*
832d5c88b73SJan Schmidt  * read tree blocks and add keys where required.
833d5c88b73SJan Schmidt  */
834e0c476b1SJeff Mahoney static int add_missing_keys(struct btrfs_fs_info *fs_info,
83538e3eebfSJosef Bacik 			    struct preftrees *preftrees, bool lock)
836d5c88b73SJan Schmidt {
837e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
838d5c88b73SJan Schmidt 	struct extent_buffer *eb;
83986d5f994SEdmund Nadolski 	struct preftree *tree = &preftrees->indirect_missing_keys;
84086d5f994SEdmund Nadolski 	struct rb_node *node;
841d5c88b73SJan Schmidt 
842ecf160b4SLiu Bo 	while ((node = rb_first_cached(&tree->root))) {
84386d5f994SEdmund Nadolski 		ref = rb_entry(node, struct prelim_ref, rbnode);
844ecf160b4SLiu Bo 		rb_erase_cached(node, &tree->root);
84586d5f994SEdmund Nadolski 
84686d5f994SEdmund Nadolski 		BUG_ON(ref->parent);	/* should not be a direct ref */
84786d5f994SEdmund Nadolski 		BUG_ON(ref->key_for_search.type);
848d5c88b73SJan Schmidt 		BUG_ON(!ref->wanted_disk_byte);
84986d5f994SEdmund Nadolski 
8501b7ec85eSJosef Bacik 		eb = read_tree_block(fs_info, ref->wanted_disk_byte,
8511b7ec85eSJosef Bacik 				     ref->root_id, 0, ref->level - 1, NULL);
85264c043deSLiu Bo 		if (IS_ERR(eb)) {
85386d5f994SEdmund Nadolski 			free_pref(ref);
85464c043deSLiu Bo 			return PTR_ERR(eb);
8554eb150d6SQu Wenruo 		}
8564eb150d6SQu Wenruo 		if (!extent_buffer_uptodate(eb)) {
85786d5f994SEdmund Nadolski 			free_pref(ref);
858416bc658SJosef Bacik 			free_extent_buffer(eb);
859416bc658SJosef Bacik 			return -EIO;
860416bc658SJosef Bacik 		}
8614eb150d6SQu Wenruo 
86238e3eebfSJosef Bacik 		if (lock)
863d5c88b73SJan Schmidt 			btrfs_tree_read_lock(eb);
864d5c88b73SJan Schmidt 		if (btrfs_header_level(eb) == 0)
865d5c88b73SJan Schmidt 			btrfs_item_key_to_cpu(eb, &ref->key_for_search, 0);
866d5c88b73SJan Schmidt 		else
867d5c88b73SJan Schmidt 			btrfs_node_key_to_cpu(eb, &ref->key_for_search, 0);
86838e3eebfSJosef Bacik 		if (lock)
869d5c88b73SJan Schmidt 			btrfs_tree_read_unlock(eb);
870d5c88b73SJan Schmidt 		free_extent_buffer(eb);
8713ec4d323SEdmund Nadolski 		prelim_ref_insert(fs_info, &preftrees->indirect, ref, NULL);
8729dd14fd6SEdmund Nadolski 		cond_resched();
873d5c88b73SJan Schmidt 	}
874d5c88b73SJan Schmidt 	return 0;
875d5c88b73SJan Schmidt }
876d5c88b73SJan Schmidt 
8778da6d581SJan Schmidt /*
8788da6d581SJan Schmidt  * add all currently queued delayed refs from this head whose seq nr is
8798da6d581SJan Schmidt  * smaller or equal that seq to the list
8808da6d581SJan Schmidt  */
88100142756SJeff Mahoney static int add_delayed_refs(const struct btrfs_fs_info *fs_info,
88200142756SJeff Mahoney 			    struct btrfs_delayed_ref_head *head, u64 seq,
883b25b0b87Sethanwu 			    struct preftrees *preftrees, struct share_check *sc)
8848da6d581SJan Schmidt {
885c6fc2454SQu Wenruo 	struct btrfs_delayed_ref_node *node;
886d5c88b73SJan Schmidt 	struct btrfs_key key;
8870e0adbcfSJosef Bacik 	struct rb_node *n;
88801747e92SEdmund Nadolski 	int count;
889b1375d64SJan Schmidt 	int ret = 0;
8908da6d581SJan Schmidt 
891d7df2c79SJosef Bacik 	spin_lock(&head->lock);
892e3d03965SLiu Bo 	for (n = rb_first_cached(&head->ref_tree); n; n = rb_next(n)) {
8930e0adbcfSJosef Bacik 		node = rb_entry(n, struct btrfs_delayed_ref_node,
8940e0adbcfSJosef Bacik 				ref_node);
8958da6d581SJan Schmidt 		if (node->seq > seq)
8968da6d581SJan Schmidt 			continue;
8978da6d581SJan Schmidt 
8988da6d581SJan Schmidt 		switch (node->action) {
8998da6d581SJan Schmidt 		case BTRFS_ADD_DELAYED_EXTENT:
9008da6d581SJan Schmidt 		case BTRFS_UPDATE_DELAYED_HEAD:
9018da6d581SJan Schmidt 			WARN_ON(1);
9028da6d581SJan Schmidt 			continue;
9038da6d581SJan Schmidt 		case BTRFS_ADD_DELAYED_REF:
90401747e92SEdmund Nadolski 			count = node->ref_mod;
9058da6d581SJan Schmidt 			break;
9068da6d581SJan Schmidt 		case BTRFS_DROP_DELAYED_REF:
90701747e92SEdmund Nadolski 			count = node->ref_mod * -1;
9088da6d581SJan Schmidt 			break;
9098da6d581SJan Schmidt 		default:
910290342f6SArnd Bergmann 			BUG();
9118da6d581SJan Schmidt 		}
9128da6d581SJan Schmidt 		switch (node->type) {
9138da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY: {
91486d5f994SEdmund Nadolski 			/* NORMAL INDIRECT METADATA backref */
9158da6d581SJan Schmidt 			struct btrfs_delayed_tree_ref *ref;
916943553efSFilipe Manana 			struct btrfs_key *key_ptr = NULL;
917943553efSFilipe Manana 
918943553efSFilipe Manana 			if (head->extent_op && head->extent_op->update_key) {
919943553efSFilipe Manana 				btrfs_disk_key_to_cpu(&key, &head->extent_op->key);
920943553efSFilipe Manana 				key_ptr = &key;
921943553efSFilipe Manana 			}
9228da6d581SJan Schmidt 
9238da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_tree_ref(node);
92400142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, ref->root,
925943553efSFilipe Manana 					       key_ptr, ref->level + 1,
92601747e92SEdmund Nadolski 					       node->bytenr, count, sc,
92701747e92SEdmund Nadolski 					       GFP_ATOMIC);
9288da6d581SJan Schmidt 			break;
9298da6d581SJan Schmidt 		}
9308da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY: {
93186d5f994SEdmund Nadolski 			/* SHARED DIRECT METADATA backref */
9328da6d581SJan Schmidt 			struct btrfs_delayed_tree_ref *ref;
9338da6d581SJan Schmidt 
9348da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_tree_ref(node);
93586d5f994SEdmund Nadolski 
93601747e92SEdmund Nadolski 			ret = add_direct_ref(fs_info, preftrees, ref->level + 1,
93701747e92SEdmund Nadolski 					     ref->parent, node->bytenr, count,
9383ec4d323SEdmund Nadolski 					     sc, GFP_ATOMIC);
9398da6d581SJan Schmidt 			break;
9408da6d581SJan Schmidt 		}
9418da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
94286d5f994SEdmund Nadolski 			/* NORMAL INDIRECT DATA backref */
9438da6d581SJan Schmidt 			struct btrfs_delayed_data_ref *ref;
9448da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_data_ref(node);
9458da6d581SJan Schmidt 
9468da6d581SJan Schmidt 			key.objectid = ref->objectid;
9478da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
9488da6d581SJan Schmidt 			key.offset = ref->offset;
949dc046b10SJosef Bacik 
950dc046b10SJosef Bacik 			/*
9514fc7b572SFilipe Manana 			 * If we have a share check context and a reference for
9524fc7b572SFilipe Manana 			 * another inode, we can't exit immediately. This is
9534fc7b572SFilipe Manana 			 * because even if this is a BTRFS_ADD_DELAYED_REF
9544fc7b572SFilipe Manana 			 * reference we may find next a BTRFS_DROP_DELAYED_REF
9554fc7b572SFilipe Manana 			 * which cancels out this ADD reference.
9564fc7b572SFilipe Manana 			 *
9574fc7b572SFilipe Manana 			 * If this is a DROP reference and there was no previous
9584fc7b572SFilipe Manana 			 * ADD reference, then we need to signal that when we
9594fc7b572SFilipe Manana 			 * process references from the extent tree (through
9604fc7b572SFilipe Manana 			 * add_inline_refs() and add_keyed_refs()), we should
9614fc7b572SFilipe Manana 			 * not exit early if we find a reference for another
9624fc7b572SFilipe Manana 			 * inode, because one of the delayed DROP references
9634fc7b572SFilipe Manana 			 * may cancel that reference in the extent tree.
964dc046b10SJosef Bacik 			 */
9654fc7b572SFilipe Manana 			if (sc && count < 0)
9664fc7b572SFilipe Manana 				sc->have_delayed_delete_refs = true;
967dc046b10SJosef Bacik 
96800142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, ref->root,
96901747e92SEdmund Nadolski 					       &key, 0, node->bytenr, count, sc,
97001747e92SEdmund Nadolski 					       GFP_ATOMIC);
9718da6d581SJan Schmidt 			break;
9728da6d581SJan Schmidt 		}
9738da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
97486d5f994SEdmund Nadolski 			/* SHARED DIRECT FULL backref */
9758da6d581SJan Schmidt 			struct btrfs_delayed_data_ref *ref;
9768da6d581SJan Schmidt 
9778da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_data_ref(node);
97886d5f994SEdmund Nadolski 
97901747e92SEdmund Nadolski 			ret = add_direct_ref(fs_info, preftrees, 0, ref->parent,
98001747e92SEdmund Nadolski 					     node->bytenr, count, sc,
98101747e92SEdmund Nadolski 					     GFP_ATOMIC);
9828da6d581SJan Schmidt 			break;
9838da6d581SJan Schmidt 		}
9848da6d581SJan Schmidt 		default:
9858da6d581SJan Schmidt 			WARN_ON(1);
9868da6d581SJan Schmidt 		}
9873ec4d323SEdmund Nadolski 		/*
9883ec4d323SEdmund Nadolski 		 * We must ignore BACKREF_FOUND_SHARED until all delayed
9893ec4d323SEdmund Nadolski 		 * refs have been checked.
9903ec4d323SEdmund Nadolski 		 */
9913ec4d323SEdmund Nadolski 		if (ret && (ret != BACKREF_FOUND_SHARED))
992d7df2c79SJosef Bacik 			break;
9938da6d581SJan Schmidt 	}
9943ec4d323SEdmund Nadolski 	if (!ret)
9953ec4d323SEdmund Nadolski 		ret = extent_is_shared(sc);
9964fc7b572SFilipe Manana 
997d7df2c79SJosef Bacik 	spin_unlock(&head->lock);
998d7df2c79SJosef Bacik 	return ret;
9998da6d581SJan Schmidt }
10008da6d581SJan Schmidt 
10018da6d581SJan Schmidt /*
10028da6d581SJan Schmidt  * add all inline backrefs for bytenr to the list
10033ec4d323SEdmund Nadolski  *
10043ec4d323SEdmund Nadolski  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
10058da6d581SJan Schmidt  */
1006f73853c7SFilipe Manana static int add_inline_refs(struct btrfs_backref_walk_ctx *ctx,
1007f73853c7SFilipe Manana 			   struct btrfs_path *path,
100886d5f994SEdmund Nadolski 			   int *info_level, struct preftrees *preftrees,
1009b25b0b87Sethanwu 			   struct share_check *sc)
10108da6d581SJan Schmidt {
1011b1375d64SJan Schmidt 	int ret = 0;
10128da6d581SJan Schmidt 	int slot;
10138da6d581SJan Schmidt 	struct extent_buffer *leaf;
10148da6d581SJan Schmidt 	struct btrfs_key key;
1015261c84b6SJosef Bacik 	struct btrfs_key found_key;
10168da6d581SJan Schmidt 	unsigned long ptr;
10178da6d581SJan Schmidt 	unsigned long end;
10188da6d581SJan Schmidt 	struct btrfs_extent_item *ei;
10198da6d581SJan Schmidt 	u64 flags;
10208da6d581SJan Schmidt 	u64 item_size;
10218da6d581SJan Schmidt 
10228da6d581SJan Schmidt 	/*
10238da6d581SJan Schmidt 	 * enumerate all inline refs
10248da6d581SJan Schmidt 	 */
10258da6d581SJan Schmidt 	leaf = path->nodes[0];
1026dadcaf78SJan Schmidt 	slot = path->slots[0];
10278da6d581SJan Schmidt 
10283212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, slot);
10298da6d581SJan Schmidt 	BUG_ON(item_size < sizeof(*ei));
10308da6d581SJan Schmidt 
10318da6d581SJan Schmidt 	ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
1032f73853c7SFilipe Manana 
1033f73853c7SFilipe Manana 	if (ctx->check_extent_item) {
1034f73853c7SFilipe Manana 		ret = ctx->check_extent_item(ctx->bytenr, ei, leaf, ctx->user_ctx);
1035f73853c7SFilipe Manana 		if (ret)
1036f73853c7SFilipe Manana 			return ret;
1037f73853c7SFilipe Manana 	}
1038f73853c7SFilipe Manana 
10398da6d581SJan Schmidt 	flags = btrfs_extent_flags(leaf, ei);
1040261c84b6SJosef Bacik 	btrfs_item_key_to_cpu(leaf, &found_key, slot);
10418da6d581SJan Schmidt 
10428da6d581SJan Schmidt 	ptr = (unsigned long)(ei + 1);
10438da6d581SJan Schmidt 	end = (unsigned long)ei + item_size;
10448da6d581SJan Schmidt 
1045261c84b6SJosef Bacik 	if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
1046261c84b6SJosef Bacik 	    flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
10478da6d581SJan Schmidt 		struct btrfs_tree_block_info *info;
10488da6d581SJan Schmidt 
10498da6d581SJan Schmidt 		info = (struct btrfs_tree_block_info *)ptr;
10508da6d581SJan Schmidt 		*info_level = btrfs_tree_block_level(leaf, info);
10518da6d581SJan Schmidt 		ptr += sizeof(struct btrfs_tree_block_info);
10528da6d581SJan Schmidt 		BUG_ON(ptr > end);
1053261c84b6SJosef Bacik 	} else if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
1054261c84b6SJosef Bacik 		*info_level = found_key.offset;
10558da6d581SJan Schmidt 	} else {
10568da6d581SJan Schmidt 		BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
10578da6d581SJan Schmidt 	}
10588da6d581SJan Schmidt 
10598da6d581SJan Schmidt 	while (ptr < end) {
10608da6d581SJan Schmidt 		struct btrfs_extent_inline_ref *iref;
10618da6d581SJan Schmidt 		u64 offset;
10628da6d581SJan Schmidt 		int type;
10638da6d581SJan Schmidt 
10648da6d581SJan Schmidt 		iref = (struct btrfs_extent_inline_ref *)ptr;
10653de28d57SLiu Bo 		type = btrfs_get_extent_inline_ref_type(leaf, iref,
10663de28d57SLiu Bo 							BTRFS_REF_TYPE_ANY);
10673de28d57SLiu Bo 		if (type == BTRFS_REF_TYPE_INVALID)
1068af431dcbSSu Yue 			return -EUCLEAN;
10693de28d57SLiu Bo 
10708da6d581SJan Schmidt 		offset = btrfs_extent_inline_ref_offset(leaf, iref);
10718da6d581SJan Schmidt 
10728da6d581SJan Schmidt 		switch (type) {
10738da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY:
1074f73853c7SFilipe Manana 			ret = add_direct_ref(ctx->fs_info, preftrees,
107500142756SJeff Mahoney 					     *info_level + 1, offset,
1076f73853c7SFilipe Manana 					     ctx->bytenr, 1, NULL, GFP_NOFS);
10778da6d581SJan Schmidt 			break;
10788da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
10798da6d581SJan Schmidt 			struct btrfs_shared_data_ref *sdref;
10808da6d581SJan Schmidt 			int count;
10818da6d581SJan Schmidt 
10828da6d581SJan Schmidt 			sdref = (struct btrfs_shared_data_ref *)(iref + 1);
10838da6d581SJan Schmidt 			count = btrfs_shared_data_ref_count(leaf, sdref);
108486d5f994SEdmund Nadolski 
1085f73853c7SFilipe Manana 			ret = add_direct_ref(ctx->fs_info, preftrees, 0, offset,
1086f73853c7SFilipe Manana 					     ctx->bytenr, count, sc, GFP_NOFS);
10878da6d581SJan Schmidt 			break;
10888da6d581SJan Schmidt 		}
10898da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY:
1090f73853c7SFilipe Manana 			ret = add_indirect_ref(ctx->fs_info, preftrees, offset,
109100142756SJeff Mahoney 					       NULL, *info_level + 1,
1092f73853c7SFilipe Manana 					       ctx->bytenr, 1, NULL, GFP_NOFS);
10938da6d581SJan Schmidt 			break;
10948da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
10958da6d581SJan Schmidt 			struct btrfs_extent_data_ref *dref;
10968da6d581SJan Schmidt 			int count;
10978da6d581SJan Schmidt 			u64 root;
10988da6d581SJan Schmidt 
10998da6d581SJan Schmidt 			dref = (struct btrfs_extent_data_ref *)(&iref->offset);
11008da6d581SJan Schmidt 			count = btrfs_extent_data_ref_count(leaf, dref);
11018da6d581SJan Schmidt 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
11028da6d581SJan Schmidt 								      dref);
11038da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
11048da6d581SJan Schmidt 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1105dc046b10SJosef Bacik 
1106a0a5472aSFilipe Manana 			if (sc && key.objectid != sc->inum &&
11074fc7b572SFilipe Manana 			    !sc->have_delayed_delete_refs) {
1108dc046b10SJosef Bacik 				ret = BACKREF_FOUND_SHARED;
1109dc046b10SJosef Bacik 				break;
1110dc046b10SJosef Bacik 			}
1111dc046b10SJosef Bacik 
11128da6d581SJan Schmidt 			root = btrfs_extent_data_ref_root(leaf, dref);
111386d5f994SEdmund Nadolski 
1114*adf02418SFilipe Manana 			if (!ctx->skip_data_ref ||
1115*adf02418SFilipe Manana 			    !ctx->skip_data_ref(root, key.objectid, key.offset,
1116*adf02418SFilipe Manana 						ctx->user_ctx))
1117*adf02418SFilipe Manana 				ret = add_indirect_ref(ctx->fs_info, preftrees,
1118*adf02418SFilipe Manana 						       root, &key, 0, ctx->bytenr,
1119*adf02418SFilipe Manana 						       count, sc, GFP_NOFS);
11208da6d581SJan Schmidt 			break;
11218da6d581SJan Schmidt 		}
11228da6d581SJan Schmidt 		default:
11238da6d581SJan Schmidt 			WARN_ON(1);
11248da6d581SJan Schmidt 		}
11251149ab6bSWang Shilong 		if (ret)
11261149ab6bSWang Shilong 			return ret;
11278da6d581SJan Schmidt 		ptr += btrfs_extent_inline_ref_size(type);
11288da6d581SJan Schmidt 	}
11298da6d581SJan Schmidt 
11308da6d581SJan Schmidt 	return 0;
11318da6d581SJan Schmidt }
11328da6d581SJan Schmidt 
11338da6d581SJan Schmidt /*
11348da6d581SJan Schmidt  * add all non-inline backrefs for bytenr to the list
11353ec4d323SEdmund Nadolski  *
11363ec4d323SEdmund Nadolski  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
11378da6d581SJan Schmidt  */
1138*adf02418SFilipe Manana static int add_keyed_refs(struct btrfs_backref_walk_ctx *ctx,
1139*adf02418SFilipe Manana 			  struct btrfs_root *extent_root,
1140*adf02418SFilipe Manana 			  struct btrfs_path *path,
114186d5f994SEdmund Nadolski 			  int info_level, struct preftrees *preftrees,
11423ec4d323SEdmund Nadolski 			  struct share_check *sc)
11438da6d581SJan Schmidt {
114498cc4222SJosef Bacik 	struct btrfs_fs_info *fs_info = extent_root->fs_info;
11458da6d581SJan Schmidt 	int ret;
11468da6d581SJan Schmidt 	int slot;
11478da6d581SJan Schmidt 	struct extent_buffer *leaf;
11488da6d581SJan Schmidt 	struct btrfs_key key;
11498da6d581SJan Schmidt 
11508da6d581SJan Schmidt 	while (1) {
11518da6d581SJan Schmidt 		ret = btrfs_next_item(extent_root, path);
11528da6d581SJan Schmidt 		if (ret < 0)
11538da6d581SJan Schmidt 			break;
11548da6d581SJan Schmidt 		if (ret) {
11558da6d581SJan Schmidt 			ret = 0;
11568da6d581SJan Schmidt 			break;
11578da6d581SJan Schmidt 		}
11588da6d581SJan Schmidt 
11598da6d581SJan Schmidt 		slot = path->slots[0];
11608da6d581SJan Schmidt 		leaf = path->nodes[0];
11618da6d581SJan Schmidt 		btrfs_item_key_to_cpu(leaf, &key, slot);
11628da6d581SJan Schmidt 
1163*adf02418SFilipe Manana 		if (key.objectid != ctx->bytenr)
11648da6d581SJan Schmidt 			break;
11658da6d581SJan Schmidt 		if (key.type < BTRFS_TREE_BLOCK_REF_KEY)
11668da6d581SJan Schmidt 			continue;
11678da6d581SJan Schmidt 		if (key.type > BTRFS_SHARED_DATA_REF_KEY)
11688da6d581SJan Schmidt 			break;
11698da6d581SJan Schmidt 
11708da6d581SJan Schmidt 		switch (key.type) {
11718da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY:
117286d5f994SEdmund Nadolski 			/* SHARED DIRECT METADATA backref */
117300142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees,
117400142756SJeff Mahoney 					     info_level + 1, key.offset,
1175*adf02418SFilipe Manana 					     ctx->bytenr, 1, NULL, GFP_NOFS);
11768da6d581SJan Schmidt 			break;
11778da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
117886d5f994SEdmund Nadolski 			/* SHARED DIRECT FULL backref */
11798da6d581SJan Schmidt 			struct btrfs_shared_data_ref *sdref;
11808da6d581SJan Schmidt 			int count;
11818da6d581SJan Schmidt 
11828da6d581SJan Schmidt 			sdref = btrfs_item_ptr(leaf, slot,
11838da6d581SJan Schmidt 					      struct btrfs_shared_data_ref);
11848da6d581SJan Schmidt 			count = btrfs_shared_data_ref_count(leaf, sdref);
118500142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees, 0,
1186*adf02418SFilipe Manana 					     key.offset, ctx->bytenr, count,
11873ec4d323SEdmund Nadolski 					     sc, GFP_NOFS);
11888da6d581SJan Schmidt 			break;
11898da6d581SJan Schmidt 		}
11908da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY:
119186d5f994SEdmund Nadolski 			/* NORMAL INDIRECT METADATA backref */
119200142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, key.offset,
1193*adf02418SFilipe Manana 					       NULL, info_level + 1, ctx->bytenr,
11943ec4d323SEdmund Nadolski 					       1, NULL, GFP_NOFS);
11958da6d581SJan Schmidt 			break;
11968da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
119786d5f994SEdmund Nadolski 			/* NORMAL INDIRECT DATA backref */
11988da6d581SJan Schmidt 			struct btrfs_extent_data_ref *dref;
11998da6d581SJan Schmidt 			int count;
12008da6d581SJan Schmidt 			u64 root;
12018da6d581SJan Schmidt 
12028da6d581SJan Schmidt 			dref = btrfs_item_ptr(leaf, slot,
12038da6d581SJan Schmidt 					      struct btrfs_extent_data_ref);
12048da6d581SJan Schmidt 			count = btrfs_extent_data_ref_count(leaf, dref);
12058da6d581SJan Schmidt 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
12068da6d581SJan Schmidt 								      dref);
12078da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
12088da6d581SJan Schmidt 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1209dc046b10SJosef Bacik 
1210a0a5472aSFilipe Manana 			if (sc && key.objectid != sc->inum &&
12114fc7b572SFilipe Manana 			    !sc->have_delayed_delete_refs) {
1212dc046b10SJosef Bacik 				ret = BACKREF_FOUND_SHARED;
1213dc046b10SJosef Bacik 				break;
1214dc046b10SJosef Bacik 			}
1215dc046b10SJosef Bacik 
12168da6d581SJan Schmidt 			root = btrfs_extent_data_ref_root(leaf, dref);
1217*adf02418SFilipe Manana 
1218*adf02418SFilipe Manana 			if (!ctx->skip_data_ref ||
1219*adf02418SFilipe Manana 			    !ctx->skip_data_ref(root, key.objectid, key.offset,
1220*adf02418SFilipe Manana 						ctx->user_ctx))
122100142756SJeff Mahoney 				ret = add_indirect_ref(fs_info, preftrees, root,
1222*adf02418SFilipe Manana 						       &key, 0, ctx->bytenr,
1223*adf02418SFilipe Manana 						       count, sc, GFP_NOFS);
12248da6d581SJan Schmidt 			break;
12258da6d581SJan Schmidt 		}
12268da6d581SJan Schmidt 		default:
12278da6d581SJan Schmidt 			WARN_ON(1);
12288da6d581SJan Schmidt 		}
12291149ab6bSWang Shilong 		if (ret)
12301149ab6bSWang Shilong 			return ret;
12311149ab6bSWang Shilong 
12328da6d581SJan Schmidt 	}
12338da6d581SJan Schmidt 
12348da6d581SJan Schmidt 	return ret;
12358da6d581SJan Schmidt }
12368da6d581SJan Schmidt 
12378da6d581SJan Schmidt /*
1238583f4ac5SFilipe Manana  * The caller has joined a transaction or is holding a read lock on the
1239583f4ac5SFilipe Manana  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1240583f4ac5SFilipe Manana  * snapshot field changing while updating or checking the cache.
1241583f4ac5SFilipe Manana  */
1242583f4ac5SFilipe Manana static bool lookup_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1243583f4ac5SFilipe Manana 					struct btrfs_root *root,
1244583f4ac5SFilipe Manana 					u64 bytenr, int level, bool *is_shared)
1245583f4ac5SFilipe Manana {
1246583f4ac5SFilipe Manana 	struct btrfs_backref_shared_cache_entry *entry;
1247583f4ac5SFilipe Manana 
1248583f4ac5SFilipe Manana 	if (!ctx->use_path_cache)
1249583f4ac5SFilipe Manana 		return false;
1250583f4ac5SFilipe Manana 
1251583f4ac5SFilipe Manana 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1252583f4ac5SFilipe Manana 		return false;
1253583f4ac5SFilipe Manana 
1254583f4ac5SFilipe Manana 	/*
1255583f4ac5SFilipe Manana 	 * Level -1 is used for the data extent, which is not reliable to cache
1256583f4ac5SFilipe Manana 	 * because its reference count can increase or decrease without us
1257583f4ac5SFilipe Manana 	 * realizing. We cache results only for extent buffers that lead from
1258583f4ac5SFilipe Manana 	 * the root node down to the leaf with the file extent item.
1259583f4ac5SFilipe Manana 	 */
1260583f4ac5SFilipe Manana 	ASSERT(level >= 0);
1261583f4ac5SFilipe Manana 
1262583f4ac5SFilipe Manana 	entry = &ctx->path_cache_entries[level];
1263583f4ac5SFilipe Manana 
1264583f4ac5SFilipe Manana 	/* Unused cache entry or being used for some other extent buffer. */
1265583f4ac5SFilipe Manana 	if (entry->bytenr != bytenr)
1266583f4ac5SFilipe Manana 		return false;
1267583f4ac5SFilipe Manana 
1268583f4ac5SFilipe Manana 	/*
1269583f4ac5SFilipe Manana 	 * We cached a false result, but the last snapshot generation of the
1270583f4ac5SFilipe Manana 	 * root changed, so we now have a snapshot. Don't trust the result.
1271583f4ac5SFilipe Manana 	 */
1272583f4ac5SFilipe Manana 	if (!entry->is_shared &&
1273583f4ac5SFilipe Manana 	    entry->gen != btrfs_root_last_snapshot(&root->root_item))
1274583f4ac5SFilipe Manana 		return false;
1275583f4ac5SFilipe Manana 
1276583f4ac5SFilipe Manana 	/*
1277583f4ac5SFilipe Manana 	 * If we cached a true result and the last generation used for dropping
1278583f4ac5SFilipe Manana 	 * a root changed, we can not trust the result, because the dropped root
1279583f4ac5SFilipe Manana 	 * could be a snapshot sharing this extent buffer.
1280583f4ac5SFilipe Manana 	 */
1281583f4ac5SFilipe Manana 	if (entry->is_shared &&
1282583f4ac5SFilipe Manana 	    entry->gen != btrfs_get_last_root_drop_gen(root->fs_info))
1283583f4ac5SFilipe Manana 		return false;
1284583f4ac5SFilipe Manana 
1285583f4ac5SFilipe Manana 	*is_shared = entry->is_shared;
1286583f4ac5SFilipe Manana 	/*
1287583f4ac5SFilipe Manana 	 * If the node at this level is shared, than all nodes below are also
1288583f4ac5SFilipe Manana 	 * shared. Currently some of the nodes below may be marked as not shared
1289583f4ac5SFilipe Manana 	 * because we have just switched from one leaf to another, and switched
1290583f4ac5SFilipe Manana 	 * also other nodes above the leaf and below the current level, so mark
1291583f4ac5SFilipe Manana 	 * them as shared.
1292583f4ac5SFilipe Manana 	 */
1293583f4ac5SFilipe Manana 	if (*is_shared) {
1294583f4ac5SFilipe Manana 		for (int i = 0; i < level; i++) {
1295583f4ac5SFilipe Manana 			ctx->path_cache_entries[i].is_shared = true;
1296583f4ac5SFilipe Manana 			ctx->path_cache_entries[i].gen = entry->gen;
1297583f4ac5SFilipe Manana 		}
1298583f4ac5SFilipe Manana 	}
1299583f4ac5SFilipe Manana 
1300583f4ac5SFilipe Manana 	return true;
1301583f4ac5SFilipe Manana }
1302583f4ac5SFilipe Manana 
1303583f4ac5SFilipe Manana /*
1304583f4ac5SFilipe Manana  * The caller has joined a transaction or is holding a read lock on the
1305583f4ac5SFilipe Manana  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1306583f4ac5SFilipe Manana  * snapshot field changing while updating or checking the cache.
1307583f4ac5SFilipe Manana  */
1308583f4ac5SFilipe Manana static void store_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1309583f4ac5SFilipe Manana 				       struct btrfs_root *root,
1310583f4ac5SFilipe Manana 				       u64 bytenr, int level, bool is_shared)
1311583f4ac5SFilipe Manana {
1312583f4ac5SFilipe Manana 	struct btrfs_backref_shared_cache_entry *entry;
1313583f4ac5SFilipe Manana 	u64 gen;
1314583f4ac5SFilipe Manana 
1315583f4ac5SFilipe Manana 	if (!ctx->use_path_cache)
1316583f4ac5SFilipe Manana 		return;
1317583f4ac5SFilipe Manana 
1318583f4ac5SFilipe Manana 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1319583f4ac5SFilipe Manana 		return;
1320583f4ac5SFilipe Manana 
1321583f4ac5SFilipe Manana 	/*
1322583f4ac5SFilipe Manana 	 * Level -1 is used for the data extent, which is not reliable to cache
1323583f4ac5SFilipe Manana 	 * because its reference count can increase or decrease without us
1324583f4ac5SFilipe Manana 	 * realizing. We cache results only for extent buffers that lead from
1325583f4ac5SFilipe Manana 	 * the root node down to the leaf with the file extent item.
1326583f4ac5SFilipe Manana 	 */
1327583f4ac5SFilipe Manana 	ASSERT(level >= 0);
1328583f4ac5SFilipe Manana 
1329583f4ac5SFilipe Manana 	if (is_shared)
1330583f4ac5SFilipe Manana 		gen = btrfs_get_last_root_drop_gen(root->fs_info);
1331583f4ac5SFilipe Manana 	else
1332583f4ac5SFilipe Manana 		gen = btrfs_root_last_snapshot(&root->root_item);
1333583f4ac5SFilipe Manana 
1334583f4ac5SFilipe Manana 	entry = &ctx->path_cache_entries[level];
1335583f4ac5SFilipe Manana 	entry->bytenr = bytenr;
1336583f4ac5SFilipe Manana 	entry->is_shared = is_shared;
1337583f4ac5SFilipe Manana 	entry->gen = gen;
1338583f4ac5SFilipe Manana 
1339583f4ac5SFilipe Manana 	/*
1340583f4ac5SFilipe Manana 	 * If we found an extent buffer is shared, set the cache result for all
1341583f4ac5SFilipe Manana 	 * extent buffers below it to true. As nodes in the path are COWed,
1342583f4ac5SFilipe Manana 	 * their sharedness is moved to their children, and if a leaf is COWed,
1343583f4ac5SFilipe Manana 	 * then the sharedness of a data extent becomes direct, the refcount of
1344583f4ac5SFilipe Manana 	 * data extent is increased in the extent item at the extent tree.
1345583f4ac5SFilipe Manana 	 */
1346583f4ac5SFilipe Manana 	if (is_shared) {
1347583f4ac5SFilipe Manana 		for (int i = 0; i < level; i++) {
1348583f4ac5SFilipe Manana 			entry = &ctx->path_cache_entries[i];
1349583f4ac5SFilipe Manana 			entry->is_shared = is_shared;
1350583f4ac5SFilipe Manana 			entry->gen = gen;
1351583f4ac5SFilipe Manana 		}
1352583f4ac5SFilipe Manana 	}
1353583f4ac5SFilipe Manana }
1354583f4ac5SFilipe Manana 
1355583f4ac5SFilipe Manana /*
13568da6d581SJan Schmidt  * this adds all existing backrefs (inline backrefs, backrefs and delayed
13578da6d581SJan Schmidt  * refs) for the given bytenr to the refs list, merges duplicates and resolves
13588da6d581SJan Schmidt  * indirect refs to their parent bytenr.
13598da6d581SJan Schmidt  * When roots are found, they're added to the roots list
13608da6d581SJan Schmidt  *
1361a2c8d27eSFilipe Manana  * @ctx:     Backref walking context object, must be not NULL.
1362a2c8d27eSFilipe Manana  * @sc:      If !NULL, then immediately return BACKREF_FOUND_SHARED when a
13633ec4d323SEdmund Nadolski  *           shared extent is detected.
13643ec4d323SEdmund Nadolski  *
13653ec4d323SEdmund Nadolski  * Otherwise this returns 0 for success and <0 for an error.
13663ec4d323SEdmund Nadolski  *
13678da6d581SJan Schmidt  * FIXME some caching might speed things up
13688da6d581SJan Schmidt  */
1369a2c8d27eSFilipe Manana static int find_parent_nodes(struct btrfs_backref_walk_ctx *ctx,
13706ce6ba53SFilipe Manana 			     struct share_check *sc)
13718da6d581SJan Schmidt {
1372a2c8d27eSFilipe Manana 	struct btrfs_root *root = btrfs_extent_root(ctx->fs_info, ctx->bytenr);
13738da6d581SJan Schmidt 	struct btrfs_key key;
13748da6d581SJan Schmidt 	struct btrfs_path *path;
13758da6d581SJan Schmidt 	struct btrfs_delayed_ref_root *delayed_refs = NULL;
1376d3b01064SLi Zefan 	struct btrfs_delayed_ref_head *head;
13778da6d581SJan Schmidt 	int info_level = 0;
13788da6d581SJan Schmidt 	int ret;
1379e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
138086d5f994SEdmund Nadolski 	struct rb_node *node;
1381f05c4746SWang Shilong 	struct extent_inode_elem *eie = NULL;
138286d5f994SEdmund Nadolski 	struct preftrees preftrees = {
138386d5f994SEdmund Nadolski 		.direct = PREFTREE_INIT,
138486d5f994SEdmund Nadolski 		.indirect = PREFTREE_INIT,
138586d5f994SEdmund Nadolski 		.indirect_missing_keys = PREFTREE_INIT
138686d5f994SEdmund Nadolski 	};
13878da6d581SJan Schmidt 
138856f5c199SFilipe Manana 	/* Roots ulist is not needed when using a sharedness check context. */
138956f5c199SFilipe Manana 	if (sc)
1390a2c8d27eSFilipe Manana 		ASSERT(ctx->roots == NULL);
139156f5c199SFilipe Manana 
1392a2c8d27eSFilipe Manana 	key.objectid = ctx->bytenr;
13938da6d581SJan Schmidt 	key.offset = (u64)-1;
1394a2c8d27eSFilipe Manana 	if (btrfs_fs_incompat(ctx->fs_info, SKINNY_METADATA))
1395261c84b6SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
1396261c84b6SJosef Bacik 	else
1397261c84b6SJosef Bacik 		key.type = BTRFS_EXTENT_ITEM_KEY;
13988da6d581SJan Schmidt 
13998da6d581SJan Schmidt 	path = btrfs_alloc_path();
14008da6d581SJan Schmidt 	if (!path)
14018da6d581SJan Schmidt 		return -ENOMEM;
1402a2c8d27eSFilipe Manana 	if (!ctx->trans) {
1403da61d31aSJosef Bacik 		path->search_commit_root = 1;
1404e84752d4SWang Shilong 		path->skip_locking = 1;
1405e84752d4SWang Shilong 	}
14068da6d581SJan Schmidt 
1407a2c8d27eSFilipe Manana 	if (ctx->time_seq == BTRFS_SEQ_LAST)
140821633fc6SQu Wenruo 		path->skip_locking = 1;
140921633fc6SQu Wenruo 
14108da6d581SJan Schmidt again:
1411d3b01064SLi Zefan 	head = NULL;
1412d3b01064SLi Zefan 
141398cc4222SJosef Bacik 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
14148da6d581SJan Schmidt 	if (ret < 0)
14158da6d581SJan Schmidt 		goto out;
1416fcba0120SJosef Bacik 	if (ret == 0) {
1417fcba0120SJosef Bacik 		/* This shouldn't happen, indicates a bug or fs corruption. */
1418fcba0120SJosef Bacik 		ASSERT(ret != 0);
1419fcba0120SJosef Bacik 		ret = -EUCLEAN;
1420fcba0120SJosef Bacik 		goto out;
1421fcba0120SJosef Bacik 	}
14228da6d581SJan Schmidt 
1423a2c8d27eSFilipe Manana 	if (ctx->trans && likely(ctx->trans->type != __TRANS_DUMMY) &&
1424a2c8d27eSFilipe Manana 	    ctx->time_seq != BTRFS_SEQ_LAST) {
14258da6d581SJan Schmidt 		/*
14269665ebd5SJosef Bacik 		 * We have a specific time_seq we care about and trans which
14279665ebd5SJosef Bacik 		 * means we have the path lock, we need to grab the ref head and
14289665ebd5SJosef Bacik 		 * lock it so we have a consistent view of the refs at the given
14299665ebd5SJosef Bacik 		 * time.
14308da6d581SJan Schmidt 		 */
1431a2c8d27eSFilipe Manana 		delayed_refs = &ctx->trans->transaction->delayed_refs;
14328da6d581SJan Schmidt 		spin_lock(&delayed_refs->lock);
1433a2c8d27eSFilipe Manana 		head = btrfs_find_delayed_ref_head(delayed_refs, ctx->bytenr);
14348da6d581SJan Schmidt 		if (head) {
14358da6d581SJan Schmidt 			if (!mutex_trylock(&head->mutex)) {
1436d278850eSJosef Bacik 				refcount_inc(&head->refs);
14378da6d581SJan Schmidt 				spin_unlock(&delayed_refs->lock);
14388da6d581SJan Schmidt 
14398da6d581SJan Schmidt 				btrfs_release_path(path);
14408da6d581SJan Schmidt 
14418da6d581SJan Schmidt 				/*
14428da6d581SJan Schmidt 				 * Mutex was contended, block until it's
14438da6d581SJan Schmidt 				 * released and try again
14448da6d581SJan Schmidt 				 */
14458da6d581SJan Schmidt 				mutex_lock(&head->mutex);
14468da6d581SJan Schmidt 				mutex_unlock(&head->mutex);
1447d278850eSJosef Bacik 				btrfs_put_delayed_ref_head(head);
14488da6d581SJan Schmidt 				goto again;
14498da6d581SJan Schmidt 			}
1450d7df2c79SJosef Bacik 			spin_unlock(&delayed_refs->lock);
1451a2c8d27eSFilipe Manana 			ret = add_delayed_refs(ctx->fs_info, head, ctx->time_seq,
1452b25b0b87Sethanwu 					       &preftrees, sc);
1453155725c9SJan Schmidt 			mutex_unlock(&head->mutex);
1454d7df2c79SJosef Bacik 			if (ret)
14558da6d581SJan Schmidt 				goto out;
1456d7df2c79SJosef Bacik 		} else {
14578da6d581SJan Schmidt 			spin_unlock(&delayed_refs->lock);
14587a3ae2f8SJan Schmidt 		}
1459d7df2c79SJosef Bacik 	}
14608da6d581SJan Schmidt 
14618da6d581SJan Schmidt 	if (path->slots[0]) {
14628da6d581SJan Schmidt 		struct extent_buffer *leaf;
14638da6d581SJan Schmidt 		int slot;
14648da6d581SJan Schmidt 
1465dadcaf78SJan Schmidt 		path->slots[0]--;
14668da6d581SJan Schmidt 		leaf = path->nodes[0];
1467dadcaf78SJan Schmidt 		slot = path->slots[0];
14688da6d581SJan Schmidt 		btrfs_item_key_to_cpu(leaf, &key, slot);
1469a2c8d27eSFilipe Manana 		if (key.objectid == ctx->bytenr &&
1470261c84b6SJosef Bacik 		    (key.type == BTRFS_EXTENT_ITEM_KEY ||
1471261c84b6SJosef Bacik 		     key.type == BTRFS_METADATA_ITEM_KEY)) {
1472f73853c7SFilipe Manana 			ret = add_inline_refs(ctx, path, &info_level,
1473f73853c7SFilipe Manana 					      &preftrees, sc);
14748da6d581SJan Schmidt 			if (ret)
14758da6d581SJan Schmidt 				goto out;
1476*adf02418SFilipe Manana 			ret = add_keyed_refs(ctx, root, path, info_level,
14773ec4d323SEdmund Nadolski 					     &preftrees, sc);
14788da6d581SJan Schmidt 			if (ret)
14798da6d581SJan Schmidt 				goto out;
14808da6d581SJan Schmidt 		}
14818da6d581SJan Schmidt 	}
148286d5f994SEdmund Nadolski 
148356f5c199SFilipe Manana 	/*
148456f5c199SFilipe Manana 	 * If we have a share context and we reached here, it means the extent
148556f5c199SFilipe Manana 	 * is not directly shared (no multiple reference items for it),
148656f5c199SFilipe Manana 	 * otherwise we would have exited earlier with a return value of
148756f5c199SFilipe Manana 	 * BACKREF_FOUND_SHARED after processing delayed references or while
148856f5c199SFilipe Manana 	 * processing inline or keyed references from the extent tree.
148956f5c199SFilipe Manana 	 * The extent may however be indirectly shared through shared subtrees
149056f5c199SFilipe Manana 	 * as a result from creating snapshots, so we determine below what is
149156f5c199SFilipe Manana 	 * its parent node, in case we are dealing with a metadata extent, or
149256f5c199SFilipe Manana 	 * what's the leaf (or leaves), from a fs tree, that has a file extent
149356f5c199SFilipe Manana 	 * item pointing to it in case we are dealing with a data extent.
149456f5c199SFilipe Manana 	 */
149556f5c199SFilipe Manana 	ASSERT(extent_is_shared(sc) == 0);
149656f5c199SFilipe Manana 
1497877c1476SFilipe Manana 	/*
1498877c1476SFilipe Manana 	 * If we are here for a data extent and we have a share_check structure
1499877c1476SFilipe Manana 	 * it means the data extent is not directly shared (does not have
1500877c1476SFilipe Manana 	 * multiple reference items), so we have to check if a path in the fs
1501877c1476SFilipe Manana 	 * tree (going from the root node down to the leaf that has the file
1502877c1476SFilipe Manana 	 * extent item pointing to the data extent) is shared, that is, if any
1503877c1476SFilipe Manana 	 * of the extent buffers in the path is referenced by other trees.
1504877c1476SFilipe Manana 	 */
1505a2c8d27eSFilipe Manana 	if (sc && ctx->bytenr == sc->data_bytenr) {
1506877c1476SFilipe Manana 		/*
15076976201fSFilipe Manana 		 * If our data extent is from a generation more recent than the
15086976201fSFilipe Manana 		 * last generation used to snapshot the root, then we know that
15096976201fSFilipe Manana 		 * it can not be shared through subtrees, so we can skip
15106976201fSFilipe Manana 		 * resolving indirect references, there's no point in
15116976201fSFilipe Manana 		 * determining the extent buffers for the path from the fs tree
15126976201fSFilipe Manana 		 * root node down to the leaf that has the file extent item that
15136976201fSFilipe Manana 		 * points to the data extent.
15146976201fSFilipe Manana 		 */
15156976201fSFilipe Manana 		if (sc->data_extent_gen >
15166976201fSFilipe Manana 		    btrfs_root_last_snapshot(&sc->root->root_item)) {
15176976201fSFilipe Manana 			ret = BACKREF_FOUND_NOT_SHARED;
15186976201fSFilipe Manana 			goto out;
15196976201fSFilipe Manana 		}
15206976201fSFilipe Manana 
15216976201fSFilipe Manana 		/*
1522877c1476SFilipe Manana 		 * If we are only determining if a data extent is shared or not
1523877c1476SFilipe Manana 		 * and the corresponding file extent item is located in the same
1524877c1476SFilipe Manana 		 * leaf as the previous file extent item, we can skip resolving
1525877c1476SFilipe Manana 		 * indirect references for a data extent, since the fs tree path
1526877c1476SFilipe Manana 		 * is the same (same leaf, so same path). We skip as long as the
1527877c1476SFilipe Manana 		 * cached result for the leaf is valid and only if there's only
1528877c1476SFilipe Manana 		 * one file extent item pointing to the data extent, because in
1529877c1476SFilipe Manana 		 * the case of multiple file extent items, they may be located
1530877c1476SFilipe Manana 		 * in different leaves and therefore we have multiple paths.
1531877c1476SFilipe Manana 		 */
1532877c1476SFilipe Manana 		if (sc->ctx->curr_leaf_bytenr == sc->ctx->prev_leaf_bytenr &&
1533877c1476SFilipe Manana 		    sc->self_ref_count == 1) {
1534877c1476SFilipe Manana 			bool cached;
1535877c1476SFilipe Manana 			bool is_shared;
1536877c1476SFilipe Manana 
1537877c1476SFilipe Manana 			cached = lookup_backref_shared_cache(sc->ctx, sc->root,
1538877c1476SFilipe Manana 						     sc->ctx->curr_leaf_bytenr,
1539877c1476SFilipe Manana 						     0, &is_shared);
1540877c1476SFilipe Manana 			if (cached) {
1541877c1476SFilipe Manana 				if (is_shared)
1542877c1476SFilipe Manana 					ret = BACKREF_FOUND_SHARED;
1543877c1476SFilipe Manana 				else
1544877c1476SFilipe Manana 					ret = BACKREF_FOUND_NOT_SHARED;
1545877c1476SFilipe Manana 				goto out;
1546877c1476SFilipe Manana 			}
1547877c1476SFilipe Manana 		}
1548877c1476SFilipe Manana 	}
1549877c1476SFilipe Manana 
15508da6d581SJan Schmidt 	btrfs_release_path(path);
15518da6d581SJan Schmidt 
1552a2c8d27eSFilipe Manana 	ret = add_missing_keys(ctx->fs_info, &preftrees, path->skip_locking == 0);
1553d5c88b73SJan Schmidt 	if (ret)
1554d5c88b73SJan Schmidt 		goto out;
1555d5c88b73SJan Schmidt 
1556ecf160b4SLiu Bo 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect_missing_keys.root.rb_root));
15578da6d581SJan Schmidt 
1558a2c8d27eSFilipe Manana 	ret = resolve_indirect_refs(ctx, path, &preftrees, sc);
15598da6d581SJan Schmidt 	if (ret)
15608da6d581SJan Schmidt 		goto out;
15618da6d581SJan Schmidt 
1562ecf160b4SLiu Bo 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect.root.rb_root));
15638da6d581SJan Schmidt 
156486d5f994SEdmund Nadolski 	/*
156586d5f994SEdmund Nadolski 	 * This walks the tree of merged and resolved refs. Tree blocks are
156686d5f994SEdmund Nadolski 	 * read in as needed. Unique entries are added to the ulist, and
156786d5f994SEdmund Nadolski 	 * the list of found roots is updated.
156886d5f994SEdmund Nadolski 	 *
156986d5f994SEdmund Nadolski 	 * We release the entire tree in one go before returning.
157086d5f994SEdmund Nadolski 	 */
1571ecf160b4SLiu Bo 	node = rb_first_cached(&preftrees.direct.root);
157286d5f994SEdmund Nadolski 	while (node) {
157386d5f994SEdmund Nadolski 		ref = rb_entry(node, struct prelim_ref, rbnode);
157486d5f994SEdmund Nadolski 		node = rb_next(&ref->rbnode);
1575c8195a7bSZygo Blaxell 		/*
1576c8195a7bSZygo Blaxell 		 * ref->count < 0 can happen here if there are delayed
1577c8195a7bSZygo Blaxell 		 * refs with a node->action of BTRFS_DROP_DELAYED_REF.
1578c8195a7bSZygo Blaxell 		 * prelim_ref_insert() relies on this when merging
1579c8195a7bSZygo Blaxell 		 * identical refs to keep the overall count correct.
1580c8195a7bSZygo Blaxell 		 * prelim_ref_insert() will merge only those refs
1581c8195a7bSZygo Blaxell 		 * which compare identically.  Any refs having
1582c8195a7bSZygo Blaxell 		 * e.g. different offsets would not be merged,
1583c8195a7bSZygo Blaxell 		 * and would retain their original ref->count < 0.
1584c8195a7bSZygo Blaxell 		 */
1585a2c8d27eSFilipe Manana 		if (ctx->roots && ref->count && ref->root_id && ref->parent == 0) {
15868da6d581SJan Schmidt 			/* no parent == root of tree */
1587a2c8d27eSFilipe Manana 			ret = ulist_add(ctx->roots, ref->root_id, 0, GFP_NOFS);
1588f1723939SWang Shilong 			if (ret < 0)
1589f1723939SWang Shilong 				goto out;
15908da6d581SJan Schmidt 		}
15918da6d581SJan Schmidt 		if (ref->count && ref->parent) {
1592a2c8d27eSFilipe Manana 			if (!ctx->ignore_extent_item_pos && !ref->inode_list &&
1593a2c8d27eSFilipe Manana 			    ref->level == 0) {
1594976b1908SJan Schmidt 				struct extent_buffer *eb;
1595707e8a07SDavid Sterba 
1596a2c8d27eSFilipe Manana 				eb = read_tree_block(ctx->fs_info, ref->parent, 0,
15971b7ec85eSJosef Bacik 						     0, ref->level, NULL);
159864c043deSLiu Bo 				if (IS_ERR(eb)) {
159964c043deSLiu Bo 					ret = PTR_ERR(eb);
160064c043deSLiu Bo 					goto out;
16014eb150d6SQu Wenruo 				}
16024eb150d6SQu Wenruo 				if (!extent_buffer_uptodate(eb)) {
1603416bc658SJosef Bacik 					free_extent_buffer(eb);
1604c16c2e2eSWang Shilong 					ret = -EIO;
1605c16c2e2eSWang Shilong 					goto out;
1606416bc658SJosef Bacik 				}
160738e3eebfSJosef Bacik 
1608ac5887c8SJosef Bacik 				if (!path->skip_locking)
16096f7ff6d7SFilipe Manana 					btrfs_tree_read_lock(eb);
161088ffb665SFilipe Manana 				ret = find_extent_in_eb(ctx, eb, &eie);
161138e3eebfSJosef Bacik 				if (!path->skip_locking)
1612ac5887c8SJosef Bacik 					btrfs_tree_read_unlock(eb);
1613976b1908SJan Schmidt 				free_extent_buffer(eb);
161488ffb665SFilipe Manana 				if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
161588ffb665SFilipe Manana 				    ret < 0)
1616f5929cd8SFilipe David Borba Manana 					goto out;
1617f5929cd8SFilipe David Borba Manana 				ref->inode_list = eie;
161892876eecSFilipe Manana 				/*
161992876eecSFilipe Manana 				 * We transferred the list ownership to the ref,
162092876eecSFilipe Manana 				 * so set to NULL to avoid a double free in case
162192876eecSFilipe Manana 				 * an error happens after this.
162292876eecSFilipe Manana 				 */
162392876eecSFilipe Manana 				eie = NULL;
1624976b1908SJan Schmidt 			}
1625a2c8d27eSFilipe Manana 			ret = ulist_add_merge_ptr(ctx->refs, ref->parent,
16264eb1f66dSTakashi Iwai 						  ref->inode_list,
16274eb1f66dSTakashi Iwai 						  (void **)&eie, GFP_NOFS);
1628f1723939SWang Shilong 			if (ret < 0)
1629f1723939SWang Shilong 				goto out;
1630a2c8d27eSFilipe Manana 			if (!ret && !ctx->ignore_extent_item_pos) {
16313301958bSJan Schmidt 				/*
16329f05c09dSJosef Bacik 				 * We've recorded that parent, so we must extend
16339f05c09dSJosef Bacik 				 * its inode list here.
16349f05c09dSJosef Bacik 				 *
16359f05c09dSJosef Bacik 				 * However if there was corruption we may not
16369f05c09dSJosef Bacik 				 * have found an eie, return an error in this
16379f05c09dSJosef Bacik 				 * case.
16383301958bSJan Schmidt 				 */
16399f05c09dSJosef Bacik 				ASSERT(eie);
16409f05c09dSJosef Bacik 				if (!eie) {
16419f05c09dSJosef Bacik 					ret = -EUCLEAN;
16429f05c09dSJosef Bacik 					goto out;
16439f05c09dSJosef Bacik 				}
16443301958bSJan Schmidt 				while (eie->next)
16453301958bSJan Schmidt 					eie = eie->next;
16463301958bSJan Schmidt 				eie->next = ref->inode_list;
16473301958bSJan Schmidt 			}
1648f05c4746SWang Shilong 			eie = NULL;
164992876eecSFilipe Manana 			/*
165092876eecSFilipe Manana 			 * We have transferred the inode list ownership from
165192876eecSFilipe Manana 			 * this ref to the ref we added to the 'refs' ulist.
165292876eecSFilipe Manana 			 * So set this ref's inode list to NULL to avoid
165392876eecSFilipe Manana 			 * use-after-free when our caller uses it or double
165492876eecSFilipe Manana 			 * frees in case an error happens before we return.
165592876eecSFilipe Manana 			 */
165692876eecSFilipe Manana 			ref->inode_list = NULL;
16578da6d581SJan Schmidt 		}
16589dd14fd6SEdmund Nadolski 		cond_resched();
16598da6d581SJan Schmidt 	}
16608da6d581SJan Schmidt 
16618da6d581SJan Schmidt out:
16628da6d581SJan Schmidt 	btrfs_free_path(path);
166386d5f994SEdmund Nadolski 
166486d5f994SEdmund Nadolski 	prelim_release(&preftrees.direct);
166586d5f994SEdmund Nadolski 	prelim_release(&preftrees.indirect);
166686d5f994SEdmund Nadolski 	prelim_release(&preftrees.indirect_missing_keys);
166786d5f994SEdmund Nadolski 
166888ffb665SFilipe Manana 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
1669f05c4746SWang Shilong 		free_inode_elem_list(eie);
16708da6d581SJan Schmidt 	return ret;
16718da6d581SJan Schmidt }
16728da6d581SJan Schmidt 
16738da6d581SJan Schmidt /*
1674a2c8d27eSFilipe Manana  * Finds all leaves with a reference to the specified combination of
1675a2c8d27eSFilipe Manana  * @ctx->bytenr and @ctx->extent_item_pos. The bytenr of the found leaves are
1676a2c8d27eSFilipe Manana  * added to the ulist at @ctx->refs, and that ulist is allocated by this
1677a2c8d27eSFilipe Manana  * function. The caller should free the ulist with free_leaf_list() if
1678a2c8d27eSFilipe Manana  * @ctx->ignore_extent_item_pos is false, otherwise a fimple ulist_free() is
1679a2c8d27eSFilipe Manana  * enough.
16808da6d581SJan Schmidt  *
1681a2c8d27eSFilipe Manana  * Returns 0 on success and < 0 on error. On error @ctx->refs is not allocated.
16828da6d581SJan Schmidt  */
1683a2c8d27eSFilipe Manana int btrfs_find_all_leafs(struct btrfs_backref_walk_ctx *ctx)
16848da6d581SJan Schmidt {
16858da6d581SJan Schmidt 	int ret;
16868da6d581SJan Schmidt 
1687a2c8d27eSFilipe Manana 	ASSERT(ctx->refs == NULL);
1688a2c8d27eSFilipe Manana 
1689a2c8d27eSFilipe Manana 	ctx->refs = ulist_alloc(GFP_NOFS);
1690a2c8d27eSFilipe Manana 	if (!ctx->refs)
16918da6d581SJan Schmidt 		return -ENOMEM;
16928da6d581SJan Schmidt 
1693a2c8d27eSFilipe Manana 	ret = find_parent_nodes(ctx, NULL);
169488ffb665SFilipe Manana 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
169588ffb665SFilipe Manana 	    (ret < 0 && ret != -ENOENT)) {
1696a2c8d27eSFilipe Manana 		free_leaf_list(ctx->refs);
1697a2c8d27eSFilipe Manana 		ctx->refs = NULL;
16988da6d581SJan Schmidt 		return ret;
16998da6d581SJan Schmidt 	}
17008da6d581SJan Schmidt 
17018da6d581SJan Schmidt 	return 0;
17028da6d581SJan Schmidt }
17038da6d581SJan Schmidt 
17048da6d581SJan Schmidt /*
1705a2c8d27eSFilipe Manana  * Walk all backrefs for a given extent to find all roots that reference this
17068da6d581SJan Schmidt  * extent. Walking a backref means finding all extents that reference this
17078da6d581SJan Schmidt  * extent and in turn walk the backrefs of those, too. Naturally this is a
17088da6d581SJan Schmidt  * recursive process, but here it is implemented in an iterative fashion: We
17098da6d581SJan Schmidt  * find all referencing extents for the extent in question and put them on a
17108da6d581SJan Schmidt  * list. In turn, we find all referencing extents for those, further appending
17118da6d581SJan Schmidt  * to the list. The way we iterate the list allows adding more elements after
17128da6d581SJan Schmidt  * the current while iterating. The process stops when we reach the end of the
1713a2c8d27eSFilipe Manana  * list.
17148da6d581SJan Schmidt  *
17151baea6f1SFilipe Manana  * Found roots are added to @ctx->roots, which is allocated by this function if
17161baea6f1SFilipe Manana  * it points to NULL, in which case the caller is responsible for freeing it
17171baea6f1SFilipe Manana  * after it's not needed anymore.
17181baea6f1SFilipe Manana  * This function requires @ctx->refs to be NULL, as it uses it for allocating a
17191baea6f1SFilipe Manana  * ulist to do temporary work, and frees it before returning.
1720a2c8d27eSFilipe Manana  *
17211baea6f1SFilipe Manana  * Returns 0 on success, < 0 on error.
17228da6d581SJan Schmidt  */
1723a2c8d27eSFilipe Manana static int btrfs_find_all_roots_safe(struct btrfs_backref_walk_ctx *ctx)
17248da6d581SJan Schmidt {
1725a2c8d27eSFilipe Manana 	const u64 orig_bytenr = ctx->bytenr;
1726a2c8d27eSFilipe Manana 	const bool orig_ignore_extent_item_pos = ctx->ignore_extent_item_pos;
17271baea6f1SFilipe Manana 	bool roots_ulist_allocated = false;
1728cd1b413cSJan Schmidt 	struct ulist_iterator uiter;
1729a2c8d27eSFilipe Manana 	int ret = 0;
17308da6d581SJan Schmidt 
1731a2c8d27eSFilipe Manana 	ASSERT(ctx->refs == NULL);
1732a2c8d27eSFilipe Manana 
1733a2c8d27eSFilipe Manana 	ctx->refs = ulist_alloc(GFP_NOFS);
1734a2c8d27eSFilipe Manana 	if (!ctx->refs)
17358da6d581SJan Schmidt 		return -ENOMEM;
1736a2c8d27eSFilipe Manana 
17371baea6f1SFilipe Manana 	if (!ctx->roots) {
1738a2c8d27eSFilipe Manana 		ctx->roots = ulist_alloc(GFP_NOFS);
1739a2c8d27eSFilipe Manana 		if (!ctx->roots) {
1740a2c8d27eSFilipe Manana 			ulist_free(ctx->refs);
1741a2c8d27eSFilipe Manana 			ctx->refs = NULL;
17428da6d581SJan Schmidt 			return -ENOMEM;
17438da6d581SJan Schmidt 		}
17441baea6f1SFilipe Manana 		roots_ulist_allocated = true;
17451baea6f1SFilipe Manana 	}
17468da6d581SJan Schmidt 
1747a2c8d27eSFilipe Manana 	ctx->ignore_extent_item_pos = true;
1748a2c8d27eSFilipe Manana 
1749cd1b413cSJan Schmidt 	ULIST_ITER_INIT(&uiter);
17508da6d581SJan Schmidt 	while (1) {
1751a2c8d27eSFilipe Manana 		struct ulist_node *node;
1752a2c8d27eSFilipe Manana 
1753a2c8d27eSFilipe Manana 		ret = find_parent_nodes(ctx, NULL);
17548da6d581SJan Schmidt 		if (ret < 0 && ret != -ENOENT) {
17551baea6f1SFilipe Manana 			if (roots_ulist_allocated) {
1756a2c8d27eSFilipe Manana 				ulist_free(ctx->roots);
1757a2c8d27eSFilipe Manana 				ctx->roots = NULL;
17581baea6f1SFilipe Manana 			}
1759a2c8d27eSFilipe Manana 			break;
17608da6d581SJan Schmidt 		}
1761a2c8d27eSFilipe Manana 		ret = 0;
1762a2c8d27eSFilipe Manana 		node = ulist_next(ctx->refs, &uiter);
17638da6d581SJan Schmidt 		if (!node)
17648da6d581SJan Schmidt 			break;
1765a2c8d27eSFilipe Manana 		ctx->bytenr = node->val;
1766bca1a290SWang Shilong 		cond_resched();
17678da6d581SJan Schmidt 	}
17688da6d581SJan Schmidt 
1769a2c8d27eSFilipe Manana 	ulist_free(ctx->refs);
1770a2c8d27eSFilipe Manana 	ctx->refs = NULL;
1771a2c8d27eSFilipe Manana 	ctx->bytenr = orig_bytenr;
1772a2c8d27eSFilipe Manana 	ctx->ignore_extent_item_pos = orig_ignore_extent_item_pos;
1773a2c8d27eSFilipe Manana 
1774a2c8d27eSFilipe Manana 	return ret;
17758da6d581SJan Schmidt }
17768da6d581SJan Schmidt 
1777a2c8d27eSFilipe Manana int btrfs_find_all_roots(struct btrfs_backref_walk_ctx *ctx,
1778c7bcbb21SFilipe Manana 			 bool skip_commit_root_sem)
17799e351cc8SJosef Bacik {
17809e351cc8SJosef Bacik 	int ret;
17819e351cc8SJosef Bacik 
1782a2c8d27eSFilipe Manana 	if (!ctx->trans && !skip_commit_root_sem)
1783a2c8d27eSFilipe Manana 		down_read(&ctx->fs_info->commit_root_sem);
1784a2c8d27eSFilipe Manana 	ret = btrfs_find_all_roots_safe(ctx);
1785a2c8d27eSFilipe Manana 	if (!ctx->trans && !skip_commit_root_sem)
1786a2c8d27eSFilipe Manana 		up_read(&ctx->fs_info->commit_root_sem);
17879e351cc8SJosef Bacik 	return ret;
17889e351cc8SJosef Bacik }
17899e351cc8SJosef Bacik 
179084a7949dSFilipe Manana struct btrfs_backref_share_check_ctx *btrfs_alloc_backref_share_check_ctx(void)
179184a7949dSFilipe Manana {
179284a7949dSFilipe Manana 	struct btrfs_backref_share_check_ctx *ctx;
179384a7949dSFilipe Manana 
179484a7949dSFilipe Manana 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
179584a7949dSFilipe Manana 	if (!ctx)
179684a7949dSFilipe Manana 		return NULL;
179784a7949dSFilipe Manana 
179884a7949dSFilipe Manana 	ulist_init(&ctx->refs);
179984a7949dSFilipe Manana 
180084a7949dSFilipe Manana 	return ctx;
180184a7949dSFilipe Manana }
180284a7949dSFilipe Manana 
180384a7949dSFilipe Manana void btrfs_free_backref_share_ctx(struct btrfs_backref_share_check_ctx *ctx)
180484a7949dSFilipe Manana {
180584a7949dSFilipe Manana 	if (!ctx)
180684a7949dSFilipe Manana 		return;
180784a7949dSFilipe Manana 
180884a7949dSFilipe Manana 	ulist_release(&ctx->refs);
180984a7949dSFilipe Manana 	kfree(ctx);
181084a7949dSFilipe Manana }
181184a7949dSFilipe Manana 
181212a824dcSFilipe Manana /*
18138eedaddaSFilipe Manana  * Check if a data extent is shared or not.
18146e353e3bSNikolay Borisov  *
1815ceb707daSFilipe Manana  * @inode:       The inode whose extent we are checking.
1816b8f164e3SFilipe Manana  * @bytenr:      Logical bytenr of the extent we are checking.
1817b8f164e3SFilipe Manana  * @extent_gen:  Generation of the extent (file extent item) or 0 if it is
1818b8f164e3SFilipe Manana  *               not known.
181961dbb952SFilipe Manana  * @ctx:         A backref sharedness check context.
18202c2ed5aaSMark Fasheh  *
18218eedaddaSFilipe Manana  * btrfs_is_data_extent_shared uses the backref walking code but will short
18222c2ed5aaSMark Fasheh  * circuit as soon as it finds a root or inode that doesn't match the
18232c2ed5aaSMark Fasheh  * one passed in. This provides a significant performance benefit for
18242c2ed5aaSMark Fasheh  * callers (such as fiemap) which want to know whether the extent is
18252c2ed5aaSMark Fasheh  * shared but do not need a ref count.
18262c2ed5aaSMark Fasheh  *
182703628cdbSFilipe Manana  * This attempts to attach to the running transaction in order to account for
182803628cdbSFilipe Manana  * delayed refs, but continues on even when no running transaction exists.
1829bb739cf0SEdmund Nadolski  *
18302c2ed5aaSMark Fasheh  * Return: 0 if extent is not shared, 1 if it is shared, < 0 on error.
18312c2ed5aaSMark Fasheh  */
1832ceb707daSFilipe Manana int btrfs_is_data_extent_shared(struct btrfs_inode *inode, u64 bytenr,
1833b8f164e3SFilipe Manana 				u64 extent_gen,
183461dbb952SFilipe Manana 				struct btrfs_backref_share_check_ctx *ctx)
1835dc046b10SJosef Bacik {
1836a2c8d27eSFilipe Manana 	struct btrfs_backref_walk_ctx walk_ctx = { 0 };
1837ceb707daSFilipe Manana 	struct btrfs_root *root = inode->root;
1838bb739cf0SEdmund Nadolski 	struct btrfs_fs_info *fs_info = root->fs_info;
1839bb739cf0SEdmund Nadolski 	struct btrfs_trans_handle *trans;
1840dc046b10SJosef Bacik 	struct ulist_iterator uiter;
1841dc046b10SJosef Bacik 	struct ulist_node *node;
1842f3a84ccdSFilipe Manana 	struct btrfs_seq_list elem = BTRFS_SEQ_LIST_INIT(elem);
1843dc046b10SJosef Bacik 	int ret = 0;
18443ec4d323SEdmund Nadolski 	struct share_check shared = {
1845877c1476SFilipe Manana 		.ctx = ctx,
1846877c1476SFilipe Manana 		.root = root,
1847ceb707daSFilipe Manana 		.inum = btrfs_ino(inode),
184873e339e6SFilipe Manana 		.data_bytenr = bytenr,
18496976201fSFilipe Manana 		.data_extent_gen = extent_gen,
18503ec4d323SEdmund Nadolski 		.share_count = 0,
185173e339e6SFilipe Manana 		.self_ref_count = 0,
18524fc7b572SFilipe Manana 		.have_delayed_delete_refs = false,
18533ec4d323SEdmund Nadolski 	};
185412a824dcSFilipe Manana 	int level;
1855dc046b10SJosef Bacik 
185673e339e6SFilipe Manana 	for (int i = 0; i < BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE; i++) {
185773e339e6SFilipe Manana 		if (ctx->prev_extents_cache[i].bytenr == bytenr)
185873e339e6SFilipe Manana 			return ctx->prev_extents_cache[i].is_shared;
185973e339e6SFilipe Manana 	}
186073e339e6SFilipe Manana 
186184a7949dSFilipe Manana 	ulist_init(&ctx->refs);
1862dc046b10SJosef Bacik 
1863a6d155d2SFilipe Manana 	trans = btrfs_join_transaction_nostart(root);
1864bb739cf0SEdmund Nadolski 	if (IS_ERR(trans)) {
186503628cdbSFilipe Manana 		if (PTR_ERR(trans) != -ENOENT && PTR_ERR(trans) != -EROFS) {
186603628cdbSFilipe Manana 			ret = PTR_ERR(trans);
186703628cdbSFilipe Manana 			goto out;
186803628cdbSFilipe Manana 		}
1869bb739cf0SEdmund Nadolski 		trans = NULL;
1870dc046b10SJosef Bacik 		down_read(&fs_info->commit_root_sem);
1871bb739cf0SEdmund Nadolski 	} else {
1872bb739cf0SEdmund Nadolski 		btrfs_get_tree_mod_seq(fs_info, &elem);
1873a2c8d27eSFilipe Manana 		walk_ctx.time_seq = elem.seq;
1874bb739cf0SEdmund Nadolski 	}
1875bb739cf0SEdmund Nadolski 
1876a2c8d27eSFilipe Manana 	walk_ctx.ignore_extent_item_pos = true;
1877a2c8d27eSFilipe Manana 	walk_ctx.trans = trans;
1878a2c8d27eSFilipe Manana 	walk_ctx.fs_info = fs_info;
1879a2c8d27eSFilipe Manana 	walk_ctx.refs = &ctx->refs;
1880a2c8d27eSFilipe Manana 
188112a824dcSFilipe Manana 	/* -1 means we are in the bytenr of the data extent. */
188212a824dcSFilipe Manana 	level = -1;
1883dc046b10SJosef Bacik 	ULIST_ITER_INIT(&uiter);
188461dbb952SFilipe Manana 	ctx->use_path_cache = true;
1885dc046b10SJosef Bacik 	while (1) {
188612a824dcSFilipe Manana 		bool is_shared;
188712a824dcSFilipe Manana 		bool cached;
188812a824dcSFilipe Manana 
1889a2c8d27eSFilipe Manana 		walk_ctx.bytenr = bytenr;
1890a2c8d27eSFilipe Manana 		ret = find_parent_nodes(&walk_ctx, &shared);
1891877c1476SFilipe Manana 		if (ret == BACKREF_FOUND_SHARED ||
1892877c1476SFilipe Manana 		    ret == BACKREF_FOUND_NOT_SHARED) {
1893877c1476SFilipe Manana 			/* If shared must return 1, otherwise return 0. */
1894877c1476SFilipe Manana 			ret = (ret == BACKREF_FOUND_SHARED) ? 1 : 0;
189512a824dcSFilipe Manana 			if (level >= 0)
189661dbb952SFilipe Manana 				store_backref_shared_cache(ctx, root, bytenr,
1897877c1476SFilipe Manana 							   level, ret == 1);
1898dc046b10SJosef Bacik 			break;
1899dc046b10SJosef Bacik 		}
1900dc046b10SJosef Bacik 		if (ret < 0 && ret != -ENOENT)
1901dc046b10SJosef Bacik 			break;
19022c2ed5aaSMark Fasheh 		ret = 0;
1903b8f164e3SFilipe Manana 
190463c84b46SFilipe Manana 		/*
190563c84b46SFilipe Manana 		 * If our data extent was not directly shared (without multiple
190663c84b46SFilipe Manana 		 * reference items), than it might have a single reference item
190763c84b46SFilipe Manana 		 * with a count > 1 for the same offset, which means there are 2
190863c84b46SFilipe Manana 		 * (or more) file extent items that point to the data extent -
190963c84b46SFilipe Manana 		 * this happens when a file extent item needs to be split and
191063c84b46SFilipe Manana 		 * then one item gets moved to another leaf due to a b+tree leaf
191163c84b46SFilipe Manana 		 * split when inserting some item. In this case the file extent
191263c84b46SFilipe Manana 		 * items may be located in different leaves and therefore some
191363c84b46SFilipe Manana 		 * of the leaves may be referenced through shared subtrees while
191463c84b46SFilipe Manana 		 * others are not. Since our extent buffer cache only works for
191563c84b46SFilipe Manana 		 * a single path (by far the most common case and simpler to
191663c84b46SFilipe Manana 		 * deal with), we can not use it if we have multiple leaves
191763c84b46SFilipe Manana 		 * (which implies multiple paths).
191863c84b46SFilipe Manana 		 */
191984a7949dSFilipe Manana 		if (level == -1 && ctx->refs.nnodes > 1)
192061dbb952SFilipe Manana 			ctx->use_path_cache = false;
192163c84b46SFilipe Manana 
192212a824dcSFilipe Manana 		if (level >= 0)
192361dbb952SFilipe Manana 			store_backref_shared_cache(ctx, root, bytenr,
192412a824dcSFilipe Manana 						   level, false);
192584a7949dSFilipe Manana 		node = ulist_next(&ctx->refs, &uiter);
1926dc046b10SJosef Bacik 		if (!node)
1927dc046b10SJosef Bacik 			break;
1928dc046b10SJosef Bacik 		bytenr = node->val;
192912a824dcSFilipe Manana 		level++;
193061dbb952SFilipe Manana 		cached = lookup_backref_shared_cache(ctx, root, bytenr, level,
193112a824dcSFilipe Manana 						     &is_shared);
193212a824dcSFilipe Manana 		if (cached) {
193312a824dcSFilipe Manana 			ret = (is_shared ? 1 : 0);
193412a824dcSFilipe Manana 			break;
193512a824dcSFilipe Manana 		}
193618bf591bSEdmund Nadolski 		shared.share_count = 0;
19374fc7b572SFilipe Manana 		shared.have_delayed_delete_refs = false;
1938dc046b10SJosef Bacik 		cond_resched();
1939dc046b10SJosef Bacik 	}
1940bb739cf0SEdmund Nadolski 
194173e339e6SFilipe Manana 	/*
194273e339e6SFilipe Manana 	 * Cache the sharedness result for the data extent if we know our inode
194373e339e6SFilipe Manana 	 * has more than 1 file extent item that refers to the data extent.
194473e339e6SFilipe Manana 	 */
194573e339e6SFilipe Manana 	if (ret >= 0 && shared.self_ref_count > 1) {
194673e339e6SFilipe Manana 		int slot = ctx->prev_extents_cache_slot;
194773e339e6SFilipe Manana 
194873e339e6SFilipe Manana 		ctx->prev_extents_cache[slot].bytenr = shared.data_bytenr;
194973e339e6SFilipe Manana 		ctx->prev_extents_cache[slot].is_shared = (ret == 1);
195073e339e6SFilipe Manana 
195173e339e6SFilipe Manana 		slot = (slot + 1) % BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE;
195273e339e6SFilipe Manana 		ctx->prev_extents_cache_slot = slot;
195373e339e6SFilipe Manana 	}
195473e339e6SFilipe Manana 
1955bb739cf0SEdmund Nadolski 	if (trans) {
1956dc046b10SJosef Bacik 		btrfs_put_tree_mod_seq(fs_info, &elem);
1957bb739cf0SEdmund Nadolski 		btrfs_end_transaction(trans);
1958bb739cf0SEdmund Nadolski 	} else {
1959dc046b10SJosef Bacik 		up_read(&fs_info->commit_root_sem);
1960bb739cf0SEdmund Nadolski 	}
196103628cdbSFilipe Manana out:
196284a7949dSFilipe Manana 	ulist_release(&ctx->refs);
1963877c1476SFilipe Manana 	ctx->prev_leaf_bytenr = ctx->curr_leaf_bytenr;
1964877c1476SFilipe Manana 
1965dc046b10SJosef Bacik 	return ret;
1966dc046b10SJosef Bacik }
1967dc046b10SJosef Bacik 
1968f186373fSMark Fasheh int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
1969f186373fSMark Fasheh 			  u64 start_off, struct btrfs_path *path,
1970f186373fSMark Fasheh 			  struct btrfs_inode_extref **ret_extref,
1971f186373fSMark Fasheh 			  u64 *found_off)
1972f186373fSMark Fasheh {
1973f186373fSMark Fasheh 	int ret, slot;
1974f186373fSMark Fasheh 	struct btrfs_key key;
1975f186373fSMark Fasheh 	struct btrfs_key found_key;
1976f186373fSMark Fasheh 	struct btrfs_inode_extref *extref;
197773980becSJeff Mahoney 	const struct extent_buffer *leaf;
1978f186373fSMark Fasheh 	unsigned long ptr;
1979f186373fSMark Fasheh 
1980f186373fSMark Fasheh 	key.objectid = inode_objectid;
1981962a298fSDavid Sterba 	key.type = BTRFS_INODE_EXTREF_KEY;
1982f186373fSMark Fasheh 	key.offset = start_off;
1983f186373fSMark Fasheh 
1984f186373fSMark Fasheh 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1985f186373fSMark Fasheh 	if (ret < 0)
1986f186373fSMark Fasheh 		return ret;
1987f186373fSMark Fasheh 
1988f186373fSMark Fasheh 	while (1) {
1989f186373fSMark Fasheh 		leaf = path->nodes[0];
1990f186373fSMark Fasheh 		slot = path->slots[0];
1991f186373fSMark Fasheh 		if (slot >= btrfs_header_nritems(leaf)) {
1992f186373fSMark Fasheh 			/*
1993f186373fSMark Fasheh 			 * If the item at offset is not found,
1994f186373fSMark Fasheh 			 * btrfs_search_slot will point us to the slot
1995f186373fSMark Fasheh 			 * where it should be inserted. In our case
1996f186373fSMark Fasheh 			 * that will be the slot directly before the
1997f186373fSMark Fasheh 			 * next INODE_REF_KEY_V2 item. In the case
1998f186373fSMark Fasheh 			 * that we're pointing to the last slot in a
1999f186373fSMark Fasheh 			 * leaf, we must move one leaf over.
2000f186373fSMark Fasheh 			 */
2001f186373fSMark Fasheh 			ret = btrfs_next_leaf(root, path);
2002f186373fSMark Fasheh 			if (ret) {
2003f186373fSMark Fasheh 				if (ret >= 1)
2004f186373fSMark Fasheh 					ret = -ENOENT;
2005f186373fSMark Fasheh 				break;
2006f186373fSMark Fasheh 			}
2007f186373fSMark Fasheh 			continue;
2008f186373fSMark Fasheh 		}
2009f186373fSMark Fasheh 
2010f186373fSMark Fasheh 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
2011f186373fSMark Fasheh 
2012f186373fSMark Fasheh 		/*
2013f186373fSMark Fasheh 		 * Check that we're still looking at an extended ref key for
2014f186373fSMark Fasheh 		 * this particular objectid. If we have different
2015f186373fSMark Fasheh 		 * objectid or type then there are no more to be found
2016f186373fSMark Fasheh 		 * in the tree and we can exit.
2017f186373fSMark Fasheh 		 */
2018f186373fSMark Fasheh 		ret = -ENOENT;
2019f186373fSMark Fasheh 		if (found_key.objectid != inode_objectid)
2020f186373fSMark Fasheh 			break;
2021962a298fSDavid Sterba 		if (found_key.type != BTRFS_INODE_EXTREF_KEY)
2022f186373fSMark Fasheh 			break;
2023f186373fSMark Fasheh 
2024f186373fSMark Fasheh 		ret = 0;
2025f186373fSMark Fasheh 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
2026f186373fSMark Fasheh 		extref = (struct btrfs_inode_extref *)ptr;
2027f186373fSMark Fasheh 		*ret_extref = extref;
2028f186373fSMark Fasheh 		if (found_off)
2029f186373fSMark Fasheh 			*found_off = found_key.offset;
2030f186373fSMark Fasheh 		break;
2031f186373fSMark Fasheh 	}
2032f186373fSMark Fasheh 
2033f186373fSMark Fasheh 	return ret;
2034f186373fSMark Fasheh }
2035f186373fSMark Fasheh 
203648a3b636SEric Sandeen /*
203748a3b636SEric Sandeen  * this iterates to turn a name (from iref/extref) into a full filesystem path.
203848a3b636SEric Sandeen  * Elements of the path are separated by '/' and the path is guaranteed to be
203948a3b636SEric Sandeen  * 0-terminated. the path is only given within the current file system.
204048a3b636SEric Sandeen  * Therefore, it never starts with a '/'. the caller is responsible to provide
204148a3b636SEric Sandeen  * "size" bytes in "dest". the dest buffer will be filled backwards. finally,
204248a3b636SEric Sandeen  * the start point of the resulting string is returned. this pointer is within
204348a3b636SEric Sandeen  * dest, normally.
204448a3b636SEric Sandeen  * in case the path buffer would overflow, the pointer is decremented further
204548a3b636SEric Sandeen  * as if output was written to the buffer, though no more output is actually
204648a3b636SEric Sandeen  * generated. that way, the caller can determine how much space would be
204748a3b636SEric Sandeen  * required for the path to fit into the buffer. in that case, the returned
204848a3b636SEric Sandeen  * value will be smaller than dest. callers must check this!
204948a3b636SEric Sandeen  */
205096b5bd77SJan Schmidt char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
2051d24bec3aSMark Fasheh 			u32 name_len, unsigned long name_off,
2052a542ad1bSJan Schmidt 			struct extent_buffer *eb_in, u64 parent,
2053a542ad1bSJan Schmidt 			char *dest, u32 size)
2054a542ad1bSJan Schmidt {
2055a542ad1bSJan Schmidt 	int slot;
2056a542ad1bSJan Schmidt 	u64 next_inum;
2057a542ad1bSJan Schmidt 	int ret;
2058661bec6bSGabriel de Perthuis 	s64 bytes_left = ((s64)size) - 1;
2059a542ad1bSJan Schmidt 	struct extent_buffer *eb = eb_in;
2060a542ad1bSJan Schmidt 	struct btrfs_key found_key;
2061d24bec3aSMark Fasheh 	struct btrfs_inode_ref *iref;
2062a542ad1bSJan Schmidt 
2063a542ad1bSJan Schmidt 	if (bytes_left >= 0)
2064a542ad1bSJan Schmidt 		dest[bytes_left] = '\0';
2065a542ad1bSJan Schmidt 
2066a542ad1bSJan Schmidt 	while (1) {
2067d24bec3aSMark Fasheh 		bytes_left -= name_len;
2068a542ad1bSJan Schmidt 		if (bytes_left >= 0)
2069a542ad1bSJan Schmidt 			read_extent_buffer(eb, dest + bytes_left,
2070d24bec3aSMark Fasheh 					   name_off, name_len);
2071b916a59aSJan Schmidt 		if (eb != eb_in) {
20720c0fe3b0SFilipe Manana 			if (!path->skip_locking)
2073ac5887c8SJosef Bacik 				btrfs_tree_read_unlock(eb);
2074a542ad1bSJan Schmidt 			free_extent_buffer(eb);
2075b916a59aSJan Schmidt 		}
2076c234a24dSDavid Sterba 		ret = btrfs_find_item(fs_root, path, parent, 0,
2077c234a24dSDavid Sterba 				BTRFS_INODE_REF_KEY, &found_key);
20788f24b496SJan Schmidt 		if (ret > 0)
20798f24b496SJan Schmidt 			ret = -ENOENT;
2080a542ad1bSJan Schmidt 		if (ret)
2081a542ad1bSJan Schmidt 			break;
2082d24bec3aSMark Fasheh 
2083a542ad1bSJan Schmidt 		next_inum = found_key.offset;
2084a542ad1bSJan Schmidt 
2085a542ad1bSJan Schmidt 		/* regular exit ahead */
2086a542ad1bSJan Schmidt 		if (parent == next_inum)
2087a542ad1bSJan Schmidt 			break;
2088a542ad1bSJan Schmidt 
2089a542ad1bSJan Schmidt 		slot = path->slots[0];
2090a542ad1bSJan Schmidt 		eb = path->nodes[0];
2091a542ad1bSJan Schmidt 		/* make sure we can use eb after releasing the path */
2092b916a59aSJan Schmidt 		if (eb != eb_in) {
20930c0fe3b0SFilipe Manana 			path->nodes[0] = NULL;
20940c0fe3b0SFilipe Manana 			path->locks[0] = 0;
2095b916a59aSJan Schmidt 		}
2096a542ad1bSJan Schmidt 		btrfs_release_path(path);
2097a542ad1bSJan Schmidt 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2098d24bec3aSMark Fasheh 
2099d24bec3aSMark Fasheh 		name_len = btrfs_inode_ref_name_len(eb, iref);
2100d24bec3aSMark Fasheh 		name_off = (unsigned long)(iref + 1);
2101d24bec3aSMark Fasheh 
2102a542ad1bSJan Schmidt 		parent = next_inum;
2103a542ad1bSJan Schmidt 		--bytes_left;
2104a542ad1bSJan Schmidt 		if (bytes_left >= 0)
2105a542ad1bSJan Schmidt 			dest[bytes_left] = '/';
2106a542ad1bSJan Schmidt 	}
2107a542ad1bSJan Schmidt 
2108a542ad1bSJan Schmidt 	btrfs_release_path(path);
2109a542ad1bSJan Schmidt 
2110a542ad1bSJan Schmidt 	if (ret)
2111a542ad1bSJan Schmidt 		return ERR_PTR(ret);
2112a542ad1bSJan Schmidt 
2113a542ad1bSJan Schmidt 	return dest + bytes_left;
2114a542ad1bSJan Schmidt }
2115a542ad1bSJan Schmidt 
2116a542ad1bSJan Schmidt /*
2117a542ad1bSJan Schmidt  * this makes the path point to (logical EXTENT_ITEM *)
2118a542ad1bSJan Schmidt  * returns BTRFS_EXTENT_FLAG_DATA for data, BTRFS_EXTENT_FLAG_TREE_BLOCK for
2119a542ad1bSJan Schmidt  * tree blocks and <0 on error.
2120a542ad1bSJan Schmidt  */
2121a542ad1bSJan Schmidt int extent_from_logical(struct btrfs_fs_info *fs_info, u64 logical,
212269917e43SLiu Bo 			struct btrfs_path *path, struct btrfs_key *found_key,
212369917e43SLiu Bo 			u64 *flags_ret)
2124a542ad1bSJan Schmidt {
212529cbcf40SJosef Bacik 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, logical);
2126a542ad1bSJan Schmidt 	int ret;
2127a542ad1bSJan Schmidt 	u64 flags;
2128261c84b6SJosef Bacik 	u64 size = 0;
2129a542ad1bSJan Schmidt 	u32 item_size;
213073980becSJeff Mahoney 	const struct extent_buffer *eb;
2131a542ad1bSJan Schmidt 	struct btrfs_extent_item *ei;
2132a542ad1bSJan Schmidt 	struct btrfs_key key;
2133a542ad1bSJan Schmidt 
2134261c84b6SJosef Bacik 	if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2135261c84b6SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
2136261c84b6SJosef Bacik 	else
2137a542ad1bSJan Schmidt 		key.type = BTRFS_EXTENT_ITEM_KEY;
2138a542ad1bSJan Schmidt 	key.objectid = logical;
2139a542ad1bSJan Schmidt 	key.offset = (u64)-1;
2140a542ad1bSJan Schmidt 
214129cbcf40SJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2142a542ad1bSJan Schmidt 	if (ret < 0)
2143a542ad1bSJan Schmidt 		return ret;
2144a542ad1bSJan Schmidt 
214529cbcf40SJosef Bacik 	ret = btrfs_previous_extent_item(extent_root, path, 0);
2146850a8cdfSWang Shilong 	if (ret) {
2147850a8cdfSWang Shilong 		if (ret > 0)
2148580f0a67SJosef Bacik 			ret = -ENOENT;
2149580f0a67SJosef Bacik 		return ret;
2150580f0a67SJosef Bacik 	}
2151850a8cdfSWang Shilong 	btrfs_item_key_to_cpu(path->nodes[0], found_key, path->slots[0]);
2152261c84b6SJosef Bacik 	if (found_key->type == BTRFS_METADATA_ITEM_KEY)
2153da17066cSJeff Mahoney 		size = fs_info->nodesize;
2154261c84b6SJosef Bacik 	else if (found_key->type == BTRFS_EXTENT_ITEM_KEY)
2155261c84b6SJosef Bacik 		size = found_key->offset;
2156261c84b6SJosef Bacik 
2157580f0a67SJosef Bacik 	if (found_key->objectid > logical ||
2158261c84b6SJosef Bacik 	    found_key->objectid + size <= logical) {
2159ab8d0fc4SJeff Mahoney 		btrfs_debug(fs_info,
2160ab8d0fc4SJeff Mahoney 			"logical %llu is not within any extent", logical);
2161a542ad1bSJan Schmidt 		return -ENOENT;
21624692cf58SJan Schmidt 	}
2163a542ad1bSJan Schmidt 
2164a542ad1bSJan Schmidt 	eb = path->nodes[0];
21653212fa14SJosef Bacik 	item_size = btrfs_item_size(eb, path->slots[0]);
2166a542ad1bSJan Schmidt 	BUG_ON(item_size < sizeof(*ei));
2167a542ad1bSJan Schmidt 
2168a542ad1bSJan Schmidt 	ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
2169a542ad1bSJan Schmidt 	flags = btrfs_extent_flags(eb, ei);
2170a542ad1bSJan Schmidt 
2171ab8d0fc4SJeff Mahoney 	btrfs_debug(fs_info,
2172ab8d0fc4SJeff Mahoney 		"logical %llu is at position %llu within the extent (%llu EXTENT_ITEM %llu) flags %#llx size %u",
2173c1c9ff7cSGeert Uytterhoeven 		 logical, logical - found_key->objectid, found_key->objectid,
2174c1c9ff7cSGeert Uytterhoeven 		 found_key->offset, flags, item_size);
217569917e43SLiu Bo 
217669917e43SLiu Bo 	WARN_ON(!flags_ret);
217769917e43SLiu Bo 	if (flags_ret) {
2178a542ad1bSJan Schmidt 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
217969917e43SLiu Bo 			*flags_ret = BTRFS_EXTENT_FLAG_TREE_BLOCK;
218069917e43SLiu Bo 		else if (flags & BTRFS_EXTENT_FLAG_DATA)
218169917e43SLiu Bo 			*flags_ret = BTRFS_EXTENT_FLAG_DATA;
218269917e43SLiu Bo 		else
2183290342f6SArnd Bergmann 			BUG();
218469917e43SLiu Bo 		return 0;
218569917e43SLiu Bo 	}
2186a542ad1bSJan Schmidt 
2187a542ad1bSJan Schmidt 	return -EIO;
2188a542ad1bSJan Schmidt }
2189a542ad1bSJan Schmidt 
2190a542ad1bSJan Schmidt /*
2191a542ad1bSJan Schmidt  * helper function to iterate extent inline refs. ptr must point to a 0 value
2192a542ad1bSJan Schmidt  * for the first call and may be modified. it is used to track state.
2193a542ad1bSJan Schmidt  * if more refs exist, 0 is returned and the next call to
2194e0c476b1SJeff Mahoney  * get_extent_inline_ref must pass the modified ptr parameter to get the
2195a542ad1bSJan Schmidt  * next ref. after the last ref was processed, 1 is returned.
2196a542ad1bSJan Schmidt  * returns <0 on error
2197a542ad1bSJan Schmidt  */
2198e0c476b1SJeff Mahoney static int get_extent_inline_ref(unsigned long *ptr,
219973980becSJeff Mahoney 				 const struct extent_buffer *eb,
220073980becSJeff Mahoney 				 const struct btrfs_key *key,
220173980becSJeff Mahoney 				 const struct btrfs_extent_item *ei,
220273980becSJeff Mahoney 				 u32 item_size,
2203a542ad1bSJan Schmidt 				 struct btrfs_extent_inline_ref **out_eiref,
2204a542ad1bSJan Schmidt 				 int *out_type)
2205a542ad1bSJan Schmidt {
2206a542ad1bSJan Schmidt 	unsigned long end;
2207a542ad1bSJan Schmidt 	u64 flags;
2208a542ad1bSJan Schmidt 	struct btrfs_tree_block_info *info;
2209a542ad1bSJan Schmidt 
2210a542ad1bSJan Schmidt 	if (!*ptr) {
2211a542ad1bSJan Schmidt 		/* first call */
2212a542ad1bSJan Schmidt 		flags = btrfs_extent_flags(eb, ei);
2213a542ad1bSJan Schmidt 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
22146eda71d0SLiu Bo 			if (key->type == BTRFS_METADATA_ITEM_KEY) {
22156eda71d0SLiu Bo 				/* a skinny metadata extent */
22166eda71d0SLiu Bo 				*out_eiref =
22176eda71d0SLiu Bo 				     (struct btrfs_extent_inline_ref *)(ei + 1);
22186eda71d0SLiu Bo 			} else {
22196eda71d0SLiu Bo 				WARN_ON(key->type != BTRFS_EXTENT_ITEM_KEY);
2220a542ad1bSJan Schmidt 				info = (struct btrfs_tree_block_info *)(ei + 1);
2221a542ad1bSJan Schmidt 				*out_eiref =
2222a542ad1bSJan Schmidt 				   (struct btrfs_extent_inline_ref *)(info + 1);
22236eda71d0SLiu Bo 			}
2224a542ad1bSJan Schmidt 		} else {
2225a542ad1bSJan Schmidt 			*out_eiref = (struct btrfs_extent_inline_ref *)(ei + 1);
2226a542ad1bSJan Schmidt 		}
2227a542ad1bSJan Schmidt 		*ptr = (unsigned long)*out_eiref;
2228cd857dd6SLiu Bo 		if ((unsigned long)(*ptr) >= (unsigned long)ei + item_size)
2229a542ad1bSJan Schmidt 			return -ENOENT;
2230a542ad1bSJan Schmidt 	}
2231a542ad1bSJan Schmidt 
2232a542ad1bSJan Schmidt 	end = (unsigned long)ei + item_size;
22336eda71d0SLiu Bo 	*out_eiref = (struct btrfs_extent_inline_ref *)(*ptr);
22343de28d57SLiu Bo 	*out_type = btrfs_get_extent_inline_ref_type(eb, *out_eiref,
22353de28d57SLiu Bo 						     BTRFS_REF_TYPE_ANY);
22363de28d57SLiu Bo 	if (*out_type == BTRFS_REF_TYPE_INVALID)
2237af431dcbSSu Yue 		return -EUCLEAN;
2238a542ad1bSJan Schmidt 
2239a542ad1bSJan Schmidt 	*ptr += btrfs_extent_inline_ref_size(*out_type);
2240a542ad1bSJan Schmidt 	WARN_ON(*ptr > end);
2241a542ad1bSJan Schmidt 	if (*ptr == end)
2242a542ad1bSJan Schmidt 		return 1; /* last */
2243a542ad1bSJan Schmidt 
2244a542ad1bSJan Schmidt 	return 0;
2245a542ad1bSJan Schmidt }
2246a542ad1bSJan Schmidt 
2247a542ad1bSJan Schmidt /*
2248a542ad1bSJan Schmidt  * reads the tree block backref for an extent. tree level and root are returned
2249a542ad1bSJan Schmidt  * through out_level and out_root. ptr must point to a 0 value for the first
2250e0c476b1SJeff Mahoney  * call and may be modified (see get_extent_inline_ref comment).
2251a542ad1bSJan Schmidt  * returns 0 if data was provided, 1 if there was no more data to provide or
2252a542ad1bSJan Schmidt  * <0 on error.
2253a542ad1bSJan Schmidt  */
2254a542ad1bSJan Schmidt int tree_backref_for_extent(unsigned long *ptr, struct extent_buffer *eb,
22556eda71d0SLiu Bo 			    struct btrfs_key *key, struct btrfs_extent_item *ei,
22566eda71d0SLiu Bo 			    u32 item_size, u64 *out_root, u8 *out_level)
2257a542ad1bSJan Schmidt {
2258a542ad1bSJan Schmidt 	int ret;
2259a542ad1bSJan Schmidt 	int type;
2260a542ad1bSJan Schmidt 	struct btrfs_extent_inline_ref *eiref;
2261a542ad1bSJan Schmidt 
2262a542ad1bSJan Schmidt 	if (*ptr == (unsigned long)-1)
2263a542ad1bSJan Schmidt 		return 1;
2264a542ad1bSJan Schmidt 
2265a542ad1bSJan Schmidt 	while (1) {
2266e0c476b1SJeff Mahoney 		ret = get_extent_inline_ref(ptr, eb, key, ei, item_size,
2267a542ad1bSJan Schmidt 					      &eiref, &type);
2268a542ad1bSJan Schmidt 		if (ret < 0)
2269a542ad1bSJan Schmidt 			return ret;
2270a542ad1bSJan Schmidt 
2271a542ad1bSJan Schmidt 		if (type == BTRFS_TREE_BLOCK_REF_KEY ||
2272a542ad1bSJan Schmidt 		    type == BTRFS_SHARED_BLOCK_REF_KEY)
2273a542ad1bSJan Schmidt 			break;
2274a542ad1bSJan Schmidt 
2275a542ad1bSJan Schmidt 		if (ret == 1)
2276a542ad1bSJan Schmidt 			return 1;
2277a542ad1bSJan Schmidt 	}
2278a542ad1bSJan Schmidt 
2279a542ad1bSJan Schmidt 	/* we can treat both ref types equally here */
2280a542ad1bSJan Schmidt 	*out_root = btrfs_extent_inline_ref_offset(eb, eiref);
2281a1317f45SFilipe Manana 
2282a1317f45SFilipe Manana 	if (key->type == BTRFS_EXTENT_ITEM_KEY) {
2283a1317f45SFilipe Manana 		struct btrfs_tree_block_info *info;
2284a1317f45SFilipe Manana 
2285a1317f45SFilipe Manana 		info = (struct btrfs_tree_block_info *)(ei + 1);
2286a542ad1bSJan Schmidt 		*out_level = btrfs_tree_block_level(eb, info);
2287a1317f45SFilipe Manana 	} else {
2288a1317f45SFilipe Manana 		ASSERT(key->type == BTRFS_METADATA_ITEM_KEY);
2289a1317f45SFilipe Manana 		*out_level = (u8)key->offset;
2290a1317f45SFilipe Manana 	}
2291a542ad1bSJan Schmidt 
2292a542ad1bSJan Schmidt 	if (ret == 1)
2293a542ad1bSJan Schmidt 		*ptr = (unsigned long)-1;
2294a542ad1bSJan Schmidt 
2295a542ad1bSJan Schmidt 	return 0;
2296a542ad1bSJan Schmidt }
2297a542ad1bSJan Schmidt 
2298ab8d0fc4SJeff Mahoney static int iterate_leaf_refs(struct btrfs_fs_info *fs_info,
2299ab8d0fc4SJeff Mahoney 			     struct extent_inode_elem *inode_list,
2300976b1908SJan Schmidt 			     u64 root, u64 extent_item_objectid,
23014692cf58SJan Schmidt 			     iterate_extent_inodes_t *iterate, void *ctx)
2302a542ad1bSJan Schmidt {
2303976b1908SJan Schmidt 	struct extent_inode_elem *eie;
23044692cf58SJan Schmidt 	int ret = 0;
2305a542ad1bSJan Schmidt 
2306976b1908SJan Schmidt 	for (eie = inode_list; eie; eie = eie->next) {
2307ab8d0fc4SJeff Mahoney 		btrfs_debug(fs_info,
2308ab8d0fc4SJeff Mahoney 			    "ref for %llu resolved, key (%llu EXTEND_DATA %llu), root %llu",
2309ab8d0fc4SJeff Mahoney 			    extent_item_objectid, eie->inum,
2310ab8d0fc4SJeff Mahoney 			    eie->offset, root);
2311c7499a64SFilipe Manana 		ret = iterate(eie->inum, eie->offset, eie->num_bytes, root, ctx);
23124692cf58SJan Schmidt 		if (ret) {
2313ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_info,
2314ab8d0fc4SJeff Mahoney 				    "stopping iteration for %llu due to ret=%d",
2315976b1908SJan Schmidt 				    extent_item_objectid, ret);
2316a542ad1bSJan Schmidt 			break;
2317a542ad1bSJan Schmidt 		}
2318a542ad1bSJan Schmidt 	}
2319a542ad1bSJan Schmidt 
2320a542ad1bSJan Schmidt 	return ret;
2321a542ad1bSJan Schmidt }
2322a542ad1bSJan Schmidt 
2323a542ad1bSJan Schmidt /*
2324a542ad1bSJan Schmidt  * calls iterate() for every inode that references the extent identified by
23254692cf58SJan Schmidt  * the given parameters.
2326a542ad1bSJan Schmidt  * when the iterator function returns a non-zero value, iteration stops.
2327a542ad1bSJan Schmidt  */
2328a2c8d27eSFilipe Manana int iterate_extent_inodes(struct btrfs_backref_walk_ctx *ctx,
2329a2c8d27eSFilipe Manana 			  bool search_commit_root,
2330a2c8d27eSFilipe Manana 			  iterate_extent_inodes_t *iterate, void *user_ctx)
2331a542ad1bSJan Schmidt {
2332a542ad1bSJan Schmidt 	int ret;
2333a2c8d27eSFilipe Manana 	struct ulist *refs;
2334a2c8d27eSFilipe Manana 	struct ulist_node *ref_node;
2335f3a84ccdSFilipe Manana 	struct btrfs_seq_list seq_elem = BTRFS_SEQ_LIST_INIT(seq_elem);
2336cd1b413cSJan Schmidt 	struct ulist_iterator ref_uiter;
2337a542ad1bSJan Schmidt 
2338a2c8d27eSFilipe Manana 	btrfs_debug(ctx->fs_info, "resolving all inodes for extent %llu",
2339a2c8d27eSFilipe Manana 		    ctx->bytenr);
2340a2c8d27eSFilipe Manana 
2341a2c8d27eSFilipe Manana 	ASSERT(ctx->trans == NULL);
23421baea6f1SFilipe Manana 	ASSERT(ctx->roots == NULL);
23431baea6f1SFilipe Manana 
2344da61d31aSJosef Bacik 	if (!search_commit_root) {
2345a2c8d27eSFilipe Manana 		struct btrfs_trans_handle *trans;
2346a2c8d27eSFilipe Manana 
2347a2c8d27eSFilipe Manana 		trans = btrfs_attach_transaction(ctx->fs_info->tree_root);
2348bfc61c36SFilipe Manana 		if (IS_ERR(trans)) {
2349bfc61c36SFilipe Manana 			if (PTR_ERR(trans) != -ENOENT &&
235066d04209SFilipe Manana 			    PTR_ERR(trans) != -EROFS)
23517a3ae2f8SJan Schmidt 				return PTR_ERR(trans);
2352bfc61c36SFilipe Manana 			trans = NULL;
23537a3ae2f8SJan Schmidt 		}
2354a2c8d27eSFilipe Manana 		ctx->trans = trans;
2355bfc61c36SFilipe Manana 	}
2356bfc61c36SFilipe Manana 
2357a2c8d27eSFilipe Manana 	if (ctx->trans) {
2358a2c8d27eSFilipe Manana 		btrfs_get_tree_mod_seq(ctx->fs_info, &seq_elem);
2359a2c8d27eSFilipe Manana 		ctx->time_seq = seq_elem.seq;
2360a2c8d27eSFilipe Manana 	} else {
2361a2c8d27eSFilipe Manana 		down_read(&ctx->fs_info->commit_root_sem);
2362a2c8d27eSFilipe Manana 	}
23634692cf58SJan Schmidt 
2364a2c8d27eSFilipe Manana 	ret = btrfs_find_all_leafs(ctx);
23654692cf58SJan Schmidt 	if (ret)
23664692cf58SJan Schmidt 		goto out;
2367a2c8d27eSFilipe Manana 	refs = ctx->refs;
2368a2c8d27eSFilipe Manana 	ctx->refs = NULL;
23694692cf58SJan Schmidt 
2370cd1b413cSJan Schmidt 	ULIST_ITER_INIT(&ref_uiter);
2371cd1b413cSJan Schmidt 	while (!ret && (ref_node = ulist_next(refs, &ref_uiter))) {
237266d04209SFilipe Manana 		const u64 leaf_bytenr = ref_node->val;
2373a2c8d27eSFilipe Manana 		struct ulist_node *root_node;
2374a2c8d27eSFilipe Manana 		struct ulist_iterator root_uiter;
237566d04209SFilipe Manana 		struct extent_inode_elem *inode_list;
2376a2c8d27eSFilipe Manana 
237766d04209SFilipe Manana 		inode_list = (struct extent_inode_elem *)(uintptr_t)ref_node->aux;
237866d04209SFilipe Manana 
237966d04209SFilipe Manana 		if (ctx->cache_lookup) {
238066d04209SFilipe Manana 			const u64 *root_ids;
238166d04209SFilipe Manana 			int root_count;
238266d04209SFilipe Manana 			bool cached;
238366d04209SFilipe Manana 
238466d04209SFilipe Manana 			cached = ctx->cache_lookup(leaf_bytenr, ctx->user_ctx,
238566d04209SFilipe Manana 						   &root_ids, &root_count);
238666d04209SFilipe Manana 			if (cached) {
238766d04209SFilipe Manana 				for (int i = 0; i < root_count; i++) {
238866d04209SFilipe Manana 					ret = iterate_leaf_refs(ctx->fs_info,
238966d04209SFilipe Manana 								inode_list,
239066d04209SFilipe Manana 								root_ids[i],
239166d04209SFilipe Manana 								leaf_bytenr,
239266d04209SFilipe Manana 								iterate,
239366d04209SFilipe Manana 								user_ctx);
239466d04209SFilipe Manana 					if (ret)
239566d04209SFilipe Manana 						break;
239666d04209SFilipe Manana 				}
239766d04209SFilipe Manana 				continue;
239866d04209SFilipe Manana 			}
239966d04209SFilipe Manana 		}
240066d04209SFilipe Manana 
240166d04209SFilipe Manana 		if (!ctx->roots) {
240266d04209SFilipe Manana 			ctx->roots = ulist_alloc(GFP_NOFS);
240366d04209SFilipe Manana 			if (!ctx->roots) {
240466d04209SFilipe Manana 				ret = -ENOMEM;
240566d04209SFilipe Manana 				break;
240666d04209SFilipe Manana 			}
240766d04209SFilipe Manana 		}
240866d04209SFilipe Manana 
240966d04209SFilipe Manana 		ctx->bytenr = leaf_bytenr;
2410a2c8d27eSFilipe Manana 		ret = btrfs_find_all_roots_safe(ctx);
24114692cf58SJan Schmidt 		if (ret)
2412a542ad1bSJan Schmidt 			break;
2413a2c8d27eSFilipe Manana 
241466d04209SFilipe Manana 		if (ctx->cache_store)
241566d04209SFilipe Manana 			ctx->cache_store(leaf_bytenr, ctx->roots, ctx->user_ctx);
241666d04209SFilipe Manana 
2417cd1b413cSJan Schmidt 		ULIST_ITER_INIT(&root_uiter);
2418a2c8d27eSFilipe Manana 		while (!ret && (root_node = ulist_next(ctx->roots, &root_uiter))) {
2419a2c8d27eSFilipe Manana 			btrfs_debug(ctx->fs_info,
2420ab8d0fc4SJeff Mahoney 				    "root %llu references leaf %llu, data list %#llx",
2421ab8d0fc4SJeff Mahoney 				    root_node->val, ref_node->val,
2422c1c9ff7cSGeert Uytterhoeven 				    ref_node->aux);
242366d04209SFilipe Manana 			ret = iterate_leaf_refs(ctx->fs_info, inode_list,
2424a2c8d27eSFilipe Manana 						root_node->val, ctx->bytenr,
2425a2c8d27eSFilipe Manana 						iterate, user_ctx);
24264692cf58SJan Schmidt 		}
24271baea6f1SFilipe Manana 		ulist_reinit(ctx->roots);
2428a542ad1bSJan Schmidt 	}
2429a542ad1bSJan Schmidt 
2430976b1908SJan Schmidt 	free_leaf_list(refs);
24314692cf58SJan Schmidt out:
2432a2c8d27eSFilipe Manana 	if (ctx->trans) {
2433a2c8d27eSFilipe Manana 		btrfs_put_tree_mod_seq(ctx->fs_info, &seq_elem);
2434a2c8d27eSFilipe Manana 		btrfs_end_transaction(ctx->trans);
2435a2c8d27eSFilipe Manana 		ctx->trans = NULL;
24369e351cc8SJosef Bacik 	} else {
2437a2c8d27eSFilipe Manana 		up_read(&ctx->fs_info->commit_root_sem);
24387a3ae2f8SJan Schmidt 	}
24397a3ae2f8SJan Schmidt 
24401baea6f1SFilipe Manana 	ulist_free(ctx->roots);
24411baea6f1SFilipe Manana 	ctx->roots = NULL;
24421baea6f1SFilipe Manana 
244388ffb665SFilipe Manana 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP)
244488ffb665SFilipe Manana 		ret = 0;
244588ffb665SFilipe Manana 
2446a542ad1bSJan Schmidt 	return ret;
2447a542ad1bSJan Schmidt }
2448a542ad1bSJan Schmidt 
2449c7499a64SFilipe Manana static int build_ino_list(u64 inum, u64 offset, u64 num_bytes, u64 root, void *ctx)
2450e3059ec0SDavid Sterba {
2451e3059ec0SDavid Sterba 	struct btrfs_data_container *inodes = ctx;
2452e3059ec0SDavid Sterba 	const size_t c = 3 * sizeof(u64);
2453e3059ec0SDavid Sterba 
2454e3059ec0SDavid Sterba 	if (inodes->bytes_left >= c) {
2455e3059ec0SDavid Sterba 		inodes->bytes_left -= c;
2456e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt] = inum;
2457e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt + 1] = offset;
2458e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt + 2] = root;
2459e3059ec0SDavid Sterba 		inodes->elem_cnt += 3;
2460e3059ec0SDavid Sterba 	} else {
2461e3059ec0SDavid Sterba 		inodes->bytes_missing += c - inodes->bytes_left;
2462e3059ec0SDavid Sterba 		inodes->bytes_left = 0;
2463e3059ec0SDavid Sterba 		inodes->elem_missed += 3;
2464e3059ec0SDavid Sterba 	}
2465e3059ec0SDavid Sterba 
2466e3059ec0SDavid Sterba 	return 0;
2467e3059ec0SDavid Sterba }
2468e3059ec0SDavid Sterba 
2469a542ad1bSJan Schmidt int iterate_inodes_from_logical(u64 logical, struct btrfs_fs_info *fs_info,
2470a542ad1bSJan Schmidt 				struct btrfs_path *path,
2471e3059ec0SDavid Sterba 				void *ctx, bool ignore_offset)
2472a542ad1bSJan Schmidt {
2473a2c8d27eSFilipe Manana 	struct btrfs_backref_walk_ctx walk_ctx = { 0 };
2474a542ad1bSJan Schmidt 	int ret;
247569917e43SLiu Bo 	u64 flags = 0;
2476a542ad1bSJan Schmidt 	struct btrfs_key found_key;
24777a3ae2f8SJan Schmidt 	int search_commit_root = path->search_commit_root;
2478a542ad1bSJan Schmidt 
247969917e43SLiu Bo 	ret = extent_from_logical(fs_info, logical, path, &found_key, &flags);
24804692cf58SJan Schmidt 	btrfs_release_path(path);
2481a542ad1bSJan Schmidt 	if (ret < 0)
2482a542ad1bSJan Schmidt 		return ret;
248369917e43SLiu Bo 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
24843627bf45SStefan Behrens 		return -EINVAL;
2485a542ad1bSJan Schmidt 
2486a2c8d27eSFilipe Manana 	walk_ctx.bytenr = found_key.objectid;
24876ce6ba53SFilipe Manana 	if (ignore_offset)
2488a2c8d27eSFilipe Manana 		walk_ctx.ignore_extent_item_pos = true;
24896ce6ba53SFilipe Manana 	else
2490a2c8d27eSFilipe Manana 		walk_ctx.extent_item_pos = logical - found_key.objectid;
2491a2c8d27eSFilipe Manana 	walk_ctx.fs_info = fs_info;
24926ce6ba53SFilipe Manana 
2493a2c8d27eSFilipe Manana 	return iterate_extent_inodes(&walk_ctx, search_commit_root,
24946ce6ba53SFilipe Manana 				     build_ino_list, ctx);
2495a542ad1bSJan Schmidt }
2496a542ad1bSJan Schmidt 
2497ad6240f6SDavid Sterba static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2498875d1daaSDavid Sterba 			 struct extent_buffer *eb, struct inode_fs_paths *ipath);
2499d24bec3aSMark Fasheh 
2500875d1daaSDavid Sterba static int iterate_inode_refs(u64 inum, struct inode_fs_paths *ipath)
2501a542ad1bSJan Schmidt {
2502aefc1eb1SJan Schmidt 	int ret = 0;
2503a542ad1bSJan Schmidt 	int slot;
2504a542ad1bSJan Schmidt 	u32 cur;
2505a542ad1bSJan Schmidt 	u32 len;
2506a542ad1bSJan Schmidt 	u32 name_len;
2507a542ad1bSJan Schmidt 	u64 parent = 0;
2508a542ad1bSJan Schmidt 	int found = 0;
2509875d1daaSDavid Sterba 	struct btrfs_root *fs_root = ipath->fs_root;
2510875d1daaSDavid Sterba 	struct btrfs_path *path = ipath->btrfs_path;
2511a542ad1bSJan Schmidt 	struct extent_buffer *eb;
2512a542ad1bSJan Schmidt 	struct btrfs_inode_ref *iref;
2513a542ad1bSJan Schmidt 	struct btrfs_key found_key;
2514a542ad1bSJan Schmidt 
2515aefc1eb1SJan Schmidt 	while (!ret) {
2516c234a24dSDavid Sterba 		ret = btrfs_find_item(fs_root, path, inum,
2517c234a24dSDavid Sterba 				parent ? parent + 1 : 0, BTRFS_INODE_REF_KEY,
2518a542ad1bSJan Schmidt 				&found_key);
2519c234a24dSDavid Sterba 
2520a542ad1bSJan Schmidt 		if (ret < 0)
2521a542ad1bSJan Schmidt 			break;
2522a542ad1bSJan Schmidt 		if (ret) {
2523a542ad1bSJan Schmidt 			ret = found ? 0 : -ENOENT;
2524a542ad1bSJan Schmidt 			break;
2525a542ad1bSJan Schmidt 		}
2526a542ad1bSJan Schmidt 		++found;
2527a542ad1bSJan Schmidt 
2528a542ad1bSJan Schmidt 		parent = found_key.offset;
2529a542ad1bSJan Schmidt 		slot = path->slots[0];
25303fe81ce2SFilipe David Borba Manana 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
25313fe81ce2SFilipe David Borba Manana 		if (!eb) {
25323fe81ce2SFilipe David Borba Manana 			ret = -ENOMEM;
25333fe81ce2SFilipe David Borba Manana 			break;
25343fe81ce2SFilipe David Borba Manana 		}
2535a542ad1bSJan Schmidt 		btrfs_release_path(path);
2536a542ad1bSJan Schmidt 
2537a542ad1bSJan Schmidt 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2538a542ad1bSJan Schmidt 
25393212fa14SJosef Bacik 		for (cur = 0; cur < btrfs_item_size(eb, slot); cur += len) {
2540a542ad1bSJan Schmidt 			name_len = btrfs_inode_ref_name_len(eb, iref);
2541a542ad1bSJan Schmidt 			/* path must be released before calling iterate()! */
2542ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_root->fs_info,
2543ab8d0fc4SJeff Mahoney 				"following ref at offset %u for inode %llu in tree %llu",
25444fd786e6SMisono Tomohiro 				cur, found_key.objectid,
25454fd786e6SMisono Tomohiro 				fs_root->root_key.objectid);
2546ad6240f6SDavid Sterba 			ret = inode_to_path(parent, name_len,
2547875d1daaSDavid Sterba 				      (unsigned long)(iref + 1), eb, ipath);
2548aefc1eb1SJan Schmidt 			if (ret)
2549a542ad1bSJan Schmidt 				break;
2550a542ad1bSJan Schmidt 			len = sizeof(*iref) + name_len;
2551a542ad1bSJan Schmidt 			iref = (struct btrfs_inode_ref *)((char *)iref + len);
2552a542ad1bSJan Schmidt 		}
2553a542ad1bSJan Schmidt 		free_extent_buffer(eb);
2554a542ad1bSJan Schmidt 	}
2555a542ad1bSJan Schmidt 
2556a542ad1bSJan Schmidt 	btrfs_release_path(path);
2557a542ad1bSJan Schmidt 
2558a542ad1bSJan Schmidt 	return ret;
2559a542ad1bSJan Schmidt }
2560a542ad1bSJan Schmidt 
2561875d1daaSDavid Sterba static int iterate_inode_extrefs(u64 inum, struct inode_fs_paths *ipath)
2562d24bec3aSMark Fasheh {
2563d24bec3aSMark Fasheh 	int ret;
2564d24bec3aSMark Fasheh 	int slot;
2565d24bec3aSMark Fasheh 	u64 offset = 0;
2566d24bec3aSMark Fasheh 	u64 parent;
2567d24bec3aSMark Fasheh 	int found = 0;
2568875d1daaSDavid Sterba 	struct btrfs_root *fs_root = ipath->fs_root;
2569875d1daaSDavid Sterba 	struct btrfs_path *path = ipath->btrfs_path;
2570d24bec3aSMark Fasheh 	struct extent_buffer *eb;
2571d24bec3aSMark Fasheh 	struct btrfs_inode_extref *extref;
2572d24bec3aSMark Fasheh 	u32 item_size;
2573d24bec3aSMark Fasheh 	u32 cur_offset;
2574d24bec3aSMark Fasheh 	unsigned long ptr;
2575d24bec3aSMark Fasheh 
2576d24bec3aSMark Fasheh 	while (1) {
2577d24bec3aSMark Fasheh 		ret = btrfs_find_one_extref(fs_root, inum, offset, path, &extref,
2578d24bec3aSMark Fasheh 					    &offset);
2579d24bec3aSMark Fasheh 		if (ret < 0)
2580d24bec3aSMark Fasheh 			break;
2581d24bec3aSMark Fasheh 		if (ret) {
2582d24bec3aSMark Fasheh 			ret = found ? 0 : -ENOENT;
2583d24bec3aSMark Fasheh 			break;
2584d24bec3aSMark Fasheh 		}
2585d24bec3aSMark Fasheh 		++found;
2586d24bec3aSMark Fasheh 
2587d24bec3aSMark Fasheh 		slot = path->slots[0];
25883fe81ce2SFilipe David Borba Manana 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
25893fe81ce2SFilipe David Borba Manana 		if (!eb) {
25903fe81ce2SFilipe David Borba Manana 			ret = -ENOMEM;
25913fe81ce2SFilipe David Borba Manana 			break;
25923fe81ce2SFilipe David Borba Manana 		}
2593d24bec3aSMark Fasheh 		btrfs_release_path(path);
2594d24bec3aSMark Fasheh 
25953212fa14SJosef Bacik 		item_size = btrfs_item_size(eb, slot);
25962849a854SChris Mason 		ptr = btrfs_item_ptr_offset(eb, slot);
2597d24bec3aSMark Fasheh 		cur_offset = 0;
2598d24bec3aSMark Fasheh 
2599d24bec3aSMark Fasheh 		while (cur_offset < item_size) {
2600d24bec3aSMark Fasheh 			u32 name_len;
2601d24bec3aSMark Fasheh 
2602d24bec3aSMark Fasheh 			extref = (struct btrfs_inode_extref *)(ptr + cur_offset);
2603d24bec3aSMark Fasheh 			parent = btrfs_inode_extref_parent(eb, extref);
2604d24bec3aSMark Fasheh 			name_len = btrfs_inode_extref_name_len(eb, extref);
2605ad6240f6SDavid Sterba 			ret = inode_to_path(parent, name_len,
2606875d1daaSDavid Sterba 				      (unsigned long)&extref->name, eb, ipath);
2607d24bec3aSMark Fasheh 			if (ret)
2608d24bec3aSMark Fasheh 				break;
2609d24bec3aSMark Fasheh 
26102849a854SChris Mason 			cur_offset += btrfs_inode_extref_name_len(eb, extref);
2611d24bec3aSMark Fasheh 			cur_offset += sizeof(*extref);
2612d24bec3aSMark Fasheh 		}
2613d24bec3aSMark Fasheh 		free_extent_buffer(eb);
2614d24bec3aSMark Fasheh 
2615d24bec3aSMark Fasheh 		offset++;
2616d24bec3aSMark Fasheh 	}
2617d24bec3aSMark Fasheh 
2618d24bec3aSMark Fasheh 	btrfs_release_path(path);
2619d24bec3aSMark Fasheh 
2620d24bec3aSMark Fasheh 	return ret;
2621d24bec3aSMark Fasheh }
2622d24bec3aSMark Fasheh 
2623a542ad1bSJan Schmidt /*
2624a542ad1bSJan Schmidt  * returns 0 if the path could be dumped (probably truncated)
2625a542ad1bSJan Schmidt  * returns <0 in case of an error
2626a542ad1bSJan Schmidt  */
2627d24bec3aSMark Fasheh static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2628875d1daaSDavid Sterba 			 struct extent_buffer *eb, struct inode_fs_paths *ipath)
2629a542ad1bSJan Schmidt {
2630a542ad1bSJan Schmidt 	char *fspath;
2631a542ad1bSJan Schmidt 	char *fspath_min;
2632a542ad1bSJan Schmidt 	int i = ipath->fspath->elem_cnt;
2633a542ad1bSJan Schmidt 	const int s_ptr = sizeof(char *);
2634a542ad1bSJan Schmidt 	u32 bytes_left;
2635a542ad1bSJan Schmidt 
2636a542ad1bSJan Schmidt 	bytes_left = ipath->fspath->bytes_left > s_ptr ?
2637a542ad1bSJan Schmidt 					ipath->fspath->bytes_left - s_ptr : 0;
2638a542ad1bSJan Schmidt 
2639740c3d22SChris Mason 	fspath_min = (char *)ipath->fspath->val + (i + 1) * s_ptr;
264096b5bd77SJan Schmidt 	fspath = btrfs_ref_to_path(ipath->fs_root, ipath->btrfs_path, name_len,
264196b5bd77SJan Schmidt 				   name_off, eb, inum, fspath_min, bytes_left);
2642a542ad1bSJan Schmidt 	if (IS_ERR(fspath))
2643a542ad1bSJan Schmidt 		return PTR_ERR(fspath);
2644a542ad1bSJan Schmidt 
2645a542ad1bSJan Schmidt 	if (fspath > fspath_min) {
2646745c4d8eSJeff Mahoney 		ipath->fspath->val[i] = (u64)(unsigned long)fspath;
2647a542ad1bSJan Schmidt 		++ipath->fspath->elem_cnt;
2648a542ad1bSJan Schmidt 		ipath->fspath->bytes_left = fspath - fspath_min;
2649a542ad1bSJan Schmidt 	} else {
2650a542ad1bSJan Schmidt 		++ipath->fspath->elem_missed;
2651a542ad1bSJan Schmidt 		ipath->fspath->bytes_missing += fspath_min - fspath;
2652a542ad1bSJan Schmidt 		ipath->fspath->bytes_left = 0;
2653a542ad1bSJan Schmidt 	}
2654a542ad1bSJan Schmidt 
2655a542ad1bSJan Schmidt 	return 0;
2656a542ad1bSJan Schmidt }
2657a542ad1bSJan Schmidt 
2658a542ad1bSJan Schmidt /*
2659a542ad1bSJan Schmidt  * this dumps all file system paths to the inode into the ipath struct, provided
2660a542ad1bSJan Schmidt  * is has been created large enough. each path is zero-terminated and accessed
2661740c3d22SChris Mason  * from ipath->fspath->val[i].
2662a542ad1bSJan Schmidt  * when it returns, there are ipath->fspath->elem_cnt number of paths available
2663740c3d22SChris Mason  * in ipath->fspath->val[]. when the allocated space wasn't sufficient, the
266401327610SNicholas D Steeves  * number of missed paths is recorded in ipath->fspath->elem_missed, otherwise,
2665a542ad1bSJan Schmidt  * it's zero. ipath->fspath->bytes_missing holds the number of bytes that would
2666a542ad1bSJan Schmidt  * have been needed to return all paths.
2667a542ad1bSJan Schmidt  */
2668a542ad1bSJan Schmidt int paths_from_inode(u64 inum, struct inode_fs_paths *ipath)
2669a542ad1bSJan Schmidt {
2670ad6240f6SDavid Sterba 	int ret;
2671ad6240f6SDavid Sterba 	int found_refs = 0;
2672ad6240f6SDavid Sterba 
2673875d1daaSDavid Sterba 	ret = iterate_inode_refs(inum, ipath);
2674ad6240f6SDavid Sterba 	if (!ret)
2675ad6240f6SDavid Sterba 		++found_refs;
2676ad6240f6SDavid Sterba 	else if (ret != -ENOENT)
2677ad6240f6SDavid Sterba 		return ret;
2678ad6240f6SDavid Sterba 
2679875d1daaSDavid Sterba 	ret = iterate_inode_extrefs(inum, ipath);
2680ad6240f6SDavid Sterba 	if (ret == -ENOENT && found_refs)
2681ad6240f6SDavid Sterba 		return 0;
2682ad6240f6SDavid Sterba 
2683ad6240f6SDavid Sterba 	return ret;
2684a542ad1bSJan Schmidt }
2685a542ad1bSJan Schmidt 
2686a542ad1bSJan Schmidt struct btrfs_data_container *init_data_container(u32 total_bytes)
2687a542ad1bSJan Schmidt {
2688a542ad1bSJan Schmidt 	struct btrfs_data_container *data;
2689a542ad1bSJan Schmidt 	size_t alloc_bytes;
2690a542ad1bSJan Schmidt 
2691a542ad1bSJan Schmidt 	alloc_bytes = max_t(size_t, total_bytes, sizeof(*data));
2692f54de068SDavid Sterba 	data = kvmalloc(alloc_bytes, GFP_KERNEL);
2693a542ad1bSJan Schmidt 	if (!data)
2694a542ad1bSJan Schmidt 		return ERR_PTR(-ENOMEM);
2695a542ad1bSJan Schmidt 
2696a542ad1bSJan Schmidt 	if (total_bytes >= sizeof(*data)) {
2697a542ad1bSJan Schmidt 		data->bytes_left = total_bytes - sizeof(*data);
2698a542ad1bSJan Schmidt 		data->bytes_missing = 0;
2699a542ad1bSJan Schmidt 	} else {
2700a542ad1bSJan Schmidt 		data->bytes_missing = sizeof(*data) - total_bytes;
2701a542ad1bSJan Schmidt 		data->bytes_left = 0;
2702a542ad1bSJan Schmidt 	}
2703a542ad1bSJan Schmidt 
2704a542ad1bSJan Schmidt 	data->elem_cnt = 0;
2705a542ad1bSJan Schmidt 	data->elem_missed = 0;
2706a542ad1bSJan Schmidt 
2707a542ad1bSJan Schmidt 	return data;
2708a542ad1bSJan Schmidt }
2709a542ad1bSJan Schmidt 
2710a542ad1bSJan Schmidt /*
2711a542ad1bSJan Schmidt  * allocates space to return multiple file system paths for an inode.
2712a542ad1bSJan Schmidt  * total_bytes to allocate are passed, note that space usable for actual path
2713a542ad1bSJan Schmidt  * information will be total_bytes - sizeof(struct inode_fs_paths).
2714a542ad1bSJan Schmidt  * the returned pointer must be freed with free_ipath() in the end.
2715a542ad1bSJan Schmidt  */
2716a542ad1bSJan Schmidt struct inode_fs_paths *init_ipath(s32 total_bytes, struct btrfs_root *fs_root,
2717a542ad1bSJan Schmidt 					struct btrfs_path *path)
2718a542ad1bSJan Schmidt {
2719a542ad1bSJan Schmidt 	struct inode_fs_paths *ifp;
2720a542ad1bSJan Schmidt 	struct btrfs_data_container *fspath;
2721a542ad1bSJan Schmidt 
2722a542ad1bSJan Schmidt 	fspath = init_data_container(total_bytes);
2723a542ad1bSJan Schmidt 	if (IS_ERR(fspath))
2724afc6961fSMisono Tomohiro 		return ERR_CAST(fspath);
2725a542ad1bSJan Schmidt 
2726f54de068SDavid Sterba 	ifp = kmalloc(sizeof(*ifp), GFP_KERNEL);
2727a542ad1bSJan Schmidt 	if (!ifp) {
2728f54de068SDavid Sterba 		kvfree(fspath);
2729a542ad1bSJan Schmidt 		return ERR_PTR(-ENOMEM);
2730a542ad1bSJan Schmidt 	}
2731a542ad1bSJan Schmidt 
2732a542ad1bSJan Schmidt 	ifp->btrfs_path = path;
2733a542ad1bSJan Schmidt 	ifp->fspath = fspath;
2734a542ad1bSJan Schmidt 	ifp->fs_root = fs_root;
2735a542ad1bSJan Schmidt 
2736a542ad1bSJan Schmidt 	return ifp;
2737a542ad1bSJan Schmidt }
2738a542ad1bSJan Schmidt 
2739a542ad1bSJan Schmidt void free_ipath(struct inode_fs_paths *ipath)
2740a542ad1bSJan Schmidt {
27414735fb28SJesper Juhl 	if (!ipath)
27424735fb28SJesper Juhl 		return;
2743f54de068SDavid Sterba 	kvfree(ipath->fspath);
2744a542ad1bSJan Schmidt 	kfree(ipath);
2745a542ad1bSJan Schmidt }
2746a37f232bSQu Wenruo 
2747d68194b2SDavid Sterba struct btrfs_backref_iter *btrfs_backref_iter_alloc(struct btrfs_fs_info *fs_info)
2748a37f232bSQu Wenruo {
2749a37f232bSQu Wenruo 	struct btrfs_backref_iter *ret;
2750a37f232bSQu Wenruo 
2751d68194b2SDavid Sterba 	ret = kzalloc(sizeof(*ret), GFP_NOFS);
2752a37f232bSQu Wenruo 	if (!ret)
2753a37f232bSQu Wenruo 		return NULL;
2754a37f232bSQu Wenruo 
2755a37f232bSQu Wenruo 	ret->path = btrfs_alloc_path();
2756c15c2ec0SBoleyn Su 	if (!ret->path) {
2757a37f232bSQu Wenruo 		kfree(ret);
2758a37f232bSQu Wenruo 		return NULL;
2759a37f232bSQu Wenruo 	}
2760a37f232bSQu Wenruo 
2761a37f232bSQu Wenruo 	/* Current backref iterator only supports iteration in commit root */
2762a37f232bSQu Wenruo 	ret->path->search_commit_root = 1;
2763a37f232bSQu Wenruo 	ret->path->skip_locking = 1;
2764a37f232bSQu Wenruo 	ret->fs_info = fs_info;
2765a37f232bSQu Wenruo 
2766a37f232bSQu Wenruo 	return ret;
2767a37f232bSQu Wenruo }
2768a37f232bSQu Wenruo 
2769a37f232bSQu Wenruo int btrfs_backref_iter_start(struct btrfs_backref_iter *iter, u64 bytenr)
2770a37f232bSQu Wenruo {
2771a37f232bSQu Wenruo 	struct btrfs_fs_info *fs_info = iter->fs_info;
277229cbcf40SJosef Bacik 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2773a37f232bSQu Wenruo 	struct btrfs_path *path = iter->path;
2774a37f232bSQu Wenruo 	struct btrfs_extent_item *ei;
2775a37f232bSQu Wenruo 	struct btrfs_key key;
2776a37f232bSQu Wenruo 	int ret;
2777a37f232bSQu Wenruo 
2778a37f232bSQu Wenruo 	key.objectid = bytenr;
2779a37f232bSQu Wenruo 	key.type = BTRFS_METADATA_ITEM_KEY;
2780a37f232bSQu Wenruo 	key.offset = (u64)-1;
2781a37f232bSQu Wenruo 	iter->bytenr = bytenr;
2782a37f232bSQu Wenruo 
278329cbcf40SJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2784a37f232bSQu Wenruo 	if (ret < 0)
2785a37f232bSQu Wenruo 		return ret;
2786a37f232bSQu Wenruo 	if (ret == 0) {
2787a37f232bSQu Wenruo 		ret = -EUCLEAN;
2788a37f232bSQu Wenruo 		goto release;
2789a37f232bSQu Wenruo 	}
2790a37f232bSQu Wenruo 	if (path->slots[0] == 0) {
2791a37f232bSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
2792a37f232bSQu Wenruo 		ret = -EUCLEAN;
2793a37f232bSQu Wenruo 		goto release;
2794a37f232bSQu Wenruo 	}
2795a37f232bSQu Wenruo 	path->slots[0]--;
2796a37f232bSQu Wenruo 
2797a37f232bSQu Wenruo 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2798a37f232bSQu Wenruo 	if ((key.type != BTRFS_EXTENT_ITEM_KEY &&
2799a37f232bSQu Wenruo 	     key.type != BTRFS_METADATA_ITEM_KEY) || key.objectid != bytenr) {
2800a37f232bSQu Wenruo 		ret = -ENOENT;
2801a37f232bSQu Wenruo 		goto release;
2802a37f232bSQu Wenruo 	}
2803a37f232bSQu Wenruo 	memcpy(&iter->cur_key, &key, sizeof(key));
2804a37f232bSQu Wenruo 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2805a37f232bSQu Wenruo 						    path->slots[0]);
2806a37f232bSQu Wenruo 	iter->end_ptr = (u32)(iter->item_ptr +
28073212fa14SJosef Bacik 			btrfs_item_size(path->nodes[0], path->slots[0]));
2808a37f232bSQu Wenruo 	ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
2809a37f232bSQu Wenruo 			    struct btrfs_extent_item);
2810a37f232bSQu Wenruo 
2811a37f232bSQu Wenruo 	/*
2812a37f232bSQu Wenruo 	 * Only support iteration on tree backref yet.
2813a37f232bSQu Wenruo 	 *
2814a37f232bSQu Wenruo 	 * This is an extra precaution for non skinny-metadata, where
2815a37f232bSQu Wenruo 	 * EXTENT_ITEM is also used for tree blocks, that we can only use
2816a37f232bSQu Wenruo 	 * extent flags to determine if it's a tree block.
2817a37f232bSQu Wenruo 	 */
2818a37f232bSQu Wenruo 	if (btrfs_extent_flags(path->nodes[0], ei) & BTRFS_EXTENT_FLAG_DATA) {
2819a37f232bSQu Wenruo 		ret = -ENOTSUPP;
2820a37f232bSQu Wenruo 		goto release;
2821a37f232bSQu Wenruo 	}
2822a37f232bSQu Wenruo 	iter->cur_ptr = (u32)(iter->item_ptr + sizeof(*ei));
2823a37f232bSQu Wenruo 
2824a37f232bSQu Wenruo 	/* If there is no inline backref, go search for keyed backref */
2825a37f232bSQu Wenruo 	if (iter->cur_ptr >= iter->end_ptr) {
282629cbcf40SJosef Bacik 		ret = btrfs_next_item(extent_root, path);
2827a37f232bSQu Wenruo 
2828a37f232bSQu Wenruo 		/* No inline nor keyed ref */
2829a37f232bSQu Wenruo 		if (ret > 0) {
2830a37f232bSQu Wenruo 			ret = -ENOENT;
2831a37f232bSQu Wenruo 			goto release;
2832a37f232bSQu Wenruo 		}
2833a37f232bSQu Wenruo 		if (ret < 0)
2834a37f232bSQu Wenruo 			goto release;
2835a37f232bSQu Wenruo 
2836a37f232bSQu Wenruo 		btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key,
2837a37f232bSQu Wenruo 				path->slots[0]);
2838a37f232bSQu Wenruo 		if (iter->cur_key.objectid != bytenr ||
2839a37f232bSQu Wenruo 		    (iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
2840a37f232bSQu Wenruo 		     iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY)) {
2841a37f232bSQu Wenruo 			ret = -ENOENT;
2842a37f232bSQu Wenruo 			goto release;
2843a37f232bSQu Wenruo 		}
2844a37f232bSQu Wenruo 		iter->cur_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2845a37f232bSQu Wenruo 							   path->slots[0]);
2846a37f232bSQu Wenruo 		iter->item_ptr = iter->cur_ptr;
28473212fa14SJosef Bacik 		iter->end_ptr = (u32)(iter->item_ptr + btrfs_item_size(
2848a37f232bSQu Wenruo 				      path->nodes[0], path->slots[0]));
2849a37f232bSQu Wenruo 	}
2850a37f232bSQu Wenruo 
2851a37f232bSQu Wenruo 	return 0;
2852a37f232bSQu Wenruo release:
2853a37f232bSQu Wenruo 	btrfs_backref_iter_release(iter);
2854a37f232bSQu Wenruo 	return ret;
2855a37f232bSQu Wenruo }
2856c39c2ddcSQu Wenruo 
2857c39c2ddcSQu Wenruo /*
2858c39c2ddcSQu Wenruo  * Go to the next backref item of current bytenr, can be either inlined or
2859c39c2ddcSQu Wenruo  * keyed.
2860c39c2ddcSQu Wenruo  *
2861c39c2ddcSQu Wenruo  * Caller needs to check whether it's inline ref or not by iter->cur_key.
2862c39c2ddcSQu Wenruo  *
2863c39c2ddcSQu Wenruo  * Return 0 if we get next backref without problem.
2864c39c2ddcSQu Wenruo  * Return >0 if there is no extra backref for this bytenr.
2865c39c2ddcSQu Wenruo  * Return <0 if there is something wrong happened.
2866c39c2ddcSQu Wenruo  */
2867c39c2ddcSQu Wenruo int btrfs_backref_iter_next(struct btrfs_backref_iter *iter)
2868c39c2ddcSQu Wenruo {
2869c39c2ddcSQu Wenruo 	struct extent_buffer *eb = btrfs_backref_get_eb(iter);
287029cbcf40SJosef Bacik 	struct btrfs_root *extent_root;
2871c39c2ddcSQu Wenruo 	struct btrfs_path *path = iter->path;
2872c39c2ddcSQu Wenruo 	struct btrfs_extent_inline_ref *iref;
2873c39c2ddcSQu Wenruo 	int ret;
2874c39c2ddcSQu Wenruo 	u32 size;
2875c39c2ddcSQu Wenruo 
2876c39c2ddcSQu Wenruo 	if (btrfs_backref_iter_is_inline_ref(iter)) {
2877c39c2ddcSQu Wenruo 		/* We're still inside the inline refs */
2878c39c2ddcSQu Wenruo 		ASSERT(iter->cur_ptr < iter->end_ptr);
2879c39c2ddcSQu Wenruo 
2880c39c2ddcSQu Wenruo 		if (btrfs_backref_has_tree_block_info(iter)) {
2881c39c2ddcSQu Wenruo 			/* First tree block info */
2882c39c2ddcSQu Wenruo 			size = sizeof(struct btrfs_tree_block_info);
2883c39c2ddcSQu Wenruo 		} else {
2884c39c2ddcSQu Wenruo 			/* Use inline ref type to determine the size */
2885c39c2ddcSQu Wenruo 			int type;
2886c39c2ddcSQu Wenruo 
2887c39c2ddcSQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
2888c39c2ddcSQu Wenruo 				((unsigned long)iter->cur_ptr);
2889c39c2ddcSQu Wenruo 			type = btrfs_extent_inline_ref_type(eb, iref);
2890c39c2ddcSQu Wenruo 
2891c39c2ddcSQu Wenruo 			size = btrfs_extent_inline_ref_size(type);
2892c39c2ddcSQu Wenruo 		}
2893c39c2ddcSQu Wenruo 		iter->cur_ptr += size;
2894c39c2ddcSQu Wenruo 		if (iter->cur_ptr < iter->end_ptr)
2895c39c2ddcSQu Wenruo 			return 0;
2896c39c2ddcSQu Wenruo 
2897c39c2ddcSQu Wenruo 		/* All inline items iterated, fall through */
2898c39c2ddcSQu Wenruo 	}
2899c39c2ddcSQu Wenruo 
2900c39c2ddcSQu Wenruo 	/* We're at keyed items, there is no inline item, go to the next one */
290129cbcf40SJosef Bacik 	extent_root = btrfs_extent_root(iter->fs_info, iter->bytenr);
290229cbcf40SJosef Bacik 	ret = btrfs_next_item(extent_root, iter->path);
2903c39c2ddcSQu Wenruo 	if (ret)
2904c39c2ddcSQu Wenruo 		return ret;
2905c39c2ddcSQu Wenruo 
2906c39c2ddcSQu Wenruo 	btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key, path->slots[0]);
2907c39c2ddcSQu Wenruo 	if (iter->cur_key.objectid != iter->bytenr ||
2908c39c2ddcSQu Wenruo 	    (iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
2909c39c2ddcSQu Wenruo 	     iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY))
2910c39c2ddcSQu Wenruo 		return 1;
2911c39c2ddcSQu Wenruo 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2912c39c2ddcSQu Wenruo 					path->slots[0]);
2913c39c2ddcSQu Wenruo 	iter->cur_ptr = iter->item_ptr;
29143212fa14SJosef Bacik 	iter->end_ptr = iter->item_ptr + (u32)btrfs_item_size(path->nodes[0],
2915c39c2ddcSQu Wenruo 						path->slots[0]);
2916c39c2ddcSQu Wenruo 	return 0;
2917c39c2ddcSQu Wenruo }
2918584fb121SQu Wenruo 
2919584fb121SQu Wenruo void btrfs_backref_init_cache(struct btrfs_fs_info *fs_info,
2920584fb121SQu Wenruo 			      struct btrfs_backref_cache *cache, int is_reloc)
2921584fb121SQu Wenruo {
2922584fb121SQu Wenruo 	int i;
2923584fb121SQu Wenruo 
2924584fb121SQu Wenruo 	cache->rb_root = RB_ROOT;
2925584fb121SQu Wenruo 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
2926584fb121SQu Wenruo 		INIT_LIST_HEAD(&cache->pending[i]);
2927584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->changed);
2928584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->detached);
2929584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->leaves);
2930584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->pending_edge);
2931584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->useless_node);
2932584fb121SQu Wenruo 	cache->fs_info = fs_info;
2933584fb121SQu Wenruo 	cache->is_reloc = is_reloc;
2934584fb121SQu Wenruo }
2935b1818dabSQu Wenruo 
2936b1818dabSQu Wenruo struct btrfs_backref_node *btrfs_backref_alloc_node(
2937b1818dabSQu Wenruo 		struct btrfs_backref_cache *cache, u64 bytenr, int level)
2938b1818dabSQu Wenruo {
2939b1818dabSQu Wenruo 	struct btrfs_backref_node *node;
2940b1818dabSQu Wenruo 
2941b1818dabSQu Wenruo 	ASSERT(level >= 0 && level < BTRFS_MAX_LEVEL);
2942b1818dabSQu Wenruo 	node = kzalloc(sizeof(*node), GFP_NOFS);
2943b1818dabSQu Wenruo 	if (!node)
2944b1818dabSQu Wenruo 		return node;
2945b1818dabSQu Wenruo 
2946b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->list);
2947b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->upper);
2948b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->lower);
2949b1818dabSQu Wenruo 	RB_CLEAR_NODE(&node->rb_node);
2950b1818dabSQu Wenruo 	cache->nr_nodes++;
2951b1818dabSQu Wenruo 	node->level = level;
2952b1818dabSQu Wenruo 	node->bytenr = bytenr;
2953b1818dabSQu Wenruo 
2954b1818dabSQu Wenruo 	return node;
2955b1818dabSQu Wenruo }
295647254d07SQu Wenruo 
295747254d07SQu Wenruo struct btrfs_backref_edge *btrfs_backref_alloc_edge(
295847254d07SQu Wenruo 		struct btrfs_backref_cache *cache)
295947254d07SQu Wenruo {
296047254d07SQu Wenruo 	struct btrfs_backref_edge *edge;
296147254d07SQu Wenruo 
296247254d07SQu Wenruo 	edge = kzalloc(sizeof(*edge), GFP_NOFS);
296347254d07SQu Wenruo 	if (edge)
296447254d07SQu Wenruo 		cache->nr_edges++;
296547254d07SQu Wenruo 	return edge;
296647254d07SQu Wenruo }
2967023acb07SQu Wenruo 
2968023acb07SQu Wenruo /*
2969023acb07SQu Wenruo  * Drop the backref node from cache, also cleaning up all its
2970023acb07SQu Wenruo  * upper edges and any uncached nodes in the path.
2971023acb07SQu Wenruo  *
2972023acb07SQu Wenruo  * This cleanup happens bottom up, thus the node should either
2973023acb07SQu Wenruo  * be the lowest node in the cache or a detached node.
2974023acb07SQu Wenruo  */
2975023acb07SQu Wenruo void btrfs_backref_cleanup_node(struct btrfs_backref_cache *cache,
2976023acb07SQu Wenruo 				struct btrfs_backref_node *node)
2977023acb07SQu Wenruo {
2978023acb07SQu Wenruo 	struct btrfs_backref_node *upper;
2979023acb07SQu Wenruo 	struct btrfs_backref_edge *edge;
2980023acb07SQu Wenruo 
2981023acb07SQu Wenruo 	if (!node)
2982023acb07SQu Wenruo 		return;
2983023acb07SQu Wenruo 
2984023acb07SQu Wenruo 	BUG_ON(!node->lowest && !node->detached);
2985023acb07SQu Wenruo 	while (!list_empty(&node->upper)) {
2986023acb07SQu Wenruo 		edge = list_entry(node->upper.next, struct btrfs_backref_edge,
2987023acb07SQu Wenruo 				  list[LOWER]);
2988023acb07SQu Wenruo 		upper = edge->node[UPPER];
2989023acb07SQu Wenruo 		list_del(&edge->list[LOWER]);
2990023acb07SQu Wenruo 		list_del(&edge->list[UPPER]);
2991023acb07SQu Wenruo 		btrfs_backref_free_edge(cache, edge);
2992023acb07SQu Wenruo 
2993023acb07SQu Wenruo 		/*
2994023acb07SQu Wenruo 		 * Add the node to leaf node list if no other child block
2995023acb07SQu Wenruo 		 * cached.
2996023acb07SQu Wenruo 		 */
2997023acb07SQu Wenruo 		if (list_empty(&upper->lower)) {
2998023acb07SQu Wenruo 			list_add_tail(&upper->lower, &cache->leaves);
2999023acb07SQu Wenruo 			upper->lowest = 1;
3000023acb07SQu Wenruo 		}
3001023acb07SQu Wenruo 	}
3002023acb07SQu Wenruo 
3003023acb07SQu Wenruo 	btrfs_backref_drop_node(cache, node);
3004023acb07SQu Wenruo }
300513fe1bdbSQu Wenruo 
300613fe1bdbSQu Wenruo /*
300713fe1bdbSQu Wenruo  * Release all nodes/edges from current cache
300813fe1bdbSQu Wenruo  */
300913fe1bdbSQu Wenruo void btrfs_backref_release_cache(struct btrfs_backref_cache *cache)
301013fe1bdbSQu Wenruo {
301113fe1bdbSQu Wenruo 	struct btrfs_backref_node *node;
301213fe1bdbSQu Wenruo 	int i;
301313fe1bdbSQu Wenruo 
301413fe1bdbSQu Wenruo 	while (!list_empty(&cache->detached)) {
301513fe1bdbSQu Wenruo 		node = list_entry(cache->detached.next,
301613fe1bdbSQu Wenruo 				  struct btrfs_backref_node, list);
301713fe1bdbSQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
301813fe1bdbSQu Wenruo 	}
301913fe1bdbSQu Wenruo 
302013fe1bdbSQu Wenruo 	while (!list_empty(&cache->leaves)) {
302113fe1bdbSQu Wenruo 		node = list_entry(cache->leaves.next,
302213fe1bdbSQu Wenruo 				  struct btrfs_backref_node, lower);
302313fe1bdbSQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
302413fe1bdbSQu Wenruo 	}
302513fe1bdbSQu Wenruo 
302613fe1bdbSQu Wenruo 	cache->last_trans = 0;
302713fe1bdbSQu Wenruo 
302813fe1bdbSQu Wenruo 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
302913fe1bdbSQu Wenruo 		ASSERT(list_empty(&cache->pending[i]));
303013fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->pending_edge));
303113fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->useless_node));
303213fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->changed));
303313fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->detached));
303413fe1bdbSQu Wenruo 	ASSERT(RB_EMPTY_ROOT(&cache->rb_root));
303513fe1bdbSQu Wenruo 	ASSERT(!cache->nr_nodes);
303613fe1bdbSQu Wenruo 	ASSERT(!cache->nr_edges);
303713fe1bdbSQu Wenruo }
30381b60d2ecSQu Wenruo 
30391b60d2ecSQu Wenruo /*
30401b60d2ecSQu Wenruo  * Handle direct tree backref
30411b60d2ecSQu Wenruo  *
30421b60d2ecSQu Wenruo  * Direct tree backref means, the backref item shows its parent bytenr
30431b60d2ecSQu Wenruo  * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
30441b60d2ecSQu Wenruo  *
30451b60d2ecSQu Wenruo  * @ref_key:	The converted backref key.
30461b60d2ecSQu Wenruo  *		For keyed backref, it's the item key.
30471b60d2ecSQu Wenruo  *		For inlined backref, objectid is the bytenr,
30481b60d2ecSQu Wenruo  *		type is btrfs_inline_ref_type, offset is
30491b60d2ecSQu Wenruo  *		btrfs_inline_ref_offset.
30501b60d2ecSQu Wenruo  */
30511b60d2ecSQu Wenruo static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
30521b60d2ecSQu Wenruo 				      struct btrfs_key *ref_key,
30531b60d2ecSQu Wenruo 				      struct btrfs_backref_node *cur)
30541b60d2ecSQu Wenruo {
30551b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
30561b60d2ecSQu Wenruo 	struct btrfs_backref_node *upper;
30571b60d2ecSQu Wenruo 	struct rb_node *rb_node;
30581b60d2ecSQu Wenruo 
30591b60d2ecSQu Wenruo 	ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
30601b60d2ecSQu Wenruo 
30611b60d2ecSQu Wenruo 	/* Only reloc root uses backref pointing to itself */
30621b60d2ecSQu Wenruo 	if (ref_key->objectid == ref_key->offset) {
30631b60d2ecSQu Wenruo 		struct btrfs_root *root;
30641b60d2ecSQu Wenruo 
30651b60d2ecSQu Wenruo 		cur->is_reloc_root = 1;
30661b60d2ecSQu Wenruo 		/* Only reloc backref cache cares about a specific root */
30671b60d2ecSQu Wenruo 		if (cache->is_reloc) {
30681b60d2ecSQu Wenruo 			root = find_reloc_root(cache->fs_info, cur->bytenr);
3069f78743fbSJosef Bacik 			if (!root)
30701b60d2ecSQu Wenruo 				return -ENOENT;
30711b60d2ecSQu Wenruo 			cur->root = root;
30721b60d2ecSQu Wenruo 		} else {
30731b60d2ecSQu Wenruo 			/*
30741b60d2ecSQu Wenruo 			 * For generic purpose backref cache, reloc root node
30751b60d2ecSQu Wenruo 			 * is useless.
30761b60d2ecSQu Wenruo 			 */
30771b60d2ecSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
30781b60d2ecSQu Wenruo 		}
30791b60d2ecSQu Wenruo 		return 0;
30801b60d2ecSQu Wenruo 	}
30811b60d2ecSQu Wenruo 
30821b60d2ecSQu Wenruo 	edge = btrfs_backref_alloc_edge(cache);
30831b60d2ecSQu Wenruo 	if (!edge)
30841b60d2ecSQu Wenruo 		return -ENOMEM;
30851b60d2ecSQu Wenruo 
30861b60d2ecSQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
30871b60d2ecSQu Wenruo 	if (!rb_node) {
30881b60d2ecSQu Wenruo 		/* Parent node not yet cached */
30891b60d2ecSQu Wenruo 		upper = btrfs_backref_alloc_node(cache, ref_key->offset,
30901b60d2ecSQu Wenruo 					   cur->level + 1);
30911b60d2ecSQu Wenruo 		if (!upper) {
30921b60d2ecSQu Wenruo 			btrfs_backref_free_edge(cache, edge);
30931b60d2ecSQu Wenruo 			return -ENOMEM;
30941b60d2ecSQu Wenruo 		}
30951b60d2ecSQu Wenruo 
30961b60d2ecSQu Wenruo 		/*
30971b60d2ecSQu Wenruo 		 *  Backrefs for the upper level block isn't cached, add the
30981b60d2ecSQu Wenruo 		 *  block to pending list
30991b60d2ecSQu Wenruo 		 */
31001b60d2ecSQu Wenruo 		list_add_tail(&edge->list[UPPER], &cache->pending_edge);
31011b60d2ecSQu Wenruo 	} else {
31021b60d2ecSQu Wenruo 		/* Parent node already cached */
31031b60d2ecSQu Wenruo 		upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
31041b60d2ecSQu Wenruo 		ASSERT(upper->checked);
31051b60d2ecSQu Wenruo 		INIT_LIST_HEAD(&edge->list[UPPER]);
31061b60d2ecSQu Wenruo 	}
31071b60d2ecSQu Wenruo 	btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
31081b60d2ecSQu Wenruo 	return 0;
31091b60d2ecSQu Wenruo }
31101b60d2ecSQu Wenruo 
31111b60d2ecSQu Wenruo /*
31121b60d2ecSQu Wenruo  * Handle indirect tree backref
31131b60d2ecSQu Wenruo  *
31141b60d2ecSQu Wenruo  * Indirect tree backref means, we only know which tree the node belongs to.
31151b60d2ecSQu Wenruo  * We still need to do a tree search to find out the parents. This is for
31161b60d2ecSQu Wenruo  * TREE_BLOCK_REF backref (keyed or inlined).
31171b60d2ecSQu Wenruo  *
31181b60d2ecSQu Wenruo  * @ref_key:	The same as @ref_key in  handle_direct_tree_backref()
31191b60d2ecSQu Wenruo  * @tree_key:	The first key of this tree block.
31201b60d2ecSQu Wenruo  * @path:	A clean (released) path, to avoid allocating path every time
31211b60d2ecSQu Wenruo  *		the function get called.
31221b60d2ecSQu Wenruo  */
31231b60d2ecSQu Wenruo static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
31241b60d2ecSQu Wenruo 					struct btrfs_path *path,
31251b60d2ecSQu Wenruo 					struct btrfs_key *ref_key,
31261b60d2ecSQu Wenruo 					struct btrfs_key *tree_key,
31271b60d2ecSQu Wenruo 					struct btrfs_backref_node *cur)
31281b60d2ecSQu Wenruo {
31291b60d2ecSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
31301b60d2ecSQu Wenruo 	struct btrfs_backref_node *upper;
31311b60d2ecSQu Wenruo 	struct btrfs_backref_node *lower;
31321b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
31331b60d2ecSQu Wenruo 	struct extent_buffer *eb;
31341b60d2ecSQu Wenruo 	struct btrfs_root *root;
31351b60d2ecSQu Wenruo 	struct rb_node *rb_node;
31361b60d2ecSQu Wenruo 	int level;
31371b60d2ecSQu Wenruo 	bool need_check = true;
31381b60d2ecSQu Wenruo 	int ret;
31391b60d2ecSQu Wenruo 
314056e9357aSDavid Sterba 	root = btrfs_get_fs_root(fs_info, ref_key->offset, false);
31411b60d2ecSQu Wenruo 	if (IS_ERR(root))
31421b60d2ecSQu Wenruo 		return PTR_ERR(root);
314392a7cc42SQu Wenruo 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
31441b60d2ecSQu Wenruo 		cur->cowonly = 1;
31451b60d2ecSQu Wenruo 
31461b60d2ecSQu Wenruo 	if (btrfs_root_level(&root->root_item) == cur->level) {
31471b60d2ecSQu Wenruo 		/* Tree root */
31481b60d2ecSQu Wenruo 		ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
3149876de781SQu Wenruo 		/*
3150876de781SQu Wenruo 		 * For reloc backref cache, we may ignore reloc root.  But for
3151876de781SQu Wenruo 		 * general purpose backref cache, we can't rely on
3152876de781SQu Wenruo 		 * btrfs_should_ignore_reloc_root() as it may conflict with
3153876de781SQu Wenruo 		 * current running relocation and lead to missing root.
3154876de781SQu Wenruo 		 *
3155876de781SQu Wenruo 		 * For general purpose backref cache, reloc root detection is
3156876de781SQu Wenruo 		 * completely relying on direct backref (key->offset is parent
3157876de781SQu Wenruo 		 * bytenr), thus only do such check for reloc cache.
3158876de781SQu Wenruo 		 */
3159876de781SQu Wenruo 		if (btrfs_should_ignore_reloc_root(root) && cache->is_reloc) {
31601b60d2ecSQu Wenruo 			btrfs_put_root(root);
31611b60d2ecSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
31621b60d2ecSQu Wenruo 		} else {
31631b60d2ecSQu Wenruo 			cur->root = root;
31641b60d2ecSQu Wenruo 		}
31651b60d2ecSQu Wenruo 		return 0;
31661b60d2ecSQu Wenruo 	}
31671b60d2ecSQu Wenruo 
31681b60d2ecSQu Wenruo 	level = cur->level + 1;
31691b60d2ecSQu Wenruo 
31701b60d2ecSQu Wenruo 	/* Search the tree to find parent blocks referring to the block */
31711b60d2ecSQu Wenruo 	path->search_commit_root = 1;
31721b60d2ecSQu Wenruo 	path->skip_locking = 1;
31731b60d2ecSQu Wenruo 	path->lowest_level = level;
31741b60d2ecSQu Wenruo 	ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
31751b60d2ecSQu Wenruo 	path->lowest_level = 0;
31761b60d2ecSQu Wenruo 	if (ret < 0) {
31771b60d2ecSQu Wenruo 		btrfs_put_root(root);
31781b60d2ecSQu Wenruo 		return ret;
31791b60d2ecSQu Wenruo 	}
31801b60d2ecSQu Wenruo 	if (ret > 0 && path->slots[level] > 0)
31811b60d2ecSQu Wenruo 		path->slots[level]--;
31821b60d2ecSQu Wenruo 
31831b60d2ecSQu Wenruo 	eb = path->nodes[level];
31841b60d2ecSQu Wenruo 	if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
31851b60d2ecSQu Wenruo 		btrfs_err(fs_info,
31861b60d2ecSQu Wenruo "couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
31871b60d2ecSQu Wenruo 			  cur->bytenr, level - 1, root->root_key.objectid,
31881b60d2ecSQu Wenruo 			  tree_key->objectid, tree_key->type, tree_key->offset);
31891b60d2ecSQu Wenruo 		btrfs_put_root(root);
31901b60d2ecSQu Wenruo 		ret = -ENOENT;
31911b60d2ecSQu Wenruo 		goto out;
31921b60d2ecSQu Wenruo 	}
31931b60d2ecSQu Wenruo 	lower = cur;
31941b60d2ecSQu Wenruo 
31951b60d2ecSQu Wenruo 	/* Add all nodes and edges in the path */
31961b60d2ecSQu Wenruo 	for (; level < BTRFS_MAX_LEVEL; level++) {
31971b60d2ecSQu Wenruo 		if (!path->nodes[level]) {
31981b60d2ecSQu Wenruo 			ASSERT(btrfs_root_bytenr(&root->root_item) ==
31991b60d2ecSQu Wenruo 			       lower->bytenr);
3200876de781SQu Wenruo 			/* Same as previous should_ignore_reloc_root() call */
3201876de781SQu Wenruo 			if (btrfs_should_ignore_reloc_root(root) &&
3202876de781SQu Wenruo 			    cache->is_reloc) {
32031b60d2ecSQu Wenruo 				btrfs_put_root(root);
32041b60d2ecSQu Wenruo 				list_add(&lower->list, &cache->useless_node);
32051b60d2ecSQu Wenruo 			} else {
32061b60d2ecSQu Wenruo 				lower->root = root;
32071b60d2ecSQu Wenruo 			}
32081b60d2ecSQu Wenruo 			break;
32091b60d2ecSQu Wenruo 		}
32101b60d2ecSQu Wenruo 
32111b60d2ecSQu Wenruo 		edge = btrfs_backref_alloc_edge(cache);
32121b60d2ecSQu Wenruo 		if (!edge) {
32131b60d2ecSQu Wenruo 			btrfs_put_root(root);
32141b60d2ecSQu Wenruo 			ret = -ENOMEM;
32151b60d2ecSQu Wenruo 			goto out;
32161b60d2ecSQu Wenruo 		}
32171b60d2ecSQu Wenruo 
32181b60d2ecSQu Wenruo 		eb = path->nodes[level];
32191b60d2ecSQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root, eb->start);
32201b60d2ecSQu Wenruo 		if (!rb_node) {
32211b60d2ecSQu Wenruo 			upper = btrfs_backref_alloc_node(cache, eb->start,
32221b60d2ecSQu Wenruo 							 lower->level + 1);
32231b60d2ecSQu Wenruo 			if (!upper) {
32241b60d2ecSQu Wenruo 				btrfs_put_root(root);
32251b60d2ecSQu Wenruo 				btrfs_backref_free_edge(cache, edge);
32261b60d2ecSQu Wenruo 				ret = -ENOMEM;
32271b60d2ecSQu Wenruo 				goto out;
32281b60d2ecSQu Wenruo 			}
32291b60d2ecSQu Wenruo 			upper->owner = btrfs_header_owner(eb);
323092a7cc42SQu Wenruo 			if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
32311b60d2ecSQu Wenruo 				upper->cowonly = 1;
32321b60d2ecSQu Wenruo 
32331b60d2ecSQu Wenruo 			/*
32341b60d2ecSQu Wenruo 			 * If we know the block isn't shared we can avoid
32351b60d2ecSQu Wenruo 			 * checking its backrefs.
32361b60d2ecSQu Wenruo 			 */
32371b60d2ecSQu Wenruo 			if (btrfs_block_can_be_shared(root, eb))
32381b60d2ecSQu Wenruo 				upper->checked = 0;
32391b60d2ecSQu Wenruo 			else
32401b60d2ecSQu Wenruo 				upper->checked = 1;
32411b60d2ecSQu Wenruo 
32421b60d2ecSQu Wenruo 			/*
32431b60d2ecSQu Wenruo 			 * Add the block to pending list if we need to check its
32441b60d2ecSQu Wenruo 			 * backrefs, we only do this once while walking up a
32451b60d2ecSQu Wenruo 			 * tree as we will catch anything else later on.
32461b60d2ecSQu Wenruo 			 */
32471b60d2ecSQu Wenruo 			if (!upper->checked && need_check) {
32481b60d2ecSQu Wenruo 				need_check = false;
32491b60d2ecSQu Wenruo 				list_add_tail(&edge->list[UPPER],
32501b60d2ecSQu Wenruo 					      &cache->pending_edge);
32511b60d2ecSQu Wenruo 			} else {
32521b60d2ecSQu Wenruo 				if (upper->checked)
32531b60d2ecSQu Wenruo 					need_check = true;
32541b60d2ecSQu Wenruo 				INIT_LIST_HEAD(&edge->list[UPPER]);
32551b60d2ecSQu Wenruo 			}
32561b60d2ecSQu Wenruo 		} else {
32571b60d2ecSQu Wenruo 			upper = rb_entry(rb_node, struct btrfs_backref_node,
32581b60d2ecSQu Wenruo 					 rb_node);
32591b60d2ecSQu Wenruo 			ASSERT(upper->checked);
32601b60d2ecSQu Wenruo 			INIT_LIST_HEAD(&edge->list[UPPER]);
32611b60d2ecSQu Wenruo 			if (!upper->owner)
32621b60d2ecSQu Wenruo 				upper->owner = btrfs_header_owner(eb);
32631b60d2ecSQu Wenruo 		}
32641b60d2ecSQu Wenruo 		btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
32651b60d2ecSQu Wenruo 
32661b60d2ecSQu Wenruo 		if (rb_node) {
32671b60d2ecSQu Wenruo 			btrfs_put_root(root);
32681b60d2ecSQu Wenruo 			break;
32691b60d2ecSQu Wenruo 		}
32701b60d2ecSQu Wenruo 		lower = upper;
32711b60d2ecSQu Wenruo 		upper = NULL;
32721b60d2ecSQu Wenruo 	}
32731b60d2ecSQu Wenruo out:
32741b60d2ecSQu Wenruo 	btrfs_release_path(path);
32751b60d2ecSQu Wenruo 	return ret;
32761b60d2ecSQu Wenruo }
32771b60d2ecSQu Wenruo 
32781b60d2ecSQu Wenruo /*
32791b60d2ecSQu Wenruo  * Add backref node @cur into @cache.
32801b60d2ecSQu Wenruo  *
32811b60d2ecSQu Wenruo  * NOTE: Even if the function returned 0, @cur is not yet cached as its upper
32821b60d2ecSQu Wenruo  *	 links aren't yet bi-directional. Needs to finish such links.
3283fc997ed0SQu Wenruo  *	 Use btrfs_backref_finish_upper_links() to finish such linkage.
32841b60d2ecSQu Wenruo  *
32851b60d2ecSQu Wenruo  * @path:	Released path for indirect tree backref lookup
32861b60d2ecSQu Wenruo  * @iter:	Released backref iter for extent tree search
32871b60d2ecSQu Wenruo  * @node_key:	The first key of the tree block
32881b60d2ecSQu Wenruo  */
32891b60d2ecSQu Wenruo int btrfs_backref_add_tree_node(struct btrfs_backref_cache *cache,
32901b60d2ecSQu Wenruo 				struct btrfs_path *path,
32911b60d2ecSQu Wenruo 				struct btrfs_backref_iter *iter,
32921b60d2ecSQu Wenruo 				struct btrfs_key *node_key,
32931b60d2ecSQu Wenruo 				struct btrfs_backref_node *cur)
32941b60d2ecSQu Wenruo {
32951b60d2ecSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
32961b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
32971b60d2ecSQu Wenruo 	struct btrfs_backref_node *exist;
32981b60d2ecSQu Wenruo 	int ret;
32991b60d2ecSQu Wenruo 
33001b60d2ecSQu Wenruo 	ret = btrfs_backref_iter_start(iter, cur->bytenr);
33011b60d2ecSQu Wenruo 	if (ret < 0)
33021b60d2ecSQu Wenruo 		return ret;
33031b60d2ecSQu Wenruo 	/*
33041b60d2ecSQu Wenruo 	 * We skip the first btrfs_tree_block_info, as we don't use the key
33051b60d2ecSQu Wenruo 	 * stored in it, but fetch it from the tree block
33061b60d2ecSQu Wenruo 	 */
33071b60d2ecSQu Wenruo 	if (btrfs_backref_has_tree_block_info(iter)) {
33081b60d2ecSQu Wenruo 		ret = btrfs_backref_iter_next(iter);
33091b60d2ecSQu Wenruo 		if (ret < 0)
33101b60d2ecSQu Wenruo 			goto out;
33111b60d2ecSQu Wenruo 		/* No extra backref? This means the tree block is corrupted */
33121b60d2ecSQu Wenruo 		if (ret > 0) {
33131b60d2ecSQu Wenruo 			ret = -EUCLEAN;
33141b60d2ecSQu Wenruo 			goto out;
33151b60d2ecSQu Wenruo 		}
33161b60d2ecSQu Wenruo 	}
33171b60d2ecSQu Wenruo 	WARN_ON(cur->checked);
33181b60d2ecSQu Wenruo 	if (!list_empty(&cur->upper)) {
33191b60d2ecSQu Wenruo 		/*
33201b60d2ecSQu Wenruo 		 * The backref was added previously when processing backref of
33211b60d2ecSQu Wenruo 		 * type BTRFS_TREE_BLOCK_REF_KEY
33221b60d2ecSQu Wenruo 		 */
33231b60d2ecSQu Wenruo 		ASSERT(list_is_singular(&cur->upper));
33241b60d2ecSQu Wenruo 		edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
33251b60d2ecSQu Wenruo 				  list[LOWER]);
33261b60d2ecSQu Wenruo 		ASSERT(list_empty(&edge->list[UPPER]));
33271b60d2ecSQu Wenruo 		exist = edge->node[UPPER];
33281b60d2ecSQu Wenruo 		/*
33291b60d2ecSQu Wenruo 		 * Add the upper level block to pending list if we need check
33301b60d2ecSQu Wenruo 		 * its backrefs
33311b60d2ecSQu Wenruo 		 */
33321b60d2ecSQu Wenruo 		if (!exist->checked)
33331b60d2ecSQu Wenruo 			list_add_tail(&edge->list[UPPER], &cache->pending_edge);
33341b60d2ecSQu Wenruo 	} else {
33351b60d2ecSQu Wenruo 		exist = NULL;
33361b60d2ecSQu Wenruo 	}
33371b60d2ecSQu Wenruo 
33381b60d2ecSQu Wenruo 	for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
33391b60d2ecSQu Wenruo 		struct extent_buffer *eb;
33401b60d2ecSQu Wenruo 		struct btrfs_key key;
33411b60d2ecSQu Wenruo 		int type;
33421b60d2ecSQu Wenruo 
33431b60d2ecSQu Wenruo 		cond_resched();
33441b60d2ecSQu Wenruo 		eb = btrfs_backref_get_eb(iter);
33451b60d2ecSQu Wenruo 
33461b60d2ecSQu Wenruo 		key.objectid = iter->bytenr;
33471b60d2ecSQu Wenruo 		if (btrfs_backref_iter_is_inline_ref(iter)) {
33481b60d2ecSQu Wenruo 			struct btrfs_extent_inline_ref *iref;
33491b60d2ecSQu Wenruo 
33501b60d2ecSQu Wenruo 			/* Update key for inline backref */
33511b60d2ecSQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
33521b60d2ecSQu Wenruo 				((unsigned long)iter->cur_ptr);
33531b60d2ecSQu Wenruo 			type = btrfs_get_extent_inline_ref_type(eb, iref,
33541b60d2ecSQu Wenruo 							BTRFS_REF_TYPE_BLOCK);
33551b60d2ecSQu Wenruo 			if (type == BTRFS_REF_TYPE_INVALID) {
33561b60d2ecSQu Wenruo 				ret = -EUCLEAN;
33571b60d2ecSQu Wenruo 				goto out;
33581b60d2ecSQu Wenruo 			}
33591b60d2ecSQu Wenruo 			key.type = type;
33601b60d2ecSQu Wenruo 			key.offset = btrfs_extent_inline_ref_offset(eb, iref);
33611b60d2ecSQu Wenruo 		} else {
33621b60d2ecSQu Wenruo 			key.type = iter->cur_key.type;
33631b60d2ecSQu Wenruo 			key.offset = iter->cur_key.offset;
33641b60d2ecSQu Wenruo 		}
33651b60d2ecSQu Wenruo 
33661b60d2ecSQu Wenruo 		/*
33671b60d2ecSQu Wenruo 		 * Parent node found and matches current inline ref, no need to
33681b60d2ecSQu Wenruo 		 * rebuild this node for this inline ref
33691b60d2ecSQu Wenruo 		 */
33701b60d2ecSQu Wenruo 		if (exist &&
33711b60d2ecSQu Wenruo 		    ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
33721b60d2ecSQu Wenruo 		      exist->owner == key.offset) ||
33731b60d2ecSQu Wenruo 		     (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
33741b60d2ecSQu Wenruo 		      exist->bytenr == key.offset))) {
33751b60d2ecSQu Wenruo 			exist = NULL;
33761b60d2ecSQu Wenruo 			continue;
33771b60d2ecSQu Wenruo 		}
33781b60d2ecSQu Wenruo 
33791b60d2ecSQu Wenruo 		/* SHARED_BLOCK_REF means key.offset is the parent bytenr */
33801b60d2ecSQu Wenruo 		if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
33811b60d2ecSQu Wenruo 			ret = handle_direct_tree_backref(cache, &key, cur);
33821b60d2ecSQu Wenruo 			if (ret < 0)
33831b60d2ecSQu Wenruo 				goto out;
33841b60d2ecSQu Wenruo 			continue;
33851b60d2ecSQu Wenruo 		} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
33861b60d2ecSQu Wenruo 			ret = -EINVAL;
33871b60d2ecSQu Wenruo 			btrfs_print_v0_err(fs_info);
33881b60d2ecSQu Wenruo 			btrfs_handle_fs_error(fs_info, ret, NULL);
33891b60d2ecSQu Wenruo 			goto out;
33901b60d2ecSQu Wenruo 		} else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
33911b60d2ecSQu Wenruo 			continue;
33921b60d2ecSQu Wenruo 		}
33931b60d2ecSQu Wenruo 
33941b60d2ecSQu Wenruo 		/*
33951b60d2ecSQu Wenruo 		 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
33961b60d2ecSQu Wenruo 		 * means the root objectid. We need to search the tree to get
33971b60d2ecSQu Wenruo 		 * its parent bytenr.
33981b60d2ecSQu Wenruo 		 */
33991b60d2ecSQu Wenruo 		ret = handle_indirect_tree_backref(cache, path, &key, node_key,
34001b60d2ecSQu Wenruo 						   cur);
34011b60d2ecSQu Wenruo 		if (ret < 0)
34021b60d2ecSQu Wenruo 			goto out;
34031b60d2ecSQu Wenruo 	}
34041b60d2ecSQu Wenruo 	ret = 0;
34051b60d2ecSQu Wenruo 	cur->checked = 1;
34061b60d2ecSQu Wenruo 	WARN_ON(exist);
34071b60d2ecSQu Wenruo out:
34081b60d2ecSQu Wenruo 	btrfs_backref_iter_release(iter);
34091b60d2ecSQu Wenruo 	return ret;
34101b60d2ecSQu Wenruo }
3411fc997ed0SQu Wenruo 
3412fc997ed0SQu Wenruo /*
3413fc997ed0SQu Wenruo  * Finish the upwards linkage created by btrfs_backref_add_tree_node()
3414fc997ed0SQu Wenruo  */
3415fc997ed0SQu Wenruo int btrfs_backref_finish_upper_links(struct btrfs_backref_cache *cache,
3416fc997ed0SQu Wenruo 				     struct btrfs_backref_node *start)
3417fc997ed0SQu Wenruo {
3418fc997ed0SQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
3419fc997ed0SQu Wenruo 	struct btrfs_backref_edge *edge;
3420fc997ed0SQu Wenruo 	struct rb_node *rb_node;
3421fc997ed0SQu Wenruo 	LIST_HEAD(pending_edge);
3422fc997ed0SQu Wenruo 
3423fc997ed0SQu Wenruo 	ASSERT(start->checked);
3424fc997ed0SQu Wenruo 
3425fc997ed0SQu Wenruo 	/* Insert this node to cache if it's not COW-only */
3426fc997ed0SQu Wenruo 	if (!start->cowonly) {
3427fc997ed0SQu Wenruo 		rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
3428fc997ed0SQu Wenruo 					   &start->rb_node);
3429fc997ed0SQu Wenruo 		if (rb_node)
3430fc997ed0SQu Wenruo 			btrfs_backref_panic(cache->fs_info, start->bytenr,
3431fc997ed0SQu Wenruo 					    -EEXIST);
3432fc997ed0SQu Wenruo 		list_add_tail(&start->lower, &cache->leaves);
3433fc997ed0SQu Wenruo 	}
3434fc997ed0SQu Wenruo 
3435fc997ed0SQu Wenruo 	/*
3436fc997ed0SQu Wenruo 	 * Use breadth first search to iterate all related edges.
3437fc997ed0SQu Wenruo 	 *
3438fc997ed0SQu Wenruo 	 * The starting points are all the edges of this node
3439fc997ed0SQu Wenruo 	 */
3440fc997ed0SQu Wenruo 	list_for_each_entry(edge, &start->upper, list[LOWER])
3441fc997ed0SQu Wenruo 		list_add_tail(&edge->list[UPPER], &pending_edge);
3442fc997ed0SQu Wenruo 
3443fc997ed0SQu Wenruo 	while (!list_empty(&pending_edge)) {
3444fc997ed0SQu Wenruo 		struct btrfs_backref_node *upper;
3445fc997ed0SQu Wenruo 		struct btrfs_backref_node *lower;
3446fc997ed0SQu Wenruo 
3447fc997ed0SQu Wenruo 		edge = list_first_entry(&pending_edge,
3448fc997ed0SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
3449fc997ed0SQu Wenruo 		list_del_init(&edge->list[UPPER]);
3450fc997ed0SQu Wenruo 		upper = edge->node[UPPER];
3451fc997ed0SQu Wenruo 		lower = edge->node[LOWER];
3452fc997ed0SQu Wenruo 
3453fc997ed0SQu Wenruo 		/* Parent is detached, no need to keep any edges */
3454fc997ed0SQu Wenruo 		if (upper->detached) {
3455fc997ed0SQu Wenruo 			list_del(&edge->list[LOWER]);
3456fc997ed0SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
3457fc997ed0SQu Wenruo 
3458fc997ed0SQu Wenruo 			/* Lower node is orphan, queue for cleanup */
3459fc997ed0SQu Wenruo 			if (list_empty(&lower->upper))
3460fc997ed0SQu Wenruo 				list_add(&lower->list, useless_node);
3461fc997ed0SQu Wenruo 			continue;
3462fc997ed0SQu Wenruo 		}
3463fc997ed0SQu Wenruo 
3464fc997ed0SQu Wenruo 		/*
3465fc997ed0SQu Wenruo 		 * All new nodes added in current build_backref_tree() haven't
3466fc997ed0SQu Wenruo 		 * been linked to the cache rb tree.
3467fc997ed0SQu Wenruo 		 * So if we have upper->rb_node populated, this means a cache
3468fc997ed0SQu Wenruo 		 * hit. We only need to link the edge, as @upper and all its
3469fc997ed0SQu Wenruo 		 * parents have already been linked.
3470fc997ed0SQu Wenruo 		 */
3471fc997ed0SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node)) {
3472fc997ed0SQu Wenruo 			if (upper->lowest) {
3473fc997ed0SQu Wenruo 				list_del_init(&upper->lower);
3474fc997ed0SQu Wenruo 				upper->lowest = 0;
3475fc997ed0SQu Wenruo 			}
3476fc997ed0SQu Wenruo 
3477fc997ed0SQu Wenruo 			list_add_tail(&edge->list[UPPER], &upper->lower);
3478fc997ed0SQu Wenruo 			continue;
3479fc997ed0SQu Wenruo 		}
3480fc997ed0SQu Wenruo 
3481fc997ed0SQu Wenruo 		/* Sanity check, we shouldn't have any unchecked nodes */
3482fc997ed0SQu Wenruo 		if (!upper->checked) {
3483fc997ed0SQu Wenruo 			ASSERT(0);
3484fc997ed0SQu Wenruo 			return -EUCLEAN;
3485fc997ed0SQu Wenruo 		}
3486fc997ed0SQu Wenruo 
3487fc997ed0SQu Wenruo 		/* Sanity check, COW-only node has non-COW-only parent */
3488fc997ed0SQu Wenruo 		if (start->cowonly != upper->cowonly) {
3489fc997ed0SQu Wenruo 			ASSERT(0);
3490fc997ed0SQu Wenruo 			return -EUCLEAN;
3491fc997ed0SQu Wenruo 		}
3492fc997ed0SQu Wenruo 
3493fc997ed0SQu Wenruo 		/* Only cache non-COW-only (subvolume trees) tree blocks */
3494fc997ed0SQu Wenruo 		if (!upper->cowonly) {
3495fc997ed0SQu Wenruo 			rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
3496fc997ed0SQu Wenruo 						   &upper->rb_node);
3497fc997ed0SQu Wenruo 			if (rb_node) {
3498fc997ed0SQu Wenruo 				btrfs_backref_panic(cache->fs_info,
3499fc997ed0SQu Wenruo 						upper->bytenr, -EEXIST);
3500fc997ed0SQu Wenruo 				return -EUCLEAN;
3501fc997ed0SQu Wenruo 			}
3502fc997ed0SQu Wenruo 		}
3503fc997ed0SQu Wenruo 
3504fc997ed0SQu Wenruo 		list_add_tail(&edge->list[UPPER], &upper->lower);
3505fc997ed0SQu Wenruo 
3506fc997ed0SQu Wenruo 		/*
3507fc997ed0SQu Wenruo 		 * Also queue all the parent edges of this uncached node
3508fc997ed0SQu Wenruo 		 * to finish the upper linkage
3509fc997ed0SQu Wenruo 		 */
3510fc997ed0SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
3511fc997ed0SQu Wenruo 			list_add_tail(&edge->list[UPPER], &pending_edge);
3512fc997ed0SQu Wenruo 	}
3513fc997ed0SQu Wenruo 	return 0;
3514fc997ed0SQu Wenruo }
35151b23ea18SQu Wenruo 
35161b23ea18SQu Wenruo void btrfs_backref_error_cleanup(struct btrfs_backref_cache *cache,
35171b23ea18SQu Wenruo 				 struct btrfs_backref_node *node)
35181b23ea18SQu Wenruo {
35191b23ea18SQu Wenruo 	struct btrfs_backref_node *lower;
35201b23ea18SQu Wenruo 	struct btrfs_backref_node *upper;
35211b23ea18SQu Wenruo 	struct btrfs_backref_edge *edge;
35221b23ea18SQu Wenruo 
35231b23ea18SQu Wenruo 	while (!list_empty(&cache->useless_node)) {
35241b23ea18SQu Wenruo 		lower = list_first_entry(&cache->useless_node,
35251b23ea18SQu Wenruo 				   struct btrfs_backref_node, list);
35261b23ea18SQu Wenruo 		list_del_init(&lower->list);
35271b23ea18SQu Wenruo 	}
35281b23ea18SQu Wenruo 	while (!list_empty(&cache->pending_edge)) {
35291b23ea18SQu Wenruo 		edge = list_first_entry(&cache->pending_edge,
35301b23ea18SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
35311b23ea18SQu Wenruo 		list_del(&edge->list[UPPER]);
35321b23ea18SQu Wenruo 		list_del(&edge->list[LOWER]);
35331b23ea18SQu Wenruo 		lower = edge->node[LOWER];
35341b23ea18SQu Wenruo 		upper = edge->node[UPPER];
35351b23ea18SQu Wenruo 		btrfs_backref_free_edge(cache, edge);
35361b23ea18SQu Wenruo 
35371b23ea18SQu Wenruo 		/*
35381b23ea18SQu Wenruo 		 * Lower is no longer linked to any upper backref nodes and
35391b23ea18SQu Wenruo 		 * isn't in the cache, we can free it ourselves.
35401b23ea18SQu Wenruo 		 */
35411b23ea18SQu Wenruo 		if (list_empty(&lower->upper) &&
35421b23ea18SQu Wenruo 		    RB_EMPTY_NODE(&lower->rb_node))
35431b23ea18SQu Wenruo 			list_add(&lower->list, &cache->useless_node);
35441b23ea18SQu Wenruo 
35451b23ea18SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node))
35461b23ea18SQu Wenruo 			continue;
35471b23ea18SQu Wenruo 
35481b23ea18SQu Wenruo 		/* Add this guy's upper edges to the list to process */
35491b23ea18SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
35501b23ea18SQu Wenruo 			list_add_tail(&edge->list[UPPER],
35511b23ea18SQu Wenruo 				      &cache->pending_edge);
35521b23ea18SQu Wenruo 		if (list_empty(&upper->upper))
35531b23ea18SQu Wenruo 			list_add(&upper->list, &cache->useless_node);
35541b23ea18SQu Wenruo 	}
35551b23ea18SQu Wenruo 
35561b23ea18SQu Wenruo 	while (!list_empty(&cache->useless_node)) {
35571b23ea18SQu Wenruo 		lower = list_first_entry(&cache->useless_node,
35581b23ea18SQu Wenruo 				   struct btrfs_backref_node, list);
35591b23ea18SQu Wenruo 		list_del_init(&lower->list);
35601b23ea18SQu Wenruo 		if (lower == node)
35611b23ea18SQu Wenruo 			node = NULL;
356249ecc679SJosef Bacik 		btrfs_backref_drop_node(cache, lower);
35631b23ea18SQu Wenruo 	}
35641b23ea18SQu Wenruo 
35651b23ea18SQu Wenruo 	btrfs_backref_cleanup_node(cache, node);
35661b23ea18SQu Wenruo 	ASSERT(list_empty(&cache->useless_node) &&
35671b23ea18SQu Wenruo 	       list_empty(&cache->pending_edge));
35681b23ea18SQu Wenruo }
3569