xref: /openbmc/linux/fs/btrfs/backref.c (revision 4e4488d4efd56951e6c1c0f60f1fc8e0f93b7964)
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 {
1255*4e4488d4SFilipe Manana 	const struct btrfs_fs_info *fs_info = root->fs_info;
1256583f4ac5SFilipe Manana 	struct btrfs_backref_shared_cache_entry *entry;
1257583f4ac5SFilipe Manana 
1258*4e4488d4SFilipe Manana 	if (!current->journal_info)
1259*4e4488d4SFilipe Manana 		lockdep_assert_held(&fs_info->commit_root_sem);
1260*4e4488d4SFilipe 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 &&
1295*4e4488d4SFilipe 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 {
1325*4e4488d4SFilipe 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 
1329*4e4488d4SFilipe Manana 	if (!current->journal_info)
1330*4e4488d4SFilipe Manana 		lockdep_assert_held(&fs_info->commit_root_sem);
1331*4e4488d4SFilipe 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)
1347*4e4488d4SFilipe 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;
1875dc046b10SJosef Bacik 
187673e339e6SFilipe Manana 	for (int i = 0; i < BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE; i++) {
187773e339e6SFilipe Manana 		if (ctx->prev_extents_cache[i].bytenr == bytenr)
187873e339e6SFilipe Manana 			return ctx->prev_extents_cache[i].is_shared;
187973e339e6SFilipe Manana 	}
188073e339e6SFilipe Manana 
188184a7949dSFilipe Manana 	ulist_init(&ctx->refs);
1882dc046b10SJosef Bacik 
1883a6d155d2SFilipe Manana 	trans = btrfs_join_transaction_nostart(root);
1884bb739cf0SEdmund Nadolski 	if (IS_ERR(trans)) {
188503628cdbSFilipe Manana 		if (PTR_ERR(trans) != -ENOENT && PTR_ERR(trans) != -EROFS) {
188603628cdbSFilipe Manana 			ret = PTR_ERR(trans);
188703628cdbSFilipe Manana 			goto out;
188803628cdbSFilipe Manana 		}
1889bb739cf0SEdmund Nadolski 		trans = NULL;
1890dc046b10SJosef Bacik 		down_read(&fs_info->commit_root_sem);
1891bb739cf0SEdmund Nadolski 	} else {
1892bb739cf0SEdmund Nadolski 		btrfs_get_tree_mod_seq(fs_info, &elem);
1893a2c8d27eSFilipe Manana 		walk_ctx.time_seq = elem.seq;
1894bb739cf0SEdmund Nadolski 	}
1895bb739cf0SEdmund Nadolski 
1896a2c8d27eSFilipe Manana 	walk_ctx.ignore_extent_item_pos = true;
1897a2c8d27eSFilipe Manana 	walk_ctx.trans = trans;
1898a2c8d27eSFilipe Manana 	walk_ctx.fs_info = fs_info;
1899a2c8d27eSFilipe Manana 	walk_ctx.refs = &ctx->refs;
1900a2c8d27eSFilipe Manana 
190112a824dcSFilipe Manana 	/* -1 means we are in the bytenr of the data extent. */
190212a824dcSFilipe Manana 	level = -1;
1903dc046b10SJosef Bacik 	ULIST_ITER_INIT(&uiter);
190461dbb952SFilipe Manana 	ctx->use_path_cache = true;
1905dc046b10SJosef Bacik 	while (1) {
190612a824dcSFilipe Manana 		bool is_shared;
190712a824dcSFilipe Manana 		bool cached;
190812a824dcSFilipe Manana 
1909a2c8d27eSFilipe Manana 		walk_ctx.bytenr = bytenr;
1910a2c8d27eSFilipe Manana 		ret = find_parent_nodes(&walk_ctx, &shared);
1911877c1476SFilipe Manana 		if (ret == BACKREF_FOUND_SHARED ||
1912877c1476SFilipe Manana 		    ret == BACKREF_FOUND_NOT_SHARED) {
1913877c1476SFilipe Manana 			/* If shared must return 1, otherwise return 0. */
1914877c1476SFilipe Manana 			ret = (ret == BACKREF_FOUND_SHARED) ? 1 : 0;
191512a824dcSFilipe Manana 			if (level >= 0)
191661dbb952SFilipe Manana 				store_backref_shared_cache(ctx, root, bytenr,
1917877c1476SFilipe Manana 							   level, ret == 1);
1918dc046b10SJosef Bacik 			break;
1919dc046b10SJosef Bacik 		}
1920dc046b10SJosef Bacik 		if (ret < 0 && ret != -ENOENT)
1921dc046b10SJosef Bacik 			break;
19222c2ed5aaSMark Fasheh 		ret = 0;
1923b8f164e3SFilipe Manana 
192463c84b46SFilipe Manana 		/*
192563c84b46SFilipe Manana 		 * If our data extent was not directly shared (without multiple
192663c84b46SFilipe Manana 		 * reference items), than it might have a single reference item
192763c84b46SFilipe Manana 		 * with a count > 1 for the same offset, which means there are 2
192863c84b46SFilipe Manana 		 * (or more) file extent items that point to the data extent -
192963c84b46SFilipe Manana 		 * this happens when a file extent item needs to be split and
193063c84b46SFilipe Manana 		 * then one item gets moved to another leaf due to a b+tree leaf
193163c84b46SFilipe Manana 		 * split when inserting some item. In this case the file extent
193263c84b46SFilipe Manana 		 * items may be located in different leaves and therefore some
193363c84b46SFilipe Manana 		 * of the leaves may be referenced through shared subtrees while
193463c84b46SFilipe Manana 		 * others are not. Since our extent buffer cache only works for
193563c84b46SFilipe Manana 		 * a single path (by far the most common case and simpler to
193663c84b46SFilipe Manana 		 * deal with), we can not use it if we have multiple leaves
193763c84b46SFilipe Manana 		 * (which implies multiple paths).
193863c84b46SFilipe Manana 		 */
193984a7949dSFilipe Manana 		if (level == -1 && ctx->refs.nnodes > 1)
194061dbb952SFilipe Manana 			ctx->use_path_cache = false;
194163c84b46SFilipe Manana 
194212a824dcSFilipe Manana 		if (level >= 0)
194361dbb952SFilipe Manana 			store_backref_shared_cache(ctx, root, bytenr,
194412a824dcSFilipe Manana 						   level, false);
194584a7949dSFilipe Manana 		node = ulist_next(&ctx->refs, &uiter);
1946dc046b10SJosef Bacik 		if (!node)
1947dc046b10SJosef Bacik 			break;
1948dc046b10SJosef Bacik 		bytenr = node->val;
194912a824dcSFilipe Manana 		level++;
195061dbb952SFilipe Manana 		cached = lookup_backref_shared_cache(ctx, root, bytenr, level,
195112a824dcSFilipe Manana 						     &is_shared);
195212a824dcSFilipe Manana 		if (cached) {
195312a824dcSFilipe Manana 			ret = (is_shared ? 1 : 0);
195412a824dcSFilipe Manana 			break;
195512a824dcSFilipe Manana 		}
195618bf591bSEdmund Nadolski 		shared.share_count = 0;
19574fc7b572SFilipe Manana 		shared.have_delayed_delete_refs = false;
1958dc046b10SJosef Bacik 		cond_resched();
1959dc046b10SJosef Bacik 	}
1960bb739cf0SEdmund Nadolski 
196173e339e6SFilipe Manana 	/*
196273e339e6SFilipe Manana 	 * Cache the sharedness result for the data extent if we know our inode
196373e339e6SFilipe Manana 	 * has more than 1 file extent item that refers to the data extent.
196473e339e6SFilipe Manana 	 */
196573e339e6SFilipe Manana 	if (ret >= 0 && shared.self_ref_count > 1) {
196673e339e6SFilipe Manana 		int slot = ctx->prev_extents_cache_slot;
196773e339e6SFilipe Manana 
196873e339e6SFilipe Manana 		ctx->prev_extents_cache[slot].bytenr = shared.data_bytenr;
196973e339e6SFilipe Manana 		ctx->prev_extents_cache[slot].is_shared = (ret == 1);
197073e339e6SFilipe Manana 
197173e339e6SFilipe Manana 		slot = (slot + 1) % BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE;
197273e339e6SFilipe Manana 		ctx->prev_extents_cache_slot = slot;
197373e339e6SFilipe Manana 	}
197473e339e6SFilipe Manana 
1975bb739cf0SEdmund Nadolski 	if (trans) {
1976dc046b10SJosef Bacik 		btrfs_put_tree_mod_seq(fs_info, &elem);
1977bb739cf0SEdmund Nadolski 		btrfs_end_transaction(trans);
1978bb739cf0SEdmund Nadolski 	} else {
1979dc046b10SJosef Bacik 		up_read(&fs_info->commit_root_sem);
1980bb739cf0SEdmund Nadolski 	}
198103628cdbSFilipe Manana out:
198284a7949dSFilipe Manana 	ulist_release(&ctx->refs);
1983877c1476SFilipe Manana 	ctx->prev_leaf_bytenr = ctx->curr_leaf_bytenr;
1984877c1476SFilipe Manana 
1985dc046b10SJosef Bacik 	return ret;
1986dc046b10SJosef Bacik }
1987dc046b10SJosef Bacik 
1988f186373fSMark Fasheh int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
1989f186373fSMark Fasheh 			  u64 start_off, struct btrfs_path *path,
1990f186373fSMark Fasheh 			  struct btrfs_inode_extref **ret_extref,
1991f186373fSMark Fasheh 			  u64 *found_off)
1992f186373fSMark Fasheh {
1993f186373fSMark Fasheh 	int ret, slot;
1994f186373fSMark Fasheh 	struct btrfs_key key;
1995f186373fSMark Fasheh 	struct btrfs_key found_key;
1996f186373fSMark Fasheh 	struct btrfs_inode_extref *extref;
199773980becSJeff Mahoney 	const struct extent_buffer *leaf;
1998f186373fSMark Fasheh 	unsigned long ptr;
1999f186373fSMark Fasheh 
2000f186373fSMark Fasheh 	key.objectid = inode_objectid;
2001962a298fSDavid Sterba 	key.type = BTRFS_INODE_EXTREF_KEY;
2002f186373fSMark Fasheh 	key.offset = start_off;
2003f186373fSMark Fasheh 
2004f186373fSMark Fasheh 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2005f186373fSMark Fasheh 	if (ret < 0)
2006f186373fSMark Fasheh 		return ret;
2007f186373fSMark Fasheh 
2008f186373fSMark Fasheh 	while (1) {
2009f186373fSMark Fasheh 		leaf = path->nodes[0];
2010f186373fSMark Fasheh 		slot = path->slots[0];
2011f186373fSMark Fasheh 		if (slot >= btrfs_header_nritems(leaf)) {
2012f186373fSMark Fasheh 			/*
2013f186373fSMark Fasheh 			 * If the item at offset is not found,
2014f186373fSMark Fasheh 			 * btrfs_search_slot will point us to the slot
2015f186373fSMark Fasheh 			 * where it should be inserted. In our case
2016f186373fSMark Fasheh 			 * that will be the slot directly before the
2017f186373fSMark Fasheh 			 * next INODE_REF_KEY_V2 item. In the case
2018f186373fSMark Fasheh 			 * that we're pointing to the last slot in a
2019f186373fSMark Fasheh 			 * leaf, we must move one leaf over.
2020f186373fSMark Fasheh 			 */
2021f186373fSMark Fasheh 			ret = btrfs_next_leaf(root, path);
2022f186373fSMark Fasheh 			if (ret) {
2023f186373fSMark Fasheh 				if (ret >= 1)
2024f186373fSMark Fasheh 					ret = -ENOENT;
2025f186373fSMark Fasheh 				break;
2026f186373fSMark Fasheh 			}
2027f186373fSMark Fasheh 			continue;
2028f186373fSMark Fasheh 		}
2029f186373fSMark Fasheh 
2030f186373fSMark Fasheh 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
2031f186373fSMark Fasheh 
2032f186373fSMark Fasheh 		/*
2033f186373fSMark Fasheh 		 * Check that we're still looking at an extended ref key for
2034f186373fSMark Fasheh 		 * this particular objectid. If we have different
2035f186373fSMark Fasheh 		 * objectid or type then there are no more to be found
2036f186373fSMark Fasheh 		 * in the tree and we can exit.
2037f186373fSMark Fasheh 		 */
2038f186373fSMark Fasheh 		ret = -ENOENT;
2039f186373fSMark Fasheh 		if (found_key.objectid != inode_objectid)
2040f186373fSMark Fasheh 			break;
2041962a298fSDavid Sterba 		if (found_key.type != BTRFS_INODE_EXTREF_KEY)
2042f186373fSMark Fasheh 			break;
2043f186373fSMark Fasheh 
2044f186373fSMark Fasheh 		ret = 0;
2045f186373fSMark Fasheh 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
2046f186373fSMark Fasheh 		extref = (struct btrfs_inode_extref *)ptr;
2047f186373fSMark Fasheh 		*ret_extref = extref;
2048f186373fSMark Fasheh 		if (found_off)
2049f186373fSMark Fasheh 			*found_off = found_key.offset;
2050f186373fSMark Fasheh 		break;
2051f186373fSMark Fasheh 	}
2052f186373fSMark Fasheh 
2053f186373fSMark Fasheh 	return ret;
2054f186373fSMark Fasheh }
2055f186373fSMark Fasheh 
205648a3b636SEric Sandeen /*
205748a3b636SEric Sandeen  * this iterates to turn a name (from iref/extref) into a full filesystem path.
205848a3b636SEric Sandeen  * Elements of the path are separated by '/' and the path is guaranteed to be
205948a3b636SEric Sandeen  * 0-terminated. the path is only given within the current file system.
206048a3b636SEric Sandeen  * Therefore, it never starts with a '/'. the caller is responsible to provide
206148a3b636SEric Sandeen  * "size" bytes in "dest". the dest buffer will be filled backwards. finally,
206248a3b636SEric Sandeen  * the start point of the resulting string is returned. this pointer is within
206348a3b636SEric Sandeen  * dest, normally.
206448a3b636SEric Sandeen  * in case the path buffer would overflow, the pointer is decremented further
206548a3b636SEric Sandeen  * as if output was written to the buffer, though no more output is actually
206648a3b636SEric Sandeen  * generated. that way, the caller can determine how much space would be
206748a3b636SEric Sandeen  * required for the path to fit into the buffer. in that case, the returned
206848a3b636SEric Sandeen  * value will be smaller than dest. callers must check this!
206948a3b636SEric Sandeen  */
207096b5bd77SJan Schmidt char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
2071d24bec3aSMark Fasheh 			u32 name_len, unsigned long name_off,
2072a542ad1bSJan Schmidt 			struct extent_buffer *eb_in, u64 parent,
2073a542ad1bSJan Schmidt 			char *dest, u32 size)
2074a542ad1bSJan Schmidt {
2075a542ad1bSJan Schmidt 	int slot;
2076a542ad1bSJan Schmidt 	u64 next_inum;
2077a542ad1bSJan Schmidt 	int ret;
2078661bec6bSGabriel de Perthuis 	s64 bytes_left = ((s64)size) - 1;
2079a542ad1bSJan Schmidt 	struct extent_buffer *eb = eb_in;
2080a542ad1bSJan Schmidt 	struct btrfs_key found_key;
2081d24bec3aSMark Fasheh 	struct btrfs_inode_ref *iref;
2082a542ad1bSJan Schmidt 
2083a542ad1bSJan Schmidt 	if (bytes_left >= 0)
2084a542ad1bSJan Schmidt 		dest[bytes_left] = '\0';
2085a542ad1bSJan Schmidt 
2086a542ad1bSJan Schmidt 	while (1) {
2087d24bec3aSMark Fasheh 		bytes_left -= name_len;
2088a542ad1bSJan Schmidt 		if (bytes_left >= 0)
2089a542ad1bSJan Schmidt 			read_extent_buffer(eb, dest + bytes_left,
2090d24bec3aSMark Fasheh 					   name_off, name_len);
2091b916a59aSJan Schmidt 		if (eb != eb_in) {
20920c0fe3b0SFilipe Manana 			if (!path->skip_locking)
2093ac5887c8SJosef Bacik 				btrfs_tree_read_unlock(eb);
2094a542ad1bSJan Schmidt 			free_extent_buffer(eb);
2095b916a59aSJan Schmidt 		}
2096c234a24dSDavid Sterba 		ret = btrfs_find_item(fs_root, path, parent, 0,
2097c234a24dSDavid Sterba 				BTRFS_INODE_REF_KEY, &found_key);
20988f24b496SJan Schmidt 		if (ret > 0)
20998f24b496SJan Schmidt 			ret = -ENOENT;
2100a542ad1bSJan Schmidt 		if (ret)
2101a542ad1bSJan Schmidt 			break;
2102d24bec3aSMark Fasheh 
2103a542ad1bSJan Schmidt 		next_inum = found_key.offset;
2104a542ad1bSJan Schmidt 
2105a542ad1bSJan Schmidt 		/* regular exit ahead */
2106a542ad1bSJan Schmidt 		if (parent == next_inum)
2107a542ad1bSJan Schmidt 			break;
2108a542ad1bSJan Schmidt 
2109a542ad1bSJan Schmidt 		slot = path->slots[0];
2110a542ad1bSJan Schmidt 		eb = path->nodes[0];
2111a542ad1bSJan Schmidt 		/* make sure we can use eb after releasing the path */
2112b916a59aSJan Schmidt 		if (eb != eb_in) {
21130c0fe3b0SFilipe Manana 			path->nodes[0] = NULL;
21140c0fe3b0SFilipe Manana 			path->locks[0] = 0;
2115b916a59aSJan Schmidt 		}
2116a542ad1bSJan Schmidt 		btrfs_release_path(path);
2117a542ad1bSJan Schmidt 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2118d24bec3aSMark Fasheh 
2119d24bec3aSMark Fasheh 		name_len = btrfs_inode_ref_name_len(eb, iref);
2120d24bec3aSMark Fasheh 		name_off = (unsigned long)(iref + 1);
2121d24bec3aSMark Fasheh 
2122a542ad1bSJan Schmidt 		parent = next_inum;
2123a542ad1bSJan Schmidt 		--bytes_left;
2124a542ad1bSJan Schmidt 		if (bytes_left >= 0)
2125a542ad1bSJan Schmidt 			dest[bytes_left] = '/';
2126a542ad1bSJan Schmidt 	}
2127a542ad1bSJan Schmidt 
2128a542ad1bSJan Schmidt 	btrfs_release_path(path);
2129a542ad1bSJan Schmidt 
2130a542ad1bSJan Schmidt 	if (ret)
2131a542ad1bSJan Schmidt 		return ERR_PTR(ret);
2132a542ad1bSJan Schmidt 
2133a542ad1bSJan Schmidt 	return dest + bytes_left;
2134a542ad1bSJan Schmidt }
2135a542ad1bSJan Schmidt 
2136a542ad1bSJan Schmidt /*
2137a542ad1bSJan Schmidt  * this makes the path point to (logical EXTENT_ITEM *)
2138a542ad1bSJan Schmidt  * returns BTRFS_EXTENT_FLAG_DATA for data, BTRFS_EXTENT_FLAG_TREE_BLOCK for
2139a542ad1bSJan Schmidt  * tree blocks and <0 on error.
2140a542ad1bSJan Schmidt  */
2141a542ad1bSJan Schmidt int extent_from_logical(struct btrfs_fs_info *fs_info, u64 logical,
214269917e43SLiu Bo 			struct btrfs_path *path, struct btrfs_key *found_key,
214369917e43SLiu Bo 			u64 *flags_ret)
2144a542ad1bSJan Schmidt {
214529cbcf40SJosef Bacik 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, logical);
2146a542ad1bSJan Schmidt 	int ret;
2147a542ad1bSJan Schmidt 	u64 flags;
2148261c84b6SJosef Bacik 	u64 size = 0;
2149a542ad1bSJan Schmidt 	u32 item_size;
215073980becSJeff Mahoney 	const struct extent_buffer *eb;
2151a542ad1bSJan Schmidt 	struct btrfs_extent_item *ei;
2152a542ad1bSJan Schmidt 	struct btrfs_key key;
2153a542ad1bSJan Schmidt 
2154261c84b6SJosef Bacik 	if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2155261c84b6SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
2156261c84b6SJosef Bacik 	else
2157a542ad1bSJan Schmidt 		key.type = BTRFS_EXTENT_ITEM_KEY;
2158a542ad1bSJan Schmidt 	key.objectid = logical;
2159a542ad1bSJan Schmidt 	key.offset = (u64)-1;
2160a542ad1bSJan Schmidt 
216129cbcf40SJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2162a542ad1bSJan Schmidt 	if (ret < 0)
2163a542ad1bSJan Schmidt 		return ret;
2164a542ad1bSJan Schmidt 
216529cbcf40SJosef Bacik 	ret = btrfs_previous_extent_item(extent_root, path, 0);
2166850a8cdfSWang Shilong 	if (ret) {
2167850a8cdfSWang Shilong 		if (ret > 0)
2168580f0a67SJosef Bacik 			ret = -ENOENT;
2169580f0a67SJosef Bacik 		return ret;
2170580f0a67SJosef Bacik 	}
2171850a8cdfSWang Shilong 	btrfs_item_key_to_cpu(path->nodes[0], found_key, path->slots[0]);
2172261c84b6SJosef Bacik 	if (found_key->type == BTRFS_METADATA_ITEM_KEY)
2173da17066cSJeff Mahoney 		size = fs_info->nodesize;
2174261c84b6SJosef Bacik 	else if (found_key->type == BTRFS_EXTENT_ITEM_KEY)
2175261c84b6SJosef Bacik 		size = found_key->offset;
2176261c84b6SJosef Bacik 
2177580f0a67SJosef Bacik 	if (found_key->objectid > logical ||
2178261c84b6SJosef Bacik 	    found_key->objectid + size <= logical) {
2179ab8d0fc4SJeff Mahoney 		btrfs_debug(fs_info,
2180ab8d0fc4SJeff Mahoney 			"logical %llu is not within any extent", logical);
2181a542ad1bSJan Schmidt 		return -ENOENT;
21824692cf58SJan Schmidt 	}
2183a542ad1bSJan Schmidt 
2184a542ad1bSJan Schmidt 	eb = path->nodes[0];
21853212fa14SJosef Bacik 	item_size = btrfs_item_size(eb, path->slots[0]);
2186a542ad1bSJan Schmidt 	BUG_ON(item_size < sizeof(*ei));
2187a542ad1bSJan Schmidt 
2188a542ad1bSJan Schmidt 	ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
2189a542ad1bSJan Schmidt 	flags = btrfs_extent_flags(eb, ei);
2190a542ad1bSJan Schmidt 
2191ab8d0fc4SJeff Mahoney 	btrfs_debug(fs_info,
2192ab8d0fc4SJeff Mahoney 		"logical %llu is at position %llu within the extent (%llu EXTENT_ITEM %llu) flags %#llx size %u",
2193c1c9ff7cSGeert Uytterhoeven 		 logical, logical - found_key->objectid, found_key->objectid,
2194c1c9ff7cSGeert Uytterhoeven 		 found_key->offset, flags, item_size);
219569917e43SLiu Bo 
219669917e43SLiu Bo 	WARN_ON(!flags_ret);
219769917e43SLiu Bo 	if (flags_ret) {
2198a542ad1bSJan Schmidt 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
219969917e43SLiu Bo 			*flags_ret = BTRFS_EXTENT_FLAG_TREE_BLOCK;
220069917e43SLiu Bo 		else if (flags & BTRFS_EXTENT_FLAG_DATA)
220169917e43SLiu Bo 			*flags_ret = BTRFS_EXTENT_FLAG_DATA;
220269917e43SLiu Bo 		else
2203290342f6SArnd Bergmann 			BUG();
220469917e43SLiu Bo 		return 0;
220569917e43SLiu Bo 	}
2206a542ad1bSJan Schmidt 
2207a542ad1bSJan Schmidt 	return -EIO;
2208a542ad1bSJan Schmidt }
2209a542ad1bSJan Schmidt 
2210a542ad1bSJan Schmidt /*
2211a542ad1bSJan Schmidt  * helper function to iterate extent inline refs. ptr must point to a 0 value
2212a542ad1bSJan Schmidt  * for the first call and may be modified. it is used to track state.
2213a542ad1bSJan Schmidt  * if more refs exist, 0 is returned and the next call to
2214e0c476b1SJeff Mahoney  * get_extent_inline_ref must pass the modified ptr parameter to get the
2215a542ad1bSJan Schmidt  * next ref. after the last ref was processed, 1 is returned.
2216a542ad1bSJan Schmidt  * returns <0 on error
2217a542ad1bSJan Schmidt  */
2218e0c476b1SJeff Mahoney static int get_extent_inline_ref(unsigned long *ptr,
221973980becSJeff Mahoney 				 const struct extent_buffer *eb,
222073980becSJeff Mahoney 				 const struct btrfs_key *key,
222173980becSJeff Mahoney 				 const struct btrfs_extent_item *ei,
222273980becSJeff Mahoney 				 u32 item_size,
2223a542ad1bSJan Schmidt 				 struct btrfs_extent_inline_ref **out_eiref,
2224a542ad1bSJan Schmidt 				 int *out_type)
2225a542ad1bSJan Schmidt {
2226a542ad1bSJan Schmidt 	unsigned long end;
2227a542ad1bSJan Schmidt 	u64 flags;
2228a542ad1bSJan Schmidt 	struct btrfs_tree_block_info *info;
2229a542ad1bSJan Schmidt 
2230a542ad1bSJan Schmidt 	if (!*ptr) {
2231a542ad1bSJan Schmidt 		/* first call */
2232a542ad1bSJan Schmidt 		flags = btrfs_extent_flags(eb, ei);
2233a542ad1bSJan Schmidt 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
22346eda71d0SLiu Bo 			if (key->type == BTRFS_METADATA_ITEM_KEY) {
22356eda71d0SLiu Bo 				/* a skinny metadata extent */
22366eda71d0SLiu Bo 				*out_eiref =
22376eda71d0SLiu Bo 				     (struct btrfs_extent_inline_ref *)(ei + 1);
22386eda71d0SLiu Bo 			} else {
22396eda71d0SLiu Bo 				WARN_ON(key->type != BTRFS_EXTENT_ITEM_KEY);
2240a542ad1bSJan Schmidt 				info = (struct btrfs_tree_block_info *)(ei + 1);
2241a542ad1bSJan Schmidt 				*out_eiref =
2242a542ad1bSJan Schmidt 				   (struct btrfs_extent_inline_ref *)(info + 1);
22436eda71d0SLiu Bo 			}
2244a542ad1bSJan Schmidt 		} else {
2245a542ad1bSJan Schmidt 			*out_eiref = (struct btrfs_extent_inline_ref *)(ei + 1);
2246a542ad1bSJan Schmidt 		}
2247a542ad1bSJan Schmidt 		*ptr = (unsigned long)*out_eiref;
2248cd857dd6SLiu Bo 		if ((unsigned long)(*ptr) >= (unsigned long)ei + item_size)
2249a542ad1bSJan Schmidt 			return -ENOENT;
2250a542ad1bSJan Schmidt 	}
2251a542ad1bSJan Schmidt 
2252a542ad1bSJan Schmidt 	end = (unsigned long)ei + item_size;
22536eda71d0SLiu Bo 	*out_eiref = (struct btrfs_extent_inline_ref *)(*ptr);
22543de28d57SLiu Bo 	*out_type = btrfs_get_extent_inline_ref_type(eb, *out_eiref,
22553de28d57SLiu Bo 						     BTRFS_REF_TYPE_ANY);
22563de28d57SLiu Bo 	if (*out_type == BTRFS_REF_TYPE_INVALID)
2257af431dcbSSu Yue 		return -EUCLEAN;
2258a542ad1bSJan Schmidt 
2259a542ad1bSJan Schmidt 	*ptr += btrfs_extent_inline_ref_size(*out_type);
2260a542ad1bSJan Schmidt 	WARN_ON(*ptr > end);
2261a542ad1bSJan Schmidt 	if (*ptr == end)
2262a542ad1bSJan Schmidt 		return 1; /* last */
2263a542ad1bSJan Schmidt 
2264a542ad1bSJan Schmidt 	return 0;
2265a542ad1bSJan Schmidt }
2266a542ad1bSJan Schmidt 
2267a542ad1bSJan Schmidt /*
2268a542ad1bSJan Schmidt  * reads the tree block backref for an extent. tree level and root are returned
2269a542ad1bSJan Schmidt  * through out_level and out_root. ptr must point to a 0 value for the first
2270e0c476b1SJeff Mahoney  * call and may be modified (see get_extent_inline_ref comment).
2271a542ad1bSJan Schmidt  * returns 0 if data was provided, 1 if there was no more data to provide or
2272a542ad1bSJan Schmidt  * <0 on error.
2273a542ad1bSJan Schmidt  */
2274a542ad1bSJan Schmidt int tree_backref_for_extent(unsigned long *ptr, struct extent_buffer *eb,
22756eda71d0SLiu Bo 			    struct btrfs_key *key, struct btrfs_extent_item *ei,
22766eda71d0SLiu Bo 			    u32 item_size, u64 *out_root, u8 *out_level)
2277a542ad1bSJan Schmidt {
2278a542ad1bSJan Schmidt 	int ret;
2279a542ad1bSJan Schmidt 	int type;
2280a542ad1bSJan Schmidt 	struct btrfs_extent_inline_ref *eiref;
2281a542ad1bSJan Schmidt 
2282a542ad1bSJan Schmidt 	if (*ptr == (unsigned long)-1)
2283a542ad1bSJan Schmidt 		return 1;
2284a542ad1bSJan Schmidt 
2285a542ad1bSJan Schmidt 	while (1) {
2286e0c476b1SJeff Mahoney 		ret = get_extent_inline_ref(ptr, eb, key, ei, item_size,
2287a542ad1bSJan Schmidt 					      &eiref, &type);
2288a542ad1bSJan Schmidt 		if (ret < 0)
2289a542ad1bSJan Schmidt 			return ret;
2290a542ad1bSJan Schmidt 
2291a542ad1bSJan Schmidt 		if (type == BTRFS_TREE_BLOCK_REF_KEY ||
2292a542ad1bSJan Schmidt 		    type == BTRFS_SHARED_BLOCK_REF_KEY)
2293a542ad1bSJan Schmidt 			break;
2294a542ad1bSJan Schmidt 
2295a542ad1bSJan Schmidt 		if (ret == 1)
2296a542ad1bSJan Schmidt 			return 1;
2297a542ad1bSJan Schmidt 	}
2298a542ad1bSJan Schmidt 
2299a542ad1bSJan Schmidt 	/* we can treat both ref types equally here */
2300a542ad1bSJan Schmidt 	*out_root = btrfs_extent_inline_ref_offset(eb, eiref);
2301a1317f45SFilipe Manana 
2302a1317f45SFilipe Manana 	if (key->type == BTRFS_EXTENT_ITEM_KEY) {
2303a1317f45SFilipe Manana 		struct btrfs_tree_block_info *info;
2304a1317f45SFilipe Manana 
2305a1317f45SFilipe Manana 		info = (struct btrfs_tree_block_info *)(ei + 1);
2306a542ad1bSJan Schmidt 		*out_level = btrfs_tree_block_level(eb, info);
2307a1317f45SFilipe Manana 	} else {
2308a1317f45SFilipe Manana 		ASSERT(key->type == BTRFS_METADATA_ITEM_KEY);
2309a1317f45SFilipe Manana 		*out_level = (u8)key->offset;
2310a1317f45SFilipe Manana 	}
2311a542ad1bSJan Schmidt 
2312a542ad1bSJan Schmidt 	if (ret == 1)
2313a542ad1bSJan Schmidt 		*ptr = (unsigned long)-1;
2314a542ad1bSJan Schmidt 
2315a542ad1bSJan Schmidt 	return 0;
2316a542ad1bSJan Schmidt }
2317a542ad1bSJan Schmidt 
2318ab8d0fc4SJeff Mahoney static int iterate_leaf_refs(struct btrfs_fs_info *fs_info,
2319ab8d0fc4SJeff Mahoney 			     struct extent_inode_elem *inode_list,
2320976b1908SJan Schmidt 			     u64 root, u64 extent_item_objectid,
23214692cf58SJan Schmidt 			     iterate_extent_inodes_t *iterate, void *ctx)
2322a542ad1bSJan Schmidt {
2323976b1908SJan Schmidt 	struct extent_inode_elem *eie;
23244692cf58SJan Schmidt 	int ret = 0;
2325a542ad1bSJan Schmidt 
2326976b1908SJan Schmidt 	for (eie = inode_list; eie; eie = eie->next) {
2327ab8d0fc4SJeff Mahoney 		btrfs_debug(fs_info,
2328ab8d0fc4SJeff Mahoney 			    "ref for %llu resolved, key (%llu EXTEND_DATA %llu), root %llu",
2329ab8d0fc4SJeff Mahoney 			    extent_item_objectid, eie->inum,
2330ab8d0fc4SJeff Mahoney 			    eie->offset, root);
2331c7499a64SFilipe Manana 		ret = iterate(eie->inum, eie->offset, eie->num_bytes, root, ctx);
23324692cf58SJan Schmidt 		if (ret) {
2333ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_info,
2334ab8d0fc4SJeff Mahoney 				    "stopping iteration for %llu due to ret=%d",
2335976b1908SJan Schmidt 				    extent_item_objectid, ret);
2336a542ad1bSJan Schmidt 			break;
2337a542ad1bSJan Schmidt 		}
2338a542ad1bSJan Schmidt 	}
2339a542ad1bSJan Schmidt 
2340a542ad1bSJan Schmidt 	return ret;
2341a542ad1bSJan Schmidt }
2342a542ad1bSJan Schmidt 
2343a542ad1bSJan Schmidt /*
2344a542ad1bSJan Schmidt  * calls iterate() for every inode that references the extent identified by
23454692cf58SJan Schmidt  * the given parameters.
2346a542ad1bSJan Schmidt  * when the iterator function returns a non-zero value, iteration stops.
2347a542ad1bSJan Schmidt  */
2348a2c8d27eSFilipe Manana int iterate_extent_inodes(struct btrfs_backref_walk_ctx *ctx,
2349a2c8d27eSFilipe Manana 			  bool search_commit_root,
2350a2c8d27eSFilipe Manana 			  iterate_extent_inodes_t *iterate, void *user_ctx)
2351a542ad1bSJan Schmidt {
2352a542ad1bSJan Schmidt 	int ret;
2353a2c8d27eSFilipe Manana 	struct ulist *refs;
2354a2c8d27eSFilipe Manana 	struct ulist_node *ref_node;
2355f3a84ccdSFilipe Manana 	struct btrfs_seq_list seq_elem = BTRFS_SEQ_LIST_INIT(seq_elem);
2356cd1b413cSJan Schmidt 	struct ulist_iterator ref_uiter;
2357a542ad1bSJan Schmidt 
2358a2c8d27eSFilipe Manana 	btrfs_debug(ctx->fs_info, "resolving all inodes for extent %llu",
2359a2c8d27eSFilipe Manana 		    ctx->bytenr);
2360a2c8d27eSFilipe Manana 
2361a2c8d27eSFilipe Manana 	ASSERT(ctx->trans == NULL);
23621baea6f1SFilipe Manana 	ASSERT(ctx->roots == NULL);
23631baea6f1SFilipe Manana 
2364da61d31aSJosef Bacik 	if (!search_commit_root) {
2365a2c8d27eSFilipe Manana 		struct btrfs_trans_handle *trans;
2366a2c8d27eSFilipe Manana 
2367a2c8d27eSFilipe Manana 		trans = btrfs_attach_transaction(ctx->fs_info->tree_root);
2368bfc61c36SFilipe Manana 		if (IS_ERR(trans)) {
2369bfc61c36SFilipe Manana 			if (PTR_ERR(trans) != -ENOENT &&
237066d04209SFilipe Manana 			    PTR_ERR(trans) != -EROFS)
23717a3ae2f8SJan Schmidt 				return PTR_ERR(trans);
2372bfc61c36SFilipe Manana 			trans = NULL;
23737a3ae2f8SJan Schmidt 		}
2374a2c8d27eSFilipe Manana 		ctx->trans = trans;
2375bfc61c36SFilipe Manana 	}
2376bfc61c36SFilipe Manana 
2377a2c8d27eSFilipe Manana 	if (ctx->trans) {
2378a2c8d27eSFilipe Manana 		btrfs_get_tree_mod_seq(ctx->fs_info, &seq_elem);
2379a2c8d27eSFilipe Manana 		ctx->time_seq = seq_elem.seq;
2380a2c8d27eSFilipe Manana 	} else {
2381a2c8d27eSFilipe Manana 		down_read(&ctx->fs_info->commit_root_sem);
2382a2c8d27eSFilipe Manana 	}
23834692cf58SJan Schmidt 
2384a2c8d27eSFilipe Manana 	ret = btrfs_find_all_leafs(ctx);
23854692cf58SJan Schmidt 	if (ret)
23864692cf58SJan Schmidt 		goto out;
2387a2c8d27eSFilipe Manana 	refs = ctx->refs;
2388a2c8d27eSFilipe Manana 	ctx->refs = NULL;
23894692cf58SJan Schmidt 
2390cd1b413cSJan Schmidt 	ULIST_ITER_INIT(&ref_uiter);
2391cd1b413cSJan Schmidt 	while (!ret && (ref_node = ulist_next(refs, &ref_uiter))) {
239266d04209SFilipe Manana 		const u64 leaf_bytenr = ref_node->val;
2393a2c8d27eSFilipe Manana 		struct ulist_node *root_node;
2394a2c8d27eSFilipe Manana 		struct ulist_iterator root_uiter;
239566d04209SFilipe Manana 		struct extent_inode_elem *inode_list;
2396a2c8d27eSFilipe Manana 
239766d04209SFilipe Manana 		inode_list = (struct extent_inode_elem *)(uintptr_t)ref_node->aux;
239866d04209SFilipe Manana 
239966d04209SFilipe Manana 		if (ctx->cache_lookup) {
240066d04209SFilipe Manana 			const u64 *root_ids;
240166d04209SFilipe Manana 			int root_count;
240266d04209SFilipe Manana 			bool cached;
240366d04209SFilipe Manana 
240466d04209SFilipe Manana 			cached = ctx->cache_lookup(leaf_bytenr, ctx->user_ctx,
240566d04209SFilipe Manana 						   &root_ids, &root_count);
240666d04209SFilipe Manana 			if (cached) {
240766d04209SFilipe Manana 				for (int i = 0; i < root_count; i++) {
240866d04209SFilipe Manana 					ret = iterate_leaf_refs(ctx->fs_info,
240966d04209SFilipe Manana 								inode_list,
241066d04209SFilipe Manana 								root_ids[i],
241166d04209SFilipe Manana 								leaf_bytenr,
241266d04209SFilipe Manana 								iterate,
241366d04209SFilipe Manana 								user_ctx);
241466d04209SFilipe Manana 					if (ret)
241566d04209SFilipe Manana 						break;
241666d04209SFilipe Manana 				}
241766d04209SFilipe Manana 				continue;
241866d04209SFilipe Manana 			}
241966d04209SFilipe Manana 		}
242066d04209SFilipe Manana 
242166d04209SFilipe Manana 		if (!ctx->roots) {
242266d04209SFilipe Manana 			ctx->roots = ulist_alloc(GFP_NOFS);
242366d04209SFilipe Manana 			if (!ctx->roots) {
242466d04209SFilipe Manana 				ret = -ENOMEM;
242566d04209SFilipe Manana 				break;
242666d04209SFilipe Manana 			}
242766d04209SFilipe Manana 		}
242866d04209SFilipe Manana 
242966d04209SFilipe Manana 		ctx->bytenr = leaf_bytenr;
2430a2c8d27eSFilipe Manana 		ret = btrfs_find_all_roots_safe(ctx);
24314692cf58SJan Schmidt 		if (ret)
2432a542ad1bSJan Schmidt 			break;
2433a2c8d27eSFilipe Manana 
243466d04209SFilipe Manana 		if (ctx->cache_store)
243566d04209SFilipe Manana 			ctx->cache_store(leaf_bytenr, ctx->roots, ctx->user_ctx);
243666d04209SFilipe Manana 
2437cd1b413cSJan Schmidt 		ULIST_ITER_INIT(&root_uiter);
2438a2c8d27eSFilipe Manana 		while (!ret && (root_node = ulist_next(ctx->roots, &root_uiter))) {
2439a2c8d27eSFilipe Manana 			btrfs_debug(ctx->fs_info,
2440ab8d0fc4SJeff Mahoney 				    "root %llu references leaf %llu, data list %#llx",
2441ab8d0fc4SJeff Mahoney 				    root_node->val, ref_node->val,
2442c1c9ff7cSGeert Uytterhoeven 				    ref_node->aux);
244366d04209SFilipe Manana 			ret = iterate_leaf_refs(ctx->fs_info, inode_list,
2444a2c8d27eSFilipe Manana 						root_node->val, ctx->bytenr,
2445a2c8d27eSFilipe Manana 						iterate, user_ctx);
24464692cf58SJan Schmidt 		}
24471baea6f1SFilipe Manana 		ulist_reinit(ctx->roots);
2448a542ad1bSJan Schmidt 	}
2449a542ad1bSJan Schmidt 
2450976b1908SJan Schmidt 	free_leaf_list(refs);
24514692cf58SJan Schmidt out:
2452a2c8d27eSFilipe Manana 	if (ctx->trans) {
2453a2c8d27eSFilipe Manana 		btrfs_put_tree_mod_seq(ctx->fs_info, &seq_elem);
2454a2c8d27eSFilipe Manana 		btrfs_end_transaction(ctx->trans);
2455a2c8d27eSFilipe Manana 		ctx->trans = NULL;
24569e351cc8SJosef Bacik 	} else {
2457a2c8d27eSFilipe Manana 		up_read(&ctx->fs_info->commit_root_sem);
24587a3ae2f8SJan Schmidt 	}
24597a3ae2f8SJan Schmidt 
24601baea6f1SFilipe Manana 	ulist_free(ctx->roots);
24611baea6f1SFilipe Manana 	ctx->roots = NULL;
24621baea6f1SFilipe Manana 
246388ffb665SFilipe Manana 	if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP)
246488ffb665SFilipe Manana 		ret = 0;
246588ffb665SFilipe Manana 
2466a542ad1bSJan Schmidt 	return ret;
2467a542ad1bSJan Schmidt }
2468a542ad1bSJan Schmidt 
2469c7499a64SFilipe Manana static int build_ino_list(u64 inum, u64 offset, u64 num_bytes, u64 root, void *ctx)
2470e3059ec0SDavid Sterba {
2471e3059ec0SDavid Sterba 	struct btrfs_data_container *inodes = ctx;
2472e3059ec0SDavid Sterba 	const size_t c = 3 * sizeof(u64);
2473e3059ec0SDavid Sterba 
2474e3059ec0SDavid Sterba 	if (inodes->bytes_left >= c) {
2475e3059ec0SDavid Sterba 		inodes->bytes_left -= c;
2476e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt] = inum;
2477e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt + 1] = offset;
2478e3059ec0SDavid Sterba 		inodes->val[inodes->elem_cnt + 2] = root;
2479e3059ec0SDavid Sterba 		inodes->elem_cnt += 3;
2480e3059ec0SDavid Sterba 	} else {
2481e3059ec0SDavid Sterba 		inodes->bytes_missing += c - inodes->bytes_left;
2482e3059ec0SDavid Sterba 		inodes->bytes_left = 0;
2483e3059ec0SDavid Sterba 		inodes->elem_missed += 3;
2484e3059ec0SDavid Sterba 	}
2485e3059ec0SDavid Sterba 
2486e3059ec0SDavid Sterba 	return 0;
2487e3059ec0SDavid Sterba }
2488e3059ec0SDavid Sterba 
2489a542ad1bSJan Schmidt int iterate_inodes_from_logical(u64 logical, struct btrfs_fs_info *fs_info,
2490a542ad1bSJan Schmidt 				struct btrfs_path *path,
2491e3059ec0SDavid Sterba 				void *ctx, bool ignore_offset)
2492a542ad1bSJan Schmidt {
2493a2c8d27eSFilipe Manana 	struct btrfs_backref_walk_ctx walk_ctx = { 0 };
2494a542ad1bSJan Schmidt 	int ret;
249569917e43SLiu Bo 	u64 flags = 0;
2496a542ad1bSJan Schmidt 	struct btrfs_key found_key;
24977a3ae2f8SJan Schmidt 	int search_commit_root = path->search_commit_root;
2498a542ad1bSJan Schmidt 
249969917e43SLiu Bo 	ret = extent_from_logical(fs_info, logical, path, &found_key, &flags);
25004692cf58SJan Schmidt 	btrfs_release_path(path);
2501a542ad1bSJan Schmidt 	if (ret < 0)
2502a542ad1bSJan Schmidt 		return ret;
250369917e43SLiu Bo 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
25043627bf45SStefan Behrens 		return -EINVAL;
2505a542ad1bSJan Schmidt 
2506a2c8d27eSFilipe Manana 	walk_ctx.bytenr = found_key.objectid;
25076ce6ba53SFilipe Manana 	if (ignore_offset)
2508a2c8d27eSFilipe Manana 		walk_ctx.ignore_extent_item_pos = true;
25096ce6ba53SFilipe Manana 	else
2510a2c8d27eSFilipe Manana 		walk_ctx.extent_item_pos = logical - found_key.objectid;
2511a2c8d27eSFilipe Manana 	walk_ctx.fs_info = fs_info;
25126ce6ba53SFilipe Manana 
2513a2c8d27eSFilipe Manana 	return iterate_extent_inodes(&walk_ctx, search_commit_root,
25146ce6ba53SFilipe Manana 				     build_ino_list, ctx);
2515a542ad1bSJan Schmidt }
2516a542ad1bSJan Schmidt 
2517ad6240f6SDavid Sterba static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2518875d1daaSDavid Sterba 			 struct extent_buffer *eb, struct inode_fs_paths *ipath);
2519d24bec3aSMark Fasheh 
2520875d1daaSDavid Sterba static int iterate_inode_refs(u64 inum, struct inode_fs_paths *ipath)
2521a542ad1bSJan Schmidt {
2522aefc1eb1SJan Schmidt 	int ret = 0;
2523a542ad1bSJan Schmidt 	int slot;
2524a542ad1bSJan Schmidt 	u32 cur;
2525a542ad1bSJan Schmidt 	u32 len;
2526a542ad1bSJan Schmidt 	u32 name_len;
2527a542ad1bSJan Schmidt 	u64 parent = 0;
2528a542ad1bSJan Schmidt 	int found = 0;
2529875d1daaSDavid Sterba 	struct btrfs_root *fs_root = ipath->fs_root;
2530875d1daaSDavid Sterba 	struct btrfs_path *path = ipath->btrfs_path;
2531a542ad1bSJan Schmidt 	struct extent_buffer *eb;
2532a542ad1bSJan Schmidt 	struct btrfs_inode_ref *iref;
2533a542ad1bSJan Schmidt 	struct btrfs_key found_key;
2534a542ad1bSJan Schmidt 
2535aefc1eb1SJan Schmidt 	while (!ret) {
2536c234a24dSDavid Sterba 		ret = btrfs_find_item(fs_root, path, inum,
2537c234a24dSDavid Sterba 				parent ? parent + 1 : 0, BTRFS_INODE_REF_KEY,
2538a542ad1bSJan Schmidt 				&found_key);
2539c234a24dSDavid Sterba 
2540a542ad1bSJan Schmidt 		if (ret < 0)
2541a542ad1bSJan Schmidt 			break;
2542a542ad1bSJan Schmidt 		if (ret) {
2543a542ad1bSJan Schmidt 			ret = found ? 0 : -ENOENT;
2544a542ad1bSJan Schmidt 			break;
2545a542ad1bSJan Schmidt 		}
2546a542ad1bSJan Schmidt 		++found;
2547a542ad1bSJan Schmidt 
2548a542ad1bSJan Schmidt 		parent = found_key.offset;
2549a542ad1bSJan Schmidt 		slot = path->slots[0];
25503fe81ce2SFilipe David Borba Manana 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
25513fe81ce2SFilipe David Borba Manana 		if (!eb) {
25523fe81ce2SFilipe David Borba Manana 			ret = -ENOMEM;
25533fe81ce2SFilipe David Borba Manana 			break;
25543fe81ce2SFilipe David Borba Manana 		}
2555a542ad1bSJan Schmidt 		btrfs_release_path(path);
2556a542ad1bSJan Schmidt 
2557a542ad1bSJan Schmidt 		iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2558a542ad1bSJan Schmidt 
25593212fa14SJosef Bacik 		for (cur = 0; cur < btrfs_item_size(eb, slot); cur += len) {
2560a542ad1bSJan Schmidt 			name_len = btrfs_inode_ref_name_len(eb, iref);
2561a542ad1bSJan Schmidt 			/* path must be released before calling iterate()! */
2562ab8d0fc4SJeff Mahoney 			btrfs_debug(fs_root->fs_info,
2563ab8d0fc4SJeff Mahoney 				"following ref at offset %u for inode %llu in tree %llu",
25644fd786e6SMisono Tomohiro 				cur, found_key.objectid,
25654fd786e6SMisono Tomohiro 				fs_root->root_key.objectid);
2566ad6240f6SDavid Sterba 			ret = inode_to_path(parent, name_len,
2567875d1daaSDavid Sterba 				      (unsigned long)(iref + 1), eb, ipath);
2568aefc1eb1SJan Schmidt 			if (ret)
2569a542ad1bSJan Schmidt 				break;
2570a542ad1bSJan Schmidt 			len = sizeof(*iref) + name_len;
2571a542ad1bSJan Schmidt 			iref = (struct btrfs_inode_ref *)((char *)iref + len);
2572a542ad1bSJan Schmidt 		}
2573a542ad1bSJan Schmidt 		free_extent_buffer(eb);
2574a542ad1bSJan Schmidt 	}
2575a542ad1bSJan Schmidt 
2576a542ad1bSJan Schmidt 	btrfs_release_path(path);
2577a542ad1bSJan Schmidt 
2578a542ad1bSJan Schmidt 	return ret;
2579a542ad1bSJan Schmidt }
2580a542ad1bSJan Schmidt 
2581875d1daaSDavid Sterba static int iterate_inode_extrefs(u64 inum, struct inode_fs_paths *ipath)
2582d24bec3aSMark Fasheh {
2583d24bec3aSMark Fasheh 	int ret;
2584d24bec3aSMark Fasheh 	int slot;
2585d24bec3aSMark Fasheh 	u64 offset = 0;
2586d24bec3aSMark Fasheh 	u64 parent;
2587d24bec3aSMark Fasheh 	int found = 0;
2588875d1daaSDavid Sterba 	struct btrfs_root *fs_root = ipath->fs_root;
2589875d1daaSDavid Sterba 	struct btrfs_path *path = ipath->btrfs_path;
2590d24bec3aSMark Fasheh 	struct extent_buffer *eb;
2591d24bec3aSMark Fasheh 	struct btrfs_inode_extref *extref;
2592d24bec3aSMark Fasheh 	u32 item_size;
2593d24bec3aSMark Fasheh 	u32 cur_offset;
2594d24bec3aSMark Fasheh 	unsigned long ptr;
2595d24bec3aSMark Fasheh 
2596d24bec3aSMark Fasheh 	while (1) {
2597d24bec3aSMark Fasheh 		ret = btrfs_find_one_extref(fs_root, inum, offset, path, &extref,
2598d24bec3aSMark Fasheh 					    &offset);
2599d24bec3aSMark Fasheh 		if (ret < 0)
2600d24bec3aSMark Fasheh 			break;
2601d24bec3aSMark Fasheh 		if (ret) {
2602d24bec3aSMark Fasheh 			ret = found ? 0 : -ENOENT;
2603d24bec3aSMark Fasheh 			break;
2604d24bec3aSMark Fasheh 		}
2605d24bec3aSMark Fasheh 		++found;
2606d24bec3aSMark Fasheh 
2607d24bec3aSMark Fasheh 		slot = path->slots[0];
26083fe81ce2SFilipe David Borba Manana 		eb = btrfs_clone_extent_buffer(path->nodes[0]);
26093fe81ce2SFilipe David Borba Manana 		if (!eb) {
26103fe81ce2SFilipe David Borba Manana 			ret = -ENOMEM;
26113fe81ce2SFilipe David Borba Manana 			break;
26123fe81ce2SFilipe David Borba Manana 		}
2613d24bec3aSMark Fasheh 		btrfs_release_path(path);
2614d24bec3aSMark Fasheh 
26153212fa14SJosef Bacik 		item_size = btrfs_item_size(eb, slot);
26162849a854SChris Mason 		ptr = btrfs_item_ptr_offset(eb, slot);
2617d24bec3aSMark Fasheh 		cur_offset = 0;
2618d24bec3aSMark Fasheh 
2619d24bec3aSMark Fasheh 		while (cur_offset < item_size) {
2620d24bec3aSMark Fasheh 			u32 name_len;
2621d24bec3aSMark Fasheh 
2622d24bec3aSMark Fasheh 			extref = (struct btrfs_inode_extref *)(ptr + cur_offset);
2623d24bec3aSMark Fasheh 			parent = btrfs_inode_extref_parent(eb, extref);
2624d24bec3aSMark Fasheh 			name_len = btrfs_inode_extref_name_len(eb, extref);
2625ad6240f6SDavid Sterba 			ret = inode_to_path(parent, name_len,
2626875d1daaSDavid Sterba 				      (unsigned long)&extref->name, eb, ipath);
2627d24bec3aSMark Fasheh 			if (ret)
2628d24bec3aSMark Fasheh 				break;
2629d24bec3aSMark Fasheh 
26302849a854SChris Mason 			cur_offset += btrfs_inode_extref_name_len(eb, extref);
2631d24bec3aSMark Fasheh 			cur_offset += sizeof(*extref);
2632d24bec3aSMark Fasheh 		}
2633d24bec3aSMark Fasheh 		free_extent_buffer(eb);
2634d24bec3aSMark Fasheh 
2635d24bec3aSMark Fasheh 		offset++;
2636d24bec3aSMark Fasheh 	}
2637d24bec3aSMark Fasheh 
2638d24bec3aSMark Fasheh 	btrfs_release_path(path);
2639d24bec3aSMark Fasheh 
2640d24bec3aSMark Fasheh 	return ret;
2641d24bec3aSMark Fasheh }
2642d24bec3aSMark Fasheh 
2643a542ad1bSJan Schmidt /*
2644a542ad1bSJan Schmidt  * returns 0 if the path could be dumped (probably truncated)
2645a542ad1bSJan Schmidt  * returns <0 in case of an error
2646a542ad1bSJan Schmidt  */
2647d24bec3aSMark Fasheh static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2648875d1daaSDavid Sterba 			 struct extent_buffer *eb, struct inode_fs_paths *ipath)
2649a542ad1bSJan Schmidt {
2650a542ad1bSJan Schmidt 	char *fspath;
2651a542ad1bSJan Schmidt 	char *fspath_min;
2652a542ad1bSJan Schmidt 	int i = ipath->fspath->elem_cnt;
2653a542ad1bSJan Schmidt 	const int s_ptr = sizeof(char *);
2654a542ad1bSJan Schmidt 	u32 bytes_left;
2655a542ad1bSJan Schmidt 
2656a542ad1bSJan Schmidt 	bytes_left = ipath->fspath->bytes_left > s_ptr ?
2657a542ad1bSJan Schmidt 					ipath->fspath->bytes_left - s_ptr : 0;
2658a542ad1bSJan Schmidt 
2659740c3d22SChris Mason 	fspath_min = (char *)ipath->fspath->val + (i + 1) * s_ptr;
266096b5bd77SJan Schmidt 	fspath = btrfs_ref_to_path(ipath->fs_root, ipath->btrfs_path, name_len,
266196b5bd77SJan Schmidt 				   name_off, eb, inum, fspath_min, bytes_left);
2662a542ad1bSJan Schmidt 	if (IS_ERR(fspath))
2663a542ad1bSJan Schmidt 		return PTR_ERR(fspath);
2664a542ad1bSJan Schmidt 
2665a542ad1bSJan Schmidt 	if (fspath > fspath_min) {
2666745c4d8eSJeff Mahoney 		ipath->fspath->val[i] = (u64)(unsigned long)fspath;
2667a542ad1bSJan Schmidt 		++ipath->fspath->elem_cnt;
2668a542ad1bSJan Schmidt 		ipath->fspath->bytes_left = fspath - fspath_min;
2669a542ad1bSJan Schmidt 	} else {
2670a542ad1bSJan Schmidt 		++ipath->fspath->elem_missed;
2671a542ad1bSJan Schmidt 		ipath->fspath->bytes_missing += fspath_min - fspath;
2672a542ad1bSJan Schmidt 		ipath->fspath->bytes_left = 0;
2673a542ad1bSJan Schmidt 	}
2674a542ad1bSJan Schmidt 
2675a542ad1bSJan Schmidt 	return 0;
2676a542ad1bSJan Schmidt }
2677a542ad1bSJan Schmidt 
2678a542ad1bSJan Schmidt /*
2679a542ad1bSJan Schmidt  * this dumps all file system paths to the inode into the ipath struct, provided
2680a542ad1bSJan Schmidt  * is has been created large enough. each path is zero-terminated and accessed
2681740c3d22SChris Mason  * from ipath->fspath->val[i].
2682a542ad1bSJan Schmidt  * when it returns, there are ipath->fspath->elem_cnt number of paths available
2683740c3d22SChris Mason  * in ipath->fspath->val[]. when the allocated space wasn't sufficient, the
268401327610SNicholas D Steeves  * number of missed paths is recorded in ipath->fspath->elem_missed, otherwise,
2685a542ad1bSJan Schmidt  * it's zero. ipath->fspath->bytes_missing holds the number of bytes that would
2686a542ad1bSJan Schmidt  * have been needed to return all paths.
2687a542ad1bSJan Schmidt  */
2688a542ad1bSJan Schmidt int paths_from_inode(u64 inum, struct inode_fs_paths *ipath)
2689a542ad1bSJan Schmidt {
2690ad6240f6SDavid Sterba 	int ret;
2691ad6240f6SDavid Sterba 	int found_refs = 0;
2692ad6240f6SDavid Sterba 
2693875d1daaSDavid Sterba 	ret = iterate_inode_refs(inum, ipath);
2694ad6240f6SDavid Sterba 	if (!ret)
2695ad6240f6SDavid Sterba 		++found_refs;
2696ad6240f6SDavid Sterba 	else if (ret != -ENOENT)
2697ad6240f6SDavid Sterba 		return ret;
2698ad6240f6SDavid Sterba 
2699875d1daaSDavid Sterba 	ret = iterate_inode_extrefs(inum, ipath);
2700ad6240f6SDavid Sterba 	if (ret == -ENOENT && found_refs)
2701ad6240f6SDavid Sterba 		return 0;
2702ad6240f6SDavid Sterba 
2703ad6240f6SDavid Sterba 	return ret;
2704a542ad1bSJan Schmidt }
2705a542ad1bSJan Schmidt 
2706a542ad1bSJan Schmidt struct btrfs_data_container *init_data_container(u32 total_bytes)
2707a542ad1bSJan Schmidt {
2708a542ad1bSJan Schmidt 	struct btrfs_data_container *data;
2709a542ad1bSJan Schmidt 	size_t alloc_bytes;
2710a542ad1bSJan Schmidt 
2711a542ad1bSJan Schmidt 	alloc_bytes = max_t(size_t, total_bytes, sizeof(*data));
2712f54de068SDavid Sterba 	data = kvmalloc(alloc_bytes, GFP_KERNEL);
2713a542ad1bSJan Schmidt 	if (!data)
2714a542ad1bSJan Schmidt 		return ERR_PTR(-ENOMEM);
2715a542ad1bSJan Schmidt 
2716a542ad1bSJan Schmidt 	if (total_bytes >= sizeof(*data)) {
2717a542ad1bSJan Schmidt 		data->bytes_left = total_bytes - sizeof(*data);
2718a542ad1bSJan Schmidt 		data->bytes_missing = 0;
2719a542ad1bSJan Schmidt 	} else {
2720a542ad1bSJan Schmidt 		data->bytes_missing = sizeof(*data) - total_bytes;
2721a542ad1bSJan Schmidt 		data->bytes_left = 0;
2722a542ad1bSJan Schmidt 	}
2723a542ad1bSJan Schmidt 
2724a542ad1bSJan Schmidt 	data->elem_cnt = 0;
2725a542ad1bSJan Schmidt 	data->elem_missed = 0;
2726a542ad1bSJan Schmidt 
2727a542ad1bSJan Schmidt 	return data;
2728a542ad1bSJan Schmidt }
2729a542ad1bSJan Schmidt 
2730a542ad1bSJan Schmidt /*
2731a542ad1bSJan Schmidt  * allocates space to return multiple file system paths for an inode.
2732a542ad1bSJan Schmidt  * total_bytes to allocate are passed, note that space usable for actual path
2733a542ad1bSJan Schmidt  * information will be total_bytes - sizeof(struct inode_fs_paths).
2734a542ad1bSJan Schmidt  * the returned pointer must be freed with free_ipath() in the end.
2735a542ad1bSJan Schmidt  */
2736a542ad1bSJan Schmidt struct inode_fs_paths *init_ipath(s32 total_bytes, struct btrfs_root *fs_root,
2737a542ad1bSJan Schmidt 					struct btrfs_path *path)
2738a542ad1bSJan Schmidt {
2739a542ad1bSJan Schmidt 	struct inode_fs_paths *ifp;
2740a542ad1bSJan Schmidt 	struct btrfs_data_container *fspath;
2741a542ad1bSJan Schmidt 
2742a542ad1bSJan Schmidt 	fspath = init_data_container(total_bytes);
2743a542ad1bSJan Schmidt 	if (IS_ERR(fspath))
2744afc6961fSMisono Tomohiro 		return ERR_CAST(fspath);
2745a542ad1bSJan Schmidt 
2746f54de068SDavid Sterba 	ifp = kmalloc(sizeof(*ifp), GFP_KERNEL);
2747a542ad1bSJan Schmidt 	if (!ifp) {
2748f54de068SDavid Sterba 		kvfree(fspath);
2749a542ad1bSJan Schmidt 		return ERR_PTR(-ENOMEM);
2750a542ad1bSJan Schmidt 	}
2751a542ad1bSJan Schmidt 
2752a542ad1bSJan Schmidt 	ifp->btrfs_path = path;
2753a542ad1bSJan Schmidt 	ifp->fspath = fspath;
2754a542ad1bSJan Schmidt 	ifp->fs_root = fs_root;
2755a542ad1bSJan Schmidt 
2756a542ad1bSJan Schmidt 	return ifp;
2757a542ad1bSJan Schmidt }
2758a542ad1bSJan Schmidt 
2759a542ad1bSJan Schmidt void free_ipath(struct inode_fs_paths *ipath)
2760a542ad1bSJan Schmidt {
27614735fb28SJesper Juhl 	if (!ipath)
27624735fb28SJesper Juhl 		return;
2763f54de068SDavid Sterba 	kvfree(ipath->fspath);
2764a542ad1bSJan Schmidt 	kfree(ipath);
2765a542ad1bSJan Schmidt }
2766a37f232bSQu Wenruo 
2767d68194b2SDavid Sterba struct btrfs_backref_iter *btrfs_backref_iter_alloc(struct btrfs_fs_info *fs_info)
2768a37f232bSQu Wenruo {
2769a37f232bSQu Wenruo 	struct btrfs_backref_iter *ret;
2770a37f232bSQu Wenruo 
2771d68194b2SDavid Sterba 	ret = kzalloc(sizeof(*ret), GFP_NOFS);
2772a37f232bSQu Wenruo 	if (!ret)
2773a37f232bSQu Wenruo 		return NULL;
2774a37f232bSQu Wenruo 
2775a37f232bSQu Wenruo 	ret->path = btrfs_alloc_path();
2776c15c2ec0SBoleyn Su 	if (!ret->path) {
2777a37f232bSQu Wenruo 		kfree(ret);
2778a37f232bSQu Wenruo 		return NULL;
2779a37f232bSQu Wenruo 	}
2780a37f232bSQu Wenruo 
2781a37f232bSQu Wenruo 	/* Current backref iterator only supports iteration in commit root */
2782a37f232bSQu Wenruo 	ret->path->search_commit_root = 1;
2783a37f232bSQu Wenruo 	ret->path->skip_locking = 1;
2784a37f232bSQu Wenruo 	ret->fs_info = fs_info;
2785a37f232bSQu Wenruo 
2786a37f232bSQu Wenruo 	return ret;
2787a37f232bSQu Wenruo }
2788a37f232bSQu Wenruo 
2789a37f232bSQu Wenruo int btrfs_backref_iter_start(struct btrfs_backref_iter *iter, u64 bytenr)
2790a37f232bSQu Wenruo {
2791a37f232bSQu Wenruo 	struct btrfs_fs_info *fs_info = iter->fs_info;
279229cbcf40SJosef Bacik 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2793a37f232bSQu Wenruo 	struct btrfs_path *path = iter->path;
2794a37f232bSQu Wenruo 	struct btrfs_extent_item *ei;
2795a37f232bSQu Wenruo 	struct btrfs_key key;
2796a37f232bSQu Wenruo 	int ret;
2797a37f232bSQu Wenruo 
2798a37f232bSQu Wenruo 	key.objectid = bytenr;
2799a37f232bSQu Wenruo 	key.type = BTRFS_METADATA_ITEM_KEY;
2800a37f232bSQu Wenruo 	key.offset = (u64)-1;
2801a37f232bSQu Wenruo 	iter->bytenr = bytenr;
2802a37f232bSQu Wenruo 
280329cbcf40SJosef Bacik 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2804a37f232bSQu Wenruo 	if (ret < 0)
2805a37f232bSQu Wenruo 		return ret;
2806a37f232bSQu Wenruo 	if (ret == 0) {
2807a37f232bSQu Wenruo 		ret = -EUCLEAN;
2808a37f232bSQu Wenruo 		goto release;
2809a37f232bSQu Wenruo 	}
2810a37f232bSQu Wenruo 	if (path->slots[0] == 0) {
2811a37f232bSQu Wenruo 		WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
2812a37f232bSQu Wenruo 		ret = -EUCLEAN;
2813a37f232bSQu Wenruo 		goto release;
2814a37f232bSQu Wenruo 	}
2815a37f232bSQu Wenruo 	path->slots[0]--;
2816a37f232bSQu Wenruo 
2817a37f232bSQu Wenruo 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2818a37f232bSQu Wenruo 	if ((key.type != BTRFS_EXTENT_ITEM_KEY &&
2819a37f232bSQu Wenruo 	     key.type != BTRFS_METADATA_ITEM_KEY) || key.objectid != bytenr) {
2820a37f232bSQu Wenruo 		ret = -ENOENT;
2821a37f232bSQu Wenruo 		goto release;
2822a37f232bSQu Wenruo 	}
2823a37f232bSQu Wenruo 	memcpy(&iter->cur_key, &key, sizeof(key));
2824a37f232bSQu Wenruo 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2825a37f232bSQu Wenruo 						    path->slots[0]);
2826a37f232bSQu Wenruo 	iter->end_ptr = (u32)(iter->item_ptr +
28273212fa14SJosef Bacik 			btrfs_item_size(path->nodes[0], path->slots[0]));
2828a37f232bSQu Wenruo 	ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
2829a37f232bSQu Wenruo 			    struct btrfs_extent_item);
2830a37f232bSQu Wenruo 
2831a37f232bSQu Wenruo 	/*
2832a37f232bSQu Wenruo 	 * Only support iteration on tree backref yet.
2833a37f232bSQu Wenruo 	 *
2834a37f232bSQu Wenruo 	 * This is an extra precaution for non skinny-metadata, where
2835a37f232bSQu Wenruo 	 * EXTENT_ITEM is also used for tree blocks, that we can only use
2836a37f232bSQu Wenruo 	 * extent flags to determine if it's a tree block.
2837a37f232bSQu Wenruo 	 */
2838a37f232bSQu Wenruo 	if (btrfs_extent_flags(path->nodes[0], ei) & BTRFS_EXTENT_FLAG_DATA) {
2839a37f232bSQu Wenruo 		ret = -ENOTSUPP;
2840a37f232bSQu Wenruo 		goto release;
2841a37f232bSQu Wenruo 	}
2842a37f232bSQu Wenruo 	iter->cur_ptr = (u32)(iter->item_ptr + sizeof(*ei));
2843a37f232bSQu Wenruo 
2844a37f232bSQu Wenruo 	/* If there is no inline backref, go search for keyed backref */
2845a37f232bSQu Wenruo 	if (iter->cur_ptr >= iter->end_ptr) {
284629cbcf40SJosef Bacik 		ret = btrfs_next_item(extent_root, path);
2847a37f232bSQu Wenruo 
2848a37f232bSQu Wenruo 		/* No inline nor keyed ref */
2849a37f232bSQu Wenruo 		if (ret > 0) {
2850a37f232bSQu Wenruo 			ret = -ENOENT;
2851a37f232bSQu Wenruo 			goto release;
2852a37f232bSQu Wenruo 		}
2853a37f232bSQu Wenruo 		if (ret < 0)
2854a37f232bSQu Wenruo 			goto release;
2855a37f232bSQu Wenruo 
2856a37f232bSQu Wenruo 		btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key,
2857a37f232bSQu Wenruo 				path->slots[0]);
2858a37f232bSQu Wenruo 		if (iter->cur_key.objectid != bytenr ||
2859a37f232bSQu Wenruo 		    (iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
2860a37f232bSQu Wenruo 		     iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY)) {
2861a37f232bSQu Wenruo 			ret = -ENOENT;
2862a37f232bSQu Wenruo 			goto release;
2863a37f232bSQu Wenruo 		}
2864a37f232bSQu Wenruo 		iter->cur_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2865a37f232bSQu Wenruo 							   path->slots[0]);
2866a37f232bSQu Wenruo 		iter->item_ptr = iter->cur_ptr;
28673212fa14SJosef Bacik 		iter->end_ptr = (u32)(iter->item_ptr + btrfs_item_size(
2868a37f232bSQu Wenruo 				      path->nodes[0], path->slots[0]));
2869a37f232bSQu Wenruo 	}
2870a37f232bSQu Wenruo 
2871a37f232bSQu Wenruo 	return 0;
2872a37f232bSQu Wenruo release:
2873a37f232bSQu Wenruo 	btrfs_backref_iter_release(iter);
2874a37f232bSQu Wenruo 	return ret;
2875a37f232bSQu Wenruo }
2876c39c2ddcSQu Wenruo 
2877c39c2ddcSQu Wenruo /*
2878c39c2ddcSQu Wenruo  * Go to the next backref item of current bytenr, can be either inlined or
2879c39c2ddcSQu Wenruo  * keyed.
2880c39c2ddcSQu Wenruo  *
2881c39c2ddcSQu Wenruo  * Caller needs to check whether it's inline ref or not by iter->cur_key.
2882c39c2ddcSQu Wenruo  *
2883c39c2ddcSQu Wenruo  * Return 0 if we get next backref without problem.
2884c39c2ddcSQu Wenruo  * Return >0 if there is no extra backref for this bytenr.
2885c39c2ddcSQu Wenruo  * Return <0 if there is something wrong happened.
2886c39c2ddcSQu Wenruo  */
2887c39c2ddcSQu Wenruo int btrfs_backref_iter_next(struct btrfs_backref_iter *iter)
2888c39c2ddcSQu Wenruo {
2889c39c2ddcSQu Wenruo 	struct extent_buffer *eb = btrfs_backref_get_eb(iter);
289029cbcf40SJosef Bacik 	struct btrfs_root *extent_root;
2891c39c2ddcSQu Wenruo 	struct btrfs_path *path = iter->path;
2892c39c2ddcSQu Wenruo 	struct btrfs_extent_inline_ref *iref;
2893c39c2ddcSQu Wenruo 	int ret;
2894c39c2ddcSQu Wenruo 	u32 size;
2895c39c2ddcSQu Wenruo 
2896c39c2ddcSQu Wenruo 	if (btrfs_backref_iter_is_inline_ref(iter)) {
2897c39c2ddcSQu Wenruo 		/* We're still inside the inline refs */
2898c39c2ddcSQu Wenruo 		ASSERT(iter->cur_ptr < iter->end_ptr);
2899c39c2ddcSQu Wenruo 
2900c39c2ddcSQu Wenruo 		if (btrfs_backref_has_tree_block_info(iter)) {
2901c39c2ddcSQu Wenruo 			/* First tree block info */
2902c39c2ddcSQu Wenruo 			size = sizeof(struct btrfs_tree_block_info);
2903c39c2ddcSQu Wenruo 		} else {
2904c39c2ddcSQu Wenruo 			/* Use inline ref type to determine the size */
2905c39c2ddcSQu Wenruo 			int type;
2906c39c2ddcSQu Wenruo 
2907c39c2ddcSQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
2908c39c2ddcSQu Wenruo 				((unsigned long)iter->cur_ptr);
2909c39c2ddcSQu Wenruo 			type = btrfs_extent_inline_ref_type(eb, iref);
2910c39c2ddcSQu Wenruo 
2911c39c2ddcSQu Wenruo 			size = btrfs_extent_inline_ref_size(type);
2912c39c2ddcSQu Wenruo 		}
2913c39c2ddcSQu Wenruo 		iter->cur_ptr += size;
2914c39c2ddcSQu Wenruo 		if (iter->cur_ptr < iter->end_ptr)
2915c39c2ddcSQu Wenruo 			return 0;
2916c39c2ddcSQu Wenruo 
2917c39c2ddcSQu Wenruo 		/* All inline items iterated, fall through */
2918c39c2ddcSQu Wenruo 	}
2919c39c2ddcSQu Wenruo 
2920c39c2ddcSQu Wenruo 	/* We're at keyed items, there is no inline item, go to the next one */
292129cbcf40SJosef Bacik 	extent_root = btrfs_extent_root(iter->fs_info, iter->bytenr);
292229cbcf40SJosef Bacik 	ret = btrfs_next_item(extent_root, iter->path);
2923c39c2ddcSQu Wenruo 	if (ret)
2924c39c2ddcSQu Wenruo 		return ret;
2925c39c2ddcSQu Wenruo 
2926c39c2ddcSQu Wenruo 	btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key, path->slots[0]);
2927c39c2ddcSQu Wenruo 	if (iter->cur_key.objectid != iter->bytenr ||
2928c39c2ddcSQu Wenruo 	    (iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
2929c39c2ddcSQu Wenruo 	     iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY))
2930c39c2ddcSQu Wenruo 		return 1;
2931c39c2ddcSQu Wenruo 	iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2932c39c2ddcSQu Wenruo 					path->slots[0]);
2933c39c2ddcSQu Wenruo 	iter->cur_ptr = iter->item_ptr;
29343212fa14SJosef Bacik 	iter->end_ptr = iter->item_ptr + (u32)btrfs_item_size(path->nodes[0],
2935c39c2ddcSQu Wenruo 						path->slots[0]);
2936c39c2ddcSQu Wenruo 	return 0;
2937c39c2ddcSQu Wenruo }
2938584fb121SQu Wenruo 
2939584fb121SQu Wenruo void btrfs_backref_init_cache(struct btrfs_fs_info *fs_info,
2940584fb121SQu Wenruo 			      struct btrfs_backref_cache *cache, int is_reloc)
2941584fb121SQu Wenruo {
2942584fb121SQu Wenruo 	int i;
2943584fb121SQu Wenruo 
2944584fb121SQu Wenruo 	cache->rb_root = RB_ROOT;
2945584fb121SQu Wenruo 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
2946584fb121SQu Wenruo 		INIT_LIST_HEAD(&cache->pending[i]);
2947584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->changed);
2948584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->detached);
2949584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->leaves);
2950584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->pending_edge);
2951584fb121SQu Wenruo 	INIT_LIST_HEAD(&cache->useless_node);
2952584fb121SQu Wenruo 	cache->fs_info = fs_info;
2953584fb121SQu Wenruo 	cache->is_reloc = is_reloc;
2954584fb121SQu Wenruo }
2955b1818dabSQu Wenruo 
2956b1818dabSQu Wenruo struct btrfs_backref_node *btrfs_backref_alloc_node(
2957b1818dabSQu Wenruo 		struct btrfs_backref_cache *cache, u64 bytenr, int level)
2958b1818dabSQu Wenruo {
2959b1818dabSQu Wenruo 	struct btrfs_backref_node *node;
2960b1818dabSQu Wenruo 
2961b1818dabSQu Wenruo 	ASSERT(level >= 0 && level < BTRFS_MAX_LEVEL);
2962b1818dabSQu Wenruo 	node = kzalloc(sizeof(*node), GFP_NOFS);
2963b1818dabSQu Wenruo 	if (!node)
2964b1818dabSQu Wenruo 		return node;
2965b1818dabSQu Wenruo 
2966b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->list);
2967b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->upper);
2968b1818dabSQu Wenruo 	INIT_LIST_HEAD(&node->lower);
2969b1818dabSQu Wenruo 	RB_CLEAR_NODE(&node->rb_node);
2970b1818dabSQu Wenruo 	cache->nr_nodes++;
2971b1818dabSQu Wenruo 	node->level = level;
2972b1818dabSQu Wenruo 	node->bytenr = bytenr;
2973b1818dabSQu Wenruo 
2974b1818dabSQu Wenruo 	return node;
2975b1818dabSQu Wenruo }
297647254d07SQu Wenruo 
297747254d07SQu Wenruo struct btrfs_backref_edge *btrfs_backref_alloc_edge(
297847254d07SQu Wenruo 		struct btrfs_backref_cache *cache)
297947254d07SQu Wenruo {
298047254d07SQu Wenruo 	struct btrfs_backref_edge *edge;
298147254d07SQu Wenruo 
298247254d07SQu Wenruo 	edge = kzalloc(sizeof(*edge), GFP_NOFS);
298347254d07SQu Wenruo 	if (edge)
298447254d07SQu Wenruo 		cache->nr_edges++;
298547254d07SQu Wenruo 	return edge;
298647254d07SQu Wenruo }
2987023acb07SQu Wenruo 
2988023acb07SQu Wenruo /*
2989023acb07SQu Wenruo  * Drop the backref node from cache, also cleaning up all its
2990023acb07SQu Wenruo  * upper edges and any uncached nodes in the path.
2991023acb07SQu Wenruo  *
2992023acb07SQu Wenruo  * This cleanup happens bottom up, thus the node should either
2993023acb07SQu Wenruo  * be the lowest node in the cache or a detached node.
2994023acb07SQu Wenruo  */
2995023acb07SQu Wenruo void btrfs_backref_cleanup_node(struct btrfs_backref_cache *cache,
2996023acb07SQu Wenruo 				struct btrfs_backref_node *node)
2997023acb07SQu Wenruo {
2998023acb07SQu Wenruo 	struct btrfs_backref_node *upper;
2999023acb07SQu Wenruo 	struct btrfs_backref_edge *edge;
3000023acb07SQu Wenruo 
3001023acb07SQu Wenruo 	if (!node)
3002023acb07SQu Wenruo 		return;
3003023acb07SQu Wenruo 
3004023acb07SQu Wenruo 	BUG_ON(!node->lowest && !node->detached);
3005023acb07SQu Wenruo 	while (!list_empty(&node->upper)) {
3006023acb07SQu Wenruo 		edge = list_entry(node->upper.next, struct btrfs_backref_edge,
3007023acb07SQu Wenruo 				  list[LOWER]);
3008023acb07SQu Wenruo 		upper = edge->node[UPPER];
3009023acb07SQu Wenruo 		list_del(&edge->list[LOWER]);
3010023acb07SQu Wenruo 		list_del(&edge->list[UPPER]);
3011023acb07SQu Wenruo 		btrfs_backref_free_edge(cache, edge);
3012023acb07SQu Wenruo 
3013023acb07SQu Wenruo 		/*
3014023acb07SQu Wenruo 		 * Add the node to leaf node list if no other child block
3015023acb07SQu Wenruo 		 * cached.
3016023acb07SQu Wenruo 		 */
3017023acb07SQu Wenruo 		if (list_empty(&upper->lower)) {
3018023acb07SQu Wenruo 			list_add_tail(&upper->lower, &cache->leaves);
3019023acb07SQu Wenruo 			upper->lowest = 1;
3020023acb07SQu Wenruo 		}
3021023acb07SQu Wenruo 	}
3022023acb07SQu Wenruo 
3023023acb07SQu Wenruo 	btrfs_backref_drop_node(cache, node);
3024023acb07SQu Wenruo }
302513fe1bdbSQu Wenruo 
302613fe1bdbSQu Wenruo /*
302713fe1bdbSQu Wenruo  * Release all nodes/edges from current cache
302813fe1bdbSQu Wenruo  */
302913fe1bdbSQu Wenruo void btrfs_backref_release_cache(struct btrfs_backref_cache *cache)
303013fe1bdbSQu Wenruo {
303113fe1bdbSQu Wenruo 	struct btrfs_backref_node *node;
303213fe1bdbSQu Wenruo 	int i;
303313fe1bdbSQu Wenruo 
303413fe1bdbSQu Wenruo 	while (!list_empty(&cache->detached)) {
303513fe1bdbSQu Wenruo 		node = list_entry(cache->detached.next,
303613fe1bdbSQu Wenruo 				  struct btrfs_backref_node, list);
303713fe1bdbSQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
303813fe1bdbSQu Wenruo 	}
303913fe1bdbSQu Wenruo 
304013fe1bdbSQu Wenruo 	while (!list_empty(&cache->leaves)) {
304113fe1bdbSQu Wenruo 		node = list_entry(cache->leaves.next,
304213fe1bdbSQu Wenruo 				  struct btrfs_backref_node, lower);
304313fe1bdbSQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
304413fe1bdbSQu Wenruo 	}
304513fe1bdbSQu Wenruo 
304613fe1bdbSQu Wenruo 	cache->last_trans = 0;
304713fe1bdbSQu Wenruo 
304813fe1bdbSQu Wenruo 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
304913fe1bdbSQu Wenruo 		ASSERT(list_empty(&cache->pending[i]));
305013fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->pending_edge));
305113fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->useless_node));
305213fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->changed));
305313fe1bdbSQu Wenruo 	ASSERT(list_empty(&cache->detached));
305413fe1bdbSQu Wenruo 	ASSERT(RB_EMPTY_ROOT(&cache->rb_root));
305513fe1bdbSQu Wenruo 	ASSERT(!cache->nr_nodes);
305613fe1bdbSQu Wenruo 	ASSERT(!cache->nr_edges);
305713fe1bdbSQu Wenruo }
30581b60d2ecSQu Wenruo 
30591b60d2ecSQu Wenruo /*
30601b60d2ecSQu Wenruo  * Handle direct tree backref
30611b60d2ecSQu Wenruo  *
30621b60d2ecSQu Wenruo  * Direct tree backref means, the backref item shows its parent bytenr
30631b60d2ecSQu Wenruo  * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
30641b60d2ecSQu Wenruo  *
30651b60d2ecSQu Wenruo  * @ref_key:	The converted backref key.
30661b60d2ecSQu Wenruo  *		For keyed backref, it's the item key.
30671b60d2ecSQu Wenruo  *		For inlined backref, objectid is the bytenr,
30681b60d2ecSQu Wenruo  *		type is btrfs_inline_ref_type, offset is
30691b60d2ecSQu Wenruo  *		btrfs_inline_ref_offset.
30701b60d2ecSQu Wenruo  */
30711b60d2ecSQu Wenruo static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
30721b60d2ecSQu Wenruo 				      struct btrfs_key *ref_key,
30731b60d2ecSQu Wenruo 				      struct btrfs_backref_node *cur)
30741b60d2ecSQu Wenruo {
30751b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
30761b60d2ecSQu Wenruo 	struct btrfs_backref_node *upper;
30771b60d2ecSQu Wenruo 	struct rb_node *rb_node;
30781b60d2ecSQu Wenruo 
30791b60d2ecSQu Wenruo 	ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
30801b60d2ecSQu Wenruo 
30811b60d2ecSQu Wenruo 	/* Only reloc root uses backref pointing to itself */
30821b60d2ecSQu Wenruo 	if (ref_key->objectid == ref_key->offset) {
30831b60d2ecSQu Wenruo 		struct btrfs_root *root;
30841b60d2ecSQu Wenruo 
30851b60d2ecSQu Wenruo 		cur->is_reloc_root = 1;
30861b60d2ecSQu Wenruo 		/* Only reloc backref cache cares about a specific root */
30871b60d2ecSQu Wenruo 		if (cache->is_reloc) {
30881b60d2ecSQu Wenruo 			root = find_reloc_root(cache->fs_info, cur->bytenr);
3089f78743fbSJosef Bacik 			if (!root)
30901b60d2ecSQu Wenruo 				return -ENOENT;
30911b60d2ecSQu Wenruo 			cur->root = root;
30921b60d2ecSQu Wenruo 		} else {
30931b60d2ecSQu Wenruo 			/*
30941b60d2ecSQu Wenruo 			 * For generic purpose backref cache, reloc root node
30951b60d2ecSQu Wenruo 			 * is useless.
30961b60d2ecSQu Wenruo 			 */
30971b60d2ecSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
30981b60d2ecSQu Wenruo 		}
30991b60d2ecSQu Wenruo 		return 0;
31001b60d2ecSQu Wenruo 	}
31011b60d2ecSQu Wenruo 
31021b60d2ecSQu Wenruo 	edge = btrfs_backref_alloc_edge(cache);
31031b60d2ecSQu Wenruo 	if (!edge)
31041b60d2ecSQu Wenruo 		return -ENOMEM;
31051b60d2ecSQu Wenruo 
31061b60d2ecSQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
31071b60d2ecSQu Wenruo 	if (!rb_node) {
31081b60d2ecSQu Wenruo 		/* Parent node not yet cached */
31091b60d2ecSQu Wenruo 		upper = btrfs_backref_alloc_node(cache, ref_key->offset,
31101b60d2ecSQu Wenruo 					   cur->level + 1);
31111b60d2ecSQu Wenruo 		if (!upper) {
31121b60d2ecSQu Wenruo 			btrfs_backref_free_edge(cache, edge);
31131b60d2ecSQu Wenruo 			return -ENOMEM;
31141b60d2ecSQu Wenruo 		}
31151b60d2ecSQu Wenruo 
31161b60d2ecSQu Wenruo 		/*
31171b60d2ecSQu Wenruo 		 *  Backrefs for the upper level block isn't cached, add the
31181b60d2ecSQu Wenruo 		 *  block to pending list
31191b60d2ecSQu Wenruo 		 */
31201b60d2ecSQu Wenruo 		list_add_tail(&edge->list[UPPER], &cache->pending_edge);
31211b60d2ecSQu Wenruo 	} else {
31221b60d2ecSQu Wenruo 		/* Parent node already cached */
31231b60d2ecSQu Wenruo 		upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
31241b60d2ecSQu Wenruo 		ASSERT(upper->checked);
31251b60d2ecSQu Wenruo 		INIT_LIST_HEAD(&edge->list[UPPER]);
31261b60d2ecSQu Wenruo 	}
31271b60d2ecSQu Wenruo 	btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
31281b60d2ecSQu Wenruo 	return 0;
31291b60d2ecSQu Wenruo }
31301b60d2ecSQu Wenruo 
31311b60d2ecSQu Wenruo /*
31321b60d2ecSQu Wenruo  * Handle indirect tree backref
31331b60d2ecSQu Wenruo  *
31341b60d2ecSQu Wenruo  * Indirect tree backref means, we only know which tree the node belongs to.
31351b60d2ecSQu Wenruo  * We still need to do a tree search to find out the parents. This is for
31361b60d2ecSQu Wenruo  * TREE_BLOCK_REF backref (keyed or inlined).
31371b60d2ecSQu Wenruo  *
31381b60d2ecSQu Wenruo  * @ref_key:	The same as @ref_key in  handle_direct_tree_backref()
31391b60d2ecSQu Wenruo  * @tree_key:	The first key of this tree block.
31401b60d2ecSQu Wenruo  * @path:	A clean (released) path, to avoid allocating path every time
31411b60d2ecSQu Wenruo  *		the function get called.
31421b60d2ecSQu Wenruo  */
31431b60d2ecSQu Wenruo static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
31441b60d2ecSQu Wenruo 					struct btrfs_path *path,
31451b60d2ecSQu Wenruo 					struct btrfs_key *ref_key,
31461b60d2ecSQu Wenruo 					struct btrfs_key *tree_key,
31471b60d2ecSQu Wenruo 					struct btrfs_backref_node *cur)
31481b60d2ecSQu Wenruo {
31491b60d2ecSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
31501b60d2ecSQu Wenruo 	struct btrfs_backref_node *upper;
31511b60d2ecSQu Wenruo 	struct btrfs_backref_node *lower;
31521b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
31531b60d2ecSQu Wenruo 	struct extent_buffer *eb;
31541b60d2ecSQu Wenruo 	struct btrfs_root *root;
31551b60d2ecSQu Wenruo 	struct rb_node *rb_node;
31561b60d2ecSQu Wenruo 	int level;
31571b60d2ecSQu Wenruo 	bool need_check = true;
31581b60d2ecSQu Wenruo 	int ret;
31591b60d2ecSQu Wenruo 
316056e9357aSDavid Sterba 	root = btrfs_get_fs_root(fs_info, ref_key->offset, false);
31611b60d2ecSQu Wenruo 	if (IS_ERR(root))
31621b60d2ecSQu Wenruo 		return PTR_ERR(root);
316392a7cc42SQu Wenruo 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
31641b60d2ecSQu Wenruo 		cur->cowonly = 1;
31651b60d2ecSQu Wenruo 
31661b60d2ecSQu Wenruo 	if (btrfs_root_level(&root->root_item) == cur->level) {
31671b60d2ecSQu Wenruo 		/* Tree root */
31681b60d2ecSQu Wenruo 		ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
3169876de781SQu Wenruo 		/*
3170876de781SQu Wenruo 		 * For reloc backref cache, we may ignore reloc root.  But for
3171876de781SQu Wenruo 		 * general purpose backref cache, we can't rely on
3172876de781SQu Wenruo 		 * btrfs_should_ignore_reloc_root() as it may conflict with
3173876de781SQu Wenruo 		 * current running relocation and lead to missing root.
3174876de781SQu Wenruo 		 *
3175876de781SQu Wenruo 		 * For general purpose backref cache, reloc root detection is
3176876de781SQu Wenruo 		 * completely relying on direct backref (key->offset is parent
3177876de781SQu Wenruo 		 * bytenr), thus only do such check for reloc cache.
3178876de781SQu Wenruo 		 */
3179876de781SQu Wenruo 		if (btrfs_should_ignore_reloc_root(root) && cache->is_reloc) {
31801b60d2ecSQu Wenruo 			btrfs_put_root(root);
31811b60d2ecSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
31821b60d2ecSQu Wenruo 		} else {
31831b60d2ecSQu Wenruo 			cur->root = root;
31841b60d2ecSQu Wenruo 		}
31851b60d2ecSQu Wenruo 		return 0;
31861b60d2ecSQu Wenruo 	}
31871b60d2ecSQu Wenruo 
31881b60d2ecSQu Wenruo 	level = cur->level + 1;
31891b60d2ecSQu Wenruo 
31901b60d2ecSQu Wenruo 	/* Search the tree to find parent blocks referring to the block */
31911b60d2ecSQu Wenruo 	path->search_commit_root = 1;
31921b60d2ecSQu Wenruo 	path->skip_locking = 1;
31931b60d2ecSQu Wenruo 	path->lowest_level = level;
31941b60d2ecSQu Wenruo 	ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
31951b60d2ecSQu Wenruo 	path->lowest_level = 0;
31961b60d2ecSQu Wenruo 	if (ret < 0) {
31971b60d2ecSQu Wenruo 		btrfs_put_root(root);
31981b60d2ecSQu Wenruo 		return ret;
31991b60d2ecSQu Wenruo 	}
32001b60d2ecSQu Wenruo 	if (ret > 0 && path->slots[level] > 0)
32011b60d2ecSQu Wenruo 		path->slots[level]--;
32021b60d2ecSQu Wenruo 
32031b60d2ecSQu Wenruo 	eb = path->nodes[level];
32041b60d2ecSQu Wenruo 	if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
32051b60d2ecSQu Wenruo 		btrfs_err(fs_info,
32061b60d2ecSQu Wenruo "couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
32071b60d2ecSQu Wenruo 			  cur->bytenr, level - 1, root->root_key.objectid,
32081b60d2ecSQu Wenruo 			  tree_key->objectid, tree_key->type, tree_key->offset);
32091b60d2ecSQu Wenruo 		btrfs_put_root(root);
32101b60d2ecSQu Wenruo 		ret = -ENOENT;
32111b60d2ecSQu Wenruo 		goto out;
32121b60d2ecSQu Wenruo 	}
32131b60d2ecSQu Wenruo 	lower = cur;
32141b60d2ecSQu Wenruo 
32151b60d2ecSQu Wenruo 	/* Add all nodes and edges in the path */
32161b60d2ecSQu Wenruo 	for (; level < BTRFS_MAX_LEVEL; level++) {
32171b60d2ecSQu Wenruo 		if (!path->nodes[level]) {
32181b60d2ecSQu Wenruo 			ASSERT(btrfs_root_bytenr(&root->root_item) ==
32191b60d2ecSQu Wenruo 			       lower->bytenr);
3220876de781SQu Wenruo 			/* Same as previous should_ignore_reloc_root() call */
3221876de781SQu Wenruo 			if (btrfs_should_ignore_reloc_root(root) &&
3222876de781SQu Wenruo 			    cache->is_reloc) {
32231b60d2ecSQu Wenruo 				btrfs_put_root(root);
32241b60d2ecSQu Wenruo 				list_add(&lower->list, &cache->useless_node);
32251b60d2ecSQu Wenruo 			} else {
32261b60d2ecSQu Wenruo 				lower->root = root;
32271b60d2ecSQu Wenruo 			}
32281b60d2ecSQu Wenruo 			break;
32291b60d2ecSQu Wenruo 		}
32301b60d2ecSQu Wenruo 
32311b60d2ecSQu Wenruo 		edge = btrfs_backref_alloc_edge(cache);
32321b60d2ecSQu Wenruo 		if (!edge) {
32331b60d2ecSQu Wenruo 			btrfs_put_root(root);
32341b60d2ecSQu Wenruo 			ret = -ENOMEM;
32351b60d2ecSQu Wenruo 			goto out;
32361b60d2ecSQu Wenruo 		}
32371b60d2ecSQu Wenruo 
32381b60d2ecSQu Wenruo 		eb = path->nodes[level];
32391b60d2ecSQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root, eb->start);
32401b60d2ecSQu Wenruo 		if (!rb_node) {
32411b60d2ecSQu Wenruo 			upper = btrfs_backref_alloc_node(cache, eb->start,
32421b60d2ecSQu Wenruo 							 lower->level + 1);
32431b60d2ecSQu Wenruo 			if (!upper) {
32441b60d2ecSQu Wenruo 				btrfs_put_root(root);
32451b60d2ecSQu Wenruo 				btrfs_backref_free_edge(cache, edge);
32461b60d2ecSQu Wenruo 				ret = -ENOMEM;
32471b60d2ecSQu Wenruo 				goto out;
32481b60d2ecSQu Wenruo 			}
32491b60d2ecSQu Wenruo 			upper->owner = btrfs_header_owner(eb);
325092a7cc42SQu Wenruo 			if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
32511b60d2ecSQu Wenruo 				upper->cowonly = 1;
32521b60d2ecSQu Wenruo 
32531b60d2ecSQu Wenruo 			/*
32541b60d2ecSQu Wenruo 			 * If we know the block isn't shared we can avoid
32551b60d2ecSQu Wenruo 			 * checking its backrefs.
32561b60d2ecSQu Wenruo 			 */
32571b60d2ecSQu Wenruo 			if (btrfs_block_can_be_shared(root, eb))
32581b60d2ecSQu Wenruo 				upper->checked = 0;
32591b60d2ecSQu Wenruo 			else
32601b60d2ecSQu Wenruo 				upper->checked = 1;
32611b60d2ecSQu Wenruo 
32621b60d2ecSQu Wenruo 			/*
32631b60d2ecSQu Wenruo 			 * Add the block to pending list if we need to check its
32641b60d2ecSQu Wenruo 			 * backrefs, we only do this once while walking up a
32651b60d2ecSQu Wenruo 			 * tree as we will catch anything else later on.
32661b60d2ecSQu Wenruo 			 */
32671b60d2ecSQu Wenruo 			if (!upper->checked && need_check) {
32681b60d2ecSQu Wenruo 				need_check = false;
32691b60d2ecSQu Wenruo 				list_add_tail(&edge->list[UPPER],
32701b60d2ecSQu Wenruo 					      &cache->pending_edge);
32711b60d2ecSQu Wenruo 			} else {
32721b60d2ecSQu Wenruo 				if (upper->checked)
32731b60d2ecSQu Wenruo 					need_check = true;
32741b60d2ecSQu Wenruo 				INIT_LIST_HEAD(&edge->list[UPPER]);
32751b60d2ecSQu Wenruo 			}
32761b60d2ecSQu Wenruo 		} else {
32771b60d2ecSQu Wenruo 			upper = rb_entry(rb_node, struct btrfs_backref_node,
32781b60d2ecSQu Wenruo 					 rb_node);
32791b60d2ecSQu Wenruo 			ASSERT(upper->checked);
32801b60d2ecSQu Wenruo 			INIT_LIST_HEAD(&edge->list[UPPER]);
32811b60d2ecSQu Wenruo 			if (!upper->owner)
32821b60d2ecSQu Wenruo 				upper->owner = btrfs_header_owner(eb);
32831b60d2ecSQu Wenruo 		}
32841b60d2ecSQu Wenruo 		btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
32851b60d2ecSQu Wenruo 
32861b60d2ecSQu Wenruo 		if (rb_node) {
32871b60d2ecSQu Wenruo 			btrfs_put_root(root);
32881b60d2ecSQu Wenruo 			break;
32891b60d2ecSQu Wenruo 		}
32901b60d2ecSQu Wenruo 		lower = upper;
32911b60d2ecSQu Wenruo 		upper = NULL;
32921b60d2ecSQu Wenruo 	}
32931b60d2ecSQu Wenruo out:
32941b60d2ecSQu Wenruo 	btrfs_release_path(path);
32951b60d2ecSQu Wenruo 	return ret;
32961b60d2ecSQu Wenruo }
32971b60d2ecSQu Wenruo 
32981b60d2ecSQu Wenruo /*
32991b60d2ecSQu Wenruo  * Add backref node @cur into @cache.
33001b60d2ecSQu Wenruo  *
33011b60d2ecSQu Wenruo  * NOTE: Even if the function returned 0, @cur is not yet cached as its upper
33021b60d2ecSQu Wenruo  *	 links aren't yet bi-directional. Needs to finish such links.
3303fc997ed0SQu Wenruo  *	 Use btrfs_backref_finish_upper_links() to finish such linkage.
33041b60d2ecSQu Wenruo  *
33051b60d2ecSQu Wenruo  * @path:	Released path for indirect tree backref lookup
33061b60d2ecSQu Wenruo  * @iter:	Released backref iter for extent tree search
33071b60d2ecSQu Wenruo  * @node_key:	The first key of the tree block
33081b60d2ecSQu Wenruo  */
33091b60d2ecSQu Wenruo int btrfs_backref_add_tree_node(struct btrfs_backref_cache *cache,
33101b60d2ecSQu Wenruo 				struct btrfs_path *path,
33111b60d2ecSQu Wenruo 				struct btrfs_backref_iter *iter,
33121b60d2ecSQu Wenruo 				struct btrfs_key *node_key,
33131b60d2ecSQu Wenruo 				struct btrfs_backref_node *cur)
33141b60d2ecSQu Wenruo {
33151b60d2ecSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
33161b60d2ecSQu Wenruo 	struct btrfs_backref_edge *edge;
33171b60d2ecSQu Wenruo 	struct btrfs_backref_node *exist;
33181b60d2ecSQu Wenruo 	int ret;
33191b60d2ecSQu Wenruo 
33201b60d2ecSQu Wenruo 	ret = btrfs_backref_iter_start(iter, cur->bytenr);
33211b60d2ecSQu Wenruo 	if (ret < 0)
33221b60d2ecSQu Wenruo 		return ret;
33231b60d2ecSQu Wenruo 	/*
33241b60d2ecSQu Wenruo 	 * We skip the first btrfs_tree_block_info, as we don't use the key
33251b60d2ecSQu Wenruo 	 * stored in it, but fetch it from the tree block
33261b60d2ecSQu Wenruo 	 */
33271b60d2ecSQu Wenruo 	if (btrfs_backref_has_tree_block_info(iter)) {
33281b60d2ecSQu Wenruo 		ret = btrfs_backref_iter_next(iter);
33291b60d2ecSQu Wenruo 		if (ret < 0)
33301b60d2ecSQu Wenruo 			goto out;
33311b60d2ecSQu Wenruo 		/* No extra backref? This means the tree block is corrupted */
33321b60d2ecSQu Wenruo 		if (ret > 0) {
33331b60d2ecSQu Wenruo 			ret = -EUCLEAN;
33341b60d2ecSQu Wenruo 			goto out;
33351b60d2ecSQu Wenruo 		}
33361b60d2ecSQu Wenruo 	}
33371b60d2ecSQu Wenruo 	WARN_ON(cur->checked);
33381b60d2ecSQu Wenruo 	if (!list_empty(&cur->upper)) {
33391b60d2ecSQu Wenruo 		/*
33401b60d2ecSQu Wenruo 		 * The backref was added previously when processing backref of
33411b60d2ecSQu Wenruo 		 * type BTRFS_TREE_BLOCK_REF_KEY
33421b60d2ecSQu Wenruo 		 */
33431b60d2ecSQu Wenruo 		ASSERT(list_is_singular(&cur->upper));
33441b60d2ecSQu Wenruo 		edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
33451b60d2ecSQu Wenruo 				  list[LOWER]);
33461b60d2ecSQu Wenruo 		ASSERT(list_empty(&edge->list[UPPER]));
33471b60d2ecSQu Wenruo 		exist = edge->node[UPPER];
33481b60d2ecSQu Wenruo 		/*
33491b60d2ecSQu Wenruo 		 * Add the upper level block to pending list if we need check
33501b60d2ecSQu Wenruo 		 * its backrefs
33511b60d2ecSQu Wenruo 		 */
33521b60d2ecSQu Wenruo 		if (!exist->checked)
33531b60d2ecSQu Wenruo 			list_add_tail(&edge->list[UPPER], &cache->pending_edge);
33541b60d2ecSQu Wenruo 	} else {
33551b60d2ecSQu Wenruo 		exist = NULL;
33561b60d2ecSQu Wenruo 	}
33571b60d2ecSQu Wenruo 
33581b60d2ecSQu Wenruo 	for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
33591b60d2ecSQu Wenruo 		struct extent_buffer *eb;
33601b60d2ecSQu Wenruo 		struct btrfs_key key;
33611b60d2ecSQu Wenruo 		int type;
33621b60d2ecSQu Wenruo 
33631b60d2ecSQu Wenruo 		cond_resched();
33641b60d2ecSQu Wenruo 		eb = btrfs_backref_get_eb(iter);
33651b60d2ecSQu Wenruo 
33661b60d2ecSQu Wenruo 		key.objectid = iter->bytenr;
33671b60d2ecSQu Wenruo 		if (btrfs_backref_iter_is_inline_ref(iter)) {
33681b60d2ecSQu Wenruo 			struct btrfs_extent_inline_ref *iref;
33691b60d2ecSQu Wenruo 
33701b60d2ecSQu Wenruo 			/* Update key for inline backref */
33711b60d2ecSQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
33721b60d2ecSQu Wenruo 				((unsigned long)iter->cur_ptr);
33731b60d2ecSQu Wenruo 			type = btrfs_get_extent_inline_ref_type(eb, iref,
33741b60d2ecSQu Wenruo 							BTRFS_REF_TYPE_BLOCK);
33751b60d2ecSQu Wenruo 			if (type == BTRFS_REF_TYPE_INVALID) {
33761b60d2ecSQu Wenruo 				ret = -EUCLEAN;
33771b60d2ecSQu Wenruo 				goto out;
33781b60d2ecSQu Wenruo 			}
33791b60d2ecSQu Wenruo 			key.type = type;
33801b60d2ecSQu Wenruo 			key.offset = btrfs_extent_inline_ref_offset(eb, iref);
33811b60d2ecSQu Wenruo 		} else {
33821b60d2ecSQu Wenruo 			key.type = iter->cur_key.type;
33831b60d2ecSQu Wenruo 			key.offset = iter->cur_key.offset;
33841b60d2ecSQu Wenruo 		}
33851b60d2ecSQu Wenruo 
33861b60d2ecSQu Wenruo 		/*
33871b60d2ecSQu Wenruo 		 * Parent node found and matches current inline ref, no need to
33881b60d2ecSQu Wenruo 		 * rebuild this node for this inline ref
33891b60d2ecSQu Wenruo 		 */
33901b60d2ecSQu Wenruo 		if (exist &&
33911b60d2ecSQu Wenruo 		    ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
33921b60d2ecSQu Wenruo 		      exist->owner == key.offset) ||
33931b60d2ecSQu Wenruo 		     (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
33941b60d2ecSQu Wenruo 		      exist->bytenr == key.offset))) {
33951b60d2ecSQu Wenruo 			exist = NULL;
33961b60d2ecSQu Wenruo 			continue;
33971b60d2ecSQu Wenruo 		}
33981b60d2ecSQu Wenruo 
33991b60d2ecSQu Wenruo 		/* SHARED_BLOCK_REF means key.offset is the parent bytenr */
34001b60d2ecSQu Wenruo 		if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
34011b60d2ecSQu Wenruo 			ret = handle_direct_tree_backref(cache, &key, cur);
34021b60d2ecSQu Wenruo 			if (ret < 0)
34031b60d2ecSQu Wenruo 				goto out;
34041b60d2ecSQu Wenruo 			continue;
34051b60d2ecSQu Wenruo 		} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
34061b60d2ecSQu Wenruo 			ret = -EINVAL;
34071b60d2ecSQu Wenruo 			btrfs_print_v0_err(fs_info);
34081b60d2ecSQu Wenruo 			btrfs_handle_fs_error(fs_info, ret, NULL);
34091b60d2ecSQu Wenruo 			goto out;
34101b60d2ecSQu Wenruo 		} else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
34111b60d2ecSQu Wenruo 			continue;
34121b60d2ecSQu Wenruo 		}
34131b60d2ecSQu Wenruo 
34141b60d2ecSQu Wenruo 		/*
34151b60d2ecSQu Wenruo 		 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
34161b60d2ecSQu Wenruo 		 * means the root objectid. We need to search the tree to get
34171b60d2ecSQu Wenruo 		 * its parent bytenr.
34181b60d2ecSQu Wenruo 		 */
34191b60d2ecSQu Wenruo 		ret = handle_indirect_tree_backref(cache, path, &key, node_key,
34201b60d2ecSQu Wenruo 						   cur);
34211b60d2ecSQu Wenruo 		if (ret < 0)
34221b60d2ecSQu Wenruo 			goto out;
34231b60d2ecSQu Wenruo 	}
34241b60d2ecSQu Wenruo 	ret = 0;
34251b60d2ecSQu Wenruo 	cur->checked = 1;
34261b60d2ecSQu Wenruo 	WARN_ON(exist);
34271b60d2ecSQu Wenruo out:
34281b60d2ecSQu Wenruo 	btrfs_backref_iter_release(iter);
34291b60d2ecSQu Wenruo 	return ret;
34301b60d2ecSQu Wenruo }
3431fc997ed0SQu Wenruo 
3432fc997ed0SQu Wenruo /*
3433fc997ed0SQu Wenruo  * Finish the upwards linkage created by btrfs_backref_add_tree_node()
3434fc997ed0SQu Wenruo  */
3435fc997ed0SQu Wenruo int btrfs_backref_finish_upper_links(struct btrfs_backref_cache *cache,
3436fc997ed0SQu Wenruo 				     struct btrfs_backref_node *start)
3437fc997ed0SQu Wenruo {
3438fc997ed0SQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
3439fc997ed0SQu Wenruo 	struct btrfs_backref_edge *edge;
3440fc997ed0SQu Wenruo 	struct rb_node *rb_node;
3441fc997ed0SQu Wenruo 	LIST_HEAD(pending_edge);
3442fc997ed0SQu Wenruo 
3443fc997ed0SQu Wenruo 	ASSERT(start->checked);
3444fc997ed0SQu Wenruo 
3445fc997ed0SQu Wenruo 	/* Insert this node to cache if it's not COW-only */
3446fc997ed0SQu Wenruo 	if (!start->cowonly) {
3447fc997ed0SQu Wenruo 		rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
3448fc997ed0SQu Wenruo 					   &start->rb_node);
3449fc997ed0SQu Wenruo 		if (rb_node)
3450fc997ed0SQu Wenruo 			btrfs_backref_panic(cache->fs_info, start->bytenr,
3451fc997ed0SQu Wenruo 					    -EEXIST);
3452fc997ed0SQu Wenruo 		list_add_tail(&start->lower, &cache->leaves);
3453fc997ed0SQu Wenruo 	}
3454fc997ed0SQu Wenruo 
3455fc997ed0SQu Wenruo 	/*
3456fc997ed0SQu Wenruo 	 * Use breadth first search to iterate all related edges.
3457fc997ed0SQu Wenruo 	 *
3458fc997ed0SQu Wenruo 	 * The starting points are all the edges of this node
3459fc997ed0SQu Wenruo 	 */
3460fc997ed0SQu Wenruo 	list_for_each_entry(edge, &start->upper, list[LOWER])
3461fc997ed0SQu Wenruo 		list_add_tail(&edge->list[UPPER], &pending_edge);
3462fc997ed0SQu Wenruo 
3463fc997ed0SQu Wenruo 	while (!list_empty(&pending_edge)) {
3464fc997ed0SQu Wenruo 		struct btrfs_backref_node *upper;
3465fc997ed0SQu Wenruo 		struct btrfs_backref_node *lower;
3466fc997ed0SQu Wenruo 
3467fc997ed0SQu Wenruo 		edge = list_first_entry(&pending_edge,
3468fc997ed0SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
3469fc997ed0SQu Wenruo 		list_del_init(&edge->list[UPPER]);
3470fc997ed0SQu Wenruo 		upper = edge->node[UPPER];
3471fc997ed0SQu Wenruo 		lower = edge->node[LOWER];
3472fc997ed0SQu Wenruo 
3473fc997ed0SQu Wenruo 		/* Parent is detached, no need to keep any edges */
3474fc997ed0SQu Wenruo 		if (upper->detached) {
3475fc997ed0SQu Wenruo 			list_del(&edge->list[LOWER]);
3476fc997ed0SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
3477fc997ed0SQu Wenruo 
3478fc997ed0SQu Wenruo 			/* Lower node is orphan, queue for cleanup */
3479fc997ed0SQu Wenruo 			if (list_empty(&lower->upper))
3480fc997ed0SQu Wenruo 				list_add(&lower->list, useless_node);
3481fc997ed0SQu Wenruo 			continue;
3482fc997ed0SQu Wenruo 		}
3483fc997ed0SQu Wenruo 
3484fc997ed0SQu Wenruo 		/*
3485fc997ed0SQu Wenruo 		 * All new nodes added in current build_backref_tree() haven't
3486fc997ed0SQu Wenruo 		 * been linked to the cache rb tree.
3487fc997ed0SQu Wenruo 		 * So if we have upper->rb_node populated, this means a cache
3488fc997ed0SQu Wenruo 		 * hit. We only need to link the edge, as @upper and all its
3489fc997ed0SQu Wenruo 		 * parents have already been linked.
3490fc997ed0SQu Wenruo 		 */
3491fc997ed0SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node)) {
3492fc997ed0SQu Wenruo 			if (upper->lowest) {
3493fc997ed0SQu Wenruo 				list_del_init(&upper->lower);
3494fc997ed0SQu Wenruo 				upper->lowest = 0;
3495fc997ed0SQu Wenruo 			}
3496fc997ed0SQu Wenruo 
3497fc997ed0SQu Wenruo 			list_add_tail(&edge->list[UPPER], &upper->lower);
3498fc997ed0SQu Wenruo 			continue;
3499fc997ed0SQu Wenruo 		}
3500fc997ed0SQu Wenruo 
3501fc997ed0SQu Wenruo 		/* Sanity check, we shouldn't have any unchecked nodes */
3502fc997ed0SQu Wenruo 		if (!upper->checked) {
3503fc997ed0SQu Wenruo 			ASSERT(0);
3504fc997ed0SQu Wenruo 			return -EUCLEAN;
3505fc997ed0SQu Wenruo 		}
3506fc997ed0SQu Wenruo 
3507fc997ed0SQu Wenruo 		/* Sanity check, COW-only node has non-COW-only parent */
3508fc997ed0SQu Wenruo 		if (start->cowonly != upper->cowonly) {
3509fc997ed0SQu Wenruo 			ASSERT(0);
3510fc997ed0SQu Wenruo 			return -EUCLEAN;
3511fc997ed0SQu Wenruo 		}
3512fc997ed0SQu Wenruo 
3513fc997ed0SQu Wenruo 		/* Only cache non-COW-only (subvolume trees) tree blocks */
3514fc997ed0SQu Wenruo 		if (!upper->cowonly) {
3515fc997ed0SQu Wenruo 			rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
3516fc997ed0SQu Wenruo 						   &upper->rb_node);
3517fc997ed0SQu Wenruo 			if (rb_node) {
3518fc997ed0SQu Wenruo 				btrfs_backref_panic(cache->fs_info,
3519fc997ed0SQu Wenruo 						upper->bytenr, -EEXIST);
3520fc997ed0SQu Wenruo 				return -EUCLEAN;
3521fc997ed0SQu Wenruo 			}
3522fc997ed0SQu Wenruo 		}
3523fc997ed0SQu Wenruo 
3524fc997ed0SQu Wenruo 		list_add_tail(&edge->list[UPPER], &upper->lower);
3525fc997ed0SQu Wenruo 
3526fc997ed0SQu Wenruo 		/*
3527fc997ed0SQu Wenruo 		 * Also queue all the parent edges of this uncached node
3528fc997ed0SQu Wenruo 		 * to finish the upper linkage
3529fc997ed0SQu Wenruo 		 */
3530fc997ed0SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
3531fc997ed0SQu Wenruo 			list_add_tail(&edge->list[UPPER], &pending_edge);
3532fc997ed0SQu Wenruo 	}
3533fc997ed0SQu Wenruo 	return 0;
3534fc997ed0SQu Wenruo }
35351b23ea18SQu Wenruo 
35361b23ea18SQu Wenruo void btrfs_backref_error_cleanup(struct btrfs_backref_cache *cache,
35371b23ea18SQu Wenruo 				 struct btrfs_backref_node *node)
35381b23ea18SQu Wenruo {
35391b23ea18SQu Wenruo 	struct btrfs_backref_node *lower;
35401b23ea18SQu Wenruo 	struct btrfs_backref_node *upper;
35411b23ea18SQu Wenruo 	struct btrfs_backref_edge *edge;
35421b23ea18SQu Wenruo 
35431b23ea18SQu Wenruo 	while (!list_empty(&cache->useless_node)) {
35441b23ea18SQu Wenruo 		lower = list_first_entry(&cache->useless_node,
35451b23ea18SQu Wenruo 				   struct btrfs_backref_node, list);
35461b23ea18SQu Wenruo 		list_del_init(&lower->list);
35471b23ea18SQu Wenruo 	}
35481b23ea18SQu Wenruo 	while (!list_empty(&cache->pending_edge)) {
35491b23ea18SQu Wenruo 		edge = list_first_entry(&cache->pending_edge,
35501b23ea18SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
35511b23ea18SQu Wenruo 		list_del(&edge->list[UPPER]);
35521b23ea18SQu Wenruo 		list_del(&edge->list[LOWER]);
35531b23ea18SQu Wenruo 		lower = edge->node[LOWER];
35541b23ea18SQu Wenruo 		upper = edge->node[UPPER];
35551b23ea18SQu Wenruo 		btrfs_backref_free_edge(cache, edge);
35561b23ea18SQu Wenruo 
35571b23ea18SQu Wenruo 		/*
35581b23ea18SQu Wenruo 		 * Lower is no longer linked to any upper backref nodes and
35591b23ea18SQu Wenruo 		 * isn't in the cache, we can free it ourselves.
35601b23ea18SQu Wenruo 		 */
35611b23ea18SQu Wenruo 		if (list_empty(&lower->upper) &&
35621b23ea18SQu Wenruo 		    RB_EMPTY_NODE(&lower->rb_node))
35631b23ea18SQu Wenruo 			list_add(&lower->list, &cache->useless_node);
35641b23ea18SQu Wenruo 
35651b23ea18SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node))
35661b23ea18SQu Wenruo 			continue;
35671b23ea18SQu Wenruo 
35681b23ea18SQu Wenruo 		/* Add this guy's upper edges to the list to process */
35691b23ea18SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
35701b23ea18SQu Wenruo 			list_add_tail(&edge->list[UPPER],
35711b23ea18SQu Wenruo 				      &cache->pending_edge);
35721b23ea18SQu Wenruo 		if (list_empty(&upper->upper))
35731b23ea18SQu Wenruo 			list_add(&upper->list, &cache->useless_node);
35741b23ea18SQu Wenruo 	}
35751b23ea18SQu Wenruo 
35761b23ea18SQu Wenruo 	while (!list_empty(&cache->useless_node)) {
35771b23ea18SQu Wenruo 		lower = list_first_entry(&cache->useless_node,
35781b23ea18SQu Wenruo 				   struct btrfs_backref_node, list);
35791b23ea18SQu Wenruo 		list_del_init(&lower->list);
35801b23ea18SQu Wenruo 		if (lower == node)
35811b23ea18SQu Wenruo 			node = NULL;
358249ecc679SJosef Bacik 		btrfs_backref_drop_node(cache, lower);
35831b23ea18SQu Wenruo 	}
35841b23ea18SQu Wenruo 
35851b23ea18SQu Wenruo 	btrfs_backref_cleanup_node(cache, node);
35861b23ea18SQu Wenruo 	ASSERT(list_empty(&cache->useless_node) &&
35871b23ea18SQu Wenruo 	       list_empty(&cache->pending_edge));
35881b23ea18SQu Wenruo }
3589