Linux 6.10-rc3
[linux-2.6-block.git] / fs / btrfs / relocation.c
CommitLineData
c1d7c514 1// SPDX-License-Identifier: GPL-2.0
5d4f98a2
YZ
2/*
3 * Copyright (C) 2009 Oracle. All rights reserved.
5d4f98a2
YZ
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>
5a0e3ad6 11#include <linux/slab.h>
726a3421 12#include <linux/error-injection.h>
5d4f98a2
YZ
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"
0af3d00b 20#include "free-space-cache.h"
62b99540 21#include "qgroup.h"
cdccee99 22#include "print-tree.h"
86736342 23#include "delalloc-space.h"
aac0023c 24#include "block-group.h"
19b546d7 25#include "backref.h"
e9a28dc5 26#include "misc.h"
c2832898 27#include "subpage.h"
7ae9bd18 28#include "zoned.h"
26c2c454 29#include "inode-item.h"
f1e5c618 30#include "space-info.h"
c7f13d42 31#include "fs.h"
07e81dc9 32#include "accessors.h"
a0231804 33#include "extent-tree.h"
45c40c8f 34#include "root-tree.h"
7c8ede16 35#include "file-item.h"
67707479 36#include "relocation.h"
7f0add25 37#include "super.h"
103c1972 38#include "tree-checker.h"
5d4f98a2 39
0c891389
QW
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
2a979612 87#define RELOCATION_RESERVED_NODES 256
5d4f98a2
YZ
88/*
89 * map address of tree root to tree
90 */
91struct mapping_node {
e9a28dc5
QW
92 struct {
93 struct rb_node rb_node;
94 u64 bytenr;
95 }; /* Use rb_simle_node for search/insert */
5d4f98a2
YZ
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 {
e9a28dc5
QW
108 struct {
109 struct rb_node rb_node;
110 u64 bytenr;
111 }; /* Use rb_simple_node for search/insert */
f7ba2d37 112 u64 owner;
5d4f98a2 113 struct btrfs_key key;
a3bb700f
DS
114 u8 level;
115 bool key_ready;
5d4f98a2
YZ
116};
117
0257bb82
YZ
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;
2672a051 125 u64 owning_root;
0257bb82
YZ
126};
127
8daf07cf
DS
128/* Stages of data relocation. */
129enum reloc_stage {
130 MOVE_DATA_EXTENTS,
131 UPDATE_DATA_PTRS
0257bb82
YZ
132};
133
5d4f98a2
YZ
134struct reloc_control {
135 /* block group to relocate */
32da5386 136 struct btrfs_block_group *block_group;
5d4f98a2
YZ
137 /* extent tree */
138 struct btrfs_root *extent_root;
139 /* inode for moving data */
140 struct inode *data_inode;
3fd0a558
YZ
141
142 struct btrfs_block_rsv *block_rsv;
143
a26195a5 144 struct btrfs_backref_cache backref_cache;
3fd0a558
YZ
145
146 struct file_extent_cluster cluster;
5d4f98a2
YZ
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;
d2311e69
QW
153 /* list of subvolume trees that get relocated */
154 struct list_head dirty_subvol_roots;
3fd0a558
YZ
155 /* size of metadata reservation for merging reloc trees */
156 u64 merging_rsv_size;
157 /* size of relocated tree nodes */
158 u64 nodes_relocated;
0647bf56
WS
159 /* reserved size for block group relocation*/
160 u64 reserved_bytes;
3fd0a558 161
5d4f98a2
YZ
162 u64 search_start;
163 u64 extents_found;
3fd0a558 164
8daf07cf 165 enum reloc_stage stage;
d23d42e3
DS
166 bool create_reloc_tree;
167 bool merge_reloc_tree;
168 bool found_file_extent;
5d4f98a2
YZ
169};
170
9569cc20 171static void mark_block_processed(struct reloc_control *rc,
a26195a5 172 struct btrfs_backref_node *node)
9569cc20
QW
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;
0acd32c2 180 set_extent_bit(&rc->processed_blocks, node->bytenr,
1d126800 181 node->bytenr + blocksize - 1, EXTENT_DIRTY, NULL);
9569cc20
QW
182 }
183 node->processed = 1;
184}
185
5d4f98a2
YZ
186/*
187 * walk up backref nodes until reach node presents tree root
188 */
a26195a5
QW
189static struct btrfs_backref_node *walk_up_backref(
190 struct btrfs_backref_node *node,
191 struct btrfs_backref_edge *edges[], int *index)
5d4f98a2 192{
a26195a5 193 struct btrfs_backref_edge *edge;
5d4f98a2
YZ
194 int idx = *index;
195
196 while (!list_empty(&node->upper)) {
197 edge = list_entry(node->upper.next,
a26195a5 198 struct btrfs_backref_edge, list[LOWER]);
5d4f98a2
YZ
199 edges[idx++] = edge;
200 node = edge->node[UPPER];
201 }
3fd0a558 202 BUG_ON(node->detached);
5d4f98a2
YZ
203 *index = idx;
204 return node;
205}
206
207/*
208 * walk down backref nodes to find start of next reference path
209 */
a26195a5
QW
210static struct btrfs_backref_node *walk_down_backref(
211 struct btrfs_backref_edge *edges[], int *index)
5d4f98a2 212{
a26195a5
QW
213 struct btrfs_backref_edge *edge;
214 struct btrfs_backref_node *lower;
5d4f98a2
YZ
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,
a26195a5 225 struct btrfs_backref_edge, list[LOWER]);
5d4f98a2
YZ
226 edges[idx - 1] = edge;
227 *index = idx;
228 return edge->node[UPPER];
229 }
230 *index = 0;
231 return NULL;
232}
5d4f98a2 233
a26195a5
QW
234static void update_backref_node(struct btrfs_backref_cache *cache,
235 struct btrfs_backref_node *node, u64 bytenr)
3fd0a558
YZ
236{
237 struct rb_node *rb_node;
238 rb_erase(&node->rb_node, &cache->rb_root);
239 node->bytenr = bytenr;
e9a28dc5 240 rb_node = rb_simple_insert(&cache->rb_root, node->bytenr, &node->rb_node);
43c04fb1 241 if (rb_node)
982c92cb 242 btrfs_backref_panic(cache->fs_info, bytenr, -EEXIST);
3fd0a558
YZ
243}
244
245/*
246 * update backref cache after a transaction commit
247 */
248static int update_backref_cache(struct btrfs_trans_handle *trans,
a26195a5 249 struct btrfs_backref_cache *cache)
3fd0a558 250{
a26195a5 251 struct btrfs_backref_node *node;
3fd0a558
YZ
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,
a26195a5 269 struct btrfs_backref_node, list);
023acb07 270 btrfs_backref_cleanup_node(cache, node);
3fd0a558
YZ
271 }
272
273 while (!list_empty(&cache->changed)) {
274 node = list_entry(cache->changed.next,
a26195a5 275 struct btrfs_backref_node, list);
3fd0a558
YZ
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
ab7c8bbf 298static bool reloc_root_is_dead(const struct btrfs_root *root)
6282675e
QW
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
55465730
QW
316 * from no reloc root. But btrfs_should_ignore_reloc_root() below is a
317 * special case.
6282675e 318 */
ab7c8bbf 319static bool have_reloc_root(const struct btrfs_root *root)
6282675e
QW
320{
321 if (reloc_root_is_dead(root))
322 return false;
323 if (!root->reloc_root)
324 return false;
325 return true;
326}
f2a97a9d 327
ab7c8bbf 328bool btrfs_should_ignore_reloc_root(const struct btrfs_root *root)
3fd0a558
YZ
329{
330 struct btrfs_root *reloc_root;
331
92a7cc42 332 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
32f2abca 333 return false;
3fd0a558 334
6282675e
QW
335 /* This root has been merged with its reloc tree, we can ignore it */
336 if (reloc_root_is_dead(root))
32f2abca 337 return true;
6282675e 338
3fd0a558
YZ
339 reloc_root = root->reloc_root;
340 if (!reloc_root)
32f2abca 341 return false;
3fd0a558 342
4d4225fc
JB
343 if (btrfs_header_generation(reloc_root->commit_root) ==
344 root->fs_info->running_transaction->transid)
32f2abca 345 return false;
3fd0a558 346 /*
32f2abca
DS
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.
3fd0a558 350 */
32f2abca 351 return true;
3fd0a558 352}
55465730 353
5d4f98a2
YZ
354/*
355 * find reloc tree by address of tree root
356 */
2433bea5 357struct btrfs_root *find_reloc_root(struct btrfs_fs_info *fs_info, u64 bytenr)
5d4f98a2 358{
2433bea5 359 struct reloc_control *rc = fs_info->reloc_ctl;
5d4f98a2
YZ
360 struct rb_node *rb_node;
361 struct mapping_node *node;
362 struct btrfs_root *root = NULL;
363
2433bea5 364 ASSERT(rc);
5d4f98a2 365 spin_lock(&rc->reloc_root_tree.lock);
e9a28dc5 366 rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root, bytenr);
5d4f98a2
YZ
367 if (rb_node) {
368 node = rb_entry(rb_node, struct mapping_node, rb_node);
0d031dc4 369 root = node->data;
5d4f98a2
YZ
370 }
371 spin_unlock(&rc->reloc_root_tree.lock);
00246528 372 return btrfs_grab_root(root);
5d4f98a2
YZ
373}
374
29db137b
QW
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,
a26195a5 389 struct btrfs_backref_node *node)
29db137b 390{
a26195a5 391 struct btrfs_backref_cache *cache = &rc->backref_cache;
29db137b
QW
392 struct list_head *useless_node = &cache->useless_node;
393 bool ret = false;
394
395 while (!list_empty(useless_node)) {
a26195a5 396 struct btrfs_backref_node *cur;
29db137b 397
a26195a5 398 cur = list_first_entry(useless_node, struct btrfs_backref_node,
29db137b
QW
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)) {
a26195a5
QW
416 struct btrfs_backref_edge *edge;
417 struct btrfs_backref_node *lower;
29db137b
QW
418
419 edge = list_entry(cur->lower.next,
a26195a5 420 struct btrfs_backref_edge, list[UPPER]);
29db137b
QW
421 list_del(&edge->list[UPPER]);
422 list_del(&edge->list[LOWER]);
423 lower = edge->node[LOWER];
741188d3 424 btrfs_backref_free_edge(cache, edge);
29db137b
QW
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);
741188d3 443 btrfs_backref_free_node(cache, cur);
29db137b
QW
444 }
445 }
446 return ret;
447}
448
e7d571c7
QW
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 */
a26195a5 463static noinline_for_stack struct btrfs_backref_node *build_backref_tree(
eb96e221 464 struct btrfs_trans_handle *trans,
e7d571c7
QW
465 struct reloc_control *rc, struct btrfs_key *node_key,
466 int level, u64 bytenr)
467{
468 struct btrfs_backref_iter *iter;
a26195a5 469 struct btrfs_backref_cache *cache = &rc->backref_cache;
e7d571c7
QW
470 /* For searching parent of TREE_BLOCK_REF */
471 struct btrfs_path *path;
a26195a5 472 struct btrfs_backref_node *cur;
a26195a5
QW
473 struct btrfs_backref_node *node = NULL;
474 struct btrfs_backref_edge *edge;
e7d571c7 475 int ret;
5d4f98a2 476
d68194b2 477 iter = btrfs_backref_iter_alloc(rc->extent_root->fs_info);
e7d571c7
QW
478 if (!iter)
479 return ERR_PTR(-ENOMEM);
480 path = btrfs_alloc_path();
481 if (!path) {
2daca1e4 482 ret = -ENOMEM;
e7d571c7
QW
483 goto out;
484 }
485
b1818dab 486 node = btrfs_backref_alloc_node(cache, bytenr, level);
e7d571c7 487 if (!node) {
2daca1e4 488 ret = -ENOMEM;
e7d571c7 489 goto out;
5d4f98a2
YZ
490 }
491
e7d571c7
QW
492 node->lowest = 1;
493 cur = node;
494
495 /* Breadth-first search to build backref cache */
496 do {
eb96e221
FM
497 ret = btrfs_backref_add_tree_node(trans, cache, path, iter,
498 node_key, cur);
2daca1e4 499 if (ret < 0)
e7d571c7 500 goto out;
2daca1e4 501
e7d571c7 502 edge = list_first_entry_or_null(&cache->pending_edge,
a26195a5 503 struct btrfs_backref_edge, list[UPPER]);
e7d571c7
QW
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
1f872924 514 /* Finish the upper linkage of newly added edges/nodes */
fc997ed0 515 ret = btrfs_backref_finish_upper_links(cache, node);
2daca1e4 516 if (ret < 0)
1f872924 517 goto out;
5d4f98a2 518
29db137b
QW
519 if (handle_useless_nodes(rc, node))
520 node = NULL;
5d4f98a2 521out:
56430c14
DS
522 btrfs_free_path(iter->path);
523 kfree(iter);
71f572a9 524 btrfs_free_path(path);
2daca1e4 525 if (ret) {
1b23ea18 526 btrfs_backref_error_cleanup(cache, node);
2daca1e4 527 return ERR_PTR(ret);
5d4f98a2 528 }
75bfb9af 529 ASSERT(!node || !node->detached);
84780289
QW
530 ASSERT(list_empty(&cache->useless_node) &&
531 list_empty(&cache->pending_edge));
5d4f98a2
YZ
532 return node;
533}
534
3fd0a558
YZ
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,
ab7c8bbf 542 const struct btrfs_root *src,
3fd0a558
YZ
543 struct btrfs_root *dest)
544{
545 struct btrfs_root *reloc_root = src->reloc_root;
a26195a5
QW
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;
3fd0a558
YZ
551 struct rb_node *rb_node;
552
553 if (cache->last_trans > 0)
554 update_backref_cache(trans, cache);
555
e9a28dc5 556 rb_node = rb_simple_search(&cache->rb_root, src->commit_root->start);
3fd0a558 557 if (rb_node) {
a26195a5 558 node = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
3fd0a558
YZ
559 if (node->detached)
560 node = NULL;
561 else
562 BUG_ON(node->new_bytenr != reloc_root->node->start);
563 }
564
565 if (!node) {
e9a28dc5
QW
566 rb_node = rb_simple_search(&cache->rb_root,
567 reloc_root->commit_root->start);
3fd0a558 568 if (rb_node) {
a26195a5 569 node = rb_entry(rb_node, struct btrfs_backref_node,
3fd0a558
YZ
570 rb_node);
571 BUG_ON(node->detached);
572 }
573 }
574
575 if (!node)
576 return 0;
577
b1818dab
QW
578 new_node = btrfs_backref_alloc_node(cache, dest->node->start,
579 node->level);
3fd0a558
YZ
580 if (!new_node)
581 return -ENOMEM;
582
3fd0a558 583 new_node->lowest = node->lowest;
6848ad64 584 new_node->checked = 1;
00246528 585 new_node->root = btrfs_grab_root(dest);
0b530bc5 586 ASSERT(new_node->root);
3fd0a558
YZ
587
588 if (!node->lowest) {
589 list_for_each_entry(edge, &node->lower, list[UPPER]) {
47254d07 590 new_edge = btrfs_backref_alloc_edge(cache);
3fd0a558
YZ
591 if (!new_edge)
592 goto fail;
593
f39911e5
QW
594 btrfs_backref_link_edge(new_edge, edge->node[LOWER],
595 new_node, LINK_UPPER);
3fd0a558 596 }
76b9e23d
MX
597 } else {
598 list_add_tail(&new_node->lower, &cache->leaves);
3fd0a558
YZ
599 }
600
e9a28dc5
QW
601 rb_node = rb_simple_insert(&cache->rb_root, new_node->bytenr,
602 &new_node->rb_node);
43c04fb1 603 if (rb_node)
982c92cb 604 btrfs_backref_panic(trans->fs_info, new_node->bytenr, -EEXIST);
3fd0a558
YZ
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,
a26195a5 616 struct btrfs_backref_edge, list[UPPER]);
3fd0a558 617 list_del(&new_edge->list[UPPER]);
741188d3 618 btrfs_backref_free_edge(cache, new_edge);
3fd0a558 619 }
741188d3 620 btrfs_backref_free_node(cache, new_node);
3fd0a558
YZ
621 return -ENOMEM;
622}
623
5d4f98a2
YZ
624/*
625 * helper to add 'address of tree root -> reloc tree' mapping
626 */
203f6a87 627static int __add_reloc_root(struct btrfs_root *root)
5d4f98a2 628{
0b246afa 629 struct btrfs_fs_info *fs_info = root->fs_info;
5d4f98a2
YZ
630 struct rb_node *rb_node;
631 struct mapping_node *node;
0b246afa 632 struct reloc_control *rc = fs_info->reloc_ctl;
5d4f98a2
YZ
633
634 node = kmalloc(sizeof(*node), GFP_NOFS);
ffd7b339
JM
635 if (!node)
636 return -ENOMEM;
5d4f98a2 637
ea287ab1 638 node->bytenr = root->commit_root->start;
5d4f98a2
YZ
639 node->data = root;
640
641 spin_lock(&rc->reloc_root_tree.lock);
e9a28dc5
QW
642 rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
643 node->bytenr, &node->rb_node);
5d4f98a2 644 spin_unlock(&rc->reloc_root_tree.lock);
ffd7b339 645 if (rb_node) {
57a304cf 646 btrfs_err(fs_info,
5d163e0e
JM
647 "Duplicate root found for start=%llu while inserting into relocation tree",
648 node->bytenr);
57a304cf 649 return -EEXIST;
ffd7b339 650 }
5d4f98a2
YZ
651
652 list_add_tail(&root->root_list, &rc->reloc_roots);
653 return 0;
654}
655
656/*
c974c464 657 * helper to delete the 'address of tree root -> reloc tree'
5d4f98a2
YZ
658 * mapping
659 */
c974c464 660static void __del_reloc_root(struct btrfs_root *root)
5d4f98a2 661{
0b246afa 662 struct btrfs_fs_info *fs_info = root->fs_info;
5d4f98a2
YZ
663 struct rb_node *rb_node;
664 struct mapping_node *node = NULL;
0b246afa 665 struct reloc_control *rc = fs_info->reloc_ctl;
f44deb74 666 bool put_ref = false;
5d4f98a2 667
65c6e82b 668 if (rc && root->node) {
389305b2 669 spin_lock(&rc->reloc_root_tree.lock);
e9a28dc5
QW
670 rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
671 root->commit_root->start);
389305b2
QW
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);
ea287ab1 675 RB_CLEAR_NODE(&node->rb_node);
389305b2
QW
676 }
677 spin_unlock(&rc->reloc_root_tree.lock);
c78a10ae 678 ASSERT(!node || (struct btrfs_root *)node->data == root);
5d4f98a2 679 }
5d4f98a2 680
f44deb74
JB
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 */
0b246afa 689 spin_lock(&fs_info->trans_lock);
f44deb74
JB
690 if (!list_empty(&root->root_list)) {
691 put_ref = true;
692 list_del_init(&root->root_list);
693 }
0b246afa 694 spin_unlock(&fs_info->trans_lock);
f44deb74
JB
695 if (put_ref)
696 btrfs_put_root(root);
c974c464
WS
697 kfree(node);
698}
699
700/*
701 * helper to update the 'address of tree root -> reloc tree'
702 * mapping
703 */
ea287ab1 704static int __update_reloc_root(struct btrfs_root *root)
c974c464 705{
0b246afa 706 struct btrfs_fs_info *fs_info = root->fs_info;
c974c464
WS
707 struct rb_node *rb_node;
708 struct mapping_node *node = NULL;
0b246afa 709 struct reloc_control *rc = fs_info->reloc_ctl;
c974c464
WS
710
711 spin_lock(&rc->reloc_root_tree.lock);
e9a28dc5
QW
712 rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
713 root->commit_root->start);
c974c464
WS
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);
5d4f98a2 717 }
c974c464
WS
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);
ea287ab1 725 node->bytenr = root->node->start;
e9a28dc5
QW
726 rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root,
727 node->bytenr, &node->rb_node);
c974c464
WS
728 spin_unlock(&rc->reloc_root_tree.lock);
729 if (rb_node)
982c92cb 730 btrfs_backref_panic(fs_info, node->bytenr, -EEXIST);
5d4f98a2
YZ
731 return 0;
732}
733
3fd0a558
YZ
734static struct btrfs_root *create_reloc_root(struct btrfs_trans_handle *trans,
735 struct btrfs_root *root, u64 objectid)
5d4f98a2 736{
0b246afa 737 struct btrfs_fs_info *fs_info = root->fs_info;
5d4f98a2
YZ
738 struct btrfs_root *reloc_root;
739 struct extent_buffer *eb;
740 struct btrfs_root_item *root_item;
741 struct btrfs_key root_key;
84c50ba5
JB
742 int ret = 0;
743 bool must_abort = false;
5d4f98a2 744
5d4f98a2 745 root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
84c50ba5
JB
746 if (!root_item)
747 return ERR_PTR(-ENOMEM);
5d4f98a2
YZ
748
749 root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
750 root_key.type = BTRFS_ROOT_ITEM_KEY;
3fd0a558 751 root_key.offset = objectid;
5d4f98a2 752
e094f480 753 if (btrfs_root_id(root) == objectid) {
054570a1
FM
754 u64 commit_root_gen;
755
3fd0a558
YZ
756 /* called by btrfs_init_reloc_root */
757 ret = btrfs_copy_root(trans, root, root->commit_root, &eb,
758 BTRFS_TREE_RELOC_OBJECTID);
84c50ba5
JB
759 if (ret)
760 goto fail;
761
054570a1
FM
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);
3fd0a558
YZ
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);
84c50ba5
JB
782 if (ret)
783 goto fail;
3fd0a558 784 }
5d4f98a2 785
84c50ba5
JB
786 /*
787 * We have changed references at this point, we must abort the
788 * transaction if anything fails.
789 */
790 must_abort = true;
791
5d4f98a2 792 memcpy(root_item, &root->root_item, sizeof(*root_item));
5d4f98a2
YZ
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);
3fd0a558 796
e094f480 797 if (btrfs_root_id(root) == objectid) {
3fd0a558
YZ
798 btrfs_set_root_refs(root_item, 0);
799 memset(&root_item->drop_progress, 0,
800 sizeof(struct btrfs_disk_key));
c8422684 801 btrfs_set_root_drop_level(root_item, 0);
3fd0a558 802 }
5d4f98a2
YZ
803
804 btrfs_tree_unlock(eb);
805 free_extent_buffer(eb);
806
0b246afa 807 ret = btrfs_insert_root(trans, fs_info->tree_root,
5d4f98a2 808 &root_key, root_item);
84c50ba5
JB
809 if (ret)
810 goto fail;
811
5d4f98a2
YZ
812 kfree(root_item);
813
3dbf1738 814 reloc_root = btrfs_read_tree_root(fs_info->tree_root, &root_key);
84c50ba5
JB
815 if (IS_ERR(reloc_root)) {
816 ret = PTR_ERR(reloc_root);
817 goto abort;
818 }
92a7cc42 819 set_bit(BTRFS_ROOT_SHAREABLE, &reloc_root->state);
5d4f98a2 820 reloc_root->last_trans = trans->transid;
3fd0a558 821 return reloc_root;
84c50ba5
JB
822fail:
823 kfree(root_item);
824abort:
825 if (must_abort)
826 btrfs_abort_transaction(trans, ret);
827 return ERR_PTR(ret);
3fd0a558
YZ
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.
f44deb74
JB
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.
3fd0a558
YZ
836 */
837int btrfs_init_reloc_root(struct btrfs_trans_handle *trans,
838 struct btrfs_root *root)
839{
0b246afa 840 struct btrfs_fs_info *fs_info = root->fs_info;
3fd0a558 841 struct btrfs_root *reloc_root;
0b246afa 842 struct reloc_control *rc = fs_info->reloc_ctl;
20dd2cbf 843 struct btrfs_block_rsv *rsv;
3fd0a558 844 int clear_rsv = 0;
ffd7b339 845 int ret;
3fd0a558 846
aec7db3b 847 if (!rc)
2abc726a
JB
848 return 0;
849
1fac4a54
QW
850 /*
851 * The subvolume has reloc tree but the swap is finished, no need to
852 * create/update the dead reloc tree
853 */
6282675e 854 if (reloc_root_is_dead(root))
1fac4a54
QW
855 return 0;
856
aec7db3b
JB
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 */
3fd0a558
YZ
865 if (root->reloc_root) {
866 reloc_root = root->reloc_root;
867 reloc_root->last_trans = trans->transid;
868 return 0;
869 }
870
aec7db3b
JB
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 */
e094f480 875 if (!rc->create_reloc_tree || btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
aec7db3b
JB
876 return 0;
877
20dd2cbf
MX
878 if (!trans->reloc_reserved) {
879 rsv = trans->block_rsv;
3fd0a558
YZ
880 trans->block_rsv = rc->block_rsv;
881 clear_rsv = 1;
882 }
e094f480 883 reloc_root = create_reloc_root(trans, root, btrfs_root_id(root));
3fd0a558 884 if (clear_rsv)
20dd2cbf 885 trans->block_rsv = rsv;
00bb36a0
JB
886 if (IS_ERR(reloc_root))
887 return PTR_ERR(reloc_root);
5d4f98a2 888
ffd7b339 889 ret = __add_reloc_root(reloc_root);
57a304cf 890 ASSERT(ret != -EEXIST);
00bb36a0
JB
891 if (ret) {
892 /* Pairs with create_reloc_root */
893 btrfs_put_root(reloc_root);
894 return ret;
895 }
f44deb74 896 root->reloc_root = btrfs_grab_root(reloc_root);
5d4f98a2
YZ
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{
0b246afa 906 struct btrfs_fs_info *fs_info = root->fs_info;
5d4f98a2
YZ
907 struct btrfs_root *reloc_root;
908 struct btrfs_root_item *root_item;
5d4f98a2
YZ
909 int ret;
910
6282675e 911 if (!have_reloc_root(root))
592fbcd5 912 return 0;
5d4f98a2
YZ
913
914 reloc_root = root->reloc_root;
915 root_item = &reloc_root->root_item;
916
f44deb74
JB
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
d2311e69 924 /* root->reloc_root will stay until current relocation finished */
0b246afa 925 if (fs_info->reloc_ctl->merge_reloc_tree &&
3fd0a558 926 btrfs_root_refs(root_item) == 0) {
d2311e69 927 set_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
6282675e
QW
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();
c974c464 933 __del_reloc_root(reloc_root);
5d4f98a2
YZ
934 }
935
5d4f98a2 936 if (reloc_root->commit_root != reloc_root->node) {
ea287ab1 937 __update_reloc_root(reloc_root);
5d4f98a2
YZ
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
0b246afa 943 ret = btrfs_update_root(trans, fs_info->tree_root,
5d4f98a2 944 &reloc_root->root_key, root_item);
f44deb74 945 btrfs_put_root(reloc_root);
592fbcd5 946 return ret;
5d4f98a2
YZ
947}
948
5d4f98a2
YZ
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)->index_cnt;
f85b7379
DS
966 ret = btrfs_lookup_file_extent(NULL, root, path,
967 btrfs_ino(BTRFS_I(reloc_inode)), bytenr, 0);
5d4f98a2
YZ
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)) {
83d4cfd4 985 ret = -EINVAL;
5d4f98a2
YZ
986 goto out;
987 }
988
3fd0a558 989 *new_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5d4f98a2
YZ
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 */
3fd0a558
YZ
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)
5d4f98a2 1005{
0b246afa 1006 struct btrfs_fs_info *fs_info = root->fs_info;
5d4f98a2
YZ
1007 struct btrfs_key key;
1008 struct btrfs_file_extent_item *fi;
5e485ac6 1009 struct btrfs_inode *inode = NULL;
5d4f98a2
YZ
1010 u64 parent;
1011 u64 bytenr;
3fd0a558 1012 u64 new_bytenr = 0;
5d4f98a2
YZ
1013 u64 num_bytes;
1014 u64 end;
1015 u32 nritems;
1016 u32 i;
83d4cfd4 1017 int ret = 0;
5d4f98a2
YZ
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 */
e094f480 1025 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
5d4f98a2
YZ
1026 parent = leaf->start;
1027 else
1028 parent = 0;
1029
1030 nritems = btrfs_header_nritems(leaf);
1031 for (i = 0; i < nritems; i++) {
82fa113f
QW
1032 struct btrfs_ref ref = { 0 };
1033
5d4f98a2
YZ
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;
9569cc20
QW
1046 if (!in_range(bytenr, rc->block_group->start,
1047 rc->block_group->length))
5d4f98a2
YZ
1048 continue;
1049
1050 /*
fb12489b 1051 * if we are modifying block in fs tree, wait for read_folio
5d4f98a2
YZ
1052 * to complete and drop the extent cache
1053 */
e094f480 1054 if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID) {
5d4f98a2 1055 if (first) {
5e485ac6 1056 inode = btrfs_find_first_inode(root, key.objectid);
5d4f98a2 1057 first = 0;
5e485ac6
FM
1058 } else if (inode && btrfs_ino(inode) < key.objectid) {
1059 btrfs_add_delayed_iput(inode);
1060 inode = btrfs_find_first_inode(root, key.objectid);
5d4f98a2 1061 }
5e485ac6 1062 if (inode && btrfs_ino(inode) == key.objectid) {
9c5c9604
JB
1063 struct extent_state *cached_state = NULL;
1064
5d4f98a2
YZ
1065 end = key.offset +
1066 btrfs_file_extent_num_bytes(leaf, fi);
1067 WARN_ON(!IS_ALIGNED(key.offset,
0b246afa
JM
1068 fs_info->sectorsize));
1069 WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
5d4f98a2 1070 end--;
5d6f0e98 1071 /* Take mmap lock to serialize with reflinks. */
5e485ac6 1072 if (!down_read_trylock(&inode->i_mmap_lock))
5d6f0e98 1073 continue;
5e485ac6
FM
1074 ret = try_lock_extent(&inode->io_tree, key.offset,
1075 end, &cached_state);
5d6f0e98 1076 if (!ret) {
5e485ac6 1077 up_read(&inode->i_mmap_lock);
5d4f98a2 1078 continue;
5d6f0e98 1079 }
5d4f98a2 1080
5e485ac6
FM
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);
5d4f98a2
YZ
1085 }
1086 }
1087
1088 ret = get_new_location(rc->data_inode, &new_bytenr,
1089 bytenr, num_bytes);
83d4cfd4
JB
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;
3fd0a558 1096 }
5d4f98a2
YZ
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);
4d09b4e9
JB
1102 ref.action = BTRFS_ADD_DELAYED_REF;
1103 ref.bytenr = new_bytenr;
12390e42 1104 ref.num_bytes = num_bytes;
4d09b4e9 1105 ref.parent = parent;
e094f480 1106 ref.owning_root = btrfs_root_id(root);
f2e69a77
JB
1107 ref.ref_root = btrfs_header_owner(leaf);
1108 btrfs_init_data_ref(&ref, key.objectid, key.offset,
e094f480 1109 btrfs_root_id(root), false);
82fa113f 1110 ret = btrfs_inc_extent_ref(trans, &ref);
83d4cfd4 1111 if (ret) {
66642832 1112 btrfs_abort_transaction(trans, ret);
83d4cfd4
JB
1113 break;
1114 }
5d4f98a2 1115
4d09b4e9
JB
1116 ref.action = BTRFS_DROP_DELAYED_REF;
1117 ref.bytenr = bytenr;
12390e42 1118 ref.num_bytes = num_bytes;
4d09b4e9 1119 ref.parent = parent;
e094f480 1120 ref.owning_root = btrfs_root_id(root);
f2e69a77
JB
1121 ref.ref_root = btrfs_header_owner(leaf);
1122 btrfs_init_data_ref(&ref, key.objectid, key.offset,
e094f480 1123 btrfs_root_id(root), false);
ffd4bb2a 1124 ret = btrfs_free_extent(trans, &ref);
83d4cfd4 1125 if (ret) {
66642832 1126 btrfs_abort_transaction(trans, ret);
83d4cfd4
JB
1127 break;
1128 }
5d4f98a2
YZ
1129 }
1130 if (dirty)
50564b65 1131 btrfs_mark_buffer_dirty(trans, leaf);
3fd0a558 1132 if (inode)
5e485ac6 1133 btrfs_add_delayed_iput(inode);
83d4cfd4 1134 return ret;
5d4f98a2
YZ
1135}
1136
ab7c8bbf
DS
1137static noinline_for_stack int memcmp_node_keys(const struct extent_buffer *eb,
1138 int slot, const struct btrfs_path *path,
1139 int level)
5d4f98a2
YZ
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 */
3fd0a558 1157static noinline_for_stack
3d0174f7 1158int replace_path(struct btrfs_trans_handle *trans, struct reloc_control *rc,
3fd0a558
YZ
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)
5d4f98a2 1162{
0b246afa 1163 struct btrfs_fs_info *fs_info = dest->fs_info;
5d4f98a2
YZ
1164 struct extent_buffer *eb;
1165 struct extent_buffer *parent;
82fa113f 1166 struct btrfs_ref ref = { 0 };
5d4f98a2
YZ
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;
3fd0a558 1174 int cow = 0;
5d4f98a2
YZ
1175 int level;
1176 int ret;
1177 int slot;
1178
e094f480
JB
1179 ASSERT(btrfs_root_id(src) == BTRFS_TREE_RELOC_OBJECTID);
1180 ASSERT(btrfs_root_id(dest) != BTRFS_TREE_RELOC_OBJECTID);
5d4f98a2
YZ
1181
1182 last_snapshot = btrfs_root_last_snapshot(&src->root_item);
3fd0a558 1183again:
5d4f98a2
YZ
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);
5d4f98a2
YZ
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
3fd0a558 1196 if (cow) {
9631e4cc
JB
1197 ret = btrfs_cow_block(trans, dest, eb, NULL, 0, &eb,
1198 BTRFS_NESTING_COW);
45b87c5d
JB
1199 if (ret) {
1200 btrfs_tree_unlock(eb);
1201 free_extent_buffer(eb);
1202 return ret;
1203 }
3fd0a558 1204 }
5d4f98a2
YZ
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);
7a9213a9 1215 ASSERT(level >= lowest_level);
5d4f98a2 1216
fdf8d595 1217 ret = btrfs_bin_search(parent, 0, &key, &slot);
cbca7d59
FM
1218 if (ret < 0)
1219 break;
5d4f98a2
YZ
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);
0b246afa 1227 blocksize = fs_info->nodesize;
5d4f98a2
YZ
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
fae7f21c 1241 if (WARN_ON(new_bytenr > 0 && new_bytenr == old_bytenr)) {
5d4f98a2
YZ
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)) {
3fd0a558 1248 if (level <= lowest_level) {
5d4f98a2
YZ
1249 ret = 0;
1250 break;
1251 }
1252
6b3426be 1253 eb = btrfs_read_node_slot(parent, slot);
64c043de
LB
1254 if (IS_ERR(eb)) {
1255 ret = PTR_ERR(eb);
264813ac 1256 break;
416bc658 1257 }
5d4f98a2 1258 btrfs_tree_lock(eb);
3fd0a558
YZ
1259 if (cow) {
1260 ret = btrfs_cow_block(trans, dest, eb, parent,
9631e4cc
JB
1261 slot, &eb,
1262 BTRFS_NESTING_COW);
45b87c5d
JB
1263 if (ret) {
1264 btrfs_tree_unlock(eb);
1265 free_extent_buffer(eb);
1266 break;
1267 }
5d4f98a2
YZ
1268 }
1269
1270 btrfs_tree_unlock(parent);
1271 free_extent_buffer(parent);
1272
1273 parent = eb;
1274 continue;
1275 }
1276
3fd0a558
YZ
1277 if (!cow) {
1278 btrfs_tree_unlock(parent);
1279 free_extent_buffer(parent);
1280 cow = 1;
1281 goto again;
1282 }
1283
5d4f98a2
YZ
1284 btrfs_node_key_to_cpu(path->nodes[level], &key,
1285 path->slots[level]);
b3b4aa74 1286 btrfs_release_path(path);
5d4f98a2
YZ
1287
1288 path->lowest_level = level;
b40130b2 1289 set_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &src->state);
5d4f98a2 1290 ret = btrfs_search_slot(trans, src, &key, path, 0, 1);
b40130b2 1291 clear_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &src->state);
5d4f98a2 1292 path->lowest_level = 0;
0e9873e2
JB
1293 if (ret) {
1294 if (ret > 0)
1295 ret = -ENOENT;
1296 break;
1297 }
5d4f98a2 1298
824d8dff
QW
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
f616f5cd
QW
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.
824d8dff 1312 */
370a11b8
QW
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;
5d4f98a2
YZ
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);
50564b65 1324 btrfs_mark_buffer_dirty(trans, parent);
5d4f98a2
YZ
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);
50564b65 1330 btrfs_mark_buffer_dirty(trans, path->nodes[level]);
5d4f98a2 1331
4d09b4e9
JB
1332 ref.action = BTRFS_ADD_DELAYED_REF;
1333 ref.bytenr = old_bytenr;
12390e42 1334 ref.num_bytes = blocksize;
4d09b4e9 1335 ref.parent = path->nodes[level]->start;
e094f480
JB
1336 ref.owning_root = btrfs_root_id(src);
1337 ref.ref_root = btrfs_root_id(src);
f2e69a77 1338 btrfs_init_tree_ref(&ref, level - 1, 0, true);
82fa113f 1339 ret = btrfs_inc_extent_ref(trans, &ref);
253e258c
JB
1340 if (ret) {
1341 btrfs_abort_transaction(trans, ret);
1342 break;
1343 }
4d09b4e9
JB
1344
1345 ref.action = BTRFS_ADD_DELAYED_REF;
1346 ref.bytenr = new_bytenr;
12390e42 1347 ref.num_bytes = blocksize;
4d09b4e9 1348 ref.parent = 0;
e094f480
JB
1349 ref.owning_root = btrfs_root_id(dest);
1350 ref.ref_root = btrfs_root_id(dest);
f2e69a77 1351 btrfs_init_tree_ref(&ref, level - 1, 0, true);
82fa113f 1352 ret = btrfs_inc_extent_ref(trans, &ref);
253e258c
JB
1353 if (ret) {
1354 btrfs_abort_transaction(trans, ret);
1355 break;
1356 }
5d4f98a2 1357
457cb1dd 1358 /* We don't know the real owning_root, use 0. */
4d09b4e9
JB
1359 ref.action = BTRFS_DROP_DELAYED_REF;
1360 ref.bytenr = new_bytenr;
12390e42 1361 ref.num_bytes = blocksize;
4d09b4e9
JB
1362 ref.parent = path->nodes[level]->start;
1363 ref.owning_root = 0;
e094f480 1364 ref.ref_root = btrfs_root_id(src);
f2e69a77 1365 btrfs_init_tree_ref(&ref, level - 1, 0, true);
ffd4bb2a 1366 ret = btrfs_free_extent(trans, &ref);
253e258c
JB
1367 if (ret) {
1368 btrfs_abort_transaction(trans, ret);
1369 break;
1370 }
5d4f98a2 1371
457cb1dd 1372 /* We don't know the real owning_root, use 0. */
4d09b4e9
JB
1373 ref.action = BTRFS_DROP_DELAYED_REF;
1374 ref.bytenr = old_bytenr;
12390e42 1375 ref.num_bytes = blocksize;
4d09b4e9
JB
1376 ref.parent = 0;
1377 ref.owning_root = 0;
e094f480 1378 ref.ref_root = btrfs_root_id(dest);
f2e69a77 1379 btrfs_init_tree_ref(&ref, level - 1, 0, true);
ffd4bb2a 1380 ret = btrfs_free_extent(trans, &ref);
253e258c
JB
1381 if (ret) {
1382 btrfs_abort_transaction(trans, ret);
1383 break;
1384 }
5d4f98a2
YZ
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;
5d4f98a2
YZ
1442 u64 ptr_gen = 0;
1443 u64 last_snapshot;
5d4f98a2
YZ
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
8ef385bb
JB
1468 eb = btrfs_read_node_slot(eb, path->slots[i]);
1469 if (IS_ERR(eb))
64c043de 1470 return PTR_ERR(eb);
5d4f98a2
YZ
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,
ab7c8bbf
DS
1483 const struct btrfs_key *min_key,
1484 const struct btrfs_key *max_key)
5d4f98a2 1485{
0b246afa 1486 struct btrfs_fs_info *fs_info = root->fs_info;
5e485ac6 1487 struct btrfs_inode *inode = NULL;
5d4f98a2
YZ
1488 u64 objectid;
1489 u64 start, end;
33345d01 1490 u64 ino;
5d4f98a2
YZ
1491
1492 objectid = min_key->objectid;
1493 while (1) {
9c5c9604
JB
1494 struct extent_state *cached_state = NULL;
1495
5d4f98a2 1496 cond_resched();
5e485ac6
FM
1497 if (inode)
1498 iput(&inode->vfs_inode);
5d4f98a2
YZ
1499
1500 if (objectid > max_key->objectid)
1501 break;
1502
5e485ac6 1503 inode = btrfs_find_first_inode(root, objectid);
5d4f98a2
YZ
1504 if (!inode)
1505 break;
5e485ac6 1506 ino = btrfs_ino(inode);
5d4f98a2 1507
33345d01 1508 if (ino > max_key->objectid) {
5e485ac6 1509 iput(&inode->vfs_inode);
5d4f98a2
YZ
1510 break;
1511 }
1512
33345d01 1513 objectid = ino + 1;
5e485ac6 1514 if (!S_ISREG(inode->vfs_inode.i_mode))
5d4f98a2
YZ
1515 continue;
1516
33345d01 1517 if (unlikely(min_key->objectid == ino)) {
5d4f98a2
YZ
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;
0b246afa 1524 WARN_ON(!IS_ALIGNED(start, fs_info->sectorsize));
5d4f98a2
YZ
1525 }
1526 } else {
1527 start = 0;
1528 }
1529
33345d01 1530 if (unlikely(max_key->objectid == ino)) {
5d4f98a2
YZ
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;
0b246afa 1539 WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
5d4f98a2
YZ
1540 end--;
1541 }
1542 } else {
1543 end = (u64)-1;
1544 }
1545
fb12489b 1546 /* the lock_extent waits for read_folio to complete */
5e485ac6
FM
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);
5d4f98a2
YZ
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
d2311e69
QW
1572/*
1573 * Insert current subvolume into reloc_control::dirty_subvol_roots
1574 */
ac54da6c
JB
1575static int insert_dirty_subvol(struct btrfs_trans_handle *trans,
1576 struct reloc_control *rc,
1577 struct btrfs_root *root)
d2311e69
QW
1578{
1579 struct btrfs_root *reloc_root = root->reloc_root;
1580 struct btrfs_root_item *reloc_root_item;
7934133f 1581 int ret;
d2311e69
QW
1582
1583 /* @root must be a subvolume tree root with a valid reloc tree */
e094f480 1584 ASSERT(btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID);
d2311e69
QW
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));
c8422684 1590 btrfs_set_root_drop_level(reloc_root_item, 0);
d2311e69 1591 btrfs_set_root_refs(reloc_root_item, 0);
7934133f
JB
1592 ret = btrfs_update_reloc_root(trans, root);
1593 if (ret)
1594 return ret;
d2311e69
QW
1595
1596 if (list_empty(&root->reloc_dirty_list)) {
00246528 1597 btrfs_grab_root(root);
d2311e69
QW
1598 list_add_tail(&root->reloc_dirty_list, &rc->dirty_subvol_roots);
1599 }
ac54da6c
JB
1600
1601 return 0;
d2311e69
QW
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;
30d40577 1609 int ret2;
d2311e69
QW
1610
1611 list_for_each_entry_safe(root, next, &rc->dirty_subvol_roots,
1612 reloc_dirty_list) {
e094f480 1613 if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID) {
30d40577
QW
1614 /* Merged subvolume, cleanup its reloc root */
1615 struct btrfs_root *reloc_root = root->reloc_root;
d2311e69 1616
30d40577
QW
1617 list_del_init(&root->reloc_dirty_list);
1618 root->reloc_root = NULL;
6282675e
QW
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();
1fac4a54 1624 clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
f28de8d8 1625 if (reloc_root) {
f44deb74
JB
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 */
f28de8d8 1631 ret2 = btrfs_drop_snapshot(reloc_root, 0, 1);
f44deb74
JB
1632 if (ret2 < 0) {
1633 btrfs_put_root(reloc_root);
1634 if (!ret)
1635 ret = ret2;
1636 }
f28de8d8 1637 }
00246528 1638 btrfs_put_root(root);
30d40577
QW
1639 } else {
1640 /* Orphan reloc tree, just clean it up */
0078a9f9 1641 ret2 = btrfs_drop_snapshot(root, 0, 1);
f44deb74
JB
1642 if (ret2 < 0) {
1643 btrfs_put_root(root);
1644 if (!ret)
1645 ret = ret2;
1646 }
d2311e69 1647 }
d2311e69
QW
1648 }
1649 return ret;
1650}
1651
5d4f98a2
YZ
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{
0b246afa 1659 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
5d4f98a2
YZ
1660 struct btrfs_key key;
1661 struct btrfs_key next_key;
9e6a0c52 1662 struct btrfs_trans_handle *trans = NULL;
5d4f98a2
YZ
1663 struct btrfs_root *reloc_root;
1664 struct btrfs_root_item *root_item;
1665 struct btrfs_path *path;
3fd0a558 1666 struct extent_buffer *leaf;
fca3a45d 1667 int reserve_level;
5d4f98a2
YZ
1668 int level;
1669 int max_level;
1670 int replaced = 0;
c6a592f2 1671 int ret = 0;
3fd0a558 1672 u32 min_reserved;
5d4f98a2
YZ
1673
1674 path = btrfs_alloc_path();
1675 if (!path)
1676 return -ENOMEM;
e4058b54 1677 path->reada = READA_FORWARD;
5d4f98a2
YZ
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);
67439dad 1684 atomic_inc(&reloc_root->node->refs);
5d4f98a2
YZ
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
c8422684 1690 level = btrfs_root_drop_level(root_item);
5d4f98a2
YZ
1691 BUG_ON(level == 0);
1692 path->lowest_level = level;
1693 ret = btrfs_search_slot(NULL, reloc_root, &key, path, 0, 0);
33c66f43 1694 path->lowest_level = 0;
5d4f98a2
YZ
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
44d354ab
QW
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 */
fca3a45d
JB
1715 reserve_level = max_t(int, 1, btrfs_root_level(root_item));
1716 min_reserved = fs_info->nodesize * reserve_level * 2;
3fd0a558 1717 memset(&next_key, 0, sizeof(next_key));
5d4f98a2 1718
3fd0a558 1719 while (1) {
9270501c
JB
1720 ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv,
1721 min_reserved,
44d354ab 1722 BTRFS_RESERVE_FLUSH_LIMIT);
c6a592f2 1723 if (ret)
9e6a0c52 1724 goto out;
9e6a0c52
JB
1725 trans = btrfs_start_transaction(root, 0);
1726 if (IS_ERR(trans)) {
c6a592f2 1727 ret = PTR_ERR(trans);
9e6a0c52
JB
1728 trans = NULL;
1729 goto out;
1730 }
2abc726a
JB
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 reloc_root->last_trans = trans->transid;
9e6a0c52 1743 trans->block_rsv = rc->block_rsv;
5d4f98a2 1744
5d4f98a2 1745 replaced = 0;
5d4f98a2
YZ
1746 max_level = level;
1747
1748 ret = walk_down_reloc_tree(reloc_root, path, &level);
c6a592f2 1749 if (ret < 0)
5d4f98a2 1750 goto out;
5d4f98a2
YZ
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;
5d4f98a2 1757 } else {
3d0174f7 1758 ret = replace_path(trans, rc, root, reloc_root, path,
3fd0a558 1759 &next_key, level, max_level);
5d4f98a2 1760 }
c6a592f2 1761 if (ret < 0)
5d4f98a2 1762 goto out;
5d4f98a2
YZ
1763 if (ret > 0) {
1764 level = ret;
1765 btrfs_node_key_to_cpu(path->nodes[level], &key,
1766 path->slots[level]);
1767 replaced = 1;
5d4f98a2
YZ
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]);
c8422684 1781 btrfs_set_root_drop_level(root_item, level);
5d4f98a2 1782
3a45bb20 1783 btrfs_end_transaction_throttle(trans);
9e6a0c52 1784 trans = NULL;
5d4f98a2 1785
2ff7e61e 1786 btrfs_btree_balance_dirty(fs_info);
5d4f98a2
YZ
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);
9631e4cc
JB
1797 ret = btrfs_cow_block(trans, root, leaf, NULL, 0, &leaf,
1798 BTRFS_NESTING_COW);
5d4f98a2
YZ
1799 btrfs_tree_unlock(leaf);
1800 free_extent_buffer(leaf);
5d4f98a2
YZ
1801out:
1802 btrfs_free_path(path);
1803
ac54da6c
JB
1804 if (ret == 0) {
1805 ret = insert_dirty_subvol(trans, rc, root);
1806 if (ret)
1807 btrfs_abort_transaction(trans, ret);
1808 }
5d4f98a2 1809
9e6a0c52 1810 if (trans)
3a45bb20 1811 btrfs_end_transaction_throttle(trans);
5d4f98a2 1812
2ff7e61e 1813 btrfs_btree_balance_dirty(fs_info);
5d4f98a2 1814
5d4f98a2
YZ
1815 if (replaced && rc->stage == UPDATE_DATA_PTRS)
1816 invalidate_extent_cache(root, &key, &next_key);
1817
c6a592f2 1818 return ret;
5d4f98a2
YZ
1819}
1820
3fd0a558
YZ
1821static noinline_for_stack
1822int prepare_to_merge(struct reloc_control *rc, int err)
5d4f98a2 1823{
3fd0a558 1824 struct btrfs_root *root = rc->extent_root;
0b246afa 1825 struct btrfs_fs_info *fs_info = root->fs_info;
5d4f98a2 1826 struct btrfs_root *reloc_root;
3fd0a558
YZ
1827 struct btrfs_trans_handle *trans;
1828 LIST_HEAD(reloc_roots);
1829 u64 num_bytes = 0;
1830 int ret;
3fd0a558 1831
0b246afa
JM
1832 mutex_lock(&fs_info->reloc_mutex);
1833 rc->merging_rsv_size += fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
3fd0a558 1834 rc->merging_rsv_size += rc->nodes_relocated * 2;
0b246afa 1835 mutex_unlock(&fs_info->reloc_mutex);
7585717f 1836
3fd0a558
YZ
1837again:
1838 if (!err) {
1839 num_bytes = rc->merging_rsv_size;
9270501c 1840 ret = btrfs_block_rsv_add(fs_info, rc->block_rsv, num_bytes,
08e007d2 1841 BTRFS_RESERVE_FLUSH_ALL);
3fd0a558
YZ
1842 if (ret)
1843 err = ret;
1844 }
1845
7a7eaa40 1846 trans = btrfs_join_transaction(rc->extent_root);
3612b495
TI
1847 if (IS_ERR(trans)) {
1848 if (!err)
2ff7e61e 1849 btrfs_block_rsv_release(fs_info, rc->block_rsv,
63f018be 1850 num_bytes, NULL);
3612b495
TI
1851 return PTR_ERR(trans);
1852 }
3fd0a558
YZ
1853
1854 if (!err) {
1855 if (num_bytes != rc->merging_rsv_size) {
3a45bb20 1856 btrfs_end_transaction(trans);
2ff7e61e 1857 btrfs_block_rsv_release(fs_info, rc->block_rsv,
63f018be 1858 num_bytes, NULL);
3fd0a558
YZ
1859 goto again;
1860 }
1861 }
5d4f98a2 1862
d23d42e3 1863 rc->merge_reloc_tree = true;
3fd0a558
YZ
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);
5d4f98a2 1869
a820feb5
DS
1870 root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
1871 false);
e0b085b0
JB
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 }
05d7ce50
QW
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",
e094f480
JB
1888 btrfs_root_id(root),
1889 btrfs_root_id(root->reloc_root),
05d7ce50
QW
1890 root->reloc_root->root_key.type,
1891 root->reloc_root->root_key.offset,
1892 btrfs_root_generation(
1893 &root->reloc_root->root_item),
e094f480 1894 btrfs_root_id(reloc_root),
05d7ce50
QW
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",
e094f480
JB
1902 btrfs_root_id(root),
1903 btrfs_root_id(reloc_root),
05d7ce50
QW
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 }
5d4f98a2 1916
3fd0a558
YZ
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);
bbae13f8 1923 ret = btrfs_update_reloc_root(trans, root);
5d4f98a2 1924
bbae13f8
JB
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 */
3fd0a558 1929 list_add(&reloc_root->root_list, &reloc_roots);
00246528 1930 btrfs_put_root(root);
bbae13f8
JB
1931
1932 if (ret) {
1933 btrfs_abort_transaction(trans, ret);
1934 if (!err)
1935 err = ret;
1936 break;
1937 }
3fd0a558 1938 }
5d4f98a2 1939
3fd0a558 1940 list_splice(&reloc_roots, &rc->reloc_roots);
5d4f98a2 1941
3fd0a558 1942 if (!err)
fb686c68 1943 err = btrfs_commit_transaction(trans);
3fd0a558 1944 else
3a45bb20 1945 btrfs_end_transaction(trans);
3fd0a558 1946 return err;
5d4f98a2
YZ
1947}
1948
aca1bba6
LB
1949static noinline_for_stack
1950void free_reloc_roots(struct list_head *list)
1951{
a7571232 1952 struct btrfs_root *reloc_root, *tmp;
aca1bba6 1953
a7571232 1954 list_for_each_entry_safe(reloc_root, tmp, list, root_list)
bb166d72 1955 __del_reloc_root(reloc_root);
aca1bba6
LB
1956}
1957
3fd0a558 1958static noinline_for_stack
94404e82 1959void merge_reloc_roots(struct reloc_control *rc)
5d4f98a2 1960{
0b246afa 1961 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
5d4f98a2 1962 struct btrfs_root *root;
3fd0a558
YZ
1963 struct btrfs_root *reloc_root;
1964 LIST_HEAD(reloc_roots);
1965 int found = 0;
aca1bba6 1966 int ret = 0;
3fd0a558
YZ
1967again:
1968 root = rc->extent_root;
7585717f
CM
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 */
0b246afa 1976 mutex_lock(&fs_info->reloc_mutex);
3fd0a558 1977 list_splice_init(&rc->reloc_roots, &reloc_roots);
0b246afa 1978 mutex_unlock(&fs_info->reloc_mutex);
5d4f98a2 1979
3fd0a558
YZ
1980 while (!list_empty(&reloc_roots)) {
1981 found = 1;
1982 reloc_root = list_entry(reloc_roots.next,
1983 struct btrfs_root, root_list);
5d4f98a2 1984
a820feb5
DS
1985 root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
1986 false);
3fd0a558 1987 if (btrfs_root_refs(&reloc_root->root_item) > 0) {
05d7ce50 1988 if (WARN_ON(IS_ERR(root))) {
24213fa4
JB
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 */
24213fa4
JB
1997 ret = PTR_ERR(root);
1998 goto out;
1999 }
05d7ce50 2000 if (WARN_ON(root->reloc_root != reloc_root)) {
24213fa4 2001 /*
05d7ce50
QW
2002 * This can happen if on-disk metadata has some
2003 * corruption, e.g. bad reloc tree key offset.
24213fa4 2004 */
24213fa4
JB
2005 ret = -EINVAL;
2006 goto out;
2007 }
3fd0a558 2008 ret = merge_reloc_root(rc, root);
00246528 2009 btrfs_put_root(root);
b37b39cd 2010 if (ret) {
25e293c2
WS
2011 if (list_empty(&reloc_root->root_list))
2012 list_add_tail(&reloc_root->root_list,
2013 &reloc_roots);
aca1bba6 2014 goto out;
b37b39cd 2015 }
3fd0a558 2016 } else {
51415b6c
QW
2017 if (!IS_ERR(root)) {
2018 if (root->reloc_root == reloc_root) {
2019 root->reloc_root = NULL;
2020 btrfs_put_root(reloc_root);
2021 }
1dae7e0e
QW
2022 clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE,
2023 &root->state);
51415b6c
QW
2024 btrfs_put_root(root);
2025 }
2026
3fd0a558 2027 list_del_init(&reloc_root->root_list);
30d40577
QW
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);
3fd0a558 2031 }
5d4f98a2
YZ
2032 }
2033
3fd0a558
YZ
2034 if (found) {
2035 found = 0;
2036 goto again;
2037 }
aca1bba6
LB
2038out:
2039 if (ret) {
0b246afa 2040 btrfs_handle_fs_error(fs_info, ret, NULL);
a7571232 2041 free_reloc_roots(&reloc_roots);
467bb1d2
WS
2042
2043 /* new reloc root may be added */
0b246afa 2044 mutex_lock(&fs_info->reloc_mutex);
467bb1d2 2045 list_splice_init(&rc->reloc_roots, &reloc_roots);
0b246afa 2046 mutex_unlock(&fs_info->reloc_mutex);
a7571232 2047 free_reloc_roots(&reloc_roots);
aca1bba6
LB
2048 }
2049
7b7b7431
JB
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 */
5d4f98a2
YZ
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{
0b246afa 2081 struct btrfs_fs_info *fs_info = reloc_root->fs_info;
5d4f98a2 2082 struct btrfs_root *root;
442b1ac5 2083 int ret;
5d4f98a2
YZ
2084
2085 if (reloc_root->last_trans == trans->transid)
2086 return 0;
2087
a820feb5 2088 root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset, false);
404bccbc
JB
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 }
442b1ac5 2110 ret = btrfs_record_root_in_trans(trans, root);
00246528 2111 btrfs_put_root(root);
5d4f98a2 2112
442b1ac5 2113 return ret;
5d4f98a2
YZ
2114}
2115
3fd0a558
YZ
2116static noinline_for_stack
2117struct btrfs_root *select_reloc_root(struct btrfs_trans_handle *trans,
2118 struct reloc_control *rc,
a26195a5
QW
2119 struct btrfs_backref_node *node,
2120 struct btrfs_backref_edge *edges[])
5d4f98a2 2121{
a26195a5 2122 struct btrfs_backref_node *next;
5d4f98a2 2123 struct btrfs_root *root;
3fd0a558 2124 int index = 0;
92de551b 2125 int ret;
3fd0a558 2126
5d4f98a2
YZ
2127 next = node;
2128 while (1) {
2129 cond_resched();
2130 next = walk_up_backref(next, edges, &index);
2131 root = next->root;
8ee66afe
JB
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 }
5d4f98a2 2159
e094f480 2160 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID) {
92de551b
JB
2161 ret = record_reloc_root_in_trans(trans, root);
2162 if (ret)
2163 return ERR_PTR(ret);
5d4f98a2
YZ
2164 break;
2165 }
2166
92de551b
JB
2167 ret = btrfs_record_root_in_trans(trans, root);
2168 if (ret)
2169 return ERR_PTR(ret);
3fd0a558
YZ
2170 root = root->reloc_root;
2171
39200e59
JB
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
3fd0a558 2179 if (next->new_bytenr != root->node->start) {
8ee66afe
JB
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
3fd0a558 2196 next->new_bytenr = root->node->start;
00246528
JB
2197 btrfs_put_root(next->root);
2198 next->root = btrfs_grab_root(root);
0b530bc5 2199 ASSERT(next->root);
3fd0a558
YZ
2200 list_add_tail(&next->list,
2201 &rc->backref_cache.changed);
9569cc20 2202 mark_block_processed(rc, next);
5d4f98a2
YZ
2203 break;
2204 }
2205
3fd0a558 2206 WARN_ON(1);
5d4f98a2
YZ
2207 root = NULL;
2208 next = walk_down_backref(edges, &index);
2209 if (!next || next->level <= node->level)
2210 break;
2211 }
cbdc2ebc
JB
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 }
5d4f98a2 2220
3fd0a558
YZ
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];
5d4f98a2 2228 }
5d4f98a2
YZ
2229 return root;
2230}
2231
3fd0a558 2232/*
92a7cc42
QW
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.
3fd0a558 2240 */
5d4f98a2 2241static noinline_for_stack
a26195a5 2242struct btrfs_root *select_one_root(struct btrfs_backref_node *node)
5d4f98a2 2243{
a26195a5 2244 struct btrfs_backref_node *next;
3fd0a558
YZ
2245 struct btrfs_root *root;
2246 struct btrfs_root *fs_root = NULL;
a26195a5 2247 struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
3fd0a558
YZ
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;
8717cf44
JB
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);
3fd0a558 2262
92a7cc42
QW
2263 /* No other choice for non-shareable tree */
2264 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
3fd0a558
YZ
2265 return root;
2266
e094f480 2267 if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID)
3fd0a558
YZ
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;
5d4f98a2
YZ
2281}
2282
30704a0d
NA
2283static noinline_for_stack u64 calcu_metadata_size(struct reloc_control *rc,
2284 struct btrfs_backref_node *node)
5d4f98a2 2285{
0b246afa 2286 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
a26195a5
QW
2287 struct btrfs_backref_node *next = node;
2288 struct btrfs_backref_edge *edge;
2289 struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
3fd0a558
YZ
2290 u64 num_bytes = 0;
2291 int index = 0;
2292
30704a0d 2293 BUG_ON(node->processed);
3fd0a558
YZ
2294
2295 while (next) {
2296 cond_resched();
2297 while (1) {
30704a0d 2298 if (next->processed)
3fd0a558
YZ
2299 break;
2300
0b246afa 2301 num_bytes += fs_info->nodesize;
3fd0a558
YZ
2302
2303 if (list_empty(&next->upper))
2304 break;
2305
2306 edge = list_entry(next->upper.next,
a26195a5 2307 struct btrfs_backref_edge, list[LOWER]);
3fd0a558
YZ
2308 edges[index++] = edge;
2309 next = edge->node[UPPER];
2310 }
2311 next = walk_down_backref(edges, &index);
2312 }
2313 return num_bytes;
5d4f98a2
YZ
2314}
2315
3fd0a558
YZ
2316static int reserve_metadata_space(struct btrfs_trans_handle *trans,
2317 struct reloc_control *rc,
a26195a5 2318 struct btrfs_backref_node *node)
5d4f98a2 2319{
3fd0a558 2320 struct btrfs_root *root = rc->extent_root;
da17066c 2321 struct btrfs_fs_info *fs_info = root->fs_info;
3fd0a558
YZ
2322 u64 num_bytes;
2323 int ret;
0647bf56 2324 u64 tmp;
3fd0a558 2325
30704a0d 2326 num_bytes = calcu_metadata_size(rc, node) * 2;
5d4f98a2 2327
3fd0a558 2328 trans->block_rsv = rc->block_rsv;
0647bf56 2329 rc->reserved_bytes += num_bytes;
8ca17f0f
JB
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 */
9270501c
JB
2336 ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv, num_bytes,
2337 BTRFS_RESERVE_FLUSH_LIMIT);
3fd0a558 2338 if (ret) {
da17066c 2339 tmp = fs_info->nodesize * RELOCATION_RESERVED_NODES;
8ca17f0f
JB
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
52042d8e 2346 * space for relocation and we will return earlier in
8ca17f0f
JB
2347 * enospc case.
2348 */
da17066c
JM
2349 rc->block_rsv->size = tmp + fs_info->nodesize *
2350 RELOCATION_RESERVED_NODES;
8ca17f0f 2351 return -EAGAIN;
5d4f98a2 2352 }
3fd0a558 2353
3fd0a558
YZ
2354 return 0;
2355}
2356
5d4f98a2
YZ
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,
3fd0a558 2365 struct reloc_control *rc,
a26195a5 2366 struct btrfs_backref_node *node,
5d4f98a2
YZ
2367 struct btrfs_key *key,
2368 struct btrfs_path *path, int lowest)
2369{
a26195a5
QW
2370 struct btrfs_backref_node *upper;
2371 struct btrfs_backref_edge *edge;
2372 struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
5d4f98a2
YZ
2373 struct btrfs_root *root;
2374 struct extent_buffer *eb;
2375 u32 blocksize;
2376 u64 bytenr;
5d4f98a2 2377 int slot;
8df01fdd 2378 int ret = 0;
5d4f98a2 2379
ffe30dd8
JB
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);
5d4f98a2
YZ
2385
2386 path->lowest_level = node->level + 1;
3fd0a558 2387 rc->backref_cache.path[node->level] = node;
5d4f98a2
YZ
2388 list_for_each_entry(edge, &node->upper, list[LOWER]) {
2389 cond_resched();
5d4f98a2
YZ
2390
2391 upper = edge->node[UPPER];
dc4103f9 2392 root = select_reloc_root(trans, rc, upper, edges);
cbdc2ebc
JB
2393 if (IS_ERR(root)) {
2394 ret = PTR_ERR(root);
2395 goto next;
2396 }
3fd0a558
YZ
2397
2398 if (upper->eb && !upper->locked) {
2399 if (!lowest) {
fdf8d595 2400 ret = btrfs_bin_search(upper->eb, 0, key, &slot);
8df01fdd 2401 if (ret < 0)
cbca7d59 2402 goto next;
3fd0a558
YZ
2403 BUG_ON(ret);
2404 bytenr = btrfs_node_blockptr(upper->eb, slot);
2405 if (node->eb->start == bytenr)
2406 goto next;
2407 }
b0fe7078 2408 btrfs_backref_drop_node_buffer(upper);
3fd0a558 2409 }
5d4f98a2
YZ
2410
2411 if (!upper->eb) {
2412 ret = btrfs_search_slot(trans, root, key, path, 0, 1);
3561b9db 2413 if (ret) {
8df01fdd
NB
2414 if (ret > 0)
2415 ret = -ENOENT;
3561b9db
LB
2416
2417 btrfs_release_path(path);
5d4f98a2
YZ
2418 break;
2419 }
5d4f98a2 2420
3fd0a558
YZ
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 }
5d4f98a2 2427
3fd0a558
YZ
2428 upper->locked = 1;
2429 path->locks[upper->level] = 0;
5d4f98a2 2430
3fd0a558 2431 slot = path->slots[upper->level];
b3b4aa74 2432 btrfs_release_path(path);
5d4f98a2 2433 } else {
fdf8d595 2434 ret = btrfs_bin_search(upper->eb, 0, key, &slot);
8df01fdd 2435 if (ret < 0)
cbca7d59 2436 goto next;
5d4f98a2
YZ
2437 BUG_ON(ret);
2438 }
2439
2440 bytenr = btrfs_node_blockptr(upper->eb, slot);
3fd0a558 2441 if (lowest) {
4547f4d8
LB
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);
8df01fdd 2447 ret = -EIO;
4547f4d8
LB
2448 goto next;
2449 }
5d4f98a2 2450 } else {
3fd0a558
YZ
2451 if (node->eb->start == bytenr)
2452 goto next;
5d4f98a2
YZ
2453 }
2454
da17066c 2455 blocksize = root->fs_info->nodesize;
c9752536 2456 eb = btrfs_read_node_slot(upper->eb, slot);
64c043de 2457 if (IS_ERR(eb)) {
8df01fdd 2458 ret = PTR_ERR(eb);
64c043de 2459 goto next;
97d9a8a4 2460 }
5d4f98a2 2461 btrfs_tree_lock(eb);
5d4f98a2
YZ
2462
2463 if (!node->eb) {
2464 ret = btrfs_cow_block(trans, root, eb, upper->eb,
9631e4cc 2465 slot, &eb, BTRFS_NESTING_COW);
3fd0a558
YZ
2466 btrfs_tree_unlock(eb);
2467 free_extent_buffer(eb);
8df01fdd 2468 if (ret < 0)
3fd0a558 2469 goto next;
ffe30dd8
JB
2470 /*
2471 * We've just COWed this block, it should have updated
2472 * the correct backref node entry.
2473 */
2474 ASSERT(node->eb == eb);
5d4f98a2 2475 } else {
4d09b4e9
JB
2476 struct btrfs_ref ref = {
2477 .action = BTRFS_ADD_DELAYED_REF,
2478 .bytenr = node->eb->start,
12390e42 2479 .num_bytes = blocksize,
4d09b4e9
JB
2480 .parent = upper->eb->start,
2481 .owning_root = btrfs_header_owner(upper->eb),
f2e69a77 2482 .ref_root = btrfs_header_owner(upper->eb),
4d09b4e9
JB
2483 };
2484
5d4f98a2
YZ
2485 btrfs_set_node_blockptr(upper->eb, slot,
2486 node->eb->start);
2487 btrfs_set_node_ptr_generation(upper->eb, slot,
2488 trans->transid);
50564b65 2489 btrfs_mark_buffer_dirty(trans, upper->eb);
5d4f98a2 2490
82fa113f 2491 btrfs_init_tree_ref(&ref, node->level,
e094f480 2492 btrfs_root_id(root), false);
82fa113f 2493 ret = btrfs_inc_extent_ref(trans, &ref);
eb6b7fb4
JB
2494 if (!ret)
2495 ret = btrfs_drop_subtree(trans, root, eb,
2496 upper->eb);
2497 if (ret)
2498 btrfs_abort_transaction(trans, ret);
5d4f98a2 2499 }
3fd0a558
YZ
2500next:
2501 if (!upper->pending)
b0fe7078 2502 btrfs_backref_drop_node_buffer(upper);
3fd0a558 2503 else
b0fe7078 2504 btrfs_backref_unlock_node_buffer(upper);
8df01fdd 2505 if (ret)
3fd0a558 2506 break;
5d4f98a2 2507 }
3fd0a558 2508
8df01fdd 2509 if (!ret && node->pending) {
b0fe7078 2510 btrfs_backref_drop_node_buffer(node);
3fd0a558
YZ
2511 list_move_tail(&node->list, &rc->backref_cache.changed);
2512 node->pending = 0;
2513 }
2514
5d4f98a2 2515 path->lowest_level = 0;
ffe30dd8
JB
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);
8df01fdd 2522 return ret;
5d4f98a2
YZ
2523}
2524
2525static int link_to_upper(struct btrfs_trans_handle *trans,
3fd0a558 2526 struct reloc_control *rc,
a26195a5 2527 struct btrfs_backref_node *node,
5d4f98a2
YZ
2528 struct btrfs_path *path)
2529{
2530 struct btrfs_key key;
5d4f98a2
YZ
2531
2532 btrfs_node_key_to_cpu(node->eb, &key, 0);
3fd0a558 2533 return do_relocation(trans, rc, node, &key, path, 0);
5d4f98a2
YZ
2534}
2535
2536static int finish_pending_nodes(struct btrfs_trans_handle *trans,
3fd0a558
YZ
2537 struct reloc_control *rc,
2538 struct btrfs_path *path, int err)
5d4f98a2 2539{
3fd0a558 2540 LIST_HEAD(list);
a26195a5
QW
2541 struct btrfs_backref_cache *cache = &rc->backref_cache;
2542 struct btrfs_backref_node *node;
5d4f98a2
YZ
2543 int level;
2544 int ret;
5d4f98a2
YZ
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,
a26195a5 2549 struct btrfs_backref_node, list);
3fd0a558
YZ
2550 list_move_tail(&node->list, &list);
2551 BUG_ON(!node->pending);
5d4f98a2 2552
3fd0a558
YZ
2553 if (!err) {
2554 ret = link_to_upper(trans, rc, node, path);
2555 if (ret < 0)
2556 err = ret;
2557 }
5d4f98a2 2558 }
3fd0a558 2559 list_splice_init(&list, &cache->pending[level]);
5d4f98a2 2560 }
5d4f98a2
YZ
2561 return err;
2562}
2563
5d4f98a2
YZ
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,
a26195a5 2569 struct btrfs_backref_node *node)
5d4f98a2 2570{
a26195a5
QW
2571 struct btrfs_backref_node *next = node;
2572 struct btrfs_backref_edge *edge;
2573 struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
5d4f98a2
YZ
2574 int index = 0;
2575
2576 while (next) {
2577 cond_resched();
2578 while (1) {
2579 if (next->processed)
2580 break;
2581
9569cc20 2582 mark_block_processed(rc, next);
5d4f98a2
YZ
2583
2584 if (list_empty(&next->upper))
2585 break;
2586
2587 edge = list_entry(next->upper.next,
a26195a5 2588 struct btrfs_backref_edge, list[LOWER]);
5d4f98a2
YZ
2589 edges[index++] = edge;
2590 next = edge->node[UPPER];
2591 }
2592 next = walk_down_backref(edges, &index);
2593 }
2594}
2595
7476dfda 2596static int tree_block_processed(u64 bytenr, struct reloc_control *rc)
3fd0a558 2597{
da17066c 2598 u32 blocksize = rc->extent_root->fs_info->nodesize;
7476dfda 2599
3fd0a558 2600 if (test_range_bit(&rc->processed_blocks, bytenr,
893fe243 2601 bytenr + blocksize - 1, EXTENT_DIRTY, NULL))
3fd0a558
YZ
2602 return 1;
2603 return 0;
5d4f98a2
YZ
2604}
2605
2ff7e61e 2606static int get_tree_block_key(struct btrfs_fs_info *fs_info,
5d4f98a2
YZ
2607 struct tree_block *block)
2608{
789d6a3a
QW
2609 struct btrfs_tree_parent_check check = {
2610 .level = block->level,
2611 .owner_root = block->owner,
2612 .transid = block->key.offset
2613 };
5d4f98a2
YZ
2614 struct extent_buffer *eb;
2615
789d6a3a 2616 eb = read_tree_block(fs_info, block->bytenr, &check);
4eb150d6 2617 if (IS_ERR(eb))
64c043de 2618 return PTR_ERR(eb);
4eb150d6 2619 if (!extent_buffer_uptodate(eb)) {
416bc658
JB
2620 free_extent_buffer(eb);
2621 return -EIO;
2622 }
5d4f98a2
YZ
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);
a3bb700f 2628 block->key_ready = true;
5d4f98a2
YZ
2629 return 0;
2630}
2631
5d4f98a2
YZ
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,
a26195a5 2637 struct btrfs_backref_node *node,
5d4f98a2
YZ
2638 struct btrfs_key *key,
2639 struct btrfs_path *path)
2640{
2641 struct btrfs_root *root;
3fd0a558
YZ
2642 int ret = 0;
2643
2644 if (!node)
2645 return 0;
5d4f98a2 2646
5f6b2e5c
JB
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
3fd0a558 2655 BUG_ON(node->processed);
147d256e 2656 root = select_one_root(node);
8717cf44
JB
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 }
3fd0a558 2666 goto out;
5d4f98a2
YZ
2667 }
2668
3fd0a558 2669 if (root) {
92a7cc42 2670 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
1c7bfa15
JB
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 }
d18c7bd9
JB
2693 ret = btrfs_record_root_in_trans(trans, root);
2694 if (ret)
2695 goto out;
39200e59
JB
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 }
3fd0a558
YZ
2704 root = root->reloc_root;
2705 node->new_bytenr = root->node->start;
00246528
JB
2706 btrfs_put_root(node->root);
2707 node->root = btrfs_grab_root(root);
0b530bc5 2708 ASSERT(node->root);
3fd0a558
YZ
2709 list_add_tail(&node->list, &rc->backref_cache.changed);
2710 } else {
2711 path->lowest_level = node->level;
2bb2e00e
FM
2712 if (root == root->fs_info->chunk_root)
2713 btrfs_reserve_chunk_metadata(trans, false);
3fd0a558 2714 ret = btrfs_search_slot(trans, root, key, path, 0, 1);
b3b4aa74 2715 btrfs_release_path(path);
2bb2e00e
FM
2716 if (root == root->fs_info->chunk_root)
2717 btrfs_trans_release_chunk_metadata(trans);
3fd0a558
YZ
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 }
5d4f98a2 2726out:
0647bf56 2727 if (ret || node->level == 0 || node->cowonly)
023acb07 2728 btrfs_backref_cleanup_node(&rc->backref_cache, node);
5d4f98a2
YZ
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{
2ff7e61e 2739 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
a26195a5 2740 struct btrfs_backref_node *node;
5d4f98a2
YZ
2741 struct btrfs_path *path;
2742 struct tree_block *block;
98ff7b94 2743 struct tree_block *next;
acde0e86 2744 int ret = 0;
5d4f98a2
YZ
2745
2746 path = btrfs_alloc_path();
e1a12670 2747 if (!path) {
acde0e86 2748 ret = -ENOMEM;
34c2b290 2749 goto out_free_blocks;
e1a12670 2750 }
5d4f98a2 2751
98ff7b94
QW
2752 /* Kick in readahead for tree blocks with missing keys */
2753 rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
5d4f98a2 2754 if (!block->key_ready)
f7ba2d37
JB
2755 btrfs_readahead_tree_block(fs_info, block->bytenr,
2756 block->owner, 0,
3fbaf258 2757 block->level);
5d4f98a2
YZ
2758 }
2759
98ff7b94
QW
2760 /* Get first keys */
2761 rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
34c2b290 2762 if (!block->key_ready) {
acde0e86
AJ
2763 ret = get_tree_block_key(fs_info, block);
2764 if (ret)
34c2b290
DS
2765 goto out_free_path;
2766 }
5d4f98a2
YZ
2767 }
2768
98ff7b94
QW
2769 /* Do tree relocation */
2770 rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
eb96e221 2771 node = build_backref_tree(trans, rc, &block->key,
5d4f98a2
YZ
2772 block->level, block->bytenr);
2773 if (IS_ERR(node)) {
acde0e86 2774 ret = PTR_ERR(node);
5d4f98a2
YZ
2775 goto out;
2776 }
2777
2778 ret = relocate_tree_block(trans, rc, node, &block->key,
2779 path);
acde0e86 2780 if (ret < 0)
50dbbb71 2781 break;
5d4f98a2 2782 }
5d4f98a2 2783out:
acde0e86 2784 ret = finish_pending_nodes(trans, rc, path, ret);
5d4f98a2 2785
34c2b290 2786out_free_path:
5d4f98a2 2787 btrfs_free_path(path);
34c2b290 2788out_free_blocks:
e1a12670 2789 free_block_list(blocks);
acde0e86 2790 return ret;
5d4f98a2
YZ
2791}
2792
056d9bec
NB
2793static noinline_for_stack int prealloc_file_extent_cluster(
2794 struct btrfs_inode *inode,
ab7c8bbf 2795 const struct file_extent_cluster *cluster)
efa56464
YZ
2796{
2797 u64 alloc_hint = 0;
2798 u64 start;
2799 u64 end;
056d9bec 2800 u64 offset = inode->index_cnt;
efa56464 2801 u64 num_bytes;
4e9d0d01 2802 int nr;
efa56464 2803 int ret = 0;
9d9ea1e6 2804 u64 i_size = i_size_read(&inode->vfs_inode);
dcb40c19
WX
2805 u64 prealloc_start = cluster->start - offset;
2806 u64 prealloc_end = cluster->end - offset;
214e61d0 2807 u64 cur_offset = prealloc_start;
efa56464 2808
9d9ea1e6
QW
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()
a16c2c48 2815 * will skip the read, and relocate_one_folio() will later writeback
9d9ea1e6
QW
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 */
ce394a7f 2820 if (!PAGE_ALIGNED(i_size)) {
9d9ea1e6
QW
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;
8d6e5f9a 2824 struct folio *folio;
9d9ea1e6
QW
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 *
fb12489b 2833 * btrfs_read_folio()
9d9ea1e6
QW
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);
8d6e5f9a 2855 folio = filemap_lock_folio(mapping, i_size >> PAGE_SHIFT);
9d9ea1e6
QW
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 */
8d6e5f9a
GR
2860 if (!IS_ERR(folio)) {
2861 btrfs_subpage_clear_uptodate(fs_info, folio, i_size,
9d9ea1e6 2862 round_up(i_size, PAGE_SIZE) - i_size);
8d6e5f9a
GR
2863 folio_unlock(folio);
2864 folio_put(folio);
9d9ea1e6
QW
2865 }
2866 }
2867
efa56464 2868 BUG_ON(cluster->start != cluster->boundary[0]);
056d9bec 2869 ret = btrfs_alloc_data_chunk_ondemand(inode,
a89ef455 2870 prealloc_end + 1 - prealloc_start);
efa56464 2871 if (ret)
214e61d0 2872 return ret;
efa56464 2873
29b6352b 2874 btrfs_inode_lock(inode, 0);
4e9d0d01 2875 for (nr = 0; nr < cluster->nr; nr++) {
9c5c9604
JB
2876 struct extent_state *cached_state = NULL;
2877
efa56464
YZ
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
9c5c9604 2884 lock_extent(&inode->io_tree, start, end, &cached_state);
efa56464 2885 num_bytes = end + 1 - start;
056d9bec 2886 ret = btrfs_prealloc_file_range(&inode->vfs_inode, 0, start,
efa56464
YZ
2887 num_bytes, num_bytes,
2888 end + 1, &alloc_hint);
18513091 2889 cur_offset = end + 1;
9c5c9604 2890 unlock_extent(&inode->io_tree, start, end, &cached_state);
efa56464
YZ
2891 if (ret)
2892 break;
efa56464 2893 }
e5d4d75b 2894 btrfs_inode_unlock(inode, 0);
214e61d0 2895
18513091 2896 if (cur_offset < prealloc_end)
056d9bec 2897 btrfs_free_reserved_data_space_noquota(inode->root->fs_info,
a89ef455 2898 prealloc_end + 1 - cur_offset);
efa56464
YZ
2899 return ret;
2900}
2901
4b01c44f
JT
2902static noinline_for_stack int setup_relocation_extent_mapping(struct inode *inode,
2903 u64 start, u64 end, u64 block_start)
0257bb82 2904{
0257bb82 2905 struct extent_map *em;
9c5c9604 2906 struct extent_state *cached_state = NULL;
0257bb82
YZ
2907 int ret = 0;
2908
172ddd60 2909 em = alloc_extent_map();
0257bb82
YZ
2910 if (!em)
2911 return -ENOMEM;
2912
2913 em->start = start;
2914 em->len = end + 1 - start;
2915 em->block_len = em->len;
2916 em->block_start = block_start;
f86f7a75 2917 em->flags |= EXTENT_FLAG_PINNED;
0257bb82 2918
9c5c9604 2919 lock_extent(&BTRFS_I(inode)->io_tree, start, end, &cached_state);
a1ba4c08 2920 ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, false);
9c5c9604 2921 unlock_extent(&BTRFS_I(inode)->io_tree, start, end, &cached_state);
a1ba4c08
FM
2922 free_extent_map(em);
2923
0257bb82
YZ
2924 return ret;
2925}
2926
726a3421 2927/*
907d2710 2928 * Allow error injection to test balance/relocation cancellation
726a3421 2929 */
ab7c8bbf 2930noinline int btrfs_should_cancel_balance(const struct btrfs_fs_info *fs_info)
726a3421 2931{
5cb502f4 2932 return atomic_read(&fs_info->balance_cancel_req) ||
907d2710 2933 atomic_read(&fs_info->reloc_cancel_req) ||
5cb502f4 2934 fatal_signal_pending(current);
726a3421
QW
2935}
2936ALLOW_ERROR_INJECTION(btrfs_should_cancel_balance, TRUE);
2937
ab7c8bbf 2938static u64 get_cluster_boundary_end(const struct file_extent_cluster *cluster,
c2832898
QW
2939 int cluster_nr)
2940{
2941 /* Last extent, use cluster end directly */
2942 if (cluster_nr >= cluster->nr - 1)
2943 return cluster->end;
2944
2945 /* Use next boundary start*/
2946 return cluster->boundary[cluster_nr + 1] - 1;
2947}
2948
a16c2c48
GR
2949static int relocate_one_folio(struct inode *inode, struct file_ra_state *ra,
2950 const struct file_extent_cluster *cluster,
2951 int *cluster_nr, unsigned long index)
5d4f98a2 2952{
41044b41 2953 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
f47960f4
QW
2954 u64 offset = BTRFS_I(inode)->index_cnt;
2955 const unsigned long last_index = (cluster->end - offset) >> PAGE_SHIFT;
2956 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
a16c2c48
GR
2957 struct folio *folio;
2958 u64 folio_start;
2959 u64 folio_end;
c2832898 2960 u64 cur;
f47960f4
QW
2961 int ret;
2962
a16c2c48
GR
2963 ASSERT(index <= last_index);
2964 folio = filemap_lock_folio(inode->i_mapping, index);
2965 if (IS_ERR(folio)) {
f47960f4 2966 page_cache_sync_readahead(inode->i_mapping, ra, NULL,
a16c2c48
GR
2967 index, last_index + 1 - index);
2968 folio = __filemap_get_folio(inode->i_mapping, index,
2969 FGP_LOCK | FGP_ACCESSED | FGP_CREAT, mask);
2970 if (IS_ERR(folio))
2971 return PTR_ERR(folio);
f47960f4 2972 }
f47960f4 2973
a16c2c48
GR
2974 WARN_ON(folio_order(folio));
2975
2976 if (folio_test_readahead(folio))
2ebdd1df 2977 page_cache_async_readahead(inode->i_mapping, ra, NULL,
a16c2c48
GR
2978 folio, index,
2979 last_index + 1 - index);
f47960f4 2980
a16c2c48
GR
2981 if (!folio_test_uptodate(folio)) {
2982 btrfs_read_folio(NULL, folio);
2983 folio_lock(folio);
2984 if (!folio_test_uptodate(folio)) {
f47960f4 2985 ret = -EIO;
a16c2c48 2986 goto release_folio;
f47960f4
QW
2987 }
2988 }
2989
e7f1326c 2990 /*
a16c2c48
GR
2991 * We could have lost folio private when we dropped the lock to read the
2992 * folio above, make sure we set_page_extent_mapped here so we have any
e7f1326c
JB
2993 * of the subpage blocksize stuff we need in place.
2994 */
a16c2c48 2995 ret = set_folio_extent_mapped(folio);
e7f1326c 2996 if (ret < 0)
a16c2c48 2997 goto release_folio;
e7f1326c 2998
a16c2c48
GR
2999 folio_start = folio_pos(folio);
3000 folio_end = folio_start + PAGE_SIZE - 1;
f47960f4 3001
c2832898
QW
3002 /*
3003 * Start from the cluster, as for subpage case, the cluster can start
a16c2c48 3004 * inside the folio.
c2832898 3005 */
a16c2c48
GR
3006 cur = max(folio_start, cluster->boundary[*cluster_nr] - offset);
3007 while (cur <= folio_end) {
9c5c9604 3008 struct extent_state *cached_state = NULL;
c2832898
QW
3009 u64 extent_start = cluster->boundary[*cluster_nr] - offset;
3010 u64 extent_end = get_cluster_boundary_end(cluster,
3011 *cluster_nr) - offset;
a16c2c48
GR
3012 u64 clamped_start = max(folio_start, extent_start);
3013 u64 clamped_end = min(folio_end, extent_end);
c2832898
QW
3014 u32 clamped_len = clamped_end + 1 - clamped_start;
3015
3016 /* Reserve metadata for this range */
3017 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
d4135134
FM
3018 clamped_len, clamped_len,
3019 false);
c2832898 3020 if (ret)
a16c2c48 3021 goto release_folio;
f47960f4 3022
c2832898 3023 /* Mark the range delalloc and dirty for later writeback */
9c5c9604
JB
3024 lock_extent(&BTRFS_I(inode)->io_tree, clamped_start, clamped_end,
3025 &cached_state);
c2832898 3026 ret = btrfs_set_extent_delalloc(BTRFS_I(inode), clamped_start,
9c5c9604 3027 clamped_end, 0, &cached_state);
c2832898 3028 if (ret) {
9c5c9604
JB
3029 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3030 clamped_start, clamped_end,
3031 EXTENT_LOCKED | EXTENT_BOUNDARY,
3032 &cached_state);
c2832898
QW
3033 btrfs_delalloc_release_metadata(BTRFS_I(inode),
3034 clamped_len, true);
3035 btrfs_delalloc_release_extents(BTRFS_I(inode),
3036 clamped_len);
a16c2c48 3037 goto release_folio;
c2832898 3038 }
a16c2c48 3039 btrfs_folio_set_dirty(fs_info, folio, clamped_start, clamped_len);
f47960f4 3040
c2832898 3041 /*
a16c2c48 3042 * Set the boundary if it's inside the folio.
c2832898
QW
3043 * Data relocation requires the destination extents to have the
3044 * same size as the source.
3045 * EXTENT_BOUNDARY bit prevents current extent from being merged
3046 * with previous extent.
3047 */
a16c2c48 3048 if (in_range(cluster->boundary[*cluster_nr] - offset, folio_start, PAGE_SIZE)) {
c2832898
QW
3049 u64 boundary_start = cluster->boundary[*cluster_nr] -
3050 offset;
3051 u64 boundary_end = boundary_start +
3052 fs_info->sectorsize - 1;
3053
0acd32c2
DS
3054 set_extent_bit(&BTRFS_I(inode)->io_tree,
3055 boundary_start, boundary_end,
1d126800 3056 EXTENT_BOUNDARY, NULL);
c2832898 3057 }
9c5c9604
JB
3058 unlock_extent(&BTRFS_I(inode)->io_tree, clamped_start, clamped_end,
3059 &cached_state);
c2832898
QW
3060 btrfs_delalloc_release_extents(BTRFS_I(inode), clamped_len);
3061 cur += clamped_len;
3062
3063 /* Crossed extent end, go to next extent */
3064 if (cur >= extent_end) {
3065 (*cluster_nr)++;
3066 /* Just finished the last extent of the cluster, exit. */
3067 if (*cluster_nr >= cluster->nr)
3068 break;
3069 }
f47960f4 3070 }
a16c2c48
GR
3071 folio_unlock(folio);
3072 folio_put(folio);
f47960f4 3073
f47960f4
QW
3074 balance_dirty_pages_ratelimited(inode->i_mapping);
3075 btrfs_throttle(fs_info);
3076 if (btrfs_should_cancel_balance(fs_info))
3077 ret = -ECANCELED;
3078 return ret;
3079
a16c2c48
GR
3080release_folio:
3081 folio_unlock(folio);
3082 folio_put(folio);
f47960f4
QW
3083 return ret;
3084}
3085
3086static int relocate_file_extent_cluster(struct inode *inode,
ab7c8bbf 3087 const struct file_extent_cluster *cluster)
f47960f4 3088{
0257bb82
YZ
3089 u64 offset = BTRFS_I(inode)->index_cnt;
3090 unsigned long index;
5d4f98a2 3091 unsigned long last_index;
5d4f98a2 3092 struct file_ra_state *ra;
f47960f4 3093 int cluster_nr = 0;
5d4f98a2
YZ
3094 int ret = 0;
3095
0257bb82
YZ
3096 if (!cluster->nr)
3097 return 0;
3098
5d4f98a2
YZ
3099 ra = kzalloc(sizeof(*ra), GFP_NOFS);
3100 if (!ra)
3101 return -ENOMEM;
3102
056d9bec 3103 ret = prealloc_file_extent_cluster(BTRFS_I(inode), cluster);
efa56464
YZ
3104 if (ret)
3105 goto out;
0257bb82 3106
efa56464 3107 file_ra_state_init(ra, inode->i_mapping);
5d4f98a2 3108
4b01c44f 3109 ret = setup_relocation_extent_mapping(inode, cluster->start - offset,
0257bb82 3110 cluster->end - offset, cluster->start);
5d4f98a2 3111 if (ret)
efa56464 3112 goto out;
5d4f98a2 3113
09cbfeaf 3114 last_index = (cluster->end - offset) >> PAGE_SHIFT;
f47960f4
QW
3115 for (index = (cluster->start - offset) >> PAGE_SHIFT;
3116 index <= last_index && !ret; index++)
a16c2c48 3117 ret = relocate_one_folio(inode, ra, cluster, &cluster_nr, index);
f47960f4
QW
3118 if (ret == 0)
3119 WARN_ON(cluster_nr != cluster->nr);
efa56464 3120out:
5d4f98a2 3121 kfree(ra);
5d4f98a2
YZ
3122 return ret;
3123}
3124
ab7c8bbf
DS
3125static noinline_for_stack int relocate_data_extent(struct inode *inode,
3126 const struct btrfs_key *extent_key,
3127 struct file_extent_cluster *cluster)
5d4f98a2 3128{
0257bb82 3129 int ret;
2672a051 3130 struct btrfs_root *root = BTRFS_I(inode)->root;
5d4f98a2 3131
0257bb82
YZ
3132 if (cluster->nr > 0 && extent_key->objectid != cluster->end + 1) {
3133 ret = relocate_file_extent_cluster(inode, cluster);
3134 if (ret)
3135 return ret;
3136 cluster->nr = 0;
5d4f98a2 3137 }
5d4f98a2 3138
2672a051
BB
3139 /*
3140 * Under simple quotas, we set root->relocation_src_root when we find
3141 * the extent. If adjacent extents have different owners, we can't merge
3142 * them while relocating. Handle this by storing the owning root that
3143 * started a cluster and if we see an extent from a different root break
3144 * cluster formation (just like the above case of non-adjacent extents).
3145 *
3146 * Without simple quotas, relocation_src_root is always 0, so we should
3147 * never see a mismatch, and it should have no effect on relocation
3148 * clusters.
3149 */
3150 if (cluster->nr > 0 && cluster->owning_root != root->relocation_src_root) {
3151 u64 tmp = root->relocation_src_root;
3152
3153 /*
3154 * root->relocation_src_root is the state that actually affects
3155 * the preallocation we do here, so set it to the root owning
3156 * the cluster we need to relocate.
3157 */
3158 root->relocation_src_root = cluster->owning_root;
3159 ret = relocate_file_extent_cluster(inode, cluster);
3160 if (ret)
3161 return ret;
3162 cluster->nr = 0;
3163 /* And reset it back for the current extent's owning root. */
3164 root->relocation_src_root = tmp;
3165 }
3166
3167 if (!cluster->nr) {
0257bb82 3168 cluster->start = extent_key->objectid;
2672a051
BB
3169 cluster->owning_root = root->relocation_src_root;
3170 }
0257bb82
YZ
3171 else
3172 BUG_ON(cluster->nr >= MAX_EXTENTS);
3173 cluster->end = extent_key->objectid + extent_key->offset - 1;
3174 cluster->boundary[cluster->nr] = extent_key->objectid;
3175 cluster->nr++;
3176
3177 if (cluster->nr >= MAX_EXTENTS) {
3178 ret = relocate_file_extent_cluster(inode, cluster);
3179 if (ret)
3180 return ret;
3181 cluster->nr = 0;
3182 }
3183 return 0;
5d4f98a2
YZ
3184}
3185
5d4f98a2
YZ
3186/*
3187 * helper to add a tree block to the list.
3188 * the major work is getting the generation and level of the block
3189 */
3190static int add_tree_block(struct reloc_control *rc,
ab7c8bbf 3191 const struct btrfs_key *extent_key,
5d4f98a2
YZ
3192 struct btrfs_path *path,
3193 struct rb_root *blocks)
3194{
3195 struct extent_buffer *eb;
3196 struct btrfs_extent_item *ei;
3197 struct btrfs_tree_block_info *bi;
3198 struct tree_block *block;
3199 struct rb_node *rb_node;
3200 u32 item_size;
3201 int level = -1;
7fdf4b60 3202 u64 generation;
f7ba2d37 3203 u64 owner = 0;
5d4f98a2
YZ
3204
3205 eb = path->nodes[0];
3212fa14 3206 item_size = btrfs_item_size(eb, path->slots[0]);
5d4f98a2 3207
3173a18f
JB
3208 if (extent_key->type == BTRFS_METADATA_ITEM_KEY ||
3209 item_size >= sizeof(*ei) + sizeof(*bi)) {
f7ba2d37
JB
3210 unsigned long ptr = 0, end;
3211
5d4f98a2
YZ
3212 ei = btrfs_item_ptr(eb, path->slots[0],
3213 struct btrfs_extent_item);
f7ba2d37 3214 end = (unsigned long)ei + item_size;
3173a18f
JB
3215 if (extent_key->type == BTRFS_EXTENT_ITEM_KEY) {
3216 bi = (struct btrfs_tree_block_info *)(ei + 1);
3217 level = btrfs_tree_block_level(eb, bi);
f7ba2d37 3218 ptr = (unsigned long)(bi + 1);
3173a18f
JB
3219 } else {
3220 level = (int)extent_key->offset;
f7ba2d37 3221 ptr = (unsigned long)(ei + 1);
3173a18f 3222 }
5d4f98a2 3223 generation = btrfs_extent_generation(eb, ei);
f7ba2d37
JB
3224
3225 /*
3226 * We're reading random blocks without knowing their owner ahead
3227 * of time. This is ok most of the time, as all reloc roots and
3228 * fs roots have the same lock type. However normal trees do
3229 * not, and the only way to know ahead of time is to read the
3230 * inline ref offset. We know it's an fs root if
3231 *
3232 * 1. There's more than one ref.
3233 * 2. There's a SHARED_DATA_REF_KEY set.
3234 * 3. FULL_BACKREF is set on the flags.
3235 *
3236 * Otherwise it's safe to assume that the ref offset == the
3237 * owner of this block, so we can use that when calling
3238 * read_tree_block.
3239 */
3240 if (btrfs_extent_refs(eb, ei) == 1 &&
3241 !(btrfs_extent_flags(eb, ei) &
3242 BTRFS_BLOCK_FLAG_FULL_BACKREF) &&
3243 ptr < end) {
3244 struct btrfs_extent_inline_ref *iref;
3245 int type;
3246
3247 iref = (struct btrfs_extent_inline_ref *)ptr;
3248 type = btrfs_get_extent_inline_ref_type(eb, iref,
3249 BTRFS_REF_TYPE_BLOCK);
3250 if (type == BTRFS_REF_TYPE_INVALID)
3251 return -EINVAL;
3252 if (type == BTRFS_TREE_BLOCK_REF_KEY)
3253 owner = btrfs_extent_inline_ref_offset(eb, iref);
3254 }
5d4f98a2 3255 } else {
182741d2
QW
3256 btrfs_print_leaf(eb);
3257 btrfs_err(rc->block_group->fs_info,
3258 "unrecognized tree backref at tree block %llu slot %u",
3259 eb->start, path->slots[0]);
3260 btrfs_release_path(path);
3261 return -EUCLEAN;
5d4f98a2
YZ
3262 }
3263
b3b4aa74 3264 btrfs_release_path(path);
5d4f98a2
YZ
3265
3266 BUG_ON(level == -1);
3267
3268 block = kmalloc(sizeof(*block), GFP_NOFS);
3269 if (!block)
3270 return -ENOMEM;
3271
3272 block->bytenr = extent_key->objectid;
da17066c 3273 block->key.objectid = rc->extent_root->fs_info->nodesize;
5d4f98a2
YZ
3274 block->key.offset = generation;
3275 block->level = level;
a3bb700f 3276 block->key_ready = false;
f7ba2d37 3277 block->owner = owner;
5d4f98a2 3278
e9a28dc5 3279 rb_node = rb_simple_insert(blocks, block->bytenr, &block->rb_node);
43c04fb1 3280 if (rb_node)
982c92cb
QW
3281 btrfs_backref_panic(rc->extent_root->fs_info, block->bytenr,
3282 -EEXIST);
5d4f98a2
YZ
3283
3284 return 0;
3285}
3286
3287/*
3288 * helper to add tree blocks for backref of type BTRFS_SHARED_DATA_REF_KEY
3289 */
3290static int __add_tree_block(struct reloc_control *rc,
3291 u64 bytenr, u32 blocksize,
3292 struct rb_root *blocks)
3293{
0b246afa 3294 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
5d4f98a2
YZ
3295 struct btrfs_path *path;
3296 struct btrfs_key key;
3297 int ret;
0b246afa 3298 bool skinny = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
5d4f98a2 3299
7476dfda 3300 if (tree_block_processed(bytenr, rc))
5d4f98a2
YZ
3301 return 0;
3302
e9a28dc5 3303 if (rb_simple_search(blocks, bytenr))
5d4f98a2
YZ
3304 return 0;
3305
3306 path = btrfs_alloc_path();
3307 if (!path)
3308 return -ENOMEM;
aee68ee5 3309again:
5d4f98a2 3310 key.objectid = bytenr;
aee68ee5
JB
3311 if (skinny) {
3312 key.type = BTRFS_METADATA_ITEM_KEY;
3313 key.offset = (u64)-1;
3314 } else {
3315 key.type = BTRFS_EXTENT_ITEM_KEY;
3316 key.offset = blocksize;
3317 }
5d4f98a2
YZ
3318
3319 path->search_commit_root = 1;
3320 path->skip_locking = 1;
3321 ret = btrfs_search_slot(NULL, rc->extent_root, &key, path, 0, 0);
3322 if (ret < 0)
3323 goto out;
5d4f98a2 3324
aee68ee5
JB
3325 if (ret > 0 && skinny) {
3326 if (path->slots[0]) {
3327 path->slots[0]--;
3328 btrfs_item_key_to_cpu(path->nodes[0], &key,
3329 path->slots[0]);
3330 if (key.objectid == bytenr &&
3331 (key.type == BTRFS_METADATA_ITEM_KEY ||
3332 (key.type == BTRFS_EXTENT_ITEM_KEY &&
3333 key.offset == blocksize)))
3334 ret = 0;
3335 }
3336
3337 if (ret) {
3338 skinny = false;
3339 btrfs_release_path(path);
3340 goto again;
3341 }
3173a18f 3342 }
cdccee99
LB
3343 if (ret) {
3344 ASSERT(ret == 1);
3345 btrfs_print_leaf(path->nodes[0]);
3346 btrfs_err(fs_info,
3347 "tree block extent item (%llu) is not found in extent tree",
3348 bytenr);
3349 WARN_ON(1);
3350 ret = -EINVAL;
3351 goto out;
3352 }
3173a18f 3353
5d4f98a2
YZ
3354 ret = add_tree_block(rc, &key, path, blocks);
3355out:
3356 btrfs_free_path(path);
3357 return ret;
3358}
3359
0af3d00b 3360static int delete_block_group_cache(struct btrfs_fs_info *fs_info,
32da5386 3361 struct btrfs_block_group *block_group,
1bbc621e
CM
3362 struct inode *inode,
3363 u64 ino)
0af3d00b 3364{
0af3d00b
JB
3365 struct btrfs_root *root = fs_info->tree_root;
3366 struct btrfs_trans_handle *trans;
0af3d00b
JB
3367 int ret = 0;
3368
3369 if (inode)
3370 goto truncate;
3371
0202e83f 3372 inode = btrfs_iget(fs_info->sb, ino, root);
2e19f1f9 3373 if (IS_ERR(inode))
0af3d00b 3374 return -ENOENT;
0af3d00b
JB
3375
3376truncate:
2ff7e61e 3377 ret = btrfs_check_trunc_cache_free_space(fs_info,
7b61cd92
MX
3378 &fs_info->global_block_rsv);
3379 if (ret)
3380 goto out;
3381
7a7eaa40 3382 trans = btrfs_join_transaction(root);
0af3d00b 3383 if (IS_ERR(trans)) {
3612b495 3384 ret = PTR_ERR(trans);
0af3d00b
JB
3385 goto out;
3386 }
3387
77ab86bf 3388 ret = btrfs_truncate_free_space_cache(trans, block_group, inode);
0af3d00b 3389
3a45bb20 3390 btrfs_end_transaction(trans);
2ff7e61e 3391 btrfs_btree_balance_dirty(fs_info);
0af3d00b
JB
3392out:
3393 iput(inode);
3394 return ret;
3395}
3396
5d4f98a2 3397/*
19b546d7
QW
3398 * Locate the free space cache EXTENT_DATA in root tree leaf and delete the
3399 * cache inode, to avoid free space cache data extent blocking data relocation.
5d4f98a2 3400 */
19b546d7
QW
3401static int delete_v1_space_cache(struct extent_buffer *leaf,
3402 struct btrfs_block_group *block_group,
3403 u64 data_bytenr)
5d4f98a2 3404{
19b546d7
QW
3405 u64 space_cache_ino;
3406 struct btrfs_file_extent_item *ei;
5d4f98a2 3407 struct btrfs_key key;
19b546d7
QW
3408 bool found = false;
3409 int i;
5d4f98a2
YZ
3410 int ret;
3411
19b546d7
QW
3412 if (btrfs_header_owner(leaf) != BTRFS_ROOT_TREE_OBJECTID)
3413 return 0;
5d4f98a2 3414
19b546d7 3415 for (i = 0; i < btrfs_header_nritems(leaf); i++) {
50e31ef4
QW
3416 u8 type;
3417
19b546d7
QW
3418 btrfs_item_key_to_cpu(leaf, &key, i);
3419 if (key.type != BTRFS_EXTENT_DATA_KEY)
3420 continue;
3421 ei = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
50e31ef4
QW
3422 type = btrfs_file_extent_type(leaf, ei);
3423
3424 if ((type == BTRFS_FILE_EXTENT_REG ||
3425 type == BTRFS_FILE_EXTENT_PREALLOC) &&
19b546d7
QW
3426 btrfs_file_extent_disk_bytenr(leaf, ei) == data_bytenr) {
3427 found = true;
3428 space_cache_ino = key.objectid;
5d4f98a2 3429 break;
5d4f98a2 3430 }
5d4f98a2 3431 }
19b546d7
QW
3432 if (!found)
3433 return -ENOENT;
3434 ret = delete_block_group_cache(leaf->fs_info, block_group, NULL,
3435 space_cache_ino);
3436 return ret;
5d4f98a2
YZ
3437}
3438
3439/*
2c016dc2 3440 * helper to find all tree blocks that reference a given data extent
5d4f98a2 3441 */
ab7c8bbf
DS
3442static noinline_for_stack int add_data_references(struct reloc_control *rc,
3443 const struct btrfs_key *extent_key,
3444 struct btrfs_path *path,
3445 struct rb_root *blocks)
5d4f98a2 3446{
a2c8d27e 3447 struct btrfs_backref_walk_ctx ctx = { 0 };
19b546d7
QW
3448 struct ulist_iterator leaf_uiter;
3449 struct ulist_node *ref_node = NULL;
a2c8d27e 3450 const u32 blocksize = rc->extent_root->fs_info->nodesize;
647f63bd 3451 int ret = 0;
5d4f98a2 3452
19b546d7 3453 btrfs_release_path(path);
a2c8d27e
FM
3454
3455 ctx.bytenr = extent_key->objectid;
0cad8f14 3456 ctx.skip_inode_ref_list = true;
a2c8d27e
FM
3457 ctx.fs_info = rc->extent_root->fs_info;
3458
3459 ret = btrfs_find_all_leafs(&ctx);
19b546d7
QW
3460 if (ret < 0)
3461 return ret;
5d4f98a2 3462
19b546d7 3463 ULIST_ITER_INIT(&leaf_uiter);
a2c8d27e 3464 while ((ref_node = ulist_next(ctx.refs, &leaf_uiter))) {
789d6a3a 3465 struct btrfs_tree_parent_check check = { 0 };
19b546d7 3466 struct extent_buffer *eb;
5d4f98a2 3467
789d6a3a 3468 eb = read_tree_block(ctx.fs_info, ref_node->val, &check);
19b546d7
QW
3469 if (IS_ERR(eb)) {
3470 ret = PTR_ERR(eb);
5d4f98a2 3471 break;
5d4f98a2 3472 }
19b546d7
QW
3473 ret = delete_v1_space_cache(eb, rc->block_group,
3474 extent_key->objectid);
3475 free_extent_buffer(eb);
3476 if (ret < 0)
3477 break;
3478 ret = __add_tree_block(rc, ref_node->val, blocksize, blocks);
3479 if (ret < 0)
5d4f98a2 3480 break;
5d4f98a2 3481 }
19b546d7 3482 if (ret < 0)
5d4f98a2 3483 free_block_list(blocks);
a2c8d27e 3484 ulist_free(ctx.refs);
19b546d7 3485 return ret;
5d4f98a2
YZ
3486}
3487
3488/*
2c016dc2 3489 * helper to find next unprocessed extent
5d4f98a2
YZ
3490 */
3491static noinline_for_stack
147d256e 3492int find_next_extent(struct reloc_control *rc, struct btrfs_path *path,
3fd0a558 3493 struct btrfs_key *extent_key)
5d4f98a2 3494{
0b246afa 3495 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
5d4f98a2
YZ
3496 struct btrfs_key key;
3497 struct extent_buffer *leaf;
3498 u64 start, end, last;
3499 int ret;
3500
b3470b5d 3501 last = rc->block_group->start + rc->block_group->length;
5d4f98a2 3502 while (1) {
e5860f82
FM
3503 bool block_found;
3504
5d4f98a2
YZ
3505 cond_resched();
3506 if (rc->search_start >= last) {
3507 ret = 1;
3508 break;
3509 }
3510
3511 key.objectid = rc->search_start;
3512 key.type = BTRFS_EXTENT_ITEM_KEY;
3513 key.offset = 0;
3514
3515 path->search_commit_root = 1;
3516 path->skip_locking = 1;
3517 ret = btrfs_search_slot(NULL, rc->extent_root, &key, path,
3518 0, 0);
3519 if (ret < 0)
3520 break;
3521next:
3522 leaf = path->nodes[0];
3523 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
3524 ret = btrfs_next_leaf(rc->extent_root, path);
3525 if (ret != 0)
3526 break;
3527 leaf = path->nodes[0];
3528 }
3529
3530 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3531 if (key.objectid >= last) {
3532 ret = 1;
3533 break;
3534 }
3535
3173a18f
JB
3536 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
3537 key.type != BTRFS_METADATA_ITEM_KEY) {
3538 path->slots[0]++;
3539 goto next;
3540 }
3541
3542 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
5d4f98a2
YZ
3543 key.objectid + key.offset <= rc->search_start) {
3544 path->slots[0]++;
3545 goto next;
3546 }
3547
3173a18f 3548 if (key.type == BTRFS_METADATA_ITEM_KEY &&
0b246afa 3549 key.objectid + fs_info->nodesize <=
3173a18f
JB
3550 rc->search_start) {
3551 path->slots[0]++;
3552 goto next;
3553 }
3554
e5860f82
FM
3555 block_found = find_first_extent_bit(&rc->processed_blocks,
3556 key.objectid, &start, &end,
3557 EXTENT_DIRTY, NULL);
5d4f98a2 3558
e5860f82 3559 if (block_found && start <= key.objectid) {
b3b4aa74 3560 btrfs_release_path(path);
5d4f98a2
YZ
3561 rc->search_start = end + 1;
3562 } else {
3173a18f
JB
3563 if (key.type == BTRFS_EXTENT_ITEM_KEY)
3564 rc->search_start = key.objectid + key.offset;
3565 else
3566 rc->search_start = key.objectid +
0b246afa 3567 fs_info->nodesize;
3fd0a558 3568 memcpy(extent_key, &key, sizeof(key));
5d4f98a2
YZ
3569 return 0;
3570 }
3571 }
b3b4aa74 3572 btrfs_release_path(path);
5d4f98a2
YZ
3573 return ret;
3574}
3575
3576static void set_reloc_control(struct reloc_control *rc)
3577{
3578 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
7585717f
CM
3579
3580 mutex_lock(&fs_info->reloc_mutex);
5d4f98a2 3581 fs_info->reloc_ctl = rc;
7585717f 3582 mutex_unlock(&fs_info->reloc_mutex);
5d4f98a2
YZ
3583}
3584
3585static void unset_reloc_control(struct reloc_control *rc)
3586{
3587 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
7585717f
CM
3588
3589 mutex_lock(&fs_info->reloc_mutex);
5d4f98a2 3590 fs_info->reloc_ctl = NULL;
7585717f 3591 mutex_unlock(&fs_info->reloc_mutex);
5d4f98a2
YZ
3592}
3593
3fd0a558
YZ
3594static noinline_for_stack
3595int prepare_to_relocate(struct reloc_control *rc)
3596{
3597 struct btrfs_trans_handle *trans;
ac2fabac 3598 int ret;
3fd0a558 3599
2ff7e61e 3600 rc->block_rsv = btrfs_alloc_block_rsv(rc->extent_root->fs_info,
66d8f3dd 3601 BTRFS_BLOCK_RSV_TEMP);
3fd0a558
YZ
3602 if (!rc->block_rsv)
3603 return -ENOMEM;
3604
3fd0a558 3605 memset(&rc->cluster, 0, sizeof(rc->cluster));
b3470b5d 3606 rc->search_start = rc->block_group->start;
3fd0a558
YZ
3607 rc->extents_found = 0;
3608 rc->nodes_relocated = 0;
3609 rc->merging_rsv_size = 0;
0647bf56 3610 rc->reserved_bytes = 0;
da17066c 3611 rc->block_rsv->size = rc->extent_root->fs_info->nodesize *
0647bf56 3612 RELOCATION_RESERVED_NODES;
9270501c 3613 ret = btrfs_block_rsv_refill(rc->extent_root->fs_info,
ac2fabac
JB
3614 rc->block_rsv, rc->block_rsv->size,
3615 BTRFS_RESERVE_FLUSH_ALL);
3616 if (ret)
3617 return ret;
3fd0a558 3618
d23d42e3 3619 rc->create_reloc_tree = true;
3fd0a558
YZ
3620 set_reloc_control(rc);
3621
7a7eaa40 3622 trans = btrfs_join_transaction(rc->extent_root);
28818947
LB
3623 if (IS_ERR(trans)) {
3624 unset_reloc_control(rc);
3625 /*
3626 * extent tree is not a ref_cow tree and has no reloc_root to
3627 * cleanup. And callers are responsible to free the above
3628 * block rsv.
3629 */
3630 return PTR_ERR(trans);
3631 }
85f02d6c
ZF
3632
3633 ret = btrfs_commit_transaction(trans);
3634 if (ret)
3635 unset_reloc_control(rc);
3636
3637 return ret;
3fd0a558 3638}
76dda93c 3639
5d4f98a2
YZ
3640static noinline_for_stack int relocate_block_group(struct reloc_control *rc)
3641{
2ff7e61e 3642 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
5d4f98a2
YZ
3643 struct rb_root blocks = RB_ROOT;
3644 struct btrfs_key key;
3645 struct btrfs_trans_handle *trans = NULL;
3646 struct btrfs_path *path;
3647 struct btrfs_extent_item *ei;
5d4f98a2 3648 u64 flags;
5d4f98a2
YZ
3649 int ret;
3650 int err = 0;
c87f08ca 3651 int progress = 0;
5d4f98a2
YZ
3652
3653 path = btrfs_alloc_path();
3fd0a558 3654 if (!path)
5d4f98a2 3655 return -ENOMEM;
e4058b54 3656 path->reada = READA_FORWARD;
5d4f98a2 3657
3fd0a558
YZ
3658 ret = prepare_to_relocate(rc);
3659 if (ret) {
3660 err = ret;
3661 goto out_free;
3662 }
5d4f98a2
YZ
3663
3664 while (1) {
0647bf56 3665 rc->reserved_bytes = 0;
9270501c
JB
3666 ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv,
3667 rc->block_rsv->size,
3668 BTRFS_RESERVE_FLUSH_ALL);
0647bf56
WS
3669 if (ret) {
3670 err = ret;
3671 break;
3672 }
c87f08ca 3673 progress++;
a22285a6 3674 trans = btrfs_start_transaction(rc->extent_root, 0);
0f788c58
LB
3675 if (IS_ERR(trans)) {
3676 err = PTR_ERR(trans);
3677 trans = NULL;
3678 break;
3679 }
c87f08ca 3680restart:
3fd0a558 3681 if (update_backref_cache(trans, &rc->backref_cache)) {
3a45bb20 3682 btrfs_end_transaction(trans);
42a657f5 3683 trans = NULL;
3fd0a558
YZ
3684 continue;
3685 }
3686
147d256e 3687 ret = find_next_extent(rc, path, &key);
5d4f98a2
YZ
3688 if (ret < 0)
3689 err = ret;
3690 if (ret != 0)
3691 break;
3692
3693 rc->extents_found++;
3694
3695 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3696 struct btrfs_extent_item);
24cd6389 3697 flags = btrfs_extent_flags(path->nodes[0], ei);
5d4f98a2 3698
2672a051
BB
3699 /*
3700 * If we are relocating a simple quota owned extent item, we
3701 * need to note the owner on the reloc data root so that when
3702 * we allocate the replacement item, we can attribute it to the
3703 * correct eventual owner (rather than the reloc data root).
3704 */
3705 if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE) {
3706 struct btrfs_root *root = BTRFS_I(rc->data_inode)->root;
3707 u64 owning_root_id = btrfs_get_extent_owner_root(fs_info,
3708 path->nodes[0],
3709 path->slots[0]);
3710
3711 root->relocation_src_root = owning_root_id;
3712 }
3713
5d4f98a2
YZ
3714 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
3715 ret = add_tree_block(rc, &key, path, &blocks);
3716 } else if (rc->stage == UPDATE_DATA_PTRS &&
3fd0a558 3717 (flags & BTRFS_EXTENT_FLAG_DATA)) {
5d4f98a2
YZ
3718 ret = add_data_references(rc, &key, path, &blocks);
3719 } else {
b3b4aa74 3720 btrfs_release_path(path);
5d4f98a2
YZ
3721 ret = 0;
3722 }
3723 if (ret < 0) {
3fd0a558 3724 err = ret;
5d4f98a2
YZ
3725 break;
3726 }
3727
3728 if (!RB_EMPTY_ROOT(&blocks)) {
3729 ret = relocate_tree_blocks(trans, rc, &blocks);
3730 if (ret < 0) {
3fd0a558
YZ
3731 if (ret != -EAGAIN) {
3732 err = ret;
3733 break;
3734 }
3735 rc->extents_found--;
3736 rc->search_start = key.objectid;
3737 }
3738 }
3739
3a45bb20 3740 btrfs_end_transaction_throttle(trans);
2ff7e61e 3741 btrfs_btree_balance_dirty(fs_info);
5d4f98a2 3742 trans = NULL;
5d4f98a2
YZ
3743
3744 if (rc->stage == MOVE_DATA_EXTENTS &&
3745 (flags & BTRFS_EXTENT_FLAG_DATA)) {
d23d42e3 3746 rc->found_file_extent = true;
0257bb82 3747 ret = relocate_data_extent(rc->data_inode,
3fd0a558 3748 &key, &rc->cluster);
5d4f98a2
YZ
3749 if (ret < 0) {
3750 err = ret;
3751 break;
3752 }
3753 }
f31ea088
QW
3754 if (btrfs_should_cancel_balance(fs_info)) {
3755 err = -ECANCELED;
3756 break;
3757 }
5d4f98a2 3758 }
c87f08ca 3759 if (trans && progress && err == -ENOSPC) {
43a7e99d 3760 ret = btrfs_force_chunk_alloc(trans, rc->block_group->flags);
9689457b 3761 if (ret == 1) {
c87f08ca
CM
3762 err = 0;
3763 progress = 0;
3764 goto restart;
3765 }
3766 }
3fd0a558 3767
b3b4aa74 3768 btrfs_release_path(path);
91166212 3769 clear_extent_bits(&rc->processed_blocks, 0, (u64)-1, EXTENT_DIRTY);
5d4f98a2
YZ
3770
3771 if (trans) {
3a45bb20 3772 btrfs_end_transaction_throttle(trans);
2ff7e61e 3773 btrfs_btree_balance_dirty(fs_info);
5d4f98a2
YZ
3774 }
3775
0257bb82 3776 if (!err) {
3fd0a558
YZ
3777 ret = relocate_file_extent_cluster(rc->data_inode,
3778 &rc->cluster);
0257bb82
YZ
3779 if (ret < 0)
3780 err = ret;
3781 }
3782
d23d42e3 3783 rc->create_reloc_tree = false;
3fd0a558 3784 set_reloc_control(rc);
0257bb82 3785
13fe1bdb 3786 btrfs_backref_release_cache(&rc->backref_cache);
63f018be 3787 btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
5d4f98a2 3788
7f913c7c
QW
3789 /*
3790 * Even in the case when the relocation is cancelled, we should all go
3791 * through prepare_to_merge() and merge_reloc_roots().
3792 *
3793 * For error (including cancelled balance), prepare_to_merge() will
3794 * mark all reloc trees orphan, then queue them for cleanup in
3795 * merge_reloc_roots()
3796 */
3fd0a558 3797 err = prepare_to_merge(rc, err);
5d4f98a2
YZ
3798
3799 merge_reloc_roots(rc);
3800
d23d42e3 3801 rc->merge_reloc_tree = false;
5d4f98a2 3802 unset_reloc_control(rc);
63f018be 3803 btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
5d4f98a2
YZ
3804
3805 /* get rid of pinned extents */
7a7eaa40 3806 trans = btrfs_join_transaction(rc->extent_root);
62b99540 3807 if (IS_ERR(trans)) {
3612b495 3808 err = PTR_ERR(trans);
62b99540
QW
3809 goto out_free;
3810 }
fb686c68
JB
3811 ret = btrfs_commit_transaction(trans);
3812 if (ret && !err)
3813 err = ret;
6217b0fa 3814out_free:
d2311e69
QW
3815 ret = clean_dirty_subvols(rc);
3816 if (ret < 0 && !err)
3817 err = ret;
2ff7e61e 3818 btrfs_free_block_rsv(fs_info, rc->block_rsv);
3fd0a558 3819 btrfs_free_path(path);
5d4f98a2
YZ
3820 return err;
3821}
3822
3823static int __insert_orphan_inode(struct btrfs_trans_handle *trans,
0257bb82 3824 struct btrfs_root *root, u64 objectid)
5d4f98a2
YZ
3825{
3826 struct btrfs_path *path;
3827 struct btrfs_inode_item *item;
3828 struct extent_buffer *leaf;
3829 int ret;
3830
3831 path = btrfs_alloc_path();
3832 if (!path)
3833 return -ENOMEM;
3834
3835 ret = btrfs_insert_empty_inode(trans, root, path, objectid);
3836 if (ret)
3837 goto out;
3838
3839 leaf = path->nodes[0];
3840 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item);
b159fa28 3841 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
5d4f98a2 3842 btrfs_set_inode_generation(leaf, item, 1);
0257bb82 3843 btrfs_set_inode_size(leaf, item, 0);
5d4f98a2 3844 btrfs_set_inode_mode(leaf, item, S_IFREG | 0600);
960a3166
JT
3845 btrfs_set_inode_flags(leaf, item, BTRFS_INODE_NOCOMPRESS |
3846 BTRFS_INODE_PREALLOC);
50564b65 3847 btrfs_mark_buffer_dirty(trans, leaf);
5d4f98a2
YZ
3848out:
3849 btrfs_free_path(path);
3850 return ret;
3851}
3852
790c1b8c
JB
3853static void delete_orphan_inode(struct btrfs_trans_handle *trans,
3854 struct btrfs_root *root, u64 objectid)
3855{
3856 struct btrfs_path *path;
3857 struct btrfs_key key;
3858 int ret = 0;
3859
3860 path = btrfs_alloc_path();
3861 if (!path) {
3862 ret = -ENOMEM;
3863 goto out;
3864 }
3865
3866 key.objectid = objectid;
3867 key.type = BTRFS_INODE_ITEM_KEY;
3868 key.offset = 0;
3869 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3870 if (ret) {
3871 if (ret > 0)
3872 ret = -ENOENT;
3873 goto out;
3874 }
3875 ret = btrfs_del_item(trans, root, path);
3876out:
3877 if (ret)
3878 btrfs_abort_transaction(trans, ret);
3879 btrfs_free_path(path);
3880}
3881
5d4f98a2
YZ
3882/*
3883 * helper to create inode for data relocation.
3884 * the inode is in data relocation tree and its link count is 0
3885 */
ab7c8bbf
DS
3886static noinline_for_stack struct inode *create_reloc_inode(
3887 struct btrfs_fs_info *fs_info,
3888 const struct btrfs_block_group *group)
5d4f98a2
YZ
3889{
3890 struct inode *inode = NULL;
3891 struct btrfs_trans_handle *trans;
3892 struct btrfs_root *root;
4624900d 3893 u64 objectid;
04e4e189 3894 int ret = 0;
5d4f98a2 3895
aeb935a4 3896 root = btrfs_grab_root(fs_info->data_reloc_root);
a22285a6 3897 trans = btrfs_start_transaction(root, 6);
76deacf0 3898 if (IS_ERR(trans)) {
00246528 3899 btrfs_put_root(root);
3fd0a558 3900 return ERR_CAST(trans);
76deacf0 3901 }
5d4f98a2 3902
04e4e189
AJ
3903 ret = btrfs_get_free_objectid(root, &objectid);
3904 if (ret)
5d4f98a2
YZ
3905 goto out;
3906
04e4e189
AJ
3907 ret = __insert_orphan_inode(trans, root, objectid);
3908 if (ret)
790c1b8c 3909 goto out;
5d4f98a2 3910
0202e83f 3911 inode = btrfs_iget(fs_info->sb, objectid, root);
790c1b8c
JB
3912 if (IS_ERR(inode)) {
3913 delete_orphan_inode(trans, root, objectid);
04e4e189 3914 ret = PTR_ERR(inode);
790c1b8c
JB
3915 inode = NULL;
3916 goto out;
3917 }
b3470b5d 3918 BTRFS_I(inode)->index_cnt = group->start;
5d4f98a2 3919
04e4e189 3920 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5d4f98a2 3921out:
00246528 3922 btrfs_put_root(root);
3a45bb20 3923 btrfs_end_transaction(trans);
2ff7e61e 3924 btrfs_btree_balance_dirty(fs_info);
04e4e189 3925 if (ret) {
8aa1e49e 3926 iput(inode);
04e4e189 3927 inode = ERR_PTR(ret);
5d4f98a2
YZ
3928 }
3929 return inode;
3930}
3931
907d2710
DS
3932/*
3933 * Mark start of chunk relocation that is cancellable. Check if the cancellation
3934 * has been requested meanwhile and don't start in that case.
3935 *
3936 * Return:
3937 * 0 success
3938 * -EINPROGRESS operation is already in progress, that's probably a bug
3939 * -ECANCELED cancellation request was set before the operation started
3940 */
3941static int reloc_chunk_start(struct btrfs_fs_info *fs_info)
3942{
3943 if (test_and_set_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags)) {
3944 /* This should not happen */
3945 btrfs_err(fs_info, "reloc already running, cannot start");
3946 return -EINPROGRESS;
3947 }
3948
3949 if (atomic_read(&fs_info->reloc_cancel_req) > 0) {
3950 btrfs_info(fs_info, "chunk relocation canceled on start");
3951 /*
3952 * On cancel, clear all requests but let the caller mark
3953 * the end after cleanup operations.
3954 */
3955 atomic_set(&fs_info->reloc_cancel_req, 0);
3956 return -ECANCELED;
3957 }
3958 return 0;
3959}
3960
3961/*
3962 * Mark end of chunk relocation that is cancellable and wake any waiters.
3963 */
3964static void reloc_chunk_end(struct btrfs_fs_info *fs_info)
3965{
3966 /* Requested after start, clear bit first so any waiters can continue */
3967 if (atomic_read(&fs_info->reloc_cancel_req) > 0)
3968 btrfs_info(fs_info, "chunk relocation canceled during operation");
3969 clear_and_wake_up_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags);
3970 atomic_set(&fs_info->reloc_cancel_req, 0);
3971}
3972
c258d6e3 3973static struct reloc_control *alloc_reloc_control(struct btrfs_fs_info *fs_info)
3fd0a558
YZ
3974{
3975 struct reloc_control *rc;
3976
3977 rc = kzalloc(sizeof(*rc), GFP_NOFS);
3978 if (!rc)
3979 return NULL;
3980
3981 INIT_LIST_HEAD(&rc->reloc_roots);
d2311e69 3982 INIT_LIST_HEAD(&rc->dirty_subvol_roots);
c71d3c69 3983 btrfs_backref_init_cache(fs_info, &rc->backref_cache, true);
733fa44d
DS
3984 rc->reloc_root_tree.rb_root = RB_ROOT;
3985 spin_lock_init(&rc->reloc_root_tree.lock);
35da5a7e 3986 extent_io_tree_init(fs_info, &rc->processed_blocks, IO_TREE_RELOC_BLOCKS);
3fd0a558
YZ
3987 return rc;
3988}
3989
1a0afa0e
JB
3990static void free_reloc_control(struct reloc_control *rc)
3991{
3992 struct mapping_node *node, *tmp;
3993
3994 free_reloc_roots(&rc->reloc_roots);
3995 rbtree_postorder_for_each_entry_safe(node, tmp,
3996 &rc->reloc_root_tree.rb_root, rb_node)
3997 kfree(node);
3998
3999 kfree(rc);
4000}
4001
ebce0e01
AB
4002/*
4003 * Print the block group being relocated
4004 */
4005static void describe_relocation(struct btrfs_fs_info *fs_info,
32da5386 4006 struct btrfs_block_group *block_group)
ebce0e01 4007{
f89e09cf 4008 char buf[128] = {'\0'};
ebce0e01 4009
f89e09cf 4010 btrfs_describe_block_groups(block_group->flags, buf, sizeof(buf));
ebce0e01
AB
4011
4012 btrfs_info(fs_info,
4013 "relocating block group %llu flags %s",
b3470b5d 4014 block_group->start, buf);
ebce0e01
AB
4015}
4016
8daf07cf 4017static const char *stage_to_string(enum reloc_stage stage)
430640e3
QW
4018{
4019 if (stage == MOVE_DATA_EXTENTS)
4020 return "move data extents";
4021 if (stage == UPDATE_DATA_PTRS)
4022 return "update data pointers";
4023 return "unknown";
4024}
4025
5d4f98a2
YZ
4026/*
4027 * function to relocate all extents in a block group.
4028 */
6bccf3ab 4029int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start)
5d4f98a2 4030{
32da5386 4031 struct btrfs_block_group *bg;
29cbcf40 4032 struct btrfs_root *extent_root = btrfs_extent_root(fs_info, group_start);
5d4f98a2 4033 struct reloc_control *rc;
0af3d00b
JB
4034 struct inode *inode;
4035 struct btrfs_path *path;
5d4f98a2 4036 int ret;
f0486c68 4037 int rw = 0;
5d4f98a2
YZ
4038 int err = 0;
4039
b4be6aef
JB
4040 /*
4041 * This only gets set if we had a half-deleted snapshot on mount. We
4042 * cannot allow relocation to start while we're still trying to clean up
4043 * these pending deletions.
4044 */
4045 ret = wait_on_bit(&fs_info->flags, BTRFS_FS_UNFINISHED_DROPS, TASK_INTERRUPTIBLE);
4046 if (ret)
4047 return ret;
4048
4049 /* We may have been woken up by close_ctree, so bail if we're closing. */
4050 if (btrfs_fs_closing(fs_info))
4051 return -EINTR;
4052
eede2bf3
OS
4053 bg = btrfs_lookup_block_group(fs_info, group_start);
4054 if (!bg)
4055 return -ENOENT;
4056
0320b353
NA
4057 /*
4058 * Relocation of a data block group creates ordered extents. Without
4059 * sb_start_write(), we can freeze the filesystem while unfinished
4060 * ordered extents are left. Such ordered extents can cause a deadlock
4061 * e.g. when syncfs() is waiting for their completion but they can't
4062 * finish because they block when joining a transaction, due to the
4063 * fact that the freeze locks are being held in write mode.
4064 */
4065 if (bg->flags & BTRFS_BLOCK_GROUP_DATA)
4066 ASSERT(sb_write_started(fs_info->sb));
4067
eede2bf3
OS
4068 if (btrfs_pinned_by_swapfile(fs_info, bg)) {
4069 btrfs_put_block_group(bg);
4070 return -ETXTBSY;
4071 }
4072
c258d6e3 4073 rc = alloc_reloc_control(fs_info);
eede2bf3
OS
4074 if (!rc) {
4075 btrfs_put_block_group(bg);
5d4f98a2 4076 return -ENOMEM;
eede2bf3 4077 }
5d4f98a2 4078
907d2710
DS
4079 ret = reloc_chunk_start(fs_info);
4080 if (ret < 0) {
4081 err = ret;
4082 goto out_put_bg;
4083 }
4084
f0486c68 4085 rc->extent_root = extent_root;
eede2bf3 4086 rc->block_group = bg;
5d4f98a2 4087
b12de528 4088 ret = btrfs_inc_block_group_ro(rc->block_group, true);
868f401a
Z
4089 if (ret) {
4090 err = ret;
4091 goto out;
f0486c68 4092 }
868f401a 4093 rw = 1;
f0486c68 4094
0af3d00b
JB
4095 path = btrfs_alloc_path();
4096 if (!path) {
4097 err = -ENOMEM;
4098 goto out;
4099 }
4100
7949f339 4101 inode = lookup_free_space_inode(rc->block_group, path);
0af3d00b
JB
4102 btrfs_free_path(path);
4103
4104 if (!IS_ERR(inode))
1bbc621e 4105 ret = delete_block_group_cache(fs_info, rc->block_group, inode, 0);
0af3d00b
JB
4106 else
4107 ret = PTR_ERR(inode);
4108
4109 if (ret && ret != -ENOENT) {
4110 err = ret;
4111 goto out;
4112 }
4113
5d4f98a2
YZ
4114 rc->data_inode = create_reloc_inode(fs_info, rc->block_group);
4115 if (IS_ERR(rc->data_inode)) {
4116 err = PTR_ERR(rc->data_inode);
4117 rc->data_inode = NULL;
4118 goto out;
4119 }
4120
0b246afa 4121 describe_relocation(fs_info, rc->block_group);
5d4f98a2 4122
9cfa3e34 4123 btrfs_wait_block_group_reservations(rc->block_group);
f78c436c 4124 btrfs_wait_nocow_writers(rc->block_group);
6374e57a 4125 btrfs_wait_ordered_roots(fs_info, U64_MAX,
b3470b5d
DS
4126 rc->block_group->start,
4127 rc->block_group->length);
5d4f98a2 4128
7ae9bd18
NA
4129 ret = btrfs_zone_finish(rc->block_group);
4130 WARN_ON(ret && ret != -EAGAIN);
4131
5d4f98a2 4132 while (1) {
8daf07cf 4133 enum reloc_stage finishes_stage;
430640e3 4134
76dda93c 4135 mutex_lock(&fs_info->cleaner_mutex);
5d4f98a2 4136 ret = relocate_block_group(rc);
76dda93c 4137 mutex_unlock(&fs_info->cleaner_mutex);
ff612ba7 4138 if (ret < 0)
5d4f98a2 4139 err = ret;
5d4f98a2 4140
430640e3 4141 finishes_stage = rc->stage;
ff612ba7
JB
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 */
5d4f98a2 4151 if (rc->stage == MOVE_DATA_EXTENTS && rc->found_file_extent) {
0ef8b726
JB
4152 ret = btrfs_wait_ordered_range(rc->data_inode, 0,
4153 (u64)-1);
ff612ba7 4154 if (ret)
0ef8b726 4155 err = ret;
5d4f98a2
YZ
4156 invalidate_mapping_pages(rc->data_inode->i_mapping,
4157 0, -1);
4158 rc->stage = UPDATE_DATA_PTRS;
5d4f98a2 4159 }
ff612ba7
JB
4160
4161 if (err < 0)
4162 goto out;
4163
4164 if (rc->extents_found == 0)
4165 break;
4166
430640e3
QW
4167 btrfs_info(fs_info, "found %llu extents, stage: %s",
4168 rc->extents_found, stage_to_string(finishes_stage));
5d4f98a2
YZ
4169 }
4170
5d4f98a2
YZ
4171 WARN_ON(rc->block_group->pinned > 0);
4172 WARN_ON(rc->block_group->reserved > 0);
bf38be65 4173 WARN_ON(rc->block_group->used > 0);
5d4f98a2 4174out:
f0486c68 4175 if (err && rw)
2ff7e61e 4176 btrfs_dec_block_group_ro(rc->block_group);
5d4f98a2 4177 iput(rc->data_inode);
907d2710
DS
4178out_put_bg:
4179 btrfs_put_block_group(bg);
4180 reloc_chunk_end(fs_info);
1a0afa0e 4181 free_reloc_control(rc);
5d4f98a2
YZ
4182 return err;
4183}
4184
76dda93c
YZ
4185static noinline_for_stack int mark_garbage_root(struct btrfs_root *root)
4186{
0b246afa 4187 struct btrfs_fs_info *fs_info = root->fs_info;
76dda93c 4188 struct btrfs_trans_handle *trans;
79787eaa 4189 int ret, err;
76dda93c 4190
0b246afa 4191 trans = btrfs_start_transaction(fs_info->tree_root, 0);
79787eaa
JM
4192 if (IS_ERR(trans))
4193 return PTR_ERR(trans);
76dda93c
YZ
4194
4195 memset(&root->root_item.drop_progress, 0,
4196 sizeof(root->root_item.drop_progress));
c8422684 4197 btrfs_set_root_drop_level(&root->root_item, 0);
76dda93c 4198 btrfs_set_root_refs(&root->root_item, 0);
0b246afa 4199 ret = btrfs_update_root(trans, fs_info->tree_root,
76dda93c 4200 &root->root_key, &root->root_item);
76dda93c 4201
3a45bb20 4202 err = btrfs_end_transaction(trans);
79787eaa
JM
4203 if (err)
4204 return err;
4205 return ret;
76dda93c
YZ
4206}
4207
5d4f98a2
YZ
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 */
7eefae6b 4214int btrfs_recover_relocation(struct btrfs_fs_info *fs_info)
5d4f98a2
YZ
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 ret;
4225 int err = 0;
4226
4227 path = btrfs_alloc_path();
4228 if (!path)
4229 return -ENOMEM;
e4058b54 4230 path->reada = READA_BACK;
5d4f98a2
YZ
4231
4232 key.objectid = BTRFS_TREE_RELOC_OBJECTID;
4233 key.type = BTRFS_ROOT_ITEM_KEY;
4234 key.offset = (u64)-1;
4235
4236 while (1) {
0b246afa 4237 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key,
5d4f98a2
YZ
4238 path, 0, 0);
4239 if (ret < 0) {
4240 err = ret;
4241 goto out;
4242 }
4243 if (ret > 0) {
4244 if (path->slots[0] == 0)
4245 break;
4246 path->slots[0]--;
4247 }
4248 leaf = path->nodes[0];
4249 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
b3b4aa74 4250 btrfs_release_path(path);
5d4f98a2
YZ
4251
4252 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID ||
4253 key.type != BTRFS_ROOT_ITEM_KEY)
4254 break;
4255
7eefae6b 4256 reloc_root = btrfs_read_tree_root(fs_info->tree_root, &key);
5d4f98a2
YZ
4257 if (IS_ERR(reloc_root)) {
4258 err = PTR_ERR(reloc_root);
4259 goto out;
4260 }
4261
92a7cc42 4262 set_bit(BTRFS_ROOT_SHAREABLE, &reloc_root->state);
5d4f98a2
YZ
4263 list_add(&reloc_root->root_list, &reloc_roots);
4264
4265 if (btrfs_root_refs(&reloc_root->root_item) > 0) {
a820feb5
DS
4266 fs_root = btrfs_get_fs_root(fs_info,
4267 reloc_root->root_key.offset, false);
5d4f98a2 4268 if (IS_ERR(fs_root)) {
76dda93c
YZ
4269 ret = PTR_ERR(fs_root);
4270 if (ret != -ENOENT) {
4271 err = ret;
4272 goto out;
4273 }
79787eaa
JM
4274 ret = mark_garbage_root(reloc_root);
4275 if (ret < 0) {
4276 err = ret;
4277 goto out;
4278 }
932fd26d 4279 } else {
00246528 4280 btrfs_put_root(fs_root);
5d4f98a2
YZ
4281 }
4282 }
4283
4284 if (key.offset == 0)
4285 break;
4286
4287 key.offset--;
4288 }
b3b4aa74 4289 btrfs_release_path(path);
5d4f98a2
YZ
4290
4291 if (list_empty(&reloc_roots))
4292 goto out;
4293
c258d6e3 4294 rc = alloc_reloc_control(fs_info);
5d4f98a2
YZ
4295 if (!rc) {
4296 err = -ENOMEM;
4297 goto out;
4298 }
4299
907d2710
DS
4300 ret = reloc_chunk_start(fs_info);
4301 if (ret < 0) {
4302 err = ret;
4303 goto out_end;
4304 }
4305
29cbcf40 4306 rc->extent_root = btrfs_extent_root(fs_info, 0);
5d4f98a2
YZ
4307
4308 set_reloc_control(rc);
4309
7a7eaa40 4310 trans = btrfs_join_transaction(rc->extent_root);
3612b495 4311 if (IS_ERR(trans)) {
3612b495 4312 err = PTR_ERR(trans);
fb2d83ee 4313 goto out_unset;
3612b495 4314 }
3fd0a558 4315
d23d42e3 4316 rc->merge_reloc_tree = true;
3fd0a558 4317
5d4f98a2
YZ
4318 while (!list_empty(&reloc_roots)) {
4319 reloc_root = list_entry(reloc_roots.next,
4320 struct btrfs_root, root_list);
4321 list_del(&reloc_root->root_list);
4322
4323 if (btrfs_root_refs(&reloc_root->root_item) == 0) {
4324 list_add_tail(&reloc_root->root_list,
4325 &rc->reloc_roots);
4326 continue;
4327 }
4328
a820feb5
DS
4329 fs_root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
4330 false);
79787eaa
JM
4331 if (IS_ERR(fs_root)) {
4332 err = PTR_ERR(fs_root);
ca1aa281 4333 list_add_tail(&reloc_root->root_list, &reloc_roots);
1402d17d 4334 btrfs_end_transaction(trans);
fb2d83ee 4335 goto out_unset;
79787eaa 4336 }
5d4f98a2 4337
ffd7b339 4338 err = __add_reloc_root(reloc_root);
57a304cf 4339 ASSERT(err != -EEXIST);
3c925863
JB
4340 if (err) {
4341 list_add_tail(&reloc_root->root_list, &reloc_roots);
4342 btrfs_put_root(fs_root);
4343 btrfs_end_transaction(trans);
4344 goto out_unset;
4345 }
f44deb74 4346 fs_root->reloc_root = btrfs_grab_root(reloc_root);
00246528 4347 btrfs_put_root(fs_root);
5d4f98a2
YZ
4348 }
4349
3a45bb20 4350 err = btrfs_commit_transaction(trans);
79787eaa 4351 if (err)
fb2d83ee 4352 goto out_unset;
5d4f98a2
YZ
4353
4354 merge_reloc_roots(rc);
4355
4356 unset_reloc_control(rc);
4357
7a7eaa40 4358 trans = btrfs_join_transaction(rc->extent_root);
62b99540 4359 if (IS_ERR(trans)) {
3612b495 4360 err = PTR_ERR(trans);
6217b0fa 4361 goto out_clean;
62b99540 4362 }
3a45bb20 4363 err = btrfs_commit_transaction(trans);
6217b0fa 4364out_clean:
d2311e69
QW
4365 ret = clean_dirty_subvols(rc);
4366 if (ret < 0 && !err)
4367 err = ret;
fb2d83ee
JB
4368out_unset:
4369 unset_reloc_control(rc);
907d2710
DS
4370out_end:
4371 reloc_chunk_end(fs_info);
1a0afa0e 4372 free_reloc_control(rc);
3612b495 4373out:
a7571232 4374 free_reloc_roots(&reloc_roots);
aca1bba6 4375
5d4f98a2
YZ
4376 btrfs_free_path(path);
4377
4378 if (err == 0) {
4379 /* cleanup orphan inode in data relocation tree */
aeb935a4
QW
4380 fs_root = btrfs_grab_root(fs_info->data_reloc_root);
4381 ASSERT(fs_root);
4382 err = btrfs_orphan_cleanup(fs_root);
4383 btrfs_put_root(fs_root);
5d4f98a2
YZ
4384 }
4385 return err;
4386}
4387
4388/*
4389 * helper to add ordered checksum for data relocation.
4390 *
4391 * cloning checksum properly handles the nodatasum extents.
4392 * it also saves CPU time to re-calculate the checksum.
4393 */
34bfaf15 4394int btrfs_reloc_clone_csums(struct btrfs_ordered_extent *ordered)
5d4f98a2 4395{
34bfaf15 4396 struct btrfs_inode *inode = BTRFS_I(ordered->inode);
7bfa9535 4397 struct btrfs_fs_info *fs_info = inode->root->fs_info;
34bfaf15
CH
4398 u64 disk_bytenr = ordered->file_offset + inode->index_cnt;
4399 struct btrfs_root *csum_root = btrfs_csum_root(fs_info, disk_bytenr);
5d4f98a2 4400 LIST_HEAD(list);
34bfaf15 4401 int ret;
5d4f98a2 4402
97e38239 4403 ret = btrfs_lookup_csums_list(csum_root, disk_bytenr,
34bfaf15 4404 disk_bytenr + ordered->num_bytes - 1,
afcb8062 4405 &list, false);
aa5ccf29
JB
4406 if (ret < 0) {
4407 btrfs_mark_ordered_extent_error(ordered);
34bfaf15 4408 return ret;
aa5ccf29 4409 }
5d4f98a2
YZ
4410
4411 while (!list_empty(&list)) {
34bfaf15
CH
4412 struct btrfs_ordered_sum *sums =
4413 list_entry(list.next, struct btrfs_ordered_sum, list);
4414
5d4f98a2
YZ
4415 list_del_init(&sums->list);
4416
4577b014
JB
4417 /*
4418 * We need to offset the new_bytenr based on where the csum is.
4419 * We need to do this because we will read in entire prealloc
4420 * extents but we may have written to say the middle of the
4421 * prealloc extent, so we need to make sure the csum goes with
4422 * the right disk offset.
4423 *
4424 * We can do this because the data reloc inode refers strictly
4425 * to the on disk bytes, so we don't have to worry about
4426 * disk_len vs real len like with real inodes since it's all
4427 * disk length.
4428 */
34bfaf15 4429 sums->logical = ordered->disk_bytenr + sums->logical - disk_bytenr;
f9756261 4430 btrfs_add_ordered_sum(ordered, sums);
5d4f98a2 4431 }
34bfaf15
CH
4432
4433 return 0;
5d4f98a2 4434}
3fd0a558 4435
83d4cfd4 4436int btrfs_reloc_cow_block(struct btrfs_trans_handle *trans,
ab7c8bbf
DS
4437 struct btrfs_root *root,
4438 const struct extent_buffer *buf,
83d4cfd4 4439 struct extent_buffer *cow)
3fd0a558 4440{
0b246afa 4441 struct btrfs_fs_info *fs_info = root->fs_info;
3fd0a558 4442 struct reloc_control *rc;
a26195a5 4443 struct btrfs_backref_node *node;
3fd0a558
YZ
4444 int first_cow = 0;
4445 int level;
83d4cfd4 4446 int ret = 0;
3fd0a558 4447
0b246afa 4448 rc = fs_info->reloc_ctl;
3fd0a558 4449 if (!rc)
83d4cfd4 4450 return 0;
3fd0a558 4451
37f00a6d 4452 BUG_ON(rc->stage == UPDATE_DATA_PTRS && btrfs_is_data_reloc_root(root));
3fd0a558
YZ
4453
4454 level = btrfs_header_level(buf);
4455 if (btrfs_header_generation(buf) <=
4456 btrfs_root_last_snapshot(&root->root_item))
4457 first_cow = 1;
4458
e094f480 4459 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID && rc->create_reloc_tree) {
3fd0a558
YZ
4460 WARN_ON(!first_cow && level == 0);
4461
4462 node = rc->backref_cache.path[level];
4463 BUG_ON(node->bytenr != buf->start &&
4464 node->new_bytenr != buf->start);
4465
b0fe7078 4466 btrfs_backref_drop_node_buffer(node);
67439dad 4467 atomic_inc(&cow->refs);
3fd0a558
YZ
4468 node->eb = cow;
4469 node->new_bytenr = cow->start;
4470
4471 if (!node->pending) {
4472 list_move_tail(&node->list,
4473 &rc->backref_cache.pending[level]);
4474 node->pending = 1;
4475 }
4476
4477 if (first_cow)
9569cc20 4478 mark_block_processed(rc, node);
3fd0a558
YZ
4479
4480 if (first_cow && level > 0)
4481 rc->nodes_relocated += buf->len;
4482 }
4483
83d4cfd4 4484 if (level == 0 && first_cow && rc->stage == UPDATE_DATA_PTRS)
3fd0a558 4485 ret = replace_file_extents(trans, rc, root, cow);
83d4cfd4 4486 return ret;
3fd0a558
YZ
4487}
4488
4489/*
4490 * called before creating snapshot. it calculates metadata reservation
01327610 4491 * required for relocating tree blocks in the snapshot
3fd0a558 4492 */
147d256e 4493void btrfs_reloc_pre_snapshot(struct btrfs_pending_snapshot *pending,
3fd0a558
YZ
4494 u64 *bytes_to_reserve)
4495{
10995c04
QW
4496 struct btrfs_root *root = pending->root;
4497 struct reloc_control *rc = root->fs_info->reloc_ctl;
3fd0a558 4498
6282675e 4499 if (!rc || !have_reloc_root(root))
3fd0a558
YZ
4500 return;
4501
3fd0a558
YZ
4502 if (!rc->merge_reloc_tree)
4503 return;
4504
4505 root = root->reloc_root;
4506 BUG_ON(btrfs_root_refs(&root->root_item) == 0);
4507 /*
4508 * relocation is in the stage of merging trees. the space
4509 * used by merging a reloc tree is twice the size of
4510 * relocated tree nodes in the worst case. half for cowing
4511 * the reloc tree, half for cowing the fs tree. the space
4512 * used by cowing the reloc tree will be freed after the
4513 * tree is dropped. if we create snapshot, cowing the fs
4514 * tree may use more space than it frees. so we need
4515 * reserve extra space.
4516 */
4517 *bytes_to_reserve += rc->nodes_relocated;
4518}
4519
4520/*
4521 * called after snapshot is created. migrate block reservation
4522 * and create reloc root for the newly created snapshot
f44deb74
JB
4523 *
4524 * This is similar to btrfs_init_reloc_root(), we come out of here with two
4525 * references held on the reloc_root, one for root->reloc_root and one for
4526 * rc->reloc_roots.
3fd0a558 4527 */
49b25e05 4528int btrfs_reloc_post_snapshot(struct btrfs_trans_handle *trans,
3fd0a558
YZ
4529 struct btrfs_pending_snapshot *pending)
4530{
4531 struct btrfs_root *root = pending->root;
4532 struct btrfs_root *reloc_root;
4533 struct btrfs_root *new_root;
10995c04 4534 struct reloc_control *rc = root->fs_info->reloc_ctl;
3fd0a558
YZ
4535 int ret;
4536
6282675e 4537 if (!rc || !have_reloc_root(root))
49b25e05 4538 return 0;
3fd0a558
YZ
4539
4540 rc = root->fs_info->reloc_ctl;
4541 rc->merging_rsv_size += rc->nodes_relocated;
4542
4543 if (rc->merge_reloc_tree) {
4544 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
4545 rc->block_rsv,
3a584174 4546 rc->nodes_relocated, true);
49b25e05
JM
4547 if (ret)
4548 return ret;
3fd0a558
YZ
4549 }
4550
4551 new_root = pending->snap;
e094f480 4552 reloc_root = create_reloc_root(trans, root->reloc_root, btrfs_root_id(new_root));
49b25e05
JM
4553 if (IS_ERR(reloc_root))
4554 return PTR_ERR(reloc_root);
3fd0a558 4555
ffd7b339 4556 ret = __add_reloc_root(reloc_root);
57a304cf 4557 ASSERT(ret != -EEXIST);
3c925863
JB
4558 if (ret) {
4559 /* Pairs with create_reloc_root */
4560 btrfs_put_root(reloc_root);
4561 return ret;
4562 }
f44deb74 4563 new_root->reloc_root = btrfs_grab_root(reloc_root);
3fd0a558 4564
49b25e05 4565 if (rc->create_reloc_tree)
3fd0a558 4566 ret = clone_backref_node(trans, rc, root, reloc_root);
49b25e05 4567 return ret;
3fd0a558 4568}
b9a9a850
QW
4569
4570/*
4571 * Get the current bytenr for the block group which is being relocated.
4572 *
4573 * Return U64_MAX if no running relocation.
4574 */
ab7c8bbf 4575u64 btrfs_get_reloc_bg_bytenr(const struct btrfs_fs_info *fs_info)
b9a9a850
QW
4576{
4577 u64 logical = U64_MAX;
4578
4579 lockdep_assert_held(&fs_info->reloc_mutex);
4580
4581 if (fs_info->reloc_ctl && fs_info->reloc_ctl->block_group)
4582 logical = fs_info->reloc_ctl->block_group->start;
4583 return logical;
4584}