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