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