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