xref: /openbmc/linux/fs/btrfs/relocation.c (revision 982c92cb)
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 
1785d4f98a2SYan Zheng /*
1795d4f98a2SYan Zheng  * walk up backref nodes until reach node presents tree root
1805d4f98a2SYan Zheng  */
181a26195a5SQu Wenruo static struct btrfs_backref_node *walk_up_backref(
182a26195a5SQu Wenruo 		struct btrfs_backref_node *node,
183a26195a5SQu Wenruo 		struct btrfs_backref_edge *edges[], int *index)
1845d4f98a2SYan Zheng {
185a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
1865d4f98a2SYan Zheng 	int idx = *index;
1875d4f98a2SYan Zheng 
1885d4f98a2SYan Zheng 	while (!list_empty(&node->upper)) {
1895d4f98a2SYan Zheng 		edge = list_entry(node->upper.next,
190a26195a5SQu Wenruo 				  struct btrfs_backref_edge, list[LOWER]);
1915d4f98a2SYan Zheng 		edges[idx++] = edge;
1925d4f98a2SYan Zheng 		node = edge->node[UPPER];
1935d4f98a2SYan Zheng 	}
1943fd0a558SYan, Zheng 	BUG_ON(node->detached);
1955d4f98a2SYan Zheng 	*index = idx;
1965d4f98a2SYan Zheng 	return node;
1975d4f98a2SYan Zheng }
1985d4f98a2SYan Zheng 
1995d4f98a2SYan Zheng /*
2005d4f98a2SYan Zheng  * walk down backref nodes to find start of next reference path
2015d4f98a2SYan Zheng  */
202a26195a5SQu Wenruo static struct btrfs_backref_node *walk_down_backref(
203a26195a5SQu Wenruo 		struct btrfs_backref_edge *edges[], int *index)
2045d4f98a2SYan Zheng {
205a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
206a26195a5SQu Wenruo 	struct btrfs_backref_node *lower;
2075d4f98a2SYan Zheng 	int idx = *index;
2085d4f98a2SYan Zheng 
2095d4f98a2SYan Zheng 	while (idx > 0) {
2105d4f98a2SYan Zheng 		edge = edges[idx - 1];
2115d4f98a2SYan Zheng 		lower = edge->node[LOWER];
2125d4f98a2SYan Zheng 		if (list_is_last(&edge->list[LOWER], &lower->upper)) {
2135d4f98a2SYan Zheng 			idx--;
2145d4f98a2SYan Zheng 			continue;
2155d4f98a2SYan Zheng 		}
2165d4f98a2SYan Zheng 		edge = list_entry(edge->list[LOWER].next,
217a26195a5SQu Wenruo 				  struct btrfs_backref_edge, list[LOWER]);
2185d4f98a2SYan Zheng 		edges[idx - 1] = edge;
2195d4f98a2SYan Zheng 		*index = idx;
2205d4f98a2SYan Zheng 		return edge->node[UPPER];
2215d4f98a2SYan Zheng 	}
2225d4f98a2SYan Zheng 	*index = 0;
2235d4f98a2SYan Zheng 	return NULL;
2245d4f98a2SYan Zheng }
2255d4f98a2SYan Zheng 
226a26195a5SQu Wenruo static void update_backref_node(struct btrfs_backref_cache *cache,
227a26195a5SQu Wenruo 				struct btrfs_backref_node *node, u64 bytenr)
2283fd0a558SYan, Zheng {
2293fd0a558SYan, Zheng 	struct rb_node *rb_node;
2303fd0a558SYan, Zheng 	rb_erase(&node->rb_node, &cache->rb_root);
2313fd0a558SYan, Zheng 	node->bytenr = bytenr;
232e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&cache->rb_root, node->bytenr, &node->rb_node);
23343c04fb1SJeff Mahoney 	if (rb_node)
234982c92cbSQu Wenruo 		btrfs_backref_panic(cache->fs_info, bytenr, -EEXIST);
2353fd0a558SYan, Zheng }
2363fd0a558SYan, Zheng 
2373fd0a558SYan, Zheng /*
2383fd0a558SYan, Zheng  * update backref cache after a transaction commit
2393fd0a558SYan, Zheng  */
2403fd0a558SYan, Zheng static int update_backref_cache(struct btrfs_trans_handle *trans,
241a26195a5SQu Wenruo 				struct btrfs_backref_cache *cache)
2423fd0a558SYan, Zheng {
243a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
2443fd0a558SYan, Zheng 	int level = 0;
2453fd0a558SYan, Zheng 
2463fd0a558SYan, Zheng 	if (cache->last_trans == 0) {
2473fd0a558SYan, Zheng 		cache->last_trans = trans->transid;
2483fd0a558SYan, Zheng 		return 0;
2493fd0a558SYan, Zheng 	}
2503fd0a558SYan, Zheng 
2513fd0a558SYan, Zheng 	if (cache->last_trans == trans->transid)
2523fd0a558SYan, Zheng 		return 0;
2533fd0a558SYan, Zheng 
2543fd0a558SYan, Zheng 	/*
2553fd0a558SYan, Zheng 	 * detached nodes are used to avoid unnecessary backref
2563fd0a558SYan, Zheng 	 * lookup. transaction commit changes the extent tree.
2573fd0a558SYan, Zheng 	 * so the detached nodes are no longer useful.
2583fd0a558SYan, Zheng 	 */
2593fd0a558SYan, Zheng 	while (!list_empty(&cache->detached)) {
2603fd0a558SYan, Zheng 		node = list_entry(cache->detached.next,
261a26195a5SQu Wenruo 				  struct btrfs_backref_node, list);
262023acb07SQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
2633fd0a558SYan, Zheng 	}
2643fd0a558SYan, Zheng 
2653fd0a558SYan, Zheng 	while (!list_empty(&cache->changed)) {
2663fd0a558SYan, Zheng 		node = list_entry(cache->changed.next,
267a26195a5SQu Wenruo 				  struct btrfs_backref_node, list);
2683fd0a558SYan, Zheng 		list_del_init(&node->list);
2693fd0a558SYan, Zheng 		BUG_ON(node->pending);
2703fd0a558SYan, Zheng 		update_backref_node(cache, node, node->new_bytenr);
2713fd0a558SYan, Zheng 	}
2723fd0a558SYan, Zheng 
2733fd0a558SYan, Zheng 	/*
2743fd0a558SYan, Zheng 	 * some nodes can be left in the pending list if there were
2753fd0a558SYan, Zheng 	 * errors during processing the pending nodes.
2763fd0a558SYan, Zheng 	 */
2773fd0a558SYan, Zheng 	for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2783fd0a558SYan, Zheng 		list_for_each_entry(node, &cache->pending[level], list) {
2793fd0a558SYan, Zheng 			BUG_ON(!node->pending);
2803fd0a558SYan, Zheng 			if (node->bytenr == node->new_bytenr)
2813fd0a558SYan, Zheng 				continue;
2823fd0a558SYan, Zheng 			update_backref_node(cache, node, node->new_bytenr);
2833fd0a558SYan, Zheng 		}
2843fd0a558SYan, Zheng 	}
2853fd0a558SYan, Zheng 
2863fd0a558SYan, Zheng 	cache->last_trans = 0;
2873fd0a558SYan, Zheng 	return 1;
2883fd0a558SYan, Zheng }
2893fd0a558SYan, Zheng 
2906282675eSQu Wenruo static bool reloc_root_is_dead(struct btrfs_root *root)
2916282675eSQu Wenruo {
2926282675eSQu Wenruo 	/*
2936282675eSQu Wenruo 	 * Pair with set_bit/clear_bit in clean_dirty_subvols and
2946282675eSQu Wenruo 	 * btrfs_update_reloc_root. We need to see the updated bit before
2956282675eSQu Wenruo 	 * trying to access reloc_root
2966282675eSQu Wenruo 	 */
2976282675eSQu Wenruo 	smp_rmb();
2986282675eSQu Wenruo 	if (test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state))
2996282675eSQu Wenruo 		return true;
3006282675eSQu Wenruo 	return false;
3016282675eSQu Wenruo }
3026282675eSQu Wenruo 
3036282675eSQu Wenruo /*
3046282675eSQu Wenruo  * Check if this subvolume tree has valid reloc tree.
3056282675eSQu Wenruo  *
3066282675eSQu Wenruo  * Reloc tree after swap is considered dead, thus not considered as valid.
3076282675eSQu Wenruo  * This is enough for most callers, as they don't distinguish dead reloc root
3086282675eSQu Wenruo  * from no reloc root.  But should_ignore_root() below is a special case.
3096282675eSQu Wenruo  */
3106282675eSQu Wenruo static bool have_reloc_root(struct btrfs_root *root)
3116282675eSQu Wenruo {
3126282675eSQu Wenruo 	if (reloc_root_is_dead(root))
3136282675eSQu Wenruo 		return false;
3146282675eSQu Wenruo 	if (!root->reloc_root)
3156282675eSQu Wenruo 		return false;
3166282675eSQu Wenruo 	return true;
3176282675eSQu Wenruo }
318f2a97a9dSDavid Sterba 
3193fd0a558SYan, Zheng static int should_ignore_root(struct btrfs_root *root)
3203fd0a558SYan, Zheng {
3213fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
3223fd0a558SYan, Zheng 
32327cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
3243fd0a558SYan, Zheng 		return 0;
3253fd0a558SYan, Zheng 
3266282675eSQu Wenruo 	/* This root has been merged with its reloc tree, we can ignore it */
3276282675eSQu Wenruo 	if (reloc_root_is_dead(root))
3286282675eSQu Wenruo 		return 1;
3296282675eSQu Wenruo 
3303fd0a558SYan, Zheng 	reloc_root = root->reloc_root;
3313fd0a558SYan, Zheng 	if (!reloc_root)
3323fd0a558SYan, Zheng 		return 0;
3333fd0a558SYan, Zheng 
3344d4225fcSJosef Bacik 	if (btrfs_header_generation(reloc_root->commit_root) ==
3354d4225fcSJosef Bacik 	    root->fs_info->running_transaction->transid)
3363fd0a558SYan, Zheng 		return 0;
3373fd0a558SYan, Zheng 	/*
3383fd0a558SYan, Zheng 	 * if there is reloc tree and it was created in previous
3393fd0a558SYan, Zheng 	 * transaction backref lookup can find the reloc tree,
3403fd0a558SYan, Zheng 	 * so backref node for the fs tree root is useless for
3413fd0a558SYan, Zheng 	 * relocation.
3423fd0a558SYan, Zheng 	 */
3433fd0a558SYan, Zheng 	return 1;
3443fd0a558SYan, Zheng }
3455d4f98a2SYan Zheng /*
3465d4f98a2SYan Zheng  * find reloc tree by address of tree root
3475d4f98a2SYan Zheng  */
3482433bea5SQu Wenruo struct btrfs_root *find_reloc_root(struct btrfs_fs_info *fs_info, u64 bytenr)
3495d4f98a2SYan Zheng {
3502433bea5SQu Wenruo 	struct reloc_control *rc = fs_info->reloc_ctl;
3515d4f98a2SYan Zheng 	struct rb_node *rb_node;
3525d4f98a2SYan Zheng 	struct mapping_node *node;
3535d4f98a2SYan Zheng 	struct btrfs_root *root = NULL;
3545d4f98a2SYan Zheng 
3552433bea5SQu Wenruo 	ASSERT(rc);
3565d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
357e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root, bytenr);
3585d4f98a2SYan Zheng 	if (rb_node) {
3595d4f98a2SYan Zheng 		node = rb_entry(rb_node, struct mapping_node, rb_node);
3605d4f98a2SYan Zheng 		root = (struct btrfs_root *)node->data;
3615d4f98a2SYan Zheng 	}
3625d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
36300246528SJosef Bacik 	return btrfs_grab_root(root);
3645d4f98a2SYan Zheng }
3655d4f98a2SYan Zheng 
3665d4f98a2SYan Zheng static struct btrfs_root *read_fs_root(struct btrfs_fs_info *fs_info,
3675d4f98a2SYan Zheng 					u64 root_objectid)
3685d4f98a2SYan Zheng {
3695d4f98a2SYan Zheng 	struct btrfs_key key;
3705d4f98a2SYan Zheng 
3715d4f98a2SYan Zheng 	key.objectid = root_objectid;
3725d4f98a2SYan Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
3735d4f98a2SYan Zheng 	key.offset = (u64)-1;
3745d4f98a2SYan Zheng 
375bc44d7c4SJosef Bacik 	return btrfs_get_fs_root(fs_info, &key, false);
3765d4f98a2SYan Zheng }
3775d4f98a2SYan Zheng 
3785d4f98a2SYan Zheng /*
3794007ea87SQu Wenruo  * Handle direct tree backref
3804007ea87SQu Wenruo  *
3814007ea87SQu Wenruo  * Direct tree backref means, the backref item shows its parent bytenr
3824007ea87SQu Wenruo  * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
3834007ea87SQu Wenruo  *
3844007ea87SQu Wenruo  * @ref_key:	The converted backref key.
3854007ea87SQu Wenruo  *		For keyed backref, it's the item key.
3864007ea87SQu Wenruo  *		For inlined backref, objectid is the bytenr,
3874007ea87SQu Wenruo  *		type is btrfs_inline_ref_type, offset is
3884007ea87SQu Wenruo  *		btrfs_inline_ref_offset.
3894007ea87SQu Wenruo  */
390a26195a5SQu Wenruo static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
3914007ea87SQu Wenruo 				      struct btrfs_key *ref_key,
392a26195a5SQu Wenruo 				      struct btrfs_backref_node *cur)
3934007ea87SQu Wenruo {
394a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
395a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
3964007ea87SQu Wenruo 	struct rb_node *rb_node;
3974007ea87SQu Wenruo 
3984007ea87SQu Wenruo 	ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
3994007ea87SQu Wenruo 
4004007ea87SQu Wenruo 	/* Only reloc root uses backref pointing to itself */
4014007ea87SQu Wenruo 	if (ref_key->objectid == ref_key->offset) {
4024007ea87SQu Wenruo 		struct btrfs_root *root;
4034007ea87SQu Wenruo 
4044007ea87SQu Wenruo 		cur->is_reloc_root = 1;
4054007ea87SQu Wenruo 		/* Only reloc backref cache cares about a specific root */
4064007ea87SQu Wenruo 		if (cache->is_reloc) {
4074007ea87SQu Wenruo 			root = find_reloc_root(cache->fs_info, cur->bytenr);
4084007ea87SQu Wenruo 			if (WARN_ON(!root))
4094007ea87SQu Wenruo 				return -ENOENT;
4104007ea87SQu Wenruo 			cur->root = root;
4114007ea87SQu Wenruo 		} else {
4124007ea87SQu Wenruo 			/*
4134007ea87SQu Wenruo 			 * For generic purpose backref cache, reloc root node
4144007ea87SQu Wenruo 			 * is useless.
4154007ea87SQu Wenruo 			 */
4164007ea87SQu Wenruo 			list_add(&cur->list, &cache->useless_node);
4174007ea87SQu Wenruo 		}
4184007ea87SQu Wenruo 		return 0;
4194007ea87SQu Wenruo 	}
4204007ea87SQu Wenruo 
42147254d07SQu Wenruo 	edge = btrfs_backref_alloc_edge(cache);
4224007ea87SQu Wenruo 	if (!edge)
4234007ea87SQu Wenruo 		return -ENOMEM;
4244007ea87SQu Wenruo 
425e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
4264007ea87SQu Wenruo 	if (!rb_node) {
4274007ea87SQu Wenruo 		/* Parent node not yet cached */
428b1818dabSQu Wenruo 		upper = btrfs_backref_alloc_node(cache, ref_key->offset,
4290304f2d8SQu Wenruo 					   cur->level + 1);
4304007ea87SQu Wenruo 		if (!upper) {
431741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
4324007ea87SQu Wenruo 			return -ENOMEM;
4334007ea87SQu Wenruo 		}
4344007ea87SQu Wenruo 
4354007ea87SQu Wenruo 		/*
4364007ea87SQu Wenruo 		 *  Backrefs for the upper level block isn't cached, add the
4374007ea87SQu Wenruo 		 *  block to pending list
4384007ea87SQu Wenruo 		 */
4394007ea87SQu Wenruo 		list_add_tail(&edge->list[UPPER], &cache->pending_edge);
4404007ea87SQu Wenruo 	} else {
4414007ea87SQu Wenruo 		/* Parent node already cached */
442a26195a5SQu Wenruo 		upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
4434007ea87SQu Wenruo 		ASSERT(upper->checked);
4444007ea87SQu Wenruo 		INIT_LIST_HEAD(&edge->list[UPPER]);
4454007ea87SQu Wenruo 	}
446f39911e5SQu Wenruo 	btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
4474007ea87SQu Wenruo 	return 0;
4484007ea87SQu Wenruo }
4494007ea87SQu Wenruo 
4504007ea87SQu Wenruo /*
4514d81ea8bSQu Wenruo  * Handle indirect tree backref
4524d81ea8bSQu Wenruo  *
4534d81ea8bSQu Wenruo  * Indirect tree backref means, we only know which tree the node belongs to.
4544d81ea8bSQu Wenruo  * We still need to do a tree search to find out the parents. This is for
4554d81ea8bSQu Wenruo  * TREE_BLOCK_REF backref (keyed or inlined).
4564d81ea8bSQu Wenruo  *
4574d81ea8bSQu Wenruo  * @ref_key:	The same as @ref_key in  handle_direct_tree_backref()
4584d81ea8bSQu Wenruo  * @tree_key:	The first key of this tree block.
4594d81ea8bSQu Wenruo  * @path:	A clean (released) path, to avoid allocating path everytime
4604d81ea8bSQu Wenruo  *		the function get called.
4614d81ea8bSQu Wenruo  */
462a26195a5SQu Wenruo static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
4634d81ea8bSQu Wenruo 					struct btrfs_path *path,
4644d81ea8bSQu Wenruo 					struct btrfs_key *ref_key,
4654d81ea8bSQu Wenruo 					struct btrfs_key *tree_key,
466a26195a5SQu Wenruo 					struct btrfs_backref_node *cur)
4674d81ea8bSQu Wenruo {
4684d81ea8bSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
469a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
470a26195a5SQu Wenruo 	struct btrfs_backref_node *lower;
471a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
4724d81ea8bSQu Wenruo 	struct extent_buffer *eb;
4734d81ea8bSQu Wenruo 	struct btrfs_root *root;
4744d81ea8bSQu Wenruo 	struct rb_node *rb_node;
4754d81ea8bSQu Wenruo 	int level;
4764d81ea8bSQu Wenruo 	bool need_check = true;
4774d81ea8bSQu Wenruo 	int ret;
4784d81ea8bSQu Wenruo 
4794d81ea8bSQu Wenruo 	root = read_fs_root(fs_info, ref_key->offset);
4804d81ea8bSQu Wenruo 	if (IS_ERR(root))
4814d81ea8bSQu Wenruo 		return PTR_ERR(root);
4824d81ea8bSQu Wenruo 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4834d81ea8bSQu Wenruo 		cur->cowonly = 1;
4844d81ea8bSQu Wenruo 
4854d81ea8bSQu Wenruo 	if (btrfs_root_level(&root->root_item) == cur->level) {
4864d81ea8bSQu Wenruo 		/* Tree root */
4874d81ea8bSQu Wenruo 		ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
4884d81ea8bSQu Wenruo 		if (should_ignore_root(root)) {
4894d81ea8bSQu Wenruo 			btrfs_put_root(root);
4904d81ea8bSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
4914d81ea8bSQu Wenruo 		} else {
4924d81ea8bSQu Wenruo 			cur->root = root;
4934d81ea8bSQu Wenruo 		}
4944d81ea8bSQu Wenruo 		return 0;
4954d81ea8bSQu Wenruo 	}
4964d81ea8bSQu Wenruo 
4974d81ea8bSQu Wenruo 	level = cur->level + 1;
4984d81ea8bSQu Wenruo 
4994d81ea8bSQu Wenruo 	/* Search the tree to find parent blocks referring to the block */
5004d81ea8bSQu Wenruo 	path->search_commit_root = 1;
5014d81ea8bSQu Wenruo 	path->skip_locking = 1;
5024d81ea8bSQu Wenruo 	path->lowest_level = level;
5034d81ea8bSQu Wenruo 	ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
5044d81ea8bSQu Wenruo 	path->lowest_level = 0;
5054d81ea8bSQu Wenruo 	if (ret < 0) {
5064d81ea8bSQu Wenruo 		btrfs_put_root(root);
5074d81ea8bSQu Wenruo 		return ret;
5084d81ea8bSQu Wenruo 	}
5094d81ea8bSQu Wenruo 	if (ret > 0 && path->slots[level] > 0)
5104d81ea8bSQu Wenruo 		path->slots[level]--;
5114d81ea8bSQu Wenruo 
5124d81ea8bSQu Wenruo 	eb = path->nodes[level];
5134d81ea8bSQu Wenruo 	if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
5144d81ea8bSQu Wenruo 		btrfs_err(fs_info,
5154d81ea8bSQu Wenruo "couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
5164d81ea8bSQu Wenruo 			  cur->bytenr, level - 1, root->root_key.objectid,
5174d81ea8bSQu Wenruo 			  tree_key->objectid, tree_key->type, tree_key->offset);
5184d81ea8bSQu Wenruo 		btrfs_put_root(root);
5194d81ea8bSQu Wenruo 		ret = -ENOENT;
5204d81ea8bSQu Wenruo 		goto out;
5214d81ea8bSQu Wenruo 	}
5224d81ea8bSQu Wenruo 	lower = cur;
5234d81ea8bSQu Wenruo 
5244d81ea8bSQu Wenruo 	/* Add all nodes and edges in the path */
5254d81ea8bSQu Wenruo 	for (; level < BTRFS_MAX_LEVEL; level++) {
5264d81ea8bSQu Wenruo 		if (!path->nodes[level]) {
5274d81ea8bSQu Wenruo 			ASSERT(btrfs_root_bytenr(&root->root_item) ==
5284d81ea8bSQu Wenruo 			       lower->bytenr);
5294d81ea8bSQu Wenruo 			if (should_ignore_root(root)) {
5304d81ea8bSQu Wenruo 				btrfs_put_root(root);
5314d81ea8bSQu Wenruo 				list_add(&lower->list, &cache->useless_node);
5324d81ea8bSQu Wenruo 			} else {
5334d81ea8bSQu Wenruo 				lower->root = root;
5344d81ea8bSQu Wenruo 			}
5354d81ea8bSQu Wenruo 			break;
5364d81ea8bSQu Wenruo 		}
5374d81ea8bSQu Wenruo 
53847254d07SQu Wenruo 		edge = btrfs_backref_alloc_edge(cache);
5394d81ea8bSQu Wenruo 		if (!edge) {
5404d81ea8bSQu Wenruo 			btrfs_put_root(root);
5414d81ea8bSQu Wenruo 			ret = -ENOMEM;
5424d81ea8bSQu Wenruo 			goto out;
5434d81ea8bSQu Wenruo 		}
5444d81ea8bSQu Wenruo 
5454d81ea8bSQu Wenruo 		eb = path->nodes[level];
546e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root, eb->start);
5474d81ea8bSQu Wenruo 		if (!rb_node) {
548b1818dabSQu Wenruo 			upper = btrfs_backref_alloc_node(cache, eb->start,
5490304f2d8SQu Wenruo 							 lower->level + 1);
5504d81ea8bSQu Wenruo 			if (!upper) {
5514d81ea8bSQu Wenruo 				btrfs_put_root(root);
552741188d3SQu Wenruo 				btrfs_backref_free_edge(cache, edge);
5534d81ea8bSQu Wenruo 				ret = -ENOMEM;
5544d81ea8bSQu Wenruo 				goto out;
5554d81ea8bSQu Wenruo 			}
5564d81ea8bSQu Wenruo 			upper->owner = btrfs_header_owner(eb);
5574d81ea8bSQu Wenruo 			if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
5584d81ea8bSQu Wenruo 				upper->cowonly = 1;
5594d81ea8bSQu Wenruo 
5604d81ea8bSQu Wenruo 			/*
5614d81ea8bSQu Wenruo 			 * If we know the block isn't shared we can avoid
5624d81ea8bSQu Wenruo 			 * checking its backrefs.
5634d81ea8bSQu Wenruo 			 */
5644d81ea8bSQu Wenruo 			if (btrfs_block_can_be_shared(root, eb))
5654d81ea8bSQu Wenruo 				upper->checked = 0;
5664d81ea8bSQu Wenruo 			else
5674d81ea8bSQu Wenruo 				upper->checked = 1;
5684d81ea8bSQu Wenruo 
5694d81ea8bSQu Wenruo 			/*
5704d81ea8bSQu Wenruo 			 * Add the block to pending list if we need to check its
5714d81ea8bSQu Wenruo 			 * backrefs, we only do this once while walking up a
5724d81ea8bSQu Wenruo 			 * tree as we will catch anything else later on.
5734d81ea8bSQu Wenruo 			 */
5744d81ea8bSQu Wenruo 			if (!upper->checked && need_check) {
5754d81ea8bSQu Wenruo 				need_check = false;
5764d81ea8bSQu Wenruo 				list_add_tail(&edge->list[UPPER],
5774d81ea8bSQu Wenruo 					      &cache->pending_edge);
5784d81ea8bSQu Wenruo 			} else {
5794d81ea8bSQu Wenruo 				if (upper->checked)
5804d81ea8bSQu Wenruo 					need_check = true;
5814d81ea8bSQu Wenruo 				INIT_LIST_HEAD(&edge->list[UPPER]);
5824d81ea8bSQu Wenruo 			}
5834d81ea8bSQu Wenruo 		} else {
584a26195a5SQu Wenruo 			upper = rb_entry(rb_node, struct btrfs_backref_node,
585a26195a5SQu Wenruo 					 rb_node);
5864d81ea8bSQu Wenruo 			ASSERT(upper->checked);
5874d81ea8bSQu Wenruo 			INIT_LIST_HEAD(&edge->list[UPPER]);
5884d81ea8bSQu Wenruo 			if (!upper->owner)
5894d81ea8bSQu Wenruo 				upper->owner = btrfs_header_owner(eb);
5904d81ea8bSQu Wenruo 		}
591f39911e5SQu Wenruo 		btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
5924d81ea8bSQu Wenruo 
5934d81ea8bSQu Wenruo 		if (rb_node) {
5944d81ea8bSQu Wenruo 			btrfs_put_root(root);
5954d81ea8bSQu Wenruo 			break;
5964d81ea8bSQu Wenruo 		}
5974d81ea8bSQu Wenruo 		lower = upper;
5984d81ea8bSQu Wenruo 		upper = NULL;
5994d81ea8bSQu Wenruo 	}
6004d81ea8bSQu Wenruo out:
6014d81ea8bSQu Wenruo 	btrfs_release_path(path);
6024d81ea8bSQu Wenruo 	return ret;
6034d81ea8bSQu Wenruo }
6044d81ea8bSQu Wenruo 
605a26195a5SQu Wenruo static int handle_one_tree_block(struct btrfs_backref_cache *cache,
606e7d571c7SQu Wenruo 				 struct btrfs_path *path,
607e7d571c7SQu Wenruo 				 struct btrfs_backref_iter *iter,
6085d4f98a2SYan Zheng 				 struct btrfs_key *node_key,
609a26195a5SQu Wenruo 				 struct btrfs_backref_node *cur)
6105d4f98a2SYan Zheng {
611e7d571c7SQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
612a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
613a26195a5SQu Wenruo 	struct btrfs_backref_node *exist;
6145d4f98a2SYan Zheng 	int ret;
6155d4f98a2SYan Zheng 
61671f572a9SQu Wenruo 	ret = btrfs_backref_iter_start(iter, cur->bytenr);
617e7d571c7SQu Wenruo 	if (ret < 0)
618e7d571c7SQu Wenruo 		return ret;
61971f572a9SQu Wenruo 	/*
62071f572a9SQu Wenruo 	 * We skip the first btrfs_tree_block_info, as we don't use the key
62171f572a9SQu Wenruo 	 * stored in it, but fetch it from the tree block
62271f572a9SQu Wenruo 	 */
62371f572a9SQu Wenruo 	if (btrfs_backref_has_tree_block_info(iter)) {
62471f572a9SQu Wenruo 		ret = btrfs_backref_iter_next(iter);
625e7d571c7SQu Wenruo 		if (ret < 0)
62671f572a9SQu Wenruo 			goto out;
62771f572a9SQu Wenruo 		/* No extra backref? This means the tree block is corrupted */
62871f572a9SQu Wenruo 		if (ret > 0) {
629e7d571c7SQu Wenruo 			ret = -EUCLEAN;
63071f572a9SQu Wenruo 			goto out;
63171f572a9SQu Wenruo 		}
63271f572a9SQu Wenruo 	}
6335d4f98a2SYan Zheng 	WARN_ON(cur->checked);
6345d4f98a2SYan Zheng 	if (!list_empty(&cur->upper)) {
6355d4f98a2SYan Zheng 		/*
63670f23fd6SJustin P. Mattock 		 * the backref was added previously when processing
6375d4f98a2SYan Zheng 		 * backref of type BTRFS_TREE_BLOCK_REF_KEY
6385d4f98a2SYan Zheng 		 */
63975bfb9afSJosef Bacik 		ASSERT(list_is_singular(&cur->upper));
640a26195a5SQu Wenruo 		edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
6415d4f98a2SYan Zheng 				  list[LOWER]);
64275bfb9afSJosef Bacik 		ASSERT(list_empty(&edge->list[UPPER]));
6435d4f98a2SYan Zheng 		exist = edge->node[UPPER];
6445d4f98a2SYan Zheng 		/*
6455d4f98a2SYan Zheng 		 * add the upper level block to pending list if we need
6465d4f98a2SYan Zheng 		 * check its backrefs
6475d4f98a2SYan Zheng 		 */
6485d4f98a2SYan Zheng 		if (!exist->checked)
64984780289SQu Wenruo 			list_add_tail(&edge->list[UPPER], &cache->pending_edge);
6505d4f98a2SYan Zheng 	} else {
6515d4f98a2SYan Zheng 		exist = NULL;
6525d4f98a2SYan Zheng 	}
6535d4f98a2SYan Zheng 
65471f572a9SQu Wenruo 	for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
65571f572a9SQu Wenruo 		struct extent_buffer *eb;
65671f572a9SQu Wenruo 		struct btrfs_key key;
6573de28d57SLiu Bo 		int type;
65871f572a9SQu Wenruo 
65971f572a9SQu Wenruo 		cond_resched();
66071f572a9SQu Wenruo 		eb = btrfs_backref_get_eb(iter);
66171f572a9SQu Wenruo 
66271f572a9SQu Wenruo 		key.objectid = iter->bytenr;
66371f572a9SQu Wenruo 		if (btrfs_backref_iter_is_inline_ref(iter)) {
66471f572a9SQu Wenruo 			struct btrfs_extent_inline_ref *iref;
66571f572a9SQu Wenruo 
66671f572a9SQu Wenruo 			/* update key for inline back ref */
66771f572a9SQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
66871f572a9SQu Wenruo 				((unsigned long)iter->cur_ptr);
6693de28d57SLiu Bo 			type = btrfs_get_extent_inline_ref_type(eb, iref,
6703de28d57SLiu Bo 							BTRFS_REF_TYPE_BLOCK);
6713de28d57SLiu Bo 			if (type == BTRFS_REF_TYPE_INVALID) {
672e7d571c7SQu Wenruo 				ret = -EUCLEAN;
6733de28d57SLiu Bo 				goto out;
6743de28d57SLiu Bo 			}
6753de28d57SLiu Bo 			key.type = type;
6765d4f98a2SYan Zheng 			key.offset = btrfs_extent_inline_ref_offset(eb, iref);
67771f572a9SQu Wenruo 		} else {
67871f572a9SQu Wenruo 			key.type = iter->cur_key.type;
67971f572a9SQu Wenruo 			key.offset = iter->cur_key.offset;
6805d4f98a2SYan Zheng 		}
6815d4f98a2SYan Zheng 
682fa6ac715SQu Wenruo 		/*
683fa6ac715SQu Wenruo 		 * Parent node found and matches current inline ref, no need to
684fa6ac715SQu Wenruo 		 * rebuild this node for this inline ref.
685fa6ac715SQu Wenruo 		 */
6865d4f98a2SYan Zheng 		if (exist &&
6875d4f98a2SYan Zheng 		    ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
6885d4f98a2SYan Zheng 		      exist->owner == key.offset) ||
6895d4f98a2SYan Zheng 		     (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
6905d4f98a2SYan Zheng 		      exist->bytenr == key.offset))) {
6915d4f98a2SYan Zheng 			exist = NULL;
69271f572a9SQu Wenruo 			continue;
6935d4f98a2SYan Zheng 		}
6945d4f98a2SYan Zheng 
695fa6ac715SQu Wenruo 		/* SHARED_BLOCK_REF means key.offset is the parent bytenr */
6965d4f98a2SYan Zheng 		if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
6974007ea87SQu Wenruo 			ret = handle_direct_tree_backref(cache, &key, cur);
698e7d571c7SQu Wenruo 			if (ret < 0)
6992433bea5SQu Wenruo 				goto out;
70071f572a9SQu Wenruo 			continue;
7016d8ff4e4SDavid Sterba 		} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
702e7d571c7SQu Wenruo 			ret = -EINVAL;
703e7d571c7SQu Wenruo 			btrfs_print_v0_err(fs_info);
704e7d571c7SQu Wenruo 			btrfs_handle_fs_error(fs_info, ret, NULL);
705ba3c2b19SNikolay Borisov 			goto out;
7065d4f98a2SYan Zheng 		} else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
70771f572a9SQu Wenruo 			continue;
7085d4f98a2SYan Zheng 		}
7095d4f98a2SYan Zheng 
710fa6ac715SQu Wenruo 		/*
711fa6ac715SQu Wenruo 		 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
712fa6ac715SQu Wenruo 		 * means the root objectid. We need to search the tree to get
713fa6ac715SQu Wenruo 		 * its parent bytenr.
714fa6ac715SQu Wenruo 		 */
7154d81ea8bSQu Wenruo 		ret = handle_indirect_tree_backref(cache, path, &key, node_key,
7164d81ea8bSQu Wenruo 						   cur);
717e7d571c7SQu Wenruo 		if (ret < 0)
71871f572a9SQu Wenruo 			goto out;
7195d4f98a2SYan Zheng 	}
72071f572a9SQu Wenruo 	ret = 0;
7215d4f98a2SYan Zheng 	cur->checked = 1;
7225d4f98a2SYan Zheng 	WARN_ON(exist);
723e7d571c7SQu Wenruo out:
724e7d571c7SQu Wenruo 	btrfs_backref_iter_release(iter);
725e7d571c7SQu Wenruo 	return ret;
726e7d571c7SQu Wenruo }
7275d4f98a2SYan Zheng 
728e7d571c7SQu Wenruo /*
7291f872924SQu Wenruo  * In handle_one_tree_backref(), we have only linked the lower node to the edge,
7301f872924SQu Wenruo  * but the upper node hasn't been linked to the edge.
731a26195a5SQu Wenruo  * This means we can only iterate through btrfs_backref_node::upper to reach
732a26195a5SQu Wenruo  * parent edges, but not through btrfs_backref_node::lower to reach children
733a26195a5SQu Wenruo  * edges.
7341f872924SQu Wenruo  *
735a26195a5SQu Wenruo  * This function will finish the btrfs_backref_node::lower to related edges,
736a26195a5SQu Wenruo  * so that backref cache can be bi-directionally iterated.
7371f872924SQu Wenruo  *
7381f872924SQu Wenruo  * Also, this will add the nodes to backref cache for the next run.
7391f872924SQu Wenruo  */
740a26195a5SQu Wenruo static int finish_upper_links(struct btrfs_backref_cache *cache,
741a26195a5SQu Wenruo 			      struct btrfs_backref_node *start)
7421f872924SQu Wenruo {
7431f872924SQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
744a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
7451f872924SQu Wenruo 	struct rb_node *rb_node;
7461f872924SQu Wenruo 	LIST_HEAD(pending_edge);
7471f872924SQu Wenruo 
7481f872924SQu Wenruo 	ASSERT(start->checked);
7491f872924SQu Wenruo 
7501f872924SQu Wenruo 	/* Insert this node to cache if it's not COW-only */
7511f872924SQu Wenruo 	if (!start->cowonly) {
752e9a28dc5SQu Wenruo 		rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
7531f872924SQu Wenruo 					   &start->rb_node);
7541f872924SQu Wenruo 		if (rb_node)
755982c92cbSQu Wenruo 			btrfs_backref_panic(cache->fs_info, start->bytenr,
756982c92cbSQu Wenruo 					    -EEXIST);
7571f872924SQu Wenruo 		list_add_tail(&start->lower, &cache->leaves);
7581f872924SQu Wenruo 	}
7591f872924SQu Wenruo 
7601f872924SQu Wenruo 	/*
7611f872924SQu Wenruo 	 * Use breadth first search to iterate all related edges.
7621f872924SQu Wenruo 	 *
7631f872924SQu Wenruo 	 * The starting points are all the edges of this node
7641f872924SQu Wenruo 	 */
7651f872924SQu Wenruo 	list_for_each_entry(edge, &start->upper, list[LOWER])
7661f872924SQu Wenruo 		list_add_tail(&edge->list[UPPER], &pending_edge);
7671f872924SQu Wenruo 
7681f872924SQu Wenruo 	while (!list_empty(&pending_edge)) {
769a26195a5SQu Wenruo 		struct btrfs_backref_node *upper;
770a26195a5SQu Wenruo 		struct btrfs_backref_node *lower;
7711f872924SQu Wenruo 		struct rb_node *rb_node;
7721f872924SQu Wenruo 
773a26195a5SQu Wenruo 		edge = list_first_entry(&pending_edge,
774a26195a5SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
7751f872924SQu Wenruo 		list_del_init(&edge->list[UPPER]);
7761f872924SQu Wenruo 		upper = edge->node[UPPER];
7771f872924SQu Wenruo 		lower = edge->node[LOWER];
7781f872924SQu Wenruo 
7791f872924SQu Wenruo 		/* Parent is detached, no need to keep any edges */
7801f872924SQu Wenruo 		if (upper->detached) {
7811f872924SQu Wenruo 			list_del(&edge->list[LOWER]);
782741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
7831f872924SQu Wenruo 
7841f872924SQu Wenruo 			/* Lower node is orphan, queue for cleanup */
7851f872924SQu Wenruo 			if (list_empty(&lower->upper))
7861f872924SQu Wenruo 				list_add(&lower->list, useless_node);
7871f872924SQu Wenruo 			continue;
7881f872924SQu Wenruo 		}
7891f872924SQu Wenruo 
7901f872924SQu Wenruo 		/*
7911f872924SQu Wenruo 		 * All new nodes added in current build_backref_tree() haven't
7921f872924SQu Wenruo 		 * been linked to the cache rb tree.
7931f872924SQu Wenruo 		 * So if we have upper->rb_node populated, this means a cache
7941f872924SQu Wenruo 		 * hit. We only need to link the edge, as @upper and all its
7951f872924SQu Wenruo 		 * parent have already been linked.
7961f872924SQu Wenruo 		 */
7971f872924SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node)) {
7981f872924SQu Wenruo 			if (upper->lowest) {
7991f872924SQu Wenruo 				list_del_init(&upper->lower);
8001f872924SQu Wenruo 				upper->lowest = 0;
8011f872924SQu Wenruo 			}
8021f872924SQu Wenruo 
8031f872924SQu Wenruo 			list_add_tail(&edge->list[UPPER], &upper->lower);
8041f872924SQu Wenruo 			continue;
8051f872924SQu Wenruo 		}
8061f872924SQu Wenruo 
8071f872924SQu Wenruo 		/* Sanity check, we shouldn't have any unchecked nodes */
8081f872924SQu Wenruo 		if (!upper->checked) {
8091f872924SQu Wenruo 			ASSERT(0);
8101f872924SQu Wenruo 			return -EUCLEAN;
8111f872924SQu Wenruo 		}
8121f872924SQu Wenruo 
8131f872924SQu Wenruo 		/* Sanity check, COW-only node has non-COW-only parent */
8141f872924SQu Wenruo 		if (start->cowonly != upper->cowonly) {
8151f872924SQu Wenruo 			ASSERT(0);
8161f872924SQu Wenruo 			return -EUCLEAN;
8171f872924SQu Wenruo 		}
8181f872924SQu Wenruo 
8191f872924SQu Wenruo 		/* Only cache non-COW-only (subvolume trees) tree blocks */
8201f872924SQu Wenruo 		if (!upper->cowonly) {
821e9a28dc5SQu Wenruo 			rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
8221f872924SQu Wenruo 						   &upper->rb_node);
8231f872924SQu Wenruo 			if (rb_node) {
824982c92cbSQu Wenruo 				btrfs_backref_panic(cache->fs_info,
825982c92cbSQu Wenruo 						upper->bytenr, -EEXIST);
8261f872924SQu Wenruo 				return -EUCLEAN;
8271f872924SQu Wenruo 			}
8281f872924SQu Wenruo 		}
8291f872924SQu Wenruo 
8301f872924SQu Wenruo 		list_add_tail(&edge->list[UPPER], &upper->lower);
8311f872924SQu Wenruo 
8321f872924SQu Wenruo 		/*
8331f872924SQu Wenruo 		 * Also queue all the parent edges of this uncached node to
8341f872924SQu Wenruo 		 * finish the upper linkage
8351f872924SQu Wenruo 		 */
8361f872924SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
8371f872924SQu Wenruo 			list_add_tail(&edge->list[UPPER], &pending_edge);
8381f872924SQu Wenruo 	}
8391f872924SQu Wenruo 	return 0;
8401f872924SQu Wenruo }
8411f872924SQu Wenruo 
8421f872924SQu Wenruo /*
84329db137bSQu Wenruo  * For useless nodes, do two major clean ups:
84429db137bSQu Wenruo  *
84529db137bSQu Wenruo  * - Cleanup the children edges and nodes
84629db137bSQu Wenruo  *   If child node is also orphan (no parent) during cleanup, then the child
84729db137bSQu Wenruo  *   node will also be cleaned up.
84829db137bSQu Wenruo  *
84929db137bSQu Wenruo  * - Freeing up leaves (level 0), keeps nodes detached
85029db137bSQu Wenruo  *   For nodes, the node is still cached as "detached"
85129db137bSQu Wenruo  *
85229db137bSQu Wenruo  * Return false if @node is not in the @useless_nodes list.
85329db137bSQu Wenruo  * Return true if @node is in the @useless_nodes list.
85429db137bSQu Wenruo  */
85529db137bSQu Wenruo static bool handle_useless_nodes(struct reloc_control *rc,
856a26195a5SQu Wenruo 				 struct btrfs_backref_node *node)
85729db137bSQu Wenruo {
858a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
85929db137bSQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
86029db137bSQu Wenruo 	bool ret = false;
86129db137bSQu Wenruo 
86229db137bSQu Wenruo 	while (!list_empty(useless_node)) {
863a26195a5SQu Wenruo 		struct btrfs_backref_node *cur;
86429db137bSQu Wenruo 
865a26195a5SQu Wenruo 		cur = list_first_entry(useless_node, struct btrfs_backref_node,
86629db137bSQu Wenruo 				 list);
86729db137bSQu Wenruo 		list_del_init(&cur->list);
86829db137bSQu Wenruo 
86929db137bSQu Wenruo 		/* Only tree root nodes can be added to @useless_nodes */
87029db137bSQu Wenruo 		ASSERT(list_empty(&cur->upper));
87129db137bSQu Wenruo 
87229db137bSQu Wenruo 		if (cur == node)
87329db137bSQu Wenruo 			ret = true;
87429db137bSQu Wenruo 
87529db137bSQu Wenruo 		/* The node is the lowest node */
87629db137bSQu Wenruo 		if (cur->lowest) {
87729db137bSQu Wenruo 			list_del_init(&cur->lower);
87829db137bSQu Wenruo 			cur->lowest = 0;
87929db137bSQu Wenruo 		}
88029db137bSQu Wenruo 
88129db137bSQu Wenruo 		/* Cleanup the lower edges */
88229db137bSQu Wenruo 		while (!list_empty(&cur->lower)) {
883a26195a5SQu Wenruo 			struct btrfs_backref_edge *edge;
884a26195a5SQu Wenruo 			struct btrfs_backref_node *lower;
88529db137bSQu Wenruo 
88629db137bSQu Wenruo 			edge = list_entry(cur->lower.next,
887a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[UPPER]);
88829db137bSQu Wenruo 			list_del(&edge->list[UPPER]);
88929db137bSQu Wenruo 			list_del(&edge->list[LOWER]);
89029db137bSQu Wenruo 			lower = edge->node[LOWER];
891741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
89229db137bSQu Wenruo 
89329db137bSQu Wenruo 			/* Child node is also orphan, queue for cleanup */
89429db137bSQu Wenruo 			if (list_empty(&lower->upper))
89529db137bSQu Wenruo 				list_add(&lower->list, useless_node);
89629db137bSQu Wenruo 		}
89729db137bSQu Wenruo 		/* Mark this block processed for relocation */
89829db137bSQu Wenruo 		mark_block_processed(rc, cur);
89929db137bSQu Wenruo 
90029db137bSQu Wenruo 		/*
90129db137bSQu Wenruo 		 * Backref nodes for tree leaves are deleted from the cache.
90229db137bSQu Wenruo 		 * Backref nodes for upper level tree blocks are left in the
90329db137bSQu Wenruo 		 * cache to avoid unnecessary backref lookup.
90429db137bSQu Wenruo 		 */
90529db137bSQu Wenruo 		if (cur->level > 0) {
90629db137bSQu Wenruo 			list_add(&cur->list, &cache->detached);
90729db137bSQu Wenruo 			cur->detached = 1;
90829db137bSQu Wenruo 		} else {
90929db137bSQu Wenruo 			rb_erase(&cur->rb_node, &cache->rb_root);
910741188d3SQu Wenruo 			btrfs_backref_free_node(cache, cur);
91129db137bSQu Wenruo 		}
91229db137bSQu Wenruo 	}
91329db137bSQu Wenruo 	return ret;
91429db137bSQu Wenruo }
91529db137bSQu Wenruo 
91629db137bSQu Wenruo /*
917e7d571c7SQu Wenruo  * Build backref tree for a given tree block. Root of the backref tree
918e7d571c7SQu Wenruo  * corresponds the tree block, leaves of the backref tree correspond roots of
919e7d571c7SQu Wenruo  * b-trees that reference the tree block.
920e7d571c7SQu Wenruo  *
921e7d571c7SQu Wenruo  * The basic idea of this function is check backrefs of a given block to find
922e7d571c7SQu Wenruo  * upper level blocks that reference the block, and then check backrefs of
923e7d571c7SQu Wenruo  * these upper level blocks recursively. The recursion stops when tree root is
924e7d571c7SQu Wenruo  * reached or backrefs for the block is cached.
925e7d571c7SQu Wenruo  *
926e7d571c7SQu Wenruo  * NOTE: if we find that backrefs for a block are cached, we know backrefs for
927e7d571c7SQu Wenruo  * all upper level blocks that directly/indirectly reference the block are also
928e7d571c7SQu Wenruo  * cached.
929e7d571c7SQu Wenruo  */
930a26195a5SQu Wenruo static noinline_for_stack struct btrfs_backref_node *build_backref_tree(
931e7d571c7SQu Wenruo 			struct reloc_control *rc, struct btrfs_key *node_key,
932e7d571c7SQu Wenruo 			int level, u64 bytenr)
933e7d571c7SQu Wenruo {
934e7d571c7SQu Wenruo 	struct btrfs_backref_iter *iter;
935a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
936e7d571c7SQu Wenruo 	/* For searching parent of TREE_BLOCK_REF */
937e7d571c7SQu Wenruo 	struct btrfs_path *path;
938a26195a5SQu Wenruo 	struct btrfs_backref_node *cur;
939a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
940a26195a5SQu Wenruo 	struct btrfs_backref_node *lower;
941a26195a5SQu Wenruo 	struct btrfs_backref_node *node = NULL;
942a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
943e7d571c7SQu Wenruo 	int ret;
944e7d571c7SQu Wenruo 	int err = 0;
945e7d571c7SQu Wenruo 
946e7d571c7SQu Wenruo 	iter = btrfs_backref_iter_alloc(rc->extent_root->fs_info, GFP_NOFS);
947e7d571c7SQu Wenruo 	if (!iter)
948e7d571c7SQu Wenruo 		return ERR_PTR(-ENOMEM);
949e7d571c7SQu Wenruo 	path = btrfs_alloc_path();
950e7d571c7SQu Wenruo 	if (!path) {
951e7d571c7SQu Wenruo 		err = -ENOMEM;
952e7d571c7SQu Wenruo 		goto out;
953e7d571c7SQu Wenruo 	}
954e7d571c7SQu Wenruo 
955b1818dabSQu Wenruo 	node = btrfs_backref_alloc_node(cache, bytenr, level);
956e7d571c7SQu Wenruo 	if (!node) {
957e7d571c7SQu Wenruo 		err = -ENOMEM;
958e7d571c7SQu Wenruo 		goto out;
959e7d571c7SQu Wenruo 	}
960e7d571c7SQu Wenruo 
961e7d571c7SQu Wenruo 	node->lowest = 1;
962e7d571c7SQu Wenruo 	cur = node;
963e7d571c7SQu Wenruo 
964e7d571c7SQu Wenruo 	/* Breadth-first search to build backref cache */
965e7d571c7SQu Wenruo 	do {
966e7d571c7SQu Wenruo 		ret = handle_one_tree_block(cache, path, iter, node_key, cur);
967e7d571c7SQu Wenruo 		if (ret < 0) {
968e7d571c7SQu Wenruo 			err = ret;
969e7d571c7SQu Wenruo 			goto out;
970e7d571c7SQu Wenruo 		}
971e7d571c7SQu Wenruo 		edge = list_first_entry_or_null(&cache->pending_edge,
972a26195a5SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
973e7d571c7SQu Wenruo 		/*
974e7d571c7SQu Wenruo 		 * The pending list isn't empty, take the first block to
975e7d571c7SQu Wenruo 		 * process
976e7d571c7SQu Wenruo 		 */
977e7d571c7SQu Wenruo 		if (edge) {
9785d4f98a2SYan Zheng 			list_del_init(&edge->list[UPPER]);
9795d4f98a2SYan Zheng 			cur = edge->node[UPPER];
9805d4f98a2SYan Zheng 		}
981e7d571c7SQu Wenruo 	} while (edge);
9825d4f98a2SYan Zheng 
9831f872924SQu Wenruo 	/* Finish the upper linkage of newly added edges/nodes */
9841f872924SQu Wenruo 	ret = finish_upper_links(cache, node);
9851f872924SQu Wenruo 	if (ret < 0) {
9861f872924SQu Wenruo 		err = ret;
98775bfb9afSJosef Bacik 		goto out;
98875bfb9afSJosef Bacik 	}
98975bfb9afSJosef Bacik 
99029db137bSQu Wenruo 	if (handle_useless_nodes(rc, node))
9913fd0a558SYan, Zheng 		node = NULL;
9925d4f98a2SYan Zheng out:
99371f572a9SQu Wenruo 	btrfs_backref_iter_free(iter);
99471f572a9SQu Wenruo 	btrfs_free_path(path);
9955d4f98a2SYan Zheng 	if (err) {
99684780289SQu Wenruo 		while (!list_empty(&cache->useless_node)) {
99784780289SQu Wenruo 			lower = list_first_entry(&cache->useless_node,
998a26195a5SQu Wenruo 					   struct btrfs_backref_node, list);
99975bfb9afSJosef Bacik 			list_del_init(&lower->list);
10003fd0a558SYan, Zheng 		}
100184780289SQu Wenruo 		while (!list_empty(&cache->pending_edge)) {
100284780289SQu Wenruo 			edge = list_first_entry(&cache->pending_edge,
1003a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[UPPER]);
100475bfb9afSJosef Bacik 			list_del(&edge->list[UPPER]);
10053fd0a558SYan, Zheng 			list_del(&edge->list[LOWER]);
100675bfb9afSJosef Bacik 			lower = edge->node[LOWER];
10075d4f98a2SYan Zheng 			upper = edge->node[UPPER];
1008741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
100975bfb9afSJosef Bacik 
101075bfb9afSJosef Bacik 			/*
101175bfb9afSJosef Bacik 			 * Lower is no longer linked to any upper backref nodes
101275bfb9afSJosef Bacik 			 * and isn't in the cache, we can free it ourselves.
101375bfb9afSJosef Bacik 			 */
101475bfb9afSJosef Bacik 			if (list_empty(&lower->upper) &&
101575bfb9afSJosef Bacik 			    RB_EMPTY_NODE(&lower->rb_node))
101684780289SQu Wenruo 				list_add(&lower->list, &cache->useless_node);
101775bfb9afSJosef Bacik 
101875bfb9afSJosef Bacik 			if (!RB_EMPTY_NODE(&upper->rb_node))
101975bfb9afSJosef Bacik 				continue;
102075bfb9afSJosef Bacik 
102101327610SNicholas D Steeves 			/* Add this guy's upper edges to the list to process */
102275bfb9afSJosef Bacik 			list_for_each_entry(edge, &upper->upper, list[LOWER])
102384780289SQu Wenruo 				list_add_tail(&edge->list[UPPER],
102484780289SQu Wenruo 					      &cache->pending_edge);
102575bfb9afSJosef Bacik 			if (list_empty(&upper->upper))
102684780289SQu Wenruo 				list_add(&upper->list, &cache->useless_node);
102775bfb9afSJosef Bacik 		}
102875bfb9afSJosef Bacik 
102984780289SQu Wenruo 		while (!list_empty(&cache->useless_node)) {
103084780289SQu Wenruo 			lower = list_first_entry(&cache->useless_node,
1031a26195a5SQu Wenruo 					   struct btrfs_backref_node, list);
103275bfb9afSJosef Bacik 			list_del_init(&lower->list);
10330fd8c3daSLiu Bo 			if (lower == node)
10340fd8c3daSLiu Bo 				node = NULL;
1035741188d3SQu Wenruo 			btrfs_backref_free_node(cache, lower);
10365d4f98a2SYan Zheng 		}
10370fd8c3daSLiu Bo 
1038023acb07SQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
103984780289SQu Wenruo 		ASSERT(list_empty(&cache->useless_node) &&
104084780289SQu Wenruo 		       list_empty(&cache->pending_edge));
10415d4f98a2SYan Zheng 		return ERR_PTR(err);
10425d4f98a2SYan Zheng 	}
104375bfb9afSJosef Bacik 	ASSERT(!node || !node->detached);
104484780289SQu Wenruo 	ASSERT(list_empty(&cache->useless_node) &&
104584780289SQu Wenruo 	       list_empty(&cache->pending_edge));
10465d4f98a2SYan Zheng 	return node;
10475d4f98a2SYan Zheng }
10485d4f98a2SYan Zheng 
10495d4f98a2SYan Zheng /*
10503fd0a558SYan, Zheng  * helper to add backref node for the newly created snapshot.
10513fd0a558SYan, Zheng  * the backref node is created by cloning backref node that
10523fd0a558SYan, Zheng  * corresponds to root of source tree
10533fd0a558SYan, Zheng  */
10543fd0a558SYan, Zheng static int clone_backref_node(struct btrfs_trans_handle *trans,
10553fd0a558SYan, Zheng 			      struct reloc_control *rc,
10563fd0a558SYan, Zheng 			      struct btrfs_root *src,
10573fd0a558SYan, Zheng 			      struct btrfs_root *dest)
10583fd0a558SYan, Zheng {
10593fd0a558SYan, Zheng 	struct btrfs_root *reloc_root = src->reloc_root;
1060a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
1061a26195a5SQu Wenruo 	struct btrfs_backref_node *node = NULL;
1062a26195a5SQu Wenruo 	struct btrfs_backref_node *new_node;
1063a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
1064a26195a5SQu Wenruo 	struct btrfs_backref_edge *new_edge;
10653fd0a558SYan, Zheng 	struct rb_node *rb_node;
10663fd0a558SYan, Zheng 
10673fd0a558SYan, Zheng 	if (cache->last_trans > 0)
10683fd0a558SYan, Zheng 		update_backref_cache(trans, cache);
10693fd0a558SYan, Zheng 
1070e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, src->commit_root->start);
10713fd0a558SYan, Zheng 	if (rb_node) {
1072a26195a5SQu Wenruo 		node = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
10733fd0a558SYan, Zheng 		if (node->detached)
10743fd0a558SYan, Zheng 			node = NULL;
10753fd0a558SYan, Zheng 		else
10763fd0a558SYan, Zheng 			BUG_ON(node->new_bytenr != reloc_root->node->start);
10773fd0a558SYan, Zheng 	}
10783fd0a558SYan, Zheng 
10793fd0a558SYan, Zheng 	if (!node) {
1080e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root,
10813fd0a558SYan, Zheng 					   reloc_root->commit_root->start);
10823fd0a558SYan, Zheng 		if (rb_node) {
1083a26195a5SQu Wenruo 			node = rb_entry(rb_node, struct btrfs_backref_node,
10843fd0a558SYan, Zheng 					rb_node);
10853fd0a558SYan, Zheng 			BUG_ON(node->detached);
10863fd0a558SYan, Zheng 		}
10873fd0a558SYan, Zheng 	}
10883fd0a558SYan, Zheng 
10893fd0a558SYan, Zheng 	if (!node)
10903fd0a558SYan, Zheng 		return 0;
10913fd0a558SYan, Zheng 
1092b1818dabSQu Wenruo 	new_node = btrfs_backref_alloc_node(cache, dest->node->start,
1093b1818dabSQu Wenruo 					    node->level);
10943fd0a558SYan, Zheng 	if (!new_node)
10953fd0a558SYan, Zheng 		return -ENOMEM;
10963fd0a558SYan, Zheng 
10973fd0a558SYan, Zheng 	new_node->lowest = node->lowest;
10986848ad64SYan, Zheng 	new_node->checked = 1;
109900246528SJosef Bacik 	new_node->root = btrfs_grab_root(dest);
11000b530bc5SJosef Bacik 	ASSERT(new_node->root);
11013fd0a558SYan, Zheng 
11023fd0a558SYan, Zheng 	if (!node->lowest) {
11033fd0a558SYan, Zheng 		list_for_each_entry(edge, &node->lower, list[UPPER]) {
110447254d07SQu Wenruo 			new_edge = btrfs_backref_alloc_edge(cache);
11053fd0a558SYan, Zheng 			if (!new_edge)
11063fd0a558SYan, Zheng 				goto fail;
11073fd0a558SYan, Zheng 
1108f39911e5SQu Wenruo 			btrfs_backref_link_edge(new_edge, edge->node[LOWER],
1109f39911e5SQu Wenruo 						new_node, LINK_UPPER);
11103fd0a558SYan, Zheng 		}
111176b9e23dSMiao Xie 	} else {
111276b9e23dSMiao Xie 		list_add_tail(&new_node->lower, &cache->leaves);
11133fd0a558SYan, Zheng 	}
11143fd0a558SYan, Zheng 
1115e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&cache->rb_root, new_node->bytenr,
11163fd0a558SYan, Zheng 				   &new_node->rb_node);
111743c04fb1SJeff Mahoney 	if (rb_node)
1118982c92cbSQu Wenruo 		btrfs_backref_panic(trans->fs_info, new_node->bytenr, -EEXIST);
11193fd0a558SYan, Zheng 
11203fd0a558SYan, Zheng 	if (!new_node->lowest) {
11213fd0a558SYan, Zheng 		list_for_each_entry(new_edge, &new_node->lower, list[UPPER]) {
11223fd0a558SYan, Zheng 			list_add_tail(&new_edge->list[LOWER],
11233fd0a558SYan, Zheng 				      &new_edge->node[LOWER]->upper);
11243fd0a558SYan, Zheng 		}
11253fd0a558SYan, Zheng 	}
11263fd0a558SYan, Zheng 	return 0;
11273fd0a558SYan, Zheng fail:
11283fd0a558SYan, Zheng 	while (!list_empty(&new_node->lower)) {
11293fd0a558SYan, Zheng 		new_edge = list_entry(new_node->lower.next,
1130a26195a5SQu Wenruo 				      struct btrfs_backref_edge, list[UPPER]);
11313fd0a558SYan, Zheng 		list_del(&new_edge->list[UPPER]);
1132741188d3SQu Wenruo 		btrfs_backref_free_edge(cache, new_edge);
11333fd0a558SYan, Zheng 	}
1134741188d3SQu Wenruo 	btrfs_backref_free_node(cache, new_node);
11353fd0a558SYan, Zheng 	return -ENOMEM;
11363fd0a558SYan, Zheng }
11373fd0a558SYan, Zheng 
11383fd0a558SYan, Zheng /*
11395d4f98a2SYan Zheng  * helper to add 'address of tree root -> reloc tree' mapping
11405d4f98a2SYan Zheng  */
1141ffd7b339SJeff Mahoney static int __must_check __add_reloc_root(struct btrfs_root *root)
11425d4f98a2SYan Zheng {
11430b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11445d4f98a2SYan Zheng 	struct rb_node *rb_node;
11455d4f98a2SYan Zheng 	struct mapping_node *node;
11460b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
11475d4f98a2SYan Zheng 
11485d4f98a2SYan Zheng 	node = kmalloc(sizeof(*node), GFP_NOFS);
1149ffd7b339SJeff Mahoney 	if (!node)
1150ffd7b339SJeff Mahoney 		return -ENOMEM;
11515d4f98a2SYan Zheng 
1152ea287ab1SJosef Bacik 	node->bytenr = root->commit_root->start;
11535d4f98a2SYan Zheng 	node->data = root;
11545d4f98a2SYan Zheng 
11555d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
1156e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
11575d4f98a2SYan Zheng 				   node->bytenr, &node->rb_node);
11585d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
1159ffd7b339SJeff Mahoney 	if (rb_node) {
11600b246afaSJeff Mahoney 		btrfs_panic(fs_info, -EEXIST,
11615d163e0eSJeff Mahoney 			    "Duplicate root found for start=%llu while inserting into relocation tree",
11625d163e0eSJeff Mahoney 			    node->bytenr);
1163ffd7b339SJeff Mahoney 	}
11645d4f98a2SYan Zheng 
11655d4f98a2SYan Zheng 	list_add_tail(&root->root_list, &rc->reloc_roots);
11665d4f98a2SYan Zheng 	return 0;
11675d4f98a2SYan Zheng }
11685d4f98a2SYan Zheng 
11695d4f98a2SYan Zheng /*
1170c974c464SWang Shilong  * helper to delete the 'address of tree root -> reloc tree'
11715d4f98a2SYan Zheng  * mapping
11725d4f98a2SYan Zheng  */
1173c974c464SWang Shilong static void __del_reloc_root(struct btrfs_root *root)
11745d4f98a2SYan Zheng {
11750b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11765d4f98a2SYan Zheng 	struct rb_node *rb_node;
11775d4f98a2SYan Zheng 	struct mapping_node *node = NULL;
11780b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
1179f44deb74SJosef Bacik 	bool put_ref = false;
11805d4f98a2SYan Zheng 
118165c6e82bSQu Wenruo 	if (rc && root->node) {
11825d4f98a2SYan Zheng 		spin_lock(&rc->reloc_root_tree.lock);
1183e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
1184ea287ab1SJosef Bacik 					   root->commit_root->start);
1185c974c464SWang Shilong 		if (rb_node) {
1186c974c464SWang Shilong 			node = rb_entry(rb_node, struct mapping_node, rb_node);
1187c974c464SWang Shilong 			rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
1188ea287ab1SJosef Bacik 			RB_CLEAR_NODE(&node->rb_node);
1189c974c464SWang Shilong 		}
1190c974c464SWang Shilong 		spin_unlock(&rc->reloc_root_tree.lock);
1191c974c464SWang Shilong 		if (!node)
1192c974c464SWang Shilong 			return;
1193c974c464SWang Shilong 		BUG_ON((struct btrfs_root *)node->data != root);
1194389305b2SQu Wenruo 	}
1195c974c464SWang Shilong 
1196f44deb74SJosef Bacik 	/*
1197f44deb74SJosef Bacik 	 * We only put the reloc root here if it's on the list.  There's a lot
1198f44deb74SJosef Bacik 	 * of places where the pattern is to splice the rc->reloc_roots, process
1199f44deb74SJosef Bacik 	 * the reloc roots, and then add the reloc root back onto
1200f44deb74SJosef Bacik 	 * rc->reloc_roots.  If we call __del_reloc_root while it's off of the
1201f44deb74SJosef Bacik 	 * list we don't want the reference being dropped, because the guy
1202f44deb74SJosef Bacik 	 * messing with the list is in charge of the reference.
1203f44deb74SJosef Bacik 	 */
12040b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
1205f44deb74SJosef Bacik 	if (!list_empty(&root->root_list)) {
1206f44deb74SJosef Bacik 		put_ref = true;
1207c974c464SWang Shilong 		list_del_init(&root->root_list);
1208f44deb74SJosef Bacik 	}
12090b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1210f44deb74SJosef Bacik 	if (put_ref)
1211f44deb74SJosef Bacik 		btrfs_put_root(root);
1212c974c464SWang Shilong 	kfree(node);
1213c974c464SWang Shilong }
1214c974c464SWang Shilong 
1215c974c464SWang Shilong /*
1216c974c464SWang Shilong  * helper to update the 'address of tree root -> reloc tree'
1217c974c464SWang Shilong  * mapping
1218c974c464SWang Shilong  */
1219ea287ab1SJosef Bacik static int __update_reloc_root(struct btrfs_root *root)
1220c974c464SWang Shilong {
12210b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1222c974c464SWang Shilong 	struct rb_node *rb_node;
1223c974c464SWang Shilong 	struct mapping_node *node = NULL;
12240b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
1225c974c464SWang Shilong 
1226c974c464SWang Shilong 	spin_lock(&rc->reloc_root_tree.lock);
1227e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
1228ea287ab1SJosef Bacik 				   root->commit_root->start);
12295d4f98a2SYan Zheng 	if (rb_node) {
12305d4f98a2SYan Zheng 		node = rb_entry(rb_node, struct mapping_node, rb_node);
12315d4f98a2SYan Zheng 		rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
12325d4f98a2SYan Zheng 	}
12335d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
12345d4f98a2SYan Zheng 
12358f71f3e0SLiu Bo 	if (!node)
12368f71f3e0SLiu Bo 		return 0;
12375d4f98a2SYan Zheng 	BUG_ON((struct btrfs_root *)node->data != root);
12385d4f98a2SYan Zheng 
12395d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
1240ea287ab1SJosef Bacik 	node->bytenr = root->node->start;
1241e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
12425d4f98a2SYan Zheng 				   node->bytenr, &node->rb_node);
12435d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
124443c04fb1SJeff Mahoney 	if (rb_node)
1245982c92cbSQu Wenruo 		btrfs_backref_panic(fs_info, node->bytenr, -EEXIST);
12465d4f98a2SYan Zheng 	return 0;
12475d4f98a2SYan Zheng }
12485d4f98a2SYan Zheng 
12493fd0a558SYan, Zheng static struct btrfs_root *create_reloc_root(struct btrfs_trans_handle *trans,
12503fd0a558SYan, Zheng 					struct btrfs_root *root, u64 objectid)
12515d4f98a2SYan Zheng {
12520b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12535d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
12545d4f98a2SYan Zheng 	struct extent_buffer *eb;
12555d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
12565d4f98a2SYan Zheng 	struct btrfs_key root_key;
12575d4f98a2SYan Zheng 	int ret;
12585d4f98a2SYan Zheng 
12595d4f98a2SYan Zheng 	root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
12605d4f98a2SYan Zheng 	BUG_ON(!root_item);
12615d4f98a2SYan Zheng 
12625d4f98a2SYan Zheng 	root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
12635d4f98a2SYan Zheng 	root_key.type = BTRFS_ROOT_ITEM_KEY;
12643fd0a558SYan, Zheng 	root_key.offset = objectid;
12655d4f98a2SYan Zheng 
12663fd0a558SYan, Zheng 	if (root->root_key.objectid == objectid) {
1267054570a1SFilipe Manana 		u64 commit_root_gen;
1268054570a1SFilipe Manana 
12693fd0a558SYan, Zheng 		/* called by btrfs_init_reloc_root */
12705d4f98a2SYan Zheng 		ret = btrfs_copy_root(trans, root, root->commit_root, &eb,
12715d4f98a2SYan Zheng 				      BTRFS_TREE_RELOC_OBJECTID);
12725d4f98a2SYan Zheng 		BUG_ON(ret);
1273054570a1SFilipe Manana 		/*
1274054570a1SFilipe Manana 		 * Set the last_snapshot field to the generation of the commit
1275054570a1SFilipe Manana 		 * root - like this ctree.c:btrfs_block_can_be_shared() behaves
1276054570a1SFilipe Manana 		 * correctly (returns true) when the relocation root is created
1277054570a1SFilipe Manana 		 * either inside the critical section of a transaction commit
1278054570a1SFilipe Manana 		 * (through transaction.c:qgroup_account_snapshot()) and when
1279054570a1SFilipe Manana 		 * it's created before the transaction commit is started.
1280054570a1SFilipe Manana 		 */
1281054570a1SFilipe Manana 		commit_root_gen = btrfs_header_generation(root->commit_root);
1282054570a1SFilipe Manana 		btrfs_set_root_last_snapshot(&root->root_item, commit_root_gen);
12833fd0a558SYan, Zheng 	} else {
12843fd0a558SYan, Zheng 		/*
12853fd0a558SYan, Zheng 		 * called by btrfs_reloc_post_snapshot_hook.
12863fd0a558SYan, Zheng 		 * the source tree is a reloc tree, all tree blocks
12873fd0a558SYan, Zheng 		 * modified after it was created have RELOC flag
12883fd0a558SYan, Zheng 		 * set in their headers. so it's OK to not update
12893fd0a558SYan, Zheng 		 * the 'last_snapshot'.
12903fd0a558SYan, Zheng 		 */
12913fd0a558SYan, Zheng 		ret = btrfs_copy_root(trans, root, root->node, &eb,
12923fd0a558SYan, Zheng 				      BTRFS_TREE_RELOC_OBJECTID);
12933fd0a558SYan, Zheng 		BUG_ON(ret);
12943fd0a558SYan, Zheng 	}
12953fd0a558SYan, Zheng 
12965d4f98a2SYan Zheng 	memcpy(root_item, &root->root_item, sizeof(*root_item));
12975d4f98a2SYan Zheng 	btrfs_set_root_bytenr(root_item, eb->start);
12985d4f98a2SYan Zheng 	btrfs_set_root_level(root_item, btrfs_header_level(eb));
12995d4f98a2SYan Zheng 	btrfs_set_root_generation(root_item, trans->transid);
13003fd0a558SYan, Zheng 
13013fd0a558SYan, Zheng 	if (root->root_key.objectid == objectid) {
13023fd0a558SYan, Zheng 		btrfs_set_root_refs(root_item, 0);
13033fd0a558SYan, Zheng 		memset(&root_item->drop_progress, 0,
13043fd0a558SYan, Zheng 		       sizeof(struct btrfs_disk_key));
13055d4f98a2SYan Zheng 		root_item->drop_level = 0;
13063fd0a558SYan, Zheng 	}
13075d4f98a2SYan Zheng 
13085d4f98a2SYan Zheng 	btrfs_tree_unlock(eb);
13095d4f98a2SYan Zheng 	free_extent_buffer(eb);
13105d4f98a2SYan Zheng 
13110b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root,
13125d4f98a2SYan Zheng 				&root_key, root_item);
13135d4f98a2SYan Zheng 	BUG_ON(ret);
13145d4f98a2SYan Zheng 	kfree(root_item);
13155d4f98a2SYan Zheng 
13163dbf1738SJosef Bacik 	reloc_root = btrfs_read_tree_root(fs_info->tree_root, &root_key);
13175d4f98a2SYan Zheng 	BUG_ON(IS_ERR(reloc_root));
13183dbf1738SJosef Bacik 	set_bit(BTRFS_ROOT_REF_COWS, &reloc_root->state);
13195d4f98a2SYan Zheng 	reloc_root->last_trans = trans->transid;
13203fd0a558SYan, Zheng 	return reloc_root;
13213fd0a558SYan, Zheng }
13223fd0a558SYan, Zheng 
13233fd0a558SYan, Zheng /*
13243fd0a558SYan, Zheng  * create reloc tree for a given fs tree. reloc tree is just a
13253fd0a558SYan, Zheng  * snapshot of the fs tree with special root objectid.
1326f44deb74SJosef Bacik  *
1327f44deb74SJosef Bacik  * The reloc_root comes out of here with two references, one for
1328f44deb74SJosef Bacik  * root->reloc_root, and another for being on the rc->reloc_roots list.
13293fd0a558SYan, Zheng  */
13303fd0a558SYan, Zheng int btrfs_init_reloc_root(struct btrfs_trans_handle *trans,
13313fd0a558SYan, Zheng 			  struct btrfs_root *root)
13323fd0a558SYan, Zheng {
13330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13343fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
13350b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
133620dd2cbfSMiao Xie 	struct btrfs_block_rsv *rsv;
13373fd0a558SYan, Zheng 	int clear_rsv = 0;
1338ffd7b339SJeff Mahoney 	int ret;
13393fd0a558SYan, Zheng 
1340aec7db3bSJosef Bacik 	if (!rc)
13412abc726aSJosef Bacik 		return 0;
13422abc726aSJosef Bacik 
13431fac4a54SQu Wenruo 	/*
13441fac4a54SQu Wenruo 	 * The subvolume has reloc tree but the swap is finished, no need to
13451fac4a54SQu Wenruo 	 * create/update the dead reloc tree
13461fac4a54SQu Wenruo 	 */
13476282675eSQu Wenruo 	if (reloc_root_is_dead(root))
13481fac4a54SQu Wenruo 		return 0;
13491fac4a54SQu Wenruo 
1350aec7db3bSJosef Bacik 	/*
1351aec7db3bSJosef Bacik 	 * This is subtle but important.  We do not do
1352aec7db3bSJosef Bacik 	 * record_root_in_transaction for reloc roots, instead we record their
1353aec7db3bSJosef Bacik 	 * corresponding fs root, and then here we update the last trans for the
1354aec7db3bSJosef Bacik 	 * reloc root.  This means that we have to do this for the entire life
1355aec7db3bSJosef Bacik 	 * of the reloc root, regardless of which stage of the relocation we are
1356aec7db3bSJosef Bacik 	 * in.
1357aec7db3bSJosef Bacik 	 */
13583fd0a558SYan, Zheng 	if (root->reloc_root) {
13593fd0a558SYan, Zheng 		reloc_root = root->reloc_root;
13603fd0a558SYan, Zheng 		reloc_root->last_trans = trans->transid;
13613fd0a558SYan, Zheng 		return 0;
13623fd0a558SYan, Zheng 	}
13633fd0a558SYan, Zheng 
1364aec7db3bSJosef Bacik 	/*
1365aec7db3bSJosef Bacik 	 * We are merging reloc roots, we do not need new reloc trees.  Also
1366aec7db3bSJosef Bacik 	 * reloc trees never need their own reloc tree.
1367aec7db3bSJosef Bacik 	 */
1368aec7db3bSJosef Bacik 	if (!rc->create_reloc_tree ||
1369aec7db3bSJosef Bacik 	    root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1370aec7db3bSJosef Bacik 		return 0;
1371aec7db3bSJosef Bacik 
137220dd2cbfSMiao Xie 	if (!trans->reloc_reserved) {
137320dd2cbfSMiao Xie 		rsv = trans->block_rsv;
13743fd0a558SYan, Zheng 		trans->block_rsv = rc->block_rsv;
13753fd0a558SYan, Zheng 		clear_rsv = 1;
13763fd0a558SYan, Zheng 	}
13773fd0a558SYan, Zheng 	reloc_root = create_reloc_root(trans, root, root->root_key.objectid);
13783fd0a558SYan, Zheng 	if (clear_rsv)
137920dd2cbfSMiao Xie 		trans->block_rsv = rsv;
13805d4f98a2SYan Zheng 
1381ffd7b339SJeff Mahoney 	ret = __add_reloc_root(reloc_root);
1382ffd7b339SJeff Mahoney 	BUG_ON(ret < 0);
1383f44deb74SJosef Bacik 	root->reloc_root = btrfs_grab_root(reloc_root);
13845d4f98a2SYan Zheng 	return 0;
13855d4f98a2SYan Zheng }
13865d4f98a2SYan Zheng 
13875d4f98a2SYan Zheng /*
13885d4f98a2SYan Zheng  * update root item of reloc tree
13895d4f98a2SYan Zheng  */
13905d4f98a2SYan Zheng int btrfs_update_reloc_root(struct btrfs_trans_handle *trans,
13915d4f98a2SYan Zheng 			    struct btrfs_root *root)
13925d4f98a2SYan Zheng {
13930b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13945d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
13955d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
13965d4f98a2SYan Zheng 	int ret;
13975d4f98a2SYan Zheng 
13986282675eSQu Wenruo 	if (!have_reloc_root(root))
13997585717fSChris Mason 		goto out;
14005d4f98a2SYan Zheng 
14015d4f98a2SYan Zheng 	reloc_root = root->reloc_root;
14025d4f98a2SYan Zheng 	root_item = &reloc_root->root_item;
14035d4f98a2SYan Zheng 
1404f44deb74SJosef Bacik 	/*
1405f44deb74SJosef Bacik 	 * We are probably ok here, but __del_reloc_root() will drop its ref of
1406f44deb74SJosef Bacik 	 * the root.  We have the ref for root->reloc_root, but just in case
1407f44deb74SJosef Bacik 	 * hold it while we update the reloc root.
1408f44deb74SJosef Bacik 	 */
1409f44deb74SJosef Bacik 	btrfs_grab_root(reloc_root);
1410f44deb74SJosef Bacik 
1411d2311e69SQu Wenruo 	/* root->reloc_root will stay until current relocation finished */
14120b246afaSJeff Mahoney 	if (fs_info->reloc_ctl->merge_reloc_tree &&
14133fd0a558SYan, Zheng 	    btrfs_root_refs(root_item) == 0) {
1414d2311e69SQu Wenruo 		set_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
14156282675eSQu Wenruo 		/*
14166282675eSQu Wenruo 		 * Mark the tree as dead before we change reloc_root so
14176282675eSQu Wenruo 		 * have_reloc_root will not touch it from now on.
14186282675eSQu Wenruo 		 */
14196282675eSQu Wenruo 		smp_wmb();
1420c974c464SWang Shilong 		__del_reloc_root(reloc_root);
14215d4f98a2SYan Zheng 	}
14225d4f98a2SYan Zheng 
14235d4f98a2SYan Zheng 	if (reloc_root->commit_root != reloc_root->node) {
1424ea287ab1SJosef Bacik 		__update_reloc_root(reloc_root);
14255d4f98a2SYan Zheng 		btrfs_set_root_node(root_item, reloc_root->node);
14265d4f98a2SYan Zheng 		free_extent_buffer(reloc_root->commit_root);
14275d4f98a2SYan Zheng 		reloc_root->commit_root = btrfs_root_node(reloc_root);
14285d4f98a2SYan Zheng 	}
14295d4f98a2SYan Zheng 
14300b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
14315d4f98a2SYan Zheng 				&reloc_root->root_key, root_item);
14325d4f98a2SYan Zheng 	BUG_ON(ret);
1433f44deb74SJosef Bacik 	btrfs_put_root(reloc_root);
14347585717fSChris Mason out:
14355d4f98a2SYan Zheng 	return 0;
14365d4f98a2SYan Zheng }
14375d4f98a2SYan Zheng 
14385d4f98a2SYan Zheng /*
14395d4f98a2SYan Zheng  * helper to find first cached inode with inode number >= objectid
14405d4f98a2SYan Zheng  * in a subvolume
14415d4f98a2SYan Zheng  */
14425d4f98a2SYan Zheng static struct inode *find_next_inode(struct btrfs_root *root, u64 objectid)
14435d4f98a2SYan Zheng {
14445d4f98a2SYan Zheng 	struct rb_node *node;
14455d4f98a2SYan Zheng 	struct rb_node *prev;
14465d4f98a2SYan Zheng 	struct btrfs_inode *entry;
14475d4f98a2SYan Zheng 	struct inode *inode;
14485d4f98a2SYan Zheng 
14495d4f98a2SYan Zheng 	spin_lock(&root->inode_lock);
14505d4f98a2SYan Zheng again:
14515d4f98a2SYan Zheng 	node = root->inode_tree.rb_node;
14525d4f98a2SYan Zheng 	prev = NULL;
14535d4f98a2SYan Zheng 	while (node) {
14545d4f98a2SYan Zheng 		prev = node;
14555d4f98a2SYan Zheng 		entry = rb_entry(node, struct btrfs_inode, rb_node);
14565d4f98a2SYan Zheng 
14574a0cc7caSNikolay Borisov 		if (objectid < btrfs_ino(entry))
14585d4f98a2SYan Zheng 			node = node->rb_left;
14594a0cc7caSNikolay Borisov 		else if (objectid > btrfs_ino(entry))
14605d4f98a2SYan Zheng 			node = node->rb_right;
14615d4f98a2SYan Zheng 		else
14625d4f98a2SYan Zheng 			break;
14635d4f98a2SYan Zheng 	}
14645d4f98a2SYan Zheng 	if (!node) {
14655d4f98a2SYan Zheng 		while (prev) {
14665d4f98a2SYan Zheng 			entry = rb_entry(prev, struct btrfs_inode, rb_node);
14674a0cc7caSNikolay Borisov 			if (objectid <= btrfs_ino(entry)) {
14685d4f98a2SYan Zheng 				node = prev;
14695d4f98a2SYan Zheng 				break;
14705d4f98a2SYan Zheng 			}
14715d4f98a2SYan Zheng 			prev = rb_next(prev);
14725d4f98a2SYan Zheng 		}
14735d4f98a2SYan Zheng 	}
14745d4f98a2SYan Zheng 	while (node) {
14755d4f98a2SYan Zheng 		entry = rb_entry(node, struct btrfs_inode, rb_node);
14765d4f98a2SYan Zheng 		inode = igrab(&entry->vfs_inode);
14775d4f98a2SYan Zheng 		if (inode) {
14785d4f98a2SYan Zheng 			spin_unlock(&root->inode_lock);
14795d4f98a2SYan Zheng 			return inode;
14805d4f98a2SYan Zheng 		}
14815d4f98a2SYan Zheng 
14824a0cc7caSNikolay Borisov 		objectid = btrfs_ino(entry) + 1;
14835d4f98a2SYan Zheng 		if (cond_resched_lock(&root->inode_lock))
14845d4f98a2SYan Zheng 			goto again;
14855d4f98a2SYan Zheng 
14865d4f98a2SYan Zheng 		node = rb_next(node);
14875d4f98a2SYan Zheng 	}
14885d4f98a2SYan Zheng 	spin_unlock(&root->inode_lock);
14895d4f98a2SYan Zheng 	return NULL;
14905d4f98a2SYan Zheng }
14915d4f98a2SYan Zheng 
14925d4f98a2SYan Zheng /*
14935d4f98a2SYan Zheng  * get new location of data
14945d4f98a2SYan Zheng  */
14955d4f98a2SYan Zheng static int get_new_location(struct inode *reloc_inode, u64 *new_bytenr,
14965d4f98a2SYan Zheng 			    u64 bytenr, u64 num_bytes)
14975d4f98a2SYan Zheng {
14985d4f98a2SYan Zheng 	struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
14995d4f98a2SYan Zheng 	struct btrfs_path *path;
15005d4f98a2SYan Zheng 	struct btrfs_file_extent_item *fi;
15015d4f98a2SYan Zheng 	struct extent_buffer *leaf;
15025d4f98a2SYan Zheng 	int ret;
15035d4f98a2SYan Zheng 
15045d4f98a2SYan Zheng 	path = btrfs_alloc_path();
15055d4f98a2SYan Zheng 	if (!path)
15065d4f98a2SYan Zheng 		return -ENOMEM;
15075d4f98a2SYan Zheng 
15085d4f98a2SYan Zheng 	bytenr -= BTRFS_I(reloc_inode)->index_cnt;
1509f85b7379SDavid Sterba 	ret = btrfs_lookup_file_extent(NULL, root, path,
1510f85b7379SDavid Sterba 			btrfs_ino(BTRFS_I(reloc_inode)), bytenr, 0);
15115d4f98a2SYan Zheng 	if (ret < 0)
15125d4f98a2SYan Zheng 		goto out;
15135d4f98a2SYan Zheng 	if (ret > 0) {
15145d4f98a2SYan Zheng 		ret = -ENOENT;
15155d4f98a2SYan Zheng 		goto out;
15165d4f98a2SYan Zheng 	}
15175d4f98a2SYan Zheng 
15185d4f98a2SYan Zheng 	leaf = path->nodes[0];
15195d4f98a2SYan Zheng 	fi = btrfs_item_ptr(leaf, path->slots[0],
15205d4f98a2SYan Zheng 			    struct btrfs_file_extent_item);
15215d4f98a2SYan Zheng 
15225d4f98a2SYan Zheng 	BUG_ON(btrfs_file_extent_offset(leaf, fi) ||
15235d4f98a2SYan Zheng 	       btrfs_file_extent_compression(leaf, fi) ||
15245d4f98a2SYan Zheng 	       btrfs_file_extent_encryption(leaf, fi) ||
15255d4f98a2SYan Zheng 	       btrfs_file_extent_other_encoding(leaf, fi));
15265d4f98a2SYan Zheng 
15275d4f98a2SYan Zheng 	if (num_bytes != btrfs_file_extent_disk_num_bytes(leaf, fi)) {
152883d4cfd4SJosef Bacik 		ret = -EINVAL;
15295d4f98a2SYan Zheng 		goto out;
15305d4f98a2SYan Zheng 	}
15315d4f98a2SYan Zheng 
15325d4f98a2SYan Zheng 	*new_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
15335d4f98a2SYan Zheng 	ret = 0;
15345d4f98a2SYan Zheng out:
15355d4f98a2SYan Zheng 	btrfs_free_path(path);
15365d4f98a2SYan Zheng 	return ret;
15375d4f98a2SYan Zheng }
15385d4f98a2SYan Zheng 
15395d4f98a2SYan Zheng /*
15405d4f98a2SYan Zheng  * update file extent items in the tree leaf to point to
15415d4f98a2SYan Zheng  * the new locations.
15425d4f98a2SYan Zheng  */
15433fd0a558SYan, Zheng static noinline_for_stack
15443fd0a558SYan, Zheng int replace_file_extents(struct btrfs_trans_handle *trans,
15455d4f98a2SYan Zheng 			 struct reloc_control *rc,
15465d4f98a2SYan Zheng 			 struct btrfs_root *root,
15473fd0a558SYan, Zheng 			 struct extent_buffer *leaf)
15485d4f98a2SYan Zheng {
15490b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15505d4f98a2SYan Zheng 	struct btrfs_key key;
15515d4f98a2SYan Zheng 	struct btrfs_file_extent_item *fi;
15525d4f98a2SYan Zheng 	struct inode *inode = NULL;
15535d4f98a2SYan Zheng 	u64 parent;
15545d4f98a2SYan Zheng 	u64 bytenr;
15553fd0a558SYan, Zheng 	u64 new_bytenr = 0;
15565d4f98a2SYan Zheng 	u64 num_bytes;
15575d4f98a2SYan Zheng 	u64 end;
15585d4f98a2SYan Zheng 	u32 nritems;
15595d4f98a2SYan Zheng 	u32 i;
156083d4cfd4SJosef Bacik 	int ret = 0;
15615d4f98a2SYan Zheng 	int first = 1;
15625d4f98a2SYan Zheng 	int dirty = 0;
15635d4f98a2SYan Zheng 
15645d4f98a2SYan Zheng 	if (rc->stage != UPDATE_DATA_PTRS)
15655d4f98a2SYan Zheng 		return 0;
15665d4f98a2SYan Zheng 
15675d4f98a2SYan Zheng 	/* reloc trees always use full backref */
15685d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
15695d4f98a2SYan Zheng 		parent = leaf->start;
15705d4f98a2SYan Zheng 	else
15715d4f98a2SYan Zheng 		parent = 0;
15725d4f98a2SYan Zheng 
15735d4f98a2SYan Zheng 	nritems = btrfs_header_nritems(leaf);
15745d4f98a2SYan Zheng 	for (i = 0; i < nritems; i++) {
157582fa113fSQu Wenruo 		struct btrfs_ref ref = { 0 };
157682fa113fSQu Wenruo 
15775d4f98a2SYan Zheng 		cond_resched();
15785d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, i);
15795d4f98a2SYan Zheng 		if (key.type != BTRFS_EXTENT_DATA_KEY)
15805d4f98a2SYan Zheng 			continue;
15815d4f98a2SYan Zheng 		fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
15825d4f98a2SYan Zheng 		if (btrfs_file_extent_type(leaf, fi) ==
15835d4f98a2SYan Zheng 		    BTRFS_FILE_EXTENT_INLINE)
15845d4f98a2SYan Zheng 			continue;
15855d4f98a2SYan Zheng 		bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
15865d4f98a2SYan Zheng 		num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
15875d4f98a2SYan Zheng 		if (bytenr == 0)
15885d4f98a2SYan Zheng 			continue;
15899569cc20SQu Wenruo 		if (!in_range(bytenr, rc->block_group->start,
15909569cc20SQu Wenruo 			      rc->block_group->length))
15915d4f98a2SYan Zheng 			continue;
15925d4f98a2SYan Zheng 
15935d4f98a2SYan Zheng 		/*
15945d4f98a2SYan Zheng 		 * if we are modifying block in fs tree, wait for readpage
15955d4f98a2SYan Zheng 		 * to complete and drop the extent cache
15965d4f98a2SYan Zheng 		 */
15975d4f98a2SYan Zheng 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
15985d4f98a2SYan Zheng 			if (first) {
15995d4f98a2SYan Zheng 				inode = find_next_inode(root, key.objectid);
16005d4f98a2SYan Zheng 				first = 0;
16014a0cc7caSNikolay Borisov 			} else if (inode && btrfs_ino(BTRFS_I(inode)) < key.objectid) {
16023fd0a558SYan, Zheng 				btrfs_add_delayed_iput(inode);
16035d4f98a2SYan Zheng 				inode = find_next_inode(root, key.objectid);
16045d4f98a2SYan Zheng 			}
16054a0cc7caSNikolay Borisov 			if (inode && btrfs_ino(BTRFS_I(inode)) == key.objectid) {
16065d4f98a2SYan Zheng 				end = key.offset +
16075d4f98a2SYan Zheng 				      btrfs_file_extent_num_bytes(leaf, fi);
16085d4f98a2SYan Zheng 				WARN_ON(!IS_ALIGNED(key.offset,
16090b246afaSJeff Mahoney 						    fs_info->sectorsize));
16100b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
16115d4f98a2SYan Zheng 				end--;
16125d4f98a2SYan Zheng 				ret = try_lock_extent(&BTRFS_I(inode)->io_tree,
1613d0082371SJeff Mahoney 						      key.offset, end);
16145d4f98a2SYan Zheng 				if (!ret)
16155d4f98a2SYan Zheng 					continue;
16165d4f98a2SYan Zheng 
1617dcdbc059SNikolay Borisov 				btrfs_drop_extent_cache(BTRFS_I(inode),
1618dcdbc059SNikolay Borisov 						key.offset,	end, 1);
16195d4f98a2SYan Zheng 				unlock_extent(&BTRFS_I(inode)->io_tree,
1620d0082371SJeff Mahoney 					      key.offset, end);
16215d4f98a2SYan Zheng 			}
16225d4f98a2SYan Zheng 		}
16235d4f98a2SYan Zheng 
16245d4f98a2SYan Zheng 		ret = get_new_location(rc->data_inode, &new_bytenr,
16255d4f98a2SYan Zheng 				       bytenr, num_bytes);
162683d4cfd4SJosef Bacik 		if (ret) {
162783d4cfd4SJosef Bacik 			/*
162883d4cfd4SJosef Bacik 			 * Don't have to abort since we've not changed anything
162983d4cfd4SJosef Bacik 			 * in the file extent yet.
163083d4cfd4SJosef Bacik 			 */
163183d4cfd4SJosef Bacik 			break;
16323fd0a558SYan, Zheng 		}
16335d4f98a2SYan Zheng 
16345d4f98a2SYan Zheng 		btrfs_set_file_extent_disk_bytenr(leaf, fi, new_bytenr);
16355d4f98a2SYan Zheng 		dirty = 1;
16365d4f98a2SYan Zheng 
16375d4f98a2SYan Zheng 		key.offset -= btrfs_file_extent_offset(leaf, fi);
163882fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new_bytenr,
163982fa113fSQu Wenruo 				       num_bytes, parent);
164082fa113fSQu Wenruo 		ref.real_root = root->root_key.objectid;
164182fa113fSQu Wenruo 		btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
1642b06c4bf5SFilipe Manana 				    key.objectid, key.offset);
164382fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
164483d4cfd4SJosef Bacik 		if (ret) {
164566642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
164683d4cfd4SJosef Bacik 			break;
164783d4cfd4SJosef Bacik 		}
16485d4f98a2SYan Zheng 
1649ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
1650ffd4bb2aSQu Wenruo 				       num_bytes, parent);
1651ffd4bb2aSQu Wenruo 		ref.real_root = root->root_key.objectid;
1652ffd4bb2aSQu Wenruo 		btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
1653b06c4bf5SFilipe Manana 				    key.objectid, key.offset);
1654ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
165583d4cfd4SJosef Bacik 		if (ret) {
165666642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
165783d4cfd4SJosef Bacik 			break;
165883d4cfd4SJosef Bacik 		}
16595d4f98a2SYan Zheng 	}
16605d4f98a2SYan Zheng 	if (dirty)
16615d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(leaf);
16623fd0a558SYan, Zheng 	if (inode)
16633fd0a558SYan, Zheng 		btrfs_add_delayed_iput(inode);
166483d4cfd4SJosef Bacik 	return ret;
16655d4f98a2SYan Zheng }
16665d4f98a2SYan Zheng 
16675d4f98a2SYan Zheng static noinline_for_stack
16685d4f98a2SYan Zheng int memcmp_node_keys(struct extent_buffer *eb, int slot,
16695d4f98a2SYan Zheng 		     struct btrfs_path *path, int level)
16705d4f98a2SYan Zheng {
16715d4f98a2SYan Zheng 	struct btrfs_disk_key key1;
16725d4f98a2SYan Zheng 	struct btrfs_disk_key key2;
16735d4f98a2SYan Zheng 	btrfs_node_key(eb, &key1, slot);
16745d4f98a2SYan Zheng 	btrfs_node_key(path->nodes[level], &key2, path->slots[level]);
16755d4f98a2SYan Zheng 	return memcmp(&key1, &key2, sizeof(key1));
16765d4f98a2SYan Zheng }
16775d4f98a2SYan Zheng 
16785d4f98a2SYan Zheng /*
16795d4f98a2SYan Zheng  * try to replace tree blocks in fs tree with the new blocks
16805d4f98a2SYan Zheng  * in reloc tree. tree blocks haven't been modified since the
16815d4f98a2SYan Zheng  * reloc tree was create can be replaced.
16825d4f98a2SYan Zheng  *
16835d4f98a2SYan Zheng  * if a block was replaced, level of the block + 1 is returned.
16845d4f98a2SYan Zheng  * if no block got replaced, 0 is returned. if there are other
16855d4f98a2SYan Zheng  * errors, a negative error number is returned.
16865d4f98a2SYan Zheng  */
16873fd0a558SYan, Zheng static noinline_for_stack
16883d0174f7SQu Wenruo int replace_path(struct btrfs_trans_handle *trans, struct reloc_control *rc,
16895d4f98a2SYan Zheng 		 struct btrfs_root *dest, struct btrfs_root *src,
16905d4f98a2SYan Zheng 		 struct btrfs_path *path, struct btrfs_key *next_key,
16915d4f98a2SYan Zheng 		 int lowest_level, int max_level)
16925d4f98a2SYan Zheng {
16930b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = dest->fs_info;
16945d4f98a2SYan Zheng 	struct extent_buffer *eb;
16955d4f98a2SYan Zheng 	struct extent_buffer *parent;
169682fa113fSQu Wenruo 	struct btrfs_ref ref = { 0 };
16975d4f98a2SYan Zheng 	struct btrfs_key key;
16985d4f98a2SYan Zheng 	u64 old_bytenr;
16995d4f98a2SYan Zheng 	u64 new_bytenr;
17005d4f98a2SYan Zheng 	u64 old_ptr_gen;
17015d4f98a2SYan Zheng 	u64 new_ptr_gen;
17025d4f98a2SYan Zheng 	u64 last_snapshot;
17035d4f98a2SYan Zheng 	u32 blocksize;
17043fd0a558SYan, Zheng 	int cow = 0;
17055d4f98a2SYan Zheng 	int level;
17065d4f98a2SYan Zheng 	int ret;
17075d4f98a2SYan Zheng 	int slot;
17085d4f98a2SYan Zheng 
17095d4f98a2SYan Zheng 	BUG_ON(src->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
17105d4f98a2SYan Zheng 	BUG_ON(dest->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID);
17115d4f98a2SYan Zheng 
17125d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&src->root_item);
17133fd0a558SYan, Zheng again:
17145d4f98a2SYan Zheng 	slot = path->slots[lowest_level];
17155d4f98a2SYan Zheng 	btrfs_node_key_to_cpu(path->nodes[lowest_level], &key, slot);
17165d4f98a2SYan Zheng 
17175d4f98a2SYan Zheng 	eb = btrfs_lock_root_node(dest);
17188bead258SDavid Sterba 	btrfs_set_lock_blocking_write(eb);
17195d4f98a2SYan Zheng 	level = btrfs_header_level(eb);
17205d4f98a2SYan Zheng 
17215d4f98a2SYan Zheng 	if (level < lowest_level) {
17225d4f98a2SYan Zheng 		btrfs_tree_unlock(eb);
17235d4f98a2SYan Zheng 		free_extent_buffer(eb);
17245d4f98a2SYan Zheng 		return 0;
17255d4f98a2SYan Zheng 	}
17265d4f98a2SYan Zheng 
17273fd0a558SYan, Zheng 	if (cow) {
17285d4f98a2SYan Zheng 		ret = btrfs_cow_block(trans, dest, eb, NULL, 0, &eb);
17295d4f98a2SYan Zheng 		BUG_ON(ret);
17303fd0a558SYan, Zheng 	}
17318bead258SDavid Sterba 	btrfs_set_lock_blocking_write(eb);
17325d4f98a2SYan Zheng 
17335d4f98a2SYan Zheng 	if (next_key) {
17345d4f98a2SYan Zheng 		next_key->objectid = (u64)-1;
17355d4f98a2SYan Zheng 		next_key->type = (u8)-1;
17365d4f98a2SYan Zheng 		next_key->offset = (u64)-1;
17375d4f98a2SYan Zheng 	}
17385d4f98a2SYan Zheng 
17395d4f98a2SYan Zheng 	parent = eb;
17405d4f98a2SYan Zheng 	while (1) {
1741581c1760SQu Wenruo 		struct btrfs_key first_key;
1742581c1760SQu Wenruo 
17435d4f98a2SYan Zheng 		level = btrfs_header_level(parent);
17445d4f98a2SYan Zheng 		BUG_ON(level < lowest_level);
17455d4f98a2SYan Zheng 
17465d4f98a2SYan Zheng 		ret = btrfs_bin_search(parent, &key, level, &slot);
1747cbca7d59SFilipe Manana 		if (ret < 0)
1748cbca7d59SFilipe Manana 			break;
17495d4f98a2SYan Zheng 		if (ret && slot > 0)
17505d4f98a2SYan Zheng 			slot--;
17515d4f98a2SYan Zheng 
17525d4f98a2SYan Zheng 		if (next_key && slot + 1 < btrfs_header_nritems(parent))
17535d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(parent, next_key, slot + 1);
17545d4f98a2SYan Zheng 
17555d4f98a2SYan Zheng 		old_bytenr = btrfs_node_blockptr(parent, slot);
17560b246afaSJeff Mahoney 		blocksize = fs_info->nodesize;
17575d4f98a2SYan Zheng 		old_ptr_gen = btrfs_node_ptr_generation(parent, slot);
175817515f1bSQu Wenruo 		btrfs_node_key_to_cpu(parent, &first_key, slot);
17595d4f98a2SYan Zheng 
17605d4f98a2SYan Zheng 		if (level <= max_level) {
17615d4f98a2SYan Zheng 			eb = path->nodes[level];
17625d4f98a2SYan Zheng 			new_bytenr = btrfs_node_blockptr(eb,
17635d4f98a2SYan Zheng 							path->slots[level]);
17645d4f98a2SYan Zheng 			new_ptr_gen = btrfs_node_ptr_generation(eb,
17655d4f98a2SYan Zheng 							path->slots[level]);
17665d4f98a2SYan Zheng 		} else {
17675d4f98a2SYan Zheng 			new_bytenr = 0;
17685d4f98a2SYan Zheng 			new_ptr_gen = 0;
17695d4f98a2SYan Zheng 		}
17705d4f98a2SYan Zheng 
1771fae7f21cSDulshani Gunawardhana 		if (WARN_ON(new_bytenr > 0 && new_bytenr == old_bytenr)) {
17725d4f98a2SYan Zheng 			ret = level;
17735d4f98a2SYan Zheng 			break;
17745d4f98a2SYan Zheng 		}
17755d4f98a2SYan Zheng 
17765d4f98a2SYan Zheng 		if (new_bytenr == 0 || old_ptr_gen > last_snapshot ||
17775d4f98a2SYan Zheng 		    memcmp_node_keys(parent, slot, path, level)) {
17783fd0a558SYan, Zheng 			if (level <= lowest_level) {
17795d4f98a2SYan Zheng 				ret = 0;
17805d4f98a2SYan Zheng 				break;
17815d4f98a2SYan Zheng 			}
17825d4f98a2SYan Zheng 
1783581c1760SQu Wenruo 			eb = read_tree_block(fs_info, old_bytenr, old_ptr_gen,
1784581c1760SQu Wenruo 					     level - 1, &first_key);
178564c043deSLiu Bo 			if (IS_ERR(eb)) {
178664c043deSLiu Bo 				ret = PTR_ERR(eb);
1787264813acSLiu Bo 				break;
178864c043deSLiu Bo 			} else if (!extent_buffer_uptodate(eb)) {
178964c043deSLiu Bo 				ret = -EIO;
1790416bc658SJosef Bacik 				free_extent_buffer(eb);
1791379cde74SStefan Behrens 				break;
1792416bc658SJosef Bacik 			}
17935d4f98a2SYan Zheng 			btrfs_tree_lock(eb);
17943fd0a558SYan, Zheng 			if (cow) {
17955d4f98a2SYan Zheng 				ret = btrfs_cow_block(trans, dest, eb, parent,
17965d4f98a2SYan Zheng 						      slot, &eb);
17975d4f98a2SYan Zheng 				BUG_ON(ret);
17985d4f98a2SYan Zheng 			}
17998bead258SDavid Sterba 			btrfs_set_lock_blocking_write(eb);
18005d4f98a2SYan Zheng 
18015d4f98a2SYan Zheng 			btrfs_tree_unlock(parent);
18025d4f98a2SYan Zheng 			free_extent_buffer(parent);
18035d4f98a2SYan Zheng 
18045d4f98a2SYan Zheng 			parent = eb;
18055d4f98a2SYan Zheng 			continue;
18065d4f98a2SYan Zheng 		}
18075d4f98a2SYan Zheng 
18083fd0a558SYan, Zheng 		if (!cow) {
18093fd0a558SYan, Zheng 			btrfs_tree_unlock(parent);
18103fd0a558SYan, Zheng 			free_extent_buffer(parent);
18113fd0a558SYan, Zheng 			cow = 1;
18123fd0a558SYan, Zheng 			goto again;
18133fd0a558SYan, Zheng 		}
18143fd0a558SYan, Zheng 
18155d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(path->nodes[level], &key,
18165d4f98a2SYan Zheng 				      path->slots[level]);
1817b3b4aa74SDavid Sterba 		btrfs_release_path(path);
18185d4f98a2SYan Zheng 
18195d4f98a2SYan Zheng 		path->lowest_level = level;
18205d4f98a2SYan Zheng 		ret = btrfs_search_slot(trans, src, &key, path, 0, 1);
18215d4f98a2SYan Zheng 		path->lowest_level = 0;
18225d4f98a2SYan Zheng 		BUG_ON(ret);
18235d4f98a2SYan Zheng 
18245d4f98a2SYan Zheng 		/*
1825824d8dffSQu Wenruo 		 * Info qgroup to trace both subtrees.
1826824d8dffSQu Wenruo 		 *
1827824d8dffSQu Wenruo 		 * We must trace both trees.
1828824d8dffSQu Wenruo 		 * 1) Tree reloc subtree
1829824d8dffSQu Wenruo 		 *    If not traced, we will leak data numbers
1830824d8dffSQu Wenruo 		 * 2) Fs subtree
1831824d8dffSQu Wenruo 		 *    If not traced, we will double count old data
1832f616f5cdSQu Wenruo 		 *
1833f616f5cdSQu Wenruo 		 * We don't scan the subtree right now, but only record
1834f616f5cdSQu Wenruo 		 * the swapped tree blocks.
1835f616f5cdSQu Wenruo 		 * The real subtree rescan is delayed until we have new
1836f616f5cdSQu Wenruo 		 * CoW on the subtree root node before transaction commit.
1837824d8dffSQu Wenruo 		 */
1838370a11b8SQu Wenruo 		ret = btrfs_qgroup_add_swapped_blocks(trans, dest,
1839370a11b8SQu Wenruo 				rc->block_group, parent, slot,
1840370a11b8SQu Wenruo 				path->nodes[level], path->slots[level],
1841370a11b8SQu Wenruo 				last_snapshot);
1842370a11b8SQu Wenruo 		if (ret < 0)
1843370a11b8SQu Wenruo 			break;
1844824d8dffSQu Wenruo 		/*
18455d4f98a2SYan Zheng 		 * swap blocks in fs tree and reloc tree.
18465d4f98a2SYan Zheng 		 */
18475d4f98a2SYan Zheng 		btrfs_set_node_blockptr(parent, slot, new_bytenr);
18485d4f98a2SYan Zheng 		btrfs_set_node_ptr_generation(parent, slot, new_ptr_gen);
18495d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(parent);
18505d4f98a2SYan Zheng 
18515d4f98a2SYan Zheng 		btrfs_set_node_blockptr(path->nodes[level],
18525d4f98a2SYan Zheng 					path->slots[level], old_bytenr);
18535d4f98a2SYan Zheng 		btrfs_set_node_ptr_generation(path->nodes[level],
18545d4f98a2SYan Zheng 					      path->slots[level], old_ptr_gen);
18555d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(path->nodes[level]);
18565d4f98a2SYan Zheng 
185782fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, old_bytenr,
185882fa113fSQu Wenruo 				       blocksize, path->nodes[level]->start);
185982fa113fSQu Wenruo 		ref.skip_qgroup = true;
186082fa113fSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, src->root_key.objectid);
186182fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
18625d4f98a2SYan Zheng 		BUG_ON(ret);
186382fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new_bytenr,
186482fa113fSQu Wenruo 				       blocksize, 0);
186582fa113fSQu Wenruo 		ref.skip_qgroup = true;
186682fa113fSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, dest->root_key.objectid);
186782fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
18685d4f98a2SYan Zheng 		BUG_ON(ret);
18695d4f98a2SYan Zheng 
1870ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, new_bytenr,
1871ffd4bb2aSQu Wenruo 				       blocksize, path->nodes[level]->start);
1872ffd4bb2aSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, src->root_key.objectid);
1873ffd4bb2aSQu Wenruo 		ref.skip_qgroup = true;
1874ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
18755d4f98a2SYan Zheng 		BUG_ON(ret);
18765d4f98a2SYan Zheng 
1877ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, old_bytenr,
1878ffd4bb2aSQu Wenruo 				       blocksize, 0);
1879ffd4bb2aSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, dest->root_key.objectid);
1880ffd4bb2aSQu Wenruo 		ref.skip_qgroup = true;
1881ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
18825d4f98a2SYan Zheng 		BUG_ON(ret);
18835d4f98a2SYan Zheng 
18845d4f98a2SYan Zheng 		btrfs_unlock_up_safe(path, 0);
18855d4f98a2SYan Zheng 
18865d4f98a2SYan Zheng 		ret = level;
18875d4f98a2SYan Zheng 		break;
18885d4f98a2SYan Zheng 	}
18895d4f98a2SYan Zheng 	btrfs_tree_unlock(parent);
18905d4f98a2SYan Zheng 	free_extent_buffer(parent);
18915d4f98a2SYan Zheng 	return ret;
18925d4f98a2SYan Zheng }
18935d4f98a2SYan Zheng 
18945d4f98a2SYan Zheng /*
18955d4f98a2SYan Zheng  * helper to find next relocated block in reloc tree
18965d4f98a2SYan Zheng  */
18975d4f98a2SYan Zheng static noinline_for_stack
18985d4f98a2SYan Zheng int walk_up_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
18995d4f98a2SYan Zheng 		       int *level)
19005d4f98a2SYan Zheng {
19015d4f98a2SYan Zheng 	struct extent_buffer *eb;
19025d4f98a2SYan Zheng 	int i;
19035d4f98a2SYan Zheng 	u64 last_snapshot;
19045d4f98a2SYan Zheng 	u32 nritems;
19055d4f98a2SYan Zheng 
19065d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
19075d4f98a2SYan Zheng 
19085d4f98a2SYan Zheng 	for (i = 0; i < *level; i++) {
19095d4f98a2SYan Zheng 		free_extent_buffer(path->nodes[i]);
19105d4f98a2SYan Zheng 		path->nodes[i] = NULL;
19115d4f98a2SYan Zheng 	}
19125d4f98a2SYan Zheng 
19135d4f98a2SYan Zheng 	for (i = *level; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
19145d4f98a2SYan Zheng 		eb = path->nodes[i];
19155d4f98a2SYan Zheng 		nritems = btrfs_header_nritems(eb);
19165d4f98a2SYan Zheng 		while (path->slots[i] + 1 < nritems) {
19175d4f98a2SYan Zheng 			path->slots[i]++;
19185d4f98a2SYan Zheng 			if (btrfs_node_ptr_generation(eb, path->slots[i]) <=
19195d4f98a2SYan Zheng 			    last_snapshot)
19205d4f98a2SYan Zheng 				continue;
19215d4f98a2SYan Zheng 
19225d4f98a2SYan Zheng 			*level = i;
19235d4f98a2SYan Zheng 			return 0;
19245d4f98a2SYan Zheng 		}
19255d4f98a2SYan Zheng 		free_extent_buffer(path->nodes[i]);
19265d4f98a2SYan Zheng 		path->nodes[i] = NULL;
19275d4f98a2SYan Zheng 	}
19285d4f98a2SYan Zheng 	return 1;
19295d4f98a2SYan Zheng }
19305d4f98a2SYan Zheng 
19315d4f98a2SYan Zheng /*
19325d4f98a2SYan Zheng  * walk down reloc tree to find relocated block of lowest level
19335d4f98a2SYan Zheng  */
19345d4f98a2SYan Zheng static noinline_for_stack
19355d4f98a2SYan Zheng int walk_down_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
19365d4f98a2SYan Zheng 			 int *level)
19375d4f98a2SYan Zheng {
19382ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
19395d4f98a2SYan Zheng 	struct extent_buffer *eb = NULL;
19405d4f98a2SYan Zheng 	int i;
19415d4f98a2SYan Zheng 	u64 bytenr;
19425d4f98a2SYan Zheng 	u64 ptr_gen = 0;
19435d4f98a2SYan Zheng 	u64 last_snapshot;
19445d4f98a2SYan Zheng 	u32 nritems;
19455d4f98a2SYan Zheng 
19465d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
19475d4f98a2SYan Zheng 
19485d4f98a2SYan Zheng 	for (i = *level; i > 0; i--) {
1949581c1760SQu Wenruo 		struct btrfs_key first_key;
1950581c1760SQu Wenruo 
19515d4f98a2SYan Zheng 		eb = path->nodes[i];
19525d4f98a2SYan Zheng 		nritems = btrfs_header_nritems(eb);
19535d4f98a2SYan Zheng 		while (path->slots[i] < nritems) {
19545d4f98a2SYan Zheng 			ptr_gen = btrfs_node_ptr_generation(eb, path->slots[i]);
19555d4f98a2SYan Zheng 			if (ptr_gen > last_snapshot)
19565d4f98a2SYan Zheng 				break;
19575d4f98a2SYan Zheng 			path->slots[i]++;
19585d4f98a2SYan Zheng 		}
19595d4f98a2SYan Zheng 		if (path->slots[i] >= nritems) {
19605d4f98a2SYan Zheng 			if (i == *level)
19615d4f98a2SYan Zheng 				break;
19625d4f98a2SYan Zheng 			*level = i + 1;
19635d4f98a2SYan Zheng 			return 0;
19645d4f98a2SYan Zheng 		}
19655d4f98a2SYan Zheng 		if (i == 1) {
19665d4f98a2SYan Zheng 			*level = i;
19675d4f98a2SYan Zheng 			return 0;
19685d4f98a2SYan Zheng 		}
19695d4f98a2SYan Zheng 
19705d4f98a2SYan Zheng 		bytenr = btrfs_node_blockptr(eb, path->slots[i]);
1971581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &first_key, path->slots[i]);
1972581c1760SQu Wenruo 		eb = read_tree_block(fs_info, bytenr, ptr_gen, i - 1,
1973581c1760SQu Wenruo 				     &first_key);
197464c043deSLiu Bo 		if (IS_ERR(eb)) {
197564c043deSLiu Bo 			return PTR_ERR(eb);
197664c043deSLiu Bo 		} else if (!extent_buffer_uptodate(eb)) {
1977416bc658SJosef Bacik 			free_extent_buffer(eb);
1978416bc658SJosef Bacik 			return -EIO;
1979416bc658SJosef Bacik 		}
19805d4f98a2SYan Zheng 		BUG_ON(btrfs_header_level(eb) != i - 1);
19815d4f98a2SYan Zheng 		path->nodes[i - 1] = eb;
19825d4f98a2SYan Zheng 		path->slots[i - 1] = 0;
19835d4f98a2SYan Zheng 	}
19845d4f98a2SYan Zheng 	return 1;
19855d4f98a2SYan Zheng }
19865d4f98a2SYan Zheng 
19875d4f98a2SYan Zheng /*
19885d4f98a2SYan Zheng  * invalidate extent cache for file extents whose key in range of
19895d4f98a2SYan Zheng  * [min_key, max_key)
19905d4f98a2SYan Zheng  */
19915d4f98a2SYan Zheng static int invalidate_extent_cache(struct btrfs_root *root,
19925d4f98a2SYan Zheng 				   struct btrfs_key *min_key,
19935d4f98a2SYan Zheng 				   struct btrfs_key *max_key)
19945d4f98a2SYan Zheng {
19950b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
19965d4f98a2SYan Zheng 	struct inode *inode = NULL;
19975d4f98a2SYan Zheng 	u64 objectid;
19985d4f98a2SYan Zheng 	u64 start, end;
199933345d01SLi Zefan 	u64 ino;
20005d4f98a2SYan Zheng 
20015d4f98a2SYan Zheng 	objectid = min_key->objectid;
20025d4f98a2SYan Zheng 	while (1) {
20035d4f98a2SYan Zheng 		cond_resched();
20045d4f98a2SYan Zheng 		iput(inode);
20055d4f98a2SYan Zheng 
20065d4f98a2SYan Zheng 		if (objectid > max_key->objectid)
20075d4f98a2SYan Zheng 			break;
20085d4f98a2SYan Zheng 
20095d4f98a2SYan Zheng 		inode = find_next_inode(root, objectid);
20105d4f98a2SYan Zheng 		if (!inode)
20115d4f98a2SYan Zheng 			break;
20124a0cc7caSNikolay Borisov 		ino = btrfs_ino(BTRFS_I(inode));
20135d4f98a2SYan Zheng 
201433345d01SLi Zefan 		if (ino > max_key->objectid) {
20155d4f98a2SYan Zheng 			iput(inode);
20165d4f98a2SYan Zheng 			break;
20175d4f98a2SYan Zheng 		}
20185d4f98a2SYan Zheng 
201933345d01SLi Zefan 		objectid = ino + 1;
20205d4f98a2SYan Zheng 		if (!S_ISREG(inode->i_mode))
20215d4f98a2SYan Zheng 			continue;
20225d4f98a2SYan Zheng 
202333345d01SLi Zefan 		if (unlikely(min_key->objectid == ino)) {
20245d4f98a2SYan Zheng 			if (min_key->type > BTRFS_EXTENT_DATA_KEY)
20255d4f98a2SYan Zheng 				continue;
20265d4f98a2SYan Zheng 			if (min_key->type < BTRFS_EXTENT_DATA_KEY)
20275d4f98a2SYan Zheng 				start = 0;
20285d4f98a2SYan Zheng 			else {
20295d4f98a2SYan Zheng 				start = min_key->offset;
20300b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(start, fs_info->sectorsize));
20315d4f98a2SYan Zheng 			}
20325d4f98a2SYan Zheng 		} else {
20335d4f98a2SYan Zheng 			start = 0;
20345d4f98a2SYan Zheng 		}
20355d4f98a2SYan Zheng 
203633345d01SLi Zefan 		if (unlikely(max_key->objectid == ino)) {
20375d4f98a2SYan Zheng 			if (max_key->type < BTRFS_EXTENT_DATA_KEY)
20385d4f98a2SYan Zheng 				continue;
20395d4f98a2SYan Zheng 			if (max_key->type > BTRFS_EXTENT_DATA_KEY) {
20405d4f98a2SYan Zheng 				end = (u64)-1;
20415d4f98a2SYan Zheng 			} else {
20425d4f98a2SYan Zheng 				if (max_key->offset == 0)
20435d4f98a2SYan Zheng 					continue;
20445d4f98a2SYan Zheng 				end = max_key->offset;
20450b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
20465d4f98a2SYan Zheng 				end--;
20475d4f98a2SYan Zheng 			}
20485d4f98a2SYan Zheng 		} else {
20495d4f98a2SYan Zheng 			end = (u64)-1;
20505d4f98a2SYan Zheng 		}
20515d4f98a2SYan Zheng 
20525d4f98a2SYan Zheng 		/* the lock_extent waits for readpage to complete */
2053d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, start, end);
2054dcdbc059SNikolay Borisov 		btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 1);
2055d0082371SJeff Mahoney 		unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
20565d4f98a2SYan Zheng 	}
20575d4f98a2SYan Zheng 	return 0;
20585d4f98a2SYan Zheng }
20595d4f98a2SYan Zheng 
20605d4f98a2SYan Zheng static int find_next_key(struct btrfs_path *path, int level,
20615d4f98a2SYan Zheng 			 struct btrfs_key *key)
20625d4f98a2SYan Zheng 
20635d4f98a2SYan Zheng {
20645d4f98a2SYan Zheng 	while (level < BTRFS_MAX_LEVEL) {
20655d4f98a2SYan Zheng 		if (!path->nodes[level])
20665d4f98a2SYan Zheng 			break;
20675d4f98a2SYan Zheng 		if (path->slots[level] + 1 <
20685d4f98a2SYan Zheng 		    btrfs_header_nritems(path->nodes[level])) {
20695d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(path->nodes[level], key,
20705d4f98a2SYan Zheng 					      path->slots[level] + 1);
20715d4f98a2SYan Zheng 			return 0;
20725d4f98a2SYan Zheng 		}
20735d4f98a2SYan Zheng 		level++;
20745d4f98a2SYan Zheng 	}
20755d4f98a2SYan Zheng 	return 1;
20765d4f98a2SYan Zheng }
20775d4f98a2SYan Zheng 
20785d4f98a2SYan Zheng /*
2079d2311e69SQu Wenruo  * Insert current subvolume into reloc_control::dirty_subvol_roots
2080d2311e69SQu Wenruo  */
2081d2311e69SQu Wenruo static void insert_dirty_subvol(struct btrfs_trans_handle *trans,
2082d2311e69SQu Wenruo 				struct reloc_control *rc,
2083d2311e69SQu Wenruo 				struct btrfs_root *root)
2084d2311e69SQu Wenruo {
2085d2311e69SQu Wenruo 	struct btrfs_root *reloc_root = root->reloc_root;
2086d2311e69SQu Wenruo 	struct btrfs_root_item *reloc_root_item;
2087d2311e69SQu Wenruo 
2088d2311e69SQu Wenruo 	/* @root must be a subvolume tree root with a valid reloc tree */
2089d2311e69SQu Wenruo 	ASSERT(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
2090d2311e69SQu Wenruo 	ASSERT(reloc_root);
2091d2311e69SQu Wenruo 
2092d2311e69SQu Wenruo 	reloc_root_item = &reloc_root->root_item;
2093d2311e69SQu Wenruo 	memset(&reloc_root_item->drop_progress, 0,
2094d2311e69SQu Wenruo 		sizeof(reloc_root_item->drop_progress));
2095d2311e69SQu Wenruo 	reloc_root_item->drop_level = 0;
2096d2311e69SQu Wenruo 	btrfs_set_root_refs(reloc_root_item, 0);
2097d2311e69SQu Wenruo 	btrfs_update_reloc_root(trans, root);
2098d2311e69SQu Wenruo 
2099d2311e69SQu Wenruo 	if (list_empty(&root->reloc_dirty_list)) {
210000246528SJosef Bacik 		btrfs_grab_root(root);
2101d2311e69SQu Wenruo 		list_add_tail(&root->reloc_dirty_list, &rc->dirty_subvol_roots);
2102d2311e69SQu Wenruo 	}
2103d2311e69SQu Wenruo }
2104d2311e69SQu Wenruo 
2105d2311e69SQu Wenruo static int clean_dirty_subvols(struct reloc_control *rc)
2106d2311e69SQu Wenruo {
2107d2311e69SQu Wenruo 	struct btrfs_root *root;
2108d2311e69SQu Wenruo 	struct btrfs_root *next;
2109d2311e69SQu Wenruo 	int ret = 0;
211030d40577SQu Wenruo 	int ret2;
2111d2311e69SQu Wenruo 
2112d2311e69SQu Wenruo 	list_for_each_entry_safe(root, next, &rc->dirty_subvol_roots,
2113d2311e69SQu Wenruo 				 reloc_dirty_list) {
211430d40577SQu Wenruo 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
211530d40577SQu Wenruo 			/* Merged subvolume, cleanup its reloc root */
2116d2311e69SQu Wenruo 			struct btrfs_root *reloc_root = root->reloc_root;
2117d2311e69SQu Wenruo 
2118d2311e69SQu Wenruo 			list_del_init(&root->reloc_dirty_list);
2119d2311e69SQu Wenruo 			root->reloc_root = NULL;
21206282675eSQu Wenruo 			/*
21216282675eSQu Wenruo 			 * Need barrier to ensure clear_bit() only happens after
21226282675eSQu Wenruo 			 * root->reloc_root = NULL. Pairs with have_reloc_root.
21236282675eSQu Wenruo 			 */
21246282675eSQu Wenruo 			smp_wmb();
21251fac4a54SQu Wenruo 			clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
2126f28de8d8SJosef Bacik 			if (reloc_root) {
2127f44deb74SJosef Bacik 				/*
2128f44deb74SJosef Bacik 				 * btrfs_drop_snapshot drops our ref we hold for
2129f44deb74SJosef Bacik 				 * ->reloc_root.  If it fails however we must
2130f44deb74SJosef Bacik 				 * drop the ref ourselves.
2131f44deb74SJosef Bacik 				 */
2132f28de8d8SJosef Bacik 				ret2 = btrfs_drop_snapshot(reloc_root, 0, 1);
2133f44deb74SJosef Bacik 				if (ret2 < 0) {
2134f44deb74SJosef Bacik 					btrfs_put_root(reloc_root);
2135f44deb74SJosef Bacik 					if (!ret)
2136f28de8d8SJosef Bacik 						ret = ret2;
2137f28de8d8SJosef Bacik 				}
2138f44deb74SJosef Bacik 			}
213900246528SJosef Bacik 			btrfs_put_root(root);
214030d40577SQu Wenruo 		} else {
214130d40577SQu Wenruo 			/* Orphan reloc tree, just clean it up */
21420078a9f9SNikolay Borisov 			ret2 = btrfs_drop_snapshot(root, 0, 1);
2143f44deb74SJosef Bacik 			if (ret2 < 0) {
2144f44deb74SJosef Bacik 				btrfs_put_root(root);
2145f44deb74SJosef Bacik 				if (!ret)
214630d40577SQu Wenruo 					ret = ret2;
214730d40577SQu Wenruo 			}
2148d2311e69SQu Wenruo 		}
2149f44deb74SJosef Bacik 	}
2150d2311e69SQu Wenruo 	return ret;
2151d2311e69SQu Wenruo }
2152d2311e69SQu Wenruo 
2153d2311e69SQu Wenruo /*
21545d4f98a2SYan Zheng  * merge the relocated tree blocks in reloc tree with corresponding
21555d4f98a2SYan Zheng  * fs tree.
21565d4f98a2SYan Zheng  */
21575d4f98a2SYan Zheng static noinline_for_stack int merge_reloc_root(struct reloc_control *rc,
21585d4f98a2SYan Zheng 					       struct btrfs_root *root)
21595d4f98a2SYan Zheng {
21600b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
21615d4f98a2SYan Zheng 	struct btrfs_key key;
21625d4f98a2SYan Zheng 	struct btrfs_key next_key;
21639e6a0c52SJosef Bacik 	struct btrfs_trans_handle *trans = NULL;
21645d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
21655d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
21665d4f98a2SYan Zheng 	struct btrfs_path *path;
21673fd0a558SYan, Zheng 	struct extent_buffer *leaf;
21685d4f98a2SYan Zheng 	int level;
21695d4f98a2SYan Zheng 	int max_level;
21705d4f98a2SYan Zheng 	int replaced = 0;
21715d4f98a2SYan Zheng 	int ret;
21725d4f98a2SYan Zheng 	int err = 0;
21733fd0a558SYan, Zheng 	u32 min_reserved;
21745d4f98a2SYan Zheng 
21755d4f98a2SYan Zheng 	path = btrfs_alloc_path();
21765d4f98a2SYan Zheng 	if (!path)
21775d4f98a2SYan Zheng 		return -ENOMEM;
2178e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
21795d4f98a2SYan Zheng 
21805d4f98a2SYan Zheng 	reloc_root = root->reloc_root;
21815d4f98a2SYan Zheng 	root_item = &reloc_root->root_item;
21825d4f98a2SYan Zheng 
21835d4f98a2SYan Zheng 	if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
21845d4f98a2SYan Zheng 		level = btrfs_root_level(root_item);
218567439dadSDavid Sterba 		atomic_inc(&reloc_root->node->refs);
21865d4f98a2SYan Zheng 		path->nodes[level] = reloc_root->node;
21875d4f98a2SYan Zheng 		path->slots[level] = 0;
21885d4f98a2SYan Zheng 	} else {
21895d4f98a2SYan Zheng 		btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
21905d4f98a2SYan Zheng 
21915d4f98a2SYan Zheng 		level = root_item->drop_level;
21925d4f98a2SYan Zheng 		BUG_ON(level == 0);
21935d4f98a2SYan Zheng 		path->lowest_level = level;
21945d4f98a2SYan Zheng 		ret = btrfs_search_slot(NULL, reloc_root, &key, path, 0, 0);
219533c66f43SYan Zheng 		path->lowest_level = 0;
21965d4f98a2SYan Zheng 		if (ret < 0) {
21975d4f98a2SYan Zheng 			btrfs_free_path(path);
21985d4f98a2SYan Zheng 			return ret;
21995d4f98a2SYan Zheng 		}
22005d4f98a2SYan Zheng 
22015d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(path->nodes[level], &next_key,
22025d4f98a2SYan Zheng 				      path->slots[level]);
22035d4f98a2SYan Zheng 		WARN_ON(memcmp(&key, &next_key, sizeof(key)));
22045d4f98a2SYan Zheng 
22055d4f98a2SYan Zheng 		btrfs_unlock_up_safe(path, 0);
22065d4f98a2SYan Zheng 	}
22075d4f98a2SYan Zheng 
22080b246afaSJeff Mahoney 	min_reserved = fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
22095d4f98a2SYan Zheng 	memset(&next_key, 0, sizeof(next_key));
22105d4f98a2SYan Zheng 
22115d4f98a2SYan Zheng 	while (1) {
221208e007d2SMiao Xie 		ret = btrfs_block_rsv_refill(root, rc->block_rsv, min_reserved,
221308e007d2SMiao Xie 					     BTRFS_RESERVE_FLUSH_ALL);
22143fd0a558SYan, Zheng 		if (ret) {
22159e6a0c52SJosef Bacik 			err = ret;
22169e6a0c52SJosef Bacik 			goto out;
22173fd0a558SYan, Zheng 		}
22189e6a0c52SJosef Bacik 		trans = btrfs_start_transaction(root, 0);
22199e6a0c52SJosef Bacik 		if (IS_ERR(trans)) {
22209e6a0c52SJosef Bacik 			err = PTR_ERR(trans);
22219e6a0c52SJosef Bacik 			trans = NULL;
22229e6a0c52SJosef Bacik 			goto out;
22239e6a0c52SJosef Bacik 		}
22242abc726aSJosef Bacik 
22252abc726aSJosef Bacik 		/*
22262abc726aSJosef Bacik 		 * At this point we no longer have a reloc_control, so we can't
22272abc726aSJosef Bacik 		 * depend on btrfs_init_reloc_root to update our last_trans.
22282abc726aSJosef Bacik 		 *
22292abc726aSJosef Bacik 		 * But that's ok, we started the trans handle on our
22302abc726aSJosef Bacik 		 * corresponding fs_root, which means it's been added to the
22312abc726aSJosef Bacik 		 * dirty list.  At commit time we'll still call
22322abc726aSJosef Bacik 		 * btrfs_update_reloc_root() and update our root item
22332abc726aSJosef Bacik 		 * appropriately.
22342abc726aSJosef Bacik 		 */
22352abc726aSJosef Bacik 		reloc_root->last_trans = trans->transid;
22369e6a0c52SJosef Bacik 		trans->block_rsv = rc->block_rsv;
22373fd0a558SYan, Zheng 
22383fd0a558SYan, Zheng 		replaced = 0;
22395d4f98a2SYan Zheng 		max_level = level;
22405d4f98a2SYan Zheng 
22415d4f98a2SYan Zheng 		ret = walk_down_reloc_tree(reloc_root, path, &level);
22425d4f98a2SYan Zheng 		if (ret < 0) {
22435d4f98a2SYan Zheng 			err = ret;
22445d4f98a2SYan Zheng 			goto out;
22455d4f98a2SYan Zheng 		}
22465d4f98a2SYan Zheng 		if (ret > 0)
22475d4f98a2SYan Zheng 			break;
22485d4f98a2SYan Zheng 
22495d4f98a2SYan Zheng 		if (!find_next_key(path, level, &key) &&
22505d4f98a2SYan Zheng 		    btrfs_comp_cpu_keys(&next_key, &key) >= 0) {
22515d4f98a2SYan Zheng 			ret = 0;
22525d4f98a2SYan Zheng 		} else {
22533d0174f7SQu Wenruo 			ret = replace_path(trans, rc, root, reloc_root, path,
22543fd0a558SYan, Zheng 					   &next_key, level, max_level);
22555d4f98a2SYan Zheng 		}
22565d4f98a2SYan Zheng 		if (ret < 0) {
22575d4f98a2SYan Zheng 			err = ret;
22585d4f98a2SYan Zheng 			goto out;
22595d4f98a2SYan Zheng 		}
22605d4f98a2SYan Zheng 
22615d4f98a2SYan Zheng 		if (ret > 0) {
22625d4f98a2SYan Zheng 			level = ret;
22635d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(path->nodes[level], &key,
22645d4f98a2SYan Zheng 					      path->slots[level]);
22655d4f98a2SYan Zheng 			replaced = 1;
22665d4f98a2SYan Zheng 		}
22675d4f98a2SYan Zheng 
22685d4f98a2SYan Zheng 		ret = walk_up_reloc_tree(reloc_root, path, &level);
22695d4f98a2SYan Zheng 		if (ret > 0)
22705d4f98a2SYan Zheng 			break;
22715d4f98a2SYan Zheng 
22725d4f98a2SYan Zheng 		BUG_ON(level == 0);
22735d4f98a2SYan Zheng 		/*
22745d4f98a2SYan Zheng 		 * save the merging progress in the drop_progress.
22755d4f98a2SYan Zheng 		 * this is OK since root refs == 1 in this case.
22765d4f98a2SYan Zheng 		 */
22775d4f98a2SYan Zheng 		btrfs_node_key(path->nodes[level], &root_item->drop_progress,
22785d4f98a2SYan Zheng 			       path->slots[level]);
22795d4f98a2SYan Zheng 		root_item->drop_level = level;
22805d4f98a2SYan Zheng 
22813a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
22829e6a0c52SJosef Bacik 		trans = NULL;
22835d4f98a2SYan Zheng 
22842ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
22855d4f98a2SYan Zheng 
22865d4f98a2SYan Zheng 		if (replaced && rc->stage == UPDATE_DATA_PTRS)
22875d4f98a2SYan Zheng 			invalidate_extent_cache(root, &key, &next_key);
22885d4f98a2SYan Zheng 	}
22895d4f98a2SYan Zheng 
22905d4f98a2SYan Zheng 	/*
22915d4f98a2SYan Zheng 	 * handle the case only one block in the fs tree need to be
22925d4f98a2SYan Zheng 	 * relocated and the block is tree root.
22935d4f98a2SYan Zheng 	 */
22945d4f98a2SYan Zheng 	leaf = btrfs_lock_root_node(root);
22955d4f98a2SYan Zheng 	ret = btrfs_cow_block(trans, root, leaf, NULL, 0, &leaf);
22965d4f98a2SYan Zheng 	btrfs_tree_unlock(leaf);
22975d4f98a2SYan Zheng 	free_extent_buffer(leaf);
22985d4f98a2SYan Zheng 	if (ret < 0)
22995d4f98a2SYan Zheng 		err = ret;
23005d4f98a2SYan Zheng out:
23015d4f98a2SYan Zheng 	btrfs_free_path(path);
23025d4f98a2SYan Zheng 
2303d2311e69SQu Wenruo 	if (err == 0)
2304d2311e69SQu Wenruo 		insert_dirty_subvol(trans, rc, root);
23055d4f98a2SYan Zheng 
23069e6a0c52SJosef Bacik 	if (trans)
23073a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
23085d4f98a2SYan Zheng 
23092ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
23105d4f98a2SYan Zheng 
23115d4f98a2SYan Zheng 	if (replaced && rc->stage == UPDATE_DATA_PTRS)
23125d4f98a2SYan Zheng 		invalidate_extent_cache(root, &key, &next_key);
23135d4f98a2SYan Zheng 
23145d4f98a2SYan Zheng 	return err;
23155d4f98a2SYan Zheng }
23165d4f98a2SYan Zheng 
23173fd0a558SYan, Zheng static noinline_for_stack
23183fd0a558SYan, Zheng int prepare_to_merge(struct reloc_control *rc, int err)
23195d4f98a2SYan Zheng {
23203fd0a558SYan, Zheng 	struct btrfs_root *root = rc->extent_root;
23210b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
23223fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
23235d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
23243fd0a558SYan, Zheng 	LIST_HEAD(reloc_roots);
23253fd0a558SYan, Zheng 	u64 num_bytes = 0;
23263fd0a558SYan, Zheng 	int ret;
23273fd0a558SYan, Zheng 
23280b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
23290b246afaSJeff Mahoney 	rc->merging_rsv_size += fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
23303fd0a558SYan, Zheng 	rc->merging_rsv_size += rc->nodes_relocated * 2;
23310b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
23327585717fSChris Mason 
23333fd0a558SYan, Zheng again:
23343fd0a558SYan, Zheng 	if (!err) {
23353fd0a558SYan, Zheng 		num_bytes = rc->merging_rsv_size;
233608e007d2SMiao Xie 		ret = btrfs_block_rsv_add(root, rc->block_rsv, num_bytes,
233708e007d2SMiao Xie 					  BTRFS_RESERVE_FLUSH_ALL);
23383fd0a558SYan, Zheng 		if (ret)
23393fd0a558SYan, Zheng 			err = ret;
23403fd0a558SYan, Zheng 	}
23413fd0a558SYan, Zheng 
23427a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
23433612b495STsutomu Itoh 	if (IS_ERR(trans)) {
23443612b495STsutomu Itoh 		if (!err)
23452ff7e61eSJeff Mahoney 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
234663f018beSNikolay Borisov 						num_bytes, NULL);
23473612b495STsutomu Itoh 		return PTR_ERR(trans);
23483612b495STsutomu Itoh 	}
23493fd0a558SYan, Zheng 
23503fd0a558SYan, Zheng 	if (!err) {
23513fd0a558SYan, Zheng 		if (num_bytes != rc->merging_rsv_size) {
23523a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
23532ff7e61eSJeff Mahoney 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
235463f018beSNikolay Borisov 						num_bytes, NULL);
23553fd0a558SYan, Zheng 			goto again;
23563fd0a558SYan, Zheng 		}
23573fd0a558SYan, Zheng 	}
23583fd0a558SYan, Zheng 
23593fd0a558SYan, Zheng 	rc->merge_reloc_tree = 1;
23603fd0a558SYan, Zheng 
23613fd0a558SYan, Zheng 	while (!list_empty(&rc->reloc_roots)) {
23623fd0a558SYan, Zheng 		reloc_root = list_entry(rc->reloc_roots.next,
23633fd0a558SYan, Zheng 					struct btrfs_root, root_list);
23643fd0a558SYan, Zheng 		list_del_init(&reloc_root->root_list);
23653fd0a558SYan, Zheng 
23660b246afaSJeff Mahoney 		root = read_fs_root(fs_info, reloc_root->root_key.offset);
23673fd0a558SYan, Zheng 		BUG_ON(IS_ERR(root));
23683fd0a558SYan, Zheng 		BUG_ON(root->reloc_root != reloc_root);
23693fd0a558SYan, Zheng 
23703fd0a558SYan, Zheng 		/*
23713fd0a558SYan, Zheng 		 * set reference count to 1, so btrfs_recover_relocation
23723fd0a558SYan, Zheng 		 * knows it should resumes merging
23733fd0a558SYan, Zheng 		 */
23743fd0a558SYan, Zheng 		if (!err)
23753fd0a558SYan, Zheng 			btrfs_set_root_refs(&reloc_root->root_item, 1);
23763fd0a558SYan, Zheng 		btrfs_update_reloc_root(trans, root);
23773fd0a558SYan, Zheng 
23783fd0a558SYan, Zheng 		list_add(&reloc_root->root_list, &reloc_roots);
237900246528SJosef Bacik 		btrfs_put_root(root);
23803fd0a558SYan, Zheng 	}
23813fd0a558SYan, Zheng 
23823fd0a558SYan, Zheng 	list_splice(&reloc_roots, &rc->reloc_roots);
23833fd0a558SYan, Zheng 
23843fd0a558SYan, Zheng 	if (!err)
23853a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
23863fd0a558SYan, Zheng 	else
23873a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
23883fd0a558SYan, Zheng 	return err;
23893fd0a558SYan, Zheng }
23903fd0a558SYan, Zheng 
23913fd0a558SYan, Zheng static noinline_for_stack
2392aca1bba6SLiu Bo void free_reloc_roots(struct list_head *list)
2393aca1bba6SLiu Bo {
2394aca1bba6SLiu Bo 	struct btrfs_root *reloc_root;
2395aca1bba6SLiu Bo 
2396aca1bba6SLiu Bo 	while (!list_empty(list)) {
2397aca1bba6SLiu Bo 		reloc_root = list_entry(list->next, struct btrfs_root,
2398aca1bba6SLiu Bo 					root_list);
2399bb166d72SNaohiro Aota 		__del_reloc_root(reloc_root);
2400aca1bba6SLiu Bo 	}
2401aca1bba6SLiu Bo }
2402aca1bba6SLiu Bo 
2403aca1bba6SLiu Bo static noinline_for_stack
240494404e82SDavid Sterba void merge_reloc_roots(struct reloc_control *rc)
24053fd0a558SYan, Zheng {
24060b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
24075d4f98a2SYan Zheng 	struct btrfs_root *root;
24085d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
24093fd0a558SYan, Zheng 	LIST_HEAD(reloc_roots);
24103fd0a558SYan, Zheng 	int found = 0;
2411aca1bba6SLiu Bo 	int ret = 0;
24123fd0a558SYan, Zheng again:
24133fd0a558SYan, Zheng 	root = rc->extent_root;
24147585717fSChris Mason 
24157585717fSChris Mason 	/*
24167585717fSChris Mason 	 * this serializes us with btrfs_record_root_in_transaction,
24177585717fSChris Mason 	 * we have to make sure nobody is in the middle of
24187585717fSChris Mason 	 * adding their roots to the list while we are
24197585717fSChris Mason 	 * doing this splice
24207585717fSChris Mason 	 */
24210b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
24223fd0a558SYan, Zheng 	list_splice_init(&rc->reloc_roots, &reloc_roots);
24230b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
24245d4f98a2SYan Zheng 
24253fd0a558SYan, Zheng 	while (!list_empty(&reloc_roots)) {
24263fd0a558SYan, Zheng 		found = 1;
24273fd0a558SYan, Zheng 		reloc_root = list_entry(reloc_roots.next,
24283fd0a558SYan, Zheng 					struct btrfs_root, root_list);
24295d4f98a2SYan Zheng 
24305d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
24310b246afaSJeff Mahoney 			root = read_fs_root(fs_info,
24325d4f98a2SYan Zheng 					    reloc_root->root_key.offset);
24335d4f98a2SYan Zheng 			BUG_ON(IS_ERR(root));
24345d4f98a2SYan Zheng 			BUG_ON(root->reloc_root != reloc_root);
24355d4f98a2SYan Zheng 
24363fd0a558SYan, Zheng 			ret = merge_reloc_root(rc, root);
243700246528SJosef Bacik 			btrfs_put_root(root);
2438b37b39cdSJosef Bacik 			if (ret) {
243925e293c2SWang Shilong 				if (list_empty(&reloc_root->root_list))
244025e293c2SWang Shilong 					list_add_tail(&reloc_root->root_list,
244125e293c2SWang Shilong 						      &reloc_roots);
2442aca1bba6SLiu Bo 				goto out;
2443b37b39cdSJosef Bacik 			}
24443fd0a558SYan, Zheng 		} else {
24453fd0a558SYan, Zheng 			list_del_init(&reloc_root->root_list);
244630d40577SQu Wenruo 			/* Don't forget to queue this reloc root for cleanup */
244730d40577SQu Wenruo 			list_add_tail(&reloc_root->reloc_dirty_list,
244830d40577SQu Wenruo 				      &rc->dirty_subvol_roots);
24493fd0a558SYan, Zheng 		}
24505d4f98a2SYan Zheng 	}
24515d4f98a2SYan Zheng 
24523fd0a558SYan, Zheng 	if (found) {
24533fd0a558SYan, Zheng 		found = 0;
24543fd0a558SYan, Zheng 		goto again;
24555d4f98a2SYan Zheng 	}
2456aca1bba6SLiu Bo out:
2457aca1bba6SLiu Bo 	if (ret) {
24580b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret, NULL);
2459aca1bba6SLiu Bo 		if (!list_empty(&reloc_roots))
2460aca1bba6SLiu Bo 			free_reloc_roots(&reloc_roots);
2461467bb1d2SWang Shilong 
2462467bb1d2SWang Shilong 		/* new reloc root may be added */
24630b246afaSJeff Mahoney 		mutex_lock(&fs_info->reloc_mutex);
2464467bb1d2SWang Shilong 		list_splice_init(&rc->reloc_roots, &reloc_roots);
24650b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
2466467bb1d2SWang Shilong 		if (!list_empty(&reloc_roots))
2467467bb1d2SWang Shilong 			free_reloc_roots(&reloc_roots);
2468aca1bba6SLiu Bo 	}
2469aca1bba6SLiu Bo 
24707b7b7431SJosef Bacik 	/*
24717b7b7431SJosef Bacik 	 * We used to have
24727b7b7431SJosef Bacik 	 *
24737b7b7431SJosef Bacik 	 * BUG_ON(!RB_EMPTY_ROOT(&rc->reloc_root_tree.rb_root));
24747b7b7431SJosef Bacik 	 *
24757b7b7431SJosef Bacik 	 * here, but it's wrong.  If we fail to start the transaction in
24767b7b7431SJosef Bacik 	 * prepare_to_merge() we will have only 0 ref reloc roots, none of which
24777b7b7431SJosef Bacik 	 * have actually been removed from the reloc_root_tree rb tree.  This is
24787b7b7431SJosef Bacik 	 * fine because we're bailing here, and we hold a reference on the root
24797b7b7431SJosef Bacik 	 * for the list that holds it, so these roots will be cleaned up when we
24807b7b7431SJosef Bacik 	 * do the reloc_dirty_list afterwards.  Meanwhile the root->reloc_root
24817b7b7431SJosef Bacik 	 * will be cleaned up on unmount.
24827b7b7431SJosef Bacik 	 *
24837b7b7431SJosef Bacik 	 * The remaining nodes will be cleaned up by free_reloc_control.
24847b7b7431SJosef Bacik 	 */
24855d4f98a2SYan Zheng }
24865d4f98a2SYan Zheng 
24875d4f98a2SYan Zheng static void free_block_list(struct rb_root *blocks)
24885d4f98a2SYan Zheng {
24895d4f98a2SYan Zheng 	struct tree_block *block;
24905d4f98a2SYan Zheng 	struct rb_node *rb_node;
24915d4f98a2SYan Zheng 	while ((rb_node = rb_first(blocks))) {
24925d4f98a2SYan Zheng 		block = rb_entry(rb_node, struct tree_block, rb_node);
24935d4f98a2SYan Zheng 		rb_erase(rb_node, blocks);
24945d4f98a2SYan Zheng 		kfree(block);
24955d4f98a2SYan Zheng 	}
24965d4f98a2SYan Zheng }
24975d4f98a2SYan Zheng 
24985d4f98a2SYan Zheng static int record_reloc_root_in_trans(struct btrfs_trans_handle *trans,
24995d4f98a2SYan Zheng 				      struct btrfs_root *reloc_root)
25005d4f98a2SYan Zheng {
25010b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = reloc_root->fs_info;
25025d4f98a2SYan Zheng 	struct btrfs_root *root;
2503442b1ac5SJosef Bacik 	int ret;
25045d4f98a2SYan Zheng 
25055d4f98a2SYan Zheng 	if (reloc_root->last_trans == trans->transid)
25065d4f98a2SYan Zheng 		return 0;
25075d4f98a2SYan Zheng 
25080b246afaSJeff Mahoney 	root = read_fs_root(fs_info, reloc_root->root_key.offset);
25095d4f98a2SYan Zheng 	BUG_ON(IS_ERR(root));
25105d4f98a2SYan Zheng 	BUG_ON(root->reloc_root != reloc_root);
2511442b1ac5SJosef Bacik 	ret = btrfs_record_root_in_trans(trans, root);
251200246528SJosef Bacik 	btrfs_put_root(root);
25135d4f98a2SYan Zheng 
2514442b1ac5SJosef Bacik 	return ret;
25155d4f98a2SYan Zheng }
25165d4f98a2SYan Zheng 
25173fd0a558SYan, Zheng static noinline_for_stack
25183fd0a558SYan, Zheng struct btrfs_root *select_reloc_root(struct btrfs_trans_handle *trans,
25193fd0a558SYan, Zheng 				     struct reloc_control *rc,
2520a26195a5SQu Wenruo 				     struct btrfs_backref_node *node,
2521a26195a5SQu Wenruo 				     struct btrfs_backref_edge *edges[])
25225d4f98a2SYan Zheng {
2523a26195a5SQu Wenruo 	struct btrfs_backref_node *next;
25245d4f98a2SYan Zheng 	struct btrfs_root *root;
25253fd0a558SYan, Zheng 	int index = 0;
25263fd0a558SYan, Zheng 
25275d4f98a2SYan Zheng 	next = node;
25285d4f98a2SYan Zheng 	while (1) {
25295d4f98a2SYan Zheng 		cond_resched();
25305d4f98a2SYan Zheng 		next = walk_up_backref(next, edges, &index);
25315d4f98a2SYan Zheng 		root = next->root;
25323fd0a558SYan, Zheng 		BUG_ON(!root);
253327cdeb70SMiao Xie 		BUG_ON(!test_bit(BTRFS_ROOT_REF_COWS, &root->state));
25345d4f98a2SYan Zheng 
25355d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
25365d4f98a2SYan Zheng 			record_reloc_root_in_trans(trans, root);
25375d4f98a2SYan Zheng 			break;
25385d4f98a2SYan Zheng 		}
25395d4f98a2SYan Zheng 
25405d4f98a2SYan Zheng 		btrfs_record_root_in_trans(trans, root);
25413fd0a558SYan, Zheng 		root = root->reloc_root;
25423fd0a558SYan, Zheng 
25433fd0a558SYan, Zheng 		if (next->new_bytenr != root->node->start) {
25443fd0a558SYan, Zheng 			BUG_ON(next->new_bytenr);
25453fd0a558SYan, Zheng 			BUG_ON(!list_empty(&next->list));
25463fd0a558SYan, Zheng 			next->new_bytenr = root->node->start;
254700246528SJosef Bacik 			btrfs_put_root(next->root);
254800246528SJosef Bacik 			next->root = btrfs_grab_root(root);
25490b530bc5SJosef Bacik 			ASSERT(next->root);
25503fd0a558SYan, Zheng 			list_add_tail(&next->list,
25513fd0a558SYan, Zheng 				      &rc->backref_cache.changed);
25529569cc20SQu Wenruo 			mark_block_processed(rc, next);
25535d4f98a2SYan Zheng 			break;
25545d4f98a2SYan Zheng 		}
25555d4f98a2SYan Zheng 
25563fd0a558SYan, Zheng 		WARN_ON(1);
25575d4f98a2SYan Zheng 		root = NULL;
25585d4f98a2SYan Zheng 		next = walk_down_backref(edges, &index);
25595d4f98a2SYan Zheng 		if (!next || next->level <= node->level)
25605d4f98a2SYan Zheng 			break;
25615d4f98a2SYan Zheng 	}
25623fd0a558SYan, Zheng 	if (!root)
25633fd0a558SYan, Zheng 		return NULL;
25645d4f98a2SYan Zheng 
25653fd0a558SYan, Zheng 	next = node;
25663fd0a558SYan, Zheng 	/* setup backref node path for btrfs_reloc_cow_block */
25673fd0a558SYan, Zheng 	while (1) {
25683fd0a558SYan, Zheng 		rc->backref_cache.path[next->level] = next;
25693fd0a558SYan, Zheng 		if (--index < 0)
25703fd0a558SYan, Zheng 			break;
25713fd0a558SYan, Zheng 		next = edges[index]->node[UPPER];
25723fd0a558SYan, Zheng 	}
25735d4f98a2SYan Zheng 	return root;
25745d4f98a2SYan Zheng }
25755d4f98a2SYan Zheng 
25763fd0a558SYan, Zheng /*
25773fd0a558SYan, Zheng  * select a tree root for relocation. return NULL if the block
25783fd0a558SYan, Zheng  * is reference counted. we should use do_relocation() in this
25793fd0a558SYan, Zheng  * case. return a tree root pointer if the block isn't reference
25803fd0a558SYan, Zheng  * counted. return -ENOENT if the block is root of reloc tree.
25813fd0a558SYan, Zheng  */
25825d4f98a2SYan Zheng static noinline_for_stack
2583a26195a5SQu Wenruo struct btrfs_root *select_one_root(struct btrfs_backref_node *node)
25845d4f98a2SYan Zheng {
2585a26195a5SQu Wenruo 	struct btrfs_backref_node *next;
25863fd0a558SYan, Zheng 	struct btrfs_root *root;
25873fd0a558SYan, Zheng 	struct btrfs_root *fs_root = NULL;
2588a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
25893fd0a558SYan, Zheng 	int index = 0;
25903fd0a558SYan, Zheng 
25913fd0a558SYan, Zheng 	next = node;
25923fd0a558SYan, Zheng 	while (1) {
25933fd0a558SYan, Zheng 		cond_resched();
25943fd0a558SYan, Zheng 		next = walk_up_backref(next, edges, &index);
25953fd0a558SYan, Zheng 		root = next->root;
25963fd0a558SYan, Zheng 		BUG_ON(!root);
25973fd0a558SYan, Zheng 
259825985edcSLucas De Marchi 		/* no other choice for non-references counted tree */
259927cdeb70SMiao Xie 		if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
26003fd0a558SYan, Zheng 			return root;
26013fd0a558SYan, Zheng 
26023fd0a558SYan, Zheng 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID)
26033fd0a558SYan, Zheng 			fs_root = root;
26043fd0a558SYan, Zheng 
26053fd0a558SYan, Zheng 		if (next != node)
26063fd0a558SYan, Zheng 			return NULL;
26073fd0a558SYan, Zheng 
26083fd0a558SYan, Zheng 		next = walk_down_backref(edges, &index);
26093fd0a558SYan, Zheng 		if (!next || next->level <= node->level)
26103fd0a558SYan, Zheng 			break;
26113fd0a558SYan, Zheng 	}
26123fd0a558SYan, Zheng 
26133fd0a558SYan, Zheng 	if (!fs_root)
26143fd0a558SYan, Zheng 		return ERR_PTR(-ENOENT);
26153fd0a558SYan, Zheng 	return fs_root;
26165d4f98a2SYan Zheng }
26175d4f98a2SYan Zheng 
26185d4f98a2SYan Zheng static noinline_for_stack
26193fd0a558SYan, Zheng u64 calcu_metadata_size(struct reloc_control *rc,
2620a26195a5SQu Wenruo 			struct btrfs_backref_node *node, int reserve)
26215d4f98a2SYan Zheng {
26220b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2623a26195a5SQu Wenruo 	struct btrfs_backref_node *next = node;
2624a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2625a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
26263fd0a558SYan, Zheng 	u64 num_bytes = 0;
26273fd0a558SYan, Zheng 	int index = 0;
26285d4f98a2SYan Zheng 
26293fd0a558SYan, Zheng 	BUG_ON(reserve && node->processed);
26303fd0a558SYan, Zheng 
26313fd0a558SYan, Zheng 	while (next) {
26323fd0a558SYan, Zheng 		cond_resched();
26335d4f98a2SYan Zheng 		while (1) {
26343fd0a558SYan, Zheng 			if (next->processed && (reserve || next != node))
26355d4f98a2SYan Zheng 				break;
26365d4f98a2SYan Zheng 
26370b246afaSJeff Mahoney 			num_bytes += fs_info->nodesize;
26383fd0a558SYan, Zheng 
26393fd0a558SYan, Zheng 			if (list_empty(&next->upper))
26403fd0a558SYan, Zheng 				break;
26413fd0a558SYan, Zheng 
26423fd0a558SYan, Zheng 			edge = list_entry(next->upper.next,
2643a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[LOWER]);
26443fd0a558SYan, Zheng 			edges[index++] = edge;
26453fd0a558SYan, Zheng 			next = edge->node[UPPER];
26465d4f98a2SYan Zheng 		}
26473fd0a558SYan, Zheng 		next = walk_down_backref(edges, &index);
26483fd0a558SYan, Zheng 	}
26493fd0a558SYan, Zheng 	return num_bytes;
26503fd0a558SYan, Zheng }
26513fd0a558SYan, Zheng 
26523fd0a558SYan, Zheng static int reserve_metadata_space(struct btrfs_trans_handle *trans,
26533fd0a558SYan, Zheng 				  struct reloc_control *rc,
2654a26195a5SQu Wenruo 				  struct btrfs_backref_node *node)
26553fd0a558SYan, Zheng {
26563fd0a558SYan, Zheng 	struct btrfs_root *root = rc->extent_root;
2657da17066cSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
26583fd0a558SYan, Zheng 	u64 num_bytes;
26593fd0a558SYan, Zheng 	int ret;
26600647bf56SWang Shilong 	u64 tmp;
26613fd0a558SYan, Zheng 
26623fd0a558SYan, Zheng 	num_bytes = calcu_metadata_size(rc, node, 1) * 2;
26633fd0a558SYan, Zheng 
26643fd0a558SYan, Zheng 	trans->block_rsv = rc->block_rsv;
26650647bf56SWang Shilong 	rc->reserved_bytes += num_bytes;
26668ca17f0fSJosef Bacik 
26678ca17f0fSJosef Bacik 	/*
26688ca17f0fSJosef Bacik 	 * We are under a transaction here so we can only do limited flushing.
26698ca17f0fSJosef Bacik 	 * If we get an enospc just kick back -EAGAIN so we know to drop the
26708ca17f0fSJosef Bacik 	 * transaction and try to refill when we can flush all the things.
26718ca17f0fSJosef Bacik 	 */
26720647bf56SWang Shilong 	ret = btrfs_block_rsv_refill(root, rc->block_rsv, num_bytes,
26738ca17f0fSJosef Bacik 				BTRFS_RESERVE_FLUSH_LIMIT);
26743fd0a558SYan, Zheng 	if (ret) {
2675da17066cSJeff Mahoney 		tmp = fs_info->nodesize * RELOCATION_RESERVED_NODES;
26760647bf56SWang Shilong 		while (tmp <= rc->reserved_bytes)
26770647bf56SWang Shilong 			tmp <<= 1;
26780647bf56SWang Shilong 		/*
26790647bf56SWang Shilong 		 * only one thread can access block_rsv at this point,
26800647bf56SWang Shilong 		 * so we don't need hold lock to protect block_rsv.
26810647bf56SWang Shilong 		 * we expand more reservation size here to allow enough
268252042d8eSAndrea Gelmini 		 * space for relocation and we will return earlier in
26830647bf56SWang Shilong 		 * enospc case.
26840647bf56SWang Shilong 		 */
2685da17066cSJeff Mahoney 		rc->block_rsv->size = tmp + fs_info->nodesize *
26860647bf56SWang Shilong 				      RELOCATION_RESERVED_NODES;
26878ca17f0fSJosef Bacik 		return -EAGAIN;
26883fd0a558SYan, Zheng 	}
26893fd0a558SYan, Zheng 
26903fd0a558SYan, Zheng 	return 0;
26913fd0a558SYan, Zheng }
26923fd0a558SYan, Zheng 
26935d4f98a2SYan Zheng /*
26945d4f98a2SYan Zheng  * relocate a block tree, and then update pointers in upper level
26955d4f98a2SYan Zheng  * blocks that reference the block to point to the new location.
26965d4f98a2SYan Zheng  *
26975d4f98a2SYan Zheng  * if called by link_to_upper, the block has already been relocated.
26985d4f98a2SYan Zheng  * in that case this function just updates pointers.
26995d4f98a2SYan Zheng  */
27005d4f98a2SYan Zheng static int do_relocation(struct btrfs_trans_handle *trans,
27013fd0a558SYan, Zheng 			 struct reloc_control *rc,
2702a26195a5SQu Wenruo 			 struct btrfs_backref_node *node,
27035d4f98a2SYan Zheng 			 struct btrfs_key *key,
27045d4f98a2SYan Zheng 			 struct btrfs_path *path, int lowest)
27055d4f98a2SYan Zheng {
27062ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2707a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
2708a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2709a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
27105d4f98a2SYan Zheng 	struct btrfs_root *root;
27115d4f98a2SYan Zheng 	struct extent_buffer *eb;
27125d4f98a2SYan Zheng 	u32 blocksize;
27135d4f98a2SYan Zheng 	u64 bytenr;
27145d4f98a2SYan Zheng 	u64 generation;
27155d4f98a2SYan Zheng 	int slot;
27165d4f98a2SYan Zheng 	int ret;
27175d4f98a2SYan Zheng 	int err = 0;
27185d4f98a2SYan Zheng 
27195d4f98a2SYan Zheng 	BUG_ON(lowest && node->eb);
27205d4f98a2SYan Zheng 
27215d4f98a2SYan Zheng 	path->lowest_level = node->level + 1;
27223fd0a558SYan, Zheng 	rc->backref_cache.path[node->level] = node;
27235d4f98a2SYan Zheng 	list_for_each_entry(edge, &node->upper, list[LOWER]) {
2724581c1760SQu Wenruo 		struct btrfs_key first_key;
272582fa113fSQu Wenruo 		struct btrfs_ref ref = { 0 };
2726581c1760SQu Wenruo 
27275d4f98a2SYan Zheng 		cond_resched();
27285d4f98a2SYan Zheng 
27295d4f98a2SYan Zheng 		upper = edge->node[UPPER];
2730dc4103f9SWang Shilong 		root = select_reloc_root(trans, rc, upper, edges);
27313fd0a558SYan, Zheng 		BUG_ON(!root);
27325d4f98a2SYan Zheng 
27333fd0a558SYan, Zheng 		if (upper->eb && !upper->locked) {
27343fd0a558SYan, Zheng 			if (!lowest) {
27353fd0a558SYan, Zheng 				ret = btrfs_bin_search(upper->eb, key,
27363fd0a558SYan, Zheng 						       upper->level, &slot);
2737cbca7d59SFilipe Manana 				if (ret < 0) {
2738cbca7d59SFilipe Manana 					err = ret;
2739cbca7d59SFilipe Manana 					goto next;
2740cbca7d59SFilipe Manana 				}
27413fd0a558SYan, Zheng 				BUG_ON(ret);
27423fd0a558SYan, Zheng 				bytenr = btrfs_node_blockptr(upper->eb, slot);
27433fd0a558SYan, Zheng 				if (node->eb->start == bytenr)
27443fd0a558SYan, Zheng 					goto next;
27453fd0a558SYan, Zheng 			}
2746b0fe7078SQu Wenruo 			btrfs_backref_drop_node_buffer(upper);
27473fd0a558SYan, Zheng 		}
27485d4f98a2SYan Zheng 
27495d4f98a2SYan Zheng 		if (!upper->eb) {
27505d4f98a2SYan Zheng 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
27513561b9dbSLiu Bo 			if (ret) {
27523561b9dbSLiu Bo 				if (ret < 0)
27535d4f98a2SYan Zheng 					err = ret;
27543561b9dbSLiu Bo 				else
27553561b9dbSLiu Bo 					err = -ENOENT;
27563561b9dbSLiu Bo 
27573561b9dbSLiu Bo 				btrfs_release_path(path);
27585d4f98a2SYan Zheng 				break;
27595d4f98a2SYan Zheng 			}
27605d4f98a2SYan Zheng 
27613fd0a558SYan, Zheng 			if (!upper->eb) {
27623fd0a558SYan, Zheng 				upper->eb = path->nodes[upper->level];
27633fd0a558SYan, Zheng 				path->nodes[upper->level] = NULL;
27643fd0a558SYan, Zheng 			} else {
27653fd0a558SYan, Zheng 				BUG_ON(upper->eb != path->nodes[upper->level]);
27663fd0a558SYan, Zheng 			}
27673fd0a558SYan, Zheng 
27683fd0a558SYan, Zheng 			upper->locked = 1;
27693fd0a558SYan, Zheng 			path->locks[upper->level] = 0;
27703fd0a558SYan, Zheng 
27715d4f98a2SYan Zheng 			slot = path->slots[upper->level];
2772b3b4aa74SDavid Sterba 			btrfs_release_path(path);
27735d4f98a2SYan Zheng 		} else {
27745d4f98a2SYan Zheng 			ret = btrfs_bin_search(upper->eb, key, upper->level,
27755d4f98a2SYan Zheng 					       &slot);
2776cbca7d59SFilipe Manana 			if (ret < 0) {
2777cbca7d59SFilipe Manana 				err = ret;
2778cbca7d59SFilipe Manana 				goto next;
2779cbca7d59SFilipe Manana 			}
27805d4f98a2SYan Zheng 			BUG_ON(ret);
27815d4f98a2SYan Zheng 		}
27825d4f98a2SYan Zheng 
27835d4f98a2SYan Zheng 		bytenr = btrfs_node_blockptr(upper->eb, slot);
27843fd0a558SYan, Zheng 		if (lowest) {
27854547f4d8SLiu Bo 			if (bytenr != node->bytenr) {
27864547f4d8SLiu Bo 				btrfs_err(root->fs_info,
27874547f4d8SLiu Bo 		"lowest leaf/node mismatch: bytenr %llu node->bytenr %llu slot %d upper %llu",
27884547f4d8SLiu Bo 					  bytenr, node->bytenr, slot,
27894547f4d8SLiu Bo 					  upper->eb->start);
27904547f4d8SLiu Bo 				err = -EIO;
27914547f4d8SLiu Bo 				goto next;
27924547f4d8SLiu Bo 			}
27935d4f98a2SYan Zheng 		} else {
27943fd0a558SYan, Zheng 			if (node->eb->start == bytenr)
27953fd0a558SYan, Zheng 				goto next;
27965d4f98a2SYan Zheng 		}
27975d4f98a2SYan Zheng 
2798da17066cSJeff Mahoney 		blocksize = root->fs_info->nodesize;
27995d4f98a2SYan Zheng 		generation = btrfs_node_ptr_generation(upper->eb, slot);
2800581c1760SQu Wenruo 		btrfs_node_key_to_cpu(upper->eb, &first_key, slot);
2801581c1760SQu Wenruo 		eb = read_tree_block(fs_info, bytenr, generation,
2802581c1760SQu Wenruo 				     upper->level - 1, &first_key);
280364c043deSLiu Bo 		if (IS_ERR(eb)) {
280464c043deSLiu Bo 			err = PTR_ERR(eb);
280564c043deSLiu Bo 			goto next;
280664c043deSLiu Bo 		} else if (!extent_buffer_uptodate(eb)) {
2807416bc658SJosef Bacik 			free_extent_buffer(eb);
280897d9a8a4STsutomu Itoh 			err = -EIO;
280997d9a8a4STsutomu Itoh 			goto next;
281097d9a8a4STsutomu Itoh 		}
28115d4f98a2SYan Zheng 		btrfs_tree_lock(eb);
28128bead258SDavid Sterba 		btrfs_set_lock_blocking_write(eb);
28135d4f98a2SYan Zheng 
28145d4f98a2SYan Zheng 		if (!node->eb) {
28155d4f98a2SYan Zheng 			ret = btrfs_cow_block(trans, root, eb, upper->eb,
28165d4f98a2SYan Zheng 					      slot, &eb);
28173fd0a558SYan, Zheng 			btrfs_tree_unlock(eb);
28183fd0a558SYan, Zheng 			free_extent_buffer(eb);
28195d4f98a2SYan Zheng 			if (ret < 0) {
28205d4f98a2SYan Zheng 				err = ret;
28213fd0a558SYan, Zheng 				goto next;
28225d4f98a2SYan Zheng 			}
28233fd0a558SYan, Zheng 			BUG_ON(node->eb != eb);
28245d4f98a2SYan Zheng 		} else {
28255d4f98a2SYan Zheng 			btrfs_set_node_blockptr(upper->eb, slot,
28265d4f98a2SYan Zheng 						node->eb->start);
28275d4f98a2SYan Zheng 			btrfs_set_node_ptr_generation(upper->eb, slot,
28285d4f98a2SYan Zheng 						      trans->transid);
28295d4f98a2SYan Zheng 			btrfs_mark_buffer_dirty(upper->eb);
28305d4f98a2SYan Zheng 
283182fa113fSQu Wenruo 			btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF,
28325d4f98a2SYan Zheng 					       node->eb->start, blocksize,
283382fa113fSQu Wenruo 					       upper->eb->start);
283482fa113fSQu Wenruo 			ref.real_root = root->root_key.objectid;
283582fa113fSQu Wenruo 			btrfs_init_tree_ref(&ref, node->level,
283682fa113fSQu Wenruo 					    btrfs_header_owner(upper->eb));
283782fa113fSQu Wenruo 			ret = btrfs_inc_extent_ref(trans, &ref);
28385d4f98a2SYan Zheng 			BUG_ON(ret);
28395d4f98a2SYan Zheng 
28405d4f98a2SYan Zheng 			ret = btrfs_drop_subtree(trans, root, eb, upper->eb);
28415d4f98a2SYan Zheng 			BUG_ON(ret);
28425d4f98a2SYan Zheng 		}
28433fd0a558SYan, Zheng next:
28443fd0a558SYan, Zheng 		if (!upper->pending)
2845b0fe7078SQu Wenruo 			btrfs_backref_drop_node_buffer(upper);
28463fd0a558SYan, Zheng 		else
2847b0fe7078SQu Wenruo 			btrfs_backref_unlock_node_buffer(upper);
28483fd0a558SYan, Zheng 		if (err)
28493fd0a558SYan, Zheng 			break;
28505d4f98a2SYan Zheng 	}
28513fd0a558SYan, Zheng 
28523fd0a558SYan, Zheng 	if (!err && node->pending) {
2853b0fe7078SQu Wenruo 		btrfs_backref_drop_node_buffer(node);
28543fd0a558SYan, Zheng 		list_move_tail(&node->list, &rc->backref_cache.changed);
28553fd0a558SYan, Zheng 		node->pending = 0;
28565d4f98a2SYan Zheng 	}
28573fd0a558SYan, Zheng 
28585d4f98a2SYan Zheng 	path->lowest_level = 0;
28593fd0a558SYan, Zheng 	BUG_ON(err == -ENOSPC);
28605d4f98a2SYan Zheng 	return err;
28615d4f98a2SYan Zheng }
28625d4f98a2SYan Zheng 
28635d4f98a2SYan Zheng static int link_to_upper(struct btrfs_trans_handle *trans,
28643fd0a558SYan, Zheng 			 struct reloc_control *rc,
2865a26195a5SQu Wenruo 			 struct btrfs_backref_node *node,
28665d4f98a2SYan Zheng 			 struct btrfs_path *path)
28675d4f98a2SYan Zheng {
28685d4f98a2SYan Zheng 	struct btrfs_key key;
28695d4f98a2SYan Zheng 
28705d4f98a2SYan Zheng 	btrfs_node_key_to_cpu(node->eb, &key, 0);
28713fd0a558SYan, Zheng 	return do_relocation(trans, rc, node, &key, path, 0);
28725d4f98a2SYan Zheng }
28735d4f98a2SYan Zheng 
28745d4f98a2SYan Zheng static int finish_pending_nodes(struct btrfs_trans_handle *trans,
28753fd0a558SYan, Zheng 				struct reloc_control *rc,
28763fd0a558SYan, Zheng 				struct btrfs_path *path, int err)
28775d4f98a2SYan Zheng {
28783fd0a558SYan, Zheng 	LIST_HEAD(list);
2879a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
2880a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
28815d4f98a2SYan Zheng 	int level;
28825d4f98a2SYan Zheng 	int ret;
28835d4f98a2SYan Zheng 
28845d4f98a2SYan Zheng 	for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
28855d4f98a2SYan Zheng 		while (!list_empty(&cache->pending[level])) {
28865d4f98a2SYan Zheng 			node = list_entry(cache->pending[level].next,
2887a26195a5SQu Wenruo 					  struct btrfs_backref_node, list);
28883fd0a558SYan, Zheng 			list_move_tail(&node->list, &list);
28893fd0a558SYan, Zheng 			BUG_ON(!node->pending);
28905d4f98a2SYan Zheng 
28913fd0a558SYan, Zheng 			if (!err) {
28923fd0a558SYan, Zheng 				ret = link_to_upper(trans, rc, node, path);
28935d4f98a2SYan Zheng 				if (ret < 0)
28945d4f98a2SYan Zheng 					err = ret;
28955d4f98a2SYan Zheng 			}
28965d4f98a2SYan Zheng 		}
28973fd0a558SYan, Zheng 		list_splice_init(&list, &cache->pending[level]);
28983fd0a558SYan, Zheng 	}
28995d4f98a2SYan Zheng 	return err;
29005d4f98a2SYan Zheng }
29015d4f98a2SYan Zheng 
29025d4f98a2SYan Zheng /*
29035d4f98a2SYan Zheng  * mark a block and all blocks directly/indirectly reference the block
29045d4f98a2SYan Zheng  * as processed.
29055d4f98a2SYan Zheng  */
29065d4f98a2SYan Zheng static void update_processed_blocks(struct reloc_control *rc,
2907a26195a5SQu Wenruo 				    struct btrfs_backref_node *node)
29085d4f98a2SYan Zheng {
2909a26195a5SQu Wenruo 	struct btrfs_backref_node *next = node;
2910a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2911a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
29125d4f98a2SYan Zheng 	int index = 0;
29135d4f98a2SYan Zheng 
29145d4f98a2SYan Zheng 	while (next) {
29155d4f98a2SYan Zheng 		cond_resched();
29165d4f98a2SYan Zheng 		while (1) {
29175d4f98a2SYan Zheng 			if (next->processed)
29185d4f98a2SYan Zheng 				break;
29195d4f98a2SYan Zheng 
29209569cc20SQu Wenruo 			mark_block_processed(rc, next);
29215d4f98a2SYan Zheng 
29225d4f98a2SYan Zheng 			if (list_empty(&next->upper))
29235d4f98a2SYan Zheng 				break;
29245d4f98a2SYan Zheng 
29255d4f98a2SYan Zheng 			edge = list_entry(next->upper.next,
2926a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[LOWER]);
29275d4f98a2SYan Zheng 			edges[index++] = edge;
29285d4f98a2SYan Zheng 			next = edge->node[UPPER];
29295d4f98a2SYan Zheng 		}
29305d4f98a2SYan Zheng 		next = walk_down_backref(edges, &index);
29315d4f98a2SYan Zheng 	}
29325d4f98a2SYan Zheng }
29335d4f98a2SYan Zheng 
29347476dfdaSDavid Sterba static int tree_block_processed(u64 bytenr, struct reloc_control *rc)
29355d4f98a2SYan Zheng {
2936da17066cSJeff Mahoney 	u32 blocksize = rc->extent_root->fs_info->nodesize;
29377476dfdaSDavid Sterba 
29385d4f98a2SYan Zheng 	if (test_range_bit(&rc->processed_blocks, bytenr,
29399655d298SChris Mason 			   bytenr + blocksize - 1, EXTENT_DIRTY, 1, NULL))
29405d4f98a2SYan Zheng 		return 1;
29415d4f98a2SYan Zheng 	return 0;
29425d4f98a2SYan Zheng }
29435d4f98a2SYan Zheng 
29442ff7e61eSJeff Mahoney static int get_tree_block_key(struct btrfs_fs_info *fs_info,
29455d4f98a2SYan Zheng 			      struct tree_block *block)
29465d4f98a2SYan Zheng {
29475d4f98a2SYan Zheng 	struct extent_buffer *eb;
29485d4f98a2SYan Zheng 
2949581c1760SQu Wenruo 	eb = read_tree_block(fs_info, block->bytenr, block->key.offset,
2950581c1760SQu Wenruo 			     block->level, NULL);
295164c043deSLiu Bo 	if (IS_ERR(eb)) {
295264c043deSLiu Bo 		return PTR_ERR(eb);
295364c043deSLiu Bo 	} else if (!extent_buffer_uptodate(eb)) {
2954416bc658SJosef Bacik 		free_extent_buffer(eb);
2955416bc658SJosef Bacik 		return -EIO;
2956416bc658SJosef Bacik 	}
29575d4f98a2SYan Zheng 	if (block->level == 0)
29585d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(eb, &block->key, 0);
29595d4f98a2SYan Zheng 	else
29605d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(eb, &block->key, 0);
29615d4f98a2SYan Zheng 	free_extent_buffer(eb);
29625d4f98a2SYan Zheng 	block->key_ready = 1;
29635d4f98a2SYan Zheng 	return 0;
29645d4f98a2SYan Zheng }
29655d4f98a2SYan Zheng 
29665d4f98a2SYan Zheng /*
29675d4f98a2SYan Zheng  * helper function to relocate a tree block
29685d4f98a2SYan Zheng  */
29695d4f98a2SYan Zheng static int relocate_tree_block(struct btrfs_trans_handle *trans,
29705d4f98a2SYan Zheng 				struct reloc_control *rc,
2971a26195a5SQu Wenruo 				struct btrfs_backref_node *node,
29725d4f98a2SYan Zheng 				struct btrfs_key *key,
29735d4f98a2SYan Zheng 				struct btrfs_path *path)
29745d4f98a2SYan Zheng {
29755d4f98a2SYan Zheng 	struct btrfs_root *root;
29763fd0a558SYan, Zheng 	int ret = 0;
29775d4f98a2SYan Zheng 
29783fd0a558SYan, Zheng 	if (!node)
29795d4f98a2SYan Zheng 		return 0;
29803fd0a558SYan, Zheng 
29815f6b2e5cSJosef Bacik 	/*
29825f6b2e5cSJosef Bacik 	 * If we fail here we want to drop our backref_node because we are going
29835f6b2e5cSJosef Bacik 	 * to start over and regenerate the tree for it.
29845f6b2e5cSJosef Bacik 	 */
29855f6b2e5cSJosef Bacik 	ret = reserve_metadata_space(trans, rc, node);
29865f6b2e5cSJosef Bacik 	if (ret)
29875f6b2e5cSJosef Bacik 		goto out;
29885f6b2e5cSJosef Bacik 
29893fd0a558SYan, Zheng 	BUG_ON(node->processed);
2990147d256eSZhaolei 	root = select_one_root(node);
29913fd0a558SYan, Zheng 	if (root == ERR_PTR(-ENOENT)) {
29923fd0a558SYan, Zheng 		update_processed_blocks(rc, node);
29933fd0a558SYan, Zheng 		goto out;
29945d4f98a2SYan Zheng 	}
29955d4f98a2SYan Zheng 
29963fd0a558SYan, Zheng 	if (root) {
299727cdeb70SMiao Xie 		if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
29983fd0a558SYan, Zheng 			BUG_ON(node->new_bytenr);
29993fd0a558SYan, Zheng 			BUG_ON(!list_empty(&node->list));
30003fd0a558SYan, Zheng 			btrfs_record_root_in_trans(trans, root);
30013fd0a558SYan, Zheng 			root = root->reloc_root;
30023fd0a558SYan, Zheng 			node->new_bytenr = root->node->start;
300300246528SJosef Bacik 			btrfs_put_root(node->root);
300400246528SJosef Bacik 			node->root = btrfs_grab_root(root);
30050b530bc5SJosef Bacik 			ASSERT(node->root);
30063fd0a558SYan, Zheng 			list_add_tail(&node->list, &rc->backref_cache.changed);
30073fd0a558SYan, Zheng 		} else {
30085d4f98a2SYan Zheng 			path->lowest_level = node->level;
30095d4f98a2SYan Zheng 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
3010b3b4aa74SDavid Sterba 			btrfs_release_path(path);
30113fd0a558SYan, Zheng 			if (ret > 0)
30125d4f98a2SYan Zheng 				ret = 0;
30133fd0a558SYan, Zheng 		}
30143fd0a558SYan, Zheng 		if (!ret)
30153fd0a558SYan, Zheng 			update_processed_blocks(rc, node);
30163fd0a558SYan, Zheng 	} else {
30173fd0a558SYan, Zheng 		ret = do_relocation(trans, rc, node, key, path, 1);
30183fd0a558SYan, Zheng 	}
30195d4f98a2SYan Zheng out:
30200647bf56SWang Shilong 	if (ret || node->level == 0 || node->cowonly)
3021023acb07SQu Wenruo 		btrfs_backref_cleanup_node(&rc->backref_cache, node);
30225d4f98a2SYan Zheng 	return ret;
30235d4f98a2SYan Zheng }
30245d4f98a2SYan Zheng 
30255d4f98a2SYan Zheng /*
30265d4f98a2SYan Zheng  * relocate a list of blocks
30275d4f98a2SYan Zheng  */
30285d4f98a2SYan Zheng static noinline_for_stack
30295d4f98a2SYan Zheng int relocate_tree_blocks(struct btrfs_trans_handle *trans,
30305d4f98a2SYan Zheng 			 struct reloc_control *rc, struct rb_root *blocks)
30315d4f98a2SYan Zheng {
30322ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3033a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
30345d4f98a2SYan Zheng 	struct btrfs_path *path;
30355d4f98a2SYan Zheng 	struct tree_block *block;
303698ff7b94SQu Wenruo 	struct tree_block *next;
30375d4f98a2SYan Zheng 	int ret;
30385d4f98a2SYan Zheng 	int err = 0;
30395d4f98a2SYan Zheng 
30405d4f98a2SYan Zheng 	path = btrfs_alloc_path();
3041e1a12670SLiu Bo 	if (!path) {
3042e1a12670SLiu Bo 		err = -ENOMEM;
304334c2b290SDavid Sterba 		goto out_free_blocks;
3044e1a12670SLiu Bo 	}
30455d4f98a2SYan Zheng 
304698ff7b94SQu Wenruo 	/* Kick in readahead for tree blocks with missing keys */
304798ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
30485d4f98a2SYan Zheng 		if (!block->key_ready)
30492ff7e61eSJeff Mahoney 			readahead_tree_block(fs_info, block->bytenr);
30505d4f98a2SYan Zheng 	}
30515d4f98a2SYan Zheng 
305298ff7b94SQu Wenruo 	/* Get first keys */
305398ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
305434c2b290SDavid Sterba 		if (!block->key_ready) {
30552ff7e61eSJeff Mahoney 			err = get_tree_block_key(fs_info, block);
305634c2b290SDavid Sterba 			if (err)
305734c2b290SDavid Sterba 				goto out_free_path;
305834c2b290SDavid Sterba 		}
30595d4f98a2SYan Zheng 	}
30605d4f98a2SYan Zheng 
306198ff7b94SQu Wenruo 	/* Do tree relocation */
306298ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
30633fd0a558SYan, Zheng 		node = build_backref_tree(rc, &block->key,
30645d4f98a2SYan Zheng 					  block->level, block->bytenr);
30655d4f98a2SYan Zheng 		if (IS_ERR(node)) {
30665d4f98a2SYan Zheng 			err = PTR_ERR(node);
30675d4f98a2SYan Zheng 			goto out;
30685d4f98a2SYan Zheng 		}
30695d4f98a2SYan Zheng 
30705d4f98a2SYan Zheng 		ret = relocate_tree_block(trans, rc, node, &block->key,
30715d4f98a2SYan Zheng 					  path);
30725d4f98a2SYan Zheng 		if (ret < 0) {
30735d4f98a2SYan Zheng 			err = ret;
307450dbbb71SJosef Bacik 			break;
30755d4f98a2SYan Zheng 		}
30765d4f98a2SYan Zheng 	}
30775d4f98a2SYan Zheng out:
30783fd0a558SYan, Zheng 	err = finish_pending_nodes(trans, rc, path, err);
30795d4f98a2SYan Zheng 
308034c2b290SDavid Sterba out_free_path:
30815d4f98a2SYan Zheng 	btrfs_free_path(path);
308234c2b290SDavid Sterba out_free_blocks:
3083e1a12670SLiu Bo 	free_block_list(blocks);
30845d4f98a2SYan Zheng 	return err;
30855d4f98a2SYan Zheng }
30865d4f98a2SYan Zheng 
30875d4f98a2SYan Zheng static noinline_for_stack
3088efa56464SYan, Zheng int prealloc_file_extent_cluster(struct inode *inode,
3089efa56464SYan, Zheng 				 struct file_extent_cluster *cluster)
3090efa56464SYan, Zheng {
3091efa56464SYan, Zheng 	u64 alloc_hint = 0;
3092efa56464SYan, Zheng 	u64 start;
3093efa56464SYan, Zheng 	u64 end;
3094efa56464SYan, Zheng 	u64 offset = BTRFS_I(inode)->index_cnt;
3095efa56464SYan, Zheng 	u64 num_bytes;
3096efa56464SYan, Zheng 	int nr = 0;
3097efa56464SYan, Zheng 	int ret = 0;
3098dcb40c19SWang Xiaoguang 	u64 prealloc_start = cluster->start - offset;
3099dcb40c19SWang Xiaoguang 	u64 prealloc_end = cluster->end - offset;
310018513091SWang Xiaoguang 	u64 cur_offset;
3101364ecf36SQu Wenruo 	struct extent_changeset *data_reserved = NULL;
3102efa56464SYan, Zheng 
3103efa56464SYan, Zheng 	BUG_ON(cluster->start != cluster->boundary[0]);
31045955102cSAl Viro 	inode_lock(inode);
3105efa56464SYan, Zheng 
3106364ecf36SQu Wenruo 	ret = btrfs_check_data_free_space(inode, &data_reserved, prealloc_start,
3107dcb40c19SWang Xiaoguang 					  prealloc_end + 1 - prealloc_start);
3108efa56464SYan, Zheng 	if (ret)
3109efa56464SYan, Zheng 		goto out;
3110efa56464SYan, Zheng 
311118513091SWang Xiaoguang 	cur_offset = prealloc_start;
3112efa56464SYan, Zheng 	while (nr < cluster->nr) {
3113efa56464SYan, Zheng 		start = cluster->boundary[nr] - offset;
3114efa56464SYan, Zheng 		if (nr + 1 < cluster->nr)
3115efa56464SYan, Zheng 			end = cluster->boundary[nr + 1] - 1 - offset;
3116efa56464SYan, Zheng 		else
3117efa56464SYan, Zheng 			end = cluster->end - offset;
3118efa56464SYan, Zheng 
3119d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, start, end);
3120efa56464SYan, Zheng 		num_bytes = end + 1 - start;
312118513091SWang Xiaoguang 		if (cur_offset < start)
3122bc42bda2SQu Wenruo 			btrfs_free_reserved_data_space(inode, data_reserved,
3123bc42bda2SQu Wenruo 					cur_offset, start - cur_offset);
3124efa56464SYan, Zheng 		ret = btrfs_prealloc_file_range(inode, 0, start,
3125efa56464SYan, Zheng 						num_bytes, num_bytes,
3126efa56464SYan, Zheng 						end + 1, &alloc_hint);
312718513091SWang Xiaoguang 		cur_offset = end + 1;
3128d0082371SJeff Mahoney 		unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
3129efa56464SYan, Zheng 		if (ret)
3130efa56464SYan, Zheng 			break;
3131efa56464SYan, Zheng 		nr++;
3132efa56464SYan, Zheng 	}
313318513091SWang Xiaoguang 	if (cur_offset < prealloc_end)
3134bc42bda2SQu Wenruo 		btrfs_free_reserved_data_space(inode, data_reserved,
3135bc42bda2SQu Wenruo 				cur_offset, prealloc_end + 1 - cur_offset);
3136efa56464SYan, Zheng out:
31375955102cSAl Viro 	inode_unlock(inode);
3138364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
3139efa56464SYan, Zheng 	return ret;
3140efa56464SYan, Zheng }
3141efa56464SYan, Zheng 
3142efa56464SYan, Zheng static noinline_for_stack
31430257bb82SYan, Zheng int setup_extent_mapping(struct inode *inode, u64 start, u64 end,
31440257bb82SYan, Zheng 			 u64 block_start)
31455d4f98a2SYan Zheng {
31465d4f98a2SYan Zheng 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
31475d4f98a2SYan Zheng 	struct extent_map *em;
31480257bb82SYan, Zheng 	int ret = 0;
31495d4f98a2SYan Zheng 
3150172ddd60SDavid Sterba 	em = alloc_extent_map();
31510257bb82SYan, Zheng 	if (!em)
31520257bb82SYan, Zheng 		return -ENOMEM;
31530257bb82SYan, Zheng 
31545d4f98a2SYan Zheng 	em->start = start;
31550257bb82SYan, Zheng 	em->len = end + 1 - start;
31560257bb82SYan, Zheng 	em->block_len = em->len;
31570257bb82SYan, Zheng 	em->block_start = block_start;
31585d4f98a2SYan Zheng 	set_bit(EXTENT_FLAG_PINNED, &em->flags);
31595d4f98a2SYan Zheng 
3160d0082371SJeff Mahoney 	lock_extent(&BTRFS_I(inode)->io_tree, start, end);
31615d4f98a2SYan Zheng 	while (1) {
3162890871beSChris Mason 		write_lock(&em_tree->lock);
316309a2a8f9SJosef Bacik 		ret = add_extent_mapping(em_tree, em, 0);
3164890871beSChris Mason 		write_unlock(&em_tree->lock);
31655d4f98a2SYan Zheng 		if (ret != -EEXIST) {
31665d4f98a2SYan Zheng 			free_extent_map(em);
31675d4f98a2SYan Zheng 			break;
31685d4f98a2SYan Zheng 		}
3169dcdbc059SNikolay Borisov 		btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
31705d4f98a2SYan Zheng 	}
3171d0082371SJeff Mahoney 	unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
31720257bb82SYan, Zheng 	return ret;
31730257bb82SYan, Zheng }
31745d4f98a2SYan Zheng 
3175726a3421SQu Wenruo /*
3176726a3421SQu Wenruo  * Allow error injection to test balance cancellation
3177726a3421SQu Wenruo  */
3178726a3421SQu Wenruo int btrfs_should_cancel_balance(struct btrfs_fs_info *fs_info)
3179726a3421SQu Wenruo {
3180726a3421SQu Wenruo 	return atomic_read(&fs_info->balance_cancel_req);
3181726a3421SQu Wenruo }
3182726a3421SQu Wenruo ALLOW_ERROR_INJECTION(btrfs_should_cancel_balance, TRUE);
3183726a3421SQu Wenruo 
31840257bb82SYan, Zheng static int relocate_file_extent_cluster(struct inode *inode,
31850257bb82SYan, Zheng 					struct file_extent_cluster *cluster)
31860257bb82SYan, Zheng {
31872ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
31880257bb82SYan, Zheng 	u64 page_start;
31890257bb82SYan, Zheng 	u64 page_end;
31900257bb82SYan, Zheng 	u64 offset = BTRFS_I(inode)->index_cnt;
31910257bb82SYan, Zheng 	unsigned long index;
31920257bb82SYan, Zheng 	unsigned long last_index;
31930257bb82SYan, Zheng 	struct page *page;
31940257bb82SYan, Zheng 	struct file_ra_state *ra;
31953b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
31960257bb82SYan, Zheng 	int nr = 0;
31970257bb82SYan, Zheng 	int ret = 0;
31980257bb82SYan, Zheng 
31990257bb82SYan, Zheng 	if (!cluster->nr)
32000257bb82SYan, Zheng 		return 0;
32010257bb82SYan, Zheng 
32020257bb82SYan, Zheng 	ra = kzalloc(sizeof(*ra), GFP_NOFS);
32030257bb82SYan, Zheng 	if (!ra)
32040257bb82SYan, Zheng 		return -ENOMEM;
32050257bb82SYan, Zheng 
3206efa56464SYan, Zheng 	ret = prealloc_file_extent_cluster(inode, cluster);
32070257bb82SYan, Zheng 	if (ret)
3208efa56464SYan, Zheng 		goto out;
32090257bb82SYan, Zheng 
32100257bb82SYan, Zheng 	file_ra_state_init(ra, inode->i_mapping);
32110257bb82SYan, Zheng 
3212efa56464SYan, Zheng 	ret = setup_extent_mapping(inode, cluster->start - offset,
3213efa56464SYan, Zheng 				   cluster->end - offset, cluster->start);
3214efa56464SYan, Zheng 	if (ret)
3215efa56464SYan, Zheng 		goto out;
3216efa56464SYan, Zheng 
321709cbfeafSKirill A. Shutemov 	index = (cluster->start - offset) >> PAGE_SHIFT;
321809cbfeafSKirill A. Shutemov 	last_index = (cluster->end - offset) >> PAGE_SHIFT;
32190257bb82SYan, Zheng 	while (index <= last_index) {
32209f3db423SNikolay Borisov 		ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
32219f3db423SNikolay Borisov 				PAGE_SIZE);
3222efa56464SYan, Zheng 		if (ret)
3223efa56464SYan, Zheng 			goto out;
3224efa56464SYan, Zheng 
32250257bb82SYan, Zheng 		page = find_lock_page(inode->i_mapping, index);
32260257bb82SYan, Zheng 		if (!page) {
32270257bb82SYan, Zheng 			page_cache_sync_readahead(inode->i_mapping,
32280257bb82SYan, Zheng 						  ra, NULL, index,
32290257bb82SYan, Zheng 						  last_index + 1 - index);
3230a94733d0SJosef Bacik 			page = find_or_create_page(inode->i_mapping, index,
32313b16a4e3SJosef Bacik 						   mask);
32320257bb82SYan, Zheng 			if (!page) {
3233691fa059SNikolay Borisov 				btrfs_delalloc_release_metadata(BTRFS_I(inode),
323443b18595SQu Wenruo 							PAGE_SIZE, true);
323544db1216SFilipe Manana 				btrfs_delalloc_release_extents(BTRFS_I(inode),
32368702ba93SQu Wenruo 							PAGE_SIZE);
32370257bb82SYan, Zheng 				ret = -ENOMEM;
3238efa56464SYan, Zheng 				goto out;
32390257bb82SYan, Zheng 			}
32400257bb82SYan, Zheng 		}
32410257bb82SYan, Zheng 
32420257bb82SYan, Zheng 		if (PageReadahead(page)) {
32430257bb82SYan, Zheng 			page_cache_async_readahead(inode->i_mapping,
32440257bb82SYan, Zheng 						   ra, NULL, page, index,
32450257bb82SYan, Zheng 						   last_index + 1 - index);
32460257bb82SYan, Zheng 		}
32470257bb82SYan, Zheng 
32480257bb82SYan, Zheng 		if (!PageUptodate(page)) {
32490257bb82SYan, Zheng 			btrfs_readpage(NULL, page);
32500257bb82SYan, Zheng 			lock_page(page);
32510257bb82SYan, Zheng 			if (!PageUptodate(page)) {
32520257bb82SYan, Zheng 				unlock_page(page);
325309cbfeafSKirill A. Shutemov 				put_page(page);
3254691fa059SNikolay Borisov 				btrfs_delalloc_release_metadata(BTRFS_I(inode),
325543b18595SQu Wenruo 							PAGE_SIZE, true);
32568b62f87bSJosef Bacik 				btrfs_delalloc_release_extents(BTRFS_I(inode),
32578702ba93SQu Wenruo 							       PAGE_SIZE);
32580257bb82SYan, Zheng 				ret = -EIO;
3259efa56464SYan, Zheng 				goto out;
32600257bb82SYan, Zheng 			}
32610257bb82SYan, Zheng 		}
32620257bb82SYan, Zheng 
32634eee4fa4SMiao Xie 		page_start = page_offset(page);
326409cbfeafSKirill A. Shutemov 		page_end = page_start + PAGE_SIZE - 1;
32650257bb82SYan, Zheng 
3266d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, page_start, page_end);
32670257bb82SYan, Zheng 
32680257bb82SYan, Zheng 		set_page_extent_mapped(page);
32690257bb82SYan, Zheng 
32700257bb82SYan, Zheng 		if (nr < cluster->nr &&
32710257bb82SYan, Zheng 		    page_start + offset == cluster->boundary[nr]) {
32720257bb82SYan, Zheng 			set_extent_bits(&BTRFS_I(inode)->io_tree,
32730257bb82SYan, Zheng 					page_start, page_end,
3274ceeb0ae7SDavid Sterba 					EXTENT_BOUNDARY);
32750257bb82SYan, Zheng 			nr++;
32760257bb82SYan, Zheng 		}
32770257bb82SYan, Zheng 
3278765f3cebSNikolay Borisov 		ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
3279330a5827SNikolay Borisov 						NULL);
3280765f3cebSNikolay Borisov 		if (ret) {
3281765f3cebSNikolay Borisov 			unlock_page(page);
3282765f3cebSNikolay Borisov 			put_page(page);
3283765f3cebSNikolay Borisov 			btrfs_delalloc_release_metadata(BTRFS_I(inode),
328443b18595SQu Wenruo 							 PAGE_SIZE, true);
3285765f3cebSNikolay Borisov 			btrfs_delalloc_release_extents(BTRFS_I(inode),
32868702ba93SQu Wenruo 			                               PAGE_SIZE);
3287765f3cebSNikolay Borisov 
3288765f3cebSNikolay Borisov 			clear_extent_bits(&BTRFS_I(inode)->io_tree,
3289765f3cebSNikolay Borisov 					  page_start, page_end,
3290765f3cebSNikolay Borisov 					  EXTENT_LOCKED | EXTENT_BOUNDARY);
3291765f3cebSNikolay Borisov 			goto out;
3292765f3cebSNikolay Borisov 
3293765f3cebSNikolay Borisov 		}
32940257bb82SYan, Zheng 		set_page_dirty(page);
32950257bb82SYan, Zheng 
32960257bb82SYan, Zheng 		unlock_extent(&BTRFS_I(inode)->io_tree,
3297d0082371SJeff Mahoney 			      page_start, page_end);
32980257bb82SYan, Zheng 		unlock_page(page);
329909cbfeafSKirill A. Shutemov 		put_page(page);
33000257bb82SYan, Zheng 
33010257bb82SYan, Zheng 		index++;
33028702ba93SQu Wenruo 		btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
3303efa56464SYan, Zheng 		balance_dirty_pages_ratelimited(inode->i_mapping);
33042ff7e61eSJeff Mahoney 		btrfs_throttle(fs_info);
33057f913c7cSQu Wenruo 		if (btrfs_should_cancel_balance(fs_info)) {
33067f913c7cSQu Wenruo 			ret = -ECANCELED;
33077f913c7cSQu Wenruo 			goto out;
33087f913c7cSQu Wenruo 		}
33090257bb82SYan, Zheng 	}
33100257bb82SYan, Zheng 	WARN_ON(nr != cluster->nr);
3311efa56464SYan, Zheng out:
33120257bb82SYan, Zheng 	kfree(ra);
33130257bb82SYan, Zheng 	return ret;
33140257bb82SYan, Zheng }
33150257bb82SYan, Zheng 
33160257bb82SYan, Zheng static noinline_for_stack
33170257bb82SYan, Zheng int relocate_data_extent(struct inode *inode, struct btrfs_key *extent_key,
33180257bb82SYan, Zheng 			 struct file_extent_cluster *cluster)
33190257bb82SYan, Zheng {
33200257bb82SYan, Zheng 	int ret;
33210257bb82SYan, Zheng 
33220257bb82SYan, Zheng 	if (cluster->nr > 0 && extent_key->objectid != cluster->end + 1) {
33230257bb82SYan, Zheng 		ret = relocate_file_extent_cluster(inode, cluster);
33240257bb82SYan, Zheng 		if (ret)
33250257bb82SYan, Zheng 			return ret;
33260257bb82SYan, Zheng 		cluster->nr = 0;
33270257bb82SYan, Zheng 	}
33280257bb82SYan, Zheng 
33290257bb82SYan, Zheng 	if (!cluster->nr)
33300257bb82SYan, Zheng 		cluster->start = extent_key->objectid;
33310257bb82SYan, Zheng 	else
33320257bb82SYan, Zheng 		BUG_ON(cluster->nr >= MAX_EXTENTS);
33330257bb82SYan, Zheng 	cluster->end = extent_key->objectid + extent_key->offset - 1;
33340257bb82SYan, Zheng 	cluster->boundary[cluster->nr] = extent_key->objectid;
33350257bb82SYan, Zheng 	cluster->nr++;
33360257bb82SYan, Zheng 
33370257bb82SYan, Zheng 	if (cluster->nr >= MAX_EXTENTS) {
33380257bb82SYan, Zheng 		ret = relocate_file_extent_cluster(inode, cluster);
33390257bb82SYan, Zheng 		if (ret)
33400257bb82SYan, Zheng 			return ret;
33410257bb82SYan, Zheng 		cluster->nr = 0;
33420257bb82SYan, Zheng 	}
33430257bb82SYan, Zheng 	return 0;
33445d4f98a2SYan Zheng }
33455d4f98a2SYan Zheng 
33465d4f98a2SYan Zheng /*
33475d4f98a2SYan Zheng  * helper to add a tree block to the list.
33485d4f98a2SYan Zheng  * the major work is getting the generation and level of the block
33495d4f98a2SYan Zheng  */
33505d4f98a2SYan Zheng static int add_tree_block(struct reloc_control *rc,
33515d4f98a2SYan Zheng 			  struct btrfs_key *extent_key,
33525d4f98a2SYan Zheng 			  struct btrfs_path *path,
33535d4f98a2SYan Zheng 			  struct rb_root *blocks)
33545d4f98a2SYan Zheng {
33555d4f98a2SYan Zheng 	struct extent_buffer *eb;
33565d4f98a2SYan Zheng 	struct btrfs_extent_item *ei;
33575d4f98a2SYan Zheng 	struct btrfs_tree_block_info *bi;
33585d4f98a2SYan Zheng 	struct tree_block *block;
33595d4f98a2SYan Zheng 	struct rb_node *rb_node;
33605d4f98a2SYan Zheng 	u32 item_size;
33615d4f98a2SYan Zheng 	int level = -1;
33627fdf4b60SWang Shilong 	u64 generation;
33635d4f98a2SYan Zheng 
33645d4f98a2SYan Zheng 	eb =  path->nodes[0];
33655d4f98a2SYan Zheng 	item_size = btrfs_item_size_nr(eb, path->slots[0]);
33665d4f98a2SYan Zheng 
33673173a18fSJosef Bacik 	if (extent_key->type == BTRFS_METADATA_ITEM_KEY ||
33683173a18fSJosef Bacik 	    item_size >= sizeof(*ei) + sizeof(*bi)) {
33695d4f98a2SYan Zheng 		ei = btrfs_item_ptr(eb, path->slots[0],
33705d4f98a2SYan Zheng 				struct btrfs_extent_item);
33713173a18fSJosef Bacik 		if (extent_key->type == BTRFS_EXTENT_ITEM_KEY) {
33725d4f98a2SYan Zheng 			bi = (struct btrfs_tree_block_info *)(ei + 1);
33735d4f98a2SYan Zheng 			level = btrfs_tree_block_level(eb, bi);
33745d4f98a2SYan Zheng 		} else {
33753173a18fSJosef Bacik 			level = (int)extent_key->offset;
33763173a18fSJosef Bacik 		}
33773173a18fSJosef Bacik 		generation = btrfs_extent_generation(eb, ei);
33786d8ff4e4SDavid Sterba 	} else if (unlikely(item_size == sizeof(struct btrfs_extent_item_v0))) {
3379ba3c2b19SNikolay Borisov 		btrfs_print_v0_err(eb->fs_info);
3380ba3c2b19SNikolay Borisov 		btrfs_handle_fs_error(eb->fs_info, -EINVAL, NULL);
3381ba3c2b19SNikolay Borisov 		return -EINVAL;
33823173a18fSJosef Bacik 	} else {
33835d4f98a2SYan Zheng 		BUG();
33845d4f98a2SYan Zheng 	}
33855d4f98a2SYan Zheng 
3386b3b4aa74SDavid Sterba 	btrfs_release_path(path);
33875d4f98a2SYan Zheng 
33885d4f98a2SYan Zheng 	BUG_ON(level == -1);
33895d4f98a2SYan Zheng 
33905d4f98a2SYan Zheng 	block = kmalloc(sizeof(*block), GFP_NOFS);
33915d4f98a2SYan Zheng 	if (!block)
33925d4f98a2SYan Zheng 		return -ENOMEM;
33935d4f98a2SYan Zheng 
33945d4f98a2SYan Zheng 	block->bytenr = extent_key->objectid;
3395da17066cSJeff Mahoney 	block->key.objectid = rc->extent_root->fs_info->nodesize;
33965d4f98a2SYan Zheng 	block->key.offset = generation;
33975d4f98a2SYan Zheng 	block->level = level;
33985d4f98a2SYan Zheng 	block->key_ready = 0;
33995d4f98a2SYan Zheng 
3400e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(blocks, block->bytenr, &block->rb_node);
340143c04fb1SJeff Mahoney 	if (rb_node)
3402982c92cbSQu Wenruo 		btrfs_backref_panic(rc->extent_root->fs_info, block->bytenr,
3403982c92cbSQu Wenruo 				    -EEXIST);
34045d4f98a2SYan Zheng 
34055d4f98a2SYan Zheng 	return 0;
34065d4f98a2SYan Zheng }
34075d4f98a2SYan Zheng 
34085d4f98a2SYan Zheng /*
34095d4f98a2SYan Zheng  * helper to add tree blocks for backref of type BTRFS_SHARED_DATA_REF_KEY
34105d4f98a2SYan Zheng  */
34115d4f98a2SYan Zheng static int __add_tree_block(struct reloc_control *rc,
34125d4f98a2SYan Zheng 			    u64 bytenr, u32 blocksize,
34135d4f98a2SYan Zheng 			    struct rb_root *blocks)
34145d4f98a2SYan Zheng {
34150b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
34165d4f98a2SYan Zheng 	struct btrfs_path *path;
34175d4f98a2SYan Zheng 	struct btrfs_key key;
34185d4f98a2SYan Zheng 	int ret;
34190b246afaSJeff Mahoney 	bool skinny = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
34205d4f98a2SYan Zheng 
34217476dfdaSDavid Sterba 	if (tree_block_processed(bytenr, rc))
34225d4f98a2SYan Zheng 		return 0;
34235d4f98a2SYan Zheng 
3424e9a28dc5SQu Wenruo 	if (rb_simple_search(blocks, bytenr))
34255d4f98a2SYan Zheng 		return 0;
34265d4f98a2SYan Zheng 
34275d4f98a2SYan Zheng 	path = btrfs_alloc_path();
34285d4f98a2SYan Zheng 	if (!path)
34295d4f98a2SYan Zheng 		return -ENOMEM;
3430aee68ee5SJosef Bacik again:
34315d4f98a2SYan Zheng 	key.objectid = bytenr;
3432aee68ee5SJosef Bacik 	if (skinny) {
3433aee68ee5SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
3434aee68ee5SJosef Bacik 		key.offset = (u64)-1;
3435aee68ee5SJosef Bacik 	} else {
34365d4f98a2SYan Zheng 		key.type = BTRFS_EXTENT_ITEM_KEY;
34375d4f98a2SYan Zheng 		key.offset = blocksize;
3438aee68ee5SJosef Bacik 	}
34395d4f98a2SYan Zheng 
34405d4f98a2SYan Zheng 	path->search_commit_root = 1;
34415d4f98a2SYan Zheng 	path->skip_locking = 1;
34425d4f98a2SYan Zheng 	ret = btrfs_search_slot(NULL, rc->extent_root, &key, path, 0, 0);
34435d4f98a2SYan Zheng 	if (ret < 0)
34445d4f98a2SYan Zheng 		goto out;
34455d4f98a2SYan Zheng 
3446aee68ee5SJosef Bacik 	if (ret > 0 && skinny) {
3447aee68ee5SJosef Bacik 		if (path->slots[0]) {
3448aee68ee5SJosef Bacik 			path->slots[0]--;
3449aee68ee5SJosef Bacik 			btrfs_item_key_to_cpu(path->nodes[0], &key,
3450aee68ee5SJosef Bacik 					      path->slots[0]);
34513173a18fSJosef Bacik 			if (key.objectid == bytenr &&
3452aee68ee5SJosef Bacik 			    (key.type == BTRFS_METADATA_ITEM_KEY ||
3453aee68ee5SJosef Bacik 			     (key.type == BTRFS_EXTENT_ITEM_KEY &&
3454aee68ee5SJosef Bacik 			      key.offset == blocksize)))
34553173a18fSJosef Bacik 				ret = 0;
34563173a18fSJosef Bacik 		}
3457aee68ee5SJosef Bacik 
3458aee68ee5SJosef Bacik 		if (ret) {
3459aee68ee5SJosef Bacik 			skinny = false;
3460aee68ee5SJosef Bacik 			btrfs_release_path(path);
3461aee68ee5SJosef Bacik 			goto again;
3462aee68ee5SJosef Bacik 		}
3463aee68ee5SJosef Bacik 	}
3464cdccee99SLiu Bo 	if (ret) {
3465cdccee99SLiu Bo 		ASSERT(ret == 1);
3466cdccee99SLiu Bo 		btrfs_print_leaf(path->nodes[0]);
3467cdccee99SLiu Bo 		btrfs_err(fs_info,
3468cdccee99SLiu Bo 	     "tree block extent item (%llu) is not found in extent tree",
3469cdccee99SLiu Bo 		     bytenr);
3470cdccee99SLiu Bo 		WARN_ON(1);
3471cdccee99SLiu Bo 		ret = -EINVAL;
3472cdccee99SLiu Bo 		goto out;
3473cdccee99SLiu Bo 	}
34743173a18fSJosef Bacik 
34755d4f98a2SYan Zheng 	ret = add_tree_block(rc, &key, path, blocks);
34765d4f98a2SYan Zheng out:
34775d4f98a2SYan Zheng 	btrfs_free_path(path);
34785d4f98a2SYan Zheng 	return ret;
34795d4f98a2SYan Zheng }
34805d4f98a2SYan Zheng 
34810af3d00bSJosef Bacik static int delete_block_group_cache(struct btrfs_fs_info *fs_info,
348232da5386SDavid Sterba 				    struct btrfs_block_group *block_group,
34831bbc621eSChris Mason 				    struct inode *inode,
34841bbc621eSChris Mason 				    u64 ino)
34850af3d00bSJosef Bacik {
34860af3d00bSJosef Bacik 	struct btrfs_key key;
34870af3d00bSJosef Bacik 	struct btrfs_root *root = fs_info->tree_root;
34880af3d00bSJosef Bacik 	struct btrfs_trans_handle *trans;
34890af3d00bSJosef Bacik 	int ret = 0;
34900af3d00bSJosef Bacik 
34910af3d00bSJosef Bacik 	if (inode)
34920af3d00bSJosef Bacik 		goto truncate;
34930af3d00bSJosef Bacik 
34940af3d00bSJosef Bacik 	key.objectid = ino;
34950af3d00bSJosef Bacik 	key.type = BTRFS_INODE_ITEM_KEY;
34960af3d00bSJosef Bacik 	key.offset = 0;
34970af3d00bSJosef Bacik 
34984c66e0d4SDavid Sterba 	inode = btrfs_iget(fs_info->sb, &key, root);
34992e19f1f9SAl Viro 	if (IS_ERR(inode))
35000af3d00bSJosef Bacik 		return -ENOENT;
35010af3d00bSJosef Bacik 
35020af3d00bSJosef Bacik truncate:
35032ff7e61eSJeff Mahoney 	ret = btrfs_check_trunc_cache_free_space(fs_info,
35047b61cd92SMiao Xie 						 &fs_info->global_block_rsv);
35057b61cd92SMiao Xie 	if (ret)
35067b61cd92SMiao Xie 		goto out;
35077b61cd92SMiao Xie 
35087a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
35090af3d00bSJosef Bacik 	if (IS_ERR(trans)) {
35103612b495STsutomu Itoh 		ret = PTR_ERR(trans);
35110af3d00bSJosef Bacik 		goto out;
35120af3d00bSJosef Bacik 	}
35130af3d00bSJosef Bacik 
351477ab86bfSJeff Mahoney 	ret = btrfs_truncate_free_space_cache(trans, block_group, inode);
35150af3d00bSJosef Bacik 
35163a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
35172ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
35180af3d00bSJosef Bacik out:
35190af3d00bSJosef Bacik 	iput(inode);
35200af3d00bSJosef Bacik 	return ret;
35210af3d00bSJosef Bacik }
35220af3d00bSJosef Bacik 
35235d4f98a2SYan Zheng /*
352419b546d7SQu Wenruo  * Locate the free space cache EXTENT_DATA in root tree leaf and delete the
352519b546d7SQu Wenruo  * cache inode, to avoid free space cache data extent blocking data relocation.
35265d4f98a2SYan Zheng  */
352719b546d7SQu Wenruo static int delete_v1_space_cache(struct extent_buffer *leaf,
352819b546d7SQu Wenruo 				 struct btrfs_block_group *block_group,
352919b546d7SQu Wenruo 				 u64 data_bytenr)
35305d4f98a2SYan Zheng {
353119b546d7SQu Wenruo 	u64 space_cache_ino;
353219b546d7SQu Wenruo 	struct btrfs_file_extent_item *ei;
35335d4f98a2SYan Zheng 	struct btrfs_key key;
353419b546d7SQu Wenruo 	bool found = false;
353519b546d7SQu Wenruo 	int i;
35365d4f98a2SYan Zheng 	int ret;
35375d4f98a2SYan Zheng 
353819b546d7SQu Wenruo 	if (btrfs_header_owner(leaf) != BTRFS_ROOT_TREE_OBJECTID)
353919b546d7SQu Wenruo 		return 0;
35405d4f98a2SYan Zheng 
354119b546d7SQu Wenruo 	for (i = 0; i < btrfs_header_nritems(leaf); i++) {
354219b546d7SQu Wenruo 		btrfs_item_key_to_cpu(leaf, &key, i);
354319b546d7SQu Wenruo 		if (key.type != BTRFS_EXTENT_DATA_KEY)
354419b546d7SQu Wenruo 			continue;
354519b546d7SQu Wenruo 		ei = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
354619b546d7SQu Wenruo 		if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_REG &&
354719b546d7SQu Wenruo 		    btrfs_file_extent_disk_bytenr(leaf, ei) == data_bytenr) {
354819b546d7SQu Wenruo 			found = true;
354919b546d7SQu Wenruo 			space_cache_ino = key.objectid;
355019b546d7SQu Wenruo 			break;
355119b546d7SQu Wenruo 		}
355219b546d7SQu Wenruo 	}
355319b546d7SQu Wenruo 	if (!found)
355419b546d7SQu Wenruo 		return -ENOENT;
355519b546d7SQu Wenruo 	ret = delete_block_group_cache(leaf->fs_info, block_group, NULL,
355619b546d7SQu Wenruo 					space_cache_ino);
35570af3d00bSJosef Bacik 	return ret;
35585d4f98a2SYan Zheng }
35595d4f98a2SYan Zheng 
35605d4f98a2SYan Zheng /*
35612c016dc2SLiu Bo  * helper to find all tree blocks that reference a given data extent
35625d4f98a2SYan Zheng  */
35635d4f98a2SYan Zheng static noinline_for_stack
35645d4f98a2SYan Zheng int add_data_references(struct reloc_control *rc,
35655d4f98a2SYan Zheng 			struct btrfs_key *extent_key,
35665d4f98a2SYan Zheng 			struct btrfs_path *path,
35675d4f98a2SYan Zheng 			struct rb_root *blocks)
35685d4f98a2SYan Zheng {
356919b546d7SQu Wenruo 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
357019b546d7SQu Wenruo 	struct ulist *leaves = NULL;
357119b546d7SQu Wenruo 	struct ulist_iterator leaf_uiter;
357219b546d7SQu Wenruo 	struct ulist_node *ref_node = NULL;
357319b546d7SQu Wenruo 	const u32 blocksize = fs_info->nodesize;
3574647f63bdSFilipe David Borba Manana 	int ret = 0;
35755d4f98a2SYan Zheng 
3576b3b4aa74SDavid Sterba 	btrfs_release_path(path);
357719b546d7SQu Wenruo 	ret = btrfs_find_all_leafs(NULL, fs_info, extent_key->objectid,
357819b546d7SQu Wenruo 				   0, &leaves, NULL, true);
357919b546d7SQu Wenruo 	if (ret < 0)
358019b546d7SQu Wenruo 		return ret;
358119b546d7SQu Wenruo 
358219b546d7SQu Wenruo 	ULIST_ITER_INIT(&leaf_uiter);
358319b546d7SQu Wenruo 	while ((ref_node = ulist_next(leaves, &leaf_uiter))) {
358419b546d7SQu Wenruo 		struct extent_buffer *eb;
358519b546d7SQu Wenruo 
358619b546d7SQu Wenruo 		eb = read_tree_block(fs_info, ref_node->val, 0, 0, NULL);
358719b546d7SQu Wenruo 		if (IS_ERR(eb)) {
358819b546d7SQu Wenruo 			ret = PTR_ERR(eb);
358919b546d7SQu Wenruo 			break;
359019b546d7SQu Wenruo 		}
359119b546d7SQu Wenruo 		ret = delete_v1_space_cache(eb, rc->block_group,
359219b546d7SQu Wenruo 					    extent_key->objectid);
359319b546d7SQu Wenruo 		free_extent_buffer(eb);
359419b546d7SQu Wenruo 		if (ret < 0)
359519b546d7SQu Wenruo 			break;
359619b546d7SQu Wenruo 		ret = __add_tree_block(rc, ref_node->val, blocksize, blocks);
359719b546d7SQu Wenruo 		if (ret < 0)
359819b546d7SQu Wenruo 			break;
359919b546d7SQu Wenruo 	}
360019b546d7SQu Wenruo 	if (ret < 0)
36015d4f98a2SYan Zheng 		free_block_list(blocks);
360219b546d7SQu Wenruo 	ulist_free(leaves);
360319b546d7SQu Wenruo 	return ret;
36045d4f98a2SYan Zheng }
36055d4f98a2SYan Zheng 
36065d4f98a2SYan Zheng /*
36072c016dc2SLiu Bo  * helper to find next unprocessed extent
36085d4f98a2SYan Zheng  */
36095d4f98a2SYan Zheng static noinline_for_stack
3610147d256eSZhaolei int find_next_extent(struct reloc_control *rc, struct btrfs_path *path,
36113fd0a558SYan, Zheng 		     struct btrfs_key *extent_key)
36125d4f98a2SYan Zheng {
36130b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
36145d4f98a2SYan Zheng 	struct btrfs_key key;
36155d4f98a2SYan Zheng 	struct extent_buffer *leaf;
36165d4f98a2SYan Zheng 	u64 start, end, last;
36175d4f98a2SYan Zheng 	int ret;
36185d4f98a2SYan Zheng 
3619b3470b5dSDavid Sterba 	last = rc->block_group->start + rc->block_group->length;
36205d4f98a2SYan Zheng 	while (1) {
36215d4f98a2SYan Zheng 		cond_resched();
36225d4f98a2SYan Zheng 		if (rc->search_start >= last) {
36235d4f98a2SYan Zheng 			ret = 1;
36245d4f98a2SYan Zheng 			break;
36255d4f98a2SYan Zheng 		}
36265d4f98a2SYan Zheng 
36275d4f98a2SYan Zheng 		key.objectid = rc->search_start;
36285d4f98a2SYan Zheng 		key.type = BTRFS_EXTENT_ITEM_KEY;
36295d4f98a2SYan Zheng 		key.offset = 0;
36305d4f98a2SYan Zheng 
36315d4f98a2SYan Zheng 		path->search_commit_root = 1;
36325d4f98a2SYan Zheng 		path->skip_locking = 1;
36335d4f98a2SYan Zheng 		ret = btrfs_search_slot(NULL, rc->extent_root, &key, path,
36345d4f98a2SYan Zheng 					0, 0);
36355d4f98a2SYan Zheng 		if (ret < 0)
36365d4f98a2SYan Zheng 			break;
36375d4f98a2SYan Zheng next:
36385d4f98a2SYan Zheng 		leaf = path->nodes[0];
36395d4f98a2SYan Zheng 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
36405d4f98a2SYan Zheng 			ret = btrfs_next_leaf(rc->extent_root, path);
36415d4f98a2SYan Zheng 			if (ret != 0)
36425d4f98a2SYan Zheng 				break;
36435d4f98a2SYan Zheng 			leaf = path->nodes[0];
36445d4f98a2SYan Zheng 		}
36455d4f98a2SYan Zheng 
36465d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
36475d4f98a2SYan Zheng 		if (key.objectid >= last) {
36485d4f98a2SYan Zheng 			ret = 1;
36495d4f98a2SYan Zheng 			break;
36505d4f98a2SYan Zheng 		}
36515d4f98a2SYan Zheng 
36523173a18fSJosef Bacik 		if (key.type != BTRFS_EXTENT_ITEM_KEY &&
36533173a18fSJosef Bacik 		    key.type != BTRFS_METADATA_ITEM_KEY) {
36543173a18fSJosef Bacik 			path->slots[0]++;
36553173a18fSJosef Bacik 			goto next;
36563173a18fSJosef Bacik 		}
36573173a18fSJosef Bacik 
36583173a18fSJosef Bacik 		if (key.type == BTRFS_EXTENT_ITEM_KEY &&
36595d4f98a2SYan Zheng 		    key.objectid + key.offset <= rc->search_start) {
36605d4f98a2SYan Zheng 			path->slots[0]++;
36615d4f98a2SYan Zheng 			goto next;
36625d4f98a2SYan Zheng 		}
36635d4f98a2SYan Zheng 
36643173a18fSJosef Bacik 		if (key.type == BTRFS_METADATA_ITEM_KEY &&
36650b246afaSJeff Mahoney 		    key.objectid + fs_info->nodesize <=
36663173a18fSJosef Bacik 		    rc->search_start) {
36673173a18fSJosef Bacik 			path->slots[0]++;
36683173a18fSJosef Bacik 			goto next;
36693173a18fSJosef Bacik 		}
36703173a18fSJosef Bacik 
36715d4f98a2SYan Zheng 		ret = find_first_extent_bit(&rc->processed_blocks,
36725d4f98a2SYan Zheng 					    key.objectid, &start, &end,
3673e6138876SJosef Bacik 					    EXTENT_DIRTY, NULL);
36745d4f98a2SYan Zheng 
36755d4f98a2SYan Zheng 		if (ret == 0 && start <= key.objectid) {
3676b3b4aa74SDavid Sterba 			btrfs_release_path(path);
36775d4f98a2SYan Zheng 			rc->search_start = end + 1;
36785d4f98a2SYan Zheng 		} else {
36793173a18fSJosef Bacik 			if (key.type == BTRFS_EXTENT_ITEM_KEY)
36805d4f98a2SYan Zheng 				rc->search_start = key.objectid + key.offset;
36813173a18fSJosef Bacik 			else
36823173a18fSJosef Bacik 				rc->search_start = key.objectid +
36830b246afaSJeff Mahoney 					fs_info->nodesize;
36843fd0a558SYan, Zheng 			memcpy(extent_key, &key, sizeof(key));
36855d4f98a2SYan Zheng 			return 0;
36865d4f98a2SYan Zheng 		}
36875d4f98a2SYan Zheng 	}
3688b3b4aa74SDavid Sterba 	btrfs_release_path(path);
36895d4f98a2SYan Zheng 	return ret;
36905d4f98a2SYan Zheng }
36915d4f98a2SYan Zheng 
36925d4f98a2SYan Zheng static void set_reloc_control(struct reloc_control *rc)
36935d4f98a2SYan Zheng {
36945d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
36957585717fSChris Mason 
36967585717fSChris Mason 	mutex_lock(&fs_info->reloc_mutex);
36975d4f98a2SYan Zheng 	fs_info->reloc_ctl = rc;
36987585717fSChris Mason 	mutex_unlock(&fs_info->reloc_mutex);
36995d4f98a2SYan Zheng }
37005d4f98a2SYan Zheng 
37015d4f98a2SYan Zheng static void unset_reloc_control(struct reloc_control *rc)
37025d4f98a2SYan Zheng {
37035d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
37047585717fSChris Mason 
37057585717fSChris Mason 	mutex_lock(&fs_info->reloc_mutex);
37065d4f98a2SYan Zheng 	fs_info->reloc_ctl = NULL;
37077585717fSChris Mason 	mutex_unlock(&fs_info->reloc_mutex);
37085d4f98a2SYan Zheng }
37095d4f98a2SYan Zheng 
37105d4f98a2SYan Zheng static int check_extent_flags(u64 flags)
37115d4f98a2SYan Zheng {
37125d4f98a2SYan Zheng 	if ((flags & BTRFS_EXTENT_FLAG_DATA) &&
37135d4f98a2SYan Zheng 	    (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
37145d4f98a2SYan Zheng 		return 1;
37155d4f98a2SYan Zheng 	if (!(flags & BTRFS_EXTENT_FLAG_DATA) &&
37165d4f98a2SYan Zheng 	    !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
37175d4f98a2SYan Zheng 		return 1;
37185d4f98a2SYan Zheng 	if ((flags & BTRFS_EXTENT_FLAG_DATA) &&
37195d4f98a2SYan Zheng 	    (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
37205d4f98a2SYan Zheng 		return 1;
37215d4f98a2SYan Zheng 	return 0;
37225d4f98a2SYan Zheng }
37235d4f98a2SYan Zheng 
37243fd0a558SYan, Zheng static noinline_for_stack
37253fd0a558SYan, Zheng int prepare_to_relocate(struct reloc_control *rc)
37263fd0a558SYan, Zheng {
37273fd0a558SYan, Zheng 	struct btrfs_trans_handle *trans;
3728ac2fabacSJosef Bacik 	int ret;
37293fd0a558SYan, Zheng 
37302ff7e61eSJeff Mahoney 	rc->block_rsv = btrfs_alloc_block_rsv(rc->extent_root->fs_info,
373166d8f3ddSMiao Xie 					      BTRFS_BLOCK_RSV_TEMP);
37323fd0a558SYan, Zheng 	if (!rc->block_rsv)
37333fd0a558SYan, Zheng 		return -ENOMEM;
37343fd0a558SYan, Zheng 
37353fd0a558SYan, Zheng 	memset(&rc->cluster, 0, sizeof(rc->cluster));
3736b3470b5dSDavid Sterba 	rc->search_start = rc->block_group->start;
37373fd0a558SYan, Zheng 	rc->extents_found = 0;
37383fd0a558SYan, Zheng 	rc->nodes_relocated = 0;
37393fd0a558SYan, Zheng 	rc->merging_rsv_size = 0;
37400647bf56SWang Shilong 	rc->reserved_bytes = 0;
3741da17066cSJeff Mahoney 	rc->block_rsv->size = rc->extent_root->fs_info->nodesize *
37420647bf56SWang Shilong 			      RELOCATION_RESERVED_NODES;
3743ac2fabacSJosef Bacik 	ret = btrfs_block_rsv_refill(rc->extent_root,
3744ac2fabacSJosef Bacik 				     rc->block_rsv, rc->block_rsv->size,
3745ac2fabacSJosef Bacik 				     BTRFS_RESERVE_FLUSH_ALL);
3746ac2fabacSJosef Bacik 	if (ret)
3747ac2fabacSJosef Bacik 		return ret;
37483fd0a558SYan, Zheng 
37493fd0a558SYan, Zheng 	rc->create_reloc_tree = 1;
37503fd0a558SYan, Zheng 	set_reloc_control(rc);
37513fd0a558SYan, Zheng 
37527a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
375328818947SLiu Bo 	if (IS_ERR(trans)) {
375428818947SLiu Bo 		unset_reloc_control(rc);
375528818947SLiu Bo 		/*
375628818947SLiu Bo 		 * extent tree is not a ref_cow tree and has no reloc_root to
375728818947SLiu Bo 		 * cleanup.  And callers are responsible to free the above
375828818947SLiu Bo 		 * block rsv.
375928818947SLiu Bo 		 */
376028818947SLiu Bo 		return PTR_ERR(trans);
376128818947SLiu Bo 	}
37623a45bb20SJeff Mahoney 	btrfs_commit_transaction(trans);
37633fd0a558SYan, Zheng 	return 0;
37643fd0a558SYan, Zheng }
376576dda93cSYan, Zheng 
37665d4f98a2SYan Zheng static noinline_for_stack int relocate_block_group(struct reloc_control *rc)
37675d4f98a2SYan Zheng {
37682ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
37695d4f98a2SYan Zheng 	struct rb_root blocks = RB_ROOT;
37705d4f98a2SYan Zheng 	struct btrfs_key key;
37715d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans = NULL;
37725d4f98a2SYan Zheng 	struct btrfs_path *path;
37735d4f98a2SYan Zheng 	struct btrfs_extent_item *ei;
37745d4f98a2SYan Zheng 	u64 flags;
37755d4f98a2SYan Zheng 	u32 item_size;
37765d4f98a2SYan Zheng 	int ret;
37775d4f98a2SYan Zheng 	int err = 0;
3778c87f08caSChris Mason 	int progress = 0;
37795d4f98a2SYan Zheng 
37805d4f98a2SYan Zheng 	path = btrfs_alloc_path();
37813fd0a558SYan, Zheng 	if (!path)
37825d4f98a2SYan Zheng 		return -ENOMEM;
3783e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
37843fd0a558SYan, Zheng 
37853fd0a558SYan, Zheng 	ret = prepare_to_relocate(rc);
37863fd0a558SYan, Zheng 	if (ret) {
37873fd0a558SYan, Zheng 		err = ret;
37883fd0a558SYan, Zheng 		goto out_free;
37892423fdfbSJiri Slaby 	}
37905d4f98a2SYan Zheng 
37915d4f98a2SYan Zheng 	while (1) {
37920647bf56SWang Shilong 		rc->reserved_bytes = 0;
37930647bf56SWang Shilong 		ret = btrfs_block_rsv_refill(rc->extent_root,
37940647bf56SWang Shilong 					rc->block_rsv, rc->block_rsv->size,
37950647bf56SWang Shilong 					BTRFS_RESERVE_FLUSH_ALL);
37960647bf56SWang Shilong 		if (ret) {
37970647bf56SWang Shilong 			err = ret;
37980647bf56SWang Shilong 			break;
37990647bf56SWang Shilong 		}
3800c87f08caSChris Mason 		progress++;
3801a22285a6SYan, Zheng 		trans = btrfs_start_transaction(rc->extent_root, 0);
38020f788c58SLiu Bo 		if (IS_ERR(trans)) {
38030f788c58SLiu Bo 			err = PTR_ERR(trans);
38040f788c58SLiu Bo 			trans = NULL;
38050f788c58SLiu Bo 			break;
38060f788c58SLiu Bo 		}
3807c87f08caSChris Mason restart:
38083fd0a558SYan, Zheng 		if (update_backref_cache(trans, &rc->backref_cache)) {
38093a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
381042a657f5SPan Bian 			trans = NULL;
38113fd0a558SYan, Zheng 			continue;
38123fd0a558SYan, Zheng 		}
38133fd0a558SYan, Zheng 
3814147d256eSZhaolei 		ret = find_next_extent(rc, path, &key);
38155d4f98a2SYan Zheng 		if (ret < 0)
38165d4f98a2SYan Zheng 			err = ret;
38175d4f98a2SYan Zheng 		if (ret != 0)
38185d4f98a2SYan Zheng 			break;
38195d4f98a2SYan Zheng 
38205d4f98a2SYan Zheng 		rc->extents_found++;
38215d4f98a2SYan Zheng 
38225d4f98a2SYan Zheng 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
38235d4f98a2SYan Zheng 				    struct btrfs_extent_item);
38243fd0a558SYan, Zheng 		item_size = btrfs_item_size_nr(path->nodes[0], path->slots[0]);
38255d4f98a2SYan Zheng 		if (item_size >= sizeof(*ei)) {
38265d4f98a2SYan Zheng 			flags = btrfs_extent_flags(path->nodes[0], ei);
38275d4f98a2SYan Zheng 			ret = check_extent_flags(flags);
38285d4f98a2SYan Zheng 			BUG_ON(ret);
38296d8ff4e4SDavid Sterba 		} else if (unlikely(item_size == sizeof(struct btrfs_extent_item_v0))) {
3830ba3c2b19SNikolay Borisov 			err = -EINVAL;
3831ba3c2b19SNikolay Borisov 			btrfs_print_v0_err(trans->fs_info);
3832ba3c2b19SNikolay Borisov 			btrfs_abort_transaction(trans, err);
3833ba3c2b19SNikolay Borisov 			break;
38345d4f98a2SYan Zheng 		} else {
38355d4f98a2SYan Zheng 			BUG();
38365d4f98a2SYan Zheng 		}
38375d4f98a2SYan Zheng 
38385d4f98a2SYan Zheng 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
38395d4f98a2SYan Zheng 			ret = add_tree_block(rc, &key, path, &blocks);
38405d4f98a2SYan Zheng 		} else if (rc->stage == UPDATE_DATA_PTRS &&
38415d4f98a2SYan Zheng 			   (flags & BTRFS_EXTENT_FLAG_DATA)) {
38425d4f98a2SYan Zheng 			ret = add_data_references(rc, &key, path, &blocks);
38435d4f98a2SYan Zheng 		} else {
3844b3b4aa74SDavid Sterba 			btrfs_release_path(path);
38455d4f98a2SYan Zheng 			ret = 0;
38465d4f98a2SYan Zheng 		}
38475d4f98a2SYan Zheng 		if (ret < 0) {
38483fd0a558SYan, Zheng 			err = ret;
38495d4f98a2SYan Zheng 			break;
38505d4f98a2SYan Zheng 		}
38515d4f98a2SYan Zheng 
38525d4f98a2SYan Zheng 		if (!RB_EMPTY_ROOT(&blocks)) {
38535d4f98a2SYan Zheng 			ret = relocate_tree_blocks(trans, rc, &blocks);
38545d4f98a2SYan Zheng 			if (ret < 0) {
38553fd0a558SYan, Zheng 				if (ret != -EAGAIN) {
38565d4f98a2SYan Zheng 					err = ret;
38575d4f98a2SYan Zheng 					break;
38585d4f98a2SYan Zheng 				}
38593fd0a558SYan, Zheng 				rc->extents_found--;
38603fd0a558SYan, Zheng 				rc->search_start = key.objectid;
38613fd0a558SYan, Zheng 			}
38625d4f98a2SYan Zheng 		}
38635d4f98a2SYan Zheng 
38643a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
38652ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
38663fd0a558SYan, Zheng 		trans = NULL;
38675d4f98a2SYan Zheng 
38685d4f98a2SYan Zheng 		if (rc->stage == MOVE_DATA_EXTENTS &&
38695d4f98a2SYan Zheng 		    (flags & BTRFS_EXTENT_FLAG_DATA)) {
38705d4f98a2SYan Zheng 			rc->found_file_extent = 1;
38710257bb82SYan, Zheng 			ret = relocate_data_extent(rc->data_inode,
38723fd0a558SYan, Zheng 						   &key, &rc->cluster);
38735d4f98a2SYan Zheng 			if (ret < 0) {
38745d4f98a2SYan Zheng 				err = ret;
38755d4f98a2SYan Zheng 				break;
38765d4f98a2SYan Zheng 			}
38775d4f98a2SYan Zheng 		}
3878f31ea088SQu Wenruo 		if (btrfs_should_cancel_balance(fs_info)) {
3879f31ea088SQu Wenruo 			err = -ECANCELED;
3880f31ea088SQu Wenruo 			break;
3881f31ea088SQu Wenruo 		}
38825d4f98a2SYan Zheng 	}
3883c87f08caSChris Mason 	if (trans && progress && err == -ENOSPC) {
388443a7e99dSNikolay Borisov 		ret = btrfs_force_chunk_alloc(trans, rc->block_group->flags);
38859689457bSShilong Wang 		if (ret == 1) {
3886c87f08caSChris Mason 			err = 0;
3887c87f08caSChris Mason 			progress = 0;
3888c87f08caSChris Mason 			goto restart;
3889c87f08caSChris Mason 		}
3890c87f08caSChris Mason 	}
38913fd0a558SYan, Zheng 
3892b3b4aa74SDavid Sterba 	btrfs_release_path(path);
389391166212SDavid Sterba 	clear_extent_bits(&rc->processed_blocks, 0, (u64)-1, EXTENT_DIRTY);
38945d4f98a2SYan Zheng 
38955d4f98a2SYan Zheng 	if (trans) {
38963a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
38972ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
38985d4f98a2SYan Zheng 	}
38995d4f98a2SYan Zheng 
39000257bb82SYan, Zheng 	if (!err) {
39013fd0a558SYan, Zheng 		ret = relocate_file_extent_cluster(rc->data_inode,
39023fd0a558SYan, Zheng 						   &rc->cluster);
39030257bb82SYan, Zheng 		if (ret < 0)
39040257bb82SYan, Zheng 			err = ret;
39050257bb82SYan, Zheng 	}
39060257bb82SYan, Zheng 
39073fd0a558SYan, Zheng 	rc->create_reloc_tree = 0;
39083fd0a558SYan, Zheng 	set_reloc_control(rc);
39090257bb82SYan, Zheng 
391013fe1bdbSQu Wenruo 	btrfs_backref_release_cache(&rc->backref_cache);
391163f018beSNikolay Borisov 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
39125d4f98a2SYan Zheng 
39137f913c7cSQu Wenruo 	/*
39147f913c7cSQu Wenruo 	 * Even in the case when the relocation is cancelled, we should all go
39157f913c7cSQu Wenruo 	 * through prepare_to_merge() and merge_reloc_roots().
39167f913c7cSQu Wenruo 	 *
39177f913c7cSQu Wenruo 	 * For error (including cancelled balance), prepare_to_merge() will
39187f913c7cSQu Wenruo 	 * mark all reloc trees orphan, then queue them for cleanup in
39197f913c7cSQu Wenruo 	 * merge_reloc_roots()
39207f913c7cSQu Wenruo 	 */
39213fd0a558SYan, Zheng 	err = prepare_to_merge(rc, err);
39225d4f98a2SYan Zheng 
39235d4f98a2SYan Zheng 	merge_reloc_roots(rc);
39245d4f98a2SYan Zheng 
39253fd0a558SYan, Zheng 	rc->merge_reloc_tree = 0;
39265d4f98a2SYan Zheng 	unset_reloc_control(rc);
392763f018beSNikolay Borisov 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
39285d4f98a2SYan Zheng 
39295d4f98a2SYan Zheng 	/* get rid of pinned extents */
39307a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
393162b99540SQu Wenruo 	if (IS_ERR(trans)) {
39323612b495STsutomu Itoh 		err = PTR_ERR(trans);
393362b99540SQu Wenruo 		goto out_free;
393462b99540SQu Wenruo 	}
39353a45bb20SJeff Mahoney 	btrfs_commit_transaction(trans);
39366217b0faSJosef Bacik out_free:
3937d2311e69SQu Wenruo 	ret = clean_dirty_subvols(rc);
3938d2311e69SQu Wenruo 	if (ret < 0 && !err)
3939d2311e69SQu Wenruo 		err = ret;
39402ff7e61eSJeff Mahoney 	btrfs_free_block_rsv(fs_info, rc->block_rsv);
39413fd0a558SYan, Zheng 	btrfs_free_path(path);
39425d4f98a2SYan Zheng 	return err;
39435d4f98a2SYan Zheng }
39445d4f98a2SYan Zheng 
39455d4f98a2SYan Zheng static int __insert_orphan_inode(struct btrfs_trans_handle *trans,
39460257bb82SYan, Zheng 				 struct btrfs_root *root, u64 objectid)
39475d4f98a2SYan Zheng {
39485d4f98a2SYan Zheng 	struct btrfs_path *path;
39495d4f98a2SYan Zheng 	struct btrfs_inode_item *item;
39505d4f98a2SYan Zheng 	struct extent_buffer *leaf;
39515d4f98a2SYan Zheng 	int ret;
39525d4f98a2SYan Zheng 
39535d4f98a2SYan Zheng 	path = btrfs_alloc_path();
39545d4f98a2SYan Zheng 	if (!path)
39555d4f98a2SYan Zheng 		return -ENOMEM;
39565d4f98a2SYan Zheng 
39575d4f98a2SYan Zheng 	ret = btrfs_insert_empty_inode(trans, root, path, objectid);
39585d4f98a2SYan Zheng 	if (ret)
39595d4f98a2SYan Zheng 		goto out;
39605d4f98a2SYan Zheng 
39615d4f98a2SYan Zheng 	leaf = path->nodes[0];
39625d4f98a2SYan Zheng 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item);
3963b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
39645d4f98a2SYan Zheng 	btrfs_set_inode_generation(leaf, item, 1);
39650257bb82SYan, Zheng 	btrfs_set_inode_size(leaf, item, 0);
39665d4f98a2SYan Zheng 	btrfs_set_inode_mode(leaf, item, S_IFREG | 0600);
39673fd0a558SYan, Zheng 	btrfs_set_inode_flags(leaf, item, BTRFS_INODE_NOCOMPRESS |
39683fd0a558SYan, Zheng 					  BTRFS_INODE_PREALLOC);
39695d4f98a2SYan Zheng 	btrfs_mark_buffer_dirty(leaf);
39705d4f98a2SYan Zheng out:
39715d4f98a2SYan Zheng 	btrfs_free_path(path);
39725d4f98a2SYan Zheng 	return ret;
39735d4f98a2SYan Zheng }
39745d4f98a2SYan Zheng 
39755d4f98a2SYan Zheng /*
39765d4f98a2SYan Zheng  * helper to create inode for data relocation.
39775d4f98a2SYan Zheng  * the inode is in data relocation tree and its link count is 0
39785d4f98a2SYan Zheng  */
39793fd0a558SYan, Zheng static noinline_for_stack
39803fd0a558SYan, Zheng struct inode *create_reloc_inode(struct btrfs_fs_info *fs_info,
398132da5386SDavid Sterba 				 struct btrfs_block_group *group)
39825d4f98a2SYan Zheng {
39835d4f98a2SYan Zheng 	struct inode *inode = NULL;
39845d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
39855d4f98a2SYan Zheng 	struct btrfs_root *root;
39865d4f98a2SYan Zheng 	struct btrfs_key key;
39874624900dSZhaolei 	u64 objectid;
39885d4f98a2SYan Zheng 	int err = 0;
39895d4f98a2SYan Zheng 
39905d4f98a2SYan Zheng 	root = read_fs_root(fs_info, BTRFS_DATA_RELOC_TREE_OBJECTID);
39915d4f98a2SYan Zheng 	if (IS_ERR(root))
39925d4f98a2SYan Zheng 		return ERR_CAST(root);
39935d4f98a2SYan Zheng 
3994a22285a6SYan, Zheng 	trans = btrfs_start_transaction(root, 6);
399576deacf0SJosef Bacik 	if (IS_ERR(trans)) {
399600246528SJosef Bacik 		btrfs_put_root(root);
39973fd0a558SYan, Zheng 		return ERR_CAST(trans);
399876deacf0SJosef Bacik 	}
39995d4f98a2SYan Zheng 
4000581bb050SLi Zefan 	err = btrfs_find_free_objectid(root, &objectid);
40015d4f98a2SYan Zheng 	if (err)
40025d4f98a2SYan Zheng 		goto out;
40035d4f98a2SYan Zheng 
40040257bb82SYan, Zheng 	err = __insert_orphan_inode(trans, root, objectid);
40055d4f98a2SYan Zheng 	BUG_ON(err);
40065d4f98a2SYan Zheng 
40075d4f98a2SYan Zheng 	key.objectid = objectid;
40085d4f98a2SYan Zheng 	key.type = BTRFS_INODE_ITEM_KEY;
40095d4f98a2SYan Zheng 	key.offset = 0;
40104c66e0d4SDavid Sterba 	inode = btrfs_iget(fs_info->sb, &key, root);
40112e19f1f9SAl Viro 	BUG_ON(IS_ERR(inode));
4012b3470b5dSDavid Sterba 	BTRFS_I(inode)->index_cnt = group->start;
40135d4f98a2SYan Zheng 
401473f2e545SNikolay Borisov 	err = btrfs_orphan_add(trans, BTRFS_I(inode));
40155d4f98a2SYan Zheng out:
401600246528SJosef Bacik 	btrfs_put_root(root);
40173a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
40182ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
40195d4f98a2SYan Zheng 	if (err) {
40205d4f98a2SYan Zheng 		if (inode)
40215d4f98a2SYan Zheng 			iput(inode);
40225d4f98a2SYan Zheng 		inode = ERR_PTR(err);
40235d4f98a2SYan Zheng 	}
40245d4f98a2SYan Zheng 	return inode;
40255d4f98a2SYan Zheng }
40265d4f98a2SYan Zheng 
4027c258d6e3SQu Wenruo static struct reloc_control *alloc_reloc_control(struct btrfs_fs_info *fs_info)
40283fd0a558SYan, Zheng {
40293fd0a558SYan, Zheng 	struct reloc_control *rc;
40303fd0a558SYan, Zheng 
40313fd0a558SYan, Zheng 	rc = kzalloc(sizeof(*rc), GFP_NOFS);
40323fd0a558SYan, Zheng 	if (!rc)
40333fd0a558SYan, Zheng 		return NULL;
40343fd0a558SYan, Zheng 
40353fd0a558SYan, Zheng 	INIT_LIST_HEAD(&rc->reloc_roots);
4036d2311e69SQu Wenruo 	INIT_LIST_HEAD(&rc->dirty_subvol_roots);
4037584fb121SQu Wenruo 	btrfs_backref_init_cache(fs_info, &rc->backref_cache, 1);
40383fd0a558SYan, Zheng 	mapping_tree_init(&rc->reloc_root_tree);
403943eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &rc->processed_blocks,
404043eb5f29SQu Wenruo 			    IO_TREE_RELOC_BLOCKS, NULL);
40413fd0a558SYan, Zheng 	return rc;
40423fd0a558SYan, Zheng }
40433fd0a558SYan, Zheng 
40441a0afa0eSJosef Bacik static void free_reloc_control(struct reloc_control *rc)
40451a0afa0eSJosef Bacik {
40461a0afa0eSJosef Bacik 	struct mapping_node *node, *tmp;
40471a0afa0eSJosef Bacik 
40481a0afa0eSJosef Bacik 	free_reloc_roots(&rc->reloc_roots);
40491a0afa0eSJosef Bacik 	rbtree_postorder_for_each_entry_safe(node, tmp,
40501a0afa0eSJosef Bacik 			&rc->reloc_root_tree.rb_root, rb_node)
40511a0afa0eSJosef Bacik 		kfree(node);
40521a0afa0eSJosef Bacik 
40531a0afa0eSJosef Bacik 	kfree(rc);
40541a0afa0eSJosef Bacik }
40551a0afa0eSJosef Bacik 
40565d4f98a2SYan Zheng /*
4057ebce0e01SAdam Borowski  * Print the block group being relocated
4058ebce0e01SAdam Borowski  */
4059ebce0e01SAdam Borowski static void describe_relocation(struct btrfs_fs_info *fs_info,
406032da5386SDavid Sterba 				struct btrfs_block_group *block_group)
4061ebce0e01SAdam Borowski {
4062f89e09cfSAnand Jain 	char buf[128] = {'\0'};
4063ebce0e01SAdam Borowski 
4064f89e09cfSAnand Jain 	btrfs_describe_block_groups(block_group->flags, buf, sizeof(buf));
4065ebce0e01SAdam Borowski 
4066ebce0e01SAdam Borowski 	btrfs_info(fs_info,
4067ebce0e01SAdam Borowski 		   "relocating block group %llu flags %s",
4068b3470b5dSDavid Sterba 		   block_group->start, buf);
4069ebce0e01SAdam Borowski }
4070ebce0e01SAdam Borowski 
4071430640e3SQu Wenruo static const char *stage_to_string(int stage)
4072430640e3SQu Wenruo {
4073430640e3SQu Wenruo 	if (stage == MOVE_DATA_EXTENTS)
4074430640e3SQu Wenruo 		return "move data extents";
4075430640e3SQu Wenruo 	if (stage == UPDATE_DATA_PTRS)
4076430640e3SQu Wenruo 		return "update data pointers";
4077430640e3SQu Wenruo 	return "unknown";
4078430640e3SQu Wenruo }
4079430640e3SQu Wenruo 
4080ebce0e01SAdam Borowski /*
40815d4f98a2SYan Zheng  * function to relocate all extents in a block group.
40825d4f98a2SYan Zheng  */
40836bccf3abSJeff Mahoney int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start)
40845d4f98a2SYan Zheng {
408532da5386SDavid Sterba 	struct btrfs_block_group *bg;
40866bccf3abSJeff Mahoney 	struct btrfs_root *extent_root = fs_info->extent_root;
40875d4f98a2SYan Zheng 	struct reloc_control *rc;
40880af3d00bSJosef Bacik 	struct inode *inode;
40890af3d00bSJosef Bacik 	struct btrfs_path *path;
40905d4f98a2SYan Zheng 	int ret;
4091f0486c68SYan, Zheng 	int rw = 0;
40925d4f98a2SYan Zheng 	int err = 0;
40935d4f98a2SYan Zheng 
4094eede2bf3SOmar Sandoval 	bg = btrfs_lookup_block_group(fs_info, group_start);
4095eede2bf3SOmar Sandoval 	if (!bg)
4096eede2bf3SOmar Sandoval 		return -ENOENT;
4097eede2bf3SOmar Sandoval 
4098eede2bf3SOmar Sandoval 	if (btrfs_pinned_by_swapfile(fs_info, bg)) {
4099eede2bf3SOmar Sandoval 		btrfs_put_block_group(bg);
4100eede2bf3SOmar Sandoval 		return -ETXTBSY;
4101eede2bf3SOmar Sandoval 	}
4102eede2bf3SOmar Sandoval 
4103c258d6e3SQu Wenruo 	rc = alloc_reloc_control(fs_info);
4104eede2bf3SOmar Sandoval 	if (!rc) {
4105eede2bf3SOmar Sandoval 		btrfs_put_block_group(bg);
41065d4f98a2SYan Zheng 		return -ENOMEM;
4107eede2bf3SOmar Sandoval 	}
41085d4f98a2SYan Zheng 
4109f0486c68SYan, Zheng 	rc->extent_root = extent_root;
4110eede2bf3SOmar Sandoval 	rc->block_group = bg;
41115d4f98a2SYan Zheng 
4112b12de528SQu Wenruo 	ret = btrfs_inc_block_group_ro(rc->block_group, true);
4113f0486c68SYan, Zheng 	if (ret) {
4114f0486c68SYan, Zheng 		err = ret;
4115f0486c68SYan, Zheng 		goto out;
4116f0486c68SYan, Zheng 	}
4117f0486c68SYan, Zheng 	rw = 1;
4118f0486c68SYan, Zheng 
41190af3d00bSJosef Bacik 	path = btrfs_alloc_path();
41200af3d00bSJosef Bacik 	if (!path) {
41210af3d00bSJosef Bacik 		err = -ENOMEM;
41220af3d00bSJosef Bacik 		goto out;
41230af3d00bSJosef Bacik 	}
41240af3d00bSJosef Bacik 
41257949f339SDavid Sterba 	inode = lookup_free_space_inode(rc->block_group, path);
41260af3d00bSJosef Bacik 	btrfs_free_path(path);
41270af3d00bSJosef Bacik 
41280af3d00bSJosef Bacik 	if (!IS_ERR(inode))
41291bbc621eSChris Mason 		ret = delete_block_group_cache(fs_info, rc->block_group, inode, 0);
41300af3d00bSJosef Bacik 	else
41310af3d00bSJosef Bacik 		ret = PTR_ERR(inode);
41320af3d00bSJosef Bacik 
41330af3d00bSJosef Bacik 	if (ret && ret != -ENOENT) {
41340af3d00bSJosef Bacik 		err = ret;
41350af3d00bSJosef Bacik 		goto out;
41360af3d00bSJosef Bacik 	}
41370af3d00bSJosef Bacik 
41385d4f98a2SYan Zheng 	rc->data_inode = create_reloc_inode(fs_info, rc->block_group);
41395d4f98a2SYan Zheng 	if (IS_ERR(rc->data_inode)) {
41405d4f98a2SYan Zheng 		err = PTR_ERR(rc->data_inode);
41415d4f98a2SYan Zheng 		rc->data_inode = NULL;
41425d4f98a2SYan Zheng 		goto out;
41435d4f98a2SYan Zheng 	}
41445d4f98a2SYan Zheng 
41450b246afaSJeff Mahoney 	describe_relocation(fs_info, rc->block_group);
41465d4f98a2SYan Zheng 
41479cfa3e34SFilipe Manana 	btrfs_wait_block_group_reservations(rc->block_group);
4148f78c436cSFilipe Manana 	btrfs_wait_nocow_writers(rc->block_group);
41496374e57aSChris Mason 	btrfs_wait_ordered_roots(fs_info, U64_MAX,
4150b3470b5dSDavid Sterba 				 rc->block_group->start,
4151b3470b5dSDavid Sterba 				 rc->block_group->length);
41525d4f98a2SYan Zheng 
41535d4f98a2SYan Zheng 	while (1) {
4154430640e3SQu Wenruo 		int finishes_stage;
4155430640e3SQu Wenruo 
415676dda93cSYan, Zheng 		mutex_lock(&fs_info->cleaner_mutex);
41575d4f98a2SYan Zheng 		ret = relocate_block_group(rc);
415876dda93cSYan, Zheng 		mutex_unlock(&fs_info->cleaner_mutex);
4159ff612ba7SJosef Bacik 		if (ret < 0)
41605d4f98a2SYan Zheng 			err = ret;
4161ff612ba7SJosef Bacik 
4162430640e3SQu Wenruo 		finishes_stage = rc->stage;
4163ff612ba7SJosef Bacik 		/*
4164ff612ba7SJosef Bacik 		 * We may have gotten ENOSPC after we already dirtied some
4165ff612ba7SJosef Bacik 		 * extents.  If writeout happens while we're relocating a
4166ff612ba7SJosef Bacik 		 * different block group we could end up hitting the
4167ff612ba7SJosef Bacik 		 * BUG_ON(rc->stage == UPDATE_DATA_PTRS) in
4168ff612ba7SJosef Bacik 		 * btrfs_reloc_cow_block.  Make sure we write everything out
4169ff612ba7SJosef Bacik 		 * properly so we don't trip over this problem, and then break
4170ff612ba7SJosef Bacik 		 * out of the loop if we hit an error.
4171ff612ba7SJosef Bacik 		 */
4172ff612ba7SJosef Bacik 		if (rc->stage == MOVE_DATA_EXTENTS && rc->found_file_extent) {
4173ff612ba7SJosef Bacik 			ret = btrfs_wait_ordered_range(rc->data_inode, 0,
4174ff612ba7SJosef Bacik 						       (u64)-1);
4175ff612ba7SJosef Bacik 			if (ret)
4176ff612ba7SJosef Bacik 				err = ret;
4177ff612ba7SJosef Bacik 			invalidate_mapping_pages(rc->data_inode->i_mapping,
4178ff612ba7SJosef Bacik 						 0, -1);
4179ff612ba7SJosef Bacik 			rc->stage = UPDATE_DATA_PTRS;
41805d4f98a2SYan Zheng 		}
41815d4f98a2SYan Zheng 
4182ff612ba7SJosef Bacik 		if (err < 0)
4183ff612ba7SJosef Bacik 			goto out;
4184ff612ba7SJosef Bacik 
41855d4f98a2SYan Zheng 		if (rc->extents_found == 0)
41865d4f98a2SYan Zheng 			break;
41875d4f98a2SYan Zheng 
4188430640e3SQu Wenruo 		btrfs_info(fs_info, "found %llu extents, stage: %s",
4189430640e3SQu Wenruo 			   rc->extents_found, stage_to_string(finishes_stage));
41905d4f98a2SYan Zheng 	}
41915d4f98a2SYan Zheng 
41925d4f98a2SYan Zheng 	WARN_ON(rc->block_group->pinned > 0);
41935d4f98a2SYan Zheng 	WARN_ON(rc->block_group->reserved > 0);
4194bf38be65SDavid Sterba 	WARN_ON(rc->block_group->used > 0);
41955d4f98a2SYan Zheng out:
4196f0486c68SYan, Zheng 	if (err && rw)
41972ff7e61eSJeff Mahoney 		btrfs_dec_block_group_ro(rc->block_group);
41985d4f98a2SYan Zheng 	iput(rc->data_inode);
41995d4f98a2SYan Zheng 	btrfs_put_block_group(rc->block_group);
42001a0afa0eSJosef Bacik 	free_reloc_control(rc);
42015d4f98a2SYan Zheng 	return err;
42025d4f98a2SYan Zheng }
42035d4f98a2SYan Zheng 
420476dda93cSYan, Zheng static noinline_for_stack int mark_garbage_root(struct btrfs_root *root)
420576dda93cSYan, Zheng {
42060b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
420776dda93cSYan, Zheng 	struct btrfs_trans_handle *trans;
420879787eaaSJeff Mahoney 	int ret, err;
420976dda93cSYan, Zheng 
42100b246afaSJeff Mahoney 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
421179787eaaSJeff Mahoney 	if (IS_ERR(trans))
421279787eaaSJeff Mahoney 		return PTR_ERR(trans);
421376dda93cSYan, Zheng 
421476dda93cSYan, Zheng 	memset(&root->root_item.drop_progress, 0,
421576dda93cSYan, Zheng 		sizeof(root->root_item.drop_progress));
421676dda93cSYan, Zheng 	root->root_item.drop_level = 0;
421776dda93cSYan, Zheng 	btrfs_set_root_refs(&root->root_item, 0);
42180b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
421976dda93cSYan, Zheng 				&root->root_key, &root->root_item);
422076dda93cSYan, Zheng 
42213a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
422279787eaaSJeff Mahoney 	if (err)
422379787eaaSJeff Mahoney 		return err;
422479787eaaSJeff Mahoney 	return ret;
422576dda93cSYan, Zheng }
422676dda93cSYan, Zheng 
42275d4f98a2SYan Zheng /*
42285d4f98a2SYan Zheng  * recover relocation interrupted by system crash.
42295d4f98a2SYan Zheng  *
42305d4f98a2SYan Zheng  * this function resumes merging reloc trees with corresponding fs trees.
42315d4f98a2SYan Zheng  * this is important for keeping the sharing of tree blocks
42325d4f98a2SYan Zheng  */
42335d4f98a2SYan Zheng int btrfs_recover_relocation(struct btrfs_root *root)
42345d4f98a2SYan Zheng {
42350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
42365d4f98a2SYan Zheng 	LIST_HEAD(reloc_roots);
42375d4f98a2SYan Zheng 	struct btrfs_key key;
42385d4f98a2SYan Zheng 	struct btrfs_root *fs_root;
42395d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
42405d4f98a2SYan Zheng 	struct btrfs_path *path;
42415d4f98a2SYan Zheng 	struct extent_buffer *leaf;
42425d4f98a2SYan Zheng 	struct reloc_control *rc = NULL;
42435d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
42445d4f98a2SYan Zheng 	int ret;
42455d4f98a2SYan Zheng 	int err = 0;
42465d4f98a2SYan Zheng 
42475d4f98a2SYan Zheng 	path = btrfs_alloc_path();
42485d4f98a2SYan Zheng 	if (!path)
42495d4f98a2SYan Zheng 		return -ENOMEM;
4250e4058b54SDavid Sterba 	path->reada = READA_BACK;
42515d4f98a2SYan Zheng 
42525d4f98a2SYan Zheng 	key.objectid = BTRFS_TREE_RELOC_OBJECTID;
42535d4f98a2SYan Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
42545d4f98a2SYan Zheng 	key.offset = (u64)-1;
42555d4f98a2SYan Zheng 
42565d4f98a2SYan Zheng 	while (1) {
42570b246afaSJeff Mahoney 		ret = btrfs_search_slot(NULL, fs_info->tree_root, &key,
42585d4f98a2SYan Zheng 					path, 0, 0);
42595d4f98a2SYan Zheng 		if (ret < 0) {
42605d4f98a2SYan Zheng 			err = ret;
42615d4f98a2SYan Zheng 			goto out;
42625d4f98a2SYan Zheng 		}
42635d4f98a2SYan Zheng 		if (ret > 0) {
42645d4f98a2SYan Zheng 			if (path->slots[0] == 0)
42655d4f98a2SYan Zheng 				break;
42665d4f98a2SYan Zheng 			path->slots[0]--;
42675d4f98a2SYan Zheng 		}
42685d4f98a2SYan Zheng 		leaf = path->nodes[0];
42695d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4270b3b4aa74SDavid Sterba 		btrfs_release_path(path);
42715d4f98a2SYan Zheng 
42725d4f98a2SYan Zheng 		if (key.objectid != BTRFS_TREE_RELOC_OBJECTID ||
42735d4f98a2SYan Zheng 		    key.type != BTRFS_ROOT_ITEM_KEY)
42745d4f98a2SYan Zheng 			break;
42755d4f98a2SYan Zheng 
42763dbf1738SJosef Bacik 		reloc_root = btrfs_read_tree_root(root, &key);
42775d4f98a2SYan Zheng 		if (IS_ERR(reloc_root)) {
42785d4f98a2SYan Zheng 			err = PTR_ERR(reloc_root);
42795d4f98a2SYan Zheng 			goto out;
42805d4f98a2SYan Zheng 		}
42815d4f98a2SYan Zheng 
42823dbf1738SJosef Bacik 		set_bit(BTRFS_ROOT_REF_COWS, &reloc_root->state);
42835d4f98a2SYan Zheng 		list_add(&reloc_root->root_list, &reloc_roots);
42845d4f98a2SYan Zheng 
42855d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
42860b246afaSJeff Mahoney 			fs_root = read_fs_root(fs_info,
42875d4f98a2SYan Zheng 					       reloc_root->root_key.offset);
42885d4f98a2SYan Zheng 			if (IS_ERR(fs_root)) {
428976dda93cSYan, Zheng 				ret = PTR_ERR(fs_root);
429076dda93cSYan, Zheng 				if (ret != -ENOENT) {
429176dda93cSYan, Zheng 					err = ret;
42925d4f98a2SYan Zheng 					goto out;
42935d4f98a2SYan Zheng 				}
429479787eaaSJeff Mahoney 				ret = mark_garbage_root(reloc_root);
429579787eaaSJeff Mahoney 				if (ret < 0) {
429679787eaaSJeff Mahoney 					err = ret;
429779787eaaSJeff Mahoney 					goto out;
429879787eaaSJeff Mahoney 				}
4299932fd26dSJosef Bacik 			} else {
430000246528SJosef Bacik 				btrfs_put_root(fs_root);
430176dda93cSYan, Zheng 			}
43025d4f98a2SYan Zheng 		}
43035d4f98a2SYan Zheng 
43045d4f98a2SYan Zheng 		if (key.offset == 0)
43055d4f98a2SYan Zheng 			break;
43065d4f98a2SYan Zheng 
43075d4f98a2SYan Zheng 		key.offset--;
43085d4f98a2SYan Zheng 	}
4309b3b4aa74SDavid Sterba 	btrfs_release_path(path);
43105d4f98a2SYan Zheng 
43115d4f98a2SYan Zheng 	if (list_empty(&reloc_roots))
43125d4f98a2SYan Zheng 		goto out;
43135d4f98a2SYan Zheng 
4314c258d6e3SQu Wenruo 	rc = alloc_reloc_control(fs_info);
43155d4f98a2SYan Zheng 	if (!rc) {
43165d4f98a2SYan Zheng 		err = -ENOMEM;
43175d4f98a2SYan Zheng 		goto out;
43185d4f98a2SYan Zheng 	}
43195d4f98a2SYan Zheng 
43200b246afaSJeff Mahoney 	rc->extent_root = fs_info->extent_root;
43215d4f98a2SYan Zheng 
43225d4f98a2SYan Zheng 	set_reloc_control(rc);
43235d4f98a2SYan Zheng 
43247a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
43253612b495STsutomu Itoh 	if (IS_ERR(trans)) {
43263612b495STsutomu Itoh 		err = PTR_ERR(trans);
4327fb2d83eeSJosef Bacik 		goto out_unset;
43283612b495STsutomu Itoh 	}
43293fd0a558SYan, Zheng 
43303fd0a558SYan, Zheng 	rc->merge_reloc_tree = 1;
43313fd0a558SYan, Zheng 
43325d4f98a2SYan Zheng 	while (!list_empty(&reloc_roots)) {
43335d4f98a2SYan Zheng 		reloc_root = list_entry(reloc_roots.next,
43345d4f98a2SYan Zheng 					struct btrfs_root, root_list);
43355d4f98a2SYan Zheng 		list_del(&reloc_root->root_list);
43365d4f98a2SYan Zheng 
43375d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) == 0) {
43385d4f98a2SYan Zheng 			list_add_tail(&reloc_root->root_list,
43395d4f98a2SYan Zheng 				      &rc->reloc_roots);
43405d4f98a2SYan Zheng 			continue;
43415d4f98a2SYan Zheng 		}
43425d4f98a2SYan Zheng 
43430b246afaSJeff Mahoney 		fs_root = read_fs_root(fs_info, reloc_root->root_key.offset);
434479787eaaSJeff Mahoney 		if (IS_ERR(fs_root)) {
434579787eaaSJeff Mahoney 			err = PTR_ERR(fs_root);
4346ca1aa281SJosef Bacik 			list_add_tail(&reloc_root->root_list, &reloc_roots);
43471402d17dSXiyu Yang 			btrfs_end_transaction(trans);
4348fb2d83eeSJosef Bacik 			goto out_unset;
434979787eaaSJeff Mahoney 		}
43505d4f98a2SYan Zheng 
4351ffd7b339SJeff Mahoney 		err = __add_reloc_root(reloc_root);
435279787eaaSJeff Mahoney 		BUG_ON(err < 0); /* -ENOMEM or logic error */
4353f44deb74SJosef Bacik 		fs_root->reloc_root = btrfs_grab_root(reloc_root);
435400246528SJosef Bacik 		btrfs_put_root(fs_root);
43555d4f98a2SYan Zheng 	}
43565d4f98a2SYan Zheng 
43573a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
435879787eaaSJeff Mahoney 	if (err)
4359fb2d83eeSJosef Bacik 		goto out_unset;
43605d4f98a2SYan Zheng 
43615d4f98a2SYan Zheng 	merge_reloc_roots(rc);
43625d4f98a2SYan Zheng 
43635d4f98a2SYan Zheng 	unset_reloc_control(rc);
43645d4f98a2SYan Zheng 
43657a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
436662b99540SQu Wenruo 	if (IS_ERR(trans)) {
43673612b495STsutomu Itoh 		err = PTR_ERR(trans);
43686217b0faSJosef Bacik 		goto out_clean;
436962b99540SQu Wenruo 	}
43703a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
43716217b0faSJosef Bacik out_clean:
4372d2311e69SQu Wenruo 	ret = clean_dirty_subvols(rc);
4373d2311e69SQu Wenruo 	if (ret < 0 && !err)
4374d2311e69SQu Wenruo 		err = ret;
4375fb2d83eeSJosef Bacik out_unset:
4376fb2d83eeSJosef Bacik 	unset_reloc_control(rc);
43771a0afa0eSJosef Bacik 	free_reloc_control(rc);
43783612b495STsutomu Itoh out:
4379aca1bba6SLiu Bo 	if (!list_empty(&reloc_roots))
4380aca1bba6SLiu Bo 		free_reloc_roots(&reloc_roots);
4381aca1bba6SLiu Bo 
43825d4f98a2SYan Zheng 	btrfs_free_path(path);
43835d4f98a2SYan Zheng 
43845d4f98a2SYan Zheng 	if (err == 0) {
43855d4f98a2SYan Zheng 		/* cleanup orphan inode in data relocation tree */
43860b246afaSJeff Mahoney 		fs_root = read_fs_root(fs_info, BTRFS_DATA_RELOC_TREE_OBJECTID);
4387932fd26dSJosef Bacik 		if (IS_ERR(fs_root)) {
43885d4f98a2SYan Zheng 			err = PTR_ERR(fs_root);
4389932fd26dSJosef Bacik 		} else {
439066b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(fs_root);
439100246528SJosef Bacik 			btrfs_put_root(fs_root);
4392932fd26dSJosef Bacik 		}
4393932fd26dSJosef Bacik 	}
43945d4f98a2SYan Zheng 	return err;
43955d4f98a2SYan Zheng }
43965d4f98a2SYan Zheng 
43975d4f98a2SYan Zheng /*
43985d4f98a2SYan Zheng  * helper to add ordered checksum for data relocation.
43995d4f98a2SYan Zheng  *
44005d4f98a2SYan Zheng  * cloning checksum properly handles the nodatasum extents.
44015d4f98a2SYan Zheng  * it also saves CPU time to re-calculate the checksum.
44025d4f98a2SYan Zheng  */
44035d4f98a2SYan Zheng int btrfs_reloc_clone_csums(struct inode *inode, u64 file_pos, u64 len)
44045d4f98a2SYan Zheng {
44050b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
44065d4f98a2SYan Zheng 	struct btrfs_ordered_sum *sums;
44075d4f98a2SYan Zheng 	struct btrfs_ordered_extent *ordered;
44085d4f98a2SYan Zheng 	int ret;
44095d4f98a2SYan Zheng 	u64 disk_bytenr;
44104577b014SJosef Bacik 	u64 new_bytenr;
44115d4f98a2SYan Zheng 	LIST_HEAD(list);
44125d4f98a2SYan Zheng 
44135d4f98a2SYan Zheng 	ordered = btrfs_lookup_ordered_extent(inode, file_pos);
4414bffe633eSOmar Sandoval 	BUG_ON(ordered->file_offset != file_pos || ordered->num_bytes != len);
44155d4f98a2SYan Zheng 
44165d4f98a2SYan Zheng 	disk_bytenr = file_pos + BTRFS_I(inode)->index_cnt;
44170b246afaSJeff Mahoney 	ret = btrfs_lookup_csums_range(fs_info->csum_root, disk_bytenr,
4418a2de733cSArne Jansen 				       disk_bytenr + len - 1, &list, 0);
441979787eaaSJeff Mahoney 	if (ret)
442079787eaaSJeff Mahoney 		goto out;
44215d4f98a2SYan Zheng 
44225d4f98a2SYan Zheng 	while (!list_empty(&list)) {
44235d4f98a2SYan Zheng 		sums = list_entry(list.next, struct btrfs_ordered_sum, list);
44245d4f98a2SYan Zheng 		list_del_init(&sums->list);
44255d4f98a2SYan Zheng 
44264577b014SJosef Bacik 		/*
44274577b014SJosef Bacik 		 * We need to offset the new_bytenr based on where the csum is.
44284577b014SJosef Bacik 		 * We need to do this because we will read in entire prealloc
44294577b014SJosef Bacik 		 * extents but we may have written to say the middle of the
44304577b014SJosef Bacik 		 * prealloc extent, so we need to make sure the csum goes with
44314577b014SJosef Bacik 		 * the right disk offset.
44324577b014SJosef Bacik 		 *
44334577b014SJosef Bacik 		 * We can do this because the data reloc inode refers strictly
44344577b014SJosef Bacik 		 * to the on disk bytes, so we don't have to worry about
44354577b014SJosef Bacik 		 * disk_len vs real len like with real inodes since it's all
44364577b014SJosef Bacik 		 * disk length.
44374577b014SJosef Bacik 		 */
4438bffe633eSOmar Sandoval 		new_bytenr = ordered->disk_bytenr + sums->bytenr - disk_bytenr;
44394577b014SJosef Bacik 		sums->bytenr = new_bytenr;
44405d4f98a2SYan Zheng 
4441f9756261SNikolay Borisov 		btrfs_add_ordered_sum(ordered, sums);
44425d4f98a2SYan Zheng 	}
444379787eaaSJeff Mahoney out:
44445d4f98a2SYan Zheng 	btrfs_put_ordered_extent(ordered);
4445411fc6bcSAndi Kleen 	return ret;
44465d4f98a2SYan Zheng }
44473fd0a558SYan, Zheng 
444883d4cfd4SJosef Bacik int btrfs_reloc_cow_block(struct btrfs_trans_handle *trans,
44493fd0a558SYan, Zheng 			  struct btrfs_root *root, struct extent_buffer *buf,
44503fd0a558SYan, Zheng 			  struct extent_buffer *cow)
44513fd0a558SYan, Zheng {
44520b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
44533fd0a558SYan, Zheng 	struct reloc_control *rc;
4454a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
44553fd0a558SYan, Zheng 	int first_cow = 0;
44563fd0a558SYan, Zheng 	int level;
445783d4cfd4SJosef Bacik 	int ret = 0;
44583fd0a558SYan, Zheng 
44590b246afaSJeff Mahoney 	rc = fs_info->reloc_ctl;
44603fd0a558SYan, Zheng 	if (!rc)
446183d4cfd4SJosef Bacik 		return 0;
44623fd0a558SYan, Zheng 
44633fd0a558SYan, Zheng 	BUG_ON(rc->stage == UPDATE_DATA_PTRS &&
44643fd0a558SYan, Zheng 	       root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID);
44653fd0a558SYan, Zheng 
44663fd0a558SYan, Zheng 	level = btrfs_header_level(buf);
44673fd0a558SYan, Zheng 	if (btrfs_header_generation(buf) <=
44683fd0a558SYan, Zheng 	    btrfs_root_last_snapshot(&root->root_item))
44693fd0a558SYan, Zheng 		first_cow = 1;
44703fd0a558SYan, Zheng 
44713fd0a558SYan, Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID &&
44723fd0a558SYan, Zheng 	    rc->create_reloc_tree) {
44733fd0a558SYan, Zheng 		WARN_ON(!first_cow && level == 0);
44743fd0a558SYan, Zheng 
44753fd0a558SYan, Zheng 		node = rc->backref_cache.path[level];
44763fd0a558SYan, Zheng 		BUG_ON(node->bytenr != buf->start &&
44773fd0a558SYan, Zheng 		       node->new_bytenr != buf->start);
44783fd0a558SYan, Zheng 
4479b0fe7078SQu Wenruo 		btrfs_backref_drop_node_buffer(node);
448067439dadSDavid Sterba 		atomic_inc(&cow->refs);
44813fd0a558SYan, Zheng 		node->eb = cow;
44823fd0a558SYan, Zheng 		node->new_bytenr = cow->start;
44833fd0a558SYan, Zheng 
44843fd0a558SYan, Zheng 		if (!node->pending) {
44853fd0a558SYan, Zheng 			list_move_tail(&node->list,
44863fd0a558SYan, Zheng 				       &rc->backref_cache.pending[level]);
44873fd0a558SYan, Zheng 			node->pending = 1;
44883fd0a558SYan, Zheng 		}
44893fd0a558SYan, Zheng 
44903fd0a558SYan, Zheng 		if (first_cow)
44919569cc20SQu Wenruo 			mark_block_processed(rc, node);
44923fd0a558SYan, Zheng 
44933fd0a558SYan, Zheng 		if (first_cow && level > 0)
44943fd0a558SYan, Zheng 			rc->nodes_relocated += buf->len;
44953fd0a558SYan, Zheng 	}
44963fd0a558SYan, Zheng 
449783d4cfd4SJosef Bacik 	if (level == 0 && first_cow && rc->stage == UPDATE_DATA_PTRS)
44983fd0a558SYan, Zheng 		ret = replace_file_extents(trans, rc, root, cow);
449983d4cfd4SJosef Bacik 	return ret;
45003fd0a558SYan, Zheng }
45013fd0a558SYan, Zheng 
45023fd0a558SYan, Zheng /*
45033fd0a558SYan, Zheng  * called before creating snapshot. it calculates metadata reservation
450401327610SNicholas D Steeves  * required for relocating tree blocks in the snapshot
45053fd0a558SYan, Zheng  */
4506147d256eSZhaolei void btrfs_reloc_pre_snapshot(struct btrfs_pending_snapshot *pending,
45073fd0a558SYan, Zheng 			      u64 *bytes_to_reserve)
45083fd0a558SYan, Zheng {
450910995c04SQu Wenruo 	struct btrfs_root *root = pending->root;
451010995c04SQu Wenruo 	struct reloc_control *rc = root->fs_info->reloc_ctl;
45113fd0a558SYan, Zheng 
45126282675eSQu Wenruo 	if (!rc || !have_reloc_root(root))
45133fd0a558SYan, Zheng 		return;
45143fd0a558SYan, Zheng 
45153fd0a558SYan, Zheng 	if (!rc->merge_reloc_tree)
45163fd0a558SYan, Zheng 		return;
45173fd0a558SYan, Zheng 
45183fd0a558SYan, Zheng 	root = root->reloc_root;
45193fd0a558SYan, Zheng 	BUG_ON(btrfs_root_refs(&root->root_item) == 0);
45203fd0a558SYan, Zheng 	/*
45213fd0a558SYan, Zheng 	 * relocation is in the stage of merging trees. the space
45223fd0a558SYan, Zheng 	 * used by merging a reloc tree is twice the size of
45233fd0a558SYan, Zheng 	 * relocated tree nodes in the worst case. half for cowing
45243fd0a558SYan, Zheng 	 * the reloc tree, half for cowing the fs tree. the space
45253fd0a558SYan, Zheng 	 * used by cowing the reloc tree will be freed after the
45263fd0a558SYan, Zheng 	 * tree is dropped. if we create snapshot, cowing the fs
45273fd0a558SYan, Zheng 	 * tree may use more space than it frees. so we need
45283fd0a558SYan, Zheng 	 * reserve extra space.
45293fd0a558SYan, Zheng 	 */
45303fd0a558SYan, Zheng 	*bytes_to_reserve += rc->nodes_relocated;
45313fd0a558SYan, Zheng }
45323fd0a558SYan, Zheng 
45333fd0a558SYan, Zheng /*
45343fd0a558SYan, Zheng  * called after snapshot is created. migrate block reservation
45353fd0a558SYan, Zheng  * and create reloc root for the newly created snapshot
4536f44deb74SJosef Bacik  *
4537f44deb74SJosef Bacik  * This is similar to btrfs_init_reloc_root(), we come out of here with two
4538f44deb74SJosef Bacik  * references held on the reloc_root, one for root->reloc_root and one for
4539f44deb74SJosef Bacik  * rc->reloc_roots.
45403fd0a558SYan, Zheng  */
454149b25e05SJeff Mahoney int btrfs_reloc_post_snapshot(struct btrfs_trans_handle *trans,
45423fd0a558SYan, Zheng 			       struct btrfs_pending_snapshot *pending)
45433fd0a558SYan, Zheng {
45443fd0a558SYan, Zheng 	struct btrfs_root *root = pending->root;
45453fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
45463fd0a558SYan, Zheng 	struct btrfs_root *new_root;
454710995c04SQu Wenruo 	struct reloc_control *rc = root->fs_info->reloc_ctl;
45483fd0a558SYan, Zheng 	int ret;
45493fd0a558SYan, Zheng 
45506282675eSQu Wenruo 	if (!rc || !have_reloc_root(root))
455149b25e05SJeff Mahoney 		return 0;
45523fd0a558SYan, Zheng 
45533fd0a558SYan, Zheng 	rc = root->fs_info->reloc_ctl;
45543fd0a558SYan, Zheng 	rc->merging_rsv_size += rc->nodes_relocated;
45553fd0a558SYan, Zheng 
45563fd0a558SYan, Zheng 	if (rc->merge_reloc_tree) {
45573fd0a558SYan, Zheng 		ret = btrfs_block_rsv_migrate(&pending->block_rsv,
45583fd0a558SYan, Zheng 					      rc->block_rsv,
45593a584174SLu Fengqi 					      rc->nodes_relocated, true);
456049b25e05SJeff Mahoney 		if (ret)
456149b25e05SJeff Mahoney 			return ret;
45623fd0a558SYan, Zheng 	}
45633fd0a558SYan, Zheng 
45643fd0a558SYan, Zheng 	new_root = pending->snap;
45653fd0a558SYan, Zheng 	reloc_root = create_reloc_root(trans, root->reloc_root,
45663fd0a558SYan, Zheng 				       new_root->root_key.objectid);
456749b25e05SJeff Mahoney 	if (IS_ERR(reloc_root))
456849b25e05SJeff Mahoney 		return PTR_ERR(reloc_root);
45693fd0a558SYan, Zheng 
4570ffd7b339SJeff Mahoney 	ret = __add_reloc_root(reloc_root);
4571ffd7b339SJeff Mahoney 	BUG_ON(ret < 0);
4572f44deb74SJosef Bacik 	new_root->reloc_root = btrfs_grab_root(reloc_root);
45733fd0a558SYan, Zheng 
457449b25e05SJeff Mahoney 	if (rc->create_reloc_tree)
45753fd0a558SYan, Zheng 		ret = clone_backref_node(trans, rc, root, reloc_root);
457649b25e05SJeff Mahoney 	return ret;
45773fd0a558SYan, Zheng }
4578