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