xref: /openbmc/linux/fs/btrfs/backref.c (revision e2fd83064a9bae368ce1c88a0cb9aee64ad4e124)
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"
2227137facSChristoph Hellwig #include "tree-checker.h"
23a542ad1bSJan Schmidt 
24877c1476SFilipe Manana /* Just arbitrary numbers so we can be sure one of these happened. */
25dc046b10SJosef Bacik #define BACKREF_FOUND_SHARED     6
26877c1476SFilipe Manana #define BACKREF_FOUND_NOT_SHARED 7
27dc046b10SJosef Bacik 
28976b1908SJan Schmidt struct extent_inode_elem {
29976b1908SJan Schmidt 	u64 inum;
30976b1908SJan Schmidt 	u64 offset;
31c7499a64SFilipe Manana 	u64 num_bytes;
32976b1908SJan Schmidt 	struct extent_inode_elem *next;
33976b1908SJan Schmidt };
34976b1908SJan Schmidt 
3588ffb665SFilipe Manana static int check_extent_in_eb(struct btrfs_backref_walk_ctx *ctx,
3688ffb665SFilipe Manana 			      const struct btrfs_key *key,
3773980becSJeff Mahoney 			      const struct extent_buffer *eb,
3873980becSJeff Mahoney 			      const struct btrfs_file_extent_item *fi,
396ce6ba53SFilipe Manana 			      struct extent_inode_elem **eie)
40976b1908SJan Schmidt {
41c7499a64SFilipe Manana 	const u64 data_len = btrfs_file_extent_num_bytes(eb, fi);
4288ffb665SFilipe Manana 	u64 offset = key->offset;
438ca15e05SJosef Bacik 	struct extent_inode_elem *e;
4488ffb665SFilipe Manana 	const u64 *root_ids;
4588ffb665SFilipe Manana 	int root_count;
4688ffb665SFilipe Manana 	bool cached;
478ca15e05SJosef Bacik 
486ce6ba53SFilipe Manana 	if (!btrfs_file_extent_compression(eb, fi) &&
498ca15e05SJosef Bacik 	    !btrfs_file_extent_encryption(eb, fi) &&
508ca15e05SJosef Bacik 	    !btrfs_file_extent_other_encoding(eb, fi)) {
51976b1908SJan Schmidt 		u64 data_offset;
52976b1908SJan Schmidt 
53976b1908SJan Schmidt 		data_offset = btrfs_file_extent_offset(eb, fi);
54976b1908SJan Schmidt 
5588ffb665SFilipe Manana 		if (ctx->extent_item_pos < data_offset ||
5688ffb665SFilipe Manana 		    ctx->extent_item_pos >= data_offset + data_len)
57976b1908SJan Schmidt 			return 1;
5888ffb665SFilipe Manana 		offset += ctx->extent_item_pos - data_offset;
598ca15e05SJosef Bacik 	}
60976b1908SJan Schmidt 
6188ffb665SFilipe Manana 	if (!ctx->indirect_ref_iterator || !ctx->cache_lookup)
6288ffb665SFilipe Manana 		goto add_inode_elem;
6388ffb665SFilipe Manana 
6488ffb665SFilipe Manana 	cached = ctx->cache_lookup(eb->start, ctx->user_ctx, &root_ids,
6588ffb665SFilipe Manana 				   &root_count);
6688ffb665SFilipe Manana 	if (!cached)
6788ffb665SFilipe Manana 		goto add_inode_elem;
6888ffb665SFilipe Manana 
6988ffb665SFilipe Manana 	for (int i = 0; i < root_count; i++) {
7088ffb665SFilipe Manana 		int ret;
7188ffb665SFilipe Manana 
7288ffb665SFilipe Manana 		ret = ctx->indirect_ref_iterator(key->objectid, offset,
7388ffb665SFilipe Manana 						 data_len, root_ids[i],
7488ffb665SFilipe Manana 						 ctx->user_ctx);
7588ffb665SFilipe Manana 		if (ret)
7688ffb665SFilipe Manana 			return ret;
7788ffb665SFilipe Manana 	}
7888ffb665SFilipe Manana 
7988ffb665SFilipe Manana add_inode_elem:
80976b1908SJan Schmidt 	e = kmalloc(sizeof(*e), GFP_NOFS);
81976b1908SJan Schmidt 	if (!e)
82976b1908SJan Schmidt 		return -ENOMEM;
83976b1908SJan Schmidt 
84976b1908SJan Schmidt 	e->next = *eie;
85976b1908SJan Schmidt 	e->inum = key->objectid;
8688ffb665SFilipe Manana 	e->offset = offset;
87c7499a64SFilipe Manana 	e->num_bytes = data_len;
88976b1908SJan Schmidt 	*eie = e;
89976b1908SJan Schmidt 
90976b1908SJan Schmidt 	return 0;
91976b1908SJan Schmidt }
92976b1908SJan Schmidt 
93f05c4746SWang Shilong static void free_inode_elem_list(struct extent_inode_elem *eie)
94f05c4746SWang Shilong {
95f05c4746SWang Shilong 	struct extent_inode_elem *eie_next;
96f05c4746SWang Shilong 
97f05c4746SWang Shilong 	for (; eie; eie = eie_next) {
98f05c4746SWang Shilong 		eie_next = eie->next;
99f05c4746SWang Shilong 		kfree(eie);
100f05c4746SWang Shilong 	}
101f05c4746SWang Shilong }
102f05c4746SWang Shilong 
10388ffb665SFilipe Manana static int find_extent_in_eb(struct btrfs_backref_walk_ctx *ctx,
10488ffb665SFilipe Manana 			     const struct extent_buffer *eb,
1056ce6ba53SFilipe Manana 			     struct extent_inode_elem **eie)
106976b1908SJan Schmidt {
107976b1908SJan Schmidt 	u64 disk_byte;
108976b1908SJan Schmidt 	struct btrfs_key key;
109976b1908SJan Schmidt 	struct btrfs_file_extent_item *fi;
110976b1908SJan Schmidt 	int slot;
111976b1908SJan Schmidt 	int nritems;
112976b1908SJan Schmidt 	int extent_type;
113976b1908SJan Schmidt 	int ret;
114976b1908SJan Schmidt 
115976b1908SJan Schmidt 	/*
116976b1908SJan Schmidt 	 * from the shared data ref, we only have the leaf but we need
117976b1908SJan Schmidt 	 * the key. thus, we must look into all items and see that we
118976b1908SJan Schmidt 	 * find one (some) with a reference to our extent item.
119976b1908SJan Schmidt 	 */
120976b1908SJan Schmidt 	nritems = btrfs_header_nritems(eb);
121976b1908SJan Schmidt 	for (slot = 0; slot < nritems; ++slot) {
122976b1908SJan Schmidt 		btrfs_item_key_to_cpu(eb, &key, slot);
123976b1908SJan Schmidt 		if (key.type != BTRFS_EXTENT_DATA_KEY)
124976b1908SJan Schmidt 			continue;
125976b1908SJan Schmidt 		fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
126976b1908SJan Schmidt 		extent_type = btrfs_file_extent_type(eb, fi);
127976b1908SJan Schmidt 		if (extent_type == BTRFS_FILE_EXTENT_INLINE)
128976b1908SJan Schmidt 			continue;
129976b1908SJan Schmidt 		/* don't skip BTRFS_FILE_EXTENT_PREALLOC, we can handle that */
130976b1908SJan Schmidt 		disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
13188ffb665SFilipe Manana 		if (disk_byte != ctx->bytenr)
132976b1908SJan Schmidt 			continue;
133976b1908SJan Schmidt 
13488ffb665SFilipe Manana 		ret = check_extent_in_eb(ctx, &key, eb, fi, eie);
13588ffb665SFilipe Manana 		if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
136976b1908SJan Schmidt 			return ret;
137976b1908SJan Schmidt 	}
138976b1908SJan Schmidt 
139976b1908SJan Schmidt 	return 0;
140976b1908SJan Schmidt }
141976b1908SJan Schmidt 
14286d5f994SEdmund Nadolski struct preftree {
143ecf160b4SLiu Bo 	struct rb_root_cached root;
1446c336b21SJeff Mahoney 	unsigned int count;
14586d5f994SEdmund Nadolski };
14686d5f994SEdmund Nadolski 
147ecf160b4SLiu Bo #define PREFTREE_INIT	{ .root = RB_ROOT_CACHED, .count = 0 }
14886d5f994SEdmund Nadolski 
14986d5f994SEdmund Nadolski struct preftrees {
15086d5f994SEdmund Nadolski 	struct preftree direct;    /* BTRFS_SHARED_[DATA|BLOCK]_REF_KEY */
15186d5f994SEdmund Nadolski 	struct preftree indirect;  /* BTRFS_[TREE_BLOCK|EXTENT_DATA]_REF_KEY */
15286d5f994SEdmund Nadolski 	struct preftree indirect_missing_keys;
15386d5f994SEdmund Nadolski };
15486d5f994SEdmund Nadolski 
1553ec4d323SEdmund Nadolski /*
1563ec4d323SEdmund Nadolski  * Checks for a shared extent during backref search.
1573ec4d323SEdmund Nadolski  *
1583ec4d323SEdmund Nadolski  * The share_count tracks prelim_refs (direct and indirect) having a
1593ec4d323SEdmund Nadolski  * ref->count >0:
1603ec4d323SEdmund Nadolski  *  - incremented when a ref->count transitions to >0
1613ec4d323SEdmund Nadolski  *  - decremented when a ref->count transitions to <1
1623ec4d323SEdmund Nadolski  */
1633ec4d323SEdmund Nadolski struct share_check {
164877c1476SFilipe Manana 	struct btrfs_backref_share_check_ctx *ctx;
165877c1476SFilipe Manana 	struct btrfs_root *root;
1663ec4d323SEdmund Nadolski 	u64 inum;
16773e339e6SFilipe Manana 	u64 data_bytenr;
1686976201fSFilipe Manana 	u64 data_extent_gen;
16973e339e6SFilipe Manana 	/*
17073e339e6SFilipe Manana 	 * Counts number of inodes that refer to an extent (different inodes in
17173e339e6SFilipe Manana 	 * the same root or different roots) that we could find. The sharedness
17273e339e6SFilipe Manana 	 * check typically stops once this counter gets greater than 1, so it
17373e339e6SFilipe Manana 	 * may not reflect the total number of inodes.
17473e339e6SFilipe Manana 	 */
1753ec4d323SEdmund Nadolski 	int share_count;
17673e339e6SFilipe Manana 	/*
17773e339e6SFilipe Manana 	 * The number of times we found our inode refers to the data extent we
17873e339e6SFilipe Manana 	 * are determining the sharedness. In other words, how many file extent
17973e339e6SFilipe Manana 	 * items we could find for our inode that point to our target data
18073e339e6SFilipe Manana 	 * extent. The value we get here after finishing the extent sharedness
18173e339e6SFilipe Manana 	 * check may be smaller than reality, but if it ends up being greater
18273e339e6SFilipe Manana 	 * than 1, then we know for sure the inode has multiple file extent
18373e339e6SFilipe Manana 	 * items that point to our inode, and we can safely assume it's useful
18473e339e6SFilipe Manana 	 * to cache the sharedness check result.
18573e339e6SFilipe Manana 	 */
18673e339e6SFilipe Manana 	int self_ref_count;
1874fc7b572SFilipe Manana 	bool have_delayed_delete_refs;
1883ec4d323SEdmund Nadolski };
1893ec4d323SEdmund Nadolski 
1903ec4d323SEdmund Nadolski static inline int extent_is_shared(struct share_check *sc)
1913ec4d323SEdmund Nadolski {
1923ec4d323SEdmund Nadolski 	return (sc && sc->share_count > 1) ? BACKREF_FOUND_SHARED : 0;
1933ec4d323SEdmund Nadolski }
1943ec4d323SEdmund Nadolski 
195b9e9a6cbSWang Shilong static struct kmem_cache *btrfs_prelim_ref_cache;
196b9e9a6cbSWang Shilong 
197b9e9a6cbSWang Shilong int __init btrfs_prelim_ref_init(void)
198b9e9a6cbSWang Shilong {
199b9e9a6cbSWang Shilong 	btrfs_prelim_ref_cache = kmem_cache_create("btrfs_prelim_ref",
200e0c476b1SJeff Mahoney 					sizeof(struct prelim_ref),
201b9e9a6cbSWang Shilong 					0,
202fba4b697SNikolay Borisov 					SLAB_MEM_SPREAD,
203b9e9a6cbSWang Shilong 					NULL);
204b9e9a6cbSWang Shilong 	if (!btrfs_prelim_ref_cache)
205b9e9a6cbSWang Shilong 		return -ENOMEM;
206b9e9a6cbSWang Shilong 	return 0;
207b9e9a6cbSWang Shilong }
208b9e9a6cbSWang Shilong 
209e67c718bSDavid Sterba void __cold btrfs_prelim_ref_exit(void)
210b9e9a6cbSWang Shilong {
211b9e9a6cbSWang Shilong 	kmem_cache_destroy(btrfs_prelim_ref_cache);
212b9e9a6cbSWang Shilong }
213b9e9a6cbSWang Shilong 
21486d5f994SEdmund Nadolski static void free_pref(struct prelim_ref *ref)
21586d5f994SEdmund Nadolski {
21686d5f994SEdmund Nadolski 	kmem_cache_free(btrfs_prelim_ref_cache, ref);
21786d5f994SEdmund Nadolski }
21886d5f994SEdmund Nadolski 
21986d5f994SEdmund Nadolski /*
22086d5f994SEdmund Nadolski  * Return 0 when both refs are for the same block (and can be merged).
22186d5f994SEdmund Nadolski  * A -1 return indicates ref1 is a 'lower' block than ref2, while 1
22286d5f994SEdmund Nadolski  * indicates a 'higher' block.
22386d5f994SEdmund Nadolski  */
22486d5f994SEdmund Nadolski static int prelim_ref_compare(struct prelim_ref *ref1,
22586d5f994SEdmund Nadolski 			      struct prelim_ref *ref2)
22686d5f994SEdmund Nadolski {
22786d5f994SEdmund Nadolski 	if (ref1->level < ref2->level)
22886d5f994SEdmund Nadolski 		return -1;
22986d5f994SEdmund Nadolski 	if (ref1->level > ref2->level)
23086d5f994SEdmund Nadolski 		return 1;
23186d5f994SEdmund Nadolski 	if (ref1->root_id < ref2->root_id)
23286d5f994SEdmund Nadolski 		return -1;
23386d5f994SEdmund Nadolski 	if (ref1->root_id > ref2->root_id)
23486d5f994SEdmund Nadolski 		return 1;
23586d5f994SEdmund Nadolski 	if (ref1->key_for_search.type < ref2->key_for_search.type)
23686d5f994SEdmund Nadolski 		return -1;
23786d5f994SEdmund Nadolski 	if (ref1->key_for_search.type > ref2->key_for_search.type)
23886d5f994SEdmund Nadolski 		return 1;
23986d5f994SEdmund Nadolski 	if (ref1->key_for_search.objectid < ref2->key_for_search.objectid)
24086d5f994SEdmund Nadolski 		return -1;
24186d5f994SEdmund Nadolski 	if (ref1->key_for_search.objectid > ref2->key_for_search.objectid)
24286d5f994SEdmund Nadolski 		return 1;
24386d5f994SEdmund Nadolski 	if (ref1->key_for_search.offset < ref2->key_for_search.offset)
24486d5f994SEdmund Nadolski 		return -1;
24586d5f994SEdmund Nadolski 	if (ref1->key_for_search.offset > ref2->key_for_search.offset)
24686d5f994SEdmund Nadolski 		return 1;
24786d5f994SEdmund Nadolski 	if (ref1->parent < ref2->parent)
24886d5f994SEdmund Nadolski 		return -1;
24986d5f994SEdmund Nadolski 	if (ref1->parent > ref2->parent)
25086d5f994SEdmund Nadolski 		return 1;
25186d5f994SEdmund Nadolski 
25286d5f994SEdmund Nadolski 	return 0;
25386d5f994SEdmund Nadolski }
25486d5f994SEdmund Nadolski 
255ccc8dc75SColin Ian King static void update_share_count(struct share_check *sc, int oldcount,
25673e339e6SFilipe Manana 			       int newcount, struct prelim_ref *newref)
2573ec4d323SEdmund Nadolski {
2583ec4d323SEdmund Nadolski 	if ((!sc) || (oldcount == 0 && newcount < 1))
2593ec4d323SEdmund Nadolski 		return;
2603ec4d323SEdmund Nadolski 
2613ec4d323SEdmund Nadolski 	if (oldcount > 0 && newcount < 1)
2623ec4d323SEdmund Nadolski 		sc->share_count--;
2633ec4d323SEdmund Nadolski 	else if (oldcount < 1 && newcount > 0)
2643ec4d323SEdmund Nadolski 		sc->share_count++;
26573e339e6SFilipe Manana 
266877c1476SFilipe Manana 	if (newref->root_id == sc->root->root_key.objectid &&
26773e339e6SFilipe Manana 	    newref->wanted_disk_byte == sc->data_bytenr &&
26873e339e6SFilipe Manana 	    newref->key_for_search.objectid == sc->inum)
26973e339e6SFilipe Manana 		sc->self_ref_count += newref->count;
2703ec4d323SEdmund Nadolski }
2713ec4d323SEdmund Nadolski 
27286d5f994SEdmund Nadolski /*
27386d5f994SEdmund Nadolski  * Add @newref to the @root rbtree, merging identical refs.
27486d5f994SEdmund Nadolski  *
2753ec4d323SEdmund Nadolski  * Callers should assume that newref has been freed after calling.
27686d5f994SEdmund Nadolski  */
27700142756SJeff Mahoney static void prelim_ref_insert(const struct btrfs_fs_info *fs_info,
27800142756SJeff Mahoney 			      struct preftree *preftree,
2793ec4d323SEdmund Nadolski 			      struct prelim_ref *newref,
2803ec4d323SEdmund Nadolski 			      struct share_check *sc)
28186d5f994SEdmund Nadolski {
282ecf160b4SLiu Bo 	struct rb_root_cached *root;
28386d5f994SEdmund Nadolski 	struct rb_node **p;
28486d5f994SEdmund Nadolski 	struct rb_node *parent = NULL;
28586d5f994SEdmund Nadolski 	struct prelim_ref *ref;
28686d5f994SEdmund Nadolski 	int result;
287ecf160b4SLiu Bo 	bool leftmost = true;
28886d5f994SEdmund Nadolski 
28986d5f994SEdmund Nadolski 	root = &preftree->root;
290ecf160b4SLiu Bo 	p = &root->rb_root.rb_node;
29186d5f994SEdmund Nadolski 
29286d5f994SEdmund Nadolski 	while (*p) {
29386d5f994SEdmund Nadolski 		parent = *p;
29486d5f994SEdmund Nadolski 		ref = rb_entry(parent, struct prelim_ref, rbnode);
29586d5f994SEdmund Nadolski 		result = prelim_ref_compare(ref, newref);
29686d5f994SEdmund Nadolski 		if (result < 0) {
29786d5f994SEdmund Nadolski 			p = &(*p)->rb_left;
29886d5f994SEdmund Nadolski 		} else if (result > 0) {
29986d5f994SEdmund Nadolski 			p = &(*p)->rb_right;
300ecf160b4SLiu Bo 			leftmost = false;
30186d5f994SEdmund Nadolski 		} else {
30286d5f994SEdmund Nadolski 			/* Identical refs, merge them and free @newref */
30386d5f994SEdmund Nadolski 			struct extent_inode_elem *eie = ref->inode_list;
30486d5f994SEdmund Nadolski 
30586d5f994SEdmund Nadolski 			while (eie && eie->next)
30686d5f994SEdmund Nadolski 				eie = eie->next;
30786d5f994SEdmund Nadolski 
30886d5f994SEdmund Nadolski 			if (!eie)
30986d5f994SEdmund Nadolski 				ref->inode_list = newref->inode_list;
31086d5f994SEdmund Nadolski 			else
31186d5f994SEdmund Nadolski 				eie->next = newref->inode_list;
31200142756SJeff Mahoney 			trace_btrfs_prelim_ref_merge(fs_info, ref, newref,
31300142756SJeff Mahoney 						     preftree->count);
3143ec4d323SEdmund Nadolski 			/*
3153ec4d323SEdmund Nadolski 			 * A delayed ref can have newref->count < 0.
3163ec4d323SEdmund Nadolski 			 * The ref->count is updated to follow any
3173ec4d323SEdmund Nadolski 			 * BTRFS_[ADD|DROP]_DELAYED_REF actions.
3183ec4d323SEdmund Nadolski 			 */
3193ec4d323SEdmund Nadolski 			update_share_count(sc, ref->count,
32073e339e6SFilipe Manana 					   ref->count + newref->count, newref);
32186d5f994SEdmund Nadolski 			ref->count += newref->count;
32286d5f994SEdmund Nadolski 			free_pref(newref);
32386d5f994SEdmund Nadolski 			return;
32486d5f994SEdmund Nadolski 		}
32586d5f994SEdmund Nadolski 	}
32686d5f994SEdmund Nadolski 
32773e339e6SFilipe Manana 	update_share_count(sc, 0, newref->count, newref);
3286c336b21SJeff Mahoney 	preftree->count++;
32900142756SJeff Mahoney 	trace_btrfs_prelim_ref_insert(fs_info, newref, NULL, preftree->count);
33086d5f994SEdmund Nadolski 	rb_link_node(&newref->rbnode, parent, p);
331ecf160b4SLiu Bo 	rb_insert_color_cached(&newref->rbnode, root, leftmost);
33286d5f994SEdmund Nadolski }
33386d5f994SEdmund Nadolski 
33486d5f994SEdmund Nadolski /*
33586d5f994SEdmund Nadolski  * Release the entire tree.  We don't care about internal consistency so
33686d5f994SEdmund Nadolski  * just free everything and then reset the tree root.
33786d5f994SEdmund Nadolski  */
33886d5f994SEdmund Nadolski static void prelim_release(struct preftree *preftree)
33986d5f994SEdmund Nadolski {
34086d5f994SEdmund Nadolski 	struct prelim_ref *ref, *next_ref;
34186d5f994SEdmund Nadolski 
342ecf160b4SLiu Bo 	rbtree_postorder_for_each_entry_safe(ref, next_ref,
34392876eecSFilipe Manana 					     &preftree->root.rb_root, rbnode) {
34492876eecSFilipe Manana 		free_inode_elem_list(ref->inode_list);
34586d5f994SEdmund Nadolski 		free_pref(ref);
34692876eecSFilipe Manana 	}
34786d5f994SEdmund Nadolski 
348ecf160b4SLiu Bo 	preftree->root = RB_ROOT_CACHED;
3496c336b21SJeff Mahoney 	preftree->count = 0;
35086d5f994SEdmund Nadolski }
35186d5f994SEdmund Nadolski 
352d5c88b73SJan Schmidt /*
353d5c88b73SJan Schmidt  * the rules for all callers of this function are:
354d5c88b73SJan Schmidt  * - obtaining the parent is the goal
355d5c88b73SJan Schmidt  * - if you add a key, you must know that it is a correct key
356d5c88b73SJan Schmidt  * - if you cannot add the parent or a correct key, then we will look into the
357d5c88b73SJan Schmidt  *   block later to set a correct key
358d5c88b73SJan Schmidt  *
359d5c88b73SJan Schmidt  * delayed refs
360d5c88b73SJan Schmidt  * ============
361d5c88b73SJan Schmidt  *        backref type | shared | indirect | shared | indirect
362d5c88b73SJan Schmidt  * information         |   tree |     tree |   data |     data
363d5c88b73SJan Schmidt  * --------------------+--------+----------+--------+----------
364d5c88b73SJan Schmidt  *      parent logical |    y   |     -    |    -   |     -
365d5c88b73SJan Schmidt  *      key to resolve |    -   |     y    |    y   |     y
366d5c88b73SJan Schmidt  *  tree block logical |    -   |     -    |    -   |     -
367d5c88b73SJan Schmidt  *  root for resolving |    y   |     y    |    y   |     y
368d5c88b73SJan Schmidt  *
369d5c88b73SJan Schmidt  * - column 1:       we've the parent -> done
370d5c88b73SJan Schmidt  * - column 2, 3, 4: we use the key to find the parent
371d5c88b73SJan Schmidt  *
372d5c88b73SJan Schmidt  * on disk refs (inline or keyed)
373d5c88b73SJan Schmidt  * ==============================
374d5c88b73SJan Schmidt  *        backref type | shared | indirect | shared | indirect
375d5c88b73SJan Schmidt  * information         |   tree |     tree |   data |     data
376d5c88b73SJan Schmidt  * --------------------+--------+----------+--------+----------
377d5c88b73SJan Schmidt  *      parent logical |    y   |     -    |    y   |     -
378d5c88b73SJan Schmidt  *      key to resolve |    -   |     -    |    -   |     y
379d5c88b73SJan Schmidt  *  tree block logical |    y   |     y    |    y   |     y
380d5c88b73SJan Schmidt  *  root for resolving |    -   |     y    |    y   |     y
381d5c88b73SJan Schmidt  *
382d5c88b73SJan Schmidt  * - column 1, 3: we've the parent -> done
383d5c88b73SJan Schmidt  * - column 2:    we take the first key from the block to find the parent
384e0c476b1SJeff Mahoney  *                (see add_missing_keys)
385d5c88b73SJan Schmidt  * - column 4:    we use the key to find the parent
386d5c88b73SJan Schmidt  *
387d5c88b73SJan Schmidt  * additional information that's available but not required to find the parent
388d5c88b73SJan Schmidt  * block might help in merging entries to gain some speed.
389d5c88b73SJan Schmidt  */
39000142756SJeff Mahoney static int add_prelim_ref(const struct btrfs_fs_info *fs_info,
39100142756SJeff Mahoney 			  struct preftree *preftree, u64 root_id,
392e0c476b1SJeff Mahoney 			  const struct btrfs_key *key, int level, u64 parent,
3933ec4d323SEdmund Nadolski 			  u64 wanted_disk_byte, int count,
3943ec4d323SEdmund Nadolski 			  struct share_check *sc, gfp_t gfp_mask)
3958da6d581SJan Schmidt {
396e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
3978da6d581SJan Schmidt 
39848ec4736SLiu Bo 	if (root_id == BTRFS_DATA_RELOC_TREE_OBJECTID)
39948ec4736SLiu Bo 		return 0;
40048ec4736SLiu Bo 
401b9e9a6cbSWang Shilong 	ref = kmem_cache_alloc(btrfs_prelim_ref_cache, gfp_mask);
4028da6d581SJan Schmidt 	if (!ref)
4038da6d581SJan Schmidt 		return -ENOMEM;
4048da6d581SJan Schmidt 
4058da6d581SJan Schmidt 	ref->root_id = root_id;
4067ac8b88eSethanwu 	if (key)
407d5c88b73SJan Schmidt 		ref->key_for_search = *key;
4087ac8b88eSethanwu 	else
409d5c88b73SJan Schmidt 		memset(&ref->key_for_search, 0, sizeof(ref->key_for_search));
4108da6d581SJan Schmidt 
4113301958bSJan Schmidt 	ref->inode_list = NULL;
4128da6d581SJan Schmidt 	ref->level = level;
4138da6d581SJan Schmidt 	ref->count = count;
4148da6d581SJan Schmidt 	ref->parent = parent;
4158da6d581SJan Schmidt 	ref->wanted_disk_byte = wanted_disk_byte;
4163ec4d323SEdmund Nadolski 	prelim_ref_insert(fs_info, preftree, ref, sc);
4173ec4d323SEdmund Nadolski 	return extent_is_shared(sc);
4188da6d581SJan Schmidt }
4198da6d581SJan Schmidt 
42086d5f994SEdmund Nadolski /* direct refs use root == 0, key == NULL */
42100142756SJeff Mahoney static int add_direct_ref(const struct btrfs_fs_info *fs_info,
42200142756SJeff Mahoney 			  struct preftrees *preftrees, int level, u64 parent,
4233ec4d323SEdmund Nadolski 			  u64 wanted_disk_byte, int count,
4243ec4d323SEdmund Nadolski 			  struct share_check *sc, gfp_t gfp_mask)
42586d5f994SEdmund Nadolski {
42600142756SJeff Mahoney 	return add_prelim_ref(fs_info, &preftrees->direct, 0, NULL, level,
4273ec4d323SEdmund Nadolski 			      parent, wanted_disk_byte, count, sc, gfp_mask);
42886d5f994SEdmund Nadolski }
42986d5f994SEdmund Nadolski 
43086d5f994SEdmund Nadolski /* indirect refs use parent == 0 */
43100142756SJeff Mahoney static int add_indirect_ref(const struct btrfs_fs_info *fs_info,
43200142756SJeff Mahoney 			    struct preftrees *preftrees, u64 root_id,
43386d5f994SEdmund Nadolski 			    const struct btrfs_key *key, int level,
4343ec4d323SEdmund Nadolski 			    u64 wanted_disk_byte, int count,
4353ec4d323SEdmund Nadolski 			    struct share_check *sc, gfp_t gfp_mask)
43686d5f994SEdmund Nadolski {
43786d5f994SEdmund Nadolski 	struct preftree *tree = &preftrees->indirect;
43886d5f994SEdmund Nadolski 
43986d5f994SEdmund Nadolski 	if (!key)
44086d5f994SEdmund Nadolski 		tree = &preftrees->indirect_missing_keys;
44100142756SJeff Mahoney 	return add_prelim_ref(fs_info, tree, root_id, key, level, 0,
4423ec4d323SEdmund Nadolski 			      wanted_disk_byte, count, sc, gfp_mask);
44386d5f994SEdmund Nadolski }
44486d5f994SEdmund Nadolski 
445ed58f2e6Sethanwu static int is_shared_data_backref(struct preftrees *preftrees, u64 bytenr)
446ed58f2e6Sethanwu {
447ed58f2e6Sethanwu 	struct rb_node **p = &preftrees->direct.root.rb_root.rb_node;
448ed58f2e6Sethanwu 	struct rb_node *parent = NULL;
449ed58f2e6Sethanwu 	struct prelim_ref *ref = NULL;
4509c6c723fSArnd Bergmann 	struct prelim_ref target = {};
451ed58f2e6Sethanwu 	int result;
452ed58f2e6Sethanwu 
453ed58f2e6Sethanwu 	target.parent = bytenr;
454ed58f2e6Sethanwu 
455ed58f2e6Sethanwu 	while (*p) {
456ed58f2e6Sethanwu 		parent = *p;
457ed58f2e6Sethanwu 		ref = rb_entry(parent, struct prelim_ref, rbnode);
458ed58f2e6Sethanwu 		result = prelim_ref_compare(ref, &target);
459ed58f2e6Sethanwu 
460ed58f2e6Sethanwu 		if (result < 0)
461ed58f2e6Sethanwu 			p = &(*p)->rb_left;
462ed58f2e6Sethanwu 		else if (result > 0)
463ed58f2e6Sethanwu 			p = &(*p)->rb_right;
464ed58f2e6Sethanwu 		else
465ed58f2e6Sethanwu 			return 1;
466ed58f2e6Sethanwu 	}
467ed58f2e6Sethanwu 	return 0;
468ed58f2e6Sethanwu }
469ed58f2e6Sethanwu 
470a2c8d27eSFilipe Manana static int add_all_parents(struct btrfs_backref_walk_ctx *ctx,
471a2c8d27eSFilipe Manana 			   struct btrfs_root *root, struct btrfs_path *path,
472ed58f2e6Sethanwu 			   struct ulist *parents,
473ed58f2e6Sethanwu 			   struct preftrees *preftrees, struct prelim_ref *ref,
474a2c8d27eSFilipe Manana 			   int level)
4758da6d581SJan Schmidt {
47669bca40dSAlexander Block 	int ret = 0;
47769bca40dSAlexander Block 	int slot;
47869bca40dSAlexander Block 	struct extent_buffer *eb;
47969bca40dSAlexander Block 	struct btrfs_key key;
4807ef81ac8SJosef Bacik 	struct btrfs_key *key_for_search = &ref->key_for_search;
4818da6d581SJan Schmidt 	struct btrfs_file_extent_item *fi;
482ed8c4913SJosef Bacik 	struct extent_inode_elem *eie = NULL, *old = NULL;
4838da6d581SJan Schmidt 	u64 disk_byte;
4847ef81ac8SJosef Bacik 	u64 wanted_disk_byte = ref->wanted_disk_byte;
4857ef81ac8SJosef Bacik 	u64 count = 0;
4867ac8b88eSethanwu 	u64 data_offset;
487560840afSBoris Burkov 	u8 type;
4888da6d581SJan Schmidt 
48969bca40dSAlexander Block 	if (level != 0) {
49069bca40dSAlexander Block 		eb = path->nodes[level];
49169bca40dSAlexander Block 		ret = ulist_add(parents, eb->start, 0, GFP_NOFS);
4923301958bSJan Schmidt 		if (ret < 0)
4933301958bSJan Schmidt 			return ret;
4948da6d581SJan Schmidt 		return 0;
49569bca40dSAlexander Block 	}
4968da6d581SJan Schmidt 
4978da6d581SJan Schmidt 	/*
498ed58f2e6Sethanwu 	 * 1. We normally enter this function with the path already pointing to
49969bca40dSAlexander Block 	 *    the first item to check. But sometimes, we may enter it with
500ed58f2e6Sethanwu 	 *    slot == nritems.
501ed58f2e6Sethanwu 	 * 2. We are searching for normal backref but bytenr of this leaf
502ed58f2e6Sethanwu 	 *    matches shared data backref
503cfc0eed0Sethanwu 	 * 3. The leaf owner is not equal to the root we are searching
504cfc0eed0Sethanwu 	 *
505ed58f2e6Sethanwu 	 * For these cases, go to the next leaf before we continue.
5068da6d581SJan Schmidt 	 */
507ed58f2e6Sethanwu 	eb = path->nodes[0];
508ed58f2e6Sethanwu 	if (path->slots[0] >= btrfs_header_nritems(eb) ||
509cfc0eed0Sethanwu 	    is_shared_data_backref(preftrees, eb->start) ||
510cfc0eed0Sethanwu 	    ref->root_id != btrfs_header_owner(eb)) {
511a2c8d27eSFilipe Manana 		if (ctx->time_seq == BTRFS_SEQ_LAST)
51221633fc6SQu Wenruo 			ret = btrfs_next_leaf(root, path);
51321633fc6SQu Wenruo 		else
514a2c8d27eSFilipe Manana 			ret = btrfs_next_old_leaf(root, path, ctx->time_seq);
51521633fc6SQu Wenruo 	}
5168da6d581SJan Schmidt 
517b25b0b87Sethanwu 	while (!ret && count < ref->count) {
5188da6d581SJan Schmidt 		eb = path->nodes[0];
51969bca40dSAlexander Block 		slot = path->slots[0];
52069bca40dSAlexander Block 
52169bca40dSAlexander Block 		btrfs_item_key_to_cpu(eb, &key, slot);
52269bca40dSAlexander Block 
52369bca40dSAlexander Block 		if (key.objectid != key_for_search->objectid ||
52469bca40dSAlexander Block 		    key.type != BTRFS_EXTENT_DATA_KEY)
52569bca40dSAlexander Block 			break;
52669bca40dSAlexander Block 
527ed58f2e6Sethanwu 		/*
528ed58f2e6Sethanwu 		 * We are searching for normal backref but bytenr of this leaf
529cfc0eed0Sethanwu 		 * matches shared data backref, OR
530cfc0eed0Sethanwu 		 * the leaf owner is not equal to the root we are searching for
531ed58f2e6Sethanwu 		 */
532cfc0eed0Sethanwu 		if (slot == 0 &&
533cfc0eed0Sethanwu 		    (is_shared_data_backref(preftrees, eb->start) ||
534cfc0eed0Sethanwu 		     ref->root_id != btrfs_header_owner(eb))) {
535a2c8d27eSFilipe Manana 			if (ctx->time_seq == BTRFS_SEQ_LAST)
536ed58f2e6Sethanwu 				ret = btrfs_next_leaf(root, path);
537ed58f2e6Sethanwu 			else
538a2c8d27eSFilipe Manana 				ret = btrfs_next_old_leaf(root, path, ctx->time_seq);
539ed58f2e6Sethanwu 			continue;
540ed58f2e6Sethanwu 		}
54169bca40dSAlexander Block 		fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
542560840afSBoris Burkov 		type = btrfs_file_extent_type(eb, fi);
543560840afSBoris Burkov 		if (type == BTRFS_FILE_EXTENT_INLINE)
544560840afSBoris Burkov 			goto next;
5458da6d581SJan Schmidt 		disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
5467ac8b88eSethanwu 		data_offset = btrfs_file_extent_offset(eb, fi);
54769bca40dSAlexander Block 
54869bca40dSAlexander Block 		if (disk_byte == wanted_disk_byte) {
54969bca40dSAlexander Block 			eie = NULL;
550ed8c4913SJosef Bacik 			old = NULL;
5517ac8b88eSethanwu 			if (ref->key_for_search.offset == key.offset - data_offset)
5527ef81ac8SJosef Bacik 				count++;
5537ac8b88eSethanwu 			else
5547ac8b88eSethanwu 				goto next;
555a2c8d27eSFilipe Manana 			if (!ctx->ignore_extent_item_pos) {
55688ffb665SFilipe Manana 				ret = check_extent_in_eb(ctx, &key, eb, fi, &eie);
55788ffb665SFilipe Manana 				if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
55888ffb665SFilipe Manana 				    ret < 0)
55969bca40dSAlexander Block 					break;
5608da6d581SJan Schmidt 			}
561ed8c4913SJosef Bacik 			if (ret > 0)
562ed8c4913SJosef Bacik 				goto next;
5634eb1f66dSTakashi Iwai 			ret = ulist_add_merge_ptr(parents, eb->start,
5644eb1f66dSTakashi Iwai 						  eie, (void **)&old, GFP_NOFS);
56569bca40dSAlexander Block 			if (ret < 0)
56669bca40dSAlexander Block 				break;
567a2c8d27eSFilipe Manana 			if (!ret && !ctx->ignore_extent_item_pos) {
568ed8c4913SJosef Bacik 				while (old->next)
569ed8c4913SJosef Bacik 					old = old->next;
570ed8c4913SJosef Bacik 				old->next = eie;
57169bca40dSAlexander Block 			}
572f05c4746SWang Shilong 			eie = NULL;
57369bca40dSAlexander Block 		}
574ed8c4913SJosef Bacik next:
575a2c8d27eSFilipe Manana 		if (ctx->time_seq == BTRFS_SEQ_LAST)
57621633fc6SQu Wenruo 			ret = btrfs_next_item(root, path);
57721633fc6SQu Wenruo 		else
578a2c8d27eSFilipe Manana 			ret = btrfs_next_old_item(root, path, ctx->time_seq);
5798da6d581SJan Schmidt 	}
5808da6d581SJan Schmidt 
58188ffb665SFilipe Manana 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
582f05c4746SWang Shilong 		free_inode_elem_list(eie);
58388ffb665SFilipe Manana 	else if (ret > 0)
58488ffb665SFilipe Manana 		ret = 0;
58588ffb665SFilipe Manana 
58669bca40dSAlexander Block 	return ret;
5878da6d581SJan Schmidt }
5888da6d581SJan Schmidt 
5898da6d581SJan Schmidt /*
5908da6d581SJan Schmidt  * resolve an indirect backref in the form (root_id, key, level)
5918da6d581SJan Schmidt  * to a logical address
5928da6d581SJan Schmidt  */
593a2c8d27eSFilipe Manana static int resolve_indirect_ref(struct btrfs_backref_walk_ctx *ctx,
594a2c8d27eSFilipe Manana 				struct btrfs_path *path,
595ed58f2e6Sethanwu 				struct preftrees *preftrees,
596a2c8d27eSFilipe Manana 				struct prelim_ref *ref, struct ulist *parents)
5978da6d581SJan Schmidt {
5988da6d581SJan Schmidt 	struct btrfs_root *root;
5998da6d581SJan Schmidt 	struct extent_buffer *eb;
6008da6d581SJan Schmidt 	int ret = 0;
6018da6d581SJan Schmidt 	int root_level;
6028da6d581SJan Schmidt 	int level = ref->level;
6037ac8b88eSethanwu 	struct btrfs_key search_key = ref->key_for_search;
6048da6d581SJan Schmidt 
60549d11beaSJosef Bacik 	/*
60649d11beaSJosef Bacik 	 * If we're search_commit_root we could possibly be holding locks on
60749d11beaSJosef Bacik 	 * other tree nodes.  This happens when qgroups does backref walks when
60849d11beaSJosef Bacik 	 * adding new delayed refs.  To deal with this we need to look in cache
60949d11beaSJosef Bacik 	 * for the root, and if we don't find it then we need to search the
61049d11beaSJosef Bacik 	 * tree_root's commit root, thus the btrfs_get_fs_root_commit_root usage
61149d11beaSJosef Bacik 	 * here.
61249d11beaSJosef Bacik 	 */
61349d11beaSJosef Bacik 	if (path->search_commit_root)
614a2c8d27eSFilipe Manana 		root = btrfs_get_fs_root_commit_root(ctx->fs_info, path, ref->root_id);
61549d11beaSJosef Bacik 	else
616a2c8d27eSFilipe Manana 		root = btrfs_get_fs_root(ctx->fs_info, ref->root_id, false);
6178da6d581SJan Schmidt 	if (IS_ERR(root)) {
6188da6d581SJan Schmidt 		ret = PTR_ERR(root);
6199326f76fSJosef Bacik 		goto out_free;
6209326f76fSJosef Bacik 	}
6219326f76fSJosef Bacik 
62239dba873SJosef Bacik 	if (!path->search_commit_root &&
62339dba873SJosef Bacik 	    test_bit(BTRFS_ROOT_DELETING, &root->state)) {
62439dba873SJosef Bacik 		ret = -ENOENT;
62539dba873SJosef Bacik 		goto out;
62639dba873SJosef Bacik 	}
62739dba873SJosef Bacik 
628a2c8d27eSFilipe Manana 	if (btrfs_is_testing(ctx->fs_info)) {
629d9ee522bSJosef Bacik 		ret = -ENOENT;
630d9ee522bSJosef Bacik 		goto out;
631d9ee522bSJosef Bacik 	}
632d9ee522bSJosef Bacik 
6339e351cc8SJosef Bacik 	if (path->search_commit_root)
6349e351cc8SJosef Bacik 		root_level = btrfs_header_level(root->commit_root);
635a2c8d27eSFilipe Manana 	else if (ctx->time_seq == BTRFS_SEQ_LAST)
63621633fc6SQu Wenruo 		root_level = btrfs_header_level(root->node);
6379e351cc8SJosef Bacik 	else
638a2c8d27eSFilipe Manana 		root_level = btrfs_old_root_level(root, ctx->time_seq);
6398da6d581SJan Schmidt 
640c75e8394SJosef Bacik 	if (root_level + 1 == level)
6418da6d581SJan Schmidt 		goto out;
6428da6d581SJan Schmidt 
6437ac8b88eSethanwu 	/*
6447ac8b88eSethanwu 	 * We can often find data backrefs with an offset that is too large
6457ac8b88eSethanwu 	 * (>= LLONG_MAX, maximum allowed file offset) due to underflows when
6467ac8b88eSethanwu 	 * subtracting a file's offset with the data offset of its
6477ac8b88eSethanwu 	 * corresponding extent data item. This can happen for example in the
6487ac8b88eSethanwu 	 * clone ioctl.
6497ac8b88eSethanwu 	 *
6507ac8b88eSethanwu 	 * So if we detect such case we set the search key's offset to zero to
6517ac8b88eSethanwu 	 * make sure we will find the matching file extent item at
6527ac8b88eSethanwu 	 * add_all_parents(), otherwise we will miss it because the offset
6537ac8b88eSethanwu 	 * taken form the backref is much larger then the offset of the file
6547ac8b88eSethanwu 	 * extent item. This can make us scan a very large number of file
6557ac8b88eSethanwu 	 * extent items, but at least it will not make us miss any.
6567ac8b88eSethanwu 	 *
6577ac8b88eSethanwu 	 * This is an ugly workaround for a behaviour that should have never
6587ac8b88eSethanwu 	 * existed, but it does and a fix for the clone ioctl would touch a lot
6597ac8b88eSethanwu 	 * of places, cause backwards incompatibility and would not fix the
6607ac8b88eSethanwu 	 * problem for extents cloned with older kernels.
6617ac8b88eSethanwu 	 */
6627ac8b88eSethanwu 	if (search_key.type == BTRFS_EXTENT_DATA_KEY &&
6637ac8b88eSethanwu 	    search_key.offset >= LLONG_MAX)
6647ac8b88eSethanwu 		search_key.offset = 0;
6658da6d581SJan Schmidt 	path->lowest_level = level;
666a2c8d27eSFilipe Manana 	if (ctx->time_seq == BTRFS_SEQ_LAST)
6677ac8b88eSethanwu 		ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
66821633fc6SQu Wenruo 	else
669a2c8d27eSFilipe Manana 		ret = btrfs_search_old_slot(root, &search_key, path, ctx->time_seq);
670538f72cdSWang Shilong 
671a2c8d27eSFilipe Manana 	btrfs_debug(ctx->fs_info,
672ab8d0fc4SJeff Mahoney 		"search slot in root %llu (level %d, ref count %d) returned %d for key (%llu %u %llu)",
673c1c9ff7cSGeert Uytterhoeven 		 ref->root_id, level, ref->count, ret,
674c1c9ff7cSGeert Uytterhoeven 		 ref->key_for_search.objectid, ref->key_for_search.type,
675c1c9ff7cSGeert Uytterhoeven 		 ref->key_for_search.offset);
6768da6d581SJan Schmidt 	if (ret < 0)
6778da6d581SJan Schmidt 		goto out;
6788da6d581SJan Schmidt 
6798da6d581SJan Schmidt 	eb = path->nodes[level];
6809345457fSJan Schmidt 	while (!eb) {
681fae7f21cSDulshani Gunawardhana 		if (WARN_ON(!level)) {
6828da6d581SJan Schmidt 			ret = 1;
6838da6d581SJan Schmidt 			goto out;
6848da6d581SJan Schmidt 		}
6859345457fSJan Schmidt 		level--;
6869345457fSJan Schmidt 		eb = path->nodes[level];
6879345457fSJan Schmidt 	}
6888da6d581SJan Schmidt 
689a2c8d27eSFilipe Manana 	ret = add_all_parents(ctx, root, path, parents, preftrees, ref, level);
6908da6d581SJan Schmidt out:
69100246528SJosef Bacik 	btrfs_put_root(root);
6929326f76fSJosef Bacik out_free:
693da61d31aSJosef Bacik 	path->lowest_level = 0;
694da61d31aSJosef Bacik 	btrfs_release_path(path);
6958da6d581SJan Schmidt 	return ret;
6968da6d581SJan Schmidt }
6978da6d581SJan Schmidt 
6984dae077aSJeff Mahoney static struct extent_inode_elem *
6994dae077aSJeff Mahoney unode_aux_to_inode_list(struct ulist_node *node)
7004dae077aSJeff Mahoney {
7014dae077aSJeff Mahoney 	if (!node)
7024dae077aSJeff Mahoney 		return NULL;
7034dae077aSJeff Mahoney 	return (struct extent_inode_elem *)(uintptr_t)node->aux;
7044dae077aSJeff Mahoney }
7054dae077aSJeff Mahoney 
7065614dc3aSFilipe Manana static void free_leaf_list(struct ulist *ulist)
7075614dc3aSFilipe Manana {
7085614dc3aSFilipe Manana 	struct ulist_node *node;
7095614dc3aSFilipe Manana 	struct ulist_iterator uiter;
7105614dc3aSFilipe Manana 
7115614dc3aSFilipe Manana 	ULIST_ITER_INIT(&uiter);
7125614dc3aSFilipe Manana 	while ((node = ulist_next(ulist, &uiter)))
7135614dc3aSFilipe Manana 		free_inode_elem_list(unode_aux_to_inode_list(node));
7145614dc3aSFilipe Manana 
7155614dc3aSFilipe Manana 	ulist_free(ulist);
7165614dc3aSFilipe Manana }
7175614dc3aSFilipe Manana 
7188da6d581SJan Schmidt /*
71952042d8eSAndrea Gelmini  * We maintain three separate rbtrees: one for direct refs, one for
72086d5f994SEdmund Nadolski  * indirect refs which have a key, and one for indirect refs which do not
72186d5f994SEdmund Nadolski  * have a key. Each tree does merge on insertion.
72286d5f994SEdmund Nadolski  *
72386d5f994SEdmund Nadolski  * Once all of the references are located, we iterate over the tree of
72486d5f994SEdmund Nadolski  * indirect refs with missing keys. An appropriate key is located and
72586d5f994SEdmund Nadolski  * the ref is moved onto the tree for indirect refs. After all missing
72686d5f994SEdmund Nadolski  * keys are thus located, we iterate over the indirect ref tree, resolve
72786d5f994SEdmund Nadolski  * each reference, and then insert the resolved reference onto the
72886d5f994SEdmund Nadolski  * direct tree (merging there too).
72986d5f994SEdmund Nadolski  *
73086d5f994SEdmund Nadolski  * New backrefs (i.e., for parent nodes) are added to the appropriate
73186d5f994SEdmund Nadolski  * rbtree as they are encountered. The new backrefs are subsequently
73286d5f994SEdmund Nadolski  * resolved as above.
7338da6d581SJan Schmidt  */
734a2c8d27eSFilipe Manana static int resolve_indirect_refs(struct btrfs_backref_walk_ctx *ctx,
735a2c8d27eSFilipe Manana 				 struct btrfs_path *path,
73686d5f994SEdmund Nadolski 				 struct preftrees *preftrees,
7376ce6ba53SFilipe Manana 				 struct share_check *sc)
7388da6d581SJan Schmidt {
7398da6d581SJan Schmidt 	int err;
7408da6d581SJan Schmidt 	int ret = 0;
7418da6d581SJan Schmidt 	struct ulist *parents;
7428da6d581SJan Schmidt 	struct ulist_node *node;
743cd1b413cSJan Schmidt 	struct ulist_iterator uiter;
74486d5f994SEdmund Nadolski 	struct rb_node *rnode;
7458da6d581SJan Schmidt 
7468da6d581SJan Schmidt 	parents = ulist_alloc(GFP_NOFS);
7478da6d581SJan Schmidt 	if (!parents)
7488da6d581SJan Schmidt 		return -ENOMEM;
7498da6d581SJan Schmidt 
7508da6d581SJan Schmidt 	/*
75186d5f994SEdmund Nadolski 	 * We could trade memory usage for performance here by iterating
75286d5f994SEdmund Nadolski 	 * the tree, allocating new refs for each insertion, and then
75386d5f994SEdmund Nadolski 	 * freeing the entire indirect tree when we're done.  In some test
75486d5f994SEdmund Nadolski 	 * cases, the tree can grow quite large (~200k objects).
7558da6d581SJan Schmidt 	 */
756ecf160b4SLiu Bo 	while ((rnode = rb_first_cached(&preftrees->indirect.root))) {
75786d5f994SEdmund Nadolski 		struct prelim_ref *ref;
75886d5f994SEdmund Nadolski 
75986d5f994SEdmund Nadolski 		ref = rb_entry(rnode, struct prelim_ref, rbnode);
76086d5f994SEdmund Nadolski 		if (WARN(ref->parent,
76186d5f994SEdmund Nadolski 			 "BUG: direct ref found in indirect tree")) {
76286d5f994SEdmund Nadolski 			ret = -EINVAL;
76386d5f994SEdmund Nadolski 			goto out;
76486d5f994SEdmund Nadolski 		}
76586d5f994SEdmund Nadolski 
766ecf160b4SLiu Bo 		rb_erase_cached(&ref->rbnode, &preftrees->indirect.root);
7676c336b21SJeff Mahoney 		preftrees->indirect.count--;
76886d5f994SEdmund Nadolski 
76986d5f994SEdmund Nadolski 		if (ref->count == 0) {
77086d5f994SEdmund Nadolski 			free_pref(ref);
7718da6d581SJan Schmidt 			continue;
77286d5f994SEdmund Nadolski 		}
77386d5f994SEdmund Nadolski 
774877c1476SFilipe Manana 		if (sc && ref->root_id != sc->root->root_key.objectid) {
77586d5f994SEdmund Nadolski 			free_pref(ref);
776dc046b10SJosef Bacik 			ret = BACKREF_FOUND_SHARED;
777dc046b10SJosef Bacik 			goto out;
778dc046b10SJosef Bacik 		}
779a2c8d27eSFilipe Manana 		err = resolve_indirect_ref(ctx, path, preftrees, ref, parents);
78095def2edSWang Shilong 		/*
78195def2edSWang Shilong 		 * we can only tolerate ENOENT,otherwise,we should catch error
78295def2edSWang Shilong 		 * and return directly.
78395def2edSWang Shilong 		 */
78495def2edSWang Shilong 		if (err == -ENOENT) {
785a2c8d27eSFilipe Manana 			prelim_ref_insert(ctx->fs_info, &preftrees->direct, ref,
7863ec4d323SEdmund Nadolski 					  NULL);
7878da6d581SJan Schmidt 			continue;
78895def2edSWang Shilong 		} else if (err) {
78986d5f994SEdmund Nadolski 			free_pref(ref);
79095def2edSWang Shilong 			ret = err;
79195def2edSWang Shilong 			goto out;
79295def2edSWang Shilong 		}
7938da6d581SJan Schmidt 
7948da6d581SJan Schmidt 		/* we put the first parent into the ref at hand */
795cd1b413cSJan Schmidt 		ULIST_ITER_INIT(&uiter);
796cd1b413cSJan Schmidt 		node = ulist_next(parents, &uiter);
7978da6d581SJan Schmidt 		ref->parent = node ? node->val : 0;
7984dae077aSJeff Mahoney 		ref->inode_list = unode_aux_to_inode_list(node);
7998da6d581SJan Schmidt 
80086d5f994SEdmund Nadolski 		/* Add a prelim_ref(s) for any other parent(s). */
801cd1b413cSJan Schmidt 		while ((node = ulist_next(parents, &uiter))) {
80286d5f994SEdmund Nadolski 			struct prelim_ref *new_ref;
80386d5f994SEdmund Nadolski 
804b9e9a6cbSWang Shilong 			new_ref = kmem_cache_alloc(btrfs_prelim_ref_cache,
805b9e9a6cbSWang Shilong 						   GFP_NOFS);
8068da6d581SJan Schmidt 			if (!new_ref) {
80786d5f994SEdmund Nadolski 				free_pref(ref);
8088da6d581SJan Schmidt 				ret = -ENOMEM;
809e36902d4SWang Shilong 				goto out;
8108da6d581SJan Schmidt 			}
8118da6d581SJan Schmidt 			memcpy(new_ref, ref, sizeof(*ref));
8128da6d581SJan Schmidt 			new_ref->parent = node->val;
8134dae077aSJeff Mahoney 			new_ref->inode_list = unode_aux_to_inode_list(node);
814a2c8d27eSFilipe Manana 			prelim_ref_insert(ctx->fs_info, &preftrees->direct,
8153ec4d323SEdmund Nadolski 					  new_ref, NULL);
8168da6d581SJan Schmidt 		}
81786d5f994SEdmund Nadolski 
8183ec4d323SEdmund Nadolski 		/*
81952042d8eSAndrea Gelmini 		 * Now it's a direct ref, put it in the direct tree. We must
8203ec4d323SEdmund Nadolski 		 * do this last because the ref could be merged/freed here.
8213ec4d323SEdmund Nadolski 		 */
822a2c8d27eSFilipe Manana 		prelim_ref_insert(ctx->fs_info, &preftrees->direct, ref, NULL);
82386d5f994SEdmund Nadolski 
8248da6d581SJan Schmidt 		ulist_reinit(parents);
8259dd14fd6SEdmund Nadolski 		cond_resched();
8268da6d581SJan Schmidt 	}
827e36902d4SWang Shilong out:
8285614dc3aSFilipe Manana 	/*
8295614dc3aSFilipe Manana 	 * We may have inode lists attached to refs in the parents ulist, so we
8305614dc3aSFilipe Manana 	 * must free them before freeing the ulist and its refs.
8315614dc3aSFilipe Manana 	 */
8325614dc3aSFilipe Manana 	free_leaf_list(parents);
8338da6d581SJan Schmidt 	return ret;
8348da6d581SJan Schmidt }
8358da6d581SJan Schmidt 
836d5c88b73SJan Schmidt /*
837d5c88b73SJan Schmidt  * read tree blocks and add keys where required.
838d5c88b73SJan Schmidt  */
839e0c476b1SJeff Mahoney static int add_missing_keys(struct btrfs_fs_info *fs_info,
84038e3eebfSJosef Bacik 			    struct preftrees *preftrees, bool lock)
841d5c88b73SJan Schmidt {
842e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
843d5c88b73SJan Schmidt 	struct extent_buffer *eb;
84486d5f994SEdmund Nadolski 	struct preftree *tree = &preftrees->indirect_missing_keys;
84586d5f994SEdmund Nadolski 	struct rb_node *node;
846d5c88b73SJan Schmidt 
847ecf160b4SLiu Bo 	while ((node = rb_first_cached(&tree->root))) {
848789d6a3aSQu Wenruo 		struct btrfs_tree_parent_check check = { 0 };
849789d6a3aSQu Wenruo 
85086d5f994SEdmund Nadolski 		ref = rb_entry(node, struct prelim_ref, rbnode);
851ecf160b4SLiu Bo 		rb_erase_cached(node, &tree->root);
85286d5f994SEdmund Nadolski 
85386d5f994SEdmund Nadolski 		BUG_ON(ref->parent);	/* should not be a direct ref */
85486d5f994SEdmund Nadolski 		BUG_ON(ref->key_for_search.type);
855d5c88b73SJan Schmidt 		BUG_ON(!ref->wanted_disk_byte);
85686d5f994SEdmund Nadolski 
857789d6a3aSQu Wenruo 		check.level = ref->level - 1;
858789d6a3aSQu Wenruo 		check.owner_root = ref->root_id;
859789d6a3aSQu Wenruo 
860789d6a3aSQu Wenruo 		eb = read_tree_block(fs_info, ref->wanted_disk_byte, &check);
86164c043deSLiu Bo 		if (IS_ERR(eb)) {
86286d5f994SEdmund Nadolski 			free_pref(ref);
86364c043deSLiu Bo 			return PTR_ERR(eb);
8644eb150d6SQu Wenruo 		}
8654eb150d6SQu Wenruo 		if (!extent_buffer_uptodate(eb)) {
86686d5f994SEdmund Nadolski 			free_pref(ref);
867416bc658SJosef Bacik 			free_extent_buffer(eb);
868416bc658SJosef Bacik 			return -EIO;
869416bc658SJosef Bacik 		}
8704eb150d6SQu Wenruo 
87138e3eebfSJosef Bacik 		if (lock)
872d5c88b73SJan Schmidt 			btrfs_tree_read_lock(eb);
873d5c88b73SJan Schmidt 		if (btrfs_header_level(eb) == 0)
874d5c88b73SJan Schmidt 			btrfs_item_key_to_cpu(eb, &ref->key_for_search, 0);
875d5c88b73SJan Schmidt 		else
876d5c88b73SJan Schmidt 			btrfs_node_key_to_cpu(eb, &ref->key_for_search, 0);
87738e3eebfSJosef Bacik 		if (lock)
878d5c88b73SJan Schmidt 			btrfs_tree_read_unlock(eb);
879d5c88b73SJan Schmidt 		free_extent_buffer(eb);
8803ec4d323SEdmund Nadolski 		prelim_ref_insert(fs_info, &preftrees->indirect, ref, NULL);
8819dd14fd6SEdmund Nadolski 		cond_resched();
882d5c88b73SJan Schmidt 	}
883d5c88b73SJan Schmidt 	return 0;
884d5c88b73SJan Schmidt }
885d5c88b73SJan Schmidt 
8868da6d581SJan Schmidt /*
8878da6d581SJan Schmidt  * add all currently queued delayed refs from this head whose seq nr is
8888da6d581SJan Schmidt  * smaller or equal that seq to the list
8898da6d581SJan Schmidt  */
89000142756SJeff Mahoney static int add_delayed_refs(const struct btrfs_fs_info *fs_info,
89100142756SJeff Mahoney 			    struct btrfs_delayed_ref_head *head, u64 seq,
892b25b0b87Sethanwu 			    struct preftrees *preftrees, struct share_check *sc)
8938da6d581SJan Schmidt {
894c6fc2454SQu Wenruo 	struct btrfs_delayed_ref_node *node;
895d5c88b73SJan Schmidt 	struct btrfs_key key;
8960e0adbcfSJosef Bacik 	struct rb_node *n;
89701747e92SEdmund Nadolski 	int count;
898b1375d64SJan Schmidt 	int ret = 0;
8998da6d581SJan Schmidt 
900d7df2c79SJosef Bacik 	spin_lock(&head->lock);
901e3d03965SLiu Bo 	for (n = rb_first_cached(&head->ref_tree); n; n = rb_next(n)) {
9020e0adbcfSJosef Bacik 		node = rb_entry(n, struct btrfs_delayed_ref_node,
9030e0adbcfSJosef Bacik 				ref_node);
9048da6d581SJan Schmidt 		if (node->seq > seq)
9058da6d581SJan Schmidt 			continue;
9068da6d581SJan Schmidt 
9078da6d581SJan Schmidt 		switch (node->action) {
9088da6d581SJan Schmidt 		case BTRFS_ADD_DELAYED_EXTENT:
9098da6d581SJan Schmidt 		case BTRFS_UPDATE_DELAYED_HEAD:
9108da6d581SJan Schmidt 			WARN_ON(1);
9118da6d581SJan Schmidt 			continue;
9128da6d581SJan Schmidt 		case BTRFS_ADD_DELAYED_REF:
91301747e92SEdmund Nadolski 			count = node->ref_mod;
9148da6d581SJan Schmidt 			break;
9158da6d581SJan Schmidt 		case BTRFS_DROP_DELAYED_REF:
91601747e92SEdmund Nadolski 			count = node->ref_mod * -1;
9178da6d581SJan Schmidt 			break;
9188da6d581SJan Schmidt 		default:
919290342f6SArnd Bergmann 			BUG();
9208da6d581SJan Schmidt 		}
9218da6d581SJan Schmidt 		switch (node->type) {
9228da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY: {
92386d5f994SEdmund Nadolski 			/* NORMAL INDIRECT METADATA backref */
9248da6d581SJan Schmidt 			struct btrfs_delayed_tree_ref *ref;
925943553efSFilipe Manana 			struct btrfs_key *key_ptr = NULL;
926943553efSFilipe Manana 
927943553efSFilipe Manana 			if (head->extent_op && head->extent_op->update_key) {
928943553efSFilipe Manana 				btrfs_disk_key_to_cpu(&key, &head->extent_op->key);
929943553efSFilipe Manana 				key_ptr = &key;
930943553efSFilipe Manana 			}
9318da6d581SJan Schmidt 
9328da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_tree_ref(node);
93300142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, ref->root,
934943553efSFilipe Manana 					       key_ptr, ref->level + 1,
93501747e92SEdmund Nadolski 					       node->bytenr, count, sc,
93601747e92SEdmund Nadolski 					       GFP_ATOMIC);
9378da6d581SJan Schmidt 			break;
9388da6d581SJan Schmidt 		}
9398da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY: {
94086d5f994SEdmund Nadolski 			/* SHARED DIRECT METADATA backref */
9418da6d581SJan Schmidt 			struct btrfs_delayed_tree_ref *ref;
9428da6d581SJan Schmidt 
9438da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_tree_ref(node);
94486d5f994SEdmund Nadolski 
94501747e92SEdmund Nadolski 			ret = add_direct_ref(fs_info, preftrees, ref->level + 1,
94601747e92SEdmund Nadolski 					     ref->parent, node->bytenr, count,
9473ec4d323SEdmund Nadolski 					     sc, GFP_ATOMIC);
9488da6d581SJan Schmidt 			break;
9498da6d581SJan Schmidt 		}
9508da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
95186d5f994SEdmund Nadolski 			/* NORMAL INDIRECT DATA backref */
9528da6d581SJan Schmidt 			struct btrfs_delayed_data_ref *ref;
9538da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_data_ref(node);
9548da6d581SJan Schmidt 
9558da6d581SJan Schmidt 			key.objectid = ref->objectid;
9568da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
9578da6d581SJan Schmidt 			key.offset = ref->offset;
958dc046b10SJosef Bacik 
959dc046b10SJosef Bacik 			/*
9604fc7b572SFilipe Manana 			 * If we have a share check context and a reference for
9614fc7b572SFilipe Manana 			 * another inode, we can't exit immediately. This is
9624fc7b572SFilipe Manana 			 * because even if this is a BTRFS_ADD_DELAYED_REF
9634fc7b572SFilipe Manana 			 * reference we may find next a BTRFS_DROP_DELAYED_REF
9644fc7b572SFilipe Manana 			 * which cancels out this ADD reference.
9654fc7b572SFilipe Manana 			 *
9664fc7b572SFilipe Manana 			 * If this is a DROP reference and there was no previous
9674fc7b572SFilipe Manana 			 * ADD reference, then we need to signal that when we
9684fc7b572SFilipe Manana 			 * process references from the extent tree (through
9694fc7b572SFilipe Manana 			 * add_inline_refs() and add_keyed_refs()), we should
9704fc7b572SFilipe Manana 			 * not exit early if we find a reference for another
9714fc7b572SFilipe Manana 			 * inode, because one of the delayed DROP references
9724fc7b572SFilipe Manana 			 * may cancel that reference in the extent tree.
973dc046b10SJosef Bacik 			 */
9744fc7b572SFilipe Manana 			if (sc && count < 0)
9754fc7b572SFilipe Manana 				sc->have_delayed_delete_refs = true;
976dc046b10SJosef Bacik 
97700142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, ref->root,
97801747e92SEdmund Nadolski 					       &key, 0, node->bytenr, count, sc,
97901747e92SEdmund Nadolski 					       GFP_ATOMIC);
9808da6d581SJan Schmidt 			break;
9818da6d581SJan Schmidt 		}
9828da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
98386d5f994SEdmund Nadolski 			/* SHARED DIRECT FULL backref */
9848da6d581SJan Schmidt 			struct btrfs_delayed_data_ref *ref;
9858da6d581SJan Schmidt 
9868da6d581SJan Schmidt 			ref = btrfs_delayed_node_to_data_ref(node);
98786d5f994SEdmund Nadolski 
98801747e92SEdmund Nadolski 			ret = add_direct_ref(fs_info, preftrees, 0, ref->parent,
98901747e92SEdmund Nadolski 					     node->bytenr, count, sc,
99001747e92SEdmund Nadolski 					     GFP_ATOMIC);
9918da6d581SJan Schmidt 			break;
9928da6d581SJan Schmidt 		}
9938da6d581SJan Schmidt 		default:
9948da6d581SJan Schmidt 			WARN_ON(1);
9958da6d581SJan Schmidt 		}
9963ec4d323SEdmund Nadolski 		/*
9973ec4d323SEdmund Nadolski 		 * We must ignore BACKREF_FOUND_SHARED until all delayed
9983ec4d323SEdmund Nadolski 		 * refs have been checked.
9993ec4d323SEdmund Nadolski 		 */
10003ec4d323SEdmund Nadolski 		if (ret && (ret != BACKREF_FOUND_SHARED))
1001d7df2c79SJosef Bacik 			break;
10028da6d581SJan Schmidt 	}
10033ec4d323SEdmund Nadolski 	if (!ret)
10043ec4d323SEdmund Nadolski 		ret = extent_is_shared(sc);
10054fc7b572SFilipe Manana 
1006d7df2c79SJosef Bacik 	spin_unlock(&head->lock);
1007d7df2c79SJosef Bacik 	return ret;
10088da6d581SJan Schmidt }
10098da6d581SJan Schmidt 
10108da6d581SJan Schmidt /*
10118da6d581SJan Schmidt  * add all inline backrefs for bytenr to the list
10123ec4d323SEdmund Nadolski  *
10133ec4d323SEdmund Nadolski  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
10148da6d581SJan Schmidt  */
1015f73853c7SFilipe Manana static int add_inline_refs(struct btrfs_backref_walk_ctx *ctx,
1016f73853c7SFilipe Manana 			   struct btrfs_path *path,
101786d5f994SEdmund Nadolski 			   int *info_level, struct preftrees *preftrees,
1018b25b0b87Sethanwu 			   struct share_check *sc)
10198da6d581SJan Schmidt {
1020b1375d64SJan Schmidt 	int ret = 0;
10218da6d581SJan Schmidt 	int slot;
10228da6d581SJan Schmidt 	struct extent_buffer *leaf;
10238da6d581SJan Schmidt 	struct btrfs_key key;
1024261c84b6SJosef Bacik 	struct btrfs_key found_key;
10258da6d581SJan Schmidt 	unsigned long ptr;
10268da6d581SJan Schmidt 	unsigned long end;
10278da6d581SJan Schmidt 	struct btrfs_extent_item *ei;
10288da6d581SJan Schmidt 	u64 flags;
10298da6d581SJan Schmidt 	u64 item_size;
10308da6d581SJan Schmidt 
10318da6d581SJan Schmidt 	/*
10328da6d581SJan Schmidt 	 * enumerate all inline refs
10338da6d581SJan Schmidt 	 */
10348da6d581SJan Schmidt 	leaf = path->nodes[0];
1035dadcaf78SJan Schmidt 	slot = path->slots[0];
10368da6d581SJan Schmidt 
10373212fa14SJosef Bacik 	item_size = btrfs_item_size(leaf, slot);
10388da6d581SJan Schmidt 	BUG_ON(item_size < sizeof(*ei));
10398da6d581SJan Schmidt 
10408da6d581SJan Schmidt 	ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
1041f73853c7SFilipe Manana 
1042f73853c7SFilipe Manana 	if (ctx->check_extent_item) {
1043f73853c7SFilipe Manana 		ret = ctx->check_extent_item(ctx->bytenr, ei, leaf, ctx->user_ctx);
1044f73853c7SFilipe Manana 		if (ret)
1045f73853c7SFilipe Manana 			return ret;
1046f73853c7SFilipe Manana 	}
1047f73853c7SFilipe Manana 
10488da6d581SJan Schmidt 	flags = btrfs_extent_flags(leaf, ei);
1049261c84b6SJosef Bacik 	btrfs_item_key_to_cpu(leaf, &found_key, slot);
10508da6d581SJan Schmidt 
10518da6d581SJan Schmidt 	ptr = (unsigned long)(ei + 1);
10528da6d581SJan Schmidt 	end = (unsigned long)ei + item_size;
10538da6d581SJan Schmidt 
1054261c84b6SJosef Bacik 	if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
1055261c84b6SJosef Bacik 	    flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
10568da6d581SJan Schmidt 		struct btrfs_tree_block_info *info;
10578da6d581SJan Schmidt 
10588da6d581SJan Schmidt 		info = (struct btrfs_tree_block_info *)ptr;
10598da6d581SJan Schmidt 		*info_level = btrfs_tree_block_level(leaf, info);
10608da6d581SJan Schmidt 		ptr += sizeof(struct btrfs_tree_block_info);
10618da6d581SJan Schmidt 		BUG_ON(ptr > end);
1062261c84b6SJosef Bacik 	} else if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
1063261c84b6SJosef Bacik 		*info_level = found_key.offset;
10648da6d581SJan Schmidt 	} else {
10658da6d581SJan Schmidt 		BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
10668da6d581SJan Schmidt 	}
10678da6d581SJan Schmidt 
10688da6d581SJan Schmidt 	while (ptr < end) {
10698da6d581SJan Schmidt 		struct btrfs_extent_inline_ref *iref;
10708da6d581SJan Schmidt 		u64 offset;
10718da6d581SJan Schmidt 		int type;
10728da6d581SJan Schmidt 
10738da6d581SJan Schmidt 		iref = (struct btrfs_extent_inline_ref *)ptr;
10743de28d57SLiu Bo 		type = btrfs_get_extent_inline_ref_type(leaf, iref,
10753de28d57SLiu Bo 							BTRFS_REF_TYPE_ANY);
10763de28d57SLiu Bo 		if (type == BTRFS_REF_TYPE_INVALID)
1077af431dcbSSu Yue 			return -EUCLEAN;
10783de28d57SLiu Bo 
10798da6d581SJan Schmidt 		offset = btrfs_extent_inline_ref_offset(leaf, iref);
10808da6d581SJan Schmidt 
10818da6d581SJan Schmidt 		switch (type) {
10828da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY:
1083f73853c7SFilipe Manana 			ret = add_direct_ref(ctx->fs_info, preftrees,
108400142756SJeff Mahoney 					     *info_level + 1, offset,
1085f73853c7SFilipe Manana 					     ctx->bytenr, 1, NULL, GFP_NOFS);
10868da6d581SJan Schmidt 			break;
10878da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
10888da6d581SJan Schmidt 			struct btrfs_shared_data_ref *sdref;
10898da6d581SJan Schmidt 			int count;
10908da6d581SJan Schmidt 
10918da6d581SJan Schmidt 			sdref = (struct btrfs_shared_data_ref *)(iref + 1);
10928da6d581SJan Schmidt 			count = btrfs_shared_data_ref_count(leaf, sdref);
109386d5f994SEdmund Nadolski 
1094f73853c7SFilipe Manana 			ret = add_direct_ref(ctx->fs_info, preftrees, 0, offset,
1095f73853c7SFilipe Manana 					     ctx->bytenr, count, sc, GFP_NOFS);
10968da6d581SJan Schmidt 			break;
10978da6d581SJan Schmidt 		}
10988da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY:
1099f73853c7SFilipe Manana 			ret = add_indirect_ref(ctx->fs_info, preftrees, offset,
110000142756SJeff Mahoney 					       NULL, *info_level + 1,
1101f73853c7SFilipe Manana 					       ctx->bytenr, 1, NULL, GFP_NOFS);
11028da6d581SJan Schmidt 			break;
11038da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
11048da6d581SJan Schmidt 			struct btrfs_extent_data_ref *dref;
11058da6d581SJan Schmidt 			int count;
11068da6d581SJan Schmidt 			u64 root;
11078da6d581SJan Schmidt 
11088da6d581SJan Schmidt 			dref = (struct btrfs_extent_data_ref *)(&iref->offset);
11098da6d581SJan Schmidt 			count = btrfs_extent_data_ref_count(leaf, dref);
11108da6d581SJan Schmidt 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
11118da6d581SJan Schmidt 								      dref);
11128da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
11138da6d581SJan Schmidt 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1114dc046b10SJosef Bacik 
1115a0a5472aSFilipe Manana 			if (sc && key.objectid != sc->inum &&
11164fc7b572SFilipe Manana 			    !sc->have_delayed_delete_refs) {
1117dc046b10SJosef Bacik 				ret = BACKREF_FOUND_SHARED;
1118dc046b10SJosef Bacik 				break;
1119dc046b10SJosef Bacik 			}
1120dc046b10SJosef Bacik 
11218da6d581SJan Schmidt 			root = btrfs_extent_data_ref_root(leaf, dref);
112286d5f994SEdmund Nadolski 
1123adf02418SFilipe Manana 			if (!ctx->skip_data_ref ||
1124adf02418SFilipe Manana 			    !ctx->skip_data_ref(root, key.objectid, key.offset,
1125adf02418SFilipe Manana 						ctx->user_ctx))
1126adf02418SFilipe Manana 				ret = add_indirect_ref(ctx->fs_info, preftrees,
1127adf02418SFilipe Manana 						       root, &key, 0, ctx->bytenr,
1128adf02418SFilipe Manana 						       count, sc, GFP_NOFS);
11298da6d581SJan Schmidt 			break;
11308da6d581SJan Schmidt 		}
11318da6d581SJan Schmidt 		default:
11328da6d581SJan Schmidt 			WARN_ON(1);
11338da6d581SJan Schmidt 		}
11341149ab6bSWang Shilong 		if (ret)
11351149ab6bSWang Shilong 			return ret;
11368da6d581SJan Schmidt 		ptr += btrfs_extent_inline_ref_size(type);
11378da6d581SJan Schmidt 	}
11388da6d581SJan Schmidt 
11398da6d581SJan Schmidt 	return 0;
11408da6d581SJan Schmidt }
11418da6d581SJan Schmidt 
11428da6d581SJan Schmidt /*
11438da6d581SJan Schmidt  * add all non-inline backrefs for bytenr to the list
11443ec4d323SEdmund Nadolski  *
11453ec4d323SEdmund Nadolski  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
11468da6d581SJan Schmidt  */
1147adf02418SFilipe Manana static int add_keyed_refs(struct btrfs_backref_walk_ctx *ctx,
1148adf02418SFilipe Manana 			  struct btrfs_root *extent_root,
1149adf02418SFilipe Manana 			  struct btrfs_path *path,
115086d5f994SEdmund Nadolski 			  int info_level, struct preftrees *preftrees,
11513ec4d323SEdmund Nadolski 			  struct share_check *sc)
11528da6d581SJan Schmidt {
115398cc4222SJosef Bacik 	struct btrfs_fs_info *fs_info = extent_root->fs_info;
11548da6d581SJan Schmidt 	int ret;
11558da6d581SJan Schmidt 	int slot;
11568da6d581SJan Schmidt 	struct extent_buffer *leaf;
11578da6d581SJan Schmidt 	struct btrfs_key key;
11588da6d581SJan Schmidt 
11598da6d581SJan Schmidt 	while (1) {
11608da6d581SJan Schmidt 		ret = btrfs_next_item(extent_root, path);
11618da6d581SJan Schmidt 		if (ret < 0)
11628da6d581SJan Schmidt 			break;
11638da6d581SJan Schmidt 		if (ret) {
11648da6d581SJan Schmidt 			ret = 0;
11658da6d581SJan Schmidt 			break;
11668da6d581SJan Schmidt 		}
11678da6d581SJan Schmidt 
11688da6d581SJan Schmidt 		slot = path->slots[0];
11698da6d581SJan Schmidt 		leaf = path->nodes[0];
11708da6d581SJan Schmidt 		btrfs_item_key_to_cpu(leaf, &key, slot);
11718da6d581SJan Schmidt 
1172adf02418SFilipe Manana 		if (key.objectid != ctx->bytenr)
11738da6d581SJan Schmidt 			break;
11748da6d581SJan Schmidt 		if (key.type < BTRFS_TREE_BLOCK_REF_KEY)
11758da6d581SJan Schmidt 			continue;
11768da6d581SJan Schmidt 		if (key.type > BTRFS_SHARED_DATA_REF_KEY)
11778da6d581SJan Schmidt 			break;
11788da6d581SJan Schmidt 
11798da6d581SJan Schmidt 		switch (key.type) {
11808da6d581SJan Schmidt 		case BTRFS_SHARED_BLOCK_REF_KEY:
118186d5f994SEdmund Nadolski 			/* SHARED DIRECT METADATA backref */
118200142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees,
118300142756SJeff Mahoney 					     info_level + 1, key.offset,
1184adf02418SFilipe Manana 					     ctx->bytenr, 1, NULL, GFP_NOFS);
11858da6d581SJan Schmidt 			break;
11868da6d581SJan Schmidt 		case BTRFS_SHARED_DATA_REF_KEY: {
118786d5f994SEdmund Nadolski 			/* SHARED DIRECT FULL backref */
11888da6d581SJan Schmidt 			struct btrfs_shared_data_ref *sdref;
11898da6d581SJan Schmidt 			int count;
11908da6d581SJan Schmidt 
11918da6d581SJan Schmidt 			sdref = btrfs_item_ptr(leaf, slot,
11928da6d581SJan Schmidt 					      struct btrfs_shared_data_ref);
11938da6d581SJan Schmidt 			count = btrfs_shared_data_ref_count(leaf, sdref);
119400142756SJeff Mahoney 			ret = add_direct_ref(fs_info, preftrees, 0,
1195adf02418SFilipe Manana 					     key.offset, ctx->bytenr, count,
11963ec4d323SEdmund Nadolski 					     sc, GFP_NOFS);
11978da6d581SJan Schmidt 			break;
11988da6d581SJan Schmidt 		}
11998da6d581SJan Schmidt 		case BTRFS_TREE_BLOCK_REF_KEY:
120086d5f994SEdmund Nadolski 			/* NORMAL INDIRECT METADATA backref */
120100142756SJeff Mahoney 			ret = add_indirect_ref(fs_info, preftrees, key.offset,
1202adf02418SFilipe Manana 					       NULL, info_level + 1, ctx->bytenr,
12033ec4d323SEdmund Nadolski 					       1, NULL, GFP_NOFS);
12048da6d581SJan Schmidt 			break;
12058da6d581SJan Schmidt 		case BTRFS_EXTENT_DATA_REF_KEY: {
120686d5f994SEdmund Nadolski 			/* NORMAL INDIRECT DATA backref */
12078da6d581SJan Schmidt 			struct btrfs_extent_data_ref *dref;
12088da6d581SJan Schmidt 			int count;
12098da6d581SJan Schmidt 			u64 root;
12108da6d581SJan Schmidt 
12118da6d581SJan Schmidt 			dref = btrfs_item_ptr(leaf, slot,
12128da6d581SJan Schmidt 					      struct btrfs_extent_data_ref);
12138da6d581SJan Schmidt 			count = btrfs_extent_data_ref_count(leaf, dref);
12148da6d581SJan Schmidt 			key.objectid = btrfs_extent_data_ref_objectid(leaf,
12158da6d581SJan Schmidt 								      dref);
12168da6d581SJan Schmidt 			key.type = BTRFS_EXTENT_DATA_KEY;
12178da6d581SJan Schmidt 			key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1218dc046b10SJosef Bacik 
1219a0a5472aSFilipe Manana 			if (sc && key.objectid != sc->inum &&
12204fc7b572SFilipe Manana 			    !sc->have_delayed_delete_refs) {
1221dc046b10SJosef Bacik 				ret = BACKREF_FOUND_SHARED;
1222dc046b10SJosef Bacik 				break;
1223dc046b10SJosef Bacik 			}
1224dc046b10SJosef Bacik 
12258da6d581SJan Schmidt 			root = btrfs_extent_data_ref_root(leaf, dref);
1226adf02418SFilipe Manana 
1227adf02418SFilipe Manana 			if (!ctx->skip_data_ref ||
1228adf02418SFilipe Manana 			    !ctx->skip_data_ref(root, key.objectid, key.offset,
1229adf02418SFilipe Manana 						ctx->user_ctx))
123000142756SJeff Mahoney 				ret = add_indirect_ref(fs_info, preftrees, root,
1231adf02418SFilipe Manana 						       &key, 0, ctx->bytenr,
1232adf02418SFilipe Manana 						       count, sc, GFP_NOFS);
12338da6d581SJan Schmidt 			break;
12348da6d581SJan Schmidt 		}
12358da6d581SJan Schmidt 		default:
12368da6d581SJan Schmidt 			WARN_ON(1);
12378da6d581SJan Schmidt 		}
12381149ab6bSWang Shilong 		if (ret)
12391149ab6bSWang Shilong 			return ret;
12401149ab6bSWang Shilong 
12418da6d581SJan Schmidt 	}
12428da6d581SJan Schmidt 
12438da6d581SJan Schmidt 	return ret;
12448da6d581SJan Schmidt }
12458da6d581SJan Schmidt 
12468da6d581SJan Schmidt /*
1247583f4ac5SFilipe Manana  * The caller has joined a transaction or is holding a read lock on the
1248583f4ac5SFilipe Manana  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1249583f4ac5SFilipe Manana  * snapshot field changing while updating or checking the cache.
1250583f4ac5SFilipe Manana  */
1251583f4ac5SFilipe Manana static bool lookup_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1252583f4ac5SFilipe Manana 					struct btrfs_root *root,
1253583f4ac5SFilipe Manana 					u64 bytenr, int level, bool *is_shared)
1254583f4ac5SFilipe Manana {
12554e4488d4SFilipe Manana 	const struct btrfs_fs_info *fs_info = root->fs_info;
1256583f4ac5SFilipe Manana 	struct btrfs_backref_shared_cache_entry *entry;
1257583f4ac5SFilipe Manana 
12584e4488d4SFilipe Manana 	if (!current->journal_info)
12594e4488d4SFilipe Manana 		lockdep_assert_held(&fs_info->commit_root_sem);
12604e4488d4SFilipe Manana 
1261583f4ac5SFilipe Manana 	if (!ctx->use_path_cache)
1262583f4ac5SFilipe Manana 		return false;
1263583f4ac5SFilipe Manana 
1264583f4ac5SFilipe Manana 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1265583f4ac5SFilipe Manana 		return false;
1266583f4ac5SFilipe Manana 
1267583f4ac5SFilipe Manana 	/*
1268583f4ac5SFilipe Manana 	 * Level -1 is used for the data extent, which is not reliable to cache
1269583f4ac5SFilipe Manana 	 * because its reference count can increase or decrease without us
1270583f4ac5SFilipe Manana 	 * realizing. We cache results only for extent buffers that lead from
1271583f4ac5SFilipe Manana 	 * the root node down to the leaf with the file extent item.
1272583f4ac5SFilipe Manana 	 */
1273583f4ac5SFilipe Manana 	ASSERT(level >= 0);
1274583f4ac5SFilipe Manana 
1275583f4ac5SFilipe Manana 	entry = &ctx->path_cache_entries[level];
1276583f4ac5SFilipe Manana 
1277583f4ac5SFilipe Manana 	/* Unused cache entry or being used for some other extent buffer. */
1278583f4ac5SFilipe Manana 	if (entry->bytenr != bytenr)
1279583f4ac5SFilipe Manana 		return false;
1280583f4ac5SFilipe Manana 
1281583f4ac5SFilipe Manana 	/*
1282583f4ac5SFilipe Manana 	 * We cached a false result, but the last snapshot generation of the
1283583f4ac5SFilipe Manana 	 * root changed, so we now have a snapshot. Don't trust the result.
1284583f4ac5SFilipe Manana 	 */
1285583f4ac5SFilipe Manana 	if (!entry->is_shared &&
1286583f4ac5SFilipe Manana 	    entry->gen != btrfs_root_last_snapshot(&root->root_item))
1287583f4ac5SFilipe Manana 		return false;
1288583f4ac5SFilipe Manana 
1289583f4ac5SFilipe Manana 	/*
1290583f4ac5SFilipe Manana 	 * If we cached a true result and the last generation used for dropping
1291583f4ac5SFilipe Manana 	 * a root changed, we can not trust the result, because the dropped root
1292583f4ac5SFilipe Manana 	 * could be a snapshot sharing this extent buffer.
1293583f4ac5SFilipe Manana 	 */
1294583f4ac5SFilipe Manana 	if (entry->is_shared &&
12954e4488d4SFilipe Manana 	    entry->gen != btrfs_get_last_root_drop_gen(fs_info))
1296583f4ac5SFilipe Manana 		return false;
1297583f4ac5SFilipe Manana 
1298583f4ac5SFilipe Manana 	*is_shared = entry->is_shared;
1299583f4ac5SFilipe Manana 	/*
1300583f4ac5SFilipe Manana 	 * If the node at this level is shared, than all nodes below are also
1301583f4ac5SFilipe Manana 	 * shared. Currently some of the nodes below may be marked as not shared
1302583f4ac5SFilipe Manana 	 * because we have just switched from one leaf to another, and switched
1303583f4ac5SFilipe Manana 	 * also other nodes above the leaf and below the current level, so mark
1304583f4ac5SFilipe Manana 	 * them as shared.
1305583f4ac5SFilipe Manana 	 */
1306583f4ac5SFilipe Manana 	if (*is_shared) {
1307583f4ac5SFilipe Manana 		for (int i = 0; i < level; i++) {
1308583f4ac5SFilipe Manana 			ctx->path_cache_entries[i].is_shared = true;
1309583f4ac5SFilipe Manana 			ctx->path_cache_entries[i].gen = entry->gen;
1310583f4ac5SFilipe Manana 		}
1311583f4ac5SFilipe Manana 	}
1312583f4ac5SFilipe Manana 
1313583f4ac5SFilipe Manana 	return true;
1314583f4ac5SFilipe Manana }
1315583f4ac5SFilipe Manana 
1316583f4ac5SFilipe Manana /*
1317583f4ac5SFilipe Manana  * The caller has joined a transaction or is holding a read lock on the
1318583f4ac5SFilipe Manana  * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1319583f4ac5SFilipe Manana  * snapshot field changing while updating or checking the cache.
1320583f4ac5SFilipe Manana  */
1321583f4ac5SFilipe Manana static void store_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1322583f4ac5SFilipe Manana 				       struct btrfs_root *root,
1323583f4ac5SFilipe Manana 				       u64 bytenr, int level, bool is_shared)
1324583f4ac5SFilipe Manana {
13254e4488d4SFilipe Manana 	const struct btrfs_fs_info *fs_info = root->fs_info;
1326583f4ac5SFilipe Manana 	struct btrfs_backref_shared_cache_entry *entry;
1327583f4ac5SFilipe Manana 	u64 gen;
1328583f4ac5SFilipe Manana 
13294e4488d4SFilipe Manana 	if (!current->journal_info)
13304e4488d4SFilipe Manana 		lockdep_assert_held(&fs_info->commit_root_sem);
13314e4488d4SFilipe Manana 
1332583f4ac5SFilipe Manana 	if (!ctx->use_path_cache)
1333583f4ac5SFilipe Manana 		return;
1334583f4ac5SFilipe Manana 
1335583f4ac5SFilipe Manana 	if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1336583f4ac5SFilipe Manana 		return;
1337583f4ac5SFilipe Manana 
1338583f4ac5SFilipe Manana 	/*
1339583f4ac5SFilipe Manana 	 * Level -1 is used for the data extent, which is not reliable to cache
1340583f4ac5SFilipe Manana 	 * because its reference count can increase or decrease without us
1341583f4ac5SFilipe Manana 	 * realizing. We cache results only for extent buffers that lead from
1342583f4ac5SFilipe Manana 	 * the root node down to the leaf with the file extent item.
1343583f4ac5SFilipe Manana 	 */
1344583f4ac5SFilipe Manana 	ASSERT(level >= 0);
1345583f4ac5SFilipe Manana 
1346583f4ac5SFilipe Manana 	if (is_shared)
13474e4488d4SFilipe Manana 		gen = btrfs_get_last_root_drop_gen(fs_info);
1348583f4ac5SFilipe Manana 	else
1349583f4ac5SFilipe Manana 		gen = btrfs_root_last_snapshot(&root->root_item);
1350583f4ac5SFilipe Manana 
1351583f4ac5SFilipe Manana 	entry = &ctx->path_cache_entries[level];
1352583f4ac5SFilipe Manana 	entry->bytenr = bytenr;
1353583f4ac5SFilipe Manana 	entry->is_shared = is_shared;
1354583f4ac5SFilipe Manana 	entry->gen = gen;
1355583f4ac5SFilipe Manana 
1356583f4ac5SFilipe Manana 	/*
1357583f4ac5SFilipe Manana 	 * If we found an extent buffer is shared, set the cache result for all
1358583f4ac5SFilipe Manana 	 * extent buffers below it to true. As nodes in the path are COWed,
1359583f4ac5SFilipe Manana 	 * their sharedness is moved to their children, and if a leaf is COWed,
1360583f4ac5SFilipe Manana 	 * then the sharedness of a data extent becomes direct, the refcount of
1361583f4ac5SFilipe Manana 	 * data extent is increased in the extent item at the extent tree.
1362583f4ac5SFilipe Manana 	 */
1363583f4ac5SFilipe Manana 	if (is_shared) {
1364583f4ac5SFilipe Manana 		for (int i = 0; i < level; i++) {
1365583f4ac5SFilipe Manana 			entry = &ctx->path_cache_entries[i];
1366583f4ac5SFilipe Manana 			entry->is_shared = is_shared;
1367583f4ac5SFilipe Manana 			entry->gen = gen;
1368583f4ac5SFilipe Manana 		}
1369583f4ac5SFilipe Manana 	}
1370583f4ac5SFilipe Manana }
1371583f4ac5SFilipe Manana 
1372583f4ac5SFilipe Manana /*
13738da6d581SJan Schmidt  * this adds all existing backrefs (inline backrefs, backrefs and delayed
13748da6d581SJan Schmidt  * refs) for the given bytenr to the refs list, merges duplicates and resolves
13758da6d581SJan Schmidt  * indirect refs to their parent bytenr.
13768da6d581SJan Schmidt  * When roots are found, they're added to the roots list
13778da6d581SJan Schmidt  *
1378a2c8d27eSFilipe Manana  * @ctx:     Backref walking context object, must be not NULL.
1379a2c8d27eSFilipe Manana  * @sc:      If !NULL, then immediately return BACKREF_FOUND_SHARED when a
13803ec4d323SEdmund Nadolski  *           shared extent is detected.
13813ec4d323SEdmund Nadolski  *
13823ec4d323SEdmund Nadolski  * Otherwise this returns 0 for success and <0 for an error.
13833ec4d323SEdmund Nadolski  *
13848da6d581SJan Schmidt  * FIXME some caching might speed things up
13858da6d581SJan Schmidt  */
1386a2c8d27eSFilipe Manana static int find_parent_nodes(struct btrfs_backref_walk_ctx *ctx,
13876ce6ba53SFilipe Manana 			     struct share_check *sc)
13888da6d581SJan Schmidt {
1389a2c8d27eSFilipe Manana 	struct btrfs_root *root = btrfs_extent_root(ctx->fs_info, ctx->bytenr);
13908da6d581SJan Schmidt 	struct btrfs_key key;
13918da6d581SJan Schmidt 	struct btrfs_path *path;
13928da6d581SJan Schmidt 	struct btrfs_delayed_ref_root *delayed_refs = NULL;
1393d3b01064SLi Zefan 	struct btrfs_delayed_ref_head *head;
13948da6d581SJan Schmidt 	int info_level = 0;
13958da6d581SJan Schmidt 	int ret;
1396e0c476b1SJeff Mahoney 	struct prelim_ref *ref;
139786d5f994SEdmund Nadolski 	struct rb_node *node;
1398f05c4746SWang Shilong 	struct extent_inode_elem *eie = NULL;
139986d5f994SEdmund Nadolski 	struct preftrees preftrees = {
140086d5f994SEdmund Nadolski 		.direct = PREFTREE_INIT,
140186d5f994SEdmund Nadolski 		.indirect = PREFTREE_INIT,
140286d5f994SEdmund Nadolski 		.indirect_missing_keys = PREFTREE_INIT
140386d5f994SEdmund Nadolski 	};
14048da6d581SJan Schmidt 
140556f5c199SFilipe Manana 	/* Roots ulist is not needed when using a sharedness check context. */
140656f5c199SFilipe Manana 	if (sc)
1407a2c8d27eSFilipe Manana 		ASSERT(ctx->roots == NULL);
140856f5c199SFilipe Manana 
1409a2c8d27eSFilipe Manana 	key.objectid = ctx->bytenr;
14108da6d581SJan Schmidt 	key.offset = (u64)-1;
1411a2c8d27eSFilipe Manana 	if (btrfs_fs_incompat(ctx->fs_info, SKINNY_METADATA))
1412261c84b6SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
1413261c84b6SJosef Bacik 	else
1414261c84b6SJosef Bacik 		key.type = BTRFS_EXTENT_ITEM_KEY;
14158da6d581SJan Schmidt 
14168da6d581SJan Schmidt 	path = btrfs_alloc_path();
14178da6d581SJan Schmidt 	if (!path)
14188da6d581SJan Schmidt 		return -ENOMEM;
1419a2c8d27eSFilipe Manana 	if (!ctx->trans) {
1420da61d31aSJosef Bacik 		path->search_commit_root = 1;
1421e84752d4SWang Shilong 		path->skip_locking = 1;
1422e84752d4SWang Shilong 	}
14238da6d581SJan Schmidt 
1424a2c8d27eSFilipe Manana 	if (ctx->time_seq == BTRFS_SEQ_LAST)
142521633fc6SQu Wenruo 		path->skip_locking = 1;
142621633fc6SQu Wenruo 
14278da6d581SJan Schmidt again:
1428d3b01064SLi Zefan 	head = NULL;
1429d3b01064SLi Zefan 
143098cc4222SJosef Bacik 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
14318da6d581SJan Schmidt 	if (ret < 0)
14328da6d581SJan Schmidt 		goto out;
1433fcba0120SJosef Bacik 	if (ret == 0) {
1434fcba0120SJosef Bacik 		/* This shouldn't happen, indicates a bug or fs corruption. */
1435fcba0120SJosef Bacik 		ASSERT(ret != 0);
1436fcba0120SJosef Bacik 		ret = -EUCLEAN;
1437fcba0120SJosef Bacik 		goto out;
1438fcba0120SJosef Bacik 	}
14398da6d581SJan Schmidt 
1440a2c8d27eSFilipe Manana 	if (ctx->trans && likely(ctx->trans->type != __TRANS_DUMMY) &&
1441a2c8d27eSFilipe Manana 	    ctx->time_seq != BTRFS_SEQ_LAST) {
14428da6d581SJan Schmidt 		/*
14439665ebd5SJosef Bacik 		 * We have a specific time_seq we care about and trans which
14449665ebd5SJosef Bacik 		 * means we have the path lock, we need to grab the ref head and
14459665ebd5SJosef Bacik 		 * lock it so we have a consistent view of the refs at the given
14469665ebd5SJosef Bacik 		 * time.
14478da6d581SJan Schmidt 		 */
1448a2c8d27eSFilipe Manana 		delayed_refs = &ctx->trans->transaction->delayed_refs;
14498da6d581SJan Schmidt 		spin_lock(&delayed_refs->lock);
1450a2c8d27eSFilipe Manana 		head = btrfs_find_delayed_ref_head(delayed_refs, ctx->bytenr);
14518da6d581SJan Schmidt 		if (head) {
14528da6d581SJan Schmidt 			if (!mutex_trylock(&head->mutex)) {
1453d278850eSJosef Bacik 				refcount_inc(&head->refs);
14548da6d581SJan Schmidt 				spin_unlock(&delayed_refs->lock);
14558da6d581SJan Schmidt 
14568da6d581SJan Schmidt 				btrfs_release_path(path);
14578da6d581SJan Schmidt 
14588da6d581SJan Schmidt 				/*
14598da6d581SJan Schmidt 				 * Mutex was contended, block until it's
14608da6d581SJan Schmidt 				 * released and try again
14618da6d581SJan Schmidt 				 */
14628da6d581SJan Schmidt 				mutex_lock(&head->mutex);
14638da6d581SJan Schmidt 				mutex_unlock(&head->mutex);
1464d278850eSJosef Bacik 				btrfs_put_delayed_ref_head(head);
14658da6d581SJan Schmidt 				goto again;
14668da6d581SJan Schmidt 			}
1467d7df2c79SJosef Bacik 			spin_unlock(&delayed_refs->lock);
1468a2c8d27eSFilipe Manana 			ret = add_delayed_refs(ctx->fs_info, head, ctx->time_seq,
1469b25b0b87Sethanwu 					       &preftrees, sc);
1470155725c9SJan Schmidt 			mutex_unlock(&head->mutex);
1471d7df2c79SJosef Bacik 			if (ret)
14728da6d581SJan Schmidt 				goto out;
1473d7df2c79SJosef Bacik 		} else {
14748da6d581SJan Schmidt 			spin_unlock(&delayed_refs->lock);
14757a3ae2f8SJan Schmidt 		}
1476d7df2c79SJosef Bacik 	}
14778da6d581SJan Schmidt 
14788da6d581SJan Schmidt 	if (path->slots[0]) {
14798da6d581SJan Schmidt 		struct extent_buffer *leaf;
14808da6d581SJan Schmidt 		int slot;
14818da6d581SJan Schmidt 
1482dadcaf78SJan Schmidt 		path->slots[0]--;
14838da6d581SJan Schmidt 		leaf = path->nodes[0];
1484dadcaf78SJan Schmidt 		slot = path->slots[0];
14858da6d581SJan Schmidt 		btrfs_item_key_to_cpu(leaf, &key, slot);
1486a2c8d27eSFilipe Manana 		if (key.objectid == ctx->bytenr &&
1487261c84b6SJosef Bacik 		    (key.type == BTRFS_EXTENT_ITEM_KEY ||
1488261c84b6SJosef Bacik 		     key.type == BTRFS_METADATA_ITEM_KEY)) {
1489f73853c7SFilipe Manana 			ret = add_inline_refs(ctx, path, &info_level,
1490f73853c7SFilipe Manana 					      &preftrees, sc);
14918da6d581SJan Schmidt 			if (ret)
14928da6d581SJan Schmidt 				goto out;
1493adf02418SFilipe Manana 			ret = add_keyed_refs(ctx, root, path, info_level,
14943ec4d323SEdmund Nadolski 					     &preftrees, sc);
14958da6d581SJan Schmidt 			if (ret)
14968da6d581SJan Schmidt 				goto out;
14978da6d581SJan Schmidt 		}
14988da6d581SJan Schmidt 	}
149986d5f994SEdmund Nadolski 
150056f5c199SFilipe Manana 	/*
150156f5c199SFilipe Manana 	 * If we have a share context and we reached here, it means the extent
150256f5c199SFilipe Manana 	 * is not directly shared (no multiple reference items for it),
150356f5c199SFilipe Manana 	 * otherwise we would have exited earlier with a return value of
150456f5c199SFilipe Manana 	 * BACKREF_FOUND_SHARED after processing delayed references or while
150556f5c199SFilipe Manana 	 * processing inline or keyed references from the extent tree.
150656f5c199SFilipe Manana 	 * The extent may however be indirectly shared through shared subtrees
150756f5c199SFilipe Manana 	 * as a result from creating snapshots, so we determine below what is
150856f5c199SFilipe Manana 	 * its parent node, in case we are dealing with a metadata extent, or
150956f5c199SFilipe Manana 	 * what's the leaf (or leaves), from a fs tree, that has a file extent
151056f5c199SFilipe Manana 	 * item pointing to it in case we are dealing with a data extent.
151156f5c199SFilipe Manana 	 */
151256f5c199SFilipe Manana 	ASSERT(extent_is_shared(sc) == 0);
151356f5c199SFilipe Manana 
1514877c1476SFilipe Manana 	/*
1515877c1476SFilipe Manana 	 * If we are here for a data extent and we have a share_check structure
1516877c1476SFilipe Manana 	 * it means the data extent is not directly shared (does not have
1517877c1476SFilipe Manana 	 * multiple reference items), so we have to check if a path in the fs
1518877c1476SFilipe Manana 	 * tree (going from the root node down to the leaf that has the file
1519877c1476SFilipe Manana 	 * extent item pointing to the data extent) is shared, that is, if any
1520877c1476SFilipe Manana 	 * of the extent buffers in the path is referenced by other trees.
1521877c1476SFilipe Manana 	 */
1522a2c8d27eSFilipe Manana 	if (sc && ctx->bytenr == sc->data_bytenr) {
1523877c1476SFilipe Manana 		/*
15246976201fSFilipe Manana 		 * If our data extent is from a generation more recent than the
15256976201fSFilipe Manana 		 * last generation used to snapshot the root, then we know that
15266976201fSFilipe Manana 		 * it can not be shared through subtrees, so we can skip
15276976201fSFilipe Manana 		 * resolving indirect references, there's no point in
15286976201fSFilipe Manana 		 * determining the extent buffers for the path from the fs tree
15296976201fSFilipe Manana 		 * root node down to the leaf that has the file extent item that
15306976201fSFilipe Manana 		 * points to the data extent.
15316976201fSFilipe Manana 		 */
15326976201fSFilipe Manana 		if (sc->data_extent_gen >
15336976201fSFilipe Manana 		    btrfs_root_last_snapshot(&sc->root->root_item)) {
15346976201fSFilipe Manana 			ret = BACKREF_FOUND_NOT_SHARED;
15356976201fSFilipe Manana 			goto out;
15366976201fSFilipe Manana 		}
15376976201fSFilipe Manana 
15386976201fSFilipe Manana 		/*
1539877c1476SFilipe Manana 		 * If we are only determining if a data extent is shared or not
1540877c1476SFilipe Manana 		 * and the corresponding file extent item is located in the same
1541877c1476SFilipe Manana 		 * leaf as the previous file extent item, we can skip resolving
1542877c1476SFilipe Manana 		 * indirect references for a data extent, since the fs tree path
1543877c1476SFilipe Manana 		 * is the same (same leaf, so same path). We skip as long as the
1544877c1476SFilipe Manana 		 * cached result for the leaf is valid and only if there's only
1545877c1476SFilipe Manana 		 * one file extent item pointing to the data extent, because in
1546877c1476SFilipe Manana 		 * the case of multiple file extent items, they may be located
1547877c1476SFilipe Manana 		 * in different leaves and therefore we have multiple paths.
1548877c1476SFilipe Manana 		 */
1549877c1476SFilipe Manana 		if (sc->ctx->curr_leaf_bytenr == sc->ctx->prev_leaf_bytenr &&
1550877c1476SFilipe Manana 		    sc->self_ref_count == 1) {
1551877c1476SFilipe Manana 			bool cached;
1552877c1476SFilipe Manana 			bool is_shared;
1553877c1476SFilipe Manana 
1554877c1476SFilipe Manana 			cached = lookup_backref_shared_cache(sc->ctx, sc->root,
1555877c1476SFilipe Manana 						     sc->ctx->curr_leaf_bytenr,
1556877c1476SFilipe Manana 						     0, &is_shared);
1557877c1476SFilipe Manana 			if (cached) {
1558877c1476SFilipe Manana 				if (is_shared)
1559877c1476SFilipe Manana 					ret = BACKREF_FOUND_SHARED;
1560877c1476SFilipe Manana 				else
1561877c1476SFilipe Manana 					ret = BACKREF_FOUND_NOT_SHARED;
1562877c1476SFilipe Manana 				goto out;
1563877c1476SFilipe Manana 			}
1564877c1476SFilipe Manana 		}
1565877c1476SFilipe Manana 	}
1566877c1476SFilipe Manana 
15678da6d581SJan Schmidt 	btrfs_release_path(path);
15688da6d581SJan Schmidt 
1569a2c8d27eSFilipe Manana 	ret = add_missing_keys(ctx->fs_info, &preftrees, path->skip_locking == 0);
1570d5c88b73SJan Schmidt 	if (ret)
1571d5c88b73SJan Schmidt 		goto out;
1572d5c88b73SJan Schmidt 
1573ecf160b4SLiu Bo 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect_missing_keys.root.rb_root));
15748da6d581SJan Schmidt 
1575a2c8d27eSFilipe Manana 	ret = resolve_indirect_refs(ctx, path, &preftrees, sc);
15768da6d581SJan Schmidt 	if (ret)
15778da6d581SJan Schmidt 		goto out;
15788da6d581SJan Schmidt 
1579ecf160b4SLiu Bo 	WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect.root.rb_root));
15808da6d581SJan Schmidt 
158186d5f994SEdmund Nadolski 	/*
158286d5f994SEdmund Nadolski 	 * This walks the tree of merged and resolved refs. Tree blocks are
158386d5f994SEdmund Nadolski 	 * read in as needed. Unique entries are added to the ulist, and
158486d5f994SEdmund Nadolski 	 * the list of found roots is updated.
158586d5f994SEdmund Nadolski 	 *
158686d5f994SEdmund Nadolski 	 * We release the entire tree in one go before returning.
158786d5f994SEdmund Nadolski 	 */
1588ecf160b4SLiu Bo 	node = rb_first_cached(&preftrees.direct.root);
158986d5f994SEdmund Nadolski 	while (node) {
159086d5f994SEdmund Nadolski 		ref = rb_entry(node, struct prelim_ref, rbnode);
159186d5f994SEdmund Nadolski 		node = rb_next(&ref->rbnode);
1592c8195a7bSZygo Blaxell 		/*
1593c8195a7bSZygo Blaxell 		 * ref->count < 0 can happen here if there are delayed
1594c8195a7bSZygo Blaxell 		 * refs with a node->action of BTRFS_DROP_DELAYED_REF.
1595c8195a7bSZygo Blaxell 		 * prelim_ref_insert() relies on this when merging
1596c8195a7bSZygo Blaxell 		 * identical refs to keep the overall count correct.
1597c8195a7bSZygo Blaxell 		 * prelim_ref_insert() will merge only those refs
1598c8195a7bSZygo Blaxell 		 * which compare identically.  Any refs having
1599c8195a7bSZygo Blaxell 		 * e.g. different offsets would not be merged,
1600c8195a7bSZygo Blaxell 		 * and would retain their original ref->count < 0.
1601c8195a7bSZygo Blaxell 		 */
1602a2c8d27eSFilipe Manana 		if (ctx->roots && ref->count && ref->root_id && ref->parent == 0) {
16038da6d581SJan Schmidt 			/* no parent == root of tree */
1604a2c8d27eSFilipe Manana 			ret = ulist_add(ctx->roots, ref->root_id, 0, GFP_NOFS);
1605f1723939SWang Shilong 			if (ret < 0)
1606f1723939SWang Shilong 				goto out;
16078da6d581SJan Schmidt 		}
16088da6d581SJan Schmidt 		if (ref->count && ref->parent) {
1609a2c8d27eSFilipe Manana 			if (!ctx->ignore_extent_item_pos && !ref->inode_list &&
1610a2c8d27eSFilipe Manana 			    ref->level == 0) {
1611789d6a3aSQu Wenruo 				struct btrfs_tree_parent_check check = { 0 };
1612976b1908SJan Schmidt 				struct extent_buffer *eb;
1613707e8a07SDavid Sterba 
1614789d6a3aSQu Wenruo 				check.level = ref->level;
1615789d6a3aSQu Wenruo 
1616789d6a3aSQu Wenruo 				eb = read_tree_block(ctx->fs_info, ref->parent,
1617789d6a3aSQu Wenruo 						     &check);
161864c043deSLiu Bo 				if (IS_ERR(eb)) {
161964c043deSLiu Bo 					ret = PTR_ERR(eb);
162064c043deSLiu Bo 					goto out;
16214eb150d6SQu Wenruo 				}
16224eb150d6SQu Wenruo 				if (!extent_buffer_uptodate(eb)) {
1623416bc658SJosef Bacik 					free_extent_buffer(eb);
1624c16c2e2eSWang Shilong 					ret = -EIO;
1625c16c2e2eSWang Shilong 					goto out;
1626416bc658SJosef Bacik 				}
162738e3eebfSJosef Bacik 
1628ac5887c8SJosef Bacik 				if (!path->skip_locking)
16296f7ff6d7SFilipe Manana 					btrfs_tree_read_lock(eb);
163088ffb665SFilipe Manana 				ret = find_extent_in_eb(ctx, eb, &eie);
163138e3eebfSJosef Bacik 				if (!path->skip_locking)
1632ac5887c8SJosef Bacik 					btrfs_tree_read_unlock(eb);
1633976b1908SJan Schmidt 				free_extent_buffer(eb);
163488ffb665SFilipe Manana 				if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
163588ffb665SFilipe Manana 				    ret < 0)
1636f5929cd8SFilipe David Borba Manana 					goto out;
1637f5929cd8SFilipe David Borba Manana 				ref->inode_list = eie;
163892876eecSFilipe Manana 				/*
163992876eecSFilipe Manana 				 * We transferred the list ownership to the ref,
164092876eecSFilipe Manana 				 * so set to NULL to avoid a double free in case
164192876eecSFilipe Manana 				 * an error happens after this.
164292876eecSFilipe Manana 				 */
164392876eecSFilipe Manana 				eie = NULL;
1644976b1908SJan Schmidt 			}
1645a2c8d27eSFilipe Manana 			ret = ulist_add_merge_ptr(ctx->refs, ref->parent,
16464eb1f66dSTakashi Iwai 						  ref->inode_list,
16474eb1f66dSTakashi Iwai 						  (void **)&eie, GFP_NOFS);
1648f1723939SWang Shilong 			if (ret < 0)
1649f1723939SWang Shilong 				goto out;
1650a2c8d27eSFilipe Manana 			if (!ret && !ctx->ignore_extent_item_pos) {
16513301958bSJan Schmidt 				/*
16529f05c09dSJosef Bacik 				 * We've recorded that parent, so we must extend
16539f05c09dSJosef Bacik 				 * its inode list here.
16549f05c09dSJosef Bacik 				 *
16559f05c09dSJosef Bacik 				 * However if there was corruption we may not
16569f05c09dSJosef Bacik 				 * have found an eie, return an error in this
16579f05c09dSJosef Bacik 				 * case.
16583301958bSJan Schmidt 				 */
16599f05c09dSJosef Bacik 				ASSERT(eie);
16609f05c09dSJosef Bacik 				if (!eie) {
16619f05c09dSJosef Bacik 					ret = -EUCLEAN;
16629f05c09dSJosef Bacik 					goto out;
16639f05c09dSJosef Bacik 				}
16643301958bSJan Schmidt 				while (eie->next)
16653301958bSJan Schmidt 					eie = eie->next;
16663301958bSJan Schmidt 				eie->next = ref->inode_list;
16673301958bSJan Schmidt 			}
1668f05c4746SWang Shilong 			eie = NULL;
166992876eecSFilipe Manana 			/*
167092876eecSFilipe Manana 			 * We have transferred the inode list ownership from
167192876eecSFilipe Manana 			 * this ref to the ref we added to the 'refs' ulist.
167292876eecSFilipe Manana 			 * So set this ref's inode list to NULL to avoid
167392876eecSFilipe Manana 			 * use-after-free when our caller uses it or double
167492876eecSFilipe Manana 			 * frees in case an error happens before we return.
167592876eecSFilipe Manana 			 */
167692876eecSFilipe Manana 			ref->inode_list = NULL;
16778da6d581SJan Schmidt 		}
16789dd14fd6SEdmund Nadolski 		cond_resched();
16798da6d581SJan Schmidt 	}
16808da6d581SJan Schmidt 
16818da6d581SJan Schmidt out:
16828da6d581SJan Schmidt 	btrfs_free_path(path);
168386d5f994SEdmund Nadolski 
168486d5f994SEdmund Nadolski 	prelim_release(&preftrees.direct);
168586d5f994SEdmund Nadolski 	prelim_release(&preftrees.indirect);
168686d5f994SEdmund Nadolski 	prelim_release(&preftrees.indirect_missing_keys);
168786d5f994SEdmund Nadolski 
168888ffb665SFilipe Manana 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
1689f05c4746SWang Shilong 		free_inode_elem_list(eie);
16908da6d581SJan Schmidt 	return ret;
16918da6d581SJan Schmidt }
16928da6d581SJan Schmidt 
16938da6d581SJan Schmidt /*
1694a2c8d27eSFilipe Manana  * Finds all leaves with a reference to the specified combination of
1695a2c8d27eSFilipe Manana  * @ctx->bytenr and @ctx->extent_item_pos. The bytenr of the found leaves are
1696a2c8d27eSFilipe Manana  * added to the ulist at @ctx->refs, and that ulist is allocated by this
1697a2c8d27eSFilipe Manana  * function. The caller should free the ulist with free_leaf_list() if
1698a2c8d27eSFilipe Manana  * @ctx->ignore_extent_item_pos is false, otherwise a fimple ulist_free() is
1699a2c8d27eSFilipe Manana  * enough.
17008da6d581SJan Schmidt  *
1701a2c8d27eSFilipe Manana  * Returns 0 on success and < 0 on error. On error @ctx->refs is not allocated.
17028da6d581SJan Schmidt  */
1703a2c8d27eSFilipe Manana int btrfs_find_all_leafs(struct btrfs_backref_walk_ctx *ctx)
17048da6d581SJan Schmidt {
17058da6d581SJan Schmidt 	int ret;
17068da6d581SJan Schmidt 
1707a2c8d27eSFilipe Manana 	ASSERT(ctx->refs == NULL);
1708a2c8d27eSFilipe Manana 
1709a2c8d27eSFilipe Manana 	ctx->refs = ulist_alloc(GFP_NOFS);
1710a2c8d27eSFilipe Manana 	if (!ctx->refs)
17118da6d581SJan Schmidt 		return -ENOMEM;
17128da6d581SJan Schmidt 
1713a2c8d27eSFilipe Manana 	ret = find_parent_nodes(ctx, NULL);
171488ffb665SFilipe Manana 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
171588ffb665SFilipe Manana 	    (ret < 0 && ret != -ENOENT)) {
1716a2c8d27eSFilipe Manana 		free_leaf_list(ctx->refs);
1717a2c8d27eSFilipe Manana 		ctx->refs = NULL;
17188da6d581SJan Schmidt 		return ret;
17198da6d581SJan Schmidt 	}
17208da6d581SJan Schmidt 
17218da6d581SJan Schmidt 	return 0;
17228da6d581SJan Schmidt }
17238da6d581SJan Schmidt 
17248da6d581SJan Schmidt /*
1725a2c8d27eSFilipe Manana  * Walk all backrefs for a given extent to find all roots that reference this
17268da6d581SJan Schmidt  * extent. Walking a backref means finding all extents that reference this
17278da6d581SJan Schmidt  * extent and in turn walk the backrefs of those, too. Naturally this is a
17288da6d581SJan Schmidt  * recursive process, but here it is implemented in an iterative fashion: We
17298da6d581SJan Schmidt  * find all referencing extents for the extent in question and put them on a
17308da6d581SJan Schmidt  * list. In turn, we find all referencing extents for those, further appending
17318da6d581SJan Schmidt  * to the list. The way we iterate the list allows adding more elements after
17328da6d581SJan Schmidt  * the current while iterating. The process stops when we reach the end of the
1733a2c8d27eSFilipe Manana  * list.
17348da6d581SJan Schmidt  *
17351baea6f1SFilipe Manana  * Found roots are added to @ctx->roots, which is allocated by this function if
17361baea6f1SFilipe Manana  * it points to NULL, in which case the caller is responsible for freeing it
17371baea6f1SFilipe Manana  * after it's not needed anymore.
17381baea6f1SFilipe Manana  * This function requires @ctx->refs to be NULL, as it uses it for allocating a
17391baea6f1SFilipe Manana  * ulist to do temporary work, and frees it before returning.
1740a2c8d27eSFilipe Manana  *
17411baea6f1SFilipe Manana  * Returns 0 on success, < 0 on error.
17428da6d581SJan Schmidt  */
1743a2c8d27eSFilipe Manana static int btrfs_find_all_roots_safe(struct btrfs_backref_walk_ctx *ctx)
17448da6d581SJan Schmidt {
1745a2c8d27eSFilipe Manana 	const u64 orig_bytenr = ctx->bytenr;
1746a2c8d27eSFilipe Manana 	const bool orig_ignore_extent_item_pos = ctx->ignore_extent_item_pos;
17471baea6f1SFilipe Manana 	bool roots_ulist_allocated = false;
1748cd1b413cSJan Schmidt 	struct ulist_iterator uiter;
1749a2c8d27eSFilipe Manana 	int ret = 0;
17508da6d581SJan Schmidt 
1751a2c8d27eSFilipe Manana 	ASSERT(ctx->refs == NULL);
1752a2c8d27eSFilipe Manana 
1753a2c8d27eSFilipe Manana 	ctx->refs = ulist_alloc(GFP_NOFS);
1754a2c8d27eSFilipe Manana 	if (!ctx->refs)
17558da6d581SJan Schmidt 		return -ENOMEM;
1756a2c8d27eSFilipe Manana 
17571baea6f1SFilipe Manana 	if (!ctx->roots) {
1758a2c8d27eSFilipe Manana 		ctx->roots = ulist_alloc(GFP_NOFS);
1759a2c8d27eSFilipe Manana 		if (!ctx->roots) {
1760a2c8d27eSFilipe Manana 			ulist_free(ctx->refs);
1761a2c8d27eSFilipe Manana 			ctx->refs = NULL;
17628da6d581SJan Schmidt 			return -ENOMEM;
17638da6d581SJan Schmidt 		}
17641baea6f1SFilipe Manana 		roots_ulist_allocated = true;
17651baea6f1SFilipe Manana 	}
17668da6d581SJan Schmidt 
1767a2c8d27eSFilipe Manana 	ctx->ignore_extent_item_pos = true;
1768a2c8d27eSFilipe Manana 
1769cd1b413cSJan Schmidt 	ULIST_ITER_INIT(&uiter);
17708da6d581SJan Schmidt 	while (1) {
1771a2c8d27eSFilipe Manana 		struct ulist_node *node;
1772a2c8d27eSFilipe Manana 
1773a2c8d27eSFilipe Manana 		ret = find_parent_nodes(ctx, NULL);
17748da6d581SJan Schmidt 		if (ret < 0 && ret != -ENOENT) {
17751baea6f1SFilipe Manana 			if (roots_ulist_allocated) {
1776a2c8d27eSFilipe Manana 				ulist_free(ctx->roots);
1777a2c8d27eSFilipe Manana 				ctx->roots = NULL;
17781baea6f1SFilipe Manana 			}
1779a2c8d27eSFilipe Manana 			break;
17808da6d581SJan Schmidt 		}
1781a2c8d27eSFilipe Manana 		ret = 0;
1782a2c8d27eSFilipe Manana 		node = ulist_next(ctx->refs, &uiter);
17838da6d581SJan Schmidt 		if (!node)
17848da6d581SJan Schmidt 			break;
1785a2c8d27eSFilipe Manana 		ctx->bytenr = node->val;
1786bca1a290SWang Shilong 		cond_resched();
17878da6d581SJan Schmidt 	}
17888da6d581SJan Schmidt 
1789a2c8d27eSFilipe Manana 	ulist_free(ctx->refs);
1790a2c8d27eSFilipe Manana 	ctx->refs = NULL;
1791a2c8d27eSFilipe Manana 	ctx->bytenr = orig_bytenr;
1792a2c8d27eSFilipe Manana 	ctx->ignore_extent_item_pos = orig_ignore_extent_item_pos;
1793a2c8d27eSFilipe Manana 
1794a2c8d27eSFilipe Manana 	return ret;
17958da6d581SJan Schmidt }
17968da6d581SJan Schmidt 
1797a2c8d27eSFilipe Manana int btrfs_find_all_roots(struct btrfs_backref_walk_ctx *ctx,
1798c7bcbb21SFilipe Manana 			 bool skip_commit_root_sem)
17999e351cc8SJosef Bacik {
18009e351cc8SJosef Bacik 	int ret;
18019e351cc8SJosef Bacik 
1802a2c8d27eSFilipe Manana 	if (!ctx->trans && !skip_commit_root_sem)
1803a2c8d27eSFilipe Manana 		down_read(&ctx->fs_info->commit_root_sem);
1804a2c8d27eSFilipe Manana 	ret = btrfs_find_all_roots_safe(ctx);
1805a2c8d27eSFilipe Manana 	if (!ctx->trans && !skip_commit_root_sem)
1806a2c8d27eSFilipe Manana 		up_read(&ctx->fs_info->commit_root_sem);
18079e351cc8SJosef Bacik 	return ret;
18089e351cc8SJosef Bacik }
18099e351cc8SJosef Bacik 
181084a7949dSFilipe Manana struct btrfs_backref_share_check_ctx *btrfs_alloc_backref_share_check_ctx(void)
181184a7949dSFilipe Manana {
181284a7949dSFilipe Manana 	struct btrfs_backref_share_check_ctx *ctx;
181384a7949dSFilipe Manana 
181484a7949dSFilipe Manana 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
181584a7949dSFilipe Manana 	if (!ctx)
181684a7949dSFilipe Manana 		return NULL;
181784a7949dSFilipe Manana 
181884a7949dSFilipe Manana 	ulist_init(&ctx->refs);
181984a7949dSFilipe Manana 
182084a7949dSFilipe Manana 	return ctx;
182184a7949dSFilipe Manana }
182284a7949dSFilipe Manana 
182384a7949dSFilipe Manana void btrfs_free_backref_share_ctx(struct btrfs_backref_share_check_ctx *ctx)
182484a7949dSFilipe Manana {
182584a7949dSFilipe Manana 	if (!ctx)
182684a7949dSFilipe Manana 		return;
182784a7949dSFilipe Manana 
182884a7949dSFilipe Manana 	ulist_release(&ctx->refs);
182984a7949dSFilipe Manana 	kfree(ctx);
183084a7949dSFilipe Manana }
183184a7949dSFilipe Manana 
183212a824dcSFilipe Manana /*
18338eedaddaSFilipe Manana  * Check if a data extent is shared or not.
18346e353e3bSNikolay Borisov  *
1835ceb707daSFilipe Manana  * @inode:       The inode whose extent we are checking.
1836b8f164e3SFilipe Manana  * @bytenr:      Logical bytenr of the extent we are checking.
1837b8f164e3SFilipe Manana  * @extent_gen:  Generation of the extent (file extent item) or 0 if it is
1838b8f164e3SFilipe Manana  *               not known.
183961dbb952SFilipe Manana  * @ctx:         A backref sharedness check context.
18402c2ed5aaSMark Fasheh  *
18418eedaddaSFilipe Manana  * btrfs_is_data_extent_shared uses the backref walking code but will short
18422c2ed5aaSMark Fasheh  * circuit as soon as it finds a root or inode that doesn't match the
18432c2ed5aaSMark Fasheh  * one passed in. This provides a significant performance benefit for
18442c2ed5aaSMark Fasheh  * callers (such as fiemap) which want to know whether the extent is
18452c2ed5aaSMark Fasheh  * shared but do not need a ref count.
18462c2ed5aaSMark Fasheh  *
184703628cdbSFilipe Manana  * This attempts to attach to the running transaction in order to account for
184803628cdbSFilipe Manana  * delayed refs, but continues on even when no running transaction exists.
1849bb739cf0SEdmund Nadolski  *
18502c2ed5aaSMark Fasheh  * Return: 0 if extent is not shared, 1 if it is shared, < 0 on error.
18512c2ed5aaSMark Fasheh  */
1852ceb707daSFilipe Manana int btrfs_is_data_extent_shared(struct btrfs_inode *inode, u64 bytenr,
1853b8f164e3SFilipe Manana 				u64 extent_gen,
185461dbb952SFilipe Manana 				struct btrfs_backref_share_check_ctx *ctx)
1855dc046b10SJosef Bacik {
1856a2c8d27eSFilipe Manana 	struct btrfs_backref_walk_ctx walk_ctx = { 0 };
1857ceb707daSFilipe Manana 	struct btrfs_root *root = inode->root;
1858bb739cf0SEdmund Nadolski 	struct btrfs_fs_info *fs_info = root->fs_info;
1859bb739cf0SEdmund Nadolski 	struct btrfs_trans_handle *trans;
1860dc046b10SJosef Bacik 	struct ulist_iterator uiter;
1861dc046b10SJosef Bacik 	struct ulist_node *node;
1862f3a84ccdSFilipe Manana 	struct btrfs_seq_list elem = BTRFS_SEQ_LIST_INIT(elem);
1863dc046b10SJosef Bacik 	int ret = 0;
18643ec4d323SEdmund Nadolski 	struct share_check shared = {
1865877c1476SFilipe Manana 		.ctx = ctx,
1866877c1476SFilipe Manana 		.root = root,
1867ceb707daSFilipe Manana 		.inum = btrfs_ino(inode),
186873e339e6SFilipe Manana 		.data_bytenr = bytenr,
18696976201fSFilipe Manana 		.data_extent_gen = extent_gen,
18703ec4d323SEdmund Nadolski 		.share_count = 0,
187173e339e6SFilipe Manana 		.self_ref_count = 0,
18724fc7b572SFilipe Manana 		.have_delayed_delete_refs = false,
18733ec4d323SEdmund Nadolski 	};
187412a824dcSFilipe Manana 	int level;
1875*e2fd8306SFilipe Manana 	bool leaf_cached;
1876*e2fd8306SFilipe Manana 	bool leaf_is_shared;
1877dc046b10SJosef Bacik 
187873e339e6SFilipe Manana 	for (int i = 0; i < BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE; i++) {
187973e339e6SFilipe Manana 		if (ctx->prev_extents_cache[i].bytenr == bytenr)
188073e339e6SFilipe Manana 			return ctx->prev_extents_cache[i].is_shared;
188173e339e6SFilipe Manana 	}
188273e339e6SFilipe Manana 
188384a7949dSFilipe Manana 	ulist_init(&ctx->refs);
1884dc046b10SJosef Bacik 
1885a6d155d2SFilipe Manana 	trans = btrfs_join_transaction_nostart(root);
1886bb739cf0SEdmund Nadolski 	if (IS_ERR(trans)) {
188703628cdbSFilipe Manana 		if (PTR_ERR(trans) != -ENOENT && PTR_ERR(trans) != -EROFS) {
188803628cdbSFilipe Manana 			ret = PTR_ERR(trans);
188903628cdbSFilipe Manana 			goto out;
189003628cdbSFilipe Manana 		}
1891bb739cf0SEdmund Nadolski 		trans = NULL;
1892dc046b10SJosef Bacik 		down_read(&fs_info->commit_root_sem);
1893bb739cf0SEdmund Nadolski 	} else {
1894bb739cf0SEdmund Nadolski 		btrfs_get_tree_mod_seq(fs_info, &elem);
1895a2c8d27eSFilipe Manana 		walk_ctx.time_seq = elem.seq;
1896bb739cf0SEdmund Nadolski 	}
1897bb739cf0SEdmund Nadolski 
1898*e2fd8306SFilipe Manana 	ctx->use_path_cache = true;
1899*e2fd8306SFilipe Manana 
1900*e2fd8306SFilipe Manana 	/*
1901*e2fd8306SFilipe Manana 	 * We may have previously determined that the current leaf is shared.
1902*e2fd8306SFilipe Manana 	 * If it is, then we have a data extent that is shared due to a shared
1903*e2fd8306SFilipe Manana 	 * subtree (caused by snapshotting) and we don't need to check for data
1904*e2fd8306SFilipe Manana 	 * backrefs. If the leaf is not shared, then we must do backref walking
1905*e2fd8306SFilipe Manana 	 * to determine if the data extent is shared through reflinks.
1906*e2fd8306SFilipe Manana 	 */
1907*e2fd8306SFilipe Manana 	leaf_cached = lookup_backref_shared_cache(ctx, root,
1908*e2fd8306SFilipe Manana 						  ctx->curr_leaf_bytenr, 0,
1909*e2fd8306SFilipe Manana 						  &leaf_is_shared);
1910*e2fd8306SFilipe Manana 	if (leaf_cached && leaf_is_shared) {
1911*e2fd8306SFilipe Manana 		ret = 1;
1912*e2fd8306SFilipe Manana 		goto out_trans;
1913*e2fd8306SFilipe Manana 	}
1914*e2fd8306SFilipe Manana 
1915a2c8d27eSFilipe Manana 	walk_ctx.ignore_extent_item_pos = true;
1916a2c8d27eSFilipe Manana 	walk_ctx.trans = trans;
1917a2c8d27eSFilipe Manana 	walk_ctx.fs_info = fs_info;
1918a2c8d27eSFilipe Manana 	walk_ctx.refs = &ctx->refs;
1919a2c8d27eSFilipe Manana 
192012a824dcSFilipe Manana 	/* -1 means we are in the bytenr of the data extent. */
192112a824dcSFilipe Manana 	level = -1;
1922dc046b10SJosef Bacik 	ULIST_ITER_INIT(&uiter);
1923dc046b10SJosef Bacik 	while (1) {
192412a824dcSFilipe Manana 		bool is_shared;
192512a824dcSFilipe Manana 		bool cached;
192612a824dcSFilipe Manana 
1927a2c8d27eSFilipe Manana 		walk_ctx.bytenr = bytenr;
1928a2c8d27eSFilipe Manana 		ret = find_parent_nodes(&walk_ctx, &shared);
1929877c1476SFilipe Manana 		if (ret == BACKREF_FOUND_SHARED ||
1930877c1476SFilipe Manana 		    ret == BACKREF_FOUND_NOT_SHARED) {
1931877c1476SFilipe Manana 			/* If shared must return 1, otherwise return 0. */
1932877c1476SFilipe Manana 			ret = (ret == BACKREF_FOUND_SHARED) ? 1 : 0;
193312a824dcSFilipe Manana 			if (level >= 0)
193461dbb952SFilipe Manana 				store_backref_shared_cache(ctx, root, bytenr,
1935877c1476SFilipe Manana 							   level, ret == 1);
1936dc046b10SJosef Bacik 			break;
1937dc046b10SJosef Bacik 		}
1938dc046b10SJosef Bacik 		if (ret < 0 && ret != -ENOENT)
1939dc046b10SJosef Bacik 			break;
19402c2ed5aaSMark Fasheh 		ret = 0;
1941b8f164e3SFilipe Manana 
194263c84b46SFilipe Manana 		/*
194363c84b46SFilipe Manana 		 * If our data extent was not directly shared (without multiple
194463c84b46SFilipe Manana 		 * reference items), than it might have a single reference item
194563c84b46SFilipe Manana 		 * with a count > 1 for the same offset, which means there are 2
194663c84b46SFilipe Manana 		 * (or more) file extent items that point to the data extent -
194763c84b46SFilipe Manana 		 * this happens when a file extent item needs to be split and
194863c84b46SFilipe Manana 		 * then one item gets moved to another leaf due to a b+tree leaf
194963c84b46SFilipe Manana 		 * split when inserting some item. In this case the file extent
195063c84b46SFilipe Manana 		 * items may be located in different leaves and therefore some
195163c84b46SFilipe Manana 		 * of the leaves may be referenced through shared subtrees while
195263c84b46SFilipe Manana 		 * others are not. Since our extent buffer cache only works for
195363c84b46SFilipe Manana 		 * a single path (by far the most common case and simpler to
195463c84b46SFilipe Manana 		 * deal with), we can not use it if we have multiple leaves
195563c84b46SFilipe Manana 		 * (which implies multiple paths).
195663c84b46SFilipe Manana 		 */
195784a7949dSFilipe Manana 		if (level == -1 && ctx->refs.nnodes > 1)
195861dbb952SFilipe Manana 			ctx->use_path_cache = false;
195963c84b46SFilipe Manana 
196012a824dcSFilipe Manana 		if (level >= 0)
196161dbb952SFilipe Manana 			store_backref_shared_cache(ctx, root, bytenr,
196212a824dcSFilipe Manana 						   level, false);
196384a7949dSFilipe Manana 		node = ulist_next(&ctx->refs, &uiter);
1964dc046b10SJosef Bacik 		if (!node)
1965dc046b10SJosef Bacik 			break;
1966dc046b10SJosef Bacik 		bytenr = node->val;
196712a824dcSFilipe Manana 		level++;
196861dbb952SFilipe Manana 		cached = lookup_backref_shared_cache(ctx, root, bytenr, level,
196912a824dcSFilipe Manana 						     &is_shared);
197012a824dcSFilipe Manana 		if (cached) {
197112a824dcSFilipe Manana 			ret = (is_shared ? 1 : 0);
197212a824dcSFilipe Manana 			break;
197312a824dcSFilipe Manana 		}
197418bf591bSEdmund Nadolski 		shared.share_count = 0;
19754fc7b572SFilipe Manana 		shared.have_delayed_delete_refs = false;
1976dc046b10SJosef Bacik 		cond_resched();
1977dc046b10SJosef Bacik 	}
1978bb739cf0SEdmund Nadolski 
197973e339e6SFilipe Manana 	/*
198073e339e6SFilipe Manana 	 * Cache the sharedness result for the data extent if we know our inode
198173e339e6SFilipe Manana 	 * has more than 1 file extent item that refers to the data extent.
198273e339e6SFilipe Manana 	 */
198373e339e6SFilipe Manana 	if (ret >= 0 && shared.self_ref_count > 1) {
198473e339e6SFilipe Manana 		int slot = ctx->prev_extents_cache_slot;
198573e339e6SFilipe Manana 
198673e339e6SFilipe Manana 		ctx->prev_extents_cache[slot].bytenr = shared.data_bytenr;
198773e339e6SFilipe Manana 		ctx->prev_extents_cache[slot].is_shared = (ret == 1);
198873e339e6SFilipe Manana 
198973e339e6SFilipe Manana 		slot = (slot + 1) % BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE;
199073e339e6SFilipe Manana 		ctx->prev_extents_cache_slot = slot;
199173e339e6SFilipe Manana 	}
199273e339e6SFilipe Manana 
1993*e2fd8306SFilipe Manana out_trans:
1994bb739cf0SEdmund Nadolski 	if (trans) {
1995dc046b10SJosef Bacik 		btrfs_put_tree_mod_seq(fs_info, &elem);
1996bb739cf0SEdmund Nadolski 		btrfs_end_transaction(trans);
1997bb739cf0SEdmund Nadolski 	} else {
1998dc046b10SJosef Bacik 		up_read(&fs_info->commit_root_sem);
1999bb739cf0SEdmund Nadolski 	}
200003628cdbSFilipe Manana out:
200184a7949dSFilipe Manana 	ulist_release(&ctx->refs);
2002877c1476SFilipe Manana 	ctx->prev_leaf_bytenr = ctx->curr_leaf_bytenr;
2003877c1476SFilipe Manana 
2004dc046b10SJosef Bacik 	return ret;
2005dc046b10SJosef Bacik }
2006dc046b10SJosef Bacik 
2007f186373fSMark Fasheh int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
2008f186373fSMark Fasheh 			  u64 start_off, struct btrfs_path *path,
2009f186373fSMark Fasheh 			  struct btrfs_inode_extref **ret_extref,
2010f186373fSMark Fasheh 			  u64 *found_off)
2011f186373fSMark Fasheh {
2012f186373fSMark Fasheh 	int ret, slot;
2013f186373fSMark Fasheh 	struct btrfs_key key;
2014f186373fSMark Fasheh 	struct btrfs_key found_key;
2015f186373fSMark Fasheh 	struct btrfs_inode_extref *extref;
201673980becSJeff Mahoney 	const struct extent_buffer *leaf;
2017f186373fSMark Fasheh 	unsigned long ptr;
2018f186373fSMark Fasheh 
2019f186373fSMark Fasheh 	key.objectid = inode_objectid;
2020962a298fSDavid Sterba 	key.type = BTRFS_INODE_EXTREF_KEY;
2021f186373fSMark Fasheh 	key.offset = start_off;
2022f186373fSMark Fasheh 
2023f186373fSMark Fasheh 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2024f186373fSMark Fasheh 	if (ret < 0)
2025f186373fSMark Fasheh 		return ret;
2026f186373fSMark Fasheh 
2027f186373fSMark Fasheh 	while (1) {
2028f186373fSMark Fasheh 		leaf = path->nodes[0];
2029f186373fSMark Fasheh 		slot = path->slots[0];
2030f186373fSMark Fasheh 		if (slot >= btrfs_header_nritems(leaf)) {
2031f186373fSMark Fasheh 			/*
2032f186373fSMark Fasheh 			 * If the item at offset is not found,
2033f186373fSMark Fasheh 			 * btrfs_search_slot will point us to the slot
2034f186373fSMark Fasheh 			 * where it should be inserted. In our case
2035f186373fSMark Fasheh 			 * that will be the slot directly before the
2036f186373fSMark Fasheh 			 * next INODE_REF_KEY_V2 item. In the case
2037f186373fSMark Fasheh 			 * that we're pointing to the last slot in a
2038f186373fSMark Fasheh 			 * leaf, we must move one leaf over.
2039f186373fSMark Fasheh 			 */
2040f186373fSMark Fasheh 			ret = btrfs_next_leaf(root, path);
2041f186373fSMark Fasheh 			if (ret) {
2042f186373fSMark Fasheh 				if (ret >= 1)
2043f186373fSMark Fasheh 					ret = -ENOENT;
2044f186373fSMark Fasheh 				break;
2045f186373fSMark Fasheh 			}
2046f186373fSMark Fasheh 			continue;
2047f186373fSMark Fasheh 		}
2048f186373fSMark Fasheh 
2049f186373fSMark Fasheh 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
2050f186373fSMark Fasheh 
2051f186373fSMark Fasheh 		/*
2052f186373fSMark Fasheh 		 * Check that we're still looking at an extended ref key for
2053f186373fSMark Fasheh 		 * this particular objectid. If we have different
2054f186373fSMark Fasheh 		 * objectid or type then there are no more to be found
2055f186373fSMark Fasheh 		 * in the tree and we can exit.
2056f186373fSMark Fasheh 		 */
2057f186373fSMark Fasheh 		ret = -ENOENT;
2058f186373fSMark Fasheh 		if (found_key.objectid != inode_objectid)
2059f186373fSMark Fasheh 			break;
2060962a298fSDavid Sterba 		if (found_key.type != BTRFS_INODE_EXTREF_KEY)
2061f186373fSMark Fasheh 			break;
2062f186373fSMark Fasheh 
2063f186373fSMark Fasheh 		ret = 0;
2064f186373fSMark Fasheh 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
2065f186373fSMark Fasheh 		extref = (struct btrfs_inode_extref *)ptr;
2066f186373fSMark Fasheh 		*ret_extref = extref;
2067f186373fSMark Fasheh 		if (found_off)
2068f186373fSMark Fasheh 			*found_off = found_key.offset;
2069f186373fSMark Fasheh 		break;
2070f186373fSMark Fasheh 	}
2071f186373fSMark Fasheh 
2072f186373fSMark Fasheh 	return ret;
2073f186373fSMark Fasheh }
2074f186373fSMark Fasheh 
207548a3b636SEric Sandeen /*
207648a3b636SEric Sandeen  * this iterates to turn a name (from iref/extref) into a full filesystem path.
207748a3b636SEric Sandeen  * Elements of the path are separated by '/' and the path is guaranteed to be
207848a3b636SEric Sandeen  * 0-terminated. the path is only given within the current file system.
207948a3b636SEric Sandeen  * Therefore, it never starts with a '/'. the caller is responsible to provide
208048a3b636SEric Sandeen  * "size" bytes in "dest". the dest buffer will be filled backwards. finally,
208148a3b636SEric Sandeen  * the start point of the resulting string is returned. this pointer is within
208248a3b636SEric Sandeen  * dest, normally.
208348a3b636SEric Sandeen  * in case the path buffer would overflow, the pointer is decremented further
208448a3b636SEric Sandeen  * as if output was written to the buffer, though no more output is actually
208548a3b636SEric Sandeen  * generated. that way, the caller can determine how much space would be
208648a3b636SEric Sandeen  * required for the path to fit into the buffer. in that case, the returned
208748a3b636SEric Sandeen  * value will be smaller than dest. callers must check this!
208848a3b636SEric Sandeen  */
208996b5bd77SJan Schmidt char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
2090d24bec3aSMark Fasheh 			u32 name_len, unsigned long name_off,
2091a542ad1bSJan Schmidt 			struct extent_buffer *eb_in, u64 parent,
2092a542ad1bSJan Schmidt 			char *dest, u32 size)
2093a542ad1bSJan Schmidt {
2094a542ad1bSJan Schmidt 	int slot;
2095a542ad1bSJan Schmidt 	u64 next_inum;
2096a542ad1bSJan Schmidt 	int ret;
2097661bec6bSGabriel de Perthuis 	s64 bytes_left = ((s64)size) - 1;
2098a542ad1bSJan Schmidt 	struct extent_buffer *eb = eb_in;
2099a542ad1bSJan Schmidt 	struct btrfs_key found_key;
2100d24bec3aSMark Fasheh 	struct btrfs_inode_ref *iref;
2101a542ad1bSJan Schmidt 
2102a542ad1bSJan Schmidt 	if (bytes_left >= 0)
2103a542ad1bSJan Schmidt 		dest[bytes_left] = '\0';
2104a542ad1bSJan Schmidt 
2105a542ad1bSJan Schmidt 	while (1) {
2106d24bec3aSMark Fasheh 		bytes_left -= name_len;
2107a542ad1bSJan Schmidt 		if (bytes_left >= 0)
2108a542ad1bSJan Schmidt 			read_extent_buffer(eb, dest + bytes_left,
2109d24bec3aSMark Fasheh 					   name_off, name_len);
2110b916a59aSJan Schmidt 		if (eb != eb_in) {
21110c0fe3b0SFilipe Manana 			if (!path->skip_locking)
2112ac5887c8SJosef Bacik 				btrfs_tree_read_unlock(eb);
2113a542ad1bSJan Schmidt 			free_extent_buffer(eb);
2114b916a59aSJan Schmidt 		}
2115c234a24dSDavid Sterba 		ret = btrfs_find_item(fs_root, path, parent, 0,
2116c234a24dSDavid Sterba 				BTRFS_INODE_REF_KEY, &found_key);
21178f24b496SJan Schmidt 		if (ret > 0)
21188f24b496SJan Schmidt 			ret = -ENOENT;
2119a542ad1bSJan Schmidt 		if (ret)
2120a542ad1bSJan Schmidt 			break;
2121d24bec3aSMark Fasheh 
2122a542ad1bSJan Schmidt 		next_inum = found_key.offset;
2123a542ad1bSJan Schmidt 
2124a542ad1bSJan Schmidt 		/* regular exit ahead */
2125a542ad1bSJan Schmidt 		if (parent == next_inum)
2126a542ad1bSJan Schmidt 			break;
2127a542ad1bSJan Schmidt 
2128a542ad1bSJan Schmidt 		slot = path->slots[0];
2129a542ad1bSJan Schmidt 		eb = path->nodes[0];
2130a542ad1bSJan Schmidt 		/* make sure we can use eb after releasing the path */
2131b916a59aSJan Schmidt 		if (eb != eb_in) {
21320c0fe3b0SFilipe Manana 			path->nodes[0] = NULL;
21330c0fe3b0SFilipe Manana 			path->locks[0] = 0;
2134b916a59aSJan Schmidt 		}
2135a542ad1bSJan Schmidt 		btrfs_release_path(path);
2136a542ad1bSJan Schmidt 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2137d24bec3aSMark Fasheh 
2138d24bec3aSMark Fasheh 		name_len = btrfs_inode_ref_name_len(eb, iref);
2139d24bec3aSMark Fasheh 		name_off = (unsigned long)(iref + 1);
2140d24bec3aSMark Fasheh 
2141a542ad1bSJan Schmidt 		parent = next_inum;
2142a542ad1bSJan Schmidt 		--bytes_left;
2143a542ad1bSJan Schmidt 		if (bytes_left >= 0)
2144a542ad1bSJan Schmidt 			dest[bytes_left] = '/';
2145a542ad1bSJan Schmidt 	}
2146a542ad1bSJan Schmidt 
2147a542ad1bSJan Schmidt 	btrfs_release_path(path);
2148a542ad1bSJan Schmidt 
2149a542ad1bSJan Schmidt 	if (ret)
2150a542ad1bSJan Schmidt 		return ERR_PTR(ret);
2151a542ad1bSJan Schmidt 
2152a542ad1bSJan Schmidt 	return dest + bytes_left;
2153a542ad1bSJan Schmidt }
2154a542ad1bSJan Schmidt 
2155a542ad1bSJan Schmidt /*
2156a542ad1bSJan Schmidt  * this makes the path point to (logical EXTENT_ITEM *)
2157a542ad1bSJan Schmidt  * returns BTRFS_EXTENT_FLAG_DATA for data, BTRFS_EXTENT_FLAG_TREE_BLOCK for
2158a542ad1bSJan Schmidt  * tree blocks and <0 on error.
2159a542ad1bSJan Schmidt  */
2160a542ad1bSJan Schmidt int extent_from_logical(struct btrfs_fs_info *fs_info, u64 logical,
216169917e43SLiu Bo 			struct btrfs_path *path, struct btrfs_key *found_key,
216269917e43SLiu Bo 			u64 *flags_ret)
2163a542ad1bSJan Schmidt {
216429cbcf40SJosef Bacik 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, logical);
2165a542ad1bSJan Schmidt 	int ret;
2166a542ad1bSJan Schmidt 	u64 flags;
2167261c84b6SJosef Bacik 	u64 size = 0;
2168a542ad1bSJan Schmidt 	u32 item_size;
216973980becSJeff Mahoney 	const struct extent_buffer *eb;
2170a542ad1bSJan Schmidt 	struct btrfs_extent_item *ei;
2171a542ad1bSJan Schmidt 	struct btrfs_key key;
2172a542ad1bSJan Schmidt 
2173261c84b6SJosef Bacik 	if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2174261c84b6SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
2175261c84b6SJosef Bacik 	else
2176a542ad1bSJan Schmidt 		key.type = BTRFS_EXTENT_ITEM_KEY;
2177a542ad1bSJan Schmidt 	key.objectid = logical;
2178a542ad1bSJan Schmidt 	key.offset = (u64)-1;
2179a542ad1bSJan Schmidt 
218029cbcf40SJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2181a542ad1bSJan Schmidt 	if (ret < 0)
2182a542ad1bSJan Schmidt 		return ret;
2183a542ad1bSJan Schmidt 
218429cbcf40SJosef Bacik 	ret = btrfs_previous_extent_item(extent_root, path, 0);
2185850a8cdfSWang Shilong 	if (ret) {
2186850a8cdfSWang Shilong 		if (ret > 0)
2187580f0a67SJosef Bacik 			ret = -ENOENT;
2188580f0a67SJosef Bacik 		return ret;
2189580f0a67SJosef Bacik 	}
2190850a8cdfSWang Shilong 	btrfs_item_key_to_cpu(path->nodes[0], found_key, path->slots[0]);
2191261c84b6SJosef Bacik 	if (found_key->type == BTRFS_METADATA_ITEM_KEY)
2192da17066cSJeff Mahoney 		size = fs_info->nodesize;
2193261c84b6SJosef Bacik 	else if (found_key->type == BTRFS_EXTENT_ITEM_KEY)
2194261c84b6SJosef Bacik 		size = found_key->offset;
2195261c84b6SJosef Bacik 
2196580f0a67SJosef Bacik 	if (found_key->objectid > logical ||
2197261c84b6SJosef Bacik 	    found_key->objectid + size <= logical) {
2198ab8d0fc4SJeff Mahoney 		btrfs_debug(fs_info,
2199ab8d0fc4SJeff Mahoney 			"logical %llu is not within any extent", logical);
2200a542ad1bSJan Schmidt 		return -ENOENT;
22014692cf58SJan Schmidt 	}
2202a542ad1bSJan Schmidt 
2203a542ad1bSJan Schmidt 	eb = path->nodes[0];
22043212fa14SJosef Bacik 	item_size = btrfs_item_size(eb, path->slots[0]);
2205a542ad1bSJan Schmidt 	BUG_ON(item_size < sizeof(*ei));
2206a542ad1bSJan Schmidt 
2207a542ad1bSJan Schmidt 	ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
2208a542ad1bSJan Schmidt 	flags = btrfs_extent_flags(eb, ei);
2209a542ad1bSJan Schmidt 
2210ab8d0fc4SJeff Mahoney 	btrfs_debug(fs_info,
2211ab8d0fc4SJeff Mahoney 		"logical %llu is at position %llu within the extent (%llu EXTENT_ITEM %llu) flags %#llx size %u",
2212c1c9ff7cSGeert Uytterhoeven 		 logical, logical - found_key->objectid, found_key->objectid,
2213c1c9ff7cSGeert Uytterhoeven 		 found_key->offset, flags, item_size);
221469917e43SLiu Bo 
221569917e43SLiu Bo 	WARN_ON(!flags_ret);
221669917e43SLiu Bo 	if (flags_ret) {
2217a542ad1bSJan Schmidt 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
221869917e43SLiu Bo 			*flags_ret = BTRFS_EXTENT_FLAG_TREE_BLOCK;
221969917e43SLiu Bo 		else if (flags & BTRFS_EXTENT_FLAG_DATA)
222069917e43SLiu Bo 			*flags_ret = BTRFS_EXTENT_FLAG_DATA;
222169917e43SLiu Bo 		else
2222290342f6SArnd Bergmann 			BUG();
222369917e43SLiu Bo 		return 0;
222469917e43SLiu Bo 	}
2225a542ad1bSJan Schmidt 
2226a542ad1bSJan Schmidt 	return -EIO;
2227a542ad1bSJan Schmidt }
2228a542ad1bSJan Schmidt 
2229a542ad1bSJan Schmidt /*
2230a542ad1bSJan Schmidt  * helper function to iterate extent inline refs. ptr must point to a 0 value
2231a542ad1bSJan Schmidt  * for the first call and may be modified. it is used to track state.
2232a542ad1bSJan Schmidt  * if more refs exist, 0 is returned and the next call to
2233e0c476b1SJeff Mahoney  * get_extent_inline_ref must pass the modified ptr parameter to get the
2234a542ad1bSJan Schmidt  * next ref. after the last ref was processed, 1 is returned.
2235a542ad1bSJan Schmidt  * returns <0 on error
2236a542ad1bSJan Schmidt  */
2237e0c476b1SJeff Mahoney static int get_extent_inline_ref(unsigned long *ptr,
223873980becSJeff Mahoney 				 const struct extent_buffer *eb,
223973980becSJeff Mahoney 				 const struct btrfs_key *key,
224073980becSJeff Mahoney 				 const struct btrfs_extent_item *ei,
224173980becSJeff Mahoney 				 u32 item_size,
2242a542ad1bSJan Schmidt 				 struct btrfs_extent_inline_ref **out_eiref,
2243a542ad1bSJan Schmidt 				 int *out_type)
2244a542ad1bSJan Schmidt {
2245a542ad1bSJan Schmidt 	unsigned long end;
2246a542ad1bSJan Schmidt 	u64 flags;
2247a542ad1bSJan Schmidt 	struct btrfs_tree_block_info *info;
2248a542ad1bSJan Schmidt 
2249a542ad1bSJan Schmidt 	if (!*ptr) {
2250a542ad1bSJan Schmidt 		/* first call */
2251a542ad1bSJan Schmidt 		flags = btrfs_extent_flags(eb, ei);
2252a542ad1bSJan Schmidt 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
22536eda71d0SLiu Bo 			if (key->type == BTRFS_METADATA_ITEM_KEY) {
22546eda71d0SLiu Bo 				/* a skinny metadata extent */
22556eda71d0SLiu Bo 				*out_eiref =
22566eda71d0SLiu Bo 				     (struct btrfs_extent_inline_ref *)(ei + 1);
22576eda71d0SLiu Bo 			} else {
22586eda71d0SLiu Bo 				WARN_ON(key->type != BTRFS_EXTENT_ITEM_KEY);
2259a542ad1bSJan Schmidt 				info = (struct btrfs_tree_block_info *)(ei + 1);
2260a542ad1bSJan Schmidt 				*out_eiref =
2261a542ad1bSJan Schmidt 				   (struct btrfs_extent_inline_ref *)(info + 1);
22626eda71d0SLiu Bo 			}
2263a542ad1bSJan Schmidt 		} else {
2264a542ad1bSJan Schmidt 			*out_eiref = (struct btrfs_extent_inline_ref *)(ei + 1);
2265a542ad1bSJan Schmidt 		}
2266a542ad1bSJan Schmidt 		*ptr = (unsigned long)*out_eiref;
2267cd857dd6SLiu Bo 		if ((unsigned long)(*ptr) >= (unsigned long)ei + item_size)
2268a542ad1bSJan Schmidt 			return -ENOENT;
2269a542ad1bSJan Schmidt 	}
2270a542ad1bSJan Schmidt 
2271a542ad1bSJan Schmidt 	end = (unsigned long)ei + item_size;
22726eda71d0SLiu Bo 	*out_eiref = (struct btrfs_extent_inline_ref *)(*ptr);
22733de28d57SLiu Bo 	*out_type = btrfs_get_extent_inline_ref_type(eb, *out_eiref,
22743de28d57SLiu Bo 						     BTRFS_REF_TYPE_ANY);
22753de28d57SLiu Bo 	if (*out_type == BTRFS_REF_TYPE_INVALID)
2276af431dcbSSu Yue 		return -EUCLEAN;
2277a542ad1bSJan Schmidt 
2278a542ad1bSJan Schmidt 	*ptr += btrfs_extent_inline_ref_size(*out_type);
2279a542ad1bSJan Schmidt 	WARN_ON(*ptr > end);
2280a542ad1bSJan Schmidt 	if (*ptr == end)
2281a542ad1bSJan Schmidt 		return 1; /* last */
2282a542ad1bSJan Schmidt 
2283a542ad1bSJan Schmidt 	return 0;
2284a542ad1bSJan Schmidt }
2285a542ad1bSJan Schmidt 
2286a542ad1bSJan Schmidt /*
2287a542ad1bSJan Schmidt  * reads the tree block backref for an extent. tree level and root are returned
2288a542ad1bSJan Schmidt  * through out_level and out_root. ptr must point to a 0 value for the first
2289e0c476b1SJeff Mahoney  * call and may be modified (see get_extent_inline_ref comment).
2290a542ad1bSJan Schmidt  * returns 0 if data was provided, 1 if there was no more data to provide or
2291a542ad1bSJan Schmidt  * <0 on error.
2292a542ad1bSJan Schmidt  */
2293a542ad1bSJan Schmidt int tree_backref_for_extent(unsigned long *ptr, struct extent_buffer *eb,
22946eda71d0SLiu Bo 			    struct btrfs_key *key, struct btrfs_extent_item *ei,
22956eda71d0SLiu Bo 			    u32 item_size, u64 *out_root, u8 *out_level)
2296a542ad1bSJan Schmidt {
2297a542ad1bSJan Schmidt 	int ret;
2298a542ad1bSJan Schmidt 	int type;
2299a542ad1bSJan Schmidt 	struct btrfs_extent_inline_ref *eiref;
2300a542ad1bSJan Schmidt 
2301a542ad1bSJan Schmidt 	if (*ptr == (unsigned long)-1)
2302a542ad1bSJan Schmidt 		return 1;
2303a542ad1bSJan Schmidt 
2304a542ad1bSJan Schmidt 	while (1) {
2305e0c476b1SJeff Mahoney 		ret = get_extent_inline_ref(ptr, eb, key, ei, item_size,
2306a542ad1bSJan Schmidt 					      &eiref, &type);
2307a542ad1bSJan Schmidt 		if (ret < 0)
2308a542ad1bSJan Schmidt 			return ret;
2309a542ad1bSJan Schmidt 
2310a542ad1bSJan Schmidt 		if (type == BTRFS_TREE_BLOCK_REF_KEY ||
2311a542ad1bSJan Schmidt 		    type == BTRFS_SHARED_BLOCK_REF_KEY)
2312a542ad1bSJan Schmidt 			break;
2313a542ad1bSJan Schmidt 
2314a542ad1bSJan Schmidt 		if (ret == 1)
2315a542ad1bSJan Schmidt 			return 1;
2316a542ad1bSJan Schmidt 	}
2317a542ad1bSJan Schmidt 
2318a542ad1bSJan Schmidt 	/* we can treat both ref types equally here */
2319a542ad1bSJan Schmidt 	*out_root = btrfs_extent_inline_ref_offset(eb, eiref);
2320a1317f45SFilipe Manana 
2321a1317f45SFilipe Manana 	if (key->type == BTRFS_EXTENT_ITEM_KEY) {
2322a1317f45SFilipe Manana 		struct btrfs_tree_block_info *info;
2323a1317f45SFilipe Manana 
2324a1317f45SFilipe Manana 		info = (struct btrfs_tree_block_info *)(ei + 1);
2325a542ad1bSJan Schmidt 		*out_level = btrfs_tree_block_level(eb, info);
2326a1317f45SFilipe Manana 	} else {
2327a1317f45SFilipe Manana 		ASSERT(key->type == BTRFS_METADATA_ITEM_KEY);
2328a1317f45SFilipe Manana 		*out_level = (u8)key->offset;
2329a1317f45SFilipe Manana 	}
2330a542ad1bSJan Schmidt 
2331a542ad1bSJan Schmidt 	if (ret == 1)
2332a542ad1bSJan Schmidt 		*ptr = (unsigned long)-1;
2333a542ad1bSJan Schmidt 
2334a542ad1bSJan Schmidt 	return 0;
2335a542ad1bSJan Schmidt }
2336a542ad1bSJan Schmidt 
2337ab8d0fc4SJeff Mahoney static int iterate_leaf_refs(struct btrfs_fs_info *fs_info,
2338ab8d0fc4SJeff Mahoney 			     struct extent_inode_elem *inode_list,
2339976b1908SJan Schmidt 			     u64 root, u64 extent_item_objectid,
23404692cf58SJan Schmidt 			     iterate_extent_inodes_t *iterate, void *ctx)
2341a542ad1bSJan Schmidt {
2342976b1908SJan Schmidt 	struct extent_inode_elem *eie;
23434692cf58SJan Schmidt 	int ret = 0;
2344a542ad1bSJan Schmidt 
2345976b1908SJan Schmidt 	for (eie = inode_list; eie; eie = eie->next) {
2346ab8d0fc4SJeff Mahoney 		btrfs_debug(fs_info,
2347ab8d0fc4SJeff Mahoney 			    "ref for %llu resolved, key (%llu EXTEND_DATA %llu), root %llu",
2348ab8d0fc4SJeff Mahoney 			    extent_item_objectid, eie->inum,
2349ab8d0fc4SJeff Mahoney 			    eie->offset, root);
2350c7499a64SFilipe Manana 		ret = iterate(eie->inum, eie->offset, eie->num_bytes, root, ctx);
23514692cf58SJan Schmidt 		if (ret) {
2352ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_info,
2353ab8d0fc4SJeff Mahoney 				    "stopping iteration for %llu due to ret=%d",
2354976b1908SJan Schmidt 				    extent_item_objectid, ret);
2355a542ad1bSJan Schmidt 			break;
2356a542ad1bSJan Schmidt 		}
2357a542ad1bSJan Schmidt 	}
2358a542ad1bSJan Schmidt 
2359a542ad1bSJan Schmidt 	return ret;
2360a542ad1bSJan Schmidt }
2361a542ad1bSJan Schmidt 
2362a542ad1bSJan Schmidt /*
2363a542ad1bSJan Schmidt  * calls iterate() for every inode that references the extent identified by
23644692cf58SJan Schmidt  * the given parameters.
2365a542ad1bSJan Schmidt  * when the iterator function returns a non-zero value, iteration stops.
2366a542ad1bSJan Schmidt  */
2367a2c8d27eSFilipe Manana int iterate_extent_inodes(struct btrfs_backref_walk_ctx *ctx,
2368a2c8d27eSFilipe Manana 			  bool search_commit_root,
2369a2c8d27eSFilipe Manana 			  iterate_extent_inodes_t *iterate, void *user_ctx)
2370a542ad1bSJan Schmidt {
2371a542ad1bSJan Schmidt 	int ret;
2372a2c8d27eSFilipe Manana 	struct ulist *refs;
2373a2c8d27eSFilipe Manana 	struct ulist_node *ref_node;
2374f3a84ccdSFilipe Manana 	struct btrfs_seq_list seq_elem = BTRFS_SEQ_LIST_INIT(seq_elem);
2375cd1b413cSJan Schmidt 	struct ulist_iterator ref_uiter;
2376a542ad1bSJan Schmidt 
2377a2c8d27eSFilipe Manana 	btrfs_debug(ctx->fs_info, "resolving all inodes for extent %llu",
2378a2c8d27eSFilipe Manana 		    ctx->bytenr);
2379a2c8d27eSFilipe Manana 
2380a2c8d27eSFilipe Manana 	ASSERT(ctx->trans == NULL);
23811baea6f1SFilipe Manana 	ASSERT(ctx->roots == NULL);
23821baea6f1SFilipe Manana 
2383da61d31aSJosef Bacik 	if (!search_commit_root) {
2384a2c8d27eSFilipe Manana 		struct btrfs_trans_handle *trans;
2385a2c8d27eSFilipe Manana 
2386a2c8d27eSFilipe Manana 		trans = btrfs_attach_transaction(ctx->fs_info->tree_root);
2387bfc61c36SFilipe Manana 		if (IS_ERR(trans)) {
2388bfc61c36SFilipe Manana 			if (PTR_ERR(trans) != -ENOENT &&
238966d04209SFilipe Manana 			    PTR_ERR(trans) != -EROFS)
23907a3ae2f8SJan Schmidt 				return PTR_ERR(trans);
2391bfc61c36SFilipe Manana 			trans = NULL;
23927a3ae2f8SJan Schmidt 		}
2393a2c8d27eSFilipe Manana 		ctx->trans = trans;
2394bfc61c36SFilipe Manana 	}
2395bfc61c36SFilipe Manana 
2396a2c8d27eSFilipe Manana 	if (ctx->trans) {
2397a2c8d27eSFilipe Manana 		btrfs_get_tree_mod_seq(ctx->fs_info, &seq_elem);
2398a2c8d27eSFilipe Manana 		ctx->time_seq = seq_elem.seq;
2399a2c8d27eSFilipe Manana 	} else {
2400a2c8d27eSFilipe Manana 		down_read(&ctx->fs_info->commit_root_sem);
2401a2c8d27eSFilipe Manana 	}
24024692cf58SJan Schmidt 
2403a2c8d27eSFilipe Manana 	ret = btrfs_find_all_leafs(ctx);
24044692cf58SJan Schmidt 	if (ret)
24054692cf58SJan Schmidt 		goto out;
2406a2c8d27eSFilipe Manana 	refs = ctx->refs;
2407a2c8d27eSFilipe Manana 	ctx->refs = NULL;
24084692cf58SJan Schmidt 
2409cd1b413cSJan Schmidt 	ULIST_ITER_INIT(&ref_uiter);
2410cd1b413cSJan Schmidt 	while (!ret && (ref_node = ulist_next(refs, &ref_uiter))) {
241166d04209SFilipe Manana 		const u64 leaf_bytenr = ref_node->val;
2412a2c8d27eSFilipe Manana 		struct ulist_node *root_node;
2413a2c8d27eSFilipe Manana 		struct ulist_iterator root_uiter;
241466d04209SFilipe Manana 		struct extent_inode_elem *inode_list;
2415a2c8d27eSFilipe Manana 
241666d04209SFilipe Manana 		inode_list = (struct extent_inode_elem *)(uintptr_t)ref_node->aux;
241766d04209SFilipe Manana 
241866d04209SFilipe Manana 		if (ctx->cache_lookup) {
241966d04209SFilipe Manana 			const u64 *root_ids;
242066d04209SFilipe Manana 			int root_count;
242166d04209SFilipe Manana 			bool cached;
242266d04209SFilipe Manana 
242366d04209SFilipe Manana 			cached = ctx->cache_lookup(leaf_bytenr, ctx->user_ctx,
242466d04209SFilipe Manana 						   &root_ids, &root_count);
242566d04209SFilipe Manana 			if (cached) {
242666d04209SFilipe Manana 				for (int i = 0; i < root_count; i++) {
242766d04209SFilipe Manana 					ret = iterate_leaf_refs(ctx->fs_info,
242866d04209SFilipe Manana 								inode_list,
242966d04209SFilipe Manana 								root_ids[i],
243066d04209SFilipe Manana 								leaf_bytenr,
243166d04209SFilipe Manana 								iterate,
243266d04209SFilipe Manana 								user_ctx);
243366d04209SFilipe Manana 					if (ret)
243466d04209SFilipe Manana 						break;
243566d04209SFilipe Manana 				}
243666d04209SFilipe Manana 				continue;
243766d04209SFilipe Manana 			}
243866d04209SFilipe Manana 		}
243966d04209SFilipe Manana 
244066d04209SFilipe Manana 		if (!ctx->roots) {
244166d04209SFilipe Manana 			ctx->roots = ulist_alloc(GFP_NOFS);
244266d04209SFilipe Manana 			if (!ctx->roots) {
244366d04209SFilipe Manana 				ret = -ENOMEM;
244466d04209SFilipe Manana 				break;
244566d04209SFilipe Manana 			}
244666d04209SFilipe Manana 		}
244766d04209SFilipe Manana 
244866d04209SFilipe Manana 		ctx->bytenr = leaf_bytenr;
2449a2c8d27eSFilipe Manana 		ret = btrfs_find_all_roots_safe(ctx);
24504692cf58SJan Schmidt 		if (ret)
2451a542ad1bSJan Schmidt 			break;
2452a2c8d27eSFilipe Manana 
245366d04209SFilipe Manana 		if (ctx->cache_store)
245466d04209SFilipe Manana 			ctx->cache_store(leaf_bytenr, ctx->roots, ctx->user_ctx);
245566d04209SFilipe Manana 
2456cd1b413cSJan Schmidt 		ULIST_ITER_INIT(&root_uiter);
2457a2c8d27eSFilipe Manana 		while (!ret && (root_node = ulist_next(ctx->roots, &root_uiter))) {
2458a2c8d27eSFilipe Manana 			btrfs_debug(ctx->fs_info,
2459ab8d0fc4SJeff Mahoney 				    "root %llu references leaf %llu, data list %#llx",
2460ab8d0fc4SJeff Mahoney 				    root_node->val, ref_node->val,
2461c1c9ff7cSGeert Uytterhoeven 				    ref_node->aux);
246266d04209SFilipe Manana 			ret = iterate_leaf_refs(ctx->fs_info, inode_list,
2463a2c8d27eSFilipe Manana 						root_node->val, ctx->bytenr,
2464a2c8d27eSFilipe Manana 						iterate, user_ctx);
24654692cf58SJan Schmidt 		}
24661baea6f1SFilipe Manana 		ulist_reinit(ctx->roots);
2467a542ad1bSJan Schmidt 	}
2468a542ad1bSJan Schmidt 
2469976b1908SJan Schmidt 	free_leaf_list(refs);
24704692cf58SJan Schmidt out:
2471a2c8d27eSFilipe Manana 	if (ctx->trans) {
2472a2c8d27eSFilipe Manana 		btrfs_put_tree_mod_seq(ctx->fs_info, &seq_elem);
2473a2c8d27eSFilipe Manana 		btrfs_end_transaction(ctx->trans);
2474a2c8d27eSFilipe Manana 		ctx->trans = NULL;
24759e351cc8SJosef Bacik 	} else {
2476a2c8d27eSFilipe Manana 		up_read(&ctx->fs_info->commit_root_sem);
24777a3ae2f8SJan Schmidt 	}
24787a3ae2f8SJan Schmidt 
24791baea6f1SFilipe Manana 	ulist_free(ctx->roots);
24801baea6f1SFilipe Manana 	ctx->roots = NULL;
24811baea6f1SFilipe Manana 
248288ffb665SFilipe Manana 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP)
248388ffb665SFilipe Manana 		ret = 0;
248488ffb665SFilipe Manana 
2485a542ad1bSJan Schmidt 	return ret;
2486a542ad1bSJan Schmidt }
2487a542ad1bSJan Schmidt 
2488c7499a64SFilipe Manana static int build_ino_list(u64 inum, u64 offset, u64 num_bytes, u64 root, void *ctx)
2489e3059ec0SDavid Sterba {
2490e3059ec0SDavid Sterba 	struct btrfs_data_container *inodes = ctx;
2491e3059ec0SDavid Sterba 	const size_t c = 3 * sizeof(u64);
2492e3059ec0SDavid Sterba 
2493e3059ec0SDavid Sterba 	if (inodes->bytes_left >= c) {
2494e3059ec0SDavid Sterba 		inodes->bytes_left -= c;
2495e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt] = inum;
2496e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt + 1] = offset;
2497e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt + 2] = root;
2498e3059ec0SDavid Sterba 		inodes->elem_cnt += 3;
2499e3059ec0SDavid Sterba 	} else {
2500e3059ec0SDavid Sterba 		inodes->bytes_missing += c - inodes->bytes_left;
2501e3059ec0SDavid Sterba 		inodes->bytes_left = 0;
2502e3059ec0SDavid Sterba 		inodes->elem_missed += 3;
2503e3059ec0SDavid Sterba 	}
2504e3059ec0SDavid Sterba 
2505e3059ec0SDavid Sterba 	return 0;
2506e3059ec0SDavid Sterba }
2507e3059ec0SDavid Sterba 
2508a542ad1bSJan Schmidt int iterate_inodes_from_logical(u64 logical, struct btrfs_fs_info *fs_info,
2509a542ad1bSJan Schmidt 				struct btrfs_path *path,
2510e3059ec0SDavid Sterba 				void *ctx, bool ignore_offset)
2511a542ad1bSJan Schmidt {
2512a2c8d27eSFilipe Manana 	struct btrfs_backref_walk_ctx walk_ctx = { 0 };
2513a542ad1bSJan Schmidt 	int ret;
251469917e43SLiu Bo 	u64 flags = 0;
2515a542ad1bSJan Schmidt 	struct btrfs_key found_key;
25167a3ae2f8SJan Schmidt 	int search_commit_root = path->search_commit_root;
2517a542ad1bSJan Schmidt 
251869917e43SLiu Bo 	ret = extent_from_logical(fs_info, logical, path, &found_key, &flags);
25194692cf58SJan Schmidt 	btrfs_release_path(path);
2520a542ad1bSJan Schmidt 	if (ret < 0)
2521a542ad1bSJan Schmidt 		return ret;
252269917e43SLiu Bo 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
25233627bf45SStefan Behrens 		return -EINVAL;
2524a542ad1bSJan Schmidt 
2525a2c8d27eSFilipe Manana 	walk_ctx.bytenr = found_key.objectid;
25266ce6ba53SFilipe Manana 	if (ignore_offset)
2527a2c8d27eSFilipe Manana 		walk_ctx.ignore_extent_item_pos = true;
25286ce6ba53SFilipe Manana 	else
2529a2c8d27eSFilipe Manana 		walk_ctx.extent_item_pos = logical - found_key.objectid;
2530a2c8d27eSFilipe Manana 	walk_ctx.fs_info = fs_info;
25316ce6ba53SFilipe Manana 
2532a2c8d27eSFilipe Manana 	return iterate_extent_inodes(&walk_ctx, search_commit_root,
25336ce6ba53SFilipe Manana 				     build_ino_list, ctx);
2534a542ad1bSJan Schmidt }
2535a542ad1bSJan Schmidt 
2536ad6240f6SDavid Sterba static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2537875d1daaSDavid Sterba 			 struct extent_buffer *eb, struct inode_fs_paths *ipath);
2538d24bec3aSMark Fasheh 
2539875d1daaSDavid Sterba static int iterate_inode_refs(u64 inum, struct inode_fs_paths *ipath)
2540a542ad1bSJan Schmidt {
2541aefc1eb1SJan Schmidt 	int ret = 0;
2542a542ad1bSJan Schmidt 	int slot;
2543a542ad1bSJan Schmidt 	u32 cur;
2544a542ad1bSJan Schmidt 	u32 len;
2545a542ad1bSJan Schmidt 	u32 name_len;
2546a542ad1bSJan Schmidt 	u64 parent = 0;
2547a542ad1bSJan Schmidt 	int found = 0;
2548875d1daaSDavid Sterba 	struct btrfs_root *fs_root = ipath->fs_root;
2549875d1daaSDavid Sterba 	struct btrfs_path *path = ipath->btrfs_path;
2550a542ad1bSJan Schmidt 	struct extent_buffer *eb;
2551a542ad1bSJan Schmidt 	struct btrfs_inode_ref *iref;
2552a542ad1bSJan Schmidt 	struct btrfs_key found_key;
2553a542ad1bSJan Schmidt 
2554aefc1eb1SJan Schmidt 	while (!ret) {
2555c234a24dSDavid Sterba 		ret = btrfs_find_item(fs_root, path, inum,
2556c234a24dSDavid Sterba 				parent ? parent + 1 : 0, BTRFS_INODE_REF_KEY,
2557a542ad1bSJan Schmidt 				&found_key);
2558c234a24dSDavid Sterba 
2559a542ad1bSJan Schmidt 		if (ret < 0)
2560a542ad1bSJan Schmidt 			break;
2561a542ad1bSJan Schmidt 		if (ret) {
2562a542ad1bSJan Schmidt 			ret = found ? 0 : -ENOENT;
2563a542ad1bSJan Schmidt 			break;
2564a542ad1bSJan Schmidt 		}
2565a542ad1bSJan Schmidt 		++found;
2566a542ad1bSJan Schmidt 
2567a542ad1bSJan Schmidt 		parent = found_key.offset;
2568a542ad1bSJan Schmidt 		slot = path->slots[0];
25693fe81ce2SFilipe David Borba Manana 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
25703fe81ce2SFilipe David Borba Manana 		if (!eb) {
25713fe81ce2SFilipe David Borba Manana 			ret = -ENOMEM;
25723fe81ce2SFilipe David Borba Manana 			break;
25733fe81ce2SFilipe David Borba Manana 		}
2574a542ad1bSJan Schmidt 		btrfs_release_path(path);
2575a542ad1bSJan Schmidt 
2576a542ad1bSJan Schmidt 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2577a542ad1bSJan Schmidt 
25783212fa14SJosef Bacik 		for (cur = 0; cur < btrfs_item_size(eb, slot); cur += len) {
2579a542ad1bSJan Schmidt 			name_len = btrfs_inode_ref_name_len(eb, iref);
2580a542ad1bSJan Schmidt 			/* path must be released before calling iterate()! */
2581ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_root->fs_info,
2582ab8d0fc4SJeff Mahoney 				"following ref at offset %u for inode %llu in tree %llu",
25834fd786e6SMisono Tomohiro 				cur, found_key.objectid,
25844fd786e6SMisono Tomohiro 				fs_root->root_key.objectid);
2585ad6240f6SDavid Sterba 			ret = inode_to_path(parent, name_len,
2586875d1daaSDavid Sterba 				      (unsigned long)(iref + 1), eb, ipath);
2587aefc1eb1SJan Schmidt 			if (ret)
2588a542ad1bSJan Schmidt 				break;
2589a542ad1bSJan Schmidt 			len = sizeof(*iref) + name_len;
2590a542ad1bSJan Schmidt 			iref = (struct btrfs_inode_ref *)((char *)iref + len);
2591a542ad1bSJan Schmidt 		}
2592a542ad1bSJan Schmidt 		free_extent_buffer(eb);
2593a542ad1bSJan Schmidt 	}
2594a542ad1bSJan Schmidt 
2595a542ad1bSJan Schmidt 	btrfs_release_path(path);
2596a542ad1bSJan Schmidt 
2597a542ad1bSJan Schmidt 	return ret;
2598a542ad1bSJan Schmidt }
2599a542ad1bSJan Schmidt 
2600875d1daaSDavid Sterba static int iterate_inode_extrefs(u64 inum, struct inode_fs_paths *ipath)
2601d24bec3aSMark Fasheh {
2602d24bec3aSMark Fasheh 	int ret;
2603d24bec3aSMark Fasheh 	int slot;
2604d24bec3aSMark Fasheh 	u64 offset = 0;
2605d24bec3aSMark Fasheh 	u64 parent;
2606d24bec3aSMark Fasheh 	int found = 0;
2607875d1daaSDavid Sterba 	struct btrfs_root *fs_root = ipath->fs_root;
2608875d1daaSDavid Sterba 	struct btrfs_path *path = ipath->btrfs_path;
2609d24bec3aSMark Fasheh 	struct extent_buffer *eb;
2610d24bec3aSMark Fasheh 	struct btrfs_inode_extref *extref;
2611d24bec3aSMark Fasheh 	u32 item_size;
2612d24bec3aSMark Fasheh 	u32 cur_offset;
2613d24bec3aSMark Fasheh 	unsigned long ptr;
2614d24bec3aSMark Fasheh 
2615d24bec3aSMark Fasheh 	while (1) {
2616d24bec3aSMark Fasheh 		ret = btrfs_find_one_extref(fs_root, inum, offset, path, &extref,
2617d24bec3aSMark Fasheh 					    &offset);
2618d24bec3aSMark Fasheh 		if (ret < 0)
2619d24bec3aSMark Fasheh 			break;
2620d24bec3aSMark Fasheh 		if (ret) {
2621d24bec3aSMark Fasheh 			ret = found ? 0 : -ENOENT;
2622d24bec3aSMark Fasheh 			break;
2623d24bec3aSMark Fasheh 		}
2624d24bec3aSMark Fasheh 		++found;
2625d24bec3aSMark Fasheh 
2626d24bec3aSMark Fasheh 		slot = path->slots[0];
26273fe81ce2SFilipe David Borba Manana 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
26283fe81ce2SFilipe David Borba Manana 		if (!eb) {
26293fe81ce2SFilipe David Borba Manana 			ret = -ENOMEM;
26303fe81ce2SFilipe David Borba Manana 			break;
26313fe81ce2SFilipe David Borba Manana 		}
2632d24bec3aSMark Fasheh 		btrfs_release_path(path);
2633d24bec3aSMark Fasheh 
26343212fa14SJosef Bacik 		item_size = btrfs_item_size(eb, slot);
26352849a854SChris Mason 		ptr = btrfs_item_ptr_offset(eb, slot);
2636d24bec3aSMark Fasheh 		cur_offset = 0;
2637d24bec3aSMark Fasheh 
2638d24bec3aSMark Fasheh 		while (cur_offset < item_size) {
2639d24bec3aSMark Fasheh 			u32 name_len;
2640d24bec3aSMark Fasheh 
2641d24bec3aSMark Fasheh 			extref = (struct btrfs_inode_extref *)(ptr + cur_offset);
2642d24bec3aSMark Fasheh 			parent = btrfs_inode_extref_parent(eb, extref);
2643d24bec3aSMark Fasheh 			name_len = btrfs_inode_extref_name_len(eb, extref);
2644ad6240f6SDavid Sterba 			ret = inode_to_path(parent, name_len,
2645875d1daaSDavid Sterba 				      (unsigned long)&extref->name, eb, ipath);
2646d24bec3aSMark Fasheh 			if (ret)
2647d24bec3aSMark Fasheh 				break;
2648d24bec3aSMark Fasheh 
26492849a854SChris Mason 			cur_offset += btrfs_inode_extref_name_len(eb, extref);
2650d24bec3aSMark Fasheh 			cur_offset += sizeof(*extref);
2651d24bec3aSMark Fasheh 		}
2652d24bec3aSMark Fasheh 		free_extent_buffer(eb);
2653d24bec3aSMark Fasheh 
2654d24bec3aSMark Fasheh 		offset++;
2655d24bec3aSMark Fasheh 	}
2656d24bec3aSMark Fasheh 
2657d24bec3aSMark Fasheh 	btrfs_release_path(path);
2658d24bec3aSMark Fasheh 
2659d24bec3aSMark Fasheh 	return ret;
2660d24bec3aSMark Fasheh }
2661d24bec3aSMark Fasheh 
2662a542ad1bSJan Schmidt /*
2663a542ad1bSJan Schmidt  * returns 0 if the path could be dumped (probably truncated)
2664a542ad1bSJan Schmidt  * returns <0 in case of an error
2665a542ad1bSJan Schmidt  */
2666d24bec3aSMark Fasheh static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2667875d1daaSDavid Sterba 			 struct extent_buffer *eb, struct inode_fs_paths *ipath)
2668a542ad1bSJan Schmidt {
2669a542ad1bSJan Schmidt 	char *fspath;
2670a542ad1bSJan Schmidt 	char *fspath_min;
2671a542ad1bSJan Schmidt 	int i = ipath->fspath->elem_cnt;
2672a542ad1bSJan Schmidt 	const int s_ptr = sizeof(char *);
2673a542ad1bSJan Schmidt 	u32 bytes_left;
2674a542ad1bSJan Schmidt 
2675a542ad1bSJan Schmidt 	bytes_left = ipath->fspath->bytes_left > s_ptr ?
2676a542ad1bSJan Schmidt 					ipath->fspath->bytes_left - s_ptr : 0;
2677a542ad1bSJan Schmidt 
2678740c3d22SChris Mason 	fspath_min = (char *)ipath->fspath->val + (i + 1) * s_ptr;
267996b5bd77SJan Schmidt 	fspath = btrfs_ref_to_path(ipath->fs_root, ipath->btrfs_path, name_len,
268096b5bd77SJan Schmidt 				   name_off, eb, inum, fspath_min, bytes_left);
2681a542ad1bSJan Schmidt 	if (IS_ERR(fspath))
2682a542ad1bSJan Schmidt 		return PTR_ERR(fspath);
2683a542ad1bSJan Schmidt 
2684a542ad1bSJan Schmidt 	if (fspath > fspath_min) {
2685745c4d8eSJeff Mahoney 		ipath->fspath->val[i] = (u64)(unsigned long)fspath;
2686a542ad1bSJan Schmidt 		++ipath->fspath->elem_cnt;
2687a542ad1bSJan Schmidt 		ipath->fspath->bytes_left = fspath - fspath_min;
2688a542ad1bSJan Schmidt 	} else {
2689a542ad1bSJan Schmidt 		++ipath->fspath->elem_missed;
2690a542ad1bSJan Schmidt 		ipath->fspath->bytes_missing += fspath_min - fspath;
2691a542ad1bSJan Schmidt 		ipath->fspath->bytes_left = 0;
2692a542ad1bSJan Schmidt 	}
2693a542ad1bSJan Schmidt 
2694a542ad1bSJan Schmidt 	return 0;
2695a542ad1bSJan Schmidt }
2696a542ad1bSJan Schmidt 
2697a542ad1bSJan Schmidt /*
2698a542ad1bSJan Schmidt  * this dumps all file system paths to the inode into the ipath struct, provided
2699a542ad1bSJan Schmidt  * is has been created large enough. each path is zero-terminated and accessed
2700740c3d22SChris Mason  * from ipath->fspath->val[i].
2701a542ad1bSJan Schmidt  * when it returns, there are ipath->fspath->elem_cnt number of paths available
2702740c3d22SChris Mason  * in ipath->fspath->val[]. when the allocated space wasn't sufficient, the
270301327610SNicholas D Steeves  * number of missed paths is recorded in ipath->fspath->elem_missed, otherwise,
2704a542ad1bSJan Schmidt  * it's zero. ipath->fspath->bytes_missing holds the number of bytes that would
2705a542ad1bSJan Schmidt  * have been needed to return all paths.
2706a542ad1bSJan Schmidt  */
2707a542ad1bSJan Schmidt int paths_from_inode(u64 inum, struct inode_fs_paths *ipath)
2708a542ad1bSJan Schmidt {
2709ad6240f6SDavid Sterba 	int ret;
2710ad6240f6SDavid Sterba 	int found_refs = 0;
2711ad6240f6SDavid Sterba 
2712875d1daaSDavid Sterba 	ret = iterate_inode_refs(inum, ipath);
2713ad6240f6SDavid Sterba 	if (!ret)
2714ad6240f6SDavid Sterba 		++found_refs;
2715ad6240f6SDavid Sterba 	else if (ret != -ENOENT)
2716ad6240f6SDavid Sterba 		return ret;
2717ad6240f6SDavid Sterba 
2718875d1daaSDavid Sterba 	ret = iterate_inode_extrefs(inum, ipath);
2719ad6240f6SDavid Sterba 	if (ret == -ENOENT && found_refs)
2720ad6240f6SDavid Sterba 		return 0;
2721ad6240f6SDavid Sterba 
2722ad6240f6SDavid Sterba 	return ret;
2723a542ad1bSJan Schmidt }
2724a542ad1bSJan Schmidt 
2725a542ad1bSJan Schmidt struct btrfs_data_container *init_data_container(u32 total_bytes)
2726a542ad1bSJan Schmidt {
2727a542ad1bSJan Schmidt 	struct btrfs_data_container *data;
2728a542ad1bSJan Schmidt 	size_t alloc_bytes;
2729a542ad1bSJan Schmidt 
2730a542ad1bSJan Schmidt 	alloc_bytes = max_t(size_t, total_bytes, sizeof(*data));
2731f54de068SDavid Sterba 	data = kvmalloc(alloc_bytes, GFP_KERNEL);
2732a542ad1bSJan Schmidt 	if (!data)
2733a542ad1bSJan Schmidt 		return ERR_PTR(-ENOMEM);
2734a542ad1bSJan Schmidt 
2735a542ad1bSJan Schmidt 	if (total_bytes >= sizeof(*data)) {
2736a542ad1bSJan Schmidt 		data->bytes_left = total_bytes - sizeof(*data);
2737a542ad1bSJan Schmidt 		data->bytes_missing = 0;
2738a542ad1bSJan Schmidt 	} else {
2739a542ad1bSJan Schmidt 		data->bytes_missing = sizeof(*data) - total_bytes;
2740a542ad1bSJan Schmidt 		data->bytes_left = 0;
2741a542ad1bSJan Schmidt 	}
2742a542ad1bSJan Schmidt 
2743a542ad1bSJan Schmidt 	data->elem_cnt = 0;
2744a542ad1bSJan Schmidt 	data->elem_missed = 0;
2745a542ad1bSJan Schmidt 
2746a542ad1bSJan Schmidt 	return data;
2747a542ad1bSJan Schmidt }
2748a542ad1bSJan Schmidt 
2749a542ad1bSJan Schmidt /*
2750a542ad1bSJan Schmidt  * allocates space to return multiple file system paths for an inode.
2751a542ad1bSJan Schmidt  * total_bytes to allocate are passed, note that space usable for actual path
2752a542ad1bSJan Schmidt  * information will be total_bytes - sizeof(struct inode_fs_paths).
2753a542ad1bSJan Schmidt  * the returned pointer must be freed with free_ipath() in the end.
2754a542ad1bSJan Schmidt  */
2755a542ad1bSJan Schmidt struct inode_fs_paths *init_ipath(s32 total_bytes, struct btrfs_root *fs_root,
2756a542ad1bSJan Schmidt 					struct btrfs_path *path)
2757a542ad1bSJan Schmidt {
2758a542ad1bSJan Schmidt 	struct inode_fs_paths *ifp;
2759a542ad1bSJan Schmidt 	struct btrfs_data_container *fspath;
2760a542ad1bSJan Schmidt 
2761a542ad1bSJan Schmidt 	fspath = init_data_container(total_bytes);
2762a542ad1bSJan Schmidt 	if (IS_ERR(fspath))
2763afc6961fSMisono Tomohiro 		return ERR_CAST(fspath);
2764a542ad1bSJan Schmidt 
2765f54de068SDavid Sterba 	ifp = kmalloc(sizeof(*ifp), GFP_KERNEL);
2766a542ad1bSJan Schmidt 	if (!ifp) {
2767f54de068SDavid Sterba 		kvfree(fspath);
2768a542ad1bSJan Schmidt 		return ERR_PTR(-ENOMEM);
2769a542ad1bSJan Schmidt 	}
2770a542ad1bSJan Schmidt 
2771a542ad1bSJan Schmidt 	ifp->btrfs_path = path;
2772a542ad1bSJan Schmidt 	ifp->fspath = fspath;
2773a542ad1bSJan Schmidt 	ifp->fs_root = fs_root;
2774a542ad1bSJan Schmidt 
2775a542ad1bSJan Schmidt 	return ifp;
2776a542ad1bSJan Schmidt }
2777a542ad1bSJan Schmidt 
2778a542ad1bSJan Schmidt void free_ipath(struct inode_fs_paths *ipath)
2779a542ad1bSJan Schmidt {
27804735fb28SJesper Juhl 	if (!ipath)
27814735fb28SJesper Juhl 		return;
2782f54de068SDavid Sterba 	kvfree(ipath->fspath);
2783a542ad1bSJan Schmidt 	kfree(ipath);
2784a542ad1bSJan Schmidt }
2785a37f232bSQu Wenruo 
2786d68194b2SDavid Sterba struct btrfs_backref_iter *btrfs_backref_iter_alloc(struct btrfs_fs_info *fs_info)
2787a37f232bSQu Wenruo {
2788a37f232bSQu Wenruo 	struct btrfs_backref_iter *ret;
2789a37f232bSQu Wenruo 
2790d68194b2SDavid Sterba 	ret = kzalloc(sizeof(*ret), GFP_NOFS);
2791a37f232bSQu Wenruo 	if (!ret)
2792a37f232bSQu Wenruo 		return NULL;
2793a37f232bSQu Wenruo 
2794a37f232bSQu Wenruo 	ret->path = btrfs_alloc_path();
2795c15c2ec0SBoleyn Su 	if (!ret->path) {
2796a37f232bSQu Wenruo 		kfree(ret);
2797a37f232bSQu Wenruo 		return NULL;
2798a37f232bSQu Wenruo 	}
2799a37f232bSQu Wenruo 
2800a37f232bSQu Wenruo 	/* Current backref iterator only supports iteration in commit root */
2801a37f232bSQu Wenruo 	ret->path->search_commit_root = 1;
2802a37f232bSQu Wenruo 	ret->path->skip_locking = 1;
2803a37f232bSQu Wenruo 	ret->fs_info = fs_info;
2804a37f232bSQu Wenruo 
2805a37f232bSQu Wenruo 	return ret;
2806a37f232bSQu Wenruo }
2807a37f232bSQu Wenruo 
2808a37f232bSQu Wenruo int btrfs_backref_iter_start(struct btrfs_backref_iter *iter, u64 bytenr)
2809a37f232bSQu Wenruo {
2810a37f232bSQu Wenruo 	struct btrfs_fs_info *fs_info = iter->fs_info;
281129cbcf40SJosef Bacik 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2812a37f232bSQu Wenruo 	struct btrfs_path *path = iter->path;
2813a37f232bSQu Wenruo 	struct btrfs_extent_item *ei;
2814a37f232bSQu Wenruo 	struct btrfs_key key;
2815a37f232bSQu Wenruo 	int ret;
2816a37f232bSQu Wenruo 
2817a37f232bSQu Wenruo 	key.objectid = bytenr;
2818a37f232bSQu Wenruo 	key.type = BTRFS_METADATA_ITEM_KEY;
2819a37f232bSQu Wenruo 	key.offset = (u64)-1;
2820a37f232bSQu Wenruo 	iter->bytenr = bytenr;
2821a37f232bSQu Wenruo 
282229cbcf40SJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2823a37f232bSQu Wenruo 	if (ret < 0)
2824a37f232bSQu Wenruo 		return ret;
2825a37f232bSQu Wenruo 	if (ret == 0) {
2826a37f232bSQu Wenruo 		ret = -EUCLEAN;
2827a37f232bSQu Wenruo 		goto release;
2828a37f232bSQu Wenruo 	}
2829a37f232bSQu Wenruo 	if (path->slots[0] == 0) {
2830a37f232bSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
2831a37f232bSQu Wenruo 		ret = -EUCLEAN;
2832a37f232bSQu Wenruo 		goto release;
2833a37f232bSQu Wenruo 	}
2834a37f232bSQu Wenruo 	path->slots[0]--;
2835a37f232bSQu Wenruo 
2836a37f232bSQu Wenruo 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2837a37f232bSQu Wenruo 	if ((key.type != BTRFS_EXTENT_ITEM_KEY &&
2838a37f232bSQu Wenruo 	     key.type != BTRFS_METADATA_ITEM_KEY) || key.objectid != bytenr) {
2839a37f232bSQu Wenruo 		ret = -ENOENT;
2840a37f232bSQu Wenruo 		goto release;
2841a37f232bSQu Wenruo 	}
2842a37f232bSQu Wenruo 	memcpy(&iter->cur_key, &key, sizeof(key));
2843a37f232bSQu Wenruo 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2844a37f232bSQu Wenruo 						    path->slots[0]);
2845a37f232bSQu Wenruo 	iter->end_ptr = (u32)(iter->item_ptr +
28463212fa14SJosef Bacik 			btrfs_item_size(path->nodes[0], path->slots[0]));
2847a37f232bSQu Wenruo 	ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
2848a37f232bSQu Wenruo 			    struct btrfs_extent_item);
2849a37f232bSQu Wenruo 
2850a37f232bSQu Wenruo 	/*
2851a37f232bSQu Wenruo 	 * Only support iteration on tree backref yet.
2852a37f232bSQu Wenruo 	 *
2853a37f232bSQu Wenruo 	 * This is an extra precaution for non skinny-metadata, where
2854a37f232bSQu Wenruo 	 * EXTENT_ITEM is also used for tree blocks, that we can only use
2855a37f232bSQu Wenruo 	 * extent flags to determine if it's a tree block.
2856a37f232bSQu Wenruo 	 */
2857a37f232bSQu Wenruo 	if (btrfs_extent_flags(path->nodes[0], ei) & BTRFS_EXTENT_FLAG_DATA) {
2858a37f232bSQu Wenruo 		ret = -ENOTSUPP;
2859a37f232bSQu Wenruo 		goto release;
2860a37f232bSQu Wenruo 	}
2861a37f232bSQu Wenruo 	iter->cur_ptr = (u32)(iter->item_ptr + sizeof(*ei));
2862a37f232bSQu Wenruo 
2863a37f232bSQu Wenruo 	/* If there is no inline backref, go search for keyed backref */
2864a37f232bSQu Wenruo 	if (iter->cur_ptr >= iter->end_ptr) {
286529cbcf40SJosef Bacik 		ret = btrfs_next_item(extent_root, path);
2866a37f232bSQu Wenruo 
2867a37f232bSQu Wenruo 		/* No inline nor keyed ref */
2868a37f232bSQu Wenruo 		if (ret > 0) {
2869a37f232bSQu Wenruo 			ret = -ENOENT;
2870a37f232bSQu Wenruo 			goto release;
2871a37f232bSQu Wenruo 		}
2872a37f232bSQu Wenruo 		if (ret < 0)
2873a37f232bSQu Wenruo 			goto release;
2874a37f232bSQu Wenruo 
2875a37f232bSQu Wenruo 		btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key,
2876a37f232bSQu Wenruo 				path->slots[0]);
2877a37f232bSQu Wenruo 		if (iter->cur_key.objectid != bytenr ||
2878a37f232bSQu Wenruo 		    (iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
2879a37f232bSQu Wenruo 		     iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY)) {
2880a37f232bSQu Wenruo 			ret = -ENOENT;
2881a37f232bSQu Wenruo 			goto release;
2882a37f232bSQu Wenruo 		}
2883a37f232bSQu Wenruo 		iter->cur_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2884a37f232bSQu Wenruo 							   path->slots[0]);
2885a37f232bSQu Wenruo 		iter->item_ptr = iter->cur_ptr;
28863212fa14SJosef Bacik 		iter->end_ptr = (u32)(iter->item_ptr + btrfs_item_size(
2887a37f232bSQu Wenruo 				      path->nodes[0], path->slots[0]));
2888a37f232bSQu Wenruo 	}
2889a37f232bSQu Wenruo 
2890a37f232bSQu Wenruo 	return 0;
2891a37f232bSQu Wenruo release:
2892a37f232bSQu Wenruo 	btrfs_backref_iter_release(iter);
2893a37f232bSQu Wenruo 	return ret;
2894a37f232bSQu Wenruo }
2895c39c2ddcSQu Wenruo 
2896c39c2ddcSQu Wenruo /*
2897c39c2ddcSQu Wenruo  * Go to the next backref item of current bytenr, can be either inlined or
2898c39c2ddcSQu Wenruo  * keyed.
2899c39c2ddcSQu Wenruo  *
2900c39c2ddcSQu Wenruo  * Caller needs to check whether it's inline ref or not by iter->cur_key.
2901c39c2ddcSQu Wenruo  *
2902c39c2ddcSQu Wenruo  * Return 0 if we get next backref without problem.
2903c39c2ddcSQu Wenruo  * Return >0 if there is no extra backref for this bytenr.
2904c39c2ddcSQu Wenruo  * Return <0 if there is something wrong happened.
2905c39c2ddcSQu Wenruo  */
2906c39c2ddcSQu Wenruo int btrfs_backref_iter_next(struct btrfs_backref_iter *iter)
2907c39c2ddcSQu Wenruo {
2908c39c2ddcSQu Wenruo 	struct extent_buffer *eb = btrfs_backref_get_eb(iter);
290929cbcf40SJosef Bacik 	struct btrfs_root *extent_root;
2910c39c2ddcSQu Wenruo 	struct btrfs_path *path = iter->path;
2911c39c2ddcSQu Wenruo 	struct btrfs_extent_inline_ref *iref;
2912c39c2ddcSQu Wenruo 	int ret;
2913c39c2ddcSQu Wenruo 	u32 size;
2914c39c2ddcSQu Wenruo 
2915c39c2ddcSQu Wenruo 	if (btrfs_backref_iter_is_inline_ref(iter)) {
2916c39c2ddcSQu Wenruo 		/* We're still inside the inline refs */
2917c39c2ddcSQu Wenruo 		ASSERT(iter->cur_ptr < iter->end_ptr);
2918c39c2ddcSQu Wenruo 
2919c39c2ddcSQu Wenruo 		if (btrfs_backref_has_tree_block_info(iter)) {
2920c39c2ddcSQu Wenruo 			/* First tree block info */
2921c39c2ddcSQu Wenruo 			size = sizeof(struct btrfs_tree_block_info);
2922c39c2ddcSQu Wenruo 		} else {
2923c39c2ddcSQu Wenruo 			/* Use inline ref type to determine the size */
2924c39c2ddcSQu Wenruo 			int type;
2925c39c2ddcSQu Wenruo 
2926c39c2ddcSQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
2927c39c2ddcSQu Wenruo 				((unsigned long)iter->cur_ptr);
2928c39c2ddcSQu Wenruo 			type = btrfs_extent_inline_ref_type(eb, iref);
2929c39c2ddcSQu Wenruo 
2930c39c2ddcSQu Wenruo 			size = btrfs_extent_inline_ref_size(type);
2931c39c2ddcSQu Wenruo 		}
2932c39c2ddcSQu Wenruo 		iter->cur_ptr += size;
2933c39c2ddcSQu Wenruo 		if (iter->cur_ptr < iter->end_ptr)
2934c39c2ddcSQu Wenruo 			return 0;
2935c39c2ddcSQu Wenruo 
2936c39c2ddcSQu Wenruo 		/* All inline items iterated, fall through */
2937c39c2ddcSQu Wenruo 	}
2938c39c2ddcSQu Wenruo 
2939c39c2ddcSQu Wenruo 	/* We're at keyed items, there is no inline item, go to the next one */
294029cbcf40SJosef Bacik 	extent_root = btrfs_extent_root(iter->fs_info, iter->bytenr);
294129cbcf40SJosef Bacik 	ret = btrfs_next_item(extent_root, iter->path);
2942c39c2ddcSQu Wenruo 	if (ret)
2943c39c2ddcSQu Wenruo 		return ret;
2944c39c2ddcSQu Wenruo 
2945c39c2ddcSQu Wenruo 	btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key, path->slots[0]);
2946c39c2ddcSQu Wenruo 	if (iter->cur_key.objectid != iter->bytenr ||
2947c39c2ddcSQu Wenruo 	    (iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
2948c39c2ddcSQu Wenruo 	     iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY))
2949c39c2ddcSQu Wenruo 		return 1;
2950c39c2ddcSQu Wenruo 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2951c39c2ddcSQu Wenruo 					path->slots[0]);
2952c39c2ddcSQu Wenruo 	iter->cur_ptr = iter->item_ptr;
29533212fa14SJosef Bacik 	iter->end_ptr = iter->item_ptr + (u32)btrfs_item_size(path->nodes[0],
2954c39c2ddcSQu Wenruo 						path->slots[0]);
2955c39c2ddcSQu Wenruo 	return 0;
2956c39c2ddcSQu Wenruo }
2957584fb121SQu Wenruo 
2958584fb121SQu Wenruo void btrfs_backref_init_cache(struct btrfs_fs_info *fs_info,
2959584fb121SQu Wenruo 			      struct btrfs_backref_cache *cache, int is_reloc)
2960584fb121SQu Wenruo {
2961584fb121SQu Wenruo 	int i;
2962584fb121SQu Wenruo 
2963584fb121SQu Wenruo 	cache->rb_root = RB_ROOT;
2964584fb121SQu Wenruo 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
2965584fb121SQu Wenruo 		INIT_LIST_HEAD(&cache->pending[i]);
2966584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->changed);
2967584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->detached);
2968584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->leaves);
2969584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->pending_edge);
2970584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->useless_node);
2971584fb121SQu Wenruo 	cache->fs_info = fs_info;
2972584fb121SQu Wenruo 	cache->is_reloc = is_reloc;
2973584fb121SQu Wenruo }
2974b1818dabSQu Wenruo 
2975b1818dabSQu Wenruo struct btrfs_backref_node *btrfs_backref_alloc_node(
2976b1818dabSQu Wenruo 		struct btrfs_backref_cache *cache, u64 bytenr, int level)
2977b1818dabSQu Wenruo {
2978b1818dabSQu Wenruo 	struct btrfs_backref_node *node;
2979b1818dabSQu Wenruo 
2980b1818dabSQu Wenruo 	ASSERT(level >= 0 && level < BTRFS_MAX_LEVEL);
2981b1818dabSQu Wenruo 	node = kzalloc(sizeof(*node), GFP_NOFS);
2982b1818dabSQu Wenruo 	if (!node)
2983b1818dabSQu Wenruo 		return node;
2984b1818dabSQu Wenruo 
2985b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->list);
2986b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->upper);
2987b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->lower);
2988b1818dabSQu Wenruo 	RB_CLEAR_NODE(&node->rb_node);
2989b1818dabSQu Wenruo 	cache->nr_nodes++;
2990b1818dabSQu Wenruo 	node->level = level;
2991b1818dabSQu Wenruo 	node->bytenr = bytenr;
2992b1818dabSQu Wenruo 
2993b1818dabSQu Wenruo 	return node;
2994b1818dabSQu Wenruo }
299547254d07SQu Wenruo 
299647254d07SQu Wenruo struct btrfs_backref_edge *btrfs_backref_alloc_edge(
299747254d07SQu Wenruo 		struct btrfs_backref_cache *cache)
299847254d07SQu Wenruo {
299947254d07SQu Wenruo 	struct btrfs_backref_edge *edge;
300047254d07SQu Wenruo 
300147254d07SQu Wenruo 	edge = kzalloc(sizeof(*edge), GFP_NOFS);
300247254d07SQu Wenruo 	if (edge)
300347254d07SQu Wenruo 		cache->nr_edges++;
300447254d07SQu Wenruo 	return edge;
300547254d07SQu Wenruo }
3006023acb07SQu Wenruo 
3007023acb07SQu Wenruo /*
3008023acb07SQu Wenruo  * Drop the backref node from cache, also cleaning up all its
3009023acb07SQu Wenruo  * upper edges and any uncached nodes in the path.
3010023acb07SQu Wenruo  *
3011023acb07SQu Wenruo  * This cleanup happens bottom up, thus the node should either
3012023acb07SQu Wenruo  * be the lowest node in the cache or a detached node.
3013023acb07SQu Wenruo  */
3014023acb07SQu Wenruo void btrfs_backref_cleanup_node(struct btrfs_backref_cache *cache,
3015023acb07SQu Wenruo 				struct btrfs_backref_node *node)
3016023acb07SQu Wenruo {
3017023acb07SQu Wenruo 	struct btrfs_backref_node *upper;
3018023acb07SQu Wenruo 	struct btrfs_backref_edge *edge;
3019023acb07SQu Wenruo 
3020023acb07SQu Wenruo 	if (!node)
3021023acb07SQu Wenruo 		return;
3022023acb07SQu Wenruo 
3023023acb07SQu Wenruo 	BUG_ON(!node->lowest && !node->detached);
3024023acb07SQu Wenruo 	while (!list_empty(&node->upper)) {
3025023acb07SQu Wenruo 		edge = list_entry(node->upper.next, struct btrfs_backref_edge,
3026023acb07SQu Wenruo 				  list[LOWER]);
3027023acb07SQu Wenruo 		upper = edge->node[UPPER];
3028023acb07SQu Wenruo 		list_del(&edge->list[LOWER]);
3029023acb07SQu Wenruo 		list_del(&edge->list[UPPER]);
3030023acb07SQu Wenruo 		btrfs_backref_free_edge(cache, edge);
3031023acb07SQu Wenruo 
3032023acb07SQu Wenruo 		/*
3033023acb07SQu Wenruo 		 * Add the node to leaf node list if no other child block
3034023acb07SQu Wenruo 		 * cached.
3035023acb07SQu Wenruo 		 */
3036023acb07SQu Wenruo 		if (list_empty(&upper->lower)) {
3037023acb07SQu Wenruo 			list_add_tail(&upper->lower, &cache->leaves);
3038023acb07SQu Wenruo 			upper->lowest = 1;
3039023acb07SQu Wenruo 		}
3040023acb07SQu Wenruo 	}
3041023acb07SQu Wenruo 
3042023acb07SQu Wenruo 	btrfs_backref_drop_node(cache, node);
3043023acb07SQu Wenruo }
304413fe1bdbSQu Wenruo 
304513fe1bdbSQu Wenruo /*
304613fe1bdbSQu Wenruo  * Release all nodes/edges from current cache
304713fe1bdbSQu Wenruo  */
304813fe1bdbSQu Wenruo void btrfs_backref_release_cache(struct btrfs_backref_cache *cache)
304913fe1bdbSQu Wenruo {
305013fe1bdbSQu Wenruo 	struct btrfs_backref_node *node;
305113fe1bdbSQu Wenruo 	int i;
305213fe1bdbSQu Wenruo 
305313fe1bdbSQu Wenruo 	while (!list_empty(&cache->detached)) {
305413fe1bdbSQu Wenruo 		node = list_entry(cache->detached.next,
305513fe1bdbSQu Wenruo 				  struct btrfs_backref_node, list);
305613fe1bdbSQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
305713fe1bdbSQu Wenruo 	}
305813fe1bdbSQu Wenruo 
305913fe1bdbSQu Wenruo 	while (!list_empty(&cache->leaves)) {
306013fe1bdbSQu Wenruo 		node = list_entry(cache->leaves.next,
306113fe1bdbSQu Wenruo 				  struct btrfs_backref_node, lower);
306213fe1bdbSQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
306313fe1bdbSQu Wenruo 	}
306413fe1bdbSQu Wenruo 
306513fe1bdbSQu Wenruo 	cache->last_trans = 0;
306613fe1bdbSQu Wenruo 
306713fe1bdbSQu Wenruo 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
306813fe1bdbSQu Wenruo 		ASSERT(list_empty(&cache->pending[i]));
306913fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->pending_edge));
307013fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->useless_node));
307113fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->changed));
307213fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->detached));
307313fe1bdbSQu Wenruo 	ASSERT(RB_EMPTY_ROOT(&cache->rb_root));
307413fe1bdbSQu Wenruo 	ASSERT(!cache->nr_nodes);
307513fe1bdbSQu Wenruo 	ASSERT(!cache->nr_edges);
307613fe1bdbSQu Wenruo }
30771b60d2ecSQu Wenruo 
30781b60d2ecSQu Wenruo /*
30791b60d2ecSQu Wenruo  * Handle direct tree backref
30801b60d2ecSQu Wenruo  *
30811b60d2ecSQu Wenruo  * Direct tree backref means, the backref item shows its parent bytenr
30821b60d2ecSQu Wenruo  * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
30831b60d2ecSQu Wenruo  *
30841b60d2ecSQu Wenruo  * @ref_key:	The converted backref key.
30851b60d2ecSQu Wenruo  *		For keyed backref, it's the item key.
30861b60d2ecSQu Wenruo  *		For inlined backref, objectid is the bytenr,
30871b60d2ecSQu Wenruo  *		type is btrfs_inline_ref_type, offset is
30881b60d2ecSQu Wenruo  *		btrfs_inline_ref_offset.
30891b60d2ecSQu Wenruo  */
30901b60d2ecSQu Wenruo static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
30911b60d2ecSQu Wenruo 				      struct btrfs_key *ref_key,
30921b60d2ecSQu Wenruo 				      struct btrfs_backref_node *cur)
30931b60d2ecSQu Wenruo {
30941b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
30951b60d2ecSQu Wenruo 	struct btrfs_backref_node *upper;
30961b60d2ecSQu Wenruo 	struct rb_node *rb_node;
30971b60d2ecSQu Wenruo 
30981b60d2ecSQu Wenruo 	ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
30991b60d2ecSQu Wenruo 
31001b60d2ecSQu Wenruo 	/* Only reloc root uses backref pointing to itself */
31011b60d2ecSQu Wenruo 	if (ref_key->objectid == ref_key->offset) {
31021b60d2ecSQu Wenruo 		struct btrfs_root *root;
31031b60d2ecSQu Wenruo 
31041b60d2ecSQu Wenruo 		cur->is_reloc_root = 1;
31051b60d2ecSQu Wenruo 		/* Only reloc backref cache cares about a specific root */
31061b60d2ecSQu Wenruo 		if (cache->is_reloc) {
31071b60d2ecSQu Wenruo 			root = find_reloc_root(cache->fs_info, cur->bytenr);
3108f78743fbSJosef Bacik 			if (!root)
31091b60d2ecSQu Wenruo 				return -ENOENT;
31101b60d2ecSQu Wenruo 			cur->root = root;
31111b60d2ecSQu Wenruo 		} else {
31121b60d2ecSQu Wenruo 			/*
31131b60d2ecSQu Wenruo 			 * For generic purpose backref cache, reloc root node
31141b60d2ecSQu Wenruo 			 * is useless.
31151b60d2ecSQu Wenruo 			 */
31161b60d2ecSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
31171b60d2ecSQu Wenruo 		}
31181b60d2ecSQu Wenruo 		return 0;
31191b60d2ecSQu Wenruo 	}
31201b60d2ecSQu Wenruo 
31211b60d2ecSQu Wenruo 	edge = btrfs_backref_alloc_edge(cache);
31221b60d2ecSQu Wenruo 	if (!edge)
31231b60d2ecSQu Wenruo 		return -ENOMEM;
31241b60d2ecSQu Wenruo 
31251b60d2ecSQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
31261b60d2ecSQu Wenruo 	if (!rb_node) {
31271b60d2ecSQu Wenruo 		/* Parent node not yet cached */
31281b60d2ecSQu Wenruo 		upper = btrfs_backref_alloc_node(cache, ref_key->offset,
31291b60d2ecSQu Wenruo 					   cur->level + 1);
31301b60d2ecSQu Wenruo 		if (!upper) {
31311b60d2ecSQu Wenruo 			btrfs_backref_free_edge(cache, edge);
31321b60d2ecSQu Wenruo 			return -ENOMEM;
31331b60d2ecSQu Wenruo 		}
31341b60d2ecSQu Wenruo 
31351b60d2ecSQu Wenruo 		/*
31361b60d2ecSQu Wenruo 		 *  Backrefs for the upper level block isn't cached, add the
31371b60d2ecSQu Wenruo 		 *  block to pending list
31381b60d2ecSQu Wenruo 		 */
31391b60d2ecSQu Wenruo 		list_add_tail(&edge->list[UPPER], &cache->pending_edge);
31401b60d2ecSQu Wenruo 	} else {
31411b60d2ecSQu Wenruo 		/* Parent node already cached */
31421b60d2ecSQu Wenruo 		upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
31431b60d2ecSQu Wenruo 		ASSERT(upper->checked);
31441b60d2ecSQu Wenruo 		INIT_LIST_HEAD(&edge->list[UPPER]);
31451b60d2ecSQu Wenruo 	}
31461b60d2ecSQu Wenruo 	btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
31471b60d2ecSQu Wenruo 	return 0;
31481b60d2ecSQu Wenruo }
31491b60d2ecSQu Wenruo 
31501b60d2ecSQu Wenruo /*
31511b60d2ecSQu Wenruo  * Handle indirect tree backref
31521b60d2ecSQu Wenruo  *
31531b60d2ecSQu Wenruo  * Indirect tree backref means, we only know which tree the node belongs to.
31541b60d2ecSQu Wenruo  * We still need to do a tree search to find out the parents. This is for
31551b60d2ecSQu Wenruo  * TREE_BLOCK_REF backref (keyed or inlined).
31561b60d2ecSQu Wenruo  *
31571b60d2ecSQu Wenruo  * @ref_key:	The same as @ref_key in  handle_direct_tree_backref()
31581b60d2ecSQu Wenruo  * @tree_key:	The first key of this tree block.
31591b60d2ecSQu Wenruo  * @path:	A clean (released) path, to avoid allocating path every time
31601b60d2ecSQu Wenruo  *		the function get called.
31611b60d2ecSQu Wenruo  */
31621b60d2ecSQu Wenruo static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
31631b60d2ecSQu Wenruo 					struct btrfs_path *path,
31641b60d2ecSQu Wenruo 					struct btrfs_key *ref_key,
31651b60d2ecSQu Wenruo 					struct btrfs_key *tree_key,
31661b60d2ecSQu Wenruo 					struct btrfs_backref_node *cur)
31671b60d2ecSQu Wenruo {
31681b60d2ecSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
31691b60d2ecSQu Wenruo 	struct btrfs_backref_node *upper;
31701b60d2ecSQu Wenruo 	struct btrfs_backref_node *lower;
31711b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
31721b60d2ecSQu Wenruo 	struct extent_buffer *eb;
31731b60d2ecSQu Wenruo 	struct btrfs_root *root;
31741b60d2ecSQu Wenruo 	struct rb_node *rb_node;
31751b60d2ecSQu Wenruo 	int level;
31761b60d2ecSQu Wenruo 	bool need_check = true;
31771b60d2ecSQu Wenruo 	int ret;
31781b60d2ecSQu Wenruo 
317956e9357aSDavid Sterba 	root = btrfs_get_fs_root(fs_info, ref_key->offset, false);
31801b60d2ecSQu Wenruo 	if (IS_ERR(root))
31811b60d2ecSQu Wenruo 		return PTR_ERR(root);
318292a7cc42SQu Wenruo 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
31831b60d2ecSQu Wenruo 		cur->cowonly = 1;
31841b60d2ecSQu Wenruo 
31851b60d2ecSQu Wenruo 	if (btrfs_root_level(&root->root_item) == cur->level) {
31861b60d2ecSQu Wenruo 		/* Tree root */
31871b60d2ecSQu Wenruo 		ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
3188876de781SQu Wenruo 		/*
3189876de781SQu Wenruo 		 * For reloc backref cache, we may ignore reloc root.  But for
3190876de781SQu Wenruo 		 * general purpose backref cache, we can't rely on
3191876de781SQu Wenruo 		 * btrfs_should_ignore_reloc_root() as it may conflict with
3192876de781SQu Wenruo 		 * current running relocation and lead to missing root.
3193876de781SQu Wenruo 		 *
3194876de781SQu Wenruo 		 * For general purpose backref cache, reloc root detection is
3195876de781SQu Wenruo 		 * completely relying on direct backref (key->offset is parent
3196876de781SQu Wenruo 		 * bytenr), thus only do such check for reloc cache.
3197876de781SQu Wenruo 		 */
3198876de781SQu Wenruo 		if (btrfs_should_ignore_reloc_root(root) && cache->is_reloc) {
31991b60d2ecSQu Wenruo 			btrfs_put_root(root);
32001b60d2ecSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
32011b60d2ecSQu Wenruo 		} else {
32021b60d2ecSQu Wenruo 			cur->root = root;
32031b60d2ecSQu Wenruo 		}
32041b60d2ecSQu Wenruo 		return 0;
32051b60d2ecSQu Wenruo 	}
32061b60d2ecSQu Wenruo 
32071b60d2ecSQu Wenruo 	level = cur->level + 1;
32081b60d2ecSQu Wenruo 
32091b60d2ecSQu Wenruo 	/* Search the tree to find parent blocks referring to the block */
32101b60d2ecSQu Wenruo 	path->search_commit_root = 1;
32111b60d2ecSQu Wenruo 	path->skip_locking = 1;
32121b60d2ecSQu Wenruo 	path->lowest_level = level;
32131b60d2ecSQu Wenruo 	ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
32141b60d2ecSQu Wenruo 	path->lowest_level = 0;
32151b60d2ecSQu Wenruo 	if (ret < 0) {
32161b60d2ecSQu Wenruo 		btrfs_put_root(root);
32171b60d2ecSQu Wenruo 		return ret;
32181b60d2ecSQu Wenruo 	}
32191b60d2ecSQu Wenruo 	if (ret > 0 && path->slots[level] > 0)
32201b60d2ecSQu Wenruo 		path->slots[level]--;
32211b60d2ecSQu Wenruo 
32221b60d2ecSQu Wenruo 	eb = path->nodes[level];
32231b60d2ecSQu Wenruo 	if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
32241b60d2ecSQu Wenruo 		btrfs_err(fs_info,
32251b60d2ecSQu Wenruo "couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
32261b60d2ecSQu Wenruo 			  cur->bytenr, level - 1, root->root_key.objectid,
32271b60d2ecSQu Wenruo 			  tree_key->objectid, tree_key->type, tree_key->offset);
32281b60d2ecSQu Wenruo 		btrfs_put_root(root);
32291b60d2ecSQu Wenruo 		ret = -ENOENT;
32301b60d2ecSQu Wenruo 		goto out;
32311b60d2ecSQu Wenruo 	}
32321b60d2ecSQu Wenruo 	lower = cur;
32331b60d2ecSQu Wenruo 
32341b60d2ecSQu Wenruo 	/* Add all nodes and edges in the path */
32351b60d2ecSQu Wenruo 	for (; level < BTRFS_MAX_LEVEL; level++) {
32361b60d2ecSQu Wenruo 		if (!path->nodes[level]) {
32371b60d2ecSQu Wenruo 			ASSERT(btrfs_root_bytenr(&root->root_item) ==
32381b60d2ecSQu Wenruo 			       lower->bytenr);
3239876de781SQu Wenruo 			/* Same as previous should_ignore_reloc_root() call */
3240876de781SQu Wenruo 			if (btrfs_should_ignore_reloc_root(root) &&
3241876de781SQu Wenruo 			    cache->is_reloc) {
32421b60d2ecSQu Wenruo 				btrfs_put_root(root);
32431b60d2ecSQu Wenruo 				list_add(&lower->list, &cache->useless_node);
32441b60d2ecSQu Wenruo 			} else {
32451b60d2ecSQu Wenruo 				lower->root = root;
32461b60d2ecSQu Wenruo 			}
32471b60d2ecSQu Wenruo 			break;
32481b60d2ecSQu Wenruo 		}
32491b60d2ecSQu Wenruo 
32501b60d2ecSQu Wenruo 		edge = btrfs_backref_alloc_edge(cache);
32511b60d2ecSQu Wenruo 		if (!edge) {
32521b60d2ecSQu Wenruo 			btrfs_put_root(root);
32531b60d2ecSQu Wenruo 			ret = -ENOMEM;
32541b60d2ecSQu Wenruo 			goto out;
32551b60d2ecSQu Wenruo 		}
32561b60d2ecSQu Wenruo 
32571b60d2ecSQu Wenruo 		eb = path->nodes[level];
32581b60d2ecSQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root, eb->start);
32591b60d2ecSQu Wenruo 		if (!rb_node) {
32601b60d2ecSQu Wenruo 			upper = btrfs_backref_alloc_node(cache, eb->start,
32611b60d2ecSQu Wenruo 							 lower->level + 1);
32621b60d2ecSQu Wenruo 			if (!upper) {
32631b60d2ecSQu Wenruo 				btrfs_put_root(root);
32641b60d2ecSQu Wenruo 				btrfs_backref_free_edge(cache, edge);
32651b60d2ecSQu Wenruo 				ret = -ENOMEM;
32661b60d2ecSQu Wenruo 				goto out;
32671b60d2ecSQu Wenruo 			}
32681b60d2ecSQu Wenruo 			upper->owner = btrfs_header_owner(eb);
326992a7cc42SQu Wenruo 			if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
32701b60d2ecSQu Wenruo 				upper->cowonly = 1;
32711b60d2ecSQu Wenruo 
32721b60d2ecSQu Wenruo 			/*
32731b60d2ecSQu Wenruo 			 * If we know the block isn't shared we can avoid
32741b60d2ecSQu Wenruo 			 * checking its backrefs.
32751b60d2ecSQu Wenruo 			 */
32761b60d2ecSQu Wenruo 			if (btrfs_block_can_be_shared(root, eb))
32771b60d2ecSQu Wenruo 				upper->checked = 0;
32781b60d2ecSQu Wenruo 			else
32791b60d2ecSQu Wenruo 				upper->checked = 1;
32801b60d2ecSQu Wenruo 
32811b60d2ecSQu Wenruo 			/*
32821b60d2ecSQu Wenruo 			 * Add the block to pending list if we need to check its
32831b60d2ecSQu Wenruo 			 * backrefs, we only do this once while walking up a
32841b60d2ecSQu Wenruo 			 * tree as we will catch anything else later on.
32851b60d2ecSQu Wenruo 			 */
32861b60d2ecSQu Wenruo 			if (!upper->checked && need_check) {
32871b60d2ecSQu Wenruo 				need_check = false;
32881b60d2ecSQu Wenruo 				list_add_tail(&edge->list[UPPER],
32891b60d2ecSQu Wenruo 					      &cache->pending_edge);
32901b60d2ecSQu Wenruo 			} else {
32911b60d2ecSQu Wenruo 				if (upper->checked)
32921b60d2ecSQu Wenruo 					need_check = true;
32931b60d2ecSQu Wenruo 				INIT_LIST_HEAD(&edge->list[UPPER]);
32941b60d2ecSQu Wenruo 			}
32951b60d2ecSQu Wenruo 		} else {
32961b60d2ecSQu Wenruo 			upper = rb_entry(rb_node, struct btrfs_backref_node,
32971b60d2ecSQu Wenruo 					 rb_node);
32981b60d2ecSQu Wenruo 			ASSERT(upper->checked);
32991b60d2ecSQu Wenruo 			INIT_LIST_HEAD(&edge->list[UPPER]);
33001b60d2ecSQu Wenruo 			if (!upper->owner)
33011b60d2ecSQu Wenruo 				upper->owner = btrfs_header_owner(eb);
33021b60d2ecSQu Wenruo 		}
33031b60d2ecSQu Wenruo 		btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
33041b60d2ecSQu Wenruo 
33051b60d2ecSQu Wenruo 		if (rb_node) {
33061b60d2ecSQu Wenruo 			btrfs_put_root(root);
33071b60d2ecSQu Wenruo 			break;
33081b60d2ecSQu Wenruo 		}
33091b60d2ecSQu Wenruo 		lower = upper;
33101b60d2ecSQu Wenruo 		upper = NULL;
33111b60d2ecSQu Wenruo 	}
33121b60d2ecSQu Wenruo out:
33131b60d2ecSQu Wenruo 	btrfs_release_path(path);
33141b60d2ecSQu Wenruo 	return ret;
33151b60d2ecSQu Wenruo }
33161b60d2ecSQu Wenruo 
33171b60d2ecSQu Wenruo /*
33181b60d2ecSQu Wenruo  * Add backref node @cur into @cache.
33191b60d2ecSQu Wenruo  *
33201b60d2ecSQu Wenruo  * NOTE: Even if the function returned 0, @cur is not yet cached as its upper
33211b60d2ecSQu Wenruo  *	 links aren't yet bi-directional. Needs to finish such links.
3322fc997ed0SQu Wenruo  *	 Use btrfs_backref_finish_upper_links() to finish such linkage.
33231b60d2ecSQu Wenruo  *
33241b60d2ecSQu Wenruo  * @path:	Released path for indirect tree backref lookup
33251b60d2ecSQu Wenruo  * @iter:	Released backref iter for extent tree search
33261b60d2ecSQu Wenruo  * @node_key:	The first key of the tree block
33271b60d2ecSQu Wenruo  */
33281b60d2ecSQu Wenruo int btrfs_backref_add_tree_node(struct btrfs_backref_cache *cache,
33291b60d2ecSQu Wenruo 				struct btrfs_path *path,
33301b60d2ecSQu Wenruo 				struct btrfs_backref_iter *iter,
33311b60d2ecSQu Wenruo 				struct btrfs_key *node_key,
33321b60d2ecSQu Wenruo 				struct btrfs_backref_node *cur)
33331b60d2ecSQu Wenruo {
33341b60d2ecSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
33351b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
33361b60d2ecSQu Wenruo 	struct btrfs_backref_node *exist;
33371b60d2ecSQu Wenruo 	int ret;
33381b60d2ecSQu Wenruo 
33391b60d2ecSQu Wenruo 	ret = btrfs_backref_iter_start(iter, cur->bytenr);
33401b60d2ecSQu Wenruo 	if (ret < 0)
33411b60d2ecSQu Wenruo 		return ret;
33421b60d2ecSQu Wenruo 	/*
33431b60d2ecSQu Wenruo 	 * We skip the first btrfs_tree_block_info, as we don't use the key
33441b60d2ecSQu Wenruo 	 * stored in it, but fetch it from the tree block
33451b60d2ecSQu Wenruo 	 */
33461b60d2ecSQu Wenruo 	if (btrfs_backref_has_tree_block_info(iter)) {
33471b60d2ecSQu Wenruo 		ret = btrfs_backref_iter_next(iter);
33481b60d2ecSQu Wenruo 		if (ret < 0)
33491b60d2ecSQu Wenruo 			goto out;
33501b60d2ecSQu Wenruo 		/* No extra backref? This means the tree block is corrupted */
33511b60d2ecSQu Wenruo 		if (ret > 0) {
33521b60d2ecSQu Wenruo 			ret = -EUCLEAN;
33531b60d2ecSQu Wenruo 			goto out;
33541b60d2ecSQu Wenruo 		}
33551b60d2ecSQu Wenruo 	}
33561b60d2ecSQu Wenruo 	WARN_ON(cur->checked);
33571b60d2ecSQu Wenruo 	if (!list_empty(&cur->upper)) {
33581b60d2ecSQu Wenruo 		/*
33591b60d2ecSQu Wenruo 		 * The backref was added previously when processing backref of
33601b60d2ecSQu Wenruo 		 * type BTRFS_TREE_BLOCK_REF_KEY
33611b60d2ecSQu Wenruo 		 */
33621b60d2ecSQu Wenruo 		ASSERT(list_is_singular(&cur->upper));
33631b60d2ecSQu Wenruo 		edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
33641b60d2ecSQu Wenruo 				  list[LOWER]);
33651b60d2ecSQu Wenruo 		ASSERT(list_empty(&edge->list[UPPER]));
33661b60d2ecSQu Wenruo 		exist = edge->node[UPPER];
33671b60d2ecSQu Wenruo 		/*
33681b60d2ecSQu Wenruo 		 * Add the upper level block to pending list if we need check
33691b60d2ecSQu Wenruo 		 * its backrefs
33701b60d2ecSQu Wenruo 		 */
33711b60d2ecSQu Wenruo 		if (!exist->checked)
33721b60d2ecSQu Wenruo 			list_add_tail(&edge->list[UPPER], &cache->pending_edge);
33731b60d2ecSQu Wenruo 	} else {
33741b60d2ecSQu Wenruo 		exist = NULL;
33751b60d2ecSQu Wenruo 	}
33761b60d2ecSQu Wenruo 
33771b60d2ecSQu Wenruo 	for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
33781b60d2ecSQu Wenruo 		struct extent_buffer *eb;
33791b60d2ecSQu Wenruo 		struct btrfs_key key;
33801b60d2ecSQu Wenruo 		int type;
33811b60d2ecSQu Wenruo 
33821b60d2ecSQu Wenruo 		cond_resched();
33831b60d2ecSQu Wenruo 		eb = btrfs_backref_get_eb(iter);
33841b60d2ecSQu Wenruo 
33851b60d2ecSQu Wenruo 		key.objectid = iter->bytenr;
33861b60d2ecSQu Wenruo 		if (btrfs_backref_iter_is_inline_ref(iter)) {
33871b60d2ecSQu Wenruo 			struct btrfs_extent_inline_ref *iref;
33881b60d2ecSQu Wenruo 
33891b60d2ecSQu Wenruo 			/* Update key for inline backref */
33901b60d2ecSQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
33911b60d2ecSQu Wenruo 				((unsigned long)iter->cur_ptr);
33921b60d2ecSQu Wenruo 			type = btrfs_get_extent_inline_ref_type(eb, iref,
33931b60d2ecSQu Wenruo 							BTRFS_REF_TYPE_BLOCK);
33941b60d2ecSQu Wenruo 			if (type == BTRFS_REF_TYPE_INVALID) {
33951b60d2ecSQu Wenruo 				ret = -EUCLEAN;
33961b60d2ecSQu Wenruo 				goto out;
33971b60d2ecSQu Wenruo 			}
33981b60d2ecSQu Wenruo 			key.type = type;
33991b60d2ecSQu Wenruo 			key.offset = btrfs_extent_inline_ref_offset(eb, iref);
34001b60d2ecSQu Wenruo 		} else {
34011b60d2ecSQu Wenruo 			key.type = iter->cur_key.type;
34021b60d2ecSQu Wenruo 			key.offset = iter->cur_key.offset;
34031b60d2ecSQu Wenruo 		}
34041b60d2ecSQu Wenruo 
34051b60d2ecSQu Wenruo 		/*
34061b60d2ecSQu Wenruo 		 * Parent node found and matches current inline ref, no need to
34071b60d2ecSQu Wenruo 		 * rebuild this node for this inline ref
34081b60d2ecSQu Wenruo 		 */
34091b60d2ecSQu Wenruo 		if (exist &&
34101b60d2ecSQu Wenruo 		    ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
34111b60d2ecSQu Wenruo 		      exist->owner == key.offset) ||
34121b60d2ecSQu Wenruo 		     (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
34131b60d2ecSQu Wenruo 		      exist->bytenr == key.offset))) {
34141b60d2ecSQu Wenruo 			exist = NULL;
34151b60d2ecSQu Wenruo 			continue;
34161b60d2ecSQu Wenruo 		}
34171b60d2ecSQu Wenruo 
34181b60d2ecSQu Wenruo 		/* SHARED_BLOCK_REF means key.offset is the parent bytenr */
34191b60d2ecSQu Wenruo 		if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
34201b60d2ecSQu Wenruo 			ret = handle_direct_tree_backref(cache, &key, cur);
34211b60d2ecSQu Wenruo 			if (ret < 0)
34221b60d2ecSQu Wenruo 				goto out;
34231b60d2ecSQu Wenruo 			continue;
34241b60d2ecSQu Wenruo 		} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
34251b60d2ecSQu Wenruo 			ret = -EINVAL;
34261b60d2ecSQu Wenruo 			btrfs_print_v0_err(fs_info);
34271b60d2ecSQu Wenruo 			btrfs_handle_fs_error(fs_info, ret, NULL);
34281b60d2ecSQu Wenruo 			goto out;
34291b60d2ecSQu Wenruo 		} else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
34301b60d2ecSQu Wenruo 			continue;
34311b60d2ecSQu Wenruo 		}
34321b60d2ecSQu Wenruo 
34331b60d2ecSQu Wenruo 		/*
34341b60d2ecSQu Wenruo 		 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
34351b60d2ecSQu Wenruo 		 * means the root objectid. We need to search the tree to get
34361b60d2ecSQu Wenruo 		 * its parent bytenr.
34371b60d2ecSQu Wenruo 		 */
34381b60d2ecSQu Wenruo 		ret = handle_indirect_tree_backref(cache, path, &key, node_key,
34391b60d2ecSQu Wenruo 						   cur);
34401b60d2ecSQu Wenruo 		if (ret < 0)
34411b60d2ecSQu Wenruo 			goto out;
34421b60d2ecSQu Wenruo 	}
34431b60d2ecSQu Wenruo 	ret = 0;
34441b60d2ecSQu Wenruo 	cur->checked = 1;
34451b60d2ecSQu Wenruo 	WARN_ON(exist);
34461b60d2ecSQu Wenruo out:
34471b60d2ecSQu Wenruo 	btrfs_backref_iter_release(iter);
34481b60d2ecSQu Wenruo 	return ret;
34491b60d2ecSQu Wenruo }
3450fc997ed0SQu Wenruo 
3451fc997ed0SQu Wenruo /*
3452fc997ed0SQu Wenruo  * Finish the upwards linkage created by btrfs_backref_add_tree_node()
3453fc997ed0SQu Wenruo  */
3454fc997ed0SQu Wenruo int btrfs_backref_finish_upper_links(struct btrfs_backref_cache *cache,
3455fc997ed0SQu Wenruo 				     struct btrfs_backref_node *start)
3456fc997ed0SQu Wenruo {
3457fc997ed0SQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
3458fc997ed0SQu Wenruo 	struct btrfs_backref_edge *edge;
3459fc997ed0SQu Wenruo 	struct rb_node *rb_node;
3460fc997ed0SQu Wenruo 	LIST_HEAD(pending_edge);
3461fc997ed0SQu Wenruo 
3462fc997ed0SQu Wenruo 	ASSERT(start->checked);
3463fc997ed0SQu Wenruo 
3464fc997ed0SQu Wenruo 	/* Insert this node to cache if it's not COW-only */
3465fc997ed0SQu Wenruo 	if (!start->cowonly) {
3466fc997ed0SQu Wenruo 		rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
3467fc997ed0SQu Wenruo 					   &start->rb_node);
3468fc997ed0SQu Wenruo 		if (rb_node)
3469fc997ed0SQu Wenruo 			btrfs_backref_panic(cache->fs_info, start->bytenr,
3470fc997ed0SQu Wenruo 					    -EEXIST);
3471fc997ed0SQu Wenruo 		list_add_tail(&start->lower, &cache->leaves);
3472fc997ed0SQu Wenruo 	}
3473fc997ed0SQu Wenruo 
3474fc997ed0SQu Wenruo 	/*
3475fc997ed0SQu Wenruo 	 * Use breadth first search to iterate all related edges.
3476fc997ed0SQu Wenruo 	 *
3477fc997ed0SQu Wenruo 	 * The starting points are all the edges of this node
3478fc997ed0SQu Wenruo 	 */
3479fc997ed0SQu Wenruo 	list_for_each_entry(edge, &start->upper, list[LOWER])
3480fc997ed0SQu Wenruo 		list_add_tail(&edge->list[UPPER], &pending_edge);
3481fc997ed0SQu Wenruo 
3482fc997ed0SQu Wenruo 	while (!list_empty(&pending_edge)) {
3483fc997ed0SQu Wenruo 		struct btrfs_backref_node *upper;
3484fc997ed0SQu Wenruo 		struct btrfs_backref_node *lower;
3485fc997ed0SQu Wenruo 
3486fc997ed0SQu Wenruo 		edge = list_first_entry(&pending_edge,
3487fc997ed0SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
3488fc997ed0SQu Wenruo 		list_del_init(&edge->list[UPPER]);
3489fc997ed0SQu Wenruo 		upper = edge->node[UPPER];
3490fc997ed0SQu Wenruo 		lower = edge->node[LOWER];
3491fc997ed0SQu Wenruo 
3492fc997ed0SQu Wenruo 		/* Parent is detached, no need to keep any edges */
3493fc997ed0SQu Wenruo 		if (upper->detached) {
3494fc997ed0SQu Wenruo 			list_del(&edge->list[LOWER]);
3495fc997ed0SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
3496fc997ed0SQu Wenruo 
3497fc997ed0SQu Wenruo 			/* Lower node is orphan, queue for cleanup */
3498fc997ed0SQu Wenruo 			if (list_empty(&lower->upper))
3499fc997ed0SQu Wenruo 				list_add(&lower->list, useless_node);
3500fc997ed0SQu Wenruo 			continue;
3501fc997ed0SQu Wenruo 		}
3502fc997ed0SQu Wenruo 
3503fc997ed0SQu Wenruo 		/*
3504fc997ed0SQu Wenruo 		 * All new nodes added in current build_backref_tree() haven't
3505fc997ed0SQu Wenruo 		 * been linked to the cache rb tree.
3506fc997ed0SQu Wenruo 		 * So if we have upper->rb_node populated, this means a cache
3507fc997ed0SQu Wenruo 		 * hit. We only need to link the edge, as @upper and all its
3508fc997ed0SQu Wenruo 		 * parents have already been linked.
3509fc997ed0SQu Wenruo 		 */
3510fc997ed0SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node)) {
3511fc997ed0SQu Wenruo 			if (upper->lowest) {
3512fc997ed0SQu Wenruo 				list_del_init(&upper->lower);
3513fc997ed0SQu Wenruo 				upper->lowest = 0;
3514fc997ed0SQu Wenruo 			}
3515fc997ed0SQu Wenruo 
3516fc997ed0SQu Wenruo 			list_add_tail(&edge->list[UPPER], &upper->lower);
3517fc997ed0SQu Wenruo 			continue;
3518fc997ed0SQu Wenruo 		}
3519fc997ed0SQu Wenruo 
3520fc997ed0SQu Wenruo 		/* Sanity check, we shouldn't have any unchecked nodes */
3521fc997ed0SQu Wenruo 		if (!upper->checked) {
3522fc997ed0SQu Wenruo 			ASSERT(0);
3523fc997ed0SQu Wenruo 			return -EUCLEAN;
3524fc997ed0SQu Wenruo 		}
3525fc997ed0SQu Wenruo 
3526fc997ed0SQu Wenruo 		/* Sanity check, COW-only node has non-COW-only parent */
3527fc997ed0SQu Wenruo 		if (start->cowonly != upper->cowonly) {
3528fc997ed0SQu Wenruo 			ASSERT(0);
3529fc997ed0SQu Wenruo 			return -EUCLEAN;
3530fc997ed0SQu Wenruo 		}
3531fc997ed0SQu Wenruo 
3532fc997ed0SQu Wenruo 		/* Only cache non-COW-only (subvolume trees) tree blocks */
3533fc997ed0SQu Wenruo 		if (!upper->cowonly) {
3534fc997ed0SQu Wenruo 			rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
3535fc997ed0SQu Wenruo 						   &upper->rb_node);
3536fc997ed0SQu Wenruo 			if (rb_node) {
3537fc997ed0SQu Wenruo 				btrfs_backref_panic(cache->fs_info,
3538fc997ed0SQu Wenruo 						upper->bytenr, -EEXIST);
3539fc997ed0SQu Wenruo 				return -EUCLEAN;
3540fc997ed0SQu Wenruo 			}
3541fc997ed0SQu Wenruo 		}
3542fc997ed0SQu Wenruo 
3543fc997ed0SQu Wenruo 		list_add_tail(&edge->list[UPPER], &upper->lower);
3544fc997ed0SQu Wenruo 
3545fc997ed0SQu Wenruo 		/*
3546fc997ed0SQu Wenruo 		 * Also queue all the parent edges of this uncached node
3547fc997ed0SQu Wenruo 		 * to finish the upper linkage
3548fc997ed0SQu Wenruo 		 */
3549fc997ed0SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
3550fc997ed0SQu Wenruo 			list_add_tail(&edge->list[UPPER], &pending_edge);
3551fc997ed0SQu Wenruo 	}
3552fc997ed0SQu Wenruo 	return 0;
3553fc997ed0SQu Wenruo }
35541b23ea18SQu Wenruo 
35551b23ea18SQu Wenruo void btrfs_backref_error_cleanup(struct btrfs_backref_cache *cache,
35561b23ea18SQu Wenruo 				 struct btrfs_backref_node *node)
35571b23ea18SQu Wenruo {
35581b23ea18SQu Wenruo 	struct btrfs_backref_node *lower;
35591b23ea18SQu Wenruo 	struct btrfs_backref_node *upper;
35601b23ea18SQu Wenruo 	struct btrfs_backref_edge *edge;
35611b23ea18SQu Wenruo 
35621b23ea18SQu Wenruo 	while (!list_empty(&cache->useless_node)) {
35631b23ea18SQu Wenruo 		lower = list_first_entry(&cache->useless_node,
35641b23ea18SQu Wenruo 				   struct btrfs_backref_node, list);
35651b23ea18SQu Wenruo 		list_del_init(&lower->list);
35661b23ea18SQu Wenruo 	}
35671b23ea18SQu Wenruo 	while (!list_empty(&cache->pending_edge)) {
35681b23ea18SQu Wenruo 		edge = list_first_entry(&cache->pending_edge,
35691b23ea18SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
35701b23ea18SQu Wenruo 		list_del(&edge->list[UPPER]);
35711b23ea18SQu Wenruo 		list_del(&edge->list[LOWER]);
35721b23ea18SQu Wenruo 		lower = edge->node[LOWER];
35731b23ea18SQu Wenruo 		upper = edge->node[UPPER];
35741b23ea18SQu Wenruo 		btrfs_backref_free_edge(cache, edge);
35751b23ea18SQu Wenruo 
35761b23ea18SQu Wenruo 		/*
35771b23ea18SQu Wenruo 		 * Lower is no longer linked to any upper backref nodes and
35781b23ea18SQu Wenruo 		 * isn't in the cache, we can free it ourselves.
35791b23ea18SQu Wenruo 		 */
35801b23ea18SQu Wenruo 		if (list_empty(&lower->upper) &&
35811b23ea18SQu Wenruo 		    RB_EMPTY_NODE(&lower->rb_node))
35821b23ea18SQu Wenruo 			list_add(&lower->list, &cache->useless_node);
35831b23ea18SQu Wenruo 
35841b23ea18SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node))
35851b23ea18SQu Wenruo 			continue;
35861b23ea18SQu Wenruo 
35871b23ea18SQu Wenruo 		/* Add this guy's upper edges to the list to process */
35881b23ea18SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
35891b23ea18SQu Wenruo 			list_add_tail(&edge->list[UPPER],
35901b23ea18SQu Wenruo 				      &cache->pending_edge);
35911b23ea18SQu Wenruo 		if (list_empty(&upper->upper))
35921b23ea18SQu Wenruo 			list_add(&upper->list, &cache->useless_node);
35931b23ea18SQu Wenruo 	}
35941b23ea18SQu Wenruo 
35951b23ea18SQu Wenruo 	while (!list_empty(&cache->useless_node)) {
35961b23ea18SQu Wenruo 		lower = list_first_entry(&cache->useless_node,
35971b23ea18SQu Wenruo 				   struct btrfs_backref_node, list);
35981b23ea18SQu Wenruo 		list_del_init(&lower->list);
35991b23ea18SQu Wenruo 		if (lower == node)
36001b23ea18SQu Wenruo 			node = NULL;
360149ecc679SJosef Bacik 		btrfs_backref_drop_node(cache, lower);
36021b23ea18SQu Wenruo 	}
36031b23ea18SQu Wenruo 
36041b23ea18SQu Wenruo 	btrfs_backref_cleanup_node(cache, node);
36051b23ea18SQu Wenruo 	ASSERT(list_empty(&cache->useless_node) &&
36061b23ea18SQu Wenruo 	       list_empty(&cache->pending_edge));
36071b23ea18SQu Wenruo }
3608