xref: /openbmc/linux/fs/btrfs/relocation.c (revision 023acb07)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
25d4f98a2SYan Zheng /*
35d4f98a2SYan Zheng  * Copyright (C) 2009 Oracle.  All rights reserved.
45d4f98a2SYan Zheng  */
55d4f98a2SYan Zheng 
65d4f98a2SYan Zheng #include <linux/sched.h>
75d4f98a2SYan Zheng #include <linux/pagemap.h>
85d4f98a2SYan Zheng #include <linux/writeback.h>
95d4f98a2SYan Zheng #include <linux/blkdev.h>
105d4f98a2SYan Zheng #include <linux/rbtree.h>
115a0e3ad6STejun Heo #include <linux/slab.h>
12726a3421SQu Wenruo #include <linux/error-injection.h>
135d4f98a2SYan Zheng #include "ctree.h"
145d4f98a2SYan Zheng #include "disk-io.h"
155d4f98a2SYan Zheng #include "transaction.h"
165d4f98a2SYan Zheng #include "volumes.h"
175d4f98a2SYan Zheng #include "locking.h"
185d4f98a2SYan Zheng #include "btrfs_inode.h"
195d4f98a2SYan Zheng #include "async-thread.h"
200af3d00bSJosef Bacik #include "free-space-cache.h"
21581bb050SLi Zefan #include "inode-map.h"
2262b99540SQu Wenruo #include "qgroup.h"
23cdccee99SLiu Bo #include "print-tree.h"
2486736342SJosef Bacik #include "delalloc-space.h"
25aac0023cSJosef Bacik #include "block-group.h"
2619b546d7SQu Wenruo #include "backref.h"
27e9a28dc5SQu Wenruo #include "misc.h"
285d4f98a2SYan Zheng 
295d4f98a2SYan Zheng /*
300c891389SQu Wenruo  * Relocation overview
310c891389SQu Wenruo  *
320c891389SQu Wenruo  * [What does relocation do]
330c891389SQu Wenruo  *
340c891389SQu Wenruo  * The objective of relocation is to relocate all extents of the target block
350c891389SQu Wenruo  * group to other block groups.
360c891389SQu Wenruo  * This is utilized by resize (shrink only), profile converting, compacting
370c891389SQu Wenruo  * space, or balance routine to spread chunks over devices.
380c891389SQu Wenruo  *
390c891389SQu Wenruo  * 		Before		|		After
400c891389SQu Wenruo  * ------------------------------------------------------------------
410c891389SQu Wenruo  *  BG A: 10 data extents	| BG A: deleted
420c891389SQu Wenruo  *  BG B:  2 data extents	| BG B: 10 data extents (2 old + 8 relocated)
430c891389SQu Wenruo  *  BG C:  1 extents		| BG C:  3 data extents (1 old + 2 relocated)
440c891389SQu Wenruo  *
450c891389SQu Wenruo  * [How does relocation work]
460c891389SQu Wenruo  *
470c891389SQu Wenruo  * 1.   Mark the target block group read-only
480c891389SQu Wenruo  *      New extents won't be allocated from the target block group.
490c891389SQu Wenruo  *
500c891389SQu Wenruo  * 2.1  Record each extent in the target block group
510c891389SQu Wenruo  *      To build a proper map of extents to be relocated.
520c891389SQu Wenruo  *
530c891389SQu Wenruo  * 2.2  Build data reloc tree and reloc trees
540c891389SQu Wenruo  *      Data reloc tree will contain an inode, recording all newly relocated
550c891389SQu Wenruo  *      data extents.
560c891389SQu Wenruo  *      There will be only one data reloc tree for one data block group.
570c891389SQu Wenruo  *
580c891389SQu Wenruo  *      Reloc tree will be a special snapshot of its source tree, containing
590c891389SQu Wenruo  *      relocated tree blocks.
600c891389SQu Wenruo  *      Each tree referring to a tree block in target block group will get its
610c891389SQu Wenruo  *      reloc tree built.
620c891389SQu Wenruo  *
630c891389SQu Wenruo  * 2.3  Swap source tree with its corresponding reloc tree
640c891389SQu Wenruo  *      Each involved tree only refers to new extents after swap.
650c891389SQu Wenruo  *
660c891389SQu Wenruo  * 3.   Cleanup reloc trees and data reloc tree.
670c891389SQu Wenruo  *      As old extents in the target block group are still referenced by reloc
680c891389SQu Wenruo  *      trees, we need to clean them up before really freeing the target block
690c891389SQu Wenruo  *      group.
700c891389SQu Wenruo  *
710c891389SQu Wenruo  * The main complexity is in steps 2.2 and 2.3.
720c891389SQu Wenruo  *
730c891389SQu Wenruo  * The entry point of relocation is relocate_block_group() function.
740c891389SQu Wenruo  */
750c891389SQu Wenruo 
760647bf56SWang Shilong #define RELOCATION_RESERVED_NODES	256
772a979612SQu Wenruo /*
785d4f98a2SYan Zheng  * map address of tree root to tree
795d4f98a2SYan Zheng  */
805d4f98a2SYan Zheng struct mapping_node {
81e9a28dc5SQu Wenruo 	struct {
825d4f98a2SYan Zheng 		struct rb_node rb_node;
835d4f98a2SYan Zheng 		u64 bytenr;
84e9a28dc5SQu Wenruo 	}; /* Use rb_simle_node for search/insert */
855d4f98a2SYan Zheng 	void *data;
865d4f98a2SYan Zheng };
875d4f98a2SYan Zheng 
885d4f98a2SYan Zheng struct mapping_tree {
895d4f98a2SYan Zheng 	struct rb_root rb_root;
905d4f98a2SYan Zheng 	spinlock_t lock;
915d4f98a2SYan Zheng };
925d4f98a2SYan Zheng 
935d4f98a2SYan Zheng /*
945d4f98a2SYan Zheng  * present a tree block to process
955d4f98a2SYan Zheng  */
965d4f98a2SYan Zheng struct tree_block {
97e9a28dc5SQu Wenruo 	struct {
985d4f98a2SYan Zheng 		struct rb_node rb_node;
995d4f98a2SYan Zheng 		u64 bytenr;
100e9a28dc5SQu Wenruo 	}; /* Use rb_simple_node for search/insert */
1015d4f98a2SYan Zheng 	struct btrfs_key key;
1025d4f98a2SYan Zheng 	unsigned int level:8;
1035d4f98a2SYan Zheng 	unsigned int key_ready:1;
1045d4f98a2SYan Zheng };
1055d4f98a2SYan Zheng 
1060257bb82SYan, Zheng #define MAX_EXTENTS 128
1070257bb82SYan, Zheng 
1080257bb82SYan, Zheng struct file_extent_cluster {
1090257bb82SYan, Zheng 	u64 start;
1100257bb82SYan, Zheng 	u64 end;
1110257bb82SYan, Zheng 	u64 boundary[MAX_EXTENTS];
1120257bb82SYan, Zheng 	unsigned int nr;
1130257bb82SYan, Zheng };
1140257bb82SYan, Zheng 
1155d4f98a2SYan Zheng struct reloc_control {
1165d4f98a2SYan Zheng 	/* block group to relocate */
11732da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1185d4f98a2SYan Zheng 	/* extent tree */
1195d4f98a2SYan Zheng 	struct btrfs_root *extent_root;
1205d4f98a2SYan Zheng 	/* inode for moving data */
1215d4f98a2SYan Zheng 	struct inode *data_inode;
1223fd0a558SYan, Zheng 
1233fd0a558SYan, Zheng 	struct btrfs_block_rsv *block_rsv;
1243fd0a558SYan, Zheng 
125a26195a5SQu Wenruo 	struct btrfs_backref_cache backref_cache;
1263fd0a558SYan, Zheng 
1273fd0a558SYan, Zheng 	struct file_extent_cluster cluster;
1285d4f98a2SYan Zheng 	/* tree blocks have been processed */
1295d4f98a2SYan Zheng 	struct extent_io_tree processed_blocks;
1305d4f98a2SYan Zheng 	/* map start of tree root to corresponding reloc tree */
1315d4f98a2SYan Zheng 	struct mapping_tree reloc_root_tree;
1325d4f98a2SYan Zheng 	/* list of reloc trees */
1335d4f98a2SYan Zheng 	struct list_head reloc_roots;
134d2311e69SQu Wenruo 	/* list of subvolume trees that get relocated */
135d2311e69SQu Wenruo 	struct list_head dirty_subvol_roots;
1363fd0a558SYan, Zheng 	/* size of metadata reservation for merging reloc trees */
1373fd0a558SYan, Zheng 	u64 merging_rsv_size;
1383fd0a558SYan, Zheng 	/* size of relocated tree nodes */
1393fd0a558SYan, Zheng 	u64 nodes_relocated;
1400647bf56SWang Shilong 	/* reserved size for block group relocation*/
1410647bf56SWang Shilong 	u64 reserved_bytes;
1423fd0a558SYan, Zheng 
1435d4f98a2SYan Zheng 	u64 search_start;
1445d4f98a2SYan Zheng 	u64 extents_found;
1453fd0a558SYan, Zheng 
1463fd0a558SYan, Zheng 	unsigned int stage:8;
1473fd0a558SYan, Zheng 	unsigned int create_reloc_tree:1;
1483fd0a558SYan, Zheng 	unsigned int merge_reloc_tree:1;
1495d4f98a2SYan Zheng 	unsigned int found_file_extent:1;
1505d4f98a2SYan Zheng };
1515d4f98a2SYan Zheng 
1525d4f98a2SYan Zheng /* stages of data relocation */
1535d4f98a2SYan Zheng #define MOVE_DATA_EXTENTS	0
1545d4f98a2SYan Zheng #define UPDATE_DATA_PTRS	1
1555d4f98a2SYan Zheng 
1569569cc20SQu Wenruo static void mark_block_processed(struct reloc_control *rc,
157a26195a5SQu Wenruo 				 struct btrfs_backref_node *node)
1589569cc20SQu Wenruo {
1599569cc20SQu Wenruo 	u32 blocksize;
1609569cc20SQu Wenruo 
1619569cc20SQu Wenruo 	if (node->level == 0 ||
1629569cc20SQu Wenruo 	    in_range(node->bytenr, rc->block_group->start,
1639569cc20SQu Wenruo 		     rc->block_group->length)) {
1649569cc20SQu Wenruo 		blocksize = rc->extent_root->fs_info->nodesize;
1659569cc20SQu Wenruo 		set_extent_bits(&rc->processed_blocks, node->bytenr,
1669569cc20SQu Wenruo 				node->bytenr + blocksize - 1, EXTENT_DIRTY);
1679569cc20SQu Wenruo 	}
1689569cc20SQu Wenruo 	node->processed = 1;
1699569cc20SQu Wenruo }
1709569cc20SQu Wenruo 
1715d4f98a2SYan Zheng 
1725d4f98a2SYan Zheng static void mapping_tree_init(struct mapping_tree *tree)
1735d4f98a2SYan Zheng {
1746bef4d31SEric Paris 	tree->rb_root = RB_ROOT;
1755d4f98a2SYan Zheng 	spin_lock_init(&tree->lock);
1765d4f98a2SYan Zheng }
1775d4f98a2SYan Zheng 
178a26195a5SQu Wenruo static void backref_cache_cleanup(struct btrfs_backref_cache *cache)
1795d4f98a2SYan Zheng {
180a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
1813fd0a558SYan, Zheng 	int i;
1823fd0a558SYan, Zheng 
1833fd0a558SYan, Zheng 	while (!list_empty(&cache->detached)) {
1843fd0a558SYan, Zheng 		node = list_entry(cache->detached.next,
185a26195a5SQu Wenruo 				  struct btrfs_backref_node, list);
186023acb07SQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
1873fd0a558SYan, Zheng 	}
1883fd0a558SYan, Zheng 
1893fd0a558SYan, Zheng 	while (!list_empty(&cache->leaves)) {
1903fd0a558SYan, Zheng 		node = list_entry(cache->leaves.next,
191a26195a5SQu Wenruo 				  struct btrfs_backref_node, lower);
192023acb07SQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
1933fd0a558SYan, Zheng 	}
1943fd0a558SYan, Zheng 
1953fd0a558SYan, Zheng 	cache->last_trans = 0;
1963fd0a558SYan, Zheng 
1973fd0a558SYan, Zheng 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
198f4907095SLiu Bo 		ASSERT(list_empty(&cache->pending[i]));
19984780289SQu Wenruo 	ASSERT(list_empty(&cache->pending_edge));
20084780289SQu Wenruo 	ASSERT(list_empty(&cache->useless_node));
201f4907095SLiu Bo 	ASSERT(list_empty(&cache->changed));
202f4907095SLiu Bo 	ASSERT(list_empty(&cache->detached));
203f4907095SLiu Bo 	ASSERT(RB_EMPTY_ROOT(&cache->rb_root));
204f4907095SLiu Bo 	ASSERT(!cache->nr_nodes);
205f4907095SLiu Bo 	ASSERT(!cache->nr_edges);
2063fd0a558SYan, Zheng }
2073fd0a558SYan, Zheng 
20848a3b636SEric Sandeen static void backref_tree_panic(struct rb_node *rb_node, int errno, u64 bytenr)
20943c04fb1SJeff Mahoney {
21043c04fb1SJeff Mahoney 
21143c04fb1SJeff Mahoney 	struct btrfs_fs_info *fs_info = NULL;
212a26195a5SQu Wenruo 	struct btrfs_backref_node *bnode = rb_entry(rb_node,
213a26195a5SQu Wenruo 			struct btrfs_backref_node, rb_node);
21443c04fb1SJeff Mahoney 	if (bnode->root)
21543c04fb1SJeff Mahoney 		fs_info = bnode->root->fs_info;
2165d163e0eSJeff Mahoney 	btrfs_panic(fs_info, errno,
2175d163e0eSJeff Mahoney 		    "Inconsistency in backref cache found at offset %llu",
2185d163e0eSJeff Mahoney 		    bytenr);
21943c04fb1SJeff Mahoney }
22043c04fb1SJeff Mahoney 
2215d4f98a2SYan Zheng /*
2225d4f98a2SYan Zheng  * walk up backref nodes until reach node presents tree root
2235d4f98a2SYan Zheng  */
224a26195a5SQu Wenruo static struct btrfs_backref_node *walk_up_backref(
225a26195a5SQu Wenruo 		struct btrfs_backref_node *node,
226a26195a5SQu Wenruo 		struct btrfs_backref_edge *edges[], int *index)
2275d4f98a2SYan Zheng {
228a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2295d4f98a2SYan Zheng 	int idx = *index;
2305d4f98a2SYan Zheng 
2315d4f98a2SYan Zheng 	while (!list_empty(&node->upper)) {
2325d4f98a2SYan Zheng 		edge = list_entry(node->upper.next,
233a26195a5SQu Wenruo 				  struct btrfs_backref_edge, list[LOWER]);
2345d4f98a2SYan Zheng 		edges[idx++] = edge;
2355d4f98a2SYan Zheng 		node = edge->node[UPPER];
2365d4f98a2SYan Zheng 	}
2373fd0a558SYan, Zheng 	BUG_ON(node->detached);
2385d4f98a2SYan Zheng 	*index = idx;
2395d4f98a2SYan Zheng 	return node;
2405d4f98a2SYan Zheng }
2415d4f98a2SYan Zheng 
2425d4f98a2SYan Zheng /*
2435d4f98a2SYan Zheng  * walk down backref nodes to find start of next reference path
2445d4f98a2SYan Zheng  */
245a26195a5SQu Wenruo static struct btrfs_backref_node *walk_down_backref(
246a26195a5SQu Wenruo 		struct btrfs_backref_edge *edges[], int *index)
2475d4f98a2SYan Zheng {
248a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
249a26195a5SQu Wenruo 	struct btrfs_backref_node *lower;
2505d4f98a2SYan Zheng 	int idx = *index;
2515d4f98a2SYan Zheng 
2525d4f98a2SYan Zheng 	while (idx > 0) {
2535d4f98a2SYan Zheng 		edge = edges[idx - 1];
2545d4f98a2SYan Zheng 		lower = edge->node[LOWER];
2555d4f98a2SYan Zheng 		if (list_is_last(&edge->list[LOWER], &lower->upper)) {
2565d4f98a2SYan Zheng 			idx--;
2575d4f98a2SYan Zheng 			continue;
2585d4f98a2SYan Zheng 		}
2595d4f98a2SYan Zheng 		edge = list_entry(edge->list[LOWER].next,
260a26195a5SQu Wenruo 				  struct btrfs_backref_edge, list[LOWER]);
2615d4f98a2SYan Zheng 		edges[idx - 1] = edge;
2625d4f98a2SYan Zheng 		*index = idx;
2635d4f98a2SYan Zheng 		return edge->node[UPPER];
2645d4f98a2SYan Zheng 	}
2655d4f98a2SYan Zheng 	*index = 0;
2665d4f98a2SYan Zheng 	return NULL;
2675d4f98a2SYan Zheng }
2685d4f98a2SYan Zheng 
269a26195a5SQu Wenruo static void update_backref_node(struct btrfs_backref_cache *cache,
270a26195a5SQu Wenruo 				struct btrfs_backref_node *node, u64 bytenr)
2713fd0a558SYan, Zheng {
2723fd0a558SYan, Zheng 	struct rb_node *rb_node;
2733fd0a558SYan, Zheng 	rb_erase(&node->rb_node, &cache->rb_root);
2743fd0a558SYan, Zheng 	node->bytenr = bytenr;
275e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&cache->rb_root, node->bytenr, &node->rb_node);
27643c04fb1SJeff Mahoney 	if (rb_node)
27743c04fb1SJeff Mahoney 		backref_tree_panic(rb_node, -EEXIST, bytenr);
2783fd0a558SYan, Zheng }
2793fd0a558SYan, Zheng 
2803fd0a558SYan, Zheng /*
2813fd0a558SYan, Zheng  * update backref cache after a transaction commit
2823fd0a558SYan, Zheng  */
2833fd0a558SYan, Zheng static int update_backref_cache(struct btrfs_trans_handle *trans,
284a26195a5SQu Wenruo 				struct btrfs_backref_cache *cache)
2853fd0a558SYan, Zheng {
286a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
2873fd0a558SYan, Zheng 	int level = 0;
2883fd0a558SYan, Zheng 
2893fd0a558SYan, Zheng 	if (cache->last_trans == 0) {
2903fd0a558SYan, Zheng 		cache->last_trans = trans->transid;
2913fd0a558SYan, Zheng 		return 0;
2923fd0a558SYan, Zheng 	}
2933fd0a558SYan, Zheng 
2943fd0a558SYan, Zheng 	if (cache->last_trans == trans->transid)
2953fd0a558SYan, Zheng 		return 0;
2963fd0a558SYan, Zheng 
2973fd0a558SYan, Zheng 	/*
2983fd0a558SYan, Zheng 	 * detached nodes are used to avoid unnecessary backref
2993fd0a558SYan, Zheng 	 * lookup. transaction commit changes the extent tree.
3003fd0a558SYan, Zheng 	 * so the detached nodes are no longer useful.
3013fd0a558SYan, Zheng 	 */
3023fd0a558SYan, Zheng 	while (!list_empty(&cache->detached)) {
3033fd0a558SYan, Zheng 		node = list_entry(cache->detached.next,
304a26195a5SQu Wenruo 				  struct btrfs_backref_node, list);
305023acb07SQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
3063fd0a558SYan, Zheng 	}
3073fd0a558SYan, Zheng 
3083fd0a558SYan, Zheng 	while (!list_empty(&cache->changed)) {
3093fd0a558SYan, Zheng 		node = list_entry(cache->changed.next,
310a26195a5SQu Wenruo 				  struct btrfs_backref_node, list);
3113fd0a558SYan, Zheng 		list_del_init(&node->list);
3123fd0a558SYan, Zheng 		BUG_ON(node->pending);
3133fd0a558SYan, Zheng 		update_backref_node(cache, node, node->new_bytenr);
3143fd0a558SYan, Zheng 	}
3153fd0a558SYan, Zheng 
3163fd0a558SYan, Zheng 	/*
3173fd0a558SYan, Zheng 	 * some nodes can be left in the pending list if there were
3183fd0a558SYan, Zheng 	 * errors during processing the pending nodes.
3193fd0a558SYan, Zheng 	 */
3203fd0a558SYan, Zheng 	for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
3213fd0a558SYan, Zheng 		list_for_each_entry(node, &cache->pending[level], list) {
3223fd0a558SYan, Zheng 			BUG_ON(!node->pending);
3233fd0a558SYan, Zheng 			if (node->bytenr == node->new_bytenr)
3243fd0a558SYan, Zheng 				continue;
3253fd0a558SYan, Zheng 			update_backref_node(cache, node, node->new_bytenr);
3263fd0a558SYan, Zheng 		}
3273fd0a558SYan, Zheng 	}
3283fd0a558SYan, Zheng 
3293fd0a558SYan, Zheng 	cache->last_trans = 0;
3303fd0a558SYan, Zheng 	return 1;
3313fd0a558SYan, Zheng }
3323fd0a558SYan, Zheng 
3336282675eSQu Wenruo static bool reloc_root_is_dead(struct btrfs_root *root)
3346282675eSQu Wenruo {
3356282675eSQu Wenruo 	/*
3366282675eSQu Wenruo 	 * Pair with set_bit/clear_bit in clean_dirty_subvols and
3376282675eSQu Wenruo 	 * btrfs_update_reloc_root. We need to see the updated bit before
3386282675eSQu Wenruo 	 * trying to access reloc_root
3396282675eSQu Wenruo 	 */
3406282675eSQu Wenruo 	smp_rmb();
3416282675eSQu Wenruo 	if (test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state))
3426282675eSQu Wenruo 		return true;
3436282675eSQu Wenruo 	return false;
3446282675eSQu Wenruo }
3456282675eSQu Wenruo 
3466282675eSQu Wenruo /*
3476282675eSQu Wenruo  * Check if this subvolume tree has valid reloc tree.
3486282675eSQu Wenruo  *
3496282675eSQu Wenruo  * Reloc tree after swap is considered dead, thus not considered as valid.
3506282675eSQu Wenruo  * This is enough for most callers, as they don't distinguish dead reloc root
3516282675eSQu Wenruo  * from no reloc root.  But should_ignore_root() below is a special case.
3526282675eSQu Wenruo  */
3536282675eSQu Wenruo static bool have_reloc_root(struct btrfs_root *root)
3546282675eSQu Wenruo {
3556282675eSQu Wenruo 	if (reloc_root_is_dead(root))
3566282675eSQu Wenruo 		return false;
3576282675eSQu Wenruo 	if (!root->reloc_root)
3586282675eSQu Wenruo 		return false;
3596282675eSQu Wenruo 	return true;
3606282675eSQu Wenruo }
361f2a97a9dSDavid Sterba 
3623fd0a558SYan, Zheng static int should_ignore_root(struct btrfs_root *root)
3633fd0a558SYan, Zheng {
3643fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
3653fd0a558SYan, Zheng 
36627cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
3673fd0a558SYan, Zheng 		return 0;
3683fd0a558SYan, Zheng 
3696282675eSQu Wenruo 	/* This root has been merged with its reloc tree, we can ignore it */
3706282675eSQu Wenruo 	if (reloc_root_is_dead(root))
3716282675eSQu Wenruo 		return 1;
3726282675eSQu Wenruo 
3733fd0a558SYan, Zheng 	reloc_root = root->reloc_root;
3743fd0a558SYan, Zheng 	if (!reloc_root)
3753fd0a558SYan, Zheng 		return 0;
3763fd0a558SYan, Zheng 
3774d4225fcSJosef Bacik 	if (btrfs_header_generation(reloc_root->commit_root) ==
3784d4225fcSJosef Bacik 	    root->fs_info->running_transaction->transid)
3793fd0a558SYan, Zheng 		return 0;
3803fd0a558SYan, Zheng 	/*
3813fd0a558SYan, Zheng 	 * if there is reloc tree and it was created in previous
3823fd0a558SYan, Zheng 	 * transaction backref lookup can find the reloc tree,
3833fd0a558SYan, Zheng 	 * so backref node for the fs tree root is useless for
3843fd0a558SYan, Zheng 	 * relocation.
3853fd0a558SYan, Zheng 	 */
3863fd0a558SYan, Zheng 	return 1;
3873fd0a558SYan, Zheng }
3885d4f98a2SYan Zheng /*
3895d4f98a2SYan Zheng  * find reloc tree by address of tree root
3905d4f98a2SYan Zheng  */
3912433bea5SQu Wenruo struct btrfs_root *find_reloc_root(struct btrfs_fs_info *fs_info, u64 bytenr)
3925d4f98a2SYan Zheng {
3932433bea5SQu Wenruo 	struct reloc_control *rc = fs_info->reloc_ctl;
3945d4f98a2SYan Zheng 	struct rb_node *rb_node;
3955d4f98a2SYan Zheng 	struct mapping_node *node;
3965d4f98a2SYan Zheng 	struct btrfs_root *root = NULL;
3975d4f98a2SYan Zheng 
3982433bea5SQu Wenruo 	ASSERT(rc);
3995d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
400e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root, bytenr);
4015d4f98a2SYan Zheng 	if (rb_node) {
4025d4f98a2SYan Zheng 		node = rb_entry(rb_node, struct mapping_node, rb_node);
4035d4f98a2SYan Zheng 		root = (struct btrfs_root *)node->data;
4045d4f98a2SYan Zheng 	}
4055d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
40600246528SJosef Bacik 	return btrfs_grab_root(root);
4075d4f98a2SYan Zheng }
4085d4f98a2SYan Zheng 
4095d4f98a2SYan Zheng static struct btrfs_root *read_fs_root(struct btrfs_fs_info *fs_info,
4105d4f98a2SYan Zheng 					u64 root_objectid)
4115d4f98a2SYan Zheng {
4125d4f98a2SYan Zheng 	struct btrfs_key key;
4135d4f98a2SYan Zheng 
4145d4f98a2SYan Zheng 	key.objectid = root_objectid;
4155d4f98a2SYan Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
4165d4f98a2SYan Zheng 	key.offset = (u64)-1;
4175d4f98a2SYan Zheng 
418bc44d7c4SJosef Bacik 	return btrfs_get_fs_root(fs_info, &key, false);
4195d4f98a2SYan Zheng }
4205d4f98a2SYan Zheng 
4215d4f98a2SYan Zheng /*
4224007ea87SQu Wenruo  * Handle direct tree backref
4234007ea87SQu Wenruo  *
4244007ea87SQu Wenruo  * Direct tree backref means, the backref item shows its parent bytenr
4254007ea87SQu Wenruo  * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
4264007ea87SQu Wenruo  *
4274007ea87SQu Wenruo  * @ref_key:	The converted backref key.
4284007ea87SQu Wenruo  *		For keyed backref, it's the item key.
4294007ea87SQu Wenruo  *		For inlined backref, objectid is the bytenr,
4304007ea87SQu Wenruo  *		type is btrfs_inline_ref_type, offset is
4314007ea87SQu Wenruo  *		btrfs_inline_ref_offset.
4324007ea87SQu Wenruo  */
433a26195a5SQu Wenruo static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
4344007ea87SQu Wenruo 				      struct btrfs_key *ref_key,
435a26195a5SQu Wenruo 				      struct btrfs_backref_node *cur)
4364007ea87SQu Wenruo {
437a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
438a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
4394007ea87SQu Wenruo 	struct rb_node *rb_node;
4404007ea87SQu Wenruo 
4414007ea87SQu Wenruo 	ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
4424007ea87SQu Wenruo 
4434007ea87SQu Wenruo 	/* Only reloc root uses backref pointing to itself */
4444007ea87SQu Wenruo 	if (ref_key->objectid == ref_key->offset) {
4454007ea87SQu Wenruo 		struct btrfs_root *root;
4464007ea87SQu Wenruo 
4474007ea87SQu Wenruo 		cur->is_reloc_root = 1;
4484007ea87SQu Wenruo 		/* Only reloc backref cache cares about a specific root */
4494007ea87SQu Wenruo 		if (cache->is_reloc) {
4504007ea87SQu Wenruo 			root = find_reloc_root(cache->fs_info, cur->bytenr);
4514007ea87SQu Wenruo 			if (WARN_ON(!root))
4524007ea87SQu Wenruo 				return -ENOENT;
4534007ea87SQu Wenruo 			cur->root = root;
4544007ea87SQu Wenruo 		} else {
4554007ea87SQu Wenruo 			/*
4564007ea87SQu Wenruo 			 * For generic purpose backref cache, reloc root node
4574007ea87SQu Wenruo 			 * is useless.
4584007ea87SQu Wenruo 			 */
4594007ea87SQu Wenruo 			list_add(&cur->list, &cache->useless_node);
4604007ea87SQu Wenruo 		}
4614007ea87SQu Wenruo 		return 0;
4624007ea87SQu Wenruo 	}
4634007ea87SQu Wenruo 
46447254d07SQu Wenruo 	edge = btrfs_backref_alloc_edge(cache);
4654007ea87SQu Wenruo 	if (!edge)
4664007ea87SQu Wenruo 		return -ENOMEM;
4674007ea87SQu Wenruo 
468e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
4694007ea87SQu Wenruo 	if (!rb_node) {
4704007ea87SQu Wenruo 		/* Parent node not yet cached */
471b1818dabSQu Wenruo 		upper = btrfs_backref_alloc_node(cache, ref_key->offset,
4720304f2d8SQu Wenruo 					   cur->level + 1);
4734007ea87SQu Wenruo 		if (!upper) {
474741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
4754007ea87SQu Wenruo 			return -ENOMEM;
4764007ea87SQu Wenruo 		}
4774007ea87SQu Wenruo 
4784007ea87SQu Wenruo 		/*
4794007ea87SQu Wenruo 		 *  Backrefs for the upper level block isn't cached, add the
4804007ea87SQu Wenruo 		 *  block to pending list
4814007ea87SQu Wenruo 		 */
4824007ea87SQu Wenruo 		list_add_tail(&edge->list[UPPER], &cache->pending_edge);
4834007ea87SQu Wenruo 	} else {
4844007ea87SQu Wenruo 		/* Parent node already cached */
485a26195a5SQu Wenruo 		upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
4864007ea87SQu Wenruo 		ASSERT(upper->checked);
4874007ea87SQu Wenruo 		INIT_LIST_HEAD(&edge->list[UPPER]);
4884007ea87SQu Wenruo 	}
489f39911e5SQu Wenruo 	btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
4904007ea87SQu Wenruo 	return 0;
4914007ea87SQu Wenruo }
4924007ea87SQu Wenruo 
4934007ea87SQu Wenruo /*
4944d81ea8bSQu Wenruo  * Handle indirect tree backref
4954d81ea8bSQu Wenruo  *
4964d81ea8bSQu Wenruo  * Indirect tree backref means, we only know which tree the node belongs to.
4974d81ea8bSQu Wenruo  * We still need to do a tree search to find out the parents. This is for
4984d81ea8bSQu Wenruo  * TREE_BLOCK_REF backref (keyed or inlined).
4994d81ea8bSQu Wenruo  *
5004d81ea8bSQu Wenruo  * @ref_key:	The same as @ref_key in  handle_direct_tree_backref()
5014d81ea8bSQu Wenruo  * @tree_key:	The first key of this tree block.
5024d81ea8bSQu Wenruo  * @path:	A clean (released) path, to avoid allocating path everytime
5034d81ea8bSQu Wenruo  *		the function get called.
5044d81ea8bSQu Wenruo  */
505a26195a5SQu Wenruo static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
5064d81ea8bSQu Wenruo 					struct btrfs_path *path,
5074d81ea8bSQu Wenruo 					struct btrfs_key *ref_key,
5084d81ea8bSQu Wenruo 					struct btrfs_key *tree_key,
509a26195a5SQu Wenruo 					struct btrfs_backref_node *cur)
5104d81ea8bSQu Wenruo {
5114d81ea8bSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
512a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
513a26195a5SQu Wenruo 	struct btrfs_backref_node *lower;
514a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
5154d81ea8bSQu Wenruo 	struct extent_buffer *eb;
5164d81ea8bSQu Wenruo 	struct btrfs_root *root;
5174d81ea8bSQu Wenruo 	struct rb_node *rb_node;
5184d81ea8bSQu Wenruo 	int level;
5194d81ea8bSQu Wenruo 	bool need_check = true;
5204d81ea8bSQu Wenruo 	int ret;
5214d81ea8bSQu Wenruo 
5224d81ea8bSQu Wenruo 	root = read_fs_root(fs_info, ref_key->offset);
5234d81ea8bSQu Wenruo 	if (IS_ERR(root))
5244d81ea8bSQu Wenruo 		return PTR_ERR(root);
5254d81ea8bSQu Wenruo 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
5264d81ea8bSQu Wenruo 		cur->cowonly = 1;
5274d81ea8bSQu Wenruo 
5284d81ea8bSQu Wenruo 	if (btrfs_root_level(&root->root_item) == cur->level) {
5294d81ea8bSQu Wenruo 		/* Tree root */
5304d81ea8bSQu Wenruo 		ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
5314d81ea8bSQu Wenruo 		if (should_ignore_root(root)) {
5324d81ea8bSQu Wenruo 			btrfs_put_root(root);
5334d81ea8bSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
5344d81ea8bSQu Wenruo 		} else {
5354d81ea8bSQu Wenruo 			cur->root = root;
5364d81ea8bSQu Wenruo 		}
5374d81ea8bSQu Wenruo 		return 0;
5384d81ea8bSQu Wenruo 	}
5394d81ea8bSQu Wenruo 
5404d81ea8bSQu Wenruo 	level = cur->level + 1;
5414d81ea8bSQu Wenruo 
5424d81ea8bSQu Wenruo 	/* Search the tree to find parent blocks referring to the block */
5434d81ea8bSQu Wenruo 	path->search_commit_root = 1;
5444d81ea8bSQu Wenruo 	path->skip_locking = 1;
5454d81ea8bSQu Wenruo 	path->lowest_level = level;
5464d81ea8bSQu Wenruo 	ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
5474d81ea8bSQu Wenruo 	path->lowest_level = 0;
5484d81ea8bSQu Wenruo 	if (ret < 0) {
5494d81ea8bSQu Wenruo 		btrfs_put_root(root);
5504d81ea8bSQu Wenruo 		return ret;
5514d81ea8bSQu Wenruo 	}
5524d81ea8bSQu Wenruo 	if (ret > 0 && path->slots[level] > 0)
5534d81ea8bSQu Wenruo 		path->slots[level]--;
5544d81ea8bSQu Wenruo 
5554d81ea8bSQu Wenruo 	eb = path->nodes[level];
5564d81ea8bSQu Wenruo 	if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
5574d81ea8bSQu Wenruo 		btrfs_err(fs_info,
5584d81ea8bSQu Wenruo "couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
5594d81ea8bSQu Wenruo 			  cur->bytenr, level - 1, root->root_key.objectid,
5604d81ea8bSQu Wenruo 			  tree_key->objectid, tree_key->type, tree_key->offset);
5614d81ea8bSQu Wenruo 		btrfs_put_root(root);
5624d81ea8bSQu Wenruo 		ret = -ENOENT;
5634d81ea8bSQu Wenruo 		goto out;
5644d81ea8bSQu Wenruo 	}
5654d81ea8bSQu Wenruo 	lower = cur;
5664d81ea8bSQu Wenruo 
5674d81ea8bSQu Wenruo 	/* Add all nodes and edges in the path */
5684d81ea8bSQu Wenruo 	for (; level < BTRFS_MAX_LEVEL; level++) {
5694d81ea8bSQu Wenruo 		if (!path->nodes[level]) {
5704d81ea8bSQu Wenruo 			ASSERT(btrfs_root_bytenr(&root->root_item) ==
5714d81ea8bSQu Wenruo 			       lower->bytenr);
5724d81ea8bSQu Wenruo 			if (should_ignore_root(root)) {
5734d81ea8bSQu Wenruo 				btrfs_put_root(root);
5744d81ea8bSQu Wenruo 				list_add(&lower->list, &cache->useless_node);
5754d81ea8bSQu Wenruo 			} else {
5764d81ea8bSQu Wenruo 				lower->root = root;
5774d81ea8bSQu Wenruo 			}
5784d81ea8bSQu Wenruo 			break;
5794d81ea8bSQu Wenruo 		}
5804d81ea8bSQu Wenruo 
58147254d07SQu Wenruo 		edge = btrfs_backref_alloc_edge(cache);
5824d81ea8bSQu Wenruo 		if (!edge) {
5834d81ea8bSQu Wenruo 			btrfs_put_root(root);
5844d81ea8bSQu Wenruo 			ret = -ENOMEM;
5854d81ea8bSQu Wenruo 			goto out;
5864d81ea8bSQu Wenruo 		}
5874d81ea8bSQu Wenruo 
5884d81ea8bSQu Wenruo 		eb = path->nodes[level];
589e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root, eb->start);
5904d81ea8bSQu Wenruo 		if (!rb_node) {
591b1818dabSQu Wenruo 			upper = btrfs_backref_alloc_node(cache, eb->start,
5920304f2d8SQu Wenruo 							 lower->level + 1);
5934d81ea8bSQu Wenruo 			if (!upper) {
5944d81ea8bSQu Wenruo 				btrfs_put_root(root);
595741188d3SQu Wenruo 				btrfs_backref_free_edge(cache, edge);
5964d81ea8bSQu Wenruo 				ret = -ENOMEM;
5974d81ea8bSQu Wenruo 				goto out;
5984d81ea8bSQu Wenruo 			}
5994d81ea8bSQu Wenruo 			upper->owner = btrfs_header_owner(eb);
6004d81ea8bSQu Wenruo 			if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
6014d81ea8bSQu Wenruo 				upper->cowonly = 1;
6024d81ea8bSQu Wenruo 
6034d81ea8bSQu Wenruo 			/*
6044d81ea8bSQu Wenruo 			 * If we know the block isn't shared we can avoid
6054d81ea8bSQu Wenruo 			 * checking its backrefs.
6064d81ea8bSQu Wenruo 			 */
6074d81ea8bSQu Wenruo 			if (btrfs_block_can_be_shared(root, eb))
6084d81ea8bSQu Wenruo 				upper->checked = 0;
6094d81ea8bSQu Wenruo 			else
6104d81ea8bSQu Wenruo 				upper->checked = 1;
6114d81ea8bSQu Wenruo 
6124d81ea8bSQu Wenruo 			/*
6134d81ea8bSQu Wenruo 			 * Add the block to pending list if we need to check its
6144d81ea8bSQu Wenruo 			 * backrefs, we only do this once while walking up a
6154d81ea8bSQu Wenruo 			 * tree as we will catch anything else later on.
6164d81ea8bSQu Wenruo 			 */
6174d81ea8bSQu Wenruo 			if (!upper->checked && need_check) {
6184d81ea8bSQu Wenruo 				need_check = false;
6194d81ea8bSQu Wenruo 				list_add_tail(&edge->list[UPPER],
6204d81ea8bSQu Wenruo 					      &cache->pending_edge);
6214d81ea8bSQu Wenruo 			} else {
6224d81ea8bSQu Wenruo 				if (upper->checked)
6234d81ea8bSQu Wenruo 					need_check = true;
6244d81ea8bSQu Wenruo 				INIT_LIST_HEAD(&edge->list[UPPER]);
6254d81ea8bSQu Wenruo 			}
6264d81ea8bSQu Wenruo 		} else {
627a26195a5SQu Wenruo 			upper = rb_entry(rb_node, struct btrfs_backref_node,
628a26195a5SQu Wenruo 					 rb_node);
6294d81ea8bSQu Wenruo 			ASSERT(upper->checked);
6304d81ea8bSQu Wenruo 			INIT_LIST_HEAD(&edge->list[UPPER]);
6314d81ea8bSQu Wenruo 			if (!upper->owner)
6324d81ea8bSQu Wenruo 				upper->owner = btrfs_header_owner(eb);
6334d81ea8bSQu Wenruo 		}
634f39911e5SQu Wenruo 		btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
6354d81ea8bSQu Wenruo 
6364d81ea8bSQu Wenruo 		if (rb_node) {
6374d81ea8bSQu Wenruo 			btrfs_put_root(root);
6384d81ea8bSQu Wenruo 			break;
6394d81ea8bSQu Wenruo 		}
6404d81ea8bSQu Wenruo 		lower = upper;
6414d81ea8bSQu Wenruo 		upper = NULL;
6424d81ea8bSQu Wenruo 	}
6434d81ea8bSQu Wenruo out:
6444d81ea8bSQu Wenruo 	btrfs_release_path(path);
6454d81ea8bSQu Wenruo 	return ret;
6464d81ea8bSQu Wenruo }
6474d81ea8bSQu Wenruo 
648a26195a5SQu Wenruo static int handle_one_tree_block(struct btrfs_backref_cache *cache,
649e7d571c7SQu Wenruo 				 struct btrfs_path *path,
650e7d571c7SQu Wenruo 				 struct btrfs_backref_iter *iter,
6515d4f98a2SYan Zheng 				 struct btrfs_key *node_key,
652a26195a5SQu Wenruo 				 struct btrfs_backref_node *cur)
6535d4f98a2SYan Zheng {
654e7d571c7SQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
655a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
656a26195a5SQu Wenruo 	struct btrfs_backref_node *exist;
6575d4f98a2SYan Zheng 	int ret;
6585d4f98a2SYan Zheng 
65971f572a9SQu Wenruo 	ret = btrfs_backref_iter_start(iter, cur->bytenr);
660e7d571c7SQu Wenruo 	if (ret < 0)
661e7d571c7SQu Wenruo 		return ret;
66271f572a9SQu Wenruo 	/*
66371f572a9SQu Wenruo 	 * We skip the first btrfs_tree_block_info, as we don't use the key
66471f572a9SQu Wenruo 	 * stored in it, but fetch it from the tree block
66571f572a9SQu Wenruo 	 */
66671f572a9SQu Wenruo 	if (btrfs_backref_has_tree_block_info(iter)) {
66771f572a9SQu Wenruo 		ret = btrfs_backref_iter_next(iter);
668e7d571c7SQu Wenruo 		if (ret < 0)
66971f572a9SQu Wenruo 			goto out;
67071f572a9SQu Wenruo 		/* No extra backref? This means the tree block is corrupted */
67171f572a9SQu Wenruo 		if (ret > 0) {
672e7d571c7SQu Wenruo 			ret = -EUCLEAN;
67371f572a9SQu Wenruo 			goto out;
67471f572a9SQu Wenruo 		}
67571f572a9SQu Wenruo 	}
6765d4f98a2SYan Zheng 	WARN_ON(cur->checked);
6775d4f98a2SYan Zheng 	if (!list_empty(&cur->upper)) {
6785d4f98a2SYan Zheng 		/*
67970f23fd6SJustin P. Mattock 		 * the backref was added previously when processing
6805d4f98a2SYan Zheng 		 * backref of type BTRFS_TREE_BLOCK_REF_KEY
6815d4f98a2SYan Zheng 		 */
68275bfb9afSJosef Bacik 		ASSERT(list_is_singular(&cur->upper));
683a26195a5SQu Wenruo 		edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
6845d4f98a2SYan Zheng 				  list[LOWER]);
68575bfb9afSJosef Bacik 		ASSERT(list_empty(&edge->list[UPPER]));
6865d4f98a2SYan Zheng 		exist = edge->node[UPPER];
6875d4f98a2SYan Zheng 		/*
6885d4f98a2SYan Zheng 		 * add the upper level block to pending list if we need
6895d4f98a2SYan Zheng 		 * check its backrefs
6905d4f98a2SYan Zheng 		 */
6915d4f98a2SYan Zheng 		if (!exist->checked)
69284780289SQu Wenruo 			list_add_tail(&edge->list[UPPER], &cache->pending_edge);
6935d4f98a2SYan Zheng 	} else {
6945d4f98a2SYan Zheng 		exist = NULL;
6955d4f98a2SYan Zheng 	}
6965d4f98a2SYan Zheng 
69771f572a9SQu Wenruo 	for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
69871f572a9SQu Wenruo 		struct extent_buffer *eb;
69971f572a9SQu Wenruo 		struct btrfs_key key;
7003de28d57SLiu Bo 		int type;
70171f572a9SQu Wenruo 
70271f572a9SQu Wenruo 		cond_resched();
70371f572a9SQu Wenruo 		eb = btrfs_backref_get_eb(iter);
70471f572a9SQu Wenruo 
70571f572a9SQu Wenruo 		key.objectid = iter->bytenr;
70671f572a9SQu Wenruo 		if (btrfs_backref_iter_is_inline_ref(iter)) {
70771f572a9SQu Wenruo 			struct btrfs_extent_inline_ref *iref;
70871f572a9SQu Wenruo 
70971f572a9SQu Wenruo 			/* update key for inline back ref */
71071f572a9SQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
71171f572a9SQu Wenruo 				((unsigned long)iter->cur_ptr);
7123de28d57SLiu Bo 			type = btrfs_get_extent_inline_ref_type(eb, iref,
7133de28d57SLiu Bo 							BTRFS_REF_TYPE_BLOCK);
7143de28d57SLiu Bo 			if (type == BTRFS_REF_TYPE_INVALID) {
715e7d571c7SQu Wenruo 				ret = -EUCLEAN;
7163de28d57SLiu Bo 				goto out;
7173de28d57SLiu Bo 			}
7183de28d57SLiu Bo 			key.type = type;
7195d4f98a2SYan Zheng 			key.offset = btrfs_extent_inline_ref_offset(eb, iref);
72071f572a9SQu Wenruo 		} else {
72171f572a9SQu Wenruo 			key.type = iter->cur_key.type;
72271f572a9SQu Wenruo 			key.offset = iter->cur_key.offset;
7235d4f98a2SYan Zheng 		}
7245d4f98a2SYan Zheng 
725fa6ac715SQu Wenruo 		/*
726fa6ac715SQu Wenruo 		 * Parent node found and matches current inline ref, no need to
727fa6ac715SQu Wenruo 		 * rebuild this node for this inline ref.
728fa6ac715SQu Wenruo 		 */
7295d4f98a2SYan Zheng 		if (exist &&
7305d4f98a2SYan Zheng 		    ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
7315d4f98a2SYan Zheng 		      exist->owner == key.offset) ||
7325d4f98a2SYan Zheng 		     (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
7335d4f98a2SYan Zheng 		      exist->bytenr == key.offset))) {
7345d4f98a2SYan Zheng 			exist = NULL;
73571f572a9SQu Wenruo 			continue;
7365d4f98a2SYan Zheng 		}
7375d4f98a2SYan Zheng 
738fa6ac715SQu Wenruo 		/* SHARED_BLOCK_REF means key.offset is the parent bytenr */
7395d4f98a2SYan Zheng 		if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
7404007ea87SQu Wenruo 			ret = handle_direct_tree_backref(cache, &key, cur);
741e7d571c7SQu Wenruo 			if (ret < 0)
7422433bea5SQu Wenruo 				goto out;
74371f572a9SQu Wenruo 			continue;
7446d8ff4e4SDavid Sterba 		} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
745e7d571c7SQu Wenruo 			ret = -EINVAL;
746e7d571c7SQu Wenruo 			btrfs_print_v0_err(fs_info);
747e7d571c7SQu Wenruo 			btrfs_handle_fs_error(fs_info, ret, NULL);
748ba3c2b19SNikolay Borisov 			goto out;
7495d4f98a2SYan Zheng 		} else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
75071f572a9SQu Wenruo 			continue;
7515d4f98a2SYan Zheng 		}
7525d4f98a2SYan Zheng 
753fa6ac715SQu Wenruo 		/*
754fa6ac715SQu Wenruo 		 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
755fa6ac715SQu Wenruo 		 * means the root objectid. We need to search the tree to get
756fa6ac715SQu Wenruo 		 * its parent bytenr.
757fa6ac715SQu Wenruo 		 */
7584d81ea8bSQu Wenruo 		ret = handle_indirect_tree_backref(cache, path, &key, node_key,
7594d81ea8bSQu Wenruo 						   cur);
760e7d571c7SQu Wenruo 		if (ret < 0)
76171f572a9SQu Wenruo 			goto out;
7625d4f98a2SYan Zheng 	}
76371f572a9SQu Wenruo 	ret = 0;
7645d4f98a2SYan Zheng 	cur->checked = 1;
7655d4f98a2SYan Zheng 	WARN_ON(exist);
766e7d571c7SQu Wenruo out:
767e7d571c7SQu Wenruo 	btrfs_backref_iter_release(iter);
768e7d571c7SQu Wenruo 	return ret;
769e7d571c7SQu Wenruo }
7705d4f98a2SYan Zheng 
771e7d571c7SQu Wenruo /*
7721f872924SQu Wenruo  * In handle_one_tree_backref(), we have only linked the lower node to the edge,
7731f872924SQu Wenruo  * but the upper node hasn't been linked to the edge.
774a26195a5SQu Wenruo  * This means we can only iterate through btrfs_backref_node::upper to reach
775a26195a5SQu Wenruo  * parent edges, but not through btrfs_backref_node::lower to reach children
776a26195a5SQu Wenruo  * edges.
7771f872924SQu Wenruo  *
778a26195a5SQu Wenruo  * This function will finish the btrfs_backref_node::lower to related edges,
779a26195a5SQu Wenruo  * so that backref cache can be bi-directionally iterated.
7801f872924SQu Wenruo  *
7811f872924SQu Wenruo  * Also, this will add the nodes to backref cache for the next run.
7821f872924SQu Wenruo  */
783a26195a5SQu Wenruo static int finish_upper_links(struct btrfs_backref_cache *cache,
784a26195a5SQu Wenruo 			      struct btrfs_backref_node *start)
7851f872924SQu Wenruo {
7861f872924SQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
787a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
7881f872924SQu Wenruo 	struct rb_node *rb_node;
7891f872924SQu Wenruo 	LIST_HEAD(pending_edge);
7901f872924SQu Wenruo 
7911f872924SQu Wenruo 	ASSERT(start->checked);
7921f872924SQu Wenruo 
7931f872924SQu Wenruo 	/* Insert this node to cache if it's not COW-only */
7941f872924SQu Wenruo 	if (!start->cowonly) {
795e9a28dc5SQu Wenruo 		rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
7961f872924SQu Wenruo 					   &start->rb_node);
7971f872924SQu Wenruo 		if (rb_node)
7981f872924SQu Wenruo 			backref_tree_panic(rb_node, -EEXIST, start->bytenr);
7991f872924SQu Wenruo 		list_add_tail(&start->lower, &cache->leaves);
8001f872924SQu Wenruo 	}
8011f872924SQu Wenruo 
8021f872924SQu Wenruo 	/*
8031f872924SQu Wenruo 	 * Use breadth first search to iterate all related edges.
8041f872924SQu Wenruo 	 *
8051f872924SQu Wenruo 	 * The starting points are all the edges of this node
8061f872924SQu Wenruo 	 */
8071f872924SQu Wenruo 	list_for_each_entry(edge, &start->upper, list[LOWER])
8081f872924SQu Wenruo 		list_add_tail(&edge->list[UPPER], &pending_edge);
8091f872924SQu Wenruo 
8101f872924SQu Wenruo 	while (!list_empty(&pending_edge)) {
811a26195a5SQu Wenruo 		struct btrfs_backref_node *upper;
812a26195a5SQu Wenruo 		struct btrfs_backref_node *lower;
8131f872924SQu Wenruo 		struct rb_node *rb_node;
8141f872924SQu Wenruo 
815a26195a5SQu Wenruo 		edge = list_first_entry(&pending_edge,
816a26195a5SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
8171f872924SQu Wenruo 		list_del_init(&edge->list[UPPER]);
8181f872924SQu Wenruo 		upper = edge->node[UPPER];
8191f872924SQu Wenruo 		lower = edge->node[LOWER];
8201f872924SQu Wenruo 
8211f872924SQu Wenruo 		/* Parent is detached, no need to keep any edges */
8221f872924SQu Wenruo 		if (upper->detached) {
8231f872924SQu Wenruo 			list_del(&edge->list[LOWER]);
824741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
8251f872924SQu Wenruo 
8261f872924SQu Wenruo 			/* Lower node is orphan, queue for cleanup */
8271f872924SQu Wenruo 			if (list_empty(&lower->upper))
8281f872924SQu Wenruo 				list_add(&lower->list, useless_node);
8291f872924SQu Wenruo 			continue;
8301f872924SQu Wenruo 		}
8311f872924SQu Wenruo 
8321f872924SQu Wenruo 		/*
8331f872924SQu Wenruo 		 * All new nodes added in current build_backref_tree() haven't
8341f872924SQu Wenruo 		 * been linked to the cache rb tree.
8351f872924SQu Wenruo 		 * So if we have upper->rb_node populated, this means a cache
8361f872924SQu Wenruo 		 * hit. We only need to link the edge, as @upper and all its
8371f872924SQu Wenruo 		 * parent have already been linked.
8381f872924SQu Wenruo 		 */
8391f872924SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node)) {
8401f872924SQu Wenruo 			if (upper->lowest) {
8411f872924SQu Wenruo 				list_del_init(&upper->lower);
8421f872924SQu Wenruo 				upper->lowest = 0;
8431f872924SQu Wenruo 			}
8441f872924SQu Wenruo 
8451f872924SQu Wenruo 			list_add_tail(&edge->list[UPPER], &upper->lower);
8461f872924SQu Wenruo 			continue;
8471f872924SQu Wenruo 		}
8481f872924SQu Wenruo 
8491f872924SQu Wenruo 		/* Sanity check, we shouldn't have any unchecked nodes */
8501f872924SQu Wenruo 		if (!upper->checked) {
8511f872924SQu Wenruo 			ASSERT(0);
8521f872924SQu Wenruo 			return -EUCLEAN;
8531f872924SQu Wenruo 		}
8541f872924SQu Wenruo 
8551f872924SQu Wenruo 		/* Sanity check, COW-only node has non-COW-only parent */
8561f872924SQu Wenruo 		if (start->cowonly != upper->cowonly) {
8571f872924SQu Wenruo 			ASSERT(0);
8581f872924SQu Wenruo 			return -EUCLEAN;
8591f872924SQu Wenruo 		}
8601f872924SQu Wenruo 
8611f872924SQu Wenruo 		/* Only cache non-COW-only (subvolume trees) tree blocks */
8621f872924SQu Wenruo 		if (!upper->cowonly) {
863e9a28dc5SQu Wenruo 			rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
8641f872924SQu Wenruo 						   &upper->rb_node);
8651f872924SQu Wenruo 			if (rb_node) {
8661f872924SQu Wenruo 				backref_tree_panic(rb_node, -EEXIST,
8671f872924SQu Wenruo 						   upper->bytenr);
8681f872924SQu Wenruo 				return -EUCLEAN;
8691f872924SQu Wenruo 			}
8701f872924SQu Wenruo 		}
8711f872924SQu Wenruo 
8721f872924SQu Wenruo 		list_add_tail(&edge->list[UPPER], &upper->lower);
8731f872924SQu Wenruo 
8741f872924SQu Wenruo 		/*
8751f872924SQu Wenruo 		 * Also queue all the parent edges of this uncached node to
8761f872924SQu Wenruo 		 * finish the upper linkage
8771f872924SQu Wenruo 		 */
8781f872924SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
8791f872924SQu Wenruo 			list_add_tail(&edge->list[UPPER], &pending_edge);
8801f872924SQu Wenruo 	}
8811f872924SQu Wenruo 	return 0;
8821f872924SQu Wenruo }
8831f872924SQu Wenruo 
8841f872924SQu Wenruo /*
88529db137bSQu Wenruo  * For useless nodes, do two major clean ups:
88629db137bSQu Wenruo  *
88729db137bSQu Wenruo  * - Cleanup the children edges and nodes
88829db137bSQu Wenruo  *   If child node is also orphan (no parent) during cleanup, then the child
88929db137bSQu Wenruo  *   node will also be cleaned up.
89029db137bSQu Wenruo  *
89129db137bSQu Wenruo  * - Freeing up leaves (level 0), keeps nodes detached
89229db137bSQu Wenruo  *   For nodes, the node is still cached as "detached"
89329db137bSQu Wenruo  *
89429db137bSQu Wenruo  * Return false if @node is not in the @useless_nodes list.
89529db137bSQu Wenruo  * Return true if @node is in the @useless_nodes list.
89629db137bSQu Wenruo  */
89729db137bSQu Wenruo static bool handle_useless_nodes(struct reloc_control *rc,
898a26195a5SQu Wenruo 				 struct btrfs_backref_node *node)
89929db137bSQu Wenruo {
900a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
90129db137bSQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
90229db137bSQu Wenruo 	bool ret = false;
90329db137bSQu Wenruo 
90429db137bSQu Wenruo 	while (!list_empty(useless_node)) {
905a26195a5SQu Wenruo 		struct btrfs_backref_node *cur;
90629db137bSQu Wenruo 
907a26195a5SQu Wenruo 		cur = list_first_entry(useless_node, struct btrfs_backref_node,
90829db137bSQu Wenruo 				 list);
90929db137bSQu Wenruo 		list_del_init(&cur->list);
91029db137bSQu Wenruo 
91129db137bSQu Wenruo 		/* Only tree root nodes can be added to @useless_nodes */
91229db137bSQu Wenruo 		ASSERT(list_empty(&cur->upper));
91329db137bSQu Wenruo 
91429db137bSQu Wenruo 		if (cur == node)
91529db137bSQu Wenruo 			ret = true;
91629db137bSQu Wenruo 
91729db137bSQu Wenruo 		/* The node is the lowest node */
91829db137bSQu Wenruo 		if (cur->lowest) {
91929db137bSQu Wenruo 			list_del_init(&cur->lower);
92029db137bSQu Wenruo 			cur->lowest = 0;
92129db137bSQu Wenruo 		}
92229db137bSQu Wenruo 
92329db137bSQu Wenruo 		/* Cleanup the lower edges */
92429db137bSQu Wenruo 		while (!list_empty(&cur->lower)) {
925a26195a5SQu Wenruo 			struct btrfs_backref_edge *edge;
926a26195a5SQu Wenruo 			struct btrfs_backref_node *lower;
92729db137bSQu Wenruo 
92829db137bSQu Wenruo 			edge = list_entry(cur->lower.next,
929a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[UPPER]);
93029db137bSQu Wenruo 			list_del(&edge->list[UPPER]);
93129db137bSQu Wenruo 			list_del(&edge->list[LOWER]);
93229db137bSQu Wenruo 			lower = edge->node[LOWER];
933741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
93429db137bSQu Wenruo 
93529db137bSQu Wenruo 			/* Child node is also orphan, queue for cleanup */
93629db137bSQu Wenruo 			if (list_empty(&lower->upper))
93729db137bSQu Wenruo 				list_add(&lower->list, useless_node);
93829db137bSQu Wenruo 		}
93929db137bSQu Wenruo 		/* Mark this block processed for relocation */
94029db137bSQu Wenruo 		mark_block_processed(rc, cur);
94129db137bSQu Wenruo 
94229db137bSQu Wenruo 		/*
94329db137bSQu Wenruo 		 * Backref nodes for tree leaves are deleted from the cache.
94429db137bSQu Wenruo 		 * Backref nodes for upper level tree blocks are left in the
94529db137bSQu Wenruo 		 * cache to avoid unnecessary backref lookup.
94629db137bSQu Wenruo 		 */
94729db137bSQu Wenruo 		if (cur->level > 0) {
94829db137bSQu Wenruo 			list_add(&cur->list, &cache->detached);
94929db137bSQu Wenruo 			cur->detached = 1;
95029db137bSQu Wenruo 		} else {
95129db137bSQu Wenruo 			rb_erase(&cur->rb_node, &cache->rb_root);
952741188d3SQu Wenruo 			btrfs_backref_free_node(cache, cur);
95329db137bSQu Wenruo 		}
95429db137bSQu Wenruo 	}
95529db137bSQu Wenruo 	return ret;
95629db137bSQu Wenruo }
95729db137bSQu Wenruo 
95829db137bSQu Wenruo /*
959e7d571c7SQu Wenruo  * Build backref tree for a given tree block. Root of the backref tree
960e7d571c7SQu Wenruo  * corresponds the tree block, leaves of the backref tree correspond roots of
961e7d571c7SQu Wenruo  * b-trees that reference the tree block.
962e7d571c7SQu Wenruo  *
963e7d571c7SQu Wenruo  * The basic idea of this function is check backrefs of a given block to find
964e7d571c7SQu Wenruo  * upper level blocks that reference the block, and then check backrefs of
965e7d571c7SQu Wenruo  * these upper level blocks recursively. The recursion stops when tree root is
966e7d571c7SQu Wenruo  * reached or backrefs for the block is cached.
967e7d571c7SQu Wenruo  *
968e7d571c7SQu Wenruo  * NOTE: if we find that backrefs for a block are cached, we know backrefs for
969e7d571c7SQu Wenruo  * all upper level blocks that directly/indirectly reference the block are also
970e7d571c7SQu Wenruo  * cached.
971e7d571c7SQu Wenruo  */
972a26195a5SQu Wenruo static noinline_for_stack struct btrfs_backref_node *build_backref_tree(
973e7d571c7SQu Wenruo 			struct reloc_control *rc, struct btrfs_key *node_key,
974e7d571c7SQu Wenruo 			int level, u64 bytenr)
975e7d571c7SQu Wenruo {
976e7d571c7SQu Wenruo 	struct btrfs_backref_iter *iter;
977a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
978e7d571c7SQu Wenruo 	/* For searching parent of TREE_BLOCK_REF */
979e7d571c7SQu Wenruo 	struct btrfs_path *path;
980a26195a5SQu Wenruo 	struct btrfs_backref_node *cur;
981a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
982a26195a5SQu Wenruo 	struct btrfs_backref_node *lower;
983a26195a5SQu Wenruo 	struct btrfs_backref_node *node = NULL;
984a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
985e7d571c7SQu Wenruo 	int ret;
986e7d571c7SQu Wenruo 	int err = 0;
987e7d571c7SQu Wenruo 
988e7d571c7SQu Wenruo 	iter = btrfs_backref_iter_alloc(rc->extent_root->fs_info, GFP_NOFS);
989e7d571c7SQu Wenruo 	if (!iter)
990e7d571c7SQu Wenruo 		return ERR_PTR(-ENOMEM);
991e7d571c7SQu Wenruo 	path = btrfs_alloc_path();
992e7d571c7SQu Wenruo 	if (!path) {
993e7d571c7SQu Wenruo 		err = -ENOMEM;
994e7d571c7SQu Wenruo 		goto out;
995e7d571c7SQu Wenruo 	}
996e7d571c7SQu Wenruo 
997b1818dabSQu Wenruo 	node = btrfs_backref_alloc_node(cache, bytenr, level);
998e7d571c7SQu Wenruo 	if (!node) {
999e7d571c7SQu Wenruo 		err = -ENOMEM;
1000e7d571c7SQu Wenruo 		goto out;
1001e7d571c7SQu Wenruo 	}
1002e7d571c7SQu Wenruo 
1003e7d571c7SQu Wenruo 	node->lowest = 1;
1004e7d571c7SQu Wenruo 	cur = node;
1005e7d571c7SQu Wenruo 
1006e7d571c7SQu Wenruo 	/* Breadth-first search to build backref cache */
1007e7d571c7SQu Wenruo 	do {
1008e7d571c7SQu Wenruo 		ret = handle_one_tree_block(cache, path, iter, node_key, cur);
1009e7d571c7SQu Wenruo 		if (ret < 0) {
1010e7d571c7SQu Wenruo 			err = ret;
1011e7d571c7SQu Wenruo 			goto out;
1012e7d571c7SQu Wenruo 		}
1013e7d571c7SQu Wenruo 		edge = list_first_entry_or_null(&cache->pending_edge,
1014a26195a5SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
1015e7d571c7SQu Wenruo 		/*
1016e7d571c7SQu Wenruo 		 * The pending list isn't empty, take the first block to
1017e7d571c7SQu Wenruo 		 * process
1018e7d571c7SQu Wenruo 		 */
1019e7d571c7SQu Wenruo 		if (edge) {
10205d4f98a2SYan Zheng 			list_del_init(&edge->list[UPPER]);
10215d4f98a2SYan Zheng 			cur = edge->node[UPPER];
10225d4f98a2SYan Zheng 		}
1023e7d571c7SQu Wenruo 	} while (edge);
10245d4f98a2SYan Zheng 
10251f872924SQu Wenruo 	/* Finish the upper linkage of newly added edges/nodes */
10261f872924SQu Wenruo 	ret = finish_upper_links(cache, node);
10271f872924SQu Wenruo 	if (ret < 0) {
10281f872924SQu Wenruo 		err = ret;
102975bfb9afSJosef Bacik 		goto out;
103075bfb9afSJosef Bacik 	}
103175bfb9afSJosef Bacik 
103229db137bSQu Wenruo 	if (handle_useless_nodes(rc, node))
10333fd0a558SYan, Zheng 		node = NULL;
10345d4f98a2SYan Zheng out:
103571f572a9SQu Wenruo 	btrfs_backref_iter_free(iter);
103671f572a9SQu Wenruo 	btrfs_free_path(path);
10375d4f98a2SYan Zheng 	if (err) {
103884780289SQu Wenruo 		while (!list_empty(&cache->useless_node)) {
103984780289SQu Wenruo 			lower = list_first_entry(&cache->useless_node,
1040a26195a5SQu Wenruo 					   struct btrfs_backref_node, list);
104175bfb9afSJosef Bacik 			list_del_init(&lower->list);
10423fd0a558SYan, Zheng 		}
104384780289SQu Wenruo 		while (!list_empty(&cache->pending_edge)) {
104484780289SQu Wenruo 			edge = list_first_entry(&cache->pending_edge,
1045a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[UPPER]);
104675bfb9afSJosef Bacik 			list_del(&edge->list[UPPER]);
10473fd0a558SYan, Zheng 			list_del(&edge->list[LOWER]);
104875bfb9afSJosef Bacik 			lower = edge->node[LOWER];
10495d4f98a2SYan Zheng 			upper = edge->node[UPPER];
1050741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
105175bfb9afSJosef Bacik 
105275bfb9afSJosef Bacik 			/*
105375bfb9afSJosef Bacik 			 * Lower is no longer linked to any upper backref nodes
105475bfb9afSJosef Bacik 			 * and isn't in the cache, we can free it ourselves.
105575bfb9afSJosef Bacik 			 */
105675bfb9afSJosef Bacik 			if (list_empty(&lower->upper) &&
105775bfb9afSJosef Bacik 			    RB_EMPTY_NODE(&lower->rb_node))
105884780289SQu Wenruo 				list_add(&lower->list, &cache->useless_node);
105975bfb9afSJosef Bacik 
106075bfb9afSJosef Bacik 			if (!RB_EMPTY_NODE(&upper->rb_node))
106175bfb9afSJosef Bacik 				continue;
106275bfb9afSJosef Bacik 
106301327610SNicholas D Steeves 			/* Add this guy's upper edges to the list to process */
106475bfb9afSJosef Bacik 			list_for_each_entry(edge, &upper->upper, list[LOWER])
106584780289SQu Wenruo 				list_add_tail(&edge->list[UPPER],
106684780289SQu Wenruo 					      &cache->pending_edge);
106775bfb9afSJosef Bacik 			if (list_empty(&upper->upper))
106884780289SQu Wenruo 				list_add(&upper->list, &cache->useless_node);
106975bfb9afSJosef Bacik 		}
107075bfb9afSJosef Bacik 
107184780289SQu Wenruo 		while (!list_empty(&cache->useless_node)) {
107284780289SQu Wenruo 			lower = list_first_entry(&cache->useless_node,
1073a26195a5SQu Wenruo 					   struct btrfs_backref_node, list);
107475bfb9afSJosef Bacik 			list_del_init(&lower->list);
10750fd8c3daSLiu Bo 			if (lower == node)
10760fd8c3daSLiu Bo 				node = NULL;
1077741188d3SQu Wenruo 			btrfs_backref_free_node(cache, lower);
10785d4f98a2SYan Zheng 		}
10790fd8c3daSLiu Bo 
1080023acb07SQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
108184780289SQu Wenruo 		ASSERT(list_empty(&cache->useless_node) &&
108284780289SQu Wenruo 		       list_empty(&cache->pending_edge));
10835d4f98a2SYan Zheng 		return ERR_PTR(err);
10845d4f98a2SYan Zheng 	}
108575bfb9afSJosef Bacik 	ASSERT(!node || !node->detached);
108684780289SQu Wenruo 	ASSERT(list_empty(&cache->useless_node) &&
108784780289SQu Wenruo 	       list_empty(&cache->pending_edge));
10885d4f98a2SYan Zheng 	return node;
10895d4f98a2SYan Zheng }
10905d4f98a2SYan Zheng 
10915d4f98a2SYan Zheng /*
10923fd0a558SYan, Zheng  * helper to add backref node for the newly created snapshot.
10933fd0a558SYan, Zheng  * the backref node is created by cloning backref node that
10943fd0a558SYan, Zheng  * corresponds to root of source tree
10953fd0a558SYan, Zheng  */
10963fd0a558SYan, Zheng static int clone_backref_node(struct btrfs_trans_handle *trans,
10973fd0a558SYan, Zheng 			      struct reloc_control *rc,
10983fd0a558SYan, Zheng 			      struct btrfs_root *src,
10993fd0a558SYan, Zheng 			      struct btrfs_root *dest)
11003fd0a558SYan, Zheng {
11013fd0a558SYan, Zheng 	struct btrfs_root *reloc_root = src->reloc_root;
1102a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
1103a26195a5SQu Wenruo 	struct btrfs_backref_node *node = NULL;
1104a26195a5SQu Wenruo 	struct btrfs_backref_node *new_node;
1105a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
1106a26195a5SQu Wenruo 	struct btrfs_backref_edge *new_edge;
11073fd0a558SYan, Zheng 	struct rb_node *rb_node;
11083fd0a558SYan, Zheng 
11093fd0a558SYan, Zheng 	if (cache->last_trans > 0)
11103fd0a558SYan, Zheng 		update_backref_cache(trans, cache);
11113fd0a558SYan, Zheng 
1112e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, src->commit_root->start);
11133fd0a558SYan, Zheng 	if (rb_node) {
1114a26195a5SQu Wenruo 		node = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
11153fd0a558SYan, Zheng 		if (node->detached)
11163fd0a558SYan, Zheng 			node = NULL;
11173fd0a558SYan, Zheng 		else
11183fd0a558SYan, Zheng 			BUG_ON(node->new_bytenr != reloc_root->node->start);
11193fd0a558SYan, Zheng 	}
11203fd0a558SYan, Zheng 
11213fd0a558SYan, Zheng 	if (!node) {
1122e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root,
11233fd0a558SYan, Zheng 					   reloc_root->commit_root->start);
11243fd0a558SYan, Zheng 		if (rb_node) {
1125a26195a5SQu Wenruo 			node = rb_entry(rb_node, struct btrfs_backref_node,
11263fd0a558SYan, Zheng 					rb_node);
11273fd0a558SYan, Zheng 			BUG_ON(node->detached);
11283fd0a558SYan, Zheng 		}
11293fd0a558SYan, Zheng 	}
11303fd0a558SYan, Zheng 
11313fd0a558SYan, Zheng 	if (!node)
11323fd0a558SYan, Zheng 		return 0;
11333fd0a558SYan, Zheng 
1134b1818dabSQu Wenruo 	new_node = btrfs_backref_alloc_node(cache, dest->node->start,
1135b1818dabSQu Wenruo 					    node->level);
11363fd0a558SYan, Zheng 	if (!new_node)
11373fd0a558SYan, Zheng 		return -ENOMEM;
11383fd0a558SYan, Zheng 
11393fd0a558SYan, Zheng 	new_node->lowest = node->lowest;
11406848ad64SYan, Zheng 	new_node->checked = 1;
114100246528SJosef Bacik 	new_node->root = btrfs_grab_root(dest);
11420b530bc5SJosef Bacik 	ASSERT(new_node->root);
11433fd0a558SYan, Zheng 
11443fd0a558SYan, Zheng 	if (!node->lowest) {
11453fd0a558SYan, Zheng 		list_for_each_entry(edge, &node->lower, list[UPPER]) {
114647254d07SQu Wenruo 			new_edge = btrfs_backref_alloc_edge(cache);
11473fd0a558SYan, Zheng 			if (!new_edge)
11483fd0a558SYan, Zheng 				goto fail;
11493fd0a558SYan, Zheng 
1150f39911e5SQu Wenruo 			btrfs_backref_link_edge(new_edge, edge->node[LOWER],
1151f39911e5SQu Wenruo 						new_node, LINK_UPPER);
11523fd0a558SYan, Zheng 		}
115376b9e23dSMiao Xie 	} else {
115476b9e23dSMiao Xie 		list_add_tail(&new_node->lower, &cache->leaves);
11553fd0a558SYan, Zheng 	}
11563fd0a558SYan, Zheng 
1157e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&cache->rb_root, new_node->bytenr,
11583fd0a558SYan, Zheng 				   &new_node->rb_node);
115943c04fb1SJeff Mahoney 	if (rb_node)
116043c04fb1SJeff Mahoney 		backref_tree_panic(rb_node, -EEXIST, new_node->bytenr);
11613fd0a558SYan, Zheng 
11623fd0a558SYan, Zheng 	if (!new_node->lowest) {
11633fd0a558SYan, Zheng 		list_for_each_entry(new_edge, &new_node->lower, list[UPPER]) {
11643fd0a558SYan, Zheng 			list_add_tail(&new_edge->list[LOWER],
11653fd0a558SYan, Zheng 				      &new_edge->node[LOWER]->upper);
11663fd0a558SYan, Zheng 		}
11673fd0a558SYan, Zheng 	}
11683fd0a558SYan, Zheng 	return 0;
11693fd0a558SYan, Zheng fail:
11703fd0a558SYan, Zheng 	while (!list_empty(&new_node->lower)) {
11713fd0a558SYan, Zheng 		new_edge = list_entry(new_node->lower.next,
1172a26195a5SQu Wenruo 				      struct btrfs_backref_edge, list[UPPER]);
11733fd0a558SYan, Zheng 		list_del(&new_edge->list[UPPER]);
1174741188d3SQu Wenruo 		btrfs_backref_free_edge(cache, new_edge);
11753fd0a558SYan, Zheng 	}
1176741188d3SQu Wenruo 	btrfs_backref_free_node(cache, new_node);
11773fd0a558SYan, Zheng 	return -ENOMEM;
11783fd0a558SYan, Zheng }
11793fd0a558SYan, Zheng 
11803fd0a558SYan, Zheng /*
11815d4f98a2SYan Zheng  * helper to add 'address of tree root -> reloc tree' mapping
11825d4f98a2SYan Zheng  */
1183ffd7b339SJeff Mahoney static int __must_check __add_reloc_root(struct btrfs_root *root)
11845d4f98a2SYan Zheng {
11850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11865d4f98a2SYan Zheng 	struct rb_node *rb_node;
11875d4f98a2SYan Zheng 	struct mapping_node *node;
11880b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
11895d4f98a2SYan Zheng 
11905d4f98a2SYan Zheng 	node = kmalloc(sizeof(*node), GFP_NOFS);
1191ffd7b339SJeff Mahoney 	if (!node)
1192ffd7b339SJeff Mahoney 		return -ENOMEM;
11935d4f98a2SYan Zheng 
1194ea287ab1SJosef Bacik 	node->bytenr = root->commit_root->start;
11955d4f98a2SYan Zheng 	node->data = root;
11965d4f98a2SYan Zheng 
11975d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
1198e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
11995d4f98a2SYan Zheng 				   node->bytenr, &node->rb_node);
12005d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
1201ffd7b339SJeff Mahoney 	if (rb_node) {
12020b246afaSJeff Mahoney 		btrfs_panic(fs_info, -EEXIST,
12035d163e0eSJeff Mahoney 			    "Duplicate root found for start=%llu while inserting into relocation tree",
12045d163e0eSJeff Mahoney 			    node->bytenr);
1205ffd7b339SJeff Mahoney 	}
12065d4f98a2SYan Zheng 
12075d4f98a2SYan Zheng 	list_add_tail(&root->root_list, &rc->reloc_roots);
12085d4f98a2SYan Zheng 	return 0;
12095d4f98a2SYan Zheng }
12105d4f98a2SYan Zheng 
12115d4f98a2SYan Zheng /*
1212c974c464SWang Shilong  * helper to delete the 'address of tree root -> reloc tree'
12135d4f98a2SYan Zheng  * mapping
12145d4f98a2SYan Zheng  */
1215c974c464SWang Shilong static void __del_reloc_root(struct btrfs_root *root)
12165d4f98a2SYan Zheng {
12170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12185d4f98a2SYan Zheng 	struct rb_node *rb_node;
12195d4f98a2SYan Zheng 	struct mapping_node *node = NULL;
12200b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
1221f44deb74SJosef Bacik 	bool put_ref = false;
12225d4f98a2SYan Zheng 
122365c6e82bSQu Wenruo 	if (rc && root->node) {
12245d4f98a2SYan Zheng 		spin_lock(&rc->reloc_root_tree.lock);
1225e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
1226ea287ab1SJosef Bacik 					   root->commit_root->start);
1227c974c464SWang Shilong 		if (rb_node) {
1228c974c464SWang Shilong 			node = rb_entry(rb_node, struct mapping_node, rb_node);
1229c974c464SWang Shilong 			rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
1230ea287ab1SJosef Bacik 			RB_CLEAR_NODE(&node->rb_node);
1231c974c464SWang Shilong 		}
1232c974c464SWang Shilong 		spin_unlock(&rc->reloc_root_tree.lock);
1233c974c464SWang Shilong 		if (!node)
1234c974c464SWang Shilong 			return;
1235c974c464SWang Shilong 		BUG_ON((struct btrfs_root *)node->data != root);
1236389305b2SQu Wenruo 	}
1237c974c464SWang Shilong 
1238f44deb74SJosef Bacik 	/*
1239f44deb74SJosef Bacik 	 * We only put the reloc root here if it's on the list.  There's a lot
1240f44deb74SJosef Bacik 	 * of places where the pattern is to splice the rc->reloc_roots, process
1241f44deb74SJosef Bacik 	 * the reloc roots, and then add the reloc root back onto
1242f44deb74SJosef Bacik 	 * rc->reloc_roots.  If we call __del_reloc_root while it's off of the
1243f44deb74SJosef Bacik 	 * list we don't want the reference being dropped, because the guy
1244f44deb74SJosef Bacik 	 * messing with the list is in charge of the reference.
1245f44deb74SJosef Bacik 	 */
12460b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
1247f44deb74SJosef Bacik 	if (!list_empty(&root->root_list)) {
1248f44deb74SJosef Bacik 		put_ref = true;
1249c974c464SWang Shilong 		list_del_init(&root->root_list);
1250f44deb74SJosef Bacik 	}
12510b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1252f44deb74SJosef Bacik 	if (put_ref)
1253f44deb74SJosef Bacik 		btrfs_put_root(root);
1254c974c464SWang Shilong 	kfree(node);
1255c974c464SWang Shilong }
1256c974c464SWang Shilong 
1257c974c464SWang Shilong /*
1258c974c464SWang Shilong  * helper to update the 'address of tree root -> reloc tree'
1259c974c464SWang Shilong  * mapping
1260c974c464SWang Shilong  */
1261ea287ab1SJosef Bacik static int __update_reloc_root(struct btrfs_root *root)
1262c974c464SWang Shilong {
12630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1264c974c464SWang Shilong 	struct rb_node *rb_node;
1265c974c464SWang Shilong 	struct mapping_node *node = NULL;
12660b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
1267c974c464SWang Shilong 
1268c974c464SWang Shilong 	spin_lock(&rc->reloc_root_tree.lock);
1269e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
1270ea287ab1SJosef Bacik 				   root->commit_root->start);
12715d4f98a2SYan Zheng 	if (rb_node) {
12725d4f98a2SYan Zheng 		node = rb_entry(rb_node, struct mapping_node, rb_node);
12735d4f98a2SYan Zheng 		rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
12745d4f98a2SYan Zheng 	}
12755d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
12765d4f98a2SYan Zheng 
12778f71f3e0SLiu Bo 	if (!node)
12788f71f3e0SLiu Bo 		return 0;
12795d4f98a2SYan Zheng 	BUG_ON((struct btrfs_root *)node->data != root);
12805d4f98a2SYan Zheng 
12815d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
1282ea287ab1SJosef Bacik 	node->bytenr = root->node->start;
1283e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
12845d4f98a2SYan Zheng 				   node->bytenr, &node->rb_node);
12855d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
128643c04fb1SJeff Mahoney 	if (rb_node)
128743c04fb1SJeff Mahoney 		backref_tree_panic(rb_node, -EEXIST, node->bytenr);
12885d4f98a2SYan Zheng 	return 0;
12895d4f98a2SYan Zheng }
12905d4f98a2SYan Zheng 
12913fd0a558SYan, Zheng static struct btrfs_root *create_reloc_root(struct btrfs_trans_handle *trans,
12923fd0a558SYan, Zheng 					struct btrfs_root *root, u64 objectid)
12935d4f98a2SYan Zheng {
12940b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12955d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
12965d4f98a2SYan Zheng 	struct extent_buffer *eb;
12975d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
12985d4f98a2SYan Zheng 	struct btrfs_key root_key;
12995d4f98a2SYan Zheng 	int ret;
13005d4f98a2SYan Zheng 
13015d4f98a2SYan Zheng 	root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
13025d4f98a2SYan Zheng 	BUG_ON(!root_item);
13035d4f98a2SYan Zheng 
13045d4f98a2SYan Zheng 	root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
13055d4f98a2SYan Zheng 	root_key.type = BTRFS_ROOT_ITEM_KEY;
13063fd0a558SYan, Zheng 	root_key.offset = objectid;
13075d4f98a2SYan Zheng 
13083fd0a558SYan, Zheng 	if (root->root_key.objectid == objectid) {
1309054570a1SFilipe Manana 		u64 commit_root_gen;
1310054570a1SFilipe Manana 
13113fd0a558SYan, Zheng 		/* called by btrfs_init_reloc_root */
13125d4f98a2SYan Zheng 		ret = btrfs_copy_root(trans, root, root->commit_root, &eb,
13135d4f98a2SYan Zheng 				      BTRFS_TREE_RELOC_OBJECTID);
13145d4f98a2SYan Zheng 		BUG_ON(ret);
1315054570a1SFilipe Manana 		/*
1316054570a1SFilipe Manana 		 * Set the last_snapshot field to the generation of the commit
1317054570a1SFilipe Manana 		 * root - like this ctree.c:btrfs_block_can_be_shared() behaves
1318054570a1SFilipe Manana 		 * correctly (returns true) when the relocation root is created
1319054570a1SFilipe Manana 		 * either inside the critical section of a transaction commit
1320054570a1SFilipe Manana 		 * (through transaction.c:qgroup_account_snapshot()) and when
1321054570a1SFilipe Manana 		 * it's created before the transaction commit is started.
1322054570a1SFilipe Manana 		 */
1323054570a1SFilipe Manana 		commit_root_gen = btrfs_header_generation(root->commit_root);
1324054570a1SFilipe Manana 		btrfs_set_root_last_snapshot(&root->root_item, commit_root_gen);
13253fd0a558SYan, Zheng 	} else {
13263fd0a558SYan, Zheng 		/*
13273fd0a558SYan, Zheng 		 * called by btrfs_reloc_post_snapshot_hook.
13283fd0a558SYan, Zheng 		 * the source tree is a reloc tree, all tree blocks
13293fd0a558SYan, Zheng 		 * modified after it was created have RELOC flag
13303fd0a558SYan, Zheng 		 * set in their headers. so it's OK to not update
13313fd0a558SYan, Zheng 		 * the 'last_snapshot'.
13323fd0a558SYan, Zheng 		 */
13333fd0a558SYan, Zheng 		ret = btrfs_copy_root(trans, root, root->node, &eb,
13343fd0a558SYan, Zheng 				      BTRFS_TREE_RELOC_OBJECTID);
13353fd0a558SYan, Zheng 		BUG_ON(ret);
13363fd0a558SYan, Zheng 	}
13373fd0a558SYan, Zheng 
13385d4f98a2SYan Zheng 	memcpy(root_item, &root->root_item, sizeof(*root_item));
13395d4f98a2SYan Zheng 	btrfs_set_root_bytenr(root_item, eb->start);
13405d4f98a2SYan Zheng 	btrfs_set_root_level(root_item, btrfs_header_level(eb));
13415d4f98a2SYan Zheng 	btrfs_set_root_generation(root_item, trans->transid);
13423fd0a558SYan, Zheng 
13433fd0a558SYan, Zheng 	if (root->root_key.objectid == objectid) {
13443fd0a558SYan, Zheng 		btrfs_set_root_refs(root_item, 0);
13453fd0a558SYan, Zheng 		memset(&root_item->drop_progress, 0,
13463fd0a558SYan, Zheng 		       sizeof(struct btrfs_disk_key));
13475d4f98a2SYan Zheng 		root_item->drop_level = 0;
13483fd0a558SYan, Zheng 	}
13495d4f98a2SYan Zheng 
13505d4f98a2SYan Zheng 	btrfs_tree_unlock(eb);
13515d4f98a2SYan Zheng 	free_extent_buffer(eb);
13525d4f98a2SYan Zheng 
13530b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root,
13545d4f98a2SYan Zheng 				&root_key, root_item);
13555d4f98a2SYan Zheng 	BUG_ON(ret);
13565d4f98a2SYan Zheng 	kfree(root_item);
13575d4f98a2SYan Zheng 
13583dbf1738SJosef Bacik 	reloc_root = btrfs_read_tree_root(fs_info->tree_root, &root_key);
13595d4f98a2SYan Zheng 	BUG_ON(IS_ERR(reloc_root));
13603dbf1738SJosef Bacik 	set_bit(BTRFS_ROOT_REF_COWS, &reloc_root->state);
13615d4f98a2SYan Zheng 	reloc_root->last_trans = trans->transid;
13623fd0a558SYan, Zheng 	return reloc_root;
13633fd0a558SYan, Zheng }
13643fd0a558SYan, Zheng 
13653fd0a558SYan, Zheng /*
13663fd0a558SYan, Zheng  * create reloc tree for a given fs tree. reloc tree is just a
13673fd0a558SYan, Zheng  * snapshot of the fs tree with special root objectid.
1368f44deb74SJosef Bacik  *
1369f44deb74SJosef Bacik  * The reloc_root comes out of here with two references, one for
1370f44deb74SJosef Bacik  * root->reloc_root, and another for being on the rc->reloc_roots list.
13713fd0a558SYan, Zheng  */
13723fd0a558SYan, Zheng int btrfs_init_reloc_root(struct btrfs_trans_handle *trans,
13733fd0a558SYan, Zheng 			  struct btrfs_root *root)
13743fd0a558SYan, Zheng {
13750b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13763fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
13770b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
137820dd2cbfSMiao Xie 	struct btrfs_block_rsv *rsv;
13793fd0a558SYan, Zheng 	int clear_rsv = 0;
1380ffd7b339SJeff Mahoney 	int ret;
13813fd0a558SYan, Zheng 
1382aec7db3bSJosef Bacik 	if (!rc)
13832abc726aSJosef Bacik 		return 0;
13842abc726aSJosef Bacik 
13851fac4a54SQu Wenruo 	/*
13861fac4a54SQu Wenruo 	 * The subvolume has reloc tree but the swap is finished, no need to
13871fac4a54SQu Wenruo 	 * create/update the dead reloc tree
13881fac4a54SQu Wenruo 	 */
13896282675eSQu Wenruo 	if (reloc_root_is_dead(root))
13901fac4a54SQu Wenruo 		return 0;
13911fac4a54SQu Wenruo 
1392aec7db3bSJosef Bacik 	/*
1393aec7db3bSJosef Bacik 	 * This is subtle but important.  We do not do
1394aec7db3bSJosef Bacik 	 * record_root_in_transaction for reloc roots, instead we record their
1395aec7db3bSJosef Bacik 	 * corresponding fs root, and then here we update the last trans for the
1396aec7db3bSJosef Bacik 	 * reloc root.  This means that we have to do this for the entire life
1397aec7db3bSJosef Bacik 	 * of the reloc root, regardless of which stage of the relocation we are
1398aec7db3bSJosef Bacik 	 * in.
1399aec7db3bSJosef Bacik 	 */
14003fd0a558SYan, Zheng 	if (root->reloc_root) {
14013fd0a558SYan, Zheng 		reloc_root = root->reloc_root;
14023fd0a558SYan, Zheng 		reloc_root->last_trans = trans->transid;
14033fd0a558SYan, Zheng 		return 0;
14043fd0a558SYan, Zheng 	}
14053fd0a558SYan, Zheng 
1406aec7db3bSJosef Bacik 	/*
1407aec7db3bSJosef Bacik 	 * We are merging reloc roots, we do not need new reloc trees.  Also
1408aec7db3bSJosef Bacik 	 * reloc trees never need their own reloc tree.
1409aec7db3bSJosef Bacik 	 */
1410aec7db3bSJosef Bacik 	if (!rc->create_reloc_tree ||
1411aec7db3bSJosef Bacik 	    root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1412aec7db3bSJosef Bacik 		return 0;
1413aec7db3bSJosef Bacik 
141420dd2cbfSMiao Xie 	if (!trans->reloc_reserved) {
141520dd2cbfSMiao Xie 		rsv = trans->block_rsv;
14163fd0a558SYan, Zheng 		trans->block_rsv = rc->block_rsv;
14173fd0a558SYan, Zheng 		clear_rsv = 1;
14183fd0a558SYan, Zheng 	}
14193fd0a558SYan, Zheng 	reloc_root = create_reloc_root(trans, root, root->root_key.objectid);
14203fd0a558SYan, Zheng 	if (clear_rsv)
142120dd2cbfSMiao Xie 		trans->block_rsv = rsv;
14225d4f98a2SYan Zheng 
1423ffd7b339SJeff Mahoney 	ret = __add_reloc_root(reloc_root);
1424ffd7b339SJeff Mahoney 	BUG_ON(ret < 0);
1425f44deb74SJosef Bacik 	root->reloc_root = btrfs_grab_root(reloc_root);
14265d4f98a2SYan Zheng 	return 0;
14275d4f98a2SYan Zheng }
14285d4f98a2SYan Zheng 
14295d4f98a2SYan Zheng /*
14305d4f98a2SYan Zheng  * update root item of reloc tree
14315d4f98a2SYan Zheng  */
14325d4f98a2SYan Zheng int btrfs_update_reloc_root(struct btrfs_trans_handle *trans,
14335d4f98a2SYan Zheng 			    struct btrfs_root *root)
14345d4f98a2SYan Zheng {
14350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14365d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
14375d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
14385d4f98a2SYan Zheng 	int ret;
14395d4f98a2SYan Zheng 
14406282675eSQu Wenruo 	if (!have_reloc_root(root))
14417585717fSChris Mason 		goto out;
14425d4f98a2SYan Zheng 
14435d4f98a2SYan Zheng 	reloc_root = root->reloc_root;
14445d4f98a2SYan Zheng 	root_item = &reloc_root->root_item;
14455d4f98a2SYan Zheng 
1446f44deb74SJosef Bacik 	/*
1447f44deb74SJosef Bacik 	 * We are probably ok here, but __del_reloc_root() will drop its ref of
1448f44deb74SJosef Bacik 	 * the root.  We have the ref for root->reloc_root, but just in case
1449f44deb74SJosef Bacik 	 * hold it while we update the reloc root.
1450f44deb74SJosef Bacik 	 */
1451f44deb74SJosef Bacik 	btrfs_grab_root(reloc_root);
1452f44deb74SJosef Bacik 
1453d2311e69SQu Wenruo 	/* root->reloc_root will stay until current relocation finished */
14540b246afaSJeff Mahoney 	if (fs_info->reloc_ctl->merge_reloc_tree &&
14553fd0a558SYan, Zheng 	    btrfs_root_refs(root_item) == 0) {
1456d2311e69SQu Wenruo 		set_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
14576282675eSQu Wenruo 		/*
14586282675eSQu Wenruo 		 * Mark the tree as dead before we change reloc_root so
14596282675eSQu Wenruo 		 * have_reloc_root will not touch it from now on.
14606282675eSQu Wenruo 		 */
14616282675eSQu Wenruo 		smp_wmb();
1462c974c464SWang Shilong 		__del_reloc_root(reloc_root);
14635d4f98a2SYan Zheng 	}
14645d4f98a2SYan Zheng 
14655d4f98a2SYan Zheng 	if (reloc_root->commit_root != reloc_root->node) {
1466ea287ab1SJosef Bacik 		__update_reloc_root(reloc_root);
14675d4f98a2SYan Zheng 		btrfs_set_root_node(root_item, reloc_root->node);
14685d4f98a2SYan Zheng 		free_extent_buffer(reloc_root->commit_root);
14695d4f98a2SYan Zheng 		reloc_root->commit_root = btrfs_root_node(reloc_root);
14705d4f98a2SYan Zheng 	}
14715d4f98a2SYan Zheng 
14720b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
14735d4f98a2SYan Zheng 				&reloc_root->root_key, root_item);
14745d4f98a2SYan Zheng 	BUG_ON(ret);
1475f44deb74SJosef Bacik 	btrfs_put_root(reloc_root);
14767585717fSChris Mason out:
14775d4f98a2SYan Zheng 	return 0;
14785d4f98a2SYan Zheng }
14795d4f98a2SYan Zheng 
14805d4f98a2SYan Zheng /*
14815d4f98a2SYan Zheng  * helper to find first cached inode with inode number >= objectid
14825d4f98a2SYan Zheng  * in a subvolume
14835d4f98a2SYan Zheng  */
14845d4f98a2SYan Zheng static struct inode *find_next_inode(struct btrfs_root *root, u64 objectid)
14855d4f98a2SYan Zheng {
14865d4f98a2SYan Zheng 	struct rb_node *node;
14875d4f98a2SYan Zheng 	struct rb_node *prev;
14885d4f98a2SYan Zheng 	struct btrfs_inode *entry;
14895d4f98a2SYan Zheng 	struct inode *inode;
14905d4f98a2SYan Zheng 
14915d4f98a2SYan Zheng 	spin_lock(&root->inode_lock);
14925d4f98a2SYan Zheng again:
14935d4f98a2SYan Zheng 	node = root->inode_tree.rb_node;
14945d4f98a2SYan Zheng 	prev = NULL;
14955d4f98a2SYan Zheng 	while (node) {
14965d4f98a2SYan Zheng 		prev = node;
14975d4f98a2SYan Zheng 		entry = rb_entry(node, struct btrfs_inode, rb_node);
14985d4f98a2SYan Zheng 
14994a0cc7caSNikolay Borisov 		if (objectid < btrfs_ino(entry))
15005d4f98a2SYan Zheng 			node = node->rb_left;
15014a0cc7caSNikolay Borisov 		else if (objectid > btrfs_ino(entry))
15025d4f98a2SYan Zheng 			node = node->rb_right;
15035d4f98a2SYan Zheng 		else
15045d4f98a2SYan Zheng 			break;
15055d4f98a2SYan Zheng 	}
15065d4f98a2SYan Zheng 	if (!node) {
15075d4f98a2SYan Zheng 		while (prev) {
15085d4f98a2SYan Zheng 			entry = rb_entry(prev, struct btrfs_inode, rb_node);
15094a0cc7caSNikolay Borisov 			if (objectid <= btrfs_ino(entry)) {
15105d4f98a2SYan Zheng 				node = prev;
15115d4f98a2SYan Zheng 				break;
15125d4f98a2SYan Zheng 			}
15135d4f98a2SYan Zheng 			prev = rb_next(prev);
15145d4f98a2SYan Zheng 		}
15155d4f98a2SYan Zheng 	}
15165d4f98a2SYan Zheng 	while (node) {
15175d4f98a2SYan Zheng 		entry = rb_entry(node, struct btrfs_inode, rb_node);
15185d4f98a2SYan Zheng 		inode = igrab(&entry->vfs_inode);
15195d4f98a2SYan Zheng 		if (inode) {
15205d4f98a2SYan Zheng 			spin_unlock(&root->inode_lock);
15215d4f98a2SYan Zheng 			return inode;
15225d4f98a2SYan Zheng 		}
15235d4f98a2SYan Zheng 
15244a0cc7caSNikolay Borisov 		objectid = btrfs_ino(entry) + 1;
15255d4f98a2SYan Zheng 		if (cond_resched_lock(&root->inode_lock))
15265d4f98a2SYan Zheng 			goto again;
15275d4f98a2SYan Zheng 
15285d4f98a2SYan Zheng 		node = rb_next(node);
15295d4f98a2SYan Zheng 	}
15305d4f98a2SYan Zheng 	spin_unlock(&root->inode_lock);
15315d4f98a2SYan Zheng 	return NULL;
15325d4f98a2SYan Zheng }
15335d4f98a2SYan Zheng 
15345d4f98a2SYan Zheng /*
15355d4f98a2SYan Zheng  * get new location of data
15365d4f98a2SYan Zheng  */
15375d4f98a2SYan Zheng static int get_new_location(struct inode *reloc_inode, u64 *new_bytenr,
15385d4f98a2SYan Zheng 			    u64 bytenr, u64 num_bytes)
15395d4f98a2SYan Zheng {
15405d4f98a2SYan Zheng 	struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
15415d4f98a2SYan Zheng 	struct btrfs_path *path;
15425d4f98a2SYan Zheng 	struct btrfs_file_extent_item *fi;
15435d4f98a2SYan Zheng 	struct extent_buffer *leaf;
15445d4f98a2SYan Zheng 	int ret;
15455d4f98a2SYan Zheng 
15465d4f98a2SYan Zheng 	path = btrfs_alloc_path();
15475d4f98a2SYan Zheng 	if (!path)
15485d4f98a2SYan Zheng 		return -ENOMEM;
15495d4f98a2SYan Zheng 
15505d4f98a2SYan Zheng 	bytenr -= BTRFS_I(reloc_inode)->index_cnt;
1551f85b7379SDavid Sterba 	ret = btrfs_lookup_file_extent(NULL, root, path,
1552f85b7379SDavid Sterba 			btrfs_ino(BTRFS_I(reloc_inode)), bytenr, 0);
15535d4f98a2SYan Zheng 	if (ret < 0)
15545d4f98a2SYan Zheng 		goto out;
15555d4f98a2SYan Zheng 	if (ret > 0) {
15565d4f98a2SYan Zheng 		ret = -ENOENT;
15575d4f98a2SYan Zheng 		goto out;
15585d4f98a2SYan Zheng 	}
15595d4f98a2SYan Zheng 
15605d4f98a2SYan Zheng 	leaf = path->nodes[0];
15615d4f98a2SYan Zheng 	fi = btrfs_item_ptr(leaf, path->slots[0],
15625d4f98a2SYan Zheng 			    struct btrfs_file_extent_item);
15635d4f98a2SYan Zheng 
15645d4f98a2SYan Zheng 	BUG_ON(btrfs_file_extent_offset(leaf, fi) ||
15655d4f98a2SYan Zheng 	       btrfs_file_extent_compression(leaf, fi) ||
15665d4f98a2SYan Zheng 	       btrfs_file_extent_encryption(leaf, fi) ||
15675d4f98a2SYan Zheng 	       btrfs_file_extent_other_encoding(leaf, fi));
15685d4f98a2SYan Zheng 
15695d4f98a2SYan Zheng 	if (num_bytes != btrfs_file_extent_disk_num_bytes(leaf, fi)) {
157083d4cfd4SJosef Bacik 		ret = -EINVAL;
15715d4f98a2SYan Zheng 		goto out;
15725d4f98a2SYan Zheng 	}
15735d4f98a2SYan Zheng 
15745d4f98a2SYan Zheng 	*new_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
15755d4f98a2SYan Zheng 	ret = 0;
15765d4f98a2SYan Zheng out:
15775d4f98a2SYan Zheng 	btrfs_free_path(path);
15785d4f98a2SYan Zheng 	return ret;
15795d4f98a2SYan Zheng }
15805d4f98a2SYan Zheng 
15815d4f98a2SYan Zheng /*
15825d4f98a2SYan Zheng  * update file extent items in the tree leaf to point to
15835d4f98a2SYan Zheng  * the new locations.
15845d4f98a2SYan Zheng  */
15853fd0a558SYan, Zheng static noinline_for_stack
15863fd0a558SYan, Zheng int replace_file_extents(struct btrfs_trans_handle *trans,
15875d4f98a2SYan Zheng 			 struct reloc_control *rc,
15885d4f98a2SYan Zheng 			 struct btrfs_root *root,
15893fd0a558SYan, Zheng 			 struct extent_buffer *leaf)
15905d4f98a2SYan Zheng {
15910b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15925d4f98a2SYan Zheng 	struct btrfs_key key;
15935d4f98a2SYan Zheng 	struct btrfs_file_extent_item *fi;
15945d4f98a2SYan Zheng 	struct inode *inode = NULL;
15955d4f98a2SYan Zheng 	u64 parent;
15965d4f98a2SYan Zheng 	u64 bytenr;
15973fd0a558SYan, Zheng 	u64 new_bytenr = 0;
15985d4f98a2SYan Zheng 	u64 num_bytes;
15995d4f98a2SYan Zheng 	u64 end;
16005d4f98a2SYan Zheng 	u32 nritems;
16015d4f98a2SYan Zheng 	u32 i;
160283d4cfd4SJosef Bacik 	int ret = 0;
16035d4f98a2SYan Zheng 	int first = 1;
16045d4f98a2SYan Zheng 	int dirty = 0;
16055d4f98a2SYan Zheng 
16065d4f98a2SYan Zheng 	if (rc->stage != UPDATE_DATA_PTRS)
16075d4f98a2SYan Zheng 		return 0;
16085d4f98a2SYan Zheng 
16095d4f98a2SYan Zheng 	/* reloc trees always use full backref */
16105d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
16115d4f98a2SYan Zheng 		parent = leaf->start;
16125d4f98a2SYan Zheng 	else
16135d4f98a2SYan Zheng 		parent = 0;
16145d4f98a2SYan Zheng 
16155d4f98a2SYan Zheng 	nritems = btrfs_header_nritems(leaf);
16165d4f98a2SYan Zheng 	for (i = 0; i < nritems; i++) {
161782fa113fSQu Wenruo 		struct btrfs_ref ref = { 0 };
161882fa113fSQu Wenruo 
16195d4f98a2SYan Zheng 		cond_resched();
16205d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, i);
16215d4f98a2SYan Zheng 		if (key.type != BTRFS_EXTENT_DATA_KEY)
16225d4f98a2SYan Zheng 			continue;
16235d4f98a2SYan Zheng 		fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
16245d4f98a2SYan Zheng 		if (btrfs_file_extent_type(leaf, fi) ==
16255d4f98a2SYan Zheng 		    BTRFS_FILE_EXTENT_INLINE)
16265d4f98a2SYan Zheng 			continue;
16275d4f98a2SYan Zheng 		bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
16285d4f98a2SYan Zheng 		num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
16295d4f98a2SYan Zheng 		if (bytenr == 0)
16305d4f98a2SYan Zheng 			continue;
16319569cc20SQu Wenruo 		if (!in_range(bytenr, rc->block_group->start,
16329569cc20SQu Wenruo 			      rc->block_group->length))
16335d4f98a2SYan Zheng 			continue;
16345d4f98a2SYan Zheng 
16355d4f98a2SYan Zheng 		/*
16365d4f98a2SYan Zheng 		 * if we are modifying block in fs tree, wait for readpage
16375d4f98a2SYan Zheng 		 * to complete and drop the extent cache
16385d4f98a2SYan Zheng 		 */
16395d4f98a2SYan Zheng 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
16405d4f98a2SYan Zheng 			if (first) {
16415d4f98a2SYan Zheng 				inode = find_next_inode(root, key.objectid);
16425d4f98a2SYan Zheng 				first = 0;
16434a0cc7caSNikolay Borisov 			} else if (inode && btrfs_ino(BTRFS_I(inode)) < key.objectid) {
16443fd0a558SYan, Zheng 				btrfs_add_delayed_iput(inode);
16455d4f98a2SYan Zheng 				inode = find_next_inode(root, key.objectid);
16465d4f98a2SYan Zheng 			}
16474a0cc7caSNikolay Borisov 			if (inode && btrfs_ino(BTRFS_I(inode)) == key.objectid) {
16485d4f98a2SYan Zheng 				end = key.offset +
16495d4f98a2SYan Zheng 				      btrfs_file_extent_num_bytes(leaf, fi);
16505d4f98a2SYan Zheng 				WARN_ON(!IS_ALIGNED(key.offset,
16510b246afaSJeff Mahoney 						    fs_info->sectorsize));
16520b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
16535d4f98a2SYan Zheng 				end--;
16545d4f98a2SYan Zheng 				ret = try_lock_extent(&BTRFS_I(inode)->io_tree,
1655d0082371SJeff Mahoney 						      key.offset, end);
16565d4f98a2SYan Zheng 				if (!ret)
16575d4f98a2SYan Zheng 					continue;
16585d4f98a2SYan Zheng 
1659dcdbc059SNikolay Borisov 				btrfs_drop_extent_cache(BTRFS_I(inode),
1660dcdbc059SNikolay Borisov 						key.offset,	end, 1);
16615d4f98a2SYan Zheng 				unlock_extent(&BTRFS_I(inode)->io_tree,
1662d0082371SJeff Mahoney 					      key.offset, end);
16635d4f98a2SYan Zheng 			}
16645d4f98a2SYan Zheng 		}
16655d4f98a2SYan Zheng 
16665d4f98a2SYan Zheng 		ret = get_new_location(rc->data_inode, &new_bytenr,
16675d4f98a2SYan Zheng 				       bytenr, num_bytes);
166883d4cfd4SJosef Bacik 		if (ret) {
166983d4cfd4SJosef Bacik 			/*
167083d4cfd4SJosef Bacik 			 * Don't have to abort since we've not changed anything
167183d4cfd4SJosef Bacik 			 * in the file extent yet.
167283d4cfd4SJosef Bacik 			 */
167383d4cfd4SJosef Bacik 			break;
16743fd0a558SYan, Zheng 		}
16755d4f98a2SYan Zheng 
16765d4f98a2SYan Zheng 		btrfs_set_file_extent_disk_bytenr(leaf, fi, new_bytenr);
16775d4f98a2SYan Zheng 		dirty = 1;
16785d4f98a2SYan Zheng 
16795d4f98a2SYan Zheng 		key.offset -= btrfs_file_extent_offset(leaf, fi);
168082fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new_bytenr,
168182fa113fSQu Wenruo 				       num_bytes, parent);
168282fa113fSQu Wenruo 		ref.real_root = root->root_key.objectid;
168382fa113fSQu Wenruo 		btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
1684b06c4bf5SFilipe Manana 				    key.objectid, key.offset);
168582fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
168683d4cfd4SJosef Bacik 		if (ret) {
168766642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
168883d4cfd4SJosef Bacik 			break;
168983d4cfd4SJosef Bacik 		}
16905d4f98a2SYan Zheng 
1691ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
1692ffd4bb2aSQu Wenruo 				       num_bytes, parent);
1693ffd4bb2aSQu Wenruo 		ref.real_root = root->root_key.objectid;
1694ffd4bb2aSQu Wenruo 		btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
1695b06c4bf5SFilipe Manana 				    key.objectid, key.offset);
1696ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
169783d4cfd4SJosef Bacik 		if (ret) {
169866642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
169983d4cfd4SJosef Bacik 			break;
170083d4cfd4SJosef Bacik 		}
17015d4f98a2SYan Zheng 	}
17025d4f98a2SYan Zheng 	if (dirty)
17035d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(leaf);
17043fd0a558SYan, Zheng 	if (inode)
17053fd0a558SYan, Zheng 		btrfs_add_delayed_iput(inode);
170683d4cfd4SJosef Bacik 	return ret;
17075d4f98a2SYan Zheng }
17085d4f98a2SYan Zheng 
17095d4f98a2SYan Zheng static noinline_for_stack
17105d4f98a2SYan Zheng int memcmp_node_keys(struct extent_buffer *eb, int slot,
17115d4f98a2SYan Zheng 		     struct btrfs_path *path, int level)
17125d4f98a2SYan Zheng {
17135d4f98a2SYan Zheng 	struct btrfs_disk_key key1;
17145d4f98a2SYan Zheng 	struct btrfs_disk_key key2;
17155d4f98a2SYan Zheng 	btrfs_node_key(eb, &key1, slot);
17165d4f98a2SYan Zheng 	btrfs_node_key(path->nodes[level], &key2, path->slots[level]);
17175d4f98a2SYan Zheng 	return memcmp(&key1, &key2, sizeof(key1));
17185d4f98a2SYan Zheng }
17195d4f98a2SYan Zheng 
17205d4f98a2SYan Zheng /*
17215d4f98a2SYan Zheng  * try to replace tree blocks in fs tree with the new blocks
17225d4f98a2SYan Zheng  * in reloc tree. tree blocks haven't been modified since the
17235d4f98a2SYan Zheng  * reloc tree was create can be replaced.
17245d4f98a2SYan Zheng  *
17255d4f98a2SYan Zheng  * if a block was replaced, level of the block + 1 is returned.
17265d4f98a2SYan Zheng  * if no block got replaced, 0 is returned. if there are other
17275d4f98a2SYan Zheng  * errors, a negative error number is returned.
17285d4f98a2SYan Zheng  */
17293fd0a558SYan, Zheng static noinline_for_stack
17303d0174f7SQu Wenruo int replace_path(struct btrfs_trans_handle *trans, struct reloc_control *rc,
17315d4f98a2SYan Zheng 		 struct btrfs_root *dest, struct btrfs_root *src,
17325d4f98a2SYan Zheng 		 struct btrfs_path *path, struct btrfs_key *next_key,
17335d4f98a2SYan Zheng 		 int lowest_level, int max_level)
17345d4f98a2SYan Zheng {
17350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = dest->fs_info;
17365d4f98a2SYan Zheng 	struct extent_buffer *eb;
17375d4f98a2SYan Zheng 	struct extent_buffer *parent;
173882fa113fSQu Wenruo 	struct btrfs_ref ref = { 0 };
17395d4f98a2SYan Zheng 	struct btrfs_key key;
17405d4f98a2SYan Zheng 	u64 old_bytenr;
17415d4f98a2SYan Zheng 	u64 new_bytenr;
17425d4f98a2SYan Zheng 	u64 old_ptr_gen;
17435d4f98a2SYan Zheng 	u64 new_ptr_gen;
17445d4f98a2SYan Zheng 	u64 last_snapshot;
17455d4f98a2SYan Zheng 	u32 blocksize;
17463fd0a558SYan, Zheng 	int cow = 0;
17475d4f98a2SYan Zheng 	int level;
17485d4f98a2SYan Zheng 	int ret;
17495d4f98a2SYan Zheng 	int slot;
17505d4f98a2SYan Zheng 
17515d4f98a2SYan Zheng 	BUG_ON(src->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
17525d4f98a2SYan Zheng 	BUG_ON(dest->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID);
17535d4f98a2SYan Zheng 
17545d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&src->root_item);
17553fd0a558SYan, Zheng again:
17565d4f98a2SYan Zheng 	slot = path->slots[lowest_level];
17575d4f98a2SYan Zheng 	btrfs_node_key_to_cpu(path->nodes[lowest_level], &key, slot);
17585d4f98a2SYan Zheng 
17595d4f98a2SYan Zheng 	eb = btrfs_lock_root_node(dest);
17608bead258SDavid Sterba 	btrfs_set_lock_blocking_write(eb);
17615d4f98a2SYan Zheng 	level = btrfs_header_level(eb);
17625d4f98a2SYan Zheng 
17635d4f98a2SYan Zheng 	if (level < lowest_level) {
17645d4f98a2SYan Zheng 		btrfs_tree_unlock(eb);
17655d4f98a2SYan Zheng 		free_extent_buffer(eb);
17665d4f98a2SYan Zheng 		return 0;
17675d4f98a2SYan Zheng 	}
17685d4f98a2SYan Zheng 
17693fd0a558SYan, Zheng 	if (cow) {
17705d4f98a2SYan Zheng 		ret = btrfs_cow_block(trans, dest, eb, NULL, 0, &eb);
17715d4f98a2SYan Zheng 		BUG_ON(ret);
17723fd0a558SYan, Zheng 	}
17738bead258SDavid Sterba 	btrfs_set_lock_blocking_write(eb);
17745d4f98a2SYan Zheng 
17755d4f98a2SYan Zheng 	if (next_key) {
17765d4f98a2SYan Zheng 		next_key->objectid = (u64)-1;
17775d4f98a2SYan Zheng 		next_key->type = (u8)-1;
17785d4f98a2SYan Zheng 		next_key->offset = (u64)-1;
17795d4f98a2SYan Zheng 	}
17805d4f98a2SYan Zheng 
17815d4f98a2SYan Zheng 	parent = eb;
17825d4f98a2SYan Zheng 	while (1) {
1783581c1760SQu Wenruo 		struct btrfs_key first_key;
1784581c1760SQu Wenruo 
17855d4f98a2SYan Zheng 		level = btrfs_header_level(parent);
17865d4f98a2SYan Zheng 		BUG_ON(level < lowest_level);
17875d4f98a2SYan Zheng 
17885d4f98a2SYan Zheng 		ret = btrfs_bin_search(parent, &key, level, &slot);
1789cbca7d59SFilipe Manana 		if (ret < 0)
1790cbca7d59SFilipe Manana 			break;
17915d4f98a2SYan Zheng 		if (ret && slot > 0)
17925d4f98a2SYan Zheng 			slot--;
17935d4f98a2SYan Zheng 
17945d4f98a2SYan Zheng 		if (next_key && slot + 1 < btrfs_header_nritems(parent))
17955d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(parent, next_key, slot + 1);
17965d4f98a2SYan Zheng 
17975d4f98a2SYan Zheng 		old_bytenr = btrfs_node_blockptr(parent, slot);
17980b246afaSJeff Mahoney 		blocksize = fs_info->nodesize;
17995d4f98a2SYan Zheng 		old_ptr_gen = btrfs_node_ptr_generation(parent, slot);
180017515f1bSQu Wenruo 		btrfs_node_key_to_cpu(parent, &first_key, slot);
18015d4f98a2SYan Zheng 
18025d4f98a2SYan Zheng 		if (level <= max_level) {
18035d4f98a2SYan Zheng 			eb = path->nodes[level];
18045d4f98a2SYan Zheng 			new_bytenr = btrfs_node_blockptr(eb,
18055d4f98a2SYan Zheng 							path->slots[level]);
18065d4f98a2SYan Zheng 			new_ptr_gen = btrfs_node_ptr_generation(eb,
18075d4f98a2SYan Zheng 							path->slots[level]);
18085d4f98a2SYan Zheng 		} else {
18095d4f98a2SYan Zheng 			new_bytenr = 0;
18105d4f98a2SYan Zheng 			new_ptr_gen = 0;
18115d4f98a2SYan Zheng 		}
18125d4f98a2SYan Zheng 
1813fae7f21cSDulshani Gunawardhana 		if (WARN_ON(new_bytenr > 0 && new_bytenr == old_bytenr)) {
18145d4f98a2SYan Zheng 			ret = level;
18155d4f98a2SYan Zheng 			break;
18165d4f98a2SYan Zheng 		}
18175d4f98a2SYan Zheng 
18185d4f98a2SYan Zheng 		if (new_bytenr == 0 || old_ptr_gen > last_snapshot ||
18195d4f98a2SYan Zheng 		    memcmp_node_keys(parent, slot, path, level)) {
18203fd0a558SYan, Zheng 			if (level <= lowest_level) {
18215d4f98a2SYan Zheng 				ret = 0;
18225d4f98a2SYan Zheng 				break;
18235d4f98a2SYan Zheng 			}
18245d4f98a2SYan Zheng 
1825581c1760SQu Wenruo 			eb = read_tree_block(fs_info, old_bytenr, old_ptr_gen,
1826581c1760SQu Wenruo 					     level - 1, &first_key);
182764c043deSLiu Bo 			if (IS_ERR(eb)) {
182864c043deSLiu Bo 				ret = PTR_ERR(eb);
1829264813acSLiu Bo 				break;
183064c043deSLiu Bo 			} else if (!extent_buffer_uptodate(eb)) {
183164c043deSLiu Bo 				ret = -EIO;
1832416bc658SJosef Bacik 				free_extent_buffer(eb);
1833379cde74SStefan Behrens 				break;
1834416bc658SJosef Bacik 			}
18355d4f98a2SYan Zheng 			btrfs_tree_lock(eb);
18363fd0a558SYan, Zheng 			if (cow) {
18375d4f98a2SYan Zheng 				ret = btrfs_cow_block(trans, dest, eb, parent,
18385d4f98a2SYan Zheng 						      slot, &eb);
18395d4f98a2SYan Zheng 				BUG_ON(ret);
18405d4f98a2SYan Zheng 			}
18418bead258SDavid Sterba 			btrfs_set_lock_blocking_write(eb);
18425d4f98a2SYan Zheng 
18435d4f98a2SYan Zheng 			btrfs_tree_unlock(parent);
18445d4f98a2SYan Zheng 			free_extent_buffer(parent);
18455d4f98a2SYan Zheng 
18465d4f98a2SYan Zheng 			parent = eb;
18475d4f98a2SYan Zheng 			continue;
18485d4f98a2SYan Zheng 		}
18495d4f98a2SYan Zheng 
18503fd0a558SYan, Zheng 		if (!cow) {
18513fd0a558SYan, Zheng 			btrfs_tree_unlock(parent);
18523fd0a558SYan, Zheng 			free_extent_buffer(parent);
18533fd0a558SYan, Zheng 			cow = 1;
18543fd0a558SYan, Zheng 			goto again;
18553fd0a558SYan, Zheng 		}
18563fd0a558SYan, Zheng 
18575d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(path->nodes[level], &key,
18585d4f98a2SYan Zheng 				      path->slots[level]);
1859b3b4aa74SDavid Sterba 		btrfs_release_path(path);
18605d4f98a2SYan Zheng 
18615d4f98a2SYan Zheng 		path->lowest_level = level;
18625d4f98a2SYan Zheng 		ret = btrfs_search_slot(trans, src, &key, path, 0, 1);
18635d4f98a2SYan Zheng 		path->lowest_level = 0;
18645d4f98a2SYan Zheng 		BUG_ON(ret);
18655d4f98a2SYan Zheng 
18665d4f98a2SYan Zheng 		/*
1867824d8dffSQu Wenruo 		 * Info qgroup to trace both subtrees.
1868824d8dffSQu Wenruo 		 *
1869824d8dffSQu Wenruo 		 * We must trace both trees.
1870824d8dffSQu Wenruo 		 * 1) Tree reloc subtree
1871824d8dffSQu Wenruo 		 *    If not traced, we will leak data numbers
1872824d8dffSQu Wenruo 		 * 2) Fs subtree
1873824d8dffSQu Wenruo 		 *    If not traced, we will double count old data
1874f616f5cdSQu Wenruo 		 *
1875f616f5cdSQu Wenruo 		 * We don't scan the subtree right now, but only record
1876f616f5cdSQu Wenruo 		 * the swapped tree blocks.
1877f616f5cdSQu Wenruo 		 * The real subtree rescan is delayed until we have new
1878f616f5cdSQu Wenruo 		 * CoW on the subtree root node before transaction commit.
1879824d8dffSQu Wenruo 		 */
1880370a11b8SQu Wenruo 		ret = btrfs_qgroup_add_swapped_blocks(trans, dest,
1881370a11b8SQu Wenruo 				rc->block_group, parent, slot,
1882370a11b8SQu Wenruo 				path->nodes[level], path->slots[level],
1883370a11b8SQu Wenruo 				last_snapshot);
1884370a11b8SQu Wenruo 		if (ret < 0)
1885370a11b8SQu Wenruo 			break;
1886824d8dffSQu Wenruo 		/*
18875d4f98a2SYan Zheng 		 * swap blocks in fs tree and reloc tree.
18885d4f98a2SYan Zheng 		 */
18895d4f98a2SYan Zheng 		btrfs_set_node_blockptr(parent, slot, new_bytenr);
18905d4f98a2SYan Zheng 		btrfs_set_node_ptr_generation(parent, slot, new_ptr_gen);
18915d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(parent);
18925d4f98a2SYan Zheng 
18935d4f98a2SYan Zheng 		btrfs_set_node_blockptr(path->nodes[level],
18945d4f98a2SYan Zheng 					path->slots[level], old_bytenr);
18955d4f98a2SYan Zheng 		btrfs_set_node_ptr_generation(path->nodes[level],
18965d4f98a2SYan Zheng 					      path->slots[level], old_ptr_gen);
18975d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(path->nodes[level]);
18985d4f98a2SYan Zheng 
189982fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, old_bytenr,
190082fa113fSQu Wenruo 				       blocksize, path->nodes[level]->start);
190182fa113fSQu Wenruo 		ref.skip_qgroup = true;
190282fa113fSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, src->root_key.objectid);
190382fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
19045d4f98a2SYan Zheng 		BUG_ON(ret);
190582fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new_bytenr,
190682fa113fSQu Wenruo 				       blocksize, 0);
190782fa113fSQu Wenruo 		ref.skip_qgroup = true;
190882fa113fSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, dest->root_key.objectid);
190982fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
19105d4f98a2SYan Zheng 		BUG_ON(ret);
19115d4f98a2SYan Zheng 
1912ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, new_bytenr,
1913ffd4bb2aSQu Wenruo 				       blocksize, path->nodes[level]->start);
1914ffd4bb2aSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, src->root_key.objectid);
1915ffd4bb2aSQu Wenruo 		ref.skip_qgroup = true;
1916ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
19175d4f98a2SYan Zheng 		BUG_ON(ret);
19185d4f98a2SYan Zheng 
1919ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, old_bytenr,
1920ffd4bb2aSQu Wenruo 				       blocksize, 0);
1921ffd4bb2aSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, dest->root_key.objectid);
1922ffd4bb2aSQu Wenruo 		ref.skip_qgroup = true;
1923ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
19245d4f98a2SYan Zheng 		BUG_ON(ret);
19255d4f98a2SYan Zheng 
19265d4f98a2SYan Zheng 		btrfs_unlock_up_safe(path, 0);
19275d4f98a2SYan Zheng 
19285d4f98a2SYan Zheng 		ret = level;
19295d4f98a2SYan Zheng 		break;
19305d4f98a2SYan Zheng 	}
19315d4f98a2SYan Zheng 	btrfs_tree_unlock(parent);
19325d4f98a2SYan Zheng 	free_extent_buffer(parent);
19335d4f98a2SYan Zheng 	return ret;
19345d4f98a2SYan Zheng }
19355d4f98a2SYan Zheng 
19365d4f98a2SYan Zheng /*
19375d4f98a2SYan Zheng  * helper to find next relocated block in reloc tree
19385d4f98a2SYan Zheng  */
19395d4f98a2SYan Zheng static noinline_for_stack
19405d4f98a2SYan Zheng int walk_up_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
19415d4f98a2SYan Zheng 		       int *level)
19425d4f98a2SYan Zheng {
19435d4f98a2SYan Zheng 	struct extent_buffer *eb;
19445d4f98a2SYan Zheng 	int i;
19455d4f98a2SYan Zheng 	u64 last_snapshot;
19465d4f98a2SYan Zheng 	u32 nritems;
19475d4f98a2SYan Zheng 
19485d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
19495d4f98a2SYan Zheng 
19505d4f98a2SYan Zheng 	for (i = 0; i < *level; i++) {
19515d4f98a2SYan Zheng 		free_extent_buffer(path->nodes[i]);
19525d4f98a2SYan Zheng 		path->nodes[i] = NULL;
19535d4f98a2SYan Zheng 	}
19545d4f98a2SYan Zheng 
19555d4f98a2SYan Zheng 	for (i = *level; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
19565d4f98a2SYan Zheng 		eb = path->nodes[i];
19575d4f98a2SYan Zheng 		nritems = btrfs_header_nritems(eb);
19585d4f98a2SYan Zheng 		while (path->slots[i] + 1 < nritems) {
19595d4f98a2SYan Zheng 			path->slots[i]++;
19605d4f98a2SYan Zheng 			if (btrfs_node_ptr_generation(eb, path->slots[i]) <=
19615d4f98a2SYan Zheng 			    last_snapshot)
19625d4f98a2SYan Zheng 				continue;
19635d4f98a2SYan Zheng 
19645d4f98a2SYan Zheng 			*level = i;
19655d4f98a2SYan Zheng 			return 0;
19665d4f98a2SYan Zheng 		}
19675d4f98a2SYan Zheng 		free_extent_buffer(path->nodes[i]);
19685d4f98a2SYan Zheng 		path->nodes[i] = NULL;
19695d4f98a2SYan Zheng 	}
19705d4f98a2SYan Zheng 	return 1;
19715d4f98a2SYan Zheng }
19725d4f98a2SYan Zheng 
19735d4f98a2SYan Zheng /*
19745d4f98a2SYan Zheng  * walk down reloc tree to find relocated block of lowest level
19755d4f98a2SYan Zheng  */
19765d4f98a2SYan Zheng static noinline_for_stack
19775d4f98a2SYan Zheng int walk_down_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
19785d4f98a2SYan Zheng 			 int *level)
19795d4f98a2SYan Zheng {
19802ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
19815d4f98a2SYan Zheng 	struct extent_buffer *eb = NULL;
19825d4f98a2SYan Zheng 	int i;
19835d4f98a2SYan Zheng 	u64 bytenr;
19845d4f98a2SYan Zheng 	u64 ptr_gen = 0;
19855d4f98a2SYan Zheng 	u64 last_snapshot;
19865d4f98a2SYan Zheng 	u32 nritems;
19875d4f98a2SYan Zheng 
19885d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
19895d4f98a2SYan Zheng 
19905d4f98a2SYan Zheng 	for (i = *level; i > 0; i--) {
1991581c1760SQu Wenruo 		struct btrfs_key first_key;
1992581c1760SQu Wenruo 
19935d4f98a2SYan Zheng 		eb = path->nodes[i];
19945d4f98a2SYan Zheng 		nritems = btrfs_header_nritems(eb);
19955d4f98a2SYan Zheng 		while (path->slots[i] < nritems) {
19965d4f98a2SYan Zheng 			ptr_gen = btrfs_node_ptr_generation(eb, path->slots[i]);
19975d4f98a2SYan Zheng 			if (ptr_gen > last_snapshot)
19985d4f98a2SYan Zheng 				break;
19995d4f98a2SYan Zheng 			path->slots[i]++;
20005d4f98a2SYan Zheng 		}
20015d4f98a2SYan Zheng 		if (path->slots[i] >= nritems) {
20025d4f98a2SYan Zheng 			if (i == *level)
20035d4f98a2SYan Zheng 				break;
20045d4f98a2SYan Zheng 			*level = i + 1;
20055d4f98a2SYan Zheng 			return 0;
20065d4f98a2SYan Zheng 		}
20075d4f98a2SYan Zheng 		if (i == 1) {
20085d4f98a2SYan Zheng 			*level = i;
20095d4f98a2SYan Zheng 			return 0;
20105d4f98a2SYan Zheng 		}
20115d4f98a2SYan Zheng 
20125d4f98a2SYan Zheng 		bytenr = btrfs_node_blockptr(eb, path->slots[i]);
2013581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &first_key, path->slots[i]);
2014581c1760SQu Wenruo 		eb = read_tree_block(fs_info, bytenr, ptr_gen, i - 1,
2015581c1760SQu Wenruo 				     &first_key);
201664c043deSLiu Bo 		if (IS_ERR(eb)) {
201764c043deSLiu Bo 			return PTR_ERR(eb);
201864c043deSLiu Bo 		} else if (!extent_buffer_uptodate(eb)) {
2019416bc658SJosef Bacik 			free_extent_buffer(eb);
2020416bc658SJosef Bacik 			return -EIO;
2021416bc658SJosef Bacik 		}
20225d4f98a2SYan Zheng 		BUG_ON(btrfs_header_level(eb) != i - 1);
20235d4f98a2SYan Zheng 		path->nodes[i - 1] = eb;
20245d4f98a2SYan Zheng 		path->slots[i - 1] = 0;
20255d4f98a2SYan Zheng 	}
20265d4f98a2SYan Zheng 	return 1;
20275d4f98a2SYan Zheng }
20285d4f98a2SYan Zheng 
20295d4f98a2SYan Zheng /*
20305d4f98a2SYan Zheng  * invalidate extent cache for file extents whose key in range of
20315d4f98a2SYan Zheng  * [min_key, max_key)
20325d4f98a2SYan Zheng  */
20335d4f98a2SYan Zheng static int invalidate_extent_cache(struct btrfs_root *root,
20345d4f98a2SYan Zheng 				   struct btrfs_key *min_key,
20355d4f98a2SYan Zheng 				   struct btrfs_key *max_key)
20365d4f98a2SYan Zheng {
20370b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
20385d4f98a2SYan Zheng 	struct inode *inode = NULL;
20395d4f98a2SYan Zheng 	u64 objectid;
20405d4f98a2SYan Zheng 	u64 start, end;
204133345d01SLi Zefan 	u64 ino;
20425d4f98a2SYan Zheng 
20435d4f98a2SYan Zheng 	objectid = min_key->objectid;
20445d4f98a2SYan Zheng 	while (1) {
20455d4f98a2SYan Zheng 		cond_resched();
20465d4f98a2SYan Zheng 		iput(inode);
20475d4f98a2SYan Zheng 
20485d4f98a2SYan Zheng 		if (objectid > max_key->objectid)
20495d4f98a2SYan Zheng 			break;
20505d4f98a2SYan Zheng 
20515d4f98a2SYan Zheng 		inode = find_next_inode(root, objectid);
20525d4f98a2SYan Zheng 		if (!inode)
20535d4f98a2SYan Zheng 			break;
20544a0cc7caSNikolay Borisov 		ino = btrfs_ino(BTRFS_I(inode));
20555d4f98a2SYan Zheng 
205633345d01SLi Zefan 		if (ino > max_key->objectid) {
20575d4f98a2SYan Zheng 			iput(inode);
20585d4f98a2SYan Zheng 			break;
20595d4f98a2SYan Zheng 		}
20605d4f98a2SYan Zheng 
206133345d01SLi Zefan 		objectid = ino + 1;
20625d4f98a2SYan Zheng 		if (!S_ISREG(inode->i_mode))
20635d4f98a2SYan Zheng 			continue;
20645d4f98a2SYan Zheng 
206533345d01SLi Zefan 		if (unlikely(min_key->objectid == ino)) {
20665d4f98a2SYan Zheng 			if (min_key->type > BTRFS_EXTENT_DATA_KEY)
20675d4f98a2SYan Zheng 				continue;
20685d4f98a2SYan Zheng 			if (min_key->type < BTRFS_EXTENT_DATA_KEY)
20695d4f98a2SYan Zheng 				start = 0;
20705d4f98a2SYan Zheng 			else {
20715d4f98a2SYan Zheng 				start = min_key->offset;
20720b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(start, fs_info->sectorsize));
20735d4f98a2SYan Zheng 			}
20745d4f98a2SYan Zheng 		} else {
20755d4f98a2SYan Zheng 			start = 0;
20765d4f98a2SYan Zheng 		}
20775d4f98a2SYan Zheng 
207833345d01SLi Zefan 		if (unlikely(max_key->objectid == ino)) {
20795d4f98a2SYan Zheng 			if (max_key->type < BTRFS_EXTENT_DATA_KEY)
20805d4f98a2SYan Zheng 				continue;
20815d4f98a2SYan Zheng 			if (max_key->type > BTRFS_EXTENT_DATA_KEY) {
20825d4f98a2SYan Zheng 				end = (u64)-1;
20835d4f98a2SYan Zheng 			} else {
20845d4f98a2SYan Zheng 				if (max_key->offset == 0)
20855d4f98a2SYan Zheng 					continue;
20865d4f98a2SYan Zheng 				end = max_key->offset;
20870b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
20885d4f98a2SYan Zheng 				end--;
20895d4f98a2SYan Zheng 			}
20905d4f98a2SYan Zheng 		} else {
20915d4f98a2SYan Zheng 			end = (u64)-1;
20925d4f98a2SYan Zheng 		}
20935d4f98a2SYan Zheng 
20945d4f98a2SYan Zheng 		/* the lock_extent waits for readpage to complete */
2095d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, start, end);
2096dcdbc059SNikolay Borisov 		btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 1);
2097d0082371SJeff Mahoney 		unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
20985d4f98a2SYan Zheng 	}
20995d4f98a2SYan Zheng 	return 0;
21005d4f98a2SYan Zheng }
21015d4f98a2SYan Zheng 
21025d4f98a2SYan Zheng static int find_next_key(struct btrfs_path *path, int level,
21035d4f98a2SYan Zheng 			 struct btrfs_key *key)
21045d4f98a2SYan Zheng 
21055d4f98a2SYan Zheng {
21065d4f98a2SYan Zheng 	while (level < BTRFS_MAX_LEVEL) {
21075d4f98a2SYan Zheng 		if (!path->nodes[level])
21085d4f98a2SYan Zheng 			break;
21095d4f98a2SYan Zheng 		if (path->slots[level] + 1 <
21105d4f98a2SYan Zheng 		    btrfs_header_nritems(path->nodes[level])) {
21115d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(path->nodes[level], key,
21125d4f98a2SYan Zheng 					      path->slots[level] + 1);
21135d4f98a2SYan Zheng 			return 0;
21145d4f98a2SYan Zheng 		}
21155d4f98a2SYan Zheng 		level++;
21165d4f98a2SYan Zheng 	}
21175d4f98a2SYan Zheng 	return 1;
21185d4f98a2SYan Zheng }
21195d4f98a2SYan Zheng 
21205d4f98a2SYan Zheng /*
2121d2311e69SQu Wenruo  * Insert current subvolume into reloc_control::dirty_subvol_roots
2122d2311e69SQu Wenruo  */
2123d2311e69SQu Wenruo static void insert_dirty_subvol(struct btrfs_trans_handle *trans,
2124d2311e69SQu Wenruo 				struct reloc_control *rc,
2125d2311e69SQu Wenruo 				struct btrfs_root *root)
2126d2311e69SQu Wenruo {
2127d2311e69SQu Wenruo 	struct btrfs_root *reloc_root = root->reloc_root;
2128d2311e69SQu Wenruo 	struct btrfs_root_item *reloc_root_item;
2129d2311e69SQu Wenruo 
2130d2311e69SQu Wenruo 	/* @root must be a subvolume tree root with a valid reloc tree */
2131d2311e69SQu Wenruo 	ASSERT(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
2132d2311e69SQu Wenruo 	ASSERT(reloc_root);
2133d2311e69SQu Wenruo 
2134d2311e69SQu Wenruo 	reloc_root_item = &reloc_root->root_item;
2135d2311e69SQu Wenruo 	memset(&reloc_root_item->drop_progress, 0,
2136d2311e69SQu Wenruo 		sizeof(reloc_root_item->drop_progress));
2137d2311e69SQu Wenruo 	reloc_root_item->drop_level = 0;
2138d2311e69SQu Wenruo 	btrfs_set_root_refs(reloc_root_item, 0);
2139d2311e69SQu Wenruo 	btrfs_update_reloc_root(trans, root);
2140d2311e69SQu Wenruo 
2141d2311e69SQu Wenruo 	if (list_empty(&root->reloc_dirty_list)) {
214200246528SJosef Bacik 		btrfs_grab_root(root);
2143d2311e69SQu Wenruo 		list_add_tail(&root->reloc_dirty_list, &rc->dirty_subvol_roots);
2144d2311e69SQu Wenruo 	}
2145d2311e69SQu Wenruo }
2146d2311e69SQu Wenruo 
2147d2311e69SQu Wenruo static int clean_dirty_subvols(struct reloc_control *rc)
2148d2311e69SQu Wenruo {
2149d2311e69SQu Wenruo 	struct btrfs_root *root;
2150d2311e69SQu Wenruo 	struct btrfs_root *next;
2151d2311e69SQu Wenruo 	int ret = 0;
215230d40577SQu Wenruo 	int ret2;
2153d2311e69SQu Wenruo 
2154d2311e69SQu Wenruo 	list_for_each_entry_safe(root, next, &rc->dirty_subvol_roots,
2155d2311e69SQu Wenruo 				 reloc_dirty_list) {
215630d40577SQu Wenruo 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
215730d40577SQu Wenruo 			/* Merged subvolume, cleanup its reloc root */
2158d2311e69SQu Wenruo 			struct btrfs_root *reloc_root = root->reloc_root;
2159d2311e69SQu Wenruo 
2160d2311e69SQu Wenruo 			list_del_init(&root->reloc_dirty_list);
2161d2311e69SQu Wenruo 			root->reloc_root = NULL;
21626282675eSQu Wenruo 			/*
21636282675eSQu Wenruo 			 * Need barrier to ensure clear_bit() only happens after
21646282675eSQu Wenruo 			 * root->reloc_root = NULL. Pairs with have_reloc_root.
21656282675eSQu Wenruo 			 */
21666282675eSQu Wenruo 			smp_wmb();
21671fac4a54SQu Wenruo 			clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
2168f28de8d8SJosef Bacik 			if (reloc_root) {
2169f44deb74SJosef Bacik 				/*
2170f44deb74SJosef Bacik 				 * btrfs_drop_snapshot drops our ref we hold for
2171f44deb74SJosef Bacik 				 * ->reloc_root.  If it fails however we must
2172f44deb74SJosef Bacik 				 * drop the ref ourselves.
2173f44deb74SJosef Bacik 				 */
2174f28de8d8SJosef Bacik 				ret2 = btrfs_drop_snapshot(reloc_root, 0, 1);
2175f44deb74SJosef Bacik 				if (ret2 < 0) {
2176f44deb74SJosef Bacik 					btrfs_put_root(reloc_root);
2177f44deb74SJosef Bacik 					if (!ret)
2178f28de8d8SJosef Bacik 						ret = ret2;
2179f28de8d8SJosef Bacik 				}
2180f44deb74SJosef Bacik 			}
218100246528SJosef Bacik 			btrfs_put_root(root);
218230d40577SQu Wenruo 		} else {
218330d40577SQu Wenruo 			/* Orphan reloc tree, just clean it up */
21840078a9f9SNikolay Borisov 			ret2 = btrfs_drop_snapshot(root, 0, 1);
2185f44deb74SJosef Bacik 			if (ret2 < 0) {
2186f44deb74SJosef Bacik 				btrfs_put_root(root);
2187f44deb74SJosef Bacik 				if (!ret)
218830d40577SQu Wenruo 					ret = ret2;
218930d40577SQu Wenruo 			}
2190d2311e69SQu Wenruo 		}
2191f44deb74SJosef Bacik 	}
2192d2311e69SQu Wenruo 	return ret;
2193d2311e69SQu Wenruo }
2194d2311e69SQu Wenruo 
2195d2311e69SQu Wenruo /*
21965d4f98a2SYan Zheng  * merge the relocated tree blocks in reloc tree with corresponding
21975d4f98a2SYan Zheng  * fs tree.
21985d4f98a2SYan Zheng  */
21995d4f98a2SYan Zheng static noinline_for_stack int merge_reloc_root(struct reloc_control *rc,
22005d4f98a2SYan Zheng 					       struct btrfs_root *root)
22015d4f98a2SYan Zheng {
22020b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
22035d4f98a2SYan Zheng 	struct btrfs_key key;
22045d4f98a2SYan Zheng 	struct btrfs_key next_key;
22059e6a0c52SJosef Bacik 	struct btrfs_trans_handle *trans = NULL;
22065d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
22075d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
22085d4f98a2SYan Zheng 	struct btrfs_path *path;
22093fd0a558SYan, Zheng 	struct extent_buffer *leaf;
22105d4f98a2SYan Zheng 	int level;
22115d4f98a2SYan Zheng 	int max_level;
22125d4f98a2SYan Zheng 	int replaced = 0;
22135d4f98a2SYan Zheng 	int ret;
22145d4f98a2SYan Zheng 	int err = 0;
22153fd0a558SYan, Zheng 	u32 min_reserved;
22165d4f98a2SYan Zheng 
22175d4f98a2SYan Zheng 	path = btrfs_alloc_path();
22185d4f98a2SYan Zheng 	if (!path)
22195d4f98a2SYan Zheng 		return -ENOMEM;
2220e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
22215d4f98a2SYan Zheng 
22225d4f98a2SYan Zheng 	reloc_root = root->reloc_root;
22235d4f98a2SYan Zheng 	root_item = &reloc_root->root_item;
22245d4f98a2SYan Zheng 
22255d4f98a2SYan Zheng 	if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
22265d4f98a2SYan Zheng 		level = btrfs_root_level(root_item);
222767439dadSDavid Sterba 		atomic_inc(&reloc_root->node->refs);
22285d4f98a2SYan Zheng 		path->nodes[level] = reloc_root->node;
22295d4f98a2SYan Zheng 		path->slots[level] = 0;
22305d4f98a2SYan Zheng 	} else {
22315d4f98a2SYan Zheng 		btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
22325d4f98a2SYan Zheng 
22335d4f98a2SYan Zheng 		level = root_item->drop_level;
22345d4f98a2SYan Zheng 		BUG_ON(level == 0);
22355d4f98a2SYan Zheng 		path->lowest_level = level;
22365d4f98a2SYan Zheng 		ret = btrfs_search_slot(NULL, reloc_root, &key, path, 0, 0);
223733c66f43SYan Zheng 		path->lowest_level = 0;
22385d4f98a2SYan Zheng 		if (ret < 0) {
22395d4f98a2SYan Zheng 			btrfs_free_path(path);
22405d4f98a2SYan Zheng 			return ret;
22415d4f98a2SYan Zheng 		}
22425d4f98a2SYan Zheng 
22435d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(path->nodes[level], &next_key,
22445d4f98a2SYan Zheng 				      path->slots[level]);
22455d4f98a2SYan Zheng 		WARN_ON(memcmp(&key, &next_key, sizeof(key)));
22465d4f98a2SYan Zheng 
22475d4f98a2SYan Zheng 		btrfs_unlock_up_safe(path, 0);
22485d4f98a2SYan Zheng 	}
22495d4f98a2SYan Zheng 
22500b246afaSJeff Mahoney 	min_reserved = fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
22515d4f98a2SYan Zheng 	memset(&next_key, 0, sizeof(next_key));
22525d4f98a2SYan Zheng 
22535d4f98a2SYan Zheng 	while (1) {
225408e007d2SMiao Xie 		ret = btrfs_block_rsv_refill(root, rc->block_rsv, min_reserved,
225508e007d2SMiao Xie 					     BTRFS_RESERVE_FLUSH_ALL);
22563fd0a558SYan, Zheng 		if (ret) {
22579e6a0c52SJosef Bacik 			err = ret;
22589e6a0c52SJosef Bacik 			goto out;
22593fd0a558SYan, Zheng 		}
22609e6a0c52SJosef Bacik 		trans = btrfs_start_transaction(root, 0);
22619e6a0c52SJosef Bacik 		if (IS_ERR(trans)) {
22629e6a0c52SJosef Bacik 			err = PTR_ERR(trans);
22639e6a0c52SJosef Bacik 			trans = NULL;
22649e6a0c52SJosef Bacik 			goto out;
22659e6a0c52SJosef Bacik 		}
22662abc726aSJosef Bacik 
22672abc726aSJosef Bacik 		/*
22682abc726aSJosef Bacik 		 * At this point we no longer have a reloc_control, so we can't
22692abc726aSJosef Bacik 		 * depend on btrfs_init_reloc_root to update our last_trans.
22702abc726aSJosef Bacik 		 *
22712abc726aSJosef Bacik 		 * But that's ok, we started the trans handle on our
22722abc726aSJosef Bacik 		 * corresponding fs_root, which means it's been added to the
22732abc726aSJosef Bacik 		 * dirty list.  At commit time we'll still call
22742abc726aSJosef Bacik 		 * btrfs_update_reloc_root() and update our root item
22752abc726aSJosef Bacik 		 * appropriately.
22762abc726aSJosef Bacik 		 */
22772abc726aSJosef Bacik 		reloc_root->last_trans = trans->transid;
22789e6a0c52SJosef Bacik 		trans->block_rsv = rc->block_rsv;
22793fd0a558SYan, Zheng 
22803fd0a558SYan, Zheng 		replaced = 0;
22815d4f98a2SYan Zheng 		max_level = level;
22825d4f98a2SYan Zheng 
22835d4f98a2SYan Zheng 		ret = walk_down_reloc_tree(reloc_root, path, &level);
22845d4f98a2SYan Zheng 		if (ret < 0) {
22855d4f98a2SYan Zheng 			err = ret;
22865d4f98a2SYan Zheng 			goto out;
22875d4f98a2SYan Zheng 		}
22885d4f98a2SYan Zheng 		if (ret > 0)
22895d4f98a2SYan Zheng 			break;
22905d4f98a2SYan Zheng 
22915d4f98a2SYan Zheng 		if (!find_next_key(path, level, &key) &&
22925d4f98a2SYan Zheng 		    btrfs_comp_cpu_keys(&next_key, &key) >= 0) {
22935d4f98a2SYan Zheng 			ret = 0;
22945d4f98a2SYan Zheng 		} else {
22953d0174f7SQu Wenruo 			ret = replace_path(trans, rc, root, reloc_root, path,
22963fd0a558SYan, Zheng 					   &next_key, level, max_level);
22975d4f98a2SYan Zheng 		}
22985d4f98a2SYan Zheng 		if (ret < 0) {
22995d4f98a2SYan Zheng 			err = ret;
23005d4f98a2SYan Zheng 			goto out;
23015d4f98a2SYan Zheng 		}
23025d4f98a2SYan Zheng 
23035d4f98a2SYan Zheng 		if (ret > 0) {
23045d4f98a2SYan Zheng 			level = ret;
23055d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(path->nodes[level], &key,
23065d4f98a2SYan Zheng 					      path->slots[level]);
23075d4f98a2SYan Zheng 			replaced = 1;
23085d4f98a2SYan Zheng 		}
23095d4f98a2SYan Zheng 
23105d4f98a2SYan Zheng 		ret = walk_up_reloc_tree(reloc_root, path, &level);
23115d4f98a2SYan Zheng 		if (ret > 0)
23125d4f98a2SYan Zheng 			break;
23135d4f98a2SYan Zheng 
23145d4f98a2SYan Zheng 		BUG_ON(level == 0);
23155d4f98a2SYan Zheng 		/*
23165d4f98a2SYan Zheng 		 * save the merging progress in the drop_progress.
23175d4f98a2SYan Zheng 		 * this is OK since root refs == 1 in this case.
23185d4f98a2SYan Zheng 		 */
23195d4f98a2SYan Zheng 		btrfs_node_key(path->nodes[level], &root_item->drop_progress,
23205d4f98a2SYan Zheng 			       path->slots[level]);
23215d4f98a2SYan Zheng 		root_item->drop_level = level;
23225d4f98a2SYan Zheng 
23233a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
23249e6a0c52SJosef Bacik 		trans = NULL;
23255d4f98a2SYan Zheng 
23262ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
23275d4f98a2SYan Zheng 
23285d4f98a2SYan Zheng 		if (replaced && rc->stage == UPDATE_DATA_PTRS)
23295d4f98a2SYan Zheng 			invalidate_extent_cache(root, &key, &next_key);
23305d4f98a2SYan Zheng 	}
23315d4f98a2SYan Zheng 
23325d4f98a2SYan Zheng 	/*
23335d4f98a2SYan Zheng 	 * handle the case only one block in the fs tree need to be
23345d4f98a2SYan Zheng 	 * relocated and the block is tree root.
23355d4f98a2SYan Zheng 	 */
23365d4f98a2SYan Zheng 	leaf = btrfs_lock_root_node(root);
23375d4f98a2SYan Zheng 	ret = btrfs_cow_block(trans, root, leaf, NULL, 0, &leaf);
23385d4f98a2SYan Zheng 	btrfs_tree_unlock(leaf);
23395d4f98a2SYan Zheng 	free_extent_buffer(leaf);
23405d4f98a2SYan Zheng 	if (ret < 0)
23415d4f98a2SYan Zheng 		err = ret;
23425d4f98a2SYan Zheng out:
23435d4f98a2SYan Zheng 	btrfs_free_path(path);
23445d4f98a2SYan Zheng 
2345d2311e69SQu Wenruo 	if (err == 0)
2346d2311e69SQu Wenruo 		insert_dirty_subvol(trans, rc, root);
23475d4f98a2SYan Zheng 
23489e6a0c52SJosef Bacik 	if (trans)
23493a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
23505d4f98a2SYan Zheng 
23512ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
23525d4f98a2SYan Zheng 
23535d4f98a2SYan Zheng 	if (replaced && rc->stage == UPDATE_DATA_PTRS)
23545d4f98a2SYan Zheng 		invalidate_extent_cache(root, &key, &next_key);
23555d4f98a2SYan Zheng 
23565d4f98a2SYan Zheng 	return err;
23575d4f98a2SYan Zheng }
23585d4f98a2SYan Zheng 
23593fd0a558SYan, Zheng static noinline_for_stack
23603fd0a558SYan, Zheng int prepare_to_merge(struct reloc_control *rc, int err)
23615d4f98a2SYan Zheng {
23623fd0a558SYan, Zheng 	struct btrfs_root *root = rc->extent_root;
23630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
23643fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
23655d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
23663fd0a558SYan, Zheng 	LIST_HEAD(reloc_roots);
23673fd0a558SYan, Zheng 	u64 num_bytes = 0;
23683fd0a558SYan, Zheng 	int ret;
23693fd0a558SYan, Zheng 
23700b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
23710b246afaSJeff Mahoney 	rc->merging_rsv_size += fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
23723fd0a558SYan, Zheng 	rc->merging_rsv_size += rc->nodes_relocated * 2;
23730b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
23747585717fSChris Mason 
23753fd0a558SYan, Zheng again:
23763fd0a558SYan, Zheng 	if (!err) {
23773fd0a558SYan, Zheng 		num_bytes = rc->merging_rsv_size;
237808e007d2SMiao Xie 		ret = btrfs_block_rsv_add(root, rc->block_rsv, num_bytes,
237908e007d2SMiao Xie 					  BTRFS_RESERVE_FLUSH_ALL);
23803fd0a558SYan, Zheng 		if (ret)
23813fd0a558SYan, Zheng 			err = ret;
23823fd0a558SYan, Zheng 	}
23833fd0a558SYan, Zheng 
23847a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
23853612b495STsutomu Itoh 	if (IS_ERR(trans)) {
23863612b495STsutomu Itoh 		if (!err)
23872ff7e61eSJeff Mahoney 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
238863f018beSNikolay Borisov 						num_bytes, NULL);
23893612b495STsutomu Itoh 		return PTR_ERR(trans);
23903612b495STsutomu Itoh 	}
23913fd0a558SYan, Zheng 
23923fd0a558SYan, Zheng 	if (!err) {
23933fd0a558SYan, Zheng 		if (num_bytes != rc->merging_rsv_size) {
23943a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
23952ff7e61eSJeff Mahoney 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
239663f018beSNikolay Borisov 						num_bytes, NULL);
23973fd0a558SYan, Zheng 			goto again;
23983fd0a558SYan, Zheng 		}
23993fd0a558SYan, Zheng 	}
24003fd0a558SYan, Zheng 
24013fd0a558SYan, Zheng 	rc->merge_reloc_tree = 1;
24023fd0a558SYan, Zheng 
24033fd0a558SYan, Zheng 	while (!list_empty(&rc->reloc_roots)) {
24043fd0a558SYan, Zheng 		reloc_root = list_entry(rc->reloc_roots.next,
24053fd0a558SYan, Zheng 					struct btrfs_root, root_list);
24063fd0a558SYan, Zheng 		list_del_init(&reloc_root->root_list);
24073fd0a558SYan, Zheng 
24080b246afaSJeff Mahoney 		root = read_fs_root(fs_info, reloc_root->root_key.offset);
24093fd0a558SYan, Zheng 		BUG_ON(IS_ERR(root));
24103fd0a558SYan, Zheng 		BUG_ON(root->reloc_root != reloc_root);
24113fd0a558SYan, Zheng 
24123fd0a558SYan, Zheng 		/*
24133fd0a558SYan, Zheng 		 * set reference count to 1, so btrfs_recover_relocation
24143fd0a558SYan, Zheng 		 * knows it should resumes merging
24153fd0a558SYan, Zheng 		 */
24163fd0a558SYan, Zheng 		if (!err)
24173fd0a558SYan, Zheng 			btrfs_set_root_refs(&reloc_root->root_item, 1);
24183fd0a558SYan, Zheng 		btrfs_update_reloc_root(trans, root);
24193fd0a558SYan, Zheng 
24203fd0a558SYan, Zheng 		list_add(&reloc_root->root_list, &reloc_roots);
242100246528SJosef Bacik 		btrfs_put_root(root);
24223fd0a558SYan, Zheng 	}
24233fd0a558SYan, Zheng 
24243fd0a558SYan, Zheng 	list_splice(&reloc_roots, &rc->reloc_roots);
24253fd0a558SYan, Zheng 
24263fd0a558SYan, Zheng 	if (!err)
24273a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
24283fd0a558SYan, Zheng 	else
24293a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
24303fd0a558SYan, Zheng 	return err;
24313fd0a558SYan, Zheng }
24323fd0a558SYan, Zheng 
24333fd0a558SYan, Zheng static noinline_for_stack
2434aca1bba6SLiu Bo void free_reloc_roots(struct list_head *list)
2435aca1bba6SLiu Bo {
2436aca1bba6SLiu Bo 	struct btrfs_root *reloc_root;
2437aca1bba6SLiu Bo 
2438aca1bba6SLiu Bo 	while (!list_empty(list)) {
2439aca1bba6SLiu Bo 		reloc_root = list_entry(list->next, struct btrfs_root,
2440aca1bba6SLiu Bo 					root_list);
2441bb166d72SNaohiro Aota 		__del_reloc_root(reloc_root);
2442aca1bba6SLiu Bo 	}
2443aca1bba6SLiu Bo }
2444aca1bba6SLiu Bo 
2445aca1bba6SLiu Bo static noinline_for_stack
244694404e82SDavid Sterba void merge_reloc_roots(struct reloc_control *rc)
24473fd0a558SYan, Zheng {
24480b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
24495d4f98a2SYan Zheng 	struct btrfs_root *root;
24505d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
24513fd0a558SYan, Zheng 	LIST_HEAD(reloc_roots);
24523fd0a558SYan, Zheng 	int found = 0;
2453aca1bba6SLiu Bo 	int ret = 0;
24543fd0a558SYan, Zheng again:
24553fd0a558SYan, Zheng 	root = rc->extent_root;
24567585717fSChris Mason 
24577585717fSChris Mason 	/*
24587585717fSChris Mason 	 * this serializes us with btrfs_record_root_in_transaction,
24597585717fSChris Mason 	 * we have to make sure nobody is in the middle of
24607585717fSChris Mason 	 * adding their roots to the list while we are
24617585717fSChris Mason 	 * doing this splice
24627585717fSChris Mason 	 */
24630b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
24643fd0a558SYan, Zheng 	list_splice_init(&rc->reloc_roots, &reloc_roots);
24650b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
24665d4f98a2SYan Zheng 
24673fd0a558SYan, Zheng 	while (!list_empty(&reloc_roots)) {
24683fd0a558SYan, Zheng 		found = 1;
24693fd0a558SYan, Zheng 		reloc_root = list_entry(reloc_roots.next,
24703fd0a558SYan, Zheng 					struct btrfs_root, root_list);
24715d4f98a2SYan Zheng 
24725d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
24730b246afaSJeff Mahoney 			root = read_fs_root(fs_info,
24745d4f98a2SYan Zheng 					    reloc_root->root_key.offset);
24755d4f98a2SYan Zheng 			BUG_ON(IS_ERR(root));
24765d4f98a2SYan Zheng 			BUG_ON(root->reloc_root != reloc_root);
24775d4f98a2SYan Zheng 
24783fd0a558SYan, Zheng 			ret = merge_reloc_root(rc, root);
247900246528SJosef Bacik 			btrfs_put_root(root);
2480b37b39cdSJosef Bacik 			if (ret) {
248125e293c2SWang Shilong 				if (list_empty(&reloc_root->root_list))
248225e293c2SWang Shilong 					list_add_tail(&reloc_root->root_list,
248325e293c2SWang Shilong 						      &reloc_roots);
2484aca1bba6SLiu Bo 				goto out;
2485b37b39cdSJosef Bacik 			}
24863fd0a558SYan, Zheng 		} else {
24873fd0a558SYan, Zheng 			list_del_init(&reloc_root->root_list);
248830d40577SQu Wenruo 			/* Don't forget to queue this reloc root for cleanup */
248930d40577SQu Wenruo 			list_add_tail(&reloc_root->reloc_dirty_list,
249030d40577SQu Wenruo 				      &rc->dirty_subvol_roots);
24913fd0a558SYan, Zheng 		}
24925d4f98a2SYan Zheng 	}
24935d4f98a2SYan Zheng 
24943fd0a558SYan, Zheng 	if (found) {
24953fd0a558SYan, Zheng 		found = 0;
24963fd0a558SYan, Zheng 		goto again;
24975d4f98a2SYan Zheng 	}
2498aca1bba6SLiu Bo out:
2499aca1bba6SLiu Bo 	if (ret) {
25000b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret, NULL);
2501aca1bba6SLiu Bo 		if (!list_empty(&reloc_roots))
2502aca1bba6SLiu Bo 			free_reloc_roots(&reloc_roots);
2503467bb1d2SWang Shilong 
2504467bb1d2SWang Shilong 		/* new reloc root may be added */
25050b246afaSJeff Mahoney 		mutex_lock(&fs_info->reloc_mutex);
2506467bb1d2SWang Shilong 		list_splice_init(&rc->reloc_roots, &reloc_roots);
25070b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
2508467bb1d2SWang Shilong 		if (!list_empty(&reloc_roots))
2509467bb1d2SWang Shilong 			free_reloc_roots(&reloc_roots);
2510aca1bba6SLiu Bo 	}
2511aca1bba6SLiu Bo 
25127b7b7431SJosef Bacik 	/*
25137b7b7431SJosef Bacik 	 * We used to have
25147b7b7431SJosef Bacik 	 *
25157b7b7431SJosef Bacik 	 * BUG_ON(!RB_EMPTY_ROOT(&rc->reloc_root_tree.rb_root));
25167b7b7431SJosef Bacik 	 *
25177b7b7431SJosef Bacik 	 * here, but it's wrong.  If we fail to start the transaction in
25187b7b7431SJosef Bacik 	 * prepare_to_merge() we will have only 0 ref reloc roots, none of which
25197b7b7431SJosef Bacik 	 * have actually been removed from the reloc_root_tree rb tree.  This is
25207b7b7431SJosef Bacik 	 * fine because we're bailing here, and we hold a reference on the root
25217b7b7431SJosef Bacik 	 * for the list that holds it, so these roots will be cleaned up when we
25227b7b7431SJosef Bacik 	 * do the reloc_dirty_list afterwards.  Meanwhile the root->reloc_root
25237b7b7431SJosef Bacik 	 * will be cleaned up on unmount.
25247b7b7431SJosef Bacik 	 *
25257b7b7431SJosef Bacik 	 * The remaining nodes will be cleaned up by free_reloc_control.
25267b7b7431SJosef Bacik 	 */
25275d4f98a2SYan Zheng }
25285d4f98a2SYan Zheng 
25295d4f98a2SYan Zheng static void free_block_list(struct rb_root *blocks)
25305d4f98a2SYan Zheng {
25315d4f98a2SYan Zheng 	struct tree_block *block;
25325d4f98a2SYan Zheng 	struct rb_node *rb_node;
25335d4f98a2SYan Zheng 	while ((rb_node = rb_first(blocks))) {
25345d4f98a2SYan Zheng 		block = rb_entry(rb_node, struct tree_block, rb_node);
25355d4f98a2SYan Zheng 		rb_erase(rb_node, blocks);
25365d4f98a2SYan Zheng 		kfree(block);
25375d4f98a2SYan Zheng 	}
25385d4f98a2SYan Zheng }
25395d4f98a2SYan Zheng 
25405d4f98a2SYan Zheng static int record_reloc_root_in_trans(struct btrfs_trans_handle *trans,
25415d4f98a2SYan Zheng 				      struct btrfs_root *reloc_root)
25425d4f98a2SYan Zheng {
25430b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = reloc_root->fs_info;
25445d4f98a2SYan Zheng 	struct btrfs_root *root;
2545442b1ac5SJosef Bacik 	int ret;
25465d4f98a2SYan Zheng 
25475d4f98a2SYan Zheng 	if (reloc_root->last_trans == trans->transid)
25485d4f98a2SYan Zheng 		return 0;
25495d4f98a2SYan Zheng 
25500b246afaSJeff Mahoney 	root = read_fs_root(fs_info, reloc_root->root_key.offset);
25515d4f98a2SYan Zheng 	BUG_ON(IS_ERR(root));
25525d4f98a2SYan Zheng 	BUG_ON(root->reloc_root != reloc_root);
2553442b1ac5SJosef Bacik 	ret = btrfs_record_root_in_trans(trans, root);
255400246528SJosef Bacik 	btrfs_put_root(root);
25555d4f98a2SYan Zheng 
2556442b1ac5SJosef Bacik 	return ret;
25575d4f98a2SYan Zheng }
25585d4f98a2SYan Zheng 
25593fd0a558SYan, Zheng static noinline_for_stack
25603fd0a558SYan, Zheng struct btrfs_root *select_reloc_root(struct btrfs_trans_handle *trans,
25613fd0a558SYan, Zheng 				     struct reloc_control *rc,
2562a26195a5SQu Wenruo 				     struct btrfs_backref_node *node,
2563a26195a5SQu Wenruo 				     struct btrfs_backref_edge *edges[])
25645d4f98a2SYan Zheng {
2565a26195a5SQu Wenruo 	struct btrfs_backref_node *next;
25665d4f98a2SYan Zheng 	struct btrfs_root *root;
25673fd0a558SYan, Zheng 	int index = 0;
25683fd0a558SYan, Zheng 
25695d4f98a2SYan Zheng 	next = node;
25705d4f98a2SYan Zheng 	while (1) {
25715d4f98a2SYan Zheng 		cond_resched();
25725d4f98a2SYan Zheng 		next = walk_up_backref(next, edges, &index);
25735d4f98a2SYan Zheng 		root = next->root;
25743fd0a558SYan, Zheng 		BUG_ON(!root);
257527cdeb70SMiao Xie 		BUG_ON(!test_bit(BTRFS_ROOT_REF_COWS, &root->state));
25765d4f98a2SYan Zheng 
25775d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
25785d4f98a2SYan Zheng 			record_reloc_root_in_trans(trans, root);
25795d4f98a2SYan Zheng 			break;
25805d4f98a2SYan Zheng 		}
25815d4f98a2SYan Zheng 
25825d4f98a2SYan Zheng 		btrfs_record_root_in_trans(trans, root);
25833fd0a558SYan, Zheng 		root = root->reloc_root;
25843fd0a558SYan, Zheng 
25853fd0a558SYan, Zheng 		if (next->new_bytenr != root->node->start) {
25863fd0a558SYan, Zheng 			BUG_ON(next->new_bytenr);
25873fd0a558SYan, Zheng 			BUG_ON(!list_empty(&next->list));
25883fd0a558SYan, Zheng 			next->new_bytenr = root->node->start;
258900246528SJosef Bacik 			btrfs_put_root(next->root);
259000246528SJosef Bacik 			next->root = btrfs_grab_root(root);
25910b530bc5SJosef Bacik 			ASSERT(next->root);
25923fd0a558SYan, Zheng 			list_add_tail(&next->list,
25933fd0a558SYan, Zheng 				      &rc->backref_cache.changed);
25949569cc20SQu Wenruo 			mark_block_processed(rc, next);
25955d4f98a2SYan Zheng 			break;
25965d4f98a2SYan Zheng 		}
25975d4f98a2SYan Zheng 
25983fd0a558SYan, Zheng 		WARN_ON(1);
25995d4f98a2SYan Zheng 		root = NULL;
26005d4f98a2SYan Zheng 		next = walk_down_backref(edges, &index);
26015d4f98a2SYan Zheng 		if (!next || next->level <= node->level)
26025d4f98a2SYan Zheng 			break;
26035d4f98a2SYan Zheng 	}
26043fd0a558SYan, Zheng 	if (!root)
26053fd0a558SYan, Zheng 		return NULL;
26065d4f98a2SYan Zheng 
26073fd0a558SYan, Zheng 	next = node;
26083fd0a558SYan, Zheng 	/* setup backref node path for btrfs_reloc_cow_block */
26093fd0a558SYan, Zheng 	while (1) {
26103fd0a558SYan, Zheng 		rc->backref_cache.path[next->level] = next;
26113fd0a558SYan, Zheng 		if (--index < 0)
26123fd0a558SYan, Zheng 			break;
26133fd0a558SYan, Zheng 		next = edges[index]->node[UPPER];
26143fd0a558SYan, Zheng 	}
26155d4f98a2SYan Zheng 	return root;
26165d4f98a2SYan Zheng }
26175d4f98a2SYan Zheng 
26183fd0a558SYan, Zheng /*
26193fd0a558SYan, Zheng  * select a tree root for relocation. return NULL if the block
26203fd0a558SYan, Zheng  * is reference counted. we should use do_relocation() in this
26213fd0a558SYan, Zheng  * case. return a tree root pointer if the block isn't reference
26223fd0a558SYan, Zheng  * counted. return -ENOENT if the block is root of reloc tree.
26233fd0a558SYan, Zheng  */
26245d4f98a2SYan Zheng static noinline_for_stack
2625a26195a5SQu Wenruo struct btrfs_root *select_one_root(struct btrfs_backref_node *node)
26265d4f98a2SYan Zheng {
2627a26195a5SQu Wenruo 	struct btrfs_backref_node *next;
26283fd0a558SYan, Zheng 	struct btrfs_root *root;
26293fd0a558SYan, Zheng 	struct btrfs_root *fs_root = NULL;
2630a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
26313fd0a558SYan, Zheng 	int index = 0;
26323fd0a558SYan, Zheng 
26333fd0a558SYan, Zheng 	next = node;
26343fd0a558SYan, Zheng 	while (1) {
26353fd0a558SYan, Zheng 		cond_resched();
26363fd0a558SYan, Zheng 		next = walk_up_backref(next, edges, &index);
26373fd0a558SYan, Zheng 		root = next->root;
26383fd0a558SYan, Zheng 		BUG_ON(!root);
26393fd0a558SYan, Zheng 
264025985edcSLucas De Marchi 		/* no other choice for non-references counted tree */
264127cdeb70SMiao Xie 		if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
26423fd0a558SYan, Zheng 			return root;
26433fd0a558SYan, Zheng 
26443fd0a558SYan, Zheng 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID)
26453fd0a558SYan, Zheng 			fs_root = root;
26463fd0a558SYan, Zheng 
26473fd0a558SYan, Zheng 		if (next != node)
26483fd0a558SYan, Zheng 			return NULL;
26493fd0a558SYan, Zheng 
26503fd0a558SYan, Zheng 		next = walk_down_backref(edges, &index);
26513fd0a558SYan, Zheng 		if (!next || next->level <= node->level)
26523fd0a558SYan, Zheng 			break;
26533fd0a558SYan, Zheng 	}
26543fd0a558SYan, Zheng 
26553fd0a558SYan, Zheng 	if (!fs_root)
26563fd0a558SYan, Zheng 		return ERR_PTR(-ENOENT);
26573fd0a558SYan, Zheng 	return fs_root;
26585d4f98a2SYan Zheng }
26595d4f98a2SYan Zheng 
26605d4f98a2SYan Zheng static noinline_for_stack
26613fd0a558SYan, Zheng u64 calcu_metadata_size(struct reloc_control *rc,
2662a26195a5SQu Wenruo 			struct btrfs_backref_node *node, int reserve)
26635d4f98a2SYan Zheng {
26640b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2665a26195a5SQu Wenruo 	struct btrfs_backref_node *next = node;
2666a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2667a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
26683fd0a558SYan, Zheng 	u64 num_bytes = 0;
26693fd0a558SYan, Zheng 	int index = 0;
26705d4f98a2SYan Zheng 
26713fd0a558SYan, Zheng 	BUG_ON(reserve && node->processed);
26723fd0a558SYan, Zheng 
26733fd0a558SYan, Zheng 	while (next) {
26743fd0a558SYan, Zheng 		cond_resched();
26755d4f98a2SYan Zheng 		while (1) {
26763fd0a558SYan, Zheng 			if (next->processed && (reserve || next != node))
26775d4f98a2SYan Zheng 				break;
26785d4f98a2SYan Zheng 
26790b246afaSJeff Mahoney 			num_bytes += fs_info->nodesize;
26803fd0a558SYan, Zheng 
26813fd0a558SYan, Zheng 			if (list_empty(&next->upper))
26823fd0a558SYan, Zheng 				break;
26833fd0a558SYan, Zheng 
26843fd0a558SYan, Zheng 			edge = list_entry(next->upper.next,
2685a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[LOWER]);
26863fd0a558SYan, Zheng 			edges[index++] = edge;
26873fd0a558SYan, Zheng 			next = edge->node[UPPER];
26885d4f98a2SYan Zheng 		}
26893fd0a558SYan, Zheng 		next = walk_down_backref(edges, &index);
26903fd0a558SYan, Zheng 	}
26913fd0a558SYan, Zheng 	return num_bytes;
26923fd0a558SYan, Zheng }
26933fd0a558SYan, Zheng 
26943fd0a558SYan, Zheng static int reserve_metadata_space(struct btrfs_trans_handle *trans,
26953fd0a558SYan, Zheng 				  struct reloc_control *rc,
2696a26195a5SQu Wenruo 				  struct btrfs_backref_node *node)
26973fd0a558SYan, Zheng {
26983fd0a558SYan, Zheng 	struct btrfs_root *root = rc->extent_root;
2699da17066cSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
27003fd0a558SYan, Zheng 	u64 num_bytes;
27013fd0a558SYan, Zheng 	int ret;
27020647bf56SWang Shilong 	u64 tmp;
27033fd0a558SYan, Zheng 
27043fd0a558SYan, Zheng 	num_bytes = calcu_metadata_size(rc, node, 1) * 2;
27053fd0a558SYan, Zheng 
27063fd0a558SYan, Zheng 	trans->block_rsv = rc->block_rsv;
27070647bf56SWang Shilong 	rc->reserved_bytes += num_bytes;
27088ca17f0fSJosef Bacik 
27098ca17f0fSJosef Bacik 	/*
27108ca17f0fSJosef Bacik 	 * We are under a transaction here so we can only do limited flushing.
27118ca17f0fSJosef Bacik 	 * If we get an enospc just kick back -EAGAIN so we know to drop the
27128ca17f0fSJosef Bacik 	 * transaction and try to refill when we can flush all the things.
27138ca17f0fSJosef Bacik 	 */
27140647bf56SWang Shilong 	ret = btrfs_block_rsv_refill(root, rc->block_rsv, num_bytes,
27158ca17f0fSJosef Bacik 				BTRFS_RESERVE_FLUSH_LIMIT);
27163fd0a558SYan, Zheng 	if (ret) {
2717da17066cSJeff Mahoney 		tmp = fs_info->nodesize * RELOCATION_RESERVED_NODES;
27180647bf56SWang Shilong 		while (tmp <= rc->reserved_bytes)
27190647bf56SWang Shilong 			tmp <<= 1;
27200647bf56SWang Shilong 		/*
27210647bf56SWang Shilong 		 * only one thread can access block_rsv at this point,
27220647bf56SWang Shilong 		 * so we don't need hold lock to protect block_rsv.
27230647bf56SWang Shilong 		 * we expand more reservation size here to allow enough
272452042d8eSAndrea Gelmini 		 * space for relocation and we will return earlier in
27250647bf56SWang Shilong 		 * enospc case.
27260647bf56SWang Shilong 		 */
2727da17066cSJeff Mahoney 		rc->block_rsv->size = tmp + fs_info->nodesize *
27280647bf56SWang Shilong 				      RELOCATION_RESERVED_NODES;
27298ca17f0fSJosef Bacik 		return -EAGAIN;
27303fd0a558SYan, Zheng 	}
27313fd0a558SYan, Zheng 
27323fd0a558SYan, Zheng 	return 0;
27333fd0a558SYan, Zheng }
27343fd0a558SYan, Zheng 
27355d4f98a2SYan Zheng /*
27365d4f98a2SYan Zheng  * relocate a block tree, and then update pointers in upper level
27375d4f98a2SYan Zheng  * blocks that reference the block to point to the new location.
27385d4f98a2SYan Zheng  *
27395d4f98a2SYan Zheng  * if called by link_to_upper, the block has already been relocated.
27405d4f98a2SYan Zheng  * in that case this function just updates pointers.
27415d4f98a2SYan Zheng  */
27425d4f98a2SYan Zheng static int do_relocation(struct btrfs_trans_handle *trans,
27433fd0a558SYan, Zheng 			 struct reloc_control *rc,
2744a26195a5SQu Wenruo 			 struct btrfs_backref_node *node,
27455d4f98a2SYan Zheng 			 struct btrfs_key *key,
27465d4f98a2SYan Zheng 			 struct btrfs_path *path, int lowest)
27475d4f98a2SYan Zheng {
27482ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2749a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
2750a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2751a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
27525d4f98a2SYan Zheng 	struct btrfs_root *root;
27535d4f98a2SYan Zheng 	struct extent_buffer *eb;
27545d4f98a2SYan Zheng 	u32 blocksize;
27555d4f98a2SYan Zheng 	u64 bytenr;
27565d4f98a2SYan Zheng 	u64 generation;
27575d4f98a2SYan Zheng 	int slot;
27585d4f98a2SYan Zheng 	int ret;
27595d4f98a2SYan Zheng 	int err = 0;
27605d4f98a2SYan Zheng 
27615d4f98a2SYan Zheng 	BUG_ON(lowest && node->eb);
27625d4f98a2SYan Zheng 
27635d4f98a2SYan Zheng 	path->lowest_level = node->level + 1;
27643fd0a558SYan, Zheng 	rc->backref_cache.path[node->level] = node;
27655d4f98a2SYan Zheng 	list_for_each_entry(edge, &node->upper, list[LOWER]) {
2766581c1760SQu Wenruo 		struct btrfs_key first_key;
276782fa113fSQu Wenruo 		struct btrfs_ref ref = { 0 };
2768581c1760SQu Wenruo 
27695d4f98a2SYan Zheng 		cond_resched();
27705d4f98a2SYan Zheng 
27715d4f98a2SYan Zheng 		upper = edge->node[UPPER];
2772dc4103f9SWang Shilong 		root = select_reloc_root(trans, rc, upper, edges);
27733fd0a558SYan, Zheng 		BUG_ON(!root);
27745d4f98a2SYan Zheng 
27753fd0a558SYan, Zheng 		if (upper->eb && !upper->locked) {
27763fd0a558SYan, Zheng 			if (!lowest) {
27773fd0a558SYan, Zheng 				ret = btrfs_bin_search(upper->eb, key,
27783fd0a558SYan, Zheng 						       upper->level, &slot);
2779cbca7d59SFilipe Manana 				if (ret < 0) {
2780cbca7d59SFilipe Manana 					err = ret;
2781cbca7d59SFilipe Manana 					goto next;
2782cbca7d59SFilipe Manana 				}
27833fd0a558SYan, Zheng 				BUG_ON(ret);
27843fd0a558SYan, Zheng 				bytenr = btrfs_node_blockptr(upper->eb, slot);
27853fd0a558SYan, Zheng 				if (node->eb->start == bytenr)
27863fd0a558SYan, Zheng 					goto next;
27873fd0a558SYan, Zheng 			}
2788b0fe7078SQu Wenruo 			btrfs_backref_drop_node_buffer(upper);
27893fd0a558SYan, Zheng 		}
27905d4f98a2SYan Zheng 
27915d4f98a2SYan Zheng 		if (!upper->eb) {
27925d4f98a2SYan Zheng 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
27933561b9dbSLiu Bo 			if (ret) {
27943561b9dbSLiu Bo 				if (ret < 0)
27955d4f98a2SYan Zheng 					err = ret;
27963561b9dbSLiu Bo 				else
27973561b9dbSLiu Bo 					err = -ENOENT;
27983561b9dbSLiu Bo 
27993561b9dbSLiu Bo 				btrfs_release_path(path);
28005d4f98a2SYan Zheng 				break;
28015d4f98a2SYan Zheng 			}
28025d4f98a2SYan Zheng 
28033fd0a558SYan, Zheng 			if (!upper->eb) {
28043fd0a558SYan, Zheng 				upper->eb = path->nodes[upper->level];
28053fd0a558SYan, Zheng 				path->nodes[upper->level] = NULL;
28063fd0a558SYan, Zheng 			} else {
28073fd0a558SYan, Zheng 				BUG_ON(upper->eb != path->nodes[upper->level]);
28083fd0a558SYan, Zheng 			}
28093fd0a558SYan, Zheng 
28103fd0a558SYan, Zheng 			upper->locked = 1;
28113fd0a558SYan, Zheng 			path->locks[upper->level] = 0;
28123fd0a558SYan, Zheng 
28135d4f98a2SYan Zheng 			slot = path->slots[upper->level];
2814b3b4aa74SDavid Sterba 			btrfs_release_path(path);
28155d4f98a2SYan Zheng 		} else {
28165d4f98a2SYan Zheng 			ret = btrfs_bin_search(upper->eb, key, upper->level,
28175d4f98a2SYan Zheng 					       &slot);
2818cbca7d59SFilipe Manana 			if (ret < 0) {
2819cbca7d59SFilipe Manana 				err = ret;
2820cbca7d59SFilipe Manana 				goto next;
2821cbca7d59SFilipe Manana 			}
28225d4f98a2SYan Zheng 			BUG_ON(ret);
28235d4f98a2SYan Zheng 		}
28245d4f98a2SYan Zheng 
28255d4f98a2SYan Zheng 		bytenr = btrfs_node_blockptr(upper->eb, slot);
28263fd0a558SYan, Zheng 		if (lowest) {
28274547f4d8SLiu Bo 			if (bytenr != node->bytenr) {
28284547f4d8SLiu Bo 				btrfs_err(root->fs_info,
28294547f4d8SLiu Bo 		"lowest leaf/node mismatch: bytenr %llu node->bytenr %llu slot %d upper %llu",
28304547f4d8SLiu Bo 					  bytenr, node->bytenr, slot,
28314547f4d8SLiu Bo 					  upper->eb->start);
28324547f4d8SLiu Bo 				err = -EIO;
28334547f4d8SLiu Bo 				goto next;
28344547f4d8SLiu Bo 			}
28355d4f98a2SYan Zheng 		} else {
28363fd0a558SYan, Zheng 			if (node->eb->start == bytenr)
28373fd0a558SYan, Zheng 				goto next;
28385d4f98a2SYan Zheng 		}
28395d4f98a2SYan Zheng 
2840da17066cSJeff Mahoney 		blocksize = root->fs_info->nodesize;
28415d4f98a2SYan Zheng 		generation = btrfs_node_ptr_generation(upper->eb, slot);
2842581c1760SQu Wenruo 		btrfs_node_key_to_cpu(upper->eb, &first_key, slot);
2843581c1760SQu Wenruo 		eb = read_tree_block(fs_info, bytenr, generation,
2844581c1760SQu Wenruo 				     upper->level - 1, &first_key);
284564c043deSLiu Bo 		if (IS_ERR(eb)) {
284664c043deSLiu Bo 			err = PTR_ERR(eb);
284764c043deSLiu Bo 			goto next;
284864c043deSLiu Bo 		} else if (!extent_buffer_uptodate(eb)) {
2849416bc658SJosef Bacik 			free_extent_buffer(eb);
285097d9a8a4STsutomu Itoh 			err = -EIO;
285197d9a8a4STsutomu Itoh 			goto next;
285297d9a8a4STsutomu Itoh 		}
28535d4f98a2SYan Zheng 		btrfs_tree_lock(eb);
28548bead258SDavid Sterba 		btrfs_set_lock_blocking_write(eb);
28555d4f98a2SYan Zheng 
28565d4f98a2SYan Zheng 		if (!node->eb) {
28575d4f98a2SYan Zheng 			ret = btrfs_cow_block(trans, root, eb, upper->eb,
28585d4f98a2SYan Zheng 					      slot, &eb);
28593fd0a558SYan, Zheng 			btrfs_tree_unlock(eb);
28603fd0a558SYan, Zheng 			free_extent_buffer(eb);
28615d4f98a2SYan Zheng 			if (ret < 0) {
28625d4f98a2SYan Zheng 				err = ret;
28633fd0a558SYan, Zheng 				goto next;
28645d4f98a2SYan Zheng 			}
28653fd0a558SYan, Zheng 			BUG_ON(node->eb != eb);
28665d4f98a2SYan Zheng 		} else {
28675d4f98a2SYan Zheng 			btrfs_set_node_blockptr(upper->eb, slot,
28685d4f98a2SYan Zheng 						node->eb->start);
28695d4f98a2SYan Zheng 			btrfs_set_node_ptr_generation(upper->eb, slot,
28705d4f98a2SYan Zheng 						      trans->transid);
28715d4f98a2SYan Zheng 			btrfs_mark_buffer_dirty(upper->eb);
28725d4f98a2SYan Zheng 
287382fa113fSQu Wenruo 			btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF,
28745d4f98a2SYan Zheng 					       node->eb->start, blocksize,
287582fa113fSQu Wenruo 					       upper->eb->start);
287682fa113fSQu Wenruo 			ref.real_root = root->root_key.objectid;
287782fa113fSQu Wenruo 			btrfs_init_tree_ref(&ref, node->level,
287882fa113fSQu Wenruo 					    btrfs_header_owner(upper->eb));
287982fa113fSQu Wenruo 			ret = btrfs_inc_extent_ref(trans, &ref);
28805d4f98a2SYan Zheng 			BUG_ON(ret);
28815d4f98a2SYan Zheng 
28825d4f98a2SYan Zheng 			ret = btrfs_drop_subtree(trans, root, eb, upper->eb);
28835d4f98a2SYan Zheng 			BUG_ON(ret);
28845d4f98a2SYan Zheng 		}
28853fd0a558SYan, Zheng next:
28863fd0a558SYan, Zheng 		if (!upper->pending)
2887b0fe7078SQu Wenruo 			btrfs_backref_drop_node_buffer(upper);
28883fd0a558SYan, Zheng 		else
2889b0fe7078SQu Wenruo 			btrfs_backref_unlock_node_buffer(upper);
28903fd0a558SYan, Zheng 		if (err)
28913fd0a558SYan, Zheng 			break;
28925d4f98a2SYan Zheng 	}
28933fd0a558SYan, Zheng 
28943fd0a558SYan, Zheng 	if (!err && node->pending) {
2895b0fe7078SQu Wenruo 		btrfs_backref_drop_node_buffer(node);
28963fd0a558SYan, Zheng 		list_move_tail(&node->list, &rc->backref_cache.changed);
28973fd0a558SYan, Zheng 		node->pending = 0;
28985d4f98a2SYan Zheng 	}
28993fd0a558SYan, Zheng 
29005d4f98a2SYan Zheng 	path->lowest_level = 0;
29013fd0a558SYan, Zheng 	BUG_ON(err == -ENOSPC);
29025d4f98a2SYan Zheng 	return err;
29035d4f98a2SYan Zheng }
29045d4f98a2SYan Zheng 
29055d4f98a2SYan Zheng static int link_to_upper(struct btrfs_trans_handle *trans,
29063fd0a558SYan, Zheng 			 struct reloc_control *rc,
2907a26195a5SQu Wenruo 			 struct btrfs_backref_node *node,
29085d4f98a2SYan Zheng 			 struct btrfs_path *path)
29095d4f98a2SYan Zheng {
29105d4f98a2SYan Zheng 	struct btrfs_key key;
29115d4f98a2SYan Zheng 
29125d4f98a2SYan Zheng 	btrfs_node_key_to_cpu(node->eb, &key, 0);
29133fd0a558SYan, Zheng 	return do_relocation(trans, rc, node, &key, path, 0);
29145d4f98a2SYan Zheng }
29155d4f98a2SYan Zheng 
29165d4f98a2SYan Zheng static int finish_pending_nodes(struct btrfs_trans_handle *trans,
29173fd0a558SYan, Zheng 				struct reloc_control *rc,
29183fd0a558SYan, Zheng 				struct btrfs_path *path, int err)
29195d4f98a2SYan Zheng {
29203fd0a558SYan, Zheng 	LIST_HEAD(list);
2921a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
2922a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
29235d4f98a2SYan Zheng 	int level;
29245d4f98a2SYan Zheng 	int ret;
29255d4f98a2SYan Zheng 
29265d4f98a2SYan Zheng 	for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
29275d4f98a2SYan Zheng 		while (!list_empty(&cache->pending[level])) {
29285d4f98a2SYan Zheng 			node = list_entry(cache->pending[level].next,
2929a26195a5SQu Wenruo 					  struct btrfs_backref_node, list);
29303fd0a558SYan, Zheng 			list_move_tail(&node->list, &list);
29313fd0a558SYan, Zheng 			BUG_ON(!node->pending);
29325d4f98a2SYan Zheng 
29333fd0a558SYan, Zheng 			if (!err) {
29343fd0a558SYan, Zheng 				ret = link_to_upper(trans, rc, node, path);
29355d4f98a2SYan Zheng 				if (ret < 0)
29365d4f98a2SYan Zheng 					err = ret;
29375d4f98a2SYan Zheng 			}
29385d4f98a2SYan Zheng 		}
29393fd0a558SYan, Zheng 		list_splice_init(&list, &cache->pending[level]);
29403fd0a558SYan, Zheng 	}
29415d4f98a2SYan Zheng 	return err;
29425d4f98a2SYan Zheng }
29435d4f98a2SYan Zheng 
29445d4f98a2SYan Zheng /*
29455d4f98a2SYan Zheng  * mark a block and all blocks directly/indirectly reference the block
29465d4f98a2SYan Zheng  * as processed.
29475d4f98a2SYan Zheng  */
29485d4f98a2SYan Zheng static void update_processed_blocks(struct reloc_control *rc,
2949a26195a5SQu Wenruo 				    struct btrfs_backref_node *node)
29505d4f98a2SYan Zheng {
2951a26195a5SQu Wenruo 	struct btrfs_backref_node *next = node;
2952a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2953a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
29545d4f98a2SYan Zheng 	int index = 0;
29555d4f98a2SYan Zheng 
29565d4f98a2SYan Zheng 	while (next) {
29575d4f98a2SYan Zheng 		cond_resched();
29585d4f98a2SYan Zheng 		while (1) {
29595d4f98a2SYan Zheng 			if (next->processed)
29605d4f98a2SYan Zheng 				break;
29615d4f98a2SYan Zheng 
29629569cc20SQu Wenruo 			mark_block_processed(rc, next);
29635d4f98a2SYan Zheng 
29645d4f98a2SYan Zheng 			if (list_empty(&next->upper))
29655d4f98a2SYan Zheng 				break;
29665d4f98a2SYan Zheng 
29675d4f98a2SYan Zheng 			edge = list_entry(next->upper.next,
2968a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[LOWER]);
29695d4f98a2SYan Zheng 			edges[index++] = edge;
29705d4f98a2SYan Zheng 			next = edge->node[UPPER];
29715d4f98a2SYan Zheng 		}
29725d4f98a2SYan Zheng 		next = walk_down_backref(edges, &index);
29735d4f98a2SYan Zheng 	}
29745d4f98a2SYan Zheng }
29755d4f98a2SYan Zheng 
29767476dfdaSDavid Sterba static int tree_block_processed(u64 bytenr, struct reloc_control *rc)
29775d4f98a2SYan Zheng {
2978da17066cSJeff Mahoney 	u32 blocksize = rc->extent_root->fs_info->nodesize;
29797476dfdaSDavid Sterba 
29805d4f98a2SYan Zheng 	if (test_range_bit(&rc->processed_blocks, bytenr,
29819655d298SChris Mason 			   bytenr + blocksize - 1, EXTENT_DIRTY, 1, NULL))
29825d4f98a2SYan Zheng 		return 1;
29835d4f98a2SYan Zheng 	return 0;
29845d4f98a2SYan Zheng }
29855d4f98a2SYan Zheng 
29862ff7e61eSJeff Mahoney static int get_tree_block_key(struct btrfs_fs_info *fs_info,
29875d4f98a2SYan Zheng 			      struct tree_block *block)
29885d4f98a2SYan Zheng {
29895d4f98a2SYan Zheng 	struct extent_buffer *eb;
29905d4f98a2SYan Zheng 
2991581c1760SQu Wenruo 	eb = read_tree_block(fs_info, block->bytenr, block->key.offset,
2992581c1760SQu Wenruo 			     block->level, NULL);
299364c043deSLiu Bo 	if (IS_ERR(eb)) {
299464c043deSLiu Bo 		return PTR_ERR(eb);
299564c043deSLiu Bo 	} else if (!extent_buffer_uptodate(eb)) {
2996416bc658SJosef Bacik 		free_extent_buffer(eb);
2997416bc658SJosef Bacik 		return -EIO;
2998416bc658SJosef Bacik 	}
29995d4f98a2SYan Zheng 	if (block->level == 0)
30005d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(eb, &block->key, 0);
30015d4f98a2SYan Zheng 	else
30025d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(eb, &block->key, 0);
30035d4f98a2SYan Zheng 	free_extent_buffer(eb);
30045d4f98a2SYan Zheng 	block->key_ready = 1;
30055d4f98a2SYan Zheng 	return 0;
30065d4f98a2SYan Zheng }
30075d4f98a2SYan Zheng 
30085d4f98a2SYan Zheng /*
30095d4f98a2SYan Zheng  * helper function to relocate a tree block
30105d4f98a2SYan Zheng  */
30115d4f98a2SYan Zheng static int relocate_tree_block(struct btrfs_trans_handle *trans,
30125d4f98a2SYan Zheng 				struct reloc_control *rc,
3013a26195a5SQu Wenruo 				struct btrfs_backref_node *node,
30145d4f98a2SYan Zheng 				struct btrfs_key *key,
30155d4f98a2SYan Zheng 				struct btrfs_path *path)
30165d4f98a2SYan Zheng {
30175d4f98a2SYan Zheng 	struct btrfs_root *root;
30183fd0a558SYan, Zheng 	int ret = 0;
30195d4f98a2SYan Zheng 
30203fd0a558SYan, Zheng 	if (!node)
30215d4f98a2SYan Zheng 		return 0;
30223fd0a558SYan, Zheng 
30235f6b2e5cSJosef Bacik 	/*
30245f6b2e5cSJosef Bacik 	 * If we fail here we want to drop our backref_node because we are going
30255f6b2e5cSJosef Bacik 	 * to start over and regenerate the tree for it.
30265f6b2e5cSJosef Bacik 	 */
30275f6b2e5cSJosef Bacik 	ret = reserve_metadata_space(trans, rc, node);
30285f6b2e5cSJosef Bacik 	if (ret)
30295f6b2e5cSJosef Bacik 		goto out;
30305f6b2e5cSJosef Bacik 
30313fd0a558SYan, Zheng 	BUG_ON(node->processed);
3032147d256eSZhaolei 	root = select_one_root(node);
30333fd0a558SYan, Zheng 	if (root == ERR_PTR(-ENOENT)) {
30343fd0a558SYan, Zheng 		update_processed_blocks(rc, node);
30353fd0a558SYan, Zheng 		goto out;
30365d4f98a2SYan Zheng 	}
30375d4f98a2SYan Zheng 
30383fd0a558SYan, Zheng 	if (root) {
303927cdeb70SMiao Xie 		if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
30403fd0a558SYan, Zheng 			BUG_ON(node->new_bytenr);
30413fd0a558SYan, Zheng 			BUG_ON(!list_empty(&node->list));
30423fd0a558SYan, Zheng 			btrfs_record_root_in_trans(trans, root);
30433fd0a558SYan, Zheng 			root = root->reloc_root;
30443fd0a558SYan, Zheng 			node->new_bytenr = root->node->start;
304500246528SJosef Bacik 			btrfs_put_root(node->root);
304600246528SJosef Bacik 			node->root = btrfs_grab_root(root);
30470b530bc5SJosef Bacik 			ASSERT(node->root);
30483fd0a558SYan, Zheng 			list_add_tail(&node->list, &rc->backref_cache.changed);
30493fd0a558SYan, Zheng 		} else {
30505d4f98a2SYan Zheng 			path->lowest_level = node->level;
30515d4f98a2SYan Zheng 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
3052b3b4aa74SDavid Sterba 			btrfs_release_path(path);
30533fd0a558SYan, Zheng 			if (ret > 0)
30545d4f98a2SYan Zheng 				ret = 0;
30553fd0a558SYan, Zheng 		}
30563fd0a558SYan, Zheng 		if (!ret)
30573fd0a558SYan, Zheng 			update_processed_blocks(rc, node);
30583fd0a558SYan, Zheng 	} else {
30593fd0a558SYan, Zheng 		ret = do_relocation(trans, rc, node, key, path, 1);
30603fd0a558SYan, Zheng 	}
30615d4f98a2SYan Zheng out:
30620647bf56SWang Shilong 	if (ret || node->level == 0 || node->cowonly)
3063023acb07SQu Wenruo 		btrfs_backref_cleanup_node(&rc->backref_cache, node);
30645d4f98a2SYan Zheng 	return ret;
30655d4f98a2SYan Zheng }
30665d4f98a2SYan Zheng 
30675d4f98a2SYan Zheng /*
30685d4f98a2SYan Zheng  * relocate a list of blocks
30695d4f98a2SYan Zheng  */
30705d4f98a2SYan Zheng static noinline_for_stack
30715d4f98a2SYan Zheng int relocate_tree_blocks(struct btrfs_trans_handle *trans,
30725d4f98a2SYan Zheng 			 struct reloc_control *rc, struct rb_root *blocks)
30735d4f98a2SYan Zheng {
30742ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3075a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
30765d4f98a2SYan Zheng 	struct btrfs_path *path;
30775d4f98a2SYan Zheng 	struct tree_block *block;
307898ff7b94SQu Wenruo 	struct tree_block *next;
30795d4f98a2SYan Zheng 	int ret;
30805d4f98a2SYan Zheng 	int err = 0;
30815d4f98a2SYan Zheng 
30825d4f98a2SYan Zheng 	path = btrfs_alloc_path();
3083e1a12670SLiu Bo 	if (!path) {
3084e1a12670SLiu Bo 		err = -ENOMEM;
308534c2b290SDavid Sterba 		goto out_free_blocks;
3086e1a12670SLiu Bo 	}
30875d4f98a2SYan Zheng 
308898ff7b94SQu Wenruo 	/* Kick in readahead for tree blocks with missing keys */
308998ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
30905d4f98a2SYan Zheng 		if (!block->key_ready)
30912ff7e61eSJeff Mahoney 			readahead_tree_block(fs_info, block->bytenr);
30925d4f98a2SYan Zheng 	}
30935d4f98a2SYan Zheng 
309498ff7b94SQu Wenruo 	/* Get first keys */
309598ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
309634c2b290SDavid Sterba 		if (!block->key_ready) {
30972ff7e61eSJeff Mahoney 			err = get_tree_block_key(fs_info, block);
309834c2b290SDavid Sterba 			if (err)
309934c2b290SDavid Sterba 				goto out_free_path;
310034c2b290SDavid Sterba 		}
31015d4f98a2SYan Zheng 	}
31025d4f98a2SYan Zheng 
310398ff7b94SQu Wenruo 	/* Do tree relocation */
310498ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
31053fd0a558SYan, Zheng 		node = build_backref_tree(rc, &block->key,
31065d4f98a2SYan Zheng 					  block->level, block->bytenr);
31075d4f98a2SYan Zheng 		if (IS_ERR(node)) {
31085d4f98a2SYan Zheng 			err = PTR_ERR(node);
31095d4f98a2SYan Zheng 			goto out;
31105d4f98a2SYan Zheng 		}
31115d4f98a2SYan Zheng 
31125d4f98a2SYan Zheng 		ret = relocate_tree_block(trans, rc, node, &block->key,
31135d4f98a2SYan Zheng 					  path);
31145d4f98a2SYan Zheng 		if (ret < 0) {
31155d4f98a2SYan Zheng 			err = ret;
311650dbbb71SJosef Bacik 			break;
31175d4f98a2SYan Zheng 		}
31185d4f98a2SYan Zheng 	}
31195d4f98a2SYan Zheng out:
31203fd0a558SYan, Zheng 	err = finish_pending_nodes(trans, rc, path, err);
31215d4f98a2SYan Zheng 
312234c2b290SDavid Sterba out_free_path:
31235d4f98a2SYan Zheng 	btrfs_free_path(path);
312434c2b290SDavid Sterba out_free_blocks:
3125e1a12670SLiu Bo 	free_block_list(blocks);
31265d4f98a2SYan Zheng 	return err;
31275d4f98a2SYan Zheng }
31285d4f98a2SYan Zheng 
31295d4f98a2SYan Zheng static noinline_for_stack
3130efa56464SYan, Zheng int prealloc_file_extent_cluster(struct inode *inode,
3131efa56464SYan, Zheng 				 struct file_extent_cluster *cluster)
3132efa56464SYan, Zheng {
3133efa56464SYan, Zheng 	u64 alloc_hint = 0;
3134efa56464SYan, Zheng 	u64 start;
3135efa56464SYan, Zheng 	u64 end;
3136efa56464SYan, Zheng 	u64 offset = BTRFS_I(inode)->index_cnt;
3137efa56464SYan, Zheng 	u64 num_bytes;
3138efa56464SYan, Zheng 	int nr = 0;
3139efa56464SYan, Zheng 	int ret = 0;
3140dcb40c19SWang Xiaoguang 	u64 prealloc_start = cluster->start - offset;
3141dcb40c19SWang Xiaoguang 	u64 prealloc_end = cluster->end - offset;
314218513091SWang Xiaoguang 	u64 cur_offset;
3143364ecf36SQu Wenruo 	struct extent_changeset *data_reserved = NULL;
3144efa56464SYan, Zheng 
3145efa56464SYan, Zheng 	BUG_ON(cluster->start != cluster->boundary[0]);
31465955102cSAl Viro 	inode_lock(inode);
3147efa56464SYan, Zheng 
3148364ecf36SQu Wenruo 	ret = btrfs_check_data_free_space(inode, &data_reserved, prealloc_start,
3149dcb40c19SWang Xiaoguang 					  prealloc_end + 1 - prealloc_start);
3150efa56464SYan, Zheng 	if (ret)
3151efa56464SYan, Zheng 		goto out;
3152efa56464SYan, Zheng 
315318513091SWang Xiaoguang 	cur_offset = prealloc_start;
3154efa56464SYan, Zheng 	while (nr < cluster->nr) {
3155efa56464SYan, Zheng 		start = cluster->boundary[nr] - offset;
3156efa56464SYan, Zheng 		if (nr + 1 < cluster->nr)
3157efa56464SYan, Zheng 			end = cluster->boundary[nr + 1] - 1 - offset;
3158efa56464SYan, Zheng 		else
3159efa56464SYan, Zheng 			end = cluster->end - offset;
3160efa56464SYan, Zheng 
3161d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, start, end);
3162efa56464SYan, Zheng 		num_bytes = end + 1 - start;
316318513091SWang Xiaoguang 		if (cur_offset < start)
3164bc42bda2SQu Wenruo 			btrfs_free_reserved_data_space(inode, data_reserved,
3165bc42bda2SQu Wenruo 					cur_offset, start - cur_offset);
3166efa56464SYan, Zheng 		ret = btrfs_prealloc_file_range(inode, 0, start,
3167efa56464SYan, Zheng 						num_bytes, num_bytes,
3168efa56464SYan, Zheng 						end + 1, &alloc_hint);
316918513091SWang Xiaoguang 		cur_offset = end + 1;
3170d0082371SJeff Mahoney 		unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
3171efa56464SYan, Zheng 		if (ret)
3172efa56464SYan, Zheng 			break;
3173efa56464SYan, Zheng 		nr++;
3174efa56464SYan, Zheng 	}
317518513091SWang Xiaoguang 	if (cur_offset < prealloc_end)
3176bc42bda2SQu Wenruo 		btrfs_free_reserved_data_space(inode, data_reserved,
3177bc42bda2SQu Wenruo 				cur_offset, prealloc_end + 1 - cur_offset);
3178efa56464SYan, Zheng out:
31795955102cSAl Viro 	inode_unlock(inode);
3180364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
3181efa56464SYan, Zheng 	return ret;
3182efa56464SYan, Zheng }
3183efa56464SYan, Zheng 
3184efa56464SYan, Zheng static noinline_for_stack
31850257bb82SYan, Zheng int setup_extent_mapping(struct inode *inode, u64 start, u64 end,
31860257bb82SYan, Zheng 			 u64 block_start)
31875d4f98a2SYan Zheng {
31885d4f98a2SYan Zheng 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
31895d4f98a2SYan Zheng 	struct extent_map *em;
31900257bb82SYan, Zheng 	int ret = 0;
31915d4f98a2SYan Zheng 
3192172ddd60SDavid Sterba 	em = alloc_extent_map();
31930257bb82SYan, Zheng 	if (!em)
31940257bb82SYan, Zheng 		return -ENOMEM;
31950257bb82SYan, Zheng 
31965d4f98a2SYan Zheng 	em->start = start;
31970257bb82SYan, Zheng 	em->len = end + 1 - start;
31980257bb82SYan, Zheng 	em->block_len = em->len;
31990257bb82SYan, Zheng 	em->block_start = block_start;
32005d4f98a2SYan Zheng 	set_bit(EXTENT_FLAG_PINNED, &em->flags);
32015d4f98a2SYan Zheng 
3202d0082371SJeff Mahoney 	lock_extent(&BTRFS_I(inode)->io_tree, start, end);
32035d4f98a2SYan Zheng 	while (1) {
3204890871beSChris Mason 		write_lock(&em_tree->lock);
320509a2a8f9SJosef Bacik 		ret = add_extent_mapping(em_tree, em, 0);
3206890871beSChris Mason 		write_unlock(&em_tree->lock);
32075d4f98a2SYan Zheng 		if (ret != -EEXIST) {
32085d4f98a2SYan Zheng 			free_extent_map(em);
32095d4f98a2SYan Zheng 			break;
32105d4f98a2SYan Zheng 		}
3211dcdbc059SNikolay Borisov 		btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
32125d4f98a2SYan Zheng 	}
3213d0082371SJeff Mahoney 	unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
32140257bb82SYan, Zheng 	return ret;
32150257bb82SYan, Zheng }
32165d4f98a2SYan Zheng 
3217726a3421SQu Wenruo /*
3218726a3421SQu Wenruo  * Allow error injection to test balance cancellation
3219726a3421SQu Wenruo  */
3220726a3421SQu Wenruo int btrfs_should_cancel_balance(struct btrfs_fs_info *fs_info)
3221726a3421SQu Wenruo {
3222726a3421SQu Wenruo 	return atomic_read(&fs_info->balance_cancel_req);
3223726a3421SQu Wenruo }
3224726a3421SQu Wenruo ALLOW_ERROR_INJECTION(btrfs_should_cancel_balance, TRUE);
3225726a3421SQu Wenruo 
32260257bb82SYan, Zheng static int relocate_file_extent_cluster(struct inode *inode,
32270257bb82SYan, Zheng 					struct file_extent_cluster *cluster)
32280257bb82SYan, Zheng {
32292ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
32300257bb82SYan, Zheng 	u64 page_start;
32310257bb82SYan, Zheng 	u64 page_end;
32320257bb82SYan, Zheng 	u64 offset = BTRFS_I(inode)->index_cnt;
32330257bb82SYan, Zheng 	unsigned long index;
32340257bb82SYan, Zheng 	unsigned long last_index;
32350257bb82SYan, Zheng 	struct page *page;
32360257bb82SYan, Zheng 	struct file_ra_state *ra;
32373b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
32380257bb82SYan, Zheng 	int nr = 0;
32390257bb82SYan, Zheng 	int ret = 0;
32400257bb82SYan, Zheng 
32410257bb82SYan, Zheng 	if (!cluster->nr)
32420257bb82SYan, Zheng 		return 0;
32430257bb82SYan, Zheng 
32440257bb82SYan, Zheng 	ra = kzalloc(sizeof(*ra), GFP_NOFS);
32450257bb82SYan, Zheng 	if (!ra)
32460257bb82SYan, Zheng 		return -ENOMEM;
32470257bb82SYan, Zheng 
3248efa56464SYan, Zheng 	ret = prealloc_file_extent_cluster(inode, cluster);
32490257bb82SYan, Zheng 	if (ret)
3250efa56464SYan, Zheng 		goto out;
32510257bb82SYan, Zheng 
32520257bb82SYan, Zheng 	file_ra_state_init(ra, inode->i_mapping);
32530257bb82SYan, Zheng 
3254efa56464SYan, Zheng 	ret = setup_extent_mapping(inode, cluster->start - offset,
3255efa56464SYan, Zheng 				   cluster->end - offset, cluster->start);
3256efa56464SYan, Zheng 	if (ret)
3257efa56464SYan, Zheng 		goto out;
3258efa56464SYan, Zheng 
325909cbfeafSKirill A. Shutemov 	index = (cluster->start - offset) >> PAGE_SHIFT;
326009cbfeafSKirill A. Shutemov 	last_index = (cluster->end - offset) >> PAGE_SHIFT;
32610257bb82SYan, Zheng 	while (index <= last_index) {
32629f3db423SNikolay Borisov 		ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
32639f3db423SNikolay Borisov 				PAGE_SIZE);
3264efa56464SYan, Zheng 		if (ret)
3265efa56464SYan, Zheng 			goto out;
3266efa56464SYan, Zheng 
32670257bb82SYan, Zheng 		page = find_lock_page(inode->i_mapping, index);
32680257bb82SYan, Zheng 		if (!page) {
32690257bb82SYan, Zheng 			page_cache_sync_readahead(inode->i_mapping,
32700257bb82SYan, Zheng 						  ra, NULL, index,
32710257bb82SYan, Zheng 						  last_index + 1 - index);
3272a94733d0SJosef Bacik 			page = find_or_create_page(inode->i_mapping, index,
32733b16a4e3SJosef Bacik 						   mask);
32740257bb82SYan, Zheng 			if (!page) {
3275691fa059SNikolay Borisov 				btrfs_delalloc_release_metadata(BTRFS_I(inode),
327643b18595SQu Wenruo 							PAGE_SIZE, true);
327744db1216SFilipe Manana 				btrfs_delalloc_release_extents(BTRFS_I(inode),
32788702ba93SQu Wenruo 							PAGE_SIZE);
32790257bb82SYan, Zheng 				ret = -ENOMEM;
3280efa56464SYan, Zheng 				goto out;
32810257bb82SYan, Zheng 			}
32820257bb82SYan, Zheng 		}
32830257bb82SYan, Zheng 
32840257bb82SYan, Zheng 		if (PageReadahead(page)) {
32850257bb82SYan, Zheng 			page_cache_async_readahead(inode->i_mapping,
32860257bb82SYan, Zheng 						   ra, NULL, page, index,
32870257bb82SYan, Zheng 						   last_index + 1 - index);
32880257bb82SYan, Zheng 		}
32890257bb82SYan, Zheng 
32900257bb82SYan, Zheng 		if (!PageUptodate(page)) {
32910257bb82SYan, Zheng 			btrfs_readpage(NULL, page);
32920257bb82SYan, Zheng 			lock_page(page);
32930257bb82SYan, Zheng 			if (!PageUptodate(page)) {
32940257bb82SYan, Zheng 				unlock_page(page);
329509cbfeafSKirill A. Shutemov 				put_page(page);
3296691fa059SNikolay Borisov 				btrfs_delalloc_release_metadata(BTRFS_I(inode),
329743b18595SQu Wenruo 							PAGE_SIZE, true);
32988b62f87bSJosef Bacik 				btrfs_delalloc_release_extents(BTRFS_I(inode),
32998702ba93SQu Wenruo 							       PAGE_SIZE);
33000257bb82SYan, Zheng 				ret = -EIO;
3301efa56464SYan, Zheng 				goto out;
33020257bb82SYan, Zheng 			}
33030257bb82SYan, Zheng 		}
33040257bb82SYan, Zheng 
33054eee4fa4SMiao Xie 		page_start = page_offset(page);
330609cbfeafSKirill A. Shutemov 		page_end = page_start + PAGE_SIZE - 1;
33070257bb82SYan, Zheng 
3308d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, page_start, page_end);
33090257bb82SYan, Zheng 
33100257bb82SYan, Zheng 		set_page_extent_mapped(page);
33110257bb82SYan, Zheng 
33120257bb82SYan, Zheng 		if (nr < cluster->nr &&
33130257bb82SYan, Zheng 		    page_start + offset == cluster->boundary[nr]) {
33140257bb82SYan, Zheng 			set_extent_bits(&BTRFS_I(inode)->io_tree,
33150257bb82SYan, Zheng 					page_start, page_end,
3316ceeb0ae7SDavid Sterba 					EXTENT_BOUNDARY);
33170257bb82SYan, Zheng 			nr++;
33180257bb82SYan, Zheng 		}
33190257bb82SYan, Zheng 
3320765f3cebSNikolay Borisov 		ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
3321330a5827SNikolay Borisov 						NULL);
3322765f3cebSNikolay Borisov 		if (ret) {
3323765f3cebSNikolay Borisov 			unlock_page(page);
3324765f3cebSNikolay Borisov 			put_page(page);
3325765f3cebSNikolay Borisov 			btrfs_delalloc_release_metadata(BTRFS_I(inode),
332643b18595SQu Wenruo 							 PAGE_SIZE, true);
3327765f3cebSNikolay Borisov 			btrfs_delalloc_release_extents(BTRFS_I(inode),
33288702ba93SQu Wenruo 			                               PAGE_SIZE);
3329765f3cebSNikolay Borisov 
3330765f3cebSNikolay Borisov 			clear_extent_bits(&BTRFS_I(inode)->io_tree,
3331765f3cebSNikolay Borisov 					  page_start, page_end,
3332765f3cebSNikolay Borisov 					  EXTENT_LOCKED | EXTENT_BOUNDARY);
3333765f3cebSNikolay Borisov 			goto out;
3334765f3cebSNikolay Borisov 
3335765f3cebSNikolay Borisov 		}
33360257bb82SYan, Zheng 		set_page_dirty(page);
33370257bb82SYan, Zheng 
33380257bb82SYan, Zheng 		unlock_extent(&BTRFS_I(inode)->io_tree,
3339d0082371SJeff Mahoney 			      page_start, page_end);
33400257bb82SYan, Zheng 		unlock_page(page);
334109cbfeafSKirill A. Shutemov 		put_page(page);
33420257bb82SYan, Zheng 
33430257bb82SYan, Zheng 		index++;
33448702ba93SQu Wenruo 		btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
3345efa56464SYan, Zheng 		balance_dirty_pages_ratelimited(inode->i_mapping);
33462ff7e61eSJeff Mahoney 		btrfs_throttle(fs_info);
33477f913c7cSQu Wenruo 		if (btrfs_should_cancel_balance(fs_info)) {
33487f913c7cSQu Wenruo 			ret = -ECANCELED;
33497f913c7cSQu Wenruo 			goto out;
33507f913c7cSQu Wenruo 		}
33510257bb82SYan, Zheng 	}
33520257bb82SYan, Zheng 	WARN_ON(nr != cluster->nr);
3353efa56464SYan, Zheng out:
33540257bb82SYan, Zheng 	kfree(ra);
33550257bb82SYan, Zheng 	return ret;
33560257bb82SYan, Zheng }
33570257bb82SYan, Zheng 
33580257bb82SYan, Zheng static noinline_for_stack
33590257bb82SYan, Zheng int relocate_data_extent(struct inode *inode, struct btrfs_key *extent_key,
33600257bb82SYan, Zheng 			 struct file_extent_cluster *cluster)
33610257bb82SYan, Zheng {
33620257bb82SYan, Zheng 	int ret;
33630257bb82SYan, Zheng 
33640257bb82SYan, Zheng 	if (cluster->nr > 0 && extent_key->objectid != cluster->end + 1) {
33650257bb82SYan, Zheng 		ret = relocate_file_extent_cluster(inode, cluster);
33660257bb82SYan, Zheng 		if (ret)
33670257bb82SYan, Zheng 			return ret;
33680257bb82SYan, Zheng 		cluster->nr = 0;
33690257bb82SYan, Zheng 	}
33700257bb82SYan, Zheng 
33710257bb82SYan, Zheng 	if (!cluster->nr)
33720257bb82SYan, Zheng 		cluster->start = extent_key->objectid;
33730257bb82SYan, Zheng 	else
33740257bb82SYan, Zheng 		BUG_ON(cluster->nr >= MAX_EXTENTS);
33750257bb82SYan, Zheng 	cluster->end = extent_key->objectid + extent_key->offset - 1;
33760257bb82SYan, Zheng 	cluster->boundary[cluster->nr] = extent_key->objectid;
33770257bb82SYan, Zheng 	cluster->nr++;
33780257bb82SYan, Zheng 
33790257bb82SYan, Zheng 	if (cluster->nr >= MAX_EXTENTS) {
33800257bb82SYan, Zheng 		ret = relocate_file_extent_cluster(inode, cluster);
33810257bb82SYan, Zheng 		if (ret)
33820257bb82SYan, Zheng 			return ret;
33830257bb82SYan, Zheng 		cluster->nr = 0;
33840257bb82SYan, Zheng 	}
33850257bb82SYan, Zheng 	return 0;
33865d4f98a2SYan Zheng }
33875d4f98a2SYan Zheng 
33885d4f98a2SYan Zheng /*
33895d4f98a2SYan Zheng  * helper to add a tree block to the list.
33905d4f98a2SYan Zheng  * the major work is getting the generation and level of the block
33915d4f98a2SYan Zheng  */
33925d4f98a2SYan Zheng static int add_tree_block(struct reloc_control *rc,
33935d4f98a2SYan Zheng 			  struct btrfs_key *extent_key,
33945d4f98a2SYan Zheng 			  struct btrfs_path *path,
33955d4f98a2SYan Zheng 			  struct rb_root *blocks)
33965d4f98a2SYan Zheng {
33975d4f98a2SYan Zheng 	struct extent_buffer *eb;
33985d4f98a2SYan Zheng 	struct btrfs_extent_item *ei;
33995d4f98a2SYan Zheng 	struct btrfs_tree_block_info *bi;
34005d4f98a2SYan Zheng 	struct tree_block *block;
34015d4f98a2SYan Zheng 	struct rb_node *rb_node;
34025d4f98a2SYan Zheng 	u32 item_size;
34035d4f98a2SYan Zheng 	int level = -1;
34047fdf4b60SWang Shilong 	u64 generation;
34055d4f98a2SYan Zheng 
34065d4f98a2SYan Zheng 	eb =  path->nodes[0];
34075d4f98a2SYan Zheng 	item_size = btrfs_item_size_nr(eb, path->slots[0]);
34085d4f98a2SYan Zheng 
34093173a18fSJosef Bacik 	if (extent_key->type == BTRFS_METADATA_ITEM_KEY ||
34103173a18fSJosef Bacik 	    item_size >= sizeof(*ei) + sizeof(*bi)) {
34115d4f98a2SYan Zheng 		ei = btrfs_item_ptr(eb, path->slots[0],
34125d4f98a2SYan Zheng 				struct btrfs_extent_item);
34133173a18fSJosef Bacik 		if (extent_key->type == BTRFS_EXTENT_ITEM_KEY) {
34145d4f98a2SYan Zheng 			bi = (struct btrfs_tree_block_info *)(ei + 1);
34155d4f98a2SYan Zheng 			level = btrfs_tree_block_level(eb, bi);
34165d4f98a2SYan Zheng 		} else {
34173173a18fSJosef Bacik 			level = (int)extent_key->offset;
34183173a18fSJosef Bacik 		}
34193173a18fSJosef Bacik 		generation = btrfs_extent_generation(eb, ei);
34206d8ff4e4SDavid Sterba 	} else if (unlikely(item_size == sizeof(struct btrfs_extent_item_v0))) {
3421ba3c2b19SNikolay Borisov 		btrfs_print_v0_err(eb->fs_info);
3422ba3c2b19SNikolay Borisov 		btrfs_handle_fs_error(eb->fs_info, -EINVAL, NULL);
3423ba3c2b19SNikolay Borisov 		return -EINVAL;
34243173a18fSJosef Bacik 	} else {
34255d4f98a2SYan Zheng 		BUG();
34265d4f98a2SYan Zheng 	}
34275d4f98a2SYan Zheng 
3428b3b4aa74SDavid Sterba 	btrfs_release_path(path);
34295d4f98a2SYan Zheng 
34305d4f98a2SYan Zheng 	BUG_ON(level == -1);
34315d4f98a2SYan Zheng 
34325d4f98a2SYan Zheng 	block = kmalloc(sizeof(*block), GFP_NOFS);
34335d4f98a2SYan Zheng 	if (!block)
34345d4f98a2SYan Zheng 		return -ENOMEM;
34355d4f98a2SYan Zheng 
34365d4f98a2SYan Zheng 	block->bytenr = extent_key->objectid;
3437da17066cSJeff Mahoney 	block->key.objectid = rc->extent_root->fs_info->nodesize;
34385d4f98a2SYan Zheng 	block->key.offset = generation;
34395d4f98a2SYan Zheng 	block->level = level;
34405d4f98a2SYan Zheng 	block->key_ready = 0;
34415d4f98a2SYan Zheng 
3442e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(blocks, block->bytenr, &block->rb_node);
344343c04fb1SJeff Mahoney 	if (rb_node)
344443c04fb1SJeff Mahoney 		backref_tree_panic(rb_node, -EEXIST, block->bytenr);
34455d4f98a2SYan Zheng 
34465d4f98a2SYan Zheng 	return 0;
34475d4f98a2SYan Zheng }
34485d4f98a2SYan Zheng 
34495d4f98a2SYan Zheng /*
34505d4f98a2SYan Zheng  * helper to add tree blocks for backref of type BTRFS_SHARED_DATA_REF_KEY
34515d4f98a2SYan Zheng  */
34525d4f98a2SYan Zheng static int __add_tree_block(struct reloc_control *rc,
34535d4f98a2SYan Zheng 			    u64 bytenr, u32 blocksize,
34545d4f98a2SYan Zheng 			    struct rb_root *blocks)
34555d4f98a2SYan Zheng {
34560b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
34575d4f98a2SYan Zheng 	struct btrfs_path *path;
34585d4f98a2SYan Zheng 	struct btrfs_key key;
34595d4f98a2SYan Zheng 	int ret;
34600b246afaSJeff Mahoney 	bool skinny = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
34615d4f98a2SYan Zheng 
34627476dfdaSDavid Sterba 	if (tree_block_processed(bytenr, rc))
34635d4f98a2SYan Zheng 		return 0;
34645d4f98a2SYan Zheng 
3465e9a28dc5SQu Wenruo 	if (rb_simple_search(blocks, bytenr))
34665d4f98a2SYan Zheng 		return 0;
34675d4f98a2SYan Zheng 
34685d4f98a2SYan Zheng 	path = btrfs_alloc_path();
34695d4f98a2SYan Zheng 	if (!path)
34705d4f98a2SYan Zheng 		return -ENOMEM;
3471aee68ee5SJosef Bacik again:
34725d4f98a2SYan Zheng 	key.objectid = bytenr;
3473aee68ee5SJosef Bacik 	if (skinny) {
3474aee68ee5SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
3475aee68ee5SJosef Bacik 		key.offset = (u64)-1;
3476aee68ee5SJosef Bacik 	} else {
34775d4f98a2SYan Zheng 		key.type = BTRFS_EXTENT_ITEM_KEY;
34785d4f98a2SYan Zheng 		key.offset = blocksize;
3479aee68ee5SJosef Bacik 	}
34805d4f98a2SYan Zheng 
34815d4f98a2SYan Zheng 	path->search_commit_root = 1;
34825d4f98a2SYan Zheng 	path->skip_locking = 1;
34835d4f98a2SYan Zheng 	ret = btrfs_search_slot(NULL, rc->extent_root, &key, path, 0, 0);
34845d4f98a2SYan Zheng 	if (ret < 0)
34855d4f98a2SYan Zheng 		goto out;
34865d4f98a2SYan Zheng 
3487aee68ee5SJosef Bacik 	if (ret > 0 && skinny) {
3488aee68ee5SJosef Bacik 		if (path->slots[0]) {
3489aee68ee5SJosef Bacik 			path->slots[0]--;
3490aee68ee5SJosef Bacik 			btrfs_item_key_to_cpu(path->nodes[0], &key,
3491aee68ee5SJosef Bacik 					      path->slots[0]);
34923173a18fSJosef Bacik 			if (key.objectid == bytenr &&
3493aee68ee5SJosef Bacik 			    (key.type == BTRFS_METADATA_ITEM_KEY ||
3494aee68ee5SJosef Bacik 			     (key.type == BTRFS_EXTENT_ITEM_KEY &&
3495aee68ee5SJosef Bacik 			      key.offset == blocksize)))
34963173a18fSJosef Bacik 				ret = 0;
34973173a18fSJosef Bacik 		}
3498aee68ee5SJosef Bacik 
3499aee68ee5SJosef Bacik 		if (ret) {
3500aee68ee5SJosef Bacik 			skinny = false;
3501aee68ee5SJosef Bacik 			btrfs_release_path(path);
3502aee68ee5SJosef Bacik 			goto again;
3503aee68ee5SJosef Bacik 		}
3504aee68ee5SJosef Bacik 	}
3505cdccee99SLiu Bo 	if (ret) {
3506cdccee99SLiu Bo 		ASSERT(ret == 1);
3507cdccee99SLiu Bo 		btrfs_print_leaf(path->nodes[0]);
3508cdccee99SLiu Bo 		btrfs_err(fs_info,
3509cdccee99SLiu Bo 	     "tree block extent item (%llu) is not found in extent tree",
3510cdccee99SLiu Bo 		     bytenr);
3511cdccee99SLiu Bo 		WARN_ON(1);
3512cdccee99SLiu Bo 		ret = -EINVAL;
3513cdccee99SLiu Bo 		goto out;
3514cdccee99SLiu Bo 	}
35153173a18fSJosef Bacik 
35165d4f98a2SYan Zheng 	ret = add_tree_block(rc, &key, path, blocks);
35175d4f98a2SYan Zheng out:
35185d4f98a2SYan Zheng 	btrfs_free_path(path);
35195d4f98a2SYan Zheng 	return ret;
35205d4f98a2SYan Zheng }
35215d4f98a2SYan Zheng 
35220af3d00bSJosef Bacik static int delete_block_group_cache(struct btrfs_fs_info *fs_info,
352332da5386SDavid Sterba 				    struct btrfs_block_group *block_group,
35241bbc621eSChris Mason 				    struct inode *inode,
35251bbc621eSChris Mason 				    u64 ino)
35260af3d00bSJosef Bacik {
35270af3d00bSJosef Bacik 	struct btrfs_key key;
35280af3d00bSJosef Bacik 	struct btrfs_root *root = fs_info->tree_root;
35290af3d00bSJosef Bacik 	struct btrfs_trans_handle *trans;
35300af3d00bSJosef Bacik 	int ret = 0;
35310af3d00bSJosef Bacik 
35320af3d00bSJosef Bacik 	if (inode)
35330af3d00bSJosef Bacik 		goto truncate;
35340af3d00bSJosef Bacik 
35350af3d00bSJosef Bacik 	key.objectid = ino;
35360af3d00bSJosef Bacik 	key.type = BTRFS_INODE_ITEM_KEY;
35370af3d00bSJosef Bacik 	key.offset = 0;
35380af3d00bSJosef Bacik 
35394c66e0d4SDavid Sterba 	inode = btrfs_iget(fs_info->sb, &key, root);
35402e19f1f9SAl Viro 	if (IS_ERR(inode))
35410af3d00bSJosef Bacik 		return -ENOENT;
35420af3d00bSJosef Bacik 
35430af3d00bSJosef Bacik truncate:
35442ff7e61eSJeff Mahoney 	ret = btrfs_check_trunc_cache_free_space(fs_info,
35457b61cd92SMiao Xie 						 &fs_info->global_block_rsv);
35467b61cd92SMiao Xie 	if (ret)
35477b61cd92SMiao Xie 		goto out;
35487b61cd92SMiao Xie 
35497a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
35500af3d00bSJosef Bacik 	if (IS_ERR(trans)) {
35513612b495STsutomu Itoh 		ret = PTR_ERR(trans);
35520af3d00bSJosef Bacik 		goto out;
35530af3d00bSJosef Bacik 	}
35540af3d00bSJosef Bacik 
355577ab86bfSJeff Mahoney 	ret = btrfs_truncate_free_space_cache(trans, block_group, inode);
35560af3d00bSJosef Bacik 
35573a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
35582ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
35590af3d00bSJosef Bacik out:
35600af3d00bSJosef Bacik 	iput(inode);
35610af3d00bSJosef Bacik 	return ret;
35620af3d00bSJosef Bacik }
35630af3d00bSJosef Bacik 
35645d4f98a2SYan Zheng /*
356519b546d7SQu Wenruo  * Locate the free space cache EXTENT_DATA in root tree leaf and delete the
356619b546d7SQu Wenruo  * cache inode, to avoid free space cache data extent blocking data relocation.
35675d4f98a2SYan Zheng  */
356819b546d7SQu Wenruo static int delete_v1_space_cache(struct extent_buffer *leaf,
356919b546d7SQu Wenruo 				 struct btrfs_block_group *block_group,
357019b546d7SQu Wenruo 				 u64 data_bytenr)
35715d4f98a2SYan Zheng {
357219b546d7SQu Wenruo 	u64 space_cache_ino;
357319b546d7SQu Wenruo 	struct btrfs_file_extent_item *ei;
35745d4f98a2SYan Zheng 	struct btrfs_key key;
357519b546d7SQu Wenruo 	bool found = false;
357619b546d7SQu Wenruo 	int i;
35775d4f98a2SYan Zheng 	int ret;
35785d4f98a2SYan Zheng 
357919b546d7SQu Wenruo 	if (btrfs_header_owner(leaf) != BTRFS_ROOT_TREE_OBJECTID)
358019b546d7SQu Wenruo 		return 0;
35815d4f98a2SYan Zheng 
358219b546d7SQu Wenruo 	for (i = 0; i < btrfs_header_nritems(leaf); i++) {
358319b546d7SQu Wenruo 		btrfs_item_key_to_cpu(leaf, &key, i);
358419b546d7SQu Wenruo 		if (key.type != BTRFS_EXTENT_DATA_KEY)
358519b546d7SQu Wenruo 			continue;
358619b546d7SQu Wenruo 		ei = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
358719b546d7SQu Wenruo 		if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_REG &&
358819b546d7SQu Wenruo 		    btrfs_file_extent_disk_bytenr(leaf, ei) == data_bytenr) {
358919b546d7SQu Wenruo 			found = true;
359019b546d7SQu Wenruo 			space_cache_ino = key.objectid;
359119b546d7SQu Wenruo 			break;
359219b546d7SQu Wenruo 		}
359319b546d7SQu Wenruo 	}
359419b546d7SQu Wenruo 	if (!found)
359519b546d7SQu Wenruo 		return -ENOENT;
359619b546d7SQu Wenruo 	ret = delete_block_group_cache(leaf->fs_info, block_group, NULL,
359719b546d7SQu Wenruo 					space_cache_ino);
35980af3d00bSJosef Bacik 	return ret;
35995d4f98a2SYan Zheng }
36005d4f98a2SYan Zheng 
36015d4f98a2SYan Zheng /*
36022c016dc2SLiu Bo  * helper to find all tree blocks that reference a given data extent
36035d4f98a2SYan Zheng  */
36045d4f98a2SYan Zheng static noinline_for_stack
36055d4f98a2SYan Zheng int add_data_references(struct reloc_control *rc,
36065d4f98a2SYan Zheng 			struct btrfs_key *extent_key,
36075d4f98a2SYan Zheng 			struct btrfs_path *path,
36085d4f98a2SYan Zheng 			struct rb_root *blocks)
36095d4f98a2SYan Zheng {
361019b546d7SQu Wenruo 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
361119b546d7SQu Wenruo 	struct ulist *leaves = NULL;
361219b546d7SQu Wenruo 	struct ulist_iterator leaf_uiter;
361319b546d7SQu Wenruo 	struct ulist_node *ref_node = NULL;
361419b546d7SQu Wenruo 	const u32 blocksize = fs_info->nodesize;
3615647f63bdSFilipe David Borba Manana 	int ret = 0;
36165d4f98a2SYan Zheng 
3617b3b4aa74SDavid Sterba 	btrfs_release_path(path);
361819b546d7SQu Wenruo 	ret = btrfs_find_all_leafs(NULL, fs_info, extent_key->objectid,
361919b546d7SQu Wenruo 				   0, &leaves, NULL, true);
362019b546d7SQu Wenruo 	if (ret < 0)
362119b546d7SQu Wenruo 		return ret;
362219b546d7SQu Wenruo 
362319b546d7SQu Wenruo 	ULIST_ITER_INIT(&leaf_uiter);
362419b546d7SQu Wenruo 	while ((ref_node = ulist_next(leaves, &leaf_uiter))) {
362519b546d7SQu Wenruo 		struct extent_buffer *eb;
362619b546d7SQu Wenruo 
362719b546d7SQu Wenruo 		eb = read_tree_block(fs_info, ref_node->val, 0, 0, NULL);
362819b546d7SQu Wenruo 		if (IS_ERR(eb)) {
362919b546d7SQu Wenruo 			ret = PTR_ERR(eb);
363019b546d7SQu Wenruo 			break;
363119b546d7SQu Wenruo 		}
363219b546d7SQu Wenruo 		ret = delete_v1_space_cache(eb, rc->block_group,
363319b546d7SQu Wenruo 					    extent_key->objectid);
363419b546d7SQu Wenruo 		free_extent_buffer(eb);
363519b546d7SQu Wenruo 		if (ret < 0)
363619b546d7SQu Wenruo 			break;
363719b546d7SQu Wenruo 		ret = __add_tree_block(rc, ref_node->val, blocksize, blocks);
363819b546d7SQu Wenruo 		if (ret < 0)
363919b546d7SQu Wenruo 			break;
364019b546d7SQu Wenruo 	}
364119b546d7SQu Wenruo 	if (ret < 0)
36425d4f98a2SYan Zheng 		free_block_list(blocks);
364319b546d7SQu Wenruo 	ulist_free(leaves);
364419b546d7SQu Wenruo 	return ret;
36455d4f98a2SYan Zheng }
36465d4f98a2SYan Zheng 
36475d4f98a2SYan Zheng /*
36482c016dc2SLiu Bo  * helper to find next unprocessed extent
36495d4f98a2SYan Zheng  */
36505d4f98a2SYan Zheng static noinline_for_stack
3651147d256eSZhaolei int find_next_extent(struct reloc_control *rc, struct btrfs_path *path,
36523fd0a558SYan, Zheng 		     struct btrfs_key *extent_key)
36535d4f98a2SYan Zheng {
36540b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
36555d4f98a2SYan Zheng 	struct btrfs_key key;
36565d4f98a2SYan Zheng 	struct extent_buffer *leaf;
36575d4f98a2SYan Zheng 	u64 start, end, last;
36585d4f98a2SYan Zheng 	int ret;
36595d4f98a2SYan Zheng 
3660b3470b5dSDavid Sterba 	last = rc->block_group->start + rc->block_group->length;
36615d4f98a2SYan Zheng 	while (1) {
36625d4f98a2SYan Zheng 		cond_resched();
36635d4f98a2SYan Zheng 		if (rc->search_start >= last) {
36645d4f98a2SYan Zheng 			ret = 1;
36655d4f98a2SYan Zheng 			break;
36665d4f98a2SYan Zheng 		}
36675d4f98a2SYan Zheng 
36685d4f98a2SYan Zheng 		key.objectid = rc->search_start;
36695d4f98a2SYan Zheng 		key.type = BTRFS_EXTENT_ITEM_KEY;
36705d4f98a2SYan Zheng 		key.offset = 0;
36715d4f98a2SYan Zheng 
36725d4f98a2SYan Zheng 		path->search_commit_root = 1;
36735d4f98a2SYan Zheng 		path->skip_locking = 1;
36745d4f98a2SYan Zheng 		ret = btrfs_search_slot(NULL, rc->extent_root, &key, path,
36755d4f98a2SYan Zheng 					0, 0);
36765d4f98a2SYan Zheng 		if (ret < 0)
36775d4f98a2SYan Zheng 			break;
36785d4f98a2SYan Zheng next:
36795d4f98a2SYan Zheng 		leaf = path->nodes[0];
36805d4f98a2SYan Zheng 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
36815d4f98a2SYan Zheng 			ret = btrfs_next_leaf(rc->extent_root, path);
36825d4f98a2SYan Zheng 			if (ret != 0)
36835d4f98a2SYan Zheng 				break;
36845d4f98a2SYan Zheng 			leaf = path->nodes[0];
36855d4f98a2SYan Zheng 		}
36865d4f98a2SYan Zheng 
36875d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
36885d4f98a2SYan Zheng 		if (key.objectid >= last) {
36895d4f98a2SYan Zheng 			ret = 1;
36905d4f98a2SYan Zheng 			break;
36915d4f98a2SYan Zheng 		}
36925d4f98a2SYan Zheng 
36933173a18fSJosef Bacik 		if (key.type != BTRFS_EXTENT_ITEM_KEY &&
36943173a18fSJosef Bacik 		    key.type != BTRFS_METADATA_ITEM_KEY) {
36953173a18fSJosef Bacik 			path->slots[0]++;
36963173a18fSJosef Bacik 			goto next;
36973173a18fSJosef Bacik 		}
36983173a18fSJosef Bacik 
36993173a18fSJosef Bacik 		if (key.type == BTRFS_EXTENT_ITEM_KEY &&
37005d4f98a2SYan Zheng 		    key.objectid + key.offset <= rc->search_start) {
37015d4f98a2SYan Zheng 			path->slots[0]++;
37025d4f98a2SYan Zheng 			goto next;
37035d4f98a2SYan Zheng 		}
37045d4f98a2SYan Zheng 
37053173a18fSJosef Bacik 		if (key.type == BTRFS_METADATA_ITEM_KEY &&
37060b246afaSJeff Mahoney 		    key.objectid + fs_info->nodesize <=
37073173a18fSJosef Bacik 		    rc->search_start) {
37083173a18fSJosef Bacik 			path->slots[0]++;
37093173a18fSJosef Bacik 			goto next;
37103173a18fSJosef Bacik 		}
37113173a18fSJosef Bacik 
37125d4f98a2SYan Zheng 		ret = find_first_extent_bit(&rc->processed_blocks,
37135d4f98a2SYan Zheng 					    key.objectid, &start, &end,
3714e6138876SJosef Bacik 					    EXTENT_DIRTY, NULL);
37155d4f98a2SYan Zheng 
37165d4f98a2SYan Zheng 		if (ret == 0 && start <= key.objectid) {
3717b3b4aa74SDavid Sterba 			btrfs_release_path(path);
37185d4f98a2SYan Zheng 			rc->search_start = end + 1;
37195d4f98a2SYan Zheng 		} else {
37203173a18fSJosef Bacik 			if (key.type == BTRFS_EXTENT_ITEM_KEY)
37215d4f98a2SYan Zheng 				rc->search_start = key.objectid + key.offset;
37223173a18fSJosef Bacik 			else
37233173a18fSJosef Bacik 				rc->search_start = key.objectid +
37240b246afaSJeff Mahoney 					fs_info->nodesize;
37253fd0a558SYan, Zheng 			memcpy(extent_key, &key, sizeof(key));
37265d4f98a2SYan Zheng 			return 0;
37275d4f98a2SYan Zheng 		}
37285d4f98a2SYan Zheng 	}
3729b3b4aa74SDavid Sterba 	btrfs_release_path(path);
37305d4f98a2SYan Zheng 	return ret;
37315d4f98a2SYan Zheng }
37325d4f98a2SYan Zheng 
37335d4f98a2SYan Zheng static void set_reloc_control(struct reloc_control *rc)
37345d4f98a2SYan Zheng {
37355d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
37367585717fSChris Mason 
37377585717fSChris Mason 	mutex_lock(&fs_info->reloc_mutex);
37385d4f98a2SYan Zheng 	fs_info->reloc_ctl = rc;
37397585717fSChris Mason 	mutex_unlock(&fs_info->reloc_mutex);
37405d4f98a2SYan Zheng }
37415d4f98a2SYan Zheng 
37425d4f98a2SYan Zheng static void unset_reloc_control(struct reloc_control *rc)
37435d4f98a2SYan Zheng {
37445d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
37457585717fSChris Mason 
37467585717fSChris Mason 	mutex_lock(&fs_info->reloc_mutex);
37475d4f98a2SYan Zheng 	fs_info->reloc_ctl = NULL;
37487585717fSChris Mason 	mutex_unlock(&fs_info->reloc_mutex);
37495d4f98a2SYan Zheng }
37505d4f98a2SYan Zheng 
37515d4f98a2SYan Zheng static int check_extent_flags(u64 flags)
37525d4f98a2SYan Zheng {
37535d4f98a2SYan Zheng 	if ((flags & BTRFS_EXTENT_FLAG_DATA) &&
37545d4f98a2SYan Zheng 	    (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
37555d4f98a2SYan Zheng 		return 1;
37565d4f98a2SYan Zheng 	if (!(flags & BTRFS_EXTENT_FLAG_DATA) &&
37575d4f98a2SYan Zheng 	    !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
37585d4f98a2SYan Zheng 		return 1;
37595d4f98a2SYan Zheng 	if ((flags & BTRFS_EXTENT_FLAG_DATA) &&
37605d4f98a2SYan Zheng 	    (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
37615d4f98a2SYan Zheng 		return 1;
37625d4f98a2SYan Zheng 	return 0;
37635d4f98a2SYan Zheng }
37645d4f98a2SYan Zheng 
37653fd0a558SYan, Zheng static noinline_for_stack
37663fd0a558SYan, Zheng int prepare_to_relocate(struct reloc_control *rc)
37673fd0a558SYan, Zheng {
37683fd0a558SYan, Zheng 	struct btrfs_trans_handle *trans;
3769ac2fabacSJosef Bacik 	int ret;
37703fd0a558SYan, Zheng 
37712ff7e61eSJeff Mahoney 	rc->block_rsv = btrfs_alloc_block_rsv(rc->extent_root->fs_info,
377266d8f3ddSMiao Xie 					      BTRFS_BLOCK_RSV_TEMP);
37733fd0a558SYan, Zheng 	if (!rc->block_rsv)
37743fd0a558SYan, Zheng 		return -ENOMEM;
37753fd0a558SYan, Zheng 
37763fd0a558SYan, Zheng 	memset(&rc->cluster, 0, sizeof(rc->cluster));
3777b3470b5dSDavid Sterba 	rc->search_start = rc->block_group->start;
37783fd0a558SYan, Zheng 	rc->extents_found = 0;
37793fd0a558SYan, Zheng 	rc->nodes_relocated = 0;
37803fd0a558SYan, Zheng 	rc->merging_rsv_size = 0;
37810647bf56SWang Shilong 	rc->reserved_bytes = 0;
3782da17066cSJeff Mahoney 	rc->block_rsv->size = rc->extent_root->fs_info->nodesize *
37830647bf56SWang Shilong 			      RELOCATION_RESERVED_NODES;
3784ac2fabacSJosef Bacik 	ret = btrfs_block_rsv_refill(rc->extent_root,
3785ac2fabacSJosef Bacik 				     rc->block_rsv, rc->block_rsv->size,
3786ac2fabacSJosef Bacik 				     BTRFS_RESERVE_FLUSH_ALL);
3787ac2fabacSJosef Bacik 	if (ret)
3788ac2fabacSJosef Bacik 		return ret;
37893fd0a558SYan, Zheng 
37903fd0a558SYan, Zheng 	rc->create_reloc_tree = 1;
37913fd0a558SYan, Zheng 	set_reloc_control(rc);
37923fd0a558SYan, Zheng 
37937a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
379428818947SLiu Bo 	if (IS_ERR(trans)) {
379528818947SLiu Bo 		unset_reloc_control(rc);
379628818947SLiu Bo 		/*
379728818947SLiu Bo 		 * extent tree is not a ref_cow tree and has no reloc_root to
379828818947SLiu Bo 		 * cleanup.  And callers are responsible to free the above
379928818947SLiu Bo 		 * block rsv.
380028818947SLiu Bo 		 */
380128818947SLiu Bo 		return PTR_ERR(trans);
380228818947SLiu Bo 	}
38033a45bb20SJeff Mahoney 	btrfs_commit_transaction(trans);
38043fd0a558SYan, Zheng 	return 0;
38053fd0a558SYan, Zheng }
380676dda93cSYan, Zheng 
38075d4f98a2SYan Zheng static noinline_for_stack int relocate_block_group(struct reloc_control *rc)
38085d4f98a2SYan Zheng {
38092ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
38105d4f98a2SYan Zheng 	struct rb_root blocks = RB_ROOT;
38115d4f98a2SYan Zheng 	struct btrfs_key key;
38125d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans = NULL;
38135d4f98a2SYan Zheng 	struct btrfs_path *path;
38145d4f98a2SYan Zheng 	struct btrfs_extent_item *ei;
38155d4f98a2SYan Zheng 	u64 flags;
38165d4f98a2SYan Zheng 	u32 item_size;
38175d4f98a2SYan Zheng 	int ret;
38185d4f98a2SYan Zheng 	int err = 0;
3819c87f08caSChris Mason 	int progress = 0;
38205d4f98a2SYan Zheng 
38215d4f98a2SYan Zheng 	path = btrfs_alloc_path();
38223fd0a558SYan, Zheng 	if (!path)
38235d4f98a2SYan Zheng 		return -ENOMEM;
3824e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
38253fd0a558SYan, Zheng 
38263fd0a558SYan, Zheng 	ret = prepare_to_relocate(rc);
38273fd0a558SYan, Zheng 	if (ret) {
38283fd0a558SYan, Zheng 		err = ret;
38293fd0a558SYan, Zheng 		goto out_free;
38302423fdfbSJiri Slaby 	}
38315d4f98a2SYan Zheng 
38325d4f98a2SYan Zheng 	while (1) {
38330647bf56SWang Shilong 		rc->reserved_bytes = 0;
38340647bf56SWang Shilong 		ret = btrfs_block_rsv_refill(rc->extent_root,
38350647bf56SWang Shilong 					rc->block_rsv, rc->block_rsv->size,
38360647bf56SWang Shilong 					BTRFS_RESERVE_FLUSH_ALL);
38370647bf56SWang Shilong 		if (ret) {
38380647bf56SWang Shilong 			err = ret;
38390647bf56SWang Shilong 			break;
38400647bf56SWang Shilong 		}
3841c87f08caSChris Mason 		progress++;
3842a22285a6SYan, Zheng 		trans = btrfs_start_transaction(rc->extent_root, 0);
38430f788c58SLiu Bo 		if (IS_ERR(trans)) {
38440f788c58SLiu Bo 			err = PTR_ERR(trans);
38450f788c58SLiu Bo 			trans = NULL;
38460f788c58SLiu Bo 			break;
38470f788c58SLiu Bo 		}
3848c87f08caSChris Mason restart:
38493fd0a558SYan, Zheng 		if (update_backref_cache(trans, &rc->backref_cache)) {
38503a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
385142a657f5SPan Bian 			trans = NULL;
38523fd0a558SYan, Zheng 			continue;
38533fd0a558SYan, Zheng 		}
38543fd0a558SYan, Zheng 
3855147d256eSZhaolei 		ret = find_next_extent(rc, path, &key);
38565d4f98a2SYan Zheng 		if (ret < 0)
38575d4f98a2SYan Zheng 			err = ret;
38585d4f98a2SYan Zheng 		if (ret != 0)
38595d4f98a2SYan Zheng 			break;
38605d4f98a2SYan Zheng 
38615d4f98a2SYan Zheng 		rc->extents_found++;
38625d4f98a2SYan Zheng 
38635d4f98a2SYan Zheng 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
38645d4f98a2SYan Zheng 				    struct btrfs_extent_item);
38653fd0a558SYan, Zheng 		item_size = btrfs_item_size_nr(path->nodes[0], path->slots[0]);
38665d4f98a2SYan Zheng 		if (item_size >= sizeof(*ei)) {
38675d4f98a2SYan Zheng 			flags = btrfs_extent_flags(path->nodes[0], ei);
38685d4f98a2SYan Zheng 			ret = check_extent_flags(flags);
38695d4f98a2SYan Zheng 			BUG_ON(ret);
38706d8ff4e4SDavid Sterba 		} else if (unlikely(item_size == sizeof(struct btrfs_extent_item_v0))) {
3871ba3c2b19SNikolay Borisov 			err = -EINVAL;
3872ba3c2b19SNikolay Borisov 			btrfs_print_v0_err(trans->fs_info);
3873ba3c2b19SNikolay Borisov 			btrfs_abort_transaction(trans, err);
3874ba3c2b19SNikolay Borisov 			break;
38755d4f98a2SYan Zheng 		} else {
38765d4f98a2SYan Zheng 			BUG();
38775d4f98a2SYan Zheng 		}
38785d4f98a2SYan Zheng 
38795d4f98a2SYan Zheng 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
38805d4f98a2SYan Zheng 			ret = add_tree_block(rc, &key, path, &blocks);
38815d4f98a2SYan Zheng 		} else if (rc->stage == UPDATE_DATA_PTRS &&
38825d4f98a2SYan Zheng 			   (flags & BTRFS_EXTENT_FLAG_DATA)) {
38835d4f98a2SYan Zheng 			ret = add_data_references(rc, &key, path, &blocks);
38845d4f98a2SYan Zheng 		} else {
3885b3b4aa74SDavid Sterba 			btrfs_release_path(path);
38865d4f98a2SYan Zheng 			ret = 0;
38875d4f98a2SYan Zheng 		}
38885d4f98a2SYan Zheng 		if (ret < 0) {
38893fd0a558SYan, Zheng 			err = ret;
38905d4f98a2SYan Zheng 			break;
38915d4f98a2SYan Zheng 		}
38925d4f98a2SYan Zheng 
38935d4f98a2SYan Zheng 		if (!RB_EMPTY_ROOT(&blocks)) {
38945d4f98a2SYan Zheng 			ret = relocate_tree_blocks(trans, rc, &blocks);
38955d4f98a2SYan Zheng 			if (ret < 0) {
38963fd0a558SYan, Zheng 				if (ret != -EAGAIN) {
38975d4f98a2SYan Zheng 					err = ret;
38985d4f98a2SYan Zheng 					break;
38995d4f98a2SYan Zheng 				}
39003fd0a558SYan, Zheng 				rc->extents_found--;
39013fd0a558SYan, Zheng 				rc->search_start = key.objectid;
39023fd0a558SYan, Zheng 			}
39035d4f98a2SYan Zheng 		}
39045d4f98a2SYan Zheng 
39053a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
39062ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
39073fd0a558SYan, Zheng 		trans = NULL;
39085d4f98a2SYan Zheng 
39095d4f98a2SYan Zheng 		if (rc->stage == MOVE_DATA_EXTENTS &&
39105d4f98a2SYan Zheng 		    (flags & BTRFS_EXTENT_FLAG_DATA)) {
39115d4f98a2SYan Zheng 			rc->found_file_extent = 1;
39120257bb82SYan, Zheng 			ret = relocate_data_extent(rc->data_inode,
39133fd0a558SYan, Zheng 						   &key, &rc->cluster);
39145d4f98a2SYan Zheng 			if (ret < 0) {
39155d4f98a2SYan Zheng 				err = ret;
39165d4f98a2SYan Zheng 				break;
39175d4f98a2SYan Zheng 			}
39185d4f98a2SYan Zheng 		}
3919f31ea088SQu Wenruo 		if (btrfs_should_cancel_balance(fs_info)) {
3920f31ea088SQu Wenruo 			err = -ECANCELED;
3921f31ea088SQu Wenruo 			break;
3922f31ea088SQu Wenruo 		}
39235d4f98a2SYan Zheng 	}
3924c87f08caSChris Mason 	if (trans && progress && err == -ENOSPC) {
392543a7e99dSNikolay Borisov 		ret = btrfs_force_chunk_alloc(trans, rc->block_group->flags);
39269689457bSShilong Wang 		if (ret == 1) {
3927c87f08caSChris Mason 			err = 0;
3928c87f08caSChris Mason 			progress = 0;
3929c87f08caSChris Mason 			goto restart;
3930c87f08caSChris Mason 		}
3931c87f08caSChris Mason 	}
39323fd0a558SYan, Zheng 
3933b3b4aa74SDavid Sterba 	btrfs_release_path(path);
393491166212SDavid Sterba 	clear_extent_bits(&rc->processed_blocks, 0, (u64)-1, EXTENT_DIRTY);
39355d4f98a2SYan Zheng 
39365d4f98a2SYan Zheng 	if (trans) {
39373a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
39382ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
39395d4f98a2SYan Zheng 	}
39405d4f98a2SYan Zheng 
39410257bb82SYan, Zheng 	if (!err) {
39423fd0a558SYan, Zheng 		ret = relocate_file_extent_cluster(rc->data_inode,
39433fd0a558SYan, Zheng 						   &rc->cluster);
39440257bb82SYan, Zheng 		if (ret < 0)
39450257bb82SYan, Zheng 			err = ret;
39460257bb82SYan, Zheng 	}
39470257bb82SYan, Zheng 
39483fd0a558SYan, Zheng 	rc->create_reloc_tree = 0;
39493fd0a558SYan, Zheng 	set_reloc_control(rc);
39500257bb82SYan, Zheng 
39513fd0a558SYan, Zheng 	backref_cache_cleanup(&rc->backref_cache);
395263f018beSNikolay Borisov 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
39535d4f98a2SYan Zheng 
39547f913c7cSQu Wenruo 	/*
39557f913c7cSQu Wenruo 	 * Even in the case when the relocation is cancelled, we should all go
39567f913c7cSQu Wenruo 	 * through prepare_to_merge() and merge_reloc_roots().
39577f913c7cSQu Wenruo 	 *
39587f913c7cSQu Wenruo 	 * For error (including cancelled balance), prepare_to_merge() will
39597f913c7cSQu Wenruo 	 * mark all reloc trees orphan, then queue them for cleanup in
39607f913c7cSQu Wenruo 	 * merge_reloc_roots()
39617f913c7cSQu Wenruo 	 */
39623fd0a558SYan, Zheng 	err = prepare_to_merge(rc, err);
39635d4f98a2SYan Zheng 
39645d4f98a2SYan Zheng 	merge_reloc_roots(rc);
39655d4f98a2SYan Zheng 
39663fd0a558SYan, Zheng 	rc->merge_reloc_tree = 0;
39675d4f98a2SYan Zheng 	unset_reloc_control(rc);
396863f018beSNikolay Borisov 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
39695d4f98a2SYan Zheng 
39705d4f98a2SYan Zheng 	/* get rid of pinned extents */
39717a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
397262b99540SQu Wenruo 	if (IS_ERR(trans)) {
39733612b495STsutomu Itoh 		err = PTR_ERR(trans);
397462b99540SQu Wenruo 		goto out_free;
397562b99540SQu Wenruo 	}
39763a45bb20SJeff Mahoney 	btrfs_commit_transaction(trans);
39776217b0faSJosef Bacik out_free:
3978d2311e69SQu Wenruo 	ret = clean_dirty_subvols(rc);
3979d2311e69SQu Wenruo 	if (ret < 0 && !err)
3980d2311e69SQu Wenruo 		err = ret;
39812ff7e61eSJeff Mahoney 	btrfs_free_block_rsv(fs_info, rc->block_rsv);
39823fd0a558SYan, Zheng 	btrfs_free_path(path);
39835d4f98a2SYan Zheng 	return err;
39845d4f98a2SYan Zheng }
39855d4f98a2SYan Zheng 
39865d4f98a2SYan Zheng static int __insert_orphan_inode(struct btrfs_trans_handle *trans,
39870257bb82SYan, Zheng 				 struct btrfs_root *root, u64 objectid)
39885d4f98a2SYan Zheng {
39895d4f98a2SYan Zheng 	struct btrfs_path *path;
39905d4f98a2SYan Zheng 	struct btrfs_inode_item *item;
39915d4f98a2SYan Zheng 	struct extent_buffer *leaf;
39925d4f98a2SYan Zheng 	int ret;
39935d4f98a2SYan Zheng 
39945d4f98a2SYan Zheng 	path = btrfs_alloc_path();
39955d4f98a2SYan Zheng 	if (!path)
39965d4f98a2SYan Zheng 		return -ENOMEM;
39975d4f98a2SYan Zheng 
39985d4f98a2SYan Zheng 	ret = btrfs_insert_empty_inode(trans, root, path, objectid);
39995d4f98a2SYan Zheng 	if (ret)
40005d4f98a2SYan Zheng 		goto out;
40015d4f98a2SYan Zheng 
40025d4f98a2SYan Zheng 	leaf = path->nodes[0];
40035d4f98a2SYan Zheng 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item);
4004b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
40055d4f98a2SYan Zheng 	btrfs_set_inode_generation(leaf, item, 1);
40060257bb82SYan, Zheng 	btrfs_set_inode_size(leaf, item, 0);
40075d4f98a2SYan Zheng 	btrfs_set_inode_mode(leaf, item, S_IFREG | 0600);
40083fd0a558SYan, Zheng 	btrfs_set_inode_flags(leaf, item, BTRFS_INODE_NOCOMPRESS |
40093fd0a558SYan, Zheng 					  BTRFS_INODE_PREALLOC);
40105d4f98a2SYan Zheng 	btrfs_mark_buffer_dirty(leaf);
40115d4f98a2SYan Zheng out:
40125d4f98a2SYan Zheng 	btrfs_free_path(path);
40135d4f98a2SYan Zheng 	return ret;
40145d4f98a2SYan Zheng }
40155d4f98a2SYan Zheng 
40165d4f98a2SYan Zheng /*
40175d4f98a2SYan Zheng  * helper to create inode for data relocation.
40185d4f98a2SYan Zheng  * the inode is in data relocation tree and its link count is 0
40195d4f98a2SYan Zheng  */
40203fd0a558SYan, Zheng static noinline_for_stack
40213fd0a558SYan, Zheng struct inode *create_reloc_inode(struct btrfs_fs_info *fs_info,
402232da5386SDavid Sterba 				 struct btrfs_block_group *group)
40235d4f98a2SYan Zheng {
40245d4f98a2SYan Zheng 	struct inode *inode = NULL;
40255d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
40265d4f98a2SYan Zheng 	struct btrfs_root *root;
40275d4f98a2SYan Zheng 	struct btrfs_key key;
40284624900dSZhaolei 	u64 objectid;
40295d4f98a2SYan Zheng 	int err = 0;
40305d4f98a2SYan Zheng 
40315d4f98a2SYan Zheng 	root = read_fs_root(fs_info, BTRFS_DATA_RELOC_TREE_OBJECTID);
40325d4f98a2SYan Zheng 	if (IS_ERR(root))
40335d4f98a2SYan Zheng 		return ERR_CAST(root);
40345d4f98a2SYan Zheng 
4035a22285a6SYan, Zheng 	trans = btrfs_start_transaction(root, 6);
403676deacf0SJosef Bacik 	if (IS_ERR(trans)) {
403700246528SJosef Bacik 		btrfs_put_root(root);
40383fd0a558SYan, Zheng 		return ERR_CAST(trans);
403976deacf0SJosef Bacik 	}
40405d4f98a2SYan Zheng 
4041581bb050SLi Zefan 	err = btrfs_find_free_objectid(root, &objectid);
40425d4f98a2SYan Zheng 	if (err)
40435d4f98a2SYan Zheng 		goto out;
40445d4f98a2SYan Zheng 
40450257bb82SYan, Zheng 	err = __insert_orphan_inode(trans, root, objectid);
40465d4f98a2SYan Zheng 	BUG_ON(err);
40475d4f98a2SYan Zheng 
40485d4f98a2SYan Zheng 	key.objectid = objectid;
40495d4f98a2SYan Zheng 	key.type = BTRFS_INODE_ITEM_KEY;
40505d4f98a2SYan Zheng 	key.offset = 0;
40514c66e0d4SDavid Sterba 	inode = btrfs_iget(fs_info->sb, &key, root);
40522e19f1f9SAl Viro 	BUG_ON(IS_ERR(inode));
4053b3470b5dSDavid Sterba 	BTRFS_I(inode)->index_cnt = group->start;
40545d4f98a2SYan Zheng 
405573f2e545SNikolay Borisov 	err = btrfs_orphan_add(trans, BTRFS_I(inode));
40565d4f98a2SYan Zheng out:
405700246528SJosef Bacik 	btrfs_put_root(root);
40583a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
40592ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
40605d4f98a2SYan Zheng 	if (err) {
40615d4f98a2SYan Zheng 		if (inode)
40625d4f98a2SYan Zheng 			iput(inode);
40635d4f98a2SYan Zheng 		inode = ERR_PTR(err);
40645d4f98a2SYan Zheng 	}
40655d4f98a2SYan Zheng 	return inode;
40665d4f98a2SYan Zheng }
40675d4f98a2SYan Zheng 
4068c258d6e3SQu Wenruo static struct reloc_control *alloc_reloc_control(struct btrfs_fs_info *fs_info)
40693fd0a558SYan, Zheng {
40703fd0a558SYan, Zheng 	struct reloc_control *rc;
40713fd0a558SYan, Zheng 
40723fd0a558SYan, Zheng 	rc = kzalloc(sizeof(*rc), GFP_NOFS);
40733fd0a558SYan, Zheng 	if (!rc)
40743fd0a558SYan, Zheng 		return NULL;
40753fd0a558SYan, Zheng 
40763fd0a558SYan, Zheng 	INIT_LIST_HEAD(&rc->reloc_roots);
4077d2311e69SQu Wenruo 	INIT_LIST_HEAD(&rc->dirty_subvol_roots);
4078584fb121SQu Wenruo 	btrfs_backref_init_cache(fs_info, &rc->backref_cache, 1);
40793fd0a558SYan, Zheng 	mapping_tree_init(&rc->reloc_root_tree);
408043eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &rc->processed_blocks,
408143eb5f29SQu Wenruo 			    IO_TREE_RELOC_BLOCKS, NULL);
40823fd0a558SYan, Zheng 	return rc;
40833fd0a558SYan, Zheng }
40843fd0a558SYan, Zheng 
40851a0afa0eSJosef Bacik static void free_reloc_control(struct reloc_control *rc)
40861a0afa0eSJosef Bacik {
40871a0afa0eSJosef Bacik 	struct mapping_node *node, *tmp;
40881a0afa0eSJosef Bacik 
40891a0afa0eSJosef Bacik 	free_reloc_roots(&rc->reloc_roots);
40901a0afa0eSJosef Bacik 	rbtree_postorder_for_each_entry_safe(node, tmp,
40911a0afa0eSJosef Bacik 			&rc->reloc_root_tree.rb_root, rb_node)
40921a0afa0eSJosef Bacik 		kfree(node);
40931a0afa0eSJosef Bacik 
40941a0afa0eSJosef Bacik 	kfree(rc);
40951a0afa0eSJosef Bacik }
40961a0afa0eSJosef Bacik 
40975d4f98a2SYan Zheng /*
4098ebce0e01SAdam Borowski  * Print the block group being relocated
4099ebce0e01SAdam Borowski  */
4100ebce0e01SAdam Borowski static void describe_relocation(struct btrfs_fs_info *fs_info,
410132da5386SDavid Sterba 				struct btrfs_block_group *block_group)
4102ebce0e01SAdam Borowski {
4103f89e09cfSAnand Jain 	char buf[128] = {'\0'};
4104ebce0e01SAdam Borowski 
4105f89e09cfSAnand Jain 	btrfs_describe_block_groups(block_group->flags, buf, sizeof(buf));
4106ebce0e01SAdam Borowski 
4107ebce0e01SAdam Borowski 	btrfs_info(fs_info,
4108ebce0e01SAdam Borowski 		   "relocating block group %llu flags %s",
4109b3470b5dSDavid Sterba 		   block_group->start, buf);
4110ebce0e01SAdam Borowski }
4111ebce0e01SAdam Borowski 
4112430640e3SQu Wenruo static const char *stage_to_string(int stage)
4113430640e3SQu Wenruo {
4114430640e3SQu Wenruo 	if (stage == MOVE_DATA_EXTENTS)
4115430640e3SQu Wenruo 		return "move data extents";
4116430640e3SQu Wenruo 	if (stage == UPDATE_DATA_PTRS)
4117430640e3SQu Wenruo 		return "update data pointers";
4118430640e3SQu Wenruo 	return "unknown";
4119430640e3SQu Wenruo }
4120430640e3SQu Wenruo 
4121ebce0e01SAdam Borowski /*
41225d4f98a2SYan Zheng  * function to relocate all extents in a block group.
41235d4f98a2SYan Zheng  */
41246bccf3abSJeff Mahoney int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start)
41255d4f98a2SYan Zheng {
412632da5386SDavid Sterba 	struct btrfs_block_group *bg;
41276bccf3abSJeff Mahoney 	struct btrfs_root *extent_root = fs_info->extent_root;
41285d4f98a2SYan Zheng 	struct reloc_control *rc;
41290af3d00bSJosef Bacik 	struct inode *inode;
41300af3d00bSJosef Bacik 	struct btrfs_path *path;
41315d4f98a2SYan Zheng 	int ret;
4132f0486c68SYan, Zheng 	int rw = 0;
41335d4f98a2SYan Zheng 	int err = 0;
41345d4f98a2SYan Zheng 
4135eede2bf3SOmar Sandoval 	bg = btrfs_lookup_block_group(fs_info, group_start);
4136eede2bf3SOmar Sandoval 	if (!bg)
4137eede2bf3SOmar Sandoval 		return -ENOENT;
4138eede2bf3SOmar Sandoval 
4139eede2bf3SOmar Sandoval 	if (btrfs_pinned_by_swapfile(fs_info, bg)) {
4140eede2bf3SOmar Sandoval 		btrfs_put_block_group(bg);
4141eede2bf3SOmar Sandoval 		return -ETXTBSY;
4142eede2bf3SOmar Sandoval 	}
4143eede2bf3SOmar Sandoval 
4144c258d6e3SQu Wenruo 	rc = alloc_reloc_control(fs_info);
4145eede2bf3SOmar Sandoval 	if (!rc) {
4146eede2bf3SOmar Sandoval 		btrfs_put_block_group(bg);
41475d4f98a2SYan Zheng 		return -ENOMEM;
4148eede2bf3SOmar Sandoval 	}
41495d4f98a2SYan Zheng 
4150f0486c68SYan, Zheng 	rc->extent_root = extent_root;
4151eede2bf3SOmar Sandoval 	rc->block_group = bg;
41525d4f98a2SYan Zheng 
4153b12de528SQu Wenruo 	ret = btrfs_inc_block_group_ro(rc->block_group, true);
4154f0486c68SYan, Zheng 	if (ret) {
4155f0486c68SYan, Zheng 		err = ret;
4156f0486c68SYan, Zheng 		goto out;
4157f0486c68SYan, Zheng 	}
4158f0486c68SYan, Zheng 	rw = 1;
4159f0486c68SYan, Zheng 
41600af3d00bSJosef Bacik 	path = btrfs_alloc_path();
41610af3d00bSJosef Bacik 	if (!path) {
41620af3d00bSJosef Bacik 		err = -ENOMEM;
41630af3d00bSJosef Bacik 		goto out;
41640af3d00bSJosef Bacik 	}
41650af3d00bSJosef Bacik 
41667949f339SDavid Sterba 	inode = lookup_free_space_inode(rc->block_group, path);
41670af3d00bSJosef Bacik 	btrfs_free_path(path);
41680af3d00bSJosef Bacik 
41690af3d00bSJosef Bacik 	if (!IS_ERR(inode))
41701bbc621eSChris Mason 		ret = delete_block_group_cache(fs_info, rc->block_group, inode, 0);
41710af3d00bSJosef Bacik 	else
41720af3d00bSJosef Bacik 		ret = PTR_ERR(inode);
41730af3d00bSJosef Bacik 
41740af3d00bSJosef Bacik 	if (ret && ret != -ENOENT) {
41750af3d00bSJosef Bacik 		err = ret;
41760af3d00bSJosef Bacik 		goto out;
41770af3d00bSJosef Bacik 	}
41780af3d00bSJosef Bacik 
41795d4f98a2SYan Zheng 	rc->data_inode = create_reloc_inode(fs_info, rc->block_group);
41805d4f98a2SYan Zheng 	if (IS_ERR(rc->data_inode)) {
41815d4f98a2SYan Zheng 		err = PTR_ERR(rc->data_inode);
41825d4f98a2SYan Zheng 		rc->data_inode = NULL;
41835d4f98a2SYan Zheng 		goto out;
41845d4f98a2SYan Zheng 	}
41855d4f98a2SYan Zheng 
41860b246afaSJeff Mahoney 	describe_relocation(fs_info, rc->block_group);
41875d4f98a2SYan Zheng 
41889cfa3e34SFilipe Manana 	btrfs_wait_block_group_reservations(rc->block_group);
4189f78c436cSFilipe Manana 	btrfs_wait_nocow_writers(rc->block_group);
41906374e57aSChris Mason 	btrfs_wait_ordered_roots(fs_info, U64_MAX,
4191b3470b5dSDavid Sterba 				 rc->block_group->start,
4192b3470b5dSDavid Sterba 				 rc->block_group->length);
41935d4f98a2SYan Zheng 
41945d4f98a2SYan Zheng 	while (1) {
4195430640e3SQu Wenruo 		int finishes_stage;
4196430640e3SQu Wenruo 
419776dda93cSYan, Zheng 		mutex_lock(&fs_info->cleaner_mutex);
41985d4f98a2SYan Zheng 		ret = relocate_block_group(rc);
419976dda93cSYan, Zheng 		mutex_unlock(&fs_info->cleaner_mutex);
4200ff612ba7SJosef Bacik 		if (ret < 0)
42015d4f98a2SYan Zheng 			err = ret;
4202ff612ba7SJosef Bacik 
4203430640e3SQu Wenruo 		finishes_stage = rc->stage;
4204ff612ba7SJosef Bacik 		/*
4205ff612ba7SJosef Bacik 		 * We may have gotten ENOSPC after we already dirtied some
4206ff612ba7SJosef Bacik 		 * extents.  If writeout happens while we're relocating a
4207ff612ba7SJosef Bacik 		 * different block group we could end up hitting the
4208ff612ba7SJosef Bacik 		 * BUG_ON(rc->stage == UPDATE_DATA_PTRS) in
4209ff612ba7SJosef Bacik 		 * btrfs_reloc_cow_block.  Make sure we write everything out
4210ff612ba7SJosef Bacik 		 * properly so we don't trip over this problem, and then break
4211ff612ba7SJosef Bacik 		 * out of the loop if we hit an error.
4212ff612ba7SJosef Bacik 		 */
4213ff612ba7SJosef Bacik 		if (rc->stage == MOVE_DATA_EXTENTS && rc->found_file_extent) {
4214ff612ba7SJosef Bacik 			ret = btrfs_wait_ordered_range(rc->data_inode, 0,
4215ff612ba7SJosef Bacik 						       (u64)-1);
4216ff612ba7SJosef Bacik 			if (ret)
4217ff612ba7SJosef Bacik 				err = ret;
4218ff612ba7SJosef Bacik 			invalidate_mapping_pages(rc->data_inode->i_mapping,
4219ff612ba7SJosef Bacik 						 0, -1);
4220ff612ba7SJosef Bacik 			rc->stage = UPDATE_DATA_PTRS;
42215d4f98a2SYan Zheng 		}
42225d4f98a2SYan Zheng 
4223ff612ba7SJosef Bacik 		if (err < 0)
4224ff612ba7SJosef Bacik 			goto out;
4225ff612ba7SJosef Bacik 
42265d4f98a2SYan Zheng 		if (rc->extents_found == 0)
42275d4f98a2SYan Zheng 			break;
42285d4f98a2SYan Zheng 
4229430640e3SQu Wenruo 		btrfs_info(fs_info, "found %llu extents, stage: %s",
4230430640e3SQu Wenruo 			   rc->extents_found, stage_to_string(finishes_stage));
42315d4f98a2SYan Zheng 	}
42325d4f98a2SYan Zheng 
42335d4f98a2SYan Zheng 	WARN_ON(rc->block_group->pinned > 0);
42345d4f98a2SYan Zheng 	WARN_ON(rc->block_group->reserved > 0);
4235bf38be65SDavid Sterba 	WARN_ON(rc->block_group->used > 0);
42365d4f98a2SYan Zheng out:
4237f0486c68SYan, Zheng 	if (err && rw)
42382ff7e61eSJeff Mahoney 		btrfs_dec_block_group_ro(rc->block_group);
42395d4f98a2SYan Zheng 	iput(rc->data_inode);
42405d4f98a2SYan Zheng 	btrfs_put_block_group(rc->block_group);
42411a0afa0eSJosef Bacik 	free_reloc_control(rc);
42425d4f98a2SYan Zheng 	return err;
42435d4f98a2SYan Zheng }
42445d4f98a2SYan Zheng 
424576dda93cSYan, Zheng static noinline_for_stack int mark_garbage_root(struct btrfs_root *root)
424676dda93cSYan, Zheng {
42470b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
424876dda93cSYan, Zheng 	struct btrfs_trans_handle *trans;
424979787eaaSJeff Mahoney 	int ret, err;
425076dda93cSYan, Zheng 
42510b246afaSJeff Mahoney 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
425279787eaaSJeff Mahoney 	if (IS_ERR(trans))
425379787eaaSJeff Mahoney 		return PTR_ERR(trans);
425476dda93cSYan, Zheng 
425576dda93cSYan, Zheng 	memset(&root->root_item.drop_progress, 0,
425676dda93cSYan, Zheng 		sizeof(root->root_item.drop_progress));
425776dda93cSYan, Zheng 	root->root_item.drop_level = 0;
425876dda93cSYan, Zheng 	btrfs_set_root_refs(&root->root_item, 0);
42590b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
426076dda93cSYan, Zheng 				&root->root_key, &root->root_item);
426176dda93cSYan, Zheng 
42623a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
426379787eaaSJeff Mahoney 	if (err)
426479787eaaSJeff Mahoney 		return err;
426579787eaaSJeff Mahoney 	return ret;
426676dda93cSYan, Zheng }
426776dda93cSYan, Zheng 
42685d4f98a2SYan Zheng /*
42695d4f98a2SYan Zheng  * recover relocation interrupted by system crash.
42705d4f98a2SYan Zheng  *
42715d4f98a2SYan Zheng  * this function resumes merging reloc trees with corresponding fs trees.
42725d4f98a2SYan Zheng  * this is important for keeping the sharing of tree blocks
42735d4f98a2SYan Zheng  */
42745d4f98a2SYan Zheng int btrfs_recover_relocation(struct btrfs_root *root)
42755d4f98a2SYan Zheng {
42760b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
42775d4f98a2SYan Zheng 	LIST_HEAD(reloc_roots);
42785d4f98a2SYan Zheng 	struct btrfs_key key;
42795d4f98a2SYan Zheng 	struct btrfs_root *fs_root;
42805d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
42815d4f98a2SYan Zheng 	struct btrfs_path *path;
42825d4f98a2SYan Zheng 	struct extent_buffer *leaf;
42835d4f98a2SYan Zheng 	struct reloc_control *rc = NULL;
42845d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
42855d4f98a2SYan Zheng 	int ret;
42865d4f98a2SYan Zheng 	int err = 0;
42875d4f98a2SYan Zheng 
42885d4f98a2SYan Zheng 	path = btrfs_alloc_path();
42895d4f98a2SYan Zheng 	if (!path)
42905d4f98a2SYan Zheng 		return -ENOMEM;
4291e4058b54SDavid Sterba 	path->reada = READA_BACK;
42925d4f98a2SYan Zheng 
42935d4f98a2SYan Zheng 	key.objectid = BTRFS_TREE_RELOC_OBJECTID;
42945d4f98a2SYan Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
42955d4f98a2SYan Zheng 	key.offset = (u64)-1;
42965d4f98a2SYan Zheng 
42975d4f98a2SYan Zheng 	while (1) {
42980b246afaSJeff Mahoney 		ret = btrfs_search_slot(NULL, fs_info->tree_root, &key,
42995d4f98a2SYan Zheng 					path, 0, 0);
43005d4f98a2SYan Zheng 		if (ret < 0) {
43015d4f98a2SYan Zheng 			err = ret;
43025d4f98a2SYan Zheng 			goto out;
43035d4f98a2SYan Zheng 		}
43045d4f98a2SYan Zheng 		if (ret > 0) {
43055d4f98a2SYan Zheng 			if (path->slots[0] == 0)
43065d4f98a2SYan Zheng 				break;
43075d4f98a2SYan Zheng 			path->slots[0]--;
43085d4f98a2SYan Zheng 		}
43095d4f98a2SYan Zheng 		leaf = path->nodes[0];
43105d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4311b3b4aa74SDavid Sterba 		btrfs_release_path(path);
43125d4f98a2SYan Zheng 
43135d4f98a2SYan Zheng 		if (key.objectid != BTRFS_TREE_RELOC_OBJECTID ||
43145d4f98a2SYan Zheng 		    key.type != BTRFS_ROOT_ITEM_KEY)
43155d4f98a2SYan Zheng 			break;
43165d4f98a2SYan Zheng 
43173dbf1738SJosef Bacik 		reloc_root = btrfs_read_tree_root(root, &key);
43185d4f98a2SYan Zheng 		if (IS_ERR(reloc_root)) {
43195d4f98a2SYan Zheng 			err = PTR_ERR(reloc_root);
43205d4f98a2SYan Zheng 			goto out;
43215d4f98a2SYan Zheng 		}
43225d4f98a2SYan Zheng 
43233dbf1738SJosef Bacik 		set_bit(BTRFS_ROOT_REF_COWS, &reloc_root->state);
43245d4f98a2SYan Zheng 		list_add(&reloc_root->root_list, &reloc_roots);
43255d4f98a2SYan Zheng 
43265d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
43270b246afaSJeff Mahoney 			fs_root = read_fs_root(fs_info,
43285d4f98a2SYan Zheng 					       reloc_root->root_key.offset);
43295d4f98a2SYan Zheng 			if (IS_ERR(fs_root)) {
433076dda93cSYan, Zheng 				ret = PTR_ERR(fs_root);
433176dda93cSYan, Zheng 				if (ret != -ENOENT) {
433276dda93cSYan, Zheng 					err = ret;
43335d4f98a2SYan Zheng 					goto out;
43345d4f98a2SYan Zheng 				}
433579787eaaSJeff Mahoney 				ret = mark_garbage_root(reloc_root);
433679787eaaSJeff Mahoney 				if (ret < 0) {
433779787eaaSJeff Mahoney 					err = ret;
433879787eaaSJeff Mahoney 					goto out;
433979787eaaSJeff Mahoney 				}
4340932fd26dSJosef Bacik 			} else {
434100246528SJosef Bacik 				btrfs_put_root(fs_root);
434276dda93cSYan, Zheng 			}
43435d4f98a2SYan Zheng 		}
43445d4f98a2SYan Zheng 
43455d4f98a2SYan Zheng 		if (key.offset == 0)
43465d4f98a2SYan Zheng 			break;
43475d4f98a2SYan Zheng 
43485d4f98a2SYan Zheng 		key.offset--;
43495d4f98a2SYan Zheng 	}
4350b3b4aa74SDavid Sterba 	btrfs_release_path(path);
43515d4f98a2SYan Zheng 
43525d4f98a2SYan Zheng 	if (list_empty(&reloc_roots))
43535d4f98a2SYan Zheng 		goto out;
43545d4f98a2SYan Zheng 
4355c258d6e3SQu Wenruo 	rc = alloc_reloc_control(fs_info);
43565d4f98a2SYan Zheng 	if (!rc) {
43575d4f98a2SYan Zheng 		err = -ENOMEM;
43585d4f98a2SYan Zheng 		goto out;
43595d4f98a2SYan Zheng 	}
43605d4f98a2SYan Zheng 
43610b246afaSJeff Mahoney 	rc->extent_root = fs_info->extent_root;
43625d4f98a2SYan Zheng 
43635d4f98a2SYan Zheng 	set_reloc_control(rc);
43645d4f98a2SYan Zheng 
43657a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
43663612b495STsutomu Itoh 	if (IS_ERR(trans)) {
43673612b495STsutomu Itoh 		err = PTR_ERR(trans);
4368fb2d83eeSJosef Bacik 		goto out_unset;
43693612b495STsutomu Itoh 	}
43703fd0a558SYan, Zheng 
43713fd0a558SYan, Zheng 	rc->merge_reloc_tree = 1;
43723fd0a558SYan, Zheng 
43735d4f98a2SYan Zheng 	while (!list_empty(&reloc_roots)) {
43745d4f98a2SYan Zheng 		reloc_root = list_entry(reloc_roots.next,
43755d4f98a2SYan Zheng 					struct btrfs_root, root_list);
43765d4f98a2SYan Zheng 		list_del(&reloc_root->root_list);
43775d4f98a2SYan Zheng 
43785d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) == 0) {
43795d4f98a2SYan Zheng 			list_add_tail(&reloc_root->root_list,
43805d4f98a2SYan Zheng 				      &rc->reloc_roots);
43815d4f98a2SYan Zheng 			continue;
43825d4f98a2SYan Zheng 		}
43835d4f98a2SYan Zheng 
43840b246afaSJeff Mahoney 		fs_root = read_fs_root(fs_info, reloc_root->root_key.offset);
438579787eaaSJeff Mahoney 		if (IS_ERR(fs_root)) {
438679787eaaSJeff Mahoney 			err = PTR_ERR(fs_root);
4387ca1aa281SJosef Bacik 			list_add_tail(&reloc_root->root_list, &reloc_roots);
43881402d17dSXiyu Yang 			btrfs_end_transaction(trans);
4389fb2d83eeSJosef Bacik 			goto out_unset;
439079787eaaSJeff Mahoney 		}
43915d4f98a2SYan Zheng 
4392ffd7b339SJeff Mahoney 		err = __add_reloc_root(reloc_root);
439379787eaaSJeff Mahoney 		BUG_ON(err < 0); /* -ENOMEM or logic error */
4394f44deb74SJosef Bacik 		fs_root->reloc_root = btrfs_grab_root(reloc_root);
439500246528SJosef Bacik 		btrfs_put_root(fs_root);
43965d4f98a2SYan Zheng 	}
43975d4f98a2SYan Zheng 
43983a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
439979787eaaSJeff Mahoney 	if (err)
4400fb2d83eeSJosef Bacik 		goto out_unset;
44015d4f98a2SYan Zheng 
44025d4f98a2SYan Zheng 	merge_reloc_roots(rc);
44035d4f98a2SYan Zheng 
44045d4f98a2SYan Zheng 	unset_reloc_control(rc);
44055d4f98a2SYan Zheng 
44067a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
440762b99540SQu Wenruo 	if (IS_ERR(trans)) {
44083612b495STsutomu Itoh 		err = PTR_ERR(trans);
44096217b0faSJosef Bacik 		goto out_clean;
441062b99540SQu Wenruo 	}
44113a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
44126217b0faSJosef Bacik out_clean:
4413d2311e69SQu Wenruo 	ret = clean_dirty_subvols(rc);
4414d2311e69SQu Wenruo 	if (ret < 0 && !err)
4415d2311e69SQu Wenruo 		err = ret;
4416fb2d83eeSJosef Bacik out_unset:
4417fb2d83eeSJosef Bacik 	unset_reloc_control(rc);
44181a0afa0eSJosef Bacik 	free_reloc_control(rc);
44193612b495STsutomu Itoh out:
4420aca1bba6SLiu Bo 	if (!list_empty(&reloc_roots))
4421aca1bba6SLiu Bo 		free_reloc_roots(&reloc_roots);
4422aca1bba6SLiu Bo 
44235d4f98a2SYan Zheng 	btrfs_free_path(path);
44245d4f98a2SYan Zheng 
44255d4f98a2SYan Zheng 	if (err == 0) {
44265d4f98a2SYan Zheng 		/* cleanup orphan inode in data relocation tree */
44270b246afaSJeff Mahoney 		fs_root = read_fs_root(fs_info, BTRFS_DATA_RELOC_TREE_OBJECTID);
4428932fd26dSJosef Bacik 		if (IS_ERR(fs_root)) {
44295d4f98a2SYan Zheng 			err = PTR_ERR(fs_root);
4430932fd26dSJosef Bacik 		} else {
443166b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(fs_root);
443200246528SJosef Bacik 			btrfs_put_root(fs_root);
4433932fd26dSJosef Bacik 		}
4434932fd26dSJosef Bacik 	}
44355d4f98a2SYan Zheng 	return err;
44365d4f98a2SYan Zheng }
44375d4f98a2SYan Zheng 
44385d4f98a2SYan Zheng /*
44395d4f98a2SYan Zheng  * helper to add ordered checksum for data relocation.
44405d4f98a2SYan Zheng  *
44415d4f98a2SYan Zheng  * cloning checksum properly handles the nodatasum extents.
44425d4f98a2SYan Zheng  * it also saves CPU time to re-calculate the checksum.
44435d4f98a2SYan Zheng  */
44445d4f98a2SYan Zheng int btrfs_reloc_clone_csums(struct inode *inode, u64 file_pos, u64 len)
44455d4f98a2SYan Zheng {
44460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
44475d4f98a2SYan Zheng 	struct btrfs_ordered_sum *sums;
44485d4f98a2SYan Zheng 	struct btrfs_ordered_extent *ordered;
44495d4f98a2SYan Zheng 	int ret;
44505d4f98a2SYan Zheng 	u64 disk_bytenr;
44514577b014SJosef Bacik 	u64 new_bytenr;
44525d4f98a2SYan Zheng 	LIST_HEAD(list);
44535d4f98a2SYan Zheng 
44545d4f98a2SYan Zheng 	ordered = btrfs_lookup_ordered_extent(inode, file_pos);
4455bffe633eSOmar Sandoval 	BUG_ON(ordered->file_offset != file_pos || ordered->num_bytes != len);
44565d4f98a2SYan Zheng 
44575d4f98a2SYan Zheng 	disk_bytenr = file_pos + BTRFS_I(inode)->index_cnt;
44580b246afaSJeff Mahoney 	ret = btrfs_lookup_csums_range(fs_info->csum_root, disk_bytenr,
4459a2de733cSArne Jansen 				       disk_bytenr + len - 1, &list, 0);
446079787eaaSJeff Mahoney 	if (ret)
446179787eaaSJeff Mahoney 		goto out;
44625d4f98a2SYan Zheng 
44635d4f98a2SYan Zheng 	while (!list_empty(&list)) {
44645d4f98a2SYan Zheng 		sums = list_entry(list.next, struct btrfs_ordered_sum, list);
44655d4f98a2SYan Zheng 		list_del_init(&sums->list);
44665d4f98a2SYan Zheng 
44674577b014SJosef Bacik 		/*
44684577b014SJosef Bacik 		 * We need to offset the new_bytenr based on where the csum is.
44694577b014SJosef Bacik 		 * We need to do this because we will read in entire prealloc
44704577b014SJosef Bacik 		 * extents but we may have written to say the middle of the
44714577b014SJosef Bacik 		 * prealloc extent, so we need to make sure the csum goes with
44724577b014SJosef Bacik 		 * the right disk offset.
44734577b014SJosef Bacik 		 *
44744577b014SJosef Bacik 		 * We can do this because the data reloc inode refers strictly
44754577b014SJosef Bacik 		 * to the on disk bytes, so we don't have to worry about
44764577b014SJosef Bacik 		 * disk_len vs real len like with real inodes since it's all
44774577b014SJosef Bacik 		 * disk length.
44784577b014SJosef Bacik 		 */
4479bffe633eSOmar Sandoval 		new_bytenr = ordered->disk_bytenr + sums->bytenr - disk_bytenr;
44804577b014SJosef Bacik 		sums->bytenr = new_bytenr;
44815d4f98a2SYan Zheng 
4482f9756261SNikolay Borisov 		btrfs_add_ordered_sum(ordered, sums);
44835d4f98a2SYan Zheng 	}
448479787eaaSJeff Mahoney out:
44855d4f98a2SYan Zheng 	btrfs_put_ordered_extent(ordered);
4486411fc6bcSAndi Kleen 	return ret;
44875d4f98a2SYan Zheng }
44883fd0a558SYan, Zheng 
448983d4cfd4SJosef Bacik int btrfs_reloc_cow_block(struct btrfs_trans_handle *trans,
44903fd0a558SYan, Zheng 			  struct btrfs_root *root, struct extent_buffer *buf,
44913fd0a558SYan, Zheng 			  struct extent_buffer *cow)
44923fd0a558SYan, Zheng {
44930b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
44943fd0a558SYan, Zheng 	struct reloc_control *rc;
4495a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
44963fd0a558SYan, Zheng 	int first_cow = 0;
44973fd0a558SYan, Zheng 	int level;
449883d4cfd4SJosef Bacik 	int ret = 0;
44993fd0a558SYan, Zheng 
45000b246afaSJeff Mahoney 	rc = fs_info->reloc_ctl;
45013fd0a558SYan, Zheng 	if (!rc)
450283d4cfd4SJosef Bacik 		return 0;
45033fd0a558SYan, Zheng 
45043fd0a558SYan, Zheng 	BUG_ON(rc->stage == UPDATE_DATA_PTRS &&
45053fd0a558SYan, Zheng 	       root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID);
45063fd0a558SYan, Zheng 
45073fd0a558SYan, Zheng 	level = btrfs_header_level(buf);
45083fd0a558SYan, Zheng 	if (btrfs_header_generation(buf) <=
45093fd0a558SYan, Zheng 	    btrfs_root_last_snapshot(&root->root_item))
45103fd0a558SYan, Zheng 		first_cow = 1;
45113fd0a558SYan, Zheng 
45123fd0a558SYan, Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID &&
45133fd0a558SYan, Zheng 	    rc->create_reloc_tree) {
45143fd0a558SYan, Zheng 		WARN_ON(!first_cow && level == 0);
45153fd0a558SYan, Zheng 
45163fd0a558SYan, Zheng 		node = rc->backref_cache.path[level];
45173fd0a558SYan, Zheng 		BUG_ON(node->bytenr != buf->start &&
45183fd0a558SYan, Zheng 		       node->new_bytenr != buf->start);
45193fd0a558SYan, Zheng 
4520b0fe7078SQu Wenruo 		btrfs_backref_drop_node_buffer(node);
452167439dadSDavid Sterba 		atomic_inc(&cow->refs);
45223fd0a558SYan, Zheng 		node->eb = cow;
45233fd0a558SYan, Zheng 		node->new_bytenr = cow->start;
45243fd0a558SYan, Zheng 
45253fd0a558SYan, Zheng 		if (!node->pending) {
45263fd0a558SYan, Zheng 			list_move_tail(&node->list,
45273fd0a558SYan, Zheng 				       &rc->backref_cache.pending[level]);
45283fd0a558SYan, Zheng 			node->pending = 1;
45293fd0a558SYan, Zheng 		}
45303fd0a558SYan, Zheng 
45313fd0a558SYan, Zheng 		if (first_cow)
45329569cc20SQu Wenruo 			mark_block_processed(rc, node);
45333fd0a558SYan, Zheng 
45343fd0a558SYan, Zheng 		if (first_cow && level > 0)
45353fd0a558SYan, Zheng 			rc->nodes_relocated += buf->len;
45363fd0a558SYan, Zheng 	}
45373fd0a558SYan, Zheng 
453883d4cfd4SJosef Bacik 	if (level == 0 && first_cow && rc->stage == UPDATE_DATA_PTRS)
45393fd0a558SYan, Zheng 		ret = replace_file_extents(trans, rc, root, cow);
454083d4cfd4SJosef Bacik 	return ret;
45413fd0a558SYan, Zheng }
45423fd0a558SYan, Zheng 
45433fd0a558SYan, Zheng /*
45443fd0a558SYan, Zheng  * called before creating snapshot. it calculates metadata reservation
454501327610SNicholas D Steeves  * required for relocating tree blocks in the snapshot
45463fd0a558SYan, Zheng  */
4547147d256eSZhaolei void btrfs_reloc_pre_snapshot(struct btrfs_pending_snapshot *pending,
45483fd0a558SYan, Zheng 			      u64 *bytes_to_reserve)
45493fd0a558SYan, Zheng {
455010995c04SQu Wenruo 	struct btrfs_root *root = pending->root;
455110995c04SQu Wenruo 	struct reloc_control *rc = root->fs_info->reloc_ctl;
45523fd0a558SYan, Zheng 
45536282675eSQu Wenruo 	if (!rc || !have_reloc_root(root))
45543fd0a558SYan, Zheng 		return;
45553fd0a558SYan, Zheng 
45563fd0a558SYan, Zheng 	if (!rc->merge_reloc_tree)
45573fd0a558SYan, Zheng 		return;
45583fd0a558SYan, Zheng 
45593fd0a558SYan, Zheng 	root = root->reloc_root;
45603fd0a558SYan, Zheng 	BUG_ON(btrfs_root_refs(&root->root_item) == 0);
45613fd0a558SYan, Zheng 	/*
45623fd0a558SYan, Zheng 	 * relocation is in the stage of merging trees. the space
45633fd0a558SYan, Zheng 	 * used by merging a reloc tree is twice the size of
45643fd0a558SYan, Zheng 	 * relocated tree nodes in the worst case. half for cowing
45653fd0a558SYan, Zheng 	 * the reloc tree, half for cowing the fs tree. the space
45663fd0a558SYan, Zheng 	 * used by cowing the reloc tree will be freed after the
45673fd0a558SYan, Zheng 	 * tree is dropped. if we create snapshot, cowing the fs
45683fd0a558SYan, Zheng 	 * tree may use more space than it frees. so we need
45693fd0a558SYan, Zheng 	 * reserve extra space.
45703fd0a558SYan, Zheng 	 */
45713fd0a558SYan, Zheng 	*bytes_to_reserve += rc->nodes_relocated;
45723fd0a558SYan, Zheng }
45733fd0a558SYan, Zheng 
45743fd0a558SYan, Zheng /*
45753fd0a558SYan, Zheng  * called after snapshot is created. migrate block reservation
45763fd0a558SYan, Zheng  * and create reloc root for the newly created snapshot
4577f44deb74SJosef Bacik  *
4578f44deb74SJosef Bacik  * This is similar to btrfs_init_reloc_root(), we come out of here with two
4579f44deb74SJosef Bacik  * references held on the reloc_root, one for root->reloc_root and one for
4580f44deb74SJosef Bacik  * rc->reloc_roots.
45813fd0a558SYan, Zheng  */
458249b25e05SJeff Mahoney int btrfs_reloc_post_snapshot(struct btrfs_trans_handle *trans,
45833fd0a558SYan, Zheng 			       struct btrfs_pending_snapshot *pending)
45843fd0a558SYan, Zheng {
45853fd0a558SYan, Zheng 	struct btrfs_root *root = pending->root;
45863fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
45873fd0a558SYan, Zheng 	struct btrfs_root *new_root;
458810995c04SQu Wenruo 	struct reloc_control *rc = root->fs_info->reloc_ctl;
45893fd0a558SYan, Zheng 	int ret;
45903fd0a558SYan, Zheng 
45916282675eSQu Wenruo 	if (!rc || !have_reloc_root(root))
459249b25e05SJeff Mahoney 		return 0;
45933fd0a558SYan, Zheng 
45943fd0a558SYan, Zheng 	rc = root->fs_info->reloc_ctl;
45953fd0a558SYan, Zheng 	rc->merging_rsv_size += rc->nodes_relocated;
45963fd0a558SYan, Zheng 
45973fd0a558SYan, Zheng 	if (rc->merge_reloc_tree) {
45983fd0a558SYan, Zheng 		ret = btrfs_block_rsv_migrate(&pending->block_rsv,
45993fd0a558SYan, Zheng 					      rc->block_rsv,
46003a584174SLu Fengqi 					      rc->nodes_relocated, true);
460149b25e05SJeff Mahoney 		if (ret)
460249b25e05SJeff Mahoney 			return ret;
46033fd0a558SYan, Zheng 	}
46043fd0a558SYan, Zheng 
46053fd0a558SYan, Zheng 	new_root = pending->snap;
46063fd0a558SYan, Zheng 	reloc_root = create_reloc_root(trans, root->reloc_root,
46073fd0a558SYan, Zheng 				       new_root->root_key.objectid);
460849b25e05SJeff Mahoney 	if (IS_ERR(reloc_root))
460949b25e05SJeff Mahoney 		return PTR_ERR(reloc_root);
46103fd0a558SYan, Zheng 
4611ffd7b339SJeff Mahoney 	ret = __add_reloc_root(reloc_root);
4612ffd7b339SJeff Mahoney 	BUG_ON(ret < 0);
4613f44deb74SJosef Bacik 	new_root->reloc_root = btrfs_grab_root(reloc_root);
46143fd0a558SYan, Zheng 
461549b25e05SJeff Mahoney 	if (rc->create_reloc_tree)
46163fd0a558SYan, Zheng 		ret = clone_backref_node(trans, rc, root, reloc_root);
461749b25e05SJeff Mahoney 	return ret;
46183fd0a558SYan, Zheng }
4619