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