xref: /linux/fs/btrfs/relocation.c (revision d2a4a07190f42e4f82805daf58e708400b703f1c)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2009 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/sched.h>
7 #include <linux/pagemap.h>
8 #include <linux/writeback.h>
9 #include <linux/blkdev.h>
10 #include <linux/rbtree.h>
11 #include <linux/slab.h>
12 #include <linux/error-injection.h>
13 #include "ctree.h"
14 #include "disk-io.h"
15 #include "transaction.h"
16 #include "volumes.h"
17 #include "locking.h"
18 #include "btrfs_inode.h"
19 #include "async-thread.h"
20 #include "free-space-cache.h"
21 #include "qgroup.h"
22 #include "print-tree.h"
23 #include "delalloc-space.h"
24 #include "block-group.h"
25 #include "backref.h"
26 #include "misc.h"
27 #include "subpage.h"
28 #include "zoned.h"
29 #include "inode-item.h"
30 #include "space-info.h"
31 #include "fs.h"
32 #include "accessors.h"
33 #include "extent-tree.h"
34 #include "root-tree.h"
35 #include "file-item.h"
36 #include "relocation.h"
37 #include "super.h"
38 #include "tree-checker.h"
39 
40 /*
41  * Relocation overview
42  *
43  * [What does relocation do]
44  *
45  * The objective of relocation is to relocate all extents of the target block
46  * group to other block groups.
47  * This is utilized by resize (shrink only), profile converting, compacting
48  * space, or balance routine to spread chunks over devices.
49  *
50  * 		Before		|		After
51  * ------------------------------------------------------------------
52  *  BG A: 10 data extents	| BG A: deleted
53  *  BG B:  2 data extents	| BG B: 10 data extents (2 old + 8 relocated)
54  *  BG C:  1 extents		| BG C:  3 data extents (1 old + 2 relocated)
55  *
56  * [How does relocation work]
57  *
58  * 1.   Mark the target block group read-only
59  *      New extents won't be allocated from the target block group.
60  *
61  * 2.1  Record each extent in the target block group
62  *      To build a proper map of extents to be relocated.
63  *
64  * 2.2  Build data reloc tree and reloc trees
65  *      Data reloc tree will contain an inode, recording all newly relocated
66  *      data extents.
67  *      There will be only one data reloc tree for one data block group.
68  *
69  *      Reloc tree will be a special snapshot of its source tree, containing
70  *      relocated tree blocks.
71  *      Each tree referring to a tree block in target block group will get its
72  *      reloc tree built.
73  *
74  * 2.3  Swap source tree with its corresponding reloc tree
75  *      Each involved tree only refers to new extents after swap.
76  *
77  * 3.   Cleanup reloc trees and data reloc tree.
78  *      As old extents in the target block group are still referenced by reloc
79  *      trees, we need to clean them up before really freeing the target block
80  *      group.
81  *
82  * The main complexity is in steps 2.2 and 2.3.
83  *
84  * The entry point of relocation is relocate_block_group() function.
85  */
86 
87 #define RELOCATION_RESERVED_NODES	256
88 /*
89  * map address of tree root to tree
90  */
91 struct mapping_node {
92 	struct {
93 		struct rb_node rb_node;
94 		u64 bytenr;
95 	}; /* Use rb_simle_node for search/insert */
96 	void *data;
97 };
98 
99 struct mapping_tree {
100 	struct rb_root rb_root;
101 	spinlock_t lock;
102 };
103 
104 /*
105  * present a tree block to process
106  */
107 struct tree_block {
108 	struct {
109 		struct rb_node rb_node;
110 		u64 bytenr;
111 	}; /* Use rb_simple_node for search/insert */
112 	u64 owner;
113 	struct btrfs_key key;
114 	u8 level;
115 	bool key_ready;
116 };
117 
118 #define MAX_EXTENTS 128
119 
120 struct file_extent_cluster {
121 	u64 start;
122 	u64 end;
123 	u64 boundary[MAX_EXTENTS];
124 	unsigned int nr;
125 	u64 owning_root;
126 };
127 
128 /* Stages of data relocation. */
129 enum reloc_stage {
130 	MOVE_DATA_EXTENTS,
131 	UPDATE_DATA_PTRS
132 };
133 
134 struct reloc_control {
135 	/* block group to relocate */
136 	struct btrfs_block_group *block_group;
137 	/* extent tree */
138 	struct btrfs_root *extent_root;
139 	/* inode for moving data */
140 	struct inode *data_inode;
141 
142 	struct btrfs_block_rsv *block_rsv;
143 
144 	struct btrfs_backref_cache backref_cache;
145 
146 	struct file_extent_cluster cluster;
147 	/* tree blocks have been processed */
148 	struct extent_io_tree processed_blocks;
149 	/* map start of tree root to corresponding reloc tree */
150 	struct mapping_tree reloc_root_tree;
151 	/* list of reloc trees */
152 	struct list_head reloc_roots;
153 	/* list of subvolume trees that get relocated */
154 	struct list_head dirty_subvol_roots;
155 	/* size of metadata reservation for merging reloc trees */
156 	u64 merging_rsv_size;
157 	/* size of relocated tree nodes */
158 	u64 nodes_relocated;
159 	/* reserved size for block group relocation*/
160 	u64 reserved_bytes;
161 
162 	u64 search_start;
163 	u64 extents_found;
164 
165 	enum reloc_stage stage;
166 	bool create_reloc_tree;
167 	bool merge_reloc_tree;
168 	bool found_file_extent;
169 };
170 
171 static void mark_block_processed(struct reloc_control *rc,
172 				 struct btrfs_backref_node *node)
173 {
174 	u32 blocksize;
175 
176 	if (node->level == 0 ||
177 	    in_range(node->bytenr, rc->block_group->start,
178 		     rc->block_group->length)) {
179 		blocksize = rc->extent_root->fs_info->nodesize;
180 		set_extent_bit(&rc->processed_blocks, node->bytenr,
181 			       node->bytenr + blocksize - 1, EXTENT_DIRTY, NULL);
182 	}
183 	node->processed = 1;
184 }
185 
186 /*
187  * walk up backref nodes until reach node presents tree root
188  */
189 static struct btrfs_backref_node *walk_up_backref(
190 		struct btrfs_backref_node *node,
191 		struct btrfs_backref_edge *edges[], int *index)
192 {
193 	struct btrfs_backref_edge *edge;
194 	int idx = *index;
195 
196 	while (!list_empty(&node->upper)) {
197 		edge = list_entry(node->upper.next,
198 				  struct btrfs_backref_edge, list[LOWER]);
199 		edges[idx++] = edge;
200 		node = edge->node[UPPER];
201 	}
202 	BUG_ON(node->detached);
203 	*index = idx;
204 	return node;
205 }
206 
207 /*
208  * walk down backref nodes to find start of next reference path
209  */
210 static struct btrfs_backref_node *walk_down_backref(
211 		struct btrfs_backref_edge *edges[], int *index)
212 {
213 	struct btrfs_backref_edge *edge;
214 	struct btrfs_backref_node *lower;
215 	int idx = *index;
216 
217 	while (idx > 0) {
218 		edge = edges[idx - 1];
219 		lower = edge->node[LOWER];
220 		if (list_is_last(&edge->list[LOWER], &lower->upper)) {
221 			idx--;
222 			continue;
223 		}
224 		edge = list_entry(edge->list[LOWER].next,
225 				  struct btrfs_backref_edge, list[LOWER]);
226 		edges[idx - 1] = edge;
227 		*index = idx;
228 		return edge->node[UPPER];
229 	}
230 	*index = 0;
231 	return NULL;
232 }
233 
234 static void update_backref_node(struct btrfs_backref_cache *cache,
235 				struct btrfs_backref_node *node, u64 bytenr)
236 {
237 	struct rb_node *rb_node;
238 	rb_erase(&node->rb_node, &cache->rb_root);
239 	node->bytenr = bytenr;
240 	rb_node = rb_simple_insert(&cache->rb_root, node->bytenr, &node->rb_node);
241 	if (rb_node)
242 		btrfs_backref_panic(cache->fs_info, bytenr, -EEXIST);
243 }
244 
245 /*
246  * update backref cache after a transaction commit
247  */
248 static int update_backref_cache(struct btrfs_trans_handle *trans,
249 				struct btrfs_backref_cache *cache)
250 {
251 	struct btrfs_backref_node *node;
252 	int level = 0;
253 
254 	if (cache->last_trans == 0) {
255 		cache->last_trans = trans->transid;
256 		return 0;
257 	}
258 
259 	if (cache->last_trans == trans->transid)
260 		return 0;
261 
262 	/*
263 	 * detached nodes are used to avoid unnecessary backref
264 	 * lookup. transaction commit changes the extent tree.
265 	 * so the detached nodes are no longer useful.
266 	 */
267 	while (!list_empty(&cache->detached)) {
268 		node = list_entry(cache->detached.next,
269 				  struct btrfs_backref_node, list);
270 		btrfs_backref_cleanup_node(cache, node);
271 	}
272 
273 	while (!list_empty(&cache->changed)) {
274 		node = list_entry(cache->changed.next,
275 				  struct btrfs_backref_node, list);
276 		list_del_init(&node->list);
277 		BUG_ON(node->pending);
278 		update_backref_node(cache, node, node->new_bytenr);
279 	}
280 
281 	/*
282 	 * some nodes can be left in the pending list if there were
283 	 * errors during processing the pending nodes.
284 	 */
285 	for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
286 		list_for_each_entry(node, &cache->pending[level], list) {
287 			BUG_ON(!node->pending);
288 			if (node->bytenr == node->new_bytenr)
289 				continue;
290 			update_backref_node(cache, node, node->new_bytenr);
291 		}
292 	}
293 
294 	cache->last_trans = 0;
295 	return 1;
296 }
297 
298 static bool reloc_root_is_dead(const struct btrfs_root *root)
299 {
300 	/*
301 	 * Pair with set_bit/clear_bit in clean_dirty_subvols and
302 	 * btrfs_update_reloc_root. We need to see the updated bit before
303 	 * trying to access reloc_root
304 	 */
305 	smp_rmb();
306 	if (test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state))
307 		return true;
308 	return false;
309 }
310 
311 /*
312  * Check if this subvolume tree has valid reloc tree.
313  *
314  * Reloc tree after swap is considered dead, thus not considered as valid.
315  * This is enough for most callers, as they don't distinguish dead reloc root
316  * from no reloc root.  But btrfs_should_ignore_reloc_root() below is a
317  * special case.
318  */
319 static bool have_reloc_root(const struct btrfs_root *root)
320 {
321 	if (reloc_root_is_dead(root))
322 		return false;
323 	if (!root->reloc_root)
324 		return false;
325 	return true;
326 }
327 
328 bool btrfs_should_ignore_reloc_root(const struct btrfs_root *root)
329 {
330 	struct btrfs_root *reloc_root;
331 
332 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
333 		return false;
334 
335 	/* This root has been merged with its reloc tree, we can ignore it */
336 	if (reloc_root_is_dead(root))
337 		return true;
338 
339 	reloc_root = root->reloc_root;
340 	if (!reloc_root)
341 		return false;
342 
343 	if (btrfs_header_generation(reloc_root->commit_root) ==
344 	    root->fs_info->running_transaction->transid)
345 		return false;
346 	/*
347 	 * If there is reloc tree and it was created in previous transaction
348 	 * backref lookup can find the reloc tree, so backref node for the fs
349 	 * tree root is useless for relocation.
350 	 */
351 	return true;
352 }
353 
354 /*
355  * find reloc tree by address of tree root
356  */
357 struct btrfs_root *find_reloc_root(struct btrfs_fs_info *fs_info, u64 bytenr)
358 {
359 	struct reloc_control *rc = fs_info->reloc_ctl;
360 	struct rb_node *rb_node;
361 	struct mapping_node *node;
362 	struct btrfs_root *root = NULL;
363 
364 	ASSERT(rc);
365 	spin_lock(&rc->reloc_root_tree.lock);
366 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root, bytenr);
367 	if (rb_node) {
368 		node = rb_entry(rb_node, struct mapping_node, rb_node);
369 		root = node->data;
370 	}
371 	spin_unlock(&rc->reloc_root_tree.lock);
372 	return btrfs_grab_root(root);
373 }
374 
375 /*
376  * For useless nodes, do two major clean ups:
377  *
378  * - Cleanup the children edges and nodes
379  *   If child node is also orphan (no parent) during cleanup, then the child
380  *   node will also be cleaned up.
381  *
382  * - Freeing up leaves (level 0), keeps nodes detached
383  *   For nodes, the node is still cached as "detached"
384  *
385  * Return false if @node is not in the @useless_nodes list.
386  * Return true if @node is in the @useless_nodes list.
387  */
388 static bool handle_useless_nodes(struct reloc_control *rc,
389 				 struct btrfs_backref_node *node)
390 {
391 	struct btrfs_backref_cache *cache = &rc->backref_cache;
392 	struct list_head *useless_node = &cache->useless_node;
393 	bool ret = false;
394 
395 	while (!list_empty(useless_node)) {
396 		struct btrfs_backref_node *cur;
397 
398 		cur = list_first_entry(useless_node, struct btrfs_backref_node,
399 				 list);
400 		list_del_init(&cur->list);
401 
402 		/* Only tree root nodes can be added to @useless_nodes */
403 		ASSERT(list_empty(&cur->upper));
404 
405 		if (cur == node)
406 			ret = true;
407 
408 		/* The node is the lowest node */
409 		if (cur->lowest) {
410 			list_del_init(&cur->lower);
411 			cur->lowest = 0;
412 		}
413 
414 		/* Cleanup the lower edges */
415 		while (!list_empty(&cur->lower)) {
416 			struct btrfs_backref_edge *edge;
417 			struct btrfs_backref_node *lower;
418 
419 			edge = list_entry(cur->lower.next,
420 					struct btrfs_backref_edge, list[UPPER]);
421 			list_del(&edge->list[UPPER]);
422 			list_del(&edge->list[LOWER]);
423 			lower = edge->node[LOWER];
424 			btrfs_backref_free_edge(cache, edge);
425 
426 			/* Child node is also orphan, queue for cleanup */
427 			if (list_empty(&lower->upper))
428 				list_add(&lower->list, useless_node);
429 		}
430 		/* Mark this block processed for relocation */
431 		mark_block_processed(rc, cur);
432 
433 		/*
434 		 * Backref nodes for tree leaves are deleted from the cache.
435 		 * Backref nodes for upper level tree blocks are left in the
436 		 * cache to avoid unnecessary backref lookup.
437 		 */
438 		if (cur->level > 0) {
439 			list_add(&cur->list, &cache->detached);
440 			cur->detached = 1;
441 		} else {
442 			rb_erase(&cur->rb_node, &cache->rb_root);
443 			btrfs_backref_free_node(cache, cur);
444 		}
445 	}
446 	return ret;
447 }
448 
449 /*
450  * Build backref tree for a given tree block. Root of the backref tree
451  * corresponds the tree block, leaves of the backref tree correspond roots of
452  * b-trees that reference the tree block.
453  *
454  * The basic idea of this function is check backrefs of a given block to find
455  * upper level blocks that reference the block, and then check backrefs of
456  * these upper level blocks recursively. The recursion stops when tree root is
457  * reached or backrefs for the block is cached.
458  *
459  * NOTE: if we find that backrefs for a block are cached, we know backrefs for
460  * all upper level blocks that directly/indirectly reference the block are also
461  * cached.
462  */
463 static noinline_for_stack struct btrfs_backref_node *build_backref_tree(
464 			struct btrfs_trans_handle *trans,
465 			struct reloc_control *rc, struct btrfs_key *node_key,
466 			int level, u64 bytenr)
467 {
468 	struct btrfs_backref_iter *iter;
469 	struct btrfs_backref_cache *cache = &rc->backref_cache;
470 	/* For searching parent of TREE_BLOCK_REF */
471 	struct btrfs_path *path;
472 	struct btrfs_backref_node *cur;
473 	struct btrfs_backref_node *node = NULL;
474 	struct btrfs_backref_edge *edge;
475 	int ret;
476 
477 	iter = btrfs_backref_iter_alloc(rc->extent_root->fs_info);
478 	if (!iter)
479 		return ERR_PTR(-ENOMEM);
480 	path = btrfs_alloc_path();
481 	if (!path) {
482 		ret = -ENOMEM;
483 		goto out;
484 	}
485 
486 	node = btrfs_backref_alloc_node(cache, bytenr, level);
487 	if (!node) {
488 		ret = -ENOMEM;
489 		goto out;
490 	}
491 
492 	node->lowest = 1;
493 	cur = node;
494 
495 	/* Breadth-first search to build backref cache */
496 	do {
497 		ret = btrfs_backref_add_tree_node(trans, cache, path, iter,
498 						  node_key, cur);
499 		if (ret < 0)
500 			goto out;
501 
502 		edge = list_first_entry_or_null(&cache->pending_edge,
503 				struct btrfs_backref_edge, list[UPPER]);
504 		/*
505 		 * The pending list isn't empty, take the first block to
506 		 * process
507 		 */
508 		if (edge) {
509 			list_del_init(&edge->list[UPPER]);
510 			cur = edge->node[UPPER];
511 		}
512 	} while (edge);
513 
514 	/* Finish the upper linkage of newly added edges/nodes */
515 	ret = btrfs_backref_finish_upper_links(cache, node);
516 	if (ret < 0)
517 		goto out;
518 
519 	if (handle_useless_nodes(rc, node))
520 		node = NULL;
521 out:
522 	btrfs_free_path(iter->path);
523 	kfree(iter);
524 	btrfs_free_path(path);
525 	if (ret) {
526 		btrfs_backref_error_cleanup(cache, node);
527 		return ERR_PTR(ret);
528 	}
529 	ASSERT(!node || !node->detached);
530 	ASSERT(list_empty(&cache->useless_node) &&
531 	       list_empty(&cache->pending_edge));
532 	return node;
533 }
534 
535 /*
536  * helper to add backref node for the newly created snapshot.
537  * the backref node is created by cloning backref node that
538  * corresponds to root of source tree
539  */
540 static int clone_backref_node(struct btrfs_trans_handle *trans,
541 			      struct reloc_control *rc,
542 			      const struct btrfs_root *src,
543 			      struct btrfs_root *dest)
544 {
545 	struct btrfs_root *reloc_root = src->reloc_root;
546 	struct btrfs_backref_cache *cache = &rc->backref_cache;
547 	struct btrfs_backref_node *node = NULL;
548 	struct btrfs_backref_node *new_node;
549 	struct btrfs_backref_edge *edge;
550 	struct btrfs_backref_edge *new_edge;
551 	struct rb_node *rb_node;
552 
553 	if (cache->last_trans > 0)
554 		update_backref_cache(trans, cache);
555 
556 	rb_node = rb_simple_search(&cache->rb_root, src->commit_root->start);
557 	if (rb_node) {
558 		node = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
559 		if (node->detached)
560 			node = NULL;
561 		else
562 			BUG_ON(node->new_bytenr != reloc_root->node->start);
563 	}
564 
565 	if (!node) {
566 		rb_node = rb_simple_search(&cache->rb_root,
567 					   reloc_root->commit_root->start);
568 		if (rb_node) {
569 			node = rb_entry(rb_node, struct btrfs_backref_node,
570 					rb_node);
571 			BUG_ON(node->detached);
572 		}
573 	}
574 
575 	if (!node)
576 		return 0;
577 
578 	new_node = btrfs_backref_alloc_node(cache, dest->node->start,
579 					    node->level);
580 	if (!new_node)
581 		return -ENOMEM;
582 
583 	new_node->lowest = node->lowest;
584 	new_node->checked = 1;
585 	new_node->root = btrfs_grab_root(dest);
586 	ASSERT(new_node->root);
587 
588 	if (!node->lowest) {
589 		list_for_each_entry(edge, &node->lower, list[UPPER]) {
590 			new_edge = btrfs_backref_alloc_edge(cache);
591 			if (!new_edge)
592 				goto fail;
593 
594 			btrfs_backref_link_edge(new_edge, edge->node[LOWER],
595 						new_node, LINK_UPPER);
596 		}
597 	} else {
598 		list_add_tail(&new_node->lower, &cache->leaves);
599 	}
600 
601 	rb_node = rb_simple_insert(&cache->rb_root, new_node->bytenr,
602 				   &new_node->rb_node);
603 	if (rb_node)
604 		btrfs_backref_panic(trans->fs_info, new_node->bytenr, -EEXIST);
605 
606 	if (!new_node->lowest) {
607 		list_for_each_entry(new_edge, &new_node->lower, list[UPPER]) {
608 			list_add_tail(&new_edge->list[LOWER],
609 				      &new_edge->node[LOWER]->upper);
610 		}
611 	}
612 	return 0;
613 fail:
614 	while (!list_empty(&new_node->lower)) {
615 		new_edge = list_entry(new_node->lower.next,
616 				      struct btrfs_backref_edge, list[UPPER]);
617 		list_del(&new_edge->list[UPPER]);
618 		btrfs_backref_free_edge(cache, new_edge);
619 	}
620 	btrfs_backref_free_node(cache, new_node);
621 	return -ENOMEM;
622 }
623 
624 /*
625  * helper to add 'address of tree root -> reloc tree' mapping
626  */
627 static int __add_reloc_root(struct btrfs_root *root)
628 {
629 	struct btrfs_fs_info *fs_info = root->fs_info;
630 	struct rb_node *rb_node;
631 	struct mapping_node *node;
632 	struct reloc_control *rc = fs_info->reloc_ctl;
633 
634 	node = kmalloc(sizeof(*node), GFP_NOFS);
635 	if (!node)
636 		return -ENOMEM;
637 
638 	node->bytenr = root->commit_root->start;
639 	node->data = root;
640 
641 	spin_lock(&rc->reloc_root_tree.lock);
642 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
643 				   node->bytenr, &node->rb_node);
644 	spin_unlock(&rc->reloc_root_tree.lock);
645 	if (rb_node) {
646 		btrfs_err(fs_info,
647 			    "Duplicate root found for start=%llu while inserting into relocation tree",
648 			    node->bytenr);
649 		return -EEXIST;
650 	}
651 
652 	list_add_tail(&root->root_list, &rc->reloc_roots);
653 	return 0;
654 }
655 
656 /*
657  * helper to delete the 'address of tree root -> reloc tree'
658  * mapping
659  */
660 static void __del_reloc_root(struct btrfs_root *root)
661 {
662 	struct btrfs_fs_info *fs_info = root->fs_info;
663 	struct rb_node *rb_node;
664 	struct mapping_node *node = NULL;
665 	struct reloc_control *rc = fs_info->reloc_ctl;
666 	bool put_ref = false;
667 
668 	if (rc && root->node) {
669 		spin_lock(&rc->reloc_root_tree.lock);
670 		rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
671 					   root->commit_root->start);
672 		if (rb_node) {
673 			node = rb_entry(rb_node, struct mapping_node, rb_node);
674 			rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
675 			RB_CLEAR_NODE(&node->rb_node);
676 		}
677 		spin_unlock(&rc->reloc_root_tree.lock);
678 		ASSERT(!node || (struct btrfs_root *)node->data == root);
679 	}
680 
681 	/*
682 	 * We only put the reloc root here if it's on the list.  There's a lot
683 	 * of places where the pattern is to splice the rc->reloc_roots, process
684 	 * the reloc roots, and then add the reloc root back onto
685 	 * rc->reloc_roots.  If we call __del_reloc_root while it's off of the
686 	 * list we don't want the reference being dropped, because the guy
687 	 * messing with the list is in charge of the reference.
688 	 */
689 	spin_lock(&fs_info->trans_lock);
690 	if (!list_empty(&root->root_list)) {
691 		put_ref = true;
692 		list_del_init(&root->root_list);
693 	}
694 	spin_unlock(&fs_info->trans_lock);
695 	if (put_ref)
696 		btrfs_put_root(root);
697 	kfree(node);
698 }
699 
700 /*
701  * helper to update the 'address of tree root -> reloc tree'
702  * mapping
703  */
704 static int __update_reloc_root(struct btrfs_root *root)
705 {
706 	struct btrfs_fs_info *fs_info = root->fs_info;
707 	struct rb_node *rb_node;
708 	struct mapping_node *node = NULL;
709 	struct reloc_control *rc = fs_info->reloc_ctl;
710 
711 	spin_lock(&rc->reloc_root_tree.lock);
712 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
713 				   root->commit_root->start);
714 	if (rb_node) {
715 		node = rb_entry(rb_node, struct mapping_node, rb_node);
716 		rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
717 	}
718 	spin_unlock(&rc->reloc_root_tree.lock);
719 
720 	if (!node)
721 		return 0;
722 	BUG_ON((struct btrfs_root *)node->data != root);
723 
724 	spin_lock(&rc->reloc_root_tree.lock);
725 	node->bytenr = root->node->start;
726 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
727 				   node->bytenr, &node->rb_node);
728 	spin_unlock(&rc->reloc_root_tree.lock);
729 	if (rb_node)
730 		btrfs_backref_panic(fs_info, node->bytenr, -EEXIST);
731 	return 0;
732 }
733 
734 static struct btrfs_root *create_reloc_root(struct btrfs_trans_handle *trans,
735 					struct btrfs_root *root, u64 objectid)
736 {
737 	struct btrfs_fs_info *fs_info = root->fs_info;
738 	struct btrfs_root *reloc_root;
739 	struct extent_buffer *eb;
740 	struct btrfs_root_item *root_item;
741 	struct btrfs_key root_key;
742 	int ret = 0;
743 	bool must_abort = false;
744 
745 	root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
746 	if (!root_item)
747 		return ERR_PTR(-ENOMEM);
748 
749 	root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
750 	root_key.type = BTRFS_ROOT_ITEM_KEY;
751 	root_key.offset = objectid;
752 
753 	if (btrfs_root_id(root) == objectid) {
754 		u64 commit_root_gen;
755 
756 		/* called by btrfs_init_reloc_root */
757 		ret = btrfs_copy_root(trans, root, root->commit_root, &eb,
758 				      BTRFS_TREE_RELOC_OBJECTID);
759 		if (ret)
760 			goto fail;
761 
762 		/*
763 		 * Set the last_snapshot field to the generation of the commit
764 		 * root - like this ctree.c:btrfs_block_can_be_shared() behaves
765 		 * correctly (returns true) when the relocation root is created
766 		 * either inside the critical section of a transaction commit
767 		 * (through transaction.c:qgroup_account_snapshot()) and when
768 		 * it's created before the transaction commit is started.
769 		 */
770 		commit_root_gen = btrfs_header_generation(root->commit_root);
771 		btrfs_set_root_last_snapshot(&root->root_item, commit_root_gen);
772 	} else {
773 		/*
774 		 * called by btrfs_reloc_post_snapshot_hook.
775 		 * the source tree is a reloc tree, all tree blocks
776 		 * modified after it was created have RELOC flag
777 		 * set in their headers. so it's OK to not update
778 		 * the 'last_snapshot'.
779 		 */
780 		ret = btrfs_copy_root(trans, root, root->node, &eb,
781 				      BTRFS_TREE_RELOC_OBJECTID);
782 		if (ret)
783 			goto fail;
784 	}
785 
786 	/*
787 	 * We have changed references at this point, we must abort the
788 	 * transaction if anything fails.
789 	 */
790 	must_abort = true;
791 
792 	memcpy(root_item, &root->root_item, sizeof(*root_item));
793 	btrfs_set_root_bytenr(root_item, eb->start);
794 	btrfs_set_root_level(root_item, btrfs_header_level(eb));
795 	btrfs_set_root_generation(root_item, trans->transid);
796 
797 	if (btrfs_root_id(root) == objectid) {
798 		btrfs_set_root_refs(root_item, 0);
799 		memset(&root_item->drop_progress, 0,
800 		       sizeof(struct btrfs_disk_key));
801 		btrfs_set_root_drop_level(root_item, 0);
802 	}
803 
804 	btrfs_tree_unlock(eb);
805 	free_extent_buffer(eb);
806 
807 	ret = btrfs_insert_root(trans, fs_info->tree_root,
808 				&root_key, root_item);
809 	if (ret)
810 		goto fail;
811 
812 	kfree(root_item);
813 
814 	reloc_root = btrfs_read_tree_root(fs_info->tree_root, &root_key);
815 	if (IS_ERR(reloc_root)) {
816 		ret = PTR_ERR(reloc_root);
817 		goto abort;
818 	}
819 	set_bit(BTRFS_ROOT_SHAREABLE, &reloc_root->state);
820 	reloc_root->last_trans = trans->transid;
821 	return reloc_root;
822 fail:
823 	kfree(root_item);
824 abort:
825 	if (must_abort)
826 		btrfs_abort_transaction(trans, ret);
827 	return ERR_PTR(ret);
828 }
829 
830 /*
831  * create reloc tree for a given fs tree. reloc tree is just a
832  * snapshot of the fs tree with special root objectid.
833  *
834  * The reloc_root comes out of here with two references, one for
835  * root->reloc_root, and another for being on the rc->reloc_roots list.
836  */
837 int btrfs_init_reloc_root(struct btrfs_trans_handle *trans,
838 			  struct btrfs_root *root)
839 {
840 	struct btrfs_fs_info *fs_info = root->fs_info;
841 	struct btrfs_root *reloc_root;
842 	struct reloc_control *rc = fs_info->reloc_ctl;
843 	struct btrfs_block_rsv *rsv;
844 	int clear_rsv = 0;
845 	int ret;
846 
847 	if (!rc)
848 		return 0;
849 
850 	/*
851 	 * The subvolume has reloc tree but the swap is finished, no need to
852 	 * create/update the dead reloc tree
853 	 */
854 	if (reloc_root_is_dead(root))
855 		return 0;
856 
857 	/*
858 	 * This is subtle but important.  We do not do
859 	 * record_root_in_transaction for reloc roots, instead we record their
860 	 * corresponding fs root, and then here we update the last trans for the
861 	 * reloc root.  This means that we have to do this for the entire life
862 	 * of the reloc root, regardless of which stage of the relocation we are
863 	 * in.
864 	 */
865 	if (root->reloc_root) {
866 		reloc_root = root->reloc_root;
867 		reloc_root->last_trans = trans->transid;
868 		return 0;
869 	}
870 
871 	/*
872 	 * We are merging reloc roots, we do not need new reloc trees.  Also
873 	 * reloc trees never need their own reloc tree.
874 	 */
875 	if (!rc->create_reloc_tree || btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
876 		return 0;
877 
878 	if (!trans->reloc_reserved) {
879 		rsv = trans->block_rsv;
880 		trans->block_rsv = rc->block_rsv;
881 		clear_rsv = 1;
882 	}
883 	reloc_root = create_reloc_root(trans, root, btrfs_root_id(root));
884 	if (clear_rsv)
885 		trans->block_rsv = rsv;
886 	if (IS_ERR(reloc_root))
887 		return PTR_ERR(reloc_root);
888 
889 	ret = __add_reloc_root(reloc_root);
890 	ASSERT(ret != -EEXIST);
891 	if (ret) {
892 		/* Pairs with create_reloc_root */
893 		btrfs_put_root(reloc_root);
894 		return ret;
895 	}
896 	root->reloc_root = btrfs_grab_root(reloc_root);
897 	return 0;
898 }
899 
900 /*
901  * update root item of reloc tree
902  */
903 int btrfs_update_reloc_root(struct btrfs_trans_handle *trans,
904 			    struct btrfs_root *root)
905 {
906 	struct btrfs_fs_info *fs_info = root->fs_info;
907 	struct btrfs_root *reloc_root;
908 	struct btrfs_root_item *root_item;
909 	int ret;
910 
911 	if (!have_reloc_root(root))
912 		return 0;
913 
914 	reloc_root = root->reloc_root;
915 	root_item = &reloc_root->root_item;
916 
917 	/*
918 	 * We are probably ok here, but __del_reloc_root() will drop its ref of
919 	 * the root.  We have the ref for root->reloc_root, but just in case
920 	 * hold it while we update the reloc root.
921 	 */
922 	btrfs_grab_root(reloc_root);
923 
924 	/* root->reloc_root will stay until current relocation finished */
925 	if (fs_info->reloc_ctl->merge_reloc_tree &&
926 	    btrfs_root_refs(root_item) == 0) {
927 		set_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
928 		/*
929 		 * Mark the tree as dead before we change reloc_root so
930 		 * have_reloc_root will not touch it from now on.
931 		 */
932 		smp_wmb();
933 		__del_reloc_root(reloc_root);
934 	}
935 
936 	if (reloc_root->commit_root != reloc_root->node) {
937 		__update_reloc_root(reloc_root);
938 		btrfs_set_root_node(root_item, reloc_root->node);
939 		free_extent_buffer(reloc_root->commit_root);
940 		reloc_root->commit_root = btrfs_root_node(reloc_root);
941 	}
942 
943 	ret = btrfs_update_root(trans, fs_info->tree_root,
944 				&reloc_root->root_key, root_item);
945 	btrfs_put_root(reloc_root);
946 	return ret;
947 }
948 
949 /*
950  * get new location of data
951  */
952 static int get_new_location(struct inode *reloc_inode, u64 *new_bytenr,
953 			    u64 bytenr, u64 num_bytes)
954 {
955 	struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
956 	struct btrfs_path *path;
957 	struct btrfs_file_extent_item *fi;
958 	struct extent_buffer *leaf;
959 	int ret;
960 
961 	path = btrfs_alloc_path();
962 	if (!path)
963 		return -ENOMEM;
964 
965 	bytenr -= BTRFS_I(reloc_inode)->index_cnt;
966 	ret = btrfs_lookup_file_extent(NULL, root, path,
967 			btrfs_ino(BTRFS_I(reloc_inode)), bytenr, 0);
968 	if (ret < 0)
969 		goto out;
970 	if (ret > 0) {
971 		ret = -ENOENT;
972 		goto out;
973 	}
974 
975 	leaf = path->nodes[0];
976 	fi = btrfs_item_ptr(leaf, path->slots[0],
977 			    struct btrfs_file_extent_item);
978 
979 	BUG_ON(btrfs_file_extent_offset(leaf, fi) ||
980 	       btrfs_file_extent_compression(leaf, fi) ||
981 	       btrfs_file_extent_encryption(leaf, fi) ||
982 	       btrfs_file_extent_other_encoding(leaf, fi));
983 
984 	if (num_bytes != btrfs_file_extent_disk_num_bytes(leaf, fi)) {
985 		ret = -EINVAL;
986 		goto out;
987 	}
988 
989 	*new_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
990 	ret = 0;
991 out:
992 	btrfs_free_path(path);
993 	return ret;
994 }
995 
996 /*
997  * update file extent items in the tree leaf to point to
998  * the new locations.
999  */
1000 static noinline_for_stack
1001 int replace_file_extents(struct btrfs_trans_handle *trans,
1002 			 struct reloc_control *rc,
1003 			 struct btrfs_root *root,
1004 			 struct extent_buffer *leaf)
1005 {
1006 	struct btrfs_fs_info *fs_info = root->fs_info;
1007 	struct btrfs_key key;
1008 	struct btrfs_file_extent_item *fi;
1009 	struct btrfs_inode *inode = NULL;
1010 	u64 parent;
1011 	u64 bytenr;
1012 	u64 new_bytenr = 0;
1013 	u64 num_bytes;
1014 	u64 end;
1015 	u32 nritems;
1016 	u32 i;
1017 	int ret = 0;
1018 	int first = 1;
1019 	int dirty = 0;
1020 
1021 	if (rc->stage != UPDATE_DATA_PTRS)
1022 		return 0;
1023 
1024 	/* reloc trees always use full backref */
1025 	if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
1026 		parent = leaf->start;
1027 	else
1028 		parent = 0;
1029 
1030 	nritems = btrfs_header_nritems(leaf);
1031 	for (i = 0; i < nritems; i++) {
1032 		struct btrfs_ref ref = { 0 };
1033 
1034 		cond_resched();
1035 		btrfs_item_key_to_cpu(leaf, &key, i);
1036 		if (key.type != BTRFS_EXTENT_DATA_KEY)
1037 			continue;
1038 		fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
1039 		if (btrfs_file_extent_type(leaf, fi) ==
1040 		    BTRFS_FILE_EXTENT_INLINE)
1041 			continue;
1042 		bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1043 		num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1044 		if (bytenr == 0)
1045 			continue;
1046 		if (!in_range(bytenr, rc->block_group->start,
1047 			      rc->block_group->length))
1048 			continue;
1049 
1050 		/*
1051 		 * if we are modifying block in fs tree, wait for read_folio
1052 		 * to complete and drop the extent cache
1053 		 */
1054 		if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID) {
1055 			if (first) {
1056 				inode = btrfs_find_first_inode(root, key.objectid);
1057 				first = 0;
1058 			} else if (inode && btrfs_ino(inode) < key.objectid) {
1059 				btrfs_add_delayed_iput(inode);
1060 				inode = btrfs_find_first_inode(root, key.objectid);
1061 			}
1062 			if (inode && btrfs_ino(inode) == key.objectid) {
1063 				struct extent_state *cached_state = NULL;
1064 
1065 				end = key.offset +
1066 				      btrfs_file_extent_num_bytes(leaf, fi);
1067 				WARN_ON(!IS_ALIGNED(key.offset,
1068 						    fs_info->sectorsize));
1069 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
1070 				end--;
1071 				/* Take mmap lock to serialize with reflinks. */
1072 				if (!down_read_trylock(&inode->i_mmap_lock))
1073 					continue;
1074 				ret = try_lock_extent(&inode->io_tree, key.offset,
1075 						      end, &cached_state);
1076 				if (!ret) {
1077 					up_read(&inode->i_mmap_lock);
1078 					continue;
1079 				}
1080 
1081 				btrfs_drop_extent_map_range(inode, key.offset, end, true);
1082 				unlock_extent(&inode->io_tree, key.offset, end,
1083 					      &cached_state);
1084 				up_read(&inode->i_mmap_lock);
1085 			}
1086 		}
1087 
1088 		ret = get_new_location(rc->data_inode, &new_bytenr,
1089 				       bytenr, num_bytes);
1090 		if (ret) {
1091 			/*
1092 			 * Don't have to abort since we've not changed anything
1093 			 * in the file extent yet.
1094 			 */
1095 			break;
1096 		}
1097 
1098 		btrfs_set_file_extent_disk_bytenr(leaf, fi, new_bytenr);
1099 		dirty = 1;
1100 
1101 		key.offset -= btrfs_file_extent_offset(leaf, fi);
1102 		ref.action = BTRFS_ADD_DELAYED_REF;
1103 		ref.bytenr = new_bytenr;
1104 		ref.num_bytes = num_bytes;
1105 		ref.parent = parent;
1106 		ref.owning_root = btrfs_root_id(root);
1107 		ref.ref_root = btrfs_header_owner(leaf);
1108 		btrfs_init_data_ref(&ref, key.objectid, key.offset,
1109 				    btrfs_root_id(root), false);
1110 		ret = btrfs_inc_extent_ref(trans, &ref);
1111 		if (ret) {
1112 			btrfs_abort_transaction(trans, ret);
1113 			break;
1114 		}
1115 
1116 		ref.action = BTRFS_DROP_DELAYED_REF;
1117 		ref.bytenr = bytenr;
1118 		ref.num_bytes = num_bytes;
1119 		ref.parent = parent;
1120 		ref.owning_root = btrfs_root_id(root);
1121 		ref.ref_root = btrfs_header_owner(leaf);
1122 		btrfs_init_data_ref(&ref, key.objectid, key.offset,
1123 				    btrfs_root_id(root), false);
1124 		ret = btrfs_free_extent(trans, &ref);
1125 		if (ret) {
1126 			btrfs_abort_transaction(trans, ret);
1127 			break;
1128 		}
1129 	}
1130 	if (dirty)
1131 		btrfs_mark_buffer_dirty(trans, leaf);
1132 	if (inode)
1133 		btrfs_add_delayed_iput(inode);
1134 	return ret;
1135 }
1136 
1137 static noinline_for_stack int memcmp_node_keys(const struct extent_buffer *eb,
1138 					       int slot, const struct btrfs_path *path,
1139 					       int level)
1140 {
1141 	struct btrfs_disk_key key1;
1142 	struct btrfs_disk_key key2;
1143 	btrfs_node_key(eb, &key1, slot);
1144 	btrfs_node_key(path->nodes[level], &key2, path->slots[level]);
1145 	return memcmp(&key1, &key2, sizeof(key1));
1146 }
1147 
1148 /*
1149  * try to replace tree blocks in fs tree with the new blocks
1150  * in reloc tree. tree blocks haven't been modified since the
1151  * reloc tree was create can be replaced.
1152  *
1153  * if a block was replaced, level of the block + 1 is returned.
1154  * if no block got replaced, 0 is returned. if there are other
1155  * errors, a negative error number is returned.
1156  */
1157 static noinline_for_stack
1158 int replace_path(struct btrfs_trans_handle *trans, struct reloc_control *rc,
1159 		 struct btrfs_root *dest, struct btrfs_root *src,
1160 		 struct btrfs_path *path, struct btrfs_key *next_key,
1161 		 int lowest_level, int max_level)
1162 {
1163 	struct btrfs_fs_info *fs_info = dest->fs_info;
1164 	struct extent_buffer *eb;
1165 	struct extent_buffer *parent;
1166 	struct btrfs_ref ref = { 0 };
1167 	struct btrfs_key key;
1168 	u64 old_bytenr;
1169 	u64 new_bytenr;
1170 	u64 old_ptr_gen;
1171 	u64 new_ptr_gen;
1172 	u64 last_snapshot;
1173 	u32 blocksize;
1174 	int cow = 0;
1175 	int level;
1176 	int ret;
1177 	int slot;
1178 
1179 	ASSERT(btrfs_root_id(src) == BTRFS_TREE_RELOC_OBJECTID);
1180 	ASSERT(btrfs_root_id(dest) != BTRFS_TREE_RELOC_OBJECTID);
1181 
1182 	last_snapshot = btrfs_root_last_snapshot(&src->root_item);
1183 again:
1184 	slot = path->slots[lowest_level];
1185 	btrfs_node_key_to_cpu(path->nodes[lowest_level], &key, slot);
1186 
1187 	eb = btrfs_lock_root_node(dest);
1188 	level = btrfs_header_level(eb);
1189 
1190 	if (level < lowest_level) {
1191 		btrfs_tree_unlock(eb);
1192 		free_extent_buffer(eb);
1193 		return 0;
1194 	}
1195 
1196 	if (cow) {
1197 		ret = btrfs_cow_block(trans, dest, eb, NULL, 0, &eb,
1198 				      BTRFS_NESTING_COW);
1199 		if (ret) {
1200 			btrfs_tree_unlock(eb);
1201 			free_extent_buffer(eb);
1202 			return ret;
1203 		}
1204 	}
1205 
1206 	if (next_key) {
1207 		next_key->objectid = (u64)-1;
1208 		next_key->type = (u8)-1;
1209 		next_key->offset = (u64)-1;
1210 	}
1211 
1212 	parent = eb;
1213 	while (1) {
1214 		level = btrfs_header_level(parent);
1215 		ASSERT(level >= lowest_level);
1216 
1217 		ret = btrfs_bin_search(parent, 0, &key, &slot);
1218 		if (ret < 0)
1219 			break;
1220 		if (ret && slot > 0)
1221 			slot--;
1222 
1223 		if (next_key && slot + 1 < btrfs_header_nritems(parent))
1224 			btrfs_node_key_to_cpu(parent, next_key, slot + 1);
1225 
1226 		old_bytenr = btrfs_node_blockptr(parent, slot);
1227 		blocksize = fs_info->nodesize;
1228 		old_ptr_gen = btrfs_node_ptr_generation(parent, slot);
1229 
1230 		if (level <= max_level) {
1231 			eb = path->nodes[level];
1232 			new_bytenr = btrfs_node_blockptr(eb,
1233 							path->slots[level]);
1234 			new_ptr_gen = btrfs_node_ptr_generation(eb,
1235 							path->slots[level]);
1236 		} else {
1237 			new_bytenr = 0;
1238 			new_ptr_gen = 0;
1239 		}
1240 
1241 		if (WARN_ON(new_bytenr > 0 && new_bytenr == old_bytenr)) {
1242 			ret = level;
1243 			break;
1244 		}
1245 
1246 		if (new_bytenr == 0 || old_ptr_gen > last_snapshot ||
1247 		    memcmp_node_keys(parent, slot, path, level)) {
1248 			if (level <= lowest_level) {
1249 				ret = 0;
1250 				break;
1251 			}
1252 
1253 			eb = btrfs_read_node_slot(parent, slot);
1254 			if (IS_ERR(eb)) {
1255 				ret = PTR_ERR(eb);
1256 				break;
1257 			}
1258 			btrfs_tree_lock(eb);
1259 			if (cow) {
1260 				ret = btrfs_cow_block(trans, dest, eb, parent,
1261 						      slot, &eb,
1262 						      BTRFS_NESTING_COW);
1263 				if (ret) {
1264 					btrfs_tree_unlock(eb);
1265 					free_extent_buffer(eb);
1266 					break;
1267 				}
1268 			}
1269 
1270 			btrfs_tree_unlock(parent);
1271 			free_extent_buffer(parent);
1272 
1273 			parent = eb;
1274 			continue;
1275 		}
1276 
1277 		if (!cow) {
1278 			btrfs_tree_unlock(parent);
1279 			free_extent_buffer(parent);
1280 			cow = 1;
1281 			goto again;
1282 		}
1283 
1284 		btrfs_node_key_to_cpu(path->nodes[level], &key,
1285 				      path->slots[level]);
1286 		btrfs_release_path(path);
1287 
1288 		path->lowest_level = level;
1289 		set_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &src->state);
1290 		ret = btrfs_search_slot(trans, src, &key, path, 0, 1);
1291 		clear_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &src->state);
1292 		path->lowest_level = 0;
1293 		if (ret) {
1294 			if (ret > 0)
1295 				ret = -ENOENT;
1296 			break;
1297 		}
1298 
1299 		/*
1300 		 * Info qgroup to trace both subtrees.
1301 		 *
1302 		 * We must trace both trees.
1303 		 * 1) Tree reloc subtree
1304 		 *    If not traced, we will leak data numbers
1305 		 * 2) Fs subtree
1306 		 *    If not traced, we will double count old data
1307 		 *
1308 		 * We don't scan the subtree right now, but only record
1309 		 * the swapped tree blocks.
1310 		 * The real subtree rescan is delayed until we have new
1311 		 * CoW on the subtree root node before transaction commit.
1312 		 */
1313 		ret = btrfs_qgroup_add_swapped_blocks(trans, dest,
1314 				rc->block_group, parent, slot,
1315 				path->nodes[level], path->slots[level],
1316 				last_snapshot);
1317 		if (ret < 0)
1318 			break;
1319 		/*
1320 		 * swap blocks in fs tree and reloc tree.
1321 		 */
1322 		btrfs_set_node_blockptr(parent, slot, new_bytenr);
1323 		btrfs_set_node_ptr_generation(parent, slot, new_ptr_gen);
1324 		btrfs_mark_buffer_dirty(trans, parent);
1325 
1326 		btrfs_set_node_blockptr(path->nodes[level],
1327 					path->slots[level], old_bytenr);
1328 		btrfs_set_node_ptr_generation(path->nodes[level],
1329 					      path->slots[level], old_ptr_gen);
1330 		btrfs_mark_buffer_dirty(trans, path->nodes[level]);
1331 
1332 		ref.action = BTRFS_ADD_DELAYED_REF;
1333 		ref.bytenr = old_bytenr;
1334 		ref.num_bytes = blocksize;
1335 		ref.parent = path->nodes[level]->start;
1336 		ref.owning_root = btrfs_root_id(src);
1337 		ref.ref_root = btrfs_root_id(src);
1338 		btrfs_init_tree_ref(&ref, level - 1, 0, true);
1339 		ret = btrfs_inc_extent_ref(trans, &ref);
1340 		if (ret) {
1341 			btrfs_abort_transaction(trans, ret);
1342 			break;
1343 		}
1344 
1345 		ref.action = BTRFS_ADD_DELAYED_REF;
1346 		ref.bytenr = new_bytenr;
1347 		ref.num_bytes = blocksize;
1348 		ref.parent = 0;
1349 		ref.owning_root = btrfs_root_id(dest);
1350 		ref.ref_root = btrfs_root_id(dest);
1351 		btrfs_init_tree_ref(&ref, level - 1, 0, true);
1352 		ret = btrfs_inc_extent_ref(trans, &ref);
1353 		if (ret) {
1354 			btrfs_abort_transaction(trans, ret);
1355 			break;
1356 		}
1357 
1358 		/* We don't know the real owning_root, use 0. */
1359 		ref.action = BTRFS_DROP_DELAYED_REF;
1360 		ref.bytenr = new_bytenr;
1361 		ref.num_bytes = blocksize;
1362 		ref.parent = path->nodes[level]->start;
1363 		ref.owning_root = 0;
1364 		ref.ref_root = btrfs_root_id(src);
1365 		btrfs_init_tree_ref(&ref, level - 1, 0, true);
1366 		ret = btrfs_free_extent(trans, &ref);
1367 		if (ret) {
1368 			btrfs_abort_transaction(trans, ret);
1369 			break;
1370 		}
1371 
1372 		/* We don't know the real owning_root, use 0. */
1373 		ref.action = BTRFS_DROP_DELAYED_REF;
1374 		ref.bytenr = old_bytenr;
1375 		ref.num_bytes = blocksize;
1376 		ref.parent = 0;
1377 		ref.owning_root = 0;
1378 		ref.ref_root = btrfs_root_id(dest);
1379 		btrfs_init_tree_ref(&ref, level - 1, 0, true);
1380 		ret = btrfs_free_extent(trans, &ref);
1381 		if (ret) {
1382 			btrfs_abort_transaction(trans, ret);
1383 			break;
1384 		}
1385 
1386 		btrfs_unlock_up_safe(path, 0);
1387 
1388 		ret = level;
1389 		break;
1390 	}
1391 	btrfs_tree_unlock(parent);
1392 	free_extent_buffer(parent);
1393 	return ret;
1394 }
1395 
1396 /*
1397  * helper to find next relocated block in reloc tree
1398  */
1399 static noinline_for_stack
1400 int walk_up_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
1401 		       int *level)
1402 {
1403 	struct extent_buffer *eb;
1404 	int i;
1405 	u64 last_snapshot;
1406 	u32 nritems;
1407 
1408 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
1409 
1410 	for (i = 0; i < *level; i++) {
1411 		free_extent_buffer(path->nodes[i]);
1412 		path->nodes[i] = NULL;
1413 	}
1414 
1415 	for (i = *level; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
1416 		eb = path->nodes[i];
1417 		nritems = btrfs_header_nritems(eb);
1418 		while (path->slots[i] + 1 < nritems) {
1419 			path->slots[i]++;
1420 			if (btrfs_node_ptr_generation(eb, path->slots[i]) <=
1421 			    last_snapshot)
1422 				continue;
1423 
1424 			*level = i;
1425 			return 0;
1426 		}
1427 		free_extent_buffer(path->nodes[i]);
1428 		path->nodes[i] = NULL;
1429 	}
1430 	return 1;
1431 }
1432 
1433 /*
1434  * walk down reloc tree to find relocated block of lowest level
1435  */
1436 static noinline_for_stack
1437 int walk_down_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
1438 			 int *level)
1439 {
1440 	struct extent_buffer *eb = NULL;
1441 	int i;
1442 	u64 ptr_gen = 0;
1443 	u64 last_snapshot;
1444 	u32 nritems;
1445 
1446 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
1447 
1448 	for (i = *level; i > 0; i--) {
1449 		eb = path->nodes[i];
1450 		nritems = btrfs_header_nritems(eb);
1451 		while (path->slots[i] < nritems) {
1452 			ptr_gen = btrfs_node_ptr_generation(eb, path->slots[i]);
1453 			if (ptr_gen > last_snapshot)
1454 				break;
1455 			path->slots[i]++;
1456 		}
1457 		if (path->slots[i] >= nritems) {
1458 			if (i == *level)
1459 				break;
1460 			*level = i + 1;
1461 			return 0;
1462 		}
1463 		if (i == 1) {
1464 			*level = i;
1465 			return 0;
1466 		}
1467 
1468 		eb = btrfs_read_node_slot(eb, path->slots[i]);
1469 		if (IS_ERR(eb))
1470 			return PTR_ERR(eb);
1471 		BUG_ON(btrfs_header_level(eb) != i - 1);
1472 		path->nodes[i - 1] = eb;
1473 		path->slots[i - 1] = 0;
1474 	}
1475 	return 1;
1476 }
1477 
1478 /*
1479  * invalidate extent cache for file extents whose key in range of
1480  * [min_key, max_key)
1481  */
1482 static int invalidate_extent_cache(struct btrfs_root *root,
1483 				   const struct btrfs_key *min_key,
1484 				   const struct btrfs_key *max_key)
1485 {
1486 	struct btrfs_fs_info *fs_info = root->fs_info;
1487 	struct btrfs_inode *inode = NULL;
1488 	u64 objectid;
1489 	u64 start, end;
1490 	u64 ino;
1491 
1492 	objectid = min_key->objectid;
1493 	while (1) {
1494 		struct extent_state *cached_state = NULL;
1495 
1496 		cond_resched();
1497 		if (inode)
1498 			iput(&inode->vfs_inode);
1499 
1500 		if (objectid > max_key->objectid)
1501 			break;
1502 
1503 		inode = btrfs_find_first_inode(root, objectid);
1504 		if (!inode)
1505 			break;
1506 		ino = btrfs_ino(inode);
1507 
1508 		if (ino > max_key->objectid) {
1509 			iput(&inode->vfs_inode);
1510 			break;
1511 		}
1512 
1513 		objectid = ino + 1;
1514 		if (!S_ISREG(inode->vfs_inode.i_mode))
1515 			continue;
1516 
1517 		if (unlikely(min_key->objectid == ino)) {
1518 			if (min_key->type > BTRFS_EXTENT_DATA_KEY)
1519 				continue;
1520 			if (min_key->type < BTRFS_EXTENT_DATA_KEY)
1521 				start = 0;
1522 			else {
1523 				start = min_key->offset;
1524 				WARN_ON(!IS_ALIGNED(start, fs_info->sectorsize));
1525 			}
1526 		} else {
1527 			start = 0;
1528 		}
1529 
1530 		if (unlikely(max_key->objectid == ino)) {
1531 			if (max_key->type < BTRFS_EXTENT_DATA_KEY)
1532 				continue;
1533 			if (max_key->type > BTRFS_EXTENT_DATA_KEY) {
1534 				end = (u64)-1;
1535 			} else {
1536 				if (max_key->offset == 0)
1537 					continue;
1538 				end = max_key->offset;
1539 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
1540 				end--;
1541 			}
1542 		} else {
1543 			end = (u64)-1;
1544 		}
1545 
1546 		/* the lock_extent waits for read_folio to complete */
1547 		lock_extent(&inode->io_tree, start, end, &cached_state);
1548 		btrfs_drop_extent_map_range(inode, start, end, true);
1549 		unlock_extent(&inode->io_tree, start, end, &cached_state);
1550 	}
1551 	return 0;
1552 }
1553 
1554 static int find_next_key(struct btrfs_path *path, int level,
1555 			 struct btrfs_key *key)
1556 
1557 {
1558 	while (level < BTRFS_MAX_LEVEL) {
1559 		if (!path->nodes[level])
1560 			break;
1561 		if (path->slots[level] + 1 <
1562 		    btrfs_header_nritems(path->nodes[level])) {
1563 			btrfs_node_key_to_cpu(path->nodes[level], key,
1564 					      path->slots[level] + 1);
1565 			return 0;
1566 		}
1567 		level++;
1568 	}
1569 	return 1;
1570 }
1571 
1572 /*
1573  * Insert current subvolume into reloc_control::dirty_subvol_roots
1574  */
1575 static int insert_dirty_subvol(struct btrfs_trans_handle *trans,
1576 			       struct reloc_control *rc,
1577 			       struct btrfs_root *root)
1578 {
1579 	struct btrfs_root *reloc_root = root->reloc_root;
1580 	struct btrfs_root_item *reloc_root_item;
1581 	int ret;
1582 
1583 	/* @root must be a subvolume tree root with a valid reloc tree */
1584 	ASSERT(btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID);
1585 	ASSERT(reloc_root);
1586 
1587 	reloc_root_item = &reloc_root->root_item;
1588 	memset(&reloc_root_item->drop_progress, 0,
1589 		sizeof(reloc_root_item->drop_progress));
1590 	btrfs_set_root_drop_level(reloc_root_item, 0);
1591 	btrfs_set_root_refs(reloc_root_item, 0);
1592 	ret = btrfs_update_reloc_root(trans, root);
1593 	if (ret)
1594 		return ret;
1595 
1596 	if (list_empty(&root->reloc_dirty_list)) {
1597 		btrfs_grab_root(root);
1598 		list_add_tail(&root->reloc_dirty_list, &rc->dirty_subvol_roots);
1599 	}
1600 
1601 	return 0;
1602 }
1603 
1604 static int clean_dirty_subvols(struct reloc_control *rc)
1605 {
1606 	struct btrfs_root *root;
1607 	struct btrfs_root *next;
1608 	int ret = 0;
1609 	int ret2;
1610 
1611 	list_for_each_entry_safe(root, next, &rc->dirty_subvol_roots,
1612 				 reloc_dirty_list) {
1613 		if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID) {
1614 			/* Merged subvolume, cleanup its reloc root */
1615 			struct btrfs_root *reloc_root = root->reloc_root;
1616 
1617 			list_del_init(&root->reloc_dirty_list);
1618 			root->reloc_root = NULL;
1619 			/*
1620 			 * Need barrier to ensure clear_bit() only happens after
1621 			 * root->reloc_root = NULL. Pairs with have_reloc_root.
1622 			 */
1623 			smp_wmb();
1624 			clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
1625 			if (reloc_root) {
1626 				/*
1627 				 * btrfs_drop_snapshot drops our ref we hold for
1628 				 * ->reloc_root.  If it fails however we must
1629 				 * drop the ref ourselves.
1630 				 */
1631 				ret2 = btrfs_drop_snapshot(reloc_root, 0, 1);
1632 				if (ret2 < 0) {
1633 					btrfs_put_root(reloc_root);
1634 					if (!ret)
1635 						ret = ret2;
1636 				}
1637 			}
1638 			btrfs_put_root(root);
1639 		} else {
1640 			/* Orphan reloc tree, just clean it up */
1641 			ret2 = btrfs_drop_snapshot(root, 0, 1);
1642 			if (ret2 < 0) {
1643 				btrfs_put_root(root);
1644 				if (!ret)
1645 					ret = ret2;
1646 			}
1647 		}
1648 	}
1649 	return ret;
1650 }
1651 
1652 /*
1653  * merge the relocated tree blocks in reloc tree with corresponding
1654  * fs tree.
1655  */
1656 static noinline_for_stack int merge_reloc_root(struct reloc_control *rc,
1657 					       struct btrfs_root *root)
1658 {
1659 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
1660 	struct btrfs_key key;
1661 	struct btrfs_key next_key;
1662 	struct btrfs_trans_handle *trans = NULL;
1663 	struct btrfs_root *reloc_root;
1664 	struct btrfs_root_item *root_item;
1665 	struct btrfs_path *path;
1666 	struct extent_buffer *leaf;
1667 	int reserve_level;
1668 	int level;
1669 	int max_level;
1670 	int replaced = 0;
1671 	int ret = 0;
1672 	u32 min_reserved;
1673 
1674 	path = btrfs_alloc_path();
1675 	if (!path)
1676 		return -ENOMEM;
1677 	path->reada = READA_FORWARD;
1678 
1679 	reloc_root = root->reloc_root;
1680 	root_item = &reloc_root->root_item;
1681 
1682 	if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
1683 		level = btrfs_root_level(root_item);
1684 		atomic_inc(&reloc_root->node->refs);
1685 		path->nodes[level] = reloc_root->node;
1686 		path->slots[level] = 0;
1687 	} else {
1688 		btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
1689 
1690 		level = btrfs_root_drop_level(root_item);
1691 		BUG_ON(level == 0);
1692 		path->lowest_level = level;
1693 		ret = btrfs_search_slot(NULL, reloc_root, &key, path, 0, 0);
1694 		path->lowest_level = 0;
1695 		if (ret < 0) {
1696 			btrfs_free_path(path);
1697 			return ret;
1698 		}
1699 
1700 		btrfs_node_key_to_cpu(path->nodes[level], &next_key,
1701 				      path->slots[level]);
1702 		WARN_ON(memcmp(&key, &next_key, sizeof(key)));
1703 
1704 		btrfs_unlock_up_safe(path, 0);
1705 	}
1706 
1707 	/*
1708 	 * In merge_reloc_root(), we modify the upper level pointer to swap the
1709 	 * tree blocks between reloc tree and subvolume tree.  Thus for tree
1710 	 * block COW, we COW at most from level 1 to root level for each tree.
1711 	 *
1712 	 * Thus the needed metadata size is at most root_level * nodesize,
1713 	 * and * 2 since we have two trees to COW.
1714 	 */
1715 	reserve_level = max_t(int, 1, btrfs_root_level(root_item));
1716 	min_reserved = fs_info->nodesize * reserve_level * 2;
1717 	memset(&next_key, 0, sizeof(next_key));
1718 
1719 	while (1) {
1720 		ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv,
1721 					     min_reserved,
1722 					     BTRFS_RESERVE_FLUSH_LIMIT);
1723 		if (ret)
1724 			goto out;
1725 		trans = btrfs_start_transaction(root, 0);
1726 		if (IS_ERR(trans)) {
1727 			ret = PTR_ERR(trans);
1728 			trans = NULL;
1729 			goto out;
1730 		}
1731 
1732 		/*
1733 		 * At this point we no longer have a reloc_control, so we can't
1734 		 * depend on btrfs_init_reloc_root to update our last_trans.
1735 		 *
1736 		 * But that's ok, we started the trans handle on our
1737 		 * corresponding fs_root, which means it's been added to the
1738 		 * dirty list.  At commit time we'll still call
1739 		 * btrfs_update_reloc_root() and update our root item
1740 		 * appropriately.
1741 		 */
1742 		reloc_root->last_trans = trans->transid;
1743 		trans->block_rsv = rc->block_rsv;
1744 
1745 		replaced = 0;
1746 		max_level = level;
1747 
1748 		ret = walk_down_reloc_tree(reloc_root, path, &level);
1749 		if (ret < 0)
1750 			goto out;
1751 		if (ret > 0)
1752 			break;
1753 
1754 		if (!find_next_key(path, level, &key) &&
1755 		    btrfs_comp_cpu_keys(&next_key, &key) >= 0) {
1756 			ret = 0;
1757 		} else {
1758 			ret = replace_path(trans, rc, root, reloc_root, path,
1759 					   &next_key, level, max_level);
1760 		}
1761 		if (ret < 0)
1762 			goto out;
1763 		if (ret > 0) {
1764 			level = ret;
1765 			btrfs_node_key_to_cpu(path->nodes[level], &key,
1766 					      path->slots[level]);
1767 			replaced = 1;
1768 		}
1769 
1770 		ret = walk_up_reloc_tree(reloc_root, path, &level);
1771 		if (ret > 0)
1772 			break;
1773 
1774 		BUG_ON(level == 0);
1775 		/*
1776 		 * save the merging progress in the drop_progress.
1777 		 * this is OK since root refs == 1 in this case.
1778 		 */
1779 		btrfs_node_key(path->nodes[level], &root_item->drop_progress,
1780 			       path->slots[level]);
1781 		btrfs_set_root_drop_level(root_item, level);
1782 
1783 		btrfs_end_transaction_throttle(trans);
1784 		trans = NULL;
1785 
1786 		btrfs_btree_balance_dirty(fs_info);
1787 
1788 		if (replaced && rc->stage == UPDATE_DATA_PTRS)
1789 			invalidate_extent_cache(root, &key, &next_key);
1790 	}
1791 
1792 	/*
1793 	 * handle the case only one block in the fs tree need to be
1794 	 * relocated and the block is tree root.
1795 	 */
1796 	leaf = btrfs_lock_root_node(root);
1797 	ret = btrfs_cow_block(trans, root, leaf, NULL, 0, &leaf,
1798 			      BTRFS_NESTING_COW);
1799 	btrfs_tree_unlock(leaf);
1800 	free_extent_buffer(leaf);
1801 out:
1802 	btrfs_free_path(path);
1803 
1804 	if (ret == 0) {
1805 		ret = insert_dirty_subvol(trans, rc, root);
1806 		if (ret)
1807 			btrfs_abort_transaction(trans, ret);
1808 	}
1809 
1810 	if (trans)
1811 		btrfs_end_transaction_throttle(trans);
1812 
1813 	btrfs_btree_balance_dirty(fs_info);
1814 
1815 	if (replaced && rc->stage == UPDATE_DATA_PTRS)
1816 		invalidate_extent_cache(root, &key, &next_key);
1817 
1818 	return ret;
1819 }
1820 
1821 static noinline_for_stack
1822 int prepare_to_merge(struct reloc_control *rc, int err)
1823 {
1824 	struct btrfs_root *root = rc->extent_root;
1825 	struct btrfs_fs_info *fs_info = root->fs_info;
1826 	struct btrfs_root *reloc_root;
1827 	struct btrfs_trans_handle *trans;
1828 	LIST_HEAD(reloc_roots);
1829 	u64 num_bytes = 0;
1830 	int ret;
1831 
1832 	mutex_lock(&fs_info->reloc_mutex);
1833 	rc->merging_rsv_size += fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
1834 	rc->merging_rsv_size += rc->nodes_relocated * 2;
1835 	mutex_unlock(&fs_info->reloc_mutex);
1836 
1837 again:
1838 	if (!err) {
1839 		num_bytes = rc->merging_rsv_size;
1840 		ret = btrfs_block_rsv_add(fs_info, rc->block_rsv, num_bytes,
1841 					  BTRFS_RESERVE_FLUSH_ALL);
1842 		if (ret)
1843 			err = ret;
1844 	}
1845 
1846 	trans = btrfs_join_transaction(rc->extent_root);
1847 	if (IS_ERR(trans)) {
1848 		if (!err)
1849 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
1850 						num_bytes, NULL);
1851 		return PTR_ERR(trans);
1852 	}
1853 
1854 	if (!err) {
1855 		if (num_bytes != rc->merging_rsv_size) {
1856 			btrfs_end_transaction(trans);
1857 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
1858 						num_bytes, NULL);
1859 			goto again;
1860 		}
1861 	}
1862 
1863 	rc->merge_reloc_tree = true;
1864 
1865 	while (!list_empty(&rc->reloc_roots)) {
1866 		reloc_root = list_entry(rc->reloc_roots.next,
1867 					struct btrfs_root, root_list);
1868 		list_del_init(&reloc_root->root_list);
1869 
1870 		root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
1871 				false);
1872 		if (IS_ERR(root)) {
1873 			/*
1874 			 * Even if we have an error we need this reloc root
1875 			 * back on our list so we can clean up properly.
1876 			 */
1877 			list_add(&reloc_root->root_list, &reloc_roots);
1878 			btrfs_abort_transaction(trans, (int)PTR_ERR(root));
1879 			if (!err)
1880 				err = PTR_ERR(root);
1881 			break;
1882 		}
1883 
1884 		if (unlikely(root->reloc_root != reloc_root)) {
1885 			if (root->reloc_root) {
1886 				btrfs_err(fs_info,
1887 "reloc tree mismatch, root %lld has reloc root key (%lld %u %llu) gen %llu, expect reloc root key (%lld %u %llu) gen %llu",
1888 					  btrfs_root_id(root),
1889 					  btrfs_root_id(root->reloc_root),
1890 					  root->reloc_root->root_key.type,
1891 					  root->reloc_root->root_key.offset,
1892 					  btrfs_root_generation(
1893 						  &root->reloc_root->root_item),
1894 					  btrfs_root_id(reloc_root),
1895 					  reloc_root->root_key.type,
1896 					  reloc_root->root_key.offset,
1897 					  btrfs_root_generation(
1898 						  &reloc_root->root_item));
1899 			} else {
1900 				btrfs_err(fs_info,
1901 "reloc tree mismatch, root %lld has no reloc root, expect reloc root key (%lld %u %llu) gen %llu",
1902 					  btrfs_root_id(root),
1903 					  btrfs_root_id(reloc_root),
1904 					  reloc_root->root_key.type,
1905 					  reloc_root->root_key.offset,
1906 					  btrfs_root_generation(
1907 						  &reloc_root->root_item));
1908 			}
1909 			list_add(&reloc_root->root_list, &reloc_roots);
1910 			btrfs_put_root(root);
1911 			btrfs_abort_transaction(trans, -EUCLEAN);
1912 			if (!err)
1913 				err = -EUCLEAN;
1914 			break;
1915 		}
1916 
1917 		/*
1918 		 * set reference count to 1, so btrfs_recover_relocation
1919 		 * knows it should resumes merging
1920 		 */
1921 		if (!err)
1922 			btrfs_set_root_refs(&reloc_root->root_item, 1);
1923 		ret = btrfs_update_reloc_root(trans, root);
1924 
1925 		/*
1926 		 * Even if we have an error we need this reloc root back on our
1927 		 * list so we can clean up properly.
1928 		 */
1929 		list_add(&reloc_root->root_list, &reloc_roots);
1930 		btrfs_put_root(root);
1931 
1932 		if (ret) {
1933 			btrfs_abort_transaction(trans, ret);
1934 			if (!err)
1935 				err = ret;
1936 			break;
1937 		}
1938 	}
1939 
1940 	list_splice(&reloc_roots, &rc->reloc_roots);
1941 
1942 	if (!err)
1943 		err = btrfs_commit_transaction(trans);
1944 	else
1945 		btrfs_end_transaction(trans);
1946 	return err;
1947 }
1948 
1949 static noinline_for_stack
1950 void free_reloc_roots(struct list_head *list)
1951 {
1952 	struct btrfs_root *reloc_root, *tmp;
1953 
1954 	list_for_each_entry_safe(reloc_root, tmp, list, root_list)
1955 		__del_reloc_root(reloc_root);
1956 }
1957 
1958 static noinline_for_stack
1959 void merge_reloc_roots(struct reloc_control *rc)
1960 {
1961 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
1962 	struct btrfs_root *root;
1963 	struct btrfs_root *reloc_root;
1964 	LIST_HEAD(reloc_roots);
1965 	int found = 0;
1966 	int ret = 0;
1967 again:
1968 	root = rc->extent_root;
1969 
1970 	/*
1971 	 * this serializes us with btrfs_record_root_in_transaction,
1972 	 * we have to make sure nobody is in the middle of
1973 	 * adding their roots to the list while we are
1974 	 * doing this splice
1975 	 */
1976 	mutex_lock(&fs_info->reloc_mutex);
1977 	list_splice_init(&rc->reloc_roots, &reloc_roots);
1978 	mutex_unlock(&fs_info->reloc_mutex);
1979 
1980 	while (!list_empty(&reloc_roots)) {
1981 		found = 1;
1982 		reloc_root = list_entry(reloc_roots.next,
1983 					struct btrfs_root, root_list);
1984 
1985 		root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
1986 					 false);
1987 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
1988 			if (WARN_ON(IS_ERR(root))) {
1989 				/*
1990 				 * For recovery we read the fs roots on mount,
1991 				 * and if we didn't find the root then we marked
1992 				 * the reloc root as a garbage root.  For normal
1993 				 * relocation obviously the root should exist in
1994 				 * memory.  However there's no reason we can't
1995 				 * handle the error properly here just in case.
1996 				 */
1997 				ret = PTR_ERR(root);
1998 				goto out;
1999 			}
2000 			if (WARN_ON(root->reloc_root != reloc_root)) {
2001 				/*
2002 				 * This can happen if on-disk metadata has some
2003 				 * corruption, e.g. bad reloc tree key offset.
2004 				 */
2005 				ret = -EINVAL;
2006 				goto out;
2007 			}
2008 			ret = merge_reloc_root(rc, root);
2009 			btrfs_put_root(root);
2010 			if (ret) {
2011 				if (list_empty(&reloc_root->root_list))
2012 					list_add_tail(&reloc_root->root_list,
2013 						      &reloc_roots);
2014 				goto out;
2015 			}
2016 		} else {
2017 			if (!IS_ERR(root)) {
2018 				if (root->reloc_root == reloc_root) {
2019 					root->reloc_root = NULL;
2020 					btrfs_put_root(reloc_root);
2021 				}
2022 				clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE,
2023 					  &root->state);
2024 				btrfs_put_root(root);
2025 			}
2026 
2027 			list_del_init(&reloc_root->root_list);
2028 			/* Don't forget to queue this reloc root for cleanup */
2029 			list_add_tail(&reloc_root->reloc_dirty_list,
2030 				      &rc->dirty_subvol_roots);
2031 		}
2032 	}
2033 
2034 	if (found) {
2035 		found = 0;
2036 		goto again;
2037 	}
2038 out:
2039 	if (ret) {
2040 		btrfs_handle_fs_error(fs_info, ret, NULL);
2041 		free_reloc_roots(&reloc_roots);
2042 
2043 		/* new reloc root may be added */
2044 		mutex_lock(&fs_info->reloc_mutex);
2045 		list_splice_init(&rc->reloc_roots, &reloc_roots);
2046 		mutex_unlock(&fs_info->reloc_mutex);
2047 		free_reloc_roots(&reloc_roots);
2048 	}
2049 
2050 	/*
2051 	 * We used to have
2052 	 *
2053 	 * BUG_ON(!RB_EMPTY_ROOT(&rc->reloc_root_tree.rb_root));
2054 	 *
2055 	 * here, but it's wrong.  If we fail to start the transaction in
2056 	 * prepare_to_merge() we will have only 0 ref reloc roots, none of which
2057 	 * have actually been removed from the reloc_root_tree rb tree.  This is
2058 	 * fine because we're bailing here, and we hold a reference on the root
2059 	 * for the list that holds it, so these roots will be cleaned up when we
2060 	 * do the reloc_dirty_list afterwards.  Meanwhile the root->reloc_root
2061 	 * will be cleaned up on unmount.
2062 	 *
2063 	 * The remaining nodes will be cleaned up by free_reloc_control.
2064 	 */
2065 }
2066 
2067 static void free_block_list(struct rb_root *blocks)
2068 {
2069 	struct tree_block *block;
2070 	struct rb_node *rb_node;
2071 	while ((rb_node = rb_first(blocks))) {
2072 		block = rb_entry(rb_node, struct tree_block, rb_node);
2073 		rb_erase(rb_node, blocks);
2074 		kfree(block);
2075 	}
2076 }
2077 
2078 static int record_reloc_root_in_trans(struct btrfs_trans_handle *trans,
2079 				      struct btrfs_root *reloc_root)
2080 {
2081 	struct btrfs_fs_info *fs_info = reloc_root->fs_info;
2082 	struct btrfs_root *root;
2083 	int ret;
2084 
2085 	if (reloc_root->last_trans == trans->transid)
2086 		return 0;
2087 
2088 	root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset, false);
2089 
2090 	/*
2091 	 * This should succeed, since we can't have a reloc root without having
2092 	 * already looked up the actual root and created the reloc root for this
2093 	 * root.
2094 	 *
2095 	 * However if there's some sort of corruption where we have a ref to a
2096 	 * reloc root without a corresponding root this could return ENOENT.
2097 	 */
2098 	if (IS_ERR(root)) {
2099 		ASSERT(0);
2100 		return PTR_ERR(root);
2101 	}
2102 	if (root->reloc_root != reloc_root) {
2103 		ASSERT(0);
2104 		btrfs_err(fs_info,
2105 			  "root %llu has two reloc roots associated with it",
2106 			  reloc_root->root_key.offset);
2107 		btrfs_put_root(root);
2108 		return -EUCLEAN;
2109 	}
2110 	ret = btrfs_record_root_in_trans(trans, root);
2111 	btrfs_put_root(root);
2112 
2113 	return ret;
2114 }
2115 
2116 static noinline_for_stack
2117 struct btrfs_root *select_reloc_root(struct btrfs_trans_handle *trans,
2118 				     struct reloc_control *rc,
2119 				     struct btrfs_backref_node *node,
2120 				     struct btrfs_backref_edge *edges[])
2121 {
2122 	struct btrfs_backref_node *next;
2123 	struct btrfs_root *root;
2124 	int index = 0;
2125 	int ret;
2126 
2127 	next = node;
2128 	while (1) {
2129 		cond_resched();
2130 		next = walk_up_backref(next, edges, &index);
2131 		root = next->root;
2132 
2133 		/*
2134 		 * If there is no root, then our references for this block are
2135 		 * incomplete, as we should be able to walk all the way up to a
2136 		 * block that is owned by a root.
2137 		 *
2138 		 * This path is only for SHAREABLE roots, so if we come upon a
2139 		 * non-SHAREABLE root then we have backrefs that resolve
2140 		 * improperly.
2141 		 *
2142 		 * Both of these cases indicate file system corruption, or a bug
2143 		 * in the backref walking code.
2144 		 */
2145 		if (!root) {
2146 			ASSERT(0);
2147 			btrfs_err(trans->fs_info,
2148 		"bytenr %llu doesn't have a backref path ending in a root",
2149 				  node->bytenr);
2150 			return ERR_PTR(-EUCLEAN);
2151 		}
2152 		if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
2153 			ASSERT(0);
2154 			btrfs_err(trans->fs_info,
2155 	"bytenr %llu has multiple refs with one ending in a non-shareable root",
2156 				  node->bytenr);
2157 			return ERR_PTR(-EUCLEAN);
2158 		}
2159 
2160 		if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID) {
2161 			ret = record_reloc_root_in_trans(trans, root);
2162 			if (ret)
2163 				return ERR_PTR(ret);
2164 			break;
2165 		}
2166 
2167 		ret = btrfs_record_root_in_trans(trans, root);
2168 		if (ret)
2169 			return ERR_PTR(ret);
2170 		root = root->reloc_root;
2171 
2172 		/*
2173 		 * We could have raced with another thread which failed, so
2174 		 * root->reloc_root may not be set, return ENOENT in this case.
2175 		 */
2176 		if (!root)
2177 			return ERR_PTR(-ENOENT);
2178 
2179 		if (next->new_bytenr != root->node->start) {
2180 			/*
2181 			 * We just created the reloc root, so we shouldn't have
2182 			 * ->new_bytenr set and this shouldn't be in the changed
2183 			 *  list.  If it is then we have multiple roots pointing
2184 			 *  at the same bytenr which indicates corruption, or
2185 			 *  we've made a mistake in the backref walking code.
2186 			 */
2187 			ASSERT(next->new_bytenr == 0);
2188 			ASSERT(list_empty(&next->list));
2189 			if (next->new_bytenr || !list_empty(&next->list)) {
2190 				btrfs_err(trans->fs_info,
2191 	"bytenr %llu possibly has multiple roots pointing at the same bytenr %llu",
2192 					  node->bytenr, next->bytenr);
2193 				return ERR_PTR(-EUCLEAN);
2194 			}
2195 
2196 			next->new_bytenr = root->node->start;
2197 			btrfs_put_root(next->root);
2198 			next->root = btrfs_grab_root(root);
2199 			ASSERT(next->root);
2200 			list_add_tail(&next->list,
2201 				      &rc->backref_cache.changed);
2202 			mark_block_processed(rc, next);
2203 			break;
2204 		}
2205 
2206 		WARN_ON(1);
2207 		root = NULL;
2208 		next = walk_down_backref(edges, &index);
2209 		if (!next || next->level <= node->level)
2210 			break;
2211 	}
2212 	if (!root) {
2213 		/*
2214 		 * This can happen if there's fs corruption or if there's a bug
2215 		 * in the backref lookup code.
2216 		 */
2217 		ASSERT(0);
2218 		return ERR_PTR(-ENOENT);
2219 	}
2220 
2221 	next = node;
2222 	/* setup backref node path for btrfs_reloc_cow_block */
2223 	while (1) {
2224 		rc->backref_cache.path[next->level] = next;
2225 		if (--index < 0)
2226 			break;
2227 		next = edges[index]->node[UPPER];
2228 	}
2229 	return root;
2230 }
2231 
2232 /*
2233  * Select a tree root for relocation.
2234  *
2235  * Return NULL if the block is not shareable. We should use do_relocation() in
2236  * this case.
2237  *
2238  * Return a tree root pointer if the block is shareable.
2239  * Return -ENOENT if the block is root of reloc tree.
2240  */
2241 static noinline_for_stack
2242 struct btrfs_root *select_one_root(struct btrfs_backref_node *node)
2243 {
2244 	struct btrfs_backref_node *next;
2245 	struct btrfs_root *root;
2246 	struct btrfs_root *fs_root = NULL;
2247 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
2248 	int index = 0;
2249 
2250 	next = node;
2251 	while (1) {
2252 		cond_resched();
2253 		next = walk_up_backref(next, edges, &index);
2254 		root = next->root;
2255 
2256 		/*
2257 		 * This can occur if we have incomplete extent refs leading all
2258 		 * the way up a particular path, in this case return -EUCLEAN.
2259 		 */
2260 		if (!root)
2261 			return ERR_PTR(-EUCLEAN);
2262 
2263 		/* No other choice for non-shareable tree */
2264 		if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
2265 			return root;
2266 
2267 		if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID)
2268 			fs_root = root;
2269 
2270 		if (next != node)
2271 			return NULL;
2272 
2273 		next = walk_down_backref(edges, &index);
2274 		if (!next || next->level <= node->level)
2275 			break;
2276 	}
2277 
2278 	if (!fs_root)
2279 		return ERR_PTR(-ENOENT);
2280 	return fs_root;
2281 }
2282 
2283 static noinline_for_stack u64 calcu_metadata_size(struct reloc_control *rc,
2284 						  struct btrfs_backref_node *node)
2285 {
2286 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2287 	struct btrfs_backref_node *next = node;
2288 	struct btrfs_backref_edge *edge;
2289 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
2290 	u64 num_bytes = 0;
2291 	int index = 0;
2292 
2293 	BUG_ON(node->processed);
2294 
2295 	while (next) {
2296 		cond_resched();
2297 		while (1) {
2298 			if (next->processed)
2299 				break;
2300 
2301 			num_bytes += fs_info->nodesize;
2302 
2303 			if (list_empty(&next->upper))
2304 				break;
2305 
2306 			edge = list_entry(next->upper.next,
2307 					struct btrfs_backref_edge, list[LOWER]);
2308 			edges[index++] = edge;
2309 			next = edge->node[UPPER];
2310 		}
2311 		next = walk_down_backref(edges, &index);
2312 	}
2313 	return num_bytes;
2314 }
2315 
2316 static int reserve_metadata_space(struct btrfs_trans_handle *trans,
2317 				  struct reloc_control *rc,
2318 				  struct btrfs_backref_node *node)
2319 {
2320 	struct btrfs_root *root = rc->extent_root;
2321 	struct btrfs_fs_info *fs_info = root->fs_info;
2322 	u64 num_bytes;
2323 	int ret;
2324 	u64 tmp;
2325 
2326 	num_bytes = calcu_metadata_size(rc, node) * 2;
2327 
2328 	trans->block_rsv = rc->block_rsv;
2329 	rc->reserved_bytes += num_bytes;
2330 
2331 	/*
2332 	 * We are under a transaction here so we can only do limited flushing.
2333 	 * If we get an enospc just kick back -EAGAIN so we know to drop the
2334 	 * transaction and try to refill when we can flush all the things.
2335 	 */
2336 	ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv, num_bytes,
2337 				     BTRFS_RESERVE_FLUSH_LIMIT);
2338 	if (ret) {
2339 		tmp = fs_info->nodesize * RELOCATION_RESERVED_NODES;
2340 		while (tmp <= rc->reserved_bytes)
2341 			tmp <<= 1;
2342 		/*
2343 		 * only one thread can access block_rsv at this point,
2344 		 * so we don't need hold lock to protect block_rsv.
2345 		 * we expand more reservation size here to allow enough
2346 		 * space for relocation and we will return earlier in
2347 		 * enospc case.
2348 		 */
2349 		rc->block_rsv->size = tmp + fs_info->nodesize *
2350 				      RELOCATION_RESERVED_NODES;
2351 		return -EAGAIN;
2352 	}
2353 
2354 	return 0;
2355 }
2356 
2357 /*
2358  * relocate a block tree, and then update pointers in upper level
2359  * blocks that reference the block to point to the new location.
2360  *
2361  * if called by link_to_upper, the block has already been relocated.
2362  * in that case this function just updates pointers.
2363  */
2364 static int do_relocation(struct btrfs_trans_handle *trans,
2365 			 struct reloc_control *rc,
2366 			 struct btrfs_backref_node *node,
2367 			 struct btrfs_key *key,
2368 			 struct btrfs_path *path, int lowest)
2369 {
2370 	struct btrfs_backref_node *upper;
2371 	struct btrfs_backref_edge *edge;
2372 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
2373 	struct btrfs_root *root;
2374 	struct extent_buffer *eb;
2375 	u32 blocksize;
2376 	u64 bytenr;
2377 	int slot;
2378 	int ret = 0;
2379 
2380 	/*
2381 	 * If we are lowest then this is the first time we're processing this
2382 	 * block, and thus shouldn't have an eb associated with it yet.
2383 	 */
2384 	ASSERT(!lowest || !node->eb);
2385 
2386 	path->lowest_level = node->level + 1;
2387 	rc->backref_cache.path[node->level] = node;
2388 	list_for_each_entry(edge, &node->upper, list[LOWER]) {
2389 		cond_resched();
2390 
2391 		upper = edge->node[UPPER];
2392 		root = select_reloc_root(trans, rc, upper, edges);
2393 		if (IS_ERR(root)) {
2394 			ret = PTR_ERR(root);
2395 			goto next;
2396 		}
2397 
2398 		if (upper->eb && !upper->locked) {
2399 			if (!lowest) {
2400 				ret = btrfs_bin_search(upper->eb, 0, key, &slot);
2401 				if (ret < 0)
2402 					goto next;
2403 				BUG_ON(ret);
2404 				bytenr = btrfs_node_blockptr(upper->eb, slot);
2405 				if (node->eb->start == bytenr)
2406 					goto next;
2407 			}
2408 			btrfs_backref_drop_node_buffer(upper);
2409 		}
2410 
2411 		if (!upper->eb) {
2412 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
2413 			if (ret) {
2414 				if (ret > 0)
2415 					ret = -ENOENT;
2416 
2417 				btrfs_release_path(path);
2418 				break;
2419 			}
2420 
2421 			if (!upper->eb) {
2422 				upper->eb = path->nodes[upper->level];
2423 				path->nodes[upper->level] = NULL;
2424 			} else {
2425 				BUG_ON(upper->eb != path->nodes[upper->level]);
2426 			}
2427 
2428 			upper->locked = 1;
2429 			path->locks[upper->level] = 0;
2430 
2431 			slot = path->slots[upper->level];
2432 			btrfs_release_path(path);
2433 		} else {
2434 			ret = btrfs_bin_search(upper->eb, 0, key, &slot);
2435 			if (ret < 0)
2436 				goto next;
2437 			BUG_ON(ret);
2438 		}
2439 
2440 		bytenr = btrfs_node_blockptr(upper->eb, slot);
2441 		if (lowest) {
2442 			if (bytenr != node->bytenr) {
2443 				btrfs_err(root->fs_info,
2444 		"lowest leaf/node mismatch: bytenr %llu node->bytenr %llu slot %d upper %llu",
2445 					  bytenr, node->bytenr, slot,
2446 					  upper->eb->start);
2447 				ret = -EIO;
2448 				goto next;
2449 			}
2450 		} else {
2451 			if (node->eb->start == bytenr)
2452 				goto next;
2453 		}
2454 
2455 		blocksize = root->fs_info->nodesize;
2456 		eb = btrfs_read_node_slot(upper->eb, slot);
2457 		if (IS_ERR(eb)) {
2458 			ret = PTR_ERR(eb);
2459 			goto next;
2460 		}
2461 		btrfs_tree_lock(eb);
2462 
2463 		if (!node->eb) {
2464 			ret = btrfs_cow_block(trans, root, eb, upper->eb,
2465 					      slot, &eb, BTRFS_NESTING_COW);
2466 			btrfs_tree_unlock(eb);
2467 			free_extent_buffer(eb);
2468 			if (ret < 0)
2469 				goto next;
2470 			/*
2471 			 * We've just COWed this block, it should have updated
2472 			 * the correct backref node entry.
2473 			 */
2474 			ASSERT(node->eb == eb);
2475 		} else {
2476 			struct btrfs_ref ref = {
2477 				.action = BTRFS_ADD_DELAYED_REF,
2478 				.bytenr = node->eb->start,
2479 				.num_bytes = blocksize,
2480 				.parent = upper->eb->start,
2481 				.owning_root = btrfs_header_owner(upper->eb),
2482 				.ref_root = btrfs_header_owner(upper->eb),
2483 			};
2484 
2485 			btrfs_set_node_blockptr(upper->eb, slot,
2486 						node->eb->start);
2487 			btrfs_set_node_ptr_generation(upper->eb, slot,
2488 						      trans->transid);
2489 			btrfs_mark_buffer_dirty(trans, upper->eb);
2490 
2491 			btrfs_init_tree_ref(&ref, node->level,
2492 					    btrfs_root_id(root), false);
2493 			ret = btrfs_inc_extent_ref(trans, &ref);
2494 			if (!ret)
2495 				ret = btrfs_drop_subtree(trans, root, eb,
2496 							 upper->eb);
2497 			if (ret)
2498 				btrfs_abort_transaction(trans, ret);
2499 		}
2500 next:
2501 		if (!upper->pending)
2502 			btrfs_backref_drop_node_buffer(upper);
2503 		else
2504 			btrfs_backref_unlock_node_buffer(upper);
2505 		if (ret)
2506 			break;
2507 	}
2508 
2509 	if (!ret && node->pending) {
2510 		btrfs_backref_drop_node_buffer(node);
2511 		list_move_tail(&node->list, &rc->backref_cache.changed);
2512 		node->pending = 0;
2513 	}
2514 
2515 	path->lowest_level = 0;
2516 
2517 	/*
2518 	 * We should have allocated all of our space in the block rsv and thus
2519 	 * shouldn't ENOSPC.
2520 	 */
2521 	ASSERT(ret != -ENOSPC);
2522 	return ret;
2523 }
2524 
2525 static int link_to_upper(struct btrfs_trans_handle *trans,
2526 			 struct reloc_control *rc,
2527 			 struct btrfs_backref_node *node,
2528 			 struct btrfs_path *path)
2529 {
2530 	struct btrfs_key key;
2531 
2532 	btrfs_node_key_to_cpu(node->eb, &key, 0);
2533 	return do_relocation(trans, rc, node, &key, path, 0);
2534 }
2535 
2536 static int finish_pending_nodes(struct btrfs_trans_handle *trans,
2537 				struct reloc_control *rc,
2538 				struct btrfs_path *path, int err)
2539 {
2540 	LIST_HEAD(list);
2541 	struct btrfs_backref_cache *cache = &rc->backref_cache;
2542 	struct btrfs_backref_node *node;
2543 	int level;
2544 	int ret;
2545 
2546 	for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2547 		while (!list_empty(&cache->pending[level])) {
2548 			node = list_entry(cache->pending[level].next,
2549 					  struct btrfs_backref_node, list);
2550 			list_move_tail(&node->list, &list);
2551 			BUG_ON(!node->pending);
2552 
2553 			if (!err) {
2554 				ret = link_to_upper(trans, rc, node, path);
2555 				if (ret < 0)
2556 					err = ret;
2557 			}
2558 		}
2559 		list_splice_init(&list, &cache->pending[level]);
2560 	}
2561 	return err;
2562 }
2563 
2564 /*
2565  * mark a block and all blocks directly/indirectly reference the block
2566  * as processed.
2567  */
2568 static void update_processed_blocks(struct reloc_control *rc,
2569 				    struct btrfs_backref_node *node)
2570 {
2571 	struct btrfs_backref_node *next = node;
2572 	struct btrfs_backref_edge *edge;
2573 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
2574 	int index = 0;
2575 
2576 	while (next) {
2577 		cond_resched();
2578 		while (1) {
2579 			if (next->processed)
2580 				break;
2581 
2582 			mark_block_processed(rc, next);
2583 
2584 			if (list_empty(&next->upper))
2585 				break;
2586 
2587 			edge = list_entry(next->upper.next,
2588 					struct btrfs_backref_edge, list[LOWER]);
2589 			edges[index++] = edge;
2590 			next = edge->node[UPPER];
2591 		}
2592 		next = walk_down_backref(edges, &index);
2593 	}
2594 }
2595 
2596 static int tree_block_processed(u64 bytenr, struct reloc_control *rc)
2597 {
2598 	u32 blocksize = rc->extent_root->fs_info->nodesize;
2599 
2600 	if (test_range_bit(&rc->processed_blocks, bytenr,
2601 			   bytenr + blocksize - 1, EXTENT_DIRTY, NULL))
2602 		return 1;
2603 	return 0;
2604 }
2605 
2606 static int get_tree_block_key(struct btrfs_fs_info *fs_info,
2607 			      struct tree_block *block)
2608 {
2609 	struct btrfs_tree_parent_check check = {
2610 		.level = block->level,
2611 		.owner_root = block->owner,
2612 		.transid = block->key.offset
2613 	};
2614 	struct extent_buffer *eb;
2615 
2616 	eb = read_tree_block(fs_info, block->bytenr, &check);
2617 	if (IS_ERR(eb))
2618 		return PTR_ERR(eb);
2619 	if (!extent_buffer_uptodate(eb)) {
2620 		free_extent_buffer(eb);
2621 		return -EIO;
2622 	}
2623 	if (block->level == 0)
2624 		btrfs_item_key_to_cpu(eb, &block->key, 0);
2625 	else
2626 		btrfs_node_key_to_cpu(eb, &block->key, 0);
2627 	free_extent_buffer(eb);
2628 	block->key_ready = true;
2629 	return 0;
2630 }
2631 
2632 /*
2633  * helper function to relocate a tree block
2634  */
2635 static int relocate_tree_block(struct btrfs_trans_handle *trans,
2636 				struct reloc_control *rc,
2637 				struct btrfs_backref_node *node,
2638 				struct btrfs_key *key,
2639 				struct btrfs_path *path)
2640 {
2641 	struct btrfs_root *root;
2642 	int ret = 0;
2643 
2644 	if (!node)
2645 		return 0;
2646 
2647 	/*
2648 	 * If we fail here we want to drop our backref_node because we are going
2649 	 * to start over and regenerate the tree for it.
2650 	 */
2651 	ret = reserve_metadata_space(trans, rc, node);
2652 	if (ret)
2653 		goto out;
2654 
2655 	BUG_ON(node->processed);
2656 	root = select_one_root(node);
2657 	if (IS_ERR(root)) {
2658 		ret = PTR_ERR(root);
2659 
2660 		/* See explanation in select_one_root for the -EUCLEAN case. */
2661 		ASSERT(ret == -ENOENT);
2662 		if (ret == -ENOENT) {
2663 			ret = 0;
2664 			update_processed_blocks(rc, node);
2665 		}
2666 		goto out;
2667 	}
2668 
2669 	if (root) {
2670 		if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
2671 			/*
2672 			 * This block was the root block of a root, and this is
2673 			 * the first time we're processing the block and thus it
2674 			 * should not have had the ->new_bytenr modified and
2675 			 * should have not been included on the changed list.
2676 			 *
2677 			 * However in the case of corruption we could have
2678 			 * multiple refs pointing to the same block improperly,
2679 			 * and thus we would trip over these checks.  ASSERT()
2680 			 * for the developer case, because it could indicate a
2681 			 * bug in the backref code, however error out for a
2682 			 * normal user in the case of corruption.
2683 			 */
2684 			ASSERT(node->new_bytenr == 0);
2685 			ASSERT(list_empty(&node->list));
2686 			if (node->new_bytenr || !list_empty(&node->list)) {
2687 				btrfs_err(root->fs_info,
2688 				  "bytenr %llu has improper references to it",
2689 					  node->bytenr);
2690 				ret = -EUCLEAN;
2691 				goto out;
2692 			}
2693 			ret = btrfs_record_root_in_trans(trans, root);
2694 			if (ret)
2695 				goto out;
2696 			/*
2697 			 * Another thread could have failed, need to check if we
2698 			 * have reloc_root actually set.
2699 			 */
2700 			if (!root->reloc_root) {
2701 				ret = -ENOENT;
2702 				goto out;
2703 			}
2704 			root = root->reloc_root;
2705 			node->new_bytenr = root->node->start;
2706 			btrfs_put_root(node->root);
2707 			node->root = btrfs_grab_root(root);
2708 			ASSERT(node->root);
2709 			list_add_tail(&node->list, &rc->backref_cache.changed);
2710 		} else {
2711 			path->lowest_level = node->level;
2712 			if (root == root->fs_info->chunk_root)
2713 				btrfs_reserve_chunk_metadata(trans, false);
2714 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
2715 			btrfs_release_path(path);
2716 			if (root == root->fs_info->chunk_root)
2717 				btrfs_trans_release_chunk_metadata(trans);
2718 			if (ret > 0)
2719 				ret = 0;
2720 		}
2721 		if (!ret)
2722 			update_processed_blocks(rc, node);
2723 	} else {
2724 		ret = do_relocation(trans, rc, node, key, path, 1);
2725 	}
2726 out:
2727 	if (ret || node->level == 0 || node->cowonly)
2728 		btrfs_backref_cleanup_node(&rc->backref_cache, node);
2729 	return ret;
2730 }
2731 
2732 /*
2733  * relocate a list of blocks
2734  */
2735 static noinline_for_stack
2736 int relocate_tree_blocks(struct btrfs_trans_handle *trans,
2737 			 struct reloc_control *rc, struct rb_root *blocks)
2738 {
2739 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2740 	struct btrfs_backref_node *node;
2741 	struct btrfs_path *path;
2742 	struct tree_block *block;
2743 	struct tree_block *next;
2744 	int ret = 0;
2745 
2746 	path = btrfs_alloc_path();
2747 	if (!path) {
2748 		ret = -ENOMEM;
2749 		goto out_free_blocks;
2750 	}
2751 
2752 	/* Kick in readahead for tree blocks with missing keys */
2753 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
2754 		if (!block->key_ready)
2755 			btrfs_readahead_tree_block(fs_info, block->bytenr,
2756 						   block->owner, 0,
2757 						   block->level);
2758 	}
2759 
2760 	/* Get first keys */
2761 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
2762 		if (!block->key_ready) {
2763 			ret = get_tree_block_key(fs_info, block);
2764 			if (ret)
2765 				goto out_free_path;
2766 		}
2767 	}
2768 
2769 	/* Do tree relocation */
2770 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
2771 		node = build_backref_tree(trans, rc, &block->key,
2772 					  block->level, block->bytenr);
2773 		if (IS_ERR(node)) {
2774 			ret = PTR_ERR(node);
2775 			goto out;
2776 		}
2777 
2778 		ret = relocate_tree_block(trans, rc, node, &block->key,
2779 					  path);
2780 		if (ret < 0)
2781 			break;
2782 	}
2783 out:
2784 	ret = finish_pending_nodes(trans, rc, path, ret);
2785 
2786 out_free_path:
2787 	btrfs_free_path(path);
2788 out_free_blocks:
2789 	free_block_list(blocks);
2790 	return ret;
2791 }
2792 
2793 static noinline_for_stack int prealloc_file_extent_cluster(
2794 				struct btrfs_inode *inode,
2795 				const struct file_extent_cluster *cluster)
2796 {
2797 	u64 alloc_hint = 0;
2798 	u64 start;
2799 	u64 end;
2800 	u64 offset = inode->index_cnt;
2801 	u64 num_bytes;
2802 	int nr;
2803 	int ret = 0;
2804 	u64 i_size = i_size_read(&inode->vfs_inode);
2805 	u64 prealloc_start = cluster->start - offset;
2806 	u64 prealloc_end = cluster->end - offset;
2807 	u64 cur_offset = prealloc_start;
2808 
2809 	/*
2810 	 * For subpage case, previous i_size may not be aligned to PAGE_SIZE.
2811 	 * This means the range [i_size, PAGE_END + 1) is filled with zeros by
2812 	 * btrfs_do_readpage() call of previously relocated file cluster.
2813 	 *
2814 	 * If the current cluster starts in the above range, btrfs_do_readpage()
2815 	 * will skip the read, and relocate_one_folio() will later writeback
2816 	 * the padding zeros as new data, causing data corruption.
2817 	 *
2818 	 * Here we have to manually invalidate the range (i_size, PAGE_END + 1).
2819 	 */
2820 	if (!PAGE_ALIGNED(i_size)) {
2821 		struct address_space *mapping = inode->vfs_inode.i_mapping;
2822 		struct btrfs_fs_info *fs_info = inode->root->fs_info;
2823 		const u32 sectorsize = fs_info->sectorsize;
2824 		struct folio *folio;
2825 
2826 		ASSERT(sectorsize < PAGE_SIZE);
2827 		ASSERT(IS_ALIGNED(i_size, sectorsize));
2828 
2829 		/*
2830 		 * Subpage can't handle page with DIRTY but without UPTODATE
2831 		 * bit as it can lead to the following deadlock:
2832 		 *
2833 		 * btrfs_read_folio()
2834 		 * | Page already *locked*
2835 		 * |- btrfs_lock_and_flush_ordered_range()
2836 		 *    |- btrfs_start_ordered_extent()
2837 		 *       |- extent_write_cache_pages()
2838 		 *          |- lock_page()
2839 		 *             We try to lock the page we already hold.
2840 		 *
2841 		 * Here we just writeback the whole data reloc inode, so that
2842 		 * we will be ensured to have no dirty range in the page, and
2843 		 * are safe to clear the uptodate bits.
2844 		 *
2845 		 * This shouldn't cause too much overhead, as we need to write
2846 		 * the data back anyway.
2847 		 */
2848 		ret = filemap_write_and_wait(mapping);
2849 		if (ret < 0)
2850 			return ret;
2851 
2852 		clear_extent_bits(&inode->io_tree, i_size,
2853 				  round_up(i_size, PAGE_SIZE) - 1,
2854 				  EXTENT_UPTODATE);
2855 		folio = filemap_lock_folio(mapping, i_size >> PAGE_SHIFT);
2856 		/*
2857 		 * If page is freed we don't need to do anything then, as we
2858 		 * will re-read the whole page anyway.
2859 		 */
2860 		if (!IS_ERR(folio)) {
2861 			btrfs_subpage_clear_uptodate(fs_info, folio, i_size,
2862 					round_up(i_size, PAGE_SIZE) - i_size);
2863 			folio_unlock(folio);
2864 			folio_put(folio);
2865 		}
2866 	}
2867 
2868 	BUG_ON(cluster->start != cluster->boundary[0]);
2869 	ret = btrfs_alloc_data_chunk_ondemand(inode,
2870 					      prealloc_end + 1 - prealloc_start);
2871 	if (ret)
2872 		return ret;
2873 
2874 	btrfs_inode_lock(inode, 0);
2875 	for (nr = 0; nr < cluster->nr; nr++) {
2876 		struct extent_state *cached_state = NULL;
2877 
2878 		start = cluster->boundary[nr] - offset;
2879 		if (nr + 1 < cluster->nr)
2880 			end = cluster->boundary[nr + 1] - 1 - offset;
2881 		else
2882 			end = cluster->end - offset;
2883 
2884 		lock_extent(&inode->io_tree, start, end, &cached_state);
2885 		num_bytes = end + 1 - start;
2886 		ret = btrfs_prealloc_file_range(&inode->vfs_inode, 0, start,
2887 						num_bytes, num_bytes,
2888 						end + 1, &alloc_hint);
2889 		cur_offset = end + 1;
2890 		unlock_extent(&inode->io_tree, start, end, &cached_state);
2891 		if (ret)
2892 			break;
2893 	}
2894 	btrfs_inode_unlock(inode, 0);
2895 
2896 	if (cur_offset < prealloc_end)
2897 		btrfs_free_reserved_data_space_noquota(inode->root->fs_info,
2898 					       prealloc_end + 1 - cur_offset);
2899 	return ret;
2900 }
2901 
2902 static noinline_for_stack int setup_relocation_extent_mapping(struct inode *inode,
2903 				u64 start, u64 end, u64 block_start)
2904 {
2905 	struct extent_map *em;
2906 	struct extent_state *cached_state = NULL;
2907 	int ret = 0;
2908 
2909 	em = alloc_extent_map();
2910 	if (!em)
2911 		return -ENOMEM;
2912 
2913 	em->start = start;
2914 	em->len = end + 1 - start;
2915 	em->block_len = em->len;
2916 	em->block_start = block_start;
2917 	em->flags |= EXTENT_FLAG_PINNED;
2918 
2919 	lock_extent(&BTRFS_I(inode)->io_tree, start, end, &cached_state);
2920 	ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, false);
2921 	unlock_extent(&BTRFS_I(inode)->io_tree, start, end, &cached_state);
2922 	free_extent_map(em);
2923 
2924 	return ret;
2925 }
2926 
2927 /*
2928  * Allow error injection to test balance/relocation cancellation
2929  */
2930 noinline int btrfs_should_cancel_balance(const struct btrfs_fs_info *fs_info)
2931 {
2932 	return atomic_read(&fs_info->balance_cancel_req) ||
2933 		atomic_read(&fs_info->reloc_cancel_req) ||
2934 		fatal_signal_pending(current);
2935 }
2936 ALLOW_ERROR_INJECTION(btrfs_should_cancel_balance, TRUE);
2937 
2938 static u64 get_cluster_boundary_end(const struct file_extent_cluster *cluster,
2939 				    int cluster_nr)
2940 {
2941 	/* Last extent, use cluster end directly */
2942 	if (cluster_nr >= cluster->nr - 1)
2943 		return cluster->end;
2944 
2945 	/* Use next boundary start*/
2946 	return cluster->boundary[cluster_nr + 1] - 1;
2947 }
2948 
2949 static int relocate_one_folio(struct inode *inode, struct file_ra_state *ra,
2950 			      const struct file_extent_cluster *cluster,
2951 			      int *cluster_nr, unsigned long index)
2952 {
2953 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
2954 	u64 offset = BTRFS_I(inode)->index_cnt;
2955 	const unsigned long last_index = (cluster->end - offset) >> PAGE_SHIFT;
2956 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
2957 	struct folio *folio;
2958 	u64 folio_start;
2959 	u64 folio_end;
2960 	u64 cur;
2961 	int ret;
2962 
2963 	ASSERT(index <= last_index);
2964 	folio = filemap_lock_folio(inode->i_mapping, index);
2965 	if (IS_ERR(folio)) {
2966 		page_cache_sync_readahead(inode->i_mapping, ra, NULL,
2967 					  index, last_index + 1 - index);
2968 		folio = __filemap_get_folio(inode->i_mapping, index,
2969 					    FGP_LOCK | FGP_ACCESSED | FGP_CREAT, mask);
2970 		if (IS_ERR(folio))
2971 			return PTR_ERR(folio);
2972 	}
2973 
2974 	WARN_ON(folio_order(folio));
2975 
2976 	if (folio_test_readahead(folio))
2977 		page_cache_async_readahead(inode->i_mapping, ra, NULL,
2978 					   folio, index,
2979 					   last_index + 1 - index);
2980 
2981 	if (!folio_test_uptodate(folio)) {
2982 		btrfs_read_folio(NULL, folio);
2983 		folio_lock(folio);
2984 		if (!folio_test_uptodate(folio)) {
2985 			ret = -EIO;
2986 			goto release_folio;
2987 		}
2988 	}
2989 
2990 	/*
2991 	 * We could have lost folio private when we dropped the lock to read the
2992 	 * folio above, make sure we set_page_extent_mapped here so we have any
2993 	 * of the subpage blocksize stuff we need in place.
2994 	 */
2995 	ret = set_folio_extent_mapped(folio);
2996 	if (ret < 0)
2997 		goto release_folio;
2998 
2999 	folio_start = folio_pos(folio);
3000 	folio_end = folio_start + PAGE_SIZE - 1;
3001 
3002 	/*
3003 	 * Start from the cluster, as for subpage case, the cluster can start
3004 	 * inside the folio.
3005 	 */
3006 	cur = max(folio_start, cluster->boundary[*cluster_nr] - offset);
3007 	while (cur <= folio_end) {
3008 		struct extent_state *cached_state = NULL;
3009 		u64 extent_start = cluster->boundary[*cluster_nr] - offset;
3010 		u64 extent_end = get_cluster_boundary_end(cluster,
3011 						*cluster_nr) - offset;
3012 		u64 clamped_start = max(folio_start, extent_start);
3013 		u64 clamped_end = min(folio_end, extent_end);
3014 		u32 clamped_len = clamped_end + 1 - clamped_start;
3015 
3016 		/* Reserve metadata for this range */
3017 		ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
3018 						      clamped_len, clamped_len,
3019 						      false);
3020 		if (ret)
3021 			goto release_folio;
3022 
3023 		/* Mark the range delalloc and dirty for later writeback */
3024 		lock_extent(&BTRFS_I(inode)->io_tree, clamped_start, clamped_end,
3025 			    &cached_state);
3026 		ret = btrfs_set_extent_delalloc(BTRFS_I(inode), clamped_start,
3027 						clamped_end, 0, &cached_state);
3028 		if (ret) {
3029 			clear_extent_bit(&BTRFS_I(inode)->io_tree,
3030 					 clamped_start, clamped_end,
3031 					 EXTENT_LOCKED | EXTENT_BOUNDARY,
3032 					 &cached_state);
3033 			btrfs_delalloc_release_metadata(BTRFS_I(inode),
3034 							clamped_len, true);
3035 			btrfs_delalloc_release_extents(BTRFS_I(inode),
3036 						       clamped_len);
3037 			goto release_folio;
3038 		}
3039 		btrfs_folio_set_dirty(fs_info, folio, clamped_start, clamped_len);
3040 
3041 		/*
3042 		 * Set the boundary if it's inside the folio.
3043 		 * Data relocation requires the destination extents to have the
3044 		 * same size as the source.
3045 		 * EXTENT_BOUNDARY bit prevents current extent from being merged
3046 		 * with previous extent.
3047 		 */
3048 		if (in_range(cluster->boundary[*cluster_nr] - offset, folio_start, PAGE_SIZE)) {
3049 			u64 boundary_start = cluster->boundary[*cluster_nr] -
3050 						offset;
3051 			u64 boundary_end = boundary_start +
3052 					   fs_info->sectorsize - 1;
3053 
3054 			set_extent_bit(&BTRFS_I(inode)->io_tree,
3055 				       boundary_start, boundary_end,
3056 				       EXTENT_BOUNDARY, NULL);
3057 		}
3058 		unlock_extent(&BTRFS_I(inode)->io_tree, clamped_start, clamped_end,
3059 			      &cached_state);
3060 		btrfs_delalloc_release_extents(BTRFS_I(inode), clamped_len);
3061 		cur += clamped_len;
3062 
3063 		/* Crossed extent end, go to next extent */
3064 		if (cur >= extent_end) {
3065 			(*cluster_nr)++;
3066 			/* Just finished the last extent of the cluster, exit. */
3067 			if (*cluster_nr >= cluster->nr)
3068 				break;
3069 		}
3070 	}
3071 	folio_unlock(folio);
3072 	folio_put(folio);
3073 
3074 	balance_dirty_pages_ratelimited(inode->i_mapping);
3075 	btrfs_throttle(fs_info);
3076 	if (btrfs_should_cancel_balance(fs_info))
3077 		ret = -ECANCELED;
3078 	return ret;
3079 
3080 release_folio:
3081 	folio_unlock(folio);
3082 	folio_put(folio);
3083 	return ret;
3084 }
3085 
3086 static int relocate_file_extent_cluster(struct inode *inode,
3087 					const struct file_extent_cluster *cluster)
3088 {
3089 	u64 offset = BTRFS_I(inode)->index_cnt;
3090 	unsigned long index;
3091 	unsigned long last_index;
3092 	struct file_ra_state *ra;
3093 	int cluster_nr = 0;
3094 	int ret = 0;
3095 
3096 	if (!cluster->nr)
3097 		return 0;
3098 
3099 	ra = kzalloc(sizeof(*ra), GFP_NOFS);
3100 	if (!ra)
3101 		return -ENOMEM;
3102 
3103 	ret = prealloc_file_extent_cluster(BTRFS_I(inode), cluster);
3104 	if (ret)
3105 		goto out;
3106 
3107 	file_ra_state_init(ra, inode->i_mapping);
3108 
3109 	ret = setup_relocation_extent_mapping(inode, cluster->start - offset,
3110 				   cluster->end - offset, cluster->start);
3111 	if (ret)
3112 		goto out;
3113 
3114 	last_index = (cluster->end - offset) >> PAGE_SHIFT;
3115 	for (index = (cluster->start - offset) >> PAGE_SHIFT;
3116 	     index <= last_index && !ret; index++)
3117 		ret = relocate_one_folio(inode, ra, cluster, &cluster_nr, index);
3118 	if (ret == 0)
3119 		WARN_ON(cluster_nr != cluster->nr);
3120 out:
3121 	kfree(ra);
3122 	return ret;
3123 }
3124 
3125 static noinline_for_stack int relocate_data_extent(struct inode *inode,
3126 				const struct btrfs_key *extent_key,
3127 				struct file_extent_cluster *cluster)
3128 {
3129 	int ret;
3130 	struct btrfs_root *root = BTRFS_I(inode)->root;
3131 
3132 	if (cluster->nr > 0 && extent_key->objectid != cluster->end + 1) {
3133 		ret = relocate_file_extent_cluster(inode, cluster);
3134 		if (ret)
3135 			return ret;
3136 		cluster->nr = 0;
3137 	}
3138 
3139 	/*
3140 	 * Under simple quotas, we set root->relocation_src_root when we find
3141 	 * the extent. If adjacent extents have different owners, we can't merge
3142 	 * them while relocating. Handle this by storing the owning root that
3143 	 * started a cluster and if we see an extent from a different root break
3144 	 * cluster formation (just like the above case of non-adjacent extents).
3145 	 *
3146 	 * Without simple quotas, relocation_src_root is always 0, so we should
3147 	 * never see a mismatch, and it should have no effect on relocation
3148 	 * clusters.
3149 	 */
3150 	if (cluster->nr > 0 && cluster->owning_root != root->relocation_src_root) {
3151 		u64 tmp = root->relocation_src_root;
3152 
3153 		/*
3154 		 * root->relocation_src_root is the state that actually affects
3155 		 * the preallocation we do here, so set it to the root owning
3156 		 * the cluster we need to relocate.
3157 		 */
3158 		root->relocation_src_root = cluster->owning_root;
3159 		ret = relocate_file_extent_cluster(inode, cluster);
3160 		if (ret)
3161 			return ret;
3162 		cluster->nr = 0;
3163 		/* And reset it back for the current extent's owning root. */
3164 		root->relocation_src_root = tmp;
3165 	}
3166 
3167 	if (!cluster->nr) {
3168 		cluster->start = extent_key->objectid;
3169 		cluster->owning_root = root->relocation_src_root;
3170 	}
3171 	else
3172 		BUG_ON(cluster->nr >= MAX_EXTENTS);
3173 	cluster->end = extent_key->objectid + extent_key->offset - 1;
3174 	cluster->boundary[cluster->nr] = extent_key->objectid;
3175 	cluster->nr++;
3176 
3177 	if (cluster->nr >= MAX_EXTENTS) {
3178 		ret = relocate_file_extent_cluster(inode, cluster);
3179 		if (ret)
3180 			return ret;
3181 		cluster->nr = 0;
3182 	}
3183 	return 0;
3184 }
3185 
3186 /*
3187  * helper to add a tree block to the list.
3188  * the major work is getting the generation and level of the block
3189  */
3190 static int add_tree_block(struct reloc_control *rc,
3191 			  const struct btrfs_key *extent_key,
3192 			  struct btrfs_path *path,
3193 			  struct rb_root *blocks)
3194 {
3195 	struct extent_buffer *eb;
3196 	struct btrfs_extent_item *ei;
3197 	struct btrfs_tree_block_info *bi;
3198 	struct tree_block *block;
3199 	struct rb_node *rb_node;
3200 	u32 item_size;
3201 	int level = -1;
3202 	u64 generation;
3203 	u64 owner = 0;
3204 
3205 	eb =  path->nodes[0];
3206 	item_size = btrfs_item_size(eb, path->slots[0]);
3207 
3208 	if (extent_key->type == BTRFS_METADATA_ITEM_KEY ||
3209 	    item_size >= sizeof(*ei) + sizeof(*bi)) {
3210 		unsigned long ptr = 0, end;
3211 
3212 		ei = btrfs_item_ptr(eb, path->slots[0],
3213 				struct btrfs_extent_item);
3214 		end = (unsigned long)ei + item_size;
3215 		if (extent_key->type == BTRFS_EXTENT_ITEM_KEY) {
3216 			bi = (struct btrfs_tree_block_info *)(ei + 1);
3217 			level = btrfs_tree_block_level(eb, bi);
3218 			ptr = (unsigned long)(bi + 1);
3219 		} else {
3220 			level = (int)extent_key->offset;
3221 			ptr = (unsigned long)(ei + 1);
3222 		}
3223 		generation = btrfs_extent_generation(eb, ei);
3224 
3225 		/*
3226 		 * We're reading random blocks without knowing their owner ahead
3227 		 * of time.  This is ok most of the time, as all reloc roots and
3228 		 * fs roots have the same lock type.  However normal trees do
3229 		 * not, and the only way to know ahead of time is to read the
3230 		 * inline ref offset.  We know it's an fs root if
3231 		 *
3232 		 * 1. There's more than one ref.
3233 		 * 2. There's a SHARED_DATA_REF_KEY set.
3234 		 * 3. FULL_BACKREF is set on the flags.
3235 		 *
3236 		 * Otherwise it's safe to assume that the ref offset == the
3237 		 * owner of this block, so we can use that when calling
3238 		 * read_tree_block.
3239 		 */
3240 		if (btrfs_extent_refs(eb, ei) == 1 &&
3241 		    !(btrfs_extent_flags(eb, ei) &
3242 		      BTRFS_BLOCK_FLAG_FULL_BACKREF) &&
3243 		    ptr < end) {
3244 			struct btrfs_extent_inline_ref *iref;
3245 			int type;
3246 
3247 			iref = (struct btrfs_extent_inline_ref *)ptr;
3248 			type = btrfs_get_extent_inline_ref_type(eb, iref,
3249 							BTRFS_REF_TYPE_BLOCK);
3250 			if (type == BTRFS_REF_TYPE_INVALID)
3251 				return -EINVAL;
3252 			if (type == BTRFS_TREE_BLOCK_REF_KEY)
3253 				owner = btrfs_extent_inline_ref_offset(eb, iref);
3254 		}
3255 	} else {
3256 		btrfs_print_leaf(eb);
3257 		btrfs_err(rc->block_group->fs_info,
3258 			  "unrecognized tree backref at tree block %llu slot %u",
3259 			  eb->start, path->slots[0]);
3260 		btrfs_release_path(path);
3261 		return -EUCLEAN;
3262 	}
3263 
3264 	btrfs_release_path(path);
3265 
3266 	BUG_ON(level == -1);
3267 
3268 	block = kmalloc(sizeof(*block), GFP_NOFS);
3269 	if (!block)
3270 		return -ENOMEM;
3271 
3272 	block->bytenr = extent_key->objectid;
3273 	block->key.objectid = rc->extent_root->fs_info->nodesize;
3274 	block->key.offset = generation;
3275 	block->level = level;
3276 	block->key_ready = false;
3277 	block->owner = owner;
3278 
3279 	rb_node = rb_simple_insert(blocks, block->bytenr, &block->rb_node);
3280 	if (rb_node)
3281 		btrfs_backref_panic(rc->extent_root->fs_info, block->bytenr,
3282 				    -EEXIST);
3283 
3284 	return 0;
3285 }
3286 
3287 /*
3288  * helper to add tree blocks for backref of type BTRFS_SHARED_DATA_REF_KEY
3289  */
3290 static int __add_tree_block(struct reloc_control *rc,
3291 			    u64 bytenr, u32 blocksize,
3292 			    struct rb_root *blocks)
3293 {
3294 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3295 	struct btrfs_path *path;
3296 	struct btrfs_key key;
3297 	int ret;
3298 	bool skinny = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
3299 
3300 	if (tree_block_processed(bytenr, rc))
3301 		return 0;
3302 
3303 	if (rb_simple_search(blocks, bytenr))
3304 		return 0;
3305 
3306 	path = btrfs_alloc_path();
3307 	if (!path)
3308 		return -ENOMEM;
3309 again:
3310 	key.objectid = bytenr;
3311 	if (skinny) {
3312 		key.type = BTRFS_METADATA_ITEM_KEY;
3313 		key.offset = (u64)-1;
3314 	} else {
3315 		key.type = BTRFS_EXTENT_ITEM_KEY;
3316 		key.offset = blocksize;
3317 	}
3318 
3319 	path->search_commit_root = 1;
3320 	path->skip_locking = 1;
3321 	ret = btrfs_search_slot(NULL, rc->extent_root, &key, path, 0, 0);
3322 	if (ret < 0)
3323 		goto out;
3324 
3325 	if (ret > 0 && skinny) {
3326 		if (path->slots[0]) {
3327 			path->slots[0]--;
3328 			btrfs_item_key_to_cpu(path->nodes[0], &key,
3329 					      path->slots[0]);
3330 			if (key.objectid == bytenr &&
3331 			    (key.type == BTRFS_METADATA_ITEM_KEY ||
3332 			     (key.type == BTRFS_EXTENT_ITEM_KEY &&
3333 			      key.offset == blocksize)))
3334 				ret = 0;
3335 		}
3336 
3337 		if (ret) {
3338 			skinny = false;
3339 			btrfs_release_path(path);
3340 			goto again;
3341 		}
3342 	}
3343 	if (ret) {
3344 		ASSERT(ret == 1);
3345 		btrfs_print_leaf(path->nodes[0]);
3346 		btrfs_err(fs_info,
3347 	     "tree block extent item (%llu) is not found in extent tree",
3348 		     bytenr);
3349 		WARN_ON(1);
3350 		ret = -EINVAL;
3351 		goto out;
3352 	}
3353 
3354 	ret = add_tree_block(rc, &key, path, blocks);
3355 out:
3356 	btrfs_free_path(path);
3357 	return ret;
3358 }
3359 
3360 static int delete_block_group_cache(struct btrfs_fs_info *fs_info,
3361 				    struct btrfs_block_group *block_group,
3362 				    struct inode *inode,
3363 				    u64 ino)
3364 {
3365 	struct btrfs_root *root = fs_info->tree_root;
3366 	struct btrfs_trans_handle *trans;
3367 	int ret = 0;
3368 
3369 	if (inode)
3370 		goto truncate;
3371 
3372 	inode = btrfs_iget(fs_info->sb, ino, root);
3373 	if (IS_ERR(inode))
3374 		return -ENOENT;
3375 
3376 truncate:
3377 	ret = btrfs_check_trunc_cache_free_space(fs_info,
3378 						 &fs_info->global_block_rsv);
3379 	if (ret)
3380 		goto out;
3381 
3382 	trans = btrfs_join_transaction(root);
3383 	if (IS_ERR(trans)) {
3384 		ret = PTR_ERR(trans);
3385 		goto out;
3386 	}
3387 
3388 	ret = btrfs_truncate_free_space_cache(trans, block_group, inode);
3389 
3390 	btrfs_end_transaction(trans);
3391 	btrfs_btree_balance_dirty(fs_info);
3392 out:
3393 	iput(inode);
3394 	return ret;
3395 }
3396 
3397 /*
3398  * Locate the free space cache EXTENT_DATA in root tree leaf and delete the
3399  * cache inode, to avoid free space cache data extent blocking data relocation.
3400  */
3401 static int delete_v1_space_cache(struct extent_buffer *leaf,
3402 				 struct btrfs_block_group *block_group,
3403 				 u64 data_bytenr)
3404 {
3405 	u64 space_cache_ino;
3406 	struct btrfs_file_extent_item *ei;
3407 	struct btrfs_key key;
3408 	bool found = false;
3409 	int i;
3410 	int ret;
3411 
3412 	if (btrfs_header_owner(leaf) != BTRFS_ROOT_TREE_OBJECTID)
3413 		return 0;
3414 
3415 	for (i = 0; i < btrfs_header_nritems(leaf); i++) {
3416 		u8 type;
3417 
3418 		btrfs_item_key_to_cpu(leaf, &key, i);
3419 		if (key.type != BTRFS_EXTENT_DATA_KEY)
3420 			continue;
3421 		ei = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
3422 		type = btrfs_file_extent_type(leaf, ei);
3423 
3424 		if ((type == BTRFS_FILE_EXTENT_REG ||
3425 		     type == BTRFS_FILE_EXTENT_PREALLOC) &&
3426 		    btrfs_file_extent_disk_bytenr(leaf, ei) == data_bytenr) {
3427 			found = true;
3428 			space_cache_ino = key.objectid;
3429 			break;
3430 		}
3431 	}
3432 	if (!found)
3433 		return -ENOENT;
3434 	ret = delete_block_group_cache(leaf->fs_info, block_group, NULL,
3435 					space_cache_ino);
3436 	return ret;
3437 }
3438 
3439 /*
3440  * helper to find all tree blocks that reference a given data extent
3441  */
3442 static noinline_for_stack int add_data_references(struct reloc_control *rc,
3443 						  const struct btrfs_key *extent_key,
3444 						  struct btrfs_path *path,
3445 						  struct rb_root *blocks)
3446 {
3447 	struct btrfs_backref_walk_ctx ctx = { 0 };
3448 	struct ulist_iterator leaf_uiter;
3449 	struct ulist_node *ref_node = NULL;
3450 	const u32 blocksize = rc->extent_root->fs_info->nodesize;
3451 	int ret = 0;
3452 
3453 	btrfs_release_path(path);
3454 
3455 	ctx.bytenr = extent_key->objectid;
3456 	ctx.skip_inode_ref_list = true;
3457 	ctx.fs_info = rc->extent_root->fs_info;
3458 
3459 	ret = btrfs_find_all_leafs(&ctx);
3460 	if (ret < 0)
3461 		return ret;
3462 
3463 	ULIST_ITER_INIT(&leaf_uiter);
3464 	while ((ref_node = ulist_next(ctx.refs, &leaf_uiter))) {
3465 		struct btrfs_tree_parent_check check = { 0 };
3466 		struct extent_buffer *eb;
3467 
3468 		eb = read_tree_block(ctx.fs_info, ref_node->val, &check);
3469 		if (IS_ERR(eb)) {
3470 			ret = PTR_ERR(eb);
3471 			break;
3472 		}
3473 		ret = delete_v1_space_cache(eb, rc->block_group,
3474 					    extent_key->objectid);
3475 		free_extent_buffer(eb);
3476 		if (ret < 0)
3477 			break;
3478 		ret = __add_tree_block(rc, ref_node->val, blocksize, blocks);
3479 		if (ret < 0)
3480 			break;
3481 	}
3482 	if (ret < 0)
3483 		free_block_list(blocks);
3484 	ulist_free(ctx.refs);
3485 	return ret;
3486 }
3487 
3488 /*
3489  * helper to find next unprocessed extent
3490  */
3491 static noinline_for_stack
3492 int find_next_extent(struct reloc_control *rc, struct btrfs_path *path,
3493 		     struct btrfs_key *extent_key)
3494 {
3495 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3496 	struct btrfs_key key;
3497 	struct extent_buffer *leaf;
3498 	u64 start, end, last;
3499 	int ret;
3500 
3501 	last = rc->block_group->start + rc->block_group->length;
3502 	while (1) {
3503 		bool block_found;
3504 
3505 		cond_resched();
3506 		if (rc->search_start >= last) {
3507 			ret = 1;
3508 			break;
3509 		}
3510 
3511 		key.objectid = rc->search_start;
3512 		key.type = BTRFS_EXTENT_ITEM_KEY;
3513 		key.offset = 0;
3514 
3515 		path->search_commit_root = 1;
3516 		path->skip_locking = 1;
3517 		ret = btrfs_search_slot(NULL, rc->extent_root, &key, path,
3518 					0, 0);
3519 		if (ret < 0)
3520 			break;
3521 next:
3522 		leaf = path->nodes[0];
3523 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
3524 			ret = btrfs_next_leaf(rc->extent_root, path);
3525 			if (ret != 0)
3526 				break;
3527 			leaf = path->nodes[0];
3528 		}
3529 
3530 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3531 		if (key.objectid >= last) {
3532 			ret = 1;
3533 			break;
3534 		}
3535 
3536 		if (key.type != BTRFS_EXTENT_ITEM_KEY &&
3537 		    key.type != BTRFS_METADATA_ITEM_KEY) {
3538 			path->slots[0]++;
3539 			goto next;
3540 		}
3541 
3542 		if (key.type == BTRFS_EXTENT_ITEM_KEY &&
3543 		    key.objectid + key.offset <= rc->search_start) {
3544 			path->slots[0]++;
3545 			goto next;
3546 		}
3547 
3548 		if (key.type == BTRFS_METADATA_ITEM_KEY &&
3549 		    key.objectid + fs_info->nodesize <=
3550 		    rc->search_start) {
3551 			path->slots[0]++;
3552 			goto next;
3553 		}
3554 
3555 		block_found = find_first_extent_bit(&rc->processed_blocks,
3556 						    key.objectid, &start, &end,
3557 						    EXTENT_DIRTY, NULL);
3558 
3559 		if (block_found && start <= key.objectid) {
3560 			btrfs_release_path(path);
3561 			rc->search_start = end + 1;
3562 		} else {
3563 			if (key.type == BTRFS_EXTENT_ITEM_KEY)
3564 				rc->search_start = key.objectid + key.offset;
3565 			else
3566 				rc->search_start = key.objectid +
3567 					fs_info->nodesize;
3568 			memcpy(extent_key, &key, sizeof(key));
3569 			return 0;
3570 		}
3571 	}
3572 	btrfs_release_path(path);
3573 	return ret;
3574 }
3575 
3576 static void set_reloc_control(struct reloc_control *rc)
3577 {
3578 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3579 
3580 	mutex_lock(&fs_info->reloc_mutex);
3581 	fs_info->reloc_ctl = rc;
3582 	mutex_unlock(&fs_info->reloc_mutex);
3583 }
3584 
3585 static void unset_reloc_control(struct reloc_control *rc)
3586 {
3587 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3588 
3589 	mutex_lock(&fs_info->reloc_mutex);
3590 	fs_info->reloc_ctl = NULL;
3591 	mutex_unlock(&fs_info->reloc_mutex);
3592 }
3593 
3594 static noinline_for_stack
3595 int prepare_to_relocate(struct reloc_control *rc)
3596 {
3597 	struct btrfs_trans_handle *trans;
3598 	int ret;
3599 
3600 	rc->block_rsv = btrfs_alloc_block_rsv(rc->extent_root->fs_info,
3601 					      BTRFS_BLOCK_RSV_TEMP);
3602 	if (!rc->block_rsv)
3603 		return -ENOMEM;
3604 
3605 	memset(&rc->cluster, 0, sizeof(rc->cluster));
3606 	rc->search_start = rc->block_group->start;
3607 	rc->extents_found = 0;
3608 	rc->nodes_relocated = 0;
3609 	rc->merging_rsv_size = 0;
3610 	rc->reserved_bytes = 0;
3611 	rc->block_rsv->size = rc->extent_root->fs_info->nodesize *
3612 			      RELOCATION_RESERVED_NODES;
3613 	ret = btrfs_block_rsv_refill(rc->extent_root->fs_info,
3614 				     rc->block_rsv, rc->block_rsv->size,
3615 				     BTRFS_RESERVE_FLUSH_ALL);
3616 	if (ret)
3617 		return ret;
3618 
3619 	rc->create_reloc_tree = true;
3620 	set_reloc_control(rc);
3621 
3622 	trans = btrfs_join_transaction(rc->extent_root);
3623 	if (IS_ERR(trans)) {
3624 		unset_reloc_control(rc);
3625 		/*
3626 		 * extent tree is not a ref_cow tree and has no reloc_root to
3627 		 * cleanup.  And callers are responsible to free the above
3628 		 * block rsv.
3629 		 */
3630 		return PTR_ERR(trans);
3631 	}
3632 
3633 	ret = btrfs_commit_transaction(trans);
3634 	if (ret)
3635 		unset_reloc_control(rc);
3636 
3637 	return ret;
3638 }
3639 
3640 static noinline_for_stack int relocate_block_group(struct reloc_control *rc)
3641 {
3642 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3643 	struct rb_root blocks = RB_ROOT;
3644 	struct btrfs_key key;
3645 	struct btrfs_trans_handle *trans = NULL;
3646 	struct btrfs_path *path;
3647 	struct btrfs_extent_item *ei;
3648 	u64 flags;
3649 	int ret;
3650 	int err = 0;
3651 	int progress = 0;
3652 
3653 	path = btrfs_alloc_path();
3654 	if (!path)
3655 		return -ENOMEM;
3656 	path->reada = READA_FORWARD;
3657 
3658 	ret = prepare_to_relocate(rc);
3659 	if (ret) {
3660 		err = ret;
3661 		goto out_free;
3662 	}
3663 
3664 	while (1) {
3665 		rc->reserved_bytes = 0;
3666 		ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv,
3667 					     rc->block_rsv->size,
3668 					     BTRFS_RESERVE_FLUSH_ALL);
3669 		if (ret) {
3670 			err = ret;
3671 			break;
3672 		}
3673 		progress++;
3674 		trans = btrfs_start_transaction(rc->extent_root, 0);
3675 		if (IS_ERR(trans)) {
3676 			err = PTR_ERR(trans);
3677 			trans = NULL;
3678 			break;
3679 		}
3680 restart:
3681 		if (update_backref_cache(trans, &rc->backref_cache)) {
3682 			btrfs_end_transaction(trans);
3683 			trans = NULL;
3684 			continue;
3685 		}
3686 
3687 		ret = find_next_extent(rc, path, &key);
3688 		if (ret < 0)
3689 			err = ret;
3690 		if (ret != 0)
3691 			break;
3692 
3693 		rc->extents_found++;
3694 
3695 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3696 				    struct btrfs_extent_item);
3697 		flags = btrfs_extent_flags(path->nodes[0], ei);
3698 
3699 		/*
3700 		 * If we are relocating a simple quota owned extent item, we
3701 		 * need to note the owner on the reloc data root so that when
3702 		 * we allocate the replacement item, we can attribute it to the
3703 		 * correct eventual owner (rather than the reloc data root).
3704 		 */
3705 		if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE) {
3706 			struct btrfs_root *root = BTRFS_I(rc->data_inode)->root;
3707 			u64 owning_root_id = btrfs_get_extent_owner_root(fs_info,
3708 								 path->nodes[0],
3709 								 path->slots[0]);
3710 
3711 			root->relocation_src_root = owning_root_id;
3712 		}
3713 
3714 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
3715 			ret = add_tree_block(rc, &key, path, &blocks);
3716 		} else if (rc->stage == UPDATE_DATA_PTRS &&
3717 			   (flags & BTRFS_EXTENT_FLAG_DATA)) {
3718 			ret = add_data_references(rc, &key, path, &blocks);
3719 		} else {
3720 			btrfs_release_path(path);
3721 			ret = 0;
3722 		}
3723 		if (ret < 0) {
3724 			err = ret;
3725 			break;
3726 		}
3727 
3728 		if (!RB_EMPTY_ROOT(&blocks)) {
3729 			ret = relocate_tree_blocks(trans, rc, &blocks);
3730 			if (ret < 0) {
3731 				if (ret != -EAGAIN) {
3732 					err = ret;
3733 					break;
3734 				}
3735 				rc->extents_found--;
3736 				rc->search_start = key.objectid;
3737 			}
3738 		}
3739 
3740 		btrfs_end_transaction_throttle(trans);
3741 		btrfs_btree_balance_dirty(fs_info);
3742 		trans = NULL;
3743 
3744 		if (rc->stage == MOVE_DATA_EXTENTS &&
3745 		    (flags & BTRFS_EXTENT_FLAG_DATA)) {
3746 			rc->found_file_extent = true;
3747 			ret = relocate_data_extent(rc->data_inode,
3748 						   &key, &rc->cluster);
3749 			if (ret < 0) {
3750 				err = ret;
3751 				break;
3752 			}
3753 		}
3754 		if (btrfs_should_cancel_balance(fs_info)) {
3755 			err = -ECANCELED;
3756 			break;
3757 		}
3758 	}
3759 	if (trans && progress && err == -ENOSPC) {
3760 		ret = btrfs_force_chunk_alloc(trans, rc->block_group->flags);
3761 		if (ret == 1) {
3762 			err = 0;
3763 			progress = 0;
3764 			goto restart;
3765 		}
3766 	}
3767 
3768 	btrfs_release_path(path);
3769 	clear_extent_bits(&rc->processed_blocks, 0, (u64)-1, EXTENT_DIRTY);
3770 
3771 	if (trans) {
3772 		btrfs_end_transaction_throttle(trans);
3773 		btrfs_btree_balance_dirty(fs_info);
3774 	}
3775 
3776 	if (!err) {
3777 		ret = relocate_file_extent_cluster(rc->data_inode,
3778 						   &rc->cluster);
3779 		if (ret < 0)
3780 			err = ret;
3781 	}
3782 
3783 	rc->create_reloc_tree = false;
3784 	set_reloc_control(rc);
3785 
3786 	btrfs_backref_release_cache(&rc->backref_cache);
3787 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
3788 
3789 	/*
3790 	 * Even in the case when the relocation is cancelled, we should all go
3791 	 * through prepare_to_merge() and merge_reloc_roots().
3792 	 *
3793 	 * For error (including cancelled balance), prepare_to_merge() will
3794 	 * mark all reloc trees orphan, then queue them for cleanup in
3795 	 * merge_reloc_roots()
3796 	 */
3797 	err = prepare_to_merge(rc, err);
3798 
3799 	merge_reloc_roots(rc);
3800 
3801 	rc->merge_reloc_tree = false;
3802 	unset_reloc_control(rc);
3803 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
3804 
3805 	/* get rid of pinned extents */
3806 	trans = btrfs_join_transaction(rc->extent_root);
3807 	if (IS_ERR(trans)) {
3808 		err = PTR_ERR(trans);
3809 		goto out_free;
3810 	}
3811 	ret = btrfs_commit_transaction(trans);
3812 	if (ret && !err)
3813 		err = ret;
3814 out_free:
3815 	ret = clean_dirty_subvols(rc);
3816 	if (ret < 0 && !err)
3817 		err = ret;
3818 	btrfs_free_block_rsv(fs_info, rc->block_rsv);
3819 	btrfs_free_path(path);
3820 	return err;
3821 }
3822 
3823 static int __insert_orphan_inode(struct btrfs_trans_handle *trans,
3824 				 struct btrfs_root *root, u64 objectid)
3825 {
3826 	struct btrfs_path *path;
3827 	struct btrfs_inode_item *item;
3828 	struct extent_buffer *leaf;
3829 	int ret;
3830 
3831 	path = btrfs_alloc_path();
3832 	if (!path)
3833 		return -ENOMEM;
3834 
3835 	ret = btrfs_insert_empty_inode(trans, root, path, objectid);
3836 	if (ret)
3837 		goto out;
3838 
3839 	leaf = path->nodes[0];
3840 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item);
3841 	memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3842 	btrfs_set_inode_generation(leaf, item, 1);
3843 	btrfs_set_inode_size(leaf, item, 0);
3844 	btrfs_set_inode_mode(leaf, item, S_IFREG | 0600);
3845 	btrfs_set_inode_flags(leaf, item, BTRFS_INODE_NOCOMPRESS |
3846 					  BTRFS_INODE_PREALLOC);
3847 	btrfs_mark_buffer_dirty(trans, leaf);
3848 out:
3849 	btrfs_free_path(path);
3850 	return ret;
3851 }
3852 
3853 static void delete_orphan_inode(struct btrfs_trans_handle *trans,
3854 				struct btrfs_root *root, u64 objectid)
3855 {
3856 	struct btrfs_path *path;
3857 	struct btrfs_key key;
3858 	int ret = 0;
3859 
3860 	path = btrfs_alloc_path();
3861 	if (!path) {
3862 		ret = -ENOMEM;
3863 		goto out;
3864 	}
3865 
3866 	key.objectid = objectid;
3867 	key.type = BTRFS_INODE_ITEM_KEY;
3868 	key.offset = 0;
3869 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3870 	if (ret) {
3871 		if (ret > 0)
3872 			ret = -ENOENT;
3873 		goto out;
3874 	}
3875 	ret = btrfs_del_item(trans, root, path);
3876 out:
3877 	if (ret)
3878 		btrfs_abort_transaction(trans, ret);
3879 	btrfs_free_path(path);
3880 }
3881 
3882 /*
3883  * helper to create inode for data relocation.
3884  * the inode is in data relocation tree and its link count is 0
3885  */
3886 static noinline_for_stack struct inode *create_reloc_inode(
3887 					struct btrfs_fs_info *fs_info,
3888 					const struct btrfs_block_group *group)
3889 {
3890 	struct inode *inode = NULL;
3891 	struct btrfs_trans_handle *trans;
3892 	struct btrfs_root *root;
3893 	u64 objectid;
3894 	int ret = 0;
3895 
3896 	root = btrfs_grab_root(fs_info->data_reloc_root);
3897 	trans = btrfs_start_transaction(root, 6);
3898 	if (IS_ERR(trans)) {
3899 		btrfs_put_root(root);
3900 		return ERR_CAST(trans);
3901 	}
3902 
3903 	ret = btrfs_get_free_objectid(root, &objectid);
3904 	if (ret)
3905 		goto out;
3906 
3907 	ret = __insert_orphan_inode(trans, root, objectid);
3908 	if (ret)
3909 		goto out;
3910 
3911 	inode = btrfs_iget(fs_info->sb, objectid, root);
3912 	if (IS_ERR(inode)) {
3913 		delete_orphan_inode(trans, root, objectid);
3914 		ret = PTR_ERR(inode);
3915 		inode = NULL;
3916 		goto out;
3917 	}
3918 	BTRFS_I(inode)->index_cnt = group->start;
3919 
3920 	ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3921 out:
3922 	btrfs_put_root(root);
3923 	btrfs_end_transaction(trans);
3924 	btrfs_btree_balance_dirty(fs_info);
3925 	if (ret) {
3926 		iput(inode);
3927 		inode = ERR_PTR(ret);
3928 	}
3929 	return inode;
3930 }
3931 
3932 /*
3933  * Mark start of chunk relocation that is cancellable. Check if the cancellation
3934  * has been requested meanwhile and don't start in that case.
3935  *
3936  * Return:
3937  *   0             success
3938  *   -EINPROGRESS  operation is already in progress, that's probably a bug
3939  *   -ECANCELED    cancellation request was set before the operation started
3940  */
3941 static int reloc_chunk_start(struct btrfs_fs_info *fs_info)
3942 {
3943 	if (test_and_set_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags)) {
3944 		/* This should not happen */
3945 		btrfs_err(fs_info, "reloc already running, cannot start");
3946 		return -EINPROGRESS;
3947 	}
3948 
3949 	if (atomic_read(&fs_info->reloc_cancel_req) > 0) {
3950 		btrfs_info(fs_info, "chunk relocation canceled on start");
3951 		/*
3952 		 * On cancel, clear all requests but let the caller mark
3953 		 * the end after cleanup operations.
3954 		 */
3955 		atomic_set(&fs_info->reloc_cancel_req, 0);
3956 		return -ECANCELED;
3957 	}
3958 	return 0;
3959 }
3960 
3961 /*
3962  * Mark end of chunk relocation that is cancellable and wake any waiters.
3963  */
3964 static void reloc_chunk_end(struct btrfs_fs_info *fs_info)
3965 {
3966 	/* Requested after start, clear bit first so any waiters can continue */
3967 	if (atomic_read(&fs_info->reloc_cancel_req) > 0)
3968 		btrfs_info(fs_info, "chunk relocation canceled during operation");
3969 	clear_and_wake_up_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags);
3970 	atomic_set(&fs_info->reloc_cancel_req, 0);
3971 }
3972 
3973 static struct reloc_control *alloc_reloc_control(struct btrfs_fs_info *fs_info)
3974 {
3975 	struct reloc_control *rc;
3976 
3977 	rc = kzalloc(sizeof(*rc), GFP_NOFS);
3978 	if (!rc)
3979 		return NULL;
3980 
3981 	INIT_LIST_HEAD(&rc->reloc_roots);
3982 	INIT_LIST_HEAD(&rc->dirty_subvol_roots);
3983 	btrfs_backref_init_cache(fs_info, &rc->backref_cache, true);
3984 	rc->reloc_root_tree.rb_root = RB_ROOT;
3985 	spin_lock_init(&rc->reloc_root_tree.lock);
3986 	extent_io_tree_init(fs_info, &rc->processed_blocks, IO_TREE_RELOC_BLOCKS);
3987 	return rc;
3988 }
3989 
3990 static void free_reloc_control(struct reloc_control *rc)
3991 {
3992 	struct mapping_node *node, *tmp;
3993 
3994 	free_reloc_roots(&rc->reloc_roots);
3995 	rbtree_postorder_for_each_entry_safe(node, tmp,
3996 			&rc->reloc_root_tree.rb_root, rb_node)
3997 		kfree(node);
3998 
3999 	kfree(rc);
4000 }
4001 
4002 /*
4003  * Print the block group being relocated
4004  */
4005 static void describe_relocation(struct btrfs_fs_info *fs_info,
4006 				struct btrfs_block_group *block_group)
4007 {
4008 	char buf[128] = {'\0'};
4009 
4010 	btrfs_describe_block_groups(block_group->flags, buf, sizeof(buf));
4011 
4012 	btrfs_info(fs_info,
4013 		   "relocating block group %llu flags %s",
4014 		   block_group->start, buf);
4015 }
4016 
4017 static const char *stage_to_string(enum reloc_stage stage)
4018 {
4019 	if (stage == MOVE_DATA_EXTENTS)
4020 		return "move data extents";
4021 	if (stage == UPDATE_DATA_PTRS)
4022 		return "update data pointers";
4023 	return "unknown";
4024 }
4025 
4026 /*
4027  * function to relocate all extents in a block group.
4028  */
4029 int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start)
4030 {
4031 	struct btrfs_block_group *bg;
4032 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, group_start);
4033 	struct reloc_control *rc;
4034 	struct inode *inode;
4035 	struct btrfs_path *path;
4036 	int ret;
4037 	int rw = 0;
4038 	int err = 0;
4039 
4040 	/*
4041 	 * This only gets set if we had a half-deleted snapshot on mount.  We
4042 	 * cannot allow relocation to start while we're still trying to clean up
4043 	 * these pending deletions.
4044 	 */
4045 	ret = wait_on_bit(&fs_info->flags, BTRFS_FS_UNFINISHED_DROPS, TASK_INTERRUPTIBLE);
4046 	if (ret)
4047 		return ret;
4048 
4049 	/* We may have been woken up by close_ctree, so bail if we're closing. */
4050 	if (btrfs_fs_closing(fs_info))
4051 		return -EINTR;
4052 
4053 	bg = btrfs_lookup_block_group(fs_info, group_start);
4054 	if (!bg)
4055 		return -ENOENT;
4056 
4057 	/*
4058 	 * Relocation of a data block group creates ordered extents.  Without
4059 	 * sb_start_write(), we can freeze the filesystem while unfinished
4060 	 * ordered extents are left. Such ordered extents can cause a deadlock
4061 	 * e.g. when syncfs() is waiting for their completion but they can't
4062 	 * finish because they block when joining a transaction, due to the
4063 	 * fact that the freeze locks are being held in write mode.
4064 	 */
4065 	if (bg->flags & BTRFS_BLOCK_GROUP_DATA)
4066 		ASSERT(sb_write_started(fs_info->sb));
4067 
4068 	if (btrfs_pinned_by_swapfile(fs_info, bg)) {
4069 		btrfs_put_block_group(bg);
4070 		return -ETXTBSY;
4071 	}
4072 
4073 	rc = alloc_reloc_control(fs_info);
4074 	if (!rc) {
4075 		btrfs_put_block_group(bg);
4076 		return -ENOMEM;
4077 	}
4078 
4079 	ret = reloc_chunk_start(fs_info);
4080 	if (ret < 0) {
4081 		err = ret;
4082 		goto out_put_bg;
4083 	}
4084 
4085 	rc->extent_root = extent_root;
4086 	rc->block_group = bg;
4087 
4088 	ret = btrfs_inc_block_group_ro(rc->block_group, true);
4089 	if (ret) {
4090 		err = ret;
4091 		goto out;
4092 	}
4093 	rw = 1;
4094 
4095 	path = btrfs_alloc_path();
4096 	if (!path) {
4097 		err = -ENOMEM;
4098 		goto out;
4099 	}
4100 
4101 	inode = lookup_free_space_inode(rc->block_group, path);
4102 	btrfs_free_path(path);
4103 
4104 	if (!IS_ERR(inode))
4105 		ret = delete_block_group_cache(fs_info, rc->block_group, inode, 0);
4106 	else
4107 		ret = PTR_ERR(inode);
4108 
4109 	if (ret && ret != -ENOENT) {
4110 		err = ret;
4111 		goto out;
4112 	}
4113 
4114 	rc->data_inode = create_reloc_inode(fs_info, rc->block_group);
4115 	if (IS_ERR(rc->data_inode)) {
4116 		err = PTR_ERR(rc->data_inode);
4117 		rc->data_inode = NULL;
4118 		goto out;
4119 	}
4120 
4121 	describe_relocation(fs_info, rc->block_group);
4122 
4123 	btrfs_wait_block_group_reservations(rc->block_group);
4124 	btrfs_wait_nocow_writers(rc->block_group);
4125 	btrfs_wait_ordered_roots(fs_info, U64_MAX,
4126 				 rc->block_group->start,
4127 				 rc->block_group->length);
4128 
4129 	ret = btrfs_zone_finish(rc->block_group);
4130 	WARN_ON(ret && ret != -EAGAIN);
4131 
4132 	while (1) {
4133 		enum reloc_stage finishes_stage;
4134 
4135 		mutex_lock(&fs_info->cleaner_mutex);
4136 		ret = relocate_block_group(rc);
4137 		mutex_unlock(&fs_info->cleaner_mutex);
4138 		if (ret < 0)
4139 			err = ret;
4140 
4141 		finishes_stage = rc->stage;
4142 		/*
4143 		 * We may have gotten ENOSPC after we already dirtied some
4144 		 * extents.  If writeout happens while we're relocating a
4145 		 * different block group we could end up hitting the
4146 		 * BUG_ON(rc->stage == UPDATE_DATA_PTRS) in
4147 		 * btrfs_reloc_cow_block.  Make sure we write everything out
4148 		 * properly so we don't trip over this problem, and then break
4149 		 * out of the loop if we hit an error.
4150 		 */
4151 		if (rc->stage == MOVE_DATA_EXTENTS && rc->found_file_extent) {
4152 			ret = btrfs_wait_ordered_range(rc->data_inode, 0,
4153 						       (u64)-1);
4154 			if (ret)
4155 				err = ret;
4156 			invalidate_mapping_pages(rc->data_inode->i_mapping,
4157 						 0, -1);
4158 			rc->stage = UPDATE_DATA_PTRS;
4159 		}
4160 
4161 		if (err < 0)
4162 			goto out;
4163 
4164 		if (rc->extents_found == 0)
4165 			break;
4166 
4167 		btrfs_info(fs_info, "found %llu extents, stage: %s",
4168 			   rc->extents_found, stage_to_string(finishes_stage));
4169 	}
4170 
4171 	WARN_ON(rc->block_group->pinned > 0);
4172 	WARN_ON(rc->block_group->reserved > 0);
4173 	WARN_ON(rc->block_group->used > 0);
4174 out:
4175 	if (err && rw)
4176 		btrfs_dec_block_group_ro(rc->block_group);
4177 	iput(rc->data_inode);
4178 out_put_bg:
4179 	btrfs_put_block_group(bg);
4180 	reloc_chunk_end(fs_info);
4181 	free_reloc_control(rc);
4182 	return err;
4183 }
4184 
4185 static noinline_for_stack int mark_garbage_root(struct btrfs_root *root)
4186 {
4187 	struct btrfs_fs_info *fs_info = root->fs_info;
4188 	struct btrfs_trans_handle *trans;
4189 	int ret, err;
4190 
4191 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
4192 	if (IS_ERR(trans))
4193 		return PTR_ERR(trans);
4194 
4195 	memset(&root->root_item.drop_progress, 0,
4196 		sizeof(root->root_item.drop_progress));
4197 	btrfs_set_root_drop_level(&root->root_item, 0);
4198 	btrfs_set_root_refs(&root->root_item, 0);
4199 	ret = btrfs_update_root(trans, fs_info->tree_root,
4200 				&root->root_key, &root->root_item);
4201 
4202 	err = btrfs_end_transaction(trans);
4203 	if (err)
4204 		return err;
4205 	return ret;
4206 }
4207 
4208 /*
4209  * recover relocation interrupted by system crash.
4210  *
4211  * this function resumes merging reloc trees with corresponding fs trees.
4212  * this is important for keeping the sharing of tree blocks
4213  */
4214 int btrfs_recover_relocation(struct btrfs_fs_info *fs_info)
4215 {
4216 	LIST_HEAD(reloc_roots);
4217 	struct btrfs_key key;
4218 	struct btrfs_root *fs_root;
4219 	struct btrfs_root *reloc_root;
4220 	struct btrfs_path *path;
4221 	struct extent_buffer *leaf;
4222 	struct reloc_control *rc = NULL;
4223 	struct btrfs_trans_handle *trans;
4224 	int ret;
4225 	int err = 0;
4226 
4227 	path = btrfs_alloc_path();
4228 	if (!path)
4229 		return -ENOMEM;
4230 	path->reada = READA_BACK;
4231 
4232 	key.objectid = BTRFS_TREE_RELOC_OBJECTID;
4233 	key.type = BTRFS_ROOT_ITEM_KEY;
4234 	key.offset = (u64)-1;
4235 
4236 	while (1) {
4237 		ret = btrfs_search_slot(NULL, fs_info->tree_root, &key,
4238 					path, 0, 0);
4239 		if (ret < 0) {
4240 			err = ret;
4241 			goto out;
4242 		}
4243 		if (ret > 0) {
4244 			if (path->slots[0] == 0)
4245 				break;
4246 			path->slots[0]--;
4247 		}
4248 		leaf = path->nodes[0];
4249 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4250 		btrfs_release_path(path);
4251 
4252 		if (key.objectid != BTRFS_TREE_RELOC_OBJECTID ||
4253 		    key.type != BTRFS_ROOT_ITEM_KEY)
4254 			break;
4255 
4256 		reloc_root = btrfs_read_tree_root(fs_info->tree_root, &key);
4257 		if (IS_ERR(reloc_root)) {
4258 			err = PTR_ERR(reloc_root);
4259 			goto out;
4260 		}
4261 
4262 		set_bit(BTRFS_ROOT_SHAREABLE, &reloc_root->state);
4263 		list_add(&reloc_root->root_list, &reloc_roots);
4264 
4265 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
4266 			fs_root = btrfs_get_fs_root(fs_info,
4267 					reloc_root->root_key.offset, false);
4268 			if (IS_ERR(fs_root)) {
4269 				ret = PTR_ERR(fs_root);
4270 				if (ret != -ENOENT) {
4271 					err = ret;
4272 					goto out;
4273 				}
4274 				ret = mark_garbage_root(reloc_root);
4275 				if (ret < 0) {
4276 					err = ret;
4277 					goto out;
4278 				}
4279 			} else {
4280 				btrfs_put_root(fs_root);
4281 			}
4282 		}
4283 
4284 		if (key.offset == 0)
4285 			break;
4286 
4287 		key.offset--;
4288 	}
4289 	btrfs_release_path(path);
4290 
4291 	if (list_empty(&reloc_roots))
4292 		goto out;
4293 
4294 	rc = alloc_reloc_control(fs_info);
4295 	if (!rc) {
4296 		err = -ENOMEM;
4297 		goto out;
4298 	}
4299 
4300 	ret = reloc_chunk_start(fs_info);
4301 	if (ret < 0) {
4302 		err = ret;
4303 		goto out_end;
4304 	}
4305 
4306 	rc->extent_root = btrfs_extent_root(fs_info, 0);
4307 
4308 	set_reloc_control(rc);
4309 
4310 	trans = btrfs_join_transaction(rc->extent_root);
4311 	if (IS_ERR(trans)) {
4312 		err = PTR_ERR(trans);
4313 		goto out_unset;
4314 	}
4315 
4316 	rc->merge_reloc_tree = true;
4317 
4318 	while (!list_empty(&reloc_roots)) {
4319 		reloc_root = list_entry(reloc_roots.next,
4320 					struct btrfs_root, root_list);
4321 		list_del(&reloc_root->root_list);
4322 
4323 		if (btrfs_root_refs(&reloc_root->root_item) == 0) {
4324 			list_add_tail(&reloc_root->root_list,
4325 				      &rc->reloc_roots);
4326 			continue;
4327 		}
4328 
4329 		fs_root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
4330 					    false);
4331 		if (IS_ERR(fs_root)) {
4332 			err = PTR_ERR(fs_root);
4333 			list_add_tail(&reloc_root->root_list, &reloc_roots);
4334 			btrfs_end_transaction(trans);
4335 			goto out_unset;
4336 		}
4337 
4338 		err = __add_reloc_root(reloc_root);
4339 		ASSERT(err != -EEXIST);
4340 		if (err) {
4341 			list_add_tail(&reloc_root->root_list, &reloc_roots);
4342 			btrfs_put_root(fs_root);
4343 			btrfs_end_transaction(trans);
4344 			goto out_unset;
4345 		}
4346 		fs_root->reloc_root = btrfs_grab_root(reloc_root);
4347 		btrfs_put_root(fs_root);
4348 	}
4349 
4350 	err = btrfs_commit_transaction(trans);
4351 	if (err)
4352 		goto out_unset;
4353 
4354 	merge_reloc_roots(rc);
4355 
4356 	unset_reloc_control(rc);
4357 
4358 	trans = btrfs_join_transaction(rc->extent_root);
4359 	if (IS_ERR(trans)) {
4360 		err = PTR_ERR(trans);
4361 		goto out_clean;
4362 	}
4363 	err = btrfs_commit_transaction(trans);
4364 out_clean:
4365 	ret = clean_dirty_subvols(rc);
4366 	if (ret < 0 && !err)
4367 		err = ret;
4368 out_unset:
4369 	unset_reloc_control(rc);
4370 out_end:
4371 	reloc_chunk_end(fs_info);
4372 	free_reloc_control(rc);
4373 out:
4374 	free_reloc_roots(&reloc_roots);
4375 
4376 	btrfs_free_path(path);
4377 
4378 	if (err == 0) {
4379 		/* cleanup orphan inode in data relocation tree */
4380 		fs_root = btrfs_grab_root(fs_info->data_reloc_root);
4381 		ASSERT(fs_root);
4382 		err = btrfs_orphan_cleanup(fs_root);
4383 		btrfs_put_root(fs_root);
4384 	}
4385 	return err;
4386 }
4387 
4388 /*
4389  * helper to add ordered checksum for data relocation.
4390  *
4391  * cloning checksum properly handles the nodatasum extents.
4392  * it also saves CPU time to re-calculate the checksum.
4393  */
4394 int btrfs_reloc_clone_csums(struct btrfs_ordered_extent *ordered)
4395 {
4396 	struct btrfs_inode *inode = BTRFS_I(ordered->inode);
4397 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
4398 	u64 disk_bytenr = ordered->file_offset + inode->index_cnt;
4399 	struct btrfs_root *csum_root = btrfs_csum_root(fs_info, disk_bytenr);
4400 	LIST_HEAD(list);
4401 	int ret;
4402 
4403 	ret = btrfs_lookup_csums_list(csum_root, disk_bytenr,
4404 				      disk_bytenr + ordered->num_bytes - 1,
4405 				      &list, false);
4406 	if (ret < 0) {
4407 		btrfs_mark_ordered_extent_error(ordered);
4408 		return ret;
4409 	}
4410 
4411 	while (!list_empty(&list)) {
4412 		struct btrfs_ordered_sum *sums =
4413 			list_entry(list.next, struct btrfs_ordered_sum, list);
4414 
4415 		list_del_init(&sums->list);
4416 
4417 		/*
4418 		 * We need to offset the new_bytenr based on where the csum is.
4419 		 * We need to do this because we will read in entire prealloc
4420 		 * extents but we may have written to say the middle of the
4421 		 * prealloc extent, so we need to make sure the csum goes with
4422 		 * the right disk offset.
4423 		 *
4424 		 * We can do this because the data reloc inode refers strictly
4425 		 * to the on disk bytes, so we don't have to worry about
4426 		 * disk_len vs real len like with real inodes since it's all
4427 		 * disk length.
4428 		 */
4429 		sums->logical = ordered->disk_bytenr + sums->logical - disk_bytenr;
4430 		btrfs_add_ordered_sum(ordered, sums);
4431 	}
4432 
4433 	return 0;
4434 }
4435 
4436 int btrfs_reloc_cow_block(struct btrfs_trans_handle *trans,
4437 			  struct btrfs_root *root,
4438 			  const struct extent_buffer *buf,
4439 			  struct extent_buffer *cow)
4440 {
4441 	struct btrfs_fs_info *fs_info = root->fs_info;
4442 	struct reloc_control *rc;
4443 	struct btrfs_backref_node *node;
4444 	int first_cow = 0;
4445 	int level;
4446 	int ret = 0;
4447 
4448 	rc = fs_info->reloc_ctl;
4449 	if (!rc)
4450 		return 0;
4451 
4452 	BUG_ON(rc->stage == UPDATE_DATA_PTRS && btrfs_is_data_reloc_root(root));
4453 
4454 	level = btrfs_header_level(buf);
4455 	if (btrfs_header_generation(buf) <=
4456 	    btrfs_root_last_snapshot(&root->root_item))
4457 		first_cow = 1;
4458 
4459 	if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID && rc->create_reloc_tree) {
4460 		WARN_ON(!first_cow && level == 0);
4461 
4462 		node = rc->backref_cache.path[level];
4463 		BUG_ON(node->bytenr != buf->start &&
4464 		       node->new_bytenr != buf->start);
4465 
4466 		btrfs_backref_drop_node_buffer(node);
4467 		atomic_inc(&cow->refs);
4468 		node->eb = cow;
4469 		node->new_bytenr = cow->start;
4470 
4471 		if (!node->pending) {
4472 			list_move_tail(&node->list,
4473 				       &rc->backref_cache.pending[level]);
4474 			node->pending = 1;
4475 		}
4476 
4477 		if (first_cow)
4478 			mark_block_processed(rc, node);
4479 
4480 		if (first_cow && level > 0)
4481 			rc->nodes_relocated += buf->len;
4482 	}
4483 
4484 	if (level == 0 && first_cow && rc->stage == UPDATE_DATA_PTRS)
4485 		ret = replace_file_extents(trans, rc, root, cow);
4486 	return ret;
4487 }
4488 
4489 /*
4490  * called before creating snapshot. it calculates metadata reservation
4491  * required for relocating tree blocks in the snapshot
4492  */
4493 void btrfs_reloc_pre_snapshot(struct btrfs_pending_snapshot *pending,
4494 			      u64 *bytes_to_reserve)
4495 {
4496 	struct btrfs_root *root = pending->root;
4497 	struct reloc_control *rc = root->fs_info->reloc_ctl;
4498 
4499 	if (!rc || !have_reloc_root(root))
4500 		return;
4501 
4502 	if (!rc->merge_reloc_tree)
4503 		return;
4504 
4505 	root = root->reloc_root;
4506 	BUG_ON(btrfs_root_refs(&root->root_item) == 0);
4507 	/*
4508 	 * relocation is in the stage of merging trees. the space
4509 	 * used by merging a reloc tree is twice the size of
4510 	 * relocated tree nodes in the worst case. half for cowing
4511 	 * the reloc tree, half for cowing the fs tree. the space
4512 	 * used by cowing the reloc tree will be freed after the
4513 	 * tree is dropped. if we create snapshot, cowing the fs
4514 	 * tree may use more space than it frees. so we need
4515 	 * reserve extra space.
4516 	 */
4517 	*bytes_to_reserve += rc->nodes_relocated;
4518 }
4519 
4520 /*
4521  * called after snapshot is created. migrate block reservation
4522  * and create reloc root for the newly created snapshot
4523  *
4524  * This is similar to btrfs_init_reloc_root(), we come out of here with two
4525  * references held on the reloc_root, one for root->reloc_root and one for
4526  * rc->reloc_roots.
4527  */
4528 int btrfs_reloc_post_snapshot(struct btrfs_trans_handle *trans,
4529 			       struct btrfs_pending_snapshot *pending)
4530 {
4531 	struct btrfs_root *root = pending->root;
4532 	struct btrfs_root *reloc_root;
4533 	struct btrfs_root *new_root;
4534 	struct reloc_control *rc = root->fs_info->reloc_ctl;
4535 	int ret;
4536 
4537 	if (!rc || !have_reloc_root(root))
4538 		return 0;
4539 
4540 	rc = root->fs_info->reloc_ctl;
4541 	rc->merging_rsv_size += rc->nodes_relocated;
4542 
4543 	if (rc->merge_reloc_tree) {
4544 		ret = btrfs_block_rsv_migrate(&pending->block_rsv,
4545 					      rc->block_rsv,
4546 					      rc->nodes_relocated, true);
4547 		if (ret)
4548 			return ret;
4549 	}
4550 
4551 	new_root = pending->snap;
4552 	reloc_root = create_reloc_root(trans, root->reloc_root, btrfs_root_id(new_root));
4553 	if (IS_ERR(reloc_root))
4554 		return PTR_ERR(reloc_root);
4555 
4556 	ret = __add_reloc_root(reloc_root);
4557 	ASSERT(ret != -EEXIST);
4558 	if (ret) {
4559 		/* Pairs with create_reloc_root */
4560 		btrfs_put_root(reloc_root);
4561 		return ret;
4562 	}
4563 	new_root->reloc_root = btrfs_grab_root(reloc_root);
4564 
4565 	if (rc->create_reloc_tree)
4566 		ret = clone_backref_node(trans, rc, root, reloc_root);
4567 	return ret;
4568 }
4569 
4570 /*
4571  * Get the current bytenr for the block group which is being relocated.
4572  *
4573  * Return U64_MAX if no running relocation.
4574  */
4575 u64 btrfs_get_reloc_bg_bytenr(const struct btrfs_fs_info *fs_info)
4576 {
4577 	u64 logical = U64_MAX;
4578 
4579 	lockdep_assert_held(&fs_info->reloc_mutex);
4580 
4581 	if (fs_info->reloc_ctl && fs_info->reloc_ctl->block_group)
4582 		logical = fs_info->reloc_ctl->block_group->start;
4583 	return logical;
4584 }
4585