xref: /openbmc/linux/fs/btrfs/relocation.c (revision 13fe1bdb)
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 
17848a3b636SEric Sandeen static void backref_tree_panic(struct rb_node *rb_node, int errno, u64 bytenr)
17943c04fb1SJeff Mahoney {
18043c04fb1SJeff Mahoney 
18143c04fb1SJeff Mahoney 	struct btrfs_fs_info *fs_info = NULL;
182a26195a5SQu Wenruo 	struct btrfs_backref_node *bnode = rb_entry(rb_node,
183a26195a5SQu Wenruo 			struct btrfs_backref_node, rb_node);
18443c04fb1SJeff Mahoney 	if (bnode->root)
18543c04fb1SJeff Mahoney 		fs_info = bnode->root->fs_info;
1865d163e0eSJeff Mahoney 	btrfs_panic(fs_info, errno,
1875d163e0eSJeff Mahoney 		    "Inconsistency in backref cache found at offset %llu",
1885d163e0eSJeff Mahoney 		    bytenr);
18943c04fb1SJeff Mahoney }
19043c04fb1SJeff Mahoney 
1915d4f98a2SYan Zheng /*
1925d4f98a2SYan Zheng  * walk up backref nodes until reach node presents tree root
1935d4f98a2SYan Zheng  */
194a26195a5SQu Wenruo static struct btrfs_backref_node *walk_up_backref(
195a26195a5SQu Wenruo 		struct btrfs_backref_node *node,
196a26195a5SQu Wenruo 		struct btrfs_backref_edge *edges[], int *index)
1975d4f98a2SYan Zheng {
198a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
1995d4f98a2SYan Zheng 	int idx = *index;
2005d4f98a2SYan Zheng 
2015d4f98a2SYan Zheng 	while (!list_empty(&node->upper)) {
2025d4f98a2SYan Zheng 		edge = list_entry(node->upper.next,
203a26195a5SQu Wenruo 				  struct btrfs_backref_edge, list[LOWER]);
2045d4f98a2SYan Zheng 		edges[idx++] = edge;
2055d4f98a2SYan Zheng 		node = edge->node[UPPER];
2065d4f98a2SYan Zheng 	}
2073fd0a558SYan, Zheng 	BUG_ON(node->detached);
2085d4f98a2SYan Zheng 	*index = idx;
2095d4f98a2SYan Zheng 	return node;
2105d4f98a2SYan Zheng }
2115d4f98a2SYan Zheng 
2125d4f98a2SYan Zheng /*
2135d4f98a2SYan Zheng  * walk down backref nodes to find start of next reference path
2145d4f98a2SYan Zheng  */
215a26195a5SQu Wenruo static struct btrfs_backref_node *walk_down_backref(
216a26195a5SQu Wenruo 		struct btrfs_backref_edge *edges[], int *index)
2175d4f98a2SYan Zheng {
218a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
219a26195a5SQu Wenruo 	struct btrfs_backref_node *lower;
2205d4f98a2SYan Zheng 	int idx = *index;
2215d4f98a2SYan Zheng 
2225d4f98a2SYan Zheng 	while (idx > 0) {
2235d4f98a2SYan Zheng 		edge = edges[idx - 1];
2245d4f98a2SYan Zheng 		lower = edge->node[LOWER];
2255d4f98a2SYan Zheng 		if (list_is_last(&edge->list[LOWER], &lower->upper)) {
2265d4f98a2SYan Zheng 			idx--;
2275d4f98a2SYan Zheng 			continue;
2285d4f98a2SYan Zheng 		}
2295d4f98a2SYan Zheng 		edge = list_entry(edge->list[LOWER].next,
230a26195a5SQu Wenruo 				  struct btrfs_backref_edge, list[LOWER]);
2315d4f98a2SYan Zheng 		edges[idx - 1] = edge;
2325d4f98a2SYan Zheng 		*index = idx;
2335d4f98a2SYan Zheng 		return edge->node[UPPER];
2345d4f98a2SYan Zheng 	}
2355d4f98a2SYan Zheng 	*index = 0;
2365d4f98a2SYan Zheng 	return NULL;
2375d4f98a2SYan Zheng }
2385d4f98a2SYan Zheng 
239a26195a5SQu Wenruo static void update_backref_node(struct btrfs_backref_cache *cache,
240a26195a5SQu Wenruo 				struct btrfs_backref_node *node, u64 bytenr)
2413fd0a558SYan, Zheng {
2423fd0a558SYan, Zheng 	struct rb_node *rb_node;
2433fd0a558SYan, Zheng 	rb_erase(&node->rb_node, &cache->rb_root);
2443fd0a558SYan, Zheng 	node->bytenr = bytenr;
245e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&cache->rb_root, node->bytenr, &node->rb_node);
24643c04fb1SJeff Mahoney 	if (rb_node)
24743c04fb1SJeff Mahoney 		backref_tree_panic(rb_node, -EEXIST, bytenr);
2483fd0a558SYan, Zheng }
2493fd0a558SYan, Zheng 
2503fd0a558SYan, Zheng /*
2513fd0a558SYan, Zheng  * update backref cache after a transaction commit
2523fd0a558SYan, Zheng  */
2533fd0a558SYan, Zheng static int update_backref_cache(struct btrfs_trans_handle *trans,
254a26195a5SQu Wenruo 				struct btrfs_backref_cache *cache)
2553fd0a558SYan, Zheng {
256a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
2573fd0a558SYan, Zheng 	int level = 0;
2583fd0a558SYan, Zheng 
2593fd0a558SYan, Zheng 	if (cache->last_trans == 0) {
2603fd0a558SYan, Zheng 		cache->last_trans = trans->transid;
2613fd0a558SYan, Zheng 		return 0;
2623fd0a558SYan, Zheng 	}
2633fd0a558SYan, Zheng 
2643fd0a558SYan, Zheng 	if (cache->last_trans == trans->transid)
2653fd0a558SYan, Zheng 		return 0;
2663fd0a558SYan, Zheng 
2673fd0a558SYan, Zheng 	/*
2683fd0a558SYan, Zheng 	 * detached nodes are used to avoid unnecessary backref
2693fd0a558SYan, Zheng 	 * lookup. transaction commit changes the extent tree.
2703fd0a558SYan, Zheng 	 * so the detached nodes are no longer useful.
2713fd0a558SYan, Zheng 	 */
2723fd0a558SYan, Zheng 	while (!list_empty(&cache->detached)) {
2733fd0a558SYan, Zheng 		node = list_entry(cache->detached.next,
274a26195a5SQu Wenruo 				  struct btrfs_backref_node, list);
275023acb07SQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
2763fd0a558SYan, Zheng 	}
2773fd0a558SYan, Zheng 
2783fd0a558SYan, Zheng 	while (!list_empty(&cache->changed)) {
2793fd0a558SYan, Zheng 		node = list_entry(cache->changed.next,
280a26195a5SQu Wenruo 				  struct btrfs_backref_node, list);
2813fd0a558SYan, Zheng 		list_del_init(&node->list);
2823fd0a558SYan, Zheng 		BUG_ON(node->pending);
2833fd0a558SYan, Zheng 		update_backref_node(cache, node, node->new_bytenr);
2843fd0a558SYan, Zheng 	}
2853fd0a558SYan, Zheng 
2863fd0a558SYan, Zheng 	/*
2873fd0a558SYan, Zheng 	 * some nodes can be left in the pending list if there were
2883fd0a558SYan, Zheng 	 * errors during processing the pending nodes.
2893fd0a558SYan, Zheng 	 */
2903fd0a558SYan, Zheng 	for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2913fd0a558SYan, Zheng 		list_for_each_entry(node, &cache->pending[level], list) {
2923fd0a558SYan, Zheng 			BUG_ON(!node->pending);
2933fd0a558SYan, Zheng 			if (node->bytenr == node->new_bytenr)
2943fd0a558SYan, Zheng 				continue;
2953fd0a558SYan, Zheng 			update_backref_node(cache, node, node->new_bytenr);
2963fd0a558SYan, Zheng 		}
2973fd0a558SYan, Zheng 	}
2983fd0a558SYan, Zheng 
2993fd0a558SYan, Zheng 	cache->last_trans = 0;
3003fd0a558SYan, Zheng 	return 1;
3013fd0a558SYan, Zheng }
3023fd0a558SYan, Zheng 
3036282675eSQu Wenruo static bool reloc_root_is_dead(struct btrfs_root *root)
3046282675eSQu Wenruo {
3056282675eSQu Wenruo 	/*
3066282675eSQu Wenruo 	 * Pair with set_bit/clear_bit in clean_dirty_subvols and
3076282675eSQu Wenruo 	 * btrfs_update_reloc_root. We need to see the updated bit before
3086282675eSQu Wenruo 	 * trying to access reloc_root
3096282675eSQu Wenruo 	 */
3106282675eSQu Wenruo 	smp_rmb();
3116282675eSQu Wenruo 	if (test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state))
3126282675eSQu Wenruo 		return true;
3136282675eSQu Wenruo 	return false;
3146282675eSQu Wenruo }
3156282675eSQu Wenruo 
3166282675eSQu Wenruo /*
3176282675eSQu Wenruo  * Check if this subvolume tree has valid reloc tree.
3186282675eSQu Wenruo  *
3196282675eSQu Wenruo  * Reloc tree after swap is considered dead, thus not considered as valid.
3206282675eSQu Wenruo  * This is enough for most callers, as they don't distinguish dead reloc root
3216282675eSQu Wenruo  * from no reloc root.  But should_ignore_root() below is a special case.
3226282675eSQu Wenruo  */
3236282675eSQu Wenruo static bool have_reloc_root(struct btrfs_root *root)
3246282675eSQu Wenruo {
3256282675eSQu Wenruo 	if (reloc_root_is_dead(root))
3266282675eSQu Wenruo 		return false;
3276282675eSQu Wenruo 	if (!root->reloc_root)
3286282675eSQu Wenruo 		return false;
3296282675eSQu Wenruo 	return true;
3306282675eSQu Wenruo }
331f2a97a9dSDavid Sterba 
3323fd0a558SYan, Zheng static int should_ignore_root(struct btrfs_root *root)
3333fd0a558SYan, Zheng {
3343fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
3353fd0a558SYan, Zheng 
33627cdeb70SMiao Xie 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
3373fd0a558SYan, Zheng 		return 0;
3383fd0a558SYan, Zheng 
3396282675eSQu Wenruo 	/* This root has been merged with its reloc tree, we can ignore it */
3406282675eSQu Wenruo 	if (reloc_root_is_dead(root))
3416282675eSQu Wenruo 		return 1;
3426282675eSQu Wenruo 
3433fd0a558SYan, Zheng 	reloc_root = root->reloc_root;
3443fd0a558SYan, Zheng 	if (!reloc_root)
3453fd0a558SYan, Zheng 		return 0;
3463fd0a558SYan, Zheng 
3474d4225fcSJosef Bacik 	if (btrfs_header_generation(reloc_root->commit_root) ==
3484d4225fcSJosef Bacik 	    root->fs_info->running_transaction->transid)
3493fd0a558SYan, Zheng 		return 0;
3503fd0a558SYan, Zheng 	/*
3513fd0a558SYan, Zheng 	 * if there is reloc tree and it was created in previous
3523fd0a558SYan, Zheng 	 * transaction backref lookup can find the reloc tree,
3533fd0a558SYan, Zheng 	 * so backref node for the fs tree root is useless for
3543fd0a558SYan, Zheng 	 * relocation.
3553fd0a558SYan, Zheng 	 */
3563fd0a558SYan, Zheng 	return 1;
3573fd0a558SYan, Zheng }
3585d4f98a2SYan Zheng /*
3595d4f98a2SYan Zheng  * find reloc tree by address of tree root
3605d4f98a2SYan Zheng  */
3612433bea5SQu Wenruo struct btrfs_root *find_reloc_root(struct btrfs_fs_info *fs_info, u64 bytenr)
3625d4f98a2SYan Zheng {
3632433bea5SQu Wenruo 	struct reloc_control *rc = fs_info->reloc_ctl;
3645d4f98a2SYan Zheng 	struct rb_node *rb_node;
3655d4f98a2SYan Zheng 	struct mapping_node *node;
3665d4f98a2SYan Zheng 	struct btrfs_root *root = NULL;
3675d4f98a2SYan Zheng 
3682433bea5SQu Wenruo 	ASSERT(rc);
3695d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
370e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root, bytenr);
3715d4f98a2SYan Zheng 	if (rb_node) {
3725d4f98a2SYan Zheng 		node = rb_entry(rb_node, struct mapping_node, rb_node);
3735d4f98a2SYan Zheng 		root = (struct btrfs_root *)node->data;
3745d4f98a2SYan Zheng 	}
3755d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
37600246528SJosef Bacik 	return btrfs_grab_root(root);
3775d4f98a2SYan Zheng }
3785d4f98a2SYan Zheng 
3795d4f98a2SYan Zheng static struct btrfs_root *read_fs_root(struct btrfs_fs_info *fs_info,
3805d4f98a2SYan Zheng 					u64 root_objectid)
3815d4f98a2SYan Zheng {
3825d4f98a2SYan Zheng 	struct btrfs_key key;
3835d4f98a2SYan Zheng 
3845d4f98a2SYan Zheng 	key.objectid = root_objectid;
3855d4f98a2SYan Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
3865d4f98a2SYan Zheng 	key.offset = (u64)-1;
3875d4f98a2SYan Zheng 
388bc44d7c4SJosef Bacik 	return btrfs_get_fs_root(fs_info, &key, false);
3895d4f98a2SYan Zheng }
3905d4f98a2SYan Zheng 
3915d4f98a2SYan Zheng /*
3924007ea87SQu Wenruo  * Handle direct tree backref
3934007ea87SQu Wenruo  *
3944007ea87SQu Wenruo  * Direct tree backref means, the backref item shows its parent bytenr
3954007ea87SQu Wenruo  * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
3964007ea87SQu Wenruo  *
3974007ea87SQu Wenruo  * @ref_key:	The converted backref key.
3984007ea87SQu Wenruo  *		For keyed backref, it's the item key.
3994007ea87SQu Wenruo  *		For inlined backref, objectid is the bytenr,
4004007ea87SQu Wenruo  *		type is btrfs_inline_ref_type, offset is
4014007ea87SQu Wenruo  *		btrfs_inline_ref_offset.
4024007ea87SQu Wenruo  */
403a26195a5SQu Wenruo static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
4044007ea87SQu Wenruo 				      struct btrfs_key *ref_key,
405a26195a5SQu Wenruo 				      struct btrfs_backref_node *cur)
4064007ea87SQu Wenruo {
407a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
408a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
4094007ea87SQu Wenruo 	struct rb_node *rb_node;
4104007ea87SQu Wenruo 
4114007ea87SQu Wenruo 	ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
4124007ea87SQu Wenruo 
4134007ea87SQu Wenruo 	/* Only reloc root uses backref pointing to itself */
4144007ea87SQu Wenruo 	if (ref_key->objectid == ref_key->offset) {
4154007ea87SQu Wenruo 		struct btrfs_root *root;
4164007ea87SQu Wenruo 
4174007ea87SQu Wenruo 		cur->is_reloc_root = 1;
4184007ea87SQu Wenruo 		/* Only reloc backref cache cares about a specific root */
4194007ea87SQu Wenruo 		if (cache->is_reloc) {
4204007ea87SQu Wenruo 			root = find_reloc_root(cache->fs_info, cur->bytenr);
4214007ea87SQu Wenruo 			if (WARN_ON(!root))
4224007ea87SQu Wenruo 				return -ENOENT;
4234007ea87SQu Wenruo 			cur->root = root;
4244007ea87SQu Wenruo 		} else {
4254007ea87SQu Wenruo 			/*
4264007ea87SQu Wenruo 			 * For generic purpose backref cache, reloc root node
4274007ea87SQu Wenruo 			 * is useless.
4284007ea87SQu Wenruo 			 */
4294007ea87SQu Wenruo 			list_add(&cur->list, &cache->useless_node);
4304007ea87SQu Wenruo 		}
4314007ea87SQu Wenruo 		return 0;
4324007ea87SQu Wenruo 	}
4334007ea87SQu Wenruo 
43447254d07SQu Wenruo 	edge = btrfs_backref_alloc_edge(cache);
4354007ea87SQu Wenruo 	if (!edge)
4364007ea87SQu Wenruo 		return -ENOMEM;
4374007ea87SQu Wenruo 
438e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
4394007ea87SQu Wenruo 	if (!rb_node) {
4404007ea87SQu Wenruo 		/* Parent node not yet cached */
441b1818dabSQu Wenruo 		upper = btrfs_backref_alloc_node(cache, ref_key->offset,
4420304f2d8SQu Wenruo 					   cur->level + 1);
4434007ea87SQu Wenruo 		if (!upper) {
444741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
4454007ea87SQu Wenruo 			return -ENOMEM;
4464007ea87SQu Wenruo 		}
4474007ea87SQu Wenruo 
4484007ea87SQu Wenruo 		/*
4494007ea87SQu Wenruo 		 *  Backrefs for the upper level block isn't cached, add the
4504007ea87SQu Wenruo 		 *  block to pending list
4514007ea87SQu Wenruo 		 */
4524007ea87SQu Wenruo 		list_add_tail(&edge->list[UPPER], &cache->pending_edge);
4534007ea87SQu Wenruo 	} else {
4544007ea87SQu Wenruo 		/* Parent node already cached */
455a26195a5SQu Wenruo 		upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
4564007ea87SQu Wenruo 		ASSERT(upper->checked);
4574007ea87SQu Wenruo 		INIT_LIST_HEAD(&edge->list[UPPER]);
4584007ea87SQu Wenruo 	}
459f39911e5SQu Wenruo 	btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
4604007ea87SQu Wenruo 	return 0;
4614007ea87SQu Wenruo }
4624007ea87SQu Wenruo 
4634007ea87SQu Wenruo /*
4644d81ea8bSQu Wenruo  * Handle indirect tree backref
4654d81ea8bSQu Wenruo  *
4664d81ea8bSQu Wenruo  * Indirect tree backref means, we only know which tree the node belongs to.
4674d81ea8bSQu Wenruo  * We still need to do a tree search to find out the parents. This is for
4684d81ea8bSQu Wenruo  * TREE_BLOCK_REF backref (keyed or inlined).
4694d81ea8bSQu Wenruo  *
4704d81ea8bSQu Wenruo  * @ref_key:	The same as @ref_key in  handle_direct_tree_backref()
4714d81ea8bSQu Wenruo  * @tree_key:	The first key of this tree block.
4724d81ea8bSQu Wenruo  * @path:	A clean (released) path, to avoid allocating path everytime
4734d81ea8bSQu Wenruo  *		the function get called.
4744d81ea8bSQu Wenruo  */
475a26195a5SQu Wenruo static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
4764d81ea8bSQu Wenruo 					struct btrfs_path *path,
4774d81ea8bSQu Wenruo 					struct btrfs_key *ref_key,
4784d81ea8bSQu Wenruo 					struct btrfs_key *tree_key,
479a26195a5SQu Wenruo 					struct btrfs_backref_node *cur)
4804d81ea8bSQu Wenruo {
4814d81ea8bSQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
482a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
483a26195a5SQu Wenruo 	struct btrfs_backref_node *lower;
484a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
4854d81ea8bSQu Wenruo 	struct extent_buffer *eb;
4864d81ea8bSQu Wenruo 	struct btrfs_root *root;
4874d81ea8bSQu Wenruo 	struct rb_node *rb_node;
4884d81ea8bSQu Wenruo 	int level;
4894d81ea8bSQu Wenruo 	bool need_check = true;
4904d81ea8bSQu Wenruo 	int ret;
4914d81ea8bSQu Wenruo 
4924d81ea8bSQu Wenruo 	root = read_fs_root(fs_info, ref_key->offset);
4934d81ea8bSQu Wenruo 	if (IS_ERR(root))
4944d81ea8bSQu Wenruo 		return PTR_ERR(root);
4954d81ea8bSQu Wenruo 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4964d81ea8bSQu Wenruo 		cur->cowonly = 1;
4974d81ea8bSQu Wenruo 
4984d81ea8bSQu Wenruo 	if (btrfs_root_level(&root->root_item) == cur->level) {
4994d81ea8bSQu Wenruo 		/* Tree root */
5004d81ea8bSQu Wenruo 		ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
5014d81ea8bSQu Wenruo 		if (should_ignore_root(root)) {
5024d81ea8bSQu Wenruo 			btrfs_put_root(root);
5034d81ea8bSQu Wenruo 			list_add(&cur->list, &cache->useless_node);
5044d81ea8bSQu Wenruo 		} else {
5054d81ea8bSQu Wenruo 			cur->root = root;
5064d81ea8bSQu Wenruo 		}
5074d81ea8bSQu Wenruo 		return 0;
5084d81ea8bSQu Wenruo 	}
5094d81ea8bSQu Wenruo 
5104d81ea8bSQu Wenruo 	level = cur->level + 1;
5114d81ea8bSQu Wenruo 
5124d81ea8bSQu Wenruo 	/* Search the tree to find parent blocks referring to the block */
5134d81ea8bSQu Wenruo 	path->search_commit_root = 1;
5144d81ea8bSQu Wenruo 	path->skip_locking = 1;
5154d81ea8bSQu Wenruo 	path->lowest_level = level;
5164d81ea8bSQu Wenruo 	ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
5174d81ea8bSQu Wenruo 	path->lowest_level = 0;
5184d81ea8bSQu Wenruo 	if (ret < 0) {
5194d81ea8bSQu Wenruo 		btrfs_put_root(root);
5204d81ea8bSQu Wenruo 		return ret;
5214d81ea8bSQu Wenruo 	}
5224d81ea8bSQu Wenruo 	if (ret > 0 && path->slots[level] > 0)
5234d81ea8bSQu Wenruo 		path->slots[level]--;
5244d81ea8bSQu Wenruo 
5254d81ea8bSQu Wenruo 	eb = path->nodes[level];
5264d81ea8bSQu Wenruo 	if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
5274d81ea8bSQu Wenruo 		btrfs_err(fs_info,
5284d81ea8bSQu Wenruo "couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
5294d81ea8bSQu Wenruo 			  cur->bytenr, level - 1, root->root_key.objectid,
5304d81ea8bSQu Wenruo 			  tree_key->objectid, tree_key->type, tree_key->offset);
5314d81ea8bSQu Wenruo 		btrfs_put_root(root);
5324d81ea8bSQu Wenruo 		ret = -ENOENT;
5334d81ea8bSQu Wenruo 		goto out;
5344d81ea8bSQu Wenruo 	}
5354d81ea8bSQu Wenruo 	lower = cur;
5364d81ea8bSQu Wenruo 
5374d81ea8bSQu Wenruo 	/* Add all nodes and edges in the path */
5384d81ea8bSQu Wenruo 	for (; level < BTRFS_MAX_LEVEL; level++) {
5394d81ea8bSQu Wenruo 		if (!path->nodes[level]) {
5404d81ea8bSQu Wenruo 			ASSERT(btrfs_root_bytenr(&root->root_item) ==
5414d81ea8bSQu Wenruo 			       lower->bytenr);
5424d81ea8bSQu Wenruo 			if (should_ignore_root(root)) {
5434d81ea8bSQu Wenruo 				btrfs_put_root(root);
5444d81ea8bSQu Wenruo 				list_add(&lower->list, &cache->useless_node);
5454d81ea8bSQu Wenruo 			} else {
5464d81ea8bSQu Wenruo 				lower->root = root;
5474d81ea8bSQu Wenruo 			}
5484d81ea8bSQu Wenruo 			break;
5494d81ea8bSQu Wenruo 		}
5504d81ea8bSQu Wenruo 
55147254d07SQu Wenruo 		edge = btrfs_backref_alloc_edge(cache);
5524d81ea8bSQu Wenruo 		if (!edge) {
5534d81ea8bSQu Wenruo 			btrfs_put_root(root);
5544d81ea8bSQu Wenruo 			ret = -ENOMEM;
5554d81ea8bSQu Wenruo 			goto out;
5564d81ea8bSQu Wenruo 		}
5574d81ea8bSQu Wenruo 
5584d81ea8bSQu Wenruo 		eb = path->nodes[level];
559e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root, eb->start);
5604d81ea8bSQu Wenruo 		if (!rb_node) {
561b1818dabSQu Wenruo 			upper = btrfs_backref_alloc_node(cache, eb->start,
5620304f2d8SQu Wenruo 							 lower->level + 1);
5634d81ea8bSQu Wenruo 			if (!upper) {
5644d81ea8bSQu Wenruo 				btrfs_put_root(root);
565741188d3SQu Wenruo 				btrfs_backref_free_edge(cache, edge);
5664d81ea8bSQu Wenruo 				ret = -ENOMEM;
5674d81ea8bSQu Wenruo 				goto out;
5684d81ea8bSQu Wenruo 			}
5694d81ea8bSQu Wenruo 			upper->owner = btrfs_header_owner(eb);
5704d81ea8bSQu Wenruo 			if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
5714d81ea8bSQu Wenruo 				upper->cowonly = 1;
5724d81ea8bSQu Wenruo 
5734d81ea8bSQu Wenruo 			/*
5744d81ea8bSQu Wenruo 			 * If we know the block isn't shared we can avoid
5754d81ea8bSQu Wenruo 			 * checking its backrefs.
5764d81ea8bSQu Wenruo 			 */
5774d81ea8bSQu Wenruo 			if (btrfs_block_can_be_shared(root, eb))
5784d81ea8bSQu Wenruo 				upper->checked = 0;
5794d81ea8bSQu Wenruo 			else
5804d81ea8bSQu Wenruo 				upper->checked = 1;
5814d81ea8bSQu Wenruo 
5824d81ea8bSQu Wenruo 			/*
5834d81ea8bSQu Wenruo 			 * Add the block to pending list if we need to check its
5844d81ea8bSQu Wenruo 			 * backrefs, we only do this once while walking up a
5854d81ea8bSQu Wenruo 			 * tree as we will catch anything else later on.
5864d81ea8bSQu Wenruo 			 */
5874d81ea8bSQu Wenruo 			if (!upper->checked && need_check) {
5884d81ea8bSQu Wenruo 				need_check = false;
5894d81ea8bSQu Wenruo 				list_add_tail(&edge->list[UPPER],
5904d81ea8bSQu Wenruo 					      &cache->pending_edge);
5914d81ea8bSQu Wenruo 			} else {
5924d81ea8bSQu Wenruo 				if (upper->checked)
5934d81ea8bSQu Wenruo 					need_check = true;
5944d81ea8bSQu Wenruo 				INIT_LIST_HEAD(&edge->list[UPPER]);
5954d81ea8bSQu Wenruo 			}
5964d81ea8bSQu Wenruo 		} else {
597a26195a5SQu Wenruo 			upper = rb_entry(rb_node, struct btrfs_backref_node,
598a26195a5SQu Wenruo 					 rb_node);
5994d81ea8bSQu Wenruo 			ASSERT(upper->checked);
6004d81ea8bSQu Wenruo 			INIT_LIST_HEAD(&edge->list[UPPER]);
6014d81ea8bSQu Wenruo 			if (!upper->owner)
6024d81ea8bSQu Wenruo 				upper->owner = btrfs_header_owner(eb);
6034d81ea8bSQu Wenruo 		}
604f39911e5SQu Wenruo 		btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
6054d81ea8bSQu Wenruo 
6064d81ea8bSQu Wenruo 		if (rb_node) {
6074d81ea8bSQu Wenruo 			btrfs_put_root(root);
6084d81ea8bSQu Wenruo 			break;
6094d81ea8bSQu Wenruo 		}
6104d81ea8bSQu Wenruo 		lower = upper;
6114d81ea8bSQu Wenruo 		upper = NULL;
6124d81ea8bSQu Wenruo 	}
6134d81ea8bSQu Wenruo out:
6144d81ea8bSQu Wenruo 	btrfs_release_path(path);
6154d81ea8bSQu Wenruo 	return ret;
6164d81ea8bSQu Wenruo }
6174d81ea8bSQu Wenruo 
618a26195a5SQu Wenruo static int handle_one_tree_block(struct btrfs_backref_cache *cache,
619e7d571c7SQu Wenruo 				 struct btrfs_path *path,
620e7d571c7SQu Wenruo 				 struct btrfs_backref_iter *iter,
6215d4f98a2SYan Zheng 				 struct btrfs_key *node_key,
622a26195a5SQu Wenruo 				 struct btrfs_backref_node *cur)
6235d4f98a2SYan Zheng {
624e7d571c7SQu Wenruo 	struct btrfs_fs_info *fs_info = cache->fs_info;
625a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
626a26195a5SQu Wenruo 	struct btrfs_backref_node *exist;
6275d4f98a2SYan Zheng 	int ret;
6285d4f98a2SYan Zheng 
62971f572a9SQu Wenruo 	ret = btrfs_backref_iter_start(iter, cur->bytenr);
630e7d571c7SQu Wenruo 	if (ret < 0)
631e7d571c7SQu Wenruo 		return ret;
63271f572a9SQu Wenruo 	/*
63371f572a9SQu Wenruo 	 * We skip the first btrfs_tree_block_info, as we don't use the key
63471f572a9SQu Wenruo 	 * stored in it, but fetch it from the tree block
63571f572a9SQu Wenruo 	 */
63671f572a9SQu Wenruo 	if (btrfs_backref_has_tree_block_info(iter)) {
63771f572a9SQu Wenruo 		ret = btrfs_backref_iter_next(iter);
638e7d571c7SQu Wenruo 		if (ret < 0)
63971f572a9SQu Wenruo 			goto out;
64071f572a9SQu Wenruo 		/* No extra backref? This means the tree block is corrupted */
64171f572a9SQu Wenruo 		if (ret > 0) {
642e7d571c7SQu Wenruo 			ret = -EUCLEAN;
64371f572a9SQu Wenruo 			goto out;
64471f572a9SQu Wenruo 		}
64571f572a9SQu Wenruo 	}
6465d4f98a2SYan Zheng 	WARN_ON(cur->checked);
6475d4f98a2SYan Zheng 	if (!list_empty(&cur->upper)) {
6485d4f98a2SYan Zheng 		/*
64970f23fd6SJustin P. Mattock 		 * the backref was added previously when processing
6505d4f98a2SYan Zheng 		 * backref of type BTRFS_TREE_BLOCK_REF_KEY
6515d4f98a2SYan Zheng 		 */
65275bfb9afSJosef Bacik 		ASSERT(list_is_singular(&cur->upper));
653a26195a5SQu Wenruo 		edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
6545d4f98a2SYan Zheng 				  list[LOWER]);
65575bfb9afSJosef Bacik 		ASSERT(list_empty(&edge->list[UPPER]));
6565d4f98a2SYan Zheng 		exist = edge->node[UPPER];
6575d4f98a2SYan Zheng 		/*
6585d4f98a2SYan Zheng 		 * add the upper level block to pending list if we need
6595d4f98a2SYan Zheng 		 * check its backrefs
6605d4f98a2SYan Zheng 		 */
6615d4f98a2SYan Zheng 		if (!exist->checked)
66284780289SQu Wenruo 			list_add_tail(&edge->list[UPPER], &cache->pending_edge);
6635d4f98a2SYan Zheng 	} else {
6645d4f98a2SYan Zheng 		exist = NULL;
6655d4f98a2SYan Zheng 	}
6665d4f98a2SYan Zheng 
66771f572a9SQu Wenruo 	for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
66871f572a9SQu Wenruo 		struct extent_buffer *eb;
66971f572a9SQu Wenruo 		struct btrfs_key key;
6703de28d57SLiu Bo 		int type;
67171f572a9SQu Wenruo 
67271f572a9SQu Wenruo 		cond_resched();
67371f572a9SQu Wenruo 		eb = btrfs_backref_get_eb(iter);
67471f572a9SQu Wenruo 
67571f572a9SQu Wenruo 		key.objectid = iter->bytenr;
67671f572a9SQu Wenruo 		if (btrfs_backref_iter_is_inline_ref(iter)) {
67771f572a9SQu Wenruo 			struct btrfs_extent_inline_ref *iref;
67871f572a9SQu Wenruo 
67971f572a9SQu Wenruo 			/* update key for inline back ref */
68071f572a9SQu Wenruo 			iref = (struct btrfs_extent_inline_ref *)
68171f572a9SQu Wenruo 				((unsigned long)iter->cur_ptr);
6823de28d57SLiu Bo 			type = btrfs_get_extent_inline_ref_type(eb, iref,
6833de28d57SLiu Bo 							BTRFS_REF_TYPE_BLOCK);
6843de28d57SLiu Bo 			if (type == BTRFS_REF_TYPE_INVALID) {
685e7d571c7SQu Wenruo 				ret = -EUCLEAN;
6863de28d57SLiu Bo 				goto out;
6873de28d57SLiu Bo 			}
6883de28d57SLiu Bo 			key.type = type;
6895d4f98a2SYan Zheng 			key.offset = btrfs_extent_inline_ref_offset(eb, iref);
69071f572a9SQu Wenruo 		} else {
69171f572a9SQu Wenruo 			key.type = iter->cur_key.type;
69271f572a9SQu Wenruo 			key.offset = iter->cur_key.offset;
6935d4f98a2SYan Zheng 		}
6945d4f98a2SYan Zheng 
695fa6ac715SQu Wenruo 		/*
696fa6ac715SQu Wenruo 		 * Parent node found and matches current inline ref, no need to
697fa6ac715SQu Wenruo 		 * rebuild this node for this inline ref.
698fa6ac715SQu Wenruo 		 */
6995d4f98a2SYan Zheng 		if (exist &&
7005d4f98a2SYan Zheng 		    ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
7015d4f98a2SYan Zheng 		      exist->owner == key.offset) ||
7025d4f98a2SYan Zheng 		     (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
7035d4f98a2SYan Zheng 		      exist->bytenr == key.offset))) {
7045d4f98a2SYan Zheng 			exist = NULL;
70571f572a9SQu Wenruo 			continue;
7065d4f98a2SYan Zheng 		}
7075d4f98a2SYan Zheng 
708fa6ac715SQu Wenruo 		/* SHARED_BLOCK_REF means key.offset is the parent bytenr */
7095d4f98a2SYan Zheng 		if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
7104007ea87SQu Wenruo 			ret = handle_direct_tree_backref(cache, &key, cur);
711e7d571c7SQu Wenruo 			if (ret < 0)
7122433bea5SQu Wenruo 				goto out;
71371f572a9SQu Wenruo 			continue;
7146d8ff4e4SDavid Sterba 		} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
715e7d571c7SQu Wenruo 			ret = -EINVAL;
716e7d571c7SQu Wenruo 			btrfs_print_v0_err(fs_info);
717e7d571c7SQu Wenruo 			btrfs_handle_fs_error(fs_info, ret, NULL);
718ba3c2b19SNikolay Borisov 			goto out;
7195d4f98a2SYan Zheng 		} else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
72071f572a9SQu Wenruo 			continue;
7215d4f98a2SYan Zheng 		}
7225d4f98a2SYan Zheng 
723fa6ac715SQu Wenruo 		/*
724fa6ac715SQu Wenruo 		 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
725fa6ac715SQu Wenruo 		 * means the root objectid. We need to search the tree to get
726fa6ac715SQu Wenruo 		 * its parent bytenr.
727fa6ac715SQu Wenruo 		 */
7284d81ea8bSQu Wenruo 		ret = handle_indirect_tree_backref(cache, path, &key, node_key,
7294d81ea8bSQu Wenruo 						   cur);
730e7d571c7SQu Wenruo 		if (ret < 0)
73171f572a9SQu Wenruo 			goto out;
7325d4f98a2SYan Zheng 	}
73371f572a9SQu Wenruo 	ret = 0;
7345d4f98a2SYan Zheng 	cur->checked = 1;
7355d4f98a2SYan Zheng 	WARN_ON(exist);
736e7d571c7SQu Wenruo out:
737e7d571c7SQu Wenruo 	btrfs_backref_iter_release(iter);
738e7d571c7SQu Wenruo 	return ret;
739e7d571c7SQu Wenruo }
7405d4f98a2SYan Zheng 
741e7d571c7SQu Wenruo /*
7421f872924SQu Wenruo  * In handle_one_tree_backref(), we have only linked the lower node to the edge,
7431f872924SQu Wenruo  * but the upper node hasn't been linked to the edge.
744a26195a5SQu Wenruo  * This means we can only iterate through btrfs_backref_node::upper to reach
745a26195a5SQu Wenruo  * parent edges, but not through btrfs_backref_node::lower to reach children
746a26195a5SQu Wenruo  * edges.
7471f872924SQu Wenruo  *
748a26195a5SQu Wenruo  * This function will finish the btrfs_backref_node::lower to related edges,
749a26195a5SQu Wenruo  * so that backref cache can be bi-directionally iterated.
7501f872924SQu Wenruo  *
7511f872924SQu Wenruo  * Also, this will add the nodes to backref cache for the next run.
7521f872924SQu Wenruo  */
753a26195a5SQu Wenruo static int finish_upper_links(struct btrfs_backref_cache *cache,
754a26195a5SQu Wenruo 			      struct btrfs_backref_node *start)
7551f872924SQu Wenruo {
7561f872924SQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
757a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
7581f872924SQu Wenruo 	struct rb_node *rb_node;
7591f872924SQu Wenruo 	LIST_HEAD(pending_edge);
7601f872924SQu Wenruo 
7611f872924SQu Wenruo 	ASSERT(start->checked);
7621f872924SQu Wenruo 
7631f872924SQu Wenruo 	/* Insert this node to cache if it's not COW-only */
7641f872924SQu Wenruo 	if (!start->cowonly) {
765e9a28dc5SQu Wenruo 		rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
7661f872924SQu Wenruo 					   &start->rb_node);
7671f872924SQu Wenruo 		if (rb_node)
7681f872924SQu Wenruo 			backref_tree_panic(rb_node, -EEXIST, start->bytenr);
7691f872924SQu Wenruo 		list_add_tail(&start->lower, &cache->leaves);
7701f872924SQu Wenruo 	}
7711f872924SQu Wenruo 
7721f872924SQu Wenruo 	/*
7731f872924SQu Wenruo 	 * Use breadth first search to iterate all related edges.
7741f872924SQu Wenruo 	 *
7751f872924SQu Wenruo 	 * The starting points are all the edges of this node
7761f872924SQu Wenruo 	 */
7771f872924SQu Wenruo 	list_for_each_entry(edge, &start->upper, list[LOWER])
7781f872924SQu Wenruo 		list_add_tail(&edge->list[UPPER], &pending_edge);
7791f872924SQu Wenruo 
7801f872924SQu Wenruo 	while (!list_empty(&pending_edge)) {
781a26195a5SQu Wenruo 		struct btrfs_backref_node *upper;
782a26195a5SQu Wenruo 		struct btrfs_backref_node *lower;
7831f872924SQu Wenruo 		struct rb_node *rb_node;
7841f872924SQu Wenruo 
785a26195a5SQu Wenruo 		edge = list_first_entry(&pending_edge,
786a26195a5SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
7871f872924SQu Wenruo 		list_del_init(&edge->list[UPPER]);
7881f872924SQu Wenruo 		upper = edge->node[UPPER];
7891f872924SQu Wenruo 		lower = edge->node[LOWER];
7901f872924SQu Wenruo 
7911f872924SQu Wenruo 		/* Parent is detached, no need to keep any edges */
7921f872924SQu Wenruo 		if (upper->detached) {
7931f872924SQu Wenruo 			list_del(&edge->list[LOWER]);
794741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
7951f872924SQu Wenruo 
7961f872924SQu Wenruo 			/* Lower node is orphan, queue for cleanup */
7971f872924SQu Wenruo 			if (list_empty(&lower->upper))
7981f872924SQu Wenruo 				list_add(&lower->list, useless_node);
7991f872924SQu Wenruo 			continue;
8001f872924SQu Wenruo 		}
8011f872924SQu Wenruo 
8021f872924SQu Wenruo 		/*
8031f872924SQu Wenruo 		 * All new nodes added in current build_backref_tree() haven't
8041f872924SQu Wenruo 		 * been linked to the cache rb tree.
8051f872924SQu Wenruo 		 * So if we have upper->rb_node populated, this means a cache
8061f872924SQu Wenruo 		 * hit. We only need to link the edge, as @upper and all its
8071f872924SQu Wenruo 		 * parent have already been linked.
8081f872924SQu Wenruo 		 */
8091f872924SQu Wenruo 		if (!RB_EMPTY_NODE(&upper->rb_node)) {
8101f872924SQu Wenruo 			if (upper->lowest) {
8111f872924SQu Wenruo 				list_del_init(&upper->lower);
8121f872924SQu Wenruo 				upper->lowest = 0;
8131f872924SQu Wenruo 			}
8141f872924SQu Wenruo 
8151f872924SQu Wenruo 			list_add_tail(&edge->list[UPPER], &upper->lower);
8161f872924SQu Wenruo 			continue;
8171f872924SQu Wenruo 		}
8181f872924SQu Wenruo 
8191f872924SQu Wenruo 		/* Sanity check, we shouldn't have any unchecked nodes */
8201f872924SQu Wenruo 		if (!upper->checked) {
8211f872924SQu Wenruo 			ASSERT(0);
8221f872924SQu Wenruo 			return -EUCLEAN;
8231f872924SQu Wenruo 		}
8241f872924SQu Wenruo 
8251f872924SQu Wenruo 		/* Sanity check, COW-only node has non-COW-only parent */
8261f872924SQu Wenruo 		if (start->cowonly != upper->cowonly) {
8271f872924SQu Wenruo 			ASSERT(0);
8281f872924SQu Wenruo 			return -EUCLEAN;
8291f872924SQu Wenruo 		}
8301f872924SQu Wenruo 
8311f872924SQu Wenruo 		/* Only cache non-COW-only (subvolume trees) tree blocks */
8321f872924SQu Wenruo 		if (!upper->cowonly) {
833e9a28dc5SQu Wenruo 			rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
8341f872924SQu Wenruo 						   &upper->rb_node);
8351f872924SQu Wenruo 			if (rb_node) {
8361f872924SQu Wenruo 				backref_tree_panic(rb_node, -EEXIST,
8371f872924SQu Wenruo 						   upper->bytenr);
8381f872924SQu Wenruo 				return -EUCLEAN;
8391f872924SQu Wenruo 			}
8401f872924SQu Wenruo 		}
8411f872924SQu Wenruo 
8421f872924SQu Wenruo 		list_add_tail(&edge->list[UPPER], &upper->lower);
8431f872924SQu Wenruo 
8441f872924SQu Wenruo 		/*
8451f872924SQu Wenruo 		 * Also queue all the parent edges of this uncached node to
8461f872924SQu Wenruo 		 * finish the upper linkage
8471f872924SQu Wenruo 		 */
8481f872924SQu Wenruo 		list_for_each_entry(edge, &upper->upper, list[LOWER])
8491f872924SQu Wenruo 			list_add_tail(&edge->list[UPPER], &pending_edge);
8501f872924SQu Wenruo 	}
8511f872924SQu Wenruo 	return 0;
8521f872924SQu Wenruo }
8531f872924SQu Wenruo 
8541f872924SQu Wenruo /*
85529db137bSQu Wenruo  * For useless nodes, do two major clean ups:
85629db137bSQu Wenruo  *
85729db137bSQu Wenruo  * - Cleanup the children edges and nodes
85829db137bSQu Wenruo  *   If child node is also orphan (no parent) during cleanup, then the child
85929db137bSQu Wenruo  *   node will also be cleaned up.
86029db137bSQu Wenruo  *
86129db137bSQu Wenruo  * - Freeing up leaves (level 0), keeps nodes detached
86229db137bSQu Wenruo  *   For nodes, the node is still cached as "detached"
86329db137bSQu Wenruo  *
86429db137bSQu Wenruo  * Return false if @node is not in the @useless_nodes list.
86529db137bSQu Wenruo  * Return true if @node is in the @useless_nodes list.
86629db137bSQu Wenruo  */
86729db137bSQu Wenruo static bool handle_useless_nodes(struct reloc_control *rc,
868a26195a5SQu Wenruo 				 struct btrfs_backref_node *node)
86929db137bSQu Wenruo {
870a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
87129db137bSQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
87229db137bSQu Wenruo 	bool ret = false;
87329db137bSQu Wenruo 
87429db137bSQu Wenruo 	while (!list_empty(useless_node)) {
875a26195a5SQu Wenruo 		struct btrfs_backref_node *cur;
87629db137bSQu Wenruo 
877a26195a5SQu Wenruo 		cur = list_first_entry(useless_node, struct btrfs_backref_node,
87829db137bSQu Wenruo 				 list);
87929db137bSQu Wenruo 		list_del_init(&cur->list);
88029db137bSQu Wenruo 
88129db137bSQu Wenruo 		/* Only tree root nodes can be added to @useless_nodes */
88229db137bSQu Wenruo 		ASSERT(list_empty(&cur->upper));
88329db137bSQu Wenruo 
88429db137bSQu Wenruo 		if (cur == node)
88529db137bSQu Wenruo 			ret = true;
88629db137bSQu Wenruo 
88729db137bSQu Wenruo 		/* The node is the lowest node */
88829db137bSQu Wenruo 		if (cur->lowest) {
88929db137bSQu Wenruo 			list_del_init(&cur->lower);
89029db137bSQu Wenruo 			cur->lowest = 0;
89129db137bSQu Wenruo 		}
89229db137bSQu Wenruo 
89329db137bSQu Wenruo 		/* Cleanup the lower edges */
89429db137bSQu Wenruo 		while (!list_empty(&cur->lower)) {
895a26195a5SQu Wenruo 			struct btrfs_backref_edge *edge;
896a26195a5SQu Wenruo 			struct btrfs_backref_node *lower;
89729db137bSQu Wenruo 
89829db137bSQu Wenruo 			edge = list_entry(cur->lower.next,
899a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[UPPER]);
90029db137bSQu Wenruo 			list_del(&edge->list[UPPER]);
90129db137bSQu Wenruo 			list_del(&edge->list[LOWER]);
90229db137bSQu Wenruo 			lower = edge->node[LOWER];
903741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
90429db137bSQu Wenruo 
90529db137bSQu Wenruo 			/* Child node is also orphan, queue for cleanup */
90629db137bSQu Wenruo 			if (list_empty(&lower->upper))
90729db137bSQu Wenruo 				list_add(&lower->list, useless_node);
90829db137bSQu Wenruo 		}
90929db137bSQu Wenruo 		/* Mark this block processed for relocation */
91029db137bSQu Wenruo 		mark_block_processed(rc, cur);
91129db137bSQu Wenruo 
91229db137bSQu Wenruo 		/*
91329db137bSQu Wenruo 		 * Backref nodes for tree leaves are deleted from the cache.
91429db137bSQu Wenruo 		 * Backref nodes for upper level tree blocks are left in the
91529db137bSQu Wenruo 		 * cache to avoid unnecessary backref lookup.
91629db137bSQu Wenruo 		 */
91729db137bSQu Wenruo 		if (cur->level > 0) {
91829db137bSQu Wenruo 			list_add(&cur->list, &cache->detached);
91929db137bSQu Wenruo 			cur->detached = 1;
92029db137bSQu Wenruo 		} else {
92129db137bSQu Wenruo 			rb_erase(&cur->rb_node, &cache->rb_root);
922741188d3SQu Wenruo 			btrfs_backref_free_node(cache, cur);
92329db137bSQu Wenruo 		}
92429db137bSQu Wenruo 	}
92529db137bSQu Wenruo 	return ret;
92629db137bSQu Wenruo }
92729db137bSQu Wenruo 
92829db137bSQu Wenruo /*
929e7d571c7SQu Wenruo  * Build backref tree for a given tree block. Root of the backref tree
930e7d571c7SQu Wenruo  * corresponds the tree block, leaves of the backref tree correspond roots of
931e7d571c7SQu Wenruo  * b-trees that reference the tree block.
932e7d571c7SQu Wenruo  *
933e7d571c7SQu Wenruo  * The basic idea of this function is check backrefs of a given block to find
934e7d571c7SQu Wenruo  * upper level blocks that reference the block, and then check backrefs of
935e7d571c7SQu Wenruo  * these upper level blocks recursively. The recursion stops when tree root is
936e7d571c7SQu Wenruo  * reached or backrefs for the block is cached.
937e7d571c7SQu Wenruo  *
938e7d571c7SQu Wenruo  * NOTE: if we find that backrefs for a block are cached, we know backrefs for
939e7d571c7SQu Wenruo  * all upper level blocks that directly/indirectly reference the block are also
940e7d571c7SQu Wenruo  * cached.
941e7d571c7SQu Wenruo  */
942a26195a5SQu Wenruo static noinline_for_stack struct btrfs_backref_node *build_backref_tree(
943e7d571c7SQu Wenruo 			struct reloc_control *rc, struct btrfs_key *node_key,
944e7d571c7SQu Wenruo 			int level, u64 bytenr)
945e7d571c7SQu Wenruo {
946e7d571c7SQu Wenruo 	struct btrfs_backref_iter *iter;
947a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
948e7d571c7SQu Wenruo 	/* For searching parent of TREE_BLOCK_REF */
949e7d571c7SQu Wenruo 	struct btrfs_path *path;
950a26195a5SQu Wenruo 	struct btrfs_backref_node *cur;
951a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
952a26195a5SQu Wenruo 	struct btrfs_backref_node *lower;
953a26195a5SQu Wenruo 	struct btrfs_backref_node *node = NULL;
954a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
955e7d571c7SQu Wenruo 	int ret;
956e7d571c7SQu Wenruo 	int err = 0;
957e7d571c7SQu Wenruo 
958e7d571c7SQu Wenruo 	iter = btrfs_backref_iter_alloc(rc->extent_root->fs_info, GFP_NOFS);
959e7d571c7SQu Wenruo 	if (!iter)
960e7d571c7SQu Wenruo 		return ERR_PTR(-ENOMEM);
961e7d571c7SQu Wenruo 	path = btrfs_alloc_path();
962e7d571c7SQu Wenruo 	if (!path) {
963e7d571c7SQu Wenruo 		err = -ENOMEM;
964e7d571c7SQu Wenruo 		goto out;
965e7d571c7SQu Wenruo 	}
966e7d571c7SQu Wenruo 
967b1818dabSQu Wenruo 	node = btrfs_backref_alloc_node(cache, bytenr, level);
968e7d571c7SQu Wenruo 	if (!node) {
969e7d571c7SQu Wenruo 		err = -ENOMEM;
970e7d571c7SQu Wenruo 		goto out;
971e7d571c7SQu Wenruo 	}
972e7d571c7SQu Wenruo 
973e7d571c7SQu Wenruo 	node->lowest = 1;
974e7d571c7SQu Wenruo 	cur = node;
975e7d571c7SQu Wenruo 
976e7d571c7SQu Wenruo 	/* Breadth-first search to build backref cache */
977e7d571c7SQu Wenruo 	do {
978e7d571c7SQu Wenruo 		ret = handle_one_tree_block(cache, path, iter, node_key, cur);
979e7d571c7SQu Wenruo 		if (ret < 0) {
980e7d571c7SQu Wenruo 			err = ret;
981e7d571c7SQu Wenruo 			goto out;
982e7d571c7SQu Wenruo 		}
983e7d571c7SQu Wenruo 		edge = list_first_entry_or_null(&cache->pending_edge,
984a26195a5SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
985e7d571c7SQu Wenruo 		/*
986e7d571c7SQu Wenruo 		 * The pending list isn't empty, take the first block to
987e7d571c7SQu Wenruo 		 * process
988e7d571c7SQu Wenruo 		 */
989e7d571c7SQu Wenruo 		if (edge) {
9905d4f98a2SYan Zheng 			list_del_init(&edge->list[UPPER]);
9915d4f98a2SYan Zheng 			cur = edge->node[UPPER];
9925d4f98a2SYan Zheng 		}
993e7d571c7SQu Wenruo 	} while (edge);
9945d4f98a2SYan Zheng 
9951f872924SQu Wenruo 	/* Finish the upper linkage of newly added edges/nodes */
9961f872924SQu Wenruo 	ret = finish_upper_links(cache, node);
9971f872924SQu Wenruo 	if (ret < 0) {
9981f872924SQu Wenruo 		err = ret;
99975bfb9afSJosef Bacik 		goto out;
100075bfb9afSJosef Bacik 	}
100175bfb9afSJosef Bacik 
100229db137bSQu Wenruo 	if (handle_useless_nodes(rc, node))
10033fd0a558SYan, Zheng 		node = NULL;
10045d4f98a2SYan Zheng out:
100571f572a9SQu Wenruo 	btrfs_backref_iter_free(iter);
100671f572a9SQu Wenruo 	btrfs_free_path(path);
10075d4f98a2SYan Zheng 	if (err) {
100884780289SQu Wenruo 		while (!list_empty(&cache->useless_node)) {
100984780289SQu Wenruo 			lower = list_first_entry(&cache->useless_node,
1010a26195a5SQu Wenruo 					   struct btrfs_backref_node, list);
101175bfb9afSJosef Bacik 			list_del_init(&lower->list);
10123fd0a558SYan, Zheng 		}
101384780289SQu Wenruo 		while (!list_empty(&cache->pending_edge)) {
101484780289SQu Wenruo 			edge = list_first_entry(&cache->pending_edge,
1015a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[UPPER]);
101675bfb9afSJosef Bacik 			list_del(&edge->list[UPPER]);
10173fd0a558SYan, Zheng 			list_del(&edge->list[LOWER]);
101875bfb9afSJosef Bacik 			lower = edge->node[LOWER];
10195d4f98a2SYan Zheng 			upper = edge->node[UPPER];
1020741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
102175bfb9afSJosef Bacik 
102275bfb9afSJosef Bacik 			/*
102375bfb9afSJosef Bacik 			 * Lower is no longer linked to any upper backref nodes
102475bfb9afSJosef Bacik 			 * and isn't in the cache, we can free it ourselves.
102575bfb9afSJosef Bacik 			 */
102675bfb9afSJosef Bacik 			if (list_empty(&lower->upper) &&
102775bfb9afSJosef Bacik 			    RB_EMPTY_NODE(&lower->rb_node))
102884780289SQu Wenruo 				list_add(&lower->list, &cache->useless_node);
102975bfb9afSJosef Bacik 
103075bfb9afSJosef Bacik 			if (!RB_EMPTY_NODE(&upper->rb_node))
103175bfb9afSJosef Bacik 				continue;
103275bfb9afSJosef Bacik 
103301327610SNicholas D Steeves 			/* Add this guy's upper edges to the list to process */
103475bfb9afSJosef Bacik 			list_for_each_entry(edge, &upper->upper, list[LOWER])
103584780289SQu Wenruo 				list_add_tail(&edge->list[UPPER],
103684780289SQu Wenruo 					      &cache->pending_edge);
103775bfb9afSJosef Bacik 			if (list_empty(&upper->upper))
103884780289SQu Wenruo 				list_add(&upper->list, &cache->useless_node);
103975bfb9afSJosef Bacik 		}
104075bfb9afSJosef Bacik 
104184780289SQu Wenruo 		while (!list_empty(&cache->useless_node)) {
104284780289SQu Wenruo 			lower = list_first_entry(&cache->useless_node,
1043a26195a5SQu Wenruo 					   struct btrfs_backref_node, list);
104475bfb9afSJosef Bacik 			list_del_init(&lower->list);
10450fd8c3daSLiu Bo 			if (lower == node)
10460fd8c3daSLiu Bo 				node = NULL;
1047741188d3SQu Wenruo 			btrfs_backref_free_node(cache, lower);
10485d4f98a2SYan Zheng 		}
10490fd8c3daSLiu Bo 
1050023acb07SQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
105184780289SQu Wenruo 		ASSERT(list_empty(&cache->useless_node) &&
105284780289SQu Wenruo 		       list_empty(&cache->pending_edge));
10535d4f98a2SYan Zheng 		return ERR_PTR(err);
10545d4f98a2SYan Zheng 	}
105575bfb9afSJosef Bacik 	ASSERT(!node || !node->detached);
105684780289SQu Wenruo 	ASSERT(list_empty(&cache->useless_node) &&
105784780289SQu Wenruo 	       list_empty(&cache->pending_edge));
10585d4f98a2SYan Zheng 	return node;
10595d4f98a2SYan Zheng }
10605d4f98a2SYan Zheng 
10615d4f98a2SYan Zheng /*
10623fd0a558SYan, Zheng  * helper to add backref node for the newly created snapshot.
10633fd0a558SYan, Zheng  * the backref node is created by cloning backref node that
10643fd0a558SYan, Zheng  * corresponds to root of source tree
10653fd0a558SYan, Zheng  */
10663fd0a558SYan, Zheng static int clone_backref_node(struct btrfs_trans_handle *trans,
10673fd0a558SYan, Zheng 			      struct reloc_control *rc,
10683fd0a558SYan, Zheng 			      struct btrfs_root *src,
10693fd0a558SYan, Zheng 			      struct btrfs_root *dest)
10703fd0a558SYan, Zheng {
10713fd0a558SYan, Zheng 	struct btrfs_root *reloc_root = src->reloc_root;
1072a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
1073a26195a5SQu Wenruo 	struct btrfs_backref_node *node = NULL;
1074a26195a5SQu Wenruo 	struct btrfs_backref_node *new_node;
1075a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
1076a26195a5SQu Wenruo 	struct btrfs_backref_edge *new_edge;
10773fd0a558SYan, Zheng 	struct rb_node *rb_node;
10783fd0a558SYan, Zheng 
10793fd0a558SYan, Zheng 	if (cache->last_trans > 0)
10803fd0a558SYan, Zheng 		update_backref_cache(trans, cache);
10813fd0a558SYan, Zheng 
1082e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, src->commit_root->start);
10833fd0a558SYan, Zheng 	if (rb_node) {
1084a26195a5SQu Wenruo 		node = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
10853fd0a558SYan, Zheng 		if (node->detached)
10863fd0a558SYan, Zheng 			node = NULL;
10873fd0a558SYan, Zheng 		else
10883fd0a558SYan, Zheng 			BUG_ON(node->new_bytenr != reloc_root->node->start);
10893fd0a558SYan, Zheng 	}
10903fd0a558SYan, Zheng 
10913fd0a558SYan, Zheng 	if (!node) {
1092e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root,
10933fd0a558SYan, Zheng 					   reloc_root->commit_root->start);
10943fd0a558SYan, Zheng 		if (rb_node) {
1095a26195a5SQu Wenruo 			node = rb_entry(rb_node, struct btrfs_backref_node,
10963fd0a558SYan, Zheng 					rb_node);
10973fd0a558SYan, Zheng 			BUG_ON(node->detached);
10983fd0a558SYan, Zheng 		}
10993fd0a558SYan, Zheng 	}
11003fd0a558SYan, Zheng 
11013fd0a558SYan, Zheng 	if (!node)
11023fd0a558SYan, Zheng 		return 0;
11033fd0a558SYan, Zheng 
1104b1818dabSQu Wenruo 	new_node = btrfs_backref_alloc_node(cache, dest->node->start,
1105b1818dabSQu Wenruo 					    node->level);
11063fd0a558SYan, Zheng 	if (!new_node)
11073fd0a558SYan, Zheng 		return -ENOMEM;
11083fd0a558SYan, Zheng 
11093fd0a558SYan, Zheng 	new_node->lowest = node->lowest;
11106848ad64SYan, Zheng 	new_node->checked = 1;
111100246528SJosef Bacik 	new_node->root = btrfs_grab_root(dest);
11120b530bc5SJosef Bacik 	ASSERT(new_node->root);
11133fd0a558SYan, Zheng 
11143fd0a558SYan, Zheng 	if (!node->lowest) {
11153fd0a558SYan, Zheng 		list_for_each_entry(edge, &node->lower, list[UPPER]) {
111647254d07SQu Wenruo 			new_edge = btrfs_backref_alloc_edge(cache);
11173fd0a558SYan, Zheng 			if (!new_edge)
11183fd0a558SYan, Zheng 				goto fail;
11193fd0a558SYan, Zheng 
1120f39911e5SQu Wenruo 			btrfs_backref_link_edge(new_edge, edge->node[LOWER],
1121f39911e5SQu Wenruo 						new_node, LINK_UPPER);
11223fd0a558SYan, Zheng 		}
112376b9e23dSMiao Xie 	} else {
112476b9e23dSMiao Xie 		list_add_tail(&new_node->lower, &cache->leaves);
11253fd0a558SYan, Zheng 	}
11263fd0a558SYan, Zheng 
1127e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&cache->rb_root, new_node->bytenr,
11283fd0a558SYan, Zheng 				   &new_node->rb_node);
112943c04fb1SJeff Mahoney 	if (rb_node)
113043c04fb1SJeff Mahoney 		backref_tree_panic(rb_node, -EEXIST, new_node->bytenr);
11313fd0a558SYan, Zheng 
11323fd0a558SYan, Zheng 	if (!new_node->lowest) {
11333fd0a558SYan, Zheng 		list_for_each_entry(new_edge, &new_node->lower, list[UPPER]) {
11343fd0a558SYan, Zheng 			list_add_tail(&new_edge->list[LOWER],
11353fd0a558SYan, Zheng 				      &new_edge->node[LOWER]->upper);
11363fd0a558SYan, Zheng 		}
11373fd0a558SYan, Zheng 	}
11383fd0a558SYan, Zheng 	return 0;
11393fd0a558SYan, Zheng fail:
11403fd0a558SYan, Zheng 	while (!list_empty(&new_node->lower)) {
11413fd0a558SYan, Zheng 		new_edge = list_entry(new_node->lower.next,
1142a26195a5SQu Wenruo 				      struct btrfs_backref_edge, list[UPPER]);
11433fd0a558SYan, Zheng 		list_del(&new_edge->list[UPPER]);
1144741188d3SQu Wenruo 		btrfs_backref_free_edge(cache, new_edge);
11453fd0a558SYan, Zheng 	}
1146741188d3SQu Wenruo 	btrfs_backref_free_node(cache, new_node);
11473fd0a558SYan, Zheng 	return -ENOMEM;
11483fd0a558SYan, Zheng }
11493fd0a558SYan, Zheng 
11503fd0a558SYan, Zheng /*
11515d4f98a2SYan Zheng  * helper to add 'address of tree root -> reloc tree' mapping
11525d4f98a2SYan Zheng  */
1153ffd7b339SJeff Mahoney static int __must_check __add_reloc_root(struct btrfs_root *root)
11545d4f98a2SYan Zheng {
11550b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11565d4f98a2SYan Zheng 	struct rb_node *rb_node;
11575d4f98a2SYan Zheng 	struct mapping_node *node;
11580b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
11595d4f98a2SYan Zheng 
11605d4f98a2SYan Zheng 	node = kmalloc(sizeof(*node), GFP_NOFS);
1161ffd7b339SJeff Mahoney 	if (!node)
1162ffd7b339SJeff Mahoney 		return -ENOMEM;
11635d4f98a2SYan Zheng 
1164ea287ab1SJosef Bacik 	node->bytenr = root->commit_root->start;
11655d4f98a2SYan Zheng 	node->data = root;
11665d4f98a2SYan Zheng 
11675d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
1168e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
11695d4f98a2SYan Zheng 				   node->bytenr, &node->rb_node);
11705d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
1171ffd7b339SJeff Mahoney 	if (rb_node) {
11720b246afaSJeff Mahoney 		btrfs_panic(fs_info, -EEXIST,
11735d163e0eSJeff Mahoney 			    "Duplicate root found for start=%llu while inserting into relocation tree",
11745d163e0eSJeff Mahoney 			    node->bytenr);
1175ffd7b339SJeff Mahoney 	}
11765d4f98a2SYan Zheng 
11775d4f98a2SYan Zheng 	list_add_tail(&root->root_list, &rc->reloc_roots);
11785d4f98a2SYan Zheng 	return 0;
11795d4f98a2SYan Zheng }
11805d4f98a2SYan Zheng 
11815d4f98a2SYan Zheng /*
1182c974c464SWang Shilong  * helper to delete the 'address of tree root -> reloc tree'
11835d4f98a2SYan Zheng  * mapping
11845d4f98a2SYan Zheng  */
1185c974c464SWang Shilong static void __del_reloc_root(struct btrfs_root *root)
11865d4f98a2SYan Zheng {
11870b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
11885d4f98a2SYan Zheng 	struct rb_node *rb_node;
11895d4f98a2SYan Zheng 	struct mapping_node *node = NULL;
11900b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
1191f44deb74SJosef Bacik 	bool put_ref = false;
11925d4f98a2SYan Zheng 
119365c6e82bSQu Wenruo 	if (rc && root->node) {
11945d4f98a2SYan Zheng 		spin_lock(&rc->reloc_root_tree.lock);
1195e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
1196ea287ab1SJosef Bacik 					   root->commit_root->start);
1197c974c464SWang Shilong 		if (rb_node) {
1198c974c464SWang Shilong 			node = rb_entry(rb_node, struct mapping_node, rb_node);
1199c974c464SWang Shilong 			rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
1200ea287ab1SJosef Bacik 			RB_CLEAR_NODE(&node->rb_node);
1201c974c464SWang Shilong 		}
1202c974c464SWang Shilong 		spin_unlock(&rc->reloc_root_tree.lock);
1203c974c464SWang Shilong 		if (!node)
1204c974c464SWang Shilong 			return;
1205c974c464SWang Shilong 		BUG_ON((struct btrfs_root *)node->data != root);
1206389305b2SQu Wenruo 	}
1207c974c464SWang Shilong 
1208f44deb74SJosef Bacik 	/*
1209f44deb74SJosef Bacik 	 * We only put the reloc root here if it's on the list.  There's a lot
1210f44deb74SJosef Bacik 	 * of places where the pattern is to splice the rc->reloc_roots, process
1211f44deb74SJosef Bacik 	 * the reloc roots, and then add the reloc root back onto
1212f44deb74SJosef Bacik 	 * rc->reloc_roots.  If we call __del_reloc_root while it's off of the
1213f44deb74SJosef Bacik 	 * list we don't want the reference being dropped, because the guy
1214f44deb74SJosef Bacik 	 * messing with the list is in charge of the reference.
1215f44deb74SJosef Bacik 	 */
12160b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
1217f44deb74SJosef Bacik 	if (!list_empty(&root->root_list)) {
1218f44deb74SJosef Bacik 		put_ref = true;
1219c974c464SWang Shilong 		list_del_init(&root->root_list);
1220f44deb74SJosef Bacik 	}
12210b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
1222f44deb74SJosef Bacik 	if (put_ref)
1223f44deb74SJosef Bacik 		btrfs_put_root(root);
1224c974c464SWang Shilong 	kfree(node);
1225c974c464SWang Shilong }
1226c974c464SWang Shilong 
1227c974c464SWang Shilong /*
1228c974c464SWang Shilong  * helper to update the 'address of tree root -> reloc tree'
1229c974c464SWang Shilong  * mapping
1230c974c464SWang Shilong  */
1231ea287ab1SJosef Bacik static int __update_reloc_root(struct btrfs_root *root)
1232c974c464SWang Shilong {
12330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
1234c974c464SWang Shilong 	struct rb_node *rb_node;
1235c974c464SWang Shilong 	struct mapping_node *node = NULL;
12360b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
1237c974c464SWang Shilong 
1238c974c464SWang Shilong 	spin_lock(&rc->reloc_root_tree.lock);
1239e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
1240ea287ab1SJosef Bacik 				   root->commit_root->start);
12415d4f98a2SYan Zheng 	if (rb_node) {
12425d4f98a2SYan Zheng 		node = rb_entry(rb_node, struct mapping_node, rb_node);
12435d4f98a2SYan Zheng 		rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
12445d4f98a2SYan Zheng 	}
12455d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
12465d4f98a2SYan Zheng 
12478f71f3e0SLiu Bo 	if (!node)
12488f71f3e0SLiu Bo 		return 0;
12495d4f98a2SYan Zheng 	BUG_ON((struct btrfs_root *)node->data != root);
12505d4f98a2SYan Zheng 
12515d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
1252ea287ab1SJosef Bacik 	node->bytenr = root->node->start;
1253e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
12545d4f98a2SYan Zheng 				   node->bytenr, &node->rb_node);
12555d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
125643c04fb1SJeff Mahoney 	if (rb_node)
125743c04fb1SJeff Mahoney 		backref_tree_panic(rb_node, -EEXIST, node->bytenr);
12585d4f98a2SYan Zheng 	return 0;
12595d4f98a2SYan Zheng }
12605d4f98a2SYan Zheng 
12613fd0a558SYan, Zheng static struct btrfs_root *create_reloc_root(struct btrfs_trans_handle *trans,
12623fd0a558SYan, Zheng 					struct btrfs_root *root, u64 objectid)
12635d4f98a2SYan Zheng {
12640b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
12655d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
12665d4f98a2SYan Zheng 	struct extent_buffer *eb;
12675d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
12685d4f98a2SYan Zheng 	struct btrfs_key root_key;
12695d4f98a2SYan Zheng 	int ret;
12705d4f98a2SYan Zheng 
12715d4f98a2SYan Zheng 	root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
12725d4f98a2SYan Zheng 	BUG_ON(!root_item);
12735d4f98a2SYan Zheng 
12745d4f98a2SYan Zheng 	root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
12755d4f98a2SYan Zheng 	root_key.type = BTRFS_ROOT_ITEM_KEY;
12763fd0a558SYan, Zheng 	root_key.offset = objectid;
12775d4f98a2SYan Zheng 
12783fd0a558SYan, Zheng 	if (root->root_key.objectid == objectid) {
1279054570a1SFilipe Manana 		u64 commit_root_gen;
1280054570a1SFilipe Manana 
12813fd0a558SYan, Zheng 		/* called by btrfs_init_reloc_root */
12825d4f98a2SYan Zheng 		ret = btrfs_copy_root(trans, root, root->commit_root, &eb,
12835d4f98a2SYan Zheng 				      BTRFS_TREE_RELOC_OBJECTID);
12845d4f98a2SYan Zheng 		BUG_ON(ret);
1285054570a1SFilipe Manana 		/*
1286054570a1SFilipe Manana 		 * Set the last_snapshot field to the generation of the commit
1287054570a1SFilipe Manana 		 * root - like this ctree.c:btrfs_block_can_be_shared() behaves
1288054570a1SFilipe Manana 		 * correctly (returns true) when the relocation root is created
1289054570a1SFilipe Manana 		 * either inside the critical section of a transaction commit
1290054570a1SFilipe Manana 		 * (through transaction.c:qgroup_account_snapshot()) and when
1291054570a1SFilipe Manana 		 * it's created before the transaction commit is started.
1292054570a1SFilipe Manana 		 */
1293054570a1SFilipe Manana 		commit_root_gen = btrfs_header_generation(root->commit_root);
1294054570a1SFilipe Manana 		btrfs_set_root_last_snapshot(&root->root_item, commit_root_gen);
12953fd0a558SYan, Zheng 	} else {
12963fd0a558SYan, Zheng 		/*
12973fd0a558SYan, Zheng 		 * called by btrfs_reloc_post_snapshot_hook.
12983fd0a558SYan, Zheng 		 * the source tree is a reloc tree, all tree blocks
12993fd0a558SYan, Zheng 		 * modified after it was created have RELOC flag
13003fd0a558SYan, Zheng 		 * set in their headers. so it's OK to not update
13013fd0a558SYan, Zheng 		 * the 'last_snapshot'.
13023fd0a558SYan, Zheng 		 */
13033fd0a558SYan, Zheng 		ret = btrfs_copy_root(trans, root, root->node, &eb,
13043fd0a558SYan, Zheng 				      BTRFS_TREE_RELOC_OBJECTID);
13053fd0a558SYan, Zheng 		BUG_ON(ret);
13063fd0a558SYan, Zheng 	}
13073fd0a558SYan, Zheng 
13085d4f98a2SYan Zheng 	memcpy(root_item, &root->root_item, sizeof(*root_item));
13095d4f98a2SYan Zheng 	btrfs_set_root_bytenr(root_item, eb->start);
13105d4f98a2SYan Zheng 	btrfs_set_root_level(root_item, btrfs_header_level(eb));
13115d4f98a2SYan Zheng 	btrfs_set_root_generation(root_item, trans->transid);
13123fd0a558SYan, Zheng 
13133fd0a558SYan, Zheng 	if (root->root_key.objectid == objectid) {
13143fd0a558SYan, Zheng 		btrfs_set_root_refs(root_item, 0);
13153fd0a558SYan, Zheng 		memset(&root_item->drop_progress, 0,
13163fd0a558SYan, Zheng 		       sizeof(struct btrfs_disk_key));
13175d4f98a2SYan Zheng 		root_item->drop_level = 0;
13183fd0a558SYan, Zheng 	}
13195d4f98a2SYan Zheng 
13205d4f98a2SYan Zheng 	btrfs_tree_unlock(eb);
13215d4f98a2SYan Zheng 	free_extent_buffer(eb);
13225d4f98a2SYan Zheng 
13230b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root,
13245d4f98a2SYan Zheng 				&root_key, root_item);
13255d4f98a2SYan Zheng 	BUG_ON(ret);
13265d4f98a2SYan Zheng 	kfree(root_item);
13275d4f98a2SYan Zheng 
13283dbf1738SJosef Bacik 	reloc_root = btrfs_read_tree_root(fs_info->tree_root, &root_key);
13295d4f98a2SYan Zheng 	BUG_ON(IS_ERR(reloc_root));
13303dbf1738SJosef Bacik 	set_bit(BTRFS_ROOT_REF_COWS, &reloc_root->state);
13315d4f98a2SYan Zheng 	reloc_root->last_trans = trans->transid;
13323fd0a558SYan, Zheng 	return reloc_root;
13333fd0a558SYan, Zheng }
13343fd0a558SYan, Zheng 
13353fd0a558SYan, Zheng /*
13363fd0a558SYan, Zheng  * create reloc tree for a given fs tree. reloc tree is just a
13373fd0a558SYan, Zheng  * snapshot of the fs tree with special root objectid.
1338f44deb74SJosef Bacik  *
1339f44deb74SJosef Bacik  * The reloc_root comes out of here with two references, one for
1340f44deb74SJosef Bacik  * root->reloc_root, and another for being on the rc->reloc_roots list.
13413fd0a558SYan, Zheng  */
13423fd0a558SYan, Zheng int btrfs_init_reloc_root(struct btrfs_trans_handle *trans,
13433fd0a558SYan, Zheng 			  struct btrfs_root *root)
13443fd0a558SYan, Zheng {
13450b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
13463fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
13470b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
134820dd2cbfSMiao Xie 	struct btrfs_block_rsv *rsv;
13493fd0a558SYan, Zheng 	int clear_rsv = 0;
1350ffd7b339SJeff Mahoney 	int ret;
13513fd0a558SYan, Zheng 
1352aec7db3bSJosef Bacik 	if (!rc)
13532abc726aSJosef Bacik 		return 0;
13542abc726aSJosef Bacik 
13551fac4a54SQu Wenruo 	/*
13561fac4a54SQu Wenruo 	 * The subvolume has reloc tree but the swap is finished, no need to
13571fac4a54SQu Wenruo 	 * create/update the dead reloc tree
13581fac4a54SQu Wenruo 	 */
13596282675eSQu Wenruo 	if (reloc_root_is_dead(root))
13601fac4a54SQu Wenruo 		return 0;
13611fac4a54SQu Wenruo 
1362aec7db3bSJosef Bacik 	/*
1363aec7db3bSJosef Bacik 	 * This is subtle but important.  We do not do
1364aec7db3bSJosef Bacik 	 * record_root_in_transaction for reloc roots, instead we record their
1365aec7db3bSJosef Bacik 	 * corresponding fs root, and then here we update the last trans for the
1366aec7db3bSJosef Bacik 	 * reloc root.  This means that we have to do this for the entire life
1367aec7db3bSJosef Bacik 	 * of the reloc root, regardless of which stage of the relocation we are
1368aec7db3bSJosef Bacik 	 * in.
1369aec7db3bSJosef Bacik 	 */
13703fd0a558SYan, Zheng 	if (root->reloc_root) {
13713fd0a558SYan, Zheng 		reloc_root = root->reloc_root;
13723fd0a558SYan, Zheng 		reloc_root->last_trans = trans->transid;
13733fd0a558SYan, Zheng 		return 0;
13743fd0a558SYan, Zheng 	}
13753fd0a558SYan, Zheng 
1376aec7db3bSJosef Bacik 	/*
1377aec7db3bSJosef Bacik 	 * We are merging reloc roots, we do not need new reloc trees.  Also
1378aec7db3bSJosef Bacik 	 * reloc trees never need their own reloc tree.
1379aec7db3bSJosef Bacik 	 */
1380aec7db3bSJosef Bacik 	if (!rc->create_reloc_tree ||
1381aec7db3bSJosef Bacik 	    root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1382aec7db3bSJosef Bacik 		return 0;
1383aec7db3bSJosef Bacik 
138420dd2cbfSMiao Xie 	if (!trans->reloc_reserved) {
138520dd2cbfSMiao Xie 		rsv = trans->block_rsv;
13863fd0a558SYan, Zheng 		trans->block_rsv = rc->block_rsv;
13873fd0a558SYan, Zheng 		clear_rsv = 1;
13883fd0a558SYan, Zheng 	}
13893fd0a558SYan, Zheng 	reloc_root = create_reloc_root(trans, root, root->root_key.objectid);
13903fd0a558SYan, Zheng 	if (clear_rsv)
139120dd2cbfSMiao Xie 		trans->block_rsv = rsv;
13925d4f98a2SYan Zheng 
1393ffd7b339SJeff Mahoney 	ret = __add_reloc_root(reloc_root);
1394ffd7b339SJeff Mahoney 	BUG_ON(ret < 0);
1395f44deb74SJosef Bacik 	root->reloc_root = btrfs_grab_root(reloc_root);
13965d4f98a2SYan Zheng 	return 0;
13975d4f98a2SYan Zheng }
13985d4f98a2SYan Zheng 
13995d4f98a2SYan Zheng /*
14005d4f98a2SYan Zheng  * update root item of reloc tree
14015d4f98a2SYan Zheng  */
14025d4f98a2SYan Zheng int btrfs_update_reloc_root(struct btrfs_trans_handle *trans,
14035d4f98a2SYan Zheng 			    struct btrfs_root *root)
14045d4f98a2SYan Zheng {
14050b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14065d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
14075d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
14085d4f98a2SYan Zheng 	int ret;
14095d4f98a2SYan Zheng 
14106282675eSQu Wenruo 	if (!have_reloc_root(root))
14117585717fSChris Mason 		goto out;
14125d4f98a2SYan Zheng 
14135d4f98a2SYan Zheng 	reloc_root = root->reloc_root;
14145d4f98a2SYan Zheng 	root_item = &reloc_root->root_item;
14155d4f98a2SYan Zheng 
1416f44deb74SJosef Bacik 	/*
1417f44deb74SJosef Bacik 	 * We are probably ok here, but __del_reloc_root() will drop its ref of
1418f44deb74SJosef Bacik 	 * the root.  We have the ref for root->reloc_root, but just in case
1419f44deb74SJosef Bacik 	 * hold it while we update the reloc root.
1420f44deb74SJosef Bacik 	 */
1421f44deb74SJosef Bacik 	btrfs_grab_root(reloc_root);
1422f44deb74SJosef Bacik 
1423d2311e69SQu Wenruo 	/* root->reloc_root will stay until current relocation finished */
14240b246afaSJeff Mahoney 	if (fs_info->reloc_ctl->merge_reloc_tree &&
14253fd0a558SYan, Zheng 	    btrfs_root_refs(root_item) == 0) {
1426d2311e69SQu Wenruo 		set_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
14276282675eSQu Wenruo 		/*
14286282675eSQu Wenruo 		 * Mark the tree as dead before we change reloc_root so
14296282675eSQu Wenruo 		 * have_reloc_root will not touch it from now on.
14306282675eSQu Wenruo 		 */
14316282675eSQu Wenruo 		smp_wmb();
1432c974c464SWang Shilong 		__del_reloc_root(reloc_root);
14335d4f98a2SYan Zheng 	}
14345d4f98a2SYan Zheng 
14355d4f98a2SYan Zheng 	if (reloc_root->commit_root != reloc_root->node) {
1436ea287ab1SJosef Bacik 		__update_reloc_root(reloc_root);
14375d4f98a2SYan Zheng 		btrfs_set_root_node(root_item, reloc_root->node);
14385d4f98a2SYan Zheng 		free_extent_buffer(reloc_root->commit_root);
14395d4f98a2SYan Zheng 		reloc_root->commit_root = btrfs_root_node(reloc_root);
14405d4f98a2SYan Zheng 	}
14415d4f98a2SYan Zheng 
14420b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
14435d4f98a2SYan Zheng 				&reloc_root->root_key, root_item);
14445d4f98a2SYan Zheng 	BUG_ON(ret);
1445f44deb74SJosef Bacik 	btrfs_put_root(reloc_root);
14467585717fSChris Mason out:
14475d4f98a2SYan Zheng 	return 0;
14485d4f98a2SYan Zheng }
14495d4f98a2SYan Zheng 
14505d4f98a2SYan Zheng /*
14515d4f98a2SYan Zheng  * helper to find first cached inode with inode number >= objectid
14525d4f98a2SYan Zheng  * in a subvolume
14535d4f98a2SYan Zheng  */
14545d4f98a2SYan Zheng static struct inode *find_next_inode(struct btrfs_root *root, u64 objectid)
14555d4f98a2SYan Zheng {
14565d4f98a2SYan Zheng 	struct rb_node *node;
14575d4f98a2SYan Zheng 	struct rb_node *prev;
14585d4f98a2SYan Zheng 	struct btrfs_inode *entry;
14595d4f98a2SYan Zheng 	struct inode *inode;
14605d4f98a2SYan Zheng 
14615d4f98a2SYan Zheng 	spin_lock(&root->inode_lock);
14625d4f98a2SYan Zheng again:
14635d4f98a2SYan Zheng 	node = root->inode_tree.rb_node;
14645d4f98a2SYan Zheng 	prev = NULL;
14655d4f98a2SYan Zheng 	while (node) {
14665d4f98a2SYan Zheng 		prev = node;
14675d4f98a2SYan Zheng 		entry = rb_entry(node, struct btrfs_inode, rb_node);
14685d4f98a2SYan Zheng 
14694a0cc7caSNikolay Borisov 		if (objectid < btrfs_ino(entry))
14705d4f98a2SYan Zheng 			node = node->rb_left;
14714a0cc7caSNikolay Borisov 		else if (objectid > btrfs_ino(entry))
14725d4f98a2SYan Zheng 			node = node->rb_right;
14735d4f98a2SYan Zheng 		else
14745d4f98a2SYan Zheng 			break;
14755d4f98a2SYan Zheng 	}
14765d4f98a2SYan Zheng 	if (!node) {
14775d4f98a2SYan Zheng 		while (prev) {
14785d4f98a2SYan Zheng 			entry = rb_entry(prev, struct btrfs_inode, rb_node);
14794a0cc7caSNikolay Borisov 			if (objectid <= btrfs_ino(entry)) {
14805d4f98a2SYan Zheng 				node = prev;
14815d4f98a2SYan Zheng 				break;
14825d4f98a2SYan Zheng 			}
14835d4f98a2SYan Zheng 			prev = rb_next(prev);
14845d4f98a2SYan Zheng 		}
14855d4f98a2SYan Zheng 	}
14865d4f98a2SYan Zheng 	while (node) {
14875d4f98a2SYan Zheng 		entry = rb_entry(node, struct btrfs_inode, rb_node);
14885d4f98a2SYan Zheng 		inode = igrab(&entry->vfs_inode);
14895d4f98a2SYan Zheng 		if (inode) {
14905d4f98a2SYan Zheng 			spin_unlock(&root->inode_lock);
14915d4f98a2SYan Zheng 			return inode;
14925d4f98a2SYan Zheng 		}
14935d4f98a2SYan Zheng 
14944a0cc7caSNikolay Borisov 		objectid = btrfs_ino(entry) + 1;
14955d4f98a2SYan Zheng 		if (cond_resched_lock(&root->inode_lock))
14965d4f98a2SYan Zheng 			goto again;
14975d4f98a2SYan Zheng 
14985d4f98a2SYan Zheng 		node = rb_next(node);
14995d4f98a2SYan Zheng 	}
15005d4f98a2SYan Zheng 	spin_unlock(&root->inode_lock);
15015d4f98a2SYan Zheng 	return NULL;
15025d4f98a2SYan Zheng }
15035d4f98a2SYan Zheng 
15045d4f98a2SYan Zheng /*
15055d4f98a2SYan Zheng  * get new location of data
15065d4f98a2SYan Zheng  */
15075d4f98a2SYan Zheng static int get_new_location(struct inode *reloc_inode, u64 *new_bytenr,
15085d4f98a2SYan Zheng 			    u64 bytenr, u64 num_bytes)
15095d4f98a2SYan Zheng {
15105d4f98a2SYan Zheng 	struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
15115d4f98a2SYan Zheng 	struct btrfs_path *path;
15125d4f98a2SYan Zheng 	struct btrfs_file_extent_item *fi;
15135d4f98a2SYan Zheng 	struct extent_buffer *leaf;
15145d4f98a2SYan Zheng 	int ret;
15155d4f98a2SYan Zheng 
15165d4f98a2SYan Zheng 	path = btrfs_alloc_path();
15175d4f98a2SYan Zheng 	if (!path)
15185d4f98a2SYan Zheng 		return -ENOMEM;
15195d4f98a2SYan Zheng 
15205d4f98a2SYan Zheng 	bytenr -= BTRFS_I(reloc_inode)->index_cnt;
1521f85b7379SDavid Sterba 	ret = btrfs_lookup_file_extent(NULL, root, path,
1522f85b7379SDavid Sterba 			btrfs_ino(BTRFS_I(reloc_inode)), bytenr, 0);
15235d4f98a2SYan Zheng 	if (ret < 0)
15245d4f98a2SYan Zheng 		goto out;
15255d4f98a2SYan Zheng 	if (ret > 0) {
15265d4f98a2SYan Zheng 		ret = -ENOENT;
15275d4f98a2SYan Zheng 		goto out;
15285d4f98a2SYan Zheng 	}
15295d4f98a2SYan Zheng 
15305d4f98a2SYan Zheng 	leaf = path->nodes[0];
15315d4f98a2SYan Zheng 	fi = btrfs_item_ptr(leaf, path->slots[0],
15325d4f98a2SYan Zheng 			    struct btrfs_file_extent_item);
15335d4f98a2SYan Zheng 
15345d4f98a2SYan Zheng 	BUG_ON(btrfs_file_extent_offset(leaf, fi) ||
15355d4f98a2SYan Zheng 	       btrfs_file_extent_compression(leaf, fi) ||
15365d4f98a2SYan Zheng 	       btrfs_file_extent_encryption(leaf, fi) ||
15375d4f98a2SYan Zheng 	       btrfs_file_extent_other_encoding(leaf, fi));
15385d4f98a2SYan Zheng 
15395d4f98a2SYan Zheng 	if (num_bytes != btrfs_file_extent_disk_num_bytes(leaf, fi)) {
154083d4cfd4SJosef Bacik 		ret = -EINVAL;
15415d4f98a2SYan Zheng 		goto out;
15425d4f98a2SYan Zheng 	}
15435d4f98a2SYan Zheng 
15445d4f98a2SYan Zheng 	*new_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
15455d4f98a2SYan Zheng 	ret = 0;
15465d4f98a2SYan Zheng out:
15475d4f98a2SYan Zheng 	btrfs_free_path(path);
15485d4f98a2SYan Zheng 	return ret;
15495d4f98a2SYan Zheng }
15505d4f98a2SYan Zheng 
15515d4f98a2SYan Zheng /*
15525d4f98a2SYan Zheng  * update file extent items in the tree leaf to point to
15535d4f98a2SYan Zheng  * the new locations.
15545d4f98a2SYan Zheng  */
15553fd0a558SYan, Zheng static noinline_for_stack
15563fd0a558SYan, Zheng int replace_file_extents(struct btrfs_trans_handle *trans,
15575d4f98a2SYan Zheng 			 struct reloc_control *rc,
15585d4f98a2SYan Zheng 			 struct btrfs_root *root,
15593fd0a558SYan, Zheng 			 struct extent_buffer *leaf)
15605d4f98a2SYan Zheng {
15610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15625d4f98a2SYan Zheng 	struct btrfs_key key;
15635d4f98a2SYan Zheng 	struct btrfs_file_extent_item *fi;
15645d4f98a2SYan Zheng 	struct inode *inode = NULL;
15655d4f98a2SYan Zheng 	u64 parent;
15665d4f98a2SYan Zheng 	u64 bytenr;
15673fd0a558SYan, Zheng 	u64 new_bytenr = 0;
15685d4f98a2SYan Zheng 	u64 num_bytes;
15695d4f98a2SYan Zheng 	u64 end;
15705d4f98a2SYan Zheng 	u32 nritems;
15715d4f98a2SYan Zheng 	u32 i;
157283d4cfd4SJosef Bacik 	int ret = 0;
15735d4f98a2SYan Zheng 	int first = 1;
15745d4f98a2SYan Zheng 	int dirty = 0;
15755d4f98a2SYan Zheng 
15765d4f98a2SYan Zheng 	if (rc->stage != UPDATE_DATA_PTRS)
15775d4f98a2SYan Zheng 		return 0;
15785d4f98a2SYan Zheng 
15795d4f98a2SYan Zheng 	/* reloc trees always use full backref */
15805d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
15815d4f98a2SYan Zheng 		parent = leaf->start;
15825d4f98a2SYan Zheng 	else
15835d4f98a2SYan Zheng 		parent = 0;
15845d4f98a2SYan Zheng 
15855d4f98a2SYan Zheng 	nritems = btrfs_header_nritems(leaf);
15865d4f98a2SYan Zheng 	for (i = 0; i < nritems; i++) {
158782fa113fSQu Wenruo 		struct btrfs_ref ref = { 0 };
158882fa113fSQu Wenruo 
15895d4f98a2SYan Zheng 		cond_resched();
15905d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, i);
15915d4f98a2SYan Zheng 		if (key.type != BTRFS_EXTENT_DATA_KEY)
15925d4f98a2SYan Zheng 			continue;
15935d4f98a2SYan Zheng 		fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
15945d4f98a2SYan Zheng 		if (btrfs_file_extent_type(leaf, fi) ==
15955d4f98a2SYan Zheng 		    BTRFS_FILE_EXTENT_INLINE)
15965d4f98a2SYan Zheng 			continue;
15975d4f98a2SYan Zheng 		bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
15985d4f98a2SYan Zheng 		num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
15995d4f98a2SYan Zheng 		if (bytenr == 0)
16005d4f98a2SYan Zheng 			continue;
16019569cc20SQu Wenruo 		if (!in_range(bytenr, rc->block_group->start,
16029569cc20SQu Wenruo 			      rc->block_group->length))
16035d4f98a2SYan Zheng 			continue;
16045d4f98a2SYan Zheng 
16055d4f98a2SYan Zheng 		/*
16065d4f98a2SYan Zheng 		 * if we are modifying block in fs tree, wait for readpage
16075d4f98a2SYan Zheng 		 * to complete and drop the extent cache
16085d4f98a2SYan Zheng 		 */
16095d4f98a2SYan Zheng 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
16105d4f98a2SYan Zheng 			if (first) {
16115d4f98a2SYan Zheng 				inode = find_next_inode(root, key.objectid);
16125d4f98a2SYan Zheng 				first = 0;
16134a0cc7caSNikolay Borisov 			} else if (inode && btrfs_ino(BTRFS_I(inode)) < key.objectid) {
16143fd0a558SYan, Zheng 				btrfs_add_delayed_iput(inode);
16155d4f98a2SYan Zheng 				inode = find_next_inode(root, key.objectid);
16165d4f98a2SYan Zheng 			}
16174a0cc7caSNikolay Borisov 			if (inode && btrfs_ino(BTRFS_I(inode)) == key.objectid) {
16185d4f98a2SYan Zheng 				end = key.offset +
16195d4f98a2SYan Zheng 				      btrfs_file_extent_num_bytes(leaf, fi);
16205d4f98a2SYan Zheng 				WARN_ON(!IS_ALIGNED(key.offset,
16210b246afaSJeff Mahoney 						    fs_info->sectorsize));
16220b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
16235d4f98a2SYan Zheng 				end--;
16245d4f98a2SYan Zheng 				ret = try_lock_extent(&BTRFS_I(inode)->io_tree,
1625d0082371SJeff Mahoney 						      key.offset, end);
16265d4f98a2SYan Zheng 				if (!ret)
16275d4f98a2SYan Zheng 					continue;
16285d4f98a2SYan Zheng 
1629dcdbc059SNikolay Borisov 				btrfs_drop_extent_cache(BTRFS_I(inode),
1630dcdbc059SNikolay Borisov 						key.offset,	end, 1);
16315d4f98a2SYan Zheng 				unlock_extent(&BTRFS_I(inode)->io_tree,
1632d0082371SJeff Mahoney 					      key.offset, end);
16335d4f98a2SYan Zheng 			}
16345d4f98a2SYan Zheng 		}
16355d4f98a2SYan Zheng 
16365d4f98a2SYan Zheng 		ret = get_new_location(rc->data_inode, &new_bytenr,
16375d4f98a2SYan Zheng 				       bytenr, num_bytes);
163883d4cfd4SJosef Bacik 		if (ret) {
163983d4cfd4SJosef Bacik 			/*
164083d4cfd4SJosef Bacik 			 * Don't have to abort since we've not changed anything
164183d4cfd4SJosef Bacik 			 * in the file extent yet.
164283d4cfd4SJosef Bacik 			 */
164383d4cfd4SJosef Bacik 			break;
16443fd0a558SYan, Zheng 		}
16455d4f98a2SYan Zheng 
16465d4f98a2SYan Zheng 		btrfs_set_file_extent_disk_bytenr(leaf, fi, new_bytenr);
16475d4f98a2SYan Zheng 		dirty = 1;
16485d4f98a2SYan Zheng 
16495d4f98a2SYan Zheng 		key.offset -= btrfs_file_extent_offset(leaf, fi);
165082fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new_bytenr,
165182fa113fSQu Wenruo 				       num_bytes, parent);
165282fa113fSQu Wenruo 		ref.real_root = root->root_key.objectid;
165382fa113fSQu Wenruo 		btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
1654b06c4bf5SFilipe Manana 				    key.objectid, key.offset);
165582fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
165683d4cfd4SJosef Bacik 		if (ret) {
165766642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
165883d4cfd4SJosef Bacik 			break;
165983d4cfd4SJosef Bacik 		}
16605d4f98a2SYan Zheng 
1661ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
1662ffd4bb2aSQu Wenruo 				       num_bytes, parent);
1663ffd4bb2aSQu Wenruo 		ref.real_root = root->root_key.objectid;
1664ffd4bb2aSQu Wenruo 		btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
1665b06c4bf5SFilipe Manana 				    key.objectid, key.offset);
1666ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
166783d4cfd4SJosef Bacik 		if (ret) {
166866642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
166983d4cfd4SJosef Bacik 			break;
167083d4cfd4SJosef Bacik 		}
16715d4f98a2SYan Zheng 	}
16725d4f98a2SYan Zheng 	if (dirty)
16735d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(leaf);
16743fd0a558SYan, Zheng 	if (inode)
16753fd0a558SYan, Zheng 		btrfs_add_delayed_iput(inode);
167683d4cfd4SJosef Bacik 	return ret;
16775d4f98a2SYan Zheng }
16785d4f98a2SYan Zheng 
16795d4f98a2SYan Zheng static noinline_for_stack
16805d4f98a2SYan Zheng int memcmp_node_keys(struct extent_buffer *eb, int slot,
16815d4f98a2SYan Zheng 		     struct btrfs_path *path, int level)
16825d4f98a2SYan Zheng {
16835d4f98a2SYan Zheng 	struct btrfs_disk_key key1;
16845d4f98a2SYan Zheng 	struct btrfs_disk_key key2;
16855d4f98a2SYan Zheng 	btrfs_node_key(eb, &key1, slot);
16865d4f98a2SYan Zheng 	btrfs_node_key(path->nodes[level], &key2, path->slots[level]);
16875d4f98a2SYan Zheng 	return memcmp(&key1, &key2, sizeof(key1));
16885d4f98a2SYan Zheng }
16895d4f98a2SYan Zheng 
16905d4f98a2SYan Zheng /*
16915d4f98a2SYan Zheng  * try to replace tree blocks in fs tree with the new blocks
16925d4f98a2SYan Zheng  * in reloc tree. tree blocks haven't been modified since the
16935d4f98a2SYan Zheng  * reloc tree was create can be replaced.
16945d4f98a2SYan Zheng  *
16955d4f98a2SYan Zheng  * if a block was replaced, level of the block + 1 is returned.
16965d4f98a2SYan Zheng  * if no block got replaced, 0 is returned. if there are other
16975d4f98a2SYan Zheng  * errors, a negative error number is returned.
16985d4f98a2SYan Zheng  */
16993fd0a558SYan, Zheng static noinline_for_stack
17003d0174f7SQu Wenruo int replace_path(struct btrfs_trans_handle *trans, struct reloc_control *rc,
17015d4f98a2SYan Zheng 		 struct btrfs_root *dest, struct btrfs_root *src,
17025d4f98a2SYan Zheng 		 struct btrfs_path *path, struct btrfs_key *next_key,
17035d4f98a2SYan Zheng 		 int lowest_level, int max_level)
17045d4f98a2SYan Zheng {
17050b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = dest->fs_info;
17065d4f98a2SYan Zheng 	struct extent_buffer *eb;
17075d4f98a2SYan Zheng 	struct extent_buffer *parent;
170882fa113fSQu Wenruo 	struct btrfs_ref ref = { 0 };
17095d4f98a2SYan Zheng 	struct btrfs_key key;
17105d4f98a2SYan Zheng 	u64 old_bytenr;
17115d4f98a2SYan Zheng 	u64 new_bytenr;
17125d4f98a2SYan Zheng 	u64 old_ptr_gen;
17135d4f98a2SYan Zheng 	u64 new_ptr_gen;
17145d4f98a2SYan Zheng 	u64 last_snapshot;
17155d4f98a2SYan Zheng 	u32 blocksize;
17163fd0a558SYan, Zheng 	int cow = 0;
17175d4f98a2SYan Zheng 	int level;
17185d4f98a2SYan Zheng 	int ret;
17195d4f98a2SYan Zheng 	int slot;
17205d4f98a2SYan Zheng 
17215d4f98a2SYan Zheng 	BUG_ON(src->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
17225d4f98a2SYan Zheng 	BUG_ON(dest->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID);
17235d4f98a2SYan Zheng 
17245d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&src->root_item);
17253fd0a558SYan, Zheng again:
17265d4f98a2SYan Zheng 	slot = path->slots[lowest_level];
17275d4f98a2SYan Zheng 	btrfs_node_key_to_cpu(path->nodes[lowest_level], &key, slot);
17285d4f98a2SYan Zheng 
17295d4f98a2SYan Zheng 	eb = btrfs_lock_root_node(dest);
17308bead258SDavid Sterba 	btrfs_set_lock_blocking_write(eb);
17315d4f98a2SYan Zheng 	level = btrfs_header_level(eb);
17325d4f98a2SYan Zheng 
17335d4f98a2SYan Zheng 	if (level < lowest_level) {
17345d4f98a2SYan Zheng 		btrfs_tree_unlock(eb);
17355d4f98a2SYan Zheng 		free_extent_buffer(eb);
17365d4f98a2SYan Zheng 		return 0;
17375d4f98a2SYan Zheng 	}
17385d4f98a2SYan Zheng 
17393fd0a558SYan, Zheng 	if (cow) {
17405d4f98a2SYan Zheng 		ret = btrfs_cow_block(trans, dest, eb, NULL, 0, &eb);
17415d4f98a2SYan Zheng 		BUG_ON(ret);
17423fd0a558SYan, Zheng 	}
17438bead258SDavid Sterba 	btrfs_set_lock_blocking_write(eb);
17445d4f98a2SYan Zheng 
17455d4f98a2SYan Zheng 	if (next_key) {
17465d4f98a2SYan Zheng 		next_key->objectid = (u64)-1;
17475d4f98a2SYan Zheng 		next_key->type = (u8)-1;
17485d4f98a2SYan Zheng 		next_key->offset = (u64)-1;
17495d4f98a2SYan Zheng 	}
17505d4f98a2SYan Zheng 
17515d4f98a2SYan Zheng 	parent = eb;
17525d4f98a2SYan Zheng 	while (1) {
1753581c1760SQu Wenruo 		struct btrfs_key first_key;
1754581c1760SQu Wenruo 
17555d4f98a2SYan Zheng 		level = btrfs_header_level(parent);
17565d4f98a2SYan Zheng 		BUG_ON(level < lowest_level);
17575d4f98a2SYan Zheng 
17585d4f98a2SYan Zheng 		ret = btrfs_bin_search(parent, &key, level, &slot);
1759cbca7d59SFilipe Manana 		if (ret < 0)
1760cbca7d59SFilipe Manana 			break;
17615d4f98a2SYan Zheng 		if (ret && slot > 0)
17625d4f98a2SYan Zheng 			slot--;
17635d4f98a2SYan Zheng 
17645d4f98a2SYan Zheng 		if (next_key && slot + 1 < btrfs_header_nritems(parent))
17655d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(parent, next_key, slot + 1);
17665d4f98a2SYan Zheng 
17675d4f98a2SYan Zheng 		old_bytenr = btrfs_node_blockptr(parent, slot);
17680b246afaSJeff Mahoney 		blocksize = fs_info->nodesize;
17695d4f98a2SYan Zheng 		old_ptr_gen = btrfs_node_ptr_generation(parent, slot);
177017515f1bSQu Wenruo 		btrfs_node_key_to_cpu(parent, &first_key, slot);
17715d4f98a2SYan Zheng 
17725d4f98a2SYan Zheng 		if (level <= max_level) {
17735d4f98a2SYan Zheng 			eb = path->nodes[level];
17745d4f98a2SYan Zheng 			new_bytenr = btrfs_node_blockptr(eb,
17755d4f98a2SYan Zheng 							path->slots[level]);
17765d4f98a2SYan Zheng 			new_ptr_gen = btrfs_node_ptr_generation(eb,
17775d4f98a2SYan Zheng 							path->slots[level]);
17785d4f98a2SYan Zheng 		} else {
17795d4f98a2SYan Zheng 			new_bytenr = 0;
17805d4f98a2SYan Zheng 			new_ptr_gen = 0;
17815d4f98a2SYan Zheng 		}
17825d4f98a2SYan Zheng 
1783fae7f21cSDulshani Gunawardhana 		if (WARN_ON(new_bytenr > 0 && new_bytenr == old_bytenr)) {
17845d4f98a2SYan Zheng 			ret = level;
17855d4f98a2SYan Zheng 			break;
17865d4f98a2SYan Zheng 		}
17875d4f98a2SYan Zheng 
17885d4f98a2SYan Zheng 		if (new_bytenr == 0 || old_ptr_gen > last_snapshot ||
17895d4f98a2SYan Zheng 		    memcmp_node_keys(parent, slot, path, level)) {
17903fd0a558SYan, Zheng 			if (level <= lowest_level) {
17915d4f98a2SYan Zheng 				ret = 0;
17925d4f98a2SYan Zheng 				break;
17935d4f98a2SYan Zheng 			}
17945d4f98a2SYan Zheng 
1795581c1760SQu Wenruo 			eb = read_tree_block(fs_info, old_bytenr, old_ptr_gen,
1796581c1760SQu Wenruo 					     level - 1, &first_key);
179764c043deSLiu Bo 			if (IS_ERR(eb)) {
179864c043deSLiu Bo 				ret = PTR_ERR(eb);
1799264813acSLiu Bo 				break;
180064c043deSLiu Bo 			} else if (!extent_buffer_uptodate(eb)) {
180164c043deSLiu Bo 				ret = -EIO;
1802416bc658SJosef Bacik 				free_extent_buffer(eb);
1803379cde74SStefan Behrens 				break;
1804416bc658SJosef Bacik 			}
18055d4f98a2SYan Zheng 			btrfs_tree_lock(eb);
18063fd0a558SYan, Zheng 			if (cow) {
18075d4f98a2SYan Zheng 				ret = btrfs_cow_block(trans, dest, eb, parent,
18085d4f98a2SYan Zheng 						      slot, &eb);
18095d4f98a2SYan Zheng 				BUG_ON(ret);
18105d4f98a2SYan Zheng 			}
18118bead258SDavid Sterba 			btrfs_set_lock_blocking_write(eb);
18125d4f98a2SYan Zheng 
18135d4f98a2SYan Zheng 			btrfs_tree_unlock(parent);
18145d4f98a2SYan Zheng 			free_extent_buffer(parent);
18155d4f98a2SYan Zheng 
18165d4f98a2SYan Zheng 			parent = eb;
18175d4f98a2SYan Zheng 			continue;
18185d4f98a2SYan Zheng 		}
18195d4f98a2SYan Zheng 
18203fd0a558SYan, Zheng 		if (!cow) {
18213fd0a558SYan, Zheng 			btrfs_tree_unlock(parent);
18223fd0a558SYan, Zheng 			free_extent_buffer(parent);
18233fd0a558SYan, Zheng 			cow = 1;
18243fd0a558SYan, Zheng 			goto again;
18253fd0a558SYan, Zheng 		}
18263fd0a558SYan, Zheng 
18275d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(path->nodes[level], &key,
18285d4f98a2SYan Zheng 				      path->slots[level]);
1829b3b4aa74SDavid Sterba 		btrfs_release_path(path);
18305d4f98a2SYan Zheng 
18315d4f98a2SYan Zheng 		path->lowest_level = level;
18325d4f98a2SYan Zheng 		ret = btrfs_search_slot(trans, src, &key, path, 0, 1);
18335d4f98a2SYan Zheng 		path->lowest_level = 0;
18345d4f98a2SYan Zheng 		BUG_ON(ret);
18355d4f98a2SYan Zheng 
18365d4f98a2SYan Zheng 		/*
1837824d8dffSQu Wenruo 		 * Info qgroup to trace both subtrees.
1838824d8dffSQu Wenruo 		 *
1839824d8dffSQu Wenruo 		 * We must trace both trees.
1840824d8dffSQu Wenruo 		 * 1) Tree reloc subtree
1841824d8dffSQu Wenruo 		 *    If not traced, we will leak data numbers
1842824d8dffSQu Wenruo 		 * 2) Fs subtree
1843824d8dffSQu Wenruo 		 *    If not traced, we will double count old data
1844f616f5cdSQu Wenruo 		 *
1845f616f5cdSQu Wenruo 		 * We don't scan the subtree right now, but only record
1846f616f5cdSQu Wenruo 		 * the swapped tree blocks.
1847f616f5cdSQu Wenruo 		 * The real subtree rescan is delayed until we have new
1848f616f5cdSQu Wenruo 		 * CoW on the subtree root node before transaction commit.
1849824d8dffSQu Wenruo 		 */
1850370a11b8SQu Wenruo 		ret = btrfs_qgroup_add_swapped_blocks(trans, dest,
1851370a11b8SQu Wenruo 				rc->block_group, parent, slot,
1852370a11b8SQu Wenruo 				path->nodes[level], path->slots[level],
1853370a11b8SQu Wenruo 				last_snapshot);
1854370a11b8SQu Wenruo 		if (ret < 0)
1855370a11b8SQu Wenruo 			break;
1856824d8dffSQu Wenruo 		/*
18575d4f98a2SYan Zheng 		 * swap blocks in fs tree and reloc tree.
18585d4f98a2SYan Zheng 		 */
18595d4f98a2SYan Zheng 		btrfs_set_node_blockptr(parent, slot, new_bytenr);
18605d4f98a2SYan Zheng 		btrfs_set_node_ptr_generation(parent, slot, new_ptr_gen);
18615d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(parent);
18625d4f98a2SYan Zheng 
18635d4f98a2SYan Zheng 		btrfs_set_node_blockptr(path->nodes[level],
18645d4f98a2SYan Zheng 					path->slots[level], old_bytenr);
18655d4f98a2SYan Zheng 		btrfs_set_node_ptr_generation(path->nodes[level],
18665d4f98a2SYan Zheng 					      path->slots[level], old_ptr_gen);
18675d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(path->nodes[level]);
18685d4f98a2SYan Zheng 
186982fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, old_bytenr,
187082fa113fSQu Wenruo 				       blocksize, path->nodes[level]->start);
187182fa113fSQu Wenruo 		ref.skip_qgroup = true;
187282fa113fSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, src->root_key.objectid);
187382fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
18745d4f98a2SYan Zheng 		BUG_ON(ret);
187582fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new_bytenr,
187682fa113fSQu Wenruo 				       blocksize, 0);
187782fa113fSQu Wenruo 		ref.skip_qgroup = true;
187882fa113fSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, dest->root_key.objectid);
187982fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
18805d4f98a2SYan Zheng 		BUG_ON(ret);
18815d4f98a2SYan Zheng 
1882ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, new_bytenr,
1883ffd4bb2aSQu Wenruo 				       blocksize, path->nodes[level]->start);
1884ffd4bb2aSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, src->root_key.objectid);
1885ffd4bb2aSQu Wenruo 		ref.skip_qgroup = true;
1886ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
18875d4f98a2SYan Zheng 		BUG_ON(ret);
18885d4f98a2SYan Zheng 
1889ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, old_bytenr,
1890ffd4bb2aSQu Wenruo 				       blocksize, 0);
1891ffd4bb2aSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, dest->root_key.objectid);
1892ffd4bb2aSQu Wenruo 		ref.skip_qgroup = true;
1893ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
18945d4f98a2SYan Zheng 		BUG_ON(ret);
18955d4f98a2SYan Zheng 
18965d4f98a2SYan Zheng 		btrfs_unlock_up_safe(path, 0);
18975d4f98a2SYan Zheng 
18985d4f98a2SYan Zheng 		ret = level;
18995d4f98a2SYan Zheng 		break;
19005d4f98a2SYan Zheng 	}
19015d4f98a2SYan Zheng 	btrfs_tree_unlock(parent);
19025d4f98a2SYan Zheng 	free_extent_buffer(parent);
19035d4f98a2SYan Zheng 	return ret;
19045d4f98a2SYan Zheng }
19055d4f98a2SYan Zheng 
19065d4f98a2SYan Zheng /*
19075d4f98a2SYan Zheng  * helper to find next relocated block in reloc tree
19085d4f98a2SYan Zheng  */
19095d4f98a2SYan Zheng static noinline_for_stack
19105d4f98a2SYan Zheng int walk_up_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
19115d4f98a2SYan Zheng 		       int *level)
19125d4f98a2SYan Zheng {
19135d4f98a2SYan Zheng 	struct extent_buffer *eb;
19145d4f98a2SYan Zheng 	int i;
19155d4f98a2SYan Zheng 	u64 last_snapshot;
19165d4f98a2SYan Zheng 	u32 nritems;
19175d4f98a2SYan Zheng 
19185d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
19195d4f98a2SYan Zheng 
19205d4f98a2SYan Zheng 	for (i = 0; i < *level; i++) {
19215d4f98a2SYan Zheng 		free_extent_buffer(path->nodes[i]);
19225d4f98a2SYan Zheng 		path->nodes[i] = NULL;
19235d4f98a2SYan Zheng 	}
19245d4f98a2SYan Zheng 
19255d4f98a2SYan Zheng 	for (i = *level; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
19265d4f98a2SYan Zheng 		eb = path->nodes[i];
19275d4f98a2SYan Zheng 		nritems = btrfs_header_nritems(eb);
19285d4f98a2SYan Zheng 		while (path->slots[i] + 1 < nritems) {
19295d4f98a2SYan Zheng 			path->slots[i]++;
19305d4f98a2SYan Zheng 			if (btrfs_node_ptr_generation(eb, path->slots[i]) <=
19315d4f98a2SYan Zheng 			    last_snapshot)
19325d4f98a2SYan Zheng 				continue;
19335d4f98a2SYan Zheng 
19345d4f98a2SYan Zheng 			*level = i;
19355d4f98a2SYan Zheng 			return 0;
19365d4f98a2SYan Zheng 		}
19375d4f98a2SYan Zheng 		free_extent_buffer(path->nodes[i]);
19385d4f98a2SYan Zheng 		path->nodes[i] = NULL;
19395d4f98a2SYan Zheng 	}
19405d4f98a2SYan Zheng 	return 1;
19415d4f98a2SYan Zheng }
19425d4f98a2SYan Zheng 
19435d4f98a2SYan Zheng /*
19445d4f98a2SYan Zheng  * walk down reloc tree to find relocated block of lowest level
19455d4f98a2SYan Zheng  */
19465d4f98a2SYan Zheng static noinline_for_stack
19475d4f98a2SYan Zheng int walk_down_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
19485d4f98a2SYan Zheng 			 int *level)
19495d4f98a2SYan Zheng {
19502ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
19515d4f98a2SYan Zheng 	struct extent_buffer *eb = NULL;
19525d4f98a2SYan Zheng 	int i;
19535d4f98a2SYan Zheng 	u64 bytenr;
19545d4f98a2SYan Zheng 	u64 ptr_gen = 0;
19555d4f98a2SYan Zheng 	u64 last_snapshot;
19565d4f98a2SYan Zheng 	u32 nritems;
19575d4f98a2SYan Zheng 
19585d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
19595d4f98a2SYan Zheng 
19605d4f98a2SYan Zheng 	for (i = *level; i > 0; i--) {
1961581c1760SQu Wenruo 		struct btrfs_key first_key;
1962581c1760SQu Wenruo 
19635d4f98a2SYan Zheng 		eb = path->nodes[i];
19645d4f98a2SYan Zheng 		nritems = btrfs_header_nritems(eb);
19655d4f98a2SYan Zheng 		while (path->slots[i] < nritems) {
19665d4f98a2SYan Zheng 			ptr_gen = btrfs_node_ptr_generation(eb, path->slots[i]);
19675d4f98a2SYan Zheng 			if (ptr_gen > last_snapshot)
19685d4f98a2SYan Zheng 				break;
19695d4f98a2SYan Zheng 			path->slots[i]++;
19705d4f98a2SYan Zheng 		}
19715d4f98a2SYan Zheng 		if (path->slots[i] >= nritems) {
19725d4f98a2SYan Zheng 			if (i == *level)
19735d4f98a2SYan Zheng 				break;
19745d4f98a2SYan Zheng 			*level = i + 1;
19755d4f98a2SYan Zheng 			return 0;
19765d4f98a2SYan Zheng 		}
19775d4f98a2SYan Zheng 		if (i == 1) {
19785d4f98a2SYan Zheng 			*level = i;
19795d4f98a2SYan Zheng 			return 0;
19805d4f98a2SYan Zheng 		}
19815d4f98a2SYan Zheng 
19825d4f98a2SYan Zheng 		bytenr = btrfs_node_blockptr(eb, path->slots[i]);
1983581c1760SQu Wenruo 		btrfs_node_key_to_cpu(eb, &first_key, path->slots[i]);
1984581c1760SQu Wenruo 		eb = read_tree_block(fs_info, bytenr, ptr_gen, i - 1,
1985581c1760SQu Wenruo 				     &first_key);
198664c043deSLiu Bo 		if (IS_ERR(eb)) {
198764c043deSLiu Bo 			return PTR_ERR(eb);
198864c043deSLiu Bo 		} else if (!extent_buffer_uptodate(eb)) {
1989416bc658SJosef Bacik 			free_extent_buffer(eb);
1990416bc658SJosef Bacik 			return -EIO;
1991416bc658SJosef Bacik 		}
19925d4f98a2SYan Zheng 		BUG_ON(btrfs_header_level(eb) != i - 1);
19935d4f98a2SYan Zheng 		path->nodes[i - 1] = eb;
19945d4f98a2SYan Zheng 		path->slots[i - 1] = 0;
19955d4f98a2SYan Zheng 	}
19965d4f98a2SYan Zheng 	return 1;
19975d4f98a2SYan Zheng }
19985d4f98a2SYan Zheng 
19995d4f98a2SYan Zheng /*
20005d4f98a2SYan Zheng  * invalidate extent cache for file extents whose key in range of
20015d4f98a2SYan Zheng  * [min_key, max_key)
20025d4f98a2SYan Zheng  */
20035d4f98a2SYan Zheng static int invalidate_extent_cache(struct btrfs_root *root,
20045d4f98a2SYan Zheng 				   struct btrfs_key *min_key,
20055d4f98a2SYan Zheng 				   struct btrfs_key *max_key)
20065d4f98a2SYan Zheng {
20070b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
20085d4f98a2SYan Zheng 	struct inode *inode = NULL;
20095d4f98a2SYan Zheng 	u64 objectid;
20105d4f98a2SYan Zheng 	u64 start, end;
201133345d01SLi Zefan 	u64 ino;
20125d4f98a2SYan Zheng 
20135d4f98a2SYan Zheng 	objectid = min_key->objectid;
20145d4f98a2SYan Zheng 	while (1) {
20155d4f98a2SYan Zheng 		cond_resched();
20165d4f98a2SYan Zheng 		iput(inode);
20175d4f98a2SYan Zheng 
20185d4f98a2SYan Zheng 		if (objectid > max_key->objectid)
20195d4f98a2SYan Zheng 			break;
20205d4f98a2SYan Zheng 
20215d4f98a2SYan Zheng 		inode = find_next_inode(root, objectid);
20225d4f98a2SYan Zheng 		if (!inode)
20235d4f98a2SYan Zheng 			break;
20244a0cc7caSNikolay Borisov 		ino = btrfs_ino(BTRFS_I(inode));
20255d4f98a2SYan Zheng 
202633345d01SLi Zefan 		if (ino > max_key->objectid) {
20275d4f98a2SYan Zheng 			iput(inode);
20285d4f98a2SYan Zheng 			break;
20295d4f98a2SYan Zheng 		}
20305d4f98a2SYan Zheng 
203133345d01SLi Zefan 		objectid = ino + 1;
20325d4f98a2SYan Zheng 		if (!S_ISREG(inode->i_mode))
20335d4f98a2SYan Zheng 			continue;
20345d4f98a2SYan Zheng 
203533345d01SLi Zefan 		if (unlikely(min_key->objectid == ino)) {
20365d4f98a2SYan Zheng 			if (min_key->type > BTRFS_EXTENT_DATA_KEY)
20375d4f98a2SYan Zheng 				continue;
20385d4f98a2SYan Zheng 			if (min_key->type < BTRFS_EXTENT_DATA_KEY)
20395d4f98a2SYan Zheng 				start = 0;
20405d4f98a2SYan Zheng 			else {
20415d4f98a2SYan Zheng 				start = min_key->offset;
20420b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(start, fs_info->sectorsize));
20435d4f98a2SYan Zheng 			}
20445d4f98a2SYan Zheng 		} else {
20455d4f98a2SYan Zheng 			start = 0;
20465d4f98a2SYan Zheng 		}
20475d4f98a2SYan Zheng 
204833345d01SLi Zefan 		if (unlikely(max_key->objectid == ino)) {
20495d4f98a2SYan Zheng 			if (max_key->type < BTRFS_EXTENT_DATA_KEY)
20505d4f98a2SYan Zheng 				continue;
20515d4f98a2SYan Zheng 			if (max_key->type > BTRFS_EXTENT_DATA_KEY) {
20525d4f98a2SYan Zheng 				end = (u64)-1;
20535d4f98a2SYan Zheng 			} else {
20545d4f98a2SYan Zheng 				if (max_key->offset == 0)
20555d4f98a2SYan Zheng 					continue;
20565d4f98a2SYan Zheng 				end = max_key->offset;
20570b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
20585d4f98a2SYan Zheng 				end--;
20595d4f98a2SYan Zheng 			}
20605d4f98a2SYan Zheng 		} else {
20615d4f98a2SYan Zheng 			end = (u64)-1;
20625d4f98a2SYan Zheng 		}
20635d4f98a2SYan Zheng 
20645d4f98a2SYan Zheng 		/* the lock_extent waits for readpage to complete */
2065d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, start, end);
2066dcdbc059SNikolay Borisov 		btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 1);
2067d0082371SJeff Mahoney 		unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
20685d4f98a2SYan Zheng 	}
20695d4f98a2SYan Zheng 	return 0;
20705d4f98a2SYan Zheng }
20715d4f98a2SYan Zheng 
20725d4f98a2SYan Zheng static int find_next_key(struct btrfs_path *path, int level,
20735d4f98a2SYan Zheng 			 struct btrfs_key *key)
20745d4f98a2SYan Zheng 
20755d4f98a2SYan Zheng {
20765d4f98a2SYan Zheng 	while (level < BTRFS_MAX_LEVEL) {
20775d4f98a2SYan Zheng 		if (!path->nodes[level])
20785d4f98a2SYan Zheng 			break;
20795d4f98a2SYan Zheng 		if (path->slots[level] + 1 <
20805d4f98a2SYan Zheng 		    btrfs_header_nritems(path->nodes[level])) {
20815d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(path->nodes[level], key,
20825d4f98a2SYan Zheng 					      path->slots[level] + 1);
20835d4f98a2SYan Zheng 			return 0;
20845d4f98a2SYan Zheng 		}
20855d4f98a2SYan Zheng 		level++;
20865d4f98a2SYan Zheng 	}
20875d4f98a2SYan Zheng 	return 1;
20885d4f98a2SYan Zheng }
20895d4f98a2SYan Zheng 
20905d4f98a2SYan Zheng /*
2091d2311e69SQu Wenruo  * Insert current subvolume into reloc_control::dirty_subvol_roots
2092d2311e69SQu Wenruo  */
2093d2311e69SQu Wenruo static void insert_dirty_subvol(struct btrfs_trans_handle *trans,
2094d2311e69SQu Wenruo 				struct reloc_control *rc,
2095d2311e69SQu Wenruo 				struct btrfs_root *root)
2096d2311e69SQu Wenruo {
2097d2311e69SQu Wenruo 	struct btrfs_root *reloc_root = root->reloc_root;
2098d2311e69SQu Wenruo 	struct btrfs_root_item *reloc_root_item;
2099d2311e69SQu Wenruo 
2100d2311e69SQu Wenruo 	/* @root must be a subvolume tree root with a valid reloc tree */
2101d2311e69SQu Wenruo 	ASSERT(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
2102d2311e69SQu Wenruo 	ASSERT(reloc_root);
2103d2311e69SQu Wenruo 
2104d2311e69SQu Wenruo 	reloc_root_item = &reloc_root->root_item;
2105d2311e69SQu Wenruo 	memset(&reloc_root_item->drop_progress, 0,
2106d2311e69SQu Wenruo 		sizeof(reloc_root_item->drop_progress));
2107d2311e69SQu Wenruo 	reloc_root_item->drop_level = 0;
2108d2311e69SQu Wenruo 	btrfs_set_root_refs(reloc_root_item, 0);
2109d2311e69SQu Wenruo 	btrfs_update_reloc_root(trans, root);
2110d2311e69SQu Wenruo 
2111d2311e69SQu Wenruo 	if (list_empty(&root->reloc_dirty_list)) {
211200246528SJosef Bacik 		btrfs_grab_root(root);
2113d2311e69SQu Wenruo 		list_add_tail(&root->reloc_dirty_list, &rc->dirty_subvol_roots);
2114d2311e69SQu Wenruo 	}
2115d2311e69SQu Wenruo }
2116d2311e69SQu Wenruo 
2117d2311e69SQu Wenruo static int clean_dirty_subvols(struct reloc_control *rc)
2118d2311e69SQu Wenruo {
2119d2311e69SQu Wenruo 	struct btrfs_root *root;
2120d2311e69SQu Wenruo 	struct btrfs_root *next;
2121d2311e69SQu Wenruo 	int ret = 0;
212230d40577SQu Wenruo 	int ret2;
2123d2311e69SQu Wenruo 
2124d2311e69SQu Wenruo 	list_for_each_entry_safe(root, next, &rc->dirty_subvol_roots,
2125d2311e69SQu Wenruo 				 reloc_dirty_list) {
212630d40577SQu Wenruo 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
212730d40577SQu Wenruo 			/* Merged subvolume, cleanup its reloc root */
2128d2311e69SQu Wenruo 			struct btrfs_root *reloc_root = root->reloc_root;
2129d2311e69SQu Wenruo 
2130d2311e69SQu Wenruo 			list_del_init(&root->reloc_dirty_list);
2131d2311e69SQu Wenruo 			root->reloc_root = NULL;
21326282675eSQu Wenruo 			/*
21336282675eSQu Wenruo 			 * Need barrier to ensure clear_bit() only happens after
21346282675eSQu Wenruo 			 * root->reloc_root = NULL. Pairs with have_reloc_root.
21356282675eSQu Wenruo 			 */
21366282675eSQu Wenruo 			smp_wmb();
21371fac4a54SQu Wenruo 			clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
2138f28de8d8SJosef Bacik 			if (reloc_root) {
2139f44deb74SJosef Bacik 				/*
2140f44deb74SJosef Bacik 				 * btrfs_drop_snapshot drops our ref we hold for
2141f44deb74SJosef Bacik 				 * ->reloc_root.  If it fails however we must
2142f44deb74SJosef Bacik 				 * drop the ref ourselves.
2143f44deb74SJosef Bacik 				 */
2144f28de8d8SJosef Bacik 				ret2 = btrfs_drop_snapshot(reloc_root, 0, 1);
2145f44deb74SJosef Bacik 				if (ret2 < 0) {
2146f44deb74SJosef Bacik 					btrfs_put_root(reloc_root);
2147f44deb74SJosef Bacik 					if (!ret)
2148f28de8d8SJosef Bacik 						ret = ret2;
2149f28de8d8SJosef Bacik 				}
2150f44deb74SJosef Bacik 			}
215100246528SJosef Bacik 			btrfs_put_root(root);
215230d40577SQu Wenruo 		} else {
215330d40577SQu Wenruo 			/* Orphan reloc tree, just clean it up */
21540078a9f9SNikolay Borisov 			ret2 = btrfs_drop_snapshot(root, 0, 1);
2155f44deb74SJosef Bacik 			if (ret2 < 0) {
2156f44deb74SJosef Bacik 				btrfs_put_root(root);
2157f44deb74SJosef Bacik 				if (!ret)
215830d40577SQu Wenruo 					ret = ret2;
215930d40577SQu Wenruo 			}
2160d2311e69SQu Wenruo 		}
2161f44deb74SJosef Bacik 	}
2162d2311e69SQu Wenruo 	return ret;
2163d2311e69SQu Wenruo }
2164d2311e69SQu Wenruo 
2165d2311e69SQu Wenruo /*
21665d4f98a2SYan Zheng  * merge the relocated tree blocks in reloc tree with corresponding
21675d4f98a2SYan Zheng  * fs tree.
21685d4f98a2SYan Zheng  */
21695d4f98a2SYan Zheng static noinline_for_stack int merge_reloc_root(struct reloc_control *rc,
21705d4f98a2SYan Zheng 					       struct btrfs_root *root)
21715d4f98a2SYan Zheng {
21720b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
21735d4f98a2SYan Zheng 	struct btrfs_key key;
21745d4f98a2SYan Zheng 	struct btrfs_key next_key;
21759e6a0c52SJosef Bacik 	struct btrfs_trans_handle *trans = NULL;
21765d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
21775d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
21785d4f98a2SYan Zheng 	struct btrfs_path *path;
21793fd0a558SYan, Zheng 	struct extent_buffer *leaf;
21805d4f98a2SYan Zheng 	int level;
21815d4f98a2SYan Zheng 	int max_level;
21825d4f98a2SYan Zheng 	int replaced = 0;
21835d4f98a2SYan Zheng 	int ret;
21845d4f98a2SYan Zheng 	int err = 0;
21853fd0a558SYan, Zheng 	u32 min_reserved;
21865d4f98a2SYan Zheng 
21875d4f98a2SYan Zheng 	path = btrfs_alloc_path();
21885d4f98a2SYan Zheng 	if (!path)
21895d4f98a2SYan Zheng 		return -ENOMEM;
2190e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
21915d4f98a2SYan Zheng 
21925d4f98a2SYan Zheng 	reloc_root = root->reloc_root;
21935d4f98a2SYan Zheng 	root_item = &reloc_root->root_item;
21945d4f98a2SYan Zheng 
21955d4f98a2SYan Zheng 	if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
21965d4f98a2SYan Zheng 		level = btrfs_root_level(root_item);
219767439dadSDavid Sterba 		atomic_inc(&reloc_root->node->refs);
21985d4f98a2SYan Zheng 		path->nodes[level] = reloc_root->node;
21995d4f98a2SYan Zheng 		path->slots[level] = 0;
22005d4f98a2SYan Zheng 	} else {
22015d4f98a2SYan Zheng 		btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
22025d4f98a2SYan Zheng 
22035d4f98a2SYan Zheng 		level = root_item->drop_level;
22045d4f98a2SYan Zheng 		BUG_ON(level == 0);
22055d4f98a2SYan Zheng 		path->lowest_level = level;
22065d4f98a2SYan Zheng 		ret = btrfs_search_slot(NULL, reloc_root, &key, path, 0, 0);
220733c66f43SYan Zheng 		path->lowest_level = 0;
22085d4f98a2SYan Zheng 		if (ret < 0) {
22095d4f98a2SYan Zheng 			btrfs_free_path(path);
22105d4f98a2SYan Zheng 			return ret;
22115d4f98a2SYan Zheng 		}
22125d4f98a2SYan Zheng 
22135d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(path->nodes[level], &next_key,
22145d4f98a2SYan Zheng 				      path->slots[level]);
22155d4f98a2SYan Zheng 		WARN_ON(memcmp(&key, &next_key, sizeof(key)));
22165d4f98a2SYan Zheng 
22175d4f98a2SYan Zheng 		btrfs_unlock_up_safe(path, 0);
22185d4f98a2SYan Zheng 	}
22195d4f98a2SYan Zheng 
22200b246afaSJeff Mahoney 	min_reserved = fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
22215d4f98a2SYan Zheng 	memset(&next_key, 0, sizeof(next_key));
22225d4f98a2SYan Zheng 
22235d4f98a2SYan Zheng 	while (1) {
222408e007d2SMiao Xie 		ret = btrfs_block_rsv_refill(root, rc->block_rsv, min_reserved,
222508e007d2SMiao Xie 					     BTRFS_RESERVE_FLUSH_ALL);
22263fd0a558SYan, Zheng 		if (ret) {
22279e6a0c52SJosef Bacik 			err = ret;
22289e6a0c52SJosef Bacik 			goto out;
22293fd0a558SYan, Zheng 		}
22309e6a0c52SJosef Bacik 		trans = btrfs_start_transaction(root, 0);
22319e6a0c52SJosef Bacik 		if (IS_ERR(trans)) {
22329e6a0c52SJosef Bacik 			err = PTR_ERR(trans);
22339e6a0c52SJosef Bacik 			trans = NULL;
22349e6a0c52SJosef Bacik 			goto out;
22359e6a0c52SJosef Bacik 		}
22362abc726aSJosef Bacik 
22372abc726aSJosef Bacik 		/*
22382abc726aSJosef Bacik 		 * At this point we no longer have a reloc_control, so we can't
22392abc726aSJosef Bacik 		 * depend on btrfs_init_reloc_root to update our last_trans.
22402abc726aSJosef Bacik 		 *
22412abc726aSJosef Bacik 		 * But that's ok, we started the trans handle on our
22422abc726aSJosef Bacik 		 * corresponding fs_root, which means it's been added to the
22432abc726aSJosef Bacik 		 * dirty list.  At commit time we'll still call
22442abc726aSJosef Bacik 		 * btrfs_update_reloc_root() and update our root item
22452abc726aSJosef Bacik 		 * appropriately.
22462abc726aSJosef Bacik 		 */
22472abc726aSJosef Bacik 		reloc_root->last_trans = trans->transid;
22489e6a0c52SJosef Bacik 		trans->block_rsv = rc->block_rsv;
22493fd0a558SYan, Zheng 
22503fd0a558SYan, Zheng 		replaced = 0;
22515d4f98a2SYan Zheng 		max_level = level;
22525d4f98a2SYan Zheng 
22535d4f98a2SYan Zheng 		ret = walk_down_reloc_tree(reloc_root, path, &level);
22545d4f98a2SYan Zheng 		if (ret < 0) {
22555d4f98a2SYan Zheng 			err = ret;
22565d4f98a2SYan Zheng 			goto out;
22575d4f98a2SYan Zheng 		}
22585d4f98a2SYan Zheng 		if (ret > 0)
22595d4f98a2SYan Zheng 			break;
22605d4f98a2SYan Zheng 
22615d4f98a2SYan Zheng 		if (!find_next_key(path, level, &key) &&
22625d4f98a2SYan Zheng 		    btrfs_comp_cpu_keys(&next_key, &key) >= 0) {
22635d4f98a2SYan Zheng 			ret = 0;
22645d4f98a2SYan Zheng 		} else {
22653d0174f7SQu Wenruo 			ret = replace_path(trans, rc, root, reloc_root, path,
22663fd0a558SYan, Zheng 					   &next_key, level, max_level);
22675d4f98a2SYan Zheng 		}
22685d4f98a2SYan Zheng 		if (ret < 0) {
22695d4f98a2SYan Zheng 			err = ret;
22705d4f98a2SYan Zheng 			goto out;
22715d4f98a2SYan Zheng 		}
22725d4f98a2SYan Zheng 
22735d4f98a2SYan Zheng 		if (ret > 0) {
22745d4f98a2SYan Zheng 			level = ret;
22755d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(path->nodes[level], &key,
22765d4f98a2SYan Zheng 					      path->slots[level]);
22775d4f98a2SYan Zheng 			replaced = 1;
22785d4f98a2SYan Zheng 		}
22795d4f98a2SYan Zheng 
22805d4f98a2SYan Zheng 		ret = walk_up_reloc_tree(reloc_root, path, &level);
22815d4f98a2SYan Zheng 		if (ret > 0)
22825d4f98a2SYan Zheng 			break;
22835d4f98a2SYan Zheng 
22845d4f98a2SYan Zheng 		BUG_ON(level == 0);
22855d4f98a2SYan Zheng 		/*
22865d4f98a2SYan Zheng 		 * save the merging progress in the drop_progress.
22875d4f98a2SYan Zheng 		 * this is OK since root refs == 1 in this case.
22885d4f98a2SYan Zheng 		 */
22895d4f98a2SYan Zheng 		btrfs_node_key(path->nodes[level], &root_item->drop_progress,
22905d4f98a2SYan Zheng 			       path->slots[level]);
22915d4f98a2SYan Zheng 		root_item->drop_level = level;
22925d4f98a2SYan Zheng 
22933a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
22949e6a0c52SJosef Bacik 		trans = NULL;
22955d4f98a2SYan Zheng 
22962ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
22975d4f98a2SYan Zheng 
22985d4f98a2SYan Zheng 		if (replaced && rc->stage == UPDATE_DATA_PTRS)
22995d4f98a2SYan Zheng 			invalidate_extent_cache(root, &key, &next_key);
23005d4f98a2SYan Zheng 	}
23015d4f98a2SYan Zheng 
23025d4f98a2SYan Zheng 	/*
23035d4f98a2SYan Zheng 	 * handle the case only one block in the fs tree need to be
23045d4f98a2SYan Zheng 	 * relocated and the block is tree root.
23055d4f98a2SYan Zheng 	 */
23065d4f98a2SYan Zheng 	leaf = btrfs_lock_root_node(root);
23075d4f98a2SYan Zheng 	ret = btrfs_cow_block(trans, root, leaf, NULL, 0, &leaf);
23085d4f98a2SYan Zheng 	btrfs_tree_unlock(leaf);
23095d4f98a2SYan Zheng 	free_extent_buffer(leaf);
23105d4f98a2SYan Zheng 	if (ret < 0)
23115d4f98a2SYan Zheng 		err = ret;
23125d4f98a2SYan Zheng out:
23135d4f98a2SYan Zheng 	btrfs_free_path(path);
23145d4f98a2SYan Zheng 
2315d2311e69SQu Wenruo 	if (err == 0)
2316d2311e69SQu Wenruo 		insert_dirty_subvol(trans, rc, root);
23175d4f98a2SYan Zheng 
23189e6a0c52SJosef Bacik 	if (trans)
23193a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
23205d4f98a2SYan Zheng 
23212ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
23225d4f98a2SYan Zheng 
23235d4f98a2SYan Zheng 	if (replaced && rc->stage == UPDATE_DATA_PTRS)
23245d4f98a2SYan Zheng 		invalidate_extent_cache(root, &key, &next_key);
23255d4f98a2SYan Zheng 
23265d4f98a2SYan Zheng 	return err;
23275d4f98a2SYan Zheng }
23285d4f98a2SYan Zheng 
23293fd0a558SYan, Zheng static noinline_for_stack
23303fd0a558SYan, Zheng int prepare_to_merge(struct reloc_control *rc, int err)
23315d4f98a2SYan Zheng {
23323fd0a558SYan, Zheng 	struct btrfs_root *root = rc->extent_root;
23330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
23343fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
23355d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
23363fd0a558SYan, Zheng 	LIST_HEAD(reloc_roots);
23373fd0a558SYan, Zheng 	u64 num_bytes = 0;
23383fd0a558SYan, Zheng 	int ret;
23393fd0a558SYan, Zheng 
23400b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
23410b246afaSJeff Mahoney 	rc->merging_rsv_size += fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
23423fd0a558SYan, Zheng 	rc->merging_rsv_size += rc->nodes_relocated * 2;
23430b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
23447585717fSChris Mason 
23453fd0a558SYan, Zheng again:
23463fd0a558SYan, Zheng 	if (!err) {
23473fd0a558SYan, Zheng 		num_bytes = rc->merging_rsv_size;
234808e007d2SMiao Xie 		ret = btrfs_block_rsv_add(root, rc->block_rsv, num_bytes,
234908e007d2SMiao Xie 					  BTRFS_RESERVE_FLUSH_ALL);
23503fd0a558SYan, Zheng 		if (ret)
23513fd0a558SYan, Zheng 			err = ret;
23523fd0a558SYan, Zheng 	}
23533fd0a558SYan, Zheng 
23547a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
23553612b495STsutomu Itoh 	if (IS_ERR(trans)) {
23563612b495STsutomu Itoh 		if (!err)
23572ff7e61eSJeff Mahoney 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
235863f018beSNikolay Borisov 						num_bytes, NULL);
23593612b495STsutomu Itoh 		return PTR_ERR(trans);
23603612b495STsutomu Itoh 	}
23613fd0a558SYan, Zheng 
23623fd0a558SYan, Zheng 	if (!err) {
23633fd0a558SYan, Zheng 		if (num_bytes != rc->merging_rsv_size) {
23643a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
23652ff7e61eSJeff Mahoney 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
236663f018beSNikolay Borisov 						num_bytes, NULL);
23673fd0a558SYan, Zheng 			goto again;
23683fd0a558SYan, Zheng 		}
23693fd0a558SYan, Zheng 	}
23703fd0a558SYan, Zheng 
23713fd0a558SYan, Zheng 	rc->merge_reloc_tree = 1;
23723fd0a558SYan, Zheng 
23733fd0a558SYan, Zheng 	while (!list_empty(&rc->reloc_roots)) {
23743fd0a558SYan, Zheng 		reloc_root = list_entry(rc->reloc_roots.next,
23753fd0a558SYan, Zheng 					struct btrfs_root, root_list);
23763fd0a558SYan, Zheng 		list_del_init(&reloc_root->root_list);
23773fd0a558SYan, Zheng 
23780b246afaSJeff Mahoney 		root = read_fs_root(fs_info, reloc_root->root_key.offset);
23793fd0a558SYan, Zheng 		BUG_ON(IS_ERR(root));
23803fd0a558SYan, Zheng 		BUG_ON(root->reloc_root != reloc_root);
23813fd0a558SYan, Zheng 
23823fd0a558SYan, Zheng 		/*
23833fd0a558SYan, Zheng 		 * set reference count to 1, so btrfs_recover_relocation
23843fd0a558SYan, Zheng 		 * knows it should resumes merging
23853fd0a558SYan, Zheng 		 */
23863fd0a558SYan, Zheng 		if (!err)
23873fd0a558SYan, Zheng 			btrfs_set_root_refs(&reloc_root->root_item, 1);
23883fd0a558SYan, Zheng 		btrfs_update_reloc_root(trans, root);
23893fd0a558SYan, Zheng 
23903fd0a558SYan, Zheng 		list_add(&reloc_root->root_list, &reloc_roots);
239100246528SJosef Bacik 		btrfs_put_root(root);
23923fd0a558SYan, Zheng 	}
23933fd0a558SYan, Zheng 
23943fd0a558SYan, Zheng 	list_splice(&reloc_roots, &rc->reloc_roots);
23953fd0a558SYan, Zheng 
23963fd0a558SYan, Zheng 	if (!err)
23973a45bb20SJeff Mahoney 		btrfs_commit_transaction(trans);
23983fd0a558SYan, Zheng 	else
23993a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
24003fd0a558SYan, Zheng 	return err;
24013fd0a558SYan, Zheng }
24023fd0a558SYan, Zheng 
24033fd0a558SYan, Zheng static noinline_for_stack
2404aca1bba6SLiu Bo void free_reloc_roots(struct list_head *list)
2405aca1bba6SLiu Bo {
2406aca1bba6SLiu Bo 	struct btrfs_root *reloc_root;
2407aca1bba6SLiu Bo 
2408aca1bba6SLiu Bo 	while (!list_empty(list)) {
2409aca1bba6SLiu Bo 		reloc_root = list_entry(list->next, struct btrfs_root,
2410aca1bba6SLiu Bo 					root_list);
2411bb166d72SNaohiro Aota 		__del_reloc_root(reloc_root);
2412aca1bba6SLiu Bo 	}
2413aca1bba6SLiu Bo }
2414aca1bba6SLiu Bo 
2415aca1bba6SLiu Bo static noinline_for_stack
241694404e82SDavid Sterba void merge_reloc_roots(struct reloc_control *rc)
24173fd0a558SYan, Zheng {
24180b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
24195d4f98a2SYan Zheng 	struct btrfs_root *root;
24205d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
24213fd0a558SYan, Zheng 	LIST_HEAD(reloc_roots);
24223fd0a558SYan, Zheng 	int found = 0;
2423aca1bba6SLiu Bo 	int ret = 0;
24243fd0a558SYan, Zheng again:
24253fd0a558SYan, Zheng 	root = rc->extent_root;
24267585717fSChris Mason 
24277585717fSChris Mason 	/*
24287585717fSChris Mason 	 * this serializes us with btrfs_record_root_in_transaction,
24297585717fSChris Mason 	 * we have to make sure nobody is in the middle of
24307585717fSChris Mason 	 * adding their roots to the list while we are
24317585717fSChris Mason 	 * doing this splice
24327585717fSChris Mason 	 */
24330b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
24343fd0a558SYan, Zheng 	list_splice_init(&rc->reloc_roots, &reloc_roots);
24350b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
24365d4f98a2SYan Zheng 
24373fd0a558SYan, Zheng 	while (!list_empty(&reloc_roots)) {
24383fd0a558SYan, Zheng 		found = 1;
24393fd0a558SYan, Zheng 		reloc_root = list_entry(reloc_roots.next,
24403fd0a558SYan, Zheng 					struct btrfs_root, root_list);
24415d4f98a2SYan Zheng 
24425d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
24430b246afaSJeff Mahoney 			root = read_fs_root(fs_info,
24445d4f98a2SYan Zheng 					    reloc_root->root_key.offset);
24455d4f98a2SYan Zheng 			BUG_ON(IS_ERR(root));
24465d4f98a2SYan Zheng 			BUG_ON(root->reloc_root != reloc_root);
24475d4f98a2SYan Zheng 
24483fd0a558SYan, Zheng 			ret = merge_reloc_root(rc, root);
244900246528SJosef Bacik 			btrfs_put_root(root);
2450b37b39cdSJosef Bacik 			if (ret) {
245125e293c2SWang Shilong 				if (list_empty(&reloc_root->root_list))
245225e293c2SWang Shilong 					list_add_tail(&reloc_root->root_list,
245325e293c2SWang Shilong 						      &reloc_roots);
2454aca1bba6SLiu Bo 				goto out;
2455b37b39cdSJosef Bacik 			}
24563fd0a558SYan, Zheng 		} else {
24573fd0a558SYan, Zheng 			list_del_init(&reloc_root->root_list);
245830d40577SQu Wenruo 			/* Don't forget to queue this reloc root for cleanup */
245930d40577SQu Wenruo 			list_add_tail(&reloc_root->reloc_dirty_list,
246030d40577SQu Wenruo 				      &rc->dirty_subvol_roots);
24613fd0a558SYan, Zheng 		}
24625d4f98a2SYan Zheng 	}
24635d4f98a2SYan Zheng 
24643fd0a558SYan, Zheng 	if (found) {
24653fd0a558SYan, Zheng 		found = 0;
24663fd0a558SYan, Zheng 		goto again;
24675d4f98a2SYan Zheng 	}
2468aca1bba6SLiu Bo out:
2469aca1bba6SLiu Bo 	if (ret) {
24700b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret, NULL);
2471aca1bba6SLiu Bo 		if (!list_empty(&reloc_roots))
2472aca1bba6SLiu Bo 			free_reloc_roots(&reloc_roots);
2473467bb1d2SWang Shilong 
2474467bb1d2SWang Shilong 		/* new reloc root may be added */
24750b246afaSJeff Mahoney 		mutex_lock(&fs_info->reloc_mutex);
2476467bb1d2SWang Shilong 		list_splice_init(&rc->reloc_roots, &reloc_roots);
24770b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
2478467bb1d2SWang Shilong 		if (!list_empty(&reloc_roots))
2479467bb1d2SWang Shilong 			free_reloc_roots(&reloc_roots);
2480aca1bba6SLiu Bo 	}
2481aca1bba6SLiu Bo 
24827b7b7431SJosef Bacik 	/*
24837b7b7431SJosef Bacik 	 * We used to have
24847b7b7431SJosef Bacik 	 *
24857b7b7431SJosef Bacik 	 * BUG_ON(!RB_EMPTY_ROOT(&rc->reloc_root_tree.rb_root));
24867b7b7431SJosef Bacik 	 *
24877b7b7431SJosef Bacik 	 * here, but it's wrong.  If we fail to start the transaction in
24887b7b7431SJosef Bacik 	 * prepare_to_merge() we will have only 0 ref reloc roots, none of which
24897b7b7431SJosef Bacik 	 * have actually been removed from the reloc_root_tree rb tree.  This is
24907b7b7431SJosef Bacik 	 * fine because we're bailing here, and we hold a reference on the root
24917b7b7431SJosef Bacik 	 * for the list that holds it, so these roots will be cleaned up when we
24927b7b7431SJosef Bacik 	 * do the reloc_dirty_list afterwards.  Meanwhile the root->reloc_root
24937b7b7431SJosef Bacik 	 * will be cleaned up on unmount.
24947b7b7431SJosef Bacik 	 *
24957b7b7431SJosef Bacik 	 * The remaining nodes will be cleaned up by free_reloc_control.
24967b7b7431SJosef Bacik 	 */
24975d4f98a2SYan Zheng }
24985d4f98a2SYan Zheng 
24995d4f98a2SYan Zheng static void free_block_list(struct rb_root *blocks)
25005d4f98a2SYan Zheng {
25015d4f98a2SYan Zheng 	struct tree_block *block;
25025d4f98a2SYan Zheng 	struct rb_node *rb_node;
25035d4f98a2SYan Zheng 	while ((rb_node = rb_first(blocks))) {
25045d4f98a2SYan Zheng 		block = rb_entry(rb_node, struct tree_block, rb_node);
25055d4f98a2SYan Zheng 		rb_erase(rb_node, blocks);
25065d4f98a2SYan Zheng 		kfree(block);
25075d4f98a2SYan Zheng 	}
25085d4f98a2SYan Zheng }
25095d4f98a2SYan Zheng 
25105d4f98a2SYan Zheng static int record_reloc_root_in_trans(struct btrfs_trans_handle *trans,
25115d4f98a2SYan Zheng 				      struct btrfs_root *reloc_root)
25125d4f98a2SYan Zheng {
25130b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = reloc_root->fs_info;
25145d4f98a2SYan Zheng 	struct btrfs_root *root;
2515442b1ac5SJosef Bacik 	int ret;
25165d4f98a2SYan Zheng 
25175d4f98a2SYan Zheng 	if (reloc_root->last_trans == trans->transid)
25185d4f98a2SYan Zheng 		return 0;
25195d4f98a2SYan Zheng 
25200b246afaSJeff Mahoney 	root = read_fs_root(fs_info, reloc_root->root_key.offset);
25215d4f98a2SYan Zheng 	BUG_ON(IS_ERR(root));
25225d4f98a2SYan Zheng 	BUG_ON(root->reloc_root != reloc_root);
2523442b1ac5SJosef Bacik 	ret = btrfs_record_root_in_trans(trans, root);
252400246528SJosef Bacik 	btrfs_put_root(root);
25255d4f98a2SYan Zheng 
2526442b1ac5SJosef Bacik 	return ret;
25275d4f98a2SYan Zheng }
25285d4f98a2SYan Zheng 
25293fd0a558SYan, Zheng static noinline_for_stack
25303fd0a558SYan, Zheng struct btrfs_root *select_reloc_root(struct btrfs_trans_handle *trans,
25313fd0a558SYan, Zheng 				     struct reloc_control *rc,
2532a26195a5SQu Wenruo 				     struct btrfs_backref_node *node,
2533a26195a5SQu Wenruo 				     struct btrfs_backref_edge *edges[])
25345d4f98a2SYan Zheng {
2535a26195a5SQu Wenruo 	struct btrfs_backref_node *next;
25365d4f98a2SYan Zheng 	struct btrfs_root *root;
25373fd0a558SYan, Zheng 	int index = 0;
25383fd0a558SYan, Zheng 
25395d4f98a2SYan Zheng 	next = node;
25405d4f98a2SYan Zheng 	while (1) {
25415d4f98a2SYan Zheng 		cond_resched();
25425d4f98a2SYan Zheng 		next = walk_up_backref(next, edges, &index);
25435d4f98a2SYan Zheng 		root = next->root;
25443fd0a558SYan, Zheng 		BUG_ON(!root);
254527cdeb70SMiao Xie 		BUG_ON(!test_bit(BTRFS_ROOT_REF_COWS, &root->state));
25465d4f98a2SYan Zheng 
25475d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
25485d4f98a2SYan Zheng 			record_reloc_root_in_trans(trans, root);
25495d4f98a2SYan Zheng 			break;
25505d4f98a2SYan Zheng 		}
25515d4f98a2SYan Zheng 
25525d4f98a2SYan Zheng 		btrfs_record_root_in_trans(trans, root);
25533fd0a558SYan, Zheng 		root = root->reloc_root;
25543fd0a558SYan, Zheng 
25553fd0a558SYan, Zheng 		if (next->new_bytenr != root->node->start) {
25563fd0a558SYan, Zheng 			BUG_ON(next->new_bytenr);
25573fd0a558SYan, Zheng 			BUG_ON(!list_empty(&next->list));
25583fd0a558SYan, Zheng 			next->new_bytenr = root->node->start;
255900246528SJosef Bacik 			btrfs_put_root(next->root);
256000246528SJosef Bacik 			next->root = btrfs_grab_root(root);
25610b530bc5SJosef Bacik 			ASSERT(next->root);
25623fd0a558SYan, Zheng 			list_add_tail(&next->list,
25633fd0a558SYan, Zheng 				      &rc->backref_cache.changed);
25649569cc20SQu Wenruo 			mark_block_processed(rc, next);
25655d4f98a2SYan Zheng 			break;
25665d4f98a2SYan Zheng 		}
25675d4f98a2SYan Zheng 
25683fd0a558SYan, Zheng 		WARN_ON(1);
25695d4f98a2SYan Zheng 		root = NULL;
25705d4f98a2SYan Zheng 		next = walk_down_backref(edges, &index);
25715d4f98a2SYan Zheng 		if (!next || next->level <= node->level)
25725d4f98a2SYan Zheng 			break;
25735d4f98a2SYan Zheng 	}
25743fd0a558SYan, Zheng 	if (!root)
25753fd0a558SYan, Zheng 		return NULL;
25765d4f98a2SYan Zheng 
25773fd0a558SYan, Zheng 	next = node;
25783fd0a558SYan, Zheng 	/* setup backref node path for btrfs_reloc_cow_block */
25793fd0a558SYan, Zheng 	while (1) {
25803fd0a558SYan, Zheng 		rc->backref_cache.path[next->level] = next;
25813fd0a558SYan, Zheng 		if (--index < 0)
25823fd0a558SYan, Zheng 			break;
25833fd0a558SYan, Zheng 		next = edges[index]->node[UPPER];
25843fd0a558SYan, Zheng 	}
25855d4f98a2SYan Zheng 	return root;
25865d4f98a2SYan Zheng }
25875d4f98a2SYan Zheng 
25883fd0a558SYan, Zheng /*
25893fd0a558SYan, Zheng  * select a tree root for relocation. return NULL if the block
25903fd0a558SYan, Zheng  * is reference counted. we should use do_relocation() in this
25913fd0a558SYan, Zheng  * case. return a tree root pointer if the block isn't reference
25923fd0a558SYan, Zheng  * counted. return -ENOENT if the block is root of reloc tree.
25933fd0a558SYan, Zheng  */
25945d4f98a2SYan Zheng static noinline_for_stack
2595a26195a5SQu Wenruo struct btrfs_root *select_one_root(struct btrfs_backref_node *node)
25965d4f98a2SYan Zheng {
2597a26195a5SQu Wenruo 	struct btrfs_backref_node *next;
25983fd0a558SYan, Zheng 	struct btrfs_root *root;
25993fd0a558SYan, Zheng 	struct btrfs_root *fs_root = NULL;
2600a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
26013fd0a558SYan, Zheng 	int index = 0;
26023fd0a558SYan, Zheng 
26033fd0a558SYan, Zheng 	next = node;
26043fd0a558SYan, Zheng 	while (1) {
26053fd0a558SYan, Zheng 		cond_resched();
26063fd0a558SYan, Zheng 		next = walk_up_backref(next, edges, &index);
26073fd0a558SYan, Zheng 		root = next->root;
26083fd0a558SYan, Zheng 		BUG_ON(!root);
26093fd0a558SYan, Zheng 
261025985edcSLucas De Marchi 		/* no other choice for non-references counted tree */
261127cdeb70SMiao Xie 		if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
26123fd0a558SYan, Zheng 			return root;
26133fd0a558SYan, Zheng 
26143fd0a558SYan, Zheng 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID)
26153fd0a558SYan, Zheng 			fs_root = root;
26163fd0a558SYan, Zheng 
26173fd0a558SYan, Zheng 		if (next != node)
26183fd0a558SYan, Zheng 			return NULL;
26193fd0a558SYan, Zheng 
26203fd0a558SYan, Zheng 		next = walk_down_backref(edges, &index);
26213fd0a558SYan, Zheng 		if (!next || next->level <= node->level)
26223fd0a558SYan, Zheng 			break;
26233fd0a558SYan, Zheng 	}
26243fd0a558SYan, Zheng 
26253fd0a558SYan, Zheng 	if (!fs_root)
26263fd0a558SYan, Zheng 		return ERR_PTR(-ENOENT);
26273fd0a558SYan, Zheng 	return fs_root;
26285d4f98a2SYan Zheng }
26295d4f98a2SYan Zheng 
26305d4f98a2SYan Zheng static noinline_for_stack
26313fd0a558SYan, Zheng u64 calcu_metadata_size(struct reloc_control *rc,
2632a26195a5SQu Wenruo 			struct btrfs_backref_node *node, int reserve)
26335d4f98a2SYan Zheng {
26340b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2635a26195a5SQu Wenruo 	struct btrfs_backref_node *next = node;
2636a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2637a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
26383fd0a558SYan, Zheng 	u64 num_bytes = 0;
26393fd0a558SYan, Zheng 	int index = 0;
26405d4f98a2SYan Zheng 
26413fd0a558SYan, Zheng 	BUG_ON(reserve && node->processed);
26423fd0a558SYan, Zheng 
26433fd0a558SYan, Zheng 	while (next) {
26443fd0a558SYan, Zheng 		cond_resched();
26455d4f98a2SYan Zheng 		while (1) {
26463fd0a558SYan, Zheng 			if (next->processed && (reserve || next != node))
26475d4f98a2SYan Zheng 				break;
26485d4f98a2SYan Zheng 
26490b246afaSJeff Mahoney 			num_bytes += fs_info->nodesize;
26503fd0a558SYan, Zheng 
26513fd0a558SYan, Zheng 			if (list_empty(&next->upper))
26523fd0a558SYan, Zheng 				break;
26533fd0a558SYan, Zheng 
26543fd0a558SYan, Zheng 			edge = list_entry(next->upper.next,
2655a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[LOWER]);
26563fd0a558SYan, Zheng 			edges[index++] = edge;
26573fd0a558SYan, Zheng 			next = edge->node[UPPER];
26585d4f98a2SYan Zheng 		}
26593fd0a558SYan, Zheng 		next = walk_down_backref(edges, &index);
26603fd0a558SYan, Zheng 	}
26613fd0a558SYan, Zheng 	return num_bytes;
26623fd0a558SYan, Zheng }
26633fd0a558SYan, Zheng 
26643fd0a558SYan, Zheng static int reserve_metadata_space(struct btrfs_trans_handle *trans,
26653fd0a558SYan, Zheng 				  struct reloc_control *rc,
2666a26195a5SQu Wenruo 				  struct btrfs_backref_node *node)
26673fd0a558SYan, Zheng {
26683fd0a558SYan, Zheng 	struct btrfs_root *root = rc->extent_root;
2669da17066cSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
26703fd0a558SYan, Zheng 	u64 num_bytes;
26713fd0a558SYan, Zheng 	int ret;
26720647bf56SWang Shilong 	u64 tmp;
26733fd0a558SYan, Zheng 
26743fd0a558SYan, Zheng 	num_bytes = calcu_metadata_size(rc, node, 1) * 2;
26753fd0a558SYan, Zheng 
26763fd0a558SYan, Zheng 	trans->block_rsv = rc->block_rsv;
26770647bf56SWang Shilong 	rc->reserved_bytes += num_bytes;
26788ca17f0fSJosef Bacik 
26798ca17f0fSJosef Bacik 	/*
26808ca17f0fSJosef Bacik 	 * We are under a transaction here so we can only do limited flushing.
26818ca17f0fSJosef Bacik 	 * If we get an enospc just kick back -EAGAIN so we know to drop the
26828ca17f0fSJosef Bacik 	 * transaction and try to refill when we can flush all the things.
26838ca17f0fSJosef Bacik 	 */
26840647bf56SWang Shilong 	ret = btrfs_block_rsv_refill(root, rc->block_rsv, num_bytes,
26858ca17f0fSJosef Bacik 				BTRFS_RESERVE_FLUSH_LIMIT);
26863fd0a558SYan, Zheng 	if (ret) {
2687da17066cSJeff Mahoney 		tmp = fs_info->nodesize * RELOCATION_RESERVED_NODES;
26880647bf56SWang Shilong 		while (tmp <= rc->reserved_bytes)
26890647bf56SWang Shilong 			tmp <<= 1;
26900647bf56SWang Shilong 		/*
26910647bf56SWang Shilong 		 * only one thread can access block_rsv at this point,
26920647bf56SWang Shilong 		 * so we don't need hold lock to protect block_rsv.
26930647bf56SWang Shilong 		 * we expand more reservation size here to allow enough
269452042d8eSAndrea Gelmini 		 * space for relocation and we will return earlier in
26950647bf56SWang Shilong 		 * enospc case.
26960647bf56SWang Shilong 		 */
2697da17066cSJeff Mahoney 		rc->block_rsv->size = tmp + fs_info->nodesize *
26980647bf56SWang Shilong 				      RELOCATION_RESERVED_NODES;
26998ca17f0fSJosef Bacik 		return -EAGAIN;
27003fd0a558SYan, Zheng 	}
27013fd0a558SYan, Zheng 
27023fd0a558SYan, Zheng 	return 0;
27033fd0a558SYan, Zheng }
27043fd0a558SYan, Zheng 
27055d4f98a2SYan Zheng /*
27065d4f98a2SYan Zheng  * relocate a block tree, and then update pointers in upper level
27075d4f98a2SYan Zheng  * blocks that reference the block to point to the new location.
27085d4f98a2SYan Zheng  *
27095d4f98a2SYan Zheng  * if called by link_to_upper, the block has already been relocated.
27105d4f98a2SYan Zheng  * in that case this function just updates pointers.
27115d4f98a2SYan Zheng  */
27125d4f98a2SYan Zheng static int do_relocation(struct btrfs_trans_handle *trans,
27133fd0a558SYan, Zheng 			 struct reloc_control *rc,
2714a26195a5SQu Wenruo 			 struct btrfs_backref_node *node,
27155d4f98a2SYan Zheng 			 struct btrfs_key *key,
27165d4f98a2SYan Zheng 			 struct btrfs_path *path, int lowest)
27175d4f98a2SYan Zheng {
27182ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2719a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
2720a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2721a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
27225d4f98a2SYan Zheng 	struct btrfs_root *root;
27235d4f98a2SYan Zheng 	struct extent_buffer *eb;
27245d4f98a2SYan Zheng 	u32 blocksize;
27255d4f98a2SYan Zheng 	u64 bytenr;
27265d4f98a2SYan Zheng 	u64 generation;
27275d4f98a2SYan Zheng 	int slot;
27285d4f98a2SYan Zheng 	int ret;
27295d4f98a2SYan Zheng 	int err = 0;
27305d4f98a2SYan Zheng 
27315d4f98a2SYan Zheng 	BUG_ON(lowest && node->eb);
27325d4f98a2SYan Zheng 
27335d4f98a2SYan Zheng 	path->lowest_level = node->level + 1;
27343fd0a558SYan, Zheng 	rc->backref_cache.path[node->level] = node;
27355d4f98a2SYan Zheng 	list_for_each_entry(edge, &node->upper, list[LOWER]) {
2736581c1760SQu Wenruo 		struct btrfs_key first_key;
273782fa113fSQu Wenruo 		struct btrfs_ref ref = { 0 };
2738581c1760SQu Wenruo 
27395d4f98a2SYan Zheng 		cond_resched();
27405d4f98a2SYan Zheng 
27415d4f98a2SYan Zheng 		upper = edge->node[UPPER];
2742dc4103f9SWang Shilong 		root = select_reloc_root(trans, rc, upper, edges);
27433fd0a558SYan, Zheng 		BUG_ON(!root);
27445d4f98a2SYan Zheng 
27453fd0a558SYan, Zheng 		if (upper->eb && !upper->locked) {
27463fd0a558SYan, Zheng 			if (!lowest) {
27473fd0a558SYan, Zheng 				ret = btrfs_bin_search(upper->eb, key,
27483fd0a558SYan, Zheng 						       upper->level, &slot);
2749cbca7d59SFilipe Manana 				if (ret < 0) {
2750cbca7d59SFilipe Manana 					err = ret;
2751cbca7d59SFilipe Manana 					goto next;
2752cbca7d59SFilipe Manana 				}
27533fd0a558SYan, Zheng 				BUG_ON(ret);
27543fd0a558SYan, Zheng 				bytenr = btrfs_node_blockptr(upper->eb, slot);
27553fd0a558SYan, Zheng 				if (node->eb->start == bytenr)
27563fd0a558SYan, Zheng 					goto next;
27573fd0a558SYan, Zheng 			}
2758b0fe7078SQu Wenruo 			btrfs_backref_drop_node_buffer(upper);
27593fd0a558SYan, Zheng 		}
27605d4f98a2SYan Zheng 
27615d4f98a2SYan Zheng 		if (!upper->eb) {
27625d4f98a2SYan Zheng 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
27633561b9dbSLiu Bo 			if (ret) {
27643561b9dbSLiu Bo 				if (ret < 0)
27655d4f98a2SYan Zheng 					err = ret;
27663561b9dbSLiu Bo 				else
27673561b9dbSLiu Bo 					err = -ENOENT;
27683561b9dbSLiu Bo 
27693561b9dbSLiu Bo 				btrfs_release_path(path);
27705d4f98a2SYan Zheng 				break;
27715d4f98a2SYan Zheng 			}
27725d4f98a2SYan Zheng 
27733fd0a558SYan, Zheng 			if (!upper->eb) {
27743fd0a558SYan, Zheng 				upper->eb = path->nodes[upper->level];
27753fd0a558SYan, Zheng 				path->nodes[upper->level] = NULL;
27763fd0a558SYan, Zheng 			} else {
27773fd0a558SYan, Zheng 				BUG_ON(upper->eb != path->nodes[upper->level]);
27783fd0a558SYan, Zheng 			}
27793fd0a558SYan, Zheng 
27803fd0a558SYan, Zheng 			upper->locked = 1;
27813fd0a558SYan, Zheng 			path->locks[upper->level] = 0;
27823fd0a558SYan, Zheng 
27835d4f98a2SYan Zheng 			slot = path->slots[upper->level];
2784b3b4aa74SDavid Sterba 			btrfs_release_path(path);
27855d4f98a2SYan Zheng 		} else {
27865d4f98a2SYan Zheng 			ret = btrfs_bin_search(upper->eb, key, upper->level,
27875d4f98a2SYan Zheng 					       &slot);
2788cbca7d59SFilipe Manana 			if (ret < 0) {
2789cbca7d59SFilipe Manana 				err = ret;
2790cbca7d59SFilipe Manana 				goto next;
2791cbca7d59SFilipe Manana 			}
27925d4f98a2SYan Zheng 			BUG_ON(ret);
27935d4f98a2SYan Zheng 		}
27945d4f98a2SYan Zheng 
27955d4f98a2SYan Zheng 		bytenr = btrfs_node_blockptr(upper->eb, slot);
27963fd0a558SYan, Zheng 		if (lowest) {
27974547f4d8SLiu Bo 			if (bytenr != node->bytenr) {
27984547f4d8SLiu Bo 				btrfs_err(root->fs_info,
27994547f4d8SLiu Bo 		"lowest leaf/node mismatch: bytenr %llu node->bytenr %llu slot %d upper %llu",
28004547f4d8SLiu Bo 					  bytenr, node->bytenr, slot,
28014547f4d8SLiu Bo 					  upper->eb->start);
28024547f4d8SLiu Bo 				err = -EIO;
28034547f4d8SLiu Bo 				goto next;
28044547f4d8SLiu Bo 			}
28055d4f98a2SYan Zheng 		} else {
28063fd0a558SYan, Zheng 			if (node->eb->start == bytenr)
28073fd0a558SYan, Zheng 				goto next;
28085d4f98a2SYan Zheng 		}
28095d4f98a2SYan Zheng 
2810da17066cSJeff Mahoney 		blocksize = root->fs_info->nodesize;
28115d4f98a2SYan Zheng 		generation = btrfs_node_ptr_generation(upper->eb, slot);
2812581c1760SQu Wenruo 		btrfs_node_key_to_cpu(upper->eb, &first_key, slot);
2813581c1760SQu Wenruo 		eb = read_tree_block(fs_info, bytenr, generation,
2814581c1760SQu Wenruo 				     upper->level - 1, &first_key);
281564c043deSLiu Bo 		if (IS_ERR(eb)) {
281664c043deSLiu Bo 			err = PTR_ERR(eb);
281764c043deSLiu Bo 			goto next;
281864c043deSLiu Bo 		} else if (!extent_buffer_uptodate(eb)) {
2819416bc658SJosef Bacik 			free_extent_buffer(eb);
282097d9a8a4STsutomu Itoh 			err = -EIO;
282197d9a8a4STsutomu Itoh 			goto next;
282297d9a8a4STsutomu Itoh 		}
28235d4f98a2SYan Zheng 		btrfs_tree_lock(eb);
28248bead258SDavid Sterba 		btrfs_set_lock_blocking_write(eb);
28255d4f98a2SYan Zheng 
28265d4f98a2SYan Zheng 		if (!node->eb) {
28275d4f98a2SYan Zheng 			ret = btrfs_cow_block(trans, root, eb, upper->eb,
28285d4f98a2SYan Zheng 					      slot, &eb);
28293fd0a558SYan, Zheng 			btrfs_tree_unlock(eb);
28303fd0a558SYan, Zheng 			free_extent_buffer(eb);
28315d4f98a2SYan Zheng 			if (ret < 0) {
28325d4f98a2SYan Zheng 				err = ret;
28333fd0a558SYan, Zheng 				goto next;
28345d4f98a2SYan Zheng 			}
28353fd0a558SYan, Zheng 			BUG_ON(node->eb != eb);
28365d4f98a2SYan Zheng 		} else {
28375d4f98a2SYan Zheng 			btrfs_set_node_blockptr(upper->eb, slot,
28385d4f98a2SYan Zheng 						node->eb->start);
28395d4f98a2SYan Zheng 			btrfs_set_node_ptr_generation(upper->eb, slot,
28405d4f98a2SYan Zheng 						      trans->transid);
28415d4f98a2SYan Zheng 			btrfs_mark_buffer_dirty(upper->eb);
28425d4f98a2SYan Zheng 
284382fa113fSQu Wenruo 			btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF,
28445d4f98a2SYan Zheng 					       node->eb->start, blocksize,
284582fa113fSQu Wenruo 					       upper->eb->start);
284682fa113fSQu Wenruo 			ref.real_root = root->root_key.objectid;
284782fa113fSQu Wenruo 			btrfs_init_tree_ref(&ref, node->level,
284882fa113fSQu Wenruo 					    btrfs_header_owner(upper->eb));
284982fa113fSQu Wenruo 			ret = btrfs_inc_extent_ref(trans, &ref);
28505d4f98a2SYan Zheng 			BUG_ON(ret);
28515d4f98a2SYan Zheng 
28525d4f98a2SYan Zheng 			ret = btrfs_drop_subtree(trans, root, eb, upper->eb);
28535d4f98a2SYan Zheng 			BUG_ON(ret);
28545d4f98a2SYan Zheng 		}
28553fd0a558SYan, Zheng next:
28563fd0a558SYan, Zheng 		if (!upper->pending)
2857b0fe7078SQu Wenruo 			btrfs_backref_drop_node_buffer(upper);
28583fd0a558SYan, Zheng 		else
2859b0fe7078SQu Wenruo 			btrfs_backref_unlock_node_buffer(upper);
28603fd0a558SYan, Zheng 		if (err)
28613fd0a558SYan, Zheng 			break;
28625d4f98a2SYan Zheng 	}
28633fd0a558SYan, Zheng 
28643fd0a558SYan, Zheng 	if (!err && node->pending) {
2865b0fe7078SQu Wenruo 		btrfs_backref_drop_node_buffer(node);
28663fd0a558SYan, Zheng 		list_move_tail(&node->list, &rc->backref_cache.changed);
28673fd0a558SYan, Zheng 		node->pending = 0;
28685d4f98a2SYan Zheng 	}
28693fd0a558SYan, Zheng 
28705d4f98a2SYan Zheng 	path->lowest_level = 0;
28713fd0a558SYan, Zheng 	BUG_ON(err == -ENOSPC);
28725d4f98a2SYan Zheng 	return err;
28735d4f98a2SYan Zheng }
28745d4f98a2SYan Zheng 
28755d4f98a2SYan Zheng static int link_to_upper(struct btrfs_trans_handle *trans,
28763fd0a558SYan, Zheng 			 struct reloc_control *rc,
2877a26195a5SQu Wenruo 			 struct btrfs_backref_node *node,
28785d4f98a2SYan Zheng 			 struct btrfs_path *path)
28795d4f98a2SYan Zheng {
28805d4f98a2SYan Zheng 	struct btrfs_key key;
28815d4f98a2SYan Zheng 
28825d4f98a2SYan Zheng 	btrfs_node_key_to_cpu(node->eb, &key, 0);
28833fd0a558SYan, Zheng 	return do_relocation(trans, rc, node, &key, path, 0);
28845d4f98a2SYan Zheng }
28855d4f98a2SYan Zheng 
28865d4f98a2SYan Zheng static int finish_pending_nodes(struct btrfs_trans_handle *trans,
28873fd0a558SYan, Zheng 				struct reloc_control *rc,
28883fd0a558SYan, Zheng 				struct btrfs_path *path, int err)
28895d4f98a2SYan Zheng {
28903fd0a558SYan, Zheng 	LIST_HEAD(list);
2891a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
2892a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
28935d4f98a2SYan Zheng 	int level;
28945d4f98a2SYan Zheng 	int ret;
28955d4f98a2SYan Zheng 
28965d4f98a2SYan Zheng 	for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
28975d4f98a2SYan Zheng 		while (!list_empty(&cache->pending[level])) {
28985d4f98a2SYan Zheng 			node = list_entry(cache->pending[level].next,
2899a26195a5SQu Wenruo 					  struct btrfs_backref_node, list);
29003fd0a558SYan, Zheng 			list_move_tail(&node->list, &list);
29013fd0a558SYan, Zheng 			BUG_ON(!node->pending);
29025d4f98a2SYan Zheng 
29033fd0a558SYan, Zheng 			if (!err) {
29043fd0a558SYan, Zheng 				ret = link_to_upper(trans, rc, node, path);
29055d4f98a2SYan Zheng 				if (ret < 0)
29065d4f98a2SYan Zheng 					err = ret;
29075d4f98a2SYan Zheng 			}
29085d4f98a2SYan Zheng 		}
29093fd0a558SYan, Zheng 		list_splice_init(&list, &cache->pending[level]);
29103fd0a558SYan, Zheng 	}
29115d4f98a2SYan Zheng 	return err;
29125d4f98a2SYan Zheng }
29135d4f98a2SYan Zheng 
29145d4f98a2SYan Zheng /*
29155d4f98a2SYan Zheng  * mark a block and all blocks directly/indirectly reference the block
29165d4f98a2SYan Zheng  * as processed.
29175d4f98a2SYan Zheng  */
29185d4f98a2SYan Zheng static void update_processed_blocks(struct reloc_control *rc,
2919a26195a5SQu Wenruo 				    struct btrfs_backref_node *node)
29205d4f98a2SYan Zheng {
2921a26195a5SQu Wenruo 	struct btrfs_backref_node *next = node;
2922a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2923a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
29245d4f98a2SYan Zheng 	int index = 0;
29255d4f98a2SYan Zheng 
29265d4f98a2SYan Zheng 	while (next) {
29275d4f98a2SYan Zheng 		cond_resched();
29285d4f98a2SYan Zheng 		while (1) {
29295d4f98a2SYan Zheng 			if (next->processed)
29305d4f98a2SYan Zheng 				break;
29315d4f98a2SYan Zheng 
29329569cc20SQu Wenruo 			mark_block_processed(rc, next);
29335d4f98a2SYan Zheng 
29345d4f98a2SYan Zheng 			if (list_empty(&next->upper))
29355d4f98a2SYan Zheng 				break;
29365d4f98a2SYan Zheng 
29375d4f98a2SYan Zheng 			edge = list_entry(next->upper.next,
2938a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[LOWER]);
29395d4f98a2SYan Zheng 			edges[index++] = edge;
29405d4f98a2SYan Zheng 			next = edge->node[UPPER];
29415d4f98a2SYan Zheng 		}
29425d4f98a2SYan Zheng 		next = walk_down_backref(edges, &index);
29435d4f98a2SYan Zheng 	}
29445d4f98a2SYan Zheng }
29455d4f98a2SYan Zheng 
29467476dfdaSDavid Sterba static int tree_block_processed(u64 bytenr, struct reloc_control *rc)
29475d4f98a2SYan Zheng {
2948da17066cSJeff Mahoney 	u32 blocksize = rc->extent_root->fs_info->nodesize;
29497476dfdaSDavid Sterba 
29505d4f98a2SYan Zheng 	if (test_range_bit(&rc->processed_blocks, bytenr,
29519655d298SChris Mason 			   bytenr + blocksize - 1, EXTENT_DIRTY, 1, NULL))
29525d4f98a2SYan Zheng 		return 1;
29535d4f98a2SYan Zheng 	return 0;
29545d4f98a2SYan Zheng }
29555d4f98a2SYan Zheng 
29562ff7e61eSJeff Mahoney static int get_tree_block_key(struct btrfs_fs_info *fs_info,
29575d4f98a2SYan Zheng 			      struct tree_block *block)
29585d4f98a2SYan Zheng {
29595d4f98a2SYan Zheng 	struct extent_buffer *eb;
29605d4f98a2SYan Zheng 
2961581c1760SQu Wenruo 	eb = read_tree_block(fs_info, block->bytenr, block->key.offset,
2962581c1760SQu Wenruo 			     block->level, NULL);
296364c043deSLiu Bo 	if (IS_ERR(eb)) {
296464c043deSLiu Bo 		return PTR_ERR(eb);
296564c043deSLiu Bo 	} else if (!extent_buffer_uptodate(eb)) {
2966416bc658SJosef Bacik 		free_extent_buffer(eb);
2967416bc658SJosef Bacik 		return -EIO;
2968416bc658SJosef Bacik 	}
29695d4f98a2SYan Zheng 	if (block->level == 0)
29705d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(eb, &block->key, 0);
29715d4f98a2SYan Zheng 	else
29725d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(eb, &block->key, 0);
29735d4f98a2SYan Zheng 	free_extent_buffer(eb);
29745d4f98a2SYan Zheng 	block->key_ready = 1;
29755d4f98a2SYan Zheng 	return 0;
29765d4f98a2SYan Zheng }
29775d4f98a2SYan Zheng 
29785d4f98a2SYan Zheng /*
29795d4f98a2SYan Zheng  * helper function to relocate a tree block
29805d4f98a2SYan Zheng  */
29815d4f98a2SYan Zheng static int relocate_tree_block(struct btrfs_trans_handle *trans,
29825d4f98a2SYan Zheng 				struct reloc_control *rc,
2983a26195a5SQu Wenruo 				struct btrfs_backref_node *node,
29845d4f98a2SYan Zheng 				struct btrfs_key *key,
29855d4f98a2SYan Zheng 				struct btrfs_path *path)
29865d4f98a2SYan Zheng {
29875d4f98a2SYan Zheng 	struct btrfs_root *root;
29883fd0a558SYan, Zheng 	int ret = 0;
29895d4f98a2SYan Zheng 
29903fd0a558SYan, Zheng 	if (!node)
29915d4f98a2SYan Zheng 		return 0;
29923fd0a558SYan, Zheng 
29935f6b2e5cSJosef Bacik 	/*
29945f6b2e5cSJosef Bacik 	 * If we fail here we want to drop our backref_node because we are going
29955f6b2e5cSJosef Bacik 	 * to start over and regenerate the tree for it.
29965f6b2e5cSJosef Bacik 	 */
29975f6b2e5cSJosef Bacik 	ret = reserve_metadata_space(trans, rc, node);
29985f6b2e5cSJosef Bacik 	if (ret)
29995f6b2e5cSJosef Bacik 		goto out;
30005f6b2e5cSJosef Bacik 
30013fd0a558SYan, Zheng 	BUG_ON(node->processed);
3002147d256eSZhaolei 	root = select_one_root(node);
30033fd0a558SYan, Zheng 	if (root == ERR_PTR(-ENOENT)) {
30043fd0a558SYan, Zheng 		update_processed_blocks(rc, node);
30053fd0a558SYan, Zheng 		goto out;
30065d4f98a2SYan Zheng 	}
30075d4f98a2SYan Zheng 
30083fd0a558SYan, Zheng 	if (root) {
300927cdeb70SMiao Xie 		if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
30103fd0a558SYan, Zheng 			BUG_ON(node->new_bytenr);
30113fd0a558SYan, Zheng 			BUG_ON(!list_empty(&node->list));
30123fd0a558SYan, Zheng 			btrfs_record_root_in_trans(trans, root);
30133fd0a558SYan, Zheng 			root = root->reloc_root;
30143fd0a558SYan, Zheng 			node->new_bytenr = root->node->start;
301500246528SJosef Bacik 			btrfs_put_root(node->root);
301600246528SJosef Bacik 			node->root = btrfs_grab_root(root);
30170b530bc5SJosef Bacik 			ASSERT(node->root);
30183fd0a558SYan, Zheng 			list_add_tail(&node->list, &rc->backref_cache.changed);
30193fd0a558SYan, Zheng 		} else {
30205d4f98a2SYan Zheng 			path->lowest_level = node->level;
30215d4f98a2SYan Zheng 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
3022b3b4aa74SDavid Sterba 			btrfs_release_path(path);
30233fd0a558SYan, Zheng 			if (ret > 0)
30245d4f98a2SYan Zheng 				ret = 0;
30253fd0a558SYan, Zheng 		}
30263fd0a558SYan, Zheng 		if (!ret)
30273fd0a558SYan, Zheng 			update_processed_blocks(rc, node);
30283fd0a558SYan, Zheng 	} else {
30293fd0a558SYan, Zheng 		ret = do_relocation(trans, rc, node, key, path, 1);
30303fd0a558SYan, Zheng 	}
30315d4f98a2SYan Zheng out:
30320647bf56SWang Shilong 	if (ret || node->level == 0 || node->cowonly)
3033023acb07SQu Wenruo 		btrfs_backref_cleanup_node(&rc->backref_cache, node);
30345d4f98a2SYan Zheng 	return ret;
30355d4f98a2SYan Zheng }
30365d4f98a2SYan Zheng 
30375d4f98a2SYan Zheng /*
30385d4f98a2SYan Zheng  * relocate a list of blocks
30395d4f98a2SYan Zheng  */
30405d4f98a2SYan Zheng static noinline_for_stack
30415d4f98a2SYan Zheng int relocate_tree_blocks(struct btrfs_trans_handle *trans,
30425d4f98a2SYan Zheng 			 struct reloc_control *rc, struct rb_root *blocks)
30435d4f98a2SYan Zheng {
30442ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3045a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
30465d4f98a2SYan Zheng 	struct btrfs_path *path;
30475d4f98a2SYan Zheng 	struct tree_block *block;
304898ff7b94SQu Wenruo 	struct tree_block *next;
30495d4f98a2SYan Zheng 	int ret;
30505d4f98a2SYan Zheng 	int err = 0;
30515d4f98a2SYan Zheng 
30525d4f98a2SYan Zheng 	path = btrfs_alloc_path();
3053e1a12670SLiu Bo 	if (!path) {
3054e1a12670SLiu Bo 		err = -ENOMEM;
305534c2b290SDavid Sterba 		goto out_free_blocks;
3056e1a12670SLiu Bo 	}
30575d4f98a2SYan Zheng 
305898ff7b94SQu Wenruo 	/* Kick in readahead for tree blocks with missing keys */
305998ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
30605d4f98a2SYan Zheng 		if (!block->key_ready)
30612ff7e61eSJeff Mahoney 			readahead_tree_block(fs_info, block->bytenr);
30625d4f98a2SYan Zheng 	}
30635d4f98a2SYan Zheng 
306498ff7b94SQu Wenruo 	/* Get first keys */
306598ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
306634c2b290SDavid Sterba 		if (!block->key_ready) {
30672ff7e61eSJeff Mahoney 			err = get_tree_block_key(fs_info, block);
306834c2b290SDavid Sterba 			if (err)
306934c2b290SDavid Sterba 				goto out_free_path;
307034c2b290SDavid Sterba 		}
30715d4f98a2SYan Zheng 	}
30725d4f98a2SYan Zheng 
307398ff7b94SQu Wenruo 	/* Do tree relocation */
307498ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
30753fd0a558SYan, Zheng 		node = build_backref_tree(rc, &block->key,
30765d4f98a2SYan Zheng 					  block->level, block->bytenr);
30775d4f98a2SYan Zheng 		if (IS_ERR(node)) {
30785d4f98a2SYan Zheng 			err = PTR_ERR(node);
30795d4f98a2SYan Zheng 			goto out;
30805d4f98a2SYan Zheng 		}
30815d4f98a2SYan Zheng 
30825d4f98a2SYan Zheng 		ret = relocate_tree_block(trans, rc, node, &block->key,
30835d4f98a2SYan Zheng 					  path);
30845d4f98a2SYan Zheng 		if (ret < 0) {
30855d4f98a2SYan Zheng 			err = ret;
308650dbbb71SJosef Bacik 			break;
30875d4f98a2SYan Zheng 		}
30885d4f98a2SYan Zheng 	}
30895d4f98a2SYan Zheng out:
30903fd0a558SYan, Zheng 	err = finish_pending_nodes(trans, rc, path, err);
30915d4f98a2SYan Zheng 
309234c2b290SDavid Sterba out_free_path:
30935d4f98a2SYan Zheng 	btrfs_free_path(path);
309434c2b290SDavid Sterba out_free_blocks:
3095e1a12670SLiu Bo 	free_block_list(blocks);
30965d4f98a2SYan Zheng 	return err;
30975d4f98a2SYan Zheng }
30985d4f98a2SYan Zheng 
30995d4f98a2SYan Zheng static noinline_for_stack
3100efa56464SYan, Zheng int prealloc_file_extent_cluster(struct inode *inode,
3101efa56464SYan, Zheng 				 struct file_extent_cluster *cluster)
3102efa56464SYan, Zheng {
3103efa56464SYan, Zheng 	u64 alloc_hint = 0;
3104efa56464SYan, Zheng 	u64 start;
3105efa56464SYan, Zheng 	u64 end;
3106efa56464SYan, Zheng 	u64 offset = BTRFS_I(inode)->index_cnt;
3107efa56464SYan, Zheng 	u64 num_bytes;
3108efa56464SYan, Zheng 	int nr = 0;
3109efa56464SYan, Zheng 	int ret = 0;
3110dcb40c19SWang Xiaoguang 	u64 prealloc_start = cluster->start - offset;
3111dcb40c19SWang Xiaoguang 	u64 prealloc_end = cluster->end - offset;
311218513091SWang Xiaoguang 	u64 cur_offset;
3113364ecf36SQu Wenruo 	struct extent_changeset *data_reserved = NULL;
3114efa56464SYan, Zheng 
3115efa56464SYan, Zheng 	BUG_ON(cluster->start != cluster->boundary[0]);
31165955102cSAl Viro 	inode_lock(inode);
3117efa56464SYan, Zheng 
3118364ecf36SQu Wenruo 	ret = btrfs_check_data_free_space(inode, &data_reserved, prealloc_start,
3119dcb40c19SWang Xiaoguang 					  prealloc_end + 1 - prealloc_start);
3120efa56464SYan, Zheng 	if (ret)
3121efa56464SYan, Zheng 		goto out;
3122efa56464SYan, Zheng 
312318513091SWang Xiaoguang 	cur_offset = prealloc_start;
3124efa56464SYan, Zheng 	while (nr < cluster->nr) {
3125efa56464SYan, Zheng 		start = cluster->boundary[nr] - offset;
3126efa56464SYan, Zheng 		if (nr + 1 < cluster->nr)
3127efa56464SYan, Zheng 			end = cluster->boundary[nr + 1] - 1 - offset;
3128efa56464SYan, Zheng 		else
3129efa56464SYan, Zheng 			end = cluster->end - offset;
3130efa56464SYan, Zheng 
3131d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, start, end);
3132efa56464SYan, Zheng 		num_bytes = end + 1 - start;
313318513091SWang Xiaoguang 		if (cur_offset < start)
3134bc42bda2SQu Wenruo 			btrfs_free_reserved_data_space(inode, data_reserved,
3135bc42bda2SQu Wenruo 					cur_offset, start - cur_offset);
3136efa56464SYan, Zheng 		ret = btrfs_prealloc_file_range(inode, 0, start,
3137efa56464SYan, Zheng 						num_bytes, num_bytes,
3138efa56464SYan, Zheng 						end + 1, &alloc_hint);
313918513091SWang Xiaoguang 		cur_offset = end + 1;
3140d0082371SJeff Mahoney 		unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
3141efa56464SYan, Zheng 		if (ret)
3142efa56464SYan, Zheng 			break;
3143efa56464SYan, Zheng 		nr++;
3144efa56464SYan, Zheng 	}
314518513091SWang Xiaoguang 	if (cur_offset < prealloc_end)
3146bc42bda2SQu Wenruo 		btrfs_free_reserved_data_space(inode, data_reserved,
3147bc42bda2SQu Wenruo 				cur_offset, prealloc_end + 1 - cur_offset);
3148efa56464SYan, Zheng out:
31495955102cSAl Viro 	inode_unlock(inode);
3150364ecf36SQu Wenruo 	extent_changeset_free(data_reserved);
3151efa56464SYan, Zheng 	return ret;
3152efa56464SYan, Zheng }
3153efa56464SYan, Zheng 
3154efa56464SYan, Zheng static noinline_for_stack
31550257bb82SYan, Zheng int setup_extent_mapping(struct inode *inode, u64 start, u64 end,
31560257bb82SYan, Zheng 			 u64 block_start)
31575d4f98a2SYan Zheng {
31585d4f98a2SYan Zheng 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
31595d4f98a2SYan Zheng 	struct extent_map *em;
31600257bb82SYan, Zheng 	int ret = 0;
31615d4f98a2SYan Zheng 
3162172ddd60SDavid Sterba 	em = alloc_extent_map();
31630257bb82SYan, Zheng 	if (!em)
31640257bb82SYan, Zheng 		return -ENOMEM;
31650257bb82SYan, Zheng 
31665d4f98a2SYan Zheng 	em->start = start;
31670257bb82SYan, Zheng 	em->len = end + 1 - start;
31680257bb82SYan, Zheng 	em->block_len = em->len;
31690257bb82SYan, Zheng 	em->block_start = block_start;
31705d4f98a2SYan Zheng 	set_bit(EXTENT_FLAG_PINNED, &em->flags);
31715d4f98a2SYan Zheng 
3172d0082371SJeff Mahoney 	lock_extent(&BTRFS_I(inode)->io_tree, start, end);
31735d4f98a2SYan Zheng 	while (1) {
3174890871beSChris Mason 		write_lock(&em_tree->lock);
317509a2a8f9SJosef Bacik 		ret = add_extent_mapping(em_tree, em, 0);
3176890871beSChris Mason 		write_unlock(&em_tree->lock);
31775d4f98a2SYan Zheng 		if (ret != -EEXIST) {
31785d4f98a2SYan Zheng 			free_extent_map(em);
31795d4f98a2SYan Zheng 			break;
31805d4f98a2SYan Zheng 		}
3181dcdbc059SNikolay Borisov 		btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
31825d4f98a2SYan Zheng 	}
3183d0082371SJeff Mahoney 	unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
31840257bb82SYan, Zheng 	return ret;
31850257bb82SYan, Zheng }
31865d4f98a2SYan Zheng 
3187726a3421SQu Wenruo /*
3188726a3421SQu Wenruo  * Allow error injection to test balance cancellation
3189726a3421SQu Wenruo  */
3190726a3421SQu Wenruo int btrfs_should_cancel_balance(struct btrfs_fs_info *fs_info)
3191726a3421SQu Wenruo {
3192726a3421SQu Wenruo 	return atomic_read(&fs_info->balance_cancel_req);
3193726a3421SQu Wenruo }
3194726a3421SQu Wenruo ALLOW_ERROR_INJECTION(btrfs_should_cancel_balance, TRUE);
3195726a3421SQu Wenruo 
31960257bb82SYan, Zheng static int relocate_file_extent_cluster(struct inode *inode,
31970257bb82SYan, Zheng 					struct file_extent_cluster *cluster)
31980257bb82SYan, Zheng {
31992ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
32000257bb82SYan, Zheng 	u64 page_start;
32010257bb82SYan, Zheng 	u64 page_end;
32020257bb82SYan, Zheng 	u64 offset = BTRFS_I(inode)->index_cnt;
32030257bb82SYan, Zheng 	unsigned long index;
32040257bb82SYan, Zheng 	unsigned long last_index;
32050257bb82SYan, Zheng 	struct page *page;
32060257bb82SYan, Zheng 	struct file_ra_state *ra;
32073b16a4e3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
32080257bb82SYan, Zheng 	int nr = 0;
32090257bb82SYan, Zheng 	int ret = 0;
32100257bb82SYan, Zheng 
32110257bb82SYan, Zheng 	if (!cluster->nr)
32120257bb82SYan, Zheng 		return 0;
32130257bb82SYan, Zheng 
32140257bb82SYan, Zheng 	ra = kzalloc(sizeof(*ra), GFP_NOFS);
32150257bb82SYan, Zheng 	if (!ra)
32160257bb82SYan, Zheng 		return -ENOMEM;
32170257bb82SYan, Zheng 
3218efa56464SYan, Zheng 	ret = prealloc_file_extent_cluster(inode, cluster);
32190257bb82SYan, Zheng 	if (ret)
3220efa56464SYan, Zheng 		goto out;
32210257bb82SYan, Zheng 
32220257bb82SYan, Zheng 	file_ra_state_init(ra, inode->i_mapping);
32230257bb82SYan, Zheng 
3224efa56464SYan, Zheng 	ret = setup_extent_mapping(inode, cluster->start - offset,
3225efa56464SYan, Zheng 				   cluster->end - offset, cluster->start);
3226efa56464SYan, Zheng 	if (ret)
3227efa56464SYan, Zheng 		goto out;
3228efa56464SYan, Zheng 
322909cbfeafSKirill A. Shutemov 	index = (cluster->start - offset) >> PAGE_SHIFT;
323009cbfeafSKirill A. Shutemov 	last_index = (cluster->end - offset) >> PAGE_SHIFT;
32310257bb82SYan, Zheng 	while (index <= last_index) {
32329f3db423SNikolay Borisov 		ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
32339f3db423SNikolay Borisov 				PAGE_SIZE);
3234efa56464SYan, Zheng 		if (ret)
3235efa56464SYan, Zheng 			goto out;
3236efa56464SYan, Zheng 
32370257bb82SYan, Zheng 		page = find_lock_page(inode->i_mapping, index);
32380257bb82SYan, Zheng 		if (!page) {
32390257bb82SYan, Zheng 			page_cache_sync_readahead(inode->i_mapping,
32400257bb82SYan, Zheng 						  ra, NULL, index,
32410257bb82SYan, Zheng 						  last_index + 1 - index);
3242a94733d0SJosef Bacik 			page = find_or_create_page(inode->i_mapping, index,
32433b16a4e3SJosef Bacik 						   mask);
32440257bb82SYan, Zheng 			if (!page) {
3245691fa059SNikolay Borisov 				btrfs_delalloc_release_metadata(BTRFS_I(inode),
324643b18595SQu Wenruo 							PAGE_SIZE, true);
324744db1216SFilipe Manana 				btrfs_delalloc_release_extents(BTRFS_I(inode),
32488702ba93SQu Wenruo 							PAGE_SIZE);
32490257bb82SYan, Zheng 				ret = -ENOMEM;
3250efa56464SYan, Zheng 				goto out;
32510257bb82SYan, Zheng 			}
32520257bb82SYan, Zheng 		}
32530257bb82SYan, Zheng 
32540257bb82SYan, Zheng 		if (PageReadahead(page)) {
32550257bb82SYan, Zheng 			page_cache_async_readahead(inode->i_mapping,
32560257bb82SYan, Zheng 						   ra, NULL, page, index,
32570257bb82SYan, Zheng 						   last_index + 1 - index);
32580257bb82SYan, Zheng 		}
32590257bb82SYan, Zheng 
32600257bb82SYan, Zheng 		if (!PageUptodate(page)) {
32610257bb82SYan, Zheng 			btrfs_readpage(NULL, page);
32620257bb82SYan, Zheng 			lock_page(page);
32630257bb82SYan, Zheng 			if (!PageUptodate(page)) {
32640257bb82SYan, Zheng 				unlock_page(page);
326509cbfeafSKirill A. Shutemov 				put_page(page);
3266691fa059SNikolay Borisov 				btrfs_delalloc_release_metadata(BTRFS_I(inode),
326743b18595SQu Wenruo 							PAGE_SIZE, true);
32688b62f87bSJosef Bacik 				btrfs_delalloc_release_extents(BTRFS_I(inode),
32698702ba93SQu Wenruo 							       PAGE_SIZE);
32700257bb82SYan, Zheng 				ret = -EIO;
3271efa56464SYan, Zheng 				goto out;
32720257bb82SYan, Zheng 			}
32730257bb82SYan, Zheng 		}
32740257bb82SYan, Zheng 
32754eee4fa4SMiao Xie 		page_start = page_offset(page);
327609cbfeafSKirill A. Shutemov 		page_end = page_start + PAGE_SIZE - 1;
32770257bb82SYan, Zheng 
3278d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, page_start, page_end);
32790257bb82SYan, Zheng 
32800257bb82SYan, Zheng 		set_page_extent_mapped(page);
32810257bb82SYan, Zheng 
32820257bb82SYan, Zheng 		if (nr < cluster->nr &&
32830257bb82SYan, Zheng 		    page_start + offset == cluster->boundary[nr]) {
32840257bb82SYan, Zheng 			set_extent_bits(&BTRFS_I(inode)->io_tree,
32850257bb82SYan, Zheng 					page_start, page_end,
3286ceeb0ae7SDavid Sterba 					EXTENT_BOUNDARY);
32870257bb82SYan, Zheng 			nr++;
32880257bb82SYan, Zheng 		}
32890257bb82SYan, Zheng 
3290765f3cebSNikolay Borisov 		ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
3291330a5827SNikolay Borisov 						NULL);
3292765f3cebSNikolay Borisov 		if (ret) {
3293765f3cebSNikolay Borisov 			unlock_page(page);
3294765f3cebSNikolay Borisov 			put_page(page);
3295765f3cebSNikolay Borisov 			btrfs_delalloc_release_metadata(BTRFS_I(inode),
329643b18595SQu Wenruo 							 PAGE_SIZE, true);
3297765f3cebSNikolay Borisov 			btrfs_delalloc_release_extents(BTRFS_I(inode),
32988702ba93SQu Wenruo 			                               PAGE_SIZE);
3299765f3cebSNikolay Borisov 
3300765f3cebSNikolay Borisov 			clear_extent_bits(&BTRFS_I(inode)->io_tree,
3301765f3cebSNikolay Borisov 					  page_start, page_end,
3302765f3cebSNikolay Borisov 					  EXTENT_LOCKED | EXTENT_BOUNDARY);
3303765f3cebSNikolay Borisov 			goto out;
3304765f3cebSNikolay Borisov 
3305765f3cebSNikolay Borisov 		}
33060257bb82SYan, Zheng 		set_page_dirty(page);
33070257bb82SYan, Zheng 
33080257bb82SYan, Zheng 		unlock_extent(&BTRFS_I(inode)->io_tree,
3309d0082371SJeff Mahoney 			      page_start, page_end);
33100257bb82SYan, Zheng 		unlock_page(page);
331109cbfeafSKirill A. Shutemov 		put_page(page);
33120257bb82SYan, Zheng 
33130257bb82SYan, Zheng 		index++;
33148702ba93SQu Wenruo 		btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
3315efa56464SYan, Zheng 		balance_dirty_pages_ratelimited(inode->i_mapping);
33162ff7e61eSJeff Mahoney 		btrfs_throttle(fs_info);
33177f913c7cSQu Wenruo 		if (btrfs_should_cancel_balance(fs_info)) {
33187f913c7cSQu Wenruo 			ret = -ECANCELED;
33197f913c7cSQu Wenruo 			goto out;
33207f913c7cSQu Wenruo 		}
33210257bb82SYan, Zheng 	}
33220257bb82SYan, Zheng 	WARN_ON(nr != cluster->nr);
3323efa56464SYan, Zheng out:
33240257bb82SYan, Zheng 	kfree(ra);
33250257bb82SYan, Zheng 	return ret;
33260257bb82SYan, Zheng }
33270257bb82SYan, Zheng 
33280257bb82SYan, Zheng static noinline_for_stack
33290257bb82SYan, Zheng int relocate_data_extent(struct inode *inode, struct btrfs_key *extent_key,
33300257bb82SYan, Zheng 			 struct file_extent_cluster *cluster)
33310257bb82SYan, Zheng {
33320257bb82SYan, Zheng 	int ret;
33330257bb82SYan, Zheng 
33340257bb82SYan, Zheng 	if (cluster->nr > 0 && extent_key->objectid != cluster->end + 1) {
33350257bb82SYan, Zheng 		ret = relocate_file_extent_cluster(inode, cluster);
33360257bb82SYan, Zheng 		if (ret)
33370257bb82SYan, Zheng 			return ret;
33380257bb82SYan, Zheng 		cluster->nr = 0;
33390257bb82SYan, Zheng 	}
33400257bb82SYan, Zheng 
33410257bb82SYan, Zheng 	if (!cluster->nr)
33420257bb82SYan, Zheng 		cluster->start = extent_key->objectid;
33430257bb82SYan, Zheng 	else
33440257bb82SYan, Zheng 		BUG_ON(cluster->nr >= MAX_EXTENTS);
33450257bb82SYan, Zheng 	cluster->end = extent_key->objectid + extent_key->offset - 1;
33460257bb82SYan, Zheng 	cluster->boundary[cluster->nr] = extent_key->objectid;
33470257bb82SYan, Zheng 	cluster->nr++;
33480257bb82SYan, Zheng 
33490257bb82SYan, Zheng 	if (cluster->nr >= MAX_EXTENTS) {
33500257bb82SYan, Zheng 		ret = relocate_file_extent_cluster(inode, cluster);
33510257bb82SYan, Zheng 		if (ret)
33520257bb82SYan, Zheng 			return ret;
33530257bb82SYan, Zheng 		cluster->nr = 0;
33540257bb82SYan, Zheng 	}
33550257bb82SYan, Zheng 	return 0;
33565d4f98a2SYan Zheng }
33575d4f98a2SYan Zheng 
33585d4f98a2SYan Zheng /*
33595d4f98a2SYan Zheng  * helper to add a tree block to the list.
33605d4f98a2SYan Zheng  * the major work is getting the generation and level of the block
33615d4f98a2SYan Zheng  */
33625d4f98a2SYan Zheng static int add_tree_block(struct reloc_control *rc,
33635d4f98a2SYan Zheng 			  struct btrfs_key *extent_key,
33645d4f98a2SYan Zheng 			  struct btrfs_path *path,
33655d4f98a2SYan Zheng 			  struct rb_root *blocks)
33665d4f98a2SYan Zheng {
33675d4f98a2SYan Zheng 	struct extent_buffer *eb;
33685d4f98a2SYan Zheng 	struct btrfs_extent_item *ei;
33695d4f98a2SYan Zheng 	struct btrfs_tree_block_info *bi;
33705d4f98a2SYan Zheng 	struct tree_block *block;
33715d4f98a2SYan Zheng 	struct rb_node *rb_node;
33725d4f98a2SYan Zheng 	u32 item_size;
33735d4f98a2SYan Zheng 	int level = -1;
33747fdf4b60SWang Shilong 	u64 generation;
33755d4f98a2SYan Zheng 
33765d4f98a2SYan Zheng 	eb =  path->nodes[0];
33775d4f98a2SYan Zheng 	item_size = btrfs_item_size_nr(eb, path->slots[0]);
33785d4f98a2SYan Zheng 
33793173a18fSJosef Bacik 	if (extent_key->type == BTRFS_METADATA_ITEM_KEY ||
33803173a18fSJosef Bacik 	    item_size >= sizeof(*ei) + sizeof(*bi)) {
33815d4f98a2SYan Zheng 		ei = btrfs_item_ptr(eb, path->slots[0],
33825d4f98a2SYan Zheng 				struct btrfs_extent_item);
33833173a18fSJosef Bacik 		if (extent_key->type == BTRFS_EXTENT_ITEM_KEY) {
33845d4f98a2SYan Zheng 			bi = (struct btrfs_tree_block_info *)(ei + 1);
33855d4f98a2SYan Zheng 			level = btrfs_tree_block_level(eb, bi);
33865d4f98a2SYan Zheng 		} else {
33873173a18fSJosef Bacik 			level = (int)extent_key->offset;
33883173a18fSJosef Bacik 		}
33893173a18fSJosef Bacik 		generation = btrfs_extent_generation(eb, ei);
33906d8ff4e4SDavid Sterba 	} else if (unlikely(item_size == sizeof(struct btrfs_extent_item_v0))) {
3391ba3c2b19SNikolay Borisov 		btrfs_print_v0_err(eb->fs_info);
3392ba3c2b19SNikolay Borisov 		btrfs_handle_fs_error(eb->fs_info, -EINVAL, NULL);
3393ba3c2b19SNikolay Borisov 		return -EINVAL;
33943173a18fSJosef Bacik 	} else {
33955d4f98a2SYan Zheng 		BUG();
33965d4f98a2SYan Zheng 	}
33975d4f98a2SYan Zheng 
3398b3b4aa74SDavid Sterba 	btrfs_release_path(path);
33995d4f98a2SYan Zheng 
34005d4f98a2SYan Zheng 	BUG_ON(level == -1);
34015d4f98a2SYan Zheng 
34025d4f98a2SYan Zheng 	block = kmalloc(sizeof(*block), GFP_NOFS);
34035d4f98a2SYan Zheng 	if (!block)
34045d4f98a2SYan Zheng 		return -ENOMEM;
34055d4f98a2SYan Zheng 
34065d4f98a2SYan Zheng 	block->bytenr = extent_key->objectid;
3407da17066cSJeff Mahoney 	block->key.objectid = rc->extent_root->fs_info->nodesize;
34085d4f98a2SYan Zheng 	block->key.offset = generation;
34095d4f98a2SYan Zheng 	block->level = level;
34105d4f98a2SYan Zheng 	block->key_ready = 0;
34115d4f98a2SYan Zheng 
3412e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(blocks, block->bytenr, &block->rb_node);
341343c04fb1SJeff Mahoney 	if (rb_node)
341443c04fb1SJeff Mahoney 		backref_tree_panic(rb_node, -EEXIST, block->bytenr);
34155d4f98a2SYan Zheng 
34165d4f98a2SYan Zheng 	return 0;
34175d4f98a2SYan Zheng }
34185d4f98a2SYan Zheng 
34195d4f98a2SYan Zheng /*
34205d4f98a2SYan Zheng  * helper to add tree blocks for backref of type BTRFS_SHARED_DATA_REF_KEY
34215d4f98a2SYan Zheng  */
34225d4f98a2SYan Zheng static int __add_tree_block(struct reloc_control *rc,
34235d4f98a2SYan Zheng 			    u64 bytenr, u32 blocksize,
34245d4f98a2SYan Zheng 			    struct rb_root *blocks)
34255d4f98a2SYan Zheng {
34260b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
34275d4f98a2SYan Zheng 	struct btrfs_path *path;
34285d4f98a2SYan Zheng 	struct btrfs_key key;
34295d4f98a2SYan Zheng 	int ret;
34300b246afaSJeff Mahoney 	bool skinny = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
34315d4f98a2SYan Zheng 
34327476dfdaSDavid Sterba 	if (tree_block_processed(bytenr, rc))
34335d4f98a2SYan Zheng 		return 0;
34345d4f98a2SYan Zheng 
3435e9a28dc5SQu Wenruo 	if (rb_simple_search(blocks, bytenr))
34365d4f98a2SYan Zheng 		return 0;
34375d4f98a2SYan Zheng 
34385d4f98a2SYan Zheng 	path = btrfs_alloc_path();
34395d4f98a2SYan Zheng 	if (!path)
34405d4f98a2SYan Zheng 		return -ENOMEM;
3441aee68ee5SJosef Bacik again:
34425d4f98a2SYan Zheng 	key.objectid = bytenr;
3443aee68ee5SJosef Bacik 	if (skinny) {
3444aee68ee5SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
3445aee68ee5SJosef Bacik 		key.offset = (u64)-1;
3446aee68ee5SJosef Bacik 	} else {
34475d4f98a2SYan Zheng 		key.type = BTRFS_EXTENT_ITEM_KEY;
34485d4f98a2SYan Zheng 		key.offset = blocksize;
3449aee68ee5SJosef Bacik 	}
34505d4f98a2SYan Zheng 
34515d4f98a2SYan Zheng 	path->search_commit_root = 1;
34525d4f98a2SYan Zheng 	path->skip_locking = 1;
34535d4f98a2SYan Zheng 	ret = btrfs_search_slot(NULL, rc->extent_root, &key, path, 0, 0);
34545d4f98a2SYan Zheng 	if (ret < 0)
34555d4f98a2SYan Zheng 		goto out;
34565d4f98a2SYan Zheng 
3457aee68ee5SJosef Bacik 	if (ret > 0 && skinny) {
3458aee68ee5SJosef Bacik 		if (path->slots[0]) {
3459aee68ee5SJosef Bacik 			path->slots[0]--;
3460aee68ee5SJosef Bacik 			btrfs_item_key_to_cpu(path->nodes[0], &key,
3461aee68ee5SJosef Bacik 					      path->slots[0]);
34623173a18fSJosef Bacik 			if (key.objectid == bytenr &&
3463aee68ee5SJosef Bacik 			    (key.type == BTRFS_METADATA_ITEM_KEY ||
3464aee68ee5SJosef Bacik 			     (key.type == BTRFS_EXTENT_ITEM_KEY &&
3465aee68ee5SJosef Bacik 			      key.offset == blocksize)))
34663173a18fSJosef Bacik 				ret = 0;
34673173a18fSJosef Bacik 		}
3468aee68ee5SJosef Bacik 
3469aee68ee5SJosef Bacik 		if (ret) {
3470aee68ee5SJosef Bacik 			skinny = false;
3471aee68ee5SJosef Bacik 			btrfs_release_path(path);
3472aee68ee5SJosef Bacik 			goto again;
3473aee68ee5SJosef Bacik 		}
3474aee68ee5SJosef Bacik 	}
3475cdccee99SLiu Bo 	if (ret) {
3476cdccee99SLiu Bo 		ASSERT(ret == 1);
3477cdccee99SLiu Bo 		btrfs_print_leaf(path->nodes[0]);
3478cdccee99SLiu Bo 		btrfs_err(fs_info,
3479cdccee99SLiu Bo 	     "tree block extent item (%llu) is not found in extent tree",
3480cdccee99SLiu Bo 		     bytenr);
3481cdccee99SLiu Bo 		WARN_ON(1);
3482cdccee99SLiu Bo 		ret = -EINVAL;
3483cdccee99SLiu Bo 		goto out;
3484cdccee99SLiu Bo 	}
34853173a18fSJosef Bacik 
34865d4f98a2SYan Zheng 	ret = add_tree_block(rc, &key, path, blocks);
34875d4f98a2SYan Zheng out:
34885d4f98a2SYan Zheng 	btrfs_free_path(path);
34895d4f98a2SYan Zheng 	return ret;
34905d4f98a2SYan Zheng }
34915d4f98a2SYan Zheng 
34920af3d00bSJosef Bacik static int delete_block_group_cache(struct btrfs_fs_info *fs_info,
349332da5386SDavid Sterba 				    struct btrfs_block_group *block_group,
34941bbc621eSChris Mason 				    struct inode *inode,
34951bbc621eSChris Mason 				    u64 ino)
34960af3d00bSJosef Bacik {
34970af3d00bSJosef Bacik 	struct btrfs_key key;
34980af3d00bSJosef Bacik 	struct btrfs_root *root = fs_info->tree_root;
34990af3d00bSJosef Bacik 	struct btrfs_trans_handle *trans;
35000af3d00bSJosef Bacik 	int ret = 0;
35010af3d00bSJosef Bacik 
35020af3d00bSJosef Bacik 	if (inode)
35030af3d00bSJosef Bacik 		goto truncate;
35040af3d00bSJosef Bacik 
35050af3d00bSJosef Bacik 	key.objectid = ino;
35060af3d00bSJosef Bacik 	key.type = BTRFS_INODE_ITEM_KEY;
35070af3d00bSJosef Bacik 	key.offset = 0;
35080af3d00bSJosef Bacik 
35094c66e0d4SDavid Sterba 	inode = btrfs_iget(fs_info->sb, &key, root);
35102e19f1f9SAl Viro 	if (IS_ERR(inode))
35110af3d00bSJosef Bacik 		return -ENOENT;
35120af3d00bSJosef Bacik 
35130af3d00bSJosef Bacik truncate:
35142ff7e61eSJeff Mahoney 	ret = btrfs_check_trunc_cache_free_space(fs_info,
35157b61cd92SMiao Xie 						 &fs_info->global_block_rsv);
35167b61cd92SMiao Xie 	if (ret)
35177b61cd92SMiao Xie 		goto out;
35187b61cd92SMiao Xie 
35197a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
35200af3d00bSJosef Bacik 	if (IS_ERR(trans)) {
35213612b495STsutomu Itoh 		ret = PTR_ERR(trans);
35220af3d00bSJosef Bacik 		goto out;
35230af3d00bSJosef Bacik 	}
35240af3d00bSJosef Bacik 
352577ab86bfSJeff Mahoney 	ret = btrfs_truncate_free_space_cache(trans, block_group, inode);
35260af3d00bSJosef Bacik 
35273a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
35282ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
35290af3d00bSJosef Bacik out:
35300af3d00bSJosef Bacik 	iput(inode);
35310af3d00bSJosef Bacik 	return ret;
35320af3d00bSJosef Bacik }
35330af3d00bSJosef Bacik 
35345d4f98a2SYan Zheng /*
353519b546d7SQu Wenruo  * Locate the free space cache EXTENT_DATA in root tree leaf and delete the
353619b546d7SQu Wenruo  * cache inode, to avoid free space cache data extent blocking data relocation.
35375d4f98a2SYan Zheng  */
353819b546d7SQu Wenruo static int delete_v1_space_cache(struct extent_buffer *leaf,
353919b546d7SQu Wenruo 				 struct btrfs_block_group *block_group,
354019b546d7SQu Wenruo 				 u64 data_bytenr)
35415d4f98a2SYan Zheng {
354219b546d7SQu Wenruo 	u64 space_cache_ino;
354319b546d7SQu Wenruo 	struct btrfs_file_extent_item *ei;
35445d4f98a2SYan Zheng 	struct btrfs_key key;
354519b546d7SQu Wenruo 	bool found = false;
354619b546d7SQu Wenruo 	int i;
35475d4f98a2SYan Zheng 	int ret;
35485d4f98a2SYan Zheng 
354919b546d7SQu Wenruo 	if (btrfs_header_owner(leaf) != BTRFS_ROOT_TREE_OBJECTID)
355019b546d7SQu Wenruo 		return 0;
35515d4f98a2SYan Zheng 
355219b546d7SQu Wenruo 	for (i = 0; i < btrfs_header_nritems(leaf); i++) {
355319b546d7SQu Wenruo 		btrfs_item_key_to_cpu(leaf, &key, i);
355419b546d7SQu Wenruo 		if (key.type != BTRFS_EXTENT_DATA_KEY)
355519b546d7SQu Wenruo 			continue;
355619b546d7SQu Wenruo 		ei = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
355719b546d7SQu Wenruo 		if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_REG &&
355819b546d7SQu Wenruo 		    btrfs_file_extent_disk_bytenr(leaf, ei) == data_bytenr) {
355919b546d7SQu Wenruo 			found = true;
356019b546d7SQu Wenruo 			space_cache_ino = key.objectid;
356119b546d7SQu Wenruo 			break;
356219b546d7SQu Wenruo 		}
356319b546d7SQu Wenruo 	}
356419b546d7SQu Wenruo 	if (!found)
356519b546d7SQu Wenruo 		return -ENOENT;
356619b546d7SQu Wenruo 	ret = delete_block_group_cache(leaf->fs_info, block_group, NULL,
356719b546d7SQu Wenruo 					space_cache_ino);
35680af3d00bSJosef Bacik 	return ret;
35695d4f98a2SYan Zheng }
35705d4f98a2SYan Zheng 
35715d4f98a2SYan Zheng /*
35722c016dc2SLiu Bo  * helper to find all tree blocks that reference a given data extent
35735d4f98a2SYan Zheng  */
35745d4f98a2SYan Zheng static noinline_for_stack
35755d4f98a2SYan Zheng int add_data_references(struct reloc_control *rc,
35765d4f98a2SYan Zheng 			struct btrfs_key *extent_key,
35775d4f98a2SYan Zheng 			struct btrfs_path *path,
35785d4f98a2SYan Zheng 			struct rb_root *blocks)
35795d4f98a2SYan Zheng {
358019b546d7SQu Wenruo 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
358119b546d7SQu Wenruo 	struct ulist *leaves = NULL;
358219b546d7SQu Wenruo 	struct ulist_iterator leaf_uiter;
358319b546d7SQu Wenruo 	struct ulist_node *ref_node = NULL;
358419b546d7SQu Wenruo 	const u32 blocksize = fs_info->nodesize;
3585647f63bdSFilipe David Borba Manana 	int ret = 0;
35865d4f98a2SYan Zheng 
3587b3b4aa74SDavid Sterba 	btrfs_release_path(path);
358819b546d7SQu Wenruo 	ret = btrfs_find_all_leafs(NULL, fs_info, extent_key->objectid,
358919b546d7SQu Wenruo 				   0, &leaves, NULL, true);
359019b546d7SQu Wenruo 	if (ret < 0)
359119b546d7SQu Wenruo 		return ret;
359219b546d7SQu Wenruo 
359319b546d7SQu Wenruo 	ULIST_ITER_INIT(&leaf_uiter);
359419b546d7SQu Wenruo 	while ((ref_node = ulist_next(leaves, &leaf_uiter))) {
359519b546d7SQu Wenruo 		struct extent_buffer *eb;
359619b546d7SQu Wenruo 
359719b546d7SQu Wenruo 		eb = read_tree_block(fs_info, ref_node->val, 0, 0, NULL);
359819b546d7SQu Wenruo 		if (IS_ERR(eb)) {
359919b546d7SQu Wenruo 			ret = PTR_ERR(eb);
360019b546d7SQu Wenruo 			break;
360119b546d7SQu Wenruo 		}
360219b546d7SQu Wenruo 		ret = delete_v1_space_cache(eb, rc->block_group,
360319b546d7SQu Wenruo 					    extent_key->objectid);
360419b546d7SQu Wenruo 		free_extent_buffer(eb);
360519b546d7SQu Wenruo 		if (ret < 0)
360619b546d7SQu Wenruo 			break;
360719b546d7SQu Wenruo 		ret = __add_tree_block(rc, ref_node->val, blocksize, blocks);
360819b546d7SQu Wenruo 		if (ret < 0)
360919b546d7SQu Wenruo 			break;
361019b546d7SQu Wenruo 	}
361119b546d7SQu Wenruo 	if (ret < 0)
36125d4f98a2SYan Zheng 		free_block_list(blocks);
361319b546d7SQu Wenruo 	ulist_free(leaves);
361419b546d7SQu Wenruo 	return ret;
36155d4f98a2SYan Zheng }
36165d4f98a2SYan Zheng 
36175d4f98a2SYan Zheng /*
36182c016dc2SLiu Bo  * helper to find next unprocessed extent
36195d4f98a2SYan Zheng  */
36205d4f98a2SYan Zheng static noinline_for_stack
3621147d256eSZhaolei int find_next_extent(struct reloc_control *rc, struct btrfs_path *path,
36223fd0a558SYan, Zheng 		     struct btrfs_key *extent_key)
36235d4f98a2SYan Zheng {
36240b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
36255d4f98a2SYan Zheng 	struct btrfs_key key;
36265d4f98a2SYan Zheng 	struct extent_buffer *leaf;
36275d4f98a2SYan Zheng 	u64 start, end, last;
36285d4f98a2SYan Zheng 	int ret;
36295d4f98a2SYan Zheng 
3630b3470b5dSDavid Sterba 	last = rc->block_group->start + rc->block_group->length;
36315d4f98a2SYan Zheng 	while (1) {
36325d4f98a2SYan Zheng 		cond_resched();
36335d4f98a2SYan Zheng 		if (rc->search_start >= last) {
36345d4f98a2SYan Zheng 			ret = 1;
36355d4f98a2SYan Zheng 			break;
36365d4f98a2SYan Zheng 		}
36375d4f98a2SYan Zheng 
36385d4f98a2SYan Zheng 		key.objectid = rc->search_start;
36395d4f98a2SYan Zheng 		key.type = BTRFS_EXTENT_ITEM_KEY;
36405d4f98a2SYan Zheng 		key.offset = 0;
36415d4f98a2SYan Zheng 
36425d4f98a2SYan Zheng 		path->search_commit_root = 1;
36435d4f98a2SYan Zheng 		path->skip_locking = 1;
36445d4f98a2SYan Zheng 		ret = btrfs_search_slot(NULL, rc->extent_root, &key, path,
36455d4f98a2SYan Zheng 					0, 0);
36465d4f98a2SYan Zheng 		if (ret < 0)
36475d4f98a2SYan Zheng 			break;
36485d4f98a2SYan Zheng next:
36495d4f98a2SYan Zheng 		leaf = path->nodes[0];
36505d4f98a2SYan Zheng 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
36515d4f98a2SYan Zheng 			ret = btrfs_next_leaf(rc->extent_root, path);
36525d4f98a2SYan Zheng 			if (ret != 0)
36535d4f98a2SYan Zheng 				break;
36545d4f98a2SYan Zheng 			leaf = path->nodes[0];
36555d4f98a2SYan Zheng 		}
36565d4f98a2SYan Zheng 
36575d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
36585d4f98a2SYan Zheng 		if (key.objectid >= last) {
36595d4f98a2SYan Zheng 			ret = 1;
36605d4f98a2SYan Zheng 			break;
36615d4f98a2SYan Zheng 		}
36625d4f98a2SYan Zheng 
36633173a18fSJosef Bacik 		if (key.type != BTRFS_EXTENT_ITEM_KEY &&
36643173a18fSJosef Bacik 		    key.type != BTRFS_METADATA_ITEM_KEY) {
36653173a18fSJosef Bacik 			path->slots[0]++;
36663173a18fSJosef Bacik 			goto next;
36673173a18fSJosef Bacik 		}
36683173a18fSJosef Bacik 
36693173a18fSJosef Bacik 		if (key.type == BTRFS_EXTENT_ITEM_KEY &&
36705d4f98a2SYan Zheng 		    key.objectid + key.offset <= rc->search_start) {
36715d4f98a2SYan Zheng 			path->slots[0]++;
36725d4f98a2SYan Zheng 			goto next;
36735d4f98a2SYan Zheng 		}
36745d4f98a2SYan Zheng 
36753173a18fSJosef Bacik 		if (key.type == BTRFS_METADATA_ITEM_KEY &&
36760b246afaSJeff Mahoney 		    key.objectid + fs_info->nodesize <=
36773173a18fSJosef Bacik 		    rc->search_start) {
36783173a18fSJosef Bacik 			path->slots[0]++;
36793173a18fSJosef Bacik 			goto next;
36803173a18fSJosef Bacik 		}
36813173a18fSJosef Bacik 
36825d4f98a2SYan Zheng 		ret = find_first_extent_bit(&rc->processed_blocks,
36835d4f98a2SYan Zheng 					    key.objectid, &start, &end,
3684e6138876SJosef Bacik 					    EXTENT_DIRTY, NULL);
36855d4f98a2SYan Zheng 
36865d4f98a2SYan Zheng 		if (ret == 0 && start <= key.objectid) {
3687b3b4aa74SDavid Sterba 			btrfs_release_path(path);
36885d4f98a2SYan Zheng 			rc->search_start = end + 1;
36895d4f98a2SYan Zheng 		} else {
36903173a18fSJosef Bacik 			if (key.type == BTRFS_EXTENT_ITEM_KEY)
36915d4f98a2SYan Zheng 				rc->search_start = key.objectid + key.offset;
36923173a18fSJosef Bacik 			else
36933173a18fSJosef Bacik 				rc->search_start = key.objectid +
36940b246afaSJeff Mahoney 					fs_info->nodesize;
36953fd0a558SYan, Zheng 			memcpy(extent_key, &key, sizeof(key));
36965d4f98a2SYan Zheng 			return 0;
36975d4f98a2SYan Zheng 		}
36985d4f98a2SYan Zheng 	}
3699b3b4aa74SDavid Sterba 	btrfs_release_path(path);
37005d4f98a2SYan Zheng 	return ret;
37015d4f98a2SYan Zheng }
37025d4f98a2SYan Zheng 
37035d4f98a2SYan Zheng static void set_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 = rc;
37097585717fSChris Mason 	mutex_unlock(&fs_info->reloc_mutex);
37105d4f98a2SYan Zheng }
37115d4f98a2SYan Zheng 
37125d4f98a2SYan Zheng static void unset_reloc_control(struct reloc_control *rc)
37135d4f98a2SYan Zheng {
37145d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
37157585717fSChris Mason 
37167585717fSChris Mason 	mutex_lock(&fs_info->reloc_mutex);
37175d4f98a2SYan Zheng 	fs_info->reloc_ctl = NULL;
37187585717fSChris Mason 	mutex_unlock(&fs_info->reloc_mutex);
37195d4f98a2SYan Zheng }
37205d4f98a2SYan Zheng 
37215d4f98a2SYan Zheng static int check_extent_flags(u64 flags)
37225d4f98a2SYan Zheng {
37235d4f98a2SYan Zheng 	if ((flags & BTRFS_EXTENT_FLAG_DATA) &&
37245d4f98a2SYan Zheng 	    (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
37255d4f98a2SYan Zheng 		return 1;
37265d4f98a2SYan Zheng 	if (!(flags & BTRFS_EXTENT_FLAG_DATA) &&
37275d4f98a2SYan Zheng 	    !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
37285d4f98a2SYan Zheng 		return 1;
37295d4f98a2SYan Zheng 	if ((flags & BTRFS_EXTENT_FLAG_DATA) &&
37305d4f98a2SYan Zheng 	    (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
37315d4f98a2SYan Zheng 		return 1;
37325d4f98a2SYan Zheng 	return 0;
37335d4f98a2SYan Zheng }
37345d4f98a2SYan Zheng 
37353fd0a558SYan, Zheng static noinline_for_stack
37363fd0a558SYan, Zheng int prepare_to_relocate(struct reloc_control *rc)
37373fd0a558SYan, Zheng {
37383fd0a558SYan, Zheng 	struct btrfs_trans_handle *trans;
3739ac2fabacSJosef Bacik 	int ret;
37403fd0a558SYan, Zheng 
37412ff7e61eSJeff Mahoney 	rc->block_rsv = btrfs_alloc_block_rsv(rc->extent_root->fs_info,
374266d8f3ddSMiao Xie 					      BTRFS_BLOCK_RSV_TEMP);
37433fd0a558SYan, Zheng 	if (!rc->block_rsv)
37443fd0a558SYan, Zheng 		return -ENOMEM;
37453fd0a558SYan, Zheng 
37463fd0a558SYan, Zheng 	memset(&rc->cluster, 0, sizeof(rc->cluster));
3747b3470b5dSDavid Sterba 	rc->search_start = rc->block_group->start;
37483fd0a558SYan, Zheng 	rc->extents_found = 0;
37493fd0a558SYan, Zheng 	rc->nodes_relocated = 0;
37503fd0a558SYan, Zheng 	rc->merging_rsv_size = 0;
37510647bf56SWang Shilong 	rc->reserved_bytes = 0;
3752da17066cSJeff Mahoney 	rc->block_rsv->size = rc->extent_root->fs_info->nodesize *
37530647bf56SWang Shilong 			      RELOCATION_RESERVED_NODES;
3754ac2fabacSJosef Bacik 	ret = btrfs_block_rsv_refill(rc->extent_root,
3755ac2fabacSJosef Bacik 				     rc->block_rsv, rc->block_rsv->size,
3756ac2fabacSJosef Bacik 				     BTRFS_RESERVE_FLUSH_ALL);
3757ac2fabacSJosef Bacik 	if (ret)
3758ac2fabacSJosef Bacik 		return ret;
37593fd0a558SYan, Zheng 
37603fd0a558SYan, Zheng 	rc->create_reloc_tree = 1;
37613fd0a558SYan, Zheng 	set_reloc_control(rc);
37623fd0a558SYan, Zheng 
37637a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
376428818947SLiu Bo 	if (IS_ERR(trans)) {
376528818947SLiu Bo 		unset_reloc_control(rc);
376628818947SLiu Bo 		/*
376728818947SLiu Bo 		 * extent tree is not a ref_cow tree and has no reloc_root to
376828818947SLiu Bo 		 * cleanup.  And callers are responsible to free the above
376928818947SLiu Bo 		 * block rsv.
377028818947SLiu Bo 		 */
377128818947SLiu Bo 		return PTR_ERR(trans);
377228818947SLiu Bo 	}
37733a45bb20SJeff Mahoney 	btrfs_commit_transaction(trans);
37743fd0a558SYan, Zheng 	return 0;
37753fd0a558SYan, Zheng }
377676dda93cSYan, Zheng 
37775d4f98a2SYan Zheng static noinline_for_stack int relocate_block_group(struct reloc_control *rc)
37785d4f98a2SYan Zheng {
37792ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
37805d4f98a2SYan Zheng 	struct rb_root blocks = RB_ROOT;
37815d4f98a2SYan Zheng 	struct btrfs_key key;
37825d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans = NULL;
37835d4f98a2SYan Zheng 	struct btrfs_path *path;
37845d4f98a2SYan Zheng 	struct btrfs_extent_item *ei;
37855d4f98a2SYan Zheng 	u64 flags;
37865d4f98a2SYan Zheng 	u32 item_size;
37875d4f98a2SYan Zheng 	int ret;
37885d4f98a2SYan Zheng 	int err = 0;
3789c87f08caSChris Mason 	int progress = 0;
37905d4f98a2SYan Zheng 
37915d4f98a2SYan Zheng 	path = btrfs_alloc_path();
37923fd0a558SYan, Zheng 	if (!path)
37935d4f98a2SYan Zheng 		return -ENOMEM;
3794e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
37953fd0a558SYan, Zheng 
37963fd0a558SYan, Zheng 	ret = prepare_to_relocate(rc);
37973fd0a558SYan, Zheng 	if (ret) {
37983fd0a558SYan, Zheng 		err = ret;
37993fd0a558SYan, Zheng 		goto out_free;
38002423fdfbSJiri Slaby 	}
38015d4f98a2SYan Zheng 
38025d4f98a2SYan Zheng 	while (1) {
38030647bf56SWang Shilong 		rc->reserved_bytes = 0;
38040647bf56SWang Shilong 		ret = btrfs_block_rsv_refill(rc->extent_root,
38050647bf56SWang Shilong 					rc->block_rsv, rc->block_rsv->size,
38060647bf56SWang Shilong 					BTRFS_RESERVE_FLUSH_ALL);
38070647bf56SWang Shilong 		if (ret) {
38080647bf56SWang Shilong 			err = ret;
38090647bf56SWang Shilong 			break;
38100647bf56SWang Shilong 		}
3811c87f08caSChris Mason 		progress++;
3812a22285a6SYan, Zheng 		trans = btrfs_start_transaction(rc->extent_root, 0);
38130f788c58SLiu Bo 		if (IS_ERR(trans)) {
38140f788c58SLiu Bo 			err = PTR_ERR(trans);
38150f788c58SLiu Bo 			trans = NULL;
38160f788c58SLiu Bo 			break;
38170f788c58SLiu Bo 		}
3818c87f08caSChris Mason restart:
38193fd0a558SYan, Zheng 		if (update_backref_cache(trans, &rc->backref_cache)) {
38203a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
382142a657f5SPan Bian 			trans = NULL;
38223fd0a558SYan, Zheng 			continue;
38233fd0a558SYan, Zheng 		}
38243fd0a558SYan, Zheng 
3825147d256eSZhaolei 		ret = find_next_extent(rc, path, &key);
38265d4f98a2SYan Zheng 		if (ret < 0)
38275d4f98a2SYan Zheng 			err = ret;
38285d4f98a2SYan Zheng 		if (ret != 0)
38295d4f98a2SYan Zheng 			break;
38305d4f98a2SYan Zheng 
38315d4f98a2SYan Zheng 		rc->extents_found++;
38325d4f98a2SYan Zheng 
38335d4f98a2SYan Zheng 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
38345d4f98a2SYan Zheng 				    struct btrfs_extent_item);
38353fd0a558SYan, Zheng 		item_size = btrfs_item_size_nr(path->nodes[0], path->slots[0]);
38365d4f98a2SYan Zheng 		if (item_size >= sizeof(*ei)) {
38375d4f98a2SYan Zheng 			flags = btrfs_extent_flags(path->nodes[0], ei);
38385d4f98a2SYan Zheng 			ret = check_extent_flags(flags);
38395d4f98a2SYan Zheng 			BUG_ON(ret);
38406d8ff4e4SDavid Sterba 		} else if (unlikely(item_size == sizeof(struct btrfs_extent_item_v0))) {
3841ba3c2b19SNikolay Borisov 			err = -EINVAL;
3842ba3c2b19SNikolay Borisov 			btrfs_print_v0_err(trans->fs_info);
3843ba3c2b19SNikolay Borisov 			btrfs_abort_transaction(trans, err);
3844ba3c2b19SNikolay Borisov 			break;
38455d4f98a2SYan Zheng 		} else {
38465d4f98a2SYan Zheng 			BUG();
38475d4f98a2SYan Zheng 		}
38485d4f98a2SYan Zheng 
38495d4f98a2SYan Zheng 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
38505d4f98a2SYan Zheng 			ret = add_tree_block(rc, &key, path, &blocks);
38515d4f98a2SYan Zheng 		} else if (rc->stage == UPDATE_DATA_PTRS &&
38525d4f98a2SYan Zheng 			   (flags & BTRFS_EXTENT_FLAG_DATA)) {
38535d4f98a2SYan Zheng 			ret = add_data_references(rc, &key, path, &blocks);
38545d4f98a2SYan Zheng 		} else {
3855b3b4aa74SDavid Sterba 			btrfs_release_path(path);
38565d4f98a2SYan Zheng 			ret = 0;
38575d4f98a2SYan Zheng 		}
38585d4f98a2SYan Zheng 		if (ret < 0) {
38593fd0a558SYan, Zheng 			err = ret;
38605d4f98a2SYan Zheng 			break;
38615d4f98a2SYan Zheng 		}
38625d4f98a2SYan Zheng 
38635d4f98a2SYan Zheng 		if (!RB_EMPTY_ROOT(&blocks)) {
38645d4f98a2SYan Zheng 			ret = relocate_tree_blocks(trans, rc, &blocks);
38655d4f98a2SYan Zheng 			if (ret < 0) {
38663fd0a558SYan, Zheng 				if (ret != -EAGAIN) {
38675d4f98a2SYan Zheng 					err = ret;
38685d4f98a2SYan Zheng 					break;
38695d4f98a2SYan Zheng 				}
38703fd0a558SYan, Zheng 				rc->extents_found--;
38713fd0a558SYan, Zheng 				rc->search_start = key.objectid;
38723fd0a558SYan, Zheng 			}
38735d4f98a2SYan Zheng 		}
38745d4f98a2SYan Zheng 
38753a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
38762ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
38773fd0a558SYan, Zheng 		trans = NULL;
38785d4f98a2SYan Zheng 
38795d4f98a2SYan Zheng 		if (rc->stage == MOVE_DATA_EXTENTS &&
38805d4f98a2SYan Zheng 		    (flags & BTRFS_EXTENT_FLAG_DATA)) {
38815d4f98a2SYan Zheng 			rc->found_file_extent = 1;
38820257bb82SYan, Zheng 			ret = relocate_data_extent(rc->data_inode,
38833fd0a558SYan, Zheng 						   &key, &rc->cluster);
38845d4f98a2SYan Zheng 			if (ret < 0) {
38855d4f98a2SYan Zheng 				err = ret;
38865d4f98a2SYan Zheng 				break;
38875d4f98a2SYan Zheng 			}
38885d4f98a2SYan Zheng 		}
3889f31ea088SQu Wenruo 		if (btrfs_should_cancel_balance(fs_info)) {
3890f31ea088SQu Wenruo 			err = -ECANCELED;
3891f31ea088SQu Wenruo 			break;
3892f31ea088SQu Wenruo 		}
38935d4f98a2SYan Zheng 	}
3894c87f08caSChris Mason 	if (trans && progress && err == -ENOSPC) {
389543a7e99dSNikolay Borisov 		ret = btrfs_force_chunk_alloc(trans, rc->block_group->flags);
38969689457bSShilong Wang 		if (ret == 1) {
3897c87f08caSChris Mason 			err = 0;
3898c87f08caSChris Mason 			progress = 0;
3899c87f08caSChris Mason 			goto restart;
3900c87f08caSChris Mason 		}
3901c87f08caSChris Mason 	}
39023fd0a558SYan, Zheng 
3903b3b4aa74SDavid Sterba 	btrfs_release_path(path);
390491166212SDavid Sterba 	clear_extent_bits(&rc->processed_blocks, 0, (u64)-1, EXTENT_DIRTY);
39055d4f98a2SYan Zheng 
39065d4f98a2SYan Zheng 	if (trans) {
39073a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
39082ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
39095d4f98a2SYan Zheng 	}
39105d4f98a2SYan Zheng 
39110257bb82SYan, Zheng 	if (!err) {
39123fd0a558SYan, Zheng 		ret = relocate_file_extent_cluster(rc->data_inode,
39133fd0a558SYan, Zheng 						   &rc->cluster);
39140257bb82SYan, Zheng 		if (ret < 0)
39150257bb82SYan, Zheng 			err = ret;
39160257bb82SYan, Zheng 	}
39170257bb82SYan, Zheng 
39183fd0a558SYan, Zheng 	rc->create_reloc_tree = 0;
39193fd0a558SYan, Zheng 	set_reloc_control(rc);
39200257bb82SYan, Zheng 
392113fe1bdbSQu Wenruo 	btrfs_backref_release_cache(&rc->backref_cache);
392263f018beSNikolay Borisov 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
39235d4f98a2SYan Zheng 
39247f913c7cSQu Wenruo 	/*
39257f913c7cSQu Wenruo 	 * Even in the case when the relocation is cancelled, we should all go
39267f913c7cSQu Wenruo 	 * through prepare_to_merge() and merge_reloc_roots().
39277f913c7cSQu Wenruo 	 *
39287f913c7cSQu Wenruo 	 * For error (including cancelled balance), prepare_to_merge() will
39297f913c7cSQu Wenruo 	 * mark all reloc trees orphan, then queue them for cleanup in
39307f913c7cSQu Wenruo 	 * merge_reloc_roots()
39317f913c7cSQu Wenruo 	 */
39323fd0a558SYan, Zheng 	err = prepare_to_merge(rc, err);
39335d4f98a2SYan Zheng 
39345d4f98a2SYan Zheng 	merge_reloc_roots(rc);
39355d4f98a2SYan Zheng 
39363fd0a558SYan, Zheng 	rc->merge_reloc_tree = 0;
39375d4f98a2SYan Zheng 	unset_reloc_control(rc);
393863f018beSNikolay Borisov 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
39395d4f98a2SYan Zheng 
39405d4f98a2SYan Zheng 	/* get rid of pinned extents */
39417a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
394262b99540SQu Wenruo 	if (IS_ERR(trans)) {
39433612b495STsutomu Itoh 		err = PTR_ERR(trans);
394462b99540SQu Wenruo 		goto out_free;
394562b99540SQu Wenruo 	}
39463a45bb20SJeff Mahoney 	btrfs_commit_transaction(trans);
39476217b0faSJosef Bacik out_free:
3948d2311e69SQu Wenruo 	ret = clean_dirty_subvols(rc);
3949d2311e69SQu Wenruo 	if (ret < 0 && !err)
3950d2311e69SQu Wenruo 		err = ret;
39512ff7e61eSJeff Mahoney 	btrfs_free_block_rsv(fs_info, rc->block_rsv);
39523fd0a558SYan, Zheng 	btrfs_free_path(path);
39535d4f98a2SYan Zheng 	return err;
39545d4f98a2SYan Zheng }
39555d4f98a2SYan Zheng 
39565d4f98a2SYan Zheng static int __insert_orphan_inode(struct btrfs_trans_handle *trans,
39570257bb82SYan, Zheng 				 struct btrfs_root *root, u64 objectid)
39585d4f98a2SYan Zheng {
39595d4f98a2SYan Zheng 	struct btrfs_path *path;
39605d4f98a2SYan Zheng 	struct btrfs_inode_item *item;
39615d4f98a2SYan Zheng 	struct extent_buffer *leaf;
39625d4f98a2SYan Zheng 	int ret;
39635d4f98a2SYan Zheng 
39645d4f98a2SYan Zheng 	path = btrfs_alloc_path();
39655d4f98a2SYan Zheng 	if (!path)
39665d4f98a2SYan Zheng 		return -ENOMEM;
39675d4f98a2SYan Zheng 
39685d4f98a2SYan Zheng 	ret = btrfs_insert_empty_inode(trans, root, path, objectid);
39695d4f98a2SYan Zheng 	if (ret)
39705d4f98a2SYan Zheng 		goto out;
39715d4f98a2SYan Zheng 
39725d4f98a2SYan Zheng 	leaf = path->nodes[0];
39735d4f98a2SYan Zheng 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item);
3974b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
39755d4f98a2SYan Zheng 	btrfs_set_inode_generation(leaf, item, 1);
39760257bb82SYan, Zheng 	btrfs_set_inode_size(leaf, item, 0);
39775d4f98a2SYan Zheng 	btrfs_set_inode_mode(leaf, item, S_IFREG | 0600);
39783fd0a558SYan, Zheng 	btrfs_set_inode_flags(leaf, item, BTRFS_INODE_NOCOMPRESS |
39793fd0a558SYan, Zheng 					  BTRFS_INODE_PREALLOC);
39805d4f98a2SYan Zheng 	btrfs_mark_buffer_dirty(leaf);
39815d4f98a2SYan Zheng out:
39825d4f98a2SYan Zheng 	btrfs_free_path(path);
39835d4f98a2SYan Zheng 	return ret;
39845d4f98a2SYan Zheng }
39855d4f98a2SYan Zheng 
39865d4f98a2SYan Zheng /*
39875d4f98a2SYan Zheng  * helper to create inode for data relocation.
39885d4f98a2SYan Zheng  * the inode is in data relocation tree and its link count is 0
39895d4f98a2SYan Zheng  */
39903fd0a558SYan, Zheng static noinline_for_stack
39913fd0a558SYan, Zheng struct inode *create_reloc_inode(struct btrfs_fs_info *fs_info,
399232da5386SDavid Sterba 				 struct btrfs_block_group *group)
39935d4f98a2SYan Zheng {
39945d4f98a2SYan Zheng 	struct inode *inode = NULL;
39955d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
39965d4f98a2SYan Zheng 	struct btrfs_root *root;
39975d4f98a2SYan Zheng 	struct btrfs_key key;
39984624900dSZhaolei 	u64 objectid;
39995d4f98a2SYan Zheng 	int err = 0;
40005d4f98a2SYan Zheng 
40015d4f98a2SYan Zheng 	root = read_fs_root(fs_info, BTRFS_DATA_RELOC_TREE_OBJECTID);
40025d4f98a2SYan Zheng 	if (IS_ERR(root))
40035d4f98a2SYan Zheng 		return ERR_CAST(root);
40045d4f98a2SYan Zheng 
4005a22285a6SYan, Zheng 	trans = btrfs_start_transaction(root, 6);
400676deacf0SJosef Bacik 	if (IS_ERR(trans)) {
400700246528SJosef Bacik 		btrfs_put_root(root);
40083fd0a558SYan, Zheng 		return ERR_CAST(trans);
400976deacf0SJosef Bacik 	}
40105d4f98a2SYan Zheng 
4011581bb050SLi Zefan 	err = btrfs_find_free_objectid(root, &objectid);
40125d4f98a2SYan Zheng 	if (err)
40135d4f98a2SYan Zheng 		goto out;
40145d4f98a2SYan Zheng 
40150257bb82SYan, Zheng 	err = __insert_orphan_inode(trans, root, objectid);
40165d4f98a2SYan Zheng 	BUG_ON(err);
40175d4f98a2SYan Zheng 
40185d4f98a2SYan Zheng 	key.objectid = objectid;
40195d4f98a2SYan Zheng 	key.type = BTRFS_INODE_ITEM_KEY;
40205d4f98a2SYan Zheng 	key.offset = 0;
40214c66e0d4SDavid Sterba 	inode = btrfs_iget(fs_info->sb, &key, root);
40222e19f1f9SAl Viro 	BUG_ON(IS_ERR(inode));
4023b3470b5dSDavid Sterba 	BTRFS_I(inode)->index_cnt = group->start;
40245d4f98a2SYan Zheng 
402573f2e545SNikolay Borisov 	err = btrfs_orphan_add(trans, BTRFS_I(inode));
40265d4f98a2SYan Zheng out:
402700246528SJosef Bacik 	btrfs_put_root(root);
40283a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
40292ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
40305d4f98a2SYan Zheng 	if (err) {
40315d4f98a2SYan Zheng 		if (inode)
40325d4f98a2SYan Zheng 			iput(inode);
40335d4f98a2SYan Zheng 		inode = ERR_PTR(err);
40345d4f98a2SYan Zheng 	}
40355d4f98a2SYan Zheng 	return inode;
40365d4f98a2SYan Zheng }
40375d4f98a2SYan Zheng 
4038c258d6e3SQu Wenruo static struct reloc_control *alloc_reloc_control(struct btrfs_fs_info *fs_info)
40393fd0a558SYan, Zheng {
40403fd0a558SYan, Zheng 	struct reloc_control *rc;
40413fd0a558SYan, Zheng 
40423fd0a558SYan, Zheng 	rc = kzalloc(sizeof(*rc), GFP_NOFS);
40433fd0a558SYan, Zheng 	if (!rc)
40443fd0a558SYan, Zheng 		return NULL;
40453fd0a558SYan, Zheng 
40463fd0a558SYan, Zheng 	INIT_LIST_HEAD(&rc->reloc_roots);
4047d2311e69SQu Wenruo 	INIT_LIST_HEAD(&rc->dirty_subvol_roots);
4048584fb121SQu Wenruo 	btrfs_backref_init_cache(fs_info, &rc->backref_cache, 1);
40493fd0a558SYan, Zheng 	mapping_tree_init(&rc->reloc_root_tree);
405043eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &rc->processed_blocks,
405143eb5f29SQu Wenruo 			    IO_TREE_RELOC_BLOCKS, NULL);
40523fd0a558SYan, Zheng 	return rc;
40533fd0a558SYan, Zheng }
40543fd0a558SYan, Zheng 
40551a0afa0eSJosef Bacik static void free_reloc_control(struct reloc_control *rc)
40561a0afa0eSJosef Bacik {
40571a0afa0eSJosef Bacik 	struct mapping_node *node, *tmp;
40581a0afa0eSJosef Bacik 
40591a0afa0eSJosef Bacik 	free_reloc_roots(&rc->reloc_roots);
40601a0afa0eSJosef Bacik 	rbtree_postorder_for_each_entry_safe(node, tmp,
40611a0afa0eSJosef Bacik 			&rc->reloc_root_tree.rb_root, rb_node)
40621a0afa0eSJosef Bacik 		kfree(node);
40631a0afa0eSJosef Bacik 
40641a0afa0eSJosef Bacik 	kfree(rc);
40651a0afa0eSJosef Bacik }
40661a0afa0eSJosef Bacik 
40675d4f98a2SYan Zheng /*
4068ebce0e01SAdam Borowski  * Print the block group being relocated
4069ebce0e01SAdam Borowski  */
4070ebce0e01SAdam Borowski static void describe_relocation(struct btrfs_fs_info *fs_info,
407132da5386SDavid Sterba 				struct btrfs_block_group *block_group)
4072ebce0e01SAdam Borowski {
4073f89e09cfSAnand Jain 	char buf[128] = {'\0'};
4074ebce0e01SAdam Borowski 
4075f89e09cfSAnand Jain 	btrfs_describe_block_groups(block_group->flags, buf, sizeof(buf));
4076ebce0e01SAdam Borowski 
4077ebce0e01SAdam Borowski 	btrfs_info(fs_info,
4078ebce0e01SAdam Borowski 		   "relocating block group %llu flags %s",
4079b3470b5dSDavid Sterba 		   block_group->start, buf);
4080ebce0e01SAdam Borowski }
4081ebce0e01SAdam Borowski 
4082430640e3SQu Wenruo static const char *stage_to_string(int stage)
4083430640e3SQu Wenruo {
4084430640e3SQu Wenruo 	if (stage == MOVE_DATA_EXTENTS)
4085430640e3SQu Wenruo 		return "move data extents";
4086430640e3SQu Wenruo 	if (stage == UPDATE_DATA_PTRS)
4087430640e3SQu Wenruo 		return "update data pointers";
4088430640e3SQu Wenruo 	return "unknown";
4089430640e3SQu Wenruo }
4090430640e3SQu Wenruo 
4091ebce0e01SAdam Borowski /*
40925d4f98a2SYan Zheng  * function to relocate all extents in a block group.
40935d4f98a2SYan Zheng  */
40946bccf3abSJeff Mahoney int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start)
40955d4f98a2SYan Zheng {
409632da5386SDavid Sterba 	struct btrfs_block_group *bg;
40976bccf3abSJeff Mahoney 	struct btrfs_root *extent_root = fs_info->extent_root;
40985d4f98a2SYan Zheng 	struct reloc_control *rc;
40990af3d00bSJosef Bacik 	struct inode *inode;
41000af3d00bSJosef Bacik 	struct btrfs_path *path;
41015d4f98a2SYan Zheng 	int ret;
4102f0486c68SYan, Zheng 	int rw = 0;
41035d4f98a2SYan Zheng 	int err = 0;
41045d4f98a2SYan Zheng 
4105eede2bf3SOmar Sandoval 	bg = btrfs_lookup_block_group(fs_info, group_start);
4106eede2bf3SOmar Sandoval 	if (!bg)
4107eede2bf3SOmar Sandoval 		return -ENOENT;
4108eede2bf3SOmar Sandoval 
4109eede2bf3SOmar Sandoval 	if (btrfs_pinned_by_swapfile(fs_info, bg)) {
4110eede2bf3SOmar Sandoval 		btrfs_put_block_group(bg);
4111eede2bf3SOmar Sandoval 		return -ETXTBSY;
4112eede2bf3SOmar Sandoval 	}
4113eede2bf3SOmar Sandoval 
4114c258d6e3SQu Wenruo 	rc = alloc_reloc_control(fs_info);
4115eede2bf3SOmar Sandoval 	if (!rc) {
4116eede2bf3SOmar Sandoval 		btrfs_put_block_group(bg);
41175d4f98a2SYan Zheng 		return -ENOMEM;
4118eede2bf3SOmar Sandoval 	}
41195d4f98a2SYan Zheng 
4120f0486c68SYan, Zheng 	rc->extent_root = extent_root;
4121eede2bf3SOmar Sandoval 	rc->block_group = bg;
41225d4f98a2SYan Zheng 
4123b12de528SQu Wenruo 	ret = btrfs_inc_block_group_ro(rc->block_group, true);
4124f0486c68SYan, Zheng 	if (ret) {
4125f0486c68SYan, Zheng 		err = ret;
4126f0486c68SYan, Zheng 		goto out;
4127f0486c68SYan, Zheng 	}
4128f0486c68SYan, Zheng 	rw = 1;
4129f0486c68SYan, Zheng 
41300af3d00bSJosef Bacik 	path = btrfs_alloc_path();
41310af3d00bSJosef Bacik 	if (!path) {
41320af3d00bSJosef Bacik 		err = -ENOMEM;
41330af3d00bSJosef Bacik 		goto out;
41340af3d00bSJosef Bacik 	}
41350af3d00bSJosef Bacik 
41367949f339SDavid Sterba 	inode = lookup_free_space_inode(rc->block_group, path);
41370af3d00bSJosef Bacik 	btrfs_free_path(path);
41380af3d00bSJosef Bacik 
41390af3d00bSJosef Bacik 	if (!IS_ERR(inode))
41401bbc621eSChris Mason 		ret = delete_block_group_cache(fs_info, rc->block_group, inode, 0);
41410af3d00bSJosef Bacik 	else
41420af3d00bSJosef Bacik 		ret = PTR_ERR(inode);
41430af3d00bSJosef Bacik 
41440af3d00bSJosef Bacik 	if (ret && ret != -ENOENT) {
41450af3d00bSJosef Bacik 		err = ret;
41460af3d00bSJosef Bacik 		goto out;
41470af3d00bSJosef Bacik 	}
41480af3d00bSJosef Bacik 
41495d4f98a2SYan Zheng 	rc->data_inode = create_reloc_inode(fs_info, rc->block_group);
41505d4f98a2SYan Zheng 	if (IS_ERR(rc->data_inode)) {
41515d4f98a2SYan Zheng 		err = PTR_ERR(rc->data_inode);
41525d4f98a2SYan Zheng 		rc->data_inode = NULL;
41535d4f98a2SYan Zheng 		goto out;
41545d4f98a2SYan Zheng 	}
41555d4f98a2SYan Zheng 
41560b246afaSJeff Mahoney 	describe_relocation(fs_info, rc->block_group);
41575d4f98a2SYan Zheng 
41589cfa3e34SFilipe Manana 	btrfs_wait_block_group_reservations(rc->block_group);
4159f78c436cSFilipe Manana 	btrfs_wait_nocow_writers(rc->block_group);
41606374e57aSChris Mason 	btrfs_wait_ordered_roots(fs_info, U64_MAX,
4161b3470b5dSDavid Sterba 				 rc->block_group->start,
4162b3470b5dSDavid Sterba 				 rc->block_group->length);
41635d4f98a2SYan Zheng 
41645d4f98a2SYan Zheng 	while (1) {
4165430640e3SQu Wenruo 		int finishes_stage;
4166430640e3SQu Wenruo 
416776dda93cSYan, Zheng 		mutex_lock(&fs_info->cleaner_mutex);
41685d4f98a2SYan Zheng 		ret = relocate_block_group(rc);
416976dda93cSYan, Zheng 		mutex_unlock(&fs_info->cleaner_mutex);
4170ff612ba7SJosef Bacik 		if (ret < 0)
41715d4f98a2SYan Zheng 			err = ret;
4172ff612ba7SJosef Bacik 
4173430640e3SQu Wenruo 		finishes_stage = rc->stage;
4174ff612ba7SJosef Bacik 		/*
4175ff612ba7SJosef Bacik 		 * We may have gotten ENOSPC after we already dirtied some
4176ff612ba7SJosef Bacik 		 * extents.  If writeout happens while we're relocating a
4177ff612ba7SJosef Bacik 		 * different block group we could end up hitting the
4178ff612ba7SJosef Bacik 		 * BUG_ON(rc->stage == UPDATE_DATA_PTRS) in
4179ff612ba7SJosef Bacik 		 * btrfs_reloc_cow_block.  Make sure we write everything out
4180ff612ba7SJosef Bacik 		 * properly so we don't trip over this problem, and then break
4181ff612ba7SJosef Bacik 		 * out of the loop if we hit an error.
4182ff612ba7SJosef Bacik 		 */
4183ff612ba7SJosef Bacik 		if (rc->stage == MOVE_DATA_EXTENTS && rc->found_file_extent) {
4184ff612ba7SJosef Bacik 			ret = btrfs_wait_ordered_range(rc->data_inode, 0,
4185ff612ba7SJosef Bacik 						       (u64)-1);
4186ff612ba7SJosef Bacik 			if (ret)
4187ff612ba7SJosef Bacik 				err = ret;
4188ff612ba7SJosef Bacik 			invalidate_mapping_pages(rc->data_inode->i_mapping,
4189ff612ba7SJosef Bacik 						 0, -1);
4190ff612ba7SJosef Bacik 			rc->stage = UPDATE_DATA_PTRS;
41915d4f98a2SYan Zheng 		}
41925d4f98a2SYan Zheng 
4193ff612ba7SJosef Bacik 		if (err < 0)
4194ff612ba7SJosef Bacik 			goto out;
4195ff612ba7SJosef Bacik 
41965d4f98a2SYan Zheng 		if (rc->extents_found == 0)
41975d4f98a2SYan Zheng 			break;
41985d4f98a2SYan Zheng 
4199430640e3SQu Wenruo 		btrfs_info(fs_info, "found %llu extents, stage: %s",
4200430640e3SQu Wenruo 			   rc->extents_found, stage_to_string(finishes_stage));
42015d4f98a2SYan Zheng 	}
42025d4f98a2SYan Zheng 
42035d4f98a2SYan Zheng 	WARN_ON(rc->block_group->pinned > 0);
42045d4f98a2SYan Zheng 	WARN_ON(rc->block_group->reserved > 0);
4205bf38be65SDavid Sterba 	WARN_ON(rc->block_group->used > 0);
42065d4f98a2SYan Zheng out:
4207f0486c68SYan, Zheng 	if (err && rw)
42082ff7e61eSJeff Mahoney 		btrfs_dec_block_group_ro(rc->block_group);
42095d4f98a2SYan Zheng 	iput(rc->data_inode);
42105d4f98a2SYan Zheng 	btrfs_put_block_group(rc->block_group);
42111a0afa0eSJosef Bacik 	free_reloc_control(rc);
42125d4f98a2SYan Zheng 	return err;
42135d4f98a2SYan Zheng }
42145d4f98a2SYan Zheng 
421576dda93cSYan, Zheng static noinline_for_stack int mark_garbage_root(struct btrfs_root *root)
421676dda93cSYan, Zheng {
42170b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
421876dda93cSYan, Zheng 	struct btrfs_trans_handle *trans;
421979787eaaSJeff Mahoney 	int ret, err;
422076dda93cSYan, Zheng 
42210b246afaSJeff Mahoney 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
422279787eaaSJeff Mahoney 	if (IS_ERR(trans))
422379787eaaSJeff Mahoney 		return PTR_ERR(trans);
422476dda93cSYan, Zheng 
422576dda93cSYan, Zheng 	memset(&root->root_item.drop_progress, 0,
422676dda93cSYan, Zheng 		sizeof(root->root_item.drop_progress));
422776dda93cSYan, Zheng 	root->root_item.drop_level = 0;
422876dda93cSYan, Zheng 	btrfs_set_root_refs(&root->root_item, 0);
42290b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
423076dda93cSYan, Zheng 				&root->root_key, &root->root_item);
423176dda93cSYan, Zheng 
42323a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
423379787eaaSJeff Mahoney 	if (err)
423479787eaaSJeff Mahoney 		return err;
423579787eaaSJeff Mahoney 	return ret;
423676dda93cSYan, Zheng }
423776dda93cSYan, Zheng 
42385d4f98a2SYan Zheng /*
42395d4f98a2SYan Zheng  * recover relocation interrupted by system crash.
42405d4f98a2SYan Zheng  *
42415d4f98a2SYan Zheng  * this function resumes merging reloc trees with corresponding fs trees.
42425d4f98a2SYan Zheng  * this is important for keeping the sharing of tree blocks
42435d4f98a2SYan Zheng  */
42445d4f98a2SYan Zheng int btrfs_recover_relocation(struct btrfs_root *root)
42455d4f98a2SYan Zheng {
42460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
42475d4f98a2SYan Zheng 	LIST_HEAD(reloc_roots);
42485d4f98a2SYan Zheng 	struct btrfs_key key;
42495d4f98a2SYan Zheng 	struct btrfs_root *fs_root;
42505d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
42515d4f98a2SYan Zheng 	struct btrfs_path *path;
42525d4f98a2SYan Zheng 	struct extent_buffer *leaf;
42535d4f98a2SYan Zheng 	struct reloc_control *rc = NULL;
42545d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
42555d4f98a2SYan Zheng 	int ret;
42565d4f98a2SYan Zheng 	int err = 0;
42575d4f98a2SYan Zheng 
42585d4f98a2SYan Zheng 	path = btrfs_alloc_path();
42595d4f98a2SYan Zheng 	if (!path)
42605d4f98a2SYan Zheng 		return -ENOMEM;
4261e4058b54SDavid Sterba 	path->reada = READA_BACK;
42625d4f98a2SYan Zheng 
42635d4f98a2SYan Zheng 	key.objectid = BTRFS_TREE_RELOC_OBJECTID;
42645d4f98a2SYan Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
42655d4f98a2SYan Zheng 	key.offset = (u64)-1;
42665d4f98a2SYan Zheng 
42675d4f98a2SYan Zheng 	while (1) {
42680b246afaSJeff Mahoney 		ret = btrfs_search_slot(NULL, fs_info->tree_root, &key,
42695d4f98a2SYan Zheng 					path, 0, 0);
42705d4f98a2SYan Zheng 		if (ret < 0) {
42715d4f98a2SYan Zheng 			err = ret;
42725d4f98a2SYan Zheng 			goto out;
42735d4f98a2SYan Zheng 		}
42745d4f98a2SYan Zheng 		if (ret > 0) {
42755d4f98a2SYan Zheng 			if (path->slots[0] == 0)
42765d4f98a2SYan Zheng 				break;
42775d4f98a2SYan Zheng 			path->slots[0]--;
42785d4f98a2SYan Zheng 		}
42795d4f98a2SYan Zheng 		leaf = path->nodes[0];
42805d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4281b3b4aa74SDavid Sterba 		btrfs_release_path(path);
42825d4f98a2SYan Zheng 
42835d4f98a2SYan Zheng 		if (key.objectid != BTRFS_TREE_RELOC_OBJECTID ||
42845d4f98a2SYan Zheng 		    key.type != BTRFS_ROOT_ITEM_KEY)
42855d4f98a2SYan Zheng 			break;
42865d4f98a2SYan Zheng 
42873dbf1738SJosef Bacik 		reloc_root = btrfs_read_tree_root(root, &key);
42885d4f98a2SYan Zheng 		if (IS_ERR(reloc_root)) {
42895d4f98a2SYan Zheng 			err = PTR_ERR(reloc_root);
42905d4f98a2SYan Zheng 			goto out;
42915d4f98a2SYan Zheng 		}
42925d4f98a2SYan Zheng 
42933dbf1738SJosef Bacik 		set_bit(BTRFS_ROOT_REF_COWS, &reloc_root->state);
42945d4f98a2SYan Zheng 		list_add(&reloc_root->root_list, &reloc_roots);
42955d4f98a2SYan Zheng 
42965d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
42970b246afaSJeff Mahoney 			fs_root = read_fs_root(fs_info,
42985d4f98a2SYan Zheng 					       reloc_root->root_key.offset);
42995d4f98a2SYan Zheng 			if (IS_ERR(fs_root)) {
430076dda93cSYan, Zheng 				ret = PTR_ERR(fs_root);
430176dda93cSYan, Zheng 				if (ret != -ENOENT) {
430276dda93cSYan, Zheng 					err = ret;
43035d4f98a2SYan Zheng 					goto out;
43045d4f98a2SYan Zheng 				}
430579787eaaSJeff Mahoney 				ret = mark_garbage_root(reloc_root);
430679787eaaSJeff Mahoney 				if (ret < 0) {
430779787eaaSJeff Mahoney 					err = ret;
430879787eaaSJeff Mahoney 					goto out;
430979787eaaSJeff Mahoney 				}
4310932fd26dSJosef Bacik 			} else {
431100246528SJosef Bacik 				btrfs_put_root(fs_root);
431276dda93cSYan, Zheng 			}
43135d4f98a2SYan Zheng 		}
43145d4f98a2SYan Zheng 
43155d4f98a2SYan Zheng 		if (key.offset == 0)
43165d4f98a2SYan Zheng 			break;
43175d4f98a2SYan Zheng 
43185d4f98a2SYan Zheng 		key.offset--;
43195d4f98a2SYan Zheng 	}
4320b3b4aa74SDavid Sterba 	btrfs_release_path(path);
43215d4f98a2SYan Zheng 
43225d4f98a2SYan Zheng 	if (list_empty(&reloc_roots))
43235d4f98a2SYan Zheng 		goto out;
43245d4f98a2SYan Zheng 
4325c258d6e3SQu Wenruo 	rc = alloc_reloc_control(fs_info);
43265d4f98a2SYan Zheng 	if (!rc) {
43275d4f98a2SYan Zheng 		err = -ENOMEM;
43285d4f98a2SYan Zheng 		goto out;
43295d4f98a2SYan Zheng 	}
43305d4f98a2SYan Zheng 
43310b246afaSJeff Mahoney 	rc->extent_root = fs_info->extent_root;
43325d4f98a2SYan Zheng 
43335d4f98a2SYan Zheng 	set_reloc_control(rc);
43345d4f98a2SYan Zheng 
43357a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
43363612b495STsutomu Itoh 	if (IS_ERR(trans)) {
43373612b495STsutomu Itoh 		err = PTR_ERR(trans);
4338fb2d83eeSJosef Bacik 		goto out_unset;
43393612b495STsutomu Itoh 	}
43403fd0a558SYan, Zheng 
43413fd0a558SYan, Zheng 	rc->merge_reloc_tree = 1;
43423fd0a558SYan, Zheng 
43435d4f98a2SYan Zheng 	while (!list_empty(&reloc_roots)) {
43445d4f98a2SYan Zheng 		reloc_root = list_entry(reloc_roots.next,
43455d4f98a2SYan Zheng 					struct btrfs_root, root_list);
43465d4f98a2SYan Zheng 		list_del(&reloc_root->root_list);
43475d4f98a2SYan Zheng 
43485d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) == 0) {
43495d4f98a2SYan Zheng 			list_add_tail(&reloc_root->root_list,
43505d4f98a2SYan Zheng 				      &rc->reloc_roots);
43515d4f98a2SYan Zheng 			continue;
43525d4f98a2SYan Zheng 		}
43535d4f98a2SYan Zheng 
43540b246afaSJeff Mahoney 		fs_root = read_fs_root(fs_info, reloc_root->root_key.offset);
435579787eaaSJeff Mahoney 		if (IS_ERR(fs_root)) {
435679787eaaSJeff Mahoney 			err = PTR_ERR(fs_root);
4357ca1aa281SJosef Bacik 			list_add_tail(&reloc_root->root_list, &reloc_roots);
43581402d17dSXiyu Yang 			btrfs_end_transaction(trans);
4359fb2d83eeSJosef Bacik 			goto out_unset;
436079787eaaSJeff Mahoney 		}
43615d4f98a2SYan Zheng 
4362ffd7b339SJeff Mahoney 		err = __add_reloc_root(reloc_root);
436379787eaaSJeff Mahoney 		BUG_ON(err < 0); /* -ENOMEM or logic error */
4364f44deb74SJosef Bacik 		fs_root->reloc_root = btrfs_grab_root(reloc_root);
436500246528SJosef Bacik 		btrfs_put_root(fs_root);
43665d4f98a2SYan Zheng 	}
43675d4f98a2SYan Zheng 
43683a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
436979787eaaSJeff Mahoney 	if (err)
4370fb2d83eeSJosef Bacik 		goto out_unset;
43715d4f98a2SYan Zheng 
43725d4f98a2SYan Zheng 	merge_reloc_roots(rc);
43735d4f98a2SYan Zheng 
43745d4f98a2SYan Zheng 	unset_reloc_control(rc);
43755d4f98a2SYan Zheng 
43767a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
437762b99540SQu Wenruo 	if (IS_ERR(trans)) {
43783612b495STsutomu Itoh 		err = PTR_ERR(trans);
43796217b0faSJosef Bacik 		goto out_clean;
438062b99540SQu Wenruo 	}
43813a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
43826217b0faSJosef Bacik out_clean:
4383d2311e69SQu Wenruo 	ret = clean_dirty_subvols(rc);
4384d2311e69SQu Wenruo 	if (ret < 0 && !err)
4385d2311e69SQu Wenruo 		err = ret;
4386fb2d83eeSJosef Bacik out_unset:
4387fb2d83eeSJosef Bacik 	unset_reloc_control(rc);
43881a0afa0eSJosef Bacik 	free_reloc_control(rc);
43893612b495STsutomu Itoh out:
4390aca1bba6SLiu Bo 	if (!list_empty(&reloc_roots))
4391aca1bba6SLiu Bo 		free_reloc_roots(&reloc_roots);
4392aca1bba6SLiu Bo 
43935d4f98a2SYan Zheng 	btrfs_free_path(path);
43945d4f98a2SYan Zheng 
43955d4f98a2SYan Zheng 	if (err == 0) {
43965d4f98a2SYan Zheng 		/* cleanup orphan inode in data relocation tree */
43970b246afaSJeff Mahoney 		fs_root = read_fs_root(fs_info, BTRFS_DATA_RELOC_TREE_OBJECTID);
4398932fd26dSJosef Bacik 		if (IS_ERR(fs_root)) {
43995d4f98a2SYan Zheng 			err = PTR_ERR(fs_root);
4400932fd26dSJosef Bacik 		} else {
440166b4ffd1SJosef Bacik 			err = btrfs_orphan_cleanup(fs_root);
440200246528SJosef Bacik 			btrfs_put_root(fs_root);
4403932fd26dSJosef Bacik 		}
4404932fd26dSJosef Bacik 	}
44055d4f98a2SYan Zheng 	return err;
44065d4f98a2SYan Zheng }
44075d4f98a2SYan Zheng 
44085d4f98a2SYan Zheng /*
44095d4f98a2SYan Zheng  * helper to add ordered checksum for data relocation.
44105d4f98a2SYan Zheng  *
44115d4f98a2SYan Zheng  * cloning checksum properly handles the nodatasum extents.
44125d4f98a2SYan Zheng  * it also saves CPU time to re-calculate the checksum.
44135d4f98a2SYan Zheng  */
44145d4f98a2SYan Zheng int btrfs_reloc_clone_csums(struct inode *inode, u64 file_pos, u64 len)
44155d4f98a2SYan Zheng {
44160b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
44175d4f98a2SYan Zheng 	struct btrfs_ordered_sum *sums;
44185d4f98a2SYan Zheng 	struct btrfs_ordered_extent *ordered;
44195d4f98a2SYan Zheng 	int ret;
44205d4f98a2SYan Zheng 	u64 disk_bytenr;
44214577b014SJosef Bacik 	u64 new_bytenr;
44225d4f98a2SYan Zheng 	LIST_HEAD(list);
44235d4f98a2SYan Zheng 
44245d4f98a2SYan Zheng 	ordered = btrfs_lookup_ordered_extent(inode, file_pos);
4425bffe633eSOmar Sandoval 	BUG_ON(ordered->file_offset != file_pos || ordered->num_bytes != len);
44265d4f98a2SYan Zheng 
44275d4f98a2SYan Zheng 	disk_bytenr = file_pos + BTRFS_I(inode)->index_cnt;
44280b246afaSJeff Mahoney 	ret = btrfs_lookup_csums_range(fs_info->csum_root, disk_bytenr,
4429a2de733cSArne Jansen 				       disk_bytenr + len - 1, &list, 0);
443079787eaaSJeff Mahoney 	if (ret)
443179787eaaSJeff Mahoney 		goto out;
44325d4f98a2SYan Zheng 
44335d4f98a2SYan Zheng 	while (!list_empty(&list)) {
44345d4f98a2SYan Zheng 		sums = list_entry(list.next, struct btrfs_ordered_sum, list);
44355d4f98a2SYan Zheng 		list_del_init(&sums->list);
44365d4f98a2SYan Zheng 
44374577b014SJosef Bacik 		/*
44384577b014SJosef Bacik 		 * We need to offset the new_bytenr based on where the csum is.
44394577b014SJosef Bacik 		 * We need to do this because we will read in entire prealloc
44404577b014SJosef Bacik 		 * extents but we may have written to say the middle of the
44414577b014SJosef Bacik 		 * prealloc extent, so we need to make sure the csum goes with
44424577b014SJosef Bacik 		 * the right disk offset.
44434577b014SJosef Bacik 		 *
44444577b014SJosef Bacik 		 * We can do this because the data reloc inode refers strictly
44454577b014SJosef Bacik 		 * to the on disk bytes, so we don't have to worry about
44464577b014SJosef Bacik 		 * disk_len vs real len like with real inodes since it's all
44474577b014SJosef Bacik 		 * disk length.
44484577b014SJosef Bacik 		 */
4449bffe633eSOmar Sandoval 		new_bytenr = ordered->disk_bytenr + sums->bytenr - disk_bytenr;
44504577b014SJosef Bacik 		sums->bytenr = new_bytenr;
44515d4f98a2SYan Zheng 
4452f9756261SNikolay Borisov 		btrfs_add_ordered_sum(ordered, sums);
44535d4f98a2SYan Zheng 	}
445479787eaaSJeff Mahoney out:
44555d4f98a2SYan Zheng 	btrfs_put_ordered_extent(ordered);
4456411fc6bcSAndi Kleen 	return ret;
44575d4f98a2SYan Zheng }
44583fd0a558SYan, Zheng 
445983d4cfd4SJosef Bacik int btrfs_reloc_cow_block(struct btrfs_trans_handle *trans,
44603fd0a558SYan, Zheng 			  struct btrfs_root *root, struct extent_buffer *buf,
44613fd0a558SYan, Zheng 			  struct extent_buffer *cow)
44623fd0a558SYan, Zheng {
44630b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
44643fd0a558SYan, Zheng 	struct reloc_control *rc;
4465a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
44663fd0a558SYan, Zheng 	int first_cow = 0;
44673fd0a558SYan, Zheng 	int level;
446883d4cfd4SJosef Bacik 	int ret = 0;
44693fd0a558SYan, Zheng 
44700b246afaSJeff Mahoney 	rc = fs_info->reloc_ctl;
44713fd0a558SYan, Zheng 	if (!rc)
447283d4cfd4SJosef Bacik 		return 0;
44733fd0a558SYan, Zheng 
44743fd0a558SYan, Zheng 	BUG_ON(rc->stage == UPDATE_DATA_PTRS &&
44753fd0a558SYan, Zheng 	       root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID);
44763fd0a558SYan, Zheng 
44773fd0a558SYan, Zheng 	level = btrfs_header_level(buf);
44783fd0a558SYan, Zheng 	if (btrfs_header_generation(buf) <=
44793fd0a558SYan, Zheng 	    btrfs_root_last_snapshot(&root->root_item))
44803fd0a558SYan, Zheng 		first_cow = 1;
44813fd0a558SYan, Zheng 
44823fd0a558SYan, Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID &&
44833fd0a558SYan, Zheng 	    rc->create_reloc_tree) {
44843fd0a558SYan, Zheng 		WARN_ON(!first_cow && level == 0);
44853fd0a558SYan, Zheng 
44863fd0a558SYan, Zheng 		node = rc->backref_cache.path[level];
44873fd0a558SYan, Zheng 		BUG_ON(node->bytenr != buf->start &&
44883fd0a558SYan, Zheng 		       node->new_bytenr != buf->start);
44893fd0a558SYan, Zheng 
4490b0fe7078SQu Wenruo 		btrfs_backref_drop_node_buffer(node);
449167439dadSDavid Sterba 		atomic_inc(&cow->refs);
44923fd0a558SYan, Zheng 		node->eb = cow;
44933fd0a558SYan, Zheng 		node->new_bytenr = cow->start;
44943fd0a558SYan, Zheng 
44953fd0a558SYan, Zheng 		if (!node->pending) {
44963fd0a558SYan, Zheng 			list_move_tail(&node->list,
44973fd0a558SYan, Zheng 				       &rc->backref_cache.pending[level]);
44983fd0a558SYan, Zheng 			node->pending = 1;
44993fd0a558SYan, Zheng 		}
45003fd0a558SYan, Zheng 
45013fd0a558SYan, Zheng 		if (first_cow)
45029569cc20SQu Wenruo 			mark_block_processed(rc, node);
45033fd0a558SYan, Zheng 
45043fd0a558SYan, Zheng 		if (first_cow && level > 0)
45053fd0a558SYan, Zheng 			rc->nodes_relocated += buf->len;
45063fd0a558SYan, Zheng 	}
45073fd0a558SYan, Zheng 
450883d4cfd4SJosef Bacik 	if (level == 0 && first_cow && rc->stage == UPDATE_DATA_PTRS)
45093fd0a558SYan, Zheng 		ret = replace_file_extents(trans, rc, root, cow);
451083d4cfd4SJosef Bacik 	return ret;
45113fd0a558SYan, Zheng }
45123fd0a558SYan, Zheng 
45133fd0a558SYan, Zheng /*
45143fd0a558SYan, Zheng  * called before creating snapshot. it calculates metadata reservation
451501327610SNicholas D Steeves  * required for relocating tree blocks in the snapshot
45163fd0a558SYan, Zheng  */
4517147d256eSZhaolei void btrfs_reloc_pre_snapshot(struct btrfs_pending_snapshot *pending,
45183fd0a558SYan, Zheng 			      u64 *bytes_to_reserve)
45193fd0a558SYan, Zheng {
452010995c04SQu Wenruo 	struct btrfs_root *root = pending->root;
452110995c04SQu Wenruo 	struct reloc_control *rc = root->fs_info->reloc_ctl;
45223fd0a558SYan, Zheng 
45236282675eSQu Wenruo 	if (!rc || !have_reloc_root(root))
45243fd0a558SYan, Zheng 		return;
45253fd0a558SYan, Zheng 
45263fd0a558SYan, Zheng 	if (!rc->merge_reloc_tree)
45273fd0a558SYan, Zheng 		return;
45283fd0a558SYan, Zheng 
45293fd0a558SYan, Zheng 	root = root->reloc_root;
45303fd0a558SYan, Zheng 	BUG_ON(btrfs_root_refs(&root->root_item) == 0);
45313fd0a558SYan, Zheng 	/*
45323fd0a558SYan, Zheng 	 * relocation is in the stage of merging trees. the space
45333fd0a558SYan, Zheng 	 * used by merging a reloc tree is twice the size of
45343fd0a558SYan, Zheng 	 * relocated tree nodes in the worst case. half for cowing
45353fd0a558SYan, Zheng 	 * the reloc tree, half for cowing the fs tree. the space
45363fd0a558SYan, Zheng 	 * used by cowing the reloc tree will be freed after the
45373fd0a558SYan, Zheng 	 * tree is dropped. if we create snapshot, cowing the fs
45383fd0a558SYan, Zheng 	 * tree may use more space than it frees. so we need
45393fd0a558SYan, Zheng 	 * reserve extra space.
45403fd0a558SYan, Zheng 	 */
45413fd0a558SYan, Zheng 	*bytes_to_reserve += rc->nodes_relocated;
45423fd0a558SYan, Zheng }
45433fd0a558SYan, Zheng 
45443fd0a558SYan, Zheng /*
45453fd0a558SYan, Zheng  * called after snapshot is created. migrate block reservation
45463fd0a558SYan, Zheng  * and create reloc root for the newly created snapshot
4547f44deb74SJosef Bacik  *
4548f44deb74SJosef Bacik  * This is similar to btrfs_init_reloc_root(), we come out of here with two
4549f44deb74SJosef Bacik  * references held on the reloc_root, one for root->reloc_root and one for
4550f44deb74SJosef Bacik  * rc->reloc_roots.
45513fd0a558SYan, Zheng  */
455249b25e05SJeff Mahoney int btrfs_reloc_post_snapshot(struct btrfs_trans_handle *trans,
45533fd0a558SYan, Zheng 			       struct btrfs_pending_snapshot *pending)
45543fd0a558SYan, Zheng {
45553fd0a558SYan, Zheng 	struct btrfs_root *root = pending->root;
45563fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
45573fd0a558SYan, Zheng 	struct btrfs_root *new_root;
455810995c04SQu Wenruo 	struct reloc_control *rc = root->fs_info->reloc_ctl;
45593fd0a558SYan, Zheng 	int ret;
45603fd0a558SYan, Zheng 
45616282675eSQu Wenruo 	if (!rc || !have_reloc_root(root))
456249b25e05SJeff Mahoney 		return 0;
45633fd0a558SYan, Zheng 
45643fd0a558SYan, Zheng 	rc = root->fs_info->reloc_ctl;
45653fd0a558SYan, Zheng 	rc->merging_rsv_size += rc->nodes_relocated;
45663fd0a558SYan, Zheng 
45673fd0a558SYan, Zheng 	if (rc->merge_reloc_tree) {
45683fd0a558SYan, Zheng 		ret = btrfs_block_rsv_migrate(&pending->block_rsv,
45693fd0a558SYan, Zheng 					      rc->block_rsv,
45703a584174SLu Fengqi 					      rc->nodes_relocated, true);
457149b25e05SJeff Mahoney 		if (ret)
457249b25e05SJeff Mahoney 			return ret;
45733fd0a558SYan, Zheng 	}
45743fd0a558SYan, Zheng 
45753fd0a558SYan, Zheng 	new_root = pending->snap;
45763fd0a558SYan, Zheng 	reloc_root = create_reloc_root(trans, root->reloc_root,
45773fd0a558SYan, Zheng 				       new_root->root_key.objectid);
457849b25e05SJeff Mahoney 	if (IS_ERR(reloc_root))
457949b25e05SJeff Mahoney 		return PTR_ERR(reloc_root);
45803fd0a558SYan, Zheng 
4581ffd7b339SJeff Mahoney 	ret = __add_reloc_root(reloc_root);
4582ffd7b339SJeff Mahoney 	BUG_ON(ret < 0);
4583f44deb74SJosef Bacik 	new_root->reloc_root = btrfs_grab_root(reloc_root);
45843fd0a558SYan, Zheng 
458549b25e05SJeff Mahoney 	if (rc->create_reloc_tree)
45863fd0a558SYan, Zheng 		ret = clone_backref_node(trans, rc, root, reloc_root);
458749b25e05SJeff Mahoney 	return ret;
45883fd0a558SYan, Zheng }
4589