xref: /openbmc/linux/fs/btrfs/relocation.c (revision c2832898)
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"
2162b99540SQu Wenruo #include "qgroup.h"
22cdccee99SLiu Bo #include "print-tree.h"
2386736342SJosef Bacik #include "delalloc-space.h"
24aac0023cSJosef Bacik #include "block-group.h"
2519b546d7SQu Wenruo #include "backref.h"
26e9a28dc5SQu Wenruo #include "misc.h"
27*c2832898SQu Wenruo #include "subpage.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 */
101f7ba2d37SJosef Bacik 	u64 owner;
1025d4f98a2SYan Zheng 	struct btrfs_key key;
1035d4f98a2SYan Zheng 	unsigned int level:8;
1045d4f98a2SYan Zheng 	unsigned int key_ready:1;
1055d4f98a2SYan Zheng };
1065d4f98a2SYan Zheng 
1070257bb82SYan, Zheng #define MAX_EXTENTS 128
1080257bb82SYan, Zheng 
1090257bb82SYan, Zheng struct file_extent_cluster {
1100257bb82SYan, Zheng 	u64 start;
1110257bb82SYan, Zheng 	u64 end;
1120257bb82SYan, Zheng 	u64 boundary[MAX_EXTENTS];
1130257bb82SYan, Zheng 	unsigned int nr;
1140257bb82SYan, Zheng };
1150257bb82SYan, Zheng 
1165d4f98a2SYan Zheng struct reloc_control {
1175d4f98a2SYan Zheng 	/* block group to relocate */
11832da5386SDavid Sterba 	struct btrfs_block_group *block_group;
1195d4f98a2SYan Zheng 	/* extent tree */
1205d4f98a2SYan Zheng 	struct btrfs_root *extent_root;
1215d4f98a2SYan Zheng 	/* inode for moving data */
1225d4f98a2SYan Zheng 	struct inode *data_inode;
1233fd0a558SYan, Zheng 
1243fd0a558SYan, Zheng 	struct btrfs_block_rsv *block_rsv;
1253fd0a558SYan, Zheng 
126a26195a5SQu Wenruo 	struct btrfs_backref_cache backref_cache;
1273fd0a558SYan, Zheng 
1283fd0a558SYan, Zheng 	struct file_extent_cluster cluster;
1295d4f98a2SYan Zheng 	/* tree blocks have been processed */
1305d4f98a2SYan Zheng 	struct extent_io_tree processed_blocks;
1315d4f98a2SYan Zheng 	/* map start of tree root to corresponding reloc tree */
1325d4f98a2SYan Zheng 	struct mapping_tree reloc_root_tree;
1335d4f98a2SYan Zheng 	/* list of reloc trees */
1345d4f98a2SYan Zheng 	struct list_head reloc_roots;
135d2311e69SQu Wenruo 	/* list of subvolume trees that get relocated */
136d2311e69SQu Wenruo 	struct list_head dirty_subvol_roots;
1373fd0a558SYan, Zheng 	/* size of metadata reservation for merging reloc trees */
1383fd0a558SYan, Zheng 	u64 merging_rsv_size;
1393fd0a558SYan, Zheng 	/* size of relocated tree nodes */
1403fd0a558SYan, Zheng 	u64 nodes_relocated;
1410647bf56SWang Shilong 	/* reserved size for block group relocation*/
1420647bf56SWang Shilong 	u64 reserved_bytes;
1433fd0a558SYan, Zheng 
1445d4f98a2SYan Zheng 	u64 search_start;
1455d4f98a2SYan Zheng 	u64 extents_found;
1463fd0a558SYan, Zheng 
1473fd0a558SYan, Zheng 	unsigned int stage:8;
1483fd0a558SYan, Zheng 	unsigned int create_reloc_tree:1;
1493fd0a558SYan, Zheng 	unsigned int merge_reloc_tree:1;
1505d4f98a2SYan Zheng 	unsigned int found_file_extent:1;
1515d4f98a2SYan Zheng };
1525d4f98a2SYan Zheng 
1535d4f98a2SYan Zheng /* stages of data relocation */
1545d4f98a2SYan Zheng #define MOVE_DATA_EXTENTS	0
1555d4f98a2SYan Zheng #define UPDATE_DATA_PTRS	1
1565d4f98a2SYan Zheng 
1579569cc20SQu Wenruo static void mark_block_processed(struct reloc_control *rc,
158a26195a5SQu Wenruo 				 struct btrfs_backref_node *node)
1599569cc20SQu Wenruo {
1609569cc20SQu Wenruo 	u32 blocksize;
1619569cc20SQu Wenruo 
1629569cc20SQu Wenruo 	if (node->level == 0 ||
1639569cc20SQu Wenruo 	    in_range(node->bytenr, rc->block_group->start,
1649569cc20SQu Wenruo 		     rc->block_group->length)) {
1659569cc20SQu Wenruo 		blocksize = rc->extent_root->fs_info->nodesize;
1669569cc20SQu Wenruo 		set_extent_bits(&rc->processed_blocks, node->bytenr,
1679569cc20SQu Wenruo 				node->bytenr + blocksize - 1, EXTENT_DIRTY);
1689569cc20SQu Wenruo 	}
1699569cc20SQu Wenruo 	node->processed = 1;
1709569cc20SQu Wenruo }
1719569cc20SQu Wenruo 
1725d4f98a2SYan Zheng 
1735d4f98a2SYan Zheng static void mapping_tree_init(struct mapping_tree *tree)
1745d4f98a2SYan Zheng {
1756bef4d31SEric Paris 	tree->rb_root = RB_ROOT;
1765d4f98a2SYan Zheng 	spin_lock_init(&tree->lock);
1775d4f98a2SYan Zheng }
1785d4f98a2SYan Zheng 
1795d4f98a2SYan Zheng /*
1805d4f98a2SYan Zheng  * walk up backref nodes until reach node presents tree root
1815d4f98a2SYan Zheng  */
182a26195a5SQu Wenruo static struct btrfs_backref_node *walk_up_backref(
183a26195a5SQu Wenruo 		struct btrfs_backref_node *node,
184a26195a5SQu Wenruo 		struct btrfs_backref_edge *edges[], int *index)
1855d4f98a2SYan Zheng {
186a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
1875d4f98a2SYan Zheng 	int idx = *index;
1885d4f98a2SYan Zheng 
1895d4f98a2SYan Zheng 	while (!list_empty(&node->upper)) {
1905d4f98a2SYan Zheng 		edge = list_entry(node->upper.next,
191a26195a5SQu Wenruo 				  struct btrfs_backref_edge, list[LOWER]);
1925d4f98a2SYan Zheng 		edges[idx++] = edge;
1935d4f98a2SYan Zheng 		node = edge->node[UPPER];
1945d4f98a2SYan Zheng 	}
1953fd0a558SYan, Zheng 	BUG_ON(node->detached);
1965d4f98a2SYan Zheng 	*index = idx;
1975d4f98a2SYan Zheng 	return node;
1985d4f98a2SYan Zheng }
1995d4f98a2SYan Zheng 
2005d4f98a2SYan Zheng /*
2015d4f98a2SYan Zheng  * walk down backref nodes to find start of next reference path
2025d4f98a2SYan Zheng  */
203a26195a5SQu Wenruo static struct btrfs_backref_node *walk_down_backref(
204a26195a5SQu Wenruo 		struct btrfs_backref_edge *edges[], int *index)
2055d4f98a2SYan Zheng {
206a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
207a26195a5SQu Wenruo 	struct btrfs_backref_node *lower;
2085d4f98a2SYan Zheng 	int idx = *index;
2095d4f98a2SYan Zheng 
2105d4f98a2SYan Zheng 	while (idx > 0) {
2115d4f98a2SYan Zheng 		edge = edges[idx - 1];
2125d4f98a2SYan Zheng 		lower = edge->node[LOWER];
2135d4f98a2SYan Zheng 		if (list_is_last(&edge->list[LOWER], &lower->upper)) {
2145d4f98a2SYan Zheng 			idx--;
2155d4f98a2SYan Zheng 			continue;
2165d4f98a2SYan Zheng 		}
2175d4f98a2SYan Zheng 		edge = list_entry(edge->list[LOWER].next,
218a26195a5SQu Wenruo 				  struct btrfs_backref_edge, list[LOWER]);
2195d4f98a2SYan Zheng 		edges[idx - 1] = edge;
2205d4f98a2SYan Zheng 		*index = idx;
2215d4f98a2SYan Zheng 		return edge->node[UPPER];
2225d4f98a2SYan Zheng 	}
2235d4f98a2SYan Zheng 	*index = 0;
2245d4f98a2SYan Zheng 	return NULL;
2255d4f98a2SYan Zheng }
2265d4f98a2SYan Zheng 
227a26195a5SQu Wenruo static void update_backref_node(struct btrfs_backref_cache *cache,
228a26195a5SQu Wenruo 				struct btrfs_backref_node *node, u64 bytenr)
2293fd0a558SYan, Zheng {
2303fd0a558SYan, Zheng 	struct rb_node *rb_node;
2313fd0a558SYan, Zheng 	rb_erase(&node->rb_node, &cache->rb_root);
2323fd0a558SYan, Zheng 	node->bytenr = bytenr;
233e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&cache->rb_root, node->bytenr, &node->rb_node);
23443c04fb1SJeff Mahoney 	if (rb_node)
235982c92cbSQu Wenruo 		btrfs_backref_panic(cache->fs_info, bytenr, -EEXIST);
2363fd0a558SYan, Zheng }
2373fd0a558SYan, Zheng 
2383fd0a558SYan, Zheng /*
2393fd0a558SYan, Zheng  * update backref cache after a transaction commit
2403fd0a558SYan, Zheng  */
2413fd0a558SYan, Zheng static int update_backref_cache(struct btrfs_trans_handle *trans,
242a26195a5SQu Wenruo 				struct btrfs_backref_cache *cache)
2433fd0a558SYan, Zheng {
244a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
2453fd0a558SYan, Zheng 	int level = 0;
2463fd0a558SYan, Zheng 
2473fd0a558SYan, Zheng 	if (cache->last_trans == 0) {
2483fd0a558SYan, Zheng 		cache->last_trans = trans->transid;
2493fd0a558SYan, Zheng 		return 0;
2503fd0a558SYan, Zheng 	}
2513fd0a558SYan, Zheng 
2523fd0a558SYan, Zheng 	if (cache->last_trans == trans->transid)
2533fd0a558SYan, Zheng 		return 0;
2543fd0a558SYan, Zheng 
2553fd0a558SYan, Zheng 	/*
2563fd0a558SYan, Zheng 	 * detached nodes are used to avoid unnecessary backref
2573fd0a558SYan, Zheng 	 * lookup. transaction commit changes the extent tree.
2583fd0a558SYan, Zheng 	 * so the detached nodes are no longer useful.
2593fd0a558SYan, Zheng 	 */
2603fd0a558SYan, Zheng 	while (!list_empty(&cache->detached)) {
2613fd0a558SYan, Zheng 		node = list_entry(cache->detached.next,
262a26195a5SQu Wenruo 				  struct btrfs_backref_node, list);
263023acb07SQu Wenruo 		btrfs_backref_cleanup_node(cache, node);
2643fd0a558SYan, Zheng 	}
2653fd0a558SYan, Zheng 
2663fd0a558SYan, Zheng 	while (!list_empty(&cache->changed)) {
2673fd0a558SYan, Zheng 		node = list_entry(cache->changed.next,
268a26195a5SQu Wenruo 				  struct btrfs_backref_node, list);
2693fd0a558SYan, Zheng 		list_del_init(&node->list);
2703fd0a558SYan, Zheng 		BUG_ON(node->pending);
2713fd0a558SYan, Zheng 		update_backref_node(cache, node, node->new_bytenr);
2723fd0a558SYan, Zheng 	}
2733fd0a558SYan, Zheng 
2743fd0a558SYan, Zheng 	/*
2753fd0a558SYan, Zheng 	 * some nodes can be left in the pending list if there were
2763fd0a558SYan, Zheng 	 * errors during processing the pending nodes.
2773fd0a558SYan, Zheng 	 */
2783fd0a558SYan, Zheng 	for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2793fd0a558SYan, Zheng 		list_for_each_entry(node, &cache->pending[level], list) {
2803fd0a558SYan, Zheng 			BUG_ON(!node->pending);
2813fd0a558SYan, Zheng 			if (node->bytenr == node->new_bytenr)
2823fd0a558SYan, Zheng 				continue;
2833fd0a558SYan, Zheng 			update_backref_node(cache, node, node->new_bytenr);
2843fd0a558SYan, Zheng 		}
2853fd0a558SYan, Zheng 	}
2863fd0a558SYan, Zheng 
2873fd0a558SYan, Zheng 	cache->last_trans = 0;
2883fd0a558SYan, Zheng 	return 1;
2893fd0a558SYan, Zheng }
2903fd0a558SYan, Zheng 
2916282675eSQu Wenruo static bool reloc_root_is_dead(struct btrfs_root *root)
2926282675eSQu Wenruo {
2936282675eSQu Wenruo 	/*
2946282675eSQu Wenruo 	 * Pair with set_bit/clear_bit in clean_dirty_subvols and
2956282675eSQu Wenruo 	 * btrfs_update_reloc_root. We need to see the updated bit before
2966282675eSQu Wenruo 	 * trying to access reloc_root
2976282675eSQu Wenruo 	 */
2986282675eSQu Wenruo 	smp_rmb();
2996282675eSQu Wenruo 	if (test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state))
3006282675eSQu Wenruo 		return true;
3016282675eSQu Wenruo 	return false;
3026282675eSQu Wenruo }
3036282675eSQu Wenruo 
3046282675eSQu Wenruo /*
3056282675eSQu Wenruo  * Check if this subvolume tree has valid reloc tree.
3066282675eSQu Wenruo  *
3076282675eSQu Wenruo  * Reloc tree after swap is considered dead, thus not considered as valid.
3086282675eSQu Wenruo  * This is enough for most callers, as they don't distinguish dead reloc root
30955465730SQu Wenruo  * from no reloc root.  But btrfs_should_ignore_reloc_root() below is a
31055465730SQu Wenruo  * special case.
3116282675eSQu Wenruo  */
3126282675eSQu Wenruo static bool have_reloc_root(struct btrfs_root *root)
3136282675eSQu Wenruo {
3146282675eSQu Wenruo 	if (reloc_root_is_dead(root))
3156282675eSQu Wenruo 		return false;
3166282675eSQu Wenruo 	if (!root->reloc_root)
3176282675eSQu Wenruo 		return false;
3186282675eSQu Wenruo 	return true;
3196282675eSQu Wenruo }
320f2a97a9dSDavid Sterba 
32155465730SQu Wenruo int btrfs_should_ignore_reloc_root(struct btrfs_root *root)
3223fd0a558SYan, Zheng {
3233fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
3243fd0a558SYan, Zheng 
32592a7cc42SQu Wenruo 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
3263fd0a558SYan, Zheng 		return 0;
3273fd0a558SYan, Zheng 
3286282675eSQu Wenruo 	/* This root has been merged with its reloc tree, we can ignore it */
3296282675eSQu Wenruo 	if (reloc_root_is_dead(root))
3306282675eSQu Wenruo 		return 1;
3316282675eSQu Wenruo 
3323fd0a558SYan, Zheng 	reloc_root = root->reloc_root;
3333fd0a558SYan, Zheng 	if (!reloc_root)
3343fd0a558SYan, Zheng 		return 0;
3353fd0a558SYan, Zheng 
3364d4225fcSJosef Bacik 	if (btrfs_header_generation(reloc_root->commit_root) ==
3374d4225fcSJosef Bacik 	    root->fs_info->running_transaction->transid)
3383fd0a558SYan, Zheng 		return 0;
3393fd0a558SYan, Zheng 	/*
3403fd0a558SYan, Zheng 	 * if there is reloc tree and it was created in previous
3413fd0a558SYan, Zheng 	 * transaction backref lookup can find the reloc tree,
3423fd0a558SYan, Zheng 	 * so backref node for the fs tree root is useless for
3433fd0a558SYan, Zheng 	 * relocation.
3443fd0a558SYan, Zheng 	 */
3453fd0a558SYan, Zheng 	return 1;
3463fd0a558SYan, Zheng }
34755465730SQu Wenruo 
3485d4f98a2SYan Zheng /*
3495d4f98a2SYan Zheng  * find reloc tree by address of tree root
3505d4f98a2SYan Zheng  */
3512433bea5SQu Wenruo struct btrfs_root *find_reloc_root(struct btrfs_fs_info *fs_info, u64 bytenr)
3525d4f98a2SYan Zheng {
3532433bea5SQu Wenruo 	struct reloc_control *rc = fs_info->reloc_ctl;
3545d4f98a2SYan Zheng 	struct rb_node *rb_node;
3555d4f98a2SYan Zheng 	struct mapping_node *node;
3565d4f98a2SYan Zheng 	struct btrfs_root *root = NULL;
3575d4f98a2SYan Zheng 
3582433bea5SQu Wenruo 	ASSERT(rc);
3595d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
360e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root, bytenr);
3615d4f98a2SYan Zheng 	if (rb_node) {
3625d4f98a2SYan Zheng 		node = rb_entry(rb_node, struct mapping_node, rb_node);
3635d4f98a2SYan Zheng 		root = (struct btrfs_root *)node->data;
3645d4f98a2SYan Zheng 	}
3655d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
36600246528SJosef Bacik 	return btrfs_grab_root(root);
3675d4f98a2SYan Zheng }
3685d4f98a2SYan Zheng 
3695d4f98a2SYan Zheng /*
37029db137bSQu Wenruo  * For useless nodes, do two major clean ups:
37129db137bSQu Wenruo  *
37229db137bSQu Wenruo  * - Cleanup the children edges and nodes
37329db137bSQu Wenruo  *   If child node is also orphan (no parent) during cleanup, then the child
37429db137bSQu Wenruo  *   node will also be cleaned up.
37529db137bSQu Wenruo  *
37629db137bSQu Wenruo  * - Freeing up leaves (level 0), keeps nodes detached
37729db137bSQu Wenruo  *   For nodes, the node is still cached as "detached"
37829db137bSQu Wenruo  *
37929db137bSQu Wenruo  * Return false if @node is not in the @useless_nodes list.
38029db137bSQu Wenruo  * Return true if @node is in the @useless_nodes list.
38129db137bSQu Wenruo  */
38229db137bSQu Wenruo static bool handle_useless_nodes(struct reloc_control *rc,
383a26195a5SQu Wenruo 				 struct btrfs_backref_node *node)
38429db137bSQu Wenruo {
385a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
38629db137bSQu Wenruo 	struct list_head *useless_node = &cache->useless_node;
38729db137bSQu Wenruo 	bool ret = false;
38829db137bSQu Wenruo 
38929db137bSQu Wenruo 	while (!list_empty(useless_node)) {
390a26195a5SQu Wenruo 		struct btrfs_backref_node *cur;
39129db137bSQu Wenruo 
392a26195a5SQu Wenruo 		cur = list_first_entry(useless_node, struct btrfs_backref_node,
39329db137bSQu Wenruo 				 list);
39429db137bSQu Wenruo 		list_del_init(&cur->list);
39529db137bSQu Wenruo 
39629db137bSQu Wenruo 		/* Only tree root nodes can be added to @useless_nodes */
39729db137bSQu Wenruo 		ASSERT(list_empty(&cur->upper));
39829db137bSQu Wenruo 
39929db137bSQu Wenruo 		if (cur == node)
40029db137bSQu Wenruo 			ret = true;
40129db137bSQu Wenruo 
40229db137bSQu Wenruo 		/* The node is the lowest node */
40329db137bSQu Wenruo 		if (cur->lowest) {
40429db137bSQu Wenruo 			list_del_init(&cur->lower);
40529db137bSQu Wenruo 			cur->lowest = 0;
40629db137bSQu Wenruo 		}
40729db137bSQu Wenruo 
40829db137bSQu Wenruo 		/* Cleanup the lower edges */
40929db137bSQu Wenruo 		while (!list_empty(&cur->lower)) {
410a26195a5SQu Wenruo 			struct btrfs_backref_edge *edge;
411a26195a5SQu Wenruo 			struct btrfs_backref_node *lower;
41229db137bSQu Wenruo 
41329db137bSQu Wenruo 			edge = list_entry(cur->lower.next,
414a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[UPPER]);
41529db137bSQu Wenruo 			list_del(&edge->list[UPPER]);
41629db137bSQu Wenruo 			list_del(&edge->list[LOWER]);
41729db137bSQu Wenruo 			lower = edge->node[LOWER];
418741188d3SQu Wenruo 			btrfs_backref_free_edge(cache, edge);
41929db137bSQu Wenruo 
42029db137bSQu Wenruo 			/* Child node is also orphan, queue for cleanup */
42129db137bSQu Wenruo 			if (list_empty(&lower->upper))
42229db137bSQu Wenruo 				list_add(&lower->list, useless_node);
42329db137bSQu Wenruo 		}
42429db137bSQu Wenruo 		/* Mark this block processed for relocation */
42529db137bSQu Wenruo 		mark_block_processed(rc, cur);
42629db137bSQu Wenruo 
42729db137bSQu Wenruo 		/*
42829db137bSQu Wenruo 		 * Backref nodes for tree leaves are deleted from the cache.
42929db137bSQu Wenruo 		 * Backref nodes for upper level tree blocks are left in the
43029db137bSQu Wenruo 		 * cache to avoid unnecessary backref lookup.
43129db137bSQu Wenruo 		 */
43229db137bSQu Wenruo 		if (cur->level > 0) {
43329db137bSQu Wenruo 			list_add(&cur->list, &cache->detached);
43429db137bSQu Wenruo 			cur->detached = 1;
43529db137bSQu Wenruo 		} else {
43629db137bSQu Wenruo 			rb_erase(&cur->rb_node, &cache->rb_root);
437741188d3SQu Wenruo 			btrfs_backref_free_node(cache, cur);
43829db137bSQu Wenruo 		}
43929db137bSQu Wenruo 	}
44029db137bSQu Wenruo 	return ret;
44129db137bSQu Wenruo }
44229db137bSQu Wenruo 
44329db137bSQu Wenruo /*
444e7d571c7SQu Wenruo  * Build backref tree for a given tree block. Root of the backref tree
445e7d571c7SQu Wenruo  * corresponds the tree block, leaves of the backref tree correspond roots of
446e7d571c7SQu Wenruo  * b-trees that reference the tree block.
447e7d571c7SQu Wenruo  *
448e7d571c7SQu Wenruo  * The basic idea of this function is check backrefs of a given block to find
449e7d571c7SQu Wenruo  * upper level blocks that reference the block, and then check backrefs of
450e7d571c7SQu Wenruo  * these upper level blocks recursively. The recursion stops when tree root is
451e7d571c7SQu Wenruo  * reached or backrefs for the block is cached.
452e7d571c7SQu Wenruo  *
453e7d571c7SQu Wenruo  * NOTE: if we find that backrefs for a block are cached, we know backrefs for
454e7d571c7SQu Wenruo  * all upper level blocks that directly/indirectly reference the block are also
455e7d571c7SQu Wenruo  * cached.
456e7d571c7SQu Wenruo  */
457a26195a5SQu Wenruo static noinline_for_stack struct btrfs_backref_node *build_backref_tree(
458e7d571c7SQu Wenruo 			struct reloc_control *rc, struct btrfs_key *node_key,
459e7d571c7SQu Wenruo 			int level, u64 bytenr)
460e7d571c7SQu Wenruo {
461e7d571c7SQu Wenruo 	struct btrfs_backref_iter *iter;
462a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
463e7d571c7SQu Wenruo 	/* For searching parent of TREE_BLOCK_REF */
464e7d571c7SQu Wenruo 	struct btrfs_path *path;
465a26195a5SQu Wenruo 	struct btrfs_backref_node *cur;
466a26195a5SQu Wenruo 	struct btrfs_backref_node *node = NULL;
467a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
468e7d571c7SQu Wenruo 	int ret;
469e7d571c7SQu Wenruo 	int err = 0;
470e7d571c7SQu Wenruo 
471e7d571c7SQu Wenruo 	iter = btrfs_backref_iter_alloc(rc->extent_root->fs_info, GFP_NOFS);
472e7d571c7SQu Wenruo 	if (!iter)
473e7d571c7SQu Wenruo 		return ERR_PTR(-ENOMEM);
474e7d571c7SQu Wenruo 	path = btrfs_alloc_path();
475e7d571c7SQu Wenruo 	if (!path) {
476e7d571c7SQu Wenruo 		err = -ENOMEM;
477e7d571c7SQu Wenruo 		goto out;
478e7d571c7SQu Wenruo 	}
479e7d571c7SQu Wenruo 
480b1818dabSQu Wenruo 	node = btrfs_backref_alloc_node(cache, bytenr, level);
481e7d571c7SQu Wenruo 	if (!node) {
482e7d571c7SQu Wenruo 		err = -ENOMEM;
483e7d571c7SQu Wenruo 		goto out;
484e7d571c7SQu Wenruo 	}
485e7d571c7SQu Wenruo 
486e7d571c7SQu Wenruo 	node->lowest = 1;
487e7d571c7SQu Wenruo 	cur = node;
488e7d571c7SQu Wenruo 
489e7d571c7SQu Wenruo 	/* Breadth-first search to build backref cache */
490e7d571c7SQu Wenruo 	do {
4911b60d2ecSQu Wenruo 		ret = btrfs_backref_add_tree_node(cache, path, iter, node_key,
4921b60d2ecSQu Wenruo 						  cur);
493e7d571c7SQu Wenruo 		if (ret < 0) {
494e7d571c7SQu Wenruo 			err = ret;
495e7d571c7SQu Wenruo 			goto out;
496e7d571c7SQu Wenruo 		}
497e7d571c7SQu Wenruo 		edge = list_first_entry_or_null(&cache->pending_edge,
498a26195a5SQu Wenruo 				struct btrfs_backref_edge, list[UPPER]);
499e7d571c7SQu Wenruo 		/*
500e7d571c7SQu Wenruo 		 * The pending list isn't empty, take the first block to
501e7d571c7SQu Wenruo 		 * process
502e7d571c7SQu Wenruo 		 */
503e7d571c7SQu Wenruo 		if (edge) {
5045d4f98a2SYan Zheng 			list_del_init(&edge->list[UPPER]);
5055d4f98a2SYan Zheng 			cur = edge->node[UPPER];
5065d4f98a2SYan Zheng 		}
507e7d571c7SQu Wenruo 	} while (edge);
5085d4f98a2SYan Zheng 
5091f872924SQu Wenruo 	/* Finish the upper linkage of newly added edges/nodes */
510fc997ed0SQu Wenruo 	ret = btrfs_backref_finish_upper_links(cache, node);
5111f872924SQu Wenruo 	if (ret < 0) {
5121f872924SQu Wenruo 		err = ret;
51375bfb9afSJosef Bacik 		goto out;
51475bfb9afSJosef Bacik 	}
51575bfb9afSJosef Bacik 
51629db137bSQu Wenruo 	if (handle_useless_nodes(rc, node))
5173fd0a558SYan, Zheng 		node = NULL;
5185d4f98a2SYan Zheng out:
51971f572a9SQu Wenruo 	btrfs_backref_iter_free(iter);
52071f572a9SQu Wenruo 	btrfs_free_path(path);
5215d4f98a2SYan Zheng 	if (err) {
5221b23ea18SQu Wenruo 		btrfs_backref_error_cleanup(cache, node);
5235d4f98a2SYan Zheng 		return ERR_PTR(err);
5245d4f98a2SYan Zheng 	}
52575bfb9afSJosef Bacik 	ASSERT(!node || !node->detached);
52684780289SQu Wenruo 	ASSERT(list_empty(&cache->useless_node) &&
52784780289SQu Wenruo 	       list_empty(&cache->pending_edge));
5285d4f98a2SYan Zheng 	return node;
5295d4f98a2SYan Zheng }
5305d4f98a2SYan Zheng 
5315d4f98a2SYan Zheng /*
5323fd0a558SYan, Zheng  * helper to add backref node for the newly created snapshot.
5333fd0a558SYan, Zheng  * the backref node is created by cloning backref node that
5343fd0a558SYan, Zheng  * corresponds to root of source tree
5353fd0a558SYan, Zheng  */
5363fd0a558SYan, Zheng static int clone_backref_node(struct btrfs_trans_handle *trans,
5373fd0a558SYan, Zheng 			      struct reloc_control *rc,
5383fd0a558SYan, Zheng 			      struct btrfs_root *src,
5393fd0a558SYan, Zheng 			      struct btrfs_root *dest)
5403fd0a558SYan, Zheng {
5413fd0a558SYan, Zheng 	struct btrfs_root *reloc_root = src->reloc_root;
542a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
543a26195a5SQu Wenruo 	struct btrfs_backref_node *node = NULL;
544a26195a5SQu Wenruo 	struct btrfs_backref_node *new_node;
545a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
546a26195a5SQu Wenruo 	struct btrfs_backref_edge *new_edge;
5473fd0a558SYan, Zheng 	struct rb_node *rb_node;
5483fd0a558SYan, Zheng 
5493fd0a558SYan, Zheng 	if (cache->last_trans > 0)
5503fd0a558SYan, Zheng 		update_backref_cache(trans, cache);
5513fd0a558SYan, Zheng 
552e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&cache->rb_root, src->commit_root->start);
5533fd0a558SYan, Zheng 	if (rb_node) {
554a26195a5SQu Wenruo 		node = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
5553fd0a558SYan, Zheng 		if (node->detached)
5563fd0a558SYan, Zheng 			node = NULL;
5573fd0a558SYan, Zheng 		else
5583fd0a558SYan, Zheng 			BUG_ON(node->new_bytenr != reloc_root->node->start);
5593fd0a558SYan, Zheng 	}
5603fd0a558SYan, Zheng 
5613fd0a558SYan, Zheng 	if (!node) {
562e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&cache->rb_root,
5633fd0a558SYan, Zheng 					   reloc_root->commit_root->start);
5643fd0a558SYan, Zheng 		if (rb_node) {
565a26195a5SQu Wenruo 			node = rb_entry(rb_node, struct btrfs_backref_node,
5663fd0a558SYan, Zheng 					rb_node);
5673fd0a558SYan, Zheng 			BUG_ON(node->detached);
5683fd0a558SYan, Zheng 		}
5693fd0a558SYan, Zheng 	}
5703fd0a558SYan, Zheng 
5713fd0a558SYan, Zheng 	if (!node)
5723fd0a558SYan, Zheng 		return 0;
5733fd0a558SYan, Zheng 
574b1818dabSQu Wenruo 	new_node = btrfs_backref_alloc_node(cache, dest->node->start,
575b1818dabSQu Wenruo 					    node->level);
5763fd0a558SYan, Zheng 	if (!new_node)
5773fd0a558SYan, Zheng 		return -ENOMEM;
5783fd0a558SYan, Zheng 
5793fd0a558SYan, Zheng 	new_node->lowest = node->lowest;
5806848ad64SYan, Zheng 	new_node->checked = 1;
58100246528SJosef Bacik 	new_node->root = btrfs_grab_root(dest);
5820b530bc5SJosef Bacik 	ASSERT(new_node->root);
5833fd0a558SYan, Zheng 
5843fd0a558SYan, Zheng 	if (!node->lowest) {
5853fd0a558SYan, Zheng 		list_for_each_entry(edge, &node->lower, list[UPPER]) {
58647254d07SQu Wenruo 			new_edge = btrfs_backref_alloc_edge(cache);
5873fd0a558SYan, Zheng 			if (!new_edge)
5883fd0a558SYan, Zheng 				goto fail;
5893fd0a558SYan, Zheng 
590f39911e5SQu Wenruo 			btrfs_backref_link_edge(new_edge, edge->node[LOWER],
591f39911e5SQu Wenruo 						new_node, LINK_UPPER);
5923fd0a558SYan, Zheng 		}
59376b9e23dSMiao Xie 	} else {
59476b9e23dSMiao Xie 		list_add_tail(&new_node->lower, &cache->leaves);
5953fd0a558SYan, Zheng 	}
5963fd0a558SYan, Zheng 
597e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&cache->rb_root, new_node->bytenr,
5983fd0a558SYan, Zheng 				   &new_node->rb_node);
59943c04fb1SJeff Mahoney 	if (rb_node)
600982c92cbSQu Wenruo 		btrfs_backref_panic(trans->fs_info, new_node->bytenr, -EEXIST);
6013fd0a558SYan, Zheng 
6023fd0a558SYan, Zheng 	if (!new_node->lowest) {
6033fd0a558SYan, Zheng 		list_for_each_entry(new_edge, &new_node->lower, list[UPPER]) {
6043fd0a558SYan, Zheng 			list_add_tail(&new_edge->list[LOWER],
6053fd0a558SYan, Zheng 				      &new_edge->node[LOWER]->upper);
6063fd0a558SYan, Zheng 		}
6073fd0a558SYan, Zheng 	}
6083fd0a558SYan, Zheng 	return 0;
6093fd0a558SYan, Zheng fail:
6103fd0a558SYan, Zheng 	while (!list_empty(&new_node->lower)) {
6113fd0a558SYan, Zheng 		new_edge = list_entry(new_node->lower.next,
612a26195a5SQu Wenruo 				      struct btrfs_backref_edge, list[UPPER]);
6133fd0a558SYan, Zheng 		list_del(&new_edge->list[UPPER]);
614741188d3SQu Wenruo 		btrfs_backref_free_edge(cache, new_edge);
6153fd0a558SYan, Zheng 	}
616741188d3SQu Wenruo 	btrfs_backref_free_node(cache, new_node);
6173fd0a558SYan, Zheng 	return -ENOMEM;
6183fd0a558SYan, Zheng }
6193fd0a558SYan, Zheng 
6203fd0a558SYan, Zheng /*
6215d4f98a2SYan Zheng  * helper to add 'address of tree root -> reloc tree' mapping
6225d4f98a2SYan Zheng  */
623ffd7b339SJeff Mahoney static int __must_check __add_reloc_root(struct btrfs_root *root)
6245d4f98a2SYan Zheng {
6250b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6265d4f98a2SYan Zheng 	struct rb_node *rb_node;
6275d4f98a2SYan Zheng 	struct mapping_node *node;
6280b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
6295d4f98a2SYan Zheng 
6305d4f98a2SYan Zheng 	node = kmalloc(sizeof(*node), GFP_NOFS);
631ffd7b339SJeff Mahoney 	if (!node)
632ffd7b339SJeff Mahoney 		return -ENOMEM;
6335d4f98a2SYan Zheng 
634ea287ab1SJosef Bacik 	node->bytenr = root->commit_root->start;
6355d4f98a2SYan Zheng 	node->data = root;
6365d4f98a2SYan Zheng 
6375d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
638e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
6395d4f98a2SYan Zheng 				   node->bytenr, &node->rb_node);
6405d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
641ffd7b339SJeff Mahoney 	if (rb_node) {
64257a304cfSJosef Bacik 		btrfs_err(fs_info,
6435d163e0eSJeff Mahoney 			    "Duplicate root found for start=%llu while inserting into relocation tree",
6445d163e0eSJeff Mahoney 			    node->bytenr);
64557a304cfSJosef Bacik 		return -EEXIST;
646ffd7b339SJeff Mahoney 	}
6475d4f98a2SYan Zheng 
6485d4f98a2SYan Zheng 	list_add_tail(&root->root_list, &rc->reloc_roots);
6495d4f98a2SYan Zheng 	return 0;
6505d4f98a2SYan Zheng }
6515d4f98a2SYan Zheng 
6525d4f98a2SYan Zheng /*
653c974c464SWang Shilong  * helper to delete the 'address of tree root -> reloc tree'
6545d4f98a2SYan Zheng  * mapping
6555d4f98a2SYan Zheng  */
656c974c464SWang Shilong static void __del_reloc_root(struct btrfs_root *root)
6575d4f98a2SYan Zheng {
6580b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
6595d4f98a2SYan Zheng 	struct rb_node *rb_node;
6605d4f98a2SYan Zheng 	struct mapping_node *node = NULL;
6610b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
662f44deb74SJosef Bacik 	bool put_ref = false;
6635d4f98a2SYan Zheng 
66465c6e82bSQu Wenruo 	if (rc && root->node) {
6655d4f98a2SYan Zheng 		spin_lock(&rc->reloc_root_tree.lock);
666e9a28dc5SQu Wenruo 		rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
667ea287ab1SJosef Bacik 					   root->commit_root->start);
668c974c464SWang Shilong 		if (rb_node) {
669c974c464SWang Shilong 			node = rb_entry(rb_node, struct mapping_node, rb_node);
670c974c464SWang Shilong 			rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
671ea287ab1SJosef Bacik 			RB_CLEAR_NODE(&node->rb_node);
672c974c464SWang Shilong 		}
673c974c464SWang Shilong 		spin_unlock(&rc->reloc_root_tree.lock);
674c78a10aeSJosef Bacik 		ASSERT(!node || (struct btrfs_root *)node->data == root);
675389305b2SQu Wenruo 	}
676c974c464SWang Shilong 
677f44deb74SJosef Bacik 	/*
678f44deb74SJosef Bacik 	 * We only put the reloc root here if it's on the list.  There's a lot
679f44deb74SJosef Bacik 	 * of places where the pattern is to splice the rc->reloc_roots, process
680f44deb74SJosef Bacik 	 * the reloc roots, and then add the reloc root back onto
681f44deb74SJosef Bacik 	 * rc->reloc_roots.  If we call __del_reloc_root while it's off of the
682f44deb74SJosef Bacik 	 * list we don't want the reference being dropped, because the guy
683f44deb74SJosef Bacik 	 * messing with the list is in charge of the reference.
684f44deb74SJosef Bacik 	 */
6850b246afaSJeff Mahoney 	spin_lock(&fs_info->trans_lock);
686f44deb74SJosef Bacik 	if (!list_empty(&root->root_list)) {
687f44deb74SJosef Bacik 		put_ref = true;
688c974c464SWang Shilong 		list_del_init(&root->root_list);
689f44deb74SJosef Bacik 	}
6900b246afaSJeff Mahoney 	spin_unlock(&fs_info->trans_lock);
691f44deb74SJosef Bacik 	if (put_ref)
692f44deb74SJosef Bacik 		btrfs_put_root(root);
693c974c464SWang Shilong 	kfree(node);
694c974c464SWang Shilong }
695c974c464SWang Shilong 
696c974c464SWang Shilong /*
697c974c464SWang Shilong  * helper to update the 'address of tree root -> reloc tree'
698c974c464SWang Shilong  * mapping
699c974c464SWang Shilong  */
700ea287ab1SJosef Bacik static int __update_reloc_root(struct btrfs_root *root)
701c974c464SWang Shilong {
7020b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
703c974c464SWang Shilong 	struct rb_node *rb_node;
704c974c464SWang Shilong 	struct mapping_node *node = NULL;
7050b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
706c974c464SWang Shilong 
707c974c464SWang Shilong 	spin_lock(&rc->reloc_root_tree.lock);
708e9a28dc5SQu Wenruo 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
709ea287ab1SJosef Bacik 				   root->commit_root->start);
7105d4f98a2SYan Zheng 	if (rb_node) {
7115d4f98a2SYan Zheng 		node = rb_entry(rb_node, struct mapping_node, rb_node);
7125d4f98a2SYan Zheng 		rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
7135d4f98a2SYan Zheng 	}
7145d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
7155d4f98a2SYan Zheng 
7168f71f3e0SLiu Bo 	if (!node)
7178f71f3e0SLiu Bo 		return 0;
7185d4f98a2SYan Zheng 	BUG_ON((struct btrfs_root *)node->data != root);
7195d4f98a2SYan Zheng 
7205d4f98a2SYan Zheng 	spin_lock(&rc->reloc_root_tree.lock);
721ea287ab1SJosef Bacik 	node->bytenr = root->node->start;
722e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
7235d4f98a2SYan Zheng 				   node->bytenr, &node->rb_node);
7245d4f98a2SYan Zheng 	spin_unlock(&rc->reloc_root_tree.lock);
72543c04fb1SJeff Mahoney 	if (rb_node)
726982c92cbSQu Wenruo 		btrfs_backref_panic(fs_info, node->bytenr, -EEXIST);
7275d4f98a2SYan Zheng 	return 0;
7285d4f98a2SYan Zheng }
7295d4f98a2SYan Zheng 
7303fd0a558SYan, Zheng static struct btrfs_root *create_reloc_root(struct btrfs_trans_handle *trans,
7313fd0a558SYan, Zheng 					struct btrfs_root *root, u64 objectid)
7325d4f98a2SYan Zheng {
7330b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
7345d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
7355d4f98a2SYan Zheng 	struct extent_buffer *eb;
7365d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
7375d4f98a2SYan Zheng 	struct btrfs_key root_key;
73884c50ba5SJosef Bacik 	int ret = 0;
73984c50ba5SJosef Bacik 	bool must_abort = false;
7405d4f98a2SYan Zheng 
7415d4f98a2SYan Zheng 	root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
74284c50ba5SJosef Bacik 	if (!root_item)
74384c50ba5SJosef Bacik 		return ERR_PTR(-ENOMEM);
7445d4f98a2SYan Zheng 
7455d4f98a2SYan Zheng 	root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
7465d4f98a2SYan Zheng 	root_key.type = BTRFS_ROOT_ITEM_KEY;
7473fd0a558SYan, Zheng 	root_key.offset = objectid;
7485d4f98a2SYan Zheng 
7493fd0a558SYan, Zheng 	if (root->root_key.objectid == objectid) {
750054570a1SFilipe Manana 		u64 commit_root_gen;
751054570a1SFilipe Manana 
7523fd0a558SYan, Zheng 		/* called by btrfs_init_reloc_root */
7535d4f98a2SYan Zheng 		ret = btrfs_copy_root(trans, root, root->commit_root, &eb,
7545d4f98a2SYan Zheng 				      BTRFS_TREE_RELOC_OBJECTID);
75584c50ba5SJosef Bacik 		if (ret)
75684c50ba5SJosef Bacik 			goto fail;
75784c50ba5SJosef Bacik 
758054570a1SFilipe Manana 		/*
759054570a1SFilipe Manana 		 * Set the last_snapshot field to the generation of the commit
760054570a1SFilipe Manana 		 * root - like this ctree.c:btrfs_block_can_be_shared() behaves
761054570a1SFilipe Manana 		 * correctly (returns true) when the relocation root is created
762054570a1SFilipe Manana 		 * either inside the critical section of a transaction commit
763054570a1SFilipe Manana 		 * (through transaction.c:qgroup_account_snapshot()) and when
764054570a1SFilipe Manana 		 * it's created before the transaction commit is started.
765054570a1SFilipe Manana 		 */
766054570a1SFilipe Manana 		commit_root_gen = btrfs_header_generation(root->commit_root);
767054570a1SFilipe Manana 		btrfs_set_root_last_snapshot(&root->root_item, commit_root_gen);
7683fd0a558SYan, Zheng 	} else {
7693fd0a558SYan, Zheng 		/*
7703fd0a558SYan, Zheng 		 * called by btrfs_reloc_post_snapshot_hook.
7713fd0a558SYan, Zheng 		 * the source tree is a reloc tree, all tree blocks
7723fd0a558SYan, Zheng 		 * modified after it was created have RELOC flag
7733fd0a558SYan, Zheng 		 * set in their headers. so it's OK to not update
7743fd0a558SYan, Zheng 		 * the 'last_snapshot'.
7753fd0a558SYan, Zheng 		 */
7763fd0a558SYan, Zheng 		ret = btrfs_copy_root(trans, root, root->node, &eb,
7773fd0a558SYan, Zheng 				      BTRFS_TREE_RELOC_OBJECTID);
77884c50ba5SJosef Bacik 		if (ret)
77984c50ba5SJosef Bacik 			goto fail;
7803fd0a558SYan, Zheng 	}
7813fd0a558SYan, Zheng 
78284c50ba5SJosef Bacik 	/*
78384c50ba5SJosef Bacik 	 * We have changed references at this point, we must abort the
78484c50ba5SJosef Bacik 	 * transaction if anything fails.
78584c50ba5SJosef Bacik 	 */
78684c50ba5SJosef Bacik 	must_abort = true;
78784c50ba5SJosef Bacik 
7885d4f98a2SYan Zheng 	memcpy(root_item, &root->root_item, sizeof(*root_item));
7895d4f98a2SYan Zheng 	btrfs_set_root_bytenr(root_item, eb->start);
7905d4f98a2SYan Zheng 	btrfs_set_root_level(root_item, btrfs_header_level(eb));
7915d4f98a2SYan Zheng 	btrfs_set_root_generation(root_item, trans->transid);
7923fd0a558SYan, Zheng 
7933fd0a558SYan, Zheng 	if (root->root_key.objectid == objectid) {
7943fd0a558SYan, Zheng 		btrfs_set_root_refs(root_item, 0);
7953fd0a558SYan, Zheng 		memset(&root_item->drop_progress, 0,
7963fd0a558SYan, Zheng 		       sizeof(struct btrfs_disk_key));
797c8422684SDavid Sterba 		btrfs_set_root_drop_level(root_item, 0);
7983fd0a558SYan, Zheng 	}
7995d4f98a2SYan Zheng 
8005d4f98a2SYan Zheng 	btrfs_tree_unlock(eb);
8015d4f98a2SYan Zheng 	free_extent_buffer(eb);
8025d4f98a2SYan Zheng 
8030b246afaSJeff Mahoney 	ret = btrfs_insert_root(trans, fs_info->tree_root,
8045d4f98a2SYan Zheng 				&root_key, root_item);
80584c50ba5SJosef Bacik 	if (ret)
80684c50ba5SJosef Bacik 		goto fail;
80784c50ba5SJosef Bacik 
8085d4f98a2SYan Zheng 	kfree(root_item);
8095d4f98a2SYan Zheng 
8103dbf1738SJosef Bacik 	reloc_root = btrfs_read_tree_root(fs_info->tree_root, &root_key);
81184c50ba5SJosef Bacik 	if (IS_ERR(reloc_root)) {
81284c50ba5SJosef Bacik 		ret = PTR_ERR(reloc_root);
81384c50ba5SJosef Bacik 		goto abort;
81484c50ba5SJosef Bacik 	}
81592a7cc42SQu Wenruo 	set_bit(BTRFS_ROOT_SHAREABLE, &reloc_root->state);
8165d4f98a2SYan Zheng 	reloc_root->last_trans = trans->transid;
8173fd0a558SYan, Zheng 	return reloc_root;
81884c50ba5SJosef Bacik fail:
81984c50ba5SJosef Bacik 	kfree(root_item);
82084c50ba5SJosef Bacik abort:
82184c50ba5SJosef Bacik 	if (must_abort)
82284c50ba5SJosef Bacik 		btrfs_abort_transaction(trans, ret);
82384c50ba5SJosef Bacik 	return ERR_PTR(ret);
8243fd0a558SYan, Zheng }
8253fd0a558SYan, Zheng 
8263fd0a558SYan, Zheng /*
8273fd0a558SYan, Zheng  * create reloc tree for a given fs tree. reloc tree is just a
8283fd0a558SYan, Zheng  * snapshot of the fs tree with special root objectid.
829f44deb74SJosef Bacik  *
830f44deb74SJosef Bacik  * The reloc_root comes out of here with two references, one for
831f44deb74SJosef Bacik  * root->reloc_root, and another for being on the rc->reloc_roots list.
8323fd0a558SYan, Zheng  */
8333fd0a558SYan, Zheng int btrfs_init_reloc_root(struct btrfs_trans_handle *trans,
8343fd0a558SYan, Zheng 			  struct btrfs_root *root)
8353fd0a558SYan, Zheng {
8360b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
8373fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
8380b246afaSJeff Mahoney 	struct reloc_control *rc = fs_info->reloc_ctl;
83920dd2cbfSMiao Xie 	struct btrfs_block_rsv *rsv;
8403fd0a558SYan, Zheng 	int clear_rsv = 0;
841ffd7b339SJeff Mahoney 	int ret;
8423fd0a558SYan, Zheng 
843aec7db3bSJosef Bacik 	if (!rc)
8442abc726aSJosef Bacik 		return 0;
8452abc726aSJosef Bacik 
8461fac4a54SQu Wenruo 	/*
8471fac4a54SQu Wenruo 	 * The subvolume has reloc tree but the swap is finished, no need to
8481fac4a54SQu Wenruo 	 * create/update the dead reloc tree
8491fac4a54SQu Wenruo 	 */
8506282675eSQu Wenruo 	if (reloc_root_is_dead(root))
8511fac4a54SQu Wenruo 		return 0;
8521fac4a54SQu Wenruo 
853aec7db3bSJosef Bacik 	/*
854aec7db3bSJosef Bacik 	 * This is subtle but important.  We do not do
855aec7db3bSJosef Bacik 	 * record_root_in_transaction for reloc roots, instead we record their
856aec7db3bSJosef Bacik 	 * corresponding fs root, and then here we update the last trans for the
857aec7db3bSJosef Bacik 	 * reloc root.  This means that we have to do this for the entire life
858aec7db3bSJosef Bacik 	 * of the reloc root, regardless of which stage of the relocation we are
859aec7db3bSJosef Bacik 	 * in.
860aec7db3bSJosef Bacik 	 */
8613fd0a558SYan, Zheng 	if (root->reloc_root) {
8623fd0a558SYan, Zheng 		reloc_root = root->reloc_root;
8633fd0a558SYan, Zheng 		reloc_root->last_trans = trans->transid;
8643fd0a558SYan, Zheng 		return 0;
8653fd0a558SYan, Zheng 	}
8663fd0a558SYan, Zheng 
867aec7db3bSJosef Bacik 	/*
868aec7db3bSJosef Bacik 	 * We are merging reloc roots, we do not need new reloc trees.  Also
869aec7db3bSJosef Bacik 	 * reloc trees never need their own reloc tree.
870aec7db3bSJosef Bacik 	 */
871aec7db3bSJosef Bacik 	if (!rc->create_reloc_tree ||
872aec7db3bSJosef Bacik 	    root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
873aec7db3bSJosef Bacik 		return 0;
874aec7db3bSJosef Bacik 
87520dd2cbfSMiao Xie 	if (!trans->reloc_reserved) {
87620dd2cbfSMiao Xie 		rsv = trans->block_rsv;
8773fd0a558SYan, Zheng 		trans->block_rsv = rc->block_rsv;
8783fd0a558SYan, Zheng 		clear_rsv = 1;
8793fd0a558SYan, Zheng 	}
8803fd0a558SYan, Zheng 	reloc_root = create_reloc_root(trans, root, root->root_key.objectid);
8813fd0a558SYan, Zheng 	if (clear_rsv)
88220dd2cbfSMiao Xie 		trans->block_rsv = rsv;
88300bb36a0SJosef Bacik 	if (IS_ERR(reloc_root))
88400bb36a0SJosef Bacik 		return PTR_ERR(reloc_root);
8855d4f98a2SYan Zheng 
886ffd7b339SJeff Mahoney 	ret = __add_reloc_root(reloc_root);
88757a304cfSJosef Bacik 	ASSERT(ret != -EEXIST);
88800bb36a0SJosef Bacik 	if (ret) {
88900bb36a0SJosef Bacik 		/* Pairs with create_reloc_root */
89000bb36a0SJosef Bacik 		btrfs_put_root(reloc_root);
89100bb36a0SJosef Bacik 		return ret;
89200bb36a0SJosef Bacik 	}
893f44deb74SJosef Bacik 	root->reloc_root = btrfs_grab_root(reloc_root);
8945d4f98a2SYan Zheng 	return 0;
8955d4f98a2SYan Zheng }
8965d4f98a2SYan Zheng 
8975d4f98a2SYan Zheng /*
8985d4f98a2SYan Zheng  * update root item of reloc tree
8995d4f98a2SYan Zheng  */
9005d4f98a2SYan Zheng int btrfs_update_reloc_root(struct btrfs_trans_handle *trans,
9015d4f98a2SYan Zheng 			    struct btrfs_root *root)
9025d4f98a2SYan Zheng {
9030b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
9045d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
9055d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
9065d4f98a2SYan Zheng 	int ret;
9075d4f98a2SYan Zheng 
9086282675eSQu Wenruo 	if (!have_reloc_root(root))
909592fbcd5SJosef Bacik 		return 0;
9105d4f98a2SYan Zheng 
9115d4f98a2SYan Zheng 	reloc_root = root->reloc_root;
9125d4f98a2SYan Zheng 	root_item = &reloc_root->root_item;
9135d4f98a2SYan Zheng 
914f44deb74SJosef Bacik 	/*
915f44deb74SJosef Bacik 	 * We are probably ok here, but __del_reloc_root() will drop its ref of
916f44deb74SJosef Bacik 	 * the root.  We have the ref for root->reloc_root, but just in case
917f44deb74SJosef Bacik 	 * hold it while we update the reloc root.
918f44deb74SJosef Bacik 	 */
919f44deb74SJosef Bacik 	btrfs_grab_root(reloc_root);
920f44deb74SJosef Bacik 
921d2311e69SQu Wenruo 	/* root->reloc_root will stay until current relocation finished */
9220b246afaSJeff Mahoney 	if (fs_info->reloc_ctl->merge_reloc_tree &&
9233fd0a558SYan, Zheng 	    btrfs_root_refs(root_item) == 0) {
924d2311e69SQu Wenruo 		set_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
9256282675eSQu Wenruo 		/*
9266282675eSQu Wenruo 		 * Mark the tree as dead before we change reloc_root so
9276282675eSQu Wenruo 		 * have_reloc_root will not touch it from now on.
9286282675eSQu Wenruo 		 */
9296282675eSQu Wenruo 		smp_wmb();
930c974c464SWang Shilong 		__del_reloc_root(reloc_root);
9315d4f98a2SYan Zheng 	}
9325d4f98a2SYan Zheng 
9335d4f98a2SYan Zheng 	if (reloc_root->commit_root != reloc_root->node) {
934ea287ab1SJosef Bacik 		__update_reloc_root(reloc_root);
9355d4f98a2SYan Zheng 		btrfs_set_root_node(root_item, reloc_root->node);
9365d4f98a2SYan Zheng 		free_extent_buffer(reloc_root->commit_root);
9375d4f98a2SYan Zheng 		reloc_root->commit_root = btrfs_root_node(reloc_root);
9385d4f98a2SYan Zheng 	}
9395d4f98a2SYan Zheng 
9400b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
9415d4f98a2SYan Zheng 				&reloc_root->root_key, root_item);
942f44deb74SJosef Bacik 	btrfs_put_root(reloc_root);
943592fbcd5SJosef Bacik 	return ret;
9445d4f98a2SYan Zheng }
9455d4f98a2SYan Zheng 
9465d4f98a2SYan Zheng /*
9475d4f98a2SYan Zheng  * helper to find first cached inode with inode number >= objectid
9485d4f98a2SYan Zheng  * in a subvolume
9495d4f98a2SYan Zheng  */
9505d4f98a2SYan Zheng static struct inode *find_next_inode(struct btrfs_root *root, u64 objectid)
9515d4f98a2SYan Zheng {
9525d4f98a2SYan Zheng 	struct rb_node *node;
9535d4f98a2SYan Zheng 	struct rb_node *prev;
9545d4f98a2SYan Zheng 	struct btrfs_inode *entry;
9555d4f98a2SYan Zheng 	struct inode *inode;
9565d4f98a2SYan Zheng 
9575d4f98a2SYan Zheng 	spin_lock(&root->inode_lock);
9585d4f98a2SYan Zheng again:
9595d4f98a2SYan Zheng 	node = root->inode_tree.rb_node;
9605d4f98a2SYan Zheng 	prev = NULL;
9615d4f98a2SYan Zheng 	while (node) {
9625d4f98a2SYan Zheng 		prev = node;
9635d4f98a2SYan Zheng 		entry = rb_entry(node, struct btrfs_inode, rb_node);
9645d4f98a2SYan Zheng 
9654a0cc7caSNikolay Borisov 		if (objectid < btrfs_ino(entry))
9665d4f98a2SYan Zheng 			node = node->rb_left;
9674a0cc7caSNikolay Borisov 		else if (objectid > btrfs_ino(entry))
9685d4f98a2SYan Zheng 			node = node->rb_right;
9695d4f98a2SYan Zheng 		else
9705d4f98a2SYan Zheng 			break;
9715d4f98a2SYan Zheng 	}
9725d4f98a2SYan Zheng 	if (!node) {
9735d4f98a2SYan Zheng 		while (prev) {
9745d4f98a2SYan Zheng 			entry = rb_entry(prev, struct btrfs_inode, rb_node);
9754a0cc7caSNikolay Borisov 			if (objectid <= btrfs_ino(entry)) {
9765d4f98a2SYan Zheng 				node = prev;
9775d4f98a2SYan Zheng 				break;
9785d4f98a2SYan Zheng 			}
9795d4f98a2SYan Zheng 			prev = rb_next(prev);
9805d4f98a2SYan Zheng 		}
9815d4f98a2SYan Zheng 	}
9825d4f98a2SYan Zheng 	while (node) {
9835d4f98a2SYan Zheng 		entry = rb_entry(node, struct btrfs_inode, rb_node);
9845d4f98a2SYan Zheng 		inode = igrab(&entry->vfs_inode);
9855d4f98a2SYan Zheng 		if (inode) {
9865d4f98a2SYan Zheng 			spin_unlock(&root->inode_lock);
9875d4f98a2SYan Zheng 			return inode;
9885d4f98a2SYan Zheng 		}
9895d4f98a2SYan Zheng 
9904a0cc7caSNikolay Borisov 		objectid = btrfs_ino(entry) + 1;
9915d4f98a2SYan Zheng 		if (cond_resched_lock(&root->inode_lock))
9925d4f98a2SYan Zheng 			goto again;
9935d4f98a2SYan Zheng 
9945d4f98a2SYan Zheng 		node = rb_next(node);
9955d4f98a2SYan Zheng 	}
9965d4f98a2SYan Zheng 	spin_unlock(&root->inode_lock);
9975d4f98a2SYan Zheng 	return NULL;
9985d4f98a2SYan Zheng }
9995d4f98a2SYan Zheng 
10005d4f98a2SYan Zheng /*
10015d4f98a2SYan Zheng  * get new location of data
10025d4f98a2SYan Zheng  */
10035d4f98a2SYan Zheng static int get_new_location(struct inode *reloc_inode, u64 *new_bytenr,
10045d4f98a2SYan Zheng 			    u64 bytenr, u64 num_bytes)
10055d4f98a2SYan Zheng {
10065d4f98a2SYan Zheng 	struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
10075d4f98a2SYan Zheng 	struct btrfs_path *path;
10085d4f98a2SYan Zheng 	struct btrfs_file_extent_item *fi;
10095d4f98a2SYan Zheng 	struct extent_buffer *leaf;
10105d4f98a2SYan Zheng 	int ret;
10115d4f98a2SYan Zheng 
10125d4f98a2SYan Zheng 	path = btrfs_alloc_path();
10135d4f98a2SYan Zheng 	if (!path)
10145d4f98a2SYan Zheng 		return -ENOMEM;
10155d4f98a2SYan Zheng 
10165d4f98a2SYan Zheng 	bytenr -= BTRFS_I(reloc_inode)->index_cnt;
1017f85b7379SDavid Sterba 	ret = btrfs_lookup_file_extent(NULL, root, path,
1018f85b7379SDavid Sterba 			btrfs_ino(BTRFS_I(reloc_inode)), bytenr, 0);
10195d4f98a2SYan Zheng 	if (ret < 0)
10205d4f98a2SYan Zheng 		goto out;
10215d4f98a2SYan Zheng 	if (ret > 0) {
10225d4f98a2SYan Zheng 		ret = -ENOENT;
10235d4f98a2SYan Zheng 		goto out;
10245d4f98a2SYan Zheng 	}
10255d4f98a2SYan Zheng 
10265d4f98a2SYan Zheng 	leaf = path->nodes[0];
10275d4f98a2SYan Zheng 	fi = btrfs_item_ptr(leaf, path->slots[0],
10285d4f98a2SYan Zheng 			    struct btrfs_file_extent_item);
10295d4f98a2SYan Zheng 
10305d4f98a2SYan Zheng 	BUG_ON(btrfs_file_extent_offset(leaf, fi) ||
10315d4f98a2SYan Zheng 	       btrfs_file_extent_compression(leaf, fi) ||
10325d4f98a2SYan Zheng 	       btrfs_file_extent_encryption(leaf, fi) ||
10335d4f98a2SYan Zheng 	       btrfs_file_extent_other_encoding(leaf, fi));
10345d4f98a2SYan Zheng 
10355d4f98a2SYan Zheng 	if (num_bytes != btrfs_file_extent_disk_num_bytes(leaf, fi)) {
103683d4cfd4SJosef Bacik 		ret = -EINVAL;
10375d4f98a2SYan Zheng 		goto out;
10385d4f98a2SYan Zheng 	}
10395d4f98a2SYan Zheng 
10405d4f98a2SYan Zheng 	*new_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
10415d4f98a2SYan Zheng 	ret = 0;
10425d4f98a2SYan Zheng out:
10435d4f98a2SYan Zheng 	btrfs_free_path(path);
10445d4f98a2SYan Zheng 	return ret;
10455d4f98a2SYan Zheng }
10465d4f98a2SYan Zheng 
10475d4f98a2SYan Zheng /*
10485d4f98a2SYan Zheng  * update file extent items in the tree leaf to point to
10495d4f98a2SYan Zheng  * the new locations.
10505d4f98a2SYan Zheng  */
10513fd0a558SYan, Zheng static noinline_for_stack
10523fd0a558SYan, Zheng int replace_file_extents(struct btrfs_trans_handle *trans,
10535d4f98a2SYan Zheng 			 struct reloc_control *rc,
10545d4f98a2SYan Zheng 			 struct btrfs_root *root,
10553fd0a558SYan, Zheng 			 struct extent_buffer *leaf)
10565d4f98a2SYan Zheng {
10570b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
10585d4f98a2SYan Zheng 	struct btrfs_key key;
10595d4f98a2SYan Zheng 	struct btrfs_file_extent_item *fi;
10605d4f98a2SYan Zheng 	struct inode *inode = NULL;
10615d4f98a2SYan Zheng 	u64 parent;
10625d4f98a2SYan Zheng 	u64 bytenr;
10633fd0a558SYan, Zheng 	u64 new_bytenr = 0;
10645d4f98a2SYan Zheng 	u64 num_bytes;
10655d4f98a2SYan Zheng 	u64 end;
10665d4f98a2SYan Zheng 	u32 nritems;
10675d4f98a2SYan Zheng 	u32 i;
106883d4cfd4SJosef Bacik 	int ret = 0;
10695d4f98a2SYan Zheng 	int first = 1;
10705d4f98a2SYan Zheng 	int dirty = 0;
10715d4f98a2SYan Zheng 
10725d4f98a2SYan Zheng 	if (rc->stage != UPDATE_DATA_PTRS)
10735d4f98a2SYan Zheng 		return 0;
10745d4f98a2SYan Zheng 
10755d4f98a2SYan Zheng 	/* reloc trees always use full backref */
10765d4f98a2SYan Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
10775d4f98a2SYan Zheng 		parent = leaf->start;
10785d4f98a2SYan Zheng 	else
10795d4f98a2SYan Zheng 		parent = 0;
10805d4f98a2SYan Zheng 
10815d4f98a2SYan Zheng 	nritems = btrfs_header_nritems(leaf);
10825d4f98a2SYan Zheng 	for (i = 0; i < nritems; i++) {
108382fa113fSQu Wenruo 		struct btrfs_ref ref = { 0 };
108482fa113fSQu Wenruo 
10855d4f98a2SYan Zheng 		cond_resched();
10865d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, i);
10875d4f98a2SYan Zheng 		if (key.type != BTRFS_EXTENT_DATA_KEY)
10885d4f98a2SYan Zheng 			continue;
10895d4f98a2SYan Zheng 		fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
10905d4f98a2SYan Zheng 		if (btrfs_file_extent_type(leaf, fi) ==
10915d4f98a2SYan Zheng 		    BTRFS_FILE_EXTENT_INLINE)
10925d4f98a2SYan Zheng 			continue;
10935d4f98a2SYan Zheng 		bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
10945d4f98a2SYan Zheng 		num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
10955d4f98a2SYan Zheng 		if (bytenr == 0)
10965d4f98a2SYan Zheng 			continue;
10979569cc20SQu Wenruo 		if (!in_range(bytenr, rc->block_group->start,
10989569cc20SQu Wenruo 			      rc->block_group->length))
10995d4f98a2SYan Zheng 			continue;
11005d4f98a2SYan Zheng 
11015d4f98a2SYan Zheng 		/*
11025d4f98a2SYan Zheng 		 * if we are modifying block in fs tree, wait for readpage
11035d4f98a2SYan Zheng 		 * to complete and drop the extent cache
11045d4f98a2SYan Zheng 		 */
11055d4f98a2SYan Zheng 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
11065d4f98a2SYan Zheng 			if (first) {
11075d4f98a2SYan Zheng 				inode = find_next_inode(root, key.objectid);
11085d4f98a2SYan Zheng 				first = 0;
11094a0cc7caSNikolay Borisov 			} else if (inode && btrfs_ino(BTRFS_I(inode)) < key.objectid) {
11103fd0a558SYan, Zheng 				btrfs_add_delayed_iput(inode);
11115d4f98a2SYan Zheng 				inode = find_next_inode(root, key.objectid);
11125d4f98a2SYan Zheng 			}
11134a0cc7caSNikolay Borisov 			if (inode && btrfs_ino(BTRFS_I(inode)) == key.objectid) {
11145d4f98a2SYan Zheng 				end = key.offset +
11155d4f98a2SYan Zheng 				      btrfs_file_extent_num_bytes(leaf, fi);
11165d4f98a2SYan Zheng 				WARN_ON(!IS_ALIGNED(key.offset,
11170b246afaSJeff Mahoney 						    fs_info->sectorsize));
11180b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
11195d4f98a2SYan Zheng 				end--;
11205d4f98a2SYan Zheng 				ret = try_lock_extent(&BTRFS_I(inode)->io_tree,
1121d0082371SJeff Mahoney 						      key.offset, end);
11225d4f98a2SYan Zheng 				if (!ret)
11235d4f98a2SYan Zheng 					continue;
11245d4f98a2SYan Zheng 
1125dcdbc059SNikolay Borisov 				btrfs_drop_extent_cache(BTRFS_I(inode),
1126dcdbc059SNikolay Borisov 						key.offset,	end, 1);
11275d4f98a2SYan Zheng 				unlock_extent(&BTRFS_I(inode)->io_tree,
1128d0082371SJeff Mahoney 					      key.offset, end);
11295d4f98a2SYan Zheng 			}
11305d4f98a2SYan Zheng 		}
11315d4f98a2SYan Zheng 
11325d4f98a2SYan Zheng 		ret = get_new_location(rc->data_inode, &new_bytenr,
11335d4f98a2SYan Zheng 				       bytenr, num_bytes);
113483d4cfd4SJosef Bacik 		if (ret) {
113583d4cfd4SJosef Bacik 			/*
113683d4cfd4SJosef Bacik 			 * Don't have to abort since we've not changed anything
113783d4cfd4SJosef Bacik 			 * in the file extent yet.
113883d4cfd4SJosef Bacik 			 */
113983d4cfd4SJosef Bacik 			break;
11403fd0a558SYan, Zheng 		}
11415d4f98a2SYan Zheng 
11425d4f98a2SYan Zheng 		btrfs_set_file_extent_disk_bytenr(leaf, fi, new_bytenr);
11435d4f98a2SYan Zheng 		dirty = 1;
11445d4f98a2SYan Zheng 
11455d4f98a2SYan Zheng 		key.offset -= btrfs_file_extent_offset(leaf, fi);
114682fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new_bytenr,
114782fa113fSQu Wenruo 				       num_bytes, parent);
114882fa113fSQu Wenruo 		ref.real_root = root->root_key.objectid;
114982fa113fSQu Wenruo 		btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
1150b06c4bf5SFilipe Manana 				    key.objectid, key.offset);
115182fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
115283d4cfd4SJosef Bacik 		if (ret) {
115366642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
115483d4cfd4SJosef Bacik 			break;
115583d4cfd4SJosef Bacik 		}
11565d4f98a2SYan Zheng 
1157ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
1158ffd4bb2aSQu Wenruo 				       num_bytes, parent);
1159ffd4bb2aSQu Wenruo 		ref.real_root = root->root_key.objectid;
1160ffd4bb2aSQu Wenruo 		btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
1161b06c4bf5SFilipe Manana 				    key.objectid, key.offset);
1162ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
116383d4cfd4SJosef Bacik 		if (ret) {
116466642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
116583d4cfd4SJosef Bacik 			break;
116683d4cfd4SJosef Bacik 		}
11675d4f98a2SYan Zheng 	}
11685d4f98a2SYan Zheng 	if (dirty)
11695d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(leaf);
11703fd0a558SYan, Zheng 	if (inode)
11713fd0a558SYan, Zheng 		btrfs_add_delayed_iput(inode);
117283d4cfd4SJosef Bacik 	return ret;
11735d4f98a2SYan Zheng }
11745d4f98a2SYan Zheng 
11755d4f98a2SYan Zheng static noinline_for_stack
11765d4f98a2SYan Zheng int memcmp_node_keys(struct extent_buffer *eb, int slot,
11775d4f98a2SYan Zheng 		     struct btrfs_path *path, int level)
11785d4f98a2SYan Zheng {
11795d4f98a2SYan Zheng 	struct btrfs_disk_key key1;
11805d4f98a2SYan Zheng 	struct btrfs_disk_key key2;
11815d4f98a2SYan Zheng 	btrfs_node_key(eb, &key1, slot);
11825d4f98a2SYan Zheng 	btrfs_node_key(path->nodes[level], &key2, path->slots[level]);
11835d4f98a2SYan Zheng 	return memcmp(&key1, &key2, sizeof(key1));
11845d4f98a2SYan Zheng }
11855d4f98a2SYan Zheng 
11865d4f98a2SYan Zheng /*
11875d4f98a2SYan Zheng  * try to replace tree blocks in fs tree with the new blocks
11885d4f98a2SYan Zheng  * in reloc tree. tree blocks haven't been modified since the
11895d4f98a2SYan Zheng  * reloc tree was create can be replaced.
11905d4f98a2SYan Zheng  *
11915d4f98a2SYan Zheng  * if a block was replaced, level of the block + 1 is returned.
11925d4f98a2SYan Zheng  * if no block got replaced, 0 is returned. if there are other
11935d4f98a2SYan Zheng  * errors, a negative error number is returned.
11945d4f98a2SYan Zheng  */
11953fd0a558SYan, Zheng static noinline_for_stack
11963d0174f7SQu Wenruo int replace_path(struct btrfs_trans_handle *trans, struct reloc_control *rc,
11975d4f98a2SYan Zheng 		 struct btrfs_root *dest, struct btrfs_root *src,
11985d4f98a2SYan Zheng 		 struct btrfs_path *path, struct btrfs_key *next_key,
11995d4f98a2SYan Zheng 		 int lowest_level, int max_level)
12005d4f98a2SYan Zheng {
12010b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = dest->fs_info;
12025d4f98a2SYan Zheng 	struct extent_buffer *eb;
12035d4f98a2SYan Zheng 	struct extent_buffer *parent;
120482fa113fSQu Wenruo 	struct btrfs_ref ref = { 0 };
12055d4f98a2SYan Zheng 	struct btrfs_key key;
12065d4f98a2SYan Zheng 	u64 old_bytenr;
12075d4f98a2SYan Zheng 	u64 new_bytenr;
12085d4f98a2SYan Zheng 	u64 old_ptr_gen;
12095d4f98a2SYan Zheng 	u64 new_ptr_gen;
12105d4f98a2SYan Zheng 	u64 last_snapshot;
12115d4f98a2SYan Zheng 	u32 blocksize;
12123fd0a558SYan, Zheng 	int cow = 0;
12135d4f98a2SYan Zheng 	int level;
12145d4f98a2SYan Zheng 	int ret;
12155d4f98a2SYan Zheng 	int slot;
12165d4f98a2SYan Zheng 
12177a9213a9SJosef Bacik 	ASSERT(src->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID);
12187a9213a9SJosef Bacik 	ASSERT(dest->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
12195d4f98a2SYan Zheng 
12205d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&src->root_item);
12213fd0a558SYan, Zheng again:
12225d4f98a2SYan Zheng 	slot = path->slots[lowest_level];
12235d4f98a2SYan Zheng 	btrfs_node_key_to_cpu(path->nodes[lowest_level], &key, slot);
12245d4f98a2SYan Zheng 
12255d4f98a2SYan Zheng 	eb = btrfs_lock_root_node(dest);
12265d4f98a2SYan Zheng 	level = btrfs_header_level(eb);
12275d4f98a2SYan Zheng 
12285d4f98a2SYan Zheng 	if (level < lowest_level) {
12295d4f98a2SYan Zheng 		btrfs_tree_unlock(eb);
12305d4f98a2SYan Zheng 		free_extent_buffer(eb);
12315d4f98a2SYan Zheng 		return 0;
12325d4f98a2SYan Zheng 	}
12335d4f98a2SYan Zheng 
12343fd0a558SYan, Zheng 	if (cow) {
12359631e4ccSJosef Bacik 		ret = btrfs_cow_block(trans, dest, eb, NULL, 0, &eb,
12369631e4ccSJosef Bacik 				      BTRFS_NESTING_COW);
123745b87c5dSJosef Bacik 		if (ret) {
123845b87c5dSJosef Bacik 			btrfs_tree_unlock(eb);
123945b87c5dSJosef Bacik 			free_extent_buffer(eb);
124045b87c5dSJosef Bacik 			return ret;
124145b87c5dSJosef Bacik 		}
12423fd0a558SYan, Zheng 	}
12435d4f98a2SYan Zheng 
12445d4f98a2SYan Zheng 	if (next_key) {
12455d4f98a2SYan Zheng 		next_key->objectid = (u64)-1;
12465d4f98a2SYan Zheng 		next_key->type = (u8)-1;
12475d4f98a2SYan Zheng 		next_key->offset = (u64)-1;
12485d4f98a2SYan Zheng 	}
12495d4f98a2SYan Zheng 
12505d4f98a2SYan Zheng 	parent = eb;
12515d4f98a2SYan Zheng 	while (1) {
12525d4f98a2SYan Zheng 		level = btrfs_header_level(parent);
12537a9213a9SJosef Bacik 		ASSERT(level >= lowest_level);
12545d4f98a2SYan Zheng 
1255e3b83361SQu Wenruo 		ret = btrfs_bin_search(parent, &key, &slot);
1256cbca7d59SFilipe Manana 		if (ret < 0)
1257cbca7d59SFilipe Manana 			break;
12585d4f98a2SYan Zheng 		if (ret && slot > 0)
12595d4f98a2SYan Zheng 			slot--;
12605d4f98a2SYan Zheng 
12615d4f98a2SYan Zheng 		if (next_key && slot + 1 < btrfs_header_nritems(parent))
12625d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(parent, next_key, slot + 1);
12635d4f98a2SYan Zheng 
12645d4f98a2SYan Zheng 		old_bytenr = btrfs_node_blockptr(parent, slot);
12650b246afaSJeff Mahoney 		blocksize = fs_info->nodesize;
12665d4f98a2SYan Zheng 		old_ptr_gen = btrfs_node_ptr_generation(parent, slot);
12675d4f98a2SYan Zheng 
12685d4f98a2SYan Zheng 		if (level <= max_level) {
12695d4f98a2SYan Zheng 			eb = path->nodes[level];
12705d4f98a2SYan Zheng 			new_bytenr = btrfs_node_blockptr(eb,
12715d4f98a2SYan Zheng 							path->slots[level]);
12725d4f98a2SYan Zheng 			new_ptr_gen = btrfs_node_ptr_generation(eb,
12735d4f98a2SYan Zheng 							path->slots[level]);
12745d4f98a2SYan Zheng 		} else {
12755d4f98a2SYan Zheng 			new_bytenr = 0;
12765d4f98a2SYan Zheng 			new_ptr_gen = 0;
12775d4f98a2SYan Zheng 		}
12785d4f98a2SYan Zheng 
1279fae7f21cSDulshani Gunawardhana 		if (WARN_ON(new_bytenr > 0 && new_bytenr == old_bytenr)) {
12805d4f98a2SYan Zheng 			ret = level;
12815d4f98a2SYan Zheng 			break;
12825d4f98a2SYan Zheng 		}
12835d4f98a2SYan Zheng 
12845d4f98a2SYan Zheng 		if (new_bytenr == 0 || old_ptr_gen > last_snapshot ||
12855d4f98a2SYan Zheng 		    memcmp_node_keys(parent, slot, path, level)) {
12863fd0a558SYan, Zheng 			if (level <= lowest_level) {
12875d4f98a2SYan Zheng 				ret = 0;
12885d4f98a2SYan Zheng 				break;
12895d4f98a2SYan Zheng 			}
12905d4f98a2SYan Zheng 
12916b3426beSJosef Bacik 			eb = btrfs_read_node_slot(parent, slot);
129264c043deSLiu Bo 			if (IS_ERR(eb)) {
129364c043deSLiu Bo 				ret = PTR_ERR(eb);
1294264813acSLiu Bo 				break;
1295416bc658SJosef Bacik 			}
12965d4f98a2SYan Zheng 			btrfs_tree_lock(eb);
12973fd0a558SYan, Zheng 			if (cow) {
12985d4f98a2SYan Zheng 				ret = btrfs_cow_block(trans, dest, eb, parent,
12999631e4ccSJosef Bacik 						      slot, &eb,
13009631e4ccSJosef Bacik 						      BTRFS_NESTING_COW);
130145b87c5dSJosef Bacik 				if (ret) {
130245b87c5dSJosef Bacik 					btrfs_tree_unlock(eb);
130345b87c5dSJosef Bacik 					free_extent_buffer(eb);
130445b87c5dSJosef Bacik 					break;
130545b87c5dSJosef Bacik 				}
13065d4f98a2SYan Zheng 			}
13075d4f98a2SYan Zheng 
13085d4f98a2SYan Zheng 			btrfs_tree_unlock(parent);
13095d4f98a2SYan Zheng 			free_extent_buffer(parent);
13105d4f98a2SYan Zheng 
13115d4f98a2SYan Zheng 			parent = eb;
13125d4f98a2SYan Zheng 			continue;
13135d4f98a2SYan Zheng 		}
13145d4f98a2SYan Zheng 
13153fd0a558SYan, Zheng 		if (!cow) {
13163fd0a558SYan, Zheng 			btrfs_tree_unlock(parent);
13173fd0a558SYan, Zheng 			free_extent_buffer(parent);
13183fd0a558SYan, Zheng 			cow = 1;
13193fd0a558SYan, Zheng 			goto again;
13203fd0a558SYan, Zheng 		}
13213fd0a558SYan, Zheng 
13225d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(path->nodes[level], &key,
13235d4f98a2SYan Zheng 				      path->slots[level]);
1324b3b4aa74SDavid Sterba 		btrfs_release_path(path);
13255d4f98a2SYan Zheng 
13265d4f98a2SYan Zheng 		path->lowest_level = level;
13275d4f98a2SYan Zheng 		ret = btrfs_search_slot(trans, src, &key, path, 0, 1);
13285d4f98a2SYan Zheng 		path->lowest_level = 0;
13290e9873e2SJosef Bacik 		if (ret) {
13300e9873e2SJosef Bacik 			if (ret > 0)
13310e9873e2SJosef Bacik 				ret = -ENOENT;
13320e9873e2SJosef Bacik 			break;
13330e9873e2SJosef Bacik 		}
13345d4f98a2SYan Zheng 
13355d4f98a2SYan Zheng 		/*
1336824d8dffSQu Wenruo 		 * Info qgroup to trace both subtrees.
1337824d8dffSQu Wenruo 		 *
1338824d8dffSQu Wenruo 		 * We must trace both trees.
1339824d8dffSQu Wenruo 		 * 1) Tree reloc subtree
1340824d8dffSQu Wenruo 		 *    If not traced, we will leak data numbers
1341824d8dffSQu Wenruo 		 * 2) Fs subtree
1342824d8dffSQu Wenruo 		 *    If not traced, we will double count old data
1343f616f5cdSQu Wenruo 		 *
1344f616f5cdSQu Wenruo 		 * We don't scan the subtree right now, but only record
1345f616f5cdSQu Wenruo 		 * the swapped tree blocks.
1346f616f5cdSQu Wenruo 		 * The real subtree rescan is delayed until we have new
1347f616f5cdSQu Wenruo 		 * CoW on the subtree root node before transaction commit.
1348824d8dffSQu Wenruo 		 */
1349370a11b8SQu Wenruo 		ret = btrfs_qgroup_add_swapped_blocks(trans, dest,
1350370a11b8SQu Wenruo 				rc->block_group, parent, slot,
1351370a11b8SQu Wenruo 				path->nodes[level], path->slots[level],
1352370a11b8SQu Wenruo 				last_snapshot);
1353370a11b8SQu Wenruo 		if (ret < 0)
1354370a11b8SQu Wenruo 			break;
1355824d8dffSQu Wenruo 		/*
13565d4f98a2SYan Zheng 		 * swap blocks in fs tree and reloc tree.
13575d4f98a2SYan Zheng 		 */
13585d4f98a2SYan Zheng 		btrfs_set_node_blockptr(parent, slot, new_bytenr);
13595d4f98a2SYan Zheng 		btrfs_set_node_ptr_generation(parent, slot, new_ptr_gen);
13605d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(parent);
13615d4f98a2SYan Zheng 
13625d4f98a2SYan Zheng 		btrfs_set_node_blockptr(path->nodes[level],
13635d4f98a2SYan Zheng 					path->slots[level], old_bytenr);
13645d4f98a2SYan Zheng 		btrfs_set_node_ptr_generation(path->nodes[level],
13655d4f98a2SYan Zheng 					      path->slots[level], old_ptr_gen);
13665d4f98a2SYan Zheng 		btrfs_mark_buffer_dirty(path->nodes[level]);
13675d4f98a2SYan Zheng 
136882fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, old_bytenr,
136982fa113fSQu Wenruo 				       blocksize, path->nodes[level]->start);
137082fa113fSQu Wenruo 		ref.skip_qgroup = true;
137182fa113fSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, src->root_key.objectid);
137282fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
1373253e258cSJosef Bacik 		if (ret) {
1374253e258cSJosef Bacik 			btrfs_abort_transaction(trans, ret);
1375253e258cSJosef Bacik 			break;
1376253e258cSJosef Bacik 		}
137782fa113fSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new_bytenr,
137882fa113fSQu Wenruo 				       blocksize, 0);
137982fa113fSQu Wenruo 		ref.skip_qgroup = true;
138082fa113fSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, dest->root_key.objectid);
138182fa113fSQu Wenruo 		ret = btrfs_inc_extent_ref(trans, &ref);
1382253e258cSJosef Bacik 		if (ret) {
1383253e258cSJosef Bacik 			btrfs_abort_transaction(trans, ret);
1384253e258cSJosef Bacik 			break;
1385253e258cSJosef Bacik 		}
13865d4f98a2SYan Zheng 
1387ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, new_bytenr,
1388ffd4bb2aSQu Wenruo 				       blocksize, path->nodes[level]->start);
1389ffd4bb2aSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, src->root_key.objectid);
1390ffd4bb2aSQu Wenruo 		ref.skip_qgroup = true;
1391ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
1392253e258cSJosef Bacik 		if (ret) {
1393253e258cSJosef Bacik 			btrfs_abort_transaction(trans, ret);
1394253e258cSJosef Bacik 			break;
1395253e258cSJosef Bacik 		}
13965d4f98a2SYan Zheng 
1397ffd4bb2aSQu Wenruo 		btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, old_bytenr,
1398ffd4bb2aSQu Wenruo 				       blocksize, 0);
1399ffd4bb2aSQu Wenruo 		btrfs_init_tree_ref(&ref, level - 1, dest->root_key.objectid);
1400ffd4bb2aSQu Wenruo 		ref.skip_qgroup = true;
1401ffd4bb2aSQu Wenruo 		ret = btrfs_free_extent(trans, &ref);
1402253e258cSJosef Bacik 		if (ret) {
1403253e258cSJosef Bacik 			btrfs_abort_transaction(trans, ret);
1404253e258cSJosef Bacik 			break;
1405253e258cSJosef Bacik 		}
14065d4f98a2SYan Zheng 
14075d4f98a2SYan Zheng 		btrfs_unlock_up_safe(path, 0);
14085d4f98a2SYan Zheng 
14095d4f98a2SYan Zheng 		ret = level;
14105d4f98a2SYan Zheng 		break;
14115d4f98a2SYan Zheng 	}
14125d4f98a2SYan Zheng 	btrfs_tree_unlock(parent);
14135d4f98a2SYan Zheng 	free_extent_buffer(parent);
14145d4f98a2SYan Zheng 	return ret;
14155d4f98a2SYan Zheng }
14165d4f98a2SYan Zheng 
14175d4f98a2SYan Zheng /*
14185d4f98a2SYan Zheng  * helper to find next relocated block in reloc tree
14195d4f98a2SYan Zheng  */
14205d4f98a2SYan Zheng static noinline_for_stack
14215d4f98a2SYan Zheng int walk_up_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
14225d4f98a2SYan Zheng 		       int *level)
14235d4f98a2SYan Zheng {
14245d4f98a2SYan Zheng 	struct extent_buffer *eb;
14255d4f98a2SYan Zheng 	int i;
14265d4f98a2SYan Zheng 	u64 last_snapshot;
14275d4f98a2SYan Zheng 	u32 nritems;
14285d4f98a2SYan Zheng 
14295d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
14305d4f98a2SYan Zheng 
14315d4f98a2SYan Zheng 	for (i = 0; i < *level; i++) {
14325d4f98a2SYan Zheng 		free_extent_buffer(path->nodes[i]);
14335d4f98a2SYan Zheng 		path->nodes[i] = NULL;
14345d4f98a2SYan Zheng 	}
14355d4f98a2SYan Zheng 
14365d4f98a2SYan Zheng 	for (i = *level; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
14375d4f98a2SYan Zheng 		eb = path->nodes[i];
14385d4f98a2SYan Zheng 		nritems = btrfs_header_nritems(eb);
14395d4f98a2SYan Zheng 		while (path->slots[i] + 1 < nritems) {
14405d4f98a2SYan Zheng 			path->slots[i]++;
14415d4f98a2SYan Zheng 			if (btrfs_node_ptr_generation(eb, path->slots[i]) <=
14425d4f98a2SYan Zheng 			    last_snapshot)
14435d4f98a2SYan Zheng 				continue;
14445d4f98a2SYan Zheng 
14455d4f98a2SYan Zheng 			*level = i;
14465d4f98a2SYan Zheng 			return 0;
14475d4f98a2SYan Zheng 		}
14485d4f98a2SYan Zheng 		free_extent_buffer(path->nodes[i]);
14495d4f98a2SYan Zheng 		path->nodes[i] = NULL;
14505d4f98a2SYan Zheng 	}
14515d4f98a2SYan Zheng 	return 1;
14525d4f98a2SYan Zheng }
14535d4f98a2SYan Zheng 
14545d4f98a2SYan Zheng /*
14555d4f98a2SYan Zheng  * walk down reloc tree to find relocated block of lowest level
14565d4f98a2SYan Zheng  */
14575d4f98a2SYan Zheng static noinline_for_stack
14585d4f98a2SYan Zheng int walk_down_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
14595d4f98a2SYan Zheng 			 int *level)
14605d4f98a2SYan Zheng {
14615d4f98a2SYan Zheng 	struct extent_buffer *eb = NULL;
14625d4f98a2SYan Zheng 	int i;
14635d4f98a2SYan Zheng 	u64 ptr_gen = 0;
14645d4f98a2SYan Zheng 	u64 last_snapshot;
14655d4f98a2SYan Zheng 	u32 nritems;
14665d4f98a2SYan Zheng 
14675d4f98a2SYan Zheng 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
14685d4f98a2SYan Zheng 
14695d4f98a2SYan Zheng 	for (i = *level; i > 0; i--) {
14705d4f98a2SYan Zheng 		eb = path->nodes[i];
14715d4f98a2SYan Zheng 		nritems = btrfs_header_nritems(eb);
14725d4f98a2SYan Zheng 		while (path->slots[i] < nritems) {
14735d4f98a2SYan Zheng 			ptr_gen = btrfs_node_ptr_generation(eb, path->slots[i]);
14745d4f98a2SYan Zheng 			if (ptr_gen > last_snapshot)
14755d4f98a2SYan Zheng 				break;
14765d4f98a2SYan Zheng 			path->slots[i]++;
14775d4f98a2SYan Zheng 		}
14785d4f98a2SYan Zheng 		if (path->slots[i] >= nritems) {
14795d4f98a2SYan Zheng 			if (i == *level)
14805d4f98a2SYan Zheng 				break;
14815d4f98a2SYan Zheng 			*level = i + 1;
14825d4f98a2SYan Zheng 			return 0;
14835d4f98a2SYan Zheng 		}
14845d4f98a2SYan Zheng 		if (i == 1) {
14855d4f98a2SYan Zheng 			*level = i;
14865d4f98a2SYan Zheng 			return 0;
14875d4f98a2SYan Zheng 		}
14885d4f98a2SYan Zheng 
14898ef385bbSJosef Bacik 		eb = btrfs_read_node_slot(eb, path->slots[i]);
14908ef385bbSJosef Bacik 		if (IS_ERR(eb))
149164c043deSLiu Bo 			return PTR_ERR(eb);
14925d4f98a2SYan Zheng 		BUG_ON(btrfs_header_level(eb) != i - 1);
14935d4f98a2SYan Zheng 		path->nodes[i - 1] = eb;
14945d4f98a2SYan Zheng 		path->slots[i - 1] = 0;
14955d4f98a2SYan Zheng 	}
14965d4f98a2SYan Zheng 	return 1;
14975d4f98a2SYan Zheng }
14985d4f98a2SYan Zheng 
14995d4f98a2SYan Zheng /*
15005d4f98a2SYan Zheng  * invalidate extent cache for file extents whose key in range of
15015d4f98a2SYan Zheng  * [min_key, max_key)
15025d4f98a2SYan Zheng  */
15035d4f98a2SYan Zheng static int invalidate_extent_cache(struct btrfs_root *root,
15045d4f98a2SYan Zheng 				   struct btrfs_key *min_key,
15055d4f98a2SYan Zheng 				   struct btrfs_key *max_key)
15065d4f98a2SYan Zheng {
15070b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15085d4f98a2SYan Zheng 	struct inode *inode = NULL;
15095d4f98a2SYan Zheng 	u64 objectid;
15105d4f98a2SYan Zheng 	u64 start, end;
151133345d01SLi Zefan 	u64 ino;
15125d4f98a2SYan Zheng 
15135d4f98a2SYan Zheng 	objectid = min_key->objectid;
15145d4f98a2SYan Zheng 	while (1) {
15155d4f98a2SYan Zheng 		cond_resched();
15165d4f98a2SYan Zheng 		iput(inode);
15175d4f98a2SYan Zheng 
15185d4f98a2SYan Zheng 		if (objectid > max_key->objectid)
15195d4f98a2SYan Zheng 			break;
15205d4f98a2SYan Zheng 
15215d4f98a2SYan Zheng 		inode = find_next_inode(root, objectid);
15225d4f98a2SYan Zheng 		if (!inode)
15235d4f98a2SYan Zheng 			break;
15244a0cc7caSNikolay Borisov 		ino = btrfs_ino(BTRFS_I(inode));
15255d4f98a2SYan Zheng 
152633345d01SLi Zefan 		if (ino > max_key->objectid) {
15275d4f98a2SYan Zheng 			iput(inode);
15285d4f98a2SYan Zheng 			break;
15295d4f98a2SYan Zheng 		}
15305d4f98a2SYan Zheng 
153133345d01SLi Zefan 		objectid = ino + 1;
15325d4f98a2SYan Zheng 		if (!S_ISREG(inode->i_mode))
15335d4f98a2SYan Zheng 			continue;
15345d4f98a2SYan Zheng 
153533345d01SLi Zefan 		if (unlikely(min_key->objectid == ino)) {
15365d4f98a2SYan Zheng 			if (min_key->type > BTRFS_EXTENT_DATA_KEY)
15375d4f98a2SYan Zheng 				continue;
15385d4f98a2SYan Zheng 			if (min_key->type < BTRFS_EXTENT_DATA_KEY)
15395d4f98a2SYan Zheng 				start = 0;
15405d4f98a2SYan Zheng 			else {
15415d4f98a2SYan Zheng 				start = min_key->offset;
15420b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(start, fs_info->sectorsize));
15435d4f98a2SYan Zheng 			}
15445d4f98a2SYan Zheng 		} else {
15455d4f98a2SYan Zheng 			start = 0;
15465d4f98a2SYan Zheng 		}
15475d4f98a2SYan Zheng 
154833345d01SLi Zefan 		if (unlikely(max_key->objectid == ino)) {
15495d4f98a2SYan Zheng 			if (max_key->type < BTRFS_EXTENT_DATA_KEY)
15505d4f98a2SYan Zheng 				continue;
15515d4f98a2SYan Zheng 			if (max_key->type > BTRFS_EXTENT_DATA_KEY) {
15525d4f98a2SYan Zheng 				end = (u64)-1;
15535d4f98a2SYan Zheng 			} else {
15545d4f98a2SYan Zheng 				if (max_key->offset == 0)
15555d4f98a2SYan Zheng 					continue;
15565d4f98a2SYan Zheng 				end = max_key->offset;
15570b246afaSJeff Mahoney 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
15585d4f98a2SYan Zheng 				end--;
15595d4f98a2SYan Zheng 			}
15605d4f98a2SYan Zheng 		} else {
15615d4f98a2SYan Zheng 			end = (u64)-1;
15625d4f98a2SYan Zheng 		}
15635d4f98a2SYan Zheng 
15645d4f98a2SYan Zheng 		/* the lock_extent waits for readpage to complete */
1565d0082371SJeff Mahoney 		lock_extent(&BTRFS_I(inode)->io_tree, start, end);
1566dcdbc059SNikolay Borisov 		btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 1);
1567d0082371SJeff Mahoney 		unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
15685d4f98a2SYan Zheng 	}
15695d4f98a2SYan Zheng 	return 0;
15705d4f98a2SYan Zheng }
15715d4f98a2SYan Zheng 
15725d4f98a2SYan Zheng static int find_next_key(struct btrfs_path *path, int level,
15735d4f98a2SYan Zheng 			 struct btrfs_key *key)
15745d4f98a2SYan Zheng 
15755d4f98a2SYan Zheng {
15765d4f98a2SYan Zheng 	while (level < BTRFS_MAX_LEVEL) {
15775d4f98a2SYan Zheng 		if (!path->nodes[level])
15785d4f98a2SYan Zheng 			break;
15795d4f98a2SYan Zheng 		if (path->slots[level] + 1 <
15805d4f98a2SYan Zheng 		    btrfs_header_nritems(path->nodes[level])) {
15815d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(path->nodes[level], key,
15825d4f98a2SYan Zheng 					      path->slots[level] + 1);
15835d4f98a2SYan Zheng 			return 0;
15845d4f98a2SYan Zheng 		}
15855d4f98a2SYan Zheng 		level++;
15865d4f98a2SYan Zheng 	}
15875d4f98a2SYan Zheng 	return 1;
15885d4f98a2SYan Zheng }
15895d4f98a2SYan Zheng 
15905d4f98a2SYan Zheng /*
1591d2311e69SQu Wenruo  * Insert current subvolume into reloc_control::dirty_subvol_roots
1592d2311e69SQu Wenruo  */
1593ac54da6cSJosef Bacik static int insert_dirty_subvol(struct btrfs_trans_handle *trans,
1594d2311e69SQu Wenruo 			       struct reloc_control *rc,
1595d2311e69SQu Wenruo 			       struct btrfs_root *root)
1596d2311e69SQu Wenruo {
1597d2311e69SQu Wenruo 	struct btrfs_root *reloc_root = root->reloc_root;
1598d2311e69SQu Wenruo 	struct btrfs_root_item *reloc_root_item;
15997934133fSJosef Bacik 	int ret;
1600d2311e69SQu Wenruo 
1601d2311e69SQu Wenruo 	/* @root must be a subvolume tree root with a valid reloc tree */
1602d2311e69SQu Wenruo 	ASSERT(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
1603d2311e69SQu Wenruo 	ASSERT(reloc_root);
1604d2311e69SQu Wenruo 
1605d2311e69SQu Wenruo 	reloc_root_item = &reloc_root->root_item;
1606d2311e69SQu Wenruo 	memset(&reloc_root_item->drop_progress, 0,
1607d2311e69SQu Wenruo 		sizeof(reloc_root_item->drop_progress));
1608c8422684SDavid Sterba 	btrfs_set_root_drop_level(reloc_root_item, 0);
1609d2311e69SQu Wenruo 	btrfs_set_root_refs(reloc_root_item, 0);
16107934133fSJosef Bacik 	ret = btrfs_update_reloc_root(trans, root);
16117934133fSJosef Bacik 	if (ret)
16127934133fSJosef Bacik 		return ret;
1613d2311e69SQu Wenruo 
1614d2311e69SQu Wenruo 	if (list_empty(&root->reloc_dirty_list)) {
161500246528SJosef Bacik 		btrfs_grab_root(root);
1616d2311e69SQu Wenruo 		list_add_tail(&root->reloc_dirty_list, &rc->dirty_subvol_roots);
1617d2311e69SQu Wenruo 	}
1618ac54da6cSJosef Bacik 
1619ac54da6cSJosef Bacik 	return 0;
1620d2311e69SQu Wenruo }
1621d2311e69SQu Wenruo 
1622d2311e69SQu Wenruo static int clean_dirty_subvols(struct reloc_control *rc)
1623d2311e69SQu Wenruo {
1624d2311e69SQu Wenruo 	struct btrfs_root *root;
1625d2311e69SQu Wenruo 	struct btrfs_root *next;
1626d2311e69SQu Wenruo 	int ret = 0;
162730d40577SQu Wenruo 	int ret2;
1628d2311e69SQu Wenruo 
1629d2311e69SQu Wenruo 	list_for_each_entry_safe(root, next, &rc->dirty_subvol_roots,
1630d2311e69SQu Wenruo 				 reloc_dirty_list) {
163130d40577SQu Wenruo 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
163230d40577SQu Wenruo 			/* Merged subvolume, cleanup its reloc root */
1633d2311e69SQu Wenruo 			struct btrfs_root *reloc_root = root->reloc_root;
1634d2311e69SQu Wenruo 
1635d2311e69SQu Wenruo 			list_del_init(&root->reloc_dirty_list);
1636d2311e69SQu Wenruo 			root->reloc_root = NULL;
16376282675eSQu Wenruo 			/*
16386282675eSQu Wenruo 			 * Need barrier to ensure clear_bit() only happens after
16396282675eSQu Wenruo 			 * root->reloc_root = NULL. Pairs with have_reloc_root.
16406282675eSQu Wenruo 			 */
16416282675eSQu Wenruo 			smp_wmb();
16421fac4a54SQu Wenruo 			clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
1643f28de8d8SJosef Bacik 			if (reloc_root) {
1644f44deb74SJosef Bacik 				/*
1645f44deb74SJosef Bacik 				 * btrfs_drop_snapshot drops our ref we hold for
1646f44deb74SJosef Bacik 				 * ->reloc_root.  If it fails however we must
1647f44deb74SJosef Bacik 				 * drop the ref ourselves.
1648f44deb74SJosef Bacik 				 */
1649f28de8d8SJosef Bacik 				ret2 = btrfs_drop_snapshot(reloc_root, 0, 1);
1650f44deb74SJosef Bacik 				if (ret2 < 0) {
1651f44deb74SJosef Bacik 					btrfs_put_root(reloc_root);
1652f44deb74SJosef Bacik 					if (!ret)
1653f28de8d8SJosef Bacik 						ret = ret2;
1654f28de8d8SJosef Bacik 				}
1655f44deb74SJosef Bacik 			}
165600246528SJosef Bacik 			btrfs_put_root(root);
165730d40577SQu Wenruo 		} else {
165830d40577SQu Wenruo 			/* Orphan reloc tree, just clean it up */
16590078a9f9SNikolay Borisov 			ret2 = btrfs_drop_snapshot(root, 0, 1);
1660f44deb74SJosef Bacik 			if (ret2 < 0) {
1661f44deb74SJosef Bacik 				btrfs_put_root(root);
1662f44deb74SJosef Bacik 				if (!ret)
166330d40577SQu Wenruo 					ret = ret2;
166430d40577SQu Wenruo 			}
1665d2311e69SQu Wenruo 		}
1666f44deb74SJosef Bacik 	}
1667d2311e69SQu Wenruo 	return ret;
1668d2311e69SQu Wenruo }
1669d2311e69SQu Wenruo 
1670d2311e69SQu Wenruo /*
16715d4f98a2SYan Zheng  * merge the relocated tree blocks in reloc tree with corresponding
16725d4f98a2SYan Zheng  * fs tree.
16735d4f98a2SYan Zheng  */
16745d4f98a2SYan Zheng static noinline_for_stack int merge_reloc_root(struct reloc_control *rc,
16755d4f98a2SYan Zheng 					       struct btrfs_root *root)
16765d4f98a2SYan Zheng {
16770b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
16785d4f98a2SYan Zheng 	struct btrfs_key key;
16795d4f98a2SYan Zheng 	struct btrfs_key next_key;
16809e6a0c52SJosef Bacik 	struct btrfs_trans_handle *trans = NULL;
16815d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
16825d4f98a2SYan Zheng 	struct btrfs_root_item *root_item;
16835d4f98a2SYan Zheng 	struct btrfs_path *path;
16843fd0a558SYan, Zheng 	struct extent_buffer *leaf;
1685fca3a45dSJosef Bacik 	int reserve_level;
16865d4f98a2SYan Zheng 	int level;
16875d4f98a2SYan Zheng 	int max_level;
16885d4f98a2SYan Zheng 	int replaced = 0;
1689c6a592f2SNikolay Borisov 	int ret = 0;
16903fd0a558SYan, Zheng 	u32 min_reserved;
16915d4f98a2SYan Zheng 
16925d4f98a2SYan Zheng 	path = btrfs_alloc_path();
16935d4f98a2SYan Zheng 	if (!path)
16945d4f98a2SYan Zheng 		return -ENOMEM;
1695e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
16965d4f98a2SYan Zheng 
16975d4f98a2SYan Zheng 	reloc_root = root->reloc_root;
16985d4f98a2SYan Zheng 	root_item = &reloc_root->root_item;
16995d4f98a2SYan Zheng 
17005d4f98a2SYan Zheng 	if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
17015d4f98a2SYan Zheng 		level = btrfs_root_level(root_item);
170267439dadSDavid Sterba 		atomic_inc(&reloc_root->node->refs);
17035d4f98a2SYan Zheng 		path->nodes[level] = reloc_root->node;
17045d4f98a2SYan Zheng 		path->slots[level] = 0;
17055d4f98a2SYan Zheng 	} else {
17065d4f98a2SYan Zheng 		btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
17075d4f98a2SYan Zheng 
1708c8422684SDavid Sterba 		level = btrfs_root_drop_level(root_item);
17095d4f98a2SYan Zheng 		BUG_ON(level == 0);
17105d4f98a2SYan Zheng 		path->lowest_level = level;
17115d4f98a2SYan Zheng 		ret = btrfs_search_slot(NULL, reloc_root, &key, path, 0, 0);
171233c66f43SYan Zheng 		path->lowest_level = 0;
17135d4f98a2SYan Zheng 		if (ret < 0) {
17145d4f98a2SYan Zheng 			btrfs_free_path(path);
17155d4f98a2SYan Zheng 			return ret;
17165d4f98a2SYan Zheng 		}
17175d4f98a2SYan Zheng 
17185d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(path->nodes[level], &next_key,
17195d4f98a2SYan Zheng 				      path->slots[level]);
17205d4f98a2SYan Zheng 		WARN_ON(memcmp(&key, &next_key, sizeof(key)));
17215d4f98a2SYan Zheng 
17225d4f98a2SYan Zheng 		btrfs_unlock_up_safe(path, 0);
17235d4f98a2SYan Zheng 	}
17245d4f98a2SYan Zheng 
172544d354abSQu Wenruo 	/*
172644d354abSQu Wenruo 	 * In merge_reloc_root(), we modify the upper level pointer to swap the
172744d354abSQu Wenruo 	 * tree blocks between reloc tree and subvolume tree.  Thus for tree
172844d354abSQu Wenruo 	 * block COW, we COW at most from level 1 to root level for each tree.
172944d354abSQu Wenruo 	 *
173044d354abSQu Wenruo 	 * Thus the needed metadata size is at most root_level * nodesize,
173144d354abSQu Wenruo 	 * and * 2 since we have two trees to COW.
173244d354abSQu Wenruo 	 */
1733fca3a45dSJosef Bacik 	reserve_level = max_t(int, 1, btrfs_root_level(root_item));
1734fca3a45dSJosef Bacik 	min_reserved = fs_info->nodesize * reserve_level * 2;
17355d4f98a2SYan Zheng 	memset(&next_key, 0, sizeof(next_key));
17365d4f98a2SYan Zheng 
17375d4f98a2SYan Zheng 	while (1) {
173808e007d2SMiao Xie 		ret = btrfs_block_rsv_refill(root, rc->block_rsv, min_reserved,
173944d354abSQu Wenruo 					     BTRFS_RESERVE_FLUSH_LIMIT);
1740c6a592f2SNikolay Borisov 		if (ret)
17419e6a0c52SJosef Bacik 			goto out;
17429e6a0c52SJosef Bacik 		trans = btrfs_start_transaction(root, 0);
17439e6a0c52SJosef Bacik 		if (IS_ERR(trans)) {
1744c6a592f2SNikolay Borisov 			ret = PTR_ERR(trans);
17459e6a0c52SJosef Bacik 			trans = NULL;
17469e6a0c52SJosef Bacik 			goto out;
17479e6a0c52SJosef Bacik 		}
17482abc726aSJosef Bacik 
17492abc726aSJosef Bacik 		/*
17502abc726aSJosef Bacik 		 * At this point we no longer have a reloc_control, so we can't
17512abc726aSJosef Bacik 		 * depend on btrfs_init_reloc_root to update our last_trans.
17522abc726aSJosef Bacik 		 *
17532abc726aSJosef Bacik 		 * But that's ok, we started the trans handle on our
17542abc726aSJosef Bacik 		 * corresponding fs_root, which means it's been added to the
17552abc726aSJosef Bacik 		 * dirty list.  At commit time we'll still call
17562abc726aSJosef Bacik 		 * btrfs_update_reloc_root() and update our root item
17572abc726aSJosef Bacik 		 * appropriately.
17582abc726aSJosef Bacik 		 */
17592abc726aSJosef Bacik 		reloc_root->last_trans = trans->transid;
17609e6a0c52SJosef Bacik 		trans->block_rsv = rc->block_rsv;
17613fd0a558SYan, Zheng 
17623fd0a558SYan, Zheng 		replaced = 0;
17635d4f98a2SYan Zheng 		max_level = level;
17645d4f98a2SYan Zheng 
17655d4f98a2SYan Zheng 		ret = walk_down_reloc_tree(reloc_root, path, &level);
1766c6a592f2SNikolay Borisov 		if (ret < 0)
17675d4f98a2SYan Zheng 			goto out;
17685d4f98a2SYan Zheng 		if (ret > 0)
17695d4f98a2SYan Zheng 			break;
17705d4f98a2SYan Zheng 
17715d4f98a2SYan Zheng 		if (!find_next_key(path, level, &key) &&
17725d4f98a2SYan Zheng 		    btrfs_comp_cpu_keys(&next_key, &key) >= 0) {
17735d4f98a2SYan Zheng 			ret = 0;
17745d4f98a2SYan Zheng 		} else {
17753d0174f7SQu Wenruo 			ret = replace_path(trans, rc, root, reloc_root, path,
17763fd0a558SYan, Zheng 					   &next_key, level, max_level);
17775d4f98a2SYan Zheng 		}
1778c6a592f2SNikolay Borisov 		if (ret < 0)
17795d4f98a2SYan Zheng 			goto out;
17805d4f98a2SYan Zheng 		if (ret > 0) {
17815d4f98a2SYan Zheng 			level = ret;
17825d4f98a2SYan Zheng 			btrfs_node_key_to_cpu(path->nodes[level], &key,
17835d4f98a2SYan Zheng 					      path->slots[level]);
17845d4f98a2SYan Zheng 			replaced = 1;
17855d4f98a2SYan Zheng 		}
17865d4f98a2SYan Zheng 
17875d4f98a2SYan Zheng 		ret = walk_up_reloc_tree(reloc_root, path, &level);
17885d4f98a2SYan Zheng 		if (ret > 0)
17895d4f98a2SYan Zheng 			break;
17905d4f98a2SYan Zheng 
17915d4f98a2SYan Zheng 		BUG_ON(level == 0);
17925d4f98a2SYan Zheng 		/*
17935d4f98a2SYan Zheng 		 * save the merging progress in the drop_progress.
17945d4f98a2SYan Zheng 		 * this is OK since root refs == 1 in this case.
17955d4f98a2SYan Zheng 		 */
17965d4f98a2SYan Zheng 		btrfs_node_key(path->nodes[level], &root_item->drop_progress,
17975d4f98a2SYan Zheng 			       path->slots[level]);
1798c8422684SDavid Sterba 		btrfs_set_root_drop_level(root_item, level);
17995d4f98a2SYan Zheng 
18003a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
18019e6a0c52SJosef Bacik 		trans = NULL;
18025d4f98a2SYan Zheng 
18032ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
18045d4f98a2SYan Zheng 
18055d4f98a2SYan Zheng 		if (replaced && rc->stage == UPDATE_DATA_PTRS)
18065d4f98a2SYan Zheng 			invalidate_extent_cache(root, &key, &next_key);
18075d4f98a2SYan Zheng 	}
18085d4f98a2SYan Zheng 
18095d4f98a2SYan Zheng 	/*
18105d4f98a2SYan Zheng 	 * handle the case only one block in the fs tree need to be
18115d4f98a2SYan Zheng 	 * relocated and the block is tree root.
18125d4f98a2SYan Zheng 	 */
18135d4f98a2SYan Zheng 	leaf = btrfs_lock_root_node(root);
18149631e4ccSJosef Bacik 	ret = btrfs_cow_block(trans, root, leaf, NULL, 0, &leaf,
18159631e4ccSJosef Bacik 			      BTRFS_NESTING_COW);
18165d4f98a2SYan Zheng 	btrfs_tree_unlock(leaf);
18175d4f98a2SYan Zheng 	free_extent_buffer(leaf);
18185d4f98a2SYan Zheng out:
18195d4f98a2SYan Zheng 	btrfs_free_path(path);
18205d4f98a2SYan Zheng 
1821ac54da6cSJosef Bacik 	if (ret == 0) {
1822ac54da6cSJosef Bacik 		ret = insert_dirty_subvol(trans, rc, root);
1823ac54da6cSJosef Bacik 		if (ret)
1824ac54da6cSJosef Bacik 			btrfs_abort_transaction(trans, ret);
1825ac54da6cSJosef Bacik 	}
18265d4f98a2SYan Zheng 
18279e6a0c52SJosef Bacik 	if (trans)
18283a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
18295d4f98a2SYan Zheng 
18302ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
18315d4f98a2SYan Zheng 
18325d4f98a2SYan Zheng 	if (replaced && rc->stage == UPDATE_DATA_PTRS)
18335d4f98a2SYan Zheng 		invalidate_extent_cache(root, &key, &next_key);
18345d4f98a2SYan Zheng 
1835c6a592f2SNikolay Borisov 	return ret;
18365d4f98a2SYan Zheng }
18375d4f98a2SYan Zheng 
18383fd0a558SYan, Zheng static noinline_for_stack
18393fd0a558SYan, Zheng int prepare_to_merge(struct reloc_control *rc, int err)
18405d4f98a2SYan Zheng {
18413fd0a558SYan, Zheng 	struct btrfs_root *root = rc->extent_root;
18420b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
18433fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
18445d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
18453fd0a558SYan, Zheng 	LIST_HEAD(reloc_roots);
18463fd0a558SYan, Zheng 	u64 num_bytes = 0;
18473fd0a558SYan, Zheng 	int ret;
18483fd0a558SYan, Zheng 
18490b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
18500b246afaSJeff Mahoney 	rc->merging_rsv_size += fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
18513fd0a558SYan, Zheng 	rc->merging_rsv_size += rc->nodes_relocated * 2;
18520b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
18537585717fSChris Mason 
18543fd0a558SYan, Zheng again:
18553fd0a558SYan, Zheng 	if (!err) {
18563fd0a558SYan, Zheng 		num_bytes = rc->merging_rsv_size;
185708e007d2SMiao Xie 		ret = btrfs_block_rsv_add(root, rc->block_rsv, num_bytes,
185808e007d2SMiao Xie 					  BTRFS_RESERVE_FLUSH_ALL);
18593fd0a558SYan, Zheng 		if (ret)
18603fd0a558SYan, Zheng 			err = ret;
18613fd0a558SYan, Zheng 	}
18623fd0a558SYan, Zheng 
18637a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
18643612b495STsutomu Itoh 	if (IS_ERR(trans)) {
18653612b495STsutomu Itoh 		if (!err)
18662ff7e61eSJeff Mahoney 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
186763f018beSNikolay Borisov 						num_bytes, NULL);
18683612b495STsutomu Itoh 		return PTR_ERR(trans);
18693612b495STsutomu Itoh 	}
18703fd0a558SYan, Zheng 
18713fd0a558SYan, Zheng 	if (!err) {
18723fd0a558SYan, Zheng 		if (num_bytes != rc->merging_rsv_size) {
18733a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
18742ff7e61eSJeff Mahoney 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
187563f018beSNikolay Borisov 						num_bytes, NULL);
18763fd0a558SYan, Zheng 			goto again;
18773fd0a558SYan, Zheng 		}
18783fd0a558SYan, Zheng 	}
18793fd0a558SYan, Zheng 
18803fd0a558SYan, Zheng 	rc->merge_reloc_tree = 1;
18813fd0a558SYan, Zheng 
18823fd0a558SYan, Zheng 	while (!list_empty(&rc->reloc_roots)) {
18833fd0a558SYan, Zheng 		reloc_root = list_entry(rc->reloc_roots.next,
18843fd0a558SYan, Zheng 					struct btrfs_root, root_list);
18853fd0a558SYan, Zheng 		list_del_init(&reloc_root->root_list);
18863fd0a558SYan, Zheng 
1887a820feb5SDavid Sterba 		root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
1888a820feb5SDavid Sterba 				false);
1889e0b085b0SJosef Bacik 		if (IS_ERR(root)) {
1890e0b085b0SJosef Bacik 			/*
1891e0b085b0SJosef Bacik 			 * Even if we have an error we need this reloc root
1892e0b085b0SJosef Bacik 			 * back on our list so we can clean up properly.
1893e0b085b0SJosef Bacik 			 */
1894e0b085b0SJosef Bacik 			list_add(&reloc_root->root_list, &reloc_roots);
1895e0b085b0SJosef Bacik 			btrfs_abort_transaction(trans, (int)PTR_ERR(root));
1896e0b085b0SJosef Bacik 			if (!err)
1897e0b085b0SJosef Bacik 				err = PTR_ERR(root);
1898e0b085b0SJosef Bacik 			break;
1899e0b085b0SJosef Bacik 		}
1900e0b085b0SJosef Bacik 		ASSERT(root->reloc_root == reloc_root);
19013fd0a558SYan, Zheng 
19023fd0a558SYan, Zheng 		/*
19033fd0a558SYan, Zheng 		 * set reference count to 1, so btrfs_recover_relocation
19043fd0a558SYan, Zheng 		 * knows it should resumes merging
19053fd0a558SYan, Zheng 		 */
19063fd0a558SYan, Zheng 		if (!err)
19073fd0a558SYan, Zheng 			btrfs_set_root_refs(&reloc_root->root_item, 1);
1908bbae13f8SJosef Bacik 		ret = btrfs_update_reloc_root(trans, root);
19093fd0a558SYan, Zheng 
1910bbae13f8SJosef Bacik 		/*
1911bbae13f8SJosef Bacik 		 * Even if we have an error we need this reloc root back on our
1912bbae13f8SJosef Bacik 		 * list so we can clean up properly.
1913bbae13f8SJosef Bacik 		 */
19143fd0a558SYan, Zheng 		list_add(&reloc_root->root_list, &reloc_roots);
191500246528SJosef Bacik 		btrfs_put_root(root);
1916bbae13f8SJosef Bacik 
1917bbae13f8SJosef Bacik 		if (ret) {
1918bbae13f8SJosef Bacik 			btrfs_abort_transaction(trans, ret);
1919bbae13f8SJosef Bacik 			if (!err)
1920bbae13f8SJosef Bacik 				err = ret;
1921bbae13f8SJosef Bacik 			break;
1922bbae13f8SJosef Bacik 		}
19233fd0a558SYan, Zheng 	}
19243fd0a558SYan, Zheng 
19253fd0a558SYan, Zheng 	list_splice(&reloc_roots, &rc->reloc_roots);
19263fd0a558SYan, Zheng 
19273fd0a558SYan, Zheng 	if (!err)
1928fb686c68SJosef Bacik 		err = btrfs_commit_transaction(trans);
19293fd0a558SYan, Zheng 	else
19303a45bb20SJeff Mahoney 		btrfs_end_transaction(trans);
19313fd0a558SYan, Zheng 	return err;
19323fd0a558SYan, Zheng }
19333fd0a558SYan, Zheng 
19343fd0a558SYan, Zheng static noinline_for_stack
1935aca1bba6SLiu Bo void free_reloc_roots(struct list_head *list)
1936aca1bba6SLiu Bo {
1937a7571232SNikolay Borisov 	struct btrfs_root *reloc_root, *tmp;
1938aca1bba6SLiu Bo 
1939a7571232SNikolay Borisov 	list_for_each_entry_safe(reloc_root, tmp, list, root_list)
1940bb166d72SNaohiro Aota 		__del_reloc_root(reloc_root);
1941aca1bba6SLiu Bo }
1942aca1bba6SLiu Bo 
1943aca1bba6SLiu Bo static noinline_for_stack
194494404e82SDavid Sterba void merge_reloc_roots(struct reloc_control *rc)
19453fd0a558SYan, Zheng {
19460b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
19475d4f98a2SYan Zheng 	struct btrfs_root *root;
19485d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
19493fd0a558SYan, Zheng 	LIST_HEAD(reloc_roots);
19503fd0a558SYan, Zheng 	int found = 0;
1951aca1bba6SLiu Bo 	int ret = 0;
19523fd0a558SYan, Zheng again:
19533fd0a558SYan, Zheng 	root = rc->extent_root;
19547585717fSChris Mason 
19557585717fSChris Mason 	/*
19567585717fSChris Mason 	 * this serializes us with btrfs_record_root_in_transaction,
19577585717fSChris Mason 	 * we have to make sure nobody is in the middle of
19587585717fSChris Mason 	 * adding their roots to the list while we are
19597585717fSChris Mason 	 * doing this splice
19607585717fSChris Mason 	 */
19610b246afaSJeff Mahoney 	mutex_lock(&fs_info->reloc_mutex);
19623fd0a558SYan, Zheng 	list_splice_init(&rc->reloc_roots, &reloc_roots);
19630b246afaSJeff Mahoney 	mutex_unlock(&fs_info->reloc_mutex);
19645d4f98a2SYan Zheng 
19653fd0a558SYan, Zheng 	while (!list_empty(&reloc_roots)) {
19663fd0a558SYan, Zheng 		found = 1;
19673fd0a558SYan, Zheng 		reloc_root = list_entry(reloc_roots.next,
19683fd0a558SYan, Zheng 					struct btrfs_root, root_list);
19695d4f98a2SYan Zheng 
1970a820feb5SDavid Sterba 		root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
1971a820feb5SDavid Sterba 					 false);
19725d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
197324213fa4SJosef Bacik 			if (IS_ERR(root)) {
197424213fa4SJosef Bacik 				/*
197524213fa4SJosef Bacik 				 * For recovery we read the fs roots on mount,
197624213fa4SJosef Bacik 				 * and if we didn't find the root then we marked
197724213fa4SJosef Bacik 				 * the reloc root as a garbage root.  For normal
197824213fa4SJosef Bacik 				 * relocation obviously the root should exist in
197924213fa4SJosef Bacik 				 * memory.  However there's no reason we can't
198024213fa4SJosef Bacik 				 * handle the error properly here just in case.
198124213fa4SJosef Bacik 				 */
198224213fa4SJosef Bacik 				ASSERT(0);
198324213fa4SJosef Bacik 				ret = PTR_ERR(root);
198424213fa4SJosef Bacik 				goto out;
198524213fa4SJosef Bacik 			}
198624213fa4SJosef Bacik 			if (root->reloc_root != reloc_root) {
198724213fa4SJosef Bacik 				/*
198824213fa4SJosef Bacik 				 * This is actually impossible without something
198924213fa4SJosef Bacik 				 * going really wrong (like weird race condition
199024213fa4SJosef Bacik 				 * or cosmic rays).
199124213fa4SJosef Bacik 				 */
199224213fa4SJosef Bacik 				ASSERT(0);
199324213fa4SJosef Bacik 				ret = -EINVAL;
199424213fa4SJosef Bacik 				goto out;
199524213fa4SJosef Bacik 			}
19963fd0a558SYan, Zheng 			ret = merge_reloc_root(rc, root);
199700246528SJosef Bacik 			btrfs_put_root(root);
1998b37b39cdSJosef Bacik 			if (ret) {
199925e293c2SWang Shilong 				if (list_empty(&reloc_root->root_list))
200025e293c2SWang Shilong 					list_add_tail(&reloc_root->root_list,
200125e293c2SWang Shilong 						      &reloc_roots);
2002aca1bba6SLiu Bo 				goto out;
2003b37b39cdSJosef Bacik 			}
20043fd0a558SYan, Zheng 		} else {
200551415b6cSQu Wenruo 			if (!IS_ERR(root)) {
200651415b6cSQu Wenruo 				if (root->reloc_root == reloc_root) {
200751415b6cSQu Wenruo 					root->reloc_root = NULL;
200851415b6cSQu Wenruo 					btrfs_put_root(reloc_root);
200951415b6cSQu Wenruo 				}
20101dae7e0eSQu Wenruo 				clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE,
20111dae7e0eSQu Wenruo 					  &root->state);
201251415b6cSQu Wenruo 				btrfs_put_root(root);
201351415b6cSQu Wenruo 			}
201451415b6cSQu Wenruo 
20153fd0a558SYan, Zheng 			list_del_init(&reloc_root->root_list);
201630d40577SQu Wenruo 			/* Don't forget to queue this reloc root for cleanup */
201730d40577SQu Wenruo 			list_add_tail(&reloc_root->reloc_dirty_list,
201830d40577SQu Wenruo 				      &rc->dirty_subvol_roots);
20193fd0a558SYan, Zheng 		}
20205d4f98a2SYan Zheng 	}
20215d4f98a2SYan Zheng 
20223fd0a558SYan, Zheng 	if (found) {
20233fd0a558SYan, Zheng 		found = 0;
20243fd0a558SYan, Zheng 		goto again;
20255d4f98a2SYan Zheng 	}
2026aca1bba6SLiu Bo out:
2027aca1bba6SLiu Bo 	if (ret) {
20280b246afaSJeff Mahoney 		btrfs_handle_fs_error(fs_info, ret, NULL);
2029aca1bba6SLiu Bo 		free_reloc_roots(&reloc_roots);
2030467bb1d2SWang Shilong 
2031467bb1d2SWang Shilong 		/* new reloc root may be added */
20320b246afaSJeff Mahoney 		mutex_lock(&fs_info->reloc_mutex);
2033467bb1d2SWang Shilong 		list_splice_init(&rc->reloc_roots, &reloc_roots);
20340b246afaSJeff Mahoney 		mutex_unlock(&fs_info->reloc_mutex);
2035467bb1d2SWang Shilong 		free_reloc_roots(&reloc_roots);
2036aca1bba6SLiu Bo 	}
2037aca1bba6SLiu Bo 
20387b7b7431SJosef Bacik 	/*
20397b7b7431SJosef Bacik 	 * We used to have
20407b7b7431SJosef Bacik 	 *
20417b7b7431SJosef Bacik 	 * BUG_ON(!RB_EMPTY_ROOT(&rc->reloc_root_tree.rb_root));
20427b7b7431SJosef Bacik 	 *
20437b7b7431SJosef Bacik 	 * here, but it's wrong.  If we fail to start the transaction in
20447b7b7431SJosef Bacik 	 * prepare_to_merge() we will have only 0 ref reloc roots, none of which
20457b7b7431SJosef Bacik 	 * have actually been removed from the reloc_root_tree rb tree.  This is
20467b7b7431SJosef Bacik 	 * fine because we're bailing here, and we hold a reference on the root
20477b7b7431SJosef Bacik 	 * for the list that holds it, so these roots will be cleaned up when we
20487b7b7431SJosef Bacik 	 * do the reloc_dirty_list afterwards.  Meanwhile the root->reloc_root
20497b7b7431SJosef Bacik 	 * will be cleaned up on unmount.
20507b7b7431SJosef Bacik 	 *
20517b7b7431SJosef Bacik 	 * The remaining nodes will be cleaned up by free_reloc_control.
20527b7b7431SJosef Bacik 	 */
20535d4f98a2SYan Zheng }
20545d4f98a2SYan Zheng 
20555d4f98a2SYan Zheng static void free_block_list(struct rb_root *blocks)
20565d4f98a2SYan Zheng {
20575d4f98a2SYan Zheng 	struct tree_block *block;
20585d4f98a2SYan Zheng 	struct rb_node *rb_node;
20595d4f98a2SYan Zheng 	while ((rb_node = rb_first(blocks))) {
20605d4f98a2SYan Zheng 		block = rb_entry(rb_node, struct tree_block, rb_node);
20615d4f98a2SYan Zheng 		rb_erase(rb_node, blocks);
20625d4f98a2SYan Zheng 		kfree(block);
20635d4f98a2SYan Zheng 	}
20645d4f98a2SYan Zheng }
20655d4f98a2SYan Zheng 
20665d4f98a2SYan Zheng static int record_reloc_root_in_trans(struct btrfs_trans_handle *trans,
20675d4f98a2SYan Zheng 				      struct btrfs_root *reloc_root)
20685d4f98a2SYan Zheng {
20690b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = reloc_root->fs_info;
20705d4f98a2SYan Zheng 	struct btrfs_root *root;
2071442b1ac5SJosef Bacik 	int ret;
20725d4f98a2SYan Zheng 
20735d4f98a2SYan Zheng 	if (reloc_root->last_trans == trans->transid)
20745d4f98a2SYan Zheng 		return 0;
20755d4f98a2SYan Zheng 
2076a820feb5SDavid Sterba 	root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset, false);
2077404bccbcSJosef Bacik 
2078404bccbcSJosef Bacik 	/*
2079404bccbcSJosef Bacik 	 * This should succeed, since we can't have a reloc root without having
2080404bccbcSJosef Bacik 	 * already looked up the actual root and created the reloc root for this
2081404bccbcSJosef Bacik 	 * root.
2082404bccbcSJosef Bacik 	 *
2083404bccbcSJosef Bacik 	 * However if there's some sort of corruption where we have a ref to a
2084404bccbcSJosef Bacik 	 * reloc root without a corresponding root this could return ENOENT.
2085404bccbcSJosef Bacik 	 */
2086404bccbcSJosef Bacik 	if (IS_ERR(root)) {
2087404bccbcSJosef Bacik 		ASSERT(0);
2088404bccbcSJosef Bacik 		return PTR_ERR(root);
2089404bccbcSJosef Bacik 	}
2090404bccbcSJosef Bacik 	if (root->reloc_root != reloc_root) {
2091404bccbcSJosef Bacik 		ASSERT(0);
2092404bccbcSJosef Bacik 		btrfs_err(fs_info,
2093404bccbcSJosef Bacik 			  "root %llu has two reloc roots associated with it",
2094404bccbcSJosef Bacik 			  reloc_root->root_key.offset);
2095404bccbcSJosef Bacik 		btrfs_put_root(root);
2096404bccbcSJosef Bacik 		return -EUCLEAN;
2097404bccbcSJosef Bacik 	}
2098442b1ac5SJosef Bacik 	ret = btrfs_record_root_in_trans(trans, root);
209900246528SJosef Bacik 	btrfs_put_root(root);
21005d4f98a2SYan Zheng 
2101442b1ac5SJosef Bacik 	return ret;
21025d4f98a2SYan Zheng }
21035d4f98a2SYan Zheng 
21043fd0a558SYan, Zheng static noinline_for_stack
21053fd0a558SYan, Zheng struct btrfs_root *select_reloc_root(struct btrfs_trans_handle *trans,
21063fd0a558SYan, Zheng 				     struct reloc_control *rc,
2107a26195a5SQu Wenruo 				     struct btrfs_backref_node *node,
2108a26195a5SQu Wenruo 				     struct btrfs_backref_edge *edges[])
21095d4f98a2SYan Zheng {
2110a26195a5SQu Wenruo 	struct btrfs_backref_node *next;
21115d4f98a2SYan Zheng 	struct btrfs_root *root;
21123fd0a558SYan, Zheng 	int index = 0;
211392de551bSJosef Bacik 	int ret;
21143fd0a558SYan, Zheng 
21155d4f98a2SYan Zheng 	next = node;
21165d4f98a2SYan Zheng 	while (1) {
21175d4f98a2SYan Zheng 		cond_resched();
21185d4f98a2SYan Zheng 		next = walk_up_backref(next, edges, &index);
21195d4f98a2SYan Zheng 		root = next->root;
21208ee66afeSJosef Bacik 
21218ee66afeSJosef Bacik 		/*
21228ee66afeSJosef Bacik 		 * If there is no root, then our references for this block are
21238ee66afeSJosef Bacik 		 * incomplete, as we should be able to walk all the way up to a
21248ee66afeSJosef Bacik 		 * block that is owned by a root.
21258ee66afeSJosef Bacik 		 *
21268ee66afeSJosef Bacik 		 * This path is only for SHAREABLE roots, so if we come upon a
21278ee66afeSJosef Bacik 		 * non-SHAREABLE root then we have backrefs that resolve
21288ee66afeSJosef Bacik 		 * improperly.
21298ee66afeSJosef Bacik 		 *
21308ee66afeSJosef Bacik 		 * Both of these cases indicate file system corruption, or a bug
21318ee66afeSJosef Bacik 		 * in the backref walking code.
21328ee66afeSJosef Bacik 		 */
21338ee66afeSJosef Bacik 		if (!root) {
21348ee66afeSJosef Bacik 			ASSERT(0);
21358ee66afeSJosef Bacik 			btrfs_err(trans->fs_info,
21368ee66afeSJosef Bacik 		"bytenr %llu doesn't have a backref path ending in a root",
21378ee66afeSJosef Bacik 				  node->bytenr);
21388ee66afeSJosef Bacik 			return ERR_PTR(-EUCLEAN);
21398ee66afeSJosef Bacik 		}
21408ee66afeSJosef Bacik 		if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
21418ee66afeSJosef Bacik 			ASSERT(0);
21428ee66afeSJosef Bacik 			btrfs_err(trans->fs_info,
21438ee66afeSJosef Bacik 	"bytenr %llu has multiple refs with one ending in a non-shareable root",
21448ee66afeSJosef Bacik 				  node->bytenr);
21458ee66afeSJosef Bacik 			return ERR_PTR(-EUCLEAN);
21468ee66afeSJosef Bacik 		}
21475d4f98a2SYan Zheng 
21485d4f98a2SYan Zheng 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
214992de551bSJosef Bacik 			ret = record_reloc_root_in_trans(trans, root);
215092de551bSJosef Bacik 			if (ret)
215192de551bSJosef Bacik 				return ERR_PTR(ret);
21525d4f98a2SYan Zheng 			break;
21535d4f98a2SYan Zheng 		}
21545d4f98a2SYan Zheng 
215592de551bSJosef Bacik 		ret = btrfs_record_root_in_trans(trans, root);
215692de551bSJosef Bacik 		if (ret)
215792de551bSJosef Bacik 			return ERR_PTR(ret);
21583fd0a558SYan, Zheng 		root = root->reloc_root;
21593fd0a558SYan, Zheng 
216039200e59SJosef Bacik 		/*
216139200e59SJosef Bacik 		 * We could have raced with another thread which failed, so
216239200e59SJosef Bacik 		 * root->reloc_root may not be set, return ENOENT in this case.
216339200e59SJosef Bacik 		 */
216439200e59SJosef Bacik 		if (!root)
216539200e59SJosef Bacik 			return ERR_PTR(-ENOENT);
216639200e59SJosef Bacik 
21673fd0a558SYan, Zheng 		if (next->new_bytenr != root->node->start) {
21688ee66afeSJosef Bacik 			/*
21698ee66afeSJosef Bacik 			 * We just created the reloc root, so we shouldn't have
21708ee66afeSJosef Bacik 			 * ->new_bytenr set and this shouldn't be in the changed
21718ee66afeSJosef Bacik 			 *  list.  If it is then we have multiple roots pointing
21728ee66afeSJosef Bacik 			 *  at the same bytenr which indicates corruption, or
21738ee66afeSJosef Bacik 			 *  we've made a mistake in the backref walking code.
21748ee66afeSJosef Bacik 			 */
21758ee66afeSJosef Bacik 			ASSERT(next->new_bytenr == 0);
21768ee66afeSJosef Bacik 			ASSERT(list_empty(&next->list));
21778ee66afeSJosef Bacik 			if (next->new_bytenr || !list_empty(&next->list)) {
21788ee66afeSJosef Bacik 				btrfs_err(trans->fs_info,
21798ee66afeSJosef Bacik 	"bytenr %llu possibly has multiple roots pointing at the same bytenr %llu",
21808ee66afeSJosef Bacik 					  node->bytenr, next->bytenr);
21818ee66afeSJosef Bacik 				return ERR_PTR(-EUCLEAN);
21828ee66afeSJosef Bacik 			}
21838ee66afeSJosef Bacik 
21843fd0a558SYan, Zheng 			next->new_bytenr = root->node->start;
218500246528SJosef Bacik 			btrfs_put_root(next->root);
218600246528SJosef Bacik 			next->root = btrfs_grab_root(root);
21870b530bc5SJosef Bacik 			ASSERT(next->root);
21883fd0a558SYan, Zheng 			list_add_tail(&next->list,
21893fd0a558SYan, Zheng 				      &rc->backref_cache.changed);
21909569cc20SQu Wenruo 			mark_block_processed(rc, next);
21915d4f98a2SYan Zheng 			break;
21925d4f98a2SYan Zheng 		}
21935d4f98a2SYan Zheng 
21943fd0a558SYan, Zheng 		WARN_ON(1);
21955d4f98a2SYan Zheng 		root = NULL;
21965d4f98a2SYan Zheng 		next = walk_down_backref(edges, &index);
21975d4f98a2SYan Zheng 		if (!next || next->level <= node->level)
21985d4f98a2SYan Zheng 			break;
21995d4f98a2SYan Zheng 	}
2200cbdc2ebcSJosef Bacik 	if (!root) {
2201cbdc2ebcSJosef Bacik 		/*
2202cbdc2ebcSJosef Bacik 		 * This can happen if there's fs corruption or if there's a bug
2203cbdc2ebcSJosef Bacik 		 * in the backref lookup code.
2204cbdc2ebcSJosef Bacik 		 */
2205cbdc2ebcSJosef Bacik 		ASSERT(0);
2206cbdc2ebcSJosef Bacik 		return ERR_PTR(-ENOENT);
2207cbdc2ebcSJosef Bacik 	}
22085d4f98a2SYan Zheng 
22093fd0a558SYan, Zheng 	next = node;
22103fd0a558SYan, Zheng 	/* setup backref node path for btrfs_reloc_cow_block */
22113fd0a558SYan, Zheng 	while (1) {
22123fd0a558SYan, Zheng 		rc->backref_cache.path[next->level] = next;
22133fd0a558SYan, Zheng 		if (--index < 0)
22143fd0a558SYan, Zheng 			break;
22153fd0a558SYan, Zheng 		next = edges[index]->node[UPPER];
22163fd0a558SYan, Zheng 	}
22175d4f98a2SYan Zheng 	return root;
22185d4f98a2SYan Zheng }
22195d4f98a2SYan Zheng 
22203fd0a558SYan, Zheng /*
222192a7cc42SQu Wenruo  * Select a tree root for relocation.
222292a7cc42SQu Wenruo  *
222392a7cc42SQu Wenruo  * Return NULL if the block is not shareable. We should use do_relocation() in
222492a7cc42SQu Wenruo  * this case.
222592a7cc42SQu Wenruo  *
222692a7cc42SQu Wenruo  * Return a tree root pointer if the block is shareable.
222792a7cc42SQu Wenruo  * Return -ENOENT if the block is root of reloc tree.
22283fd0a558SYan, Zheng  */
22295d4f98a2SYan Zheng static noinline_for_stack
2230a26195a5SQu Wenruo struct btrfs_root *select_one_root(struct btrfs_backref_node *node)
22315d4f98a2SYan Zheng {
2232a26195a5SQu Wenruo 	struct btrfs_backref_node *next;
22333fd0a558SYan, Zheng 	struct btrfs_root *root;
22343fd0a558SYan, Zheng 	struct btrfs_root *fs_root = NULL;
2235a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
22363fd0a558SYan, Zheng 	int index = 0;
22373fd0a558SYan, Zheng 
22383fd0a558SYan, Zheng 	next = node;
22393fd0a558SYan, Zheng 	while (1) {
22403fd0a558SYan, Zheng 		cond_resched();
22413fd0a558SYan, Zheng 		next = walk_up_backref(next, edges, &index);
22423fd0a558SYan, Zheng 		root = next->root;
22438717cf44SJosef Bacik 
22448717cf44SJosef Bacik 		/*
22458717cf44SJosef Bacik 		 * This can occur if we have incomplete extent refs leading all
22468717cf44SJosef Bacik 		 * the way up a particular path, in this case return -EUCLEAN.
22478717cf44SJosef Bacik 		 */
22488717cf44SJosef Bacik 		if (!root)
22498717cf44SJosef Bacik 			return ERR_PTR(-EUCLEAN);
22503fd0a558SYan, Zheng 
225192a7cc42SQu Wenruo 		/* No other choice for non-shareable tree */
225292a7cc42SQu Wenruo 		if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
22533fd0a558SYan, Zheng 			return root;
22543fd0a558SYan, Zheng 
22553fd0a558SYan, Zheng 		if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID)
22563fd0a558SYan, Zheng 			fs_root = root;
22573fd0a558SYan, Zheng 
22583fd0a558SYan, Zheng 		if (next != node)
22593fd0a558SYan, Zheng 			return NULL;
22603fd0a558SYan, Zheng 
22613fd0a558SYan, Zheng 		next = walk_down_backref(edges, &index);
22623fd0a558SYan, Zheng 		if (!next || next->level <= node->level)
22633fd0a558SYan, Zheng 			break;
22643fd0a558SYan, Zheng 	}
22653fd0a558SYan, Zheng 
22663fd0a558SYan, Zheng 	if (!fs_root)
22673fd0a558SYan, Zheng 		return ERR_PTR(-ENOENT);
22683fd0a558SYan, Zheng 	return fs_root;
22695d4f98a2SYan Zheng }
22705d4f98a2SYan Zheng 
22715d4f98a2SYan Zheng static noinline_for_stack
22723fd0a558SYan, Zheng u64 calcu_metadata_size(struct reloc_control *rc,
2273a26195a5SQu Wenruo 			struct btrfs_backref_node *node, int reserve)
22745d4f98a2SYan Zheng {
22750b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2276a26195a5SQu Wenruo 	struct btrfs_backref_node *next = node;
2277a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2278a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
22793fd0a558SYan, Zheng 	u64 num_bytes = 0;
22803fd0a558SYan, Zheng 	int index = 0;
22815d4f98a2SYan Zheng 
22823fd0a558SYan, Zheng 	BUG_ON(reserve && node->processed);
22833fd0a558SYan, Zheng 
22843fd0a558SYan, Zheng 	while (next) {
22853fd0a558SYan, Zheng 		cond_resched();
22865d4f98a2SYan Zheng 		while (1) {
22873fd0a558SYan, Zheng 			if (next->processed && (reserve || next != node))
22885d4f98a2SYan Zheng 				break;
22895d4f98a2SYan Zheng 
22900b246afaSJeff Mahoney 			num_bytes += fs_info->nodesize;
22913fd0a558SYan, Zheng 
22923fd0a558SYan, Zheng 			if (list_empty(&next->upper))
22933fd0a558SYan, Zheng 				break;
22943fd0a558SYan, Zheng 
22953fd0a558SYan, Zheng 			edge = list_entry(next->upper.next,
2296a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[LOWER]);
22973fd0a558SYan, Zheng 			edges[index++] = edge;
22983fd0a558SYan, Zheng 			next = edge->node[UPPER];
22995d4f98a2SYan Zheng 		}
23003fd0a558SYan, Zheng 		next = walk_down_backref(edges, &index);
23013fd0a558SYan, Zheng 	}
23023fd0a558SYan, Zheng 	return num_bytes;
23033fd0a558SYan, Zheng }
23043fd0a558SYan, Zheng 
23053fd0a558SYan, Zheng static int reserve_metadata_space(struct btrfs_trans_handle *trans,
23063fd0a558SYan, Zheng 				  struct reloc_control *rc,
2307a26195a5SQu Wenruo 				  struct btrfs_backref_node *node)
23083fd0a558SYan, Zheng {
23093fd0a558SYan, Zheng 	struct btrfs_root *root = rc->extent_root;
2310da17066cSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
23113fd0a558SYan, Zheng 	u64 num_bytes;
23123fd0a558SYan, Zheng 	int ret;
23130647bf56SWang Shilong 	u64 tmp;
23143fd0a558SYan, Zheng 
23153fd0a558SYan, Zheng 	num_bytes = calcu_metadata_size(rc, node, 1) * 2;
23163fd0a558SYan, Zheng 
23173fd0a558SYan, Zheng 	trans->block_rsv = rc->block_rsv;
23180647bf56SWang Shilong 	rc->reserved_bytes += num_bytes;
23198ca17f0fSJosef Bacik 
23208ca17f0fSJosef Bacik 	/*
23218ca17f0fSJosef Bacik 	 * We are under a transaction here so we can only do limited flushing.
23228ca17f0fSJosef Bacik 	 * If we get an enospc just kick back -EAGAIN so we know to drop the
23238ca17f0fSJosef Bacik 	 * transaction and try to refill when we can flush all the things.
23248ca17f0fSJosef Bacik 	 */
23250647bf56SWang Shilong 	ret = btrfs_block_rsv_refill(root, rc->block_rsv, num_bytes,
23268ca17f0fSJosef Bacik 				BTRFS_RESERVE_FLUSH_LIMIT);
23273fd0a558SYan, Zheng 	if (ret) {
2328da17066cSJeff Mahoney 		tmp = fs_info->nodesize * RELOCATION_RESERVED_NODES;
23290647bf56SWang Shilong 		while (tmp <= rc->reserved_bytes)
23300647bf56SWang Shilong 			tmp <<= 1;
23310647bf56SWang Shilong 		/*
23320647bf56SWang Shilong 		 * only one thread can access block_rsv at this point,
23330647bf56SWang Shilong 		 * so we don't need hold lock to protect block_rsv.
23340647bf56SWang Shilong 		 * we expand more reservation size here to allow enough
233552042d8eSAndrea Gelmini 		 * space for relocation and we will return earlier in
23360647bf56SWang Shilong 		 * enospc case.
23370647bf56SWang Shilong 		 */
2338da17066cSJeff Mahoney 		rc->block_rsv->size = tmp + fs_info->nodesize *
23390647bf56SWang Shilong 				      RELOCATION_RESERVED_NODES;
23408ca17f0fSJosef Bacik 		return -EAGAIN;
23413fd0a558SYan, Zheng 	}
23423fd0a558SYan, Zheng 
23433fd0a558SYan, Zheng 	return 0;
23443fd0a558SYan, Zheng }
23453fd0a558SYan, Zheng 
23465d4f98a2SYan Zheng /*
23475d4f98a2SYan Zheng  * relocate a block tree, and then update pointers in upper level
23485d4f98a2SYan Zheng  * blocks that reference the block to point to the new location.
23495d4f98a2SYan Zheng  *
23505d4f98a2SYan Zheng  * if called by link_to_upper, the block has already been relocated.
23515d4f98a2SYan Zheng  * in that case this function just updates pointers.
23525d4f98a2SYan Zheng  */
23535d4f98a2SYan Zheng static int do_relocation(struct btrfs_trans_handle *trans,
23543fd0a558SYan, Zheng 			 struct reloc_control *rc,
2355a26195a5SQu Wenruo 			 struct btrfs_backref_node *node,
23565d4f98a2SYan Zheng 			 struct btrfs_key *key,
23575d4f98a2SYan Zheng 			 struct btrfs_path *path, int lowest)
23585d4f98a2SYan Zheng {
2359a26195a5SQu Wenruo 	struct btrfs_backref_node *upper;
2360a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2361a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
23625d4f98a2SYan Zheng 	struct btrfs_root *root;
23635d4f98a2SYan Zheng 	struct extent_buffer *eb;
23645d4f98a2SYan Zheng 	u32 blocksize;
23655d4f98a2SYan Zheng 	u64 bytenr;
23665d4f98a2SYan Zheng 	int slot;
23678df01fddSNikolay Borisov 	int ret = 0;
23685d4f98a2SYan Zheng 
2369ffe30dd8SJosef Bacik 	/*
2370ffe30dd8SJosef Bacik 	 * If we are lowest then this is the first time we're processing this
2371ffe30dd8SJosef Bacik 	 * block, and thus shouldn't have an eb associated with it yet.
2372ffe30dd8SJosef Bacik 	 */
2373ffe30dd8SJosef Bacik 	ASSERT(!lowest || !node->eb);
23745d4f98a2SYan Zheng 
23755d4f98a2SYan Zheng 	path->lowest_level = node->level + 1;
23763fd0a558SYan, Zheng 	rc->backref_cache.path[node->level] = node;
23775d4f98a2SYan Zheng 	list_for_each_entry(edge, &node->upper, list[LOWER]) {
237882fa113fSQu Wenruo 		struct btrfs_ref ref = { 0 };
2379581c1760SQu Wenruo 
23805d4f98a2SYan Zheng 		cond_resched();
23815d4f98a2SYan Zheng 
23825d4f98a2SYan Zheng 		upper = edge->node[UPPER];
2383dc4103f9SWang Shilong 		root = select_reloc_root(trans, rc, upper, edges);
2384cbdc2ebcSJosef Bacik 		if (IS_ERR(root)) {
2385cbdc2ebcSJosef Bacik 			ret = PTR_ERR(root);
2386cbdc2ebcSJosef Bacik 			goto next;
2387cbdc2ebcSJosef Bacik 		}
23885d4f98a2SYan Zheng 
23893fd0a558SYan, Zheng 		if (upper->eb && !upper->locked) {
23903fd0a558SYan, Zheng 			if (!lowest) {
2391e3b83361SQu Wenruo 				ret = btrfs_bin_search(upper->eb, key, &slot);
23928df01fddSNikolay Borisov 				if (ret < 0)
2393cbca7d59SFilipe Manana 					goto next;
23943fd0a558SYan, Zheng 				BUG_ON(ret);
23953fd0a558SYan, Zheng 				bytenr = btrfs_node_blockptr(upper->eb, slot);
23963fd0a558SYan, Zheng 				if (node->eb->start == bytenr)
23973fd0a558SYan, Zheng 					goto next;
23983fd0a558SYan, Zheng 			}
2399b0fe7078SQu Wenruo 			btrfs_backref_drop_node_buffer(upper);
24003fd0a558SYan, Zheng 		}
24015d4f98a2SYan Zheng 
24025d4f98a2SYan Zheng 		if (!upper->eb) {
24035d4f98a2SYan Zheng 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
24043561b9dbSLiu Bo 			if (ret) {
24058df01fddSNikolay Borisov 				if (ret > 0)
24068df01fddSNikolay Borisov 					ret = -ENOENT;
24073561b9dbSLiu Bo 
24083561b9dbSLiu Bo 				btrfs_release_path(path);
24095d4f98a2SYan Zheng 				break;
24105d4f98a2SYan Zheng 			}
24115d4f98a2SYan Zheng 
24123fd0a558SYan, Zheng 			if (!upper->eb) {
24133fd0a558SYan, Zheng 				upper->eb = path->nodes[upper->level];
24143fd0a558SYan, Zheng 				path->nodes[upper->level] = NULL;
24153fd0a558SYan, Zheng 			} else {
24163fd0a558SYan, Zheng 				BUG_ON(upper->eb != path->nodes[upper->level]);
24173fd0a558SYan, Zheng 			}
24183fd0a558SYan, Zheng 
24193fd0a558SYan, Zheng 			upper->locked = 1;
24203fd0a558SYan, Zheng 			path->locks[upper->level] = 0;
24213fd0a558SYan, Zheng 
24225d4f98a2SYan Zheng 			slot = path->slots[upper->level];
2423b3b4aa74SDavid Sterba 			btrfs_release_path(path);
24245d4f98a2SYan Zheng 		} else {
2425e3b83361SQu Wenruo 			ret = btrfs_bin_search(upper->eb, key, &slot);
24268df01fddSNikolay Borisov 			if (ret < 0)
2427cbca7d59SFilipe Manana 				goto next;
24285d4f98a2SYan Zheng 			BUG_ON(ret);
24295d4f98a2SYan Zheng 		}
24305d4f98a2SYan Zheng 
24315d4f98a2SYan Zheng 		bytenr = btrfs_node_blockptr(upper->eb, slot);
24323fd0a558SYan, Zheng 		if (lowest) {
24334547f4d8SLiu Bo 			if (bytenr != node->bytenr) {
24344547f4d8SLiu Bo 				btrfs_err(root->fs_info,
24354547f4d8SLiu Bo 		"lowest leaf/node mismatch: bytenr %llu node->bytenr %llu slot %d upper %llu",
24364547f4d8SLiu Bo 					  bytenr, node->bytenr, slot,
24374547f4d8SLiu Bo 					  upper->eb->start);
24388df01fddSNikolay Borisov 				ret = -EIO;
24394547f4d8SLiu Bo 				goto next;
24404547f4d8SLiu Bo 			}
24415d4f98a2SYan Zheng 		} else {
24423fd0a558SYan, Zheng 			if (node->eb->start == bytenr)
24433fd0a558SYan, Zheng 				goto next;
24445d4f98a2SYan Zheng 		}
24455d4f98a2SYan Zheng 
2446da17066cSJeff Mahoney 		blocksize = root->fs_info->nodesize;
2447c9752536SJosef Bacik 		eb = btrfs_read_node_slot(upper->eb, slot);
244864c043deSLiu Bo 		if (IS_ERR(eb)) {
24498df01fddSNikolay Borisov 			ret = PTR_ERR(eb);
245064c043deSLiu Bo 			goto next;
245197d9a8a4STsutomu Itoh 		}
24525d4f98a2SYan Zheng 		btrfs_tree_lock(eb);
24535d4f98a2SYan Zheng 
24545d4f98a2SYan Zheng 		if (!node->eb) {
24555d4f98a2SYan Zheng 			ret = btrfs_cow_block(trans, root, eb, upper->eb,
24569631e4ccSJosef Bacik 					      slot, &eb, BTRFS_NESTING_COW);
24573fd0a558SYan, Zheng 			btrfs_tree_unlock(eb);
24583fd0a558SYan, Zheng 			free_extent_buffer(eb);
24598df01fddSNikolay Borisov 			if (ret < 0)
24603fd0a558SYan, Zheng 				goto next;
2461ffe30dd8SJosef Bacik 			/*
2462ffe30dd8SJosef Bacik 			 * We've just COWed this block, it should have updated
2463ffe30dd8SJosef Bacik 			 * the correct backref node entry.
2464ffe30dd8SJosef Bacik 			 */
2465ffe30dd8SJosef Bacik 			ASSERT(node->eb == eb);
24665d4f98a2SYan Zheng 		} else {
24675d4f98a2SYan Zheng 			btrfs_set_node_blockptr(upper->eb, slot,
24685d4f98a2SYan Zheng 						node->eb->start);
24695d4f98a2SYan Zheng 			btrfs_set_node_ptr_generation(upper->eb, slot,
24705d4f98a2SYan Zheng 						      trans->transid);
24715d4f98a2SYan Zheng 			btrfs_mark_buffer_dirty(upper->eb);
24725d4f98a2SYan Zheng 
247382fa113fSQu Wenruo 			btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF,
24745d4f98a2SYan Zheng 					       node->eb->start, blocksize,
247582fa113fSQu Wenruo 					       upper->eb->start);
247682fa113fSQu Wenruo 			ref.real_root = root->root_key.objectid;
247782fa113fSQu Wenruo 			btrfs_init_tree_ref(&ref, node->level,
247882fa113fSQu Wenruo 					    btrfs_header_owner(upper->eb));
247982fa113fSQu Wenruo 			ret = btrfs_inc_extent_ref(trans, &ref);
2480eb6b7fb4SJosef Bacik 			if (!ret)
2481eb6b7fb4SJosef Bacik 				ret = btrfs_drop_subtree(trans, root, eb,
2482eb6b7fb4SJosef Bacik 							 upper->eb);
2483eb6b7fb4SJosef Bacik 			if (ret)
2484eb6b7fb4SJosef Bacik 				btrfs_abort_transaction(trans, ret);
24855d4f98a2SYan Zheng 		}
24863fd0a558SYan, Zheng next:
24873fd0a558SYan, Zheng 		if (!upper->pending)
2488b0fe7078SQu Wenruo 			btrfs_backref_drop_node_buffer(upper);
24893fd0a558SYan, Zheng 		else
2490b0fe7078SQu Wenruo 			btrfs_backref_unlock_node_buffer(upper);
24918df01fddSNikolay Borisov 		if (ret)
24923fd0a558SYan, Zheng 			break;
24935d4f98a2SYan Zheng 	}
24943fd0a558SYan, Zheng 
24958df01fddSNikolay Borisov 	if (!ret && node->pending) {
2496b0fe7078SQu Wenruo 		btrfs_backref_drop_node_buffer(node);
24973fd0a558SYan, Zheng 		list_move_tail(&node->list, &rc->backref_cache.changed);
24983fd0a558SYan, Zheng 		node->pending = 0;
24995d4f98a2SYan Zheng 	}
25003fd0a558SYan, Zheng 
25015d4f98a2SYan Zheng 	path->lowest_level = 0;
2502ffe30dd8SJosef Bacik 
2503ffe30dd8SJosef Bacik 	/*
2504ffe30dd8SJosef Bacik 	 * We should have allocated all of our space in the block rsv and thus
2505ffe30dd8SJosef Bacik 	 * shouldn't ENOSPC.
2506ffe30dd8SJosef Bacik 	 */
2507ffe30dd8SJosef Bacik 	ASSERT(ret != -ENOSPC);
25088df01fddSNikolay Borisov 	return ret;
25095d4f98a2SYan Zheng }
25105d4f98a2SYan Zheng 
25115d4f98a2SYan Zheng static int link_to_upper(struct btrfs_trans_handle *trans,
25123fd0a558SYan, Zheng 			 struct reloc_control *rc,
2513a26195a5SQu Wenruo 			 struct btrfs_backref_node *node,
25145d4f98a2SYan Zheng 			 struct btrfs_path *path)
25155d4f98a2SYan Zheng {
25165d4f98a2SYan Zheng 	struct btrfs_key key;
25175d4f98a2SYan Zheng 
25185d4f98a2SYan Zheng 	btrfs_node_key_to_cpu(node->eb, &key, 0);
25193fd0a558SYan, Zheng 	return do_relocation(trans, rc, node, &key, path, 0);
25205d4f98a2SYan Zheng }
25215d4f98a2SYan Zheng 
25225d4f98a2SYan Zheng static int finish_pending_nodes(struct btrfs_trans_handle *trans,
25233fd0a558SYan, Zheng 				struct reloc_control *rc,
25243fd0a558SYan, Zheng 				struct btrfs_path *path, int err)
25255d4f98a2SYan Zheng {
25263fd0a558SYan, Zheng 	LIST_HEAD(list);
2527a26195a5SQu Wenruo 	struct btrfs_backref_cache *cache = &rc->backref_cache;
2528a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
25295d4f98a2SYan Zheng 	int level;
25305d4f98a2SYan Zheng 	int ret;
25315d4f98a2SYan Zheng 
25325d4f98a2SYan Zheng 	for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
25335d4f98a2SYan Zheng 		while (!list_empty(&cache->pending[level])) {
25345d4f98a2SYan Zheng 			node = list_entry(cache->pending[level].next,
2535a26195a5SQu Wenruo 					  struct btrfs_backref_node, list);
25363fd0a558SYan, Zheng 			list_move_tail(&node->list, &list);
25373fd0a558SYan, Zheng 			BUG_ON(!node->pending);
25385d4f98a2SYan Zheng 
25393fd0a558SYan, Zheng 			if (!err) {
25403fd0a558SYan, Zheng 				ret = link_to_upper(trans, rc, node, path);
25415d4f98a2SYan Zheng 				if (ret < 0)
25425d4f98a2SYan Zheng 					err = ret;
25435d4f98a2SYan Zheng 			}
25445d4f98a2SYan Zheng 		}
25453fd0a558SYan, Zheng 		list_splice_init(&list, &cache->pending[level]);
25463fd0a558SYan, Zheng 	}
25475d4f98a2SYan Zheng 	return err;
25485d4f98a2SYan Zheng }
25495d4f98a2SYan Zheng 
25505d4f98a2SYan Zheng /*
25515d4f98a2SYan Zheng  * mark a block and all blocks directly/indirectly reference the block
25525d4f98a2SYan Zheng  * as processed.
25535d4f98a2SYan Zheng  */
25545d4f98a2SYan Zheng static void update_processed_blocks(struct reloc_control *rc,
2555a26195a5SQu Wenruo 				    struct btrfs_backref_node *node)
25565d4f98a2SYan Zheng {
2557a26195a5SQu Wenruo 	struct btrfs_backref_node *next = node;
2558a26195a5SQu Wenruo 	struct btrfs_backref_edge *edge;
2559a26195a5SQu Wenruo 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
25605d4f98a2SYan Zheng 	int index = 0;
25615d4f98a2SYan Zheng 
25625d4f98a2SYan Zheng 	while (next) {
25635d4f98a2SYan Zheng 		cond_resched();
25645d4f98a2SYan Zheng 		while (1) {
25655d4f98a2SYan Zheng 			if (next->processed)
25665d4f98a2SYan Zheng 				break;
25675d4f98a2SYan Zheng 
25689569cc20SQu Wenruo 			mark_block_processed(rc, next);
25695d4f98a2SYan Zheng 
25705d4f98a2SYan Zheng 			if (list_empty(&next->upper))
25715d4f98a2SYan Zheng 				break;
25725d4f98a2SYan Zheng 
25735d4f98a2SYan Zheng 			edge = list_entry(next->upper.next,
2574a26195a5SQu Wenruo 					struct btrfs_backref_edge, list[LOWER]);
25755d4f98a2SYan Zheng 			edges[index++] = edge;
25765d4f98a2SYan Zheng 			next = edge->node[UPPER];
25775d4f98a2SYan Zheng 		}
25785d4f98a2SYan Zheng 		next = walk_down_backref(edges, &index);
25795d4f98a2SYan Zheng 	}
25805d4f98a2SYan Zheng }
25815d4f98a2SYan Zheng 
25827476dfdaSDavid Sterba static int tree_block_processed(u64 bytenr, struct reloc_control *rc)
25835d4f98a2SYan Zheng {
2584da17066cSJeff Mahoney 	u32 blocksize = rc->extent_root->fs_info->nodesize;
25857476dfdaSDavid Sterba 
25865d4f98a2SYan Zheng 	if (test_range_bit(&rc->processed_blocks, bytenr,
25879655d298SChris Mason 			   bytenr + blocksize - 1, EXTENT_DIRTY, 1, NULL))
25885d4f98a2SYan Zheng 		return 1;
25895d4f98a2SYan Zheng 	return 0;
25905d4f98a2SYan Zheng }
25915d4f98a2SYan Zheng 
25922ff7e61eSJeff Mahoney static int get_tree_block_key(struct btrfs_fs_info *fs_info,
25935d4f98a2SYan Zheng 			      struct tree_block *block)
25945d4f98a2SYan Zheng {
25955d4f98a2SYan Zheng 	struct extent_buffer *eb;
25965d4f98a2SYan Zheng 
2597f7ba2d37SJosef Bacik 	eb = read_tree_block(fs_info, block->bytenr, block->owner,
2598f7ba2d37SJosef Bacik 			     block->key.offset, block->level, NULL);
259964c043deSLiu Bo 	if (IS_ERR(eb)) {
260064c043deSLiu Bo 		return PTR_ERR(eb);
260164c043deSLiu Bo 	} else if (!extent_buffer_uptodate(eb)) {
2602416bc658SJosef Bacik 		free_extent_buffer(eb);
2603416bc658SJosef Bacik 		return -EIO;
2604416bc658SJosef Bacik 	}
26055d4f98a2SYan Zheng 	if (block->level == 0)
26065d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(eb, &block->key, 0);
26075d4f98a2SYan Zheng 	else
26085d4f98a2SYan Zheng 		btrfs_node_key_to_cpu(eb, &block->key, 0);
26095d4f98a2SYan Zheng 	free_extent_buffer(eb);
26105d4f98a2SYan Zheng 	block->key_ready = 1;
26115d4f98a2SYan Zheng 	return 0;
26125d4f98a2SYan Zheng }
26135d4f98a2SYan Zheng 
26145d4f98a2SYan Zheng /*
26155d4f98a2SYan Zheng  * helper function to relocate a tree block
26165d4f98a2SYan Zheng  */
26175d4f98a2SYan Zheng static int relocate_tree_block(struct btrfs_trans_handle *trans,
26185d4f98a2SYan Zheng 				struct reloc_control *rc,
2619a26195a5SQu Wenruo 				struct btrfs_backref_node *node,
26205d4f98a2SYan Zheng 				struct btrfs_key *key,
26215d4f98a2SYan Zheng 				struct btrfs_path *path)
26225d4f98a2SYan Zheng {
26235d4f98a2SYan Zheng 	struct btrfs_root *root;
26243fd0a558SYan, Zheng 	int ret = 0;
26255d4f98a2SYan Zheng 
26263fd0a558SYan, Zheng 	if (!node)
26275d4f98a2SYan Zheng 		return 0;
26283fd0a558SYan, Zheng 
26295f6b2e5cSJosef Bacik 	/*
26305f6b2e5cSJosef Bacik 	 * If we fail here we want to drop our backref_node because we are going
26315f6b2e5cSJosef Bacik 	 * to start over and regenerate the tree for it.
26325f6b2e5cSJosef Bacik 	 */
26335f6b2e5cSJosef Bacik 	ret = reserve_metadata_space(trans, rc, node);
26345f6b2e5cSJosef Bacik 	if (ret)
26355f6b2e5cSJosef Bacik 		goto out;
26365f6b2e5cSJosef Bacik 
26373fd0a558SYan, Zheng 	BUG_ON(node->processed);
2638147d256eSZhaolei 	root = select_one_root(node);
26398717cf44SJosef Bacik 	if (IS_ERR(root)) {
26408717cf44SJosef Bacik 		ret = PTR_ERR(root);
26418717cf44SJosef Bacik 
26428717cf44SJosef Bacik 		/* See explanation in select_one_root for the -EUCLEAN case. */
26438717cf44SJosef Bacik 		ASSERT(ret == -ENOENT);
26448717cf44SJosef Bacik 		if (ret == -ENOENT) {
26458717cf44SJosef Bacik 			ret = 0;
26463fd0a558SYan, Zheng 			update_processed_blocks(rc, node);
26478717cf44SJosef Bacik 		}
26483fd0a558SYan, Zheng 		goto out;
26495d4f98a2SYan Zheng 	}
26505d4f98a2SYan Zheng 
26513fd0a558SYan, Zheng 	if (root) {
265292a7cc42SQu Wenruo 		if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
26531c7bfa15SJosef Bacik 			/*
26541c7bfa15SJosef Bacik 			 * This block was the root block of a root, and this is
26551c7bfa15SJosef Bacik 			 * the first time we're processing the block and thus it
26561c7bfa15SJosef Bacik 			 * should not have had the ->new_bytenr modified and
26571c7bfa15SJosef Bacik 			 * should have not been included on the changed list.
26581c7bfa15SJosef Bacik 			 *
26591c7bfa15SJosef Bacik 			 * However in the case of corruption we could have
26601c7bfa15SJosef Bacik 			 * multiple refs pointing to the same block improperly,
26611c7bfa15SJosef Bacik 			 * and thus we would trip over these checks.  ASSERT()
26621c7bfa15SJosef Bacik 			 * for the developer case, because it could indicate a
26631c7bfa15SJosef Bacik 			 * bug in the backref code, however error out for a
26641c7bfa15SJosef Bacik 			 * normal user in the case of corruption.
26651c7bfa15SJosef Bacik 			 */
26661c7bfa15SJosef Bacik 			ASSERT(node->new_bytenr == 0);
26671c7bfa15SJosef Bacik 			ASSERT(list_empty(&node->list));
26681c7bfa15SJosef Bacik 			if (node->new_bytenr || !list_empty(&node->list)) {
26691c7bfa15SJosef Bacik 				btrfs_err(root->fs_info,
26701c7bfa15SJosef Bacik 				  "bytenr %llu has improper references to it",
26711c7bfa15SJosef Bacik 					  node->bytenr);
26721c7bfa15SJosef Bacik 				ret = -EUCLEAN;
26731c7bfa15SJosef Bacik 				goto out;
26741c7bfa15SJosef Bacik 			}
2675d18c7bd9SJosef Bacik 			ret = btrfs_record_root_in_trans(trans, root);
2676d18c7bd9SJosef Bacik 			if (ret)
2677d18c7bd9SJosef Bacik 				goto out;
267839200e59SJosef Bacik 			/*
267939200e59SJosef Bacik 			 * Another thread could have failed, need to check if we
268039200e59SJosef Bacik 			 * have reloc_root actually set.
268139200e59SJosef Bacik 			 */
268239200e59SJosef Bacik 			if (!root->reloc_root) {
268339200e59SJosef Bacik 				ret = -ENOENT;
268439200e59SJosef Bacik 				goto out;
268539200e59SJosef Bacik 			}
26863fd0a558SYan, Zheng 			root = root->reloc_root;
26873fd0a558SYan, Zheng 			node->new_bytenr = root->node->start;
268800246528SJosef Bacik 			btrfs_put_root(node->root);
268900246528SJosef Bacik 			node->root = btrfs_grab_root(root);
26900b530bc5SJosef Bacik 			ASSERT(node->root);
26913fd0a558SYan, Zheng 			list_add_tail(&node->list, &rc->backref_cache.changed);
26923fd0a558SYan, Zheng 		} else {
26935d4f98a2SYan Zheng 			path->lowest_level = node->level;
26945d4f98a2SYan Zheng 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
2695b3b4aa74SDavid Sterba 			btrfs_release_path(path);
26963fd0a558SYan, Zheng 			if (ret > 0)
26975d4f98a2SYan Zheng 				ret = 0;
26983fd0a558SYan, Zheng 		}
26993fd0a558SYan, Zheng 		if (!ret)
27003fd0a558SYan, Zheng 			update_processed_blocks(rc, node);
27013fd0a558SYan, Zheng 	} else {
27023fd0a558SYan, Zheng 		ret = do_relocation(trans, rc, node, key, path, 1);
27033fd0a558SYan, Zheng 	}
27045d4f98a2SYan Zheng out:
27050647bf56SWang Shilong 	if (ret || node->level == 0 || node->cowonly)
2706023acb07SQu Wenruo 		btrfs_backref_cleanup_node(&rc->backref_cache, node);
27075d4f98a2SYan Zheng 	return ret;
27085d4f98a2SYan Zheng }
27095d4f98a2SYan Zheng 
27105d4f98a2SYan Zheng /*
27115d4f98a2SYan Zheng  * relocate a list of blocks
27125d4f98a2SYan Zheng  */
27135d4f98a2SYan Zheng static noinline_for_stack
27145d4f98a2SYan Zheng int relocate_tree_blocks(struct btrfs_trans_handle *trans,
27155d4f98a2SYan Zheng 			 struct reloc_control *rc, struct rb_root *blocks)
27165d4f98a2SYan Zheng {
27172ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2718a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
27195d4f98a2SYan Zheng 	struct btrfs_path *path;
27205d4f98a2SYan Zheng 	struct tree_block *block;
272198ff7b94SQu Wenruo 	struct tree_block *next;
27225d4f98a2SYan Zheng 	int ret;
27235d4f98a2SYan Zheng 	int err = 0;
27245d4f98a2SYan Zheng 
27255d4f98a2SYan Zheng 	path = btrfs_alloc_path();
2726e1a12670SLiu Bo 	if (!path) {
2727e1a12670SLiu Bo 		err = -ENOMEM;
272834c2b290SDavid Sterba 		goto out_free_blocks;
2729e1a12670SLiu Bo 	}
27305d4f98a2SYan Zheng 
273198ff7b94SQu Wenruo 	/* Kick in readahead for tree blocks with missing keys */
273298ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
27335d4f98a2SYan Zheng 		if (!block->key_ready)
2734f7ba2d37SJosef Bacik 			btrfs_readahead_tree_block(fs_info, block->bytenr,
2735f7ba2d37SJosef Bacik 						   block->owner, 0,
27363fbaf258SJosef Bacik 						   block->level);
27375d4f98a2SYan Zheng 	}
27385d4f98a2SYan Zheng 
273998ff7b94SQu Wenruo 	/* Get first keys */
274098ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
274134c2b290SDavid Sterba 		if (!block->key_ready) {
27422ff7e61eSJeff Mahoney 			err = get_tree_block_key(fs_info, block);
274334c2b290SDavid Sterba 			if (err)
274434c2b290SDavid Sterba 				goto out_free_path;
274534c2b290SDavid Sterba 		}
27465d4f98a2SYan Zheng 	}
27475d4f98a2SYan Zheng 
274898ff7b94SQu Wenruo 	/* Do tree relocation */
274998ff7b94SQu Wenruo 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
27503fd0a558SYan, Zheng 		node = build_backref_tree(rc, &block->key,
27515d4f98a2SYan Zheng 					  block->level, block->bytenr);
27525d4f98a2SYan Zheng 		if (IS_ERR(node)) {
27535d4f98a2SYan Zheng 			err = PTR_ERR(node);
27545d4f98a2SYan Zheng 			goto out;
27555d4f98a2SYan Zheng 		}
27565d4f98a2SYan Zheng 
27575d4f98a2SYan Zheng 		ret = relocate_tree_block(trans, rc, node, &block->key,
27585d4f98a2SYan Zheng 					  path);
27595d4f98a2SYan Zheng 		if (ret < 0) {
27605d4f98a2SYan Zheng 			err = ret;
276150dbbb71SJosef Bacik 			break;
27625d4f98a2SYan Zheng 		}
27635d4f98a2SYan Zheng 	}
27645d4f98a2SYan Zheng out:
27653fd0a558SYan, Zheng 	err = finish_pending_nodes(trans, rc, path, err);
27665d4f98a2SYan Zheng 
276734c2b290SDavid Sterba out_free_path:
27685d4f98a2SYan Zheng 	btrfs_free_path(path);
276934c2b290SDavid Sterba out_free_blocks:
2770e1a12670SLiu Bo 	free_block_list(blocks);
27715d4f98a2SYan Zheng 	return err;
27725d4f98a2SYan Zheng }
27735d4f98a2SYan Zheng 
2774056d9becSNikolay Borisov static noinline_for_stack int prealloc_file_extent_cluster(
2775056d9becSNikolay Borisov 				struct btrfs_inode *inode,
2776efa56464SYan, Zheng 				struct file_extent_cluster *cluster)
2777efa56464SYan, Zheng {
2778efa56464SYan, Zheng 	u64 alloc_hint = 0;
2779efa56464SYan, Zheng 	u64 start;
2780efa56464SYan, Zheng 	u64 end;
2781056d9becSNikolay Borisov 	u64 offset = inode->index_cnt;
2782efa56464SYan, Zheng 	u64 num_bytes;
27834e9d0d01SNikolay Borisov 	int nr;
2784efa56464SYan, Zheng 	int ret = 0;
2785dcb40c19SWang Xiaoguang 	u64 prealloc_start = cluster->start - offset;
2786dcb40c19SWang Xiaoguang 	u64 prealloc_end = cluster->end - offset;
2787214e61d0SNikolay Borisov 	u64 cur_offset = prealloc_start;
2788efa56464SYan, Zheng 
2789efa56464SYan, Zheng 	BUG_ON(cluster->start != cluster->boundary[0]);
2790056d9becSNikolay Borisov 	ret = btrfs_alloc_data_chunk_ondemand(inode,
2791dcb40c19SWang Xiaoguang 					      prealloc_end + 1 - prealloc_start);
2792efa56464SYan, Zheng 	if (ret)
2793214e61d0SNikolay Borisov 		return ret;
2794efa56464SYan, Zheng 
279532430c61SNaohiro Aota 	/*
279632430c61SNaohiro Aota 	 * On a zoned filesystem, we cannot preallocate the file region.
279732430c61SNaohiro Aota 	 * Instead, we dirty and fiemap_write the region.
279832430c61SNaohiro Aota 	 */
279932430c61SNaohiro Aota 	if (btrfs_is_zoned(inode->root->fs_info)) {
280032430c61SNaohiro Aota 		struct btrfs_root *root = inode->root;
280132430c61SNaohiro Aota 		struct btrfs_trans_handle *trans;
280232430c61SNaohiro Aota 
280332430c61SNaohiro Aota 		end = cluster->end - offset + 1;
280432430c61SNaohiro Aota 		trans = btrfs_start_transaction(root, 1);
280532430c61SNaohiro Aota 		if (IS_ERR(trans))
280632430c61SNaohiro Aota 			return PTR_ERR(trans);
280732430c61SNaohiro Aota 
280832430c61SNaohiro Aota 		inode->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
280932430c61SNaohiro Aota 		i_size_write(&inode->vfs_inode, end);
281032430c61SNaohiro Aota 		ret = btrfs_update_inode(trans, root, inode);
281132430c61SNaohiro Aota 		if (ret) {
281232430c61SNaohiro Aota 			btrfs_abort_transaction(trans, ret);
281332430c61SNaohiro Aota 			btrfs_end_transaction(trans);
281432430c61SNaohiro Aota 			return ret;
281532430c61SNaohiro Aota 		}
281632430c61SNaohiro Aota 
281732430c61SNaohiro Aota 		return btrfs_end_transaction(trans);
281832430c61SNaohiro Aota 	}
281932430c61SNaohiro Aota 
282064708539SJosef Bacik 	btrfs_inode_lock(&inode->vfs_inode, 0);
28214e9d0d01SNikolay Borisov 	for (nr = 0; nr < cluster->nr; nr++) {
2822efa56464SYan, Zheng 		start = cluster->boundary[nr] - offset;
2823efa56464SYan, Zheng 		if (nr + 1 < cluster->nr)
2824efa56464SYan, Zheng 			end = cluster->boundary[nr + 1] - 1 - offset;
2825efa56464SYan, Zheng 		else
2826efa56464SYan, Zheng 			end = cluster->end - offset;
2827efa56464SYan, Zheng 
2828056d9becSNikolay Borisov 		lock_extent(&inode->io_tree, start, end);
2829efa56464SYan, Zheng 		num_bytes = end + 1 - start;
2830056d9becSNikolay Borisov 		ret = btrfs_prealloc_file_range(&inode->vfs_inode, 0, start,
2831efa56464SYan, Zheng 						num_bytes, num_bytes,
2832efa56464SYan, Zheng 						end + 1, &alloc_hint);
283318513091SWang Xiaoguang 		cur_offset = end + 1;
2834056d9becSNikolay Borisov 		unlock_extent(&inode->io_tree, start, end);
2835efa56464SYan, Zheng 		if (ret)
2836efa56464SYan, Zheng 			break;
2837efa56464SYan, Zheng 	}
283864708539SJosef Bacik 	btrfs_inode_unlock(&inode->vfs_inode, 0);
2839214e61d0SNikolay Borisov 
284018513091SWang Xiaoguang 	if (cur_offset < prealloc_end)
2841056d9becSNikolay Borisov 		btrfs_free_reserved_data_space_noquota(inode->root->fs_info,
2842a89ef455SFilipe Manana 					       prealloc_end + 1 - cur_offset);
2843efa56464SYan, Zheng 	return ret;
2844efa56464SYan, Zheng }
2845efa56464SYan, Zheng 
2846efa56464SYan, Zheng static noinline_for_stack
28470257bb82SYan, Zheng int setup_extent_mapping(struct inode *inode, u64 start, u64 end,
28480257bb82SYan, Zheng 			 u64 block_start)
28495d4f98a2SYan Zheng {
28505d4f98a2SYan Zheng 	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
28515d4f98a2SYan Zheng 	struct extent_map *em;
28520257bb82SYan, Zheng 	int ret = 0;
28535d4f98a2SYan Zheng 
2854172ddd60SDavid Sterba 	em = alloc_extent_map();
28550257bb82SYan, Zheng 	if (!em)
28560257bb82SYan, Zheng 		return -ENOMEM;
28570257bb82SYan, Zheng 
28585d4f98a2SYan Zheng 	em->start = start;
28590257bb82SYan, Zheng 	em->len = end + 1 - start;
28600257bb82SYan, Zheng 	em->block_len = em->len;
28610257bb82SYan, Zheng 	em->block_start = block_start;
28625d4f98a2SYan Zheng 	set_bit(EXTENT_FLAG_PINNED, &em->flags);
28635d4f98a2SYan Zheng 
2864d0082371SJeff Mahoney 	lock_extent(&BTRFS_I(inode)->io_tree, start, end);
28655d4f98a2SYan Zheng 	while (1) {
2866890871beSChris Mason 		write_lock(&em_tree->lock);
286709a2a8f9SJosef Bacik 		ret = add_extent_mapping(em_tree, em, 0);
2868890871beSChris Mason 		write_unlock(&em_tree->lock);
28695d4f98a2SYan Zheng 		if (ret != -EEXIST) {
28705d4f98a2SYan Zheng 			free_extent_map(em);
28715d4f98a2SYan Zheng 			break;
28725d4f98a2SYan Zheng 		}
2873dcdbc059SNikolay Borisov 		btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
28745d4f98a2SYan Zheng 	}
2875d0082371SJeff Mahoney 	unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
28760257bb82SYan, Zheng 	return ret;
28770257bb82SYan, Zheng }
28785d4f98a2SYan Zheng 
2879726a3421SQu Wenruo /*
2880907d2710SDavid Sterba  * Allow error injection to test balance/relocation cancellation
2881726a3421SQu Wenruo  */
28821fec12a5SJosef Bacik noinline int btrfs_should_cancel_balance(struct btrfs_fs_info *fs_info)
2883726a3421SQu Wenruo {
28845cb502f4SQu Wenruo 	return atomic_read(&fs_info->balance_cancel_req) ||
2885907d2710SDavid Sterba 		atomic_read(&fs_info->reloc_cancel_req) ||
28865cb502f4SQu Wenruo 		fatal_signal_pending(current);
2887726a3421SQu Wenruo }
2888726a3421SQu Wenruo ALLOW_ERROR_INJECTION(btrfs_should_cancel_balance, TRUE);
2889726a3421SQu Wenruo 
2890*c2832898SQu Wenruo static u64 get_cluster_boundary_end(struct file_extent_cluster *cluster,
2891*c2832898SQu Wenruo 				    int cluster_nr)
2892*c2832898SQu Wenruo {
2893*c2832898SQu Wenruo 	/* Last extent, use cluster end directly */
2894*c2832898SQu Wenruo 	if (cluster_nr >= cluster->nr - 1)
2895*c2832898SQu Wenruo 		return cluster->end;
2896*c2832898SQu Wenruo 
2897*c2832898SQu Wenruo 	/* Use next boundary start*/
2898*c2832898SQu Wenruo 	return cluster->boundary[cluster_nr + 1] - 1;
2899*c2832898SQu Wenruo }
2900*c2832898SQu Wenruo 
2901f47960f4SQu Wenruo static int relocate_one_page(struct inode *inode, struct file_ra_state *ra,
2902f47960f4SQu Wenruo 			     struct file_extent_cluster *cluster,
2903f47960f4SQu Wenruo 			     int *cluster_nr, unsigned long page_index)
2904f47960f4SQu Wenruo {
2905f47960f4SQu Wenruo 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2906f47960f4SQu Wenruo 	u64 offset = BTRFS_I(inode)->index_cnt;
2907f47960f4SQu Wenruo 	const unsigned long last_index = (cluster->end - offset) >> PAGE_SHIFT;
2908f47960f4SQu Wenruo 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
2909f47960f4SQu Wenruo 	struct page *page;
2910f47960f4SQu Wenruo 	u64 page_start;
2911f47960f4SQu Wenruo 	u64 page_end;
2912*c2832898SQu Wenruo 	u64 cur;
2913f47960f4SQu Wenruo 	int ret;
2914f47960f4SQu Wenruo 
2915f47960f4SQu Wenruo 	ASSERT(page_index <= last_index);
2916f47960f4SQu Wenruo 	page = find_lock_page(inode->i_mapping, page_index);
2917f47960f4SQu Wenruo 	if (!page) {
2918f47960f4SQu Wenruo 		page_cache_sync_readahead(inode->i_mapping, ra, NULL,
2919f47960f4SQu Wenruo 				page_index, last_index + 1 - page_index);
2920f47960f4SQu Wenruo 		page = find_or_create_page(inode->i_mapping, page_index, mask);
2921*c2832898SQu Wenruo 		if (!page)
2922*c2832898SQu Wenruo 			return -ENOMEM;
2923f47960f4SQu Wenruo 	}
2924f47960f4SQu Wenruo 	ret = set_page_extent_mapped(page);
2925f47960f4SQu Wenruo 	if (ret < 0)
2926f47960f4SQu Wenruo 		goto release_page;
2927f47960f4SQu Wenruo 
2928f47960f4SQu Wenruo 	if (PageReadahead(page))
2929f47960f4SQu Wenruo 		page_cache_async_readahead(inode->i_mapping, ra, NULL, page,
2930f47960f4SQu Wenruo 				   page_index, last_index + 1 - page_index);
2931f47960f4SQu Wenruo 
2932f47960f4SQu Wenruo 	if (!PageUptodate(page)) {
2933f47960f4SQu Wenruo 		btrfs_readpage(NULL, page);
2934f47960f4SQu Wenruo 		lock_page(page);
2935f47960f4SQu Wenruo 		if (!PageUptodate(page)) {
2936f47960f4SQu Wenruo 			ret = -EIO;
2937f47960f4SQu Wenruo 			goto release_page;
2938f47960f4SQu Wenruo 		}
2939f47960f4SQu Wenruo 	}
2940f47960f4SQu Wenruo 
2941f47960f4SQu Wenruo 	page_start = page_offset(page);
2942f47960f4SQu Wenruo 	page_end = page_start + PAGE_SIZE - 1;
2943f47960f4SQu Wenruo 
2944*c2832898SQu Wenruo 	/*
2945*c2832898SQu Wenruo 	 * Start from the cluster, as for subpage case, the cluster can start
2946*c2832898SQu Wenruo 	 * inside the page.
2947*c2832898SQu Wenruo 	 */
2948*c2832898SQu Wenruo 	cur = max(page_start, cluster->boundary[*cluster_nr] - offset);
2949*c2832898SQu Wenruo 	while (cur <= page_end) {
2950*c2832898SQu Wenruo 		u64 extent_start = cluster->boundary[*cluster_nr] - offset;
2951*c2832898SQu Wenruo 		u64 extent_end = get_cluster_boundary_end(cluster,
2952*c2832898SQu Wenruo 						*cluster_nr) - offset;
2953*c2832898SQu Wenruo 		u64 clamped_start = max(page_start, extent_start);
2954*c2832898SQu Wenruo 		u64 clamped_end = min(page_end, extent_end);
2955*c2832898SQu Wenruo 		u32 clamped_len = clamped_end + 1 - clamped_start;
2956f47960f4SQu Wenruo 
2957*c2832898SQu Wenruo 		/* Reserve metadata for this range */
2958*c2832898SQu Wenruo 		ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
2959*c2832898SQu Wenruo 						      clamped_len);
2960*c2832898SQu Wenruo 		if (ret)
2961f47960f4SQu Wenruo 			goto release_page;
2962f47960f4SQu Wenruo 
2963*c2832898SQu Wenruo 		/* Mark the range delalloc and dirty for later writeback */
2964*c2832898SQu Wenruo 		lock_extent(&BTRFS_I(inode)->io_tree, clamped_start, clamped_end);
2965*c2832898SQu Wenruo 		ret = btrfs_set_extent_delalloc(BTRFS_I(inode), clamped_start,
2966*c2832898SQu Wenruo 						clamped_end, 0, NULL);
2967*c2832898SQu Wenruo 		if (ret) {
2968*c2832898SQu Wenruo 			clear_extent_bits(&BTRFS_I(inode)->io_tree,
2969*c2832898SQu Wenruo 					clamped_start, clamped_end,
2970*c2832898SQu Wenruo 					EXTENT_LOCKED | EXTENT_BOUNDARY);
2971*c2832898SQu Wenruo 			btrfs_delalloc_release_metadata(BTRFS_I(inode),
2972*c2832898SQu Wenruo 							clamped_len, true);
2973*c2832898SQu Wenruo 			btrfs_delalloc_release_extents(BTRFS_I(inode),
2974*c2832898SQu Wenruo 						       clamped_len);
2975*c2832898SQu Wenruo 			goto release_page;
2976f47960f4SQu Wenruo 		}
2977*c2832898SQu Wenruo 		btrfs_page_set_dirty(fs_info, page, clamped_start, clamped_len);
2978f47960f4SQu Wenruo 
2979*c2832898SQu Wenruo 		/*
2980*c2832898SQu Wenruo 		 * Set the boundary if it's inside the page.
2981*c2832898SQu Wenruo 		 * Data relocation requires the destination extents to have the
2982*c2832898SQu Wenruo 		 * same size as the source.
2983*c2832898SQu Wenruo 		 * EXTENT_BOUNDARY bit prevents current extent from being merged
2984*c2832898SQu Wenruo 		 * with previous extent.
2985*c2832898SQu Wenruo 		 */
2986*c2832898SQu Wenruo 		if (in_range(cluster->boundary[*cluster_nr] - offset,
2987*c2832898SQu Wenruo 			     page_start, PAGE_SIZE)) {
2988*c2832898SQu Wenruo 			u64 boundary_start = cluster->boundary[*cluster_nr] -
2989*c2832898SQu Wenruo 						offset;
2990*c2832898SQu Wenruo 			u64 boundary_end = boundary_start +
2991*c2832898SQu Wenruo 					   fs_info->sectorsize - 1;
2992*c2832898SQu Wenruo 
2993*c2832898SQu Wenruo 			set_extent_bits(&BTRFS_I(inode)->io_tree,
2994*c2832898SQu Wenruo 					boundary_start, boundary_end,
2995*c2832898SQu Wenruo 					EXTENT_BOUNDARY);
2996*c2832898SQu Wenruo 		}
2997*c2832898SQu Wenruo 		unlock_extent(&BTRFS_I(inode)->io_tree, clamped_start, clamped_end);
2998*c2832898SQu Wenruo 		btrfs_delalloc_release_extents(BTRFS_I(inode), clamped_len);
2999*c2832898SQu Wenruo 		cur += clamped_len;
3000*c2832898SQu Wenruo 
3001*c2832898SQu Wenruo 		/* Crossed extent end, go to next extent */
3002*c2832898SQu Wenruo 		if (cur >= extent_end) {
3003*c2832898SQu Wenruo 			(*cluster_nr)++;
3004*c2832898SQu Wenruo 			/* Just finished the last extent of the cluster, exit. */
3005*c2832898SQu Wenruo 			if (*cluster_nr >= cluster->nr)
3006*c2832898SQu Wenruo 				break;
3007*c2832898SQu Wenruo 		}
3008*c2832898SQu Wenruo 	}
3009f47960f4SQu Wenruo 	unlock_page(page);
3010f47960f4SQu Wenruo 	put_page(page);
3011f47960f4SQu Wenruo 
3012f47960f4SQu Wenruo 	balance_dirty_pages_ratelimited(inode->i_mapping);
3013f47960f4SQu Wenruo 	btrfs_throttle(fs_info);
3014f47960f4SQu Wenruo 	if (btrfs_should_cancel_balance(fs_info))
3015f47960f4SQu Wenruo 		ret = -ECANCELED;
3016f47960f4SQu Wenruo 	return ret;
3017f47960f4SQu Wenruo 
3018f47960f4SQu Wenruo release_page:
3019f47960f4SQu Wenruo 	unlock_page(page);
3020f47960f4SQu Wenruo 	put_page(page);
3021f47960f4SQu Wenruo 	return ret;
3022f47960f4SQu Wenruo }
3023f47960f4SQu Wenruo 
30240257bb82SYan, Zheng static int relocate_file_extent_cluster(struct inode *inode,
30250257bb82SYan, Zheng 					struct file_extent_cluster *cluster)
30260257bb82SYan, Zheng {
30272ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
30280257bb82SYan, Zheng 	u64 offset = BTRFS_I(inode)->index_cnt;
30290257bb82SYan, Zheng 	unsigned long index;
30300257bb82SYan, Zheng 	unsigned long last_index;
30310257bb82SYan, Zheng 	struct file_ra_state *ra;
3032f47960f4SQu Wenruo 	int cluster_nr = 0;
30330257bb82SYan, Zheng 	int ret = 0;
30340257bb82SYan, Zheng 
30350257bb82SYan, Zheng 	if (!cluster->nr)
30360257bb82SYan, Zheng 		return 0;
30370257bb82SYan, Zheng 
30380257bb82SYan, Zheng 	ra = kzalloc(sizeof(*ra), GFP_NOFS);
30390257bb82SYan, Zheng 	if (!ra)
30400257bb82SYan, Zheng 		return -ENOMEM;
30410257bb82SYan, Zheng 
3042056d9becSNikolay Borisov 	ret = prealloc_file_extent_cluster(BTRFS_I(inode), cluster);
30430257bb82SYan, Zheng 	if (ret)
3044efa56464SYan, Zheng 		goto out;
30450257bb82SYan, Zheng 
30460257bb82SYan, Zheng 	file_ra_state_init(ra, inode->i_mapping);
30470257bb82SYan, Zheng 
3048efa56464SYan, Zheng 	ret = setup_extent_mapping(inode, cluster->start - offset,
3049efa56464SYan, Zheng 				   cluster->end - offset, cluster->start);
3050efa56464SYan, Zheng 	if (ret)
3051efa56464SYan, Zheng 		goto out;
3052efa56464SYan, Zheng 
305309cbfeafSKirill A. Shutemov 	last_index = (cluster->end - offset) >> PAGE_SHIFT;
3054f47960f4SQu Wenruo 	for (index = (cluster->start - offset) >> PAGE_SHIFT;
3055f47960f4SQu Wenruo 	     index <= last_index && !ret; index++)
3056f47960f4SQu Wenruo 		ret = relocate_one_page(inode, ra, cluster, &cluster_nr, index);
305732430c61SNaohiro Aota 	if (btrfs_is_zoned(fs_info) && !ret)
305832430c61SNaohiro Aota 		ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
3059f47960f4SQu Wenruo 	if (ret == 0)
3060f47960f4SQu Wenruo 		WARN_ON(cluster_nr != cluster->nr);
3061efa56464SYan, Zheng out:
30620257bb82SYan, Zheng 	kfree(ra);
30630257bb82SYan, Zheng 	return ret;
30640257bb82SYan, Zheng }
30650257bb82SYan, Zheng 
30660257bb82SYan, Zheng static noinline_for_stack
30670257bb82SYan, Zheng int relocate_data_extent(struct inode *inode, struct btrfs_key *extent_key,
30680257bb82SYan, Zheng 			 struct file_extent_cluster *cluster)
30690257bb82SYan, Zheng {
30700257bb82SYan, Zheng 	int ret;
30710257bb82SYan, Zheng 
30720257bb82SYan, Zheng 	if (cluster->nr > 0 && extent_key->objectid != cluster->end + 1) {
30730257bb82SYan, Zheng 		ret = relocate_file_extent_cluster(inode, cluster);
30740257bb82SYan, Zheng 		if (ret)
30750257bb82SYan, Zheng 			return ret;
30760257bb82SYan, Zheng 		cluster->nr = 0;
30770257bb82SYan, Zheng 	}
30780257bb82SYan, Zheng 
30790257bb82SYan, Zheng 	if (!cluster->nr)
30800257bb82SYan, Zheng 		cluster->start = extent_key->objectid;
30810257bb82SYan, Zheng 	else
30820257bb82SYan, Zheng 		BUG_ON(cluster->nr >= MAX_EXTENTS);
30830257bb82SYan, Zheng 	cluster->end = extent_key->objectid + extent_key->offset - 1;
30840257bb82SYan, Zheng 	cluster->boundary[cluster->nr] = extent_key->objectid;
30850257bb82SYan, Zheng 	cluster->nr++;
30860257bb82SYan, Zheng 
30870257bb82SYan, Zheng 	if (cluster->nr >= MAX_EXTENTS) {
30880257bb82SYan, Zheng 		ret = relocate_file_extent_cluster(inode, cluster);
30890257bb82SYan, Zheng 		if (ret)
30900257bb82SYan, Zheng 			return ret;
30910257bb82SYan, Zheng 		cluster->nr = 0;
30920257bb82SYan, Zheng 	}
30930257bb82SYan, Zheng 	return 0;
30945d4f98a2SYan Zheng }
30955d4f98a2SYan Zheng 
30965d4f98a2SYan Zheng /*
30975d4f98a2SYan Zheng  * helper to add a tree block to the list.
30985d4f98a2SYan Zheng  * the major work is getting the generation and level of the block
30995d4f98a2SYan Zheng  */
31005d4f98a2SYan Zheng static int add_tree_block(struct reloc_control *rc,
31015d4f98a2SYan Zheng 			  struct btrfs_key *extent_key,
31025d4f98a2SYan Zheng 			  struct btrfs_path *path,
31035d4f98a2SYan Zheng 			  struct rb_root *blocks)
31045d4f98a2SYan Zheng {
31055d4f98a2SYan Zheng 	struct extent_buffer *eb;
31065d4f98a2SYan Zheng 	struct btrfs_extent_item *ei;
31075d4f98a2SYan Zheng 	struct btrfs_tree_block_info *bi;
31085d4f98a2SYan Zheng 	struct tree_block *block;
31095d4f98a2SYan Zheng 	struct rb_node *rb_node;
31105d4f98a2SYan Zheng 	u32 item_size;
31115d4f98a2SYan Zheng 	int level = -1;
31127fdf4b60SWang Shilong 	u64 generation;
3113f7ba2d37SJosef Bacik 	u64 owner = 0;
31145d4f98a2SYan Zheng 
31155d4f98a2SYan Zheng 	eb =  path->nodes[0];
31165d4f98a2SYan Zheng 	item_size = btrfs_item_size_nr(eb, path->slots[0]);
31175d4f98a2SYan Zheng 
31183173a18fSJosef Bacik 	if (extent_key->type == BTRFS_METADATA_ITEM_KEY ||
31193173a18fSJosef Bacik 	    item_size >= sizeof(*ei) + sizeof(*bi)) {
3120f7ba2d37SJosef Bacik 		unsigned long ptr = 0, end;
3121f7ba2d37SJosef Bacik 
31225d4f98a2SYan Zheng 		ei = btrfs_item_ptr(eb, path->slots[0],
31235d4f98a2SYan Zheng 				struct btrfs_extent_item);
3124f7ba2d37SJosef Bacik 		end = (unsigned long)ei + item_size;
31253173a18fSJosef Bacik 		if (extent_key->type == BTRFS_EXTENT_ITEM_KEY) {
31265d4f98a2SYan Zheng 			bi = (struct btrfs_tree_block_info *)(ei + 1);
31275d4f98a2SYan Zheng 			level = btrfs_tree_block_level(eb, bi);
3128f7ba2d37SJosef Bacik 			ptr = (unsigned long)(bi + 1);
31295d4f98a2SYan Zheng 		} else {
31303173a18fSJosef Bacik 			level = (int)extent_key->offset;
3131f7ba2d37SJosef Bacik 			ptr = (unsigned long)(ei + 1);
31323173a18fSJosef Bacik 		}
31333173a18fSJosef Bacik 		generation = btrfs_extent_generation(eb, ei);
3134f7ba2d37SJosef Bacik 
3135f7ba2d37SJosef Bacik 		/*
3136f7ba2d37SJosef Bacik 		 * We're reading random blocks without knowing their owner ahead
3137f7ba2d37SJosef Bacik 		 * of time.  This is ok most of the time, as all reloc roots and
3138f7ba2d37SJosef Bacik 		 * fs roots have the same lock type.  However normal trees do
3139f7ba2d37SJosef Bacik 		 * not, and the only way to know ahead of time is to read the
3140f7ba2d37SJosef Bacik 		 * inline ref offset.  We know it's an fs root if
3141f7ba2d37SJosef Bacik 		 *
3142f7ba2d37SJosef Bacik 		 * 1. There's more than one ref.
3143f7ba2d37SJosef Bacik 		 * 2. There's a SHARED_DATA_REF_KEY set.
3144f7ba2d37SJosef Bacik 		 * 3. FULL_BACKREF is set on the flags.
3145f7ba2d37SJosef Bacik 		 *
3146f7ba2d37SJosef Bacik 		 * Otherwise it's safe to assume that the ref offset == the
3147f7ba2d37SJosef Bacik 		 * owner of this block, so we can use that when calling
3148f7ba2d37SJosef Bacik 		 * read_tree_block.
3149f7ba2d37SJosef Bacik 		 */
3150f7ba2d37SJosef Bacik 		if (btrfs_extent_refs(eb, ei) == 1 &&
3151f7ba2d37SJosef Bacik 		    !(btrfs_extent_flags(eb, ei) &
3152f7ba2d37SJosef Bacik 		      BTRFS_BLOCK_FLAG_FULL_BACKREF) &&
3153f7ba2d37SJosef Bacik 		    ptr < end) {
3154f7ba2d37SJosef Bacik 			struct btrfs_extent_inline_ref *iref;
3155f7ba2d37SJosef Bacik 			int type;
3156f7ba2d37SJosef Bacik 
3157f7ba2d37SJosef Bacik 			iref = (struct btrfs_extent_inline_ref *)ptr;
3158f7ba2d37SJosef Bacik 			type = btrfs_get_extent_inline_ref_type(eb, iref,
3159f7ba2d37SJosef Bacik 							BTRFS_REF_TYPE_BLOCK);
3160f7ba2d37SJosef Bacik 			if (type == BTRFS_REF_TYPE_INVALID)
3161f7ba2d37SJosef Bacik 				return -EINVAL;
3162f7ba2d37SJosef Bacik 			if (type == BTRFS_TREE_BLOCK_REF_KEY)
3163f7ba2d37SJosef Bacik 				owner = btrfs_extent_inline_ref_offset(eb, iref);
3164f7ba2d37SJosef Bacik 		}
31656d8ff4e4SDavid Sterba 	} else if (unlikely(item_size == sizeof(struct btrfs_extent_item_v0))) {
3166ba3c2b19SNikolay Borisov 		btrfs_print_v0_err(eb->fs_info);
3167ba3c2b19SNikolay Borisov 		btrfs_handle_fs_error(eb->fs_info, -EINVAL, NULL);
3168ba3c2b19SNikolay Borisov 		return -EINVAL;
31693173a18fSJosef Bacik 	} else {
31705d4f98a2SYan Zheng 		BUG();
31715d4f98a2SYan Zheng 	}
31725d4f98a2SYan Zheng 
3173b3b4aa74SDavid Sterba 	btrfs_release_path(path);
31745d4f98a2SYan Zheng 
31755d4f98a2SYan Zheng 	BUG_ON(level == -1);
31765d4f98a2SYan Zheng 
31775d4f98a2SYan Zheng 	block = kmalloc(sizeof(*block), GFP_NOFS);
31785d4f98a2SYan Zheng 	if (!block)
31795d4f98a2SYan Zheng 		return -ENOMEM;
31805d4f98a2SYan Zheng 
31815d4f98a2SYan Zheng 	block->bytenr = extent_key->objectid;
3182da17066cSJeff Mahoney 	block->key.objectid = rc->extent_root->fs_info->nodesize;
31835d4f98a2SYan Zheng 	block->key.offset = generation;
31845d4f98a2SYan Zheng 	block->level = level;
31855d4f98a2SYan Zheng 	block->key_ready = 0;
3186f7ba2d37SJosef Bacik 	block->owner = owner;
31875d4f98a2SYan Zheng 
3188e9a28dc5SQu Wenruo 	rb_node = rb_simple_insert(blocks, block->bytenr, &block->rb_node);
318943c04fb1SJeff Mahoney 	if (rb_node)
3190982c92cbSQu Wenruo 		btrfs_backref_panic(rc->extent_root->fs_info, block->bytenr,
3191982c92cbSQu Wenruo 				    -EEXIST);
31925d4f98a2SYan Zheng 
31935d4f98a2SYan Zheng 	return 0;
31945d4f98a2SYan Zheng }
31955d4f98a2SYan Zheng 
31965d4f98a2SYan Zheng /*
31975d4f98a2SYan Zheng  * helper to add tree blocks for backref of type BTRFS_SHARED_DATA_REF_KEY
31985d4f98a2SYan Zheng  */
31995d4f98a2SYan Zheng static int __add_tree_block(struct reloc_control *rc,
32005d4f98a2SYan Zheng 			    u64 bytenr, u32 blocksize,
32015d4f98a2SYan Zheng 			    struct rb_root *blocks)
32025d4f98a2SYan Zheng {
32030b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
32045d4f98a2SYan Zheng 	struct btrfs_path *path;
32055d4f98a2SYan Zheng 	struct btrfs_key key;
32065d4f98a2SYan Zheng 	int ret;
32070b246afaSJeff Mahoney 	bool skinny = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
32085d4f98a2SYan Zheng 
32097476dfdaSDavid Sterba 	if (tree_block_processed(bytenr, rc))
32105d4f98a2SYan Zheng 		return 0;
32115d4f98a2SYan Zheng 
3212e9a28dc5SQu Wenruo 	if (rb_simple_search(blocks, bytenr))
32135d4f98a2SYan Zheng 		return 0;
32145d4f98a2SYan Zheng 
32155d4f98a2SYan Zheng 	path = btrfs_alloc_path();
32165d4f98a2SYan Zheng 	if (!path)
32175d4f98a2SYan Zheng 		return -ENOMEM;
3218aee68ee5SJosef Bacik again:
32195d4f98a2SYan Zheng 	key.objectid = bytenr;
3220aee68ee5SJosef Bacik 	if (skinny) {
3221aee68ee5SJosef Bacik 		key.type = BTRFS_METADATA_ITEM_KEY;
3222aee68ee5SJosef Bacik 		key.offset = (u64)-1;
3223aee68ee5SJosef Bacik 	} else {
32245d4f98a2SYan Zheng 		key.type = BTRFS_EXTENT_ITEM_KEY;
32255d4f98a2SYan Zheng 		key.offset = blocksize;
3226aee68ee5SJosef Bacik 	}
32275d4f98a2SYan Zheng 
32285d4f98a2SYan Zheng 	path->search_commit_root = 1;
32295d4f98a2SYan Zheng 	path->skip_locking = 1;
32305d4f98a2SYan Zheng 	ret = btrfs_search_slot(NULL, rc->extent_root, &key, path, 0, 0);
32315d4f98a2SYan Zheng 	if (ret < 0)
32325d4f98a2SYan Zheng 		goto out;
32335d4f98a2SYan Zheng 
3234aee68ee5SJosef Bacik 	if (ret > 0 && skinny) {
3235aee68ee5SJosef Bacik 		if (path->slots[0]) {
3236aee68ee5SJosef Bacik 			path->slots[0]--;
3237aee68ee5SJosef Bacik 			btrfs_item_key_to_cpu(path->nodes[0], &key,
3238aee68ee5SJosef Bacik 					      path->slots[0]);
32393173a18fSJosef Bacik 			if (key.objectid == bytenr &&
3240aee68ee5SJosef Bacik 			    (key.type == BTRFS_METADATA_ITEM_KEY ||
3241aee68ee5SJosef Bacik 			     (key.type == BTRFS_EXTENT_ITEM_KEY &&
3242aee68ee5SJosef Bacik 			      key.offset == blocksize)))
32433173a18fSJosef Bacik 				ret = 0;
32443173a18fSJosef Bacik 		}
3245aee68ee5SJosef Bacik 
3246aee68ee5SJosef Bacik 		if (ret) {
3247aee68ee5SJosef Bacik 			skinny = false;
3248aee68ee5SJosef Bacik 			btrfs_release_path(path);
3249aee68ee5SJosef Bacik 			goto again;
3250aee68ee5SJosef Bacik 		}
3251aee68ee5SJosef Bacik 	}
3252cdccee99SLiu Bo 	if (ret) {
3253cdccee99SLiu Bo 		ASSERT(ret == 1);
3254cdccee99SLiu Bo 		btrfs_print_leaf(path->nodes[0]);
3255cdccee99SLiu Bo 		btrfs_err(fs_info,
3256cdccee99SLiu Bo 	     "tree block extent item (%llu) is not found in extent tree",
3257cdccee99SLiu Bo 		     bytenr);
3258cdccee99SLiu Bo 		WARN_ON(1);
3259cdccee99SLiu Bo 		ret = -EINVAL;
3260cdccee99SLiu Bo 		goto out;
3261cdccee99SLiu Bo 	}
32623173a18fSJosef Bacik 
32635d4f98a2SYan Zheng 	ret = add_tree_block(rc, &key, path, blocks);
32645d4f98a2SYan Zheng out:
32655d4f98a2SYan Zheng 	btrfs_free_path(path);
32665d4f98a2SYan Zheng 	return ret;
32675d4f98a2SYan Zheng }
32685d4f98a2SYan Zheng 
32690af3d00bSJosef Bacik static int delete_block_group_cache(struct btrfs_fs_info *fs_info,
327032da5386SDavid Sterba 				    struct btrfs_block_group *block_group,
32711bbc621eSChris Mason 				    struct inode *inode,
32721bbc621eSChris Mason 				    u64 ino)
32730af3d00bSJosef Bacik {
32740af3d00bSJosef Bacik 	struct btrfs_root *root = fs_info->tree_root;
32750af3d00bSJosef Bacik 	struct btrfs_trans_handle *trans;
32760af3d00bSJosef Bacik 	int ret = 0;
32770af3d00bSJosef Bacik 
32780af3d00bSJosef Bacik 	if (inode)
32790af3d00bSJosef Bacik 		goto truncate;
32800af3d00bSJosef Bacik 
32810202e83fSDavid Sterba 	inode = btrfs_iget(fs_info->sb, ino, root);
32822e19f1f9SAl Viro 	if (IS_ERR(inode))
32830af3d00bSJosef Bacik 		return -ENOENT;
32840af3d00bSJosef Bacik 
32850af3d00bSJosef Bacik truncate:
32862ff7e61eSJeff Mahoney 	ret = btrfs_check_trunc_cache_free_space(fs_info,
32877b61cd92SMiao Xie 						 &fs_info->global_block_rsv);
32887b61cd92SMiao Xie 	if (ret)
32897b61cd92SMiao Xie 		goto out;
32907b61cd92SMiao Xie 
32917a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(root);
32920af3d00bSJosef Bacik 	if (IS_ERR(trans)) {
32933612b495STsutomu Itoh 		ret = PTR_ERR(trans);
32940af3d00bSJosef Bacik 		goto out;
32950af3d00bSJosef Bacik 	}
32960af3d00bSJosef Bacik 
329777ab86bfSJeff Mahoney 	ret = btrfs_truncate_free_space_cache(trans, block_group, inode);
32980af3d00bSJosef Bacik 
32993a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
33002ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
33010af3d00bSJosef Bacik out:
33020af3d00bSJosef Bacik 	iput(inode);
33030af3d00bSJosef Bacik 	return ret;
33040af3d00bSJosef Bacik }
33050af3d00bSJosef Bacik 
33065d4f98a2SYan Zheng /*
330719b546d7SQu Wenruo  * Locate the free space cache EXTENT_DATA in root tree leaf and delete the
330819b546d7SQu Wenruo  * cache inode, to avoid free space cache data extent blocking data relocation.
33095d4f98a2SYan Zheng  */
331019b546d7SQu Wenruo static int delete_v1_space_cache(struct extent_buffer *leaf,
331119b546d7SQu Wenruo 				 struct btrfs_block_group *block_group,
331219b546d7SQu Wenruo 				 u64 data_bytenr)
33135d4f98a2SYan Zheng {
331419b546d7SQu Wenruo 	u64 space_cache_ino;
331519b546d7SQu Wenruo 	struct btrfs_file_extent_item *ei;
33165d4f98a2SYan Zheng 	struct btrfs_key key;
331719b546d7SQu Wenruo 	bool found = false;
331819b546d7SQu Wenruo 	int i;
33195d4f98a2SYan Zheng 	int ret;
33205d4f98a2SYan Zheng 
332119b546d7SQu Wenruo 	if (btrfs_header_owner(leaf) != BTRFS_ROOT_TREE_OBJECTID)
332219b546d7SQu Wenruo 		return 0;
33235d4f98a2SYan Zheng 
332419b546d7SQu Wenruo 	for (i = 0; i < btrfs_header_nritems(leaf); i++) {
332550e31ef4SQu Wenruo 		u8 type;
332650e31ef4SQu Wenruo 
332719b546d7SQu Wenruo 		btrfs_item_key_to_cpu(leaf, &key, i);
332819b546d7SQu Wenruo 		if (key.type != BTRFS_EXTENT_DATA_KEY)
332919b546d7SQu Wenruo 			continue;
333019b546d7SQu Wenruo 		ei = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
333150e31ef4SQu Wenruo 		type = btrfs_file_extent_type(leaf, ei);
333250e31ef4SQu Wenruo 
333350e31ef4SQu Wenruo 		if ((type == BTRFS_FILE_EXTENT_REG ||
333450e31ef4SQu Wenruo 		     type == BTRFS_FILE_EXTENT_PREALLOC) &&
333519b546d7SQu Wenruo 		    btrfs_file_extent_disk_bytenr(leaf, ei) == data_bytenr) {
333619b546d7SQu Wenruo 			found = true;
333719b546d7SQu Wenruo 			space_cache_ino = key.objectid;
333819b546d7SQu Wenruo 			break;
333919b546d7SQu Wenruo 		}
334019b546d7SQu Wenruo 	}
334119b546d7SQu Wenruo 	if (!found)
334219b546d7SQu Wenruo 		return -ENOENT;
334319b546d7SQu Wenruo 	ret = delete_block_group_cache(leaf->fs_info, block_group, NULL,
334419b546d7SQu Wenruo 					space_cache_ino);
33450af3d00bSJosef Bacik 	return ret;
33465d4f98a2SYan Zheng }
33475d4f98a2SYan Zheng 
33485d4f98a2SYan Zheng /*
33492c016dc2SLiu Bo  * helper to find all tree blocks that reference a given data extent
33505d4f98a2SYan Zheng  */
33515d4f98a2SYan Zheng static noinline_for_stack
33525d4f98a2SYan Zheng int add_data_references(struct reloc_control *rc,
33535d4f98a2SYan Zheng 			struct btrfs_key *extent_key,
33545d4f98a2SYan Zheng 			struct btrfs_path *path,
33555d4f98a2SYan Zheng 			struct rb_root *blocks)
33565d4f98a2SYan Zheng {
335719b546d7SQu Wenruo 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
335819b546d7SQu Wenruo 	struct ulist *leaves = NULL;
335919b546d7SQu Wenruo 	struct ulist_iterator leaf_uiter;
336019b546d7SQu Wenruo 	struct ulist_node *ref_node = NULL;
336119b546d7SQu Wenruo 	const u32 blocksize = fs_info->nodesize;
3362647f63bdSFilipe David Borba Manana 	int ret = 0;
33635d4f98a2SYan Zheng 
3364b3b4aa74SDavid Sterba 	btrfs_release_path(path);
336519b546d7SQu Wenruo 	ret = btrfs_find_all_leafs(NULL, fs_info, extent_key->objectid,
336619b546d7SQu Wenruo 				   0, &leaves, NULL, true);
336719b546d7SQu Wenruo 	if (ret < 0)
336819b546d7SQu Wenruo 		return ret;
336919b546d7SQu Wenruo 
337019b546d7SQu Wenruo 	ULIST_ITER_INIT(&leaf_uiter);
337119b546d7SQu Wenruo 	while ((ref_node = ulist_next(leaves, &leaf_uiter))) {
337219b546d7SQu Wenruo 		struct extent_buffer *eb;
337319b546d7SQu Wenruo 
33741b7ec85eSJosef Bacik 		eb = read_tree_block(fs_info, ref_node->val, 0, 0, 0, NULL);
337519b546d7SQu Wenruo 		if (IS_ERR(eb)) {
337619b546d7SQu Wenruo 			ret = PTR_ERR(eb);
337719b546d7SQu Wenruo 			break;
337819b546d7SQu Wenruo 		}
337919b546d7SQu Wenruo 		ret = delete_v1_space_cache(eb, rc->block_group,
338019b546d7SQu Wenruo 					    extent_key->objectid);
338119b546d7SQu Wenruo 		free_extent_buffer(eb);
338219b546d7SQu Wenruo 		if (ret < 0)
338319b546d7SQu Wenruo 			break;
338419b546d7SQu Wenruo 		ret = __add_tree_block(rc, ref_node->val, blocksize, blocks);
338519b546d7SQu Wenruo 		if (ret < 0)
338619b546d7SQu Wenruo 			break;
338719b546d7SQu Wenruo 	}
338819b546d7SQu Wenruo 	if (ret < 0)
33895d4f98a2SYan Zheng 		free_block_list(blocks);
339019b546d7SQu Wenruo 	ulist_free(leaves);
339119b546d7SQu Wenruo 	return ret;
33925d4f98a2SYan Zheng }
33935d4f98a2SYan Zheng 
33945d4f98a2SYan Zheng /*
33952c016dc2SLiu Bo  * helper to find next unprocessed extent
33965d4f98a2SYan Zheng  */
33975d4f98a2SYan Zheng static noinline_for_stack
3398147d256eSZhaolei int find_next_extent(struct reloc_control *rc, struct btrfs_path *path,
33993fd0a558SYan, Zheng 		     struct btrfs_key *extent_key)
34005d4f98a2SYan Zheng {
34010b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
34025d4f98a2SYan Zheng 	struct btrfs_key key;
34035d4f98a2SYan Zheng 	struct extent_buffer *leaf;
34045d4f98a2SYan Zheng 	u64 start, end, last;
34055d4f98a2SYan Zheng 	int ret;
34065d4f98a2SYan Zheng 
3407b3470b5dSDavid Sterba 	last = rc->block_group->start + rc->block_group->length;
34085d4f98a2SYan Zheng 	while (1) {
34095d4f98a2SYan Zheng 		cond_resched();
34105d4f98a2SYan Zheng 		if (rc->search_start >= last) {
34115d4f98a2SYan Zheng 			ret = 1;
34125d4f98a2SYan Zheng 			break;
34135d4f98a2SYan Zheng 		}
34145d4f98a2SYan Zheng 
34155d4f98a2SYan Zheng 		key.objectid = rc->search_start;
34165d4f98a2SYan Zheng 		key.type = BTRFS_EXTENT_ITEM_KEY;
34175d4f98a2SYan Zheng 		key.offset = 0;
34185d4f98a2SYan Zheng 
34195d4f98a2SYan Zheng 		path->search_commit_root = 1;
34205d4f98a2SYan Zheng 		path->skip_locking = 1;
34215d4f98a2SYan Zheng 		ret = btrfs_search_slot(NULL, rc->extent_root, &key, path,
34225d4f98a2SYan Zheng 					0, 0);
34235d4f98a2SYan Zheng 		if (ret < 0)
34245d4f98a2SYan Zheng 			break;
34255d4f98a2SYan Zheng next:
34265d4f98a2SYan Zheng 		leaf = path->nodes[0];
34275d4f98a2SYan Zheng 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
34285d4f98a2SYan Zheng 			ret = btrfs_next_leaf(rc->extent_root, path);
34295d4f98a2SYan Zheng 			if (ret != 0)
34305d4f98a2SYan Zheng 				break;
34315d4f98a2SYan Zheng 			leaf = path->nodes[0];
34325d4f98a2SYan Zheng 		}
34335d4f98a2SYan Zheng 
34345d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
34355d4f98a2SYan Zheng 		if (key.objectid >= last) {
34365d4f98a2SYan Zheng 			ret = 1;
34375d4f98a2SYan Zheng 			break;
34385d4f98a2SYan Zheng 		}
34395d4f98a2SYan Zheng 
34403173a18fSJosef Bacik 		if (key.type != BTRFS_EXTENT_ITEM_KEY &&
34413173a18fSJosef Bacik 		    key.type != BTRFS_METADATA_ITEM_KEY) {
34423173a18fSJosef Bacik 			path->slots[0]++;
34433173a18fSJosef Bacik 			goto next;
34443173a18fSJosef Bacik 		}
34453173a18fSJosef Bacik 
34463173a18fSJosef Bacik 		if (key.type == BTRFS_EXTENT_ITEM_KEY &&
34475d4f98a2SYan Zheng 		    key.objectid + key.offset <= rc->search_start) {
34485d4f98a2SYan Zheng 			path->slots[0]++;
34495d4f98a2SYan Zheng 			goto next;
34505d4f98a2SYan Zheng 		}
34515d4f98a2SYan Zheng 
34523173a18fSJosef Bacik 		if (key.type == BTRFS_METADATA_ITEM_KEY &&
34530b246afaSJeff Mahoney 		    key.objectid + fs_info->nodesize <=
34543173a18fSJosef Bacik 		    rc->search_start) {
34553173a18fSJosef Bacik 			path->slots[0]++;
34563173a18fSJosef Bacik 			goto next;
34573173a18fSJosef Bacik 		}
34583173a18fSJosef Bacik 
34595d4f98a2SYan Zheng 		ret = find_first_extent_bit(&rc->processed_blocks,
34605d4f98a2SYan Zheng 					    key.objectid, &start, &end,
3461e6138876SJosef Bacik 					    EXTENT_DIRTY, NULL);
34625d4f98a2SYan Zheng 
34635d4f98a2SYan Zheng 		if (ret == 0 && start <= key.objectid) {
3464b3b4aa74SDavid Sterba 			btrfs_release_path(path);
34655d4f98a2SYan Zheng 			rc->search_start = end + 1;
34665d4f98a2SYan Zheng 		} else {
34673173a18fSJosef Bacik 			if (key.type == BTRFS_EXTENT_ITEM_KEY)
34685d4f98a2SYan Zheng 				rc->search_start = key.objectid + key.offset;
34693173a18fSJosef Bacik 			else
34703173a18fSJosef Bacik 				rc->search_start = key.objectid +
34710b246afaSJeff Mahoney 					fs_info->nodesize;
34723fd0a558SYan, Zheng 			memcpy(extent_key, &key, sizeof(key));
34735d4f98a2SYan Zheng 			return 0;
34745d4f98a2SYan Zheng 		}
34755d4f98a2SYan Zheng 	}
3476b3b4aa74SDavid Sterba 	btrfs_release_path(path);
34775d4f98a2SYan Zheng 	return ret;
34785d4f98a2SYan Zheng }
34795d4f98a2SYan Zheng 
34805d4f98a2SYan Zheng static void set_reloc_control(struct reloc_control *rc)
34815d4f98a2SYan Zheng {
34825d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
34837585717fSChris Mason 
34847585717fSChris Mason 	mutex_lock(&fs_info->reloc_mutex);
34855d4f98a2SYan Zheng 	fs_info->reloc_ctl = rc;
34867585717fSChris Mason 	mutex_unlock(&fs_info->reloc_mutex);
34875d4f98a2SYan Zheng }
34885d4f98a2SYan Zheng 
34895d4f98a2SYan Zheng static void unset_reloc_control(struct reloc_control *rc)
34905d4f98a2SYan Zheng {
34915d4f98a2SYan Zheng 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
34927585717fSChris Mason 
34937585717fSChris Mason 	mutex_lock(&fs_info->reloc_mutex);
34945d4f98a2SYan Zheng 	fs_info->reloc_ctl = NULL;
34957585717fSChris Mason 	mutex_unlock(&fs_info->reloc_mutex);
34965d4f98a2SYan Zheng }
34975d4f98a2SYan Zheng 
34983fd0a558SYan, Zheng static noinline_for_stack
34993fd0a558SYan, Zheng int prepare_to_relocate(struct reloc_control *rc)
35003fd0a558SYan, Zheng {
35013fd0a558SYan, Zheng 	struct btrfs_trans_handle *trans;
3502ac2fabacSJosef Bacik 	int ret;
35033fd0a558SYan, Zheng 
35042ff7e61eSJeff Mahoney 	rc->block_rsv = btrfs_alloc_block_rsv(rc->extent_root->fs_info,
350566d8f3ddSMiao Xie 					      BTRFS_BLOCK_RSV_TEMP);
35063fd0a558SYan, Zheng 	if (!rc->block_rsv)
35073fd0a558SYan, Zheng 		return -ENOMEM;
35083fd0a558SYan, Zheng 
35093fd0a558SYan, Zheng 	memset(&rc->cluster, 0, sizeof(rc->cluster));
3510b3470b5dSDavid Sterba 	rc->search_start = rc->block_group->start;
35113fd0a558SYan, Zheng 	rc->extents_found = 0;
35123fd0a558SYan, Zheng 	rc->nodes_relocated = 0;
35133fd0a558SYan, Zheng 	rc->merging_rsv_size = 0;
35140647bf56SWang Shilong 	rc->reserved_bytes = 0;
3515da17066cSJeff Mahoney 	rc->block_rsv->size = rc->extent_root->fs_info->nodesize *
35160647bf56SWang Shilong 			      RELOCATION_RESERVED_NODES;
3517ac2fabacSJosef Bacik 	ret = btrfs_block_rsv_refill(rc->extent_root,
3518ac2fabacSJosef Bacik 				     rc->block_rsv, rc->block_rsv->size,
3519ac2fabacSJosef Bacik 				     BTRFS_RESERVE_FLUSH_ALL);
3520ac2fabacSJosef Bacik 	if (ret)
3521ac2fabacSJosef Bacik 		return ret;
35223fd0a558SYan, Zheng 
35233fd0a558SYan, Zheng 	rc->create_reloc_tree = 1;
35243fd0a558SYan, Zheng 	set_reloc_control(rc);
35253fd0a558SYan, Zheng 
35267a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
352728818947SLiu Bo 	if (IS_ERR(trans)) {
352828818947SLiu Bo 		unset_reloc_control(rc);
352928818947SLiu Bo 		/*
353028818947SLiu Bo 		 * extent tree is not a ref_cow tree and has no reloc_root to
353128818947SLiu Bo 		 * cleanup.  And callers are responsible to free the above
353228818947SLiu Bo 		 * block rsv.
353328818947SLiu Bo 		 */
353428818947SLiu Bo 		return PTR_ERR(trans);
353528818947SLiu Bo 	}
3536fb686c68SJosef Bacik 	return btrfs_commit_transaction(trans);
35373fd0a558SYan, Zheng }
353876dda93cSYan, Zheng 
35395d4f98a2SYan Zheng static noinline_for_stack int relocate_block_group(struct reloc_control *rc)
35405d4f98a2SYan Zheng {
35412ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
35425d4f98a2SYan Zheng 	struct rb_root blocks = RB_ROOT;
35435d4f98a2SYan Zheng 	struct btrfs_key key;
35445d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans = NULL;
35455d4f98a2SYan Zheng 	struct btrfs_path *path;
35465d4f98a2SYan Zheng 	struct btrfs_extent_item *ei;
35475d4f98a2SYan Zheng 	u64 flags;
35485d4f98a2SYan Zheng 	int ret;
35495d4f98a2SYan Zheng 	int err = 0;
3550c87f08caSChris Mason 	int progress = 0;
35515d4f98a2SYan Zheng 
35525d4f98a2SYan Zheng 	path = btrfs_alloc_path();
35533fd0a558SYan, Zheng 	if (!path)
35545d4f98a2SYan Zheng 		return -ENOMEM;
3555e4058b54SDavid Sterba 	path->reada = READA_FORWARD;
35563fd0a558SYan, Zheng 
35573fd0a558SYan, Zheng 	ret = prepare_to_relocate(rc);
35583fd0a558SYan, Zheng 	if (ret) {
35593fd0a558SYan, Zheng 		err = ret;
35603fd0a558SYan, Zheng 		goto out_free;
35612423fdfbSJiri Slaby 	}
35625d4f98a2SYan Zheng 
35635d4f98a2SYan Zheng 	while (1) {
35640647bf56SWang Shilong 		rc->reserved_bytes = 0;
35650647bf56SWang Shilong 		ret = btrfs_block_rsv_refill(rc->extent_root,
35660647bf56SWang Shilong 					rc->block_rsv, rc->block_rsv->size,
35670647bf56SWang Shilong 					BTRFS_RESERVE_FLUSH_ALL);
35680647bf56SWang Shilong 		if (ret) {
35690647bf56SWang Shilong 			err = ret;
35700647bf56SWang Shilong 			break;
35710647bf56SWang Shilong 		}
3572c87f08caSChris Mason 		progress++;
3573a22285a6SYan, Zheng 		trans = btrfs_start_transaction(rc->extent_root, 0);
35740f788c58SLiu Bo 		if (IS_ERR(trans)) {
35750f788c58SLiu Bo 			err = PTR_ERR(trans);
35760f788c58SLiu Bo 			trans = NULL;
35770f788c58SLiu Bo 			break;
35780f788c58SLiu Bo 		}
3579c87f08caSChris Mason restart:
35803fd0a558SYan, Zheng 		if (update_backref_cache(trans, &rc->backref_cache)) {
35813a45bb20SJeff Mahoney 			btrfs_end_transaction(trans);
358242a657f5SPan Bian 			trans = NULL;
35833fd0a558SYan, Zheng 			continue;
35843fd0a558SYan, Zheng 		}
35853fd0a558SYan, Zheng 
3586147d256eSZhaolei 		ret = find_next_extent(rc, path, &key);
35875d4f98a2SYan Zheng 		if (ret < 0)
35885d4f98a2SYan Zheng 			err = ret;
35895d4f98a2SYan Zheng 		if (ret != 0)
35905d4f98a2SYan Zheng 			break;
35915d4f98a2SYan Zheng 
35925d4f98a2SYan Zheng 		rc->extents_found++;
35935d4f98a2SYan Zheng 
35945d4f98a2SYan Zheng 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
35955d4f98a2SYan Zheng 				    struct btrfs_extent_item);
35965d4f98a2SYan Zheng 		flags = btrfs_extent_flags(path->nodes[0], ei);
35975d4f98a2SYan Zheng 
35985d4f98a2SYan Zheng 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
35995d4f98a2SYan Zheng 			ret = add_tree_block(rc, &key, path, &blocks);
36005d4f98a2SYan Zheng 		} else if (rc->stage == UPDATE_DATA_PTRS &&
36015d4f98a2SYan Zheng 			   (flags & BTRFS_EXTENT_FLAG_DATA)) {
36025d4f98a2SYan Zheng 			ret = add_data_references(rc, &key, path, &blocks);
36035d4f98a2SYan Zheng 		} else {
3604b3b4aa74SDavid Sterba 			btrfs_release_path(path);
36055d4f98a2SYan Zheng 			ret = 0;
36065d4f98a2SYan Zheng 		}
36075d4f98a2SYan Zheng 		if (ret < 0) {
36083fd0a558SYan, Zheng 			err = ret;
36095d4f98a2SYan Zheng 			break;
36105d4f98a2SYan Zheng 		}
36115d4f98a2SYan Zheng 
36125d4f98a2SYan Zheng 		if (!RB_EMPTY_ROOT(&blocks)) {
36135d4f98a2SYan Zheng 			ret = relocate_tree_blocks(trans, rc, &blocks);
36145d4f98a2SYan Zheng 			if (ret < 0) {
36153fd0a558SYan, Zheng 				if (ret != -EAGAIN) {
36165d4f98a2SYan Zheng 					err = ret;
36175d4f98a2SYan Zheng 					break;
36185d4f98a2SYan Zheng 				}
36193fd0a558SYan, Zheng 				rc->extents_found--;
36203fd0a558SYan, Zheng 				rc->search_start = key.objectid;
36213fd0a558SYan, Zheng 			}
36225d4f98a2SYan Zheng 		}
36235d4f98a2SYan Zheng 
36243a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
36252ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
36263fd0a558SYan, Zheng 		trans = NULL;
36275d4f98a2SYan Zheng 
36285d4f98a2SYan Zheng 		if (rc->stage == MOVE_DATA_EXTENTS &&
36295d4f98a2SYan Zheng 		    (flags & BTRFS_EXTENT_FLAG_DATA)) {
36305d4f98a2SYan Zheng 			rc->found_file_extent = 1;
36310257bb82SYan, Zheng 			ret = relocate_data_extent(rc->data_inode,
36323fd0a558SYan, Zheng 						   &key, &rc->cluster);
36335d4f98a2SYan Zheng 			if (ret < 0) {
36345d4f98a2SYan Zheng 				err = ret;
36355d4f98a2SYan Zheng 				break;
36365d4f98a2SYan Zheng 			}
36375d4f98a2SYan Zheng 		}
3638f31ea088SQu Wenruo 		if (btrfs_should_cancel_balance(fs_info)) {
3639f31ea088SQu Wenruo 			err = -ECANCELED;
3640f31ea088SQu Wenruo 			break;
3641f31ea088SQu Wenruo 		}
36425d4f98a2SYan Zheng 	}
3643c87f08caSChris Mason 	if (trans && progress && err == -ENOSPC) {
364443a7e99dSNikolay Borisov 		ret = btrfs_force_chunk_alloc(trans, rc->block_group->flags);
36459689457bSShilong Wang 		if (ret == 1) {
3646c87f08caSChris Mason 			err = 0;
3647c87f08caSChris Mason 			progress = 0;
3648c87f08caSChris Mason 			goto restart;
3649c87f08caSChris Mason 		}
3650c87f08caSChris Mason 	}
36513fd0a558SYan, Zheng 
3652b3b4aa74SDavid Sterba 	btrfs_release_path(path);
365391166212SDavid Sterba 	clear_extent_bits(&rc->processed_blocks, 0, (u64)-1, EXTENT_DIRTY);
36545d4f98a2SYan Zheng 
36555d4f98a2SYan Zheng 	if (trans) {
36563a45bb20SJeff Mahoney 		btrfs_end_transaction_throttle(trans);
36572ff7e61eSJeff Mahoney 		btrfs_btree_balance_dirty(fs_info);
36585d4f98a2SYan Zheng 	}
36595d4f98a2SYan Zheng 
36600257bb82SYan, Zheng 	if (!err) {
36613fd0a558SYan, Zheng 		ret = relocate_file_extent_cluster(rc->data_inode,
36623fd0a558SYan, Zheng 						   &rc->cluster);
36630257bb82SYan, Zheng 		if (ret < 0)
36640257bb82SYan, Zheng 			err = ret;
36650257bb82SYan, Zheng 	}
36660257bb82SYan, Zheng 
36673fd0a558SYan, Zheng 	rc->create_reloc_tree = 0;
36683fd0a558SYan, Zheng 	set_reloc_control(rc);
36690257bb82SYan, Zheng 
367013fe1bdbSQu Wenruo 	btrfs_backref_release_cache(&rc->backref_cache);
367163f018beSNikolay Borisov 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
36725d4f98a2SYan Zheng 
36737f913c7cSQu Wenruo 	/*
36747f913c7cSQu Wenruo 	 * Even in the case when the relocation is cancelled, we should all go
36757f913c7cSQu Wenruo 	 * through prepare_to_merge() and merge_reloc_roots().
36767f913c7cSQu Wenruo 	 *
36777f913c7cSQu Wenruo 	 * For error (including cancelled balance), prepare_to_merge() will
36787f913c7cSQu Wenruo 	 * mark all reloc trees orphan, then queue them for cleanup in
36797f913c7cSQu Wenruo 	 * merge_reloc_roots()
36807f913c7cSQu Wenruo 	 */
36813fd0a558SYan, Zheng 	err = prepare_to_merge(rc, err);
36825d4f98a2SYan Zheng 
36835d4f98a2SYan Zheng 	merge_reloc_roots(rc);
36845d4f98a2SYan Zheng 
36853fd0a558SYan, Zheng 	rc->merge_reloc_tree = 0;
36865d4f98a2SYan Zheng 	unset_reloc_control(rc);
368763f018beSNikolay Borisov 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
36885d4f98a2SYan Zheng 
36895d4f98a2SYan Zheng 	/* get rid of pinned extents */
36907a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
369162b99540SQu Wenruo 	if (IS_ERR(trans)) {
36923612b495STsutomu Itoh 		err = PTR_ERR(trans);
369362b99540SQu Wenruo 		goto out_free;
369462b99540SQu Wenruo 	}
3695fb686c68SJosef Bacik 	ret = btrfs_commit_transaction(trans);
3696fb686c68SJosef Bacik 	if (ret && !err)
3697fb686c68SJosef Bacik 		err = ret;
36986217b0faSJosef Bacik out_free:
3699d2311e69SQu Wenruo 	ret = clean_dirty_subvols(rc);
3700d2311e69SQu Wenruo 	if (ret < 0 && !err)
3701d2311e69SQu Wenruo 		err = ret;
37022ff7e61eSJeff Mahoney 	btrfs_free_block_rsv(fs_info, rc->block_rsv);
37033fd0a558SYan, Zheng 	btrfs_free_path(path);
37045d4f98a2SYan Zheng 	return err;
37055d4f98a2SYan Zheng }
37065d4f98a2SYan Zheng 
37075d4f98a2SYan Zheng static int __insert_orphan_inode(struct btrfs_trans_handle *trans,
37080257bb82SYan, Zheng 				 struct btrfs_root *root, u64 objectid)
37095d4f98a2SYan Zheng {
37105d4f98a2SYan Zheng 	struct btrfs_path *path;
37115d4f98a2SYan Zheng 	struct btrfs_inode_item *item;
37125d4f98a2SYan Zheng 	struct extent_buffer *leaf;
371332430c61SNaohiro Aota 	u64 flags = BTRFS_INODE_NOCOMPRESS | BTRFS_INODE_PREALLOC;
37145d4f98a2SYan Zheng 	int ret;
37155d4f98a2SYan Zheng 
371632430c61SNaohiro Aota 	if (btrfs_is_zoned(trans->fs_info))
371732430c61SNaohiro Aota 		flags &= ~BTRFS_INODE_PREALLOC;
371832430c61SNaohiro Aota 
37195d4f98a2SYan Zheng 	path = btrfs_alloc_path();
37205d4f98a2SYan Zheng 	if (!path)
37215d4f98a2SYan Zheng 		return -ENOMEM;
37225d4f98a2SYan Zheng 
37235d4f98a2SYan Zheng 	ret = btrfs_insert_empty_inode(trans, root, path, objectid);
37245d4f98a2SYan Zheng 	if (ret)
37255d4f98a2SYan Zheng 		goto out;
37265d4f98a2SYan Zheng 
37275d4f98a2SYan Zheng 	leaf = path->nodes[0];
37285d4f98a2SYan Zheng 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item);
3729b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
37305d4f98a2SYan Zheng 	btrfs_set_inode_generation(leaf, item, 1);
37310257bb82SYan, Zheng 	btrfs_set_inode_size(leaf, item, 0);
37325d4f98a2SYan Zheng 	btrfs_set_inode_mode(leaf, item, S_IFREG | 0600);
373332430c61SNaohiro Aota 	btrfs_set_inode_flags(leaf, item, flags);
37345d4f98a2SYan Zheng 	btrfs_mark_buffer_dirty(leaf);
37355d4f98a2SYan Zheng out:
37365d4f98a2SYan Zheng 	btrfs_free_path(path);
37375d4f98a2SYan Zheng 	return ret;
37385d4f98a2SYan Zheng }
37395d4f98a2SYan Zheng 
3740790c1b8cSJosef Bacik static void delete_orphan_inode(struct btrfs_trans_handle *trans,
3741790c1b8cSJosef Bacik 				struct btrfs_root *root, u64 objectid)
3742790c1b8cSJosef Bacik {
3743790c1b8cSJosef Bacik 	struct btrfs_path *path;
3744790c1b8cSJosef Bacik 	struct btrfs_key key;
3745790c1b8cSJosef Bacik 	int ret = 0;
3746790c1b8cSJosef Bacik 
3747790c1b8cSJosef Bacik 	path = btrfs_alloc_path();
3748790c1b8cSJosef Bacik 	if (!path) {
3749790c1b8cSJosef Bacik 		ret = -ENOMEM;
3750790c1b8cSJosef Bacik 		goto out;
3751790c1b8cSJosef Bacik 	}
3752790c1b8cSJosef Bacik 
3753790c1b8cSJosef Bacik 	key.objectid = objectid;
3754790c1b8cSJosef Bacik 	key.type = BTRFS_INODE_ITEM_KEY;
3755790c1b8cSJosef Bacik 	key.offset = 0;
3756790c1b8cSJosef Bacik 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3757790c1b8cSJosef Bacik 	if (ret) {
3758790c1b8cSJosef Bacik 		if (ret > 0)
3759790c1b8cSJosef Bacik 			ret = -ENOENT;
3760790c1b8cSJosef Bacik 		goto out;
3761790c1b8cSJosef Bacik 	}
3762790c1b8cSJosef Bacik 	ret = btrfs_del_item(trans, root, path);
3763790c1b8cSJosef Bacik out:
3764790c1b8cSJosef Bacik 	if (ret)
3765790c1b8cSJosef Bacik 		btrfs_abort_transaction(trans, ret);
3766790c1b8cSJosef Bacik 	btrfs_free_path(path);
3767790c1b8cSJosef Bacik }
3768790c1b8cSJosef Bacik 
37695d4f98a2SYan Zheng /*
37705d4f98a2SYan Zheng  * helper to create inode for data relocation.
37715d4f98a2SYan Zheng  * the inode is in data relocation tree and its link count is 0
37725d4f98a2SYan Zheng  */
37733fd0a558SYan, Zheng static noinline_for_stack
37743fd0a558SYan, Zheng struct inode *create_reloc_inode(struct btrfs_fs_info *fs_info,
377532da5386SDavid Sterba 				 struct btrfs_block_group *group)
37765d4f98a2SYan Zheng {
37775d4f98a2SYan Zheng 	struct inode *inode = NULL;
37785d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
37795d4f98a2SYan Zheng 	struct btrfs_root *root;
37804624900dSZhaolei 	u64 objectid;
37815d4f98a2SYan Zheng 	int err = 0;
37825d4f98a2SYan Zheng 
3783aeb935a4SQu Wenruo 	root = btrfs_grab_root(fs_info->data_reloc_root);
3784a22285a6SYan, Zheng 	trans = btrfs_start_transaction(root, 6);
378576deacf0SJosef Bacik 	if (IS_ERR(trans)) {
378600246528SJosef Bacik 		btrfs_put_root(root);
37873fd0a558SYan, Zheng 		return ERR_CAST(trans);
378876deacf0SJosef Bacik 	}
37895d4f98a2SYan Zheng 
3790543068a2SNikolay Borisov 	err = btrfs_get_free_objectid(root, &objectid);
37915d4f98a2SYan Zheng 	if (err)
37925d4f98a2SYan Zheng 		goto out;
37935d4f98a2SYan Zheng 
37940257bb82SYan, Zheng 	err = __insert_orphan_inode(trans, root, objectid);
3795790c1b8cSJosef Bacik 	if (err)
3796790c1b8cSJosef Bacik 		goto out;
37975d4f98a2SYan Zheng 
37980202e83fSDavid Sterba 	inode = btrfs_iget(fs_info->sb, objectid, root);
3799790c1b8cSJosef Bacik 	if (IS_ERR(inode)) {
3800790c1b8cSJosef Bacik 		delete_orphan_inode(trans, root, objectid);
3801790c1b8cSJosef Bacik 		err = PTR_ERR(inode);
3802790c1b8cSJosef Bacik 		inode = NULL;
3803790c1b8cSJosef Bacik 		goto out;
3804790c1b8cSJosef Bacik 	}
3805b3470b5dSDavid Sterba 	BTRFS_I(inode)->index_cnt = group->start;
38065d4f98a2SYan Zheng 
380773f2e545SNikolay Borisov 	err = btrfs_orphan_add(trans, BTRFS_I(inode));
38085d4f98a2SYan Zheng out:
380900246528SJosef Bacik 	btrfs_put_root(root);
38103a45bb20SJeff Mahoney 	btrfs_end_transaction(trans);
38112ff7e61eSJeff Mahoney 	btrfs_btree_balance_dirty(fs_info);
38125d4f98a2SYan Zheng 	if (err) {
38135d4f98a2SYan Zheng 		if (inode)
38145d4f98a2SYan Zheng 			iput(inode);
38155d4f98a2SYan Zheng 		inode = ERR_PTR(err);
38165d4f98a2SYan Zheng 	}
38175d4f98a2SYan Zheng 	return inode;
38185d4f98a2SYan Zheng }
38195d4f98a2SYan Zheng 
3820907d2710SDavid Sterba /*
3821907d2710SDavid Sterba  * Mark start of chunk relocation that is cancellable. Check if the cancellation
3822907d2710SDavid Sterba  * has been requested meanwhile and don't start in that case.
3823907d2710SDavid Sterba  *
3824907d2710SDavid Sterba  * Return:
3825907d2710SDavid Sterba  *   0             success
3826907d2710SDavid Sterba  *   -EINPROGRESS  operation is already in progress, that's probably a bug
3827907d2710SDavid Sterba  *   -ECANCELED    cancellation request was set before the operation started
38281cea5cf0SFilipe Manana  *   -EAGAIN       can not start because there are ongoing send operations
3829907d2710SDavid Sterba  */
3830907d2710SDavid Sterba static int reloc_chunk_start(struct btrfs_fs_info *fs_info)
3831907d2710SDavid Sterba {
38321cea5cf0SFilipe Manana 	spin_lock(&fs_info->send_reloc_lock);
38331cea5cf0SFilipe Manana 	if (fs_info->send_in_progress) {
38341cea5cf0SFilipe Manana 		btrfs_warn_rl(fs_info,
38351cea5cf0SFilipe Manana "cannot run relocation while send operations are in progress (%d in progress)",
38361cea5cf0SFilipe Manana 			      fs_info->send_in_progress);
38371cea5cf0SFilipe Manana 		spin_unlock(&fs_info->send_reloc_lock);
38381cea5cf0SFilipe Manana 		return -EAGAIN;
38391cea5cf0SFilipe Manana 	}
3840907d2710SDavid Sterba 	if (test_and_set_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags)) {
3841907d2710SDavid Sterba 		/* This should not happen */
38421cea5cf0SFilipe Manana 		spin_unlock(&fs_info->send_reloc_lock);
3843907d2710SDavid Sterba 		btrfs_err(fs_info, "reloc already running, cannot start");
3844907d2710SDavid Sterba 		return -EINPROGRESS;
3845907d2710SDavid Sterba 	}
38461cea5cf0SFilipe Manana 	spin_unlock(&fs_info->send_reloc_lock);
3847907d2710SDavid Sterba 
3848907d2710SDavid Sterba 	if (atomic_read(&fs_info->reloc_cancel_req) > 0) {
3849907d2710SDavid Sterba 		btrfs_info(fs_info, "chunk relocation canceled on start");
3850907d2710SDavid Sterba 		/*
3851907d2710SDavid Sterba 		 * On cancel, clear all requests but let the caller mark
3852907d2710SDavid Sterba 		 * the end after cleanup operations.
3853907d2710SDavid Sterba 		 */
3854907d2710SDavid Sterba 		atomic_set(&fs_info->reloc_cancel_req, 0);
3855907d2710SDavid Sterba 		return -ECANCELED;
3856907d2710SDavid Sterba 	}
3857907d2710SDavid Sterba 	return 0;
3858907d2710SDavid Sterba }
3859907d2710SDavid Sterba 
3860907d2710SDavid Sterba /*
3861907d2710SDavid Sterba  * Mark end of chunk relocation that is cancellable and wake any waiters.
3862907d2710SDavid Sterba  */
3863907d2710SDavid Sterba static void reloc_chunk_end(struct btrfs_fs_info *fs_info)
3864907d2710SDavid Sterba {
3865907d2710SDavid Sterba 	/* Requested after start, clear bit first so any waiters can continue */
3866907d2710SDavid Sterba 	if (atomic_read(&fs_info->reloc_cancel_req) > 0)
3867907d2710SDavid Sterba 		btrfs_info(fs_info, "chunk relocation canceled during operation");
38681cea5cf0SFilipe Manana 	spin_lock(&fs_info->send_reloc_lock);
3869907d2710SDavid Sterba 	clear_and_wake_up_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags);
38701cea5cf0SFilipe Manana 	spin_unlock(&fs_info->send_reloc_lock);
3871907d2710SDavid Sterba 	atomic_set(&fs_info->reloc_cancel_req, 0);
3872907d2710SDavid Sterba }
3873907d2710SDavid Sterba 
3874c258d6e3SQu Wenruo static struct reloc_control *alloc_reloc_control(struct btrfs_fs_info *fs_info)
38753fd0a558SYan, Zheng {
38763fd0a558SYan, Zheng 	struct reloc_control *rc;
38773fd0a558SYan, Zheng 
38783fd0a558SYan, Zheng 	rc = kzalloc(sizeof(*rc), GFP_NOFS);
38793fd0a558SYan, Zheng 	if (!rc)
38803fd0a558SYan, Zheng 		return NULL;
38813fd0a558SYan, Zheng 
38823fd0a558SYan, Zheng 	INIT_LIST_HEAD(&rc->reloc_roots);
3883d2311e69SQu Wenruo 	INIT_LIST_HEAD(&rc->dirty_subvol_roots);
3884584fb121SQu Wenruo 	btrfs_backref_init_cache(fs_info, &rc->backref_cache, 1);
38853fd0a558SYan, Zheng 	mapping_tree_init(&rc->reloc_root_tree);
388643eb5f29SQu Wenruo 	extent_io_tree_init(fs_info, &rc->processed_blocks,
388743eb5f29SQu Wenruo 			    IO_TREE_RELOC_BLOCKS, NULL);
38883fd0a558SYan, Zheng 	return rc;
38893fd0a558SYan, Zheng }
38903fd0a558SYan, Zheng 
38911a0afa0eSJosef Bacik static void free_reloc_control(struct reloc_control *rc)
38921a0afa0eSJosef Bacik {
38931a0afa0eSJosef Bacik 	struct mapping_node *node, *tmp;
38941a0afa0eSJosef Bacik 
38951a0afa0eSJosef Bacik 	free_reloc_roots(&rc->reloc_roots);
38961a0afa0eSJosef Bacik 	rbtree_postorder_for_each_entry_safe(node, tmp,
38971a0afa0eSJosef Bacik 			&rc->reloc_root_tree.rb_root, rb_node)
38981a0afa0eSJosef Bacik 		kfree(node);
38991a0afa0eSJosef Bacik 
39001a0afa0eSJosef Bacik 	kfree(rc);
39011a0afa0eSJosef Bacik }
39021a0afa0eSJosef Bacik 
39035d4f98a2SYan Zheng /*
3904ebce0e01SAdam Borowski  * Print the block group being relocated
3905ebce0e01SAdam Borowski  */
3906ebce0e01SAdam Borowski static void describe_relocation(struct btrfs_fs_info *fs_info,
390732da5386SDavid Sterba 				struct btrfs_block_group *block_group)
3908ebce0e01SAdam Borowski {
3909f89e09cfSAnand Jain 	char buf[128] = {'\0'};
3910ebce0e01SAdam Borowski 
3911f89e09cfSAnand Jain 	btrfs_describe_block_groups(block_group->flags, buf, sizeof(buf));
3912ebce0e01SAdam Borowski 
3913ebce0e01SAdam Borowski 	btrfs_info(fs_info,
3914ebce0e01SAdam Borowski 		   "relocating block group %llu flags %s",
3915b3470b5dSDavid Sterba 		   block_group->start, buf);
3916ebce0e01SAdam Borowski }
3917ebce0e01SAdam Borowski 
3918430640e3SQu Wenruo static const char *stage_to_string(int stage)
3919430640e3SQu Wenruo {
3920430640e3SQu Wenruo 	if (stage == MOVE_DATA_EXTENTS)
3921430640e3SQu Wenruo 		return "move data extents";
3922430640e3SQu Wenruo 	if (stage == UPDATE_DATA_PTRS)
3923430640e3SQu Wenruo 		return "update data pointers";
3924430640e3SQu Wenruo 	return "unknown";
3925430640e3SQu Wenruo }
3926430640e3SQu Wenruo 
3927ebce0e01SAdam Borowski /*
39285d4f98a2SYan Zheng  * function to relocate all extents in a block group.
39295d4f98a2SYan Zheng  */
39306bccf3abSJeff Mahoney int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start)
39315d4f98a2SYan Zheng {
393232da5386SDavid Sterba 	struct btrfs_block_group *bg;
39336bccf3abSJeff Mahoney 	struct btrfs_root *extent_root = fs_info->extent_root;
39345d4f98a2SYan Zheng 	struct reloc_control *rc;
39350af3d00bSJosef Bacik 	struct inode *inode;
39360af3d00bSJosef Bacik 	struct btrfs_path *path;
39375d4f98a2SYan Zheng 	int ret;
3938f0486c68SYan, Zheng 	int rw = 0;
39395d4f98a2SYan Zheng 	int err = 0;
39405d4f98a2SYan Zheng 
3941eede2bf3SOmar Sandoval 	bg = btrfs_lookup_block_group(fs_info, group_start);
3942eede2bf3SOmar Sandoval 	if (!bg)
3943eede2bf3SOmar Sandoval 		return -ENOENT;
3944eede2bf3SOmar Sandoval 
3945eede2bf3SOmar Sandoval 	if (btrfs_pinned_by_swapfile(fs_info, bg)) {
3946eede2bf3SOmar Sandoval 		btrfs_put_block_group(bg);
3947eede2bf3SOmar Sandoval 		return -ETXTBSY;
3948eede2bf3SOmar Sandoval 	}
3949eede2bf3SOmar Sandoval 
3950c258d6e3SQu Wenruo 	rc = alloc_reloc_control(fs_info);
3951eede2bf3SOmar Sandoval 	if (!rc) {
3952eede2bf3SOmar Sandoval 		btrfs_put_block_group(bg);
39535d4f98a2SYan Zheng 		return -ENOMEM;
3954eede2bf3SOmar Sandoval 	}
39555d4f98a2SYan Zheng 
3956907d2710SDavid Sterba 	ret = reloc_chunk_start(fs_info);
3957907d2710SDavid Sterba 	if (ret < 0) {
3958907d2710SDavid Sterba 		err = ret;
3959907d2710SDavid Sterba 		goto out_put_bg;
3960907d2710SDavid Sterba 	}
3961907d2710SDavid Sterba 
3962f0486c68SYan, Zheng 	rc->extent_root = extent_root;
3963eede2bf3SOmar Sandoval 	rc->block_group = bg;
39645d4f98a2SYan Zheng 
3965b12de528SQu Wenruo 	ret = btrfs_inc_block_group_ro(rc->block_group, true);
3966f0486c68SYan, Zheng 	if (ret) {
3967f0486c68SYan, Zheng 		err = ret;
3968f0486c68SYan, Zheng 		goto out;
3969f0486c68SYan, Zheng 	}
3970f0486c68SYan, Zheng 	rw = 1;
3971f0486c68SYan, Zheng 
39720af3d00bSJosef Bacik 	path = btrfs_alloc_path();
39730af3d00bSJosef Bacik 	if (!path) {
39740af3d00bSJosef Bacik 		err = -ENOMEM;
39750af3d00bSJosef Bacik 		goto out;
39760af3d00bSJosef Bacik 	}
39770af3d00bSJosef Bacik 
39787949f339SDavid Sterba 	inode = lookup_free_space_inode(rc->block_group, path);
39790af3d00bSJosef Bacik 	btrfs_free_path(path);
39800af3d00bSJosef Bacik 
39810af3d00bSJosef Bacik 	if (!IS_ERR(inode))
39821bbc621eSChris Mason 		ret = delete_block_group_cache(fs_info, rc->block_group, inode, 0);
39830af3d00bSJosef Bacik 	else
39840af3d00bSJosef Bacik 		ret = PTR_ERR(inode);
39850af3d00bSJosef Bacik 
39860af3d00bSJosef Bacik 	if (ret && ret != -ENOENT) {
39870af3d00bSJosef Bacik 		err = ret;
39880af3d00bSJosef Bacik 		goto out;
39890af3d00bSJosef Bacik 	}
39900af3d00bSJosef Bacik 
39915d4f98a2SYan Zheng 	rc->data_inode = create_reloc_inode(fs_info, rc->block_group);
39925d4f98a2SYan Zheng 	if (IS_ERR(rc->data_inode)) {
39935d4f98a2SYan Zheng 		err = PTR_ERR(rc->data_inode);
39945d4f98a2SYan Zheng 		rc->data_inode = NULL;
39955d4f98a2SYan Zheng 		goto out;
39965d4f98a2SYan Zheng 	}
39975d4f98a2SYan Zheng 
39980b246afaSJeff Mahoney 	describe_relocation(fs_info, rc->block_group);
39995d4f98a2SYan Zheng 
40009cfa3e34SFilipe Manana 	btrfs_wait_block_group_reservations(rc->block_group);
4001f78c436cSFilipe Manana 	btrfs_wait_nocow_writers(rc->block_group);
40026374e57aSChris Mason 	btrfs_wait_ordered_roots(fs_info, U64_MAX,
4003b3470b5dSDavid Sterba 				 rc->block_group->start,
4004b3470b5dSDavid Sterba 				 rc->block_group->length);
40055d4f98a2SYan Zheng 
40065d4f98a2SYan Zheng 	while (1) {
4007430640e3SQu Wenruo 		int finishes_stage;
4008430640e3SQu Wenruo 
400976dda93cSYan, Zheng 		mutex_lock(&fs_info->cleaner_mutex);
40105d4f98a2SYan Zheng 		ret = relocate_block_group(rc);
401176dda93cSYan, Zheng 		mutex_unlock(&fs_info->cleaner_mutex);
4012ff612ba7SJosef Bacik 		if (ret < 0)
40135d4f98a2SYan Zheng 			err = ret;
4014ff612ba7SJosef Bacik 
4015430640e3SQu Wenruo 		finishes_stage = rc->stage;
4016ff612ba7SJosef Bacik 		/*
4017ff612ba7SJosef Bacik 		 * We may have gotten ENOSPC after we already dirtied some
4018ff612ba7SJosef Bacik 		 * extents.  If writeout happens while we're relocating a
4019ff612ba7SJosef Bacik 		 * different block group we could end up hitting the
4020ff612ba7SJosef Bacik 		 * BUG_ON(rc->stage == UPDATE_DATA_PTRS) in
4021ff612ba7SJosef Bacik 		 * btrfs_reloc_cow_block.  Make sure we write everything out
4022ff612ba7SJosef Bacik 		 * properly so we don't trip over this problem, and then break
4023ff612ba7SJosef Bacik 		 * out of the loop if we hit an error.
4024ff612ba7SJosef Bacik 		 */
4025ff612ba7SJosef Bacik 		if (rc->stage == MOVE_DATA_EXTENTS && rc->found_file_extent) {
4026ff612ba7SJosef Bacik 			ret = btrfs_wait_ordered_range(rc->data_inode, 0,
4027ff612ba7SJosef Bacik 						       (u64)-1);
4028ff612ba7SJosef Bacik 			if (ret)
4029ff612ba7SJosef Bacik 				err = ret;
4030ff612ba7SJosef Bacik 			invalidate_mapping_pages(rc->data_inode->i_mapping,
4031ff612ba7SJosef Bacik 						 0, -1);
4032ff612ba7SJosef Bacik 			rc->stage = UPDATE_DATA_PTRS;
40335d4f98a2SYan Zheng 		}
40345d4f98a2SYan Zheng 
4035ff612ba7SJosef Bacik 		if (err < 0)
4036ff612ba7SJosef Bacik 			goto out;
4037ff612ba7SJosef Bacik 
40385d4f98a2SYan Zheng 		if (rc->extents_found == 0)
40395d4f98a2SYan Zheng 			break;
40405d4f98a2SYan Zheng 
4041430640e3SQu Wenruo 		btrfs_info(fs_info, "found %llu extents, stage: %s",
4042430640e3SQu Wenruo 			   rc->extents_found, stage_to_string(finishes_stage));
40435d4f98a2SYan Zheng 	}
40445d4f98a2SYan Zheng 
40455d4f98a2SYan Zheng 	WARN_ON(rc->block_group->pinned > 0);
40465d4f98a2SYan Zheng 	WARN_ON(rc->block_group->reserved > 0);
4047bf38be65SDavid Sterba 	WARN_ON(rc->block_group->used > 0);
40485d4f98a2SYan Zheng out:
4049f0486c68SYan, Zheng 	if (err && rw)
40502ff7e61eSJeff Mahoney 		btrfs_dec_block_group_ro(rc->block_group);
40515d4f98a2SYan Zheng 	iput(rc->data_inode);
4052907d2710SDavid Sterba out_put_bg:
4053907d2710SDavid Sterba 	btrfs_put_block_group(bg);
4054907d2710SDavid Sterba 	reloc_chunk_end(fs_info);
40551a0afa0eSJosef Bacik 	free_reloc_control(rc);
40565d4f98a2SYan Zheng 	return err;
40575d4f98a2SYan Zheng }
40585d4f98a2SYan Zheng 
405976dda93cSYan, Zheng static noinline_for_stack int mark_garbage_root(struct btrfs_root *root)
406076dda93cSYan, Zheng {
40610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
406276dda93cSYan, Zheng 	struct btrfs_trans_handle *trans;
406379787eaaSJeff Mahoney 	int ret, err;
406476dda93cSYan, Zheng 
40650b246afaSJeff Mahoney 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
406679787eaaSJeff Mahoney 	if (IS_ERR(trans))
406779787eaaSJeff Mahoney 		return PTR_ERR(trans);
406876dda93cSYan, Zheng 
406976dda93cSYan, Zheng 	memset(&root->root_item.drop_progress, 0,
407076dda93cSYan, Zheng 		sizeof(root->root_item.drop_progress));
4071c8422684SDavid Sterba 	btrfs_set_root_drop_level(&root->root_item, 0);
407276dda93cSYan, Zheng 	btrfs_set_root_refs(&root->root_item, 0);
40730b246afaSJeff Mahoney 	ret = btrfs_update_root(trans, fs_info->tree_root,
407476dda93cSYan, Zheng 				&root->root_key, &root->root_item);
407576dda93cSYan, Zheng 
40763a45bb20SJeff Mahoney 	err = btrfs_end_transaction(trans);
407779787eaaSJeff Mahoney 	if (err)
407879787eaaSJeff Mahoney 		return err;
407979787eaaSJeff Mahoney 	return ret;
408076dda93cSYan, Zheng }
408176dda93cSYan, Zheng 
40825d4f98a2SYan Zheng /*
40835d4f98a2SYan Zheng  * recover relocation interrupted by system crash.
40845d4f98a2SYan Zheng  *
40855d4f98a2SYan Zheng  * this function resumes merging reloc trees with corresponding fs trees.
40865d4f98a2SYan Zheng  * this is important for keeping the sharing of tree blocks
40875d4f98a2SYan Zheng  */
40885d4f98a2SYan Zheng int btrfs_recover_relocation(struct btrfs_root *root)
40895d4f98a2SYan Zheng {
40900b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
40915d4f98a2SYan Zheng 	LIST_HEAD(reloc_roots);
40925d4f98a2SYan Zheng 	struct btrfs_key key;
40935d4f98a2SYan Zheng 	struct btrfs_root *fs_root;
40945d4f98a2SYan Zheng 	struct btrfs_root *reloc_root;
40955d4f98a2SYan Zheng 	struct btrfs_path *path;
40965d4f98a2SYan Zheng 	struct extent_buffer *leaf;
40975d4f98a2SYan Zheng 	struct reloc_control *rc = NULL;
40985d4f98a2SYan Zheng 	struct btrfs_trans_handle *trans;
40995d4f98a2SYan Zheng 	int ret;
41005d4f98a2SYan Zheng 	int err = 0;
41015d4f98a2SYan Zheng 
41025d4f98a2SYan Zheng 	path = btrfs_alloc_path();
41035d4f98a2SYan Zheng 	if (!path)
41045d4f98a2SYan Zheng 		return -ENOMEM;
4105e4058b54SDavid Sterba 	path->reada = READA_BACK;
41065d4f98a2SYan Zheng 
41075d4f98a2SYan Zheng 	key.objectid = BTRFS_TREE_RELOC_OBJECTID;
41085d4f98a2SYan Zheng 	key.type = BTRFS_ROOT_ITEM_KEY;
41095d4f98a2SYan Zheng 	key.offset = (u64)-1;
41105d4f98a2SYan Zheng 
41115d4f98a2SYan Zheng 	while (1) {
41120b246afaSJeff Mahoney 		ret = btrfs_search_slot(NULL, fs_info->tree_root, &key,
41135d4f98a2SYan Zheng 					path, 0, 0);
41145d4f98a2SYan Zheng 		if (ret < 0) {
41155d4f98a2SYan Zheng 			err = ret;
41165d4f98a2SYan Zheng 			goto out;
41175d4f98a2SYan Zheng 		}
41185d4f98a2SYan Zheng 		if (ret > 0) {
41195d4f98a2SYan Zheng 			if (path->slots[0] == 0)
41205d4f98a2SYan Zheng 				break;
41215d4f98a2SYan Zheng 			path->slots[0]--;
41225d4f98a2SYan Zheng 		}
41235d4f98a2SYan Zheng 		leaf = path->nodes[0];
41245d4f98a2SYan Zheng 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4125b3b4aa74SDavid Sterba 		btrfs_release_path(path);
41265d4f98a2SYan Zheng 
41275d4f98a2SYan Zheng 		if (key.objectid != BTRFS_TREE_RELOC_OBJECTID ||
41285d4f98a2SYan Zheng 		    key.type != BTRFS_ROOT_ITEM_KEY)
41295d4f98a2SYan Zheng 			break;
41305d4f98a2SYan Zheng 
41313dbf1738SJosef Bacik 		reloc_root = btrfs_read_tree_root(root, &key);
41325d4f98a2SYan Zheng 		if (IS_ERR(reloc_root)) {
41335d4f98a2SYan Zheng 			err = PTR_ERR(reloc_root);
41345d4f98a2SYan Zheng 			goto out;
41355d4f98a2SYan Zheng 		}
41365d4f98a2SYan Zheng 
413792a7cc42SQu Wenruo 		set_bit(BTRFS_ROOT_SHAREABLE, &reloc_root->state);
41385d4f98a2SYan Zheng 		list_add(&reloc_root->root_list, &reloc_roots);
41395d4f98a2SYan Zheng 
41405d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
4141a820feb5SDavid Sterba 			fs_root = btrfs_get_fs_root(fs_info,
4142a820feb5SDavid Sterba 					reloc_root->root_key.offset, false);
41435d4f98a2SYan Zheng 			if (IS_ERR(fs_root)) {
414476dda93cSYan, Zheng 				ret = PTR_ERR(fs_root);
414576dda93cSYan, Zheng 				if (ret != -ENOENT) {
414676dda93cSYan, Zheng 					err = ret;
41475d4f98a2SYan Zheng 					goto out;
41485d4f98a2SYan Zheng 				}
414979787eaaSJeff Mahoney 				ret = mark_garbage_root(reloc_root);
415079787eaaSJeff Mahoney 				if (ret < 0) {
415179787eaaSJeff Mahoney 					err = ret;
415279787eaaSJeff Mahoney 					goto out;
415379787eaaSJeff Mahoney 				}
4154932fd26dSJosef Bacik 			} else {
415500246528SJosef Bacik 				btrfs_put_root(fs_root);
415676dda93cSYan, Zheng 			}
41575d4f98a2SYan Zheng 		}
41585d4f98a2SYan Zheng 
41595d4f98a2SYan Zheng 		if (key.offset == 0)
41605d4f98a2SYan Zheng 			break;
41615d4f98a2SYan Zheng 
41625d4f98a2SYan Zheng 		key.offset--;
41635d4f98a2SYan Zheng 	}
4164b3b4aa74SDavid Sterba 	btrfs_release_path(path);
41655d4f98a2SYan Zheng 
41665d4f98a2SYan Zheng 	if (list_empty(&reloc_roots))
41675d4f98a2SYan Zheng 		goto out;
41685d4f98a2SYan Zheng 
4169c258d6e3SQu Wenruo 	rc = alloc_reloc_control(fs_info);
41705d4f98a2SYan Zheng 	if (!rc) {
41715d4f98a2SYan Zheng 		err = -ENOMEM;
41725d4f98a2SYan Zheng 		goto out;
41735d4f98a2SYan Zheng 	}
41745d4f98a2SYan Zheng 
4175907d2710SDavid Sterba 	ret = reloc_chunk_start(fs_info);
4176907d2710SDavid Sterba 	if (ret < 0) {
4177907d2710SDavid Sterba 		err = ret;
4178907d2710SDavid Sterba 		goto out_end;
4179907d2710SDavid Sterba 	}
4180907d2710SDavid Sterba 
41810b246afaSJeff Mahoney 	rc->extent_root = fs_info->extent_root;
41825d4f98a2SYan Zheng 
41835d4f98a2SYan Zheng 	set_reloc_control(rc);
41845d4f98a2SYan Zheng 
41857a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
41863612b495STsutomu Itoh 	if (IS_ERR(trans)) {
41873612b495STsutomu Itoh 		err = PTR_ERR(trans);
4188fb2d83eeSJosef Bacik 		goto out_unset;
41893612b495STsutomu Itoh 	}
41903fd0a558SYan, Zheng 
41913fd0a558SYan, Zheng 	rc->merge_reloc_tree = 1;
41923fd0a558SYan, Zheng 
41935d4f98a2SYan Zheng 	while (!list_empty(&reloc_roots)) {
41945d4f98a2SYan Zheng 		reloc_root = list_entry(reloc_roots.next,
41955d4f98a2SYan Zheng 					struct btrfs_root, root_list);
41965d4f98a2SYan Zheng 		list_del(&reloc_root->root_list);
41975d4f98a2SYan Zheng 
41985d4f98a2SYan Zheng 		if (btrfs_root_refs(&reloc_root->root_item) == 0) {
41995d4f98a2SYan Zheng 			list_add_tail(&reloc_root->root_list,
42005d4f98a2SYan Zheng 				      &rc->reloc_roots);
42015d4f98a2SYan Zheng 			continue;
42025d4f98a2SYan Zheng 		}
42035d4f98a2SYan Zheng 
4204a820feb5SDavid Sterba 		fs_root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
4205a820feb5SDavid Sterba 					    false);
420679787eaaSJeff Mahoney 		if (IS_ERR(fs_root)) {
420779787eaaSJeff Mahoney 			err = PTR_ERR(fs_root);
4208ca1aa281SJosef Bacik 			list_add_tail(&reloc_root->root_list, &reloc_roots);
42091402d17dSXiyu Yang 			btrfs_end_transaction(trans);
4210fb2d83eeSJosef Bacik 			goto out_unset;
421179787eaaSJeff Mahoney 		}
42125d4f98a2SYan Zheng 
4213ffd7b339SJeff Mahoney 		err = __add_reloc_root(reloc_root);
421457a304cfSJosef Bacik 		ASSERT(err != -EEXIST);
42153c925863SJosef Bacik 		if (err) {
42163c925863SJosef Bacik 			list_add_tail(&reloc_root->root_list, &reloc_roots);
42173c925863SJosef Bacik 			btrfs_put_root(fs_root);
42183c925863SJosef Bacik 			btrfs_end_transaction(trans);
42193c925863SJosef Bacik 			goto out_unset;
42203c925863SJosef Bacik 		}
4221f44deb74SJosef Bacik 		fs_root->reloc_root = btrfs_grab_root(reloc_root);
422200246528SJosef Bacik 		btrfs_put_root(fs_root);
42235d4f98a2SYan Zheng 	}
42245d4f98a2SYan Zheng 
42253a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
422679787eaaSJeff Mahoney 	if (err)
4227fb2d83eeSJosef Bacik 		goto out_unset;
42285d4f98a2SYan Zheng 
42295d4f98a2SYan Zheng 	merge_reloc_roots(rc);
42305d4f98a2SYan Zheng 
42315d4f98a2SYan Zheng 	unset_reloc_control(rc);
42325d4f98a2SYan Zheng 
42337a7eaa40SJosef Bacik 	trans = btrfs_join_transaction(rc->extent_root);
423462b99540SQu Wenruo 	if (IS_ERR(trans)) {
42353612b495STsutomu Itoh 		err = PTR_ERR(trans);
42366217b0faSJosef Bacik 		goto out_clean;
423762b99540SQu Wenruo 	}
42383a45bb20SJeff Mahoney 	err = btrfs_commit_transaction(trans);
42396217b0faSJosef Bacik out_clean:
4240d2311e69SQu Wenruo 	ret = clean_dirty_subvols(rc);
4241d2311e69SQu Wenruo 	if (ret < 0 && !err)
4242d2311e69SQu Wenruo 		err = ret;
4243fb2d83eeSJosef Bacik out_unset:
4244fb2d83eeSJosef Bacik 	unset_reloc_control(rc);
4245907d2710SDavid Sterba out_end:
4246907d2710SDavid Sterba 	reloc_chunk_end(fs_info);
42471a0afa0eSJosef Bacik 	free_reloc_control(rc);
42483612b495STsutomu Itoh out:
4249aca1bba6SLiu Bo 	free_reloc_roots(&reloc_roots);
4250aca1bba6SLiu Bo 
42515d4f98a2SYan Zheng 	btrfs_free_path(path);
42525d4f98a2SYan Zheng 
42535d4f98a2SYan Zheng 	if (err == 0) {
42545d4f98a2SYan Zheng 		/* cleanup orphan inode in data relocation tree */
4255aeb935a4SQu Wenruo 		fs_root = btrfs_grab_root(fs_info->data_reloc_root);
4256aeb935a4SQu Wenruo 		ASSERT(fs_root);
425766b4ffd1SJosef Bacik 		err = btrfs_orphan_cleanup(fs_root);
425800246528SJosef Bacik 		btrfs_put_root(fs_root);
4259932fd26dSJosef Bacik 	}
42605d4f98a2SYan Zheng 	return err;
42615d4f98a2SYan Zheng }
42625d4f98a2SYan Zheng 
42635d4f98a2SYan Zheng /*
42645d4f98a2SYan Zheng  * helper to add ordered checksum for data relocation.
42655d4f98a2SYan Zheng  *
42665d4f98a2SYan Zheng  * cloning checksum properly handles the nodatasum extents.
42675d4f98a2SYan Zheng  * it also saves CPU time to re-calculate the checksum.
42685d4f98a2SYan Zheng  */
42697bfa9535SNikolay Borisov int btrfs_reloc_clone_csums(struct btrfs_inode *inode, u64 file_pos, u64 len)
42705d4f98a2SYan Zheng {
42717bfa9535SNikolay Borisov 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
42725d4f98a2SYan Zheng 	struct btrfs_ordered_sum *sums;
42735d4f98a2SYan Zheng 	struct btrfs_ordered_extent *ordered;
42745d4f98a2SYan Zheng 	int ret;
42755d4f98a2SYan Zheng 	u64 disk_bytenr;
42764577b014SJosef Bacik 	u64 new_bytenr;
42775d4f98a2SYan Zheng 	LIST_HEAD(list);
42785d4f98a2SYan Zheng 
42797bfa9535SNikolay Borisov 	ordered = btrfs_lookup_ordered_extent(inode, file_pos);
4280bffe633eSOmar Sandoval 	BUG_ON(ordered->file_offset != file_pos || ordered->num_bytes != len);
42815d4f98a2SYan Zheng 
42827bfa9535SNikolay Borisov 	disk_bytenr = file_pos + inode->index_cnt;
42830b246afaSJeff Mahoney 	ret = btrfs_lookup_csums_range(fs_info->csum_root, disk_bytenr,
4284a2de733cSArne Jansen 				       disk_bytenr + len - 1, &list, 0);
428579787eaaSJeff Mahoney 	if (ret)
428679787eaaSJeff Mahoney 		goto out;
42875d4f98a2SYan Zheng 
42885d4f98a2SYan Zheng 	while (!list_empty(&list)) {
42895d4f98a2SYan Zheng 		sums = list_entry(list.next, struct btrfs_ordered_sum, list);
42905d4f98a2SYan Zheng 		list_del_init(&sums->list);
42915d4f98a2SYan Zheng 
42924577b014SJosef Bacik 		/*
42934577b014SJosef Bacik 		 * We need to offset the new_bytenr based on where the csum is.
42944577b014SJosef Bacik 		 * We need to do this because we will read in entire prealloc
42954577b014SJosef Bacik 		 * extents but we may have written to say the middle of the
42964577b014SJosef Bacik 		 * prealloc extent, so we need to make sure the csum goes with
42974577b014SJosef Bacik 		 * the right disk offset.
42984577b014SJosef Bacik 		 *
42994577b014SJosef Bacik 		 * We can do this because the data reloc inode refers strictly
43004577b014SJosef Bacik 		 * to the on disk bytes, so we don't have to worry about
43014577b014SJosef Bacik 		 * disk_len vs real len like with real inodes since it's all
43024577b014SJosef Bacik 		 * disk length.
43034577b014SJosef Bacik 		 */
4304bffe633eSOmar Sandoval 		new_bytenr = ordered->disk_bytenr + sums->bytenr - disk_bytenr;
43054577b014SJosef Bacik 		sums->bytenr = new_bytenr;
43065d4f98a2SYan Zheng 
4307f9756261SNikolay Borisov 		btrfs_add_ordered_sum(ordered, sums);
43085d4f98a2SYan Zheng 	}
430979787eaaSJeff Mahoney out:
43105d4f98a2SYan Zheng 	btrfs_put_ordered_extent(ordered);
4311411fc6bcSAndi Kleen 	return ret;
43125d4f98a2SYan Zheng }
43133fd0a558SYan, Zheng 
431483d4cfd4SJosef Bacik int btrfs_reloc_cow_block(struct btrfs_trans_handle *trans,
43153fd0a558SYan, Zheng 			  struct btrfs_root *root, struct extent_buffer *buf,
43163fd0a558SYan, Zheng 			  struct extent_buffer *cow)
43173fd0a558SYan, Zheng {
43180b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
43193fd0a558SYan, Zheng 	struct reloc_control *rc;
4320a26195a5SQu Wenruo 	struct btrfs_backref_node *node;
43213fd0a558SYan, Zheng 	int first_cow = 0;
43223fd0a558SYan, Zheng 	int level;
432383d4cfd4SJosef Bacik 	int ret = 0;
43243fd0a558SYan, Zheng 
43250b246afaSJeff Mahoney 	rc = fs_info->reloc_ctl;
43263fd0a558SYan, Zheng 	if (!rc)
432783d4cfd4SJosef Bacik 		return 0;
43283fd0a558SYan, Zheng 
43293fd0a558SYan, Zheng 	BUG_ON(rc->stage == UPDATE_DATA_PTRS &&
43303fd0a558SYan, Zheng 	       root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID);
43313fd0a558SYan, Zheng 
43323fd0a558SYan, Zheng 	level = btrfs_header_level(buf);
43333fd0a558SYan, Zheng 	if (btrfs_header_generation(buf) <=
43343fd0a558SYan, Zheng 	    btrfs_root_last_snapshot(&root->root_item))
43353fd0a558SYan, Zheng 		first_cow = 1;
43363fd0a558SYan, Zheng 
43373fd0a558SYan, Zheng 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID &&
43383fd0a558SYan, Zheng 	    rc->create_reloc_tree) {
43393fd0a558SYan, Zheng 		WARN_ON(!first_cow && level == 0);
43403fd0a558SYan, Zheng 
43413fd0a558SYan, Zheng 		node = rc->backref_cache.path[level];
43423fd0a558SYan, Zheng 		BUG_ON(node->bytenr != buf->start &&
43433fd0a558SYan, Zheng 		       node->new_bytenr != buf->start);
43443fd0a558SYan, Zheng 
4345b0fe7078SQu Wenruo 		btrfs_backref_drop_node_buffer(node);
434667439dadSDavid Sterba 		atomic_inc(&cow->refs);
43473fd0a558SYan, Zheng 		node->eb = cow;
43483fd0a558SYan, Zheng 		node->new_bytenr = cow->start;
43493fd0a558SYan, Zheng 
43503fd0a558SYan, Zheng 		if (!node->pending) {
43513fd0a558SYan, Zheng 			list_move_tail(&node->list,
43523fd0a558SYan, Zheng 				       &rc->backref_cache.pending[level]);
43533fd0a558SYan, Zheng 			node->pending = 1;
43543fd0a558SYan, Zheng 		}
43553fd0a558SYan, Zheng 
43563fd0a558SYan, Zheng 		if (first_cow)
43579569cc20SQu Wenruo 			mark_block_processed(rc, node);
43583fd0a558SYan, Zheng 
43593fd0a558SYan, Zheng 		if (first_cow && level > 0)
43603fd0a558SYan, Zheng 			rc->nodes_relocated += buf->len;
43613fd0a558SYan, Zheng 	}
43623fd0a558SYan, Zheng 
436383d4cfd4SJosef Bacik 	if (level == 0 && first_cow && rc->stage == UPDATE_DATA_PTRS)
43643fd0a558SYan, Zheng 		ret = replace_file_extents(trans, rc, root, cow);
436583d4cfd4SJosef Bacik 	return ret;
43663fd0a558SYan, Zheng }
43673fd0a558SYan, Zheng 
43683fd0a558SYan, Zheng /*
43693fd0a558SYan, Zheng  * called before creating snapshot. it calculates metadata reservation
437001327610SNicholas D Steeves  * required for relocating tree blocks in the snapshot
43713fd0a558SYan, Zheng  */
4372147d256eSZhaolei void btrfs_reloc_pre_snapshot(struct btrfs_pending_snapshot *pending,
43733fd0a558SYan, Zheng 			      u64 *bytes_to_reserve)
43743fd0a558SYan, Zheng {
437510995c04SQu Wenruo 	struct btrfs_root *root = pending->root;
437610995c04SQu Wenruo 	struct reloc_control *rc = root->fs_info->reloc_ctl;
43773fd0a558SYan, Zheng 
43786282675eSQu Wenruo 	if (!rc || !have_reloc_root(root))
43793fd0a558SYan, Zheng 		return;
43803fd0a558SYan, Zheng 
43813fd0a558SYan, Zheng 	if (!rc->merge_reloc_tree)
43823fd0a558SYan, Zheng 		return;
43833fd0a558SYan, Zheng 
43843fd0a558SYan, Zheng 	root = root->reloc_root;
43853fd0a558SYan, Zheng 	BUG_ON(btrfs_root_refs(&root->root_item) == 0);
43863fd0a558SYan, Zheng 	/*
43873fd0a558SYan, Zheng 	 * relocation is in the stage of merging trees. the space
43883fd0a558SYan, Zheng 	 * used by merging a reloc tree is twice the size of
43893fd0a558SYan, Zheng 	 * relocated tree nodes in the worst case. half for cowing
43903fd0a558SYan, Zheng 	 * the reloc tree, half for cowing the fs tree. the space
43913fd0a558SYan, Zheng 	 * used by cowing the reloc tree will be freed after the
43923fd0a558SYan, Zheng 	 * tree is dropped. if we create snapshot, cowing the fs
43933fd0a558SYan, Zheng 	 * tree may use more space than it frees. so we need
43943fd0a558SYan, Zheng 	 * reserve extra space.
43953fd0a558SYan, Zheng 	 */
43963fd0a558SYan, Zheng 	*bytes_to_reserve += rc->nodes_relocated;
43973fd0a558SYan, Zheng }
43983fd0a558SYan, Zheng 
43993fd0a558SYan, Zheng /*
44003fd0a558SYan, Zheng  * called after snapshot is created. migrate block reservation
44013fd0a558SYan, Zheng  * and create reloc root for the newly created snapshot
4402f44deb74SJosef Bacik  *
4403f44deb74SJosef Bacik  * This is similar to btrfs_init_reloc_root(), we come out of here with two
4404f44deb74SJosef Bacik  * references held on the reloc_root, one for root->reloc_root and one for
4405f44deb74SJosef Bacik  * rc->reloc_roots.
44063fd0a558SYan, Zheng  */
440749b25e05SJeff Mahoney int btrfs_reloc_post_snapshot(struct btrfs_trans_handle *trans,
44083fd0a558SYan, Zheng 			       struct btrfs_pending_snapshot *pending)
44093fd0a558SYan, Zheng {
44103fd0a558SYan, Zheng 	struct btrfs_root *root = pending->root;
44113fd0a558SYan, Zheng 	struct btrfs_root *reloc_root;
44123fd0a558SYan, Zheng 	struct btrfs_root *new_root;
441310995c04SQu Wenruo 	struct reloc_control *rc = root->fs_info->reloc_ctl;
44143fd0a558SYan, Zheng 	int ret;
44153fd0a558SYan, Zheng 
44166282675eSQu Wenruo 	if (!rc || !have_reloc_root(root))
441749b25e05SJeff Mahoney 		return 0;
44183fd0a558SYan, Zheng 
44193fd0a558SYan, Zheng 	rc = root->fs_info->reloc_ctl;
44203fd0a558SYan, Zheng 	rc->merging_rsv_size += rc->nodes_relocated;
44213fd0a558SYan, Zheng 
44223fd0a558SYan, Zheng 	if (rc->merge_reloc_tree) {
44233fd0a558SYan, Zheng 		ret = btrfs_block_rsv_migrate(&pending->block_rsv,
44243fd0a558SYan, Zheng 					      rc->block_rsv,
44253a584174SLu Fengqi 					      rc->nodes_relocated, true);
442649b25e05SJeff Mahoney 		if (ret)
442749b25e05SJeff Mahoney 			return ret;
44283fd0a558SYan, Zheng 	}
44293fd0a558SYan, Zheng 
44303fd0a558SYan, Zheng 	new_root = pending->snap;
44313fd0a558SYan, Zheng 	reloc_root = create_reloc_root(trans, root->reloc_root,
44323fd0a558SYan, Zheng 				       new_root->root_key.objectid);
443349b25e05SJeff Mahoney 	if (IS_ERR(reloc_root))
443449b25e05SJeff Mahoney 		return PTR_ERR(reloc_root);
44353fd0a558SYan, Zheng 
4436ffd7b339SJeff Mahoney 	ret = __add_reloc_root(reloc_root);
443757a304cfSJosef Bacik 	ASSERT(ret != -EEXIST);
44383c925863SJosef Bacik 	if (ret) {
44393c925863SJosef Bacik 		/* Pairs with create_reloc_root */
44403c925863SJosef Bacik 		btrfs_put_root(reloc_root);
44413c925863SJosef Bacik 		return ret;
44423c925863SJosef Bacik 	}
4443f44deb74SJosef Bacik 	new_root->reloc_root = btrfs_grab_root(reloc_root);
44443fd0a558SYan, Zheng 
444549b25e05SJeff Mahoney 	if (rc->create_reloc_tree)
44463fd0a558SYan, Zheng 		ret = clone_backref_node(trans, rc, root, reloc_root);
444749b25e05SJeff Mahoney 	return ret;
44483fd0a558SYan, Zheng }
4449