xref: /openbmc/linux/fs/btrfs/relocation.c (revision 55465730)
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
308*55465730SQu Wenruo  * from no reloc root.  But btrfs_should_ignore_reloc_root() below is a
309*55465730SQu Wenruo  * special case.
3106282675eSQu Wenruo  */
3116282675eSQu Wenruo static bool have_reloc_root(struct btrfs_root *root)
3126282675eSQu Wenruo {
3136282675eSQu Wenruo 	if (reloc_root_is_dead(root))
3146282675eSQu Wenruo 		return false;
3156282675eSQu Wenruo 	if (!root->reloc_root)
3166282675eSQu Wenruo 		return false;
3176282675eSQu Wenruo 	return true;
3186282675eSQu Wenruo }
319f2a97a9dSDavid Sterba 
320*55465730SQu Wenruo int btrfs_should_ignore_reloc_root(struct btrfs_root *root)
3213fd0a558SYan, Zheng {
3223fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
3233fd0a558SYan, Zheng 
32427cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
3253fd0a558SYan, Zheng 		return 0;
3263fd0a558SYan, Zheng 
3276282675eSQu Wenruo 	/* This root has been merged with its reloc tree, we can ignore it */
3286282675eSQu Wenruo 	if (reloc_root_is_dead(root))
3296282675eSQu Wenruo 		return 1;
3306282675eSQu Wenruo 
3313fd0a558SYan, Zheng 	reloc_root = root->reloc_root;
3323fd0a558SYan, Zheng 	if (!reloc_root)
3333fd0a558SYan, Zheng 		return 0;
3343fd0a558SYan, Zheng 
3354d4225fcSJosef Bacik 	if (btrfs_header_generation(reloc_root->commit_root) ==
3364d4225fcSJosef Bacik 	    root->fs_info->running_transaction->transid)
3373fd0a558SYan, Zheng 		return 0;
3383fd0a558SYan, Zheng 	/*
3393fd0a558SYan, Zheng 	 * if there is reloc tree and it was created in previous
3403fd0a558SYan, Zheng 	 * transaction backref lookup can find the reloc tree,
3413fd0a558SYan, Zheng 	 * so backref node for the fs tree root is useless for
3423fd0a558SYan, Zheng 	 * relocation.
3433fd0a558SYan, Zheng 	 */
3443fd0a558SYan, Zheng 	return 1;
3453fd0a558SYan, Zheng }
346*55465730SQu Wenruo 
3475d4f98a2SYan Zheng /*
3485d4f98a2SYan Zheng  * find reloc tree by address of tree root
3495d4f98a2SYan Zheng  */
3502433bea5SQu Wenruo struct btrfs_root *find_reloc_root(struct btrfs_fs_info *fs_info, u64 bytenr)
3515d4f98a2SYan Zheng {
3522433bea5SQu Wenruo 	struct reloc_control *rc = fs_info->reloc_ctl;
3535d4f98a2SYan Zheng 	struct rb_node *rb_node;
3545d4f98a2SYan Zheng 	struct mapping_node *node;
3555d4f98a2SYan Zheng 	struct btrfs_root *root = NULL;
3565d4f98a2SYan Zheng 
3572433bea5SQu Wenruo 	ASSERT(rc);
3585d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
359e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root, bytenr);
3605d4f98a2SYan Zheng 	if (rb_node) {
3615d4f98a2SYan Zheng 		node = rb_entry(rb_node, struct mapping_node, rb_node);
3625d4f98a2SYan Zheng 		root = (struct btrfs_root *)node->data;
3635d4f98a2SYan Zheng 	}
3645d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
36500246528SJosef Bacik 	return btrfs_grab_root(root);
3665d4f98a2SYan Zheng }
3675d4f98a2SYan Zheng 
3685d4f98a2SYan Zheng static struct btrfs_root *read_fs_root(struct btrfs_fs_info *fs_info,
3695d4f98a2SYan Zheng 					u64 root_objectid)
3705d4f98a2SYan Zheng {
3715d4f98a2SYan Zheng 	struct btrfs_key key;
3725d4f98a2SYan Zheng 
3735d4f98a2SYan Zheng 	key.objectid = root_objectid;
3745d4f98a2SYan Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
3755d4f98a2SYan Zheng 	key.offset = (u64)-1;
3765d4f98a2SYan Zheng 
377bc44d7c4SJosef Bacik 	return btrfs_get_fs_root(fs_info, &key, false);
3785d4f98a2SYan Zheng }
3795d4f98a2SYan Zheng 
3805d4f98a2SYan Zheng /*
3814007ea87SQu Wenruo  * Handle direct tree backref
3824007ea87SQu Wenruo  *
3834007ea87SQu Wenruo  * Direct tree backref means, the backref item shows its parent bytenr
3844007ea87SQu Wenruo  * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
3854007ea87SQu Wenruo  *
3864007ea87SQu Wenruo  * @ref_key:	The converted backref key.
3874007ea87SQu Wenruo  *		For keyed backref, it's the item key.
3884007ea87SQu Wenruo  *		For inlined backref, objectid is the bytenr,
3894007ea87SQu Wenruo  *		type is btrfs_inline_ref_type, offset is
3904007ea87SQu Wenruo  *		btrfs_inline_ref_offset.
3914007ea87SQu Wenruo  */
392a26195a5SQu Wenruo static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
3934007ea87SQu Wenruo 				      struct btrfs_key *ref_key,
394a26195a5SQu Wenruo 				      struct btrfs_backref_node *cur)
3954007ea87SQu Wenruo {
396a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
397a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
3984007ea87SQu Wenruo 	struct rb_node *rb_node;
3994007ea87SQu Wenruo 
4004007ea87SQu Wenruo 	ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
4014007ea87SQu Wenruo 
4024007ea87SQu Wenruo 	/* Only reloc root uses backref pointing to itself */
4034007ea87SQu Wenruo 	if (ref_key->objectid == ref_key->offset) {
4044007ea87SQu Wenruo 		struct btrfs_root *root;
4054007ea87SQu Wenruo 
4064007ea87SQu Wenruo 		cur->is_reloc_root = 1;
4074007ea87SQu Wenruo 		/* Only reloc backref cache cares about a specific root */
4084007ea87SQu Wenruo 		if (cache->is_reloc) {
4094007ea87SQu Wenruo 			root = find_reloc_root(cache->fs_info, cur->bytenr);
4104007ea87SQu Wenruo 			if (WARN_ON(!root))
4114007ea87SQu Wenruo 				return -ENOENT;
4124007ea87SQu Wenruo 			cur->root = root;
4134007ea87SQu Wenruo 		} else {
4144007ea87SQu Wenruo 			/*
4154007ea87SQu Wenruo 			 * For generic purpose backref cache, reloc root node
4164007ea87SQu Wenruo 			 * is useless.
4174007ea87SQu Wenruo 			 */
4184007ea87SQu Wenruo 			list_add(&cur->list, &cache->useless_node);
4194007ea87SQu Wenruo 		}
4204007ea87SQu Wenruo 		return 0;
4214007ea87SQu Wenruo 	}
4224007ea87SQu Wenruo 
42347254d07SQu Wenruo 	edge = btrfs_backref_alloc_edge(cache);
4244007ea87SQu Wenruo 	if (!edge)
4254007ea87SQu Wenruo 		return -ENOMEM;
4264007ea87SQu Wenruo 
427e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
4284007ea87SQu Wenruo 	if (!rb_node) {
4294007ea87SQu Wenruo 		/* Parent node not yet cached */
430b1818dabSQu Wenruo 		upper = btrfs_backref_alloc_node(cache, ref_key->offset,
4310304f2d8SQu Wenruo 					   cur->level + 1);
4324007ea87SQu Wenruo 		if (!upper) {
433741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
4344007ea87SQu Wenruo 			return -ENOMEM;
4354007ea87SQu Wenruo 		}
4364007ea87SQu Wenruo 
4374007ea87SQu Wenruo 		/*
4384007ea87SQu Wenruo 		 *  Backrefs for the upper level block isn't cached, add the
4394007ea87SQu Wenruo 		 *  block to pending list
4404007ea87SQu Wenruo 		 */
4414007ea87SQu Wenruo 		list_add_tail(&edge->list[UPPER], &cache->pending_edge);
4424007ea87SQu Wenruo 	} else {
4434007ea87SQu Wenruo 		/* Parent node already cached */
444a26195a5SQu Wenruo 		upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
4454007ea87SQu Wenruo 		ASSERT(upper->checked);
4464007ea87SQu Wenruo 		INIT_LIST_HEAD(&edge->list[UPPER]);
4474007ea87SQu Wenruo 	}
448f39911e5SQu Wenruo 	btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
4494007ea87SQu Wenruo 	return 0;
4504007ea87SQu Wenruo }
4514007ea87SQu Wenruo 
4524007ea87SQu Wenruo /*
4534d81ea8bSQu Wenruo  * Handle indirect tree backref
4544d81ea8bSQu Wenruo  *
4554d81ea8bSQu Wenruo  * Indirect tree backref means, we only know which tree the node belongs to.
4564d81ea8bSQu Wenruo  * We still need to do a tree search to find out the parents. This is for
4574d81ea8bSQu Wenruo  * TREE_BLOCK_REF backref (keyed or inlined).
4584d81ea8bSQu Wenruo  *
4594d81ea8bSQu Wenruo  * @ref_key:	The same as @ref_key in  handle_direct_tree_backref()
4604d81ea8bSQu Wenruo  * @tree_key:	The first key of this tree block.
4614d81ea8bSQu Wenruo  * @path:	A clean (released) path, to avoid allocating path everytime
4624d81ea8bSQu Wenruo  *		the function get called.
4634d81ea8bSQu Wenruo  */
464a26195a5SQu Wenruo static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
4654d81ea8bSQu Wenruo 					struct btrfs_path *path,
4664d81ea8bSQu Wenruo 					struct btrfs_key *ref_key,
4674d81ea8bSQu Wenruo 					struct btrfs_key *tree_key,
468a26195a5SQu Wenruo 					struct btrfs_backref_node *cur)
4694d81ea8bSQu Wenruo {
4704d81ea8bSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
471a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
472a26195a5SQu Wenruo 	struct btrfs_backref_node *lower;
473a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
4744d81ea8bSQu Wenruo 	struct extent_buffer *eb;
4754d81ea8bSQu Wenruo 	struct btrfs_root *root;
4764d81ea8bSQu Wenruo 	struct rb_node *rb_node;
4774d81ea8bSQu Wenruo 	int level;
4784d81ea8bSQu Wenruo 	bool need_check = true;
4794d81ea8bSQu Wenruo 	int ret;
4804d81ea8bSQu Wenruo 
4814d81ea8bSQu Wenruo 	root = read_fs_root(fs_info, ref_key->offset);
4824d81ea8bSQu Wenruo 	if (IS_ERR(root))
4834d81ea8bSQu Wenruo 		return PTR_ERR(root);
4844d81ea8bSQu Wenruo 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4854d81ea8bSQu Wenruo 		cur->cowonly = 1;
4864d81ea8bSQu Wenruo 
4874d81ea8bSQu Wenruo 	if (btrfs_root_level(&root->root_item) == cur->level) {
4884d81ea8bSQu Wenruo 		/* Tree root */
4894d81ea8bSQu Wenruo 		ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
490*55465730SQu Wenruo 		if (btrfs_should_ignore_reloc_root(root)) {
4914d81ea8bSQu Wenruo 			btrfs_put_root(root);
4924d81ea8bSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
4934d81ea8bSQu Wenruo 		} else {
4944d81ea8bSQu Wenruo 			cur->root = root;
4954d81ea8bSQu Wenruo 		}
4964d81ea8bSQu Wenruo 		return 0;
4974d81ea8bSQu Wenruo 	}
4984d81ea8bSQu Wenruo 
4994d81ea8bSQu Wenruo 	level = cur->level + 1;
5004d81ea8bSQu Wenruo 
5014d81ea8bSQu Wenruo 	/* Search the tree to find parent blocks referring to the block */
5024d81ea8bSQu Wenruo 	path->search_commit_root = 1;
5034d81ea8bSQu Wenruo 	path->skip_locking = 1;
5044d81ea8bSQu Wenruo 	path->lowest_level = level;
5054d81ea8bSQu Wenruo 	ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
5064d81ea8bSQu Wenruo 	path->lowest_level = 0;
5074d81ea8bSQu Wenruo 	if (ret < 0) {
5084d81ea8bSQu Wenruo 		btrfs_put_root(root);
5094d81ea8bSQu Wenruo 		return ret;
5104d81ea8bSQu Wenruo 	}
5114d81ea8bSQu Wenruo 	if (ret > 0 && path->slots[level] > 0)
5124d81ea8bSQu Wenruo 		path->slots[level]--;
5134d81ea8bSQu Wenruo 
5144d81ea8bSQu Wenruo 	eb = path->nodes[level];
5154d81ea8bSQu Wenruo 	if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
5164d81ea8bSQu Wenruo 		btrfs_err(fs_info,
5174d81ea8bSQu Wenruo "couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
5184d81ea8bSQu Wenruo 			  cur->bytenr, level - 1, root->root_key.objectid,
5194d81ea8bSQu Wenruo 			  tree_key->objectid, tree_key->type, tree_key->offset);
5204d81ea8bSQu Wenruo 		btrfs_put_root(root);
5214d81ea8bSQu Wenruo 		ret = -ENOENT;
5224d81ea8bSQu Wenruo 		goto out;
5234d81ea8bSQu Wenruo 	}
5244d81ea8bSQu Wenruo 	lower = cur;
5254d81ea8bSQu Wenruo 
5264d81ea8bSQu Wenruo 	/* Add all nodes and edges in the path */
5274d81ea8bSQu Wenruo 	for (; level < BTRFS_MAX_LEVEL; level++) {
5284d81ea8bSQu Wenruo 		if (!path->nodes[level]) {
5294d81ea8bSQu Wenruo 			ASSERT(btrfs_root_bytenr(&root->root_item) ==
5304d81ea8bSQu Wenruo 			       lower->bytenr);
531*55465730SQu Wenruo 			if (btrfs_should_ignore_reloc_root(root)) {
5324d81ea8bSQu Wenruo 				btrfs_put_root(root);
5334d81ea8bSQu Wenruo 				list_add(&lower->list, &cache->useless_node);
5344d81ea8bSQu Wenruo 			} else {
5354d81ea8bSQu Wenruo 				lower->root = root;
5364d81ea8bSQu Wenruo 			}
5374d81ea8bSQu Wenruo 			break;
5384d81ea8bSQu Wenruo 		}
5394d81ea8bSQu Wenruo 
54047254d07SQu Wenruo 		edge = btrfs_backref_alloc_edge(cache);
5414d81ea8bSQu Wenruo 		if (!edge) {
5424d81ea8bSQu Wenruo 			btrfs_put_root(root);
5434d81ea8bSQu Wenruo 			ret = -ENOMEM;
5444d81ea8bSQu Wenruo 			goto out;
5454d81ea8bSQu Wenruo 		}
5464d81ea8bSQu Wenruo 
5474d81ea8bSQu Wenruo 		eb = path->nodes[level];
548e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root, eb->start);
5494d81ea8bSQu Wenruo 		if (!rb_node) {
550b1818dabSQu Wenruo 			upper = btrfs_backref_alloc_node(cache, eb->start,
5510304f2d8SQu Wenruo 							 lower->level + 1);
5524d81ea8bSQu Wenruo 			if (!upper) {
5534d81ea8bSQu Wenruo 				btrfs_put_root(root);
554741188d3SQu Wenruo 				btrfs_backref_free_edge(cache, edge);
5554d81ea8bSQu Wenruo 				ret = -ENOMEM;
5564d81ea8bSQu Wenruo 				goto out;
5574d81ea8bSQu Wenruo 			}
5584d81ea8bSQu Wenruo 			upper->owner = btrfs_header_owner(eb);
5594d81ea8bSQu Wenruo 			if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
5604d81ea8bSQu Wenruo 				upper->cowonly = 1;
5614d81ea8bSQu Wenruo 
5624d81ea8bSQu Wenruo 			/*
5634d81ea8bSQu Wenruo 			 * If we know the block isn't shared we can avoid
5644d81ea8bSQu Wenruo 			 * checking its backrefs.
5654d81ea8bSQu Wenruo 			 */
5664d81ea8bSQu Wenruo 			if (btrfs_block_can_be_shared(root, eb))
5674d81ea8bSQu Wenruo 				upper->checked = 0;
5684d81ea8bSQu Wenruo 			else
5694d81ea8bSQu Wenruo 				upper->checked = 1;
5704d81ea8bSQu Wenruo 
5714d81ea8bSQu Wenruo 			/*
5724d81ea8bSQu Wenruo 			 * Add the block to pending list if we need to check its
5734d81ea8bSQu Wenruo 			 * backrefs, we only do this once while walking up a
5744d81ea8bSQu Wenruo 			 * tree as we will catch anything else later on.
5754d81ea8bSQu Wenruo 			 */
5764d81ea8bSQu Wenruo 			if (!upper->checked && need_check) {
5774d81ea8bSQu Wenruo 				need_check = false;
5784d81ea8bSQu Wenruo 				list_add_tail(&edge->list[UPPER],
5794d81ea8bSQu Wenruo 					      &cache->pending_edge);
5804d81ea8bSQu Wenruo 			} else {
5814d81ea8bSQu Wenruo 				if (upper->checked)
5824d81ea8bSQu Wenruo 					need_check = true;
5834d81ea8bSQu Wenruo 				INIT_LIST_HEAD(&edge->list[UPPER]);
5844d81ea8bSQu Wenruo 			}
5854d81ea8bSQu Wenruo 		} else {
586a26195a5SQu Wenruo 			upper = rb_entry(rb_node, struct btrfs_backref_node,
587a26195a5SQu Wenruo 					 rb_node);
5884d81ea8bSQu Wenruo 			ASSERT(upper->checked);
5894d81ea8bSQu Wenruo 			INIT_LIST_HEAD(&edge->list[UPPER]);
5904d81ea8bSQu Wenruo 			if (!upper->owner)
5914d81ea8bSQu Wenruo 				upper->owner = btrfs_header_owner(eb);
5924d81ea8bSQu Wenruo 		}
593f39911e5SQu Wenruo 		btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
5944d81ea8bSQu Wenruo 
5954d81ea8bSQu Wenruo 		if (rb_node) {
5964d81ea8bSQu Wenruo 			btrfs_put_root(root);
5974d81ea8bSQu Wenruo 			break;
5984d81ea8bSQu Wenruo 		}
5994d81ea8bSQu Wenruo 		lower = upper;
6004d81ea8bSQu Wenruo 		upper = NULL;
6014d81ea8bSQu Wenruo 	}
6024d81ea8bSQu Wenruo out:
6034d81ea8bSQu Wenruo 	btrfs_release_path(path);
6044d81ea8bSQu Wenruo 	return ret;
6054d81ea8bSQu Wenruo }
6064d81ea8bSQu Wenruo 
607a26195a5SQu Wenruo static int handle_one_tree_block(struct btrfs_backref_cache *cache,
608e7d571c7SQu Wenruo 				 struct btrfs_path *path,
609e7d571c7SQu Wenruo 				 struct btrfs_backref_iter *iter,
6105d4f98a2SYan Zheng 				 struct btrfs_key *node_key,
611a26195a5SQu Wenruo 				 struct btrfs_backref_node *cur)
6125d4f98a2SYan Zheng {
613e7d571c7SQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
614a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
615a26195a5SQu Wenruo 	struct btrfs_backref_node *exist;
6165d4f98a2SYan Zheng 	int ret;
6175d4f98a2SYan Zheng 
61871f572a9SQu Wenruo 	ret = btrfs_backref_iter_start(iter, cur->bytenr);
619e7d571c7SQu Wenruo 	if (ret < 0)
620e7d571c7SQu Wenruo 		return ret;
62171f572a9SQu Wenruo 	/*
62271f572a9SQu Wenruo 	 * We skip the first btrfs_tree_block_info, as we don't use the key
62371f572a9SQu Wenruo 	 * stored in it, but fetch it from the tree block
62471f572a9SQu Wenruo 	 */
62571f572a9SQu Wenruo 	if (btrfs_backref_has_tree_block_info(iter)) {
62671f572a9SQu Wenruo 		ret = btrfs_backref_iter_next(iter);
627e7d571c7SQu Wenruo 		if (ret < 0)
62871f572a9SQu Wenruo 			goto out;
62971f572a9SQu Wenruo 		/* No extra backref? This means the tree block is corrupted */
63071f572a9SQu Wenruo 		if (ret > 0) {
631e7d571c7SQu Wenruo 			ret = -EUCLEAN;
63271f572a9SQu Wenruo 			goto out;
63371f572a9SQu Wenruo 		}
63471f572a9SQu Wenruo 	}
6355d4f98a2SYan Zheng 	WARN_ON(cur->checked);
6365d4f98a2SYan Zheng 	if (!list_empty(&cur->upper)) {
6375d4f98a2SYan Zheng 		/*
63870f23fd6SJustin P. Mattock 		 * the backref was added previously when processing
6395d4f98a2SYan Zheng 		 * backref of type BTRFS_TREE_BLOCK_REF_KEY
6405d4f98a2SYan Zheng 		 */
64175bfb9afSJosef Bacik 		ASSERT(list_is_singular(&cur->upper));
642a26195a5SQu Wenruo 		edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
6435d4f98a2SYan Zheng 				  list[LOWER]);
64475bfb9afSJosef Bacik 		ASSERT(list_empty(&edge->list[UPPER]));
6455d4f98a2SYan Zheng 		exist = edge->node[UPPER];
6465d4f98a2SYan Zheng 		/*
6475d4f98a2SYan Zheng 		 * add the upper level block to pending list if we need
6485d4f98a2SYan Zheng 		 * check its backrefs
6495d4f98a2SYan Zheng 		 */
6505d4f98a2SYan Zheng 		if (!exist->checked)
65184780289SQu Wenruo 			list_add_tail(&edge->list[UPPER], &cache->pending_edge);
6525d4f98a2SYan Zheng 	} else {
6535d4f98a2SYan Zheng 		exist = NULL;
6545d4f98a2SYan Zheng 	}
6555d4f98a2SYan Zheng 
65671f572a9SQu Wenruo 	for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
65771f572a9SQu Wenruo 		struct extent_buffer *eb;
65871f572a9SQu Wenruo 		struct btrfs_key key;
6593de28d57SLiu Bo 		int type;
66071f572a9SQu Wenruo 
66171f572a9SQu Wenruo 		cond_resched();
66271f572a9SQu Wenruo 		eb = btrfs_backref_get_eb(iter);
66371f572a9SQu Wenruo 
66471f572a9SQu Wenruo 		key.objectid = iter->bytenr;
66571f572a9SQu Wenruo 		if (btrfs_backref_iter_is_inline_ref(iter)) {
66671f572a9SQu Wenruo 			struct btrfs_extent_inline_ref *iref;
66771f572a9SQu Wenruo 
66871f572a9SQu Wenruo 			/* update key for inline back ref */
66971f572a9SQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
67071f572a9SQu Wenruo 				((unsigned long)iter->cur_ptr);
6713de28d57SLiu Bo 			type = btrfs_get_extent_inline_ref_type(eb, iref,
6723de28d57SLiu Bo 							BTRFS_REF_TYPE_BLOCK);
6733de28d57SLiu Bo 			if (type == BTRFS_REF_TYPE_INVALID) {
674e7d571c7SQu Wenruo 				ret = -EUCLEAN;
6753de28d57SLiu Bo 				goto out;
6763de28d57SLiu Bo 			}
6773de28d57SLiu Bo 			key.type = type;
6785d4f98a2SYan Zheng 			key.offset = btrfs_extent_inline_ref_offset(eb, iref);
67971f572a9SQu Wenruo 		} else {
68071f572a9SQu Wenruo 			key.type = iter->cur_key.type;
68171f572a9SQu Wenruo 			key.offset = iter->cur_key.offset;
6825d4f98a2SYan Zheng 		}
6835d4f98a2SYan Zheng 
684fa6ac715SQu Wenruo 		/*
685fa6ac715SQu Wenruo 		 * Parent node found and matches current inline ref, no need to
686fa6ac715SQu Wenruo 		 * rebuild this node for this inline ref.
687fa6ac715SQu Wenruo 		 */
6885d4f98a2SYan Zheng 		if (exist &&
6895d4f98a2SYan Zheng 		    ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
6905d4f98a2SYan Zheng 		      exist->owner == key.offset) ||
6915d4f98a2SYan Zheng 		     (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
6925d4f98a2SYan Zheng 		      exist->bytenr == key.offset))) {
6935d4f98a2SYan Zheng 			exist = NULL;
69471f572a9SQu Wenruo 			continue;
6955d4f98a2SYan Zheng 		}
6965d4f98a2SYan Zheng 
697fa6ac715SQu Wenruo 		/* SHARED_BLOCK_REF means key.offset is the parent bytenr */
6985d4f98a2SYan Zheng 		if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
6994007ea87SQu Wenruo 			ret = handle_direct_tree_backref(cache, &key, cur);
700e7d571c7SQu Wenruo 			if (ret < 0)
7012433bea5SQu Wenruo 				goto out;
70271f572a9SQu Wenruo 			continue;
7036d8ff4e4SDavid Sterba 		} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
704e7d571c7SQu Wenruo 			ret = -EINVAL;
705e7d571c7SQu Wenruo 			btrfs_print_v0_err(fs_info);
706e7d571c7SQu Wenruo 			btrfs_handle_fs_error(fs_info, ret, NULL);
707ba3c2b19SNikolay Borisov 			goto out;
7085d4f98a2SYan Zheng 		} else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
70971f572a9SQu Wenruo 			continue;
7105d4f98a2SYan Zheng 		}
7115d4f98a2SYan Zheng 
712fa6ac715SQu Wenruo 		/*
713fa6ac715SQu Wenruo 		 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
714fa6ac715SQu Wenruo 		 * means the root objectid. We need to search the tree to get
715fa6ac715SQu Wenruo 		 * its parent bytenr.
716fa6ac715SQu Wenruo 		 */
7174d81ea8bSQu Wenruo 		ret = handle_indirect_tree_backref(cache, path, &key, node_key,
7184d81ea8bSQu Wenruo 						   cur);
719e7d571c7SQu Wenruo 		if (ret < 0)
72071f572a9SQu Wenruo 			goto out;
7215d4f98a2SYan Zheng 	}
72271f572a9SQu Wenruo 	ret = 0;
7235d4f98a2SYan Zheng 	cur->checked = 1;
7245d4f98a2SYan Zheng 	WARN_ON(exist);
725e7d571c7SQu Wenruo out:
726e7d571c7SQu Wenruo 	btrfs_backref_iter_release(iter);
727e7d571c7SQu Wenruo 	return ret;
728e7d571c7SQu Wenruo }
7295d4f98a2SYan Zheng 
730e7d571c7SQu Wenruo /*
7311f872924SQu Wenruo  * In handle_one_tree_backref(), we have only linked the lower node to the edge,
7321f872924SQu Wenruo  * but the upper node hasn't been linked to the edge.
733a26195a5SQu Wenruo  * This means we can only iterate through btrfs_backref_node::upper to reach
734a26195a5SQu Wenruo  * parent edges, but not through btrfs_backref_node::lower to reach children
735a26195a5SQu Wenruo  * edges.
7361f872924SQu Wenruo  *
737a26195a5SQu Wenruo  * This function will finish the btrfs_backref_node::lower to related edges,
738a26195a5SQu Wenruo  * so that backref cache can be bi-directionally iterated.
7391f872924SQu Wenruo  *
7401f872924SQu Wenruo  * Also, this will add the nodes to backref cache for the next run.
7411f872924SQu Wenruo  */
742a26195a5SQu Wenruo static int finish_upper_links(struct btrfs_backref_cache *cache,
743a26195a5SQu Wenruo 			      struct btrfs_backref_node *start)
7441f872924SQu Wenruo {
7451f872924SQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
746a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
7471f872924SQu Wenruo 	struct rb_node *rb_node;
7481f872924SQu Wenruo 	LIST_HEAD(pending_edge);
7491f872924SQu Wenruo 
7501f872924SQu Wenruo 	ASSERT(start->checked);
7511f872924SQu Wenruo 
7521f872924SQu Wenruo 	/* Insert this node to cache if it's not COW-only */
7531f872924SQu Wenruo 	if (!start->cowonly) {
754e9a28dc5SQu Wenruo 		rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
7551f872924SQu Wenruo 					   &start->rb_node);
7561f872924SQu Wenruo 		if (rb_node)
757982c92cbSQu Wenruo 			btrfs_backref_panic(cache->fs_info, start->bytenr,
758982c92cbSQu Wenruo 					    -EEXIST);
7591f872924SQu Wenruo 		list_add_tail(&start->lower, &cache->leaves);
7601f872924SQu Wenruo 	}
7611f872924SQu Wenruo 
7621f872924SQu Wenruo 	/*
7631f872924SQu Wenruo 	 * Use breadth first search to iterate all related edges.
7641f872924SQu Wenruo 	 *
7651f872924SQu Wenruo 	 * The starting points are all the edges of this node
7661f872924SQu Wenruo 	 */
7671f872924SQu Wenruo 	list_for_each_entry(edge, &start->upper, list[LOWER])
7681f872924SQu Wenruo 		list_add_tail(&edge->list[UPPER], &pending_edge);
7691f872924SQu Wenruo 
7701f872924SQu Wenruo 	while (!list_empty(&pending_edge)) {
771a26195a5SQu Wenruo 		struct btrfs_backref_node *upper;
772a26195a5SQu Wenruo 		struct btrfs_backref_node *lower;
7731f872924SQu Wenruo 		struct rb_node *rb_node;
7741f872924SQu Wenruo 
775a26195a5SQu Wenruo 		edge = list_first_entry(&pending_edge,
776a26195a5SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
7771f872924SQu Wenruo 		list_del_init(&edge->list[UPPER]);
7781f872924SQu Wenruo 		upper = edge->node[UPPER];
7791f872924SQu Wenruo 		lower = edge->node[LOWER];
7801f872924SQu Wenruo 
7811f872924SQu Wenruo 		/* Parent is detached, no need to keep any edges */
7821f872924SQu Wenruo 		if (upper->detached) {
7831f872924SQu Wenruo 			list_del(&edge->list[LOWER]);
784741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
7851f872924SQu Wenruo 
7861f872924SQu Wenruo 			/* Lower node is orphan, queue for cleanup */
7871f872924SQu Wenruo 			if (list_empty(&lower->upper))
7881f872924SQu Wenruo 				list_add(&lower->list, useless_node);
7891f872924SQu Wenruo 			continue;
7901f872924SQu Wenruo 		}
7911f872924SQu Wenruo 
7921f872924SQu Wenruo 		/*
7931f872924SQu Wenruo 		 * All new nodes added in current build_backref_tree() haven't
7941f872924SQu Wenruo 		 * been linked to the cache rb tree.
7951f872924SQu Wenruo 		 * So if we have upper->rb_node populated, this means a cache
7961f872924SQu Wenruo 		 * hit. We only need to link the edge, as @upper and all its
7971f872924SQu Wenruo 		 * parent have already been linked.
7981f872924SQu Wenruo 		 */
7991f872924SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node)) {
8001f872924SQu Wenruo 			if (upper->lowest) {
8011f872924SQu Wenruo 				list_del_init(&upper->lower);
8021f872924SQu Wenruo 				upper->lowest = 0;
8031f872924SQu Wenruo 			}
8041f872924SQu Wenruo 
8051f872924SQu Wenruo 			list_add_tail(&edge->list[UPPER], &upper->lower);
8061f872924SQu Wenruo 			continue;
8071f872924SQu Wenruo 		}
8081f872924SQu Wenruo 
8091f872924SQu Wenruo 		/* Sanity check, we shouldn't have any unchecked nodes */
8101f872924SQu Wenruo 		if (!upper->checked) {
8111f872924SQu Wenruo 			ASSERT(0);
8121f872924SQu Wenruo 			return -EUCLEAN;
8131f872924SQu Wenruo 		}
8141f872924SQu Wenruo 
8151f872924SQu Wenruo 		/* Sanity check, COW-only node has non-COW-only parent */
8161f872924SQu Wenruo 		if (start->cowonly != upper->cowonly) {
8171f872924SQu Wenruo 			ASSERT(0);
8181f872924SQu Wenruo 			return -EUCLEAN;
8191f872924SQu Wenruo 		}
8201f872924SQu Wenruo 
8211f872924SQu Wenruo 		/* Only cache non-COW-only (subvolume trees) tree blocks */
8221f872924SQu Wenruo 		if (!upper->cowonly) {
823e9a28dc5SQu Wenruo 			rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
8241f872924SQu Wenruo 						   &upper->rb_node);
8251f872924SQu Wenruo 			if (rb_node) {
826982c92cbSQu Wenruo 				btrfs_backref_panic(cache->fs_info,
827982c92cbSQu Wenruo 						upper->bytenr, -EEXIST);
8281f872924SQu Wenruo 				return -EUCLEAN;
8291f872924SQu Wenruo 			}
8301f872924SQu Wenruo 		}
8311f872924SQu Wenruo 
8321f872924SQu Wenruo 		list_add_tail(&edge->list[UPPER], &upper->lower);
8331f872924SQu Wenruo 
8341f872924SQu Wenruo 		/*
8351f872924SQu Wenruo 		 * Also queue all the parent edges of this uncached node to
8361f872924SQu Wenruo 		 * finish the upper linkage
8371f872924SQu Wenruo 		 */
8381f872924SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
8391f872924SQu Wenruo 			list_add_tail(&edge->list[UPPER], &pending_edge);
8401f872924SQu Wenruo 	}
8411f872924SQu Wenruo 	return 0;
8421f872924SQu Wenruo }
8431f872924SQu Wenruo 
8441f872924SQu Wenruo /*
84529db137bSQu Wenruo  * For useless nodes, do two major clean ups:
84629db137bSQu Wenruo  *
84729db137bSQu Wenruo  * - Cleanup the children edges and nodes
84829db137bSQu Wenruo  *   If child node is also orphan (no parent) during cleanup, then the child
84929db137bSQu Wenruo  *   node will also be cleaned up.
85029db137bSQu Wenruo  *
85129db137bSQu Wenruo  * - Freeing up leaves (level 0), keeps nodes detached
85229db137bSQu Wenruo  *   For nodes, the node is still cached as "detached"
85329db137bSQu Wenruo  *
85429db137bSQu Wenruo  * Return false if @node is not in the @useless_nodes list.
85529db137bSQu Wenruo  * Return true if @node is in the @useless_nodes list.
85629db137bSQu Wenruo  */
85729db137bSQu Wenruo static bool handle_useless_nodes(struct reloc_control *rc,
858a26195a5SQu Wenruo 				 struct btrfs_backref_node *node)
85929db137bSQu Wenruo {
860a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
86129db137bSQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
86229db137bSQu Wenruo 	bool ret = false;
86329db137bSQu Wenruo 
86429db137bSQu Wenruo 	while (!list_empty(useless_node)) {
865a26195a5SQu Wenruo 		struct btrfs_backref_node *cur;
86629db137bSQu Wenruo 
867a26195a5SQu Wenruo 		cur = list_first_entry(useless_node, struct btrfs_backref_node,
86829db137bSQu Wenruo 				 list);
86929db137bSQu Wenruo 		list_del_init(&cur->list);
87029db137bSQu Wenruo 
87129db137bSQu Wenruo 		/* Only tree root nodes can be added to @useless_nodes */
87229db137bSQu Wenruo 		ASSERT(list_empty(&cur->upper));
87329db137bSQu Wenruo 
87429db137bSQu Wenruo 		if (cur == node)
87529db137bSQu Wenruo 			ret = true;
87629db137bSQu Wenruo 
87729db137bSQu Wenruo 		/* The node is the lowest node */
87829db137bSQu Wenruo 		if (cur->lowest) {
87929db137bSQu Wenruo 			list_del_init(&cur->lower);
88029db137bSQu Wenruo 			cur->lowest = 0;
88129db137bSQu Wenruo 		}
88229db137bSQu Wenruo 
88329db137bSQu Wenruo 		/* Cleanup the lower edges */
88429db137bSQu Wenruo 		while (!list_empty(&cur->lower)) {
885a26195a5SQu Wenruo 			struct btrfs_backref_edge *edge;
886a26195a5SQu Wenruo 			struct btrfs_backref_node *lower;
88729db137bSQu Wenruo 
88829db137bSQu Wenruo 			edge = list_entry(cur->lower.next,
889a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[UPPER]);
89029db137bSQu Wenruo 			list_del(&edge->list[UPPER]);
89129db137bSQu Wenruo 			list_del(&edge->list[LOWER]);
89229db137bSQu Wenruo 			lower = edge->node[LOWER];
893741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
89429db137bSQu Wenruo 
89529db137bSQu Wenruo 			/* Child node is also orphan, queue for cleanup */
89629db137bSQu Wenruo 			if (list_empty(&lower->upper))
89729db137bSQu Wenruo 				list_add(&lower->list, useless_node);
89829db137bSQu Wenruo 		}
89929db137bSQu Wenruo 		/* Mark this block processed for relocation */
90029db137bSQu Wenruo 		mark_block_processed(rc, cur);
90129db137bSQu Wenruo 
90229db137bSQu Wenruo 		/*
90329db137bSQu Wenruo 		 * Backref nodes for tree leaves are deleted from the cache.
90429db137bSQu Wenruo 		 * Backref nodes for upper level tree blocks are left in the
90529db137bSQu Wenruo 		 * cache to avoid unnecessary backref lookup.
90629db137bSQu Wenruo 		 */
90729db137bSQu Wenruo 		if (cur->level > 0) {
90829db137bSQu Wenruo 			list_add(&cur->list, &cache->detached);
90929db137bSQu Wenruo 			cur->detached = 1;
91029db137bSQu Wenruo 		} else {
91129db137bSQu Wenruo 			rb_erase(&cur->rb_node, &cache->rb_root);
912741188d3SQu Wenruo 			btrfs_backref_free_node(cache, cur);
91329db137bSQu Wenruo 		}
91429db137bSQu Wenruo 	}
91529db137bSQu Wenruo 	return ret;
91629db137bSQu Wenruo }
91729db137bSQu Wenruo 
91829db137bSQu Wenruo /*
919e7d571c7SQu Wenruo  * Build backref tree for a given tree block. Root of the backref tree
920e7d571c7SQu Wenruo  * corresponds the tree block, leaves of the backref tree correspond roots of
921e7d571c7SQu Wenruo  * b-trees that reference the tree block.
922e7d571c7SQu Wenruo  *
923e7d571c7SQu Wenruo  * The basic idea of this function is check backrefs of a given block to find
924e7d571c7SQu Wenruo  * upper level blocks that reference the block, and then check backrefs of
925e7d571c7SQu Wenruo  * these upper level blocks recursively. The recursion stops when tree root is
926e7d571c7SQu Wenruo  * reached or backrefs for the block is cached.
927e7d571c7SQu Wenruo  *
928e7d571c7SQu Wenruo  * NOTE: if we find that backrefs for a block are cached, we know backrefs for
929e7d571c7SQu Wenruo  * all upper level blocks that directly/indirectly reference the block are also
930e7d571c7SQu Wenruo  * cached.
931e7d571c7SQu Wenruo  */
932a26195a5SQu Wenruo static noinline_for_stack struct btrfs_backref_node *build_backref_tree(
933e7d571c7SQu Wenruo 			struct reloc_control *rc, struct btrfs_key *node_key,
934e7d571c7SQu Wenruo 			int level, u64 bytenr)
935e7d571c7SQu Wenruo {
936e7d571c7SQu Wenruo 	struct btrfs_backref_iter *iter;
937a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
938e7d571c7SQu Wenruo 	/* For searching parent of TREE_BLOCK_REF */
939e7d571c7SQu Wenruo 	struct btrfs_path *path;
940a26195a5SQu Wenruo 	struct btrfs_backref_node *cur;
941a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
942a26195a5SQu Wenruo 	struct btrfs_backref_node *lower;
943a26195a5SQu Wenruo 	struct btrfs_backref_node *node = NULL;
944a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
945e7d571c7SQu Wenruo 	int ret;
946e7d571c7SQu Wenruo 	int err = 0;
947e7d571c7SQu Wenruo 
948e7d571c7SQu Wenruo 	iter = btrfs_backref_iter_alloc(rc->extent_root->fs_info, GFP_NOFS);
949e7d571c7SQu Wenruo 	if (!iter)
950e7d571c7SQu Wenruo 		return ERR_PTR(-ENOMEM);
951e7d571c7SQu Wenruo 	path = btrfs_alloc_path();
952e7d571c7SQu Wenruo 	if (!path) {
953e7d571c7SQu Wenruo 		err = -ENOMEM;
954e7d571c7SQu Wenruo 		goto out;
955e7d571c7SQu Wenruo 	}
956e7d571c7SQu Wenruo 
957b1818dabSQu Wenruo 	node = btrfs_backref_alloc_node(cache, bytenr, level);
958e7d571c7SQu Wenruo 	if (!node) {
959e7d571c7SQu Wenruo 		err = -ENOMEM;
960e7d571c7SQu Wenruo 		goto out;
961e7d571c7SQu Wenruo 	}
962e7d571c7SQu Wenruo 
963e7d571c7SQu Wenruo 	node->lowest = 1;
964e7d571c7SQu Wenruo 	cur = node;
965e7d571c7SQu Wenruo 
966e7d571c7SQu Wenruo 	/* Breadth-first search to build backref cache */
967e7d571c7SQu Wenruo 	do {
968e7d571c7SQu Wenruo 		ret = handle_one_tree_block(cache, path, iter, node_key, cur);
969e7d571c7SQu Wenruo 		if (ret < 0) {
970e7d571c7SQu Wenruo 			err = ret;
971e7d571c7SQu Wenruo 			goto out;
972e7d571c7SQu Wenruo 		}
973e7d571c7SQu Wenruo 		edge = list_first_entry_or_null(&cache->pending_edge,
974a26195a5SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
975e7d571c7SQu Wenruo 		/*
976e7d571c7SQu Wenruo 		 * The pending list isn't empty, take the first block to
977e7d571c7SQu Wenruo 		 * process
978e7d571c7SQu Wenruo 		 */
979e7d571c7SQu Wenruo 		if (edge) {
9805d4f98a2SYan Zheng 			list_del_init(&edge->list[UPPER]);
9815d4f98a2SYan Zheng 			cur = edge->node[UPPER];
9825d4f98a2SYan Zheng 		}
983e7d571c7SQu Wenruo 	} while (edge);
9845d4f98a2SYan Zheng 
9851f872924SQu Wenruo 	/* Finish the upper linkage of newly added edges/nodes */
9861f872924SQu Wenruo 	ret = finish_upper_links(cache, node);
9871f872924SQu Wenruo 	if (ret < 0) {
9881f872924SQu Wenruo 		err = ret;
98975bfb9afSJosef Bacik 		goto out;
99075bfb9afSJosef Bacik 	}
99175bfb9afSJosef Bacik 
99229db137bSQu Wenruo 	if (handle_useless_nodes(rc, node))
9933fd0a558SYan, Zheng 		node = NULL;
9945d4f98a2SYan Zheng out:
99571f572a9SQu Wenruo 	btrfs_backref_iter_free(iter);
99671f572a9SQu Wenruo 	btrfs_free_path(path);
9975d4f98a2SYan Zheng 	if (err) {
99884780289SQu Wenruo 		while (!list_empty(&cache->useless_node)) {
99984780289SQu Wenruo 			lower = list_first_entry(&cache->useless_node,
1000a26195a5SQu Wenruo 					   struct btrfs_backref_node, list);
100175bfb9afSJosef Bacik 			list_del_init(&lower->list);
10023fd0a558SYan, Zheng 		}
100384780289SQu Wenruo 		while (!list_empty(&cache->pending_edge)) {
100484780289SQu Wenruo 			edge = list_first_entry(&cache->pending_edge,
1005a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[UPPER]);
100675bfb9afSJosef Bacik 			list_del(&edge->list[UPPER]);
10073fd0a558SYan, Zheng 			list_del(&edge->list[LOWER]);
100875bfb9afSJosef Bacik 			lower = edge->node[LOWER];
10095d4f98a2SYan Zheng 			upper = edge->node[UPPER];
1010741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
101175bfb9afSJosef Bacik 
101275bfb9afSJosef Bacik 			/*
101375bfb9afSJosef Bacik 			 * Lower is no longer linked to any upper backref nodes
101475bfb9afSJosef Bacik 			 * and isn't in the cache, we can free it ourselves.
101575bfb9afSJosef Bacik 			 */
101675bfb9afSJosef Bacik 			if (list_empty(&lower->upper) &&
101775bfb9afSJosef Bacik 			    RB_EMPTY_NODE(&lower->rb_node))
101884780289SQu Wenruo 				list_add(&lower->list, &cache->useless_node);
101975bfb9afSJosef Bacik 
102075bfb9afSJosef Bacik 			if (!RB_EMPTY_NODE(&upper->rb_node))
102175bfb9afSJosef Bacik 				continue;
102275bfb9afSJosef Bacik 
102301327610SNicholas D Steeves 			/* Add this guy's upper edges to the list to process */
102475bfb9afSJosef Bacik 			list_for_each_entry(edge, &upper->upper, list[LOWER])
102584780289SQu Wenruo 				list_add_tail(&edge->list[UPPER],
102684780289SQu Wenruo 					      &cache->pending_edge);
102775bfb9afSJosef Bacik 			if (list_empty(&upper->upper))
102884780289SQu Wenruo 				list_add(&upper->list, &cache->useless_node);
102975bfb9afSJosef Bacik 		}
103075bfb9afSJosef Bacik 
103184780289SQu Wenruo 		while (!list_empty(&cache->useless_node)) {
103284780289SQu Wenruo 			lower = list_first_entry(&cache->useless_node,
1033a26195a5SQu Wenruo 					   struct btrfs_backref_node, list);
103475bfb9afSJosef Bacik 			list_del_init(&lower->list);
10350fd8c3daSLiu Bo 			if (lower == node)
10360fd8c3daSLiu Bo 				node = NULL;
1037741188d3SQu Wenruo 			btrfs_backref_free_node(cache, lower);
10385d4f98a2SYan Zheng 		}
10390fd8c3daSLiu Bo 
1040023acb07SQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
104184780289SQu Wenruo 		ASSERT(list_empty(&cache->useless_node) &&
104284780289SQu Wenruo 		       list_empty(&cache->pending_edge));
10435d4f98a2SYan Zheng 		return ERR_PTR(err);
10445d4f98a2SYan Zheng 	}
104575bfb9afSJosef Bacik 	ASSERT(!node || !node->detached);
104684780289SQu Wenruo 	ASSERT(list_empty(&cache->useless_node) &&
104784780289SQu Wenruo 	       list_empty(&cache->pending_edge));
10485d4f98a2SYan Zheng 	return node;
10495d4f98a2SYan Zheng }
10505d4f98a2SYan Zheng 
10515d4f98a2SYan Zheng /*
10523fd0a558SYan, Zheng  * helper to add backref node for the newly created snapshot.
10533fd0a558SYan, Zheng  * the backref node is created by cloning backref node that
10543fd0a558SYan, Zheng  * corresponds to root of source tree
10553fd0a558SYan, Zheng  */
10563fd0a558SYan, Zheng static int clone_backref_node(struct btrfs_trans_handle *trans,
10573fd0a558SYan, Zheng 			      struct reloc_control *rc,
10583fd0a558SYan, Zheng 			      struct btrfs_root *src,
10593fd0a558SYan, Zheng 			      struct btrfs_root *dest)
10603fd0a558SYan, Zheng {
10613fd0a558SYan, Zheng 	struct btrfs_root *reloc_root = src->reloc_root;
1062a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
1063a26195a5SQu Wenruo 	struct btrfs_backref_node *node = NULL;
1064a26195a5SQu Wenruo 	struct btrfs_backref_node *new_node;
1065a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
1066a26195a5SQu Wenruo 	struct btrfs_backref_edge *new_edge;
10673fd0a558SYan, Zheng 	struct rb_node *rb_node;
10683fd0a558SYan, Zheng 
10693fd0a558SYan, Zheng 	if (cache->last_trans > 0)
10703fd0a558SYan, Zheng 		update_backref_cache(trans, cache);
10713fd0a558SYan, Zheng 
1072e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, src->commit_root->start);
10733fd0a558SYan, Zheng 	if (rb_node) {
1074a26195a5SQu Wenruo 		node = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
10753fd0a558SYan, Zheng 		if (node->detached)
10763fd0a558SYan, Zheng 			node = NULL;
10773fd0a558SYan, Zheng 		else
10783fd0a558SYan, Zheng 			BUG_ON(node->new_bytenr != reloc_root->node->start);
10793fd0a558SYan, Zheng 	}
10803fd0a558SYan, Zheng 
10813fd0a558SYan, Zheng 	if (!node) {
1082e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root,
10833fd0a558SYan, Zheng 					   reloc_root->commit_root->start);
10843fd0a558SYan, Zheng 		if (rb_node) {
1085a26195a5SQu Wenruo 			node = rb_entry(rb_node, struct btrfs_backref_node,
10863fd0a558SYan, Zheng 					rb_node);
10873fd0a558SYan, Zheng 			BUG_ON(node->detached);
10883fd0a558SYan, Zheng 		}
10893fd0a558SYan, Zheng 	}
10903fd0a558SYan, Zheng 
10913fd0a558SYan, Zheng 	if (!node)
10923fd0a558SYan, Zheng 		return 0;
10933fd0a558SYan, Zheng 
1094b1818dabSQu Wenruo 	new_node = btrfs_backref_alloc_node(cache, dest->node->start,
1095b1818dabSQu Wenruo 					    node->level);
10963fd0a558SYan, Zheng 	if (!new_node)
10973fd0a558SYan, Zheng 		return -ENOMEM;
10983fd0a558SYan, Zheng 
10993fd0a558SYan, Zheng 	new_node->lowest = node->lowest;
11006848ad64SYan, Zheng 	new_node->checked = 1;
110100246528SJosef Bacik 	new_node->root = btrfs_grab_root(dest);
11020b530bc5SJosef Bacik 	ASSERT(new_node->root);
11033fd0a558SYan, Zheng 
11043fd0a558SYan, Zheng 	if (!node->lowest) {
11053fd0a558SYan, Zheng 		list_for_each_entry(edge, &node->lower, list[UPPER]) {
110647254d07SQu Wenruo 			new_edge = btrfs_backref_alloc_edge(cache);
11073fd0a558SYan, Zheng 			if (!new_edge)
11083fd0a558SYan, Zheng 				goto fail;
11093fd0a558SYan, Zheng 
1110f39911e5SQu Wenruo 			btrfs_backref_link_edge(new_edge, edge->node[LOWER],
1111f39911e5SQu Wenruo 						new_node, LINK_UPPER);
11123fd0a558SYan, Zheng 		}
111376b9e23dSMiao Xie 	} else {
111476b9e23dSMiao Xie 		list_add_tail(&new_node->lower, &cache->leaves);
11153fd0a558SYan, Zheng 	}
11163fd0a558SYan, Zheng 
1117e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&cache->rb_root, new_node->bytenr,
11183fd0a558SYan, Zheng 				   &new_node->rb_node);
111943c04fb1SJeff Mahoney 	if (rb_node)
1120982c92cbSQu Wenruo 		btrfs_backref_panic(trans->fs_info, new_node->bytenr, -EEXIST);
11213fd0a558SYan, Zheng 
11223fd0a558SYan, Zheng 	if (!new_node->lowest) {
11233fd0a558SYan, Zheng 		list_for_each_entry(new_edge, &new_node->lower, list[UPPER]) {
11243fd0a558SYan, Zheng 			list_add_tail(&new_edge->list[LOWER],
11253fd0a558SYan, Zheng 				      &new_edge->node[LOWER]->upper);
11263fd0a558SYan, Zheng 		}
11273fd0a558SYan, Zheng 	}
11283fd0a558SYan, Zheng 	return 0;
11293fd0a558SYan, Zheng fail:
11303fd0a558SYan, Zheng 	while (!list_empty(&new_node->lower)) {
11313fd0a558SYan, Zheng 		new_edge = list_entry(new_node->lower.next,
1132a26195a5SQu Wenruo 				      struct btrfs_backref_edge, list[UPPER]);
11333fd0a558SYan, Zheng 		list_del(&new_edge->list[UPPER]);
1134741188d3SQu Wenruo 		btrfs_backref_free_edge(cache, new_edge);
11353fd0a558SYan, Zheng 	}
1136741188d3SQu Wenruo 	btrfs_backref_free_node(cache, new_node);
11373fd0a558SYan, Zheng 	return -ENOMEM;
11383fd0a558SYan, Zheng }
11393fd0a558SYan, Zheng 
11403fd0a558SYan, Zheng /*
11415d4f98a2SYan Zheng  * helper to add 'address of tree root -> reloc tree' mapping
11425d4f98a2SYan Zheng  */
1143ffd7b339SJeff Mahoney static int __must_check __add_reloc_root(struct btrfs_root *root)
11445d4f98a2SYan Zheng {
11450b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11465d4f98a2SYan Zheng 	struct rb_node *rb_node;
11475d4f98a2SYan Zheng 	struct mapping_node *node;
11480b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
11495d4f98a2SYan Zheng 
11505d4f98a2SYan Zheng 	node = kmalloc(sizeof(*node), GFP_NOFS);
1151ffd7b339SJeff Mahoney 	if (!node)
1152ffd7b339SJeff Mahoney 		return -ENOMEM;
11535d4f98a2SYan Zheng 
1154ea287ab1SJosef Bacik 	node->bytenr = root->commit_root->start;
11555d4f98a2SYan Zheng 	node->data = root;
11565d4f98a2SYan Zheng 
11575d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
1158e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
11595d4f98a2SYan Zheng 				   node->bytenr, &node->rb_node);
11605d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
1161ffd7b339SJeff Mahoney 	if (rb_node) {
11620b246afaSJeff Mahoney 		btrfs_panic(fs_info, -EEXIST,
11635d163e0eSJeff Mahoney 			    "Duplicate root found for start=%llu while inserting into relocation tree",
11645d163e0eSJeff Mahoney 			    node->bytenr);
1165ffd7b339SJeff Mahoney 	}
11665d4f98a2SYan Zheng 
11675d4f98a2SYan Zheng 	list_add_tail(&root->root_list, &rc->reloc_roots);
11685d4f98a2SYan Zheng 	return 0;
11695d4f98a2SYan Zheng }
11705d4f98a2SYan Zheng 
11715d4f98a2SYan Zheng /*
1172c974c464SWang Shilong  * helper to delete the 'address of tree root -> reloc tree'
11735d4f98a2SYan Zheng  * mapping
11745d4f98a2SYan Zheng  */
1175c974c464SWang Shilong static void __del_reloc_root(struct btrfs_root *root)
11765d4f98a2SYan Zheng {
11770b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11785d4f98a2SYan Zheng 	struct rb_node *rb_node;
11795d4f98a2SYan Zheng 	struct mapping_node *node = NULL;
11800b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
1181f44deb74SJosef Bacik 	bool put_ref = false;
11825d4f98a2SYan Zheng 
118365c6e82bSQu Wenruo 	if (rc && root->node) {
11845d4f98a2SYan Zheng 		spin_lock(&rc->reloc_root_tree.lock);
1185e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
1186ea287ab1SJosef Bacik 					   root->commit_root->start);
1187c974c464SWang Shilong 		if (rb_node) {
1188c974c464SWang Shilong 			node = rb_entry(rb_node, struct mapping_node, rb_node);
1189c974c464SWang Shilong 			rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
1190ea287ab1SJosef Bacik 			RB_CLEAR_NODE(&node->rb_node);
1191c974c464SWang Shilong 		}
1192c974c464SWang Shilong 		spin_unlock(&rc->reloc_root_tree.lock);
1193c974c464SWang Shilong 		if (!node)
1194c974c464SWang Shilong 			return;
1195c974c464SWang Shilong 		BUG_ON((struct btrfs_root *)node->data != root);
1196389305b2SQu Wenruo 	}
1197c974c464SWang Shilong 
1198f44deb74SJosef Bacik 	/*
1199f44deb74SJosef Bacik 	 * We only put the reloc root here if it's on the list.  There's a lot
1200f44deb74SJosef Bacik 	 * of places where the pattern is to splice the rc->reloc_roots, process
1201f44deb74SJosef Bacik 	 * the reloc roots, and then add the reloc root back onto
1202f44deb74SJosef Bacik 	 * rc->reloc_roots.  If we call __del_reloc_root while it's off of the
1203f44deb74SJosef Bacik 	 * list we don't want the reference being dropped, because the guy
1204f44deb74SJosef Bacik 	 * messing with the list is in charge of the reference.
1205f44deb74SJosef Bacik 	 */
12060b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
1207f44deb74SJosef Bacik 	if (!list_empty(&root->root_list)) {
1208f44deb74SJosef Bacik 		put_ref = true;
1209c974c464SWang Shilong 		list_del_init(&root->root_list);
1210f44deb74SJosef Bacik 	}
12110b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1212f44deb74SJosef Bacik 	if (put_ref)
1213f44deb74SJosef Bacik 		btrfs_put_root(root);
1214c974c464SWang Shilong 	kfree(node);
1215c974c464SWang Shilong }
1216c974c464SWang Shilong 
1217c974c464SWang Shilong /*
1218c974c464SWang Shilong  * helper to update the 'address of tree root -> reloc tree'
1219c974c464SWang Shilong  * mapping
1220c974c464SWang Shilong  */
1221ea287ab1SJosef Bacik static int __update_reloc_root(struct btrfs_root *root)
1222c974c464SWang Shilong {
12230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1224c974c464SWang Shilong 	struct rb_node *rb_node;
1225c974c464SWang Shilong 	struct mapping_node *node = NULL;
12260b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
1227c974c464SWang Shilong 
1228c974c464SWang Shilong 	spin_lock(&rc->reloc_root_tree.lock);
1229e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
1230ea287ab1SJosef Bacik 				   root->commit_root->start);
12315d4f98a2SYan Zheng 	if (rb_node) {
12325d4f98a2SYan Zheng 		node = rb_entry(rb_node, struct mapping_node, rb_node);
12335d4f98a2SYan Zheng 		rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
12345d4f98a2SYan Zheng 	}
12355d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
12365d4f98a2SYan Zheng 
12378f71f3e0SLiu Bo 	if (!node)
12388f71f3e0SLiu Bo 		return 0;
12395d4f98a2SYan Zheng 	BUG_ON((struct btrfs_root *)node->data != root);
12405d4f98a2SYan Zheng 
12415d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
1242ea287ab1SJosef Bacik 	node->bytenr = root->node->start;
1243e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
12445d4f98a2SYan Zheng 				   node->bytenr, &node->rb_node);
12455d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
124643c04fb1SJeff Mahoney 	if (rb_node)
1247982c92cbSQu Wenruo 		btrfs_backref_panic(fs_info, node->bytenr, -EEXIST);
12485d4f98a2SYan Zheng 	return 0;
12495d4f98a2SYan Zheng }
12505d4f98a2SYan Zheng 
12513fd0a558SYan, Zheng static struct btrfs_root *create_reloc_root(struct btrfs_trans_handle *trans,
12523fd0a558SYan, Zheng 					struct btrfs_root *root, u64 objectid)
12535d4f98a2SYan Zheng {
12540b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12555d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
12565d4f98a2SYan Zheng 	struct extent_buffer *eb;
12575d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
12585d4f98a2SYan Zheng 	struct btrfs_key root_key;
12595d4f98a2SYan Zheng 	int ret;
12605d4f98a2SYan Zheng 
12615d4f98a2SYan Zheng 	root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
12625d4f98a2SYan Zheng 	BUG_ON(!root_item);
12635d4f98a2SYan Zheng 
12645d4f98a2SYan Zheng 	root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
12655d4f98a2SYan Zheng 	root_key.type = BTRFS_ROOT_ITEM_KEY;
12663fd0a558SYan, Zheng 	root_key.offset = objectid;
12675d4f98a2SYan Zheng 
12683fd0a558SYan, Zheng 	if (root->root_key.objectid == objectid) {
1269054570a1SFilipe Manana 		u64 commit_root_gen;
1270054570a1SFilipe Manana 
12713fd0a558SYan, Zheng 		/* called by btrfs_init_reloc_root */
12725d4f98a2SYan Zheng 		ret = btrfs_copy_root(trans, root, root->commit_root, &eb,
12735d4f98a2SYan Zheng 				      BTRFS_TREE_RELOC_OBJECTID);
12745d4f98a2SYan Zheng 		BUG_ON(ret);
1275054570a1SFilipe Manana 		/*
1276054570a1SFilipe Manana 		 * Set the last_snapshot field to the generation of the commit
1277054570a1SFilipe Manana 		 * root - like this ctree.c:btrfs_block_can_be_shared() behaves
1278054570a1SFilipe Manana 		 * correctly (returns true) when the relocation root is created
1279054570a1SFilipe Manana 		 * either inside the critical section of a transaction commit
1280054570a1SFilipe Manana 		 * (through transaction.c:qgroup_account_snapshot()) and when
1281054570a1SFilipe Manana 		 * it's created before the transaction commit is started.
1282054570a1SFilipe Manana 		 */
1283054570a1SFilipe Manana 		commit_root_gen = btrfs_header_generation(root->commit_root);
1284054570a1SFilipe Manana 		btrfs_set_root_last_snapshot(&root->root_item, commit_root_gen);
12853fd0a558SYan, Zheng 	} else {
12863fd0a558SYan, Zheng 		/*
12873fd0a558SYan, Zheng 		 * called by btrfs_reloc_post_snapshot_hook.
12883fd0a558SYan, Zheng 		 * the source tree is a reloc tree, all tree blocks
12893fd0a558SYan, Zheng 		 * modified after it was created have RELOC flag
12903fd0a558SYan, Zheng 		 * set in their headers. so it's OK to not update
12913fd0a558SYan, Zheng 		 * the 'last_snapshot'.
12923fd0a558SYan, Zheng 		 */
12933fd0a558SYan, Zheng 		ret = btrfs_copy_root(trans, root, root->node, &eb,
12943fd0a558SYan, Zheng 				      BTRFS_TREE_RELOC_OBJECTID);
12953fd0a558SYan, Zheng 		BUG_ON(ret);
12963fd0a558SYan, Zheng 	}
12973fd0a558SYan, Zheng 
12985d4f98a2SYan Zheng 	memcpy(root_item, &root->root_item, sizeof(*root_item));
12995d4f98a2SYan Zheng 	btrfs_set_root_bytenr(root_item, eb->start);
13005d4f98a2SYan Zheng 	btrfs_set_root_level(root_item, btrfs_header_level(eb));
13015d4f98a2SYan Zheng 	btrfs_set_root_generation(root_item, trans->transid);
13023fd0a558SYan, Zheng 
13033fd0a558SYan, Zheng 	if (root->root_key.objectid == objectid) {
13043fd0a558SYan, Zheng 		btrfs_set_root_refs(root_item, 0);
13053fd0a558SYan, Zheng 		memset(&root_item->drop_progress, 0,
13063fd0a558SYan, Zheng 		       sizeof(struct btrfs_disk_key));
13075d4f98a2SYan Zheng 		root_item->drop_level = 0;
13083fd0a558SYan, Zheng 	}
13095d4f98a2SYan Zheng 
13105d4f98a2SYan Zheng 	btrfs_tree_unlock(eb);
13115d4f98a2SYan Zheng 	free_extent_buffer(eb);
13125d4f98a2SYan Zheng 
13130b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root,
13145d4f98a2SYan Zheng 				&root_key, root_item);
13155d4f98a2SYan Zheng 	BUG_ON(ret);
13165d4f98a2SYan Zheng 	kfree(root_item);
13175d4f98a2SYan Zheng 
13183dbf1738SJosef Bacik 	reloc_root = btrfs_read_tree_root(fs_info->tree_root, &root_key);
13195d4f98a2SYan Zheng 	BUG_ON(IS_ERR(reloc_root));
13203dbf1738SJosef Bacik 	set_bit(BTRFS_ROOT_REF_COWS, &reloc_root->state);
13215d4f98a2SYan Zheng 	reloc_root->last_trans = trans->transid;
13223fd0a558SYan, Zheng 	return reloc_root;
13233fd0a558SYan, Zheng }
13243fd0a558SYan, Zheng 
13253fd0a558SYan, Zheng /*
13263fd0a558SYan, Zheng  * create reloc tree for a given fs tree. reloc tree is just a
13273fd0a558SYan, Zheng  * snapshot of the fs tree with special root objectid.
1328f44deb74SJosef Bacik  *
1329f44deb74SJosef Bacik  * The reloc_root comes out of here with two references, one for
1330f44deb74SJosef Bacik  * root->reloc_root, and another for being on the rc->reloc_roots list.
13313fd0a558SYan, Zheng  */
13323fd0a558SYan, Zheng int btrfs_init_reloc_root(struct btrfs_trans_handle *trans,
13333fd0a558SYan, Zheng 			  struct btrfs_root *root)
13343fd0a558SYan, Zheng {
13350b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13363fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
13370b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
133820dd2cbfSMiao Xie 	struct btrfs_block_rsv *rsv;
13393fd0a558SYan, Zheng 	int clear_rsv = 0;
1340ffd7b339SJeff Mahoney 	int ret;
13413fd0a558SYan, Zheng 
1342aec7db3bSJosef Bacik 	if (!rc)
13432abc726aSJosef Bacik 		return 0;
13442abc726aSJosef Bacik 
13451fac4a54SQu Wenruo 	/*
13461fac4a54SQu Wenruo 	 * The subvolume has reloc tree but the swap is finished, no need to
13471fac4a54SQu Wenruo 	 * create/update the dead reloc tree
13481fac4a54SQu Wenruo 	 */
13496282675eSQu Wenruo 	if (reloc_root_is_dead(root))
13501fac4a54SQu Wenruo 		return 0;
13511fac4a54SQu Wenruo 
1352aec7db3bSJosef Bacik 	/*
1353aec7db3bSJosef Bacik 	 * This is subtle but important.  We do not do
1354aec7db3bSJosef Bacik 	 * record_root_in_transaction for reloc roots, instead we record their
1355aec7db3bSJosef Bacik 	 * corresponding fs root, and then here we update the last trans for the
1356aec7db3bSJosef Bacik 	 * reloc root.  This means that we have to do this for the entire life
1357aec7db3bSJosef Bacik 	 * of the reloc root, regardless of which stage of the relocation we are
1358aec7db3bSJosef Bacik 	 * in.
1359aec7db3bSJosef Bacik 	 */
13603fd0a558SYan, Zheng 	if (root->reloc_root) {
13613fd0a558SYan, Zheng 		reloc_root = root->reloc_root;
13623fd0a558SYan, Zheng 		reloc_root->last_trans = trans->transid;
13633fd0a558SYan, Zheng 		return 0;
13643fd0a558SYan, Zheng 	}
13653fd0a558SYan, Zheng 
1366aec7db3bSJosef Bacik 	/*
1367aec7db3bSJosef Bacik 	 * We are merging reloc roots, we do not need new reloc trees.  Also
1368aec7db3bSJosef Bacik 	 * reloc trees never need their own reloc tree.
1369aec7db3bSJosef Bacik 	 */
1370aec7db3bSJosef Bacik 	if (!rc->create_reloc_tree ||
1371aec7db3bSJosef Bacik 	    root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1372aec7db3bSJosef Bacik 		return 0;
1373aec7db3bSJosef Bacik 
137420dd2cbfSMiao Xie 	if (!trans->reloc_reserved) {
137520dd2cbfSMiao Xie 		rsv = trans->block_rsv;
13763fd0a558SYan, Zheng 		trans->block_rsv = rc->block_rsv;
13773fd0a558SYan, Zheng 		clear_rsv = 1;
13783fd0a558SYan, Zheng 	}
13793fd0a558SYan, Zheng 	reloc_root = create_reloc_root(trans, root, root->root_key.objectid);
13803fd0a558SYan, Zheng 	if (clear_rsv)
138120dd2cbfSMiao Xie 		trans->block_rsv = rsv;
13825d4f98a2SYan Zheng 
1383ffd7b339SJeff Mahoney 	ret = __add_reloc_root(reloc_root);
1384ffd7b339SJeff Mahoney 	BUG_ON(ret < 0);
1385f44deb74SJosef Bacik 	root->reloc_root = btrfs_grab_root(reloc_root);
13865d4f98a2SYan Zheng 	return 0;
13875d4f98a2SYan Zheng }
13885d4f98a2SYan Zheng 
13895d4f98a2SYan Zheng /*
13905d4f98a2SYan Zheng  * update root item of reloc tree
13915d4f98a2SYan Zheng  */
13925d4f98a2SYan Zheng int btrfs_update_reloc_root(struct btrfs_trans_handle *trans,
13935d4f98a2SYan Zheng 			    struct btrfs_root *root)
13945d4f98a2SYan Zheng {
13950b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13965d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
13975d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
13985d4f98a2SYan Zheng 	int ret;
13995d4f98a2SYan Zheng 
14006282675eSQu Wenruo 	if (!have_reloc_root(root))
14017585717fSChris Mason 		goto out;
14025d4f98a2SYan Zheng 
14035d4f98a2SYan Zheng 	reloc_root = root->reloc_root;
14045d4f98a2SYan Zheng 	root_item = &reloc_root->root_item;
14055d4f98a2SYan Zheng 
1406f44deb74SJosef Bacik 	/*
1407f44deb74SJosef Bacik 	 * We are probably ok here, but __del_reloc_root() will drop its ref of
1408f44deb74SJosef Bacik 	 * the root.  We have the ref for root->reloc_root, but just in case
1409f44deb74SJosef Bacik 	 * hold it while we update the reloc root.
1410f44deb74SJosef Bacik 	 */
1411f44deb74SJosef Bacik 	btrfs_grab_root(reloc_root);
1412f44deb74SJosef Bacik 
1413d2311e69SQu Wenruo 	/* root->reloc_root will stay until current relocation finished */
14140b246afaSJeff Mahoney 	if (fs_info->reloc_ctl->merge_reloc_tree &&
14153fd0a558SYan, Zheng 	    btrfs_root_refs(root_item) == 0) {
1416d2311e69SQu Wenruo 		set_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
14176282675eSQu Wenruo 		/*
14186282675eSQu Wenruo 		 * Mark the tree as dead before we change reloc_root so
14196282675eSQu Wenruo 		 * have_reloc_root will not touch it from now on.
14206282675eSQu Wenruo 		 */
14216282675eSQu Wenruo 		smp_wmb();
1422c974c464SWang Shilong 		__del_reloc_root(reloc_root);
14235d4f98a2SYan Zheng 	}
14245d4f98a2SYan Zheng 
14255d4f98a2SYan Zheng 	if (reloc_root->commit_root != reloc_root->node) {
1426ea287ab1SJosef Bacik 		__update_reloc_root(reloc_root);
14275d4f98a2SYan Zheng 		btrfs_set_root_node(root_item, reloc_root->node);
14285d4f98a2SYan Zheng 		free_extent_buffer(reloc_root->commit_root);
14295d4f98a2SYan Zheng 		reloc_root->commit_root = btrfs_root_node(reloc_root);
14305d4f98a2SYan Zheng 	}
14315d4f98a2SYan Zheng 
14320b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
14335d4f98a2SYan Zheng 				&reloc_root->root_key, root_item);
14345d4f98a2SYan Zheng 	BUG_ON(ret);
1435f44deb74SJosef Bacik 	btrfs_put_root(reloc_root);
14367585717fSChris Mason out:
14375d4f98a2SYan Zheng 	return 0;
14385d4f98a2SYan Zheng }
14395d4f98a2SYan Zheng 
14405d4f98a2SYan Zheng /*
14415d4f98a2SYan Zheng  * helper to find first cached inode with inode number >= objectid
14425d4f98a2SYan Zheng  * in a subvolume
14435d4f98a2SYan Zheng  */
14445d4f98a2SYan Zheng static struct inode *find_next_inode(struct btrfs_root *root, u64 objectid)
14455d4f98a2SYan Zheng {
14465d4f98a2SYan Zheng 	struct rb_node *node;
14475d4f98a2SYan Zheng 	struct rb_node *prev;
14485d4f98a2SYan Zheng 	struct btrfs_inode *entry;
14495d4f98a2SYan Zheng 	struct inode *inode;
14505d4f98a2SYan Zheng 
14515d4f98a2SYan Zheng 	spin_lock(&root->inode_lock);
14525d4f98a2SYan Zheng again:
14535d4f98a2SYan Zheng 	node = root->inode_tree.rb_node;
14545d4f98a2SYan Zheng 	prev = NULL;
14555d4f98a2SYan Zheng 	while (node) {
14565d4f98a2SYan Zheng 		prev = node;
14575d4f98a2SYan Zheng 		entry = rb_entry(node, struct btrfs_inode, rb_node);
14585d4f98a2SYan Zheng 
14594a0cc7caSNikolay Borisov 		if (objectid < btrfs_ino(entry))
14605d4f98a2SYan Zheng 			node = node->rb_left;
14614a0cc7caSNikolay Borisov 		else if (objectid > btrfs_ino(entry))
14625d4f98a2SYan Zheng 			node = node->rb_right;
14635d4f98a2SYan Zheng 		else
14645d4f98a2SYan Zheng 			break;
14655d4f98a2SYan Zheng 	}
14665d4f98a2SYan Zheng 	if (!node) {
14675d4f98a2SYan Zheng 		while (prev) {
14685d4f98a2SYan Zheng 			entry = rb_entry(prev, struct btrfs_inode, rb_node);
14694a0cc7caSNikolay Borisov 			if (objectid <= btrfs_ino(entry)) {
14705d4f98a2SYan Zheng 				node = prev;
14715d4f98a2SYan Zheng 				break;
14725d4f98a2SYan Zheng 			}
14735d4f98a2SYan Zheng 			prev = rb_next(prev);
14745d4f98a2SYan Zheng 		}
14755d4f98a2SYan Zheng 	}
14765d4f98a2SYan Zheng 	while (node) {
14775d4f98a2SYan Zheng 		entry = rb_entry(node, struct btrfs_inode, rb_node);
14785d4f98a2SYan Zheng 		inode = igrab(&entry->vfs_inode);
14795d4f98a2SYan Zheng 		if (inode) {
14805d4f98a2SYan Zheng 			spin_unlock(&root->inode_lock);
14815d4f98a2SYan Zheng 			return inode;
14825d4f98a2SYan Zheng 		}
14835d4f98a2SYan Zheng 
14844a0cc7caSNikolay Borisov 		objectid = btrfs_ino(entry) + 1;
14855d4f98a2SYan Zheng 		if (cond_resched_lock(&root->inode_lock))
14865d4f98a2SYan Zheng 			goto again;
14875d4f98a2SYan Zheng 
14885d4f98a2SYan Zheng 		node = rb_next(node);
14895d4f98a2SYan Zheng 	}
14905d4f98a2SYan Zheng 	spin_unlock(&root->inode_lock);
14915d4f98a2SYan Zheng 	return NULL;
14925d4f98a2SYan Zheng }
14935d4f98a2SYan Zheng 
14945d4f98a2SYan Zheng /*
14955d4f98a2SYan Zheng  * get new location of data
14965d4f98a2SYan Zheng  */
14975d4f98a2SYan Zheng static int get_new_location(struct inode *reloc_inode, u64 *new_bytenr,
14985d4f98a2SYan Zheng 			    u64 bytenr, u64 num_bytes)
14995d4f98a2SYan Zheng {
15005d4f98a2SYan Zheng 	struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
15015d4f98a2SYan Zheng 	struct btrfs_path *path;
15025d4f98a2SYan Zheng 	struct btrfs_file_extent_item *fi;
15035d4f98a2SYan Zheng 	struct extent_buffer *leaf;
15045d4f98a2SYan Zheng 	int ret;
15055d4f98a2SYan Zheng 
15065d4f98a2SYan Zheng 	path = btrfs_alloc_path();
15075d4f98a2SYan Zheng 	if (!path)
15085d4f98a2SYan Zheng 		return -ENOMEM;
15095d4f98a2SYan Zheng 
15105d4f98a2SYan Zheng 	bytenr -= BTRFS_I(reloc_inode)->index_cnt;
1511f85b7379SDavid Sterba 	ret = btrfs_lookup_file_extent(NULL, root, path,
1512f85b7379SDavid Sterba 			btrfs_ino(BTRFS_I(reloc_inode)), bytenr, 0);
15135d4f98a2SYan Zheng 	if (ret < 0)
15145d4f98a2SYan Zheng 		goto out;
15155d4f98a2SYan Zheng 	if (ret > 0) {
15165d4f98a2SYan Zheng 		ret = -ENOENT;
15175d4f98a2SYan Zheng 		goto out;
15185d4f98a2SYan Zheng 	}
15195d4f98a2SYan Zheng 
15205d4f98a2SYan Zheng 	leaf = path->nodes[0];
15215d4f98a2SYan Zheng 	fi = btrfs_item_ptr(leaf, path->slots[0],
15225d4f98a2SYan Zheng 			    struct btrfs_file_extent_item);
15235d4f98a2SYan Zheng 
15245d4f98a2SYan Zheng 	BUG_ON(btrfs_file_extent_offset(leaf, fi) ||
15255d4f98a2SYan Zheng 	       btrfs_file_extent_compression(leaf, fi) ||
15265d4f98a2SYan Zheng 	       btrfs_file_extent_encryption(leaf, fi) ||
15275d4f98a2SYan Zheng 	       btrfs_file_extent_other_encoding(leaf, fi));
15285d4f98a2SYan Zheng 
15295d4f98a2SYan Zheng 	if (num_bytes != btrfs_file_extent_disk_num_bytes(leaf, fi)) {
153083d4cfd4SJosef Bacik 		ret = -EINVAL;
15315d4f98a2SYan Zheng 		goto out;
15325d4f98a2SYan Zheng 	}
15335d4f98a2SYan Zheng 
15345d4f98a2SYan Zheng 	*new_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
15355d4f98a2SYan Zheng 	ret = 0;
15365d4f98a2SYan Zheng out:
15375d4f98a2SYan Zheng 	btrfs_free_path(path);
15385d4f98a2SYan Zheng 	return ret;
15395d4f98a2SYan Zheng }
15405d4f98a2SYan Zheng 
15415d4f98a2SYan Zheng /*
15425d4f98a2SYan Zheng  * update file extent items in the tree leaf to point to
15435d4f98a2SYan Zheng  * the new locations.
15445d4f98a2SYan Zheng  */
15453fd0a558SYan, Zheng static noinline_for_stack
15463fd0a558SYan, Zheng int replace_file_extents(struct btrfs_trans_handle *trans,
15475d4f98a2SYan Zheng 			 struct reloc_control *rc,
15485d4f98a2SYan Zheng 			 struct btrfs_root *root,
15493fd0a558SYan, Zheng 			 struct extent_buffer *leaf)
15505d4f98a2SYan Zheng {
15510b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15525d4f98a2SYan Zheng 	struct btrfs_key key;
15535d4f98a2SYan Zheng 	struct btrfs_file_extent_item *fi;
15545d4f98a2SYan Zheng 	struct inode *inode = NULL;
15555d4f98a2SYan Zheng 	u64 parent;
15565d4f98a2SYan Zheng 	u64 bytenr;
15573fd0a558SYan, Zheng 	u64 new_bytenr = 0;
15585d4f98a2SYan Zheng 	u64 num_bytes;
15595d4f98a2SYan Zheng 	u64 end;
15605d4f98a2SYan Zheng 	u32 nritems;
15615d4f98a2SYan Zheng 	u32 i;
156283d4cfd4SJosef Bacik 	int ret = 0;
15635d4f98a2SYan Zheng 	int first = 1;
15645d4f98a2SYan Zheng 	int dirty = 0;
15655d4f98a2SYan Zheng 
15665d4f98a2SYan Zheng 	if (rc->stage != UPDATE_DATA_PTRS)
15675d4f98a2SYan Zheng 		return 0;
15685d4f98a2SYan Zheng 
15695d4f98a2SYan Zheng 	/* reloc trees always use full backref */
15705d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
15715d4f98a2SYan Zheng 		parent = leaf->start;
15725d4f98a2SYan Zheng 	else
15735d4f98a2SYan Zheng 		parent = 0;
15745d4f98a2SYan Zheng 
15755d4f98a2SYan Zheng 	nritems = btrfs_header_nritems(leaf);
15765d4f98a2SYan Zheng 	for (i = 0; i < nritems; i++) {
157782fa113fSQu Wenruo 		struct btrfs_ref ref = { 0 };
157882fa113fSQu Wenruo 
15795d4f98a2SYan Zheng 		cond_resched();
15805d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, i);
15815d4f98a2SYan Zheng 		if (key.type != BTRFS_EXTENT_DATA_KEY)
15825d4f98a2SYan Zheng 			continue;
15835d4f98a2SYan Zheng 		fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
15845d4f98a2SYan Zheng 		if (btrfs_file_extent_type(leaf, fi) ==
15855d4f98a2SYan Zheng 		    BTRFS_FILE_EXTENT_INLINE)
15865d4f98a2SYan Zheng 			continue;
15875d4f98a2SYan Zheng 		bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
15885d4f98a2SYan Zheng 		num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
15895d4f98a2SYan Zheng 		if (bytenr == 0)
15905d4f98a2SYan Zheng 			continue;
15919569cc20SQu Wenruo 		if (!in_range(bytenr, rc->block_group->start,
15929569cc20SQu Wenruo 			      rc->block_group->length))
15935d4f98a2SYan Zheng 			continue;
15945d4f98a2SYan Zheng 
15955d4f98a2SYan Zheng 		/*
15965d4f98a2SYan Zheng 		 * if we are modifying block in fs tree, wait for readpage
15975d4f98a2SYan Zheng 		 * to complete and drop the extent cache
15985d4f98a2SYan Zheng 		 */
15995d4f98a2SYan Zheng 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
16005d4f98a2SYan Zheng 			if (first) {
16015d4f98a2SYan Zheng 				inode = find_next_inode(root, key.objectid);
16025d4f98a2SYan Zheng 				first = 0;
16034a0cc7caSNikolay Borisov 			} else if (inode && btrfs_ino(BTRFS_I(inode)) < key.objectid) {
16043fd0a558SYan, Zheng 				btrfs_add_delayed_iput(inode);
16055d4f98a2SYan Zheng 				inode = find_next_inode(root, key.objectid);
16065d4f98a2SYan Zheng 			}
16074a0cc7caSNikolay Borisov 			if (inode && btrfs_ino(BTRFS_I(inode)) == key.objectid) {
16085d4f98a2SYan Zheng 				end = key.offset +
16095d4f98a2SYan Zheng 				      btrfs_file_extent_num_bytes(leaf, fi);
16105d4f98a2SYan Zheng 				WARN_ON(!IS_ALIGNED(key.offset,
16110b246afaSJeff Mahoney 						    fs_info->sectorsize));
16120b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
16135d4f98a2SYan Zheng 				end--;
16145d4f98a2SYan Zheng 				ret = try_lock_extent(&BTRFS_I(inode)->io_tree,
1615d0082371SJeff Mahoney 						      key.offset, end);
16165d4f98a2SYan Zheng 				if (!ret)
16175d4f98a2SYan Zheng 					continue;
16185d4f98a2SYan Zheng 
1619dcdbc059SNikolay Borisov 				btrfs_drop_extent_cache(BTRFS_I(inode),
1620dcdbc059SNikolay Borisov 						key.offset,	end, 1);
16215d4f98a2SYan Zheng 				unlock_extent(&BTRFS_I(inode)->io_tree,
1622d0082371SJeff Mahoney 					      key.offset, end);
16235d4f98a2SYan Zheng 			}
16245d4f98a2SYan Zheng 		}
16255d4f98a2SYan Zheng 
16265d4f98a2SYan Zheng 		ret = get_new_location(rc->data_inode, &new_bytenr,
16275d4f98a2SYan Zheng 				       bytenr, num_bytes);
162883d4cfd4SJosef Bacik 		if (ret) {
162983d4cfd4SJosef Bacik 			/*
163083d4cfd4SJosef Bacik 			 * Don't have to abort since we've not changed anything
163183d4cfd4SJosef Bacik 			 * in the file extent yet.
163283d4cfd4SJosef Bacik 			 */
163383d4cfd4SJosef Bacik 			break;
16343fd0a558SYan, Zheng 		}
16355d4f98a2SYan Zheng 
16365d4f98a2SYan Zheng 		btrfs_set_file_extent_disk_bytenr(leaf, fi, new_bytenr);
16375d4f98a2SYan Zheng 		dirty = 1;
16385d4f98a2SYan Zheng 
16395d4f98a2SYan Zheng 		key.offset -= btrfs_file_extent_offset(leaf, fi);
164082fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new_bytenr,
164182fa113fSQu Wenruo 				       num_bytes, parent);
164282fa113fSQu Wenruo 		ref.real_root = root->root_key.objectid;
164382fa113fSQu Wenruo 		btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
1644b06c4bf5SFilipe Manana 				    key.objectid, key.offset);
164582fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
164683d4cfd4SJosef Bacik 		if (ret) {
164766642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
164883d4cfd4SJosef Bacik 			break;
164983d4cfd4SJosef Bacik 		}
16505d4f98a2SYan Zheng 
1651ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
1652ffd4bb2aSQu Wenruo 				       num_bytes, parent);
1653ffd4bb2aSQu Wenruo 		ref.real_root = root->root_key.objectid;
1654ffd4bb2aSQu Wenruo 		btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
1655b06c4bf5SFilipe Manana 				    key.objectid, key.offset);
1656ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
165783d4cfd4SJosef Bacik 		if (ret) {
165866642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
165983d4cfd4SJosef Bacik 			break;
166083d4cfd4SJosef Bacik 		}
16615d4f98a2SYan Zheng 	}
16625d4f98a2SYan Zheng 	if (dirty)
16635d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(leaf);
16643fd0a558SYan, Zheng 	if (inode)
16653fd0a558SYan, Zheng 		btrfs_add_delayed_iput(inode);
166683d4cfd4SJosef Bacik 	return ret;
16675d4f98a2SYan Zheng }
16685d4f98a2SYan Zheng 
16695d4f98a2SYan Zheng static noinline_for_stack
16705d4f98a2SYan Zheng int memcmp_node_keys(struct extent_buffer *eb, int slot,
16715d4f98a2SYan Zheng 		     struct btrfs_path *path, int level)
16725d4f98a2SYan Zheng {
16735d4f98a2SYan Zheng 	struct btrfs_disk_key key1;
16745d4f98a2SYan Zheng 	struct btrfs_disk_key key2;
16755d4f98a2SYan Zheng 	btrfs_node_key(eb, &key1, slot);
16765d4f98a2SYan Zheng 	btrfs_node_key(path->nodes[level], &key2, path->slots[level]);
16775d4f98a2SYan Zheng 	return memcmp(&key1, &key2, sizeof(key1));
16785d4f98a2SYan Zheng }
16795d4f98a2SYan Zheng 
16805d4f98a2SYan Zheng /*
16815d4f98a2SYan Zheng  * try to replace tree blocks in fs tree with the new blocks
16825d4f98a2SYan Zheng  * in reloc tree. tree blocks haven't been modified since the
16835d4f98a2SYan Zheng  * reloc tree was create can be replaced.
16845d4f98a2SYan Zheng  *
16855d4f98a2SYan Zheng  * if a block was replaced, level of the block + 1 is returned.
16865d4f98a2SYan Zheng  * if no block got replaced, 0 is returned. if there are other
16875d4f98a2SYan Zheng  * errors, a negative error number is returned.
16885d4f98a2SYan Zheng  */
16893fd0a558SYan, Zheng static noinline_for_stack
16903d0174f7SQu Wenruo int replace_path(struct btrfs_trans_handle *trans, struct reloc_control *rc,
16915d4f98a2SYan Zheng 		 struct btrfs_root *dest, struct btrfs_root *src,
16925d4f98a2SYan Zheng 		 struct btrfs_path *path, struct btrfs_key *next_key,
16935d4f98a2SYan Zheng 		 int lowest_level, int max_level)
16945d4f98a2SYan Zheng {
16950b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = dest->fs_info;
16965d4f98a2SYan Zheng 	struct extent_buffer *eb;
16975d4f98a2SYan Zheng 	struct extent_buffer *parent;
169882fa113fSQu Wenruo 	struct btrfs_ref ref = { 0 };
16995d4f98a2SYan Zheng 	struct btrfs_key key;
17005d4f98a2SYan Zheng 	u64 old_bytenr;
17015d4f98a2SYan Zheng 	u64 new_bytenr;
17025d4f98a2SYan Zheng 	u64 old_ptr_gen;
17035d4f98a2SYan Zheng 	u64 new_ptr_gen;
17045d4f98a2SYan Zheng 	u64 last_snapshot;
17055d4f98a2SYan Zheng 	u32 blocksize;
17063fd0a558SYan, Zheng 	int cow = 0;
17075d4f98a2SYan Zheng 	int level;
17085d4f98a2SYan Zheng 	int ret;
17095d4f98a2SYan Zheng 	int slot;
17105d4f98a2SYan Zheng 
17115d4f98a2SYan Zheng 	BUG_ON(src->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
17125d4f98a2SYan Zheng 	BUG_ON(dest->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID);
17135d4f98a2SYan Zheng 
17145d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&src->root_item);
17153fd0a558SYan, Zheng again:
17165d4f98a2SYan Zheng 	slot = path->slots[lowest_level];
17175d4f98a2SYan Zheng 	btrfs_node_key_to_cpu(path->nodes[lowest_level], &key, slot);
17185d4f98a2SYan Zheng 
17195d4f98a2SYan Zheng 	eb = btrfs_lock_root_node(dest);
17208bead258SDavid Sterba 	btrfs_set_lock_blocking_write(eb);
17215d4f98a2SYan Zheng 	level = btrfs_header_level(eb);
17225d4f98a2SYan Zheng 
17235d4f98a2SYan Zheng 	if (level < lowest_level) {
17245d4f98a2SYan Zheng 		btrfs_tree_unlock(eb);
17255d4f98a2SYan Zheng 		free_extent_buffer(eb);
17265d4f98a2SYan Zheng 		return 0;
17275d4f98a2SYan Zheng 	}
17285d4f98a2SYan Zheng 
17293fd0a558SYan, Zheng 	if (cow) {
17305d4f98a2SYan Zheng 		ret = btrfs_cow_block(trans, dest, eb, NULL, 0, &eb);
17315d4f98a2SYan Zheng 		BUG_ON(ret);
17323fd0a558SYan, Zheng 	}
17338bead258SDavid Sterba 	btrfs_set_lock_blocking_write(eb);
17345d4f98a2SYan Zheng 
17355d4f98a2SYan Zheng 	if (next_key) {
17365d4f98a2SYan Zheng 		next_key->objectid = (u64)-1;
17375d4f98a2SYan Zheng 		next_key->type = (u8)-1;
17385d4f98a2SYan Zheng 		next_key->offset = (u64)-1;
17395d4f98a2SYan Zheng 	}
17405d4f98a2SYan Zheng 
17415d4f98a2SYan Zheng 	parent = eb;
17425d4f98a2SYan Zheng 	while (1) {
1743581c1760SQu Wenruo 		struct btrfs_key first_key;
1744581c1760SQu Wenruo 
17455d4f98a2SYan Zheng 		level = btrfs_header_level(parent);
17465d4f98a2SYan Zheng 		BUG_ON(level < lowest_level);
17475d4f98a2SYan Zheng 
17485d4f98a2SYan Zheng 		ret = btrfs_bin_search(parent, &key, level, &slot);
1749cbca7d59SFilipe Manana 		if (ret < 0)
1750cbca7d59SFilipe Manana 			break;
17515d4f98a2SYan Zheng 		if (ret && slot > 0)
17525d4f98a2SYan Zheng 			slot--;
17535d4f98a2SYan Zheng 
17545d4f98a2SYan Zheng 		if (next_key && slot + 1 < btrfs_header_nritems(parent))
17555d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(parent, next_key, slot + 1);
17565d4f98a2SYan Zheng 
17575d4f98a2SYan Zheng 		old_bytenr = btrfs_node_blockptr(parent, slot);
17580b246afaSJeff Mahoney 		blocksize = fs_info->nodesize;
17595d4f98a2SYan Zheng 		old_ptr_gen = btrfs_node_ptr_generation(parent, slot);
176017515f1bSQu Wenruo 		btrfs_node_key_to_cpu(parent, &first_key, slot);
17615d4f98a2SYan Zheng 
17625d4f98a2SYan Zheng 		if (level <= max_level) {
17635d4f98a2SYan Zheng 			eb = path->nodes[level];
17645d4f98a2SYan Zheng 			new_bytenr = btrfs_node_blockptr(eb,
17655d4f98a2SYan Zheng 							path->slots[level]);
17665d4f98a2SYan Zheng 			new_ptr_gen = btrfs_node_ptr_generation(eb,
17675d4f98a2SYan Zheng 							path->slots[level]);
17685d4f98a2SYan Zheng 		} else {
17695d4f98a2SYan Zheng 			new_bytenr = 0;
17705d4f98a2SYan Zheng 			new_ptr_gen = 0;
17715d4f98a2SYan Zheng 		}
17725d4f98a2SYan Zheng 
1773fae7f21cSDulshani Gunawardhana 		if (WARN_ON(new_bytenr > 0 && new_bytenr == old_bytenr)) {
17745d4f98a2SYan Zheng 			ret = level;
17755d4f98a2SYan Zheng 			break;
17765d4f98a2SYan Zheng 		}
17775d4f98a2SYan Zheng 
17785d4f98a2SYan Zheng 		if (new_bytenr == 0 || old_ptr_gen > last_snapshot ||
17795d4f98a2SYan Zheng 		    memcmp_node_keys(parent, slot, path, level)) {
17803fd0a558SYan, Zheng 			if (level <= lowest_level) {
17815d4f98a2SYan Zheng 				ret = 0;
17825d4f98a2SYan Zheng 				break;
17835d4f98a2SYan Zheng 			}
17845d4f98a2SYan Zheng 
1785581c1760SQu Wenruo 			eb = read_tree_block(fs_info, old_bytenr, old_ptr_gen,
1786581c1760SQu Wenruo 					     level - 1, &first_key);
178764c043deSLiu Bo 			if (IS_ERR(eb)) {
178864c043deSLiu Bo 				ret = PTR_ERR(eb);
1789264813acSLiu Bo 				break;
179064c043deSLiu Bo 			} else if (!extent_buffer_uptodate(eb)) {
179164c043deSLiu Bo 				ret = -EIO;
1792416bc658SJosef Bacik 				free_extent_buffer(eb);
1793379cde74SStefan Behrens 				break;
1794416bc658SJosef Bacik 			}
17955d4f98a2SYan Zheng 			btrfs_tree_lock(eb);
17963fd0a558SYan, Zheng 			if (cow) {
17975d4f98a2SYan Zheng 				ret = btrfs_cow_block(trans, dest, eb, parent,
17985d4f98a2SYan Zheng 						      slot, &eb);
17995d4f98a2SYan Zheng 				BUG_ON(ret);
18005d4f98a2SYan Zheng 			}
18018bead258SDavid Sterba 			btrfs_set_lock_blocking_write(eb);
18025d4f98a2SYan Zheng 
18035d4f98a2SYan Zheng 			btrfs_tree_unlock(parent);
18045d4f98a2SYan Zheng 			free_extent_buffer(parent);
18055d4f98a2SYan Zheng 
18065d4f98a2SYan Zheng 			parent = eb;
18075d4f98a2SYan Zheng 			continue;
18085d4f98a2SYan Zheng 		}
18095d4f98a2SYan Zheng 
18103fd0a558SYan, Zheng 		if (!cow) {
18113fd0a558SYan, Zheng 			btrfs_tree_unlock(parent);
18123fd0a558SYan, Zheng 			free_extent_buffer(parent);
18133fd0a558SYan, Zheng 			cow = 1;
18143fd0a558SYan, Zheng 			goto again;
18153fd0a558SYan, Zheng 		}
18163fd0a558SYan, Zheng 
18175d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(path->nodes[level], &key,
18185d4f98a2SYan Zheng 				      path->slots[level]);
1819b3b4aa74SDavid Sterba 		btrfs_release_path(path);
18205d4f98a2SYan Zheng 
18215d4f98a2SYan Zheng 		path->lowest_level = level;
18225d4f98a2SYan Zheng 		ret = btrfs_search_slot(trans, src, &key, path, 0, 1);
18235d4f98a2SYan Zheng 		path->lowest_level = 0;
18245d4f98a2SYan Zheng 		BUG_ON(ret);
18255d4f98a2SYan Zheng 
18265d4f98a2SYan Zheng 		/*
1827824d8dffSQu Wenruo 		 * Info qgroup to trace both subtrees.
1828824d8dffSQu Wenruo 		 *
1829824d8dffSQu Wenruo 		 * We must trace both trees.
1830824d8dffSQu Wenruo 		 * 1) Tree reloc subtree
1831824d8dffSQu Wenruo 		 *    If not traced, we will leak data numbers
1832824d8dffSQu Wenruo 		 * 2) Fs subtree
1833824d8dffSQu Wenruo 		 *    If not traced, we will double count old data
1834f616f5cdSQu Wenruo 		 *
1835f616f5cdSQu Wenruo 		 * We don't scan the subtree right now, but only record
1836f616f5cdSQu Wenruo 		 * the swapped tree blocks.
1837f616f5cdSQu Wenruo 		 * The real subtree rescan is delayed until we have new
1838f616f5cdSQu Wenruo 		 * CoW on the subtree root node before transaction commit.
1839824d8dffSQu Wenruo 		 */
1840370a11b8SQu Wenruo 		ret = btrfs_qgroup_add_swapped_blocks(trans, dest,
1841370a11b8SQu Wenruo 				rc->block_group, parent, slot,
1842370a11b8SQu Wenruo 				path->nodes[level], path->slots[level],
1843370a11b8SQu Wenruo 				last_snapshot);
1844370a11b8SQu Wenruo 		if (ret < 0)
1845370a11b8SQu Wenruo 			break;
1846824d8dffSQu Wenruo 		/*
18475d4f98a2SYan Zheng 		 * swap blocks in fs tree and reloc tree.
18485d4f98a2SYan Zheng 		 */
18495d4f98a2SYan Zheng 		btrfs_set_node_blockptr(parent, slot, new_bytenr);
18505d4f98a2SYan Zheng 		btrfs_set_node_ptr_generation(parent, slot, new_ptr_gen);
18515d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(parent);
18525d4f98a2SYan Zheng 
18535d4f98a2SYan Zheng 		btrfs_set_node_blockptr(path->nodes[level],
18545d4f98a2SYan Zheng 					path->slots[level], old_bytenr);
18555d4f98a2SYan Zheng 		btrfs_set_node_ptr_generation(path->nodes[level],
18565d4f98a2SYan Zheng 					      path->slots[level], old_ptr_gen);
18575d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(path->nodes[level]);
18585d4f98a2SYan Zheng 
185982fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, old_bytenr,
186082fa113fSQu Wenruo 				       blocksize, path->nodes[level]->start);
186182fa113fSQu Wenruo 		ref.skip_qgroup = true;
186282fa113fSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, src->root_key.objectid);
186382fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
18645d4f98a2SYan Zheng 		BUG_ON(ret);
186582fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new_bytenr,
186682fa113fSQu Wenruo 				       blocksize, 0);
186782fa113fSQu Wenruo 		ref.skip_qgroup = true;
186882fa113fSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, dest->root_key.objectid);
186982fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
18705d4f98a2SYan Zheng 		BUG_ON(ret);
18715d4f98a2SYan Zheng 
1872ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, new_bytenr,
1873ffd4bb2aSQu Wenruo 				       blocksize, path->nodes[level]->start);
1874ffd4bb2aSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, src->root_key.objectid);
1875ffd4bb2aSQu Wenruo 		ref.skip_qgroup = true;
1876ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
18775d4f98a2SYan Zheng 		BUG_ON(ret);
18785d4f98a2SYan Zheng 
1879ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, old_bytenr,
1880ffd4bb2aSQu Wenruo 				       blocksize, 0);
1881ffd4bb2aSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, dest->root_key.objectid);
1882ffd4bb2aSQu Wenruo 		ref.skip_qgroup = true;
1883ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
18845d4f98a2SYan Zheng 		BUG_ON(ret);
18855d4f98a2SYan Zheng 
18865d4f98a2SYan Zheng 		btrfs_unlock_up_safe(path, 0);
18875d4f98a2SYan Zheng 
18885d4f98a2SYan Zheng 		ret = level;
18895d4f98a2SYan Zheng 		break;
18905d4f98a2SYan Zheng 	}
18915d4f98a2SYan Zheng 	btrfs_tree_unlock(parent);
18925d4f98a2SYan Zheng 	free_extent_buffer(parent);
18935d4f98a2SYan Zheng 	return ret;
18945d4f98a2SYan Zheng }
18955d4f98a2SYan Zheng 
18965d4f98a2SYan Zheng /*
18975d4f98a2SYan Zheng  * helper to find next relocated block in reloc tree
18985d4f98a2SYan Zheng  */
18995d4f98a2SYan Zheng static noinline_for_stack
19005d4f98a2SYan Zheng int walk_up_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
19015d4f98a2SYan Zheng 		       int *level)
19025d4f98a2SYan Zheng {
19035d4f98a2SYan Zheng 	struct extent_buffer *eb;
19045d4f98a2SYan Zheng 	int i;
19055d4f98a2SYan Zheng 	u64 last_snapshot;
19065d4f98a2SYan Zheng 	u32 nritems;
19075d4f98a2SYan Zheng 
19085d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
19095d4f98a2SYan Zheng 
19105d4f98a2SYan Zheng 	for (i = 0; i < *level; i++) {
19115d4f98a2SYan Zheng 		free_extent_buffer(path->nodes[i]);
19125d4f98a2SYan Zheng 		path->nodes[i] = NULL;
19135d4f98a2SYan Zheng 	}
19145d4f98a2SYan Zheng 
19155d4f98a2SYan Zheng 	for (i = *level; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
19165d4f98a2SYan Zheng 		eb = path->nodes[i];
19175d4f98a2SYan Zheng 		nritems = btrfs_header_nritems(eb);
19185d4f98a2SYan Zheng 		while (path->slots[i] + 1 < nritems) {
19195d4f98a2SYan Zheng 			path->slots[i]++;
19205d4f98a2SYan Zheng 			if (btrfs_node_ptr_generation(eb, path->slots[i]) <=
19215d4f98a2SYan Zheng 			    last_snapshot)
19225d4f98a2SYan Zheng 				continue;
19235d4f98a2SYan Zheng 
19245d4f98a2SYan Zheng 			*level = i;
19255d4f98a2SYan Zheng 			return 0;
19265d4f98a2SYan Zheng 		}
19275d4f98a2SYan Zheng 		free_extent_buffer(path->nodes[i]);
19285d4f98a2SYan Zheng 		path->nodes[i] = NULL;
19295d4f98a2SYan Zheng 	}
19305d4f98a2SYan Zheng 	return 1;
19315d4f98a2SYan Zheng }
19325d4f98a2SYan Zheng 
19335d4f98a2SYan Zheng /*
19345d4f98a2SYan Zheng  * walk down reloc tree to find relocated block of lowest level
19355d4f98a2SYan Zheng  */
19365d4f98a2SYan Zheng static noinline_for_stack
19375d4f98a2SYan Zheng int walk_down_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
19385d4f98a2SYan Zheng 			 int *level)
19395d4f98a2SYan Zheng {
19402ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
19415d4f98a2SYan Zheng 	struct extent_buffer *eb = NULL;
19425d4f98a2SYan Zheng 	int i;
19435d4f98a2SYan Zheng 	u64 bytenr;
19445d4f98a2SYan Zheng 	u64 ptr_gen = 0;
19455d4f98a2SYan Zheng 	u64 last_snapshot;
19465d4f98a2SYan Zheng 	u32 nritems;
19475d4f98a2SYan Zheng 
19485d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
19495d4f98a2SYan Zheng 
19505d4f98a2SYan Zheng 	for (i = *level; i > 0; i--) {
1951581c1760SQu Wenruo 		struct btrfs_key first_key;
1952581c1760SQu Wenruo 
19535d4f98a2SYan Zheng 		eb = path->nodes[i];
19545d4f98a2SYan Zheng 		nritems = btrfs_header_nritems(eb);
19555d4f98a2SYan Zheng 		while (path->slots[i] < nritems) {
19565d4f98a2SYan Zheng 			ptr_gen = btrfs_node_ptr_generation(eb, path->slots[i]);
19575d4f98a2SYan Zheng 			if (ptr_gen > last_snapshot)
19585d4f98a2SYan Zheng 				break;
19595d4f98a2SYan Zheng 			path->slots[i]++;
19605d4f98a2SYan Zheng 		}
19615d4f98a2SYan Zheng 		if (path->slots[i] >= nritems) {
19625d4f98a2SYan Zheng 			if (i == *level)
19635d4f98a2SYan Zheng 				break;
19645d4f98a2SYan Zheng 			*level = i + 1;
19655d4f98a2SYan Zheng 			return 0;
19665d4f98a2SYan Zheng 		}
19675d4f98a2SYan Zheng 		if (i == 1) {
19685d4f98a2SYan Zheng 			*level = i;
19695d4f98a2SYan Zheng 			return 0;
19705d4f98a2SYan Zheng 		}
19715d4f98a2SYan Zheng 
19725d4f98a2SYan Zheng 		bytenr = btrfs_node_blockptr(eb, path->slots[i]);
1973581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &first_key, path->slots[i]);
1974581c1760SQu Wenruo 		eb = read_tree_block(fs_info, bytenr, ptr_gen, i - 1,
1975581c1760SQu Wenruo 				     &first_key);
197664c043deSLiu Bo 		if (IS_ERR(eb)) {
197764c043deSLiu Bo 			return PTR_ERR(eb);
197864c043deSLiu Bo 		} else if (!extent_buffer_uptodate(eb)) {
1979416bc658SJosef Bacik 			free_extent_buffer(eb);
1980416bc658SJosef Bacik 			return -EIO;
1981416bc658SJosef Bacik 		}
19825d4f98a2SYan Zheng 		BUG_ON(btrfs_header_level(eb) != i - 1);
19835d4f98a2SYan Zheng 		path->nodes[i - 1] = eb;
19845d4f98a2SYan Zheng 		path->slots[i - 1] = 0;
19855d4f98a2SYan Zheng 	}
19865d4f98a2SYan Zheng 	return 1;
19875d4f98a2SYan Zheng }
19885d4f98a2SYan Zheng 
19895d4f98a2SYan Zheng /*
19905d4f98a2SYan Zheng  * invalidate extent cache for file extents whose key in range of
19915d4f98a2SYan Zheng  * [min_key, max_key)
19925d4f98a2SYan Zheng  */
19935d4f98a2SYan Zheng static int invalidate_extent_cache(struct btrfs_root *root,
19945d4f98a2SYan Zheng 				   struct btrfs_key *min_key,
19955d4f98a2SYan Zheng 				   struct btrfs_key *max_key)
19965d4f98a2SYan Zheng {
19970b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
19985d4f98a2SYan Zheng 	struct inode *inode = NULL;
19995d4f98a2SYan Zheng 	u64 objectid;
20005d4f98a2SYan Zheng 	u64 start, end;
200133345d01SLi Zefan 	u64 ino;
20025d4f98a2SYan Zheng 
20035d4f98a2SYan Zheng 	objectid = min_key->objectid;
20045d4f98a2SYan Zheng 	while (1) {
20055d4f98a2SYan Zheng 		cond_resched();
20065d4f98a2SYan Zheng 		iput(inode);
20075d4f98a2SYan Zheng 
20085d4f98a2SYan Zheng 		if (objectid > max_key->objectid)
20095d4f98a2SYan Zheng 			break;
20105d4f98a2SYan Zheng 
20115d4f98a2SYan Zheng 		inode = find_next_inode(root, objectid);
20125d4f98a2SYan Zheng 		if (!inode)
20135d4f98a2SYan Zheng 			break;
20144a0cc7caSNikolay Borisov 		ino = btrfs_ino(BTRFS_I(inode));
20155d4f98a2SYan Zheng 
201633345d01SLi Zefan 		if (ino > max_key->objectid) {
20175d4f98a2SYan Zheng 			iput(inode);
20185d4f98a2SYan Zheng 			break;
20195d4f98a2SYan Zheng 		}
20205d4f98a2SYan Zheng 
202133345d01SLi Zefan 		objectid = ino + 1;
20225d4f98a2SYan Zheng 		if (!S_ISREG(inode->i_mode))
20235d4f98a2SYan Zheng 			continue;
20245d4f98a2SYan Zheng 
202533345d01SLi Zefan 		if (unlikely(min_key->objectid == ino)) {
20265d4f98a2SYan Zheng 			if (min_key->type > BTRFS_EXTENT_DATA_KEY)
20275d4f98a2SYan Zheng 				continue;
20285d4f98a2SYan Zheng 			if (min_key->type < BTRFS_EXTENT_DATA_KEY)
20295d4f98a2SYan Zheng 				start = 0;
20305d4f98a2SYan Zheng 			else {
20315d4f98a2SYan Zheng 				start = min_key->offset;
20320b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(start, fs_info->sectorsize));
20335d4f98a2SYan Zheng 			}
20345d4f98a2SYan Zheng 		} else {
20355d4f98a2SYan Zheng 			start = 0;
20365d4f98a2SYan Zheng 		}
20375d4f98a2SYan Zheng 
203833345d01SLi Zefan 		if (unlikely(max_key->objectid == ino)) {
20395d4f98a2SYan Zheng 			if (max_key->type < BTRFS_EXTENT_DATA_KEY)
20405d4f98a2SYan Zheng 				continue;
20415d4f98a2SYan Zheng 			if (max_key->type > BTRFS_EXTENT_DATA_KEY) {
20425d4f98a2SYan Zheng 				end = (u64)-1;
20435d4f98a2SYan Zheng 			} else {
20445d4f98a2SYan Zheng 				if (max_key->offset == 0)
20455d4f98a2SYan Zheng 					continue;
20465d4f98a2SYan Zheng 				end = max_key->offset;
20470b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
20485d4f98a2SYan Zheng 				end--;
20495d4f98a2SYan Zheng 			}
20505d4f98a2SYan Zheng 		} else {
20515d4f98a2SYan Zheng 			end = (u64)-1;
20525d4f98a2SYan Zheng 		}
20535d4f98a2SYan Zheng 
20545d4f98a2SYan Zheng 		/* the lock_extent waits for readpage to complete */
2055d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, start, end);
2056dcdbc059SNikolay Borisov 		btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 1);
2057d0082371SJeff Mahoney 		unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
20585d4f98a2SYan Zheng 	}
20595d4f98a2SYan Zheng 	return 0;
20605d4f98a2SYan Zheng }
20615d4f98a2SYan Zheng 
20625d4f98a2SYan Zheng static int find_next_key(struct btrfs_path *path, int level,
20635d4f98a2SYan Zheng 			 struct btrfs_key *key)
20645d4f98a2SYan Zheng 
20655d4f98a2SYan Zheng {
20665d4f98a2SYan Zheng 	while (level < BTRFS_MAX_LEVEL) {
20675d4f98a2SYan Zheng 		if (!path->nodes[level])
20685d4f98a2SYan Zheng 			break;
20695d4f98a2SYan Zheng 		if (path->slots[level] + 1 <
20705d4f98a2SYan Zheng 		    btrfs_header_nritems(path->nodes[level])) {
20715d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(path->nodes[level], key,
20725d4f98a2SYan Zheng 					      path->slots[level] + 1);
20735d4f98a2SYan Zheng 			return 0;
20745d4f98a2SYan Zheng 		}
20755d4f98a2SYan Zheng 		level++;
20765d4f98a2SYan Zheng 	}
20775d4f98a2SYan Zheng 	return 1;
20785d4f98a2SYan Zheng }
20795d4f98a2SYan Zheng 
20805d4f98a2SYan Zheng /*
2081d2311e69SQu Wenruo  * Insert current subvolume into reloc_control::dirty_subvol_roots
2082d2311e69SQu Wenruo  */
2083d2311e69SQu Wenruo static void insert_dirty_subvol(struct btrfs_trans_handle *trans,
2084d2311e69SQu Wenruo 				struct reloc_control *rc,
2085d2311e69SQu Wenruo 				struct btrfs_root *root)
2086d2311e69SQu Wenruo {
2087d2311e69SQu Wenruo 	struct btrfs_root *reloc_root = root->reloc_root;
2088d2311e69SQu Wenruo 	struct btrfs_root_item *reloc_root_item;
2089d2311e69SQu Wenruo 
2090d2311e69SQu Wenruo 	/* @root must be a subvolume tree root with a valid reloc tree */
2091d2311e69SQu Wenruo 	ASSERT(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
2092d2311e69SQu Wenruo 	ASSERT(reloc_root);
2093d2311e69SQu Wenruo 
2094d2311e69SQu Wenruo 	reloc_root_item = &reloc_root->root_item;
2095d2311e69SQu Wenruo 	memset(&reloc_root_item->drop_progress, 0,
2096d2311e69SQu Wenruo 		sizeof(reloc_root_item->drop_progress));
2097d2311e69SQu Wenruo 	reloc_root_item->drop_level = 0;
2098d2311e69SQu Wenruo 	btrfs_set_root_refs(reloc_root_item, 0);
2099d2311e69SQu Wenruo 	btrfs_update_reloc_root(trans, root);
2100d2311e69SQu Wenruo 
2101d2311e69SQu Wenruo 	if (list_empty(&root->reloc_dirty_list)) {
210200246528SJosef Bacik 		btrfs_grab_root(root);
2103d2311e69SQu Wenruo 		list_add_tail(&root->reloc_dirty_list, &rc->dirty_subvol_roots);
2104d2311e69SQu Wenruo 	}
2105d2311e69SQu Wenruo }
2106d2311e69SQu Wenruo 
2107d2311e69SQu Wenruo static int clean_dirty_subvols(struct reloc_control *rc)
2108d2311e69SQu Wenruo {
2109d2311e69SQu Wenruo 	struct btrfs_root *root;
2110d2311e69SQu Wenruo 	struct btrfs_root *next;
2111d2311e69SQu Wenruo 	int ret = 0;
211230d40577SQu Wenruo 	int ret2;
2113d2311e69SQu Wenruo 
2114d2311e69SQu Wenruo 	list_for_each_entry_safe(root, next, &rc->dirty_subvol_roots,
2115d2311e69SQu Wenruo 				 reloc_dirty_list) {
211630d40577SQu Wenruo 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
211730d40577SQu Wenruo 			/* Merged subvolume, cleanup its reloc root */
2118d2311e69SQu Wenruo 			struct btrfs_root *reloc_root = root->reloc_root;
2119d2311e69SQu Wenruo 
2120d2311e69SQu Wenruo 			list_del_init(&root->reloc_dirty_list);
2121d2311e69SQu Wenruo 			root->reloc_root = NULL;
21226282675eSQu Wenruo 			/*
21236282675eSQu Wenruo 			 * Need barrier to ensure clear_bit() only happens after
21246282675eSQu Wenruo 			 * root->reloc_root = NULL. Pairs with have_reloc_root.
21256282675eSQu Wenruo 			 */
21266282675eSQu Wenruo 			smp_wmb();
21271fac4a54SQu Wenruo 			clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
2128f28de8d8SJosef Bacik 			if (reloc_root) {
2129f44deb74SJosef Bacik 				/*
2130f44deb74SJosef Bacik 				 * btrfs_drop_snapshot drops our ref we hold for
2131f44deb74SJosef Bacik 				 * ->reloc_root.  If it fails however we must
2132f44deb74SJosef Bacik 				 * drop the ref ourselves.
2133f44deb74SJosef Bacik 				 */
2134f28de8d8SJosef Bacik 				ret2 = btrfs_drop_snapshot(reloc_root, 0, 1);
2135f44deb74SJosef Bacik 				if (ret2 < 0) {
2136f44deb74SJosef Bacik 					btrfs_put_root(reloc_root);
2137f44deb74SJosef Bacik 					if (!ret)
2138f28de8d8SJosef Bacik 						ret = ret2;
2139f28de8d8SJosef Bacik 				}
2140f44deb74SJosef Bacik 			}
214100246528SJosef Bacik 			btrfs_put_root(root);
214230d40577SQu Wenruo 		} else {
214330d40577SQu Wenruo 			/* Orphan reloc tree, just clean it up */
21440078a9f9SNikolay Borisov 			ret2 = btrfs_drop_snapshot(root, 0, 1);
2145f44deb74SJosef Bacik 			if (ret2 < 0) {
2146f44deb74SJosef Bacik 				btrfs_put_root(root);
2147f44deb74SJosef Bacik 				if (!ret)
214830d40577SQu Wenruo 					ret = ret2;
214930d40577SQu Wenruo 			}
2150d2311e69SQu Wenruo 		}
2151f44deb74SJosef Bacik 	}
2152d2311e69SQu Wenruo 	return ret;
2153d2311e69SQu Wenruo }
2154d2311e69SQu Wenruo 
2155d2311e69SQu Wenruo /*
21565d4f98a2SYan Zheng  * merge the relocated tree blocks in reloc tree with corresponding
21575d4f98a2SYan Zheng  * fs tree.
21585d4f98a2SYan Zheng  */
21595d4f98a2SYan Zheng static noinline_for_stack int merge_reloc_root(struct reloc_control *rc,
21605d4f98a2SYan Zheng 					       struct btrfs_root *root)
21615d4f98a2SYan Zheng {
21620b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
21635d4f98a2SYan Zheng 	struct btrfs_key key;
21645d4f98a2SYan Zheng 	struct btrfs_key next_key;
21659e6a0c52SJosef Bacik 	struct btrfs_trans_handle *trans = NULL;
21665d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
21675d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
21685d4f98a2SYan Zheng 	struct btrfs_path *path;
21693fd0a558SYan, Zheng 	struct extent_buffer *leaf;
21705d4f98a2SYan Zheng 	int level;
21715d4f98a2SYan Zheng 	int max_level;
21725d4f98a2SYan Zheng 	int replaced = 0;
21735d4f98a2SYan Zheng 	int ret;
21745d4f98a2SYan Zheng 	int err = 0;
21753fd0a558SYan, Zheng 	u32 min_reserved;
21765d4f98a2SYan Zheng 
21775d4f98a2SYan Zheng 	path = btrfs_alloc_path();
21785d4f98a2SYan Zheng 	if (!path)
21795d4f98a2SYan Zheng 		return -ENOMEM;
2180e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
21815d4f98a2SYan Zheng 
21825d4f98a2SYan Zheng 	reloc_root = root->reloc_root;
21835d4f98a2SYan Zheng 	root_item = &reloc_root->root_item;
21845d4f98a2SYan Zheng 
21855d4f98a2SYan Zheng 	if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
21865d4f98a2SYan Zheng 		level = btrfs_root_level(root_item);
218767439dadSDavid Sterba 		atomic_inc(&reloc_root->node->refs);
21885d4f98a2SYan Zheng 		path->nodes[level] = reloc_root->node;
21895d4f98a2SYan Zheng 		path->slots[level] = 0;
21905d4f98a2SYan Zheng 	} else {
21915d4f98a2SYan Zheng 		btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
21925d4f98a2SYan Zheng 
21935d4f98a2SYan Zheng 		level = root_item->drop_level;
21945d4f98a2SYan Zheng 		BUG_ON(level == 0);
21955d4f98a2SYan Zheng 		path->lowest_level = level;
21965d4f98a2SYan Zheng 		ret = btrfs_search_slot(NULL, reloc_root, &key, path, 0, 0);
219733c66f43SYan Zheng 		path->lowest_level = 0;
21985d4f98a2SYan Zheng 		if (ret < 0) {
21995d4f98a2SYan Zheng 			btrfs_free_path(path);
22005d4f98a2SYan Zheng 			return ret;
22015d4f98a2SYan Zheng 		}
22025d4f98a2SYan Zheng 
22035d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(path->nodes[level], &next_key,
22045d4f98a2SYan Zheng 				      path->slots[level]);
22055d4f98a2SYan Zheng 		WARN_ON(memcmp(&key, &next_key, sizeof(key)));
22065d4f98a2SYan Zheng 
22075d4f98a2SYan Zheng 		btrfs_unlock_up_safe(path, 0);
22085d4f98a2SYan Zheng 	}
22095d4f98a2SYan Zheng 
22100b246afaSJeff Mahoney 	min_reserved = fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
22115d4f98a2SYan Zheng 	memset(&next_key, 0, sizeof(next_key));
22125d4f98a2SYan Zheng 
22135d4f98a2SYan Zheng 	while (1) {
221408e007d2SMiao Xie 		ret = btrfs_block_rsv_refill(root, rc->block_rsv, min_reserved,
221508e007d2SMiao Xie 					     BTRFS_RESERVE_FLUSH_ALL);
22163fd0a558SYan, Zheng 		if (ret) {
22179e6a0c52SJosef Bacik 			err = ret;
22189e6a0c52SJosef Bacik 			goto out;
22193fd0a558SYan, Zheng 		}
22209e6a0c52SJosef Bacik 		trans = btrfs_start_transaction(root, 0);
22219e6a0c52SJosef Bacik 		if (IS_ERR(trans)) {
22229e6a0c52SJosef Bacik 			err = PTR_ERR(trans);
22239e6a0c52SJosef Bacik 			trans = NULL;
22249e6a0c52SJosef Bacik 			goto out;
22259e6a0c52SJosef Bacik 		}
22262abc726aSJosef Bacik 
22272abc726aSJosef Bacik 		/*
22282abc726aSJosef Bacik 		 * At this point we no longer have a reloc_control, so we can't
22292abc726aSJosef Bacik 		 * depend on btrfs_init_reloc_root to update our last_trans.
22302abc726aSJosef Bacik 		 *
22312abc726aSJosef Bacik 		 * But that's ok, we started the trans handle on our
22322abc726aSJosef Bacik 		 * corresponding fs_root, which means it's been added to the
22332abc726aSJosef Bacik 		 * dirty list.  At commit time we'll still call
22342abc726aSJosef Bacik 		 * btrfs_update_reloc_root() and update our root item
22352abc726aSJosef Bacik 		 * appropriately.
22362abc726aSJosef Bacik 		 */
22372abc726aSJosef Bacik 		reloc_root->last_trans = trans->transid;
22389e6a0c52SJosef Bacik 		trans->block_rsv = rc->block_rsv;
22393fd0a558SYan, Zheng 
22403fd0a558SYan, Zheng 		replaced = 0;
22415d4f98a2SYan Zheng 		max_level = level;
22425d4f98a2SYan Zheng 
22435d4f98a2SYan Zheng 		ret = walk_down_reloc_tree(reloc_root, path, &level);
22445d4f98a2SYan Zheng 		if (ret < 0) {
22455d4f98a2SYan Zheng 			err = ret;
22465d4f98a2SYan Zheng 			goto out;
22475d4f98a2SYan Zheng 		}
22485d4f98a2SYan Zheng 		if (ret > 0)
22495d4f98a2SYan Zheng 			break;
22505d4f98a2SYan Zheng 
22515d4f98a2SYan Zheng 		if (!find_next_key(path, level, &key) &&
22525d4f98a2SYan Zheng 		    btrfs_comp_cpu_keys(&next_key, &key) >= 0) {
22535d4f98a2SYan Zheng 			ret = 0;
22545d4f98a2SYan Zheng 		} else {
22553d0174f7SQu Wenruo 			ret = replace_path(trans, rc, root, reloc_root, path,
22563fd0a558SYan, Zheng 					   &next_key, level, max_level);
22575d4f98a2SYan Zheng 		}
22585d4f98a2SYan Zheng 		if (ret < 0) {
22595d4f98a2SYan Zheng 			err = ret;
22605d4f98a2SYan Zheng 			goto out;
22615d4f98a2SYan Zheng 		}
22625d4f98a2SYan Zheng 
22635d4f98a2SYan Zheng 		if (ret > 0) {
22645d4f98a2SYan Zheng 			level = ret;
22655d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(path->nodes[level], &key,
22665d4f98a2SYan Zheng 					      path->slots[level]);
22675d4f98a2SYan Zheng 			replaced = 1;
22685d4f98a2SYan Zheng 		}
22695d4f98a2SYan Zheng 
22705d4f98a2SYan Zheng 		ret = walk_up_reloc_tree(reloc_root, path, &level);
22715d4f98a2SYan Zheng 		if (ret > 0)
22725d4f98a2SYan Zheng 			break;
22735d4f98a2SYan Zheng 
22745d4f98a2SYan Zheng 		BUG_ON(level == 0);
22755d4f98a2SYan Zheng 		/*
22765d4f98a2SYan Zheng 		 * save the merging progress in the drop_progress.
22775d4f98a2SYan Zheng 		 * this is OK since root refs == 1 in this case.
22785d4f98a2SYan Zheng 		 */
22795d4f98a2SYan Zheng 		btrfs_node_key(path->nodes[level], &root_item->drop_progress,
22805d4f98a2SYan Zheng 			       path->slots[level]);
22815d4f98a2SYan Zheng 		root_item->drop_level = level;
22825d4f98a2SYan Zheng 
22833a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
22849e6a0c52SJosef Bacik 		trans = NULL;
22855d4f98a2SYan Zheng 
22862ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
22875d4f98a2SYan Zheng 
22885d4f98a2SYan Zheng 		if (replaced && rc->stage == UPDATE_DATA_PTRS)
22895d4f98a2SYan Zheng 			invalidate_extent_cache(root, &key, &next_key);
22905d4f98a2SYan Zheng 	}
22915d4f98a2SYan Zheng 
22925d4f98a2SYan Zheng 	/*
22935d4f98a2SYan Zheng 	 * handle the case only one block in the fs tree need to be
22945d4f98a2SYan Zheng 	 * relocated and the block is tree root.
22955d4f98a2SYan Zheng 	 */
22965d4f98a2SYan Zheng 	leaf = btrfs_lock_root_node(root);
22975d4f98a2SYan Zheng 	ret = btrfs_cow_block(trans, root, leaf, NULL, 0, &leaf);
22985d4f98a2SYan Zheng 	btrfs_tree_unlock(leaf);
22995d4f98a2SYan Zheng 	free_extent_buffer(leaf);
23005d4f98a2SYan Zheng 	if (ret < 0)
23015d4f98a2SYan Zheng 		err = ret;
23025d4f98a2SYan Zheng out:
23035d4f98a2SYan Zheng 	btrfs_free_path(path);
23045d4f98a2SYan Zheng 
2305d2311e69SQu Wenruo 	if (err == 0)
2306d2311e69SQu Wenruo 		insert_dirty_subvol(trans, rc, root);
23075d4f98a2SYan Zheng 
23089e6a0c52SJosef Bacik 	if (trans)
23093a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
23105d4f98a2SYan Zheng 
23112ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
23125d4f98a2SYan Zheng 
23135d4f98a2SYan Zheng 	if (replaced && rc->stage == UPDATE_DATA_PTRS)
23145d4f98a2SYan Zheng 		invalidate_extent_cache(root, &key, &next_key);
23155d4f98a2SYan Zheng 
23165d4f98a2SYan Zheng 	return err;
23175d4f98a2SYan Zheng }
23185d4f98a2SYan Zheng 
23193fd0a558SYan, Zheng static noinline_for_stack
23203fd0a558SYan, Zheng int prepare_to_merge(struct reloc_control *rc, int err)
23215d4f98a2SYan Zheng {
23223fd0a558SYan, Zheng 	struct btrfs_root *root = rc->extent_root;
23230b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
23243fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
23255d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
23263fd0a558SYan, Zheng 	LIST_HEAD(reloc_roots);
23273fd0a558SYan, Zheng 	u64 num_bytes = 0;
23283fd0a558SYan, Zheng 	int ret;
23293fd0a558SYan, Zheng 
23300b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
23310b246afaSJeff Mahoney 	rc->merging_rsv_size += fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
23323fd0a558SYan, Zheng 	rc->merging_rsv_size += rc->nodes_relocated * 2;
23330b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
23347585717fSChris Mason 
23353fd0a558SYan, Zheng again:
23363fd0a558SYan, Zheng 	if (!err) {
23373fd0a558SYan, Zheng 		num_bytes = rc->merging_rsv_size;
233808e007d2SMiao Xie 		ret = btrfs_block_rsv_add(root, rc->block_rsv, num_bytes,
233908e007d2SMiao Xie 					  BTRFS_RESERVE_FLUSH_ALL);
23403fd0a558SYan, Zheng 		if (ret)
23413fd0a558SYan, Zheng 			err = ret;
23423fd0a558SYan, Zheng 	}
23433fd0a558SYan, Zheng 
23447a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
23453612b495STsutomu Itoh 	if (IS_ERR(trans)) {
23463612b495STsutomu Itoh 		if (!err)
23472ff7e61eSJeff Mahoney 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
234863f018beSNikolay Borisov 						num_bytes, NULL);
23493612b495STsutomu Itoh 		return PTR_ERR(trans);
23503612b495STsutomu Itoh 	}
23513fd0a558SYan, Zheng 
23523fd0a558SYan, Zheng 	if (!err) {
23533fd0a558SYan, Zheng 		if (num_bytes != rc->merging_rsv_size) {
23543a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
23552ff7e61eSJeff Mahoney 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
235663f018beSNikolay Borisov 						num_bytes, NULL);
23573fd0a558SYan, Zheng 			goto again;
23583fd0a558SYan, Zheng 		}
23593fd0a558SYan, Zheng 	}
23603fd0a558SYan, Zheng 
23613fd0a558SYan, Zheng 	rc->merge_reloc_tree = 1;
23623fd0a558SYan, Zheng 
23633fd0a558SYan, Zheng 	while (!list_empty(&rc->reloc_roots)) {
23643fd0a558SYan, Zheng 		reloc_root = list_entry(rc->reloc_roots.next,
23653fd0a558SYan, Zheng 					struct btrfs_root, root_list);
23663fd0a558SYan, Zheng 		list_del_init(&reloc_root->root_list);
23673fd0a558SYan, Zheng 
23680b246afaSJeff Mahoney 		root = read_fs_root(fs_info, reloc_root->root_key.offset);
23693fd0a558SYan, Zheng 		BUG_ON(IS_ERR(root));
23703fd0a558SYan, Zheng 		BUG_ON(root->reloc_root != reloc_root);
23713fd0a558SYan, Zheng 
23723fd0a558SYan, Zheng 		/*
23733fd0a558SYan, Zheng 		 * set reference count to 1, so btrfs_recover_relocation
23743fd0a558SYan, Zheng 		 * knows it should resumes merging
23753fd0a558SYan, Zheng 		 */
23763fd0a558SYan, Zheng 		if (!err)
23773fd0a558SYan, Zheng 			btrfs_set_root_refs(&reloc_root->root_item, 1);
23783fd0a558SYan, Zheng 		btrfs_update_reloc_root(trans, root);
23793fd0a558SYan, Zheng 
23803fd0a558SYan, Zheng 		list_add(&reloc_root->root_list, &reloc_roots);
238100246528SJosef Bacik 		btrfs_put_root(root);
23823fd0a558SYan, Zheng 	}
23833fd0a558SYan, Zheng 
23843fd0a558SYan, Zheng 	list_splice(&reloc_roots, &rc->reloc_roots);
23853fd0a558SYan, Zheng 
23863fd0a558SYan, Zheng 	if (!err)
23873a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
23883fd0a558SYan, Zheng 	else
23893a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
23903fd0a558SYan, Zheng 	return err;
23913fd0a558SYan, Zheng }
23923fd0a558SYan, Zheng 
23933fd0a558SYan, Zheng static noinline_for_stack
2394aca1bba6SLiu Bo void free_reloc_roots(struct list_head *list)
2395aca1bba6SLiu Bo {
2396aca1bba6SLiu Bo 	struct btrfs_root *reloc_root;
2397aca1bba6SLiu Bo 
2398aca1bba6SLiu Bo 	while (!list_empty(list)) {
2399aca1bba6SLiu Bo 		reloc_root = list_entry(list->next, struct btrfs_root,
2400aca1bba6SLiu Bo 					root_list);
2401bb166d72SNaohiro Aota 		__del_reloc_root(reloc_root);
2402aca1bba6SLiu Bo 	}
2403aca1bba6SLiu Bo }
2404aca1bba6SLiu Bo 
2405aca1bba6SLiu Bo static noinline_for_stack
240694404e82SDavid Sterba void merge_reloc_roots(struct reloc_control *rc)
24073fd0a558SYan, Zheng {
24080b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
24095d4f98a2SYan Zheng 	struct btrfs_root *root;
24105d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
24113fd0a558SYan, Zheng 	LIST_HEAD(reloc_roots);
24123fd0a558SYan, Zheng 	int found = 0;
2413aca1bba6SLiu Bo 	int ret = 0;
24143fd0a558SYan, Zheng again:
24153fd0a558SYan, Zheng 	root = rc->extent_root;
24167585717fSChris Mason 
24177585717fSChris Mason 	/*
24187585717fSChris Mason 	 * this serializes us with btrfs_record_root_in_transaction,
24197585717fSChris Mason 	 * we have to make sure nobody is in the middle of
24207585717fSChris Mason 	 * adding their roots to the list while we are
24217585717fSChris Mason 	 * doing this splice
24227585717fSChris Mason 	 */
24230b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
24243fd0a558SYan, Zheng 	list_splice_init(&rc->reloc_roots, &reloc_roots);
24250b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
24265d4f98a2SYan Zheng 
24273fd0a558SYan, Zheng 	while (!list_empty(&reloc_roots)) {
24283fd0a558SYan, Zheng 		found = 1;
24293fd0a558SYan, Zheng 		reloc_root = list_entry(reloc_roots.next,
24303fd0a558SYan, Zheng 					struct btrfs_root, root_list);
24315d4f98a2SYan Zheng 
24325d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
24330b246afaSJeff Mahoney 			root = read_fs_root(fs_info,
24345d4f98a2SYan Zheng 					    reloc_root->root_key.offset);
24355d4f98a2SYan Zheng 			BUG_ON(IS_ERR(root));
24365d4f98a2SYan Zheng 			BUG_ON(root->reloc_root != reloc_root);
24375d4f98a2SYan Zheng 
24383fd0a558SYan, Zheng 			ret = merge_reloc_root(rc, root);
243900246528SJosef Bacik 			btrfs_put_root(root);
2440b37b39cdSJosef Bacik 			if (ret) {
244125e293c2SWang Shilong 				if (list_empty(&reloc_root->root_list))
244225e293c2SWang Shilong 					list_add_tail(&reloc_root->root_list,
244325e293c2SWang Shilong 						      &reloc_roots);
2444aca1bba6SLiu Bo 				goto out;
2445b37b39cdSJosef Bacik 			}
24463fd0a558SYan, Zheng 		} else {
24473fd0a558SYan, Zheng 			list_del_init(&reloc_root->root_list);
244830d40577SQu Wenruo 			/* Don't forget to queue this reloc root for cleanup */
244930d40577SQu Wenruo 			list_add_tail(&reloc_root->reloc_dirty_list,
245030d40577SQu Wenruo 				      &rc->dirty_subvol_roots);
24513fd0a558SYan, Zheng 		}
24525d4f98a2SYan Zheng 	}
24535d4f98a2SYan Zheng 
24543fd0a558SYan, Zheng 	if (found) {
24553fd0a558SYan, Zheng 		found = 0;
24563fd0a558SYan, Zheng 		goto again;
24575d4f98a2SYan Zheng 	}
2458aca1bba6SLiu Bo out:
2459aca1bba6SLiu Bo 	if (ret) {
24600b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret, NULL);
2461aca1bba6SLiu Bo 		if (!list_empty(&reloc_roots))
2462aca1bba6SLiu Bo 			free_reloc_roots(&reloc_roots);
2463467bb1d2SWang Shilong 
2464467bb1d2SWang Shilong 		/* new reloc root may be added */
24650b246afaSJeff Mahoney 		mutex_lock(&fs_info->reloc_mutex);
2466467bb1d2SWang Shilong 		list_splice_init(&rc->reloc_roots, &reloc_roots);
24670b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
2468467bb1d2SWang Shilong 		if (!list_empty(&reloc_roots))
2469467bb1d2SWang Shilong 			free_reloc_roots(&reloc_roots);
2470aca1bba6SLiu Bo 	}
2471aca1bba6SLiu Bo 
24727b7b7431SJosef Bacik 	/*
24737b7b7431SJosef Bacik 	 * We used to have
24747b7b7431SJosef Bacik 	 *
24757b7b7431SJosef Bacik 	 * BUG_ON(!RB_EMPTY_ROOT(&rc->reloc_root_tree.rb_root));
24767b7b7431SJosef Bacik 	 *
24777b7b7431SJosef Bacik 	 * here, but it's wrong.  If we fail to start the transaction in
24787b7b7431SJosef Bacik 	 * prepare_to_merge() we will have only 0 ref reloc roots, none of which
24797b7b7431SJosef Bacik 	 * have actually been removed from the reloc_root_tree rb tree.  This is
24807b7b7431SJosef Bacik 	 * fine because we're bailing here, and we hold a reference on the root
24817b7b7431SJosef Bacik 	 * for the list that holds it, so these roots will be cleaned up when we
24827b7b7431SJosef Bacik 	 * do the reloc_dirty_list afterwards.  Meanwhile the root->reloc_root
24837b7b7431SJosef Bacik 	 * will be cleaned up on unmount.
24847b7b7431SJosef Bacik 	 *
24857b7b7431SJosef Bacik 	 * The remaining nodes will be cleaned up by free_reloc_control.
24867b7b7431SJosef Bacik 	 */
24875d4f98a2SYan Zheng }
24885d4f98a2SYan Zheng 
24895d4f98a2SYan Zheng static void free_block_list(struct rb_root *blocks)
24905d4f98a2SYan Zheng {
24915d4f98a2SYan Zheng 	struct tree_block *block;
24925d4f98a2SYan Zheng 	struct rb_node *rb_node;
24935d4f98a2SYan Zheng 	while ((rb_node = rb_first(blocks))) {
24945d4f98a2SYan Zheng 		block = rb_entry(rb_node, struct tree_block, rb_node);
24955d4f98a2SYan Zheng 		rb_erase(rb_node, blocks);
24965d4f98a2SYan Zheng 		kfree(block);
24975d4f98a2SYan Zheng 	}
24985d4f98a2SYan Zheng }
24995d4f98a2SYan Zheng 
25005d4f98a2SYan Zheng static int record_reloc_root_in_trans(struct btrfs_trans_handle *trans,
25015d4f98a2SYan Zheng 				      struct btrfs_root *reloc_root)
25025d4f98a2SYan Zheng {
25030b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = reloc_root->fs_info;
25045d4f98a2SYan Zheng 	struct btrfs_root *root;
2505442b1ac5SJosef Bacik 	int ret;
25065d4f98a2SYan Zheng 
25075d4f98a2SYan Zheng 	if (reloc_root->last_trans == trans->transid)
25085d4f98a2SYan Zheng 		return 0;
25095d4f98a2SYan Zheng 
25100b246afaSJeff Mahoney 	root = read_fs_root(fs_info, reloc_root->root_key.offset);
25115d4f98a2SYan Zheng 	BUG_ON(IS_ERR(root));
25125d4f98a2SYan Zheng 	BUG_ON(root->reloc_root != reloc_root);
2513442b1ac5SJosef Bacik 	ret = btrfs_record_root_in_trans(trans, root);
251400246528SJosef Bacik 	btrfs_put_root(root);
25155d4f98a2SYan Zheng 
2516442b1ac5SJosef Bacik 	return ret;
25175d4f98a2SYan Zheng }
25185d4f98a2SYan Zheng 
25193fd0a558SYan, Zheng static noinline_for_stack
25203fd0a558SYan, Zheng struct btrfs_root *select_reloc_root(struct btrfs_trans_handle *trans,
25213fd0a558SYan, Zheng 				     struct reloc_control *rc,
2522a26195a5SQu Wenruo 				     struct btrfs_backref_node *node,
2523a26195a5SQu Wenruo 				     struct btrfs_backref_edge *edges[])
25245d4f98a2SYan Zheng {
2525a26195a5SQu Wenruo 	struct btrfs_backref_node *next;
25265d4f98a2SYan Zheng 	struct btrfs_root *root;
25273fd0a558SYan, Zheng 	int index = 0;
25283fd0a558SYan, Zheng 
25295d4f98a2SYan Zheng 	next = node;
25305d4f98a2SYan Zheng 	while (1) {
25315d4f98a2SYan Zheng 		cond_resched();
25325d4f98a2SYan Zheng 		next = walk_up_backref(next, edges, &index);
25335d4f98a2SYan Zheng 		root = next->root;
25343fd0a558SYan, Zheng 		BUG_ON(!root);
253527cdeb70SMiao Xie 		BUG_ON(!test_bit(BTRFS_ROOT_REF_COWS, &root->state));
25365d4f98a2SYan Zheng 
25375d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
25385d4f98a2SYan Zheng 			record_reloc_root_in_trans(trans, root);
25395d4f98a2SYan Zheng 			break;
25405d4f98a2SYan Zheng 		}
25415d4f98a2SYan Zheng 
25425d4f98a2SYan Zheng 		btrfs_record_root_in_trans(trans, root);
25433fd0a558SYan, Zheng 		root = root->reloc_root;
25443fd0a558SYan, Zheng 
25453fd0a558SYan, Zheng 		if (next->new_bytenr != root->node->start) {
25463fd0a558SYan, Zheng 			BUG_ON(next->new_bytenr);
25473fd0a558SYan, Zheng 			BUG_ON(!list_empty(&next->list));
25483fd0a558SYan, Zheng 			next->new_bytenr = root->node->start;
254900246528SJosef Bacik 			btrfs_put_root(next->root);
255000246528SJosef Bacik 			next->root = btrfs_grab_root(root);
25510b530bc5SJosef Bacik 			ASSERT(next->root);
25523fd0a558SYan, Zheng 			list_add_tail(&next->list,
25533fd0a558SYan, Zheng 				      &rc->backref_cache.changed);
25549569cc20SQu Wenruo 			mark_block_processed(rc, next);
25555d4f98a2SYan Zheng 			break;
25565d4f98a2SYan Zheng 		}
25575d4f98a2SYan Zheng 
25583fd0a558SYan, Zheng 		WARN_ON(1);
25595d4f98a2SYan Zheng 		root = NULL;
25605d4f98a2SYan Zheng 		next = walk_down_backref(edges, &index);
25615d4f98a2SYan Zheng 		if (!next || next->level <= node->level)
25625d4f98a2SYan Zheng 			break;
25635d4f98a2SYan Zheng 	}
25643fd0a558SYan, Zheng 	if (!root)
25653fd0a558SYan, Zheng 		return NULL;
25665d4f98a2SYan Zheng 
25673fd0a558SYan, Zheng 	next = node;
25683fd0a558SYan, Zheng 	/* setup backref node path for btrfs_reloc_cow_block */
25693fd0a558SYan, Zheng 	while (1) {
25703fd0a558SYan, Zheng 		rc->backref_cache.path[next->level] = next;
25713fd0a558SYan, Zheng 		if (--index < 0)
25723fd0a558SYan, Zheng 			break;
25733fd0a558SYan, Zheng 		next = edges[index]->node[UPPER];
25743fd0a558SYan, Zheng 	}
25755d4f98a2SYan Zheng 	return root;
25765d4f98a2SYan Zheng }
25775d4f98a2SYan Zheng 
25783fd0a558SYan, Zheng /*
25793fd0a558SYan, Zheng  * select a tree root for relocation. return NULL if the block
25803fd0a558SYan, Zheng  * is reference counted. we should use do_relocation() in this
25813fd0a558SYan, Zheng  * case. return a tree root pointer if the block isn't reference
25823fd0a558SYan, Zheng  * counted. return -ENOENT if the block is root of reloc tree.
25833fd0a558SYan, Zheng  */
25845d4f98a2SYan Zheng static noinline_for_stack
2585a26195a5SQu Wenruo struct btrfs_root *select_one_root(struct btrfs_backref_node *node)
25865d4f98a2SYan Zheng {
2587a26195a5SQu Wenruo 	struct btrfs_backref_node *next;
25883fd0a558SYan, Zheng 	struct btrfs_root *root;
25893fd0a558SYan, Zheng 	struct btrfs_root *fs_root = NULL;
2590a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
25913fd0a558SYan, Zheng 	int index = 0;
25923fd0a558SYan, Zheng 
25933fd0a558SYan, Zheng 	next = node;
25943fd0a558SYan, Zheng 	while (1) {
25953fd0a558SYan, Zheng 		cond_resched();
25963fd0a558SYan, Zheng 		next = walk_up_backref(next, edges, &index);
25973fd0a558SYan, Zheng 		root = next->root;
25983fd0a558SYan, Zheng 		BUG_ON(!root);
25993fd0a558SYan, Zheng 
260025985edcSLucas De Marchi 		/* no other choice for non-references counted tree */
260127cdeb70SMiao Xie 		if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
26023fd0a558SYan, Zheng 			return root;
26033fd0a558SYan, Zheng 
26043fd0a558SYan, Zheng 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID)
26053fd0a558SYan, Zheng 			fs_root = root;
26063fd0a558SYan, Zheng 
26073fd0a558SYan, Zheng 		if (next != node)
26083fd0a558SYan, Zheng 			return NULL;
26093fd0a558SYan, Zheng 
26103fd0a558SYan, Zheng 		next = walk_down_backref(edges, &index);
26113fd0a558SYan, Zheng 		if (!next || next->level <= node->level)
26123fd0a558SYan, Zheng 			break;
26133fd0a558SYan, Zheng 	}
26143fd0a558SYan, Zheng 
26153fd0a558SYan, Zheng 	if (!fs_root)
26163fd0a558SYan, Zheng 		return ERR_PTR(-ENOENT);
26173fd0a558SYan, Zheng 	return fs_root;
26185d4f98a2SYan Zheng }
26195d4f98a2SYan Zheng 
26205d4f98a2SYan Zheng static noinline_for_stack
26213fd0a558SYan, Zheng u64 calcu_metadata_size(struct reloc_control *rc,
2622a26195a5SQu Wenruo 			struct btrfs_backref_node *node, int reserve)
26235d4f98a2SYan Zheng {
26240b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2625a26195a5SQu Wenruo 	struct btrfs_backref_node *next = node;
2626a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2627a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
26283fd0a558SYan, Zheng 	u64 num_bytes = 0;
26293fd0a558SYan, Zheng 	int index = 0;
26305d4f98a2SYan Zheng 
26313fd0a558SYan, Zheng 	BUG_ON(reserve && node->processed);
26323fd0a558SYan, Zheng 
26333fd0a558SYan, Zheng 	while (next) {
26343fd0a558SYan, Zheng 		cond_resched();
26355d4f98a2SYan Zheng 		while (1) {
26363fd0a558SYan, Zheng 			if (next->processed && (reserve || next != node))
26375d4f98a2SYan Zheng 				break;
26385d4f98a2SYan Zheng 
26390b246afaSJeff Mahoney 			num_bytes += fs_info->nodesize;
26403fd0a558SYan, Zheng 
26413fd0a558SYan, Zheng 			if (list_empty(&next->upper))
26423fd0a558SYan, Zheng 				break;
26433fd0a558SYan, Zheng 
26443fd0a558SYan, Zheng 			edge = list_entry(next->upper.next,
2645a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[LOWER]);
26463fd0a558SYan, Zheng 			edges[index++] = edge;
26473fd0a558SYan, Zheng 			next = edge->node[UPPER];
26485d4f98a2SYan Zheng 		}
26493fd0a558SYan, Zheng 		next = walk_down_backref(edges, &index);
26503fd0a558SYan, Zheng 	}
26513fd0a558SYan, Zheng 	return num_bytes;
26523fd0a558SYan, Zheng }
26533fd0a558SYan, Zheng 
26543fd0a558SYan, Zheng static int reserve_metadata_space(struct btrfs_trans_handle *trans,
26553fd0a558SYan, Zheng 				  struct reloc_control *rc,
2656a26195a5SQu Wenruo 				  struct btrfs_backref_node *node)
26573fd0a558SYan, Zheng {
26583fd0a558SYan, Zheng 	struct btrfs_root *root = rc->extent_root;
2659da17066cSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
26603fd0a558SYan, Zheng 	u64 num_bytes;
26613fd0a558SYan, Zheng 	int ret;
26620647bf56SWang Shilong 	u64 tmp;
26633fd0a558SYan, Zheng 
26643fd0a558SYan, Zheng 	num_bytes = calcu_metadata_size(rc, node, 1) * 2;
26653fd0a558SYan, Zheng 
26663fd0a558SYan, Zheng 	trans->block_rsv = rc->block_rsv;
26670647bf56SWang Shilong 	rc->reserved_bytes += num_bytes;
26688ca17f0fSJosef Bacik 
26698ca17f0fSJosef Bacik 	/*
26708ca17f0fSJosef Bacik 	 * We are under a transaction here so we can only do limited flushing.
26718ca17f0fSJosef Bacik 	 * If we get an enospc just kick back -EAGAIN so we know to drop the
26728ca17f0fSJosef Bacik 	 * transaction and try to refill when we can flush all the things.
26738ca17f0fSJosef Bacik 	 */
26740647bf56SWang Shilong 	ret = btrfs_block_rsv_refill(root, rc->block_rsv, num_bytes,
26758ca17f0fSJosef Bacik 				BTRFS_RESERVE_FLUSH_LIMIT);
26763fd0a558SYan, Zheng 	if (ret) {
2677da17066cSJeff Mahoney 		tmp = fs_info->nodesize * RELOCATION_RESERVED_NODES;
26780647bf56SWang Shilong 		while (tmp <= rc->reserved_bytes)
26790647bf56SWang Shilong 			tmp <<= 1;
26800647bf56SWang Shilong 		/*
26810647bf56SWang Shilong 		 * only one thread can access block_rsv at this point,
26820647bf56SWang Shilong 		 * so we don't need hold lock to protect block_rsv.
26830647bf56SWang Shilong 		 * we expand more reservation size here to allow enough
268452042d8eSAndrea Gelmini 		 * space for relocation and we will return earlier in
26850647bf56SWang Shilong 		 * enospc case.
26860647bf56SWang Shilong 		 */
2687da17066cSJeff Mahoney 		rc->block_rsv->size = tmp + fs_info->nodesize *
26880647bf56SWang Shilong 				      RELOCATION_RESERVED_NODES;
26898ca17f0fSJosef Bacik 		return -EAGAIN;
26903fd0a558SYan, Zheng 	}
26913fd0a558SYan, Zheng 
26923fd0a558SYan, Zheng 	return 0;
26933fd0a558SYan, Zheng }
26943fd0a558SYan, Zheng 
26955d4f98a2SYan Zheng /*
26965d4f98a2SYan Zheng  * relocate a block tree, and then update pointers in upper level
26975d4f98a2SYan Zheng  * blocks that reference the block to point to the new location.
26985d4f98a2SYan Zheng  *
26995d4f98a2SYan Zheng  * if called by link_to_upper, the block has already been relocated.
27005d4f98a2SYan Zheng  * in that case this function just updates pointers.
27015d4f98a2SYan Zheng  */
27025d4f98a2SYan Zheng static int do_relocation(struct btrfs_trans_handle *trans,
27033fd0a558SYan, Zheng 			 struct reloc_control *rc,
2704a26195a5SQu Wenruo 			 struct btrfs_backref_node *node,
27055d4f98a2SYan Zheng 			 struct btrfs_key *key,
27065d4f98a2SYan Zheng 			 struct btrfs_path *path, int lowest)
27075d4f98a2SYan Zheng {
27082ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2709a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
2710a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2711a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
27125d4f98a2SYan Zheng 	struct btrfs_root *root;
27135d4f98a2SYan Zheng 	struct extent_buffer *eb;
27145d4f98a2SYan Zheng 	u32 blocksize;
27155d4f98a2SYan Zheng 	u64 bytenr;
27165d4f98a2SYan Zheng 	u64 generation;
27175d4f98a2SYan Zheng 	int slot;
27185d4f98a2SYan Zheng 	int ret;
27195d4f98a2SYan Zheng 	int err = 0;
27205d4f98a2SYan Zheng 
27215d4f98a2SYan Zheng 	BUG_ON(lowest && node->eb);
27225d4f98a2SYan Zheng 
27235d4f98a2SYan Zheng 	path->lowest_level = node->level + 1;
27243fd0a558SYan, Zheng 	rc->backref_cache.path[node->level] = node;
27255d4f98a2SYan Zheng 	list_for_each_entry(edge, &node->upper, list[LOWER]) {
2726581c1760SQu Wenruo 		struct btrfs_key first_key;
272782fa113fSQu Wenruo 		struct btrfs_ref ref = { 0 };
2728581c1760SQu Wenruo 
27295d4f98a2SYan Zheng 		cond_resched();
27305d4f98a2SYan Zheng 
27315d4f98a2SYan Zheng 		upper = edge->node[UPPER];
2732dc4103f9SWang Shilong 		root = select_reloc_root(trans, rc, upper, edges);
27333fd0a558SYan, Zheng 		BUG_ON(!root);
27345d4f98a2SYan Zheng 
27353fd0a558SYan, Zheng 		if (upper->eb && !upper->locked) {
27363fd0a558SYan, Zheng 			if (!lowest) {
27373fd0a558SYan, Zheng 				ret = btrfs_bin_search(upper->eb, key,
27383fd0a558SYan, Zheng 						       upper->level, &slot);
2739cbca7d59SFilipe Manana 				if (ret < 0) {
2740cbca7d59SFilipe Manana 					err = ret;
2741cbca7d59SFilipe Manana 					goto next;
2742cbca7d59SFilipe Manana 				}
27433fd0a558SYan, Zheng 				BUG_ON(ret);
27443fd0a558SYan, Zheng 				bytenr = btrfs_node_blockptr(upper->eb, slot);
27453fd0a558SYan, Zheng 				if (node->eb->start == bytenr)
27463fd0a558SYan, Zheng 					goto next;
27473fd0a558SYan, Zheng 			}
2748b0fe7078SQu Wenruo 			btrfs_backref_drop_node_buffer(upper);
27493fd0a558SYan, Zheng 		}
27505d4f98a2SYan Zheng 
27515d4f98a2SYan Zheng 		if (!upper->eb) {
27525d4f98a2SYan Zheng 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
27533561b9dbSLiu Bo 			if (ret) {
27543561b9dbSLiu Bo 				if (ret < 0)
27555d4f98a2SYan Zheng 					err = ret;
27563561b9dbSLiu Bo 				else
27573561b9dbSLiu Bo 					err = -ENOENT;
27583561b9dbSLiu Bo 
27593561b9dbSLiu Bo 				btrfs_release_path(path);
27605d4f98a2SYan Zheng 				break;
27615d4f98a2SYan Zheng 			}
27625d4f98a2SYan Zheng 
27633fd0a558SYan, Zheng 			if (!upper->eb) {
27643fd0a558SYan, Zheng 				upper->eb = path->nodes[upper->level];
27653fd0a558SYan, Zheng 				path->nodes[upper->level] = NULL;
27663fd0a558SYan, Zheng 			} else {
27673fd0a558SYan, Zheng 				BUG_ON(upper->eb != path->nodes[upper->level]);
27683fd0a558SYan, Zheng 			}
27693fd0a558SYan, Zheng 
27703fd0a558SYan, Zheng 			upper->locked = 1;
27713fd0a558SYan, Zheng 			path->locks[upper->level] = 0;
27723fd0a558SYan, Zheng 
27735d4f98a2SYan Zheng 			slot = path->slots[upper->level];
2774b3b4aa74SDavid Sterba 			btrfs_release_path(path);
27755d4f98a2SYan Zheng 		} else {
27765d4f98a2SYan Zheng 			ret = btrfs_bin_search(upper->eb, key, upper->level,
27775d4f98a2SYan Zheng 					       &slot);
2778cbca7d59SFilipe Manana 			if (ret < 0) {
2779cbca7d59SFilipe Manana 				err = ret;
2780cbca7d59SFilipe Manana 				goto next;
2781cbca7d59SFilipe Manana 			}
27825d4f98a2SYan Zheng 			BUG_ON(ret);
27835d4f98a2SYan Zheng 		}
27845d4f98a2SYan Zheng 
27855d4f98a2SYan Zheng 		bytenr = btrfs_node_blockptr(upper->eb, slot);
27863fd0a558SYan, Zheng 		if (lowest) {
27874547f4d8SLiu Bo 			if (bytenr != node->bytenr) {
27884547f4d8SLiu Bo 				btrfs_err(root->fs_info,
27894547f4d8SLiu Bo 		"lowest leaf/node mismatch: bytenr %llu node->bytenr %llu slot %d upper %llu",
27904547f4d8SLiu Bo 					  bytenr, node->bytenr, slot,
27914547f4d8SLiu Bo 					  upper->eb->start);
27924547f4d8SLiu Bo 				err = -EIO;
27934547f4d8SLiu Bo 				goto next;
27944547f4d8SLiu Bo 			}
27955d4f98a2SYan Zheng 		} else {
27963fd0a558SYan, Zheng 			if (node->eb->start == bytenr)
27973fd0a558SYan, Zheng 				goto next;
27985d4f98a2SYan Zheng 		}
27995d4f98a2SYan Zheng 
2800da17066cSJeff Mahoney 		blocksize = root->fs_info->nodesize;
28015d4f98a2SYan Zheng 		generation = btrfs_node_ptr_generation(upper->eb, slot);
2802581c1760SQu Wenruo 		btrfs_node_key_to_cpu(upper->eb, &first_key, slot);
2803581c1760SQu Wenruo 		eb = read_tree_block(fs_info, bytenr, generation,
2804581c1760SQu Wenruo 				     upper->level - 1, &first_key);
280564c043deSLiu Bo 		if (IS_ERR(eb)) {
280664c043deSLiu Bo 			err = PTR_ERR(eb);
280764c043deSLiu Bo 			goto next;
280864c043deSLiu Bo 		} else if (!extent_buffer_uptodate(eb)) {
2809416bc658SJosef Bacik 			free_extent_buffer(eb);
281097d9a8a4STsutomu Itoh 			err = -EIO;
281197d9a8a4STsutomu Itoh 			goto next;
281297d9a8a4STsutomu Itoh 		}
28135d4f98a2SYan Zheng 		btrfs_tree_lock(eb);
28148bead258SDavid Sterba 		btrfs_set_lock_blocking_write(eb);
28155d4f98a2SYan Zheng 
28165d4f98a2SYan Zheng 		if (!node->eb) {
28175d4f98a2SYan Zheng 			ret = btrfs_cow_block(trans, root, eb, upper->eb,
28185d4f98a2SYan Zheng 					      slot, &eb);
28193fd0a558SYan, Zheng 			btrfs_tree_unlock(eb);
28203fd0a558SYan, Zheng 			free_extent_buffer(eb);
28215d4f98a2SYan Zheng 			if (ret < 0) {
28225d4f98a2SYan Zheng 				err = ret;
28233fd0a558SYan, Zheng 				goto next;
28245d4f98a2SYan Zheng 			}
28253fd0a558SYan, Zheng 			BUG_ON(node->eb != eb);
28265d4f98a2SYan Zheng 		} else {
28275d4f98a2SYan Zheng 			btrfs_set_node_blockptr(upper->eb, slot,
28285d4f98a2SYan Zheng 						node->eb->start);
28295d4f98a2SYan Zheng 			btrfs_set_node_ptr_generation(upper->eb, slot,
28305d4f98a2SYan Zheng 						      trans->transid);
28315d4f98a2SYan Zheng 			btrfs_mark_buffer_dirty(upper->eb);
28325d4f98a2SYan Zheng 
283382fa113fSQu Wenruo 			btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF,
28345d4f98a2SYan Zheng 					       node->eb->start, blocksize,
283582fa113fSQu Wenruo 					       upper->eb->start);
283682fa113fSQu Wenruo 			ref.real_root = root->root_key.objectid;
283782fa113fSQu Wenruo 			btrfs_init_tree_ref(&ref, node->level,
283882fa113fSQu Wenruo 					    btrfs_header_owner(upper->eb));
283982fa113fSQu Wenruo 			ret = btrfs_inc_extent_ref(trans, &ref);
28405d4f98a2SYan Zheng 			BUG_ON(ret);
28415d4f98a2SYan Zheng 
28425d4f98a2SYan Zheng 			ret = btrfs_drop_subtree(trans, root, eb, upper->eb);
28435d4f98a2SYan Zheng 			BUG_ON(ret);
28445d4f98a2SYan Zheng 		}
28453fd0a558SYan, Zheng next:
28463fd0a558SYan, Zheng 		if (!upper->pending)
2847b0fe7078SQu Wenruo 			btrfs_backref_drop_node_buffer(upper);
28483fd0a558SYan, Zheng 		else
2849b0fe7078SQu Wenruo 			btrfs_backref_unlock_node_buffer(upper);
28503fd0a558SYan, Zheng 		if (err)
28513fd0a558SYan, Zheng 			break;
28525d4f98a2SYan Zheng 	}
28533fd0a558SYan, Zheng 
28543fd0a558SYan, Zheng 	if (!err && node->pending) {
2855b0fe7078SQu Wenruo 		btrfs_backref_drop_node_buffer(node);
28563fd0a558SYan, Zheng 		list_move_tail(&node->list, &rc->backref_cache.changed);
28573fd0a558SYan, Zheng 		node->pending = 0;
28585d4f98a2SYan Zheng 	}
28593fd0a558SYan, Zheng 
28605d4f98a2SYan Zheng 	path->lowest_level = 0;
28613fd0a558SYan, Zheng 	BUG_ON(err == -ENOSPC);
28625d4f98a2SYan Zheng 	return err;
28635d4f98a2SYan Zheng }
28645d4f98a2SYan Zheng 
28655d4f98a2SYan Zheng static int link_to_upper(struct btrfs_trans_handle *trans,
28663fd0a558SYan, Zheng 			 struct reloc_control *rc,
2867a26195a5SQu Wenruo 			 struct btrfs_backref_node *node,
28685d4f98a2SYan Zheng 			 struct btrfs_path *path)
28695d4f98a2SYan Zheng {
28705d4f98a2SYan Zheng 	struct btrfs_key key;
28715d4f98a2SYan Zheng 
28725d4f98a2SYan Zheng 	btrfs_node_key_to_cpu(node->eb, &key, 0);
28733fd0a558SYan, Zheng 	return do_relocation(trans, rc, node, &key, path, 0);
28745d4f98a2SYan Zheng }
28755d4f98a2SYan Zheng 
28765d4f98a2SYan Zheng static int finish_pending_nodes(struct btrfs_trans_handle *trans,
28773fd0a558SYan, Zheng 				struct reloc_control *rc,
28783fd0a558SYan, Zheng 				struct btrfs_path *path, int err)
28795d4f98a2SYan Zheng {
28803fd0a558SYan, Zheng 	LIST_HEAD(list);
2881a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
2882a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
28835d4f98a2SYan Zheng 	int level;
28845d4f98a2SYan Zheng 	int ret;
28855d4f98a2SYan Zheng 
28865d4f98a2SYan Zheng 	for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
28875d4f98a2SYan Zheng 		while (!list_empty(&cache->pending[level])) {
28885d4f98a2SYan Zheng 			node = list_entry(cache->pending[level].next,
2889a26195a5SQu Wenruo 					  struct btrfs_backref_node, list);
28903fd0a558SYan, Zheng 			list_move_tail(&node->list, &list);
28913fd0a558SYan, Zheng 			BUG_ON(!node->pending);
28925d4f98a2SYan Zheng 
28933fd0a558SYan, Zheng 			if (!err) {
28943fd0a558SYan, Zheng 				ret = link_to_upper(trans, rc, node, path);
28955d4f98a2SYan Zheng 				if (ret < 0)
28965d4f98a2SYan Zheng 					err = ret;
28975d4f98a2SYan Zheng 			}
28985d4f98a2SYan Zheng 		}
28993fd0a558SYan, Zheng 		list_splice_init(&list, &cache->pending[level]);
29003fd0a558SYan, Zheng 	}
29015d4f98a2SYan Zheng 	return err;
29025d4f98a2SYan Zheng }
29035d4f98a2SYan Zheng 
29045d4f98a2SYan Zheng /*
29055d4f98a2SYan Zheng  * mark a block and all blocks directly/indirectly reference the block
29065d4f98a2SYan Zheng  * as processed.
29075d4f98a2SYan Zheng  */
29085d4f98a2SYan Zheng static void update_processed_blocks(struct reloc_control *rc,
2909a26195a5SQu Wenruo 				    struct btrfs_backref_node *node)
29105d4f98a2SYan Zheng {
2911a26195a5SQu Wenruo 	struct btrfs_backref_node *next = node;
2912a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2913a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
29145d4f98a2SYan Zheng 	int index = 0;
29155d4f98a2SYan Zheng 
29165d4f98a2SYan Zheng 	while (next) {
29175d4f98a2SYan Zheng 		cond_resched();
29185d4f98a2SYan Zheng 		while (1) {
29195d4f98a2SYan Zheng 			if (next->processed)
29205d4f98a2SYan Zheng 				break;
29215d4f98a2SYan Zheng 
29229569cc20SQu Wenruo 			mark_block_processed(rc, next);
29235d4f98a2SYan Zheng 
29245d4f98a2SYan Zheng 			if (list_empty(&next->upper))
29255d4f98a2SYan Zheng 				break;
29265d4f98a2SYan Zheng 
29275d4f98a2SYan Zheng 			edge = list_entry(next->upper.next,
2928a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[LOWER]);
29295d4f98a2SYan Zheng 			edges[index++] = edge;
29305d4f98a2SYan Zheng 			next = edge->node[UPPER];
29315d4f98a2SYan Zheng 		}
29325d4f98a2SYan Zheng 		next = walk_down_backref(edges, &index);
29335d4f98a2SYan Zheng 	}
29345d4f98a2SYan Zheng }
29355d4f98a2SYan Zheng 
29367476dfdaSDavid Sterba static int tree_block_processed(u64 bytenr, struct reloc_control *rc)
29375d4f98a2SYan Zheng {
2938da17066cSJeff Mahoney 	u32 blocksize = rc->extent_root->fs_info->nodesize;
29397476dfdaSDavid Sterba 
29405d4f98a2SYan Zheng 	if (test_range_bit(&rc->processed_blocks, bytenr,
29419655d298SChris Mason 			   bytenr + blocksize - 1, EXTENT_DIRTY, 1, NULL))
29425d4f98a2SYan Zheng 		return 1;
29435d4f98a2SYan Zheng 	return 0;
29445d4f98a2SYan Zheng }
29455d4f98a2SYan Zheng 
29462ff7e61eSJeff Mahoney static int get_tree_block_key(struct btrfs_fs_info *fs_info,
29475d4f98a2SYan Zheng 			      struct tree_block *block)
29485d4f98a2SYan Zheng {
29495d4f98a2SYan Zheng 	struct extent_buffer *eb;
29505d4f98a2SYan Zheng 
2951581c1760SQu Wenruo 	eb = read_tree_block(fs_info, block->bytenr, block->key.offset,
2952581c1760SQu Wenruo 			     block->level, NULL);
295364c043deSLiu Bo 	if (IS_ERR(eb)) {
295464c043deSLiu Bo 		return PTR_ERR(eb);
295564c043deSLiu Bo 	} else if (!extent_buffer_uptodate(eb)) {
2956416bc658SJosef Bacik 		free_extent_buffer(eb);
2957416bc658SJosef Bacik 		return -EIO;
2958416bc658SJosef Bacik 	}
29595d4f98a2SYan Zheng 	if (block->level == 0)
29605d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(eb, &block->key, 0);
29615d4f98a2SYan Zheng 	else
29625d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(eb, &block->key, 0);
29635d4f98a2SYan Zheng 	free_extent_buffer(eb);
29645d4f98a2SYan Zheng 	block->key_ready = 1;
29655d4f98a2SYan Zheng 	return 0;
29665d4f98a2SYan Zheng }
29675d4f98a2SYan Zheng 
29685d4f98a2SYan Zheng /*
29695d4f98a2SYan Zheng  * helper function to relocate a tree block
29705d4f98a2SYan Zheng  */
29715d4f98a2SYan Zheng static int relocate_tree_block(struct btrfs_trans_handle *trans,
29725d4f98a2SYan Zheng 				struct reloc_control *rc,
2973a26195a5SQu Wenruo 				struct btrfs_backref_node *node,
29745d4f98a2SYan Zheng 				struct btrfs_key *key,
29755d4f98a2SYan Zheng 				struct btrfs_path *path)
29765d4f98a2SYan Zheng {
29775d4f98a2SYan Zheng 	struct btrfs_root *root;
29783fd0a558SYan, Zheng 	int ret = 0;
29795d4f98a2SYan Zheng 
29803fd0a558SYan, Zheng 	if (!node)
29815d4f98a2SYan Zheng 		return 0;
29823fd0a558SYan, Zheng 
29835f6b2e5cSJosef Bacik 	/*
29845f6b2e5cSJosef Bacik 	 * If we fail here we want to drop our backref_node because we are going
29855f6b2e5cSJosef Bacik 	 * to start over and regenerate the tree for it.
29865f6b2e5cSJosef Bacik 	 */
29875f6b2e5cSJosef Bacik 	ret = reserve_metadata_space(trans, rc, node);
29885f6b2e5cSJosef Bacik 	if (ret)
29895f6b2e5cSJosef Bacik 		goto out;
29905f6b2e5cSJosef Bacik 
29913fd0a558SYan, Zheng 	BUG_ON(node->processed);
2992147d256eSZhaolei 	root = select_one_root(node);
29933fd0a558SYan, Zheng 	if (root == ERR_PTR(-ENOENT)) {
29943fd0a558SYan, Zheng 		update_processed_blocks(rc, node);
29953fd0a558SYan, Zheng 		goto out;
29965d4f98a2SYan Zheng 	}
29975d4f98a2SYan Zheng 
29983fd0a558SYan, Zheng 	if (root) {
299927cdeb70SMiao Xie 		if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
30003fd0a558SYan, Zheng 			BUG_ON(node->new_bytenr);
30013fd0a558SYan, Zheng 			BUG_ON(!list_empty(&node->list));
30023fd0a558SYan, Zheng 			btrfs_record_root_in_trans(trans, root);
30033fd0a558SYan, Zheng 			root = root->reloc_root;
30043fd0a558SYan, Zheng 			node->new_bytenr = root->node->start;
300500246528SJosef Bacik 			btrfs_put_root(node->root);
300600246528SJosef Bacik 			node->root = btrfs_grab_root(root);
30070b530bc5SJosef Bacik 			ASSERT(node->root);
30083fd0a558SYan, Zheng 			list_add_tail(&node->list, &rc->backref_cache.changed);
30093fd0a558SYan, Zheng 		} else {
30105d4f98a2SYan Zheng 			path->lowest_level = node->level;
30115d4f98a2SYan Zheng 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
3012b3b4aa74SDavid Sterba 			btrfs_release_path(path);
30133fd0a558SYan, Zheng 			if (ret > 0)
30145d4f98a2SYan Zheng 				ret = 0;
30153fd0a558SYan, Zheng 		}
30163fd0a558SYan, Zheng 		if (!ret)
30173fd0a558SYan, Zheng 			update_processed_blocks(rc, node);
30183fd0a558SYan, Zheng 	} else {
30193fd0a558SYan, Zheng 		ret = do_relocation(trans, rc, node, key, path, 1);
30203fd0a558SYan, Zheng 	}
30215d4f98a2SYan Zheng out:
30220647bf56SWang Shilong 	if (ret || node->level == 0 || node->cowonly)
3023023acb07SQu Wenruo 		btrfs_backref_cleanup_node(&rc->backref_cache, node);
30245d4f98a2SYan Zheng 	return ret;
30255d4f98a2SYan Zheng }
30265d4f98a2SYan Zheng 
30275d4f98a2SYan Zheng /*
30285d4f98a2SYan Zheng  * relocate a list of blocks
30295d4f98a2SYan Zheng  */
30305d4f98a2SYan Zheng static noinline_for_stack
30315d4f98a2SYan Zheng int relocate_tree_blocks(struct btrfs_trans_handle *trans,
30325d4f98a2SYan Zheng 			 struct reloc_control *rc, struct rb_root *blocks)
30335d4f98a2SYan Zheng {
30342ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3035a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
30365d4f98a2SYan Zheng 	struct btrfs_path *path;
30375d4f98a2SYan Zheng 	struct tree_block *block;
303898ff7b94SQu Wenruo 	struct tree_block *next;
30395d4f98a2SYan Zheng 	int ret;
30405d4f98a2SYan Zheng 	int err = 0;
30415d4f98a2SYan Zheng 
30425d4f98a2SYan Zheng 	path = btrfs_alloc_path();
3043e1a12670SLiu Bo 	if (!path) {
3044e1a12670SLiu Bo 		err = -ENOMEM;
304534c2b290SDavid Sterba 		goto out_free_blocks;
3046e1a12670SLiu Bo 	}
30475d4f98a2SYan Zheng 
304898ff7b94SQu Wenruo 	/* Kick in readahead for tree blocks with missing keys */
304998ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
30505d4f98a2SYan Zheng 		if (!block->key_ready)
30512ff7e61eSJeff Mahoney 			readahead_tree_block(fs_info, block->bytenr);
30525d4f98a2SYan Zheng 	}
30535d4f98a2SYan Zheng 
305498ff7b94SQu Wenruo 	/* Get first keys */
305598ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
305634c2b290SDavid Sterba 		if (!block->key_ready) {
30572ff7e61eSJeff Mahoney 			err = get_tree_block_key(fs_info, block);
305834c2b290SDavid Sterba 			if (err)
305934c2b290SDavid Sterba 				goto out_free_path;
306034c2b290SDavid Sterba 		}
30615d4f98a2SYan Zheng 	}
30625d4f98a2SYan Zheng 
306398ff7b94SQu Wenruo 	/* Do tree relocation */
306498ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
30653fd0a558SYan, Zheng 		node = build_backref_tree(rc, &block->key,
30665d4f98a2SYan Zheng 					  block->level, block->bytenr);
30675d4f98a2SYan Zheng 		if (IS_ERR(node)) {
30685d4f98a2SYan Zheng 			err = PTR_ERR(node);
30695d4f98a2SYan Zheng 			goto out;
30705d4f98a2SYan Zheng 		}
30715d4f98a2SYan Zheng 
30725d4f98a2SYan Zheng 		ret = relocate_tree_block(trans, rc, node, &block->key,
30735d4f98a2SYan Zheng 					  path);
30745d4f98a2SYan Zheng 		if (ret < 0) {
30755d4f98a2SYan Zheng 			err = ret;
307650dbbb71SJosef Bacik 			break;
30775d4f98a2SYan Zheng 		}
30785d4f98a2SYan Zheng 	}
30795d4f98a2SYan Zheng out:
30803fd0a558SYan, Zheng 	err = finish_pending_nodes(trans, rc, path, err);
30815d4f98a2SYan Zheng 
308234c2b290SDavid Sterba out_free_path:
30835d4f98a2SYan Zheng 	btrfs_free_path(path);
308434c2b290SDavid Sterba out_free_blocks:
3085e1a12670SLiu Bo 	free_block_list(blocks);
30865d4f98a2SYan Zheng 	return err;
30875d4f98a2SYan Zheng }
30885d4f98a2SYan Zheng 
30895d4f98a2SYan Zheng static noinline_for_stack
3090efa56464SYan, Zheng int prealloc_file_extent_cluster(struct inode *inode,
3091efa56464SYan, Zheng 				 struct file_extent_cluster *cluster)
3092efa56464SYan, Zheng {
3093efa56464SYan, Zheng 	u64 alloc_hint = 0;
3094efa56464SYan, Zheng 	u64 start;
3095efa56464SYan, Zheng 	u64 end;
3096efa56464SYan, Zheng 	u64 offset = BTRFS_I(inode)->index_cnt;
3097efa56464SYan, Zheng 	u64 num_bytes;
3098efa56464SYan, Zheng 	int nr = 0;
3099efa56464SYan, Zheng 	int ret = 0;
3100dcb40c19SWang Xiaoguang 	u64 prealloc_start = cluster->start - offset;
3101dcb40c19SWang Xiaoguang 	u64 prealloc_end = cluster->end - offset;
310218513091SWang Xiaoguang 	u64 cur_offset;
3103364ecf36SQu Wenruo 	struct extent_changeset *data_reserved = NULL;
3104efa56464SYan, Zheng 
3105efa56464SYan, Zheng 	BUG_ON(cluster->start != cluster->boundary[0]);
31065955102cSAl Viro 	inode_lock(inode);
3107efa56464SYan, Zheng 
3108364ecf36SQu Wenruo 	ret = btrfs_check_data_free_space(inode, &data_reserved, prealloc_start,
3109dcb40c19SWang Xiaoguang 					  prealloc_end + 1 - prealloc_start);
3110efa56464SYan, Zheng 	if (ret)
3111efa56464SYan, Zheng 		goto out;
3112efa56464SYan, Zheng 
311318513091SWang Xiaoguang 	cur_offset = prealloc_start;
3114efa56464SYan, Zheng 	while (nr < cluster->nr) {
3115efa56464SYan, Zheng 		start = cluster->boundary[nr] - offset;
3116efa56464SYan, Zheng 		if (nr + 1 < cluster->nr)
3117efa56464SYan, Zheng 			end = cluster->boundary[nr + 1] - 1 - offset;
3118efa56464SYan, Zheng 		else
3119efa56464SYan, Zheng 			end = cluster->end - offset;
3120efa56464SYan, Zheng 
3121d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, start, end);
3122efa56464SYan, Zheng 		num_bytes = end + 1 - start;
312318513091SWang Xiaoguang 		if (cur_offset < start)
3124bc42bda2SQu Wenruo 			btrfs_free_reserved_data_space(inode, data_reserved,
3125bc42bda2SQu Wenruo 					cur_offset, start - cur_offset);
3126efa56464SYan, Zheng 		ret = btrfs_prealloc_file_range(inode, 0, start,
3127efa56464SYan, Zheng 						num_bytes, num_bytes,
3128efa56464SYan, Zheng 						end + 1, &alloc_hint);
312918513091SWang Xiaoguang 		cur_offset = end + 1;
3130d0082371SJeff Mahoney 		unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
3131efa56464SYan, Zheng 		if (ret)
3132efa56464SYan, Zheng 			break;
3133efa56464SYan, Zheng 		nr++;
3134efa56464SYan, Zheng 	}
313518513091SWang Xiaoguang 	if (cur_offset < prealloc_end)
3136bc42bda2SQu Wenruo 		btrfs_free_reserved_data_space(inode, data_reserved,
3137bc42bda2SQu Wenruo 				cur_offset, prealloc_end + 1 - cur_offset);
3138efa56464SYan, Zheng out:
31395955102cSAl Viro 	inode_unlock(inode);
3140364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
3141efa56464SYan, Zheng 	return ret;
3142efa56464SYan, Zheng }
3143efa56464SYan, Zheng 
3144efa56464SYan, Zheng static noinline_for_stack
31450257bb82SYan, Zheng int setup_extent_mapping(struct inode *inode, u64 start, u64 end,
31460257bb82SYan, Zheng 			 u64 block_start)
31475d4f98a2SYan Zheng {
31485d4f98a2SYan Zheng 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
31495d4f98a2SYan Zheng 	struct extent_map *em;
31500257bb82SYan, Zheng 	int ret = 0;
31515d4f98a2SYan Zheng 
3152172ddd60SDavid Sterba 	em = alloc_extent_map();
31530257bb82SYan, Zheng 	if (!em)
31540257bb82SYan, Zheng 		return -ENOMEM;
31550257bb82SYan, Zheng 
31565d4f98a2SYan Zheng 	em->start = start;
31570257bb82SYan, Zheng 	em->len = end + 1 - start;
31580257bb82SYan, Zheng 	em->block_len = em->len;
31590257bb82SYan, Zheng 	em->block_start = block_start;
31605d4f98a2SYan Zheng 	set_bit(EXTENT_FLAG_PINNED, &em->flags);
31615d4f98a2SYan Zheng 
3162d0082371SJeff Mahoney 	lock_extent(&BTRFS_I(inode)->io_tree, start, end);
31635d4f98a2SYan Zheng 	while (1) {
3164890871beSChris Mason 		write_lock(&em_tree->lock);
316509a2a8f9SJosef Bacik 		ret = add_extent_mapping(em_tree, em, 0);
3166890871beSChris Mason 		write_unlock(&em_tree->lock);
31675d4f98a2SYan Zheng 		if (ret != -EEXIST) {
31685d4f98a2SYan Zheng 			free_extent_map(em);
31695d4f98a2SYan Zheng 			break;
31705d4f98a2SYan Zheng 		}
3171dcdbc059SNikolay Borisov 		btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
31725d4f98a2SYan Zheng 	}
3173d0082371SJeff Mahoney 	unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
31740257bb82SYan, Zheng 	return ret;
31750257bb82SYan, Zheng }
31765d4f98a2SYan Zheng 
3177726a3421SQu Wenruo /*
3178726a3421SQu Wenruo  * Allow error injection to test balance cancellation
3179726a3421SQu Wenruo  */
3180726a3421SQu Wenruo int btrfs_should_cancel_balance(struct btrfs_fs_info *fs_info)
3181726a3421SQu Wenruo {
3182726a3421SQu Wenruo 	return atomic_read(&fs_info->balance_cancel_req);
3183726a3421SQu Wenruo }
3184726a3421SQu Wenruo ALLOW_ERROR_INJECTION(btrfs_should_cancel_balance, TRUE);
3185726a3421SQu Wenruo 
31860257bb82SYan, Zheng static int relocate_file_extent_cluster(struct inode *inode,
31870257bb82SYan, Zheng 					struct file_extent_cluster *cluster)
31880257bb82SYan, Zheng {
31892ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
31900257bb82SYan, Zheng 	u64 page_start;
31910257bb82SYan, Zheng 	u64 page_end;
31920257bb82SYan, Zheng 	u64 offset = BTRFS_I(inode)->index_cnt;
31930257bb82SYan, Zheng 	unsigned long index;
31940257bb82SYan, Zheng 	unsigned long last_index;
31950257bb82SYan, Zheng 	struct page *page;
31960257bb82SYan, Zheng 	struct file_ra_state *ra;
31973b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
31980257bb82SYan, Zheng 	int nr = 0;
31990257bb82SYan, Zheng 	int ret = 0;
32000257bb82SYan, Zheng 
32010257bb82SYan, Zheng 	if (!cluster->nr)
32020257bb82SYan, Zheng 		return 0;
32030257bb82SYan, Zheng 
32040257bb82SYan, Zheng 	ra = kzalloc(sizeof(*ra), GFP_NOFS);
32050257bb82SYan, Zheng 	if (!ra)
32060257bb82SYan, Zheng 		return -ENOMEM;
32070257bb82SYan, Zheng 
3208efa56464SYan, Zheng 	ret = prealloc_file_extent_cluster(inode, cluster);
32090257bb82SYan, Zheng 	if (ret)
3210efa56464SYan, Zheng 		goto out;
32110257bb82SYan, Zheng 
32120257bb82SYan, Zheng 	file_ra_state_init(ra, inode->i_mapping);
32130257bb82SYan, Zheng 
3214efa56464SYan, Zheng 	ret = setup_extent_mapping(inode, cluster->start - offset,
3215efa56464SYan, Zheng 				   cluster->end - offset, cluster->start);
3216efa56464SYan, Zheng 	if (ret)
3217efa56464SYan, Zheng 		goto out;
3218efa56464SYan, Zheng 
321909cbfeafSKirill A. Shutemov 	index = (cluster->start - offset) >> PAGE_SHIFT;
322009cbfeafSKirill A. Shutemov 	last_index = (cluster->end - offset) >> PAGE_SHIFT;
32210257bb82SYan, Zheng 	while (index <= last_index) {
32229f3db423SNikolay Borisov 		ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
32239f3db423SNikolay Borisov 				PAGE_SIZE);
3224efa56464SYan, Zheng 		if (ret)
3225efa56464SYan, Zheng 			goto out;
3226efa56464SYan, Zheng 
32270257bb82SYan, Zheng 		page = find_lock_page(inode->i_mapping, index);
32280257bb82SYan, Zheng 		if (!page) {
32290257bb82SYan, Zheng 			page_cache_sync_readahead(inode->i_mapping,
32300257bb82SYan, Zheng 						  ra, NULL, index,
32310257bb82SYan, Zheng 						  last_index + 1 - index);
3232a94733d0SJosef Bacik 			page = find_or_create_page(inode->i_mapping, index,
32333b16a4e3SJosef Bacik 						   mask);
32340257bb82SYan, Zheng 			if (!page) {
3235691fa059SNikolay Borisov 				btrfs_delalloc_release_metadata(BTRFS_I(inode),
323643b18595SQu Wenruo 							PAGE_SIZE, true);
323744db1216SFilipe Manana 				btrfs_delalloc_release_extents(BTRFS_I(inode),
32388702ba93SQu Wenruo 							PAGE_SIZE);
32390257bb82SYan, Zheng 				ret = -ENOMEM;
3240efa56464SYan, Zheng 				goto out;
32410257bb82SYan, Zheng 			}
32420257bb82SYan, Zheng 		}
32430257bb82SYan, Zheng 
32440257bb82SYan, Zheng 		if (PageReadahead(page)) {
32450257bb82SYan, Zheng 			page_cache_async_readahead(inode->i_mapping,
32460257bb82SYan, Zheng 						   ra, NULL, page, index,
32470257bb82SYan, Zheng 						   last_index + 1 - index);
32480257bb82SYan, Zheng 		}
32490257bb82SYan, Zheng 
32500257bb82SYan, Zheng 		if (!PageUptodate(page)) {
32510257bb82SYan, Zheng 			btrfs_readpage(NULL, page);
32520257bb82SYan, Zheng 			lock_page(page);
32530257bb82SYan, Zheng 			if (!PageUptodate(page)) {
32540257bb82SYan, Zheng 				unlock_page(page);
325509cbfeafSKirill A. Shutemov 				put_page(page);
3256691fa059SNikolay Borisov 				btrfs_delalloc_release_metadata(BTRFS_I(inode),
325743b18595SQu Wenruo 							PAGE_SIZE, true);
32588b62f87bSJosef Bacik 				btrfs_delalloc_release_extents(BTRFS_I(inode),
32598702ba93SQu Wenruo 							       PAGE_SIZE);
32600257bb82SYan, Zheng 				ret = -EIO;
3261efa56464SYan, Zheng 				goto out;
32620257bb82SYan, Zheng 			}
32630257bb82SYan, Zheng 		}
32640257bb82SYan, Zheng 
32654eee4fa4SMiao Xie 		page_start = page_offset(page);
326609cbfeafSKirill A. Shutemov 		page_end = page_start + PAGE_SIZE - 1;
32670257bb82SYan, Zheng 
3268d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, page_start, page_end);
32690257bb82SYan, Zheng 
32700257bb82SYan, Zheng 		set_page_extent_mapped(page);
32710257bb82SYan, Zheng 
32720257bb82SYan, Zheng 		if (nr < cluster->nr &&
32730257bb82SYan, Zheng 		    page_start + offset == cluster->boundary[nr]) {
32740257bb82SYan, Zheng 			set_extent_bits(&BTRFS_I(inode)->io_tree,
32750257bb82SYan, Zheng 					page_start, page_end,
3276ceeb0ae7SDavid Sterba 					EXTENT_BOUNDARY);
32770257bb82SYan, Zheng 			nr++;
32780257bb82SYan, Zheng 		}
32790257bb82SYan, Zheng 
3280765f3cebSNikolay Borisov 		ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
3281330a5827SNikolay Borisov 						NULL);
3282765f3cebSNikolay Borisov 		if (ret) {
3283765f3cebSNikolay Borisov 			unlock_page(page);
3284765f3cebSNikolay Borisov 			put_page(page);
3285765f3cebSNikolay Borisov 			btrfs_delalloc_release_metadata(BTRFS_I(inode),
328643b18595SQu Wenruo 							 PAGE_SIZE, true);
3287765f3cebSNikolay Borisov 			btrfs_delalloc_release_extents(BTRFS_I(inode),
32888702ba93SQu Wenruo 			                               PAGE_SIZE);
3289765f3cebSNikolay Borisov 
3290765f3cebSNikolay Borisov 			clear_extent_bits(&BTRFS_I(inode)->io_tree,
3291765f3cebSNikolay Borisov 					  page_start, page_end,
3292765f3cebSNikolay Borisov 					  EXTENT_LOCKED | EXTENT_BOUNDARY);
3293765f3cebSNikolay Borisov 			goto out;
3294765f3cebSNikolay Borisov 
3295765f3cebSNikolay Borisov 		}
32960257bb82SYan, Zheng 		set_page_dirty(page);
32970257bb82SYan, Zheng 
32980257bb82SYan, Zheng 		unlock_extent(&BTRFS_I(inode)->io_tree,
3299d0082371SJeff Mahoney 			      page_start, page_end);
33000257bb82SYan, Zheng 		unlock_page(page);
330109cbfeafSKirill A. Shutemov 		put_page(page);
33020257bb82SYan, Zheng 
33030257bb82SYan, Zheng 		index++;
33048702ba93SQu Wenruo 		btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
3305efa56464SYan, Zheng 		balance_dirty_pages_ratelimited(inode->i_mapping);
33062ff7e61eSJeff Mahoney 		btrfs_throttle(fs_info);
33077f913c7cSQu Wenruo 		if (btrfs_should_cancel_balance(fs_info)) {
33087f913c7cSQu Wenruo 			ret = -ECANCELED;
33097f913c7cSQu Wenruo 			goto out;
33107f913c7cSQu Wenruo 		}
33110257bb82SYan, Zheng 	}
33120257bb82SYan, Zheng 	WARN_ON(nr != cluster->nr);
3313efa56464SYan, Zheng out:
33140257bb82SYan, Zheng 	kfree(ra);
33150257bb82SYan, Zheng 	return ret;
33160257bb82SYan, Zheng }
33170257bb82SYan, Zheng 
33180257bb82SYan, Zheng static noinline_for_stack
33190257bb82SYan, Zheng int relocate_data_extent(struct inode *inode, struct btrfs_key *extent_key,
33200257bb82SYan, Zheng 			 struct file_extent_cluster *cluster)
33210257bb82SYan, Zheng {
33220257bb82SYan, Zheng 	int ret;
33230257bb82SYan, Zheng 
33240257bb82SYan, Zheng 	if (cluster->nr > 0 && extent_key->objectid != cluster->end + 1) {
33250257bb82SYan, Zheng 		ret = relocate_file_extent_cluster(inode, cluster);
33260257bb82SYan, Zheng 		if (ret)
33270257bb82SYan, Zheng 			return ret;
33280257bb82SYan, Zheng 		cluster->nr = 0;
33290257bb82SYan, Zheng 	}
33300257bb82SYan, Zheng 
33310257bb82SYan, Zheng 	if (!cluster->nr)
33320257bb82SYan, Zheng 		cluster->start = extent_key->objectid;
33330257bb82SYan, Zheng 	else
33340257bb82SYan, Zheng 		BUG_ON(cluster->nr >= MAX_EXTENTS);
33350257bb82SYan, Zheng 	cluster->end = extent_key->objectid + extent_key->offset - 1;
33360257bb82SYan, Zheng 	cluster->boundary[cluster->nr] = extent_key->objectid;
33370257bb82SYan, Zheng 	cluster->nr++;
33380257bb82SYan, Zheng 
33390257bb82SYan, Zheng 	if (cluster->nr >= MAX_EXTENTS) {
33400257bb82SYan, Zheng 		ret = relocate_file_extent_cluster(inode, cluster);
33410257bb82SYan, Zheng 		if (ret)
33420257bb82SYan, Zheng 			return ret;
33430257bb82SYan, Zheng 		cluster->nr = 0;
33440257bb82SYan, Zheng 	}
33450257bb82SYan, Zheng 	return 0;
33465d4f98a2SYan Zheng }
33475d4f98a2SYan Zheng 
33485d4f98a2SYan Zheng /*
33495d4f98a2SYan Zheng  * helper to add a tree block to the list.
33505d4f98a2SYan Zheng  * the major work is getting the generation and level of the block
33515d4f98a2SYan Zheng  */
33525d4f98a2SYan Zheng static int add_tree_block(struct reloc_control *rc,
33535d4f98a2SYan Zheng 			  struct btrfs_key *extent_key,
33545d4f98a2SYan Zheng 			  struct btrfs_path *path,
33555d4f98a2SYan Zheng 			  struct rb_root *blocks)
33565d4f98a2SYan Zheng {
33575d4f98a2SYan Zheng 	struct extent_buffer *eb;
33585d4f98a2SYan Zheng 	struct btrfs_extent_item *ei;
33595d4f98a2SYan Zheng 	struct btrfs_tree_block_info *bi;
33605d4f98a2SYan Zheng 	struct tree_block *block;
33615d4f98a2SYan Zheng 	struct rb_node *rb_node;
33625d4f98a2SYan Zheng 	u32 item_size;
33635d4f98a2SYan Zheng 	int level = -1;
33647fdf4b60SWang Shilong 	u64 generation;
33655d4f98a2SYan Zheng 
33665d4f98a2SYan Zheng 	eb =  path->nodes[0];
33675d4f98a2SYan Zheng 	item_size = btrfs_item_size_nr(eb, path->slots[0]);
33685d4f98a2SYan Zheng 
33693173a18fSJosef Bacik 	if (extent_key->type == BTRFS_METADATA_ITEM_KEY ||
33703173a18fSJosef Bacik 	    item_size >= sizeof(*ei) + sizeof(*bi)) {
33715d4f98a2SYan Zheng 		ei = btrfs_item_ptr(eb, path->slots[0],
33725d4f98a2SYan Zheng 				struct btrfs_extent_item);
33733173a18fSJosef Bacik 		if (extent_key->type == BTRFS_EXTENT_ITEM_KEY) {
33745d4f98a2SYan Zheng 			bi = (struct btrfs_tree_block_info *)(ei + 1);
33755d4f98a2SYan Zheng 			level = btrfs_tree_block_level(eb, bi);
33765d4f98a2SYan Zheng 		} else {
33773173a18fSJosef Bacik 			level = (int)extent_key->offset;
33783173a18fSJosef Bacik 		}
33793173a18fSJosef Bacik 		generation = btrfs_extent_generation(eb, ei);
33806d8ff4e4SDavid Sterba 	} else if (unlikely(item_size == sizeof(struct btrfs_extent_item_v0))) {
3381ba3c2b19SNikolay Borisov 		btrfs_print_v0_err(eb->fs_info);
3382ba3c2b19SNikolay Borisov 		btrfs_handle_fs_error(eb->fs_info, -EINVAL, NULL);
3383ba3c2b19SNikolay Borisov 		return -EINVAL;
33843173a18fSJosef Bacik 	} else {
33855d4f98a2SYan Zheng 		BUG();
33865d4f98a2SYan Zheng 	}
33875d4f98a2SYan Zheng 
3388b3b4aa74SDavid Sterba 	btrfs_release_path(path);
33895d4f98a2SYan Zheng 
33905d4f98a2SYan Zheng 	BUG_ON(level == -1);
33915d4f98a2SYan Zheng 
33925d4f98a2SYan Zheng 	block = kmalloc(sizeof(*block), GFP_NOFS);
33935d4f98a2SYan Zheng 	if (!block)
33945d4f98a2SYan Zheng 		return -ENOMEM;
33955d4f98a2SYan Zheng 
33965d4f98a2SYan Zheng 	block->bytenr = extent_key->objectid;
3397da17066cSJeff Mahoney 	block->key.objectid = rc->extent_root->fs_info->nodesize;
33985d4f98a2SYan Zheng 	block->key.offset = generation;
33995d4f98a2SYan Zheng 	block->level = level;
34005d4f98a2SYan Zheng 	block->key_ready = 0;
34015d4f98a2SYan Zheng 
3402e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(blocks, block->bytenr, &block->rb_node);
340343c04fb1SJeff Mahoney 	if (rb_node)
3404982c92cbSQu Wenruo 		btrfs_backref_panic(rc->extent_root->fs_info, block->bytenr,
3405982c92cbSQu Wenruo 				    -EEXIST);
34065d4f98a2SYan Zheng 
34075d4f98a2SYan Zheng 	return 0;
34085d4f98a2SYan Zheng }
34095d4f98a2SYan Zheng 
34105d4f98a2SYan Zheng /*
34115d4f98a2SYan Zheng  * helper to add tree blocks for backref of type BTRFS_SHARED_DATA_REF_KEY
34125d4f98a2SYan Zheng  */
34135d4f98a2SYan Zheng static int __add_tree_block(struct reloc_control *rc,
34145d4f98a2SYan Zheng 			    u64 bytenr, u32 blocksize,
34155d4f98a2SYan Zheng 			    struct rb_root *blocks)
34165d4f98a2SYan Zheng {
34170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
34185d4f98a2SYan Zheng 	struct btrfs_path *path;
34195d4f98a2SYan Zheng 	struct btrfs_key key;
34205d4f98a2SYan Zheng 	int ret;
34210b246afaSJeff Mahoney 	bool skinny = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
34225d4f98a2SYan Zheng 
34237476dfdaSDavid Sterba 	if (tree_block_processed(bytenr, rc))
34245d4f98a2SYan Zheng 		return 0;
34255d4f98a2SYan Zheng 
3426e9a28dc5SQu Wenruo 	if (rb_simple_search(blocks, bytenr))
34275d4f98a2SYan Zheng 		return 0;
34285d4f98a2SYan Zheng 
34295d4f98a2SYan Zheng 	path = btrfs_alloc_path();
34305d4f98a2SYan Zheng 	if (!path)
34315d4f98a2SYan Zheng 		return -ENOMEM;
3432aee68ee5SJosef Bacik again:
34335d4f98a2SYan Zheng 	key.objectid = bytenr;
3434aee68ee5SJosef Bacik 	if (skinny) {
3435aee68ee5SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
3436aee68ee5SJosef Bacik 		key.offset = (u64)-1;
3437aee68ee5SJosef Bacik 	} else {
34385d4f98a2SYan Zheng 		key.type = BTRFS_EXTENT_ITEM_KEY;
34395d4f98a2SYan Zheng 		key.offset = blocksize;
3440aee68ee5SJosef Bacik 	}
34415d4f98a2SYan Zheng 
34425d4f98a2SYan Zheng 	path->search_commit_root = 1;
34435d4f98a2SYan Zheng 	path->skip_locking = 1;
34445d4f98a2SYan Zheng 	ret = btrfs_search_slot(NULL, rc->extent_root, &key, path, 0, 0);
34455d4f98a2SYan Zheng 	if (ret < 0)
34465d4f98a2SYan Zheng 		goto out;
34475d4f98a2SYan Zheng 
3448aee68ee5SJosef Bacik 	if (ret > 0 && skinny) {
3449aee68ee5SJosef Bacik 		if (path->slots[0]) {
3450aee68ee5SJosef Bacik 			path->slots[0]--;
3451aee68ee5SJosef Bacik 			btrfs_item_key_to_cpu(path->nodes[0], &key,
3452aee68ee5SJosef Bacik 					      path->slots[0]);
34533173a18fSJosef Bacik 			if (key.objectid == bytenr &&
3454aee68ee5SJosef Bacik 			    (key.type == BTRFS_METADATA_ITEM_KEY ||
3455aee68ee5SJosef Bacik 			     (key.type == BTRFS_EXTENT_ITEM_KEY &&
3456aee68ee5SJosef Bacik 			      key.offset == blocksize)))
34573173a18fSJosef Bacik 				ret = 0;
34583173a18fSJosef Bacik 		}
3459aee68ee5SJosef Bacik 
3460aee68ee5SJosef Bacik 		if (ret) {
3461aee68ee5SJosef Bacik 			skinny = false;
3462aee68ee5SJosef Bacik 			btrfs_release_path(path);
3463aee68ee5SJosef Bacik 			goto again;
3464aee68ee5SJosef Bacik 		}
3465aee68ee5SJosef Bacik 	}
3466cdccee99SLiu Bo 	if (ret) {
3467cdccee99SLiu Bo 		ASSERT(ret == 1);
3468cdccee99SLiu Bo 		btrfs_print_leaf(path->nodes[0]);
3469cdccee99SLiu Bo 		btrfs_err(fs_info,
3470cdccee99SLiu Bo 	     "tree block extent item (%llu) is not found in extent tree",
3471cdccee99SLiu Bo 		     bytenr);
3472cdccee99SLiu Bo 		WARN_ON(1);
3473cdccee99SLiu Bo 		ret = -EINVAL;
3474cdccee99SLiu Bo 		goto out;
3475cdccee99SLiu Bo 	}
34763173a18fSJosef Bacik 
34775d4f98a2SYan Zheng 	ret = add_tree_block(rc, &key, path, blocks);
34785d4f98a2SYan Zheng out:
34795d4f98a2SYan Zheng 	btrfs_free_path(path);
34805d4f98a2SYan Zheng 	return ret;
34815d4f98a2SYan Zheng }
34825d4f98a2SYan Zheng 
34830af3d00bSJosef Bacik static int delete_block_group_cache(struct btrfs_fs_info *fs_info,
348432da5386SDavid Sterba 				    struct btrfs_block_group *block_group,
34851bbc621eSChris Mason 				    struct inode *inode,
34861bbc621eSChris Mason 				    u64 ino)
34870af3d00bSJosef Bacik {
34880af3d00bSJosef Bacik 	struct btrfs_key key;
34890af3d00bSJosef Bacik 	struct btrfs_root *root = fs_info->tree_root;
34900af3d00bSJosef Bacik 	struct btrfs_trans_handle *trans;
34910af3d00bSJosef Bacik 	int ret = 0;
34920af3d00bSJosef Bacik 
34930af3d00bSJosef Bacik 	if (inode)
34940af3d00bSJosef Bacik 		goto truncate;
34950af3d00bSJosef Bacik 
34960af3d00bSJosef Bacik 	key.objectid = ino;
34970af3d00bSJosef Bacik 	key.type = BTRFS_INODE_ITEM_KEY;
34980af3d00bSJosef Bacik 	key.offset = 0;
34990af3d00bSJosef Bacik 
35004c66e0d4SDavid Sterba 	inode = btrfs_iget(fs_info->sb, &key, root);
35012e19f1f9SAl Viro 	if (IS_ERR(inode))
35020af3d00bSJosef Bacik 		return -ENOENT;
35030af3d00bSJosef Bacik 
35040af3d00bSJosef Bacik truncate:
35052ff7e61eSJeff Mahoney 	ret = btrfs_check_trunc_cache_free_space(fs_info,
35067b61cd92SMiao Xie 						 &fs_info->global_block_rsv);
35077b61cd92SMiao Xie 	if (ret)
35087b61cd92SMiao Xie 		goto out;
35097b61cd92SMiao Xie 
35107a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
35110af3d00bSJosef Bacik 	if (IS_ERR(trans)) {
35123612b495STsutomu Itoh 		ret = PTR_ERR(trans);
35130af3d00bSJosef Bacik 		goto out;
35140af3d00bSJosef Bacik 	}
35150af3d00bSJosef Bacik 
351677ab86bfSJeff Mahoney 	ret = btrfs_truncate_free_space_cache(trans, block_group, inode);
35170af3d00bSJosef Bacik 
35183a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
35192ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
35200af3d00bSJosef Bacik out:
35210af3d00bSJosef Bacik 	iput(inode);
35220af3d00bSJosef Bacik 	return ret;
35230af3d00bSJosef Bacik }
35240af3d00bSJosef Bacik 
35255d4f98a2SYan Zheng /*
352619b546d7SQu Wenruo  * Locate the free space cache EXTENT_DATA in root tree leaf and delete the
352719b546d7SQu Wenruo  * cache inode, to avoid free space cache data extent blocking data relocation.
35285d4f98a2SYan Zheng  */
352919b546d7SQu Wenruo static int delete_v1_space_cache(struct extent_buffer *leaf,
353019b546d7SQu Wenruo 				 struct btrfs_block_group *block_group,
353119b546d7SQu Wenruo 				 u64 data_bytenr)
35325d4f98a2SYan Zheng {
353319b546d7SQu Wenruo 	u64 space_cache_ino;
353419b546d7SQu Wenruo 	struct btrfs_file_extent_item *ei;
35355d4f98a2SYan Zheng 	struct btrfs_key key;
353619b546d7SQu Wenruo 	bool found = false;
353719b546d7SQu Wenruo 	int i;
35385d4f98a2SYan Zheng 	int ret;
35395d4f98a2SYan Zheng 
354019b546d7SQu Wenruo 	if (btrfs_header_owner(leaf) != BTRFS_ROOT_TREE_OBJECTID)
354119b546d7SQu Wenruo 		return 0;
35425d4f98a2SYan Zheng 
354319b546d7SQu Wenruo 	for (i = 0; i < btrfs_header_nritems(leaf); i++) {
354419b546d7SQu Wenruo 		btrfs_item_key_to_cpu(leaf, &key, i);
354519b546d7SQu Wenruo 		if (key.type != BTRFS_EXTENT_DATA_KEY)
354619b546d7SQu Wenruo 			continue;
354719b546d7SQu Wenruo 		ei = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
354819b546d7SQu Wenruo 		if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_REG &&
354919b546d7SQu Wenruo 		    btrfs_file_extent_disk_bytenr(leaf, ei) == data_bytenr) {
355019b546d7SQu Wenruo 			found = true;
355119b546d7SQu Wenruo 			space_cache_ino = key.objectid;
355219b546d7SQu Wenruo 			break;
355319b546d7SQu Wenruo 		}
355419b546d7SQu Wenruo 	}
355519b546d7SQu Wenruo 	if (!found)
355619b546d7SQu Wenruo 		return -ENOENT;
355719b546d7SQu Wenruo 	ret = delete_block_group_cache(leaf->fs_info, block_group, NULL,
355819b546d7SQu Wenruo 					space_cache_ino);
35590af3d00bSJosef Bacik 	return ret;
35605d4f98a2SYan Zheng }
35615d4f98a2SYan Zheng 
35625d4f98a2SYan Zheng /*
35632c016dc2SLiu Bo  * helper to find all tree blocks that reference a given data extent
35645d4f98a2SYan Zheng  */
35655d4f98a2SYan Zheng static noinline_for_stack
35665d4f98a2SYan Zheng int add_data_references(struct reloc_control *rc,
35675d4f98a2SYan Zheng 			struct btrfs_key *extent_key,
35685d4f98a2SYan Zheng 			struct btrfs_path *path,
35695d4f98a2SYan Zheng 			struct rb_root *blocks)
35705d4f98a2SYan Zheng {
357119b546d7SQu Wenruo 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
357219b546d7SQu Wenruo 	struct ulist *leaves = NULL;
357319b546d7SQu Wenruo 	struct ulist_iterator leaf_uiter;
357419b546d7SQu Wenruo 	struct ulist_node *ref_node = NULL;
357519b546d7SQu Wenruo 	const u32 blocksize = fs_info->nodesize;
3576647f63bdSFilipe David Borba Manana 	int ret = 0;
35775d4f98a2SYan Zheng 
3578b3b4aa74SDavid Sterba 	btrfs_release_path(path);
357919b546d7SQu Wenruo 	ret = btrfs_find_all_leafs(NULL, fs_info, extent_key->objectid,
358019b546d7SQu Wenruo 				   0, &leaves, NULL, true);
358119b546d7SQu Wenruo 	if (ret < 0)
358219b546d7SQu Wenruo 		return ret;
358319b546d7SQu Wenruo 
358419b546d7SQu Wenruo 	ULIST_ITER_INIT(&leaf_uiter);
358519b546d7SQu Wenruo 	while ((ref_node = ulist_next(leaves, &leaf_uiter))) {
358619b546d7SQu Wenruo 		struct extent_buffer *eb;
358719b546d7SQu Wenruo 
358819b546d7SQu Wenruo 		eb = read_tree_block(fs_info, ref_node->val, 0, 0, NULL);
358919b546d7SQu Wenruo 		if (IS_ERR(eb)) {
359019b546d7SQu Wenruo 			ret = PTR_ERR(eb);
359119b546d7SQu Wenruo 			break;
359219b546d7SQu Wenruo 		}
359319b546d7SQu Wenruo 		ret = delete_v1_space_cache(eb, rc->block_group,
359419b546d7SQu Wenruo 					    extent_key->objectid);
359519b546d7SQu Wenruo 		free_extent_buffer(eb);
359619b546d7SQu Wenruo 		if (ret < 0)
359719b546d7SQu Wenruo 			break;
359819b546d7SQu Wenruo 		ret = __add_tree_block(rc, ref_node->val, blocksize, blocks);
359919b546d7SQu Wenruo 		if (ret < 0)
360019b546d7SQu Wenruo 			break;
360119b546d7SQu Wenruo 	}
360219b546d7SQu Wenruo 	if (ret < 0)
36035d4f98a2SYan Zheng 		free_block_list(blocks);
360419b546d7SQu Wenruo 	ulist_free(leaves);
360519b546d7SQu Wenruo 	return ret;
36065d4f98a2SYan Zheng }
36075d4f98a2SYan Zheng 
36085d4f98a2SYan Zheng /*
36092c016dc2SLiu Bo  * helper to find next unprocessed extent
36105d4f98a2SYan Zheng  */
36115d4f98a2SYan Zheng static noinline_for_stack
3612147d256eSZhaolei int find_next_extent(struct reloc_control *rc, struct btrfs_path *path,
36133fd0a558SYan, Zheng 		     struct btrfs_key *extent_key)
36145d4f98a2SYan Zheng {
36150b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
36165d4f98a2SYan Zheng 	struct btrfs_key key;
36175d4f98a2SYan Zheng 	struct extent_buffer *leaf;
36185d4f98a2SYan Zheng 	u64 start, end, last;
36195d4f98a2SYan Zheng 	int ret;
36205d4f98a2SYan Zheng 
3621b3470b5dSDavid Sterba 	last = rc->block_group->start + rc->block_group->length;
36225d4f98a2SYan Zheng 	while (1) {
36235d4f98a2SYan Zheng 		cond_resched();
36245d4f98a2SYan Zheng 		if (rc->search_start >= last) {
36255d4f98a2SYan Zheng 			ret = 1;
36265d4f98a2SYan Zheng 			break;
36275d4f98a2SYan Zheng 		}
36285d4f98a2SYan Zheng 
36295d4f98a2SYan Zheng 		key.objectid = rc->search_start;
36305d4f98a2SYan Zheng 		key.type = BTRFS_EXTENT_ITEM_KEY;
36315d4f98a2SYan Zheng 		key.offset = 0;
36325d4f98a2SYan Zheng 
36335d4f98a2SYan Zheng 		path->search_commit_root = 1;
36345d4f98a2SYan Zheng 		path->skip_locking = 1;
36355d4f98a2SYan Zheng 		ret = btrfs_search_slot(NULL, rc->extent_root, &key, path,
36365d4f98a2SYan Zheng 					0, 0);
36375d4f98a2SYan Zheng 		if (ret < 0)
36385d4f98a2SYan Zheng 			break;
36395d4f98a2SYan Zheng next:
36405d4f98a2SYan Zheng 		leaf = path->nodes[0];
36415d4f98a2SYan Zheng 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
36425d4f98a2SYan Zheng 			ret = btrfs_next_leaf(rc->extent_root, path);
36435d4f98a2SYan Zheng 			if (ret != 0)
36445d4f98a2SYan Zheng 				break;
36455d4f98a2SYan Zheng 			leaf = path->nodes[0];
36465d4f98a2SYan Zheng 		}
36475d4f98a2SYan Zheng 
36485d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
36495d4f98a2SYan Zheng 		if (key.objectid >= last) {
36505d4f98a2SYan Zheng 			ret = 1;
36515d4f98a2SYan Zheng 			break;
36525d4f98a2SYan Zheng 		}
36535d4f98a2SYan Zheng 
36543173a18fSJosef Bacik 		if (key.type != BTRFS_EXTENT_ITEM_KEY &&
36553173a18fSJosef Bacik 		    key.type != BTRFS_METADATA_ITEM_KEY) {
36563173a18fSJosef Bacik 			path->slots[0]++;
36573173a18fSJosef Bacik 			goto next;
36583173a18fSJosef Bacik 		}
36593173a18fSJosef Bacik 
36603173a18fSJosef Bacik 		if (key.type == BTRFS_EXTENT_ITEM_KEY &&
36615d4f98a2SYan Zheng 		    key.objectid + key.offset <= rc->search_start) {
36625d4f98a2SYan Zheng 			path->slots[0]++;
36635d4f98a2SYan Zheng 			goto next;
36645d4f98a2SYan Zheng 		}
36655d4f98a2SYan Zheng 
36663173a18fSJosef Bacik 		if (key.type == BTRFS_METADATA_ITEM_KEY &&
36670b246afaSJeff Mahoney 		    key.objectid + fs_info->nodesize <=
36683173a18fSJosef Bacik 		    rc->search_start) {
36693173a18fSJosef Bacik 			path->slots[0]++;
36703173a18fSJosef Bacik 			goto next;
36713173a18fSJosef Bacik 		}
36723173a18fSJosef Bacik 
36735d4f98a2SYan Zheng 		ret = find_first_extent_bit(&rc->processed_blocks,
36745d4f98a2SYan Zheng 					    key.objectid, &start, &end,
3675e6138876SJosef Bacik 					    EXTENT_DIRTY, NULL);
36765d4f98a2SYan Zheng 
36775d4f98a2SYan Zheng 		if (ret == 0 && start <= key.objectid) {
3678b3b4aa74SDavid Sterba 			btrfs_release_path(path);
36795d4f98a2SYan Zheng 			rc->search_start = end + 1;
36805d4f98a2SYan Zheng 		} else {
36813173a18fSJosef Bacik 			if (key.type == BTRFS_EXTENT_ITEM_KEY)
36825d4f98a2SYan Zheng 				rc->search_start = key.objectid + key.offset;
36833173a18fSJosef Bacik 			else
36843173a18fSJosef Bacik 				rc->search_start = key.objectid +
36850b246afaSJeff Mahoney 					fs_info->nodesize;
36863fd0a558SYan, Zheng 			memcpy(extent_key, &key, sizeof(key));
36875d4f98a2SYan Zheng 			return 0;
36885d4f98a2SYan Zheng 		}
36895d4f98a2SYan Zheng 	}
3690b3b4aa74SDavid Sterba 	btrfs_release_path(path);
36915d4f98a2SYan Zheng 	return ret;
36925d4f98a2SYan Zheng }
36935d4f98a2SYan Zheng 
36945d4f98a2SYan Zheng static void set_reloc_control(struct reloc_control *rc)
36955d4f98a2SYan Zheng {
36965d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
36977585717fSChris Mason 
36987585717fSChris Mason 	mutex_lock(&fs_info->reloc_mutex);
36995d4f98a2SYan Zheng 	fs_info->reloc_ctl = rc;
37007585717fSChris Mason 	mutex_unlock(&fs_info->reloc_mutex);
37015d4f98a2SYan Zheng }
37025d4f98a2SYan Zheng 
37035d4f98a2SYan Zheng static void unset_reloc_control(struct reloc_control *rc)
37045d4f98a2SYan Zheng {
37055d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
37067585717fSChris Mason 
37077585717fSChris Mason 	mutex_lock(&fs_info->reloc_mutex);
37085d4f98a2SYan Zheng 	fs_info->reloc_ctl = NULL;
37097585717fSChris Mason 	mutex_unlock(&fs_info->reloc_mutex);
37105d4f98a2SYan Zheng }
37115d4f98a2SYan Zheng 
37125d4f98a2SYan Zheng static int check_extent_flags(u64 flags)
37135d4f98a2SYan Zheng {
37145d4f98a2SYan Zheng 	if ((flags & BTRFS_EXTENT_FLAG_DATA) &&
37155d4f98a2SYan Zheng 	    (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
37165d4f98a2SYan Zheng 		return 1;
37175d4f98a2SYan Zheng 	if (!(flags & BTRFS_EXTENT_FLAG_DATA) &&
37185d4f98a2SYan Zheng 	    !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
37195d4f98a2SYan Zheng 		return 1;
37205d4f98a2SYan Zheng 	if ((flags & BTRFS_EXTENT_FLAG_DATA) &&
37215d4f98a2SYan Zheng 	    (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
37225d4f98a2SYan Zheng 		return 1;
37235d4f98a2SYan Zheng 	return 0;
37245d4f98a2SYan Zheng }
37255d4f98a2SYan Zheng 
37263fd0a558SYan, Zheng static noinline_for_stack
37273fd0a558SYan, Zheng int prepare_to_relocate(struct reloc_control *rc)
37283fd0a558SYan, Zheng {
37293fd0a558SYan, Zheng 	struct btrfs_trans_handle *trans;
3730ac2fabacSJosef Bacik 	int ret;
37313fd0a558SYan, Zheng 
37322ff7e61eSJeff Mahoney 	rc->block_rsv = btrfs_alloc_block_rsv(rc->extent_root->fs_info,
373366d8f3ddSMiao Xie 					      BTRFS_BLOCK_RSV_TEMP);
37343fd0a558SYan, Zheng 	if (!rc->block_rsv)
37353fd0a558SYan, Zheng 		return -ENOMEM;
37363fd0a558SYan, Zheng 
37373fd0a558SYan, Zheng 	memset(&rc->cluster, 0, sizeof(rc->cluster));
3738b3470b5dSDavid Sterba 	rc->search_start = rc->block_group->start;
37393fd0a558SYan, Zheng 	rc->extents_found = 0;
37403fd0a558SYan, Zheng 	rc->nodes_relocated = 0;
37413fd0a558SYan, Zheng 	rc->merging_rsv_size = 0;
37420647bf56SWang Shilong 	rc->reserved_bytes = 0;
3743da17066cSJeff Mahoney 	rc->block_rsv->size = rc->extent_root->fs_info->nodesize *
37440647bf56SWang Shilong 			      RELOCATION_RESERVED_NODES;
3745ac2fabacSJosef Bacik 	ret = btrfs_block_rsv_refill(rc->extent_root,
3746ac2fabacSJosef Bacik 				     rc->block_rsv, rc->block_rsv->size,
3747ac2fabacSJosef Bacik 				     BTRFS_RESERVE_FLUSH_ALL);
3748ac2fabacSJosef Bacik 	if (ret)
3749ac2fabacSJosef Bacik 		return ret;
37503fd0a558SYan, Zheng 
37513fd0a558SYan, Zheng 	rc->create_reloc_tree = 1;
37523fd0a558SYan, Zheng 	set_reloc_control(rc);
37533fd0a558SYan, Zheng 
37547a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
375528818947SLiu Bo 	if (IS_ERR(trans)) {
375628818947SLiu Bo 		unset_reloc_control(rc);
375728818947SLiu Bo 		/*
375828818947SLiu Bo 		 * extent tree is not a ref_cow tree and has no reloc_root to
375928818947SLiu Bo 		 * cleanup.  And callers are responsible to free the above
376028818947SLiu Bo 		 * block rsv.
376128818947SLiu Bo 		 */
376228818947SLiu Bo 		return PTR_ERR(trans);
376328818947SLiu Bo 	}
37643a45bb20SJeff Mahoney 	btrfs_commit_transaction(trans);
37653fd0a558SYan, Zheng 	return 0;
37663fd0a558SYan, Zheng }
376776dda93cSYan, Zheng 
37685d4f98a2SYan Zheng static noinline_for_stack int relocate_block_group(struct reloc_control *rc)
37695d4f98a2SYan Zheng {
37702ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
37715d4f98a2SYan Zheng 	struct rb_root blocks = RB_ROOT;
37725d4f98a2SYan Zheng 	struct btrfs_key key;
37735d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans = NULL;
37745d4f98a2SYan Zheng 	struct btrfs_path *path;
37755d4f98a2SYan Zheng 	struct btrfs_extent_item *ei;
37765d4f98a2SYan Zheng 	u64 flags;
37775d4f98a2SYan Zheng 	u32 item_size;
37785d4f98a2SYan Zheng 	int ret;
37795d4f98a2SYan Zheng 	int err = 0;
3780c87f08caSChris Mason 	int progress = 0;
37815d4f98a2SYan Zheng 
37825d4f98a2SYan Zheng 	path = btrfs_alloc_path();
37833fd0a558SYan, Zheng 	if (!path)
37845d4f98a2SYan Zheng 		return -ENOMEM;
3785e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
37863fd0a558SYan, Zheng 
37873fd0a558SYan, Zheng 	ret = prepare_to_relocate(rc);
37883fd0a558SYan, Zheng 	if (ret) {
37893fd0a558SYan, Zheng 		err = ret;
37903fd0a558SYan, Zheng 		goto out_free;
37912423fdfbSJiri Slaby 	}
37925d4f98a2SYan Zheng 
37935d4f98a2SYan Zheng 	while (1) {
37940647bf56SWang Shilong 		rc->reserved_bytes = 0;
37950647bf56SWang Shilong 		ret = btrfs_block_rsv_refill(rc->extent_root,
37960647bf56SWang Shilong 					rc->block_rsv, rc->block_rsv->size,
37970647bf56SWang Shilong 					BTRFS_RESERVE_FLUSH_ALL);
37980647bf56SWang Shilong 		if (ret) {
37990647bf56SWang Shilong 			err = ret;
38000647bf56SWang Shilong 			break;
38010647bf56SWang Shilong 		}
3802c87f08caSChris Mason 		progress++;
3803a22285a6SYan, Zheng 		trans = btrfs_start_transaction(rc->extent_root, 0);
38040f788c58SLiu Bo 		if (IS_ERR(trans)) {
38050f788c58SLiu Bo 			err = PTR_ERR(trans);
38060f788c58SLiu Bo 			trans = NULL;
38070f788c58SLiu Bo 			break;
38080f788c58SLiu Bo 		}
3809c87f08caSChris Mason restart:
38103fd0a558SYan, Zheng 		if (update_backref_cache(trans, &rc->backref_cache)) {
38113a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
381242a657f5SPan Bian 			trans = NULL;
38133fd0a558SYan, Zheng 			continue;
38143fd0a558SYan, Zheng 		}
38153fd0a558SYan, Zheng 
3816147d256eSZhaolei 		ret = find_next_extent(rc, path, &key);
38175d4f98a2SYan Zheng 		if (ret < 0)
38185d4f98a2SYan Zheng 			err = ret;
38195d4f98a2SYan Zheng 		if (ret != 0)
38205d4f98a2SYan Zheng 			break;
38215d4f98a2SYan Zheng 
38225d4f98a2SYan Zheng 		rc->extents_found++;
38235d4f98a2SYan Zheng 
38245d4f98a2SYan Zheng 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
38255d4f98a2SYan Zheng 				    struct btrfs_extent_item);
38263fd0a558SYan, Zheng 		item_size = btrfs_item_size_nr(path->nodes[0], path->slots[0]);
38275d4f98a2SYan Zheng 		if (item_size >= sizeof(*ei)) {
38285d4f98a2SYan Zheng 			flags = btrfs_extent_flags(path->nodes[0], ei);
38295d4f98a2SYan Zheng 			ret = check_extent_flags(flags);
38305d4f98a2SYan Zheng 			BUG_ON(ret);
38316d8ff4e4SDavid Sterba 		} else if (unlikely(item_size == sizeof(struct btrfs_extent_item_v0))) {
3832ba3c2b19SNikolay Borisov 			err = -EINVAL;
3833ba3c2b19SNikolay Borisov 			btrfs_print_v0_err(trans->fs_info);
3834ba3c2b19SNikolay Borisov 			btrfs_abort_transaction(trans, err);
3835ba3c2b19SNikolay Borisov 			break;
38365d4f98a2SYan Zheng 		} else {
38375d4f98a2SYan Zheng 			BUG();
38385d4f98a2SYan Zheng 		}
38395d4f98a2SYan Zheng 
38405d4f98a2SYan Zheng 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
38415d4f98a2SYan Zheng 			ret = add_tree_block(rc, &key, path, &blocks);
38425d4f98a2SYan Zheng 		} else if (rc->stage == UPDATE_DATA_PTRS &&
38435d4f98a2SYan Zheng 			   (flags & BTRFS_EXTENT_FLAG_DATA)) {
38445d4f98a2SYan Zheng 			ret = add_data_references(rc, &key, path, &blocks);
38455d4f98a2SYan Zheng 		} else {
3846b3b4aa74SDavid Sterba 			btrfs_release_path(path);
38475d4f98a2SYan Zheng 			ret = 0;
38485d4f98a2SYan Zheng 		}
38495d4f98a2SYan Zheng 		if (ret < 0) {
38503fd0a558SYan, Zheng 			err = ret;
38515d4f98a2SYan Zheng 			break;
38525d4f98a2SYan Zheng 		}
38535d4f98a2SYan Zheng 
38545d4f98a2SYan Zheng 		if (!RB_EMPTY_ROOT(&blocks)) {
38555d4f98a2SYan Zheng 			ret = relocate_tree_blocks(trans, rc, &blocks);
38565d4f98a2SYan Zheng 			if (ret < 0) {
38573fd0a558SYan, Zheng 				if (ret != -EAGAIN) {
38585d4f98a2SYan Zheng 					err = ret;
38595d4f98a2SYan Zheng 					break;
38605d4f98a2SYan Zheng 				}
38613fd0a558SYan, Zheng 				rc->extents_found--;
38623fd0a558SYan, Zheng 				rc->search_start = key.objectid;
38633fd0a558SYan, Zheng 			}
38645d4f98a2SYan Zheng 		}
38655d4f98a2SYan Zheng 
38663a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
38672ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
38683fd0a558SYan, Zheng 		trans = NULL;
38695d4f98a2SYan Zheng 
38705d4f98a2SYan Zheng 		if (rc->stage == MOVE_DATA_EXTENTS &&
38715d4f98a2SYan Zheng 		    (flags & BTRFS_EXTENT_FLAG_DATA)) {
38725d4f98a2SYan Zheng 			rc->found_file_extent = 1;
38730257bb82SYan, Zheng 			ret = relocate_data_extent(rc->data_inode,
38743fd0a558SYan, Zheng 						   &key, &rc->cluster);
38755d4f98a2SYan Zheng 			if (ret < 0) {
38765d4f98a2SYan Zheng 				err = ret;
38775d4f98a2SYan Zheng 				break;
38785d4f98a2SYan Zheng 			}
38795d4f98a2SYan Zheng 		}
3880f31ea088SQu Wenruo 		if (btrfs_should_cancel_balance(fs_info)) {
3881f31ea088SQu Wenruo 			err = -ECANCELED;
3882f31ea088SQu Wenruo 			break;
3883f31ea088SQu Wenruo 		}
38845d4f98a2SYan Zheng 	}
3885c87f08caSChris Mason 	if (trans && progress && err == -ENOSPC) {
388643a7e99dSNikolay Borisov 		ret = btrfs_force_chunk_alloc(trans, rc->block_group->flags);
38879689457bSShilong Wang 		if (ret == 1) {
3888c87f08caSChris Mason 			err = 0;
3889c87f08caSChris Mason 			progress = 0;
3890c87f08caSChris Mason 			goto restart;
3891c87f08caSChris Mason 		}
3892c87f08caSChris Mason 	}
38933fd0a558SYan, Zheng 
3894b3b4aa74SDavid Sterba 	btrfs_release_path(path);
389591166212SDavid Sterba 	clear_extent_bits(&rc->processed_blocks, 0, (u64)-1, EXTENT_DIRTY);
38965d4f98a2SYan Zheng 
38975d4f98a2SYan Zheng 	if (trans) {
38983a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
38992ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
39005d4f98a2SYan Zheng 	}
39015d4f98a2SYan Zheng 
39020257bb82SYan, Zheng 	if (!err) {
39033fd0a558SYan, Zheng 		ret = relocate_file_extent_cluster(rc->data_inode,
39043fd0a558SYan, Zheng 						   &rc->cluster);
39050257bb82SYan, Zheng 		if (ret < 0)
39060257bb82SYan, Zheng 			err = ret;
39070257bb82SYan, Zheng 	}
39080257bb82SYan, Zheng 
39093fd0a558SYan, Zheng 	rc->create_reloc_tree = 0;
39103fd0a558SYan, Zheng 	set_reloc_control(rc);
39110257bb82SYan, Zheng 
391213fe1bdbSQu Wenruo 	btrfs_backref_release_cache(&rc->backref_cache);
391363f018beSNikolay Borisov 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
39145d4f98a2SYan Zheng 
39157f913c7cSQu Wenruo 	/*
39167f913c7cSQu Wenruo 	 * Even in the case when the relocation is cancelled, we should all go
39177f913c7cSQu Wenruo 	 * through prepare_to_merge() and merge_reloc_roots().
39187f913c7cSQu Wenruo 	 *
39197f913c7cSQu Wenruo 	 * For error (including cancelled balance), prepare_to_merge() will
39207f913c7cSQu Wenruo 	 * mark all reloc trees orphan, then queue them for cleanup in
39217f913c7cSQu Wenruo 	 * merge_reloc_roots()
39227f913c7cSQu Wenruo 	 */
39233fd0a558SYan, Zheng 	err = prepare_to_merge(rc, err);
39245d4f98a2SYan Zheng 
39255d4f98a2SYan Zheng 	merge_reloc_roots(rc);
39265d4f98a2SYan Zheng 
39273fd0a558SYan, Zheng 	rc->merge_reloc_tree = 0;
39285d4f98a2SYan Zheng 	unset_reloc_control(rc);
392963f018beSNikolay Borisov 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
39305d4f98a2SYan Zheng 
39315d4f98a2SYan Zheng 	/* get rid of pinned extents */
39327a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
393362b99540SQu Wenruo 	if (IS_ERR(trans)) {
39343612b495STsutomu Itoh 		err = PTR_ERR(trans);
393562b99540SQu Wenruo 		goto out_free;
393662b99540SQu Wenruo 	}
39373a45bb20SJeff Mahoney 	btrfs_commit_transaction(trans);
39386217b0faSJosef Bacik out_free:
3939d2311e69SQu Wenruo 	ret = clean_dirty_subvols(rc);
3940d2311e69SQu Wenruo 	if (ret < 0 && !err)
3941d2311e69SQu Wenruo 		err = ret;
39422ff7e61eSJeff Mahoney 	btrfs_free_block_rsv(fs_info, rc->block_rsv);
39433fd0a558SYan, Zheng 	btrfs_free_path(path);
39445d4f98a2SYan Zheng 	return err;
39455d4f98a2SYan Zheng }
39465d4f98a2SYan Zheng 
39475d4f98a2SYan Zheng static int __insert_orphan_inode(struct btrfs_trans_handle *trans,
39480257bb82SYan, Zheng 				 struct btrfs_root *root, u64 objectid)
39495d4f98a2SYan Zheng {
39505d4f98a2SYan Zheng 	struct btrfs_path *path;
39515d4f98a2SYan Zheng 	struct btrfs_inode_item *item;
39525d4f98a2SYan Zheng 	struct extent_buffer *leaf;
39535d4f98a2SYan Zheng 	int ret;
39545d4f98a2SYan Zheng 
39555d4f98a2SYan Zheng 	path = btrfs_alloc_path();
39565d4f98a2SYan Zheng 	if (!path)
39575d4f98a2SYan Zheng 		return -ENOMEM;
39585d4f98a2SYan Zheng 
39595d4f98a2SYan Zheng 	ret = btrfs_insert_empty_inode(trans, root, path, objectid);
39605d4f98a2SYan Zheng 	if (ret)
39615d4f98a2SYan Zheng 		goto out;
39625d4f98a2SYan Zheng 
39635d4f98a2SYan Zheng 	leaf = path->nodes[0];
39645d4f98a2SYan Zheng 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item);
3965b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
39665d4f98a2SYan Zheng 	btrfs_set_inode_generation(leaf, item, 1);
39670257bb82SYan, Zheng 	btrfs_set_inode_size(leaf, item, 0);
39685d4f98a2SYan Zheng 	btrfs_set_inode_mode(leaf, item, S_IFREG | 0600);
39693fd0a558SYan, Zheng 	btrfs_set_inode_flags(leaf, item, BTRFS_INODE_NOCOMPRESS |
39703fd0a558SYan, Zheng 					  BTRFS_INODE_PREALLOC);
39715d4f98a2SYan Zheng 	btrfs_mark_buffer_dirty(leaf);
39725d4f98a2SYan Zheng out:
39735d4f98a2SYan Zheng 	btrfs_free_path(path);
39745d4f98a2SYan Zheng 	return ret;
39755d4f98a2SYan Zheng }
39765d4f98a2SYan Zheng 
39775d4f98a2SYan Zheng /*
39785d4f98a2SYan Zheng  * helper to create inode for data relocation.
39795d4f98a2SYan Zheng  * the inode is in data relocation tree and its link count is 0
39805d4f98a2SYan Zheng  */
39813fd0a558SYan, Zheng static noinline_for_stack
39823fd0a558SYan, Zheng struct inode *create_reloc_inode(struct btrfs_fs_info *fs_info,
398332da5386SDavid Sterba 				 struct btrfs_block_group *group)
39845d4f98a2SYan Zheng {
39855d4f98a2SYan Zheng 	struct inode *inode = NULL;
39865d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
39875d4f98a2SYan Zheng 	struct btrfs_root *root;
39885d4f98a2SYan Zheng 	struct btrfs_key key;
39894624900dSZhaolei 	u64 objectid;
39905d4f98a2SYan Zheng 	int err = 0;
39915d4f98a2SYan Zheng 
39925d4f98a2SYan Zheng 	root = read_fs_root(fs_info, BTRFS_DATA_RELOC_TREE_OBJECTID);
39935d4f98a2SYan Zheng 	if (IS_ERR(root))
39945d4f98a2SYan Zheng 		return ERR_CAST(root);
39955d4f98a2SYan Zheng 
3996a22285a6SYan, Zheng 	trans = btrfs_start_transaction(root, 6);
399776deacf0SJosef Bacik 	if (IS_ERR(trans)) {
399800246528SJosef Bacik 		btrfs_put_root(root);
39993fd0a558SYan, Zheng 		return ERR_CAST(trans);
400076deacf0SJosef Bacik 	}
40015d4f98a2SYan Zheng 
4002581bb050SLi Zefan 	err = btrfs_find_free_objectid(root, &objectid);
40035d4f98a2SYan Zheng 	if (err)
40045d4f98a2SYan Zheng 		goto out;
40055d4f98a2SYan Zheng 
40060257bb82SYan, Zheng 	err = __insert_orphan_inode(trans, root, objectid);
40075d4f98a2SYan Zheng 	BUG_ON(err);
40085d4f98a2SYan Zheng 
40095d4f98a2SYan Zheng 	key.objectid = objectid;
40105d4f98a2SYan Zheng 	key.type = BTRFS_INODE_ITEM_KEY;
40115d4f98a2SYan Zheng 	key.offset = 0;
40124c66e0d4SDavid Sterba 	inode = btrfs_iget(fs_info->sb, &key, root);
40132e19f1f9SAl Viro 	BUG_ON(IS_ERR(inode));
4014b3470b5dSDavid Sterba 	BTRFS_I(inode)->index_cnt = group->start;
40155d4f98a2SYan Zheng 
401673f2e545SNikolay Borisov 	err = btrfs_orphan_add(trans, BTRFS_I(inode));
40175d4f98a2SYan Zheng out:
401800246528SJosef Bacik 	btrfs_put_root(root);
40193a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
40202ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
40215d4f98a2SYan Zheng 	if (err) {
40225d4f98a2SYan Zheng 		if (inode)
40235d4f98a2SYan Zheng 			iput(inode);
40245d4f98a2SYan Zheng 		inode = ERR_PTR(err);
40255d4f98a2SYan Zheng 	}
40265d4f98a2SYan Zheng 	return inode;
40275d4f98a2SYan Zheng }
40285d4f98a2SYan Zheng 
4029c258d6e3SQu Wenruo static struct reloc_control *alloc_reloc_control(struct btrfs_fs_info *fs_info)
40303fd0a558SYan, Zheng {
40313fd0a558SYan, Zheng 	struct reloc_control *rc;
40323fd0a558SYan, Zheng 
40333fd0a558SYan, Zheng 	rc = kzalloc(sizeof(*rc), GFP_NOFS);
40343fd0a558SYan, Zheng 	if (!rc)
40353fd0a558SYan, Zheng 		return NULL;
40363fd0a558SYan, Zheng 
40373fd0a558SYan, Zheng 	INIT_LIST_HEAD(&rc->reloc_roots);
4038d2311e69SQu Wenruo 	INIT_LIST_HEAD(&rc->dirty_subvol_roots);
4039584fb121SQu Wenruo 	btrfs_backref_init_cache(fs_info, &rc->backref_cache, 1);
40403fd0a558SYan, Zheng 	mapping_tree_init(&rc->reloc_root_tree);
404143eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &rc->processed_blocks,
404243eb5f29SQu Wenruo 			    IO_TREE_RELOC_BLOCKS, NULL);
40433fd0a558SYan, Zheng 	return rc;
40443fd0a558SYan, Zheng }
40453fd0a558SYan, Zheng 
40461a0afa0eSJosef Bacik static void free_reloc_control(struct reloc_control *rc)
40471a0afa0eSJosef Bacik {
40481a0afa0eSJosef Bacik 	struct mapping_node *node, *tmp;
40491a0afa0eSJosef Bacik 
40501a0afa0eSJosef Bacik 	free_reloc_roots(&rc->reloc_roots);
40511a0afa0eSJosef Bacik 	rbtree_postorder_for_each_entry_safe(node, tmp,
40521a0afa0eSJosef Bacik 			&rc->reloc_root_tree.rb_root, rb_node)
40531a0afa0eSJosef Bacik 		kfree(node);
40541a0afa0eSJosef Bacik 
40551a0afa0eSJosef Bacik 	kfree(rc);
40561a0afa0eSJosef Bacik }
40571a0afa0eSJosef Bacik 
40585d4f98a2SYan Zheng /*
4059ebce0e01SAdam Borowski  * Print the block group being relocated
4060ebce0e01SAdam Borowski  */
4061ebce0e01SAdam Borowski static void describe_relocation(struct btrfs_fs_info *fs_info,
406232da5386SDavid Sterba 				struct btrfs_block_group *block_group)
4063ebce0e01SAdam Borowski {
4064f89e09cfSAnand Jain 	char buf[128] = {'\0'};
4065ebce0e01SAdam Borowski 
4066f89e09cfSAnand Jain 	btrfs_describe_block_groups(block_group->flags, buf, sizeof(buf));
4067ebce0e01SAdam Borowski 
4068ebce0e01SAdam Borowski 	btrfs_info(fs_info,
4069ebce0e01SAdam Borowski 		   "relocating block group %llu flags %s",
4070b3470b5dSDavid Sterba 		   block_group->start, buf);
4071ebce0e01SAdam Borowski }
4072ebce0e01SAdam Borowski 
4073430640e3SQu Wenruo static const char *stage_to_string(int stage)
4074430640e3SQu Wenruo {
4075430640e3SQu Wenruo 	if (stage == MOVE_DATA_EXTENTS)
4076430640e3SQu Wenruo 		return "move data extents";
4077430640e3SQu Wenruo 	if (stage == UPDATE_DATA_PTRS)
4078430640e3SQu Wenruo 		return "update data pointers";
4079430640e3SQu Wenruo 	return "unknown";
4080430640e3SQu Wenruo }
4081430640e3SQu Wenruo 
4082ebce0e01SAdam Borowski /*
40835d4f98a2SYan Zheng  * function to relocate all extents in a block group.
40845d4f98a2SYan Zheng  */
40856bccf3abSJeff Mahoney int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start)
40865d4f98a2SYan Zheng {
408732da5386SDavid Sterba 	struct btrfs_block_group *bg;
40886bccf3abSJeff Mahoney 	struct btrfs_root *extent_root = fs_info->extent_root;
40895d4f98a2SYan Zheng 	struct reloc_control *rc;
40900af3d00bSJosef Bacik 	struct inode *inode;
40910af3d00bSJosef Bacik 	struct btrfs_path *path;
40925d4f98a2SYan Zheng 	int ret;
4093f0486c68SYan, Zheng 	int rw = 0;
40945d4f98a2SYan Zheng 	int err = 0;
40955d4f98a2SYan Zheng 
4096eede2bf3SOmar Sandoval 	bg = btrfs_lookup_block_group(fs_info, group_start);
4097eede2bf3SOmar Sandoval 	if (!bg)
4098eede2bf3SOmar Sandoval 		return -ENOENT;
4099eede2bf3SOmar Sandoval 
4100eede2bf3SOmar Sandoval 	if (btrfs_pinned_by_swapfile(fs_info, bg)) {
4101eede2bf3SOmar Sandoval 		btrfs_put_block_group(bg);
4102eede2bf3SOmar Sandoval 		return -ETXTBSY;
4103eede2bf3SOmar Sandoval 	}
4104eede2bf3SOmar Sandoval 
4105c258d6e3SQu Wenruo 	rc = alloc_reloc_control(fs_info);
4106eede2bf3SOmar Sandoval 	if (!rc) {
4107eede2bf3SOmar Sandoval 		btrfs_put_block_group(bg);
41085d4f98a2SYan Zheng 		return -ENOMEM;
4109eede2bf3SOmar Sandoval 	}
41105d4f98a2SYan Zheng 
4111f0486c68SYan, Zheng 	rc->extent_root = extent_root;
4112eede2bf3SOmar Sandoval 	rc->block_group = bg;
41135d4f98a2SYan Zheng 
4114b12de528SQu Wenruo 	ret = btrfs_inc_block_group_ro(rc->block_group, true);
4115f0486c68SYan, Zheng 	if (ret) {
4116f0486c68SYan, Zheng 		err = ret;
4117f0486c68SYan, Zheng 		goto out;
4118f0486c68SYan, Zheng 	}
4119f0486c68SYan, Zheng 	rw = 1;
4120f0486c68SYan, Zheng 
41210af3d00bSJosef Bacik 	path = btrfs_alloc_path();
41220af3d00bSJosef Bacik 	if (!path) {
41230af3d00bSJosef Bacik 		err = -ENOMEM;
41240af3d00bSJosef Bacik 		goto out;
41250af3d00bSJosef Bacik 	}
41260af3d00bSJosef Bacik 
41277949f339SDavid Sterba 	inode = lookup_free_space_inode(rc->block_group, path);
41280af3d00bSJosef Bacik 	btrfs_free_path(path);
41290af3d00bSJosef Bacik 
41300af3d00bSJosef Bacik 	if (!IS_ERR(inode))
41311bbc621eSChris Mason 		ret = delete_block_group_cache(fs_info, rc->block_group, inode, 0);
41320af3d00bSJosef Bacik 	else
41330af3d00bSJosef Bacik 		ret = PTR_ERR(inode);
41340af3d00bSJosef Bacik 
41350af3d00bSJosef Bacik 	if (ret && ret != -ENOENT) {
41360af3d00bSJosef Bacik 		err = ret;
41370af3d00bSJosef Bacik 		goto out;
41380af3d00bSJosef Bacik 	}
41390af3d00bSJosef Bacik 
41405d4f98a2SYan Zheng 	rc->data_inode = create_reloc_inode(fs_info, rc->block_group);
41415d4f98a2SYan Zheng 	if (IS_ERR(rc->data_inode)) {
41425d4f98a2SYan Zheng 		err = PTR_ERR(rc->data_inode);
41435d4f98a2SYan Zheng 		rc->data_inode = NULL;
41445d4f98a2SYan Zheng 		goto out;
41455d4f98a2SYan Zheng 	}
41465d4f98a2SYan Zheng 
41470b246afaSJeff Mahoney 	describe_relocation(fs_info, rc->block_group);
41485d4f98a2SYan Zheng 
41499cfa3e34SFilipe Manana 	btrfs_wait_block_group_reservations(rc->block_group);
4150f78c436cSFilipe Manana 	btrfs_wait_nocow_writers(rc->block_group);
41516374e57aSChris Mason 	btrfs_wait_ordered_roots(fs_info, U64_MAX,
4152b3470b5dSDavid Sterba 				 rc->block_group->start,
4153b3470b5dSDavid Sterba 				 rc->block_group->length);
41545d4f98a2SYan Zheng 
41555d4f98a2SYan Zheng 	while (1) {
4156430640e3SQu Wenruo 		int finishes_stage;
4157430640e3SQu Wenruo 
415876dda93cSYan, Zheng 		mutex_lock(&fs_info->cleaner_mutex);
41595d4f98a2SYan Zheng 		ret = relocate_block_group(rc);
416076dda93cSYan, Zheng 		mutex_unlock(&fs_info->cleaner_mutex);
4161ff612ba7SJosef Bacik 		if (ret < 0)
41625d4f98a2SYan Zheng 			err = ret;
4163ff612ba7SJosef Bacik 
4164430640e3SQu Wenruo 		finishes_stage = rc->stage;
4165ff612ba7SJosef Bacik 		/*
4166ff612ba7SJosef Bacik 		 * We may have gotten ENOSPC after we already dirtied some
4167ff612ba7SJosef Bacik 		 * extents.  If writeout happens while we're relocating a
4168ff612ba7SJosef Bacik 		 * different block group we could end up hitting the
4169ff612ba7SJosef Bacik 		 * BUG_ON(rc->stage == UPDATE_DATA_PTRS) in
4170ff612ba7SJosef Bacik 		 * btrfs_reloc_cow_block.  Make sure we write everything out
4171ff612ba7SJosef Bacik 		 * properly so we don't trip over this problem, and then break
4172ff612ba7SJosef Bacik 		 * out of the loop if we hit an error.
4173ff612ba7SJosef Bacik 		 */
4174ff612ba7SJosef Bacik 		if (rc->stage == MOVE_DATA_EXTENTS && rc->found_file_extent) {
4175ff612ba7SJosef Bacik 			ret = btrfs_wait_ordered_range(rc->data_inode, 0,
4176ff612ba7SJosef Bacik 						       (u64)-1);
4177ff612ba7SJosef Bacik 			if (ret)
4178ff612ba7SJosef Bacik 				err = ret;
4179ff612ba7SJosef Bacik 			invalidate_mapping_pages(rc->data_inode->i_mapping,
4180ff612ba7SJosef Bacik 						 0, -1);
4181ff612ba7SJosef Bacik 			rc->stage = UPDATE_DATA_PTRS;
41825d4f98a2SYan Zheng 		}
41835d4f98a2SYan Zheng 
4184ff612ba7SJosef Bacik 		if (err < 0)
4185ff612ba7SJosef Bacik 			goto out;
4186ff612ba7SJosef Bacik 
41875d4f98a2SYan Zheng 		if (rc->extents_found == 0)
41885d4f98a2SYan Zheng 			break;
41895d4f98a2SYan Zheng 
4190430640e3SQu Wenruo 		btrfs_info(fs_info, "found %llu extents, stage: %s",
4191430640e3SQu Wenruo 			   rc->extents_found, stage_to_string(finishes_stage));
41925d4f98a2SYan Zheng 	}
41935d4f98a2SYan Zheng 
41945d4f98a2SYan Zheng 	WARN_ON(rc->block_group->pinned > 0);
41955d4f98a2SYan Zheng 	WARN_ON(rc->block_group->reserved > 0);
4196bf38be65SDavid Sterba 	WARN_ON(rc->block_group->used > 0);
41975d4f98a2SYan Zheng out:
4198f0486c68SYan, Zheng 	if (err && rw)
41992ff7e61eSJeff Mahoney 		btrfs_dec_block_group_ro(rc->block_group);
42005d4f98a2SYan Zheng 	iput(rc->data_inode);
42015d4f98a2SYan Zheng 	btrfs_put_block_group(rc->block_group);
42021a0afa0eSJosef Bacik 	free_reloc_control(rc);
42035d4f98a2SYan Zheng 	return err;
42045d4f98a2SYan Zheng }
42055d4f98a2SYan Zheng 
420676dda93cSYan, Zheng static noinline_for_stack int mark_garbage_root(struct btrfs_root *root)
420776dda93cSYan, Zheng {
42080b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
420976dda93cSYan, Zheng 	struct btrfs_trans_handle *trans;
421079787eaaSJeff Mahoney 	int ret, err;
421176dda93cSYan, Zheng 
42120b246afaSJeff Mahoney 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
421379787eaaSJeff Mahoney 	if (IS_ERR(trans))
421479787eaaSJeff Mahoney 		return PTR_ERR(trans);
421576dda93cSYan, Zheng 
421676dda93cSYan, Zheng 	memset(&root->root_item.drop_progress, 0,
421776dda93cSYan, Zheng 		sizeof(root->root_item.drop_progress));
421876dda93cSYan, Zheng 	root->root_item.drop_level = 0;
421976dda93cSYan, Zheng 	btrfs_set_root_refs(&root->root_item, 0);
42200b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
422176dda93cSYan, Zheng 				&root->root_key, &root->root_item);
422276dda93cSYan, Zheng 
42233a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
422479787eaaSJeff Mahoney 	if (err)
422579787eaaSJeff Mahoney 		return err;
422679787eaaSJeff Mahoney 	return ret;
422776dda93cSYan, Zheng }
422876dda93cSYan, Zheng 
42295d4f98a2SYan Zheng /*
42305d4f98a2SYan Zheng  * recover relocation interrupted by system crash.
42315d4f98a2SYan Zheng  *
42325d4f98a2SYan Zheng  * this function resumes merging reloc trees with corresponding fs trees.
42335d4f98a2SYan Zheng  * this is important for keeping the sharing of tree blocks
42345d4f98a2SYan Zheng  */
42355d4f98a2SYan Zheng int btrfs_recover_relocation(struct btrfs_root *root)
42365d4f98a2SYan Zheng {
42370b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
42385d4f98a2SYan Zheng 	LIST_HEAD(reloc_roots);
42395d4f98a2SYan Zheng 	struct btrfs_key key;
42405d4f98a2SYan Zheng 	struct btrfs_root *fs_root;
42415d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
42425d4f98a2SYan Zheng 	struct btrfs_path *path;
42435d4f98a2SYan Zheng 	struct extent_buffer *leaf;
42445d4f98a2SYan Zheng 	struct reloc_control *rc = NULL;
42455d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
42465d4f98a2SYan Zheng 	int ret;
42475d4f98a2SYan Zheng 	int err = 0;
42485d4f98a2SYan Zheng 
42495d4f98a2SYan Zheng 	path = btrfs_alloc_path();
42505d4f98a2SYan Zheng 	if (!path)
42515d4f98a2SYan Zheng 		return -ENOMEM;
4252e4058b54SDavid Sterba 	path->reada = READA_BACK;
42535d4f98a2SYan Zheng 
42545d4f98a2SYan Zheng 	key.objectid = BTRFS_TREE_RELOC_OBJECTID;
42555d4f98a2SYan Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
42565d4f98a2SYan Zheng 	key.offset = (u64)-1;
42575d4f98a2SYan Zheng 
42585d4f98a2SYan Zheng 	while (1) {
42590b246afaSJeff Mahoney 		ret = btrfs_search_slot(NULL, fs_info->tree_root, &key,
42605d4f98a2SYan Zheng 					path, 0, 0);
42615d4f98a2SYan Zheng 		if (ret < 0) {
42625d4f98a2SYan Zheng 			err = ret;
42635d4f98a2SYan Zheng 			goto out;
42645d4f98a2SYan Zheng 		}
42655d4f98a2SYan Zheng 		if (ret > 0) {
42665d4f98a2SYan Zheng 			if (path->slots[0] == 0)
42675d4f98a2SYan Zheng 				break;
42685d4f98a2SYan Zheng 			path->slots[0]--;
42695d4f98a2SYan Zheng 		}
42705d4f98a2SYan Zheng 		leaf = path->nodes[0];
42715d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4272b3b4aa74SDavid Sterba 		btrfs_release_path(path);
42735d4f98a2SYan Zheng 
42745d4f98a2SYan Zheng 		if (key.objectid != BTRFS_TREE_RELOC_OBJECTID ||
42755d4f98a2SYan Zheng 		    key.type != BTRFS_ROOT_ITEM_KEY)
42765d4f98a2SYan Zheng 			break;
42775d4f98a2SYan Zheng 
42783dbf1738SJosef Bacik 		reloc_root = btrfs_read_tree_root(root, &key);
42795d4f98a2SYan Zheng 		if (IS_ERR(reloc_root)) {
42805d4f98a2SYan Zheng 			err = PTR_ERR(reloc_root);
42815d4f98a2SYan Zheng 			goto out;
42825d4f98a2SYan Zheng 		}
42835d4f98a2SYan Zheng 
42843dbf1738SJosef Bacik 		set_bit(BTRFS_ROOT_REF_COWS, &reloc_root->state);
42855d4f98a2SYan Zheng 		list_add(&reloc_root->root_list, &reloc_roots);
42865d4f98a2SYan Zheng 
42875d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
42880b246afaSJeff Mahoney 			fs_root = read_fs_root(fs_info,
42895d4f98a2SYan Zheng 					       reloc_root->root_key.offset);
42905d4f98a2SYan Zheng 			if (IS_ERR(fs_root)) {
429176dda93cSYan, Zheng 				ret = PTR_ERR(fs_root);
429276dda93cSYan, Zheng 				if (ret != -ENOENT) {
429376dda93cSYan, Zheng 					err = ret;
42945d4f98a2SYan Zheng 					goto out;
42955d4f98a2SYan Zheng 				}
429679787eaaSJeff Mahoney 				ret = mark_garbage_root(reloc_root);
429779787eaaSJeff Mahoney 				if (ret < 0) {
429879787eaaSJeff Mahoney 					err = ret;
429979787eaaSJeff Mahoney 					goto out;
430079787eaaSJeff Mahoney 				}
4301932fd26dSJosef Bacik 			} else {
430200246528SJosef Bacik 				btrfs_put_root(fs_root);
430376dda93cSYan, Zheng 			}
43045d4f98a2SYan Zheng 		}
43055d4f98a2SYan Zheng 
43065d4f98a2SYan Zheng 		if (key.offset == 0)
43075d4f98a2SYan Zheng 			break;
43085d4f98a2SYan Zheng 
43095d4f98a2SYan Zheng 		key.offset--;
43105d4f98a2SYan Zheng 	}
4311b3b4aa74SDavid Sterba 	btrfs_release_path(path);
43125d4f98a2SYan Zheng 
43135d4f98a2SYan Zheng 	if (list_empty(&reloc_roots))
43145d4f98a2SYan Zheng 		goto out;
43155d4f98a2SYan Zheng 
4316c258d6e3SQu Wenruo 	rc = alloc_reloc_control(fs_info);
43175d4f98a2SYan Zheng 	if (!rc) {
43185d4f98a2SYan Zheng 		err = -ENOMEM;
43195d4f98a2SYan Zheng 		goto out;
43205d4f98a2SYan Zheng 	}
43215d4f98a2SYan Zheng 
43220b246afaSJeff Mahoney 	rc->extent_root = fs_info->extent_root;
43235d4f98a2SYan Zheng 
43245d4f98a2SYan Zheng 	set_reloc_control(rc);
43255d4f98a2SYan Zheng 
43267a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
43273612b495STsutomu Itoh 	if (IS_ERR(trans)) {
43283612b495STsutomu Itoh 		err = PTR_ERR(trans);
4329fb2d83eeSJosef Bacik 		goto out_unset;
43303612b495STsutomu Itoh 	}
43313fd0a558SYan, Zheng 
43323fd0a558SYan, Zheng 	rc->merge_reloc_tree = 1;
43333fd0a558SYan, Zheng 
43345d4f98a2SYan Zheng 	while (!list_empty(&reloc_roots)) {
43355d4f98a2SYan Zheng 		reloc_root = list_entry(reloc_roots.next,
43365d4f98a2SYan Zheng 					struct btrfs_root, root_list);
43375d4f98a2SYan Zheng 		list_del(&reloc_root->root_list);
43385d4f98a2SYan Zheng 
43395d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) == 0) {
43405d4f98a2SYan Zheng 			list_add_tail(&reloc_root->root_list,
43415d4f98a2SYan Zheng 				      &rc->reloc_roots);
43425d4f98a2SYan Zheng 			continue;
43435d4f98a2SYan Zheng 		}
43445d4f98a2SYan Zheng 
43450b246afaSJeff Mahoney 		fs_root = read_fs_root(fs_info, reloc_root->root_key.offset);
434679787eaaSJeff Mahoney 		if (IS_ERR(fs_root)) {
434779787eaaSJeff Mahoney 			err = PTR_ERR(fs_root);
4348ca1aa281SJosef Bacik 			list_add_tail(&reloc_root->root_list, &reloc_roots);
43491402d17dSXiyu Yang 			btrfs_end_transaction(trans);
4350fb2d83eeSJosef Bacik 			goto out_unset;
435179787eaaSJeff Mahoney 		}
43525d4f98a2SYan Zheng 
4353ffd7b339SJeff Mahoney 		err = __add_reloc_root(reloc_root);
435479787eaaSJeff Mahoney 		BUG_ON(err < 0); /* -ENOMEM or logic error */
4355f44deb74SJosef Bacik 		fs_root->reloc_root = btrfs_grab_root(reloc_root);
435600246528SJosef Bacik 		btrfs_put_root(fs_root);
43575d4f98a2SYan Zheng 	}
43585d4f98a2SYan Zheng 
43593a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
436079787eaaSJeff Mahoney 	if (err)
4361fb2d83eeSJosef Bacik 		goto out_unset;
43625d4f98a2SYan Zheng 
43635d4f98a2SYan Zheng 	merge_reloc_roots(rc);
43645d4f98a2SYan Zheng 
43655d4f98a2SYan Zheng 	unset_reloc_control(rc);
43665d4f98a2SYan Zheng 
43677a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
436862b99540SQu Wenruo 	if (IS_ERR(trans)) {
43693612b495STsutomu Itoh 		err = PTR_ERR(trans);
43706217b0faSJosef Bacik 		goto out_clean;
437162b99540SQu Wenruo 	}
43723a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
43736217b0faSJosef Bacik out_clean:
4374d2311e69SQu Wenruo 	ret = clean_dirty_subvols(rc);
4375d2311e69SQu Wenruo 	if (ret < 0 && !err)
4376d2311e69SQu Wenruo 		err = ret;
4377fb2d83eeSJosef Bacik out_unset:
4378fb2d83eeSJosef Bacik 	unset_reloc_control(rc);
43791a0afa0eSJosef Bacik 	free_reloc_control(rc);
43803612b495STsutomu Itoh out:
4381aca1bba6SLiu Bo 	if (!list_empty(&reloc_roots))
4382aca1bba6SLiu Bo 		free_reloc_roots(&reloc_roots);
4383aca1bba6SLiu Bo 
43845d4f98a2SYan Zheng 	btrfs_free_path(path);
43855d4f98a2SYan Zheng 
43865d4f98a2SYan Zheng 	if (err == 0) {
43875d4f98a2SYan Zheng 		/* cleanup orphan inode in data relocation tree */
43880b246afaSJeff Mahoney 		fs_root = read_fs_root(fs_info, BTRFS_DATA_RELOC_TREE_OBJECTID);
4389932fd26dSJosef Bacik 		if (IS_ERR(fs_root)) {
43905d4f98a2SYan Zheng 			err = PTR_ERR(fs_root);
4391932fd26dSJosef Bacik 		} else {
439266b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(fs_root);
439300246528SJosef Bacik 			btrfs_put_root(fs_root);
4394932fd26dSJosef Bacik 		}
4395932fd26dSJosef Bacik 	}
43965d4f98a2SYan Zheng 	return err;
43975d4f98a2SYan Zheng }
43985d4f98a2SYan Zheng 
43995d4f98a2SYan Zheng /*
44005d4f98a2SYan Zheng  * helper to add ordered checksum for data relocation.
44015d4f98a2SYan Zheng  *
44025d4f98a2SYan Zheng  * cloning checksum properly handles the nodatasum extents.
44035d4f98a2SYan Zheng  * it also saves CPU time to re-calculate the checksum.
44045d4f98a2SYan Zheng  */
44055d4f98a2SYan Zheng int btrfs_reloc_clone_csums(struct inode *inode, u64 file_pos, u64 len)
44065d4f98a2SYan Zheng {
44070b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
44085d4f98a2SYan Zheng 	struct btrfs_ordered_sum *sums;
44095d4f98a2SYan Zheng 	struct btrfs_ordered_extent *ordered;
44105d4f98a2SYan Zheng 	int ret;
44115d4f98a2SYan Zheng 	u64 disk_bytenr;
44124577b014SJosef Bacik 	u64 new_bytenr;
44135d4f98a2SYan Zheng 	LIST_HEAD(list);
44145d4f98a2SYan Zheng 
44155d4f98a2SYan Zheng 	ordered = btrfs_lookup_ordered_extent(inode, file_pos);
4416bffe633eSOmar Sandoval 	BUG_ON(ordered->file_offset != file_pos || ordered->num_bytes != len);
44175d4f98a2SYan Zheng 
44185d4f98a2SYan Zheng 	disk_bytenr = file_pos + BTRFS_I(inode)->index_cnt;
44190b246afaSJeff Mahoney 	ret = btrfs_lookup_csums_range(fs_info->csum_root, disk_bytenr,
4420a2de733cSArne Jansen 				       disk_bytenr + len - 1, &list, 0);
442179787eaaSJeff Mahoney 	if (ret)
442279787eaaSJeff Mahoney 		goto out;
44235d4f98a2SYan Zheng 
44245d4f98a2SYan Zheng 	while (!list_empty(&list)) {
44255d4f98a2SYan Zheng 		sums = list_entry(list.next, struct btrfs_ordered_sum, list);
44265d4f98a2SYan Zheng 		list_del_init(&sums->list);
44275d4f98a2SYan Zheng 
44284577b014SJosef Bacik 		/*
44294577b014SJosef Bacik 		 * We need to offset the new_bytenr based on where the csum is.
44304577b014SJosef Bacik 		 * We need to do this because we will read in entire prealloc
44314577b014SJosef Bacik 		 * extents but we may have written to say the middle of the
44324577b014SJosef Bacik 		 * prealloc extent, so we need to make sure the csum goes with
44334577b014SJosef Bacik 		 * the right disk offset.
44344577b014SJosef Bacik 		 *
44354577b014SJosef Bacik 		 * We can do this because the data reloc inode refers strictly
44364577b014SJosef Bacik 		 * to the on disk bytes, so we don't have to worry about
44374577b014SJosef Bacik 		 * disk_len vs real len like with real inodes since it's all
44384577b014SJosef Bacik 		 * disk length.
44394577b014SJosef Bacik 		 */
4440bffe633eSOmar Sandoval 		new_bytenr = ordered->disk_bytenr + sums->bytenr - disk_bytenr;
44414577b014SJosef Bacik 		sums->bytenr = new_bytenr;
44425d4f98a2SYan Zheng 
4443f9756261SNikolay Borisov 		btrfs_add_ordered_sum(ordered, sums);
44445d4f98a2SYan Zheng 	}
444579787eaaSJeff Mahoney out:
44465d4f98a2SYan Zheng 	btrfs_put_ordered_extent(ordered);
4447411fc6bcSAndi Kleen 	return ret;
44485d4f98a2SYan Zheng }
44493fd0a558SYan, Zheng 
445083d4cfd4SJosef Bacik int btrfs_reloc_cow_block(struct btrfs_trans_handle *trans,
44513fd0a558SYan, Zheng 			  struct btrfs_root *root, struct extent_buffer *buf,
44523fd0a558SYan, Zheng 			  struct extent_buffer *cow)
44533fd0a558SYan, Zheng {
44540b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
44553fd0a558SYan, Zheng 	struct reloc_control *rc;
4456a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
44573fd0a558SYan, Zheng 	int first_cow = 0;
44583fd0a558SYan, Zheng 	int level;
445983d4cfd4SJosef Bacik 	int ret = 0;
44603fd0a558SYan, Zheng 
44610b246afaSJeff Mahoney 	rc = fs_info->reloc_ctl;
44623fd0a558SYan, Zheng 	if (!rc)
446383d4cfd4SJosef Bacik 		return 0;
44643fd0a558SYan, Zheng 
44653fd0a558SYan, Zheng 	BUG_ON(rc->stage == UPDATE_DATA_PTRS &&
44663fd0a558SYan, Zheng 	       root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID);
44673fd0a558SYan, Zheng 
44683fd0a558SYan, Zheng 	level = btrfs_header_level(buf);
44693fd0a558SYan, Zheng 	if (btrfs_header_generation(buf) <=
44703fd0a558SYan, Zheng 	    btrfs_root_last_snapshot(&root->root_item))
44713fd0a558SYan, Zheng 		first_cow = 1;
44723fd0a558SYan, Zheng 
44733fd0a558SYan, Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID &&
44743fd0a558SYan, Zheng 	    rc->create_reloc_tree) {
44753fd0a558SYan, Zheng 		WARN_ON(!first_cow && level == 0);
44763fd0a558SYan, Zheng 
44773fd0a558SYan, Zheng 		node = rc->backref_cache.path[level];
44783fd0a558SYan, Zheng 		BUG_ON(node->bytenr != buf->start &&
44793fd0a558SYan, Zheng 		       node->new_bytenr != buf->start);
44803fd0a558SYan, Zheng 
4481b0fe7078SQu Wenruo 		btrfs_backref_drop_node_buffer(node);
448267439dadSDavid Sterba 		atomic_inc(&cow->refs);
44833fd0a558SYan, Zheng 		node->eb = cow;
44843fd0a558SYan, Zheng 		node->new_bytenr = cow->start;
44853fd0a558SYan, Zheng 
44863fd0a558SYan, Zheng 		if (!node->pending) {
44873fd0a558SYan, Zheng 			list_move_tail(&node->list,
44883fd0a558SYan, Zheng 				       &rc->backref_cache.pending[level]);
44893fd0a558SYan, Zheng 			node->pending = 1;
44903fd0a558SYan, Zheng 		}
44913fd0a558SYan, Zheng 
44923fd0a558SYan, Zheng 		if (first_cow)
44939569cc20SQu Wenruo 			mark_block_processed(rc, node);
44943fd0a558SYan, Zheng 
44953fd0a558SYan, Zheng 		if (first_cow && level > 0)
44963fd0a558SYan, Zheng 			rc->nodes_relocated += buf->len;
44973fd0a558SYan, Zheng 	}
44983fd0a558SYan, Zheng 
449983d4cfd4SJosef Bacik 	if (level == 0 && first_cow && rc->stage == UPDATE_DATA_PTRS)
45003fd0a558SYan, Zheng 		ret = replace_file_extents(trans, rc, root, cow);
450183d4cfd4SJosef Bacik 	return ret;
45023fd0a558SYan, Zheng }
45033fd0a558SYan, Zheng 
45043fd0a558SYan, Zheng /*
45053fd0a558SYan, Zheng  * called before creating snapshot. it calculates metadata reservation
450601327610SNicholas D Steeves  * required for relocating tree blocks in the snapshot
45073fd0a558SYan, Zheng  */
4508147d256eSZhaolei void btrfs_reloc_pre_snapshot(struct btrfs_pending_snapshot *pending,
45093fd0a558SYan, Zheng 			      u64 *bytes_to_reserve)
45103fd0a558SYan, Zheng {
451110995c04SQu Wenruo 	struct btrfs_root *root = pending->root;
451210995c04SQu Wenruo 	struct reloc_control *rc = root->fs_info->reloc_ctl;
45133fd0a558SYan, Zheng 
45146282675eSQu Wenruo 	if (!rc || !have_reloc_root(root))
45153fd0a558SYan, Zheng 		return;
45163fd0a558SYan, Zheng 
45173fd0a558SYan, Zheng 	if (!rc->merge_reloc_tree)
45183fd0a558SYan, Zheng 		return;
45193fd0a558SYan, Zheng 
45203fd0a558SYan, Zheng 	root = root->reloc_root;
45213fd0a558SYan, Zheng 	BUG_ON(btrfs_root_refs(&root->root_item) == 0);
45223fd0a558SYan, Zheng 	/*
45233fd0a558SYan, Zheng 	 * relocation is in the stage of merging trees. the space
45243fd0a558SYan, Zheng 	 * used by merging a reloc tree is twice the size of
45253fd0a558SYan, Zheng 	 * relocated tree nodes in the worst case. half for cowing
45263fd0a558SYan, Zheng 	 * the reloc tree, half for cowing the fs tree. the space
45273fd0a558SYan, Zheng 	 * used by cowing the reloc tree will be freed after the
45283fd0a558SYan, Zheng 	 * tree is dropped. if we create snapshot, cowing the fs
45293fd0a558SYan, Zheng 	 * tree may use more space than it frees. so we need
45303fd0a558SYan, Zheng 	 * reserve extra space.
45313fd0a558SYan, Zheng 	 */
45323fd0a558SYan, Zheng 	*bytes_to_reserve += rc->nodes_relocated;
45333fd0a558SYan, Zheng }
45343fd0a558SYan, Zheng 
45353fd0a558SYan, Zheng /*
45363fd0a558SYan, Zheng  * called after snapshot is created. migrate block reservation
45373fd0a558SYan, Zheng  * and create reloc root for the newly created snapshot
4538f44deb74SJosef Bacik  *
4539f44deb74SJosef Bacik  * This is similar to btrfs_init_reloc_root(), we come out of here with two
4540f44deb74SJosef Bacik  * references held on the reloc_root, one for root->reloc_root and one for
4541f44deb74SJosef Bacik  * rc->reloc_roots.
45423fd0a558SYan, Zheng  */
454349b25e05SJeff Mahoney int btrfs_reloc_post_snapshot(struct btrfs_trans_handle *trans,
45443fd0a558SYan, Zheng 			       struct btrfs_pending_snapshot *pending)
45453fd0a558SYan, Zheng {
45463fd0a558SYan, Zheng 	struct btrfs_root *root = pending->root;
45473fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
45483fd0a558SYan, Zheng 	struct btrfs_root *new_root;
454910995c04SQu Wenruo 	struct reloc_control *rc = root->fs_info->reloc_ctl;
45503fd0a558SYan, Zheng 	int ret;
45513fd0a558SYan, Zheng 
45526282675eSQu Wenruo 	if (!rc || !have_reloc_root(root))
455349b25e05SJeff Mahoney 		return 0;
45543fd0a558SYan, Zheng 
45553fd0a558SYan, Zheng 	rc = root->fs_info->reloc_ctl;
45563fd0a558SYan, Zheng 	rc->merging_rsv_size += rc->nodes_relocated;
45573fd0a558SYan, Zheng 
45583fd0a558SYan, Zheng 	if (rc->merge_reloc_tree) {
45593fd0a558SYan, Zheng 		ret = btrfs_block_rsv_migrate(&pending->block_rsv,
45603fd0a558SYan, Zheng 					      rc->block_rsv,
45613a584174SLu Fengqi 					      rc->nodes_relocated, true);
456249b25e05SJeff Mahoney 		if (ret)
456349b25e05SJeff Mahoney 			return ret;
45643fd0a558SYan, Zheng 	}
45653fd0a558SYan, Zheng 
45663fd0a558SYan, Zheng 	new_root = pending->snap;
45673fd0a558SYan, Zheng 	reloc_root = create_reloc_root(trans, root->reloc_root,
45683fd0a558SYan, Zheng 				       new_root->root_key.objectid);
456949b25e05SJeff Mahoney 	if (IS_ERR(reloc_root))
457049b25e05SJeff Mahoney 		return PTR_ERR(reloc_root);
45713fd0a558SYan, Zheng 
4572ffd7b339SJeff Mahoney 	ret = __add_reloc_root(reloc_root);
4573ffd7b339SJeff Mahoney 	BUG_ON(ret < 0);
4574f44deb74SJosef Bacik 	new_root->reloc_root = btrfs_grab_root(reloc_root);
45753fd0a558SYan, Zheng 
457649b25e05SJeff Mahoney 	if (rc->create_reloc_tree)
45773fd0a558SYan, Zheng 		ret = clone_backref_node(trans, rc, root, reloc_root);
457849b25e05SJeff Mahoney 	return ret;
45793fd0a558SYan, Zheng }
4580