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