xref: /linux/fs/btrfs/relocation.c (revision fafb66e5903c2bcfc7b7e259042a8282f18a6faa)
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 #include "raid-stripe-tree.h"
40 #include "free-space-tree.h"
41 
42 /*
43  * Relocation overview
44  *
45  * [What does relocation do]
46  *
47  * The objective of relocation is to relocate all extents of the target block
48  * group to other block groups.
49  * This is utilized by resize (shrink only), profile converting, compacting
50  * space, or balance routine to spread chunks over devices.
51  *
52  * 		Before		|		After
53  * ------------------------------------------------------------------
54  *  BG A: 10 data extents	| BG A: deleted
55  *  BG B:  2 data extents	| BG B: 10 data extents (2 old + 8 relocated)
56  *  BG C:  1 extents		| BG C:  3 data extents (1 old + 2 relocated)
57  *
58  * [How does relocation work]
59  *
60  * 1.   Mark the target block group read-only
61  *      New extents won't be allocated from the target block group.
62  *
63  * 2.1  Record each extent in the target block group
64  *      To build a proper map of extents to be relocated.
65  *
66  * 2.2  Build data reloc tree and reloc trees
67  *      Data reloc tree will contain an inode, recording all newly relocated
68  *      data extents.
69  *      There will be only one data reloc tree for one data block group.
70  *
71  *      Reloc tree will be a special snapshot of its source tree, containing
72  *      relocated tree blocks.
73  *      Each tree referring to a tree block in target block group will get its
74  *      reloc tree built.
75  *
76  * 2.3  Swap source tree with its corresponding reloc tree
77  *      Each involved tree only refers to new extents after swap.
78  *
79  * 3.   Cleanup reloc trees and data reloc tree.
80  *      As old extents in the target block group are still referenced by reloc
81  *      trees, we need to clean them up before really freeing the target block
82  *      group.
83  *
84  * The main complexity is in steps 2.2 and 2.3.
85  *
86  * The entry point of relocation is relocate_block_group() function.
87  */
88 
89 #define RELOCATION_RESERVED_NODES	256
90 /*
91  * map address of tree root to tree
92  */
93 struct mapping_node {
94 	union {
95 		/* Use rb_simple_node for search/insert */
96 		struct {
97 			struct rb_node rb_node;
98 			u64 bytenr;
99 		};
100 
101 		struct rb_simple_node simple_node;
102 	};
103 	void *data;
104 };
105 
106 struct mapping_tree {
107 	struct rb_root rb_root;
108 	spinlock_t lock;
109 };
110 
111 /*
112  * present a tree block to process
113  */
114 struct tree_block {
115 	union {
116 		/* Use rb_simple_node for search/insert */
117 		struct {
118 			struct rb_node rb_node;
119 			u64 bytenr;
120 		};
121 
122 		struct rb_simple_node simple_node;
123 	};
124 	u64 owner;
125 	struct btrfs_key key;
126 	u8 level;
127 	bool key_ready;
128 };
129 
130 #define MAX_EXTENTS 128
131 
132 struct file_extent_cluster {
133 	u64 start;
134 	u64 end;
135 	u64 boundary[MAX_EXTENTS];
136 	unsigned int nr;
137 	u64 owning_root;
138 };
139 
140 /* Stages of data relocation. */
141 enum reloc_stage {
142 	MOVE_DATA_EXTENTS,
143 	UPDATE_DATA_PTRS
144 };
145 
146 struct reloc_control {
147 	/* block group to relocate */
148 	struct btrfs_block_group *block_group;
149 	/* extent tree */
150 	struct btrfs_root *extent_root;
151 	/* inode for moving data */
152 	struct inode *data_inode;
153 
154 	struct btrfs_block_rsv *block_rsv;
155 
156 	struct btrfs_backref_cache backref_cache;
157 
158 	struct file_extent_cluster cluster;
159 	/* tree blocks have been processed */
160 	struct extent_io_tree processed_blocks;
161 	/* map start of tree root to corresponding reloc tree */
162 	struct mapping_tree reloc_root_tree;
163 	/* list of reloc trees */
164 	struct list_head reloc_roots;
165 	/* list of subvolume trees that get relocated */
166 	struct list_head dirty_subvol_roots;
167 	/* size of metadata reservation for merging reloc trees */
168 	u64 merging_rsv_size;
169 	/* size of relocated tree nodes */
170 	u64 nodes_relocated;
171 	/* reserved size for block group relocation*/
172 	u64 reserved_bytes;
173 
174 	u64 search_start;
175 	u64 extents_found;
176 
177 	enum reloc_stage stage;
178 	bool create_reloc_tree;
179 	bool merge_reloc_tree;
180 	bool found_file_extent;
181 
182 	refcount_t refs;
183 };
184 
185 static struct reloc_control *get_reloc_control(struct btrfs_fs_info *fs_info)
186 {
187 	struct reloc_control *rc;
188 
189 	/* Quick path, avoid lock contention on fs_info->reloc_ctl_lock. */
190 	if (!data_race(fs_info->reloc_ctl))
191 		return NULL;
192 
193 	spin_lock(&fs_info->reloc_ctl_lock);
194 	rc = fs_info->reloc_ctl;
195 	if (rc)
196 		refcount_inc(&rc->refs);
197 	spin_unlock(&fs_info->reloc_ctl_lock);
198 
199 	return rc;
200 }
201 
202 static void __del_reloc_root(struct btrfs_root *root);
203 
204 static noinline_for_stack void free_reloc_roots(struct list_head *list)
205 {
206 	struct btrfs_root *reloc_root, *tmp;
207 
208 	list_for_each_entry_safe(reloc_root, tmp, list, root_list)
209 		__del_reloc_root(reloc_root);
210 }
211 
212 static void put_reloc_control(struct reloc_control *rc)
213 {
214 	if (refcount_dec_and_test(&rc->refs)) {
215 		struct mapping_node *node, *tmp;
216 
217 		if (rc->extent_root)
218 			ASSERT(rc->extent_root->fs_info->reloc_ctl != rc);
219 
220 		free_reloc_roots(&rc->reloc_roots);
221 		rbtree_postorder_for_each_entry_safe(node, tmp,
222 						     &rc->reloc_root_tree.rb_root,
223 						     rb_node)
224 			kfree(node);
225 
226 		if (rc->block_group)
227 			btrfs_put_block_group(rc->block_group);
228 
229 		kfree(rc);
230 	}
231 }
232 
233 /* Helper to delete the 'address of tree root -> reloc tree' mapping. */
234 static void __del_reloc_root(struct btrfs_root *root)
235 {
236 	struct btrfs_fs_info *fs_info = root->fs_info;
237 	struct rb_node *rb_node;
238 	struct mapping_node AUTO_KFREE(node);
239 	struct reloc_control *rc;
240 	bool put_ref = false;
241 
242 	rc = get_reloc_control(fs_info);
243 	if (rc && root->node) {
244 		spin_lock(&rc->reloc_root_tree.lock);
245 		rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
246 					   root->commit_root->start);
247 		if (rb_node) {
248 			node = rb_entry(rb_node, struct mapping_node, rb_node);
249 			rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
250 			RB_CLEAR_NODE(&node->rb_node);
251 		}
252 		spin_unlock(&rc->reloc_root_tree.lock);
253 		ASSERT(!node || (struct btrfs_root *)node->data == root);
254 	}
255 
256 	/*
257 	 * We only put the reloc root here if it's on the list.  There's a lot
258 	 * of places where the pattern is to splice the rc->reloc_roots, process
259 	 * the reloc roots, and then add the reloc root back onto
260 	 * rc->reloc_roots.  If we call __del_reloc_root while it's off of the
261 	 * list we don't want the reference being dropped, because the guy
262 	 * messing with the list is in charge of the reference.
263 	 */
264 	spin_lock(&fs_info->trans_lock);
265 	if (!list_empty(&root->root_list)) {
266 		put_ref = true;
267 		list_del_init(&root->root_list);
268 	}
269 	spin_unlock(&fs_info->trans_lock);
270 	if (put_ref)
271 		btrfs_put_root(root);
272 	if (rc)
273 		put_reloc_control(rc);
274 }
275 
276 static void mark_block_processed(struct reloc_control *rc,
277 				 struct btrfs_backref_node *node)
278 {
279 	u32 blocksize;
280 
281 	if (node->level == 0 ||
282 	    in_range(node->bytenr, rc->block_group->start,
283 		     rc->block_group->length)) {
284 		blocksize = rc->extent_root->fs_info->nodesize;
285 		btrfs_set_extent_bit(&rc->processed_blocks, node->bytenr,
286 				     node->bytenr + blocksize - 1, EXTENT_DIRTY,
287 				     NULL);
288 	}
289 	node->processed = 1;
290 }
291 
292 /*
293  * walk up backref nodes until reach node presents tree root
294  */
295 static struct btrfs_backref_node *walk_up_backref(
296 		struct btrfs_backref_node *node,
297 		struct btrfs_backref_edge *edges[], int *index)
298 {
299 	struct btrfs_backref_edge *edge;
300 	int idx = *index;
301 
302 	while (!list_empty(&node->upper)) {
303 		edge = list_first_entry(&node->upper, struct btrfs_backref_edge,
304 					list[LOWER]);
305 		edges[idx++] = edge;
306 		node = edge->node[UPPER];
307 	}
308 	BUG_ON(node->detached);
309 	*index = idx;
310 	return node;
311 }
312 
313 /*
314  * walk down backref nodes to find start of next reference path
315  */
316 static struct btrfs_backref_node *walk_down_backref(
317 		struct btrfs_backref_edge *edges[], int *index)
318 {
319 	struct btrfs_backref_edge *edge;
320 	struct btrfs_backref_node *lower;
321 	int idx = *index;
322 
323 	while (idx > 0) {
324 		edge = edges[idx - 1];
325 		lower = edge->node[LOWER];
326 		if (list_is_last(&edge->list[LOWER], &lower->upper)) {
327 			idx--;
328 			continue;
329 		}
330 		edge = list_first_entry(&edge->list[LOWER], struct btrfs_backref_edge,
331 					list[LOWER]);
332 		edges[idx - 1] = edge;
333 		*index = idx;
334 		return edge->node[UPPER];
335 	}
336 	*index = 0;
337 	return NULL;
338 }
339 
340 static bool reloc_root_is_dead(const struct btrfs_root *root)
341 {
342 	/*
343 	 * Pair with set_bit/clear_bit in clean_dirty_subvols and
344 	 * btrfs_update_reloc_root. We need to see the updated bit before
345 	 * trying to access reloc_root
346 	 */
347 	smp_rmb();
348 	if (test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state))
349 		return true;
350 	return false;
351 }
352 
353 /*
354  * Check if this subvolume tree has valid reloc tree.
355  *
356  * Reloc tree after swap is considered dead, thus not considered as valid.
357  * This is enough for most callers, as they don't distinguish dead reloc root
358  * from no reloc root.  But btrfs_should_ignore_reloc_root() below is a
359  * special case.
360  */
361 static bool have_reloc_root(const struct btrfs_root *root)
362 {
363 	if (reloc_root_is_dead(root))
364 		return false;
365 	if (!root->reloc_root)
366 		return false;
367 	return true;
368 }
369 
370 bool btrfs_should_ignore_reloc_root(const struct btrfs_root *root)
371 {
372 	struct btrfs_root *reloc_root;
373 
374 	if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
375 		return false;
376 
377 	/* This root has been merged with its reloc tree, we can ignore it */
378 	if (reloc_root_is_dead(root))
379 		return true;
380 
381 	reloc_root = root->reloc_root;
382 	if (!reloc_root)
383 		return false;
384 
385 	if (btrfs_header_generation(reloc_root->commit_root) ==
386 	    root->fs_info->running_transaction->transid)
387 		return false;
388 	/*
389 	 * If there is reloc tree and it was created in previous transaction
390 	 * backref lookup can find the reloc tree, so backref node for the fs
391 	 * tree root is useless for relocation.
392 	 */
393 	return true;
394 }
395 
396 /*
397  * find reloc tree by address of tree root
398  */
399 struct btrfs_root *find_reloc_root(struct btrfs_fs_info *fs_info, u64 bytenr)
400 {
401 	struct reloc_control *rc = fs_info->reloc_ctl;
402 	struct rb_node *rb_node;
403 	struct mapping_node *node;
404 	struct btrfs_root *root = NULL;
405 
406 	ASSERT(rc);
407 	spin_lock(&rc->reloc_root_tree.lock);
408 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root, bytenr);
409 	if (rb_node) {
410 		node = rb_entry(rb_node, struct mapping_node, rb_node);
411 		root = node->data;
412 	}
413 	spin_unlock(&rc->reloc_root_tree.lock);
414 	return btrfs_grab_root(root);
415 }
416 
417 /*
418  * For useless nodes, do two major clean ups:
419  *
420  * - Cleanup the children edges and nodes
421  *   If child node is also orphan (no parent) during cleanup, then the child
422  *   node will also be cleaned up.
423  *
424  * - Freeing up leaves (level 0), keeps nodes detached
425  *   For nodes, the node is still cached as "detached"
426  *
427  * Return false if @node is not in the @useless_nodes list.
428  * Return true if @node is in the @useless_nodes list.
429  */
430 static bool handle_useless_nodes(struct reloc_control *rc,
431 				 struct btrfs_backref_node *node)
432 {
433 	struct btrfs_backref_cache *cache = &rc->backref_cache;
434 	struct list_head *useless_node = &cache->useless_node;
435 	bool ret = false;
436 
437 	while (!list_empty(useless_node)) {
438 		struct btrfs_backref_node *cur;
439 
440 		cur = list_first_entry(useless_node, struct btrfs_backref_node,
441 				 list);
442 		list_del_init(&cur->list);
443 
444 		/* Only tree root nodes can be added to @useless_nodes */
445 		ASSERT(list_empty(&cur->upper));
446 
447 		if (cur == node)
448 			ret = true;
449 
450 		/* Cleanup the lower edges */
451 		while (!list_empty(&cur->lower)) {
452 			struct btrfs_backref_edge *edge;
453 			struct btrfs_backref_node *lower;
454 
455 			edge = list_first_entry(&cur->lower, struct btrfs_backref_edge,
456 						list[UPPER]);
457 			list_del(&edge->list[UPPER]);
458 			list_del(&edge->list[LOWER]);
459 			lower = edge->node[LOWER];
460 			btrfs_backref_free_edge(cache, edge);
461 
462 			/* Child node is also orphan, queue for cleanup */
463 			if (list_empty(&lower->upper))
464 				list_add(&lower->list, useless_node);
465 		}
466 		/* Mark this block processed for relocation */
467 		mark_block_processed(rc, cur);
468 
469 		/*
470 		 * Backref nodes for tree leaves are deleted from the cache.
471 		 * Backref nodes for upper level tree blocks are left in the
472 		 * cache to avoid unnecessary backref lookup.
473 		 */
474 		if (cur->level > 0) {
475 			cur->detached = 1;
476 		} else {
477 			rb_erase(&cur->rb_node, &cache->rb_root);
478 			btrfs_backref_free_node(cache, cur);
479 		}
480 	}
481 	return ret;
482 }
483 
484 /*
485  * Build backref tree for a given tree block. Root of the backref tree
486  * corresponds the tree block, leaves of the backref tree correspond roots of
487  * b-trees that reference the tree block.
488  *
489  * The basic idea of this function is check backrefs of a given block to find
490  * upper level blocks that reference the block, and then check backrefs of
491  * these upper level blocks recursively. The recursion stops when tree root is
492  * reached or backrefs for the block is cached.
493  *
494  * NOTE: if we find that backrefs for a block are cached, we know backrefs for
495  * all upper level blocks that directly/indirectly reference the block are also
496  * cached.
497  */
498 static noinline_for_stack struct btrfs_backref_node *build_backref_tree(
499 			struct btrfs_trans_handle *trans,
500 			struct reloc_control *rc, struct btrfs_key *node_key,
501 			int level, u64 bytenr)
502 {
503 	struct btrfs_backref_iter iter;
504 	struct btrfs_backref_cache *cache = &rc->backref_cache;
505 	/* For searching parent of TREE_BLOCK_REF */
506 	struct btrfs_path *path;
507 	struct btrfs_backref_node *cur;
508 	struct btrfs_backref_node *node = NULL;
509 	struct btrfs_backref_edge *edge;
510 	int ret;
511 
512 	ret = btrfs_backref_iter_init(&iter);
513 	if (ret < 0)
514 		return ERR_PTR(ret);
515 	path = btrfs_alloc_path();
516 	if (!path) {
517 		ret = -ENOMEM;
518 		goto out;
519 	}
520 
521 	node = btrfs_backref_alloc_node(cache, bytenr, level);
522 	if (!node) {
523 		ret = -ENOMEM;
524 		goto out;
525 	}
526 
527 	cur = node;
528 
529 	/* Breadth-first search to build backref cache */
530 	do {
531 		ret = btrfs_backref_add_tree_node(trans, cache, path, &iter,
532 						  node_key, cur);
533 		if (ret < 0)
534 			goto out;
535 
536 		edge = list_first_entry_or_null(&cache->pending_edge,
537 				struct btrfs_backref_edge, list[UPPER]);
538 		/*
539 		 * The pending list isn't empty, take the first block to
540 		 * process
541 		 */
542 		if (edge) {
543 			list_del_init(&edge->list[UPPER]);
544 			cur = edge->node[UPPER];
545 		}
546 	} while (edge);
547 
548 	/* Finish the upper linkage of newly added edges/nodes */
549 	ret = btrfs_backref_finish_upper_links(cache, node);
550 	if (ret < 0)
551 		goto out;
552 
553 	if (handle_useless_nodes(rc, node))
554 		node = NULL;
555 out:
556 	btrfs_free_path(iter.path);
557 	btrfs_free_path(path);
558 	if (ret) {
559 		btrfs_backref_error_cleanup(cache, node);
560 		return ERR_PTR(ret);
561 	}
562 	ASSERT(!node || !node->detached);
563 	ASSERT(list_empty(&cache->useless_node) &&
564 	       list_empty(&cache->pending_edge));
565 	return node;
566 }
567 
568 /*
569  * helper to add 'address of tree root -> reloc tree' mapping
570  */
571 static int __add_reloc_root(struct btrfs_root *root, struct reloc_control *rc)
572 {
573 	struct btrfs_fs_info *fs_info = root->fs_info;
574 	struct rb_node *rb_node;
575 	struct mapping_node *node;
576 
577 	node = kmalloc_obj(*node, GFP_NOFS);
578 	if (!node)
579 		return -ENOMEM;
580 
581 	node->bytenr = root->commit_root->start;
582 	node->data = root;
583 
584 	spin_lock(&rc->reloc_root_tree.lock);
585 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root, &node->simple_node);
586 	spin_unlock(&rc->reloc_root_tree.lock);
587 	if (rb_node) {
588 		btrfs_err(fs_info,
589 			    "Duplicate root found for start=%llu while inserting into relocation tree",
590 			    node->bytenr);
591 		return -EEXIST;
592 	}
593 
594 	list_add_tail(&root->root_list, &rc->reloc_roots);
595 	return 0;
596 }
597 
598 /*
599  * helper to update the 'address of tree root -> reloc tree'
600  * mapping
601  */
602 static int __update_reloc_root(struct btrfs_root *root)
603 {
604 	struct btrfs_fs_info *fs_info = root->fs_info;
605 	struct rb_node *rb_node;
606 	struct mapping_node *node = NULL;
607 	struct reloc_control *rc = fs_info->reloc_ctl;
608 
609 	spin_lock(&rc->reloc_root_tree.lock);
610 	rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
611 				   root->commit_root->start);
612 	if (rb_node) {
613 		node = rb_entry(rb_node, struct mapping_node, rb_node);
614 		rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
615 	}
616 	spin_unlock(&rc->reloc_root_tree.lock);
617 
618 	if (!node)
619 		return 0;
620 	BUG_ON((struct btrfs_root *)node->data != root);
621 
622 	spin_lock(&rc->reloc_root_tree.lock);
623 	node->bytenr = root->node->start;
624 	rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root, &node->simple_node);
625 	spin_unlock(&rc->reloc_root_tree.lock);
626 	if (rb_node)
627 		btrfs_backref_panic(fs_info, node->bytenr, -EEXIST);
628 	return 0;
629 }
630 
631 static struct btrfs_root *create_reloc_root(struct btrfs_trans_handle *trans,
632 					struct btrfs_root *root, u64 objectid)
633 {
634 	struct btrfs_fs_info *fs_info = root->fs_info;
635 	struct btrfs_root *reloc_root;
636 	struct extent_buffer *eb;
637 	struct btrfs_root_item AUTO_KFREE(root_item);
638 	struct btrfs_key root_key;
639 	int ret = 0;
640 
641 	root_item = kmalloc_obj(*root_item, GFP_NOFS);
642 	if (!root_item)
643 		return ERR_PTR(-ENOMEM);
644 
645 	root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
646 	root_key.type = BTRFS_ROOT_ITEM_KEY;
647 	root_key.offset = objectid;
648 
649 	if (btrfs_root_id(root) == objectid) {
650 		u64 commit_root_gen;
651 
652 		/*
653 		 * Relocation will wait for cleaner thread, and any half-dropped
654 		 * subvolume will be fully cleaned up at mount time.
655 		 * So here we shouldn't hit a subvolume with non-zero drop_progress.
656 		 *
657 		 * If this isn't the case, error out since it can make us attempt to
658 		 * drop references for extents that were already dropped before.
659 		 */
660 		if (unlikely(btrfs_disk_key_objectid(&root->root_item.drop_progress))) {
661 			struct btrfs_key cpu_key;
662 
663 			btrfs_disk_key_to_cpu(&cpu_key, &root->root_item.drop_progress);
664 			btrfs_err(fs_info,
665 	"cannot relocate partially dropped subvolume %llu, drop progress key " BTRFS_KEY_FMT,
666 				  objectid, BTRFS_KEY_FMT_VALUE(&cpu_key));
667 			return ERR_PTR(-EUCLEAN);
668 		}
669 
670 		/* called by btrfs_init_reloc_root */
671 		ret = btrfs_copy_root(trans, root, root->commit_root, &eb,
672 				      BTRFS_TREE_RELOC_OBJECTID);
673 		if (ret)
674 			return ERR_PTR(ret);
675 
676 		/*
677 		 * Set the last_snapshot field to the generation of the commit
678 		 * root - like this ctree.c:btrfs_block_can_be_shared() behaves
679 		 * correctly (returns true) when the relocation root is created
680 		 * either inside the critical section of a transaction commit
681 		 * (through transaction.c:qgroup_account_snapshot()) and when
682 		 * it's created before the transaction commit is started.
683 		 */
684 		commit_root_gen = btrfs_header_generation(root->commit_root);
685 		btrfs_set_root_last_snapshot(&root->root_item, commit_root_gen);
686 	} else {
687 		/*
688 		 * called by btrfs_reloc_post_snapshot_hook.
689 		 * the source tree is a reloc tree, all tree blocks
690 		 * modified after it was created have RELOC flag
691 		 * set in their headers. so it's OK to not update
692 		 * the 'last_snapshot'.
693 		 */
694 		ret = btrfs_copy_root(trans, root, root->node, &eb,
695 				      BTRFS_TREE_RELOC_OBJECTID);
696 		if (ret)
697 			return ERR_PTR(ret);
698 	}
699 
700 	/*
701 	 * We have changed references at this point, we must abort the
702 	 * transaction if anything fails (i.e. 'goto abort').
703 	 */
704 
705 	memcpy(root_item, &root->root_item, sizeof(*root_item));
706 	btrfs_set_root_bytenr(root_item, eb->start);
707 	btrfs_set_root_level(root_item, btrfs_header_level(eb));
708 	btrfs_set_root_generation(root_item, trans->transid);
709 
710 	if (btrfs_root_id(root) == objectid) {
711 		btrfs_set_root_refs(root_item, 0);
712 		memset(&root_item->drop_progress, 0,
713 		       sizeof(struct btrfs_disk_key));
714 		btrfs_set_root_drop_level(root_item, 0);
715 	}
716 
717 	btrfs_tree_unlock(eb);
718 	free_extent_buffer(eb);
719 
720 	ret = btrfs_insert_root(trans, fs_info->tree_root,
721 				&root_key, root_item);
722 	if (unlikely(ret)) {
723 		btrfs_abort_transaction(trans, ret);
724 		return ERR_PTR(ret);
725 	}
726 
727 	reloc_root = btrfs_read_tree_root(fs_info->tree_root, &root_key);
728 	if (IS_ERR(reloc_root)) {
729 		btrfs_abort_transaction(trans, PTR_ERR(reloc_root));
730 		return ERR_CAST(reloc_root);
731 	}
732 	set_bit(BTRFS_ROOT_SHAREABLE, &reloc_root->state);
733 	btrfs_set_root_last_trans(reloc_root, trans->transid);
734 	return reloc_root;
735 }
736 
737 /*
738  * create reloc tree for a given fs tree. reloc tree is just a
739  * snapshot of the fs tree with special root objectid.
740  *
741  * The reloc_root comes out of here with two references, one for
742  * root->reloc_root, and another for being on the rc->reloc_roots list.
743  */
744 int btrfs_init_reloc_root(struct btrfs_trans_handle *trans,
745 			  struct btrfs_root *root)
746 {
747 	struct btrfs_fs_info *fs_info = root->fs_info;
748 	struct btrfs_root *reloc_root;
749 	struct reloc_control *rc;
750 	struct btrfs_block_rsv *rsv;
751 	bool clear_rsv = false;
752 	int ret = 0;
753 
754 	rc = get_reloc_control(fs_info);
755 	if (!rc)
756 		return 0;
757 
758 	/*
759 	 * The subvolume has reloc tree but the swap is finished, no need to
760 	 * create/update the dead reloc tree
761 	 */
762 	if (reloc_root_is_dead(root))
763 		goto out;
764 
765 	/*
766 	 * This is subtle but important.  We do not do
767 	 * record_root_in_transaction for reloc roots, instead we record their
768 	 * corresponding fs root, and then here we update the last trans for the
769 	 * reloc root.  This means that we have to do this for the entire life
770 	 * of the reloc root, regardless of which stage of the relocation we are
771 	 * in.
772 	 */
773 	if (root->reloc_root) {
774 		btrfs_set_root_last_trans(root->reloc_root, trans->transid);
775 		goto out;
776 	}
777 
778 	/*
779 	 * We are merging reloc roots, we do not need new reloc trees.  Also
780 	 * reloc trees never need their own reloc tree.
781 	 */
782 	if (!rc->create_reloc_tree || btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
783 		goto out;
784 
785 	if (!trans->reloc_reserved) {
786 		rsv = trans->block_rsv;
787 		trans->block_rsv = rc->block_rsv;
788 		clear_rsv = true;
789 	}
790 	reloc_root = create_reloc_root(trans, root, btrfs_root_id(root));
791 	if (clear_rsv)
792 		trans->block_rsv = rsv;
793 	if (IS_ERR(reloc_root)) {
794 		ret = PTR_ERR(reloc_root);
795 		goto out;
796 	}
797 
798 	ret = __add_reloc_root(reloc_root, rc);
799 	ASSERT(ret != -EEXIST);
800 	if (ret) {
801 		/* Pairs with create_reloc_root */
802 		btrfs_put_root(reloc_root);
803 		goto out;
804 	}
805 	root->reloc_root = btrfs_grab_root(reloc_root);
806 out:
807 	put_reloc_control(rc);
808 
809 	return ret;
810 }
811 
812 /*
813  * update root item of reloc tree
814  */
815 int btrfs_update_reloc_root(struct btrfs_trans_handle *trans,
816 			    struct btrfs_root *root)
817 {
818 	struct btrfs_fs_info *fs_info = root->fs_info;
819 	struct btrfs_root *reloc_root;
820 	struct btrfs_root_item *root_item;
821 	struct reloc_control *rc;
822 	int ret;
823 
824 	if (!have_reloc_root(root))
825 		return 0;
826 
827 	reloc_root = root->reloc_root;
828 	root_item = &reloc_root->root_item;
829 
830 	/*
831 	 * We are probably ok here, but __del_reloc_root() will drop its ref of
832 	 * the root.  We have the ref for root->reloc_root, but just in case
833 	 * hold it while we update the reloc root.
834 	 */
835 	btrfs_grab_root(reloc_root);
836 
837 	rc = get_reloc_control(fs_info);
838 	/* root->reloc_root will stay until current relocation finished */
839 	if (rc && rc->merge_reloc_tree && btrfs_root_refs(root_item) == 0) {
840 		set_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
841 		/*
842 		 * Mark the tree as dead before we change reloc_root so
843 		 * have_reloc_root will not touch it from now on.
844 		 */
845 		smp_wmb();
846 		__del_reloc_root(reloc_root);
847 	}
848 
849 	if (reloc_root->commit_root != reloc_root->node) {
850 		__update_reloc_root(reloc_root);
851 		btrfs_set_root_node(root_item, reloc_root->node);
852 		free_extent_buffer(reloc_root->commit_root);
853 		reloc_root->commit_root = btrfs_root_node(reloc_root);
854 	}
855 
856 	ret = btrfs_update_root(trans, fs_info->tree_root,
857 				&reloc_root->root_key, root_item);
858 	btrfs_put_root(reloc_root);
859 	if (rc)
860 		put_reloc_control(rc);
861 
862 	return ret;
863 }
864 
865 /*
866  * get new location of data
867  */
868 static int get_new_location(struct inode *reloc_inode, u64 *new_bytenr,
869 			    u64 bytenr, u64 num_bytes)
870 {
871 	struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
872 	struct btrfs_fs_info *fs_info = root->fs_info;
873 	BTRFS_PATH_AUTO_FREE(path);
874 	struct btrfs_file_extent_item *fi;
875 	struct extent_buffer *leaf;
876 	int ret;
877 
878 	path = btrfs_alloc_path();
879 	if (!path)
880 		return -ENOMEM;
881 
882 	bytenr -= BTRFS_I(reloc_inode)->reloc_block_group_start;
883 	ret = btrfs_lookup_file_extent(NULL, root, path,
884 			btrfs_ino(BTRFS_I(reloc_inode)), bytenr, 0);
885 	if (ret < 0)
886 		return ret;
887 	if (ret > 0)
888 		return -ENOENT;
889 
890 	leaf = path->nodes[0];
891 	fi = btrfs_item_ptr(leaf, path->slots[0],
892 			    struct btrfs_file_extent_item);
893 
894 	/*
895 	 * The cluster-boundary key searched above is always written by
896 	 * relocation with offset 0: either by insert_prealloc_file_extent()
897 	 * (memsets the stack item to 0) or by the front portion of a partial
898 	 * writeback (offset=0 by construction). A non-zero value here means
899 	 * the on-disk leaf does not match what relocation wrote, i.e.
900 	 * corruption. The other encoding fields are caught earlier by
901 	 * tree-checker's check_extent_data_item().
902 	 */
903 	if (unlikely(btrfs_file_extent_offset(leaf, fi))) {
904 		btrfs_print_leaf(leaf);
905 		btrfs_err(fs_info,
906 "unexpected non-zero offset in file extent item for data reloc inode %llu key offset %llu offset %llu",
907 			  btrfs_ino(BTRFS_I(reloc_inode)), bytenr,
908 			  btrfs_file_extent_offset(leaf, fi));
909 		return -EUCLEAN;
910 	}
911 
912 	if (num_bytes != btrfs_file_extent_disk_num_bytes(leaf, fi))
913 		return -EINVAL;
914 
915 	*new_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
916 	return 0;
917 }
918 
919 /*
920  * update file extent items in the tree leaf to point to
921  * the new locations.
922  */
923 static noinline_for_stack
924 int replace_file_extents(struct btrfs_trans_handle *trans,
925 			 struct reloc_control *rc,
926 			 struct btrfs_root *root,
927 			 struct extent_buffer *leaf)
928 {
929 	struct btrfs_fs_info *fs_info = root->fs_info;
930 	struct btrfs_key key;
931 	struct btrfs_file_extent_item *fi;
932 	struct btrfs_inode *inode = NULL;
933 	u64 parent;
934 	u64 bytenr;
935 	u64 new_bytenr = 0;
936 	u64 num_bytes;
937 	u64 end;
938 	u32 nritems;
939 	u32 i;
940 	int ret = 0;
941 	bool first = true;
942 
943 	if (rc->stage != UPDATE_DATA_PTRS)
944 		return 0;
945 
946 	/* reloc trees always use full backref */
947 	if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
948 		parent = leaf->start;
949 	else
950 		parent = 0;
951 
952 	nritems = btrfs_header_nritems(leaf);
953 	for (i = 0; i < nritems; i++) {
954 		struct btrfs_ref ref = { 0 };
955 
956 		cond_resched();
957 		btrfs_item_key_to_cpu(leaf, &key, i);
958 		if (key.type != BTRFS_EXTENT_DATA_KEY)
959 			continue;
960 		fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
961 		if (btrfs_file_extent_type(leaf, fi) ==
962 		    BTRFS_FILE_EXTENT_INLINE)
963 			continue;
964 		bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
965 		num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
966 		if (bytenr == 0)
967 			continue;
968 		if (!in_range(bytenr, rc->block_group->start,
969 			      rc->block_group->length))
970 			continue;
971 
972 		/*
973 		 * if we are modifying block in fs tree, wait for read_folio
974 		 * to complete and drop the extent cache
975 		 */
976 		if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID) {
977 			if (first) {
978 				inode = btrfs_find_first_inode(root, key.objectid);
979 				first = false;
980 			} else if (inode && btrfs_ino(inode) < key.objectid) {
981 				btrfs_add_delayed_iput(inode);
982 				inode = btrfs_find_first_inode(root, key.objectid);
983 			}
984 			if (inode && btrfs_ino(inode) == key.objectid) {
985 				struct extent_state *cached_state = NULL;
986 
987 				end = key.offset +
988 				      btrfs_file_extent_num_bytes(leaf, fi);
989 				WARN_ON(!IS_ALIGNED(key.offset,
990 						    fs_info->sectorsize));
991 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
992 				end--;
993 				/* Take mmap lock to serialize with reflinks. */
994 				if (!down_read_trylock(&inode->i_mmap_lock))
995 					continue;
996 				ret = btrfs_try_lock_extent(&inode->io_tree, key.offset,
997 							    end, &cached_state);
998 				if (!ret) {
999 					up_read(&inode->i_mmap_lock);
1000 					continue;
1001 				}
1002 
1003 				btrfs_drop_extent_map_range(inode, key.offset, end, true);
1004 				btrfs_unlock_extent(&inode->io_tree, key.offset, end,
1005 						    &cached_state);
1006 				up_read(&inode->i_mmap_lock);
1007 			}
1008 		}
1009 
1010 		ret = get_new_location(rc->data_inode, &new_bytenr,
1011 				       bytenr, num_bytes);
1012 		if (ret) {
1013 			/*
1014 			 * Don't have to abort since we've not changed anything
1015 			 * in the file extent yet.
1016 			 */
1017 			break;
1018 		}
1019 
1020 		btrfs_set_file_extent_disk_bytenr(leaf, fi, new_bytenr);
1021 
1022 		key.offset -= btrfs_file_extent_offset(leaf, fi);
1023 		ref.action = BTRFS_ADD_DELAYED_REF;
1024 		ref.bytenr = new_bytenr;
1025 		ref.num_bytes = num_bytes;
1026 		ref.parent = parent;
1027 		ref.owning_root = btrfs_root_id(root);
1028 		ref.ref_root = btrfs_header_owner(leaf);
1029 		btrfs_init_data_ref(&ref, key.objectid, key.offset,
1030 				    btrfs_root_id(root), false);
1031 		ret = btrfs_inc_extent_ref(trans, &ref);
1032 		if (unlikely(ret)) {
1033 			btrfs_abort_transaction(trans, ret);
1034 			break;
1035 		}
1036 
1037 		ref.action = BTRFS_DROP_DELAYED_REF;
1038 		ref.bytenr = bytenr;
1039 		ref.num_bytes = num_bytes;
1040 		ref.parent = parent;
1041 		ref.owning_root = btrfs_root_id(root);
1042 		ref.ref_root = btrfs_header_owner(leaf);
1043 		btrfs_init_data_ref(&ref, key.objectid, key.offset,
1044 				    btrfs_root_id(root), false);
1045 		ret = btrfs_free_extent(trans, &ref);
1046 		if (unlikely(ret)) {
1047 			btrfs_abort_transaction(trans, ret);
1048 			break;
1049 		}
1050 	}
1051 	if (inode)
1052 		btrfs_add_delayed_iput(inode);
1053 	return ret;
1054 }
1055 
1056 static noinline_for_stack int memcmp_node_keys(const struct extent_buffer *eb,
1057 					       int slot, const struct btrfs_path *path,
1058 					       int level)
1059 {
1060 	struct btrfs_disk_key key1;
1061 	struct btrfs_disk_key key2;
1062 	btrfs_node_key(eb, &key1, slot);
1063 	btrfs_node_key(path->nodes[level], &key2, path->slots[level]);
1064 	return memcmp(&key1, &key2, sizeof(key1));
1065 }
1066 
1067 /*
1068  * try to replace tree blocks in fs tree with the new blocks
1069  * in reloc tree. tree blocks haven't been modified since the
1070  * reloc tree was create can be replaced.
1071  *
1072  * if a block was replaced, level of the block + 1 is returned.
1073  * if no block got replaced, 0 is returned. if there are other
1074  * errors, a negative error number is returned.
1075  */
1076 static noinline_for_stack
1077 int replace_path(struct btrfs_trans_handle *trans, struct reloc_control *rc,
1078 		 struct btrfs_root *dest, struct btrfs_root *src,
1079 		 struct btrfs_path *path, struct btrfs_key *next_key,
1080 		 int lowest_level, int max_level)
1081 {
1082 	struct btrfs_fs_info *fs_info = dest->fs_info;
1083 	struct extent_buffer *eb;
1084 	struct extent_buffer *parent;
1085 	struct btrfs_ref ref = { 0 };
1086 	struct btrfs_key key;
1087 	u64 old_bytenr;
1088 	u64 new_bytenr;
1089 	u64 old_ptr_gen;
1090 	u64 new_ptr_gen;
1091 	u64 last_snapshot;
1092 	u32 blocksize;
1093 	bool cow = false;
1094 	int level;
1095 	int ret;
1096 	int slot;
1097 
1098 	ASSERT(btrfs_root_id(src) == BTRFS_TREE_RELOC_OBJECTID);
1099 	ASSERT(btrfs_root_id(dest) != BTRFS_TREE_RELOC_OBJECTID);
1100 
1101 	last_snapshot = btrfs_root_last_snapshot(&src->root_item);
1102 again:
1103 	slot = path->slots[lowest_level];
1104 	btrfs_node_key_to_cpu(path->nodes[lowest_level], &key, slot);
1105 
1106 	eb = btrfs_lock_root_node(dest);
1107 	level = btrfs_header_level(eb);
1108 
1109 	if (level < lowest_level) {
1110 		btrfs_tree_unlock(eb);
1111 		free_extent_buffer(eb);
1112 		return 0;
1113 	}
1114 
1115 	if (cow) {
1116 		ret = btrfs_cow_block(trans, dest, eb, NULL, 0, &eb,
1117 				      BTRFS_NESTING_COW);
1118 		if (ret) {
1119 			btrfs_tree_unlock(eb);
1120 			free_extent_buffer(eb);
1121 			return ret;
1122 		}
1123 	}
1124 
1125 	if (next_key) {
1126 		next_key->objectid = (u64)-1;
1127 		next_key->type = (u8)-1;
1128 		next_key->offset = (u64)-1;
1129 	}
1130 
1131 	parent = eb;
1132 	while (1) {
1133 		level = btrfs_header_level(parent);
1134 		ASSERT(level >= lowest_level);
1135 
1136 		ret = btrfs_bin_search(parent, 0, &key, &slot);
1137 		if (ret < 0)
1138 			break;
1139 		if (ret && slot > 0)
1140 			slot--;
1141 
1142 		if (next_key && slot + 1 < btrfs_header_nritems(parent))
1143 			btrfs_node_key_to_cpu(parent, next_key, slot + 1);
1144 
1145 		old_bytenr = btrfs_node_blockptr(parent, slot);
1146 		blocksize = fs_info->nodesize;
1147 		old_ptr_gen = btrfs_node_ptr_generation(parent, slot);
1148 
1149 		if (level <= max_level) {
1150 			eb = path->nodes[level];
1151 			new_bytenr = btrfs_node_blockptr(eb,
1152 							path->slots[level]);
1153 			new_ptr_gen = btrfs_node_ptr_generation(eb,
1154 							path->slots[level]);
1155 		} else {
1156 			new_bytenr = 0;
1157 			new_ptr_gen = 0;
1158 		}
1159 
1160 		if (WARN_ON(new_bytenr > 0 && new_bytenr == old_bytenr)) {
1161 			ret = level;
1162 			break;
1163 		}
1164 
1165 		if (new_bytenr == 0 || old_ptr_gen > last_snapshot ||
1166 		    memcmp_node_keys(parent, slot, path, level)) {
1167 			if (level <= lowest_level) {
1168 				ret = 0;
1169 				break;
1170 			}
1171 
1172 			eb = btrfs_read_node_slot(parent, slot);
1173 			if (IS_ERR(eb)) {
1174 				ret = PTR_ERR(eb);
1175 				break;
1176 			}
1177 			btrfs_tree_lock(eb);
1178 			if (cow) {
1179 				ret = btrfs_cow_block(trans, dest, eb, parent,
1180 						      slot, &eb,
1181 						      BTRFS_NESTING_COW);
1182 				if (ret) {
1183 					btrfs_tree_unlock(eb);
1184 					free_extent_buffer(eb);
1185 					break;
1186 				}
1187 			}
1188 
1189 			btrfs_tree_unlock(parent);
1190 			free_extent_buffer(parent);
1191 
1192 			parent = eb;
1193 			continue;
1194 		}
1195 
1196 		if (!cow) {
1197 			btrfs_tree_unlock(parent);
1198 			free_extent_buffer(parent);
1199 			cow = true;
1200 			goto again;
1201 		}
1202 
1203 		btrfs_node_key_to_cpu(path->nodes[level], &key,
1204 				      path->slots[level]);
1205 		btrfs_release_path(path);
1206 
1207 		path->lowest_level = level;
1208 		set_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &src->state);
1209 		ret = btrfs_search_slot(trans, src, &key, path, 0, 1);
1210 		clear_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &src->state);
1211 		path->lowest_level = 0;
1212 		if (ret) {
1213 			if (ret > 0)
1214 				ret = -ENOENT;
1215 			break;
1216 		}
1217 
1218 		/*
1219 		 * Info qgroup to trace both subtrees.
1220 		 *
1221 		 * We must trace both trees.
1222 		 * 1) Tree reloc subtree
1223 		 *    If not traced, we will leak data numbers
1224 		 * 2) Fs subtree
1225 		 *    If not traced, we will double count old data
1226 		 *
1227 		 * We don't scan the subtree right now, but only record
1228 		 * the swapped tree blocks.
1229 		 * The real subtree rescan is delayed until we have new
1230 		 * CoW on the subtree root node before transaction commit.
1231 		 */
1232 		ret = btrfs_qgroup_add_swapped_blocks(dest,
1233 				rc->block_group, parent, slot,
1234 				path->nodes[level], path->slots[level],
1235 				last_snapshot);
1236 		if (ret < 0)
1237 			break;
1238 		/*
1239 		 * swap blocks in fs tree and reloc tree.
1240 		 */
1241 		btrfs_set_node_blockptr(parent, slot, new_bytenr);
1242 		btrfs_set_node_ptr_generation(parent, slot, new_ptr_gen);
1243 
1244 		btrfs_set_node_blockptr(path->nodes[level],
1245 					path->slots[level], old_bytenr);
1246 		btrfs_set_node_ptr_generation(path->nodes[level],
1247 					      path->slots[level], old_ptr_gen);
1248 
1249 		ref.action = BTRFS_ADD_DELAYED_REF;
1250 		ref.bytenr = old_bytenr;
1251 		ref.num_bytes = blocksize;
1252 		ref.parent = path->nodes[level]->start;
1253 		ref.owning_root = btrfs_root_id(src);
1254 		ref.ref_root = btrfs_root_id(src);
1255 		btrfs_init_tree_ref(&ref, level - 1, 0, true);
1256 		ret = btrfs_inc_extent_ref(trans, &ref);
1257 		if (unlikely(ret)) {
1258 			btrfs_abort_transaction(trans, ret);
1259 			break;
1260 		}
1261 
1262 		ref.action = BTRFS_ADD_DELAYED_REF;
1263 		ref.bytenr = new_bytenr;
1264 		ref.num_bytes = blocksize;
1265 		ref.parent = 0;
1266 		ref.owning_root = btrfs_root_id(dest);
1267 		ref.ref_root = btrfs_root_id(dest);
1268 		btrfs_init_tree_ref(&ref, level - 1, 0, true);
1269 		ret = btrfs_inc_extent_ref(trans, &ref);
1270 		if (unlikely(ret)) {
1271 			btrfs_abort_transaction(trans, ret);
1272 			break;
1273 		}
1274 
1275 		/* We don't know the real owning_root, use 0. */
1276 		ref.action = BTRFS_DROP_DELAYED_REF;
1277 		ref.bytenr = new_bytenr;
1278 		ref.num_bytes = blocksize;
1279 		ref.parent = path->nodes[level]->start;
1280 		ref.owning_root = 0;
1281 		ref.ref_root = btrfs_root_id(src);
1282 		btrfs_init_tree_ref(&ref, level - 1, 0, true);
1283 		ret = btrfs_free_extent(trans, &ref);
1284 		if (unlikely(ret)) {
1285 			btrfs_abort_transaction(trans, ret);
1286 			break;
1287 		}
1288 
1289 		/* We don't know the real owning_root, use 0. */
1290 		ref.action = BTRFS_DROP_DELAYED_REF;
1291 		ref.bytenr = old_bytenr;
1292 		ref.num_bytes = blocksize;
1293 		ref.parent = 0;
1294 		ref.owning_root = 0;
1295 		ref.ref_root = btrfs_root_id(dest);
1296 		btrfs_init_tree_ref(&ref, level - 1, 0, true);
1297 		ret = btrfs_free_extent(trans, &ref);
1298 		if (unlikely(ret)) {
1299 			btrfs_abort_transaction(trans, ret);
1300 			break;
1301 		}
1302 
1303 		btrfs_unlock_up_safe(path, 0);
1304 
1305 		ret = level;
1306 		break;
1307 	}
1308 	btrfs_tree_unlock(parent);
1309 	free_extent_buffer(parent);
1310 	return ret;
1311 }
1312 
1313 /*
1314  * helper to find next relocated block in reloc tree
1315  */
1316 static noinline_for_stack
1317 int walk_up_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
1318 		       int *level)
1319 {
1320 	struct extent_buffer *eb;
1321 	int i;
1322 	u64 last_snapshot;
1323 	u32 nritems;
1324 
1325 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
1326 
1327 	for (i = 0; i < *level; i++) {
1328 		free_extent_buffer(path->nodes[i]);
1329 		path->nodes[i] = NULL;
1330 	}
1331 
1332 	for (i = *level; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
1333 		eb = path->nodes[i];
1334 		nritems = btrfs_header_nritems(eb);
1335 		while (path->slots[i] + 1 < nritems) {
1336 			path->slots[i]++;
1337 			if (btrfs_node_ptr_generation(eb, path->slots[i]) <=
1338 			    last_snapshot)
1339 				continue;
1340 
1341 			*level = i;
1342 			return 0;
1343 		}
1344 		free_extent_buffer(path->nodes[i]);
1345 		path->nodes[i] = NULL;
1346 	}
1347 	return 1;
1348 }
1349 
1350 /*
1351  * walk down reloc tree to find relocated block of lowest level
1352  */
1353 static noinline_for_stack
1354 int walk_down_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
1355 			 int *level)
1356 {
1357 	struct extent_buffer *eb = NULL;
1358 	int i;
1359 	u64 ptr_gen = 0;
1360 	u64 last_snapshot;
1361 	u32 nritems;
1362 
1363 	last_snapshot = btrfs_root_last_snapshot(&root->root_item);
1364 
1365 	for (i = *level; i > 0; i--) {
1366 		eb = path->nodes[i];
1367 		nritems = btrfs_header_nritems(eb);
1368 		while (path->slots[i] < nritems) {
1369 			ptr_gen = btrfs_node_ptr_generation(eb, path->slots[i]);
1370 			if (ptr_gen > last_snapshot)
1371 				break;
1372 			path->slots[i]++;
1373 		}
1374 		if (path->slots[i] >= nritems) {
1375 			if (i == *level)
1376 				break;
1377 			*level = i + 1;
1378 			return 0;
1379 		}
1380 		if (i == 1) {
1381 			*level = i;
1382 			return 0;
1383 		}
1384 
1385 		eb = btrfs_read_node_slot(eb, path->slots[i]);
1386 		if (IS_ERR(eb))
1387 			return PTR_ERR(eb);
1388 		BUG_ON(btrfs_header_level(eb) != i - 1);
1389 		path->nodes[i - 1] = eb;
1390 		path->slots[i - 1] = 0;
1391 	}
1392 	return 1;
1393 }
1394 
1395 /*
1396  * invalidate extent cache for file extents whose key in range of
1397  * [min_key, max_key)
1398  */
1399 static int invalidate_extent_cache(struct btrfs_root *root,
1400 				   const struct btrfs_key *min_key,
1401 				   const struct btrfs_key *max_key)
1402 {
1403 	struct btrfs_fs_info *fs_info = root->fs_info;
1404 	struct btrfs_inode *inode = NULL;
1405 	u64 objectid;
1406 	u64 start, end;
1407 	u64 ino;
1408 
1409 	objectid = min_key->objectid;
1410 	while (1) {
1411 		struct extent_state *cached_state = NULL;
1412 
1413 		cond_resched();
1414 		if (inode)
1415 			iput(&inode->vfs_inode);
1416 
1417 		if (objectid > max_key->objectid)
1418 			break;
1419 
1420 		inode = btrfs_find_first_inode(root, objectid);
1421 		if (!inode)
1422 			break;
1423 		ino = btrfs_ino(inode);
1424 
1425 		if (ino > max_key->objectid) {
1426 			iput(&inode->vfs_inode);
1427 			break;
1428 		}
1429 
1430 		objectid = ino + 1;
1431 		if (!S_ISREG(inode->vfs_inode.i_mode))
1432 			continue;
1433 
1434 		if (unlikely(min_key->objectid == ino)) {
1435 			if (min_key->type > BTRFS_EXTENT_DATA_KEY)
1436 				continue;
1437 			if (min_key->type < BTRFS_EXTENT_DATA_KEY)
1438 				start = 0;
1439 			else {
1440 				start = min_key->offset;
1441 				WARN_ON(!IS_ALIGNED(start, fs_info->sectorsize));
1442 			}
1443 		} else {
1444 			start = 0;
1445 		}
1446 
1447 		if (unlikely(max_key->objectid == ino)) {
1448 			if (max_key->type < BTRFS_EXTENT_DATA_KEY)
1449 				continue;
1450 			if (max_key->type > BTRFS_EXTENT_DATA_KEY) {
1451 				end = (u64)-1;
1452 			} else {
1453 				if (max_key->offset == 0)
1454 					continue;
1455 				end = max_key->offset;
1456 				WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
1457 				end--;
1458 			}
1459 		} else {
1460 			end = (u64)-1;
1461 		}
1462 
1463 		/* the lock_extent waits for read_folio to complete */
1464 		btrfs_lock_extent(&inode->io_tree, start, end, &cached_state);
1465 		btrfs_drop_extent_map_range(inode, start, end, true);
1466 		btrfs_unlock_extent(&inode->io_tree, start, end, &cached_state);
1467 	}
1468 	return 0;
1469 }
1470 
1471 static int find_next_key(struct btrfs_path *path, int level,
1472 			 struct btrfs_key *key)
1473 
1474 {
1475 	while (level < BTRFS_MAX_LEVEL) {
1476 		if (!path->nodes[level])
1477 			break;
1478 		if (path->slots[level] + 1 <
1479 		    btrfs_header_nritems(path->nodes[level])) {
1480 			btrfs_node_key_to_cpu(path->nodes[level], key,
1481 					      path->slots[level] + 1);
1482 			return 0;
1483 		}
1484 		level++;
1485 	}
1486 	return 1;
1487 }
1488 
1489 /*
1490  * Insert current subvolume into reloc_control::dirty_subvol_roots
1491  */
1492 static int insert_dirty_subvol(struct btrfs_trans_handle *trans,
1493 			       struct reloc_control *rc,
1494 			       struct btrfs_root *root)
1495 {
1496 	struct btrfs_root *reloc_root = root->reloc_root;
1497 	struct btrfs_root_item *reloc_root_item;
1498 	int ret;
1499 
1500 	/* @root must be a subvolume tree root with a valid reloc tree */
1501 	ASSERT(btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID);
1502 	ASSERT(reloc_root);
1503 
1504 	reloc_root_item = &reloc_root->root_item;
1505 	memset(&reloc_root_item->drop_progress, 0,
1506 		sizeof(reloc_root_item->drop_progress));
1507 	btrfs_set_root_drop_level(reloc_root_item, 0);
1508 	btrfs_set_root_refs(reloc_root_item, 0);
1509 	ret = btrfs_update_reloc_root(trans, root);
1510 	if (ret)
1511 		return ret;
1512 
1513 	if (list_empty(&root->reloc_dirty_list)) {
1514 		btrfs_grab_root(root);
1515 		list_add_tail(&root->reloc_dirty_list, &rc->dirty_subvol_roots);
1516 	}
1517 
1518 	return 0;
1519 }
1520 
1521 static int clean_dirty_subvols(struct reloc_control *rc)
1522 {
1523 	struct btrfs_root *root;
1524 	struct btrfs_root *next;
1525 	int ret = 0;
1526 	int ret2;
1527 
1528 	list_for_each_entry_safe(root, next, &rc->dirty_subvol_roots,
1529 				 reloc_dirty_list) {
1530 		if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID) {
1531 			/* Merged subvolume, cleanup its reloc root */
1532 			struct btrfs_root *reloc_root = root->reloc_root;
1533 
1534 			list_del_init(&root->reloc_dirty_list);
1535 			root->reloc_root = NULL;
1536 			/*
1537 			 * Need barrier to ensure clear_bit() only happens after
1538 			 * root->reloc_root = NULL. Pairs with have_reloc_root.
1539 			 */
1540 			smp_wmb();
1541 			clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
1542 			if (reloc_root) {
1543 				/*
1544 				 * btrfs_drop_snapshot drops our ref we hold for
1545 				 * ->reloc_root.  If it fails however we must
1546 				 * drop the ref ourselves.
1547 				 */
1548 				ret2 = btrfs_drop_snapshot(reloc_root, false, true);
1549 				if (ret2 < 0) {
1550 					btrfs_put_root(reloc_root);
1551 					if (!ret)
1552 						ret = ret2;
1553 				}
1554 			}
1555 			btrfs_put_root(root);
1556 		} else {
1557 			/* Orphan reloc tree, just clean it up */
1558 			ret2 = btrfs_drop_snapshot(root, false, true);
1559 			if (ret2 < 0) {
1560 				btrfs_put_root(root);
1561 				if (!ret)
1562 					ret = ret2;
1563 			}
1564 		}
1565 	}
1566 	return ret;
1567 }
1568 
1569 /*
1570  * merge the relocated tree blocks in reloc tree with corresponding
1571  * fs tree.
1572  */
1573 static noinline_for_stack int merge_reloc_root(struct reloc_control *rc,
1574 					       struct btrfs_root *root)
1575 {
1576 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
1577 	struct btrfs_key key;
1578 	struct btrfs_key next_key;
1579 	struct btrfs_trans_handle *trans = NULL;
1580 	struct btrfs_root *reloc_root;
1581 	struct btrfs_root_item *root_item;
1582 	struct btrfs_path *path;
1583 	struct extent_buffer *leaf;
1584 	int reserve_level;
1585 	int level;
1586 	int max_level;
1587 	bool replaced = false;
1588 	int ret = 0;
1589 	u32 min_reserved;
1590 
1591 	path = btrfs_alloc_path();
1592 	if (!path)
1593 		return -ENOMEM;
1594 	path->reada = READA_FORWARD;
1595 
1596 	reloc_root = root->reloc_root;
1597 	root_item = &reloc_root->root_item;
1598 
1599 	if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
1600 		level = btrfs_root_level(root_item);
1601 		refcount_inc(&reloc_root->node->refs);
1602 		path->nodes[level] = reloc_root->node;
1603 		path->slots[level] = 0;
1604 	} else {
1605 		btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
1606 
1607 		level = btrfs_root_drop_level(root_item);
1608 		BUG_ON(level == 0);
1609 		path->lowest_level = level;
1610 		ret = btrfs_search_slot(NULL, reloc_root, &key, path, 0, 0);
1611 		path->lowest_level = 0;
1612 		if (ret < 0) {
1613 			btrfs_free_path(path);
1614 			return ret;
1615 		}
1616 
1617 		btrfs_node_key_to_cpu(path->nodes[level], &next_key,
1618 				      path->slots[level]);
1619 		WARN_ON(memcmp(&key, &next_key, sizeof(key)));
1620 
1621 		btrfs_unlock_up_safe(path, 0);
1622 	}
1623 
1624 	/*
1625 	 * In merge_reloc_root(), we modify the upper level pointer to swap the
1626 	 * tree blocks between reloc tree and subvolume tree.  Thus for tree
1627 	 * block COW, we COW at most from level 1 to root level for each tree.
1628 	 *
1629 	 * Thus the needed metadata size is at most root_level * nodesize,
1630 	 * and * 2 since we have two trees to COW.
1631 	 */
1632 	reserve_level = max_t(int, 1, btrfs_root_level(root_item));
1633 	min_reserved = (reserve_level << fs_info->nodesize_bits) * 2;
1634 	memset(&next_key, 0, sizeof(next_key));
1635 
1636 	while (1) {
1637 		ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv,
1638 					     min_reserved,
1639 					     BTRFS_RESERVE_FLUSH_LIMIT);
1640 		if (ret)
1641 			goto out;
1642 		trans = btrfs_start_transaction(root, 0);
1643 		if (IS_ERR(trans)) {
1644 			ret = PTR_ERR(trans);
1645 			trans = NULL;
1646 			goto out;
1647 		}
1648 
1649 		/*
1650 		 * At this point we no longer have a reloc_control, so we can't
1651 		 * depend on btrfs_init_reloc_root to update our last_trans.
1652 		 *
1653 		 * But that's ok, we started the trans handle on our
1654 		 * corresponding fs_root, which means it's been added to the
1655 		 * dirty list.  At commit time we'll still call
1656 		 * btrfs_update_reloc_root() and update our root item
1657 		 * appropriately.
1658 		 */
1659 		btrfs_set_root_last_trans(reloc_root, trans->transid);
1660 		trans->block_rsv = rc->block_rsv;
1661 
1662 		replaced = false;
1663 		max_level = level;
1664 
1665 		ret = walk_down_reloc_tree(reloc_root, path, &level);
1666 		if (ret < 0)
1667 			goto out;
1668 		if (ret > 0)
1669 			break;
1670 
1671 		if (!find_next_key(path, level, &key) &&
1672 		    btrfs_comp_cpu_keys(&next_key, &key) >= 0) {
1673 			ret = 0;
1674 		} else {
1675 			ret = replace_path(trans, rc, root, reloc_root, path,
1676 					   &next_key, level, max_level);
1677 		}
1678 		if (ret < 0)
1679 			goto out;
1680 		if (ret > 0) {
1681 			level = ret;
1682 			btrfs_node_key_to_cpu(path->nodes[level], &key,
1683 					      path->slots[level]);
1684 			replaced = true;
1685 		}
1686 
1687 		ret = walk_up_reloc_tree(reloc_root, path, &level);
1688 		if (ret > 0)
1689 			break;
1690 
1691 		BUG_ON(level == 0);
1692 		/*
1693 		 * save the merging progress in the drop_progress.
1694 		 * this is OK since root refs == 1 in this case.
1695 		 */
1696 		btrfs_node_key(path->nodes[level], &root_item->drop_progress,
1697 			       path->slots[level]);
1698 		btrfs_set_root_drop_level(root_item, level);
1699 
1700 		btrfs_end_transaction_throttle(trans);
1701 		trans = NULL;
1702 
1703 		btrfs_btree_balance_dirty(fs_info);
1704 
1705 		if (replaced && rc->stage == UPDATE_DATA_PTRS)
1706 			invalidate_extent_cache(root, &key, &next_key);
1707 	}
1708 
1709 	/*
1710 	 * handle the case only one block in the fs tree need to be
1711 	 * relocated and the block is tree root.
1712 	 */
1713 	leaf = btrfs_lock_root_node(root);
1714 	ret = btrfs_cow_block(trans, root, leaf, NULL, 0, &leaf,
1715 			      BTRFS_NESTING_COW);
1716 	btrfs_tree_unlock(leaf);
1717 	free_extent_buffer(leaf);
1718 out:
1719 	btrfs_free_path(path);
1720 
1721 	if (ret == 0) {
1722 		ret = insert_dirty_subvol(trans, rc, root);
1723 		if (ret)
1724 			btrfs_abort_transaction(trans, ret);
1725 	}
1726 
1727 	if (trans)
1728 		btrfs_end_transaction_throttle(trans);
1729 
1730 	btrfs_btree_balance_dirty(fs_info);
1731 
1732 	if (replaced && rc->stage == UPDATE_DATA_PTRS)
1733 		invalidate_extent_cache(root, &key, &next_key);
1734 
1735 	return ret;
1736 }
1737 
1738 static noinline_for_stack
1739 int prepare_to_merge(struct reloc_control *rc, int err)
1740 {
1741 	struct btrfs_root *root = rc->extent_root;
1742 	struct btrfs_fs_info *fs_info = root->fs_info;
1743 	struct btrfs_root *reloc_root;
1744 	struct btrfs_trans_handle *trans;
1745 	LIST_HEAD(reloc_roots);
1746 	u64 num_bytes = 0;
1747 	int ret;
1748 
1749 	mutex_lock(&fs_info->reloc_mutex);
1750 	rc->merging_rsv_size += fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
1751 	rc->merging_rsv_size += rc->nodes_relocated * 2;
1752 	mutex_unlock(&fs_info->reloc_mutex);
1753 
1754 again:
1755 	if (!err) {
1756 		num_bytes = rc->merging_rsv_size;
1757 		ret = btrfs_block_rsv_add(fs_info, rc->block_rsv, num_bytes,
1758 					  BTRFS_RESERVE_FLUSH_ALL);
1759 		if (ret)
1760 			err = ret;
1761 	}
1762 
1763 	trans = btrfs_join_transaction(rc->extent_root);
1764 	if (IS_ERR(trans)) {
1765 		if (!err)
1766 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
1767 						num_bytes, NULL);
1768 		return PTR_ERR(trans);
1769 	}
1770 
1771 	if (!err) {
1772 		if (num_bytes != rc->merging_rsv_size) {
1773 			btrfs_end_transaction(trans);
1774 			btrfs_block_rsv_release(fs_info, rc->block_rsv,
1775 						num_bytes, NULL);
1776 			goto again;
1777 		}
1778 	}
1779 
1780 	rc->merge_reloc_tree = true;
1781 
1782 	while (!list_empty(&rc->reloc_roots)) {
1783 		reloc_root = list_first_entry(&rc->reloc_roots,
1784 					      struct btrfs_root, root_list);
1785 		list_del_init(&reloc_root->root_list);
1786 
1787 		root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
1788 				false);
1789 		if (IS_ERR(root)) {
1790 			/*
1791 			 * Even if we have an error we need this reloc root
1792 			 * back on our list so we can clean up properly.
1793 			 */
1794 			list_add(&reloc_root->root_list, &reloc_roots);
1795 			btrfs_abort_transaction(trans, (int)PTR_ERR(root));
1796 			if (!err)
1797 				err = PTR_ERR(root);
1798 			break;
1799 		}
1800 
1801 		if (unlikely(root->reloc_root != reloc_root)) {
1802 			if (root->reloc_root) {
1803 				btrfs_err(fs_info,
1804 "reloc tree mismatch, root %lld has reloc root key (%lld %u %llu) gen %llu, expect reloc root key (%lld %u %llu) gen %llu",
1805 					  btrfs_root_id(root),
1806 					  btrfs_root_id(root->reloc_root),
1807 					  root->reloc_root->root_key.type,
1808 					  root->reloc_root->root_key.offset,
1809 					  btrfs_root_generation(
1810 						  &root->reloc_root->root_item),
1811 					  btrfs_root_id(reloc_root),
1812 					  reloc_root->root_key.type,
1813 					  reloc_root->root_key.offset,
1814 					  btrfs_root_generation(
1815 						  &reloc_root->root_item));
1816 			} else {
1817 				btrfs_err(fs_info,
1818 "reloc tree mismatch, root %lld has no reloc root, expect reloc root key (%lld %u %llu) gen %llu",
1819 					  btrfs_root_id(root),
1820 					  btrfs_root_id(reloc_root),
1821 					  reloc_root->root_key.type,
1822 					  reloc_root->root_key.offset,
1823 					  btrfs_root_generation(
1824 						  &reloc_root->root_item));
1825 			}
1826 			list_add(&reloc_root->root_list, &reloc_roots);
1827 			btrfs_put_root(root);
1828 			btrfs_abort_transaction(trans, -EUCLEAN);
1829 			if (!err)
1830 				err = -EUCLEAN;
1831 			break;
1832 		}
1833 
1834 		/*
1835 		 * set reference count to 1, so btrfs_recover_relocation
1836 		 * knows it should resumes merging
1837 		 */
1838 		if (!err)
1839 			btrfs_set_root_refs(&reloc_root->root_item, 1);
1840 		ret = btrfs_update_reloc_root(trans, root);
1841 
1842 		/*
1843 		 * Even if we have an error we need this reloc root back on our
1844 		 * list so we can clean up properly.
1845 		 */
1846 		list_add(&reloc_root->root_list, &reloc_roots);
1847 		btrfs_put_root(root);
1848 
1849 		if (unlikely(ret)) {
1850 			btrfs_abort_transaction(trans, ret);
1851 			if (!err)
1852 				err = ret;
1853 			break;
1854 		}
1855 	}
1856 
1857 	list_splice(&reloc_roots, &rc->reloc_roots);
1858 
1859 	if (!err)
1860 		err = btrfs_commit_transaction(trans);
1861 	else
1862 		btrfs_end_transaction(trans);
1863 	return err;
1864 }
1865 
1866 static noinline_for_stack
1867 void merge_reloc_roots(struct reloc_control *rc)
1868 {
1869 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
1870 	struct btrfs_root *root;
1871 	struct btrfs_root *reloc_root;
1872 	LIST_HEAD(reloc_roots);
1873 	bool found = false;
1874 	int ret = 0;
1875 again:
1876 	root = rc->extent_root;
1877 
1878 	/*
1879 	 * this serializes us with btrfs_record_root_in_transaction,
1880 	 * we have to make sure nobody is in the middle of
1881 	 * adding their roots to the list while we are
1882 	 * doing this splice
1883 	 */
1884 	mutex_lock(&fs_info->reloc_mutex);
1885 	list_splice_init(&rc->reloc_roots, &reloc_roots);
1886 	mutex_unlock(&fs_info->reloc_mutex);
1887 
1888 	while (!list_empty(&reloc_roots)) {
1889 		found = true;
1890 		reloc_root = list_first_entry(&reloc_roots, struct btrfs_root, root_list);
1891 
1892 		root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
1893 					 false);
1894 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
1895 			if (WARN_ON(IS_ERR(root))) {
1896 				/*
1897 				 * For recovery we read the fs roots on mount,
1898 				 * and if we didn't find the root then we marked
1899 				 * the reloc root as a garbage root.  For normal
1900 				 * relocation obviously the root should exist in
1901 				 * memory.  However there's no reason we can't
1902 				 * handle the error properly here just in case.
1903 				 */
1904 				ret = PTR_ERR(root);
1905 				goto out;
1906 			}
1907 			if (WARN_ON(root->reloc_root != reloc_root)) {
1908 				/*
1909 				 * This can happen if on-disk metadata has some
1910 				 * corruption, e.g. bad reloc tree key offset.
1911 				 */
1912 				ret = -EINVAL;
1913 				btrfs_put_root(root);
1914 				goto out;
1915 			}
1916 			ret = merge_reloc_root(rc, root);
1917 			btrfs_put_root(root);
1918 			if (ret) {
1919 				if (list_empty(&reloc_root->root_list))
1920 					list_add_tail(&reloc_root->root_list,
1921 						      &reloc_roots);
1922 				goto out;
1923 			}
1924 		} else {
1925 			if (!IS_ERR(root)) {
1926 				if (root->reloc_root == reloc_root) {
1927 					root->reloc_root = NULL;
1928 					btrfs_put_root(reloc_root);
1929 				}
1930 				clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE,
1931 					  &root->state);
1932 				btrfs_put_root(root);
1933 			}
1934 
1935 			list_del_init(&reloc_root->root_list);
1936 			/* Don't forget to queue this reloc root for cleanup */
1937 			list_add_tail(&reloc_root->reloc_dirty_list,
1938 				      &rc->dirty_subvol_roots);
1939 		}
1940 	}
1941 
1942 	if (found) {
1943 		found = false;
1944 		goto again;
1945 	}
1946 out:
1947 	if (ret) {
1948 		btrfs_handle_fs_error(fs_info, ret, NULL);
1949 		free_reloc_roots(&reloc_roots);
1950 
1951 		/* new reloc root may be added */
1952 		mutex_lock(&fs_info->reloc_mutex);
1953 		list_splice_init(&rc->reloc_roots, &reloc_roots);
1954 		mutex_unlock(&fs_info->reloc_mutex);
1955 		free_reloc_roots(&reloc_roots);
1956 	}
1957 
1958 	/*
1959 	 * We used to have
1960 	 *
1961 	 * BUG_ON(!RB_EMPTY_ROOT(&rc->reloc_root_tree.rb_root));
1962 	 *
1963 	 * here, but it's wrong.  If we fail to start the transaction in
1964 	 * prepare_to_merge() we will have only 0 ref reloc roots, none of which
1965 	 * have actually been removed from the reloc_root_tree rb tree.  This is
1966 	 * fine because we're bailing here, and we hold a reference on the root
1967 	 * for the list that holds it, so these roots will be cleaned up when we
1968 	 * do the reloc_dirty_list afterwards.  Meanwhile the root->reloc_root
1969 	 * will be cleaned up on unmount.
1970 	 *
1971 	 * The remaining nodes will be cleaned up by put_reloc_control().
1972 	 */
1973 }
1974 
1975 static void free_block_list(struct rb_root *blocks)
1976 {
1977 	struct tree_block *block;
1978 	struct rb_node *rb_node;
1979 	while ((rb_node = rb_first(blocks))) {
1980 		block = rb_entry(rb_node, struct tree_block, rb_node);
1981 		rb_erase(rb_node, blocks);
1982 		kfree(block);
1983 	}
1984 }
1985 
1986 static int record_reloc_root_in_trans(struct btrfs_trans_handle *trans,
1987 				      struct btrfs_root *reloc_root)
1988 {
1989 	struct btrfs_fs_info *fs_info = reloc_root->fs_info;
1990 	struct btrfs_root *root;
1991 	int ret;
1992 
1993 	if (btrfs_get_root_last_trans(reloc_root) == trans->transid)
1994 		return 0;
1995 
1996 	root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset, false);
1997 
1998 	/*
1999 	 * This should succeed, since we can't have a reloc root without having
2000 	 * already looked up the actual root and created the reloc root for this
2001 	 * root.
2002 	 *
2003 	 * However if there's some sort of corruption where we have a ref to a
2004 	 * reloc root without a corresponding root this could return ENOENT.
2005 	 */
2006 	if (IS_ERR(root)) {
2007 		DEBUG_WARN("error %ld reading root for reloc root", PTR_ERR(root));
2008 		return PTR_ERR(root);
2009 	}
2010 	if (unlikely(root->reloc_root != reloc_root)) {
2011 		DEBUG_WARN("unexpected reloc root found");
2012 		btrfs_err(fs_info,
2013 			  "root %llu has two reloc roots associated with it",
2014 			  reloc_root->root_key.offset);
2015 		btrfs_put_root(root);
2016 		return -EUCLEAN;
2017 	}
2018 	ret = btrfs_record_root_in_trans(trans, root);
2019 	btrfs_put_root(root);
2020 
2021 	return ret;
2022 }
2023 
2024 static noinline_for_stack
2025 struct btrfs_root *select_reloc_root(struct btrfs_trans_handle *trans,
2026 				     struct reloc_control *rc,
2027 				     struct btrfs_backref_node *node,
2028 				     struct btrfs_backref_edge *edges[])
2029 {
2030 	struct btrfs_backref_node *next;
2031 	struct btrfs_root *root;
2032 	int index = 0;
2033 	int ret;
2034 
2035 	next = walk_up_backref(node, edges, &index);
2036 	root = next->root;
2037 
2038 	/*
2039 	 * If there is no root, then our references for this block are
2040 	 * incomplete, as we should be able to walk all the way up to a block
2041 	 * that is owned by a root.
2042 	 *
2043 	 * This path is only for SHAREABLE roots, so if we come upon a
2044 	 * non-SHAREABLE root then we have backrefs that resolve improperly.
2045 	 *
2046 	 * Both of these cases indicate file system corruption, or a bug in the
2047 	 * backref walking code.
2048 	 */
2049 	if (unlikely(!root)) {
2050 		btrfs_err(trans->fs_info,
2051 			  "bytenr %llu doesn't have a backref path ending in a root",
2052 			  node->bytenr);
2053 		return ERR_PTR(-EUCLEAN);
2054 	}
2055 	if (unlikely(!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))) {
2056 		btrfs_err(trans->fs_info,
2057 			  "bytenr %llu has multiple refs with one ending in a non-shareable root",
2058 			  node->bytenr);
2059 		return ERR_PTR(-EUCLEAN);
2060 	}
2061 
2062 	if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID) {
2063 		ret = record_reloc_root_in_trans(trans, root);
2064 		if (ret)
2065 			return ERR_PTR(ret);
2066 		goto found;
2067 	}
2068 
2069 	ret = btrfs_record_root_in_trans(trans, root);
2070 	if (ret)
2071 		return ERR_PTR(ret);
2072 	root = root->reloc_root;
2073 
2074 	/*
2075 	 * We could have raced with another thread which failed, so
2076 	 * root->reloc_root may not be set, return ENOENT in this case.
2077 	 */
2078 	if (!root)
2079 		return ERR_PTR(-ENOENT);
2080 
2081 	if (unlikely(next->new_bytenr)) {
2082 		/*
2083 		 * We just created the reloc root, so we shouldn't have
2084 		 * ->new_bytenr set yet. If it is then we have multiple roots
2085 		 *  pointing at the same bytenr which indicates corruption, or
2086 		 *  we've made a mistake in the backref walking code.
2087 		 */
2088 		ASSERT(next->new_bytenr == 0);
2089 		btrfs_err(trans->fs_info,
2090 			  "bytenr %llu possibly has multiple roots pointing at the same bytenr %llu",
2091 			  node->bytenr, next->bytenr);
2092 		return ERR_PTR(-EUCLEAN);
2093 	}
2094 
2095 	next->new_bytenr = root->node->start;
2096 	btrfs_put_root(next->root);
2097 	next->root = btrfs_grab_root(root);
2098 	ASSERT(next->root);
2099 	mark_block_processed(rc, next);
2100 found:
2101 	next = node;
2102 	/* setup backref node path for btrfs_reloc_cow_block */
2103 	while (1) {
2104 		rc->backref_cache.path[next->level] = next;
2105 		if (--index < 0)
2106 			break;
2107 		next = edges[index]->node[UPPER];
2108 	}
2109 	return root;
2110 }
2111 
2112 /*
2113  * Select a tree root for relocation.
2114  *
2115  * Return NULL if the block is not shareable. We should use do_relocation() in
2116  * this case.
2117  *
2118  * Return a tree root pointer if the block is shareable.
2119  * Return -ENOENT if the block is root of reloc tree.
2120  */
2121 static noinline_for_stack
2122 struct btrfs_root *select_one_root(struct btrfs_backref_node *node)
2123 {
2124 	struct btrfs_backref_node *next;
2125 	struct btrfs_root *root;
2126 	struct btrfs_root *fs_root = NULL;
2127 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
2128 	int index = 0;
2129 
2130 	next = node;
2131 	while (1) {
2132 		cond_resched();
2133 		next = walk_up_backref(next, edges, &index);
2134 		root = next->root;
2135 
2136 		/*
2137 		 * This can occur if we have incomplete extent refs leading all
2138 		 * the way up a particular path, in this case return -EUCLEAN.
2139 		 */
2140 		if (unlikely(!root))
2141 			return ERR_PTR(-EUCLEAN);
2142 
2143 		/* No other choice for non-shareable tree */
2144 		if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
2145 			return root;
2146 
2147 		if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID)
2148 			fs_root = root;
2149 
2150 		if (next != node)
2151 			return NULL;
2152 
2153 		next = walk_down_backref(edges, &index);
2154 		if (!next || next->level <= node->level)
2155 			break;
2156 	}
2157 
2158 	if (!fs_root)
2159 		return ERR_PTR(-ENOENT);
2160 	return fs_root;
2161 }
2162 
2163 static noinline_for_stack u64 calcu_metadata_size(struct reloc_control *rc,
2164 						  struct btrfs_backref_node *node)
2165 {
2166 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2167 	struct btrfs_backref_node *next = node;
2168 	struct btrfs_backref_edge *edge;
2169 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
2170 	u64 num_bytes = 0;
2171 	int index = 0;
2172 
2173 	BUG_ON(node->processed);
2174 
2175 	while (next) {
2176 		cond_resched();
2177 		while (1) {
2178 			if (next->processed)
2179 				break;
2180 
2181 			num_bytes += fs_info->nodesize;
2182 
2183 			if (list_empty(&next->upper))
2184 				break;
2185 
2186 			edge = list_first_entry(&next->upper, struct btrfs_backref_edge,
2187 						list[LOWER]);
2188 			edges[index++] = edge;
2189 			next = edge->node[UPPER];
2190 		}
2191 		next = walk_down_backref(edges, &index);
2192 	}
2193 	return num_bytes;
2194 }
2195 
2196 static int refill_metadata_space(struct btrfs_trans_handle *trans,
2197 				 struct reloc_control *rc, u64 num_bytes)
2198 {
2199 	struct btrfs_fs_info *fs_info = trans->fs_info;
2200 	int ret;
2201 
2202 	trans->block_rsv = rc->block_rsv;
2203 	rc->reserved_bytes += num_bytes;
2204 
2205 	/*
2206 	 * We are under a transaction here so we can only do limited flushing.
2207 	 * If we get an enospc just kick back -EAGAIN so we know to drop the
2208 	 * transaction and try to refill when we can flush all the things.
2209 	 */
2210 	ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv, num_bytes,
2211 				     BTRFS_RESERVE_FLUSH_LIMIT);
2212 	if (ret) {
2213 		u64 tmp = fs_info->nodesize * RELOCATION_RESERVED_NODES;
2214 
2215 		while (tmp <= rc->reserved_bytes)
2216 			tmp <<= 1;
2217 		/*
2218 		 * only one thread can access block_rsv at this point,
2219 		 * so we don't need hold lock to protect block_rsv.
2220 		 * we expand more reservation size here to allow enough
2221 		 * space for relocation and we will return earlier in
2222 		 * enospc case.
2223 		 */
2224 		rc->block_rsv->size = tmp + fs_info->nodesize *
2225 				      RELOCATION_RESERVED_NODES;
2226 		return -EAGAIN;
2227 	}
2228 
2229 	return 0;
2230 }
2231 
2232 static int reserve_metadata_space(struct btrfs_trans_handle *trans,
2233 				  struct reloc_control *rc,
2234 				  struct btrfs_backref_node *node)
2235 {
2236 	u64 num_bytes;
2237 
2238 	num_bytes = calcu_metadata_size(rc, node) * 2;
2239 	return refill_metadata_space(trans, rc, num_bytes);
2240 }
2241 
2242 /*
2243  * relocate a block tree, and then update pointers in upper level
2244  * blocks that reference the block to point to the new location.
2245  *
2246  * if called by link_to_upper, the block has already been relocated.
2247  * in that case this function just updates pointers.
2248  */
2249 static int do_relocation(struct btrfs_trans_handle *trans,
2250 			 struct reloc_control *rc,
2251 			 struct btrfs_backref_node *node,
2252 			 struct btrfs_key *key,
2253 			 struct btrfs_path *path, int lowest)
2254 {
2255 	struct btrfs_backref_node *upper;
2256 	struct btrfs_backref_edge *edge;
2257 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
2258 	struct btrfs_root *root;
2259 	struct extent_buffer *eb;
2260 	u32 blocksize;
2261 	u64 bytenr;
2262 	int slot;
2263 	int ret = 0;
2264 
2265 	/*
2266 	 * If we are lowest then this is the first time we're processing this
2267 	 * block, and thus shouldn't have an eb associated with it yet.
2268 	 */
2269 	ASSERT(!lowest || !node->eb);
2270 
2271 	path->lowest_level = node->level + 1;
2272 	rc->backref_cache.path[node->level] = node;
2273 	list_for_each_entry(edge, &node->upper, list[LOWER]) {
2274 		cond_resched();
2275 
2276 		upper = edge->node[UPPER];
2277 		root = select_reloc_root(trans, rc, upper, edges);
2278 		if (IS_ERR(root)) {
2279 			ret = PTR_ERR(root);
2280 			goto next;
2281 		}
2282 
2283 		if (upper->eb && !upper->locked) {
2284 			if (!lowest) {
2285 				ret = btrfs_bin_search(upper->eb, 0, key, &slot);
2286 				if (ret < 0)
2287 					goto next;
2288 				BUG_ON(ret);
2289 				bytenr = btrfs_node_blockptr(upper->eb, slot);
2290 				if (node->eb->start == bytenr)
2291 					goto next;
2292 			}
2293 			btrfs_backref_drop_node_buffer(upper);
2294 		}
2295 
2296 		if (!upper->eb) {
2297 			ret = btrfs_search_slot(trans, root, key, path, 0, 1);
2298 			if (ret) {
2299 				if (ret > 0)
2300 					ret = -ENOENT;
2301 
2302 				btrfs_release_path(path);
2303 				break;
2304 			}
2305 
2306 			if (!upper->eb) {
2307 				upper->eb = path->nodes[upper->level];
2308 				path->nodes[upper->level] = NULL;
2309 			} else {
2310 				BUG_ON(upper->eb != path->nodes[upper->level]);
2311 			}
2312 
2313 			upper->locked = 1;
2314 			path->locks[upper->level] = 0;
2315 
2316 			slot = path->slots[upper->level];
2317 			btrfs_release_path(path);
2318 		} else {
2319 			ret = btrfs_bin_search(upper->eb, 0, key, &slot);
2320 			if (ret < 0)
2321 				goto next;
2322 			BUG_ON(ret);
2323 		}
2324 
2325 		bytenr = btrfs_node_blockptr(upper->eb, slot);
2326 		if (lowest) {
2327 			if (unlikely(bytenr != node->bytenr)) {
2328 				btrfs_err(root->fs_info,
2329 		"lowest leaf/node mismatch: bytenr %llu node->bytenr %llu slot %d upper %llu",
2330 					  bytenr, node->bytenr, slot,
2331 					  upper->eb->start);
2332 				ret = -EIO;
2333 				goto next;
2334 			}
2335 		} else {
2336 			if (node->eb->start == bytenr)
2337 				goto next;
2338 		}
2339 
2340 		blocksize = root->fs_info->nodesize;
2341 		eb = btrfs_read_node_slot(upper->eb, slot);
2342 		if (IS_ERR(eb)) {
2343 			ret = PTR_ERR(eb);
2344 			goto next;
2345 		}
2346 		btrfs_tree_lock(eb);
2347 
2348 		if (!node->eb) {
2349 			ret = btrfs_cow_block(trans, root, eb, upper->eb,
2350 					      slot, &eb, BTRFS_NESTING_COW);
2351 			btrfs_tree_unlock(eb);
2352 			free_extent_buffer(eb);
2353 			if (ret < 0)
2354 				goto next;
2355 			/*
2356 			 * We've just COWed this block, it should have updated
2357 			 * the correct backref node entry.
2358 			 */
2359 			ASSERT(node->eb == eb);
2360 		} else {
2361 			struct btrfs_ref ref = {
2362 				.action = BTRFS_ADD_DELAYED_REF,
2363 				.bytenr = node->eb->start,
2364 				.num_bytes = blocksize,
2365 				.parent = upper->eb->start,
2366 				.owning_root = btrfs_header_owner(upper->eb),
2367 				.ref_root = btrfs_header_owner(upper->eb),
2368 			};
2369 
2370 			btrfs_set_node_blockptr(upper->eb, slot,
2371 						node->eb->start);
2372 			btrfs_set_node_ptr_generation(upper->eb, slot,
2373 						      trans->transid);
2374 			btrfs_mark_buffer_dirty(trans, upper->eb);
2375 
2376 			btrfs_init_tree_ref(&ref, node->level,
2377 					    btrfs_root_id(root), false);
2378 			ret = btrfs_inc_extent_ref(trans, &ref);
2379 			if (!ret)
2380 				ret = btrfs_drop_subtree(trans, root, eb,
2381 							 upper->eb);
2382 			if (unlikely(ret))
2383 				btrfs_abort_transaction(trans, ret);
2384 		}
2385 next:
2386 		if (!upper->pending)
2387 			btrfs_backref_drop_node_buffer(upper);
2388 		else
2389 			btrfs_backref_unlock_node_buffer(upper);
2390 		if (ret)
2391 			break;
2392 	}
2393 
2394 	if (!ret && node->pending) {
2395 		btrfs_backref_drop_node_buffer(node);
2396 		list_del_init(&node->list);
2397 		node->pending = 0;
2398 	}
2399 
2400 	path->lowest_level = 0;
2401 
2402 	/*
2403 	 * We should have allocated all of our space in the block rsv and thus
2404 	 * shouldn't ENOSPC.
2405 	 */
2406 	ASSERT(ret != -ENOSPC);
2407 	return ret;
2408 }
2409 
2410 static int link_to_upper(struct btrfs_trans_handle *trans,
2411 			 struct reloc_control *rc,
2412 			 struct btrfs_backref_node *node,
2413 			 struct btrfs_path *path)
2414 {
2415 	struct btrfs_key key;
2416 
2417 	btrfs_node_key_to_cpu(node->eb, &key, 0);
2418 	return do_relocation(trans, rc, node, &key, path, 0);
2419 }
2420 
2421 static int finish_pending_nodes(struct btrfs_trans_handle *trans,
2422 				struct reloc_control *rc,
2423 				struct btrfs_path *path, int err)
2424 {
2425 	LIST_HEAD(list);
2426 	struct btrfs_backref_cache *cache = &rc->backref_cache;
2427 	struct btrfs_backref_node *node;
2428 	int level;
2429 	int ret;
2430 
2431 	for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2432 		while (!list_empty(&cache->pending[level])) {
2433 			node = list_first_entry(&cache->pending[level],
2434 						struct btrfs_backref_node, list);
2435 			list_move_tail(&node->list, &list);
2436 			BUG_ON(!node->pending);
2437 
2438 			if (!err) {
2439 				ret = link_to_upper(trans, rc, node, path);
2440 				if (ret < 0)
2441 					err = ret;
2442 			}
2443 		}
2444 		list_splice_init(&list, &cache->pending[level]);
2445 	}
2446 	return err;
2447 }
2448 
2449 /*
2450  * mark a block and all blocks directly/indirectly reference the block
2451  * as processed.
2452  */
2453 static void update_processed_blocks(struct reloc_control *rc,
2454 				    struct btrfs_backref_node *node)
2455 {
2456 	struct btrfs_backref_node *next = node;
2457 	struct btrfs_backref_edge *edge;
2458 	struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
2459 	int index = 0;
2460 
2461 	while (next) {
2462 		cond_resched();
2463 		while (1) {
2464 			if (next->processed)
2465 				break;
2466 
2467 			mark_block_processed(rc, next);
2468 
2469 			if (list_empty(&next->upper))
2470 				break;
2471 
2472 			edge = list_first_entry(&next->upper, struct btrfs_backref_edge,
2473 						list[LOWER]);
2474 			edges[index++] = edge;
2475 			next = edge->node[UPPER];
2476 		}
2477 		next = walk_down_backref(edges, &index);
2478 	}
2479 }
2480 
2481 static int tree_block_processed(u64 bytenr, struct reloc_control *rc)
2482 {
2483 	u32 blocksize = rc->extent_root->fs_info->nodesize;
2484 
2485 	if (btrfs_test_range_bit(&rc->processed_blocks, bytenr,
2486 				 bytenr + blocksize - 1, EXTENT_DIRTY, NULL))
2487 		return 1;
2488 	return 0;
2489 }
2490 
2491 static int get_tree_block_key(struct btrfs_fs_info *fs_info,
2492 			      struct tree_block *block)
2493 {
2494 	struct btrfs_tree_parent_check check = {
2495 		.level = block->level,
2496 		.owner_root = block->owner,
2497 		.transid = block->key.offset
2498 	};
2499 	struct extent_buffer *eb;
2500 
2501 	eb = read_tree_block(fs_info, block->bytenr, &check);
2502 	if (IS_ERR(eb))
2503 		return PTR_ERR(eb);
2504 
2505 	if (block->level == 0)
2506 		btrfs_item_key_to_cpu(eb, &block->key, 0);
2507 	else
2508 		btrfs_node_key_to_cpu(eb, &block->key, 0);
2509 	free_extent_buffer(eb);
2510 	block->key_ready = true;
2511 	return 0;
2512 }
2513 
2514 /*
2515  * helper function to relocate a tree block
2516  */
2517 static int relocate_tree_block(struct btrfs_trans_handle *trans,
2518 				struct reloc_control *rc,
2519 				struct btrfs_backref_node *node,
2520 				struct btrfs_key *key,
2521 				struct btrfs_path *path)
2522 {
2523 	struct btrfs_root *root;
2524 	int ret = 0;
2525 
2526 	if (!node)
2527 		return 0;
2528 
2529 	/*
2530 	 * If we fail here we want to drop our backref_node because we are going
2531 	 * to start over and regenerate the tree for it.
2532 	 */
2533 	ret = reserve_metadata_space(trans, rc, node);
2534 	if (ret)
2535 		goto out;
2536 
2537 	BUG_ON(node->processed);
2538 	root = select_one_root(node);
2539 	if (IS_ERR(root)) {
2540 		ret = PTR_ERR(root);
2541 
2542 		/* See explanation in select_one_root for the -EUCLEAN case. */
2543 		ASSERT(ret == -ENOENT);
2544 		if (ret == -ENOENT) {
2545 			ret = 0;
2546 			update_processed_blocks(rc, node);
2547 		}
2548 		goto out;
2549 	}
2550 
2551 	if (root) {
2552 		if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
2553 			/*
2554 			 * This block was the root block of a root, and this is
2555 			 * the first time we're processing the block and thus it
2556 			 * should not have had the ->new_bytenr modified.
2557 			 *
2558 			 * However in the case of corruption we could have
2559 			 * multiple refs pointing to the same block improperly,
2560 			 * and thus we would trip over these checks.  ASSERT()
2561 			 * for the developer case, because it could indicate a
2562 			 * bug in the backref code, however error out for a
2563 			 * normal user in the case of corruption.
2564 			 */
2565 			ASSERT(node->new_bytenr == 0);
2566 			if (unlikely(node->new_bytenr)) {
2567 				btrfs_err(root->fs_info,
2568 				  "bytenr %llu has improper references to it",
2569 					  node->bytenr);
2570 				ret = -EUCLEAN;
2571 				goto out;
2572 			}
2573 			ret = btrfs_record_root_in_trans(trans, root);
2574 			if (ret)
2575 				goto out;
2576 			/*
2577 			 * Another thread could have failed, need to check if we
2578 			 * have reloc_root actually set.
2579 			 */
2580 			if (!root->reloc_root) {
2581 				ret = -ENOENT;
2582 				goto out;
2583 			}
2584 			root = root->reloc_root;
2585 			node->new_bytenr = root->node->start;
2586 			btrfs_put_root(node->root);
2587 			node->root = btrfs_grab_root(root);
2588 			ASSERT(node->root);
2589 		} else {
2590 			btrfs_err(root->fs_info,
2591 				  "bytenr %llu resolved to a non-shareable root",
2592 				  node->bytenr);
2593 			ret = -EUCLEAN;
2594 			goto out;
2595 		}
2596 		if (!ret)
2597 			update_processed_blocks(rc, node);
2598 	} else {
2599 		ret = do_relocation(trans, rc, node, key, path, 1);
2600 	}
2601 out:
2602 	if (ret || node->level == 0)
2603 		btrfs_backref_cleanup_node(&rc->backref_cache, node);
2604 	return ret;
2605 }
2606 
2607 static int relocate_cowonly_block(struct btrfs_trans_handle *trans,
2608 				  struct reloc_control *rc, struct tree_block *block,
2609 				  struct btrfs_path *path)
2610 {
2611 	struct btrfs_fs_info *fs_info = trans->fs_info;
2612 	struct btrfs_root *root;
2613 	u64 num_bytes;
2614 	int nr_levels;
2615 	int ret;
2616 
2617 	root = btrfs_get_fs_root(fs_info, block->owner, true);
2618 	if (IS_ERR(root))
2619 		return PTR_ERR(root);
2620 
2621 	nr_levels = max(btrfs_header_level(root->node) - block->level, 0) + 1;
2622 
2623 	num_bytes = (nr_levels << fs_info->nodesize_bits);
2624 	ret = refill_metadata_space(trans, rc, num_bytes);
2625 	if (ret) {
2626 		btrfs_put_root(root);
2627 		return ret;
2628 	}
2629 	path->lowest_level = block->level;
2630 	if (root == root->fs_info->chunk_root)
2631 		btrfs_reserve_chunk_metadata(trans, false);
2632 
2633 	ret = btrfs_search_slot(trans, root, &block->key, path, 0, 1);
2634 	path->lowest_level = 0;
2635 	btrfs_release_path(path);
2636 
2637 	if (root == root->fs_info->chunk_root)
2638 		btrfs_trans_release_chunk_metadata(trans);
2639 	if (ret > 0)
2640 		ret = 0;
2641 	btrfs_put_root(root);
2642 
2643 	return ret;
2644 }
2645 
2646 /*
2647  * relocate a list of blocks
2648  */
2649 static noinline_for_stack
2650 int relocate_tree_blocks(struct btrfs_trans_handle *trans,
2651 			 struct reloc_control *rc, struct rb_root *blocks)
2652 {
2653 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2654 	struct btrfs_backref_node *node;
2655 	struct btrfs_path *path;
2656 	struct tree_block *block;
2657 	struct tree_block *next;
2658 	int ret = 0;
2659 
2660 	path = btrfs_alloc_path();
2661 	if (!path) {
2662 		ret = -ENOMEM;
2663 		goto out_free_blocks;
2664 	}
2665 
2666 	/* Kick in readahead for tree blocks with missing keys */
2667 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
2668 		if (!block->key_ready)
2669 			btrfs_readahead_tree_block(fs_info, block->bytenr,
2670 						   block->owner, 0,
2671 						   block->level, NULL);
2672 	}
2673 
2674 	/* Get first keys */
2675 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
2676 		if (!block->key_ready) {
2677 			ret = get_tree_block_key(fs_info, block);
2678 			if (ret)
2679 				goto out_free_path;
2680 		}
2681 	}
2682 
2683 	/* Do tree relocation */
2684 	rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
2685 		/*
2686 		 * For COWonly blocks, or the data reloc tree, we only need to
2687 		 * COW down to the block, there's no need to generate a backref
2688 		 * tree.
2689 		 */
2690 		if (block->owner &&
2691 		    (!btrfs_is_fstree(block->owner) ||
2692 		     block->owner == BTRFS_DATA_RELOC_TREE_OBJECTID)) {
2693 			ret = relocate_cowonly_block(trans, rc, block, path);
2694 			if (ret)
2695 				break;
2696 			continue;
2697 		}
2698 
2699 		node = build_backref_tree(trans, rc, &block->key,
2700 					  block->level, block->bytenr);
2701 		if (IS_ERR(node)) {
2702 			ret = PTR_ERR(node);
2703 			goto out;
2704 		}
2705 
2706 		ret = relocate_tree_block(trans, rc, node, &block->key,
2707 					  path);
2708 		if (ret < 0)
2709 			break;
2710 	}
2711 out:
2712 	ret = finish_pending_nodes(trans, rc, path, ret);
2713 
2714 out_free_path:
2715 	btrfs_free_path(path);
2716 out_free_blocks:
2717 	free_block_list(blocks);
2718 	return ret;
2719 }
2720 
2721 static noinline_for_stack int prealloc_file_extent_cluster(struct reloc_control *rc)
2722 {
2723 	const struct file_extent_cluster *cluster = &rc->cluster;
2724 	struct btrfs_inode *inode = BTRFS_I(rc->data_inode);
2725 	u64 alloc_hint = 0;
2726 	u64 start;
2727 	u64 end;
2728 	u64 offset = inode->reloc_block_group_start;
2729 	u64 num_bytes;
2730 	int nr;
2731 	int ret = 0;
2732 	u64 prealloc_start = cluster->start - offset;
2733 	u64 prealloc_end = cluster->end - offset;
2734 	u64 cur_offset = prealloc_start;
2735 
2736 	/*
2737 	 * For blocksize < folio size case (either bs < page size or large folios),
2738 	 * beyond i_size, all blocks are filled with zero.
2739 	 *
2740 	 * If the current cluster covers the above range, btrfs_do_readpage()
2741 	 * will skip the read, and relocate_one_folio() will later writeback
2742 	 * the padding zeros as new data, causing data corruption.
2743 	 *
2744 	 * Here we have to invalidate the cache covering our cluster.
2745 	 */
2746 	ret = filemap_invalidate_inode(&inode->vfs_inode, true, prealloc_start,
2747 				       prealloc_end);
2748 	if (ret < 0)
2749 		return ret;
2750 
2751 	BUG_ON(cluster->start != cluster->boundary[0]);
2752 	ret = btrfs_alloc_data_chunk_ondemand(inode,
2753 					      prealloc_end + 1 - prealloc_start);
2754 	if (ret)
2755 		return ret;
2756 
2757 	btrfs_inode_lock(inode, 0);
2758 	for (nr = 0; nr < cluster->nr; nr++) {
2759 		struct extent_state *cached_state = NULL;
2760 
2761 		start = cluster->boundary[nr] - offset;
2762 		if (nr + 1 < cluster->nr)
2763 			end = cluster->boundary[nr + 1] - 1 - offset;
2764 		else
2765 			end = cluster->end - offset;
2766 
2767 		btrfs_lock_extent(&inode->io_tree, start, end, &cached_state);
2768 		num_bytes = end + 1 - start;
2769 		ret = btrfs_prealloc_file_range(&inode->vfs_inode, 0, start,
2770 						num_bytes, num_bytes,
2771 						end + 1, &alloc_hint);
2772 		cur_offset = end + 1;
2773 		btrfs_unlock_extent(&inode->io_tree, start, end, &cached_state);
2774 		if (ret)
2775 			break;
2776 	}
2777 	btrfs_inode_unlock(inode, 0);
2778 
2779 	if (cur_offset < prealloc_end)
2780 		btrfs_free_reserved_data_space_noquota(inode,
2781 						       prealloc_end + 1 - cur_offset);
2782 	return ret;
2783 }
2784 
2785 static noinline_for_stack int setup_relocation_extent_mapping(struct reloc_control *rc)
2786 {
2787 	struct btrfs_inode *inode = BTRFS_I(rc->data_inode);
2788 	struct extent_map *em;
2789 	struct extent_state *cached_state = NULL;
2790 	u64 offset = inode->reloc_block_group_start;
2791 	u64 start = rc->cluster.start - offset;
2792 	u64 end = rc->cluster.end - offset;
2793 	int ret = 0;
2794 
2795 	em = btrfs_alloc_extent_map();
2796 	if (!em)
2797 		return -ENOMEM;
2798 
2799 	em->start = start;
2800 	em->len = end + 1 - start;
2801 	em->disk_bytenr = rc->cluster.start;
2802 	em->disk_num_bytes = em->len;
2803 	em->ram_bytes = em->len;
2804 	em->flags |= EXTENT_FLAG_PINNED;
2805 
2806 	btrfs_lock_extent(&inode->io_tree, start, end, &cached_state);
2807 	ret = btrfs_replace_extent_map_range(inode, em, false);
2808 	btrfs_unlock_extent(&inode->io_tree, start, end, &cached_state);
2809 	btrfs_free_extent_map(em);
2810 
2811 	return ret;
2812 }
2813 
2814 /*
2815  * Allow error injection to test balance/relocation cancellation
2816  */
2817 noinline int btrfs_should_cancel_balance(const struct btrfs_fs_info *fs_info)
2818 {
2819 	return atomic_read(&fs_info->balance_cancel_req) ||
2820 		atomic_read(&fs_info->reloc_cancel_req) ||
2821 		fatal_signal_pending(current);
2822 }
2823 ALLOW_ERROR_INJECTION(btrfs_should_cancel_balance, TRUE);
2824 
2825 static u64 get_cluster_boundary_end(const struct file_extent_cluster *cluster,
2826 				    int cluster_nr)
2827 {
2828 	/* Last extent, use cluster end directly */
2829 	if (cluster_nr >= cluster->nr - 1)
2830 		return cluster->end;
2831 
2832 	/* Use next boundary start*/
2833 	return cluster->boundary[cluster_nr + 1] - 1;
2834 }
2835 
2836 static int relocate_one_folio(struct reloc_control *rc,
2837 			      struct file_ra_state *ra,
2838 			      int *cluster_nr, u64 *file_offset_ret)
2839 {
2840 	const struct file_extent_cluster *cluster = &rc->cluster;
2841 	struct inode *inode = rc->data_inode;
2842 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
2843 	const u64 orig_file_offset = *file_offset_ret;
2844 	u64 offset = BTRFS_I(inode)->reloc_block_group_start;
2845 	const pgoff_t last_index = (cluster->end - offset) >> PAGE_SHIFT;
2846 	const pgoff_t index = orig_file_offset >> PAGE_SHIFT;
2847 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
2848 	struct folio *folio;
2849 	u64 folio_start;
2850 	u64 folio_end;
2851 	u64 cur;
2852 	int ret;
2853 	const bool use_rst = btrfs_need_stripe_tree_update(fs_info, rc->block_group->flags);
2854 
2855 	ASSERT(index <= last_index);
2856 again:
2857 	folio = filemap_lock_folio(inode->i_mapping, index);
2858 	if (IS_ERR(folio)) {
2859 
2860 		/*
2861 		 * On relocation we're doing readahead on the relocation inode,
2862 		 * but if the filesystem is backed by a RAID stripe tree we can
2863 		 * get ENOENT (e.g. due to preallocated extents not being
2864 		 * mapped in the RST) from the lookup.
2865 		 *
2866 		 * But readahead doesn't handle the error and submits invalid
2867 		 * reads to the device, causing a assertion failures.
2868 		 */
2869 		if (!use_rst)
2870 			page_cache_sync_readahead(inode->i_mapping, ra, NULL,
2871 						  index, last_index + 1 - index);
2872 		folio = __filemap_get_folio(inode->i_mapping, index,
2873 					    FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
2874 					    mask);
2875 		if (IS_ERR(folio))
2876 			return PTR_ERR(folio);
2877 	}
2878 
2879 	if (folio_test_readahead(folio) && !use_rst)
2880 		page_cache_async_readahead(inode->i_mapping, ra, NULL,
2881 					   folio, last_index + 1 - index);
2882 
2883 	if (!folio_test_uptodate(folio)) {
2884 		btrfs_read_folio(NULL, folio);
2885 		folio_lock(folio);
2886 		if (unlikely(!folio_test_uptodate(folio))) {
2887 			ret = -EIO;
2888 			goto release_folio;
2889 		}
2890 		if (folio->mapping != inode->i_mapping) {
2891 			folio_unlock(folio);
2892 			folio_put(folio);
2893 			goto again;
2894 		}
2895 	}
2896 
2897 	/*
2898 	 * We could have lost folio private when we dropped the lock to read the
2899 	 * folio above, make sure we set_folio_extent_mapped() here so we have any
2900 	 * of the subpage blocksize stuff we need in place.
2901 	 */
2902 	ret = set_folio_extent_mapped(folio);
2903 	if (ret < 0)
2904 		goto release_folio;
2905 
2906 	folio_start = folio_pos(folio);
2907 	folio_end = folio_start + folio_size(folio) - 1;
2908 
2909 	/*
2910 	 * Start from the cluster, as for subpage case, the cluster can start
2911 	 * inside the folio.
2912 	 */
2913 	cur = max(folio_start, cluster->boundary[*cluster_nr] - offset);
2914 	while (cur <= folio_end) {
2915 		struct extent_state *cached_state = NULL;
2916 		u64 extent_start = cluster->boundary[*cluster_nr] - offset;
2917 		u64 extent_end = get_cluster_boundary_end(cluster,
2918 						*cluster_nr) - offset;
2919 		u64 clamped_start = max(folio_start, extent_start);
2920 		u64 clamped_end = min(folio_end, extent_end);
2921 		u32 clamped_len = clamped_end + 1 - clamped_start;
2922 
2923 		/* Reserve metadata for this range */
2924 		ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
2925 						      clamped_len, clamped_len,
2926 						      false);
2927 		if (ret)
2928 			goto release_folio;
2929 
2930 		/* Mark the range delalloc and dirty for later writeback */
2931 		btrfs_lock_extent(&BTRFS_I(inode)->io_tree, clamped_start,
2932 				  clamped_end, &cached_state);
2933 		ret = btrfs_set_extent_delalloc(BTRFS_I(inode), clamped_start,
2934 						clamped_end, 0, &cached_state);
2935 		if (ret) {
2936 			btrfs_clear_extent_bit(&BTRFS_I(inode)->io_tree,
2937 					       clamped_start, clamped_end,
2938 					       EXTENT_LOCKED | EXTENT_BOUNDARY,
2939 					       &cached_state);
2940 			btrfs_delalloc_release_metadata(BTRFS_I(inode),
2941 							clamped_len, true);
2942 			btrfs_delalloc_release_extents(BTRFS_I(inode),
2943 						       clamped_len);
2944 			goto release_folio;
2945 		}
2946 		btrfs_folio_set_dirty(fs_info, folio, clamped_start, clamped_len);
2947 
2948 		/*
2949 		 * Set the boundary if it's inside the folio.
2950 		 * Data relocation requires the destination extents to have the
2951 		 * same size as the source.
2952 		 * EXTENT_BOUNDARY bit prevents current extent from being merged
2953 		 * with previous extent.
2954 		 */
2955 		if (in_range(cluster->boundary[*cluster_nr] - offset,
2956 			     folio_start, folio_size(folio))) {
2957 			u64 boundary_start = cluster->boundary[*cluster_nr] -
2958 						offset;
2959 			u64 boundary_end = boundary_start +
2960 					   fs_info->sectorsize - 1;
2961 
2962 			btrfs_set_extent_bit(&BTRFS_I(inode)->io_tree,
2963 					     boundary_start, boundary_end,
2964 					     EXTENT_BOUNDARY, NULL);
2965 		}
2966 		btrfs_unlock_extent(&BTRFS_I(inode)->io_tree, clamped_start, clamped_end,
2967 				    &cached_state);
2968 		btrfs_delalloc_release_extents(BTRFS_I(inode), clamped_len);
2969 		cur += clamped_len;
2970 
2971 		/* Crossed extent end, go to next extent */
2972 		if (cur >= extent_end) {
2973 			(*cluster_nr)++;
2974 			/* Just finished the last extent of the cluster, exit. */
2975 			if (*cluster_nr >= cluster->nr)
2976 				break;
2977 		}
2978 	}
2979 	folio_unlock(folio);
2980 	folio_put(folio);
2981 
2982 	balance_dirty_pages_ratelimited(inode->i_mapping);
2983 	btrfs_throttle(fs_info);
2984 	if (btrfs_should_cancel_balance(fs_info))
2985 		ret = -ECANCELED;
2986 	*file_offset_ret = folio_end + 1;
2987 	return ret;
2988 
2989 release_folio:
2990 	folio_unlock(folio);
2991 	folio_put(folio);
2992 	return ret;
2993 }
2994 
2995 static int relocate_file_extent_cluster(struct reloc_control *rc)
2996 {
2997 	struct inode *inode = rc->data_inode;
2998 	const struct file_extent_cluster *cluster = &rc->cluster;
2999 	u64 offset = BTRFS_I(inode)->reloc_block_group_start;
3000 	u64 cur_file_offset = cluster->start - offset;
3001 	struct file_ra_state AUTO_KFREE(ra);
3002 	int cluster_nr = 0;
3003 	int ret = 0;
3004 
3005 	if (!cluster->nr)
3006 		return 0;
3007 
3008 	ra = kzalloc_obj(*ra, GFP_NOFS);
3009 	if (!ra)
3010 		return -ENOMEM;
3011 
3012 	ret = prealloc_file_extent_cluster(rc);
3013 	if (ret)
3014 		return ret;
3015 
3016 	file_ra_state_init(ra, inode->i_mapping);
3017 
3018 	ret = setup_relocation_extent_mapping(rc);
3019 	if (ret)
3020 		return ret;
3021 
3022 	while (cur_file_offset < cluster->end - offset) {
3023 		ret = relocate_one_folio(rc, ra, &cluster_nr, &cur_file_offset);
3024 		if (ret)
3025 			break;
3026 	}
3027 	if (ret == 0)
3028 		WARN_ON(cluster_nr != cluster->nr);
3029 	return ret;
3030 }
3031 
3032 static noinline_for_stack int relocate_data_extent(struct reloc_control *rc,
3033 					   const struct btrfs_key *extent_key)
3034 {
3035 	struct inode *inode = rc->data_inode;
3036 	struct file_extent_cluster *cluster = &rc->cluster;
3037 	int ret;
3038 	struct btrfs_root *root = BTRFS_I(inode)->root;
3039 
3040 	if (cluster->nr > 0 && extent_key->objectid != cluster->end + 1) {
3041 		ret = relocate_file_extent_cluster(rc);
3042 		if (ret)
3043 			return ret;
3044 		cluster->nr = 0;
3045 	}
3046 
3047 	/*
3048 	 * Under simple quotas, we set root->relocation_src_root when we find
3049 	 * the extent. If adjacent extents have different owners, we can't merge
3050 	 * them while relocating. Handle this by storing the owning root that
3051 	 * started a cluster and if we see an extent from a different root break
3052 	 * cluster formation (just like the above case of non-adjacent extents).
3053 	 *
3054 	 * Without simple quotas, relocation_src_root is always 0, so we should
3055 	 * never see a mismatch, and it should have no effect on relocation
3056 	 * clusters.
3057 	 */
3058 	if (cluster->nr > 0 && cluster->owning_root != root->relocation_src_root) {
3059 		u64 tmp = root->relocation_src_root;
3060 
3061 		/*
3062 		 * root->relocation_src_root is the state that actually affects
3063 		 * the preallocation we do here, so set it to the root owning
3064 		 * the cluster we need to relocate.
3065 		 */
3066 		root->relocation_src_root = cluster->owning_root;
3067 		ret = relocate_file_extent_cluster(rc);
3068 		if (ret)
3069 			return ret;
3070 		cluster->nr = 0;
3071 		/* And reset it back for the current extent's owning root. */
3072 		root->relocation_src_root = tmp;
3073 	}
3074 
3075 	if (!cluster->nr) {
3076 		cluster->start = extent_key->objectid;
3077 		cluster->owning_root = root->relocation_src_root;
3078 	}
3079 	else
3080 		BUG_ON(cluster->nr >= MAX_EXTENTS);
3081 	cluster->end = extent_key->objectid + extent_key->offset - 1;
3082 	cluster->boundary[cluster->nr] = extent_key->objectid;
3083 	cluster->nr++;
3084 
3085 	if (cluster->nr >= MAX_EXTENTS) {
3086 		ret = relocate_file_extent_cluster(rc);
3087 		if (ret)
3088 			return ret;
3089 		cluster->nr = 0;
3090 	}
3091 	return 0;
3092 }
3093 
3094 /*
3095  * helper to add a tree block to the list.
3096  * the major work is getting the generation and level of the block
3097  */
3098 static int add_tree_block(struct reloc_control *rc,
3099 			  const struct btrfs_key *extent_key,
3100 			  struct btrfs_path *path,
3101 			  struct rb_root *blocks)
3102 {
3103 	struct extent_buffer *eb;
3104 	struct btrfs_extent_item *ei;
3105 	struct btrfs_tree_block_info *bi;
3106 	struct tree_block *block;
3107 	struct rb_node *rb_node;
3108 	u32 item_size;
3109 	int level = -1;
3110 	u64 generation;
3111 	u64 owner = 0;
3112 
3113 	eb =  path->nodes[0];
3114 	item_size = btrfs_item_size(eb, path->slots[0]);
3115 
3116 	if (extent_key->type == BTRFS_METADATA_ITEM_KEY ||
3117 	    item_size >= sizeof(*ei) + sizeof(*bi)) {
3118 		unsigned long ptr = 0, end;
3119 
3120 		ei = btrfs_item_ptr(eb, path->slots[0],
3121 				struct btrfs_extent_item);
3122 		end = (unsigned long)ei + item_size;
3123 		if (extent_key->type == BTRFS_EXTENT_ITEM_KEY) {
3124 			bi = (struct btrfs_tree_block_info *)(ei + 1);
3125 			level = btrfs_tree_block_level(eb, bi);
3126 			ptr = (unsigned long)(bi + 1);
3127 		} else {
3128 			level = (int)extent_key->offset;
3129 			ptr = (unsigned long)(ei + 1);
3130 		}
3131 		generation = btrfs_extent_generation(eb, ei);
3132 
3133 		/*
3134 		 * We're reading random blocks without knowing their owner ahead
3135 		 * of time.  This is ok most of the time, as all reloc roots and
3136 		 * fs roots have the same lock type.  However normal trees do
3137 		 * not, and the only way to know ahead of time is to read the
3138 		 * inline ref offset.  We know it's an fs root if
3139 		 *
3140 		 * 1. There's more than one ref.
3141 		 * 2. There's a SHARED_DATA_REF_KEY set.
3142 		 * 3. FULL_BACKREF is set on the flags.
3143 		 *
3144 		 * Otherwise it's safe to assume that the ref offset == the
3145 		 * owner of this block, so we can use that when calling
3146 		 * read_tree_block.
3147 		 */
3148 		if (btrfs_extent_refs(eb, ei) == 1 &&
3149 		    !(btrfs_extent_flags(eb, ei) &
3150 		      BTRFS_BLOCK_FLAG_FULL_BACKREF) &&
3151 		    ptr < end) {
3152 			struct btrfs_extent_inline_ref *iref;
3153 			int type;
3154 
3155 			iref = (struct btrfs_extent_inline_ref *)ptr;
3156 			type = btrfs_get_extent_inline_ref_type(eb, iref,
3157 							BTRFS_REF_TYPE_BLOCK);
3158 			if (type == BTRFS_REF_TYPE_INVALID)
3159 				return -EINVAL;
3160 			if (type == BTRFS_TREE_BLOCK_REF_KEY)
3161 				owner = btrfs_extent_inline_ref_offset(eb, iref);
3162 		}
3163 	} else {
3164 		btrfs_print_leaf(eb);
3165 		btrfs_err(rc->block_group->fs_info,
3166 			  "unrecognized tree backref at tree block %llu slot %u",
3167 			  eb->start, path->slots[0]);
3168 		btrfs_release_path(path);
3169 		return -EUCLEAN;
3170 	}
3171 
3172 	btrfs_release_path(path);
3173 
3174 	BUG_ON(level == -1);
3175 
3176 	block = kmalloc_obj(*block, GFP_NOFS);
3177 	if (!block)
3178 		return -ENOMEM;
3179 
3180 	block->bytenr = extent_key->objectid;
3181 	block->key.objectid = rc->extent_root->fs_info->nodesize;
3182 	block->key.offset = generation;
3183 	block->level = level;
3184 	block->key_ready = false;
3185 	block->owner = owner;
3186 
3187 	rb_node = rb_simple_insert(blocks, &block->simple_node);
3188 	if (rb_node)
3189 		btrfs_backref_panic(rc->extent_root->fs_info, block->bytenr,
3190 				    -EEXIST);
3191 
3192 	return 0;
3193 }
3194 
3195 /*
3196  * helper to add tree blocks for backref of type BTRFS_SHARED_DATA_REF_KEY
3197  */
3198 static int __add_tree_block(struct reloc_control *rc,
3199 			    u64 bytenr, u32 blocksize,
3200 			    struct rb_root *blocks)
3201 {
3202 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3203 	BTRFS_PATH_AUTO_FREE(path);
3204 	struct btrfs_key key;
3205 	int ret;
3206 	bool skinny = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
3207 
3208 	if (tree_block_processed(bytenr, rc))
3209 		return 0;
3210 
3211 	if (rb_simple_search(blocks, bytenr))
3212 		return 0;
3213 
3214 	path = btrfs_alloc_path();
3215 	if (!path)
3216 		return -ENOMEM;
3217 again:
3218 	key.objectid = bytenr;
3219 	if (skinny) {
3220 		key.type = BTRFS_METADATA_ITEM_KEY;
3221 		key.offset = (u64)-1;
3222 	} else {
3223 		key.type = BTRFS_EXTENT_ITEM_KEY;
3224 		key.offset = blocksize;
3225 	}
3226 
3227 	path->search_commit_root = true;
3228 	path->skip_locking = true;
3229 	ret = btrfs_search_slot(NULL, rc->extent_root, &key, path, 0, 0);
3230 	if (ret < 0)
3231 		return ret;
3232 
3233 	if (ret > 0 && skinny) {
3234 		if (path->slots[0]) {
3235 			path->slots[0]--;
3236 			btrfs_item_key_to_cpu(path->nodes[0], &key,
3237 					      path->slots[0]);
3238 			if (key.objectid == bytenr &&
3239 			    (key.type == BTRFS_METADATA_ITEM_KEY ||
3240 			     (key.type == BTRFS_EXTENT_ITEM_KEY &&
3241 			      key.offset == blocksize)))
3242 				ret = 0;
3243 		}
3244 
3245 		if (ret) {
3246 			skinny = false;
3247 			btrfs_release_path(path);
3248 			goto again;
3249 		}
3250 	}
3251 	if (WARN_ON(ret)) {
3252 		ASSERT(ret == 1);
3253 		btrfs_print_leaf(path->nodes[0]);
3254 		btrfs_err(fs_info,
3255 	     "tree block extent item (%llu) is not found in extent tree",
3256 		     bytenr);
3257 		return -EINVAL;
3258 	}
3259 
3260 	return add_tree_block(rc, &key, path, blocks);
3261 }
3262 
3263 static int delete_block_group_cache(struct btrfs_block_group *block_group,
3264 				    struct inode *inode,
3265 				    u64 ino)
3266 {
3267 	struct btrfs_fs_info *fs_info = block_group->fs_info;
3268 	struct btrfs_root *root = fs_info->tree_root;
3269 	struct btrfs_trans_handle *trans;
3270 	struct btrfs_inode *btrfs_inode;
3271 	int ret = 0;
3272 
3273 	if (inode)
3274 		goto truncate;
3275 
3276 	btrfs_inode = btrfs_iget(ino, root);
3277 	if (IS_ERR(btrfs_inode))
3278 		return -ENOENT;
3279 	inode = &btrfs_inode->vfs_inode;
3280 
3281 truncate:
3282 	ret = btrfs_check_trunc_cache_free_space(fs_info,
3283 						 &fs_info->global_block_rsv);
3284 	if (ret)
3285 		goto out;
3286 
3287 	trans = btrfs_join_transaction(root);
3288 	if (IS_ERR(trans)) {
3289 		ret = PTR_ERR(trans);
3290 		goto out;
3291 	}
3292 
3293 	ret = btrfs_truncate_free_space_cache(trans, block_group, inode);
3294 
3295 	btrfs_end_transaction(trans);
3296 	btrfs_btree_balance_dirty(fs_info);
3297 out:
3298 	iput(inode);
3299 	return ret;
3300 }
3301 
3302 /*
3303  * Locate the free space cache EXTENT_DATA in root tree leaf and delete the
3304  * cache inode, to avoid free space cache data extent blocking data relocation.
3305  */
3306 static int delete_v1_space_cache(struct extent_buffer *leaf,
3307 				 struct btrfs_block_group *block_group,
3308 				 u64 data_bytenr)
3309 {
3310 	u64 space_cache_ino;
3311 	struct btrfs_file_extent_item *ei;
3312 	struct btrfs_key key;
3313 	bool found = false;
3314 	int i;
3315 
3316 	if (btrfs_header_owner(leaf) != BTRFS_ROOT_TREE_OBJECTID)
3317 		return 0;
3318 
3319 	for (i = 0; i < btrfs_header_nritems(leaf); i++) {
3320 		u8 type;
3321 
3322 		btrfs_item_key_to_cpu(leaf, &key, i);
3323 		if (key.type != BTRFS_EXTENT_DATA_KEY)
3324 			continue;
3325 		ei = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
3326 		type = btrfs_file_extent_type(leaf, ei);
3327 
3328 		if ((type == BTRFS_FILE_EXTENT_REG ||
3329 		     type == BTRFS_FILE_EXTENT_PREALLOC) &&
3330 		    btrfs_file_extent_disk_bytenr(leaf, ei) == data_bytenr) {
3331 			found = true;
3332 			space_cache_ino = key.objectid;
3333 			break;
3334 		}
3335 	}
3336 	if (!found)
3337 		return -ENOENT;
3338 
3339 	return delete_block_group_cache(block_group, NULL, space_cache_ino);
3340 }
3341 
3342 /*
3343  * helper to find all tree blocks that reference a given data extent
3344  */
3345 static noinline_for_stack int add_data_references(struct reloc_control *rc,
3346 						  const struct btrfs_key *extent_key,
3347 						  struct btrfs_path *path,
3348 						  struct rb_root *blocks)
3349 {
3350 	struct btrfs_backref_walk_ctx ctx = { 0 };
3351 	struct ulist_iterator leaf_uiter;
3352 	struct ulist_node *ref_node = NULL;
3353 	const u32 blocksize = rc->extent_root->fs_info->nodesize;
3354 	int ret = 0;
3355 
3356 	btrfs_release_path(path);
3357 
3358 	ctx.bytenr = extent_key->objectid;
3359 	ctx.skip_inode_ref_list = true;
3360 	ctx.fs_info = rc->extent_root->fs_info;
3361 
3362 	ret = btrfs_find_all_leafs(&ctx);
3363 	if (ret < 0)
3364 		return ret;
3365 
3366 	ULIST_ITER_INIT(&leaf_uiter);
3367 	while ((ref_node = ulist_next(ctx.refs, &leaf_uiter))) {
3368 		struct btrfs_tree_parent_check check = { 0 };
3369 		struct extent_buffer *eb;
3370 
3371 		eb = read_tree_block(ctx.fs_info, ref_node->val, &check);
3372 		if (IS_ERR(eb)) {
3373 			ret = PTR_ERR(eb);
3374 			break;
3375 		}
3376 		ret = delete_v1_space_cache(eb, rc->block_group,
3377 					    extent_key->objectid);
3378 		free_extent_buffer(eb);
3379 		if (ret < 0)
3380 			break;
3381 		ret = __add_tree_block(rc, ref_node->val, blocksize, blocks);
3382 		if (ret < 0)
3383 			break;
3384 	}
3385 	if (ret < 0)
3386 		free_block_list(blocks);
3387 	ulist_free(ctx.refs);
3388 	return ret;
3389 }
3390 
3391 /*
3392  * helper to find next unprocessed extent
3393  */
3394 static noinline_for_stack
3395 int find_next_extent(struct reloc_control *rc, struct btrfs_path *path,
3396 		     struct btrfs_key *extent_key)
3397 {
3398 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3399 	struct btrfs_key key;
3400 	struct extent_buffer *leaf;
3401 	u64 start, end, last;
3402 	int ret;
3403 
3404 	last = rc->block_group->start + rc->block_group->length;
3405 	while (1) {
3406 		bool block_found;
3407 
3408 		cond_resched();
3409 		if (rc->search_start >= last) {
3410 			ret = 1;
3411 			break;
3412 		}
3413 
3414 		key.objectid = rc->search_start;
3415 		key.type = BTRFS_EXTENT_ITEM_KEY;
3416 		key.offset = 0;
3417 
3418 		path->search_commit_root = true;
3419 		path->skip_locking = true;
3420 		ret = btrfs_search_slot(NULL, rc->extent_root, &key, path,
3421 					0, 0);
3422 		if (ret < 0)
3423 			break;
3424 next:
3425 		leaf = path->nodes[0];
3426 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
3427 			ret = btrfs_next_leaf(rc->extent_root, path);
3428 			if (ret != 0)
3429 				break;
3430 			leaf = path->nodes[0];
3431 		}
3432 
3433 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3434 		if (key.objectid >= last) {
3435 			ret = 1;
3436 			break;
3437 		}
3438 
3439 		if (key.type != BTRFS_EXTENT_ITEM_KEY &&
3440 		    key.type != BTRFS_METADATA_ITEM_KEY) {
3441 			path->slots[0]++;
3442 			goto next;
3443 		}
3444 
3445 		if (key.type == BTRFS_EXTENT_ITEM_KEY &&
3446 		    key.objectid + key.offset <= rc->search_start) {
3447 			path->slots[0]++;
3448 			goto next;
3449 		}
3450 
3451 		if (key.type == BTRFS_METADATA_ITEM_KEY &&
3452 		    key.objectid + fs_info->nodesize <=
3453 		    rc->search_start) {
3454 			path->slots[0]++;
3455 			goto next;
3456 		}
3457 
3458 		block_found = btrfs_find_first_extent_bit(&rc->processed_blocks,
3459 							  key.objectid, &start, &end,
3460 							  EXTENT_DIRTY, NULL);
3461 
3462 		if (block_found && start <= key.objectid) {
3463 			btrfs_release_path(path);
3464 			rc->search_start = end + 1;
3465 		} else {
3466 			if (key.type == BTRFS_EXTENT_ITEM_KEY)
3467 				rc->search_start = key.objectid + key.offset;
3468 			else
3469 				rc->search_start = key.objectid +
3470 					fs_info->nodesize;
3471 			memcpy(extent_key, &key, sizeof(key));
3472 			return 0;
3473 		}
3474 	}
3475 	btrfs_release_path(path);
3476 	return ret;
3477 }
3478 
3479 static void set_reloc_control(struct reloc_control *rc)
3480 {
3481 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3482 
3483 	mutex_lock(&fs_info->reloc_mutex);
3484 	spin_lock(&fs_info->reloc_ctl_lock);
3485 	fs_info->reloc_ctl = rc;
3486 	spin_unlock(&fs_info->reloc_ctl_lock);
3487 	mutex_unlock(&fs_info->reloc_mutex);
3488 }
3489 
3490 static void unset_reloc_control(struct reloc_control *rc)
3491 {
3492 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3493 
3494 	mutex_lock(&fs_info->reloc_mutex);
3495 	spin_lock(&fs_info->reloc_ctl_lock);
3496 	fs_info->reloc_ctl = NULL;
3497 	spin_unlock(&fs_info->reloc_ctl_lock);
3498 	mutex_unlock(&fs_info->reloc_mutex);
3499 }
3500 
3501 static noinline_for_stack
3502 int prepare_to_relocate(struct reloc_control *rc)
3503 {
3504 	struct btrfs_trans_handle *trans;
3505 	int ret;
3506 
3507 	rc->block_rsv = btrfs_alloc_block_rsv(rc->extent_root->fs_info,
3508 					      BTRFS_BLOCK_RSV_TEMP);
3509 	if (!rc->block_rsv)
3510 		return -ENOMEM;
3511 
3512 	memset(&rc->cluster, 0, sizeof(rc->cluster));
3513 	rc->search_start = rc->block_group->start;
3514 	rc->extents_found = 0;
3515 	rc->nodes_relocated = 0;
3516 	rc->merging_rsv_size = 0;
3517 	rc->reserved_bytes = 0;
3518 	rc->block_rsv->size = rc->extent_root->fs_info->nodesize *
3519 			      RELOCATION_RESERVED_NODES;
3520 	ret = btrfs_block_rsv_refill(rc->extent_root->fs_info,
3521 				     rc->block_rsv, rc->block_rsv->size,
3522 				     BTRFS_RESERVE_FLUSH_ALL);
3523 	if (ret)
3524 		return ret;
3525 
3526 	rc->create_reloc_tree = true;
3527 	set_reloc_control(rc);
3528 
3529 	trans = btrfs_join_transaction(rc->extent_root);
3530 	if (IS_ERR(trans)) {
3531 		unset_reloc_control(rc);
3532 		/*
3533 		 * extent tree is not a ref_cow tree and has no reloc_root to
3534 		 * cleanup.  And callers are responsible to free the above
3535 		 * block rsv.
3536 		 */
3537 		return PTR_ERR(trans);
3538 	}
3539 
3540 	ret = btrfs_commit_transaction(trans);
3541 	if (ret)
3542 		unset_reloc_control(rc);
3543 
3544 	return ret;
3545 }
3546 
3547 static noinline_for_stack int relocate_block_group(struct reloc_control *rc)
3548 {
3549 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3550 	struct rb_root blocks = RB_ROOT;
3551 	struct btrfs_key key;
3552 	struct btrfs_trans_handle *trans = NULL;
3553 	BTRFS_PATH_AUTO_FREE(path);
3554 	struct btrfs_extent_item *ei;
3555 	u64 flags;
3556 	int ret;
3557 	int err = 0;
3558 	int progress = 0;
3559 
3560 	path = btrfs_alloc_path();
3561 	if (!path)
3562 		return -ENOMEM;
3563 	path->reada = READA_FORWARD;
3564 
3565 	ret = prepare_to_relocate(rc);
3566 	if (ret) {
3567 		err = ret;
3568 		goto out_free;
3569 	}
3570 
3571 	while (1) {
3572 		rc->reserved_bytes = 0;
3573 		ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv,
3574 					     rc->block_rsv->size,
3575 					     BTRFS_RESERVE_FLUSH_ALL);
3576 		if (ret) {
3577 			err = ret;
3578 			break;
3579 		}
3580 		progress++;
3581 		trans = btrfs_start_transaction(rc->extent_root, 0);
3582 		if (IS_ERR(trans)) {
3583 			err = PTR_ERR(trans);
3584 			trans = NULL;
3585 			break;
3586 		}
3587 restart:
3588 		if (rc->backref_cache.last_trans != trans->transid)
3589 			btrfs_backref_release_cache(&rc->backref_cache);
3590 		rc->backref_cache.last_trans = trans->transid;
3591 
3592 		ret = find_next_extent(rc, path, &key);
3593 		if (ret < 0)
3594 			err = ret;
3595 		if (ret != 0)
3596 			break;
3597 
3598 		rc->extents_found++;
3599 
3600 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3601 				    struct btrfs_extent_item);
3602 		flags = btrfs_extent_flags(path->nodes[0], ei);
3603 
3604 		/*
3605 		 * If we are relocating a simple quota owned extent item, we
3606 		 * need to note the owner on the reloc data root so that when
3607 		 * we allocate the replacement item, we can attribute it to the
3608 		 * correct eventual owner (rather than the reloc data root).
3609 		 */
3610 		if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE) {
3611 			struct btrfs_root *root = BTRFS_I(rc->data_inode)->root;
3612 			u64 owning_root_id = btrfs_get_extent_owner_root(fs_info,
3613 								 path->nodes[0],
3614 								 path->slots[0]);
3615 
3616 			root->relocation_src_root = owning_root_id;
3617 		}
3618 
3619 		if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
3620 			ret = add_tree_block(rc, &key, path, &blocks);
3621 		} else if (rc->stage == UPDATE_DATA_PTRS &&
3622 			   (flags & BTRFS_EXTENT_FLAG_DATA)) {
3623 			ret = add_data_references(rc, &key, path, &blocks);
3624 		} else {
3625 			btrfs_release_path(path);
3626 			ret = 0;
3627 		}
3628 		if (ret < 0) {
3629 			err = ret;
3630 			break;
3631 		}
3632 
3633 		if (!RB_EMPTY_ROOT(&blocks)) {
3634 			ret = relocate_tree_blocks(trans, rc, &blocks);
3635 			if (ret < 0) {
3636 				if (ret != -EAGAIN) {
3637 					err = ret;
3638 					break;
3639 				}
3640 				rc->extents_found--;
3641 				rc->search_start = key.objectid;
3642 			}
3643 		}
3644 
3645 		btrfs_end_transaction_throttle(trans);
3646 		btrfs_btree_balance_dirty(fs_info);
3647 		trans = NULL;
3648 
3649 		if (rc->stage == MOVE_DATA_EXTENTS &&
3650 		    (flags & BTRFS_EXTENT_FLAG_DATA)) {
3651 			rc->found_file_extent = true;
3652 			ret = relocate_data_extent(rc, &key);
3653 			if (ret < 0) {
3654 				err = ret;
3655 				break;
3656 			}
3657 		}
3658 		if (btrfs_should_cancel_balance(fs_info)) {
3659 			err = -ECANCELED;
3660 			break;
3661 		}
3662 	}
3663 	if (trans && progress && err == -ENOSPC) {
3664 		ret = btrfs_force_chunk_alloc(trans, rc->block_group->flags);
3665 		if (ret == 1) {
3666 			err = 0;
3667 			progress = 0;
3668 			goto restart;
3669 		}
3670 	}
3671 
3672 	btrfs_release_path(path);
3673 	btrfs_clear_extent_bit(&rc->processed_blocks, 0, (u64)-1, EXTENT_DIRTY, NULL);
3674 
3675 	if (trans) {
3676 		btrfs_end_transaction_throttle(trans);
3677 		btrfs_btree_balance_dirty(fs_info);
3678 	}
3679 
3680 	if (!err && !btrfs_fs_incompat(fs_info, REMAP_TREE)) {
3681 		ret = relocate_file_extent_cluster(rc);
3682 		if (ret < 0)
3683 			err = ret;
3684 	}
3685 
3686 	rc->create_reloc_tree = false;
3687 	set_reloc_control(rc);
3688 
3689 	btrfs_backref_release_cache(&rc->backref_cache);
3690 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
3691 
3692 	/*
3693 	 * Even in the case when the relocation is cancelled, we should all go
3694 	 * through prepare_to_merge() and merge_reloc_roots().
3695 	 *
3696 	 * For error (including cancelled balance), prepare_to_merge() will
3697 	 * mark all reloc trees orphan, then queue them for cleanup in
3698 	 * merge_reloc_roots()
3699 	 */
3700 	err = prepare_to_merge(rc, err);
3701 
3702 	merge_reloc_roots(rc);
3703 
3704 	rc->merge_reloc_tree = false;
3705 	unset_reloc_control(rc);
3706 	btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
3707 
3708 	/* get rid of pinned extents */
3709 	ret = btrfs_commit_current_transaction(rc->extent_root);
3710 	if (ret && !err)
3711 		err = ret;
3712 out_free:
3713 	ret = clean_dirty_subvols(rc);
3714 	if (ret < 0 && !err)
3715 		err = ret;
3716 	btrfs_free_block_rsv(fs_info, rc->block_rsv);
3717 	return err;
3718 }
3719 
3720 static int __insert_orphan_inode(struct btrfs_trans_handle *trans,
3721 				 struct btrfs_root *root, u64 objectid)
3722 {
3723 	BTRFS_PATH_AUTO_FREE(path);
3724 	struct btrfs_inode_item *item;
3725 	struct extent_buffer *leaf;
3726 	int ret;
3727 
3728 	path = btrfs_alloc_path();
3729 	if (!path)
3730 		return -ENOMEM;
3731 
3732 	ret = btrfs_insert_empty_inode(trans, root, path, objectid);
3733 	if (ret)
3734 		return ret;
3735 
3736 	leaf = path->nodes[0];
3737 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item);
3738 	memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3739 	btrfs_set_inode_generation(leaf, item, 1);
3740 	btrfs_set_inode_size(leaf, item, 0);
3741 	btrfs_set_inode_mode(leaf, item, S_IFREG | 0600);
3742 	btrfs_set_inode_flags(leaf, item, BTRFS_INODE_NOCOMPRESS |
3743 					  BTRFS_INODE_PREALLOC);
3744 	return 0;
3745 }
3746 
3747 static void delete_orphan_inode(struct btrfs_trans_handle *trans,
3748 				struct btrfs_root *root, u64 objectid)
3749 {
3750 	BTRFS_PATH_AUTO_FREE(path);
3751 	struct btrfs_key key;
3752 	int ret = 0;
3753 
3754 	path = btrfs_alloc_path();
3755 	if (!path) {
3756 		ret = -ENOMEM;
3757 		goto out;
3758 	}
3759 
3760 	key.objectid = objectid;
3761 	key.type = BTRFS_INODE_ITEM_KEY;
3762 	key.offset = 0;
3763 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3764 	if (ret) {
3765 		if (ret > 0)
3766 			ret = -ENOENT;
3767 		goto out;
3768 	}
3769 	ret = btrfs_del_item(trans, root, path);
3770 out:
3771 	if (ret)
3772 		btrfs_abort_transaction(trans, ret);
3773 }
3774 
3775 /*
3776  * helper to create inode for data relocation.
3777  * the inode is in data relocation tree and its link count is 0
3778  */
3779 static noinline_for_stack struct inode *create_reloc_inode(
3780 					const struct btrfs_block_group *group)
3781 {
3782 	struct btrfs_fs_info *fs_info = group->fs_info;
3783 	struct btrfs_inode *inode = NULL;
3784 	struct btrfs_trans_handle *trans;
3785 	struct btrfs_root *root;
3786 	u64 objectid;
3787 	int ret = 0;
3788 
3789 	root = btrfs_grab_root(fs_info->data_reloc_root);
3790 	trans = btrfs_start_transaction(root, 6);
3791 	if (IS_ERR(trans)) {
3792 		btrfs_put_root(root);
3793 		return ERR_CAST(trans);
3794 	}
3795 
3796 	ret = btrfs_get_free_objectid(root, &objectid);
3797 	if (ret)
3798 		goto out;
3799 
3800 	ret = __insert_orphan_inode(trans, root, objectid);
3801 	if (ret)
3802 		goto out;
3803 
3804 	inode = btrfs_iget(objectid, root);
3805 	if (IS_ERR(inode)) {
3806 		delete_orphan_inode(trans, root, objectid);
3807 		ret = PTR_ERR(inode);
3808 		inode = NULL;
3809 		goto out;
3810 	}
3811 	inode->reloc_block_group_start = group->start;
3812 
3813 	ret = btrfs_orphan_add(trans, inode);
3814 out:
3815 	btrfs_put_root(root);
3816 	btrfs_end_transaction(trans);
3817 	btrfs_btree_balance_dirty(fs_info);
3818 	if (ret) {
3819 		if (inode)
3820 			iput(&inode->vfs_inode);
3821 		return ERR_PTR(ret);
3822 	}
3823 	return &inode->vfs_inode;
3824 }
3825 
3826 /*
3827  * Mark start of chunk relocation that is cancellable. Check if the cancellation
3828  * has been requested meanwhile and don't start in that case.
3829  * NOTE: if this returns an error, reloc_chunk_end() must not be called.
3830  *
3831  * Return:
3832  *   0             success
3833  *   -EINPROGRESS  operation is already in progress, that's probably a bug
3834  *   -ECANCELED    cancellation request was set before the operation started
3835  */
3836 static int reloc_chunk_start(struct btrfs_fs_info *fs_info)
3837 {
3838 	if (test_and_set_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags)) {
3839 		/* This should not happen */
3840 		btrfs_err(fs_info, "reloc already running, cannot start");
3841 		return -EINPROGRESS;
3842 	}
3843 
3844 	if (atomic_read(&fs_info->reloc_cancel_req) > 0) {
3845 		btrfs_info(fs_info, "chunk relocation canceled on start");
3846 		/* On cancel, clear all requests. */
3847 		clear_and_wake_up_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags);
3848 		atomic_set(&fs_info->reloc_cancel_req, 0);
3849 		return -ECANCELED;
3850 	}
3851 	return 0;
3852 }
3853 
3854 /*
3855  * Mark end of chunk relocation that is cancellable and wake any waiters.
3856  * NOTE: call only if a previous call to reloc_chunk_start() succeeded.
3857  */
3858 static void reloc_chunk_end(struct btrfs_fs_info *fs_info)
3859 {
3860 	ASSERT(test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags));
3861 	/* Requested after start, clear bit first so any waiters can continue */
3862 	if (atomic_read(&fs_info->reloc_cancel_req) > 0)
3863 		btrfs_info(fs_info, "chunk relocation canceled during operation");
3864 	clear_and_wake_up_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags);
3865 	atomic_set(&fs_info->reloc_cancel_req, 0);
3866 }
3867 
3868 static struct reloc_control *alloc_reloc_control(struct btrfs_fs_info *fs_info)
3869 {
3870 	struct reloc_control *rc;
3871 
3872 	rc = kzalloc_obj(*rc, GFP_NOFS);
3873 	if (!rc)
3874 		return NULL;
3875 
3876 	INIT_LIST_HEAD(&rc->reloc_roots);
3877 	INIT_LIST_HEAD(&rc->dirty_subvol_roots);
3878 	btrfs_backref_init_cache(fs_info, &rc->backref_cache, true);
3879 	rc->reloc_root_tree.rb_root = RB_ROOT;
3880 	spin_lock_init(&rc->reloc_root_tree.lock);
3881 	btrfs_extent_io_tree_init(fs_info, &rc->processed_blocks, IO_TREE_RELOC_BLOCKS);
3882 	refcount_set(&rc->refs, 1);
3883 
3884 	return rc;
3885 }
3886 
3887 /*
3888  * Print the block group being relocated
3889  */
3890 static void describe_relocation(struct btrfs_block_group *block_group)
3891 {
3892 	char buf[128] = "NONE";
3893 
3894 	btrfs_describe_block_groups(block_group->flags, buf, sizeof(buf));
3895 
3896 	btrfs_info(block_group->fs_info, "relocating block group %llu flags %s",
3897 		   block_group->start, buf);
3898 }
3899 
3900 static const char *stage_to_string(enum reloc_stage stage)
3901 {
3902 	if (stage == MOVE_DATA_EXTENTS)
3903 		return "move data extents";
3904 	if (stage == UPDATE_DATA_PTRS)
3905 		return "update data pointers";
3906 	return "unknown";
3907 }
3908 
3909 static int add_remap_tree_entries(struct btrfs_trans_handle *trans, struct btrfs_path *path,
3910 				  struct btrfs_key *entries, unsigned int num_entries)
3911 {
3912 	int ret;
3913 	struct btrfs_fs_info *fs_info = trans->fs_info;
3914 	struct btrfs_item_batch batch;
3915 	u32 *data_sizes;
3916 	u32 max_items;
3917 
3918 	max_items = BTRFS_LEAF_DATA_SIZE(trans->fs_info) / sizeof(struct btrfs_item);
3919 
3920 	data_sizes = kzalloc_objs(u32, min_t(u32, num_entries, max_items), GFP_NOFS);
3921 	if (!data_sizes)
3922 		return -ENOMEM;
3923 
3924 	while (true) {
3925 		batch.keys = entries;
3926 		batch.data_sizes = data_sizes;
3927 		batch.total_data_size = 0;
3928 		batch.nr = min_t(u32, num_entries, max_items);
3929 
3930 		ret = btrfs_insert_empty_items(trans, fs_info->remap_root, path, &batch);
3931 		btrfs_release_path(path);
3932 
3933 		if (ret || num_entries <= max_items)
3934 			break;
3935 
3936 		num_entries -= max_items;
3937 		entries += max_items;
3938 	}
3939 
3940 	kfree(data_sizes);
3941 
3942 	return ret;
3943 }
3944 
3945 struct space_run {
3946 	u64 start;
3947 	u64 end;
3948 };
3949 
3950 static void parse_bitmap(u64 block_size, const unsigned long *bitmap,
3951 			 unsigned long size, u64 address, struct space_run *space_runs,
3952 			 unsigned int *num_space_runs)
3953 {
3954 	unsigned long pos, end;
3955 	u64 run_start, run_length;
3956 
3957 	pos = find_first_bit(bitmap, size);
3958 	if (pos == size)
3959 		return;
3960 
3961 	while (true) {
3962 		end = find_next_zero_bit(bitmap, size, pos);
3963 
3964 		run_start = address + (pos * block_size);
3965 		run_length = (end - pos) * block_size;
3966 
3967 		if (*num_space_runs != 0 &&
3968 		    space_runs[*num_space_runs - 1].end == run_start) {
3969 			space_runs[*num_space_runs - 1].end += run_length;
3970 		} else {
3971 			space_runs[*num_space_runs].start = run_start;
3972 			space_runs[*num_space_runs].end = run_start + run_length;
3973 
3974 			(*num_space_runs)++;
3975 		}
3976 
3977 		if (end == size)
3978 			break;
3979 
3980 		pos = find_next_bit(bitmap, size, end + 1);
3981 		if (pos == size)
3982 			break;
3983 	}
3984 }
3985 
3986 static void adjust_block_group_remap_bytes(struct btrfs_trans_handle *trans,
3987 					   struct btrfs_block_group *bg, s64 diff)
3988 {
3989 	struct btrfs_fs_info *fs_info = trans->fs_info;
3990 	bool bg_already_dirty = true;
3991 	bool mark_unused = false;
3992 
3993 	spin_lock(&bg->lock);
3994 	bg->remap_bytes += diff;
3995 	if (bg->used == 0 && bg->remap_bytes == 0)
3996 		mark_unused = true;
3997 	spin_unlock(&bg->lock);
3998 
3999 	if (mark_unused)
4000 		btrfs_mark_bg_unused(bg);
4001 
4002 	spin_lock(&trans->transaction->dirty_bgs_lock);
4003 	if (list_empty(&bg->dirty_list)) {
4004 		list_add_tail(&bg->dirty_list, &trans->transaction->dirty_bgs);
4005 		bg_already_dirty = false;
4006 		btrfs_get_block_group(bg);
4007 	}
4008 	spin_unlock(&trans->transaction->dirty_bgs_lock);
4009 
4010 	/* Modified block groups are accounted for in the delayed_refs_rsv. */
4011 	if (!bg_already_dirty)
4012 		btrfs_inc_delayed_refs_rsv_bg_updates(fs_info);
4013 }
4014 
4015 /* Private structure for I/O from copy_remapped_data().  */
4016 struct reloc_io_private {
4017 	struct completion done;
4018 	refcount_t pending_refs;
4019 	blk_status_t status;
4020 };
4021 
4022 static void reloc_endio(struct btrfs_bio *bbio)
4023 {
4024 	struct reloc_io_private *priv = bbio->private;
4025 
4026 	if (bbio->bio.bi_status)
4027 		WRITE_ONCE(priv->status, bbio->bio.bi_status);
4028 
4029 	if (refcount_dec_and_test(&priv->pending_refs))
4030 		complete(&priv->done);
4031 
4032 	bio_put(&bbio->bio);
4033 }
4034 
4035 static int copy_remapped_data_io(struct btrfs_fs_info *fs_info,
4036 				 struct reloc_io_private *priv,
4037 				 struct page **pages, u64 addr, u64 length,
4038 				 blk_opf_t op)
4039 {
4040 	struct btrfs_bio *bbio;
4041 	int i;
4042 
4043 	init_completion(&priv->done);
4044 	refcount_set(&priv->pending_refs, 1);
4045 	priv->status = 0;
4046 
4047 	bbio = btrfs_bio_alloc(BIO_MAX_VECS, op, BTRFS_I(fs_info->btree_inode),
4048 			       addr, reloc_endio, priv);
4049 	bbio->bio.bi_iter.bi_sector = (addr >> SECTOR_SHIFT);
4050 	bbio->is_remap = true;
4051 
4052 	i = 0;
4053 	do {
4054 		size_t bytes = min_t(u64, length, PAGE_SIZE);
4055 
4056 		if (bio_add_page(&bbio->bio, pages[i], bytes, 0) < bytes) {
4057 			refcount_inc(&priv->pending_refs);
4058 			btrfs_submit_bbio(bbio, 0);
4059 
4060 			bbio = btrfs_bio_alloc(BIO_MAX_VECS, op,
4061 					       BTRFS_I(fs_info->btree_inode),
4062 					       addr, reloc_endio, priv);
4063 			bbio->bio.bi_iter.bi_sector = (addr >> SECTOR_SHIFT);
4064 			bbio->is_remap = true;
4065 			continue;
4066 		}
4067 
4068 		i++;
4069 		addr += bytes;
4070 		length -= bytes;
4071 	} while (length);
4072 
4073 	refcount_inc(&priv->pending_refs);
4074 	btrfs_submit_bbio(bbio, 0);
4075 
4076 	if (!refcount_dec_and_test(&priv->pending_refs))
4077 		wait_for_completion_io(&priv->done);
4078 
4079 	return blk_status_to_errno(READ_ONCE(priv->status));
4080 }
4081 
4082 static int copy_remapped_data(struct btrfs_fs_info *fs_info, u64 old_addr,
4083 			      u64 new_addr, u64 length)
4084 {
4085 	int ret;
4086 	u64 copy_len = min_t(u64, length, SZ_1M);
4087 	struct page **pages;
4088 	struct reloc_io_private priv;
4089 	unsigned int nr_pages = DIV_ROUND_UP(length, PAGE_SIZE);
4090 
4091 	pages = kzalloc_objs(struct page *, nr_pages, GFP_NOFS);
4092 	if (!pages)
4093 		return -ENOMEM;
4094 
4095 	ret = btrfs_alloc_page_array(nr_pages, pages, GFP_NOFS);
4096 	if (ret) {
4097 		ret = -ENOMEM;
4098 		goto end;
4099 	}
4100 
4101 	/* Copy 1MB at a time, to avoid using too much memory. */
4102 	do {
4103 		u64 to_copy = min_t(u64, length, copy_len);
4104 
4105 		/* Limit to one bio. */
4106 		to_copy = min_t(u64, to_copy, BIO_MAX_VECS << PAGE_SHIFT);
4107 
4108 		ret = copy_remapped_data_io(fs_info, &priv, pages, old_addr,
4109 					    to_copy, REQ_OP_READ);
4110 		if (ret)
4111 			goto end;
4112 
4113 		ret = copy_remapped_data_io(fs_info, &priv, pages, new_addr,
4114 					    to_copy, REQ_OP_WRITE);
4115 		if (ret)
4116 			goto end;
4117 
4118 		if (to_copy == length)
4119 			break;
4120 
4121 		old_addr += to_copy;
4122 		new_addr += to_copy;
4123 		length -= to_copy;
4124 	} while (true);
4125 
4126 	ret = 0;
4127 end:
4128 	for (int i = 0; i < nr_pages; i++) {
4129 		if (pages[i])
4130 			__free_page(pages[i]);
4131 	}
4132 	kfree(pages);
4133 
4134 	return ret;
4135 }
4136 
4137 static int add_remap_item(struct btrfs_trans_handle *trans,
4138 			  struct btrfs_path *path, u64 new_addr, u64 length,
4139 			  u64 old_addr)
4140 {
4141 	struct btrfs_fs_info *fs_info = trans->fs_info;
4142 	struct btrfs_remap_item remap = { 0 };
4143 	struct btrfs_key key;
4144 	struct extent_buffer *leaf;
4145 	int ret;
4146 
4147 	key.objectid = old_addr;
4148 	key.type = BTRFS_REMAP_KEY;
4149 	key.offset = length;
4150 
4151 	ret = btrfs_insert_empty_item(trans, fs_info->remap_root, path,
4152 				      &key, sizeof(struct btrfs_remap_item));
4153 	if (ret)
4154 		return ret;
4155 
4156 	leaf = path->nodes[0];
4157 	btrfs_set_stack_remap_address(&remap, new_addr);
4158 	write_extent_buffer(leaf, &remap, btrfs_item_ptr_offset(leaf, path->slots[0]),
4159 			    sizeof(struct btrfs_remap_item));
4160 
4161 	btrfs_release_path(path);
4162 
4163 	return 0;
4164 }
4165 
4166 static int add_remap_backref_item(struct btrfs_trans_handle *trans,
4167 				  struct btrfs_path *path, u64 new_addr,
4168 				  u64 length, u64 old_addr)
4169 {
4170 	struct btrfs_fs_info *fs_info = trans->fs_info;
4171 	struct btrfs_remap_item remap = { 0 };
4172 	struct btrfs_key key;
4173 	struct extent_buffer *leaf;
4174 	int ret;
4175 
4176 	key.objectid = new_addr;
4177 	key.type = BTRFS_REMAP_BACKREF_KEY;
4178 	key.offset = length;
4179 
4180 	ret = btrfs_insert_empty_item(trans, fs_info->remap_root, path, &key,
4181 				      sizeof(struct btrfs_remap_item));
4182 	if (ret)
4183 		return ret;
4184 
4185 	leaf = path->nodes[0];
4186 	btrfs_set_stack_remap_address(&remap, old_addr);
4187 	write_extent_buffer(leaf, &remap, btrfs_item_ptr_offset(leaf, path->slots[0]),
4188 			    sizeof(struct btrfs_remap_item));
4189 
4190 	btrfs_release_path(path);
4191 
4192 	return 0;
4193 }
4194 
4195 static int move_existing_remap(struct btrfs_fs_info *fs_info,
4196 			       struct btrfs_path *path,
4197 			       struct btrfs_block_group *bg, u64 new_addr,
4198 			       u64 length, u64 old_addr)
4199 {
4200 	struct btrfs_trans_handle *trans;
4201 	struct extent_buffer *leaf;
4202 	struct btrfs_remap_item *remap_ptr;
4203 	struct btrfs_remap_item remap = { 0 };
4204 	struct btrfs_key key, ins;
4205 	u64 dest_addr, dest_length, min_size;
4206 	struct btrfs_block_group *dest_bg;
4207 	int ret;
4208 	const bool is_data = (bg->flags & BTRFS_BLOCK_GROUP_DATA);
4209 	struct btrfs_space_info *sinfo = bg->space_info;
4210 	bool mutex_taken = false;
4211 	bool bg_needs_free_space;
4212 
4213 	spin_lock(&sinfo->lock);
4214 	btrfs_space_info_update_bytes_may_use(sinfo, length);
4215 	spin_unlock(&sinfo->lock);
4216 
4217 	if (is_data)
4218 		min_size = fs_info->sectorsize;
4219 	else
4220 		min_size = fs_info->nodesize;
4221 
4222 	ret = btrfs_reserve_extent(fs_info->fs_root, length, length, min_size,
4223 				   0, 0, &ins, is_data, false);
4224 	if (unlikely(ret)) {
4225 		spin_lock(&sinfo->lock);
4226 		btrfs_space_info_update_bytes_may_use(sinfo, -length);
4227 		spin_unlock(&sinfo->lock);
4228 		return ret;
4229 	}
4230 
4231 	if (ins.offset < length) {
4232 		spin_lock(&sinfo->lock);
4233 		btrfs_space_info_update_bytes_may_use(sinfo, ins.offset - length);
4234 		spin_unlock(&sinfo->lock);
4235 	}
4236 
4237 	dest_addr = ins.objectid;
4238 	dest_length = ins.offset;
4239 
4240 	dest_bg = btrfs_lookup_block_group(fs_info, dest_addr);
4241 
4242 	if (!is_data && !IS_ALIGNED(dest_length, fs_info->nodesize)) {
4243 		u64 new_length = ALIGN_DOWN(dest_length, fs_info->nodesize);
4244 
4245 		btrfs_free_reserved_extent(fs_info, dest_addr + new_length,
4246 					   dest_length - new_length, 0);
4247 
4248 		dest_length = new_length;
4249 	}
4250 
4251 	trans = btrfs_join_transaction(fs_info->remap_root);
4252 	if (IS_ERR(trans)) {
4253 		ret = PTR_ERR(trans);
4254 		trans = NULL;
4255 		goto end;
4256 	}
4257 
4258 	mutex_lock(&fs_info->remap_mutex);
4259 	mutex_taken = true;
4260 
4261 	/* Find old remap entry. */
4262 	key.objectid = old_addr;
4263 	key.type = BTRFS_REMAP_KEY;
4264 	key.offset = length;
4265 
4266 	ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, 0, 1);
4267 	if (ret == 1) {
4268 		/*
4269 		 * Not a problem if the remap entry wasn't found: that means
4270 		 * that another transaction has deallocated the data.
4271 		 * move_existing_remaps() loops until the BG contains no
4272 		 * remaps, so we can just return 0 in this case.
4273 		 */
4274 		btrfs_release_path(path);
4275 		ret = 0;
4276 		goto end;
4277 	} else if (unlikely(ret)) {
4278 		goto end;
4279 	}
4280 
4281 	ret = copy_remapped_data(fs_info, new_addr, dest_addr, dest_length);
4282 	if (unlikely(ret))
4283 		goto end;
4284 
4285 	/* Change data of old remap entry. */
4286 	leaf = path->nodes[0];
4287 	remap_ptr = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_remap_item);
4288 	btrfs_set_remap_address(leaf, remap_ptr, dest_addr);
4289 	btrfs_mark_buffer_dirty(trans, leaf);
4290 
4291 	if (dest_length != length) {
4292 		key.offset = dest_length;
4293 		btrfs_set_item_key_safe(trans, path, &key);
4294 	}
4295 
4296 	btrfs_release_path(path);
4297 
4298 	if (dest_length != length) {
4299 		/* Add remap item for remainder. */
4300 		ret = add_remap_item(trans, path, new_addr + dest_length,
4301 				     length - dest_length, old_addr + dest_length);
4302 		if (unlikely(ret))
4303 			goto end;
4304 	}
4305 
4306 	/* Change or remove old backref. */
4307 	key.objectid = new_addr;
4308 	key.type = BTRFS_REMAP_BACKREF_KEY;
4309 	key.offset = length;
4310 
4311 	ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, -1, 1);
4312 	if (unlikely(ret)) {
4313 		if (ret == 1) {
4314 			btrfs_release_path(path);
4315 			ret = -ENOENT;
4316 		}
4317 		goto end;
4318 	}
4319 
4320 	leaf = path->nodes[0];
4321 
4322 	if (dest_length == length) {
4323 		ret = btrfs_del_item(trans, fs_info->remap_root, path);
4324 		if (unlikely(ret)) {
4325 			btrfs_release_path(path);
4326 			goto end;
4327 		}
4328 	} else {
4329 		key.objectid += dest_length;
4330 		key.offset -= dest_length;
4331 		btrfs_set_item_key_safe(trans, path, &key);
4332 		btrfs_set_stack_remap_address(&remap, old_addr + dest_length);
4333 
4334 		write_extent_buffer(leaf, &remap,
4335 				    btrfs_item_ptr_offset(leaf, path->slots[0]),
4336 				    sizeof(struct btrfs_remap_item));
4337 	}
4338 
4339 	btrfs_release_path(path);
4340 
4341 	/* Add new backref. */
4342 	ret = add_remap_backref_item(trans, path, dest_addr, dest_length, old_addr);
4343 	if (unlikely(ret))
4344 		goto end;
4345 
4346 	adjust_block_group_remap_bytes(trans, bg, -dest_length);
4347 
4348 	ret = btrfs_add_to_free_space_tree(trans, new_addr, dest_length);
4349 	if (unlikely(ret))
4350 		goto end;
4351 
4352 	adjust_block_group_remap_bytes(trans, dest_bg, dest_length);
4353 
4354 	mutex_lock(&dest_bg->free_space_lock);
4355 	bg_needs_free_space = test_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE,
4356 				       &dest_bg->runtime_flags);
4357 	mutex_unlock(&dest_bg->free_space_lock);
4358 
4359 	if (bg_needs_free_space) {
4360 		ret = btrfs_add_block_group_free_space(trans, dest_bg);
4361 		if (unlikely(ret))
4362 			goto end;
4363 	}
4364 
4365 	ret = btrfs_remove_from_free_space_tree(trans, dest_addr, dest_length);
4366 	if (unlikely(ret)) {
4367 		btrfs_remove_from_free_space_tree(trans, new_addr, dest_length);
4368 		goto end;
4369 	}
4370 
4371 	ret = 0;
4372 
4373 end:
4374 	if (mutex_taken)
4375 		mutex_unlock(&fs_info->remap_mutex);
4376 
4377 	btrfs_dec_block_group_reservations(fs_info, dest_addr);
4378 
4379 	if (unlikely(ret)) {
4380 		btrfs_free_reserved_extent(fs_info, dest_addr, dest_length, 0);
4381 
4382 		if (trans) {
4383 			btrfs_abort_transaction(trans, ret);
4384 			btrfs_end_transaction(trans);
4385 		}
4386 	} else {
4387 		btrfs_free_reserved_bytes(dest_bg, dest_length, 0);
4388 
4389 		ret = btrfs_commit_transaction(trans);
4390 	}
4391 
4392 	btrfs_put_block_group(dest_bg);
4393 
4394 	return ret;
4395 }
4396 
4397 static int move_existing_remaps(struct btrfs_fs_info *fs_info,
4398 				struct btrfs_block_group *bg,
4399 				struct btrfs_path *path)
4400 {
4401 	int ret;
4402 	struct btrfs_key key;
4403 	struct extent_buffer *leaf;
4404 	struct btrfs_remap_item *remap;
4405 	u64 old_addr;
4406 
4407 	/* Look for backrefs in remap tree. */
4408 	while (bg->remap_bytes > 0) {
4409 		key.objectid = bg->start;
4410 		key.type = BTRFS_REMAP_BACKREF_KEY;
4411 		key.offset = 0;
4412 
4413 		ret = btrfs_search_slot(NULL, fs_info->remap_root, &key, path, 0, 0);
4414 		if (ret < 0)
4415 			return ret;
4416 
4417 		leaf = path->nodes[0];
4418 
4419 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4420 			ret = btrfs_next_leaf(fs_info->remap_root, path);
4421 			if (ret < 0) {
4422 				btrfs_release_path(path);
4423 				return ret;
4424 			}
4425 
4426 			if (ret) {
4427 				btrfs_release_path(path);
4428 				break;
4429 			}
4430 
4431 			leaf = path->nodes[0];
4432 		}
4433 
4434 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4435 
4436 		if (key.type != BTRFS_REMAP_BACKREF_KEY) {
4437 			path->slots[0]++;
4438 
4439 			if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4440 				ret = btrfs_next_leaf(fs_info->remap_root, path);
4441 				if (ret < 0) {
4442 					btrfs_release_path(path);
4443 					return ret;
4444 				}
4445 
4446 				if (ret) {
4447 					btrfs_release_path(path);
4448 					break;
4449 				}
4450 
4451 				leaf = path->nodes[0];
4452 			}
4453 
4454 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4455 		}
4456 
4457 		remap = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_remap_item);
4458 		old_addr = btrfs_remap_address(leaf, remap);
4459 
4460 		btrfs_release_path(path);
4461 
4462 		ret = move_existing_remap(fs_info, path, bg, key.objectid,
4463 					  key.offset, old_addr);
4464 		if (ret)
4465 			return ret;
4466 	}
4467 
4468 	ASSERT(bg->remap_bytes == 0);
4469 
4470 	return 0;
4471 }
4472 
4473 static int create_remap_tree_entries(struct btrfs_trans_handle *trans,
4474 				     struct btrfs_path *path,
4475 				     struct btrfs_block_group *bg)
4476 {
4477 	struct btrfs_fs_info *fs_info = trans->fs_info;
4478 	struct btrfs_free_space_info *fsi;
4479 	struct btrfs_key key, found_key;
4480 	struct extent_buffer *leaf;
4481 	struct btrfs_root *space_root;
4482 	u32 extent_count;
4483 	struct space_run *space_runs = NULL;
4484 	unsigned int num_space_runs = 0;
4485 	struct btrfs_key *entries = NULL;
4486 	unsigned int max_entries, num_entries;
4487 	int ret;
4488 
4489 	mutex_lock(&bg->free_space_lock);
4490 
4491 	if (test_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE, &bg->runtime_flags)) {
4492 		mutex_unlock(&bg->free_space_lock);
4493 
4494 		ret = btrfs_add_block_group_free_space(trans, bg);
4495 		if (ret)
4496 			return ret;
4497 
4498 		mutex_lock(&bg->free_space_lock);
4499 	}
4500 
4501 	fsi = btrfs_search_free_space_info(trans, bg, path, 0);
4502 	if (IS_ERR(fsi)) {
4503 		mutex_unlock(&bg->free_space_lock);
4504 		return PTR_ERR(fsi);
4505 	}
4506 
4507 	extent_count = btrfs_free_space_extent_count(path->nodes[0], fsi);
4508 
4509 	btrfs_release_path(path);
4510 
4511 	space_runs = kmalloc_objs(*space_runs, extent_count, GFP_NOFS);
4512 	if (!space_runs) {
4513 		mutex_unlock(&bg->free_space_lock);
4514 		return -ENOMEM;
4515 	}
4516 
4517 	key.objectid = bg->start;
4518 	key.type = 0;
4519 	key.offset = 0;
4520 
4521 	space_root = btrfs_free_space_root(bg);
4522 
4523 	ret = btrfs_search_slot(trans, space_root, &key, path, 0, 0);
4524 	if (ret < 0) {
4525 		mutex_unlock(&bg->free_space_lock);
4526 		goto out;
4527 	}
4528 
4529 	ret = 0;
4530 
4531 	while (true) {
4532 		leaf = path->nodes[0];
4533 
4534 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4535 
4536 		if (found_key.objectid >= bg->start + bg->length)
4537 			break;
4538 
4539 		if (found_key.type == BTRFS_FREE_SPACE_EXTENT_KEY) {
4540 			if (num_space_runs != 0 &&
4541 			    space_runs[num_space_runs - 1].end == found_key.objectid) {
4542 				space_runs[num_space_runs - 1].end =
4543 					found_key.objectid + found_key.offset;
4544 			} else {
4545 				ASSERT(num_space_runs < extent_count);
4546 
4547 				space_runs[num_space_runs].start = found_key.objectid;
4548 				space_runs[num_space_runs].end =
4549 					found_key.objectid + found_key.offset;
4550 
4551 				num_space_runs++;
4552 			}
4553 		} else if (found_key.type == BTRFS_FREE_SPACE_BITMAP_KEY) {
4554 			void *bitmap;
4555 			unsigned long offset;
4556 			u32 data_size;
4557 
4558 			offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
4559 			data_size = btrfs_item_size(leaf, path->slots[0]);
4560 
4561 			if (data_size != 0) {
4562 				bitmap = kmalloc(data_size, GFP_NOFS);
4563 				if (!bitmap) {
4564 					mutex_unlock(&bg->free_space_lock);
4565 					ret = -ENOMEM;
4566 					goto out;
4567 				}
4568 
4569 				read_extent_buffer(leaf, bitmap, offset, data_size);
4570 
4571 				parse_bitmap(fs_info->sectorsize, bitmap,
4572 					     data_size * BITS_PER_BYTE,
4573 					     found_key.objectid, space_runs,
4574 					     &num_space_runs);
4575 
4576 				ASSERT(num_space_runs <= extent_count);
4577 
4578 				kfree(bitmap);
4579 			}
4580 		}
4581 
4582 		path->slots[0]++;
4583 
4584 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4585 			ret = btrfs_next_leaf(space_root, path);
4586 			if (ret != 0) {
4587 				if (ret == 1)
4588 					ret = 0;
4589 				break;
4590 			}
4591 			leaf = path->nodes[0];
4592 		}
4593 	}
4594 
4595 	btrfs_release_path(path);
4596 
4597 	mutex_unlock(&bg->free_space_lock);
4598 
4599 	max_entries = extent_count + 2;
4600 	entries = kmalloc_objs(*entries, max_entries, GFP_NOFS);
4601 	if (!entries) {
4602 		ret = -ENOMEM;
4603 		goto out;
4604 	}
4605 
4606 	num_entries = 0;
4607 
4608 	if (num_space_runs == 0) {
4609 		entries[num_entries].objectid = bg->start;
4610 		entries[num_entries].type = BTRFS_IDENTITY_REMAP_KEY;
4611 		entries[num_entries].offset = bg->length;
4612 		num_entries++;
4613 	} else {
4614 		if (space_runs[0].start > bg->start) {
4615 			entries[num_entries].objectid = bg->start;
4616 			entries[num_entries].type = BTRFS_IDENTITY_REMAP_KEY;
4617 			entries[num_entries].offset = space_runs[0].start - bg->start;
4618 			num_entries++;
4619 		}
4620 
4621 		for (unsigned int i = 1; i < num_space_runs; i++) {
4622 			entries[num_entries].objectid = space_runs[i - 1].end;
4623 			entries[num_entries].type = BTRFS_IDENTITY_REMAP_KEY;
4624 			entries[num_entries].offset =
4625 				space_runs[i].start - space_runs[i - 1].end;
4626 			num_entries++;
4627 		}
4628 
4629 		if (space_runs[num_space_runs - 1].end < bg->start + bg->length) {
4630 			entries[num_entries].objectid =
4631 				space_runs[num_space_runs - 1].end;
4632 			entries[num_entries].type = BTRFS_IDENTITY_REMAP_KEY;
4633 			entries[num_entries].offset =
4634 				bg->start + bg->length - space_runs[num_space_runs - 1].end;
4635 			num_entries++;
4636 		}
4637 
4638 		if (num_entries == 0)
4639 			goto out;
4640 	}
4641 
4642 	bg->identity_remap_count = num_entries;
4643 
4644 	ret = add_remap_tree_entries(trans, path, entries, num_entries);
4645 
4646 out:
4647 	kfree(entries);
4648 	kfree(space_runs);
4649 
4650 	return ret;
4651 }
4652 
4653 static int find_next_identity_remap(struct btrfs_trans_handle *trans,
4654 				    struct btrfs_path *path, u64 bg_end,
4655 				    u64 last_start, u64 *start, u64 *length)
4656 {
4657 	int ret;
4658 	struct btrfs_key key, found_key;
4659 	struct btrfs_root *remap_root = trans->fs_info->remap_root;
4660 	struct extent_buffer *leaf;
4661 
4662 	key.objectid = last_start;
4663 	key.type = BTRFS_IDENTITY_REMAP_KEY;
4664 	key.offset = 0;
4665 
4666 	ret = btrfs_search_slot(trans, remap_root, &key, path, 0, 0);
4667 	if (ret < 0)
4668 		goto out;
4669 
4670 	leaf = path->nodes[0];
4671 	while (true) {
4672 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4673 			ret = btrfs_next_leaf(remap_root, path);
4674 
4675 			if (ret != 0) {
4676 				if (ret == 1)
4677 					ret = -ENOENT;
4678 				goto out;
4679 			}
4680 
4681 			leaf = path->nodes[0];
4682 		}
4683 
4684 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4685 
4686 		if (found_key.objectid >= bg_end) {
4687 			ret = -ENOENT;
4688 			goto out;
4689 		}
4690 
4691 		if (found_key.type == BTRFS_IDENTITY_REMAP_KEY) {
4692 			*start = found_key.objectid;
4693 			*length = found_key.offset;
4694 			ret = 0;
4695 			goto out;
4696 		}
4697 
4698 		path->slots[0]++;
4699 	}
4700 
4701 out:
4702 	btrfs_release_path(path);
4703 
4704 	return ret;
4705 }
4706 
4707 static int remove_chunk_stripes(struct btrfs_trans_handle *trans,
4708 				struct btrfs_chunk_map *chunk_map,
4709 				struct btrfs_path *path)
4710 {
4711 	struct btrfs_fs_info *fs_info = trans->fs_info;
4712 	struct btrfs_key key;
4713 	struct extent_buffer *leaf;
4714 	struct btrfs_chunk *chunk;
4715 	int ret;
4716 
4717 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4718 	key.type = BTRFS_CHUNK_ITEM_KEY;
4719 	key.offset = chunk_map->start;
4720 
4721 	btrfs_reserve_chunk_metadata(trans, false);
4722 
4723 	ret = btrfs_search_slot(trans, fs_info->chunk_root, &key, path, 0, 1);
4724 	if (ret) {
4725 		if (ret == 1) {
4726 			btrfs_release_path(path);
4727 			ret = -ENOENT;
4728 		}
4729 		btrfs_trans_release_chunk_metadata(trans);
4730 		return ret;
4731 	}
4732 
4733 	leaf = path->nodes[0];
4734 
4735 	chunk = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_chunk);
4736 	btrfs_set_chunk_num_stripes(leaf, chunk, 0);
4737 	btrfs_set_chunk_sub_stripes(leaf, chunk, 0);
4738 
4739 	btrfs_truncate_item(trans, path, offsetof(struct btrfs_chunk, stripe), 1);
4740 
4741 	btrfs_mark_buffer_dirty(trans, leaf);
4742 
4743 	btrfs_release_path(path);
4744 	btrfs_trans_release_chunk_metadata(trans);
4745 
4746 	return 0;
4747 }
4748 
4749 int btrfs_last_identity_remap_gone(struct btrfs_chunk_map *chunk_map,
4750 				   struct btrfs_block_group *bg)
4751 {
4752 	struct btrfs_fs_info *fs_info = bg->fs_info;
4753 	struct btrfs_trans_handle *trans;
4754 	int ret;
4755 	unsigned int num_items;
4756 	BTRFS_PATH_AUTO_FREE(path);
4757 
4758 	path = btrfs_alloc_path();
4759 	if (!path)
4760 		return -ENOMEM;
4761 
4762 	/*
4763 	 * One item for each entry we're removing in the dev extents tree, and
4764 	 * another for each device. DUP chunks are all on one device,
4765 	 * everything else has one device per stripe.
4766 	 */
4767 	if (bg->flags & BTRFS_BLOCK_GROUP_DUP)
4768 		num_items = chunk_map->num_stripes + 1;
4769 	else
4770 		num_items = 2 * chunk_map->num_stripes;
4771 
4772 	trans = btrfs_start_transaction_fallback_global_rsv(fs_info->tree_root, num_items);
4773 	if (IS_ERR(trans))
4774 		return PTR_ERR(trans);
4775 
4776 	ret = btrfs_remove_dev_extents(trans, chunk_map);
4777 	if (unlikely(ret)) {
4778 		btrfs_abort_transaction(trans, ret);
4779 		btrfs_end_transaction(trans);
4780 		return ret;
4781 	}
4782 
4783 	mutex_lock(&trans->fs_info->chunk_mutex);
4784 	for (unsigned int i = 0; i < chunk_map->num_stripes; i++) {
4785 		ret = btrfs_update_device(trans, chunk_map->stripes[i].dev);
4786 		if (unlikely(ret)) {
4787 			mutex_unlock(&trans->fs_info->chunk_mutex);
4788 			btrfs_abort_transaction(trans, ret);
4789 			btrfs_end_transaction(trans);
4790 			return ret;
4791 		}
4792 	}
4793 	mutex_unlock(&trans->fs_info->chunk_mutex);
4794 
4795 	write_lock(&trans->fs_info->mapping_tree_lock);
4796 	btrfs_chunk_map_device_clear_bits(chunk_map, CHUNK_ALLOCATED);
4797 	write_unlock(&trans->fs_info->mapping_tree_lock);
4798 
4799 	btrfs_remove_bg_from_sinfo(bg);
4800 
4801 	spin_lock(&bg->lock);
4802 	clear_bit(BLOCK_GROUP_FLAG_STRIPE_REMOVAL_PENDING, &bg->runtime_flags);
4803 	spin_unlock(&bg->lock);
4804 
4805 	ret = remove_chunk_stripes(trans, chunk_map, path);
4806 	if (unlikely(ret)) {
4807 		btrfs_abort_transaction(trans, ret);
4808 		btrfs_end_transaction(trans);
4809 		return ret;
4810 	}
4811 
4812 	ret = btrfs_commit_transaction(trans);
4813 	if (ret)
4814 		return ret;
4815 
4816 	return 0;
4817 }
4818 
4819 static void adjust_identity_remap_count(struct btrfs_trans_handle *trans,
4820 				        struct btrfs_block_group *bg, int delta)
4821 {
4822 	struct btrfs_fs_info *fs_info = trans->fs_info;
4823 	bool bg_already_dirty = true;
4824 	bool mark_fully_remapped = false;
4825 
4826 	WARN_ON(delta < 0 && -delta > bg->identity_remap_count);
4827 
4828 	spin_lock(&bg->lock);
4829 
4830 	bg->identity_remap_count += delta;
4831 
4832 	if (bg->identity_remap_count == 0 &&
4833 	    !test_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &bg->runtime_flags)) {
4834 		set_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &bg->runtime_flags);
4835 		mark_fully_remapped = true;
4836 	}
4837 
4838 	spin_unlock(&bg->lock);
4839 
4840 	spin_lock(&trans->transaction->dirty_bgs_lock);
4841 	if (list_empty(&bg->dirty_list)) {
4842 		list_add_tail(&bg->dirty_list, &trans->transaction->dirty_bgs);
4843 		bg_already_dirty = false;
4844 		btrfs_get_block_group(bg);
4845 	}
4846 	spin_unlock(&trans->transaction->dirty_bgs_lock);
4847 
4848 	/* Modified block groups are accounted for in the delayed_refs_rsv. */
4849 	if (!bg_already_dirty)
4850 		btrfs_inc_delayed_refs_rsv_bg_updates(fs_info);
4851 
4852 	if (mark_fully_remapped)
4853 		btrfs_mark_bg_fully_remapped(bg, trans);
4854 }
4855 
4856 static int add_remap_entry(struct btrfs_trans_handle *trans,
4857 			   struct btrfs_path *path,
4858 			   struct btrfs_block_group *src_bg, u64 old_addr,
4859 			   u64 new_addr, u64 length)
4860 {
4861 	struct btrfs_fs_info *fs_info = trans->fs_info;
4862 	struct btrfs_key key, new_key;
4863 	int ret;
4864 	int identity_count_delta = 0;
4865 
4866 	key.objectid = old_addr;
4867 	key.type = (u8)-1;
4868 	key.offset = (u64)-1;
4869 
4870 	ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, -1, 1);
4871 	if (ret < 0)
4872 		goto end;
4873 
4874 	if (path->slots[0] == 0) {
4875 		ret = -ENOENT;
4876 		goto end;
4877 	}
4878 
4879 	path->slots[0]--;
4880 
4881 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4882 
4883 	if (key.type != BTRFS_IDENTITY_REMAP_KEY ||
4884 	    key.objectid > old_addr ||
4885 	    key.objectid + key.offset <= old_addr) {
4886 		ret = -ENOENT;
4887 		goto end;
4888 	}
4889 
4890 	/* Shorten or delete identity mapping entry. */
4891 	if (key.objectid == old_addr) {
4892 		ret = btrfs_del_item(trans, fs_info->remap_root, path);
4893 		if (ret)
4894 			goto end;
4895 
4896 		identity_count_delta--;
4897 	} else {
4898 		new_key.objectid = key.objectid;
4899 		new_key.type = BTRFS_IDENTITY_REMAP_KEY;
4900 		new_key.offset = old_addr - key.objectid;
4901 
4902 		btrfs_set_item_key_safe(trans, path, &new_key);
4903 	}
4904 
4905 	btrfs_release_path(path);
4906 
4907 	/* Create new remap entry. */
4908 	ret = add_remap_item(trans, path, new_addr, length, old_addr);
4909 	if (ret)
4910 		goto end;
4911 
4912 	/* Add entry for remainder of identity mapping, if necessary. */
4913 	if (key.objectid + key.offset != old_addr + length) {
4914 		new_key.objectid = old_addr + length;
4915 		new_key.type = BTRFS_IDENTITY_REMAP_KEY;
4916 		new_key.offset = key.objectid + key.offset - old_addr - length;
4917 
4918 		ret = btrfs_insert_empty_item(trans, fs_info->remap_root,
4919 					      path, &new_key, 0);
4920 		if (ret)
4921 			goto end;
4922 
4923 		btrfs_release_path(path);
4924 
4925 		identity_count_delta++;
4926 	}
4927 
4928 	/* Add backref. */
4929 	ret = add_remap_backref_item(trans, path, new_addr, length, old_addr);
4930 	if (ret)
4931 		goto end;
4932 
4933 	if (identity_count_delta != 0)
4934 		adjust_identity_remap_count(trans, src_bg, identity_count_delta);
4935 
4936 end:
4937 	btrfs_release_path(path);
4938 
4939 	return ret;
4940 }
4941 
4942 static int mark_chunk_remapped(struct btrfs_trans_handle *trans,
4943 			       struct btrfs_path *path, u64 start)
4944 {
4945 	struct btrfs_fs_info *fs_info = trans->fs_info;
4946 	struct btrfs_chunk_map *chunk_map;
4947 	struct btrfs_key key;
4948 	u64 type;
4949 	int ret;
4950 	struct extent_buffer *leaf;
4951 	struct btrfs_chunk *chunk;
4952 
4953 	read_lock(&fs_info->mapping_tree_lock);
4954 
4955 	chunk_map = btrfs_find_chunk_map_nolock(fs_info, start, 1);
4956 	if (!chunk_map) {
4957 		read_unlock(&fs_info->mapping_tree_lock);
4958 		return -ENOENT;
4959 	}
4960 
4961 	chunk_map->type |= BTRFS_BLOCK_GROUP_REMAPPED;
4962 	type = chunk_map->type;
4963 
4964 	read_unlock(&fs_info->mapping_tree_lock);
4965 
4966 	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4967 	key.type = BTRFS_CHUNK_ITEM_KEY;
4968 	key.offset = start;
4969 
4970 	ret = btrfs_search_slot(trans, fs_info->chunk_root, &key, path, 0, 1);
4971 	if (ret == 1) {
4972 		ret = -ENOENT;
4973 		goto end;
4974 	} else if (ret < 0)
4975 		goto end;
4976 
4977 	leaf = path->nodes[0];
4978 
4979 	chunk = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_chunk);
4980 	btrfs_set_chunk_type(leaf, chunk, type);
4981 	btrfs_mark_buffer_dirty(trans, leaf);
4982 
4983 	ret = 0;
4984 end:
4985 	btrfs_free_chunk_map(chunk_map);
4986 	btrfs_release_path(path);
4987 
4988 	return ret;
4989 }
4990 
4991 static int do_remap_reloc_trans(struct btrfs_fs_info *fs_info,
4992 				struct btrfs_block_group *src_bg,
4993 				struct btrfs_path *path, u64 *last_start)
4994 {
4995 	struct btrfs_trans_handle *trans;
4996 	struct btrfs_root *extent_root;
4997 	struct btrfs_key ins;
4998 	struct btrfs_block_group *dest_bg = NULL;
4999 	u64 start = 0, remap_length = 0;
5000 	u64 length, new_addr, min_size;
5001 	int ret;
5002 	const bool is_data = (src_bg->flags & BTRFS_BLOCK_GROUP_DATA);
5003 	bool no_more = false;
5004 	bool made_reservation = false, bg_needs_free_space;
5005 	struct btrfs_space_info *sinfo = src_bg->space_info;
5006 
5007 	extent_root = btrfs_extent_root(fs_info, src_bg->start);
5008 	if (unlikely(!extent_root)) {
5009 		btrfs_err(fs_info,
5010 			  "missing extent root for block group at offset %llu",
5011 			  src_bg->start);
5012 		return -EUCLEAN;
5013 	}
5014 
5015 	trans = btrfs_start_transaction(extent_root, 0);
5016 	if (IS_ERR(trans))
5017 		return PTR_ERR(trans);
5018 
5019 	mutex_lock(&fs_info->remap_mutex);
5020 
5021 	ret = find_next_identity_remap(trans, path, src_bg->start + src_bg->length,
5022 				       *last_start, &start, &remap_length);
5023 	if (ret == -ENOENT) {
5024 		no_more = true;
5025 		goto next;
5026 	} else if (ret) {
5027 		mutex_unlock(&fs_info->remap_mutex);
5028 		btrfs_end_transaction(trans);
5029 		return ret;
5030 	}
5031 
5032 	/* Try to reserve enough space for block. */
5033 	spin_lock(&sinfo->lock);
5034 	btrfs_space_info_update_bytes_may_use(sinfo, remap_length);
5035 	spin_unlock(&sinfo->lock);
5036 
5037 	if (is_data)
5038 		min_size = fs_info->sectorsize;
5039 	else
5040 		min_size = fs_info->nodesize;
5041 
5042 	/*
5043 	 * We're using btrfs_reserve_extent() to allocate a contiguous
5044 	 * logical address range, but this will become a remap item rather than
5045 	 * an extent in the extent tree.
5046 	 *
5047 	 * Short allocations are fine: it means that we chop off the beginning
5048 	 * of the identity remap that we're processing, and will tackle the
5049 	 * rest of it the next time round.
5050 	 */
5051 	ret = btrfs_reserve_extent(fs_info->fs_root, remap_length, remap_length,
5052 				   min_size, 0, 0, &ins, is_data, false);
5053 	if (ret) {
5054 		spin_lock(&sinfo->lock);
5055 		btrfs_space_info_update_bytes_may_use(sinfo, -remap_length);
5056 		spin_unlock(&sinfo->lock);
5057 
5058 		mutex_unlock(&fs_info->remap_mutex);
5059 		btrfs_end_transaction(trans);
5060 		return ret;
5061 	}
5062 
5063 	if (ins.offset < remap_length) {
5064 		spin_lock(&sinfo->lock);
5065 		btrfs_space_info_update_bytes_may_use(sinfo, ins.offset - remap_length);
5066 		spin_unlock(&sinfo->lock);
5067 	}
5068 
5069 	made_reservation = true;
5070 
5071 	new_addr = ins.objectid;
5072 	length = ins.offset;
5073 
5074 	if (!is_data && !IS_ALIGNED(length, fs_info->nodesize)) {
5075 		u64 new_length = ALIGN_DOWN(length, fs_info->nodesize);
5076 
5077 		btrfs_free_reserved_extent(fs_info, new_addr + new_length,
5078 					   length - new_length, 0);
5079 
5080 		length = new_length;
5081 	}
5082 
5083 	dest_bg = btrfs_lookup_block_group(fs_info, new_addr);
5084 
5085 	mutex_lock(&dest_bg->free_space_lock);
5086 	bg_needs_free_space = test_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE,
5087 				       &dest_bg->runtime_flags);
5088 	mutex_unlock(&dest_bg->free_space_lock);
5089 
5090 	if (bg_needs_free_space) {
5091 		ret = btrfs_add_block_group_free_space(trans, dest_bg);
5092 		if (ret) {
5093 			btrfs_abort_transaction(trans, ret);
5094 			goto fail;
5095 		}
5096 	}
5097 
5098 	ret = copy_remapped_data(fs_info, start, new_addr, length);
5099 	if (ret) {
5100 		btrfs_abort_transaction(trans, ret);
5101 		goto fail;
5102 	}
5103 
5104 	ret = btrfs_remove_from_free_space_tree(trans, new_addr, length);
5105 	if (ret) {
5106 		btrfs_abort_transaction(trans, ret);
5107 		goto fail;
5108 	}
5109 
5110 	ret = add_remap_entry(trans, path, src_bg, start, new_addr, length);
5111 	if (ret) {
5112 		btrfs_abort_transaction(trans, ret);
5113 		goto fail;
5114 	}
5115 
5116 	adjust_block_group_remap_bytes(trans, dest_bg, length);
5117 	btrfs_free_reserved_bytes(dest_bg, length, 0);
5118 
5119 	spin_lock(&sinfo->lock);
5120 	sinfo->bytes_readonly += length;
5121 	spin_unlock(&sinfo->lock);
5122 
5123 next:
5124 	if (dest_bg)
5125 		btrfs_put_block_group(dest_bg);
5126 
5127 	if (made_reservation)
5128 		btrfs_dec_block_group_reservations(fs_info, new_addr);
5129 
5130 	mutex_unlock(&fs_info->remap_mutex);
5131 
5132 	if (src_bg->identity_remap_count == 0) {
5133 		bool mark_fully_remapped = false;
5134 
5135 		spin_lock(&src_bg->lock);
5136 		if (!test_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &src_bg->runtime_flags)) {
5137 			mark_fully_remapped = true;
5138 			set_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &src_bg->runtime_flags);
5139 		}
5140 		spin_unlock(&src_bg->lock);
5141 
5142 		if (mark_fully_remapped)
5143 			btrfs_mark_bg_fully_remapped(src_bg, trans);
5144 	}
5145 
5146 	ret = btrfs_end_transaction(trans);
5147 	if (ret)
5148 		return ret;
5149 
5150 	if (no_more)
5151 		return 1;
5152 
5153 	*last_start = start;
5154 
5155 	return 0;
5156 
5157 fail:
5158 	if (dest_bg)
5159 		btrfs_put_block_group(dest_bg);
5160 
5161 	btrfs_free_reserved_extent(fs_info, new_addr, length, 0);
5162 
5163 	mutex_unlock(&fs_info->remap_mutex);
5164 	btrfs_end_transaction(trans);
5165 
5166 	return ret;
5167 }
5168 
5169 static int do_remap_reloc(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
5170 			  struct btrfs_block_group *bg)
5171 {
5172 	u64 last_start = bg->start;
5173 	int ret;
5174 
5175 	while (true) {
5176 		ret = do_remap_reloc_trans(fs_info, bg, path, &last_start);
5177 		if (ret) {
5178 			if (ret == 1)
5179 				ret = 0;
5180 			break;
5181 		}
5182 	}
5183 
5184 	return ret;
5185 }
5186 
5187 int btrfs_translate_remap(struct btrfs_fs_info *fs_info, u64 *logical, u64 *length)
5188 {
5189 	int ret;
5190 	struct btrfs_key key, found_key;
5191 	struct extent_buffer *leaf;
5192 	struct btrfs_remap_item *remap;
5193 	BTRFS_PATH_AUTO_FREE(path);
5194 
5195 	path = btrfs_alloc_path();
5196 	if (!path)
5197 		return -ENOMEM;
5198 
5199 	key.objectid = *logical;
5200 	key.type = (u8)-1;
5201 	key.offset = (u64)-1;
5202 
5203 	ret = btrfs_search_slot(NULL, fs_info->remap_root, &key, path, 0, 0);
5204 	if (ret < 0)
5205 		return ret;
5206 
5207 	leaf = path->nodes[0];
5208 	if (path->slots[0] == 0)
5209 		return -ENOENT;
5210 
5211 	path->slots[0]--;
5212 
5213 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5214 
5215 	if (found_key.type != BTRFS_REMAP_KEY &&
5216 	    found_key.type != BTRFS_IDENTITY_REMAP_KEY) {
5217 		return -ENOENT;
5218 	}
5219 
5220 	if (found_key.objectid > *logical ||
5221 	    found_key.objectid + found_key.offset <= *logical) {
5222 		return -ENOENT;
5223 	}
5224 
5225 	if (*logical + *length > found_key.objectid + found_key.offset)
5226 		*length = found_key.objectid + found_key.offset - *logical;
5227 
5228 	if (found_key.type == BTRFS_IDENTITY_REMAP_KEY)
5229 		return 0;
5230 
5231 	remap = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_remap_item);
5232 	*logical += btrfs_remap_address(leaf, remap) - found_key.objectid;
5233 
5234 	return 0;
5235 }
5236 
5237 static int start_block_group_remapping(struct btrfs_fs_info *fs_info,
5238 				       struct btrfs_path *path,
5239 				       struct btrfs_block_group *bg)
5240 {
5241 	struct btrfs_trans_handle *trans;
5242 	bool bg_already_dirty = true;
5243 	int ret, ret2;
5244 
5245 	ret = btrfs_cache_block_group(bg, true);
5246 	if (ret)
5247 		return ret;
5248 
5249 	trans = btrfs_start_transaction(fs_info->remap_root, 0);
5250 	if (IS_ERR(trans))
5251 		return PTR_ERR(trans);
5252 
5253 	/* We need to run delayed refs, to make sure FST is up to date. */
5254 	ret = btrfs_run_delayed_refs(trans, U64_MAX);
5255 	if (ret) {
5256 		btrfs_end_transaction(trans);
5257 		return ret;
5258 	}
5259 
5260 	mutex_lock(&fs_info->remap_mutex);
5261 
5262 	if (bg->flags & BTRFS_BLOCK_GROUP_REMAPPED) {
5263 		ret = 0;
5264 		goto end;
5265 	}
5266 
5267 	ret = create_remap_tree_entries(trans, path, bg);
5268 	if (unlikely(ret)) {
5269 		btrfs_abort_transaction(trans, ret);
5270 		goto end;
5271 	}
5272 
5273 	spin_lock(&bg->lock);
5274 	bg->flags |= BTRFS_BLOCK_GROUP_REMAPPED;
5275 	spin_unlock(&bg->lock);
5276 
5277 	spin_lock(&trans->transaction->dirty_bgs_lock);
5278 	if (list_empty(&bg->dirty_list)) {
5279 		list_add_tail(&bg->dirty_list, &trans->transaction->dirty_bgs);
5280 		bg_already_dirty = false;
5281 		btrfs_get_block_group(bg);
5282 	}
5283 	spin_unlock(&trans->transaction->dirty_bgs_lock);
5284 
5285 	/* Modified block groups are accounted for in the delayed_refs_rsv. */
5286 	if (!bg_already_dirty)
5287 		btrfs_inc_delayed_refs_rsv_bg_updates(fs_info);
5288 
5289 	ret = mark_chunk_remapped(trans, path, bg->start);
5290 	if (unlikely(ret)) {
5291 		btrfs_abort_transaction(trans, ret);
5292 		goto end;
5293 	}
5294 
5295 	ret = btrfs_remove_block_group_free_space(trans, bg);
5296 	if (unlikely(ret)) {
5297 		btrfs_abort_transaction(trans, ret);
5298 		goto end;
5299 	}
5300 
5301 	btrfs_remove_free_space_cache(bg);
5302 
5303 end:
5304 	mutex_unlock(&fs_info->remap_mutex);
5305 
5306 	ret2 = btrfs_end_transaction(trans);
5307 	if (!ret)
5308 		ret = ret2;
5309 
5310 	return ret;
5311 }
5312 
5313 static int do_nonremap_reloc(struct btrfs_fs_info *fs_info, bool verbose,
5314 			     struct reloc_control *rc)
5315 {
5316 	int ret;
5317 
5318 	while (1) {
5319 		enum reloc_stage finishes_stage;
5320 
5321 		mutex_lock(&fs_info->cleaner_mutex);
5322 		ret = relocate_block_group(rc);
5323 		mutex_unlock(&fs_info->cleaner_mutex);
5324 
5325 		finishes_stage = rc->stage;
5326 		/*
5327 		 * We may have gotten ENOSPC after we already dirtied some
5328 		 * extents.  If writeout happens while we're relocating a
5329 		 * different block group we could end up hitting the
5330 		 * BUG_ON(rc->stage == UPDATE_DATA_PTRS) in
5331 		 * btrfs_reloc_cow_block.  Make sure we write everything out
5332 		 * properly so we don't trip over this problem, and then break
5333 		 * out of the loop if we hit an error.
5334 		 */
5335 		if (rc->stage == MOVE_DATA_EXTENTS && rc->found_file_extent) {
5336 			int wb_ret;
5337 
5338 			wb_ret = btrfs_wait_ordered_range(BTRFS_I(rc->data_inode),
5339 							  0, (u64)-1);
5340 			if (wb_ret && ret == 0)
5341 				ret = wb_ret;
5342 			invalidate_mapping_pages(rc->data_inode->i_mapping, 0, -1);
5343 			rc->stage = UPDATE_DATA_PTRS;
5344 		}
5345 
5346 		if (ret < 0)
5347 			return ret;
5348 
5349 		if (rc->extents_found == 0)
5350 			break;
5351 
5352 		if (verbose)
5353 			btrfs_info(fs_info, "found %llu extents, stage: %s",
5354 				   rc->extents_found, stage_to_string(finishes_stage));
5355 	}
5356 
5357 	WARN_ON(rc->block_group->pinned > 0);
5358 	WARN_ON(rc->block_group->reserved > 0);
5359 	WARN_ON(rc->block_group->used > 0);
5360 
5361 	return 0;
5362 }
5363 
5364 /*
5365  * function to relocate all extents in a block group.
5366  */
5367 int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
5368 			       bool verbose)
5369 {
5370 	struct btrfs_block_group *bg;
5371 	struct btrfs_root *extent_root = btrfs_extent_root(fs_info, group_start);
5372 	struct reloc_control *rc;
5373 	struct inode *inode;
5374 	struct btrfs_path *path = NULL;
5375 	int ret;
5376 	bool bg_is_ro = false;
5377 
5378 	if (unlikely(!extent_root)) {
5379 		btrfs_err(fs_info,
5380 			  "missing extent root for block group at offset %llu",
5381 			  group_start);
5382 		return -EUCLEAN;
5383 	}
5384 
5385 	/*
5386 	 * This only gets set if we had a half-deleted snapshot on mount.  We
5387 	 * cannot allow relocation to start while we're still trying to clean up
5388 	 * these pending deletions.
5389 	 */
5390 	ret = wait_on_bit(&fs_info->flags, BTRFS_FS_UNFINISHED_DROPS, TASK_INTERRUPTIBLE);
5391 	if (ret)
5392 		return ret;
5393 
5394 	/* We may have been woken up by close_ctree, so bail if we're closing. */
5395 	if (btrfs_fs_closing(fs_info))
5396 		return -EINTR;
5397 
5398 	bg = btrfs_lookup_block_group(fs_info, group_start);
5399 	if (!bg)
5400 		return -ENOENT;
5401 
5402 	/*
5403 	 * Relocation of a data block group creates ordered extents.  Without
5404 	 * sb_start_write(), we can freeze the filesystem while unfinished
5405 	 * ordered extents are left. Such ordered extents can cause a deadlock
5406 	 * e.g. when syncfs() is waiting for their completion but they can't
5407 	 * finish because they block when joining a transaction, due to the
5408 	 * fact that the freeze locks are being held in write mode.
5409 	 */
5410 	if (bg->flags & BTRFS_BLOCK_GROUP_DATA)
5411 		ASSERT(sb_write_started(fs_info->sb));
5412 
5413 	if (btrfs_pinned_by_swapfile(fs_info, bg)) {
5414 		btrfs_put_block_group(bg);
5415 		return -ETXTBSY;
5416 	}
5417 
5418 	rc = alloc_reloc_control(fs_info);
5419 	if (!rc) {
5420 		btrfs_put_block_group(bg);
5421 		return -ENOMEM;
5422 	}
5423 
5424 	rc->extent_root = extent_root;
5425 	/* Block group ref now owned by rc, put_reloc_control() will drop it. */
5426 	rc->block_group = bg;
5427 
5428 	ret = reloc_chunk_start(fs_info);
5429 	if (ret < 0)
5430 		goto out_put_rc;
5431 
5432 	ret = btrfs_inc_block_group_ro(rc->block_group, true);
5433 	if (ret)
5434 		goto out;
5435 	bg_is_ro = true;
5436 
5437 	path = btrfs_alloc_path();
5438 	if (!path) {
5439 		ret = -ENOMEM;
5440 		goto out;
5441 	}
5442 
5443 	inode = lookup_free_space_inode(rc->block_group, path);
5444 	btrfs_release_path(path);
5445 
5446 	if (!IS_ERR(inode))
5447 		ret = delete_block_group_cache(rc->block_group, inode, 0);
5448 	else
5449 		ret = PTR_ERR(inode);
5450 
5451 	if (ret && ret != -ENOENT)
5452 		goto out;
5453 
5454 	if (!btrfs_fs_incompat(fs_info, REMAP_TREE)) {
5455 		rc->data_inode = create_reloc_inode(rc->block_group);
5456 		if (IS_ERR(rc->data_inode)) {
5457 			ret = PTR_ERR(rc->data_inode);
5458 			rc->data_inode = NULL;
5459 			goto out;
5460 		}
5461 	}
5462 
5463 	if (verbose)
5464 		describe_relocation(rc->block_group);
5465 
5466 	btrfs_wait_block_group_reservations(rc->block_group);
5467 	btrfs_wait_nocow_writers(rc->block_group);
5468 	btrfs_wait_ordered_roots(fs_info, U64_MAX, rc->block_group);
5469 
5470 	ret = btrfs_zone_finish(rc->block_group);
5471 	WARN_ON(ret && ret != -EAGAIN);
5472 
5473 	if (should_relocate_using_remap_tree(bg)) {
5474 		if (bg->remap_bytes != 0) {
5475 			ret = move_existing_remaps(fs_info, bg, path);
5476 			if (ret)
5477 				goto out;
5478 		}
5479 		ret = start_block_group_remapping(fs_info, path, bg);
5480 		if (ret)
5481 			goto out;
5482 
5483 		ret = do_remap_reloc(fs_info, path, rc->block_group);
5484 		if (ret)
5485 			goto out;
5486 
5487 		btrfs_delete_unused_bgs(fs_info);
5488 	} else {
5489 		ret = do_nonremap_reloc(fs_info, verbose, rc);
5490 	}
5491 
5492 out:
5493 	if (ret && bg_is_ro)
5494 		btrfs_dec_block_group_ro(rc->block_group);
5495 	if (!btrfs_fs_incompat(fs_info, REMAP_TREE))
5496 		iput(rc->data_inode);
5497 	btrfs_free_path(path);
5498 	reloc_chunk_end(fs_info);
5499 out_put_rc:
5500 	put_reloc_control(rc);
5501 	return ret;
5502 }
5503 
5504 static noinline_for_stack int mark_garbage_root(struct btrfs_root *root)
5505 {
5506 	struct btrfs_fs_info *fs_info = root->fs_info;
5507 	struct btrfs_trans_handle *trans;
5508 	int ret, err;
5509 
5510 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
5511 	if (IS_ERR(trans))
5512 		return PTR_ERR(trans);
5513 
5514 	memset(&root->root_item.drop_progress, 0,
5515 		sizeof(root->root_item.drop_progress));
5516 	btrfs_set_root_drop_level(&root->root_item, 0);
5517 	btrfs_set_root_refs(&root->root_item, 0);
5518 	ret = btrfs_update_root(trans, fs_info->tree_root,
5519 				&root->root_key, &root->root_item);
5520 
5521 	err = btrfs_end_transaction(trans);
5522 	if (err)
5523 		return err;
5524 	return ret;
5525 }
5526 
5527 /*
5528  * recover relocation interrupted by system crash.
5529  *
5530  * this function resumes merging reloc trees with corresponding fs trees.
5531  * this is important for keeping the sharing of tree blocks
5532  */
5533 int btrfs_recover_relocation(struct btrfs_fs_info *fs_info)
5534 {
5535 	LIST_HEAD(reloc_roots);
5536 	struct btrfs_key key;
5537 	struct btrfs_root *fs_root;
5538 	struct btrfs_root *reloc_root;
5539 	struct btrfs_path *path;
5540 	struct extent_buffer *leaf;
5541 	struct reloc_control *rc = NULL;
5542 	struct btrfs_trans_handle *trans;
5543 	int ret2;
5544 	int ret = 0;
5545 
5546 	path = btrfs_alloc_path();
5547 	if (!path)
5548 		return -ENOMEM;
5549 	path->reada = READA_BACK;
5550 
5551 	key.objectid = BTRFS_TREE_RELOC_OBJECTID;
5552 	key.type = BTRFS_ROOT_ITEM_KEY;
5553 	key.offset = (u64)-1;
5554 
5555 	while (1) {
5556 		ret = btrfs_search_slot(NULL, fs_info->tree_root, &key,
5557 					path, 0, 0);
5558 		if (ret < 0)
5559 			goto out;
5560 		if (ret > 0) {
5561 			if (path->slots[0] == 0)
5562 				break;
5563 			path->slots[0]--;
5564 		}
5565 		ret = 0;
5566 		leaf = path->nodes[0];
5567 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5568 		btrfs_release_path(path);
5569 
5570 		if (key.objectid != BTRFS_TREE_RELOC_OBJECTID ||
5571 		    key.type != BTRFS_ROOT_ITEM_KEY)
5572 			break;
5573 
5574 		reloc_root = btrfs_read_tree_root(fs_info->tree_root, &key);
5575 		if (IS_ERR(reloc_root)) {
5576 			ret = PTR_ERR(reloc_root);
5577 			goto out;
5578 		}
5579 
5580 		set_bit(BTRFS_ROOT_SHAREABLE, &reloc_root->state);
5581 		list_add(&reloc_root->root_list, &reloc_roots);
5582 
5583 		if (btrfs_root_refs(&reloc_root->root_item) > 0) {
5584 			fs_root = btrfs_get_fs_root(fs_info,
5585 					reloc_root->root_key.offset, false);
5586 			if (IS_ERR(fs_root)) {
5587 				ret = PTR_ERR(fs_root);
5588 				if (ret != -ENOENT)
5589 					goto out;
5590 				ret = mark_garbage_root(reloc_root);
5591 				if (ret < 0)
5592 					goto out;
5593 				ret = 0;
5594 			} else {
5595 				btrfs_put_root(fs_root);
5596 			}
5597 		}
5598 
5599 		if (key.offset == 0)
5600 			break;
5601 
5602 		key.offset--;
5603 	}
5604 	btrfs_release_path(path);
5605 
5606 	if (list_empty(&reloc_roots))
5607 		goto out;
5608 
5609 	rc = alloc_reloc_control(fs_info);
5610 	if (!rc) {
5611 		ret = -ENOMEM;
5612 		goto out;
5613 	}
5614 
5615 	rc->extent_root = btrfs_extent_root(fs_info, 0);
5616 	if (unlikely(!rc->extent_root)) {
5617 		btrfs_err(fs_info, "missing extent root for extent at bytenr 0");
5618 		ret = -EUCLEAN;
5619 		goto out;
5620 	}
5621 
5622 	ret = reloc_chunk_start(fs_info);
5623 	if (ret < 0)
5624 		goto out_end;
5625 
5626 	set_reloc_control(rc);
5627 
5628 	trans = btrfs_join_transaction(rc->extent_root);
5629 	if (IS_ERR(trans)) {
5630 		ret = PTR_ERR(trans);
5631 		goto out_unset;
5632 	}
5633 
5634 	rc->merge_reloc_tree = true;
5635 
5636 	while (!list_empty(&reloc_roots)) {
5637 		reloc_root = list_first_entry(&reloc_roots, struct btrfs_root, root_list);
5638 		list_del(&reloc_root->root_list);
5639 
5640 		if (btrfs_root_refs(&reloc_root->root_item) == 0) {
5641 			list_add_tail(&reloc_root->root_list,
5642 				      &rc->reloc_roots);
5643 			continue;
5644 		}
5645 
5646 		fs_root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
5647 					    false);
5648 		if (IS_ERR(fs_root)) {
5649 			ret = PTR_ERR(fs_root);
5650 			list_add_tail(&reloc_root->root_list, &reloc_roots);
5651 			btrfs_end_transaction(trans);
5652 			goto out_unset;
5653 		}
5654 
5655 		ret = __add_reloc_root(reloc_root, rc);
5656 		ASSERT(ret != -EEXIST);
5657 		if (ret) {
5658 			list_add_tail(&reloc_root->root_list, &reloc_roots);
5659 			btrfs_put_root(fs_root);
5660 			btrfs_end_transaction(trans);
5661 			goto out_unset;
5662 		}
5663 		fs_root->reloc_root = btrfs_grab_root(reloc_root);
5664 		btrfs_put_root(fs_root);
5665 	}
5666 
5667 	ret = btrfs_commit_transaction(trans);
5668 	if (ret)
5669 		goto out_unset;
5670 
5671 	merge_reloc_roots(rc);
5672 
5673 	unset_reloc_control(rc);
5674 
5675 	trans = btrfs_join_transaction(rc->extent_root);
5676 	if (IS_ERR(trans)) {
5677 		ret = PTR_ERR(trans);
5678 		goto out_clean;
5679 	}
5680 	ret = btrfs_commit_transaction(trans);
5681 out_clean:
5682 	ret2 = clean_dirty_subvols(rc);
5683 	if (ret2 < 0 && !ret)
5684 		ret = ret2;
5685 out_unset:
5686 	unset_reloc_control(rc);
5687 	reloc_chunk_end(fs_info);
5688 out_end:
5689 	put_reloc_control(rc);
5690 out:
5691 	free_reloc_roots(&reloc_roots);
5692 
5693 	btrfs_free_path(path);
5694 
5695 	if (ret == 0 && !btrfs_fs_incompat(fs_info, REMAP_TREE)) {
5696 		/* cleanup orphan inode in data relocation tree */
5697 		fs_root = btrfs_grab_root(fs_info->data_reloc_root);
5698 		ASSERT(fs_root);
5699 		ret = btrfs_orphan_cleanup(fs_root);
5700 		btrfs_put_root(fs_root);
5701 	}
5702 	return ret;
5703 }
5704 
5705 /*
5706  * helper to add ordered checksum for data relocation.
5707  *
5708  * cloning checksum properly handles the nodatasum extents.
5709  * it also saves CPU time to re-calculate the checksum.
5710  */
5711 int btrfs_reloc_clone_csums(struct btrfs_ordered_extent *ordered)
5712 {
5713 	struct btrfs_inode *inode = ordered->inode;
5714 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
5715 	u64 disk_bytenr = ordered->file_offset + inode->reloc_block_group_start;
5716 	struct btrfs_root *csum_root = btrfs_csum_root(fs_info, disk_bytenr);
5717 	LIST_HEAD(list);
5718 	int ret;
5719 
5720 	if (unlikely(!csum_root)) {
5721 		btrfs_mark_ordered_extent_error(ordered);
5722 		btrfs_err(fs_info,
5723 			  "missing csum root for extent at bytenr %llu",
5724 			  disk_bytenr);
5725 		return -EUCLEAN;
5726 	}
5727 
5728 	ret = btrfs_lookup_csums_list(csum_root, disk_bytenr,
5729 				      disk_bytenr + ordered->num_bytes - 1,
5730 				      &list, false);
5731 	if (ret < 0) {
5732 		btrfs_mark_ordered_extent_error(ordered);
5733 		return ret;
5734 	}
5735 
5736 	while (!list_empty(&list)) {
5737 		struct btrfs_ordered_sum *sums =
5738 			list_first_entry(&list, struct btrfs_ordered_sum, list);
5739 
5740 		list_del_init(&sums->list);
5741 
5742 		/*
5743 		 * We need to offset the new_bytenr based on where the csum is.
5744 		 * We need to do this because we will read in entire prealloc
5745 		 * extents but we may have written to say the middle of the
5746 		 * prealloc extent, so we need to make sure the csum goes with
5747 		 * the right disk offset.
5748 		 *
5749 		 * We can do this because the data reloc inode refers strictly
5750 		 * to the on disk bytes, so we don't have to worry about
5751 		 * disk_len vs real len like with real inodes since it's all
5752 		 * disk length.
5753 		 */
5754 		sums->logical = ordered->disk_bytenr + sums->logical - disk_bytenr;
5755 		btrfs_add_ordered_sum(ordered, sums);
5756 	}
5757 
5758 	return 0;
5759 }
5760 
5761 int btrfs_reloc_cow_block(struct btrfs_trans_handle *trans,
5762 			  struct btrfs_root *root,
5763 			  const struct extent_buffer *buf,
5764 			  struct extent_buffer *cow)
5765 {
5766 	struct btrfs_fs_info *fs_info = root->fs_info;
5767 	struct reloc_control *rc;
5768 	struct btrfs_backref_node *node;
5769 	bool first_cow = false;
5770 	int level;
5771 	int ret = 0;
5772 
5773 	rc = get_reloc_control(fs_info);
5774 	if (!rc)
5775 		return 0;
5776 
5777 	BUG_ON(rc->stage == UPDATE_DATA_PTRS && btrfs_is_data_reloc_root(root));
5778 
5779 	level = btrfs_header_level(buf);
5780 	if (btrfs_header_generation(buf) <=
5781 	    btrfs_root_last_snapshot(&root->root_item))
5782 		first_cow = true;
5783 
5784 	if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID && rc->create_reloc_tree) {
5785 		WARN_ON(!first_cow && level == 0);
5786 
5787 		node = rc->backref_cache.path[level];
5788 
5789 		/*
5790 		 * If node->bytenr != buf->start and node->new_bytenr !=
5791 		 * buf->start then we've got the wrong backref node for what we
5792 		 * expected to see here and the cache is incorrect.
5793 		 */
5794 		if (unlikely(node->bytenr != buf->start && node->new_bytenr != buf->start)) {
5795 			btrfs_err(fs_info,
5796 "bytenr %llu was found but our backref cache was expecting %llu or %llu",
5797 				  buf->start, node->bytenr, node->new_bytenr);
5798 			ret = -EUCLEAN;
5799 			goto out;
5800 		}
5801 
5802 		btrfs_backref_drop_node_buffer(node);
5803 		refcount_inc(&cow->refs);
5804 		node->eb = cow;
5805 		node->new_bytenr = cow->start;
5806 
5807 		if (!node->pending) {
5808 			list_move_tail(&node->list,
5809 				       &rc->backref_cache.pending[level]);
5810 			node->pending = 1;
5811 		}
5812 
5813 		if (first_cow)
5814 			mark_block_processed(rc, node);
5815 
5816 		if (first_cow && level > 0)
5817 			rc->nodes_relocated += buf->len;
5818 	}
5819 
5820 	if (level == 0 && first_cow && rc->stage == UPDATE_DATA_PTRS)
5821 		ret = replace_file_extents(trans, rc, root, cow);
5822 out:
5823 	put_reloc_control(rc);
5824 
5825 	return ret;
5826 }
5827 
5828 /*
5829  * called before creating snapshot. it calculates metadata reservation
5830  * required for relocating tree blocks in the snapshot
5831  */
5832 void btrfs_reloc_pre_snapshot(struct btrfs_pending_snapshot *pending,
5833 			      u64 *bytes_to_reserve)
5834 {
5835 	struct btrfs_root *root = pending->root;
5836 	struct reloc_control *rc = root->fs_info->reloc_ctl;
5837 
5838 	if (!rc || !have_reloc_root(root))
5839 		return;
5840 
5841 	if (!rc->merge_reloc_tree)
5842 		return;
5843 
5844 	root = root->reloc_root;
5845 	BUG_ON(btrfs_root_refs(&root->root_item) == 0);
5846 	/*
5847 	 * relocation is in the stage of merging trees. the space
5848 	 * used by merging a reloc tree is twice the size of
5849 	 * relocated tree nodes in the worst case. half for cowing
5850 	 * the reloc tree, half for cowing the fs tree. the space
5851 	 * used by cowing the reloc tree will be freed after the
5852 	 * tree is dropped. if we create snapshot, cowing the fs
5853 	 * tree may use more space than it frees. so we need
5854 	 * reserve extra space.
5855 	 */
5856 	*bytes_to_reserve += rc->nodes_relocated;
5857 }
5858 
5859 /*
5860  * called after snapshot is created. migrate block reservation
5861  * and create reloc root for the newly created snapshot
5862  *
5863  * This is similar to btrfs_init_reloc_root(), we come out of here with two
5864  * references held on the reloc_root, one for root->reloc_root and one for
5865  * rc->reloc_roots.
5866  */
5867 int btrfs_reloc_post_snapshot(struct btrfs_trans_handle *trans,
5868 			       struct btrfs_pending_snapshot *pending)
5869 {
5870 	struct btrfs_root *root = pending->root;
5871 	struct btrfs_root *reloc_root;
5872 	struct btrfs_root *new_root;
5873 	struct reloc_control *rc;
5874 	int ret = 0;
5875 
5876 	rc = get_reloc_control(trans->fs_info);
5877 	if (!rc)
5878 		return 0;
5879 
5880 	if (!have_reloc_root(root))
5881 		goto out;
5882 
5883 	rc->merging_rsv_size += rc->nodes_relocated;
5884 
5885 	if (rc->merge_reloc_tree) {
5886 		ret = btrfs_block_rsv_migrate(&pending->block_rsv,
5887 					      rc->block_rsv,
5888 					      rc->nodes_relocated, true);
5889 		if (ret)
5890 			goto out;
5891 	}
5892 
5893 	new_root = pending->snap;
5894 	reloc_root = create_reloc_root(trans, root->reloc_root, btrfs_root_id(new_root));
5895 	if (IS_ERR(reloc_root)) {
5896 		ret = PTR_ERR(reloc_root);
5897 		goto out;
5898 	}
5899 
5900 	ret = __add_reloc_root(reloc_root, rc);
5901 	ASSERT(ret != -EEXIST);
5902 	if (ret) {
5903 		/* Pairs with create_reloc_root */
5904 		btrfs_put_root(reloc_root);
5905 		goto out;
5906 	}
5907 	new_root->reloc_root = btrfs_grab_root(reloc_root);
5908 out:
5909 	put_reloc_control(rc);
5910 
5911 	return ret;
5912 }
5913 
5914 /*
5915  * Get the current bytenr for the block group which is being relocated.
5916  *
5917  * Return U64_MAX if no running relocation.
5918  */
5919 u64 btrfs_get_reloc_bg_bytenr(struct btrfs_fs_info *fs_info)
5920 {
5921 	u64 logical = U64_MAX;
5922 
5923 	mutex_lock(&fs_info->reloc_mutex);
5924 	if (fs_info->reloc_ctl && fs_info->reloc_ctl->block_group)
5925 		logical = fs_info->reloc_ctl->block_group->start;
5926 	mutex_unlock(&fs_info->reloc_mutex);
5927 
5928 	return logical;
5929 }
5930 
5931 static int insert_remap_item(struct btrfs_trans_handle *trans, struct btrfs_path *path,
5932 			     u64 old_addr, u64 length, u64 new_addr)
5933 {
5934 	int ret;
5935 	struct btrfs_fs_info *fs_info = trans->fs_info;
5936 	struct btrfs_key key;
5937 	struct btrfs_remap_item remap = { 0 };
5938 
5939 	if (old_addr == new_addr) {
5940 		/* Add new identity remap item. */
5941 		key.objectid = old_addr;
5942 		key.type = BTRFS_IDENTITY_REMAP_KEY;
5943 		key.offset = length;
5944 
5945 		ret = btrfs_insert_empty_item(trans, fs_info->remap_root, path,
5946 					      &key, 0);
5947 		if (ret)
5948 			return ret;
5949 	} else {
5950 		/* Add new remap item. */
5951 		key.objectid = old_addr;
5952 		key.type = BTRFS_REMAP_KEY;
5953 		key.offset = length;
5954 
5955 		ret = btrfs_insert_empty_item(trans, fs_info->remap_root,
5956 					      path, &key, sizeof(struct btrfs_remap_item));
5957 		if (ret)
5958 			return ret;
5959 
5960 		btrfs_set_stack_remap_address(&remap, new_addr);
5961 
5962 		write_extent_buffer(path->nodes[0], &remap,
5963 			btrfs_item_ptr_offset(path->nodes[0], path->slots[0]),
5964 			sizeof(struct btrfs_remap_item));
5965 
5966 		btrfs_release_path(path);
5967 
5968 		/* Add new backref item. */
5969 		key.objectid = new_addr;
5970 		key.type = BTRFS_REMAP_BACKREF_KEY;
5971 		key.offset = length;
5972 
5973 		ret = btrfs_insert_empty_item(trans, fs_info->remap_root,
5974 					      path, &key,
5975 					      sizeof(struct btrfs_remap_item));
5976 		if (ret)
5977 			return ret;
5978 
5979 		btrfs_set_stack_remap_address(&remap, old_addr);
5980 
5981 		write_extent_buffer(path->nodes[0], &remap,
5982 			btrfs_item_ptr_offset(path->nodes[0], path->slots[0]),
5983 			sizeof(struct btrfs_remap_item));
5984 	}
5985 
5986 	btrfs_release_path(path);
5987 
5988 	return 0;
5989 }
5990 
5991 /*
5992  * Punch a hole in the remap item or identity remap item pointed to by path,
5993  * for the range [hole_start, hole_start + hole_length).
5994  */
5995 static int remove_range_from_remap_tree(struct btrfs_trans_handle *trans,
5996 					struct btrfs_path *path,
5997 					struct btrfs_block_group *bg,
5998 					u64 hole_start, u64 hole_length)
5999 {
6000 	int ret;
6001 	struct btrfs_fs_info *fs_info = trans->fs_info;
6002 	struct extent_buffer *leaf = path->nodes[0];
6003 	struct btrfs_key key;
6004 	u64 hole_end, new_addr, remap_start, remap_length, remap_end;
6005 	u64 overlap_length;
6006 	bool is_identity_remap;
6007 	int identity_count_delta = 0;
6008 
6009 	hole_end = hole_start + hole_length;
6010 
6011 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6012 
6013 	is_identity_remap = (key.type == BTRFS_IDENTITY_REMAP_KEY);
6014 
6015 	remap_start = key.objectid;
6016 	remap_length = key.offset;
6017 	remap_end = remap_start + remap_length;
6018 
6019 	if (is_identity_remap) {
6020 		new_addr = remap_start;
6021 	} else {
6022 		struct btrfs_remap_item *remap_ptr;
6023 
6024 		remap_ptr = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_remap_item);
6025 		new_addr = btrfs_remap_address(leaf, remap_ptr);
6026 	}
6027 
6028 	/* Delete old item. */
6029 	ret = btrfs_del_item(trans, fs_info->remap_root, path);
6030 	btrfs_release_path(path);
6031 	if (ret)
6032 		return ret;
6033 
6034 	if (is_identity_remap) {
6035 		identity_count_delta = -1;
6036 	} else {
6037 		/* Remove backref. */
6038 		key.objectid = new_addr;
6039 		key.type = BTRFS_REMAP_BACKREF_KEY;
6040 		key.offset = remap_length;
6041 
6042 		ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, -1, 1);
6043 		if (ret) {
6044 			if (ret == 1) {
6045 				btrfs_release_path(path);
6046 				ret = -ENOENT;
6047 			}
6048 			return ret;
6049 		}
6050 
6051 		ret = btrfs_del_item(trans, fs_info->remap_root, path);
6052 
6053 		btrfs_release_path(path);
6054 
6055 		if (ret)
6056 			return ret;
6057 	}
6058 
6059 	/* If hole_start > remap_start, re-add the start of the remap item. */
6060 	if (hole_start > remap_start) {
6061 		ret = insert_remap_item(trans, path, remap_start,
6062 					hole_start - remap_start, new_addr);
6063 		if (ret)
6064 			return ret;
6065 
6066 		if (is_identity_remap)
6067 			identity_count_delta++;
6068 	}
6069 
6070 	/* If hole_end < remap_end, re-add the end of the remap item. */
6071 	if (hole_end < remap_end) {
6072 		ret = insert_remap_item(trans, path, hole_end,
6073 					remap_end - hole_end,
6074 					hole_end - remap_start + new_addr);
6075 		if (ret)
6076 			return ret;
6077 
6078 		if (is_identity_remap)
6079 			identity_count_delta++;
6080 	}
6081 
6082 	if (identity_count_delta != 0)
6083 		adjust_identity_remap_count(trans, bg, identity_count_delta);
6084 
6085 	overlap_length = min_t(u64, hole_end, remap_end) -
6086 			 max_t(u64, hole_start, remap_start);
6087 
6088 	if (!is_identity_remap) {
6089 		struct btrfs_block_group *dest_bg;
6090 
6091 		dest_bg = btrfs_lookup_block_group(fs_info, new_addr);
6092 		if (unlikely(!dest_bg))
6093 			return -EUCLEAN;
6094 
6095 		adjust_block_group_remap_bytes(trans, dest_bg, -overlap_length);
6096 		btrfs_put_block_group(dest_bg);
6097 		ret = btrfs_add_to_free_space_tree(trans,
6098 						   hole_start - remap_start + new_addr,
6099 						   overlap_length);
6100 		if (ret)
6101 			return ret;
6102 	}
6103 
6104 	ret = overlap_length;
6105 
6106 	return ret;
6107 }
6108 
6109 /*
6110  * Return 1 if remove_range_from_remap_tree() has been called successfully,
6111  * 0 if block group wasn't remapped, and a negative number on error.
6112  */
6113 int btrfs_remove_extent_from_remap_tree(struct btrfs_trans_handle *trans,
6114 					struct btrfs_path *path,
6115 					u64 bytenr, u64 num_bytes)
6116 {
6117 	struct btrfs_fs_info *fs_info = trans->fs_info;
6118 	struct btrfs_key key, found_key;
6119 	struct extent_buffer *leaf;
6120 	struct btrfs_block_group *bg;
6121 	int ret, length;
6122 
6123 	if (!(btrfs_super_incompat_flags(fs_info->super_copy) &
6124 	      BTRFS_FEATURE_INCOMPAT_REMAP_TREE))
6125 		return 0;
6126 
6127 	bg = btrfs_lookup_block_group(fs_info, bytenr);
6128 	if (!bg)
6129 		return 0;
6130 
6131 	mutex_lock(&fs_info->remap_mutex);
6132 
6133 	if (!(bg->flags & BTRFS_BLOCK_GROUP_REMAPPED)) {
6134 		mutex_unlock(&fs_info->remap_mutex);
6135 		btrfs_put_block_group(bg);
6136 		return 0;
6137 	}
6138 
6139 	do {
6140 		key.objectid = bytenr;
6141 		key.type = (u8)-1;
6142 		key.offset = (u64)-1;
6143 
6144 		ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, -1, 1);
6145 		if (ret < 0)
6146 			goto end;
6147 
6148 		leaf = path->nodes[0];
6149 		if (path->slots[0] == 0) {
6150 			ret = -ENOENT;
6151 			goto end;
6152 		}
6153 
6154 		path->slots[0]--;
6155 
6156 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6157 
6158 		if (found_key.type != BTRFS_IDENTITY_REMAP_KEY &&
6159 		    found_key.type != BTRFS_REMAP_KEY) {
6160 			ret = -ENOENT;
6161 			goto end;
6162 		}
6163 
6164 		if (bytenr < found_key.objectid ||
6165 		    bytenr >= found_key.objectid + found_key.offset) {
6166 			ret = -ENOENT;
6167 			goto end;
6168 		}
6169 
6170 		length = remove_range_from_remap_tree(trans, path, bg, bytenr, num_bytes);
6171 		if (length < 0) {
6172 			ret = length;
6173 			goto end;
6174 		}
6175 
6176 		bytenr += length;
6177 		num_bytes -= length;
6178 	} while (num_bytes > 0);
6179 
6180 	ret = 1;
6181 
6182 end:
6183 	mutex_unlock(&fs_info->remap_mutex);
6184 
6185 	btrfs_put_block_group(bg);
6186 	btrfs_release_path(path);
6187 
6188 	return ret;
6189 }
6190