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