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