1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (C) 2009 Oracle. All rights reserved.
4 */
5
6 #include <linux/sched.h>
7 #include <linux/pagemap.h>
8 #include <linux/writeback.h>
9 #include <linux/blkdev.h>
10 #include <linux/rbtree.h>
11 #include <linux/slab.h>
12 #include <linux/error-injection.h>
13 #include "ctree.h"
14 #include "disk-io.h"
15 #include "transaction.h"
16 #include "volumes.h"
17 #include "locking.h"
18 #include "btrfs_inode.h"
19 #include "async-thread.h"
20 #include "free-space-cache.h"
21 #include "qgroup.h"
22 #include "print-tree.h"
23 #include "delalloc-space.h"
24 #include "block-group.h"
25 #include "backref.h"
26 #include "misc.h"
27 #include "subpage.h"
28 #include "zoned.h"
29 #include "inode-item.h"
30 #include "space-info.h"
31 #include "fs.h"
32 #include "accessors.h"
33 #include "extent-tree.h"
34 #include "root-tree.h"
35 #include "file-item.h"
36 #include "relocation.h"
37 #include "super.h"
38 #include "tree-checker.h"
39 #include "raid-stripe-tree.h"
40 #include "free-space-tree.h"
41
42 /*
43 * Relocation overview
44 *
45 * [What does relocation do]
46 *
47 * The objective of relocation is to relocate all extents of the target block
48 * group to other block groups.
49 * This is utilized by resize (shrink only), profile converting, compacting
50 * space, or balance routine to spread chunks over devices.
51 *
52 * Before | After
53 * ------------------------------------------------------------------
54 * BG A: 10 data extents | BG A: deleted
55 * BG B: 2 data extents | BG B: 10 data extents (2 old + 8 relocated)
56 * BG C: 1 extents | BG C: 3 data extents (1 old + 2 relocated)
57 *
58 * [How does relocation work]
59 *
60 * 1. Mark the target block group read-only
61 * New extents won't be allocated from the target block group.
62 *
63 * 2.1 Record each extent in the target block group
64 * To build a proper map of extents to be relocated.
65 *
66 * 2.2 Build data reloc tree and reloc trees
67 * Data reloc tree will contain an inode, recording all newly relocated
68 * data extents.
69 * There will be only one data reloc tree for one data block group.
70 *
71 * Reloc tree will be a special snapshot of its source tree, containing
72 * relocated tree blocks.
73 * Each tree referring to a tree block in target block group will get its
74 * reloc tree built.
75 *
76 * 2.3 Swap source tree with its corresponding reloc tree
77 * Each involved tree only refers to new extents after swap.
78 *
79 * 3. Cleanup reloc trees and data reloc tree.
80 * As old extents in the target block group are still referenced by reloc
81 * trees, we need to clean them up before really freeing the target block
82 * group.
83 *
84 * The main complexity is in steps 2.2 and 2.3.
85 *
86 * The entry point of relocation is relocate_block_group() function.
87 */
88
89 #define RELOCATION_RESERVED_NODES 256
90 /*
91 * map address of tree root to tree
92 */
93 struct mapping_node {
94 union {
95 /* Use rb_simple_node for search/insert */
96 struct {
97 struct rb_node rb_node;
98 u64 bytenr;
99 };
100
101 struct rb_simple_node simple_node;
102 };
103 void *data;
104 };
105
106 struct mapping_tree {
107 struct rb_root rb_root;
108 spinlock_t lock;
109 };
110
111 /*
112 * present a tree block to process
113 */
114 struct tree_block {
115 union {
116 /* Use rb_simple_node for search/insert */
117 struct {
118 struct rb_node rb_node;
119 u64 bytenr;
120 };
121
122 struct rb_simple_node simple_node;
123 };
124 u64 owner;
125 struct btrfs_key key;
126 u8 level;
127 bool key_ready;
128 };
129
130 #define MAX_EXTENTS 128
131
132 struct file_extent_cluster {
133 u64 start;
134 u64 end;
135 u64 boundary[MAX_EXTENTS];
136 unsigned int nr;
137 u64 owning_root;
138 };
139
140 /* Stages of data relocation. */
141 enum reloc_stage {
142 MOVE_DATA_EXTENTS,
143 UPDATE_DATA_PTRS
144 };
145
146 struct reloc_control {
147 /* block group to relocate */
148 struct btrfs_block_group *block_group;
149 /* extent tree */
150 struct btrfs_root *extent_root;
151 /* inode for moving data */
152 struct inode *data_inode;
153
154 struct btrfs_block_rsv *block_rsv;
155
156 struct btrfs_backref_cache backref_cache;
157
158 struct file_extent_cluster cluster;
159 /* tree blocks have been processed */
160 struct extent_io_tree processed_blocks;
161 /* map start of tree root to corresponding reloc tree */
162 struct mapping_tree reloc_root_tree;
163 /* list of reloc trees */
164 struct list_head reloc_roots;
165 /* list of subvolume trees that get relocated */
166 struct list_head dirty_subvol_roots;
167 /* size of metadata reservation for merging reloc trees */
168 u64 merging_rsv_size;
169 /* size of relocated tree nodes */
170 u64 nodes_relocated;
171 /* reserved size for block group relocation*/
172 u64 reserved_bytes;
173
174 u64 search_start;
175 u64 extents_found;
176
177 enum reloc_stage stage;
178 bool create_reloc_tree;
179 bool merge_reloc_tree;
180 bool found_file_extent;
181
182 refcount_t refs;
183 };
184
get_reloc_control(struct btrfs_fs_info * fs_info)185 static struct reloc_control *get_reloc_control(struct btrfs_fs_info *fs_info)
186 {
187 struct reloc_control *rc;
188
189 /* Quick path, avoid lock contention on fs_info->reloc_ctl_lock. */
190 if (!data_race(fs_info->reloc_ctl))
191 return NULL;
192
193 spin_lock(&fs_info->reloc_ctl_lock);
194 rc = fs_info->reloc_ctl;
195 if (rc)
196 refcount_inc(&rc->refs);
197 spin_unlock(&fs_info->reloc_ctl_lock);
198
199 return rc;
200 }
201
202 static void __del_reloc_root(struct btrfs_root *root);
203
free_reloc_roots(struct list_head * list)204 static noinline_for_stack void free_reloc_roots(struct list_head *list)
205 {
206 struct btrfs_root *reloc_root, *tmp;
207
208 list_for_each_entry_safe(reloc_root, tmp, list, root_list)
209 __del_reloc_root(reloc_root);
210 }
211
put_reloc_control(struct reloc_control * rc)212 static void put_reloc_control(struct reloc_control *rc)
213 {
214 if (refcount_dec_and_test(&rc->refs)) {
215 struct mapping_node *node, *tmp;
216
217 if (rc->extent_root)
218 ASSERT(rc->extent_root->fs_info->reloc_ctl != rc);
219
220 free_reloc_roots(&rc->reloc_roots);
221 rbtree_postorder_for_each_entry_safe(node, tmp,
222 &rc->reloc_root_tree.rb_root,
223 rb_node)
224 kfree(node);
225
226 if (rc->block_group)
227 btrfs_put_block_group(rc->block_group);
228
229 kfree(rc);
230 }
231 }
232
233 /* Helper to delete the 'address of tree root -> reloc tree' mapping. */
__del_reloc_root(struct btrfs_root * root)234 static void __del_reloc_root(struct btrfs_root *root)
235 {
236 struct btrfs_fs_info *fs_info = root->fs_info;
237 struct rb_node *rb_node;
238 struct mapping_node AUTO_KFREE(node);
239 struct reloc_control *rc;
240 bool put_ref = false;
241
242 rc = get_reloc_control(fs_info);
243 if (rc && root->node) {
244 spin_lock(&rc->reloc_root_tree.lock);
245 rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
246 root->commit_root->start);
247 if (rb_node) {
248 node = rb_entry(rb_node, struct mapping_node, rb_node);
249 rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
250 RB_CLEAR_NODE(&node->rb_node);
251 }
252 spin_unlock(&rc->reloc_root_tree.lock);
253 ASSERT(!node || (struct btrfs_root *)node->data == root);
254 }
255
256 /*
257 * We only put the reloc root here if it's on the list. There's a lot
258 * of places where the pattern is to splice the rc->reloc_roots, process
259 * the reloc roots, and then add the reloc root back onto
260 * rc->reloc_roots. If we call __del_reloc_root while it's off of the
261 * list we don't want the reference being dropped, because the guy
262 * messing with the list is in charge of the reference.
263 */
264 spin_lock(&fs_info->trans_lock);
265 if (!list_empty(&root->root_list)) {
266 put_ref = true;
267 list_del_init(&root->root_list);
268 }
269 spin_unlock(&fs_info->trans_lock);
270 if (put_ref)
271 btrfs_put_root(root);
272 if (rc)
273 put_reloc_control(rc);
274 }
275
mark_block_processed(struct reloc_control * rc,struct btrfs_backref_node * node)276 static void mark_block_processed(struct reloc_control *rc,
277 struct btrfs_backref_node *node)
278 {
279 u32 blocksize;
280
281 if (node->level == 0 ||
282 in_range(node->bytenr, rc->block_group->start,
283 rc->block_group->length)) {
284 blocksize = rc->extent_root->fs_info->nodesize;
285 btrfs_set_extent_bit(&rc->processed_blocks, node->bytenr,
286 node->bytenr + blocksize - 1, EXTENT_DIRTY,
287 NULL);
288 }
289 node->processed = 1;
290 }
291
292 /*
293 * walk up backref nodes until reach node presents tree root
294 */
walk_up_backref(struct btrfs_backref_node * node,struct btrfs_backref_edge * edges[],int * index)295 static struct btrfs_backref_node *walk_up_backref(
296 struct btrfs_backref_node *node,
297 struct btrfs_backref_edge *edges[], int *index)
298 {
299 struct btrfs_backref_edge *edge;
300 int idx = *index;
301
302 while (!list_empty(&node->upper)) {
303 edge = list_first_entry(&node->upper, struct btrfs_backref_edge,
304 list[LOWER]);
305 edges[idx++] = edge;
306 node = edge->node[UPPER];
307 }
308 BUG_ON(node->detached);
309 *index = idx;
310 return node;
311 }
312
313 /*
314 * walk down backref nodes to find start of next reference path
315 */
walk_down_backref(struct btrfs_backref_edge * edges[],int * index)316 static struct btrfs_backref_node *walk_down_backref(
317 struct btrfs_backref_edge *edges[], int *index)
318 {
319 struct btrfs_backref_edge *edge;
320 struct btrfs_backref_node *lower;
321 int idx = *index;
322
323 while (idx > 0) {
324 edge = edges[idx - 1];
325 lower = edge->node[LOWER];
326 if (list_is_last(&edge->list[LOWER], &lower->upper)) {
327 idx--;
328 continue;
329 }
330 edge = list_first_entry(&edge->list[LOWER], struct btrfs_backref_edge,
331 list[LOWER]);
332 edges[idx - 1] = edge;
333 *index = idx;
334 return edge->node[UPPER];
335 }
336 *index = 0;
337 return NULL;
338 }
339
reloc_root_is_dead(const struct btrfs_root * root)340 static bool reloc_root_is_dead(const struct btrfs_root *root)
341 {
342 if (test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state))
343 return true;
344 /*
345 * Pairs with set_bit/clear_bit in clear_reloc_root() and
346 * btrfs_update_reloc_root(). We need to see the updated bit before
347 * trying to access root->reloc_root in our callers.
348 */
349 smp_rmb();
350
351 return false;
352 }
353
354 /*
355 * Check if this subvolume tree has valid reloc tree.
356 *
357 * Reloc tree after swap is considered dead, thus not considered as valid.
358 * This is enough for most callers, as they don't distinguish dead reloc root
359 * from no reloc root. But btrfs_should_ignore_reloc_root() below is a
360 * special case.
361 */
have_reloc_root(const struct btrfs_root * root)362 static bool have_reloc_root(const struct btrfs_root *root)
363 {
364 if (reloc_root_is_dead(root))
365 return false;
366 if (!root->reloc_root)
367 return false;
368 return true;
369 }
370
btrfs_should_ignore_reloc_root(const struct btrfs_root * root)371 bool btrfs_should_ignore_reloc_root(const struct btrfs_root *root)
372 {
373 struct btrfs_root *reloc_root;
374
375 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
376 return false;
377
378 /* This root has been merged with its reloc tree, we can ignore it */
379 if (reloc_root_is_dead(root))
380 return true;
381
382 reloc_root = root->reloc_root;
383 if (!reloc_root)
384 return false;
385
386 if (btrfs_header_generation(reloc_root->commit_root) ==
387 root->fs_info->running_transaction->transid)
388 return false;
389 /*
390 * If there is reloc tree and it was created in previous transaction
391 * backref lookup can find the reloc tree, so backref node for the fs
392 * tree root is useless for relocation.
393 */
394 return true;
395 }
396
397 /*
398 * find reloc tree by address of tree root
399 */
find_reloc_root(struct btrfs_fs_info * fs_info,u64 bytenr)400 struct btrfs_root *find_reloc_root(struct btrfs_fs_info *fs_info, u64 bytenr)
401 {
402 struct reloc_control *rc = fs_info->reloc_ctl;
403 struct rb_node *rb_node;
404 struct mapping_node *node;
405 struct btrfs_root *root = NULL;
406
407 ASSERT(rc);
408 spin_lock(&rc->reloc_root_tree.lock);
409 rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root, bytenr);
410 if (rb_node) {
411 node = rb_entry(rb_node, struct mapping_node, rb_node);
412 root = node->data;
413 }
414 spin_unlock(&rc->reloc_root_tree.lock);
415 return btrfs_grab_root(root);
416 }
417
418 /*
419 * For useless nodes, do two major clean ups:
420 *
421 * - Cleanup the children edges and nodes
422 * If child node is also orphan (no parent) during cleanup, then the child
423 * node will also be cleaned up.
424 *
425 * - Freeing up leaves (level 0), keeps nodes detached
426 * For nodes, the node is still cached as "detached"
427 *
428 * Return false if @node is not in the @useless_nodes list.
429 * Return true if @node is in the @useless_nodes list.
430 */
handle_useless_nodes(struct reloc_control * rc,struct btrfs_backref_node * node)431 static bool handle_useless_nodes(struct reloc_control *rc,
432 struct btrfs_backref_node *node)
433 {
434 struct btrfs_backref_cache *cache = &rc->backref_cache;
435 struct list_head *useless_node = &cache->useless_node;
436 bool ret = false;
437
438 while (!list_empty(useless_node)) {
439 struct btrfs_backref_node *cur;
440
441 cur = list_first_entry(useless_node, struct btrfs_backref_node,
442 list);
443 list_del_init(&cur->list);
444
445 /* Only tree root nodes can be added to @useless_nodes */
446 ASSERT(list_empty(&cur->upper));
447
448 if (cur == node)
449 ret = true;
450
451 /* Cleanup the lower edges */
452 while (!list_empty(&cur->lower)) {
453 struct btrfs_backref_edge *edge;
454 struct btrfs_backref_node *lower;
455
456 edge = list_first_entry(&cur->lower, struct btrfs_backref_edge,
457 list[UPPER]);
458 list_del(&edge->list[UPPER]);
459 list_del(&edge->list[LOWER]);
460 lower = edge->node[LOWER];
461 btrfs_backref_free_edge(cache, edge);
462
463 /* Child node is also orphan, queue for cleanup */
464 if (list_empty(&lower->upper))
465 list_add(&lower->list, useless_node);
466 }
467 /* Mark this block processed for relocation */
468 mark_block_processed(rc, cur);
469
470 /*
471 * Backref nodes for tree leaves are deleted from the cache.
472 * Backref nodes for upper level tree blocks are left in the
473 * cache to avoid unnecessary backref lookup.
474 */
475 if (cur->level > 0) {
476 cur->detached = 1;
477 } else {
478 rb_erase(&cur->rb_node, &cache->rb_root);
479 btrfs_backref_free_node(cache, cur);
480 }
481 }
482 return ret;
483 }
484
485 /*
486 * Build backref tree for a given tree block. Root of the backref tree
487 * corresponds the tree block, leaves of the backref tree correspond roots of
488 * b-trees that reference the tree block.
489 *
490 * The basic idea of this function is check backrefs of a given block to find
491 * upper level blocks that reference the block, and then check backrefs of
492 * these upper level blocks recursively. The recursion stops when tree root is
493 * reached or backrefs for the block is cached.
494 *
495 * NOTE: if we find that backrefs for a block are cached, we know backrefs for
496 * all upper level blocks that directly/indirectly reference the block are also
497 * cached.
498 */
build_backref_tree(struct btrfs_trans_handle * trans,struct reloc_control * rc,struct btrfs_key * node_key,int level,u64 bytenr)499 static noinline_for_stack struct btrfs_backref_node *build_backref_tree(
500 struct btrfs_trans_handle *trans,
501 struct reloc_control *rc, struct btrfs_key *node_key,
502 int level, u64 bytenr)
503 {
504 struct btrfs_backref_iter iter;
505 struct btrfs_backref_cache *cache = &rc->backref_cache;
506 /* For searching parent of TREE_BLOCK_REF */
507 struct btrfs_path *path;
508 struct btrfs_backref_node *cur;
509 struct btrfs_backref_node *node = NULL;
510 struct btrfs_backref_edge *edge;
511 int ret;
512
513 ret = btrfs_backref_iter_init(&iter);
514 if (ret < 0)
515 return ERR_PTR(ret);
516 path = btrfs_alloc_path();
517 if (!path) {
518 ret = -ENOMEM;
519 goto out;
520 }
521
522 node = btrfs_backref_alloc_node(cache, bytenr, level);
523 if (!node) {
524 ret = -ENOMEM;
525 goto out;
526 }
527
528 cur = node;
529
530 /* Breadth-first search to build backref cache */
531 do {
532 ret = btrfs_backref_add_tree_node(trans, cache, path, &iter,
533 node_key, cur);
534 if (ret < 0)
535 goto out;
536
537 edge = list_first_entry_or_null(&cache->pending_edge,
538 struct btrfs_backref_edge, list[UPPER]);
539 /*
540 * The pending list isn't empty, take the first block to
541 * process
542 */
543 if (edge) {
544 list_del_init(&edge->list[UPPER]);
545 cur = edge->node[UPPER];
546 }
547 } while (edge);
548
549 /* Finish the upper linkage of newly added edges/nodes */
550 ret = btrfs_backref_finish_upper_links(cache, node);
551 if (ret < 0)
552 goto out;
553
554 if (handle_useless_nodes(rc, node))
555 node = NULL;
556 out:
557 btrfs_free_path(iter.path);
558 btrfs_free_path(path);
559 if (ret) {
560 btrfs_backref_error_cleanup(cache, node);
561 return ERR_PTR(ret);
562 }
563 ASSERT(!node || !node->detached);
564 ASSERT(list_empty(&cache->useless_node) &&
565 list_empty(&cache->pending_edge));
566 return node;
567 }
568
569 /*
570 * helper to add 'address of tree root -> reloc tree' mapping
571 */
__add_reloc_root(struct btrfs_root * root,struct reloc_control * rc)572 static int __add_reloc_root(struct btrfs_root *root, struct reloc_control *rc)
573 {
574 struct btrfs_fs_info *fs_info = root->fs_info;
575 struct rb_node *rb_node;
576 struct mapping_node *node;
577
578 node = kmalloc_obj(*node, GFP_NOFS);
579 if (!node)
580 return -ENOMEM;
581
582 node->bytenr = root->commit_root->start;
583 node->data = root;
584
585 spin_lock(&rc->reloc_root_tree.lock);
586 rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root, &node->simple_node);
587 spin_unlock(&rc->reloc_root_tree.lock);
588 if (rb_node) {
589 btrfs_err(fs_info,
590 "Duplicate root found for start=%llu while inserting into relocation tree",
591 node->bytenr);
592 kfree(node);
593 return -EEXIST;
594 }
595
596 list_add_tail(&root->root_list, &rc->reloc_roots);
597 return 0;
598 }
599
600 /*
601 * helper to update the 'address of tree root -> reloc tree'
602 * mapping
603 */
__update_reloc_root(struct btrfs_root * root)604 static int __update_reloc_root(struct btrfs_root *root)
605 {
606 struct btrfs_fs_info *fs_info = root->fs_info;
607 struct rb_node *rb_node;
608 struct mapping_node *node = NULL;
609 struct reloc_control *rc = fs_info->reloc_ctl;
610
611 spin_lock(&rc->reloc_root_tree.lock);
612 rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
613 root->commit_root->start);
614 if (rb_node) {
615 node = rb_entry(rb_node, struct mapping_node, rb_node);
616 rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
617 }
618 spin_unlock(&rc->reloc_root_tree.lock);
619
620 if (!node)
621 return 0;
622 BUG_ON((struct btrfs_root *)node->data != root);
623
624 spin_lock(&rc->reloc_root_tree.lock);
625 node->bytenr = root->node->start;
626 rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root, &node->simple_node);
627 spin_unlock(&rc->reloc_root_tree.lock);
628 if (rb_node)
629 btrfs_backref_panic(fs_info, node->bytenr, -EEXIST);
630 return 0;
631 }
632
create_reloc_root(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 objectid)633 static struct btrfs_root *create_reloc_root(struct btrfs_trans_handle *trans,
634 struct btrfs_root *root, u64 objectid)
635 {
636 struct btrfs_fs_info *fs_info = root->fs_info;
637 struct btrfs_root *reloc_root;
638 struct extent_buffer *eb;
639 struct btrfs_root_item AUTO_KFREE(root_item);
640 struct btrfs_key root_key;
641 int ret = 0;
642
643 root_item = kmalloc_obj(*root_item, GFP_NOFS);
644 if (!root_item)
645 return ERR_PTR(-ENOMEM);
646
647 root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
648 root_key.type = BTRFS_ROOT_ITEM_KEY;
649 root_key.offset = objectid;
650
651 if (btrfs_root_id(root) == objectid) {
652 u64 commit_root_gen;
653
654 /*
655 * Relocation will wait for cleaner thread, and any half-dropped
656 * subvolume will be fully cleaned up at mount time.
657 * So here we shouldn't hit a subvolume with non-zero drop_progress.
658 *
659 * If this isn't the case, error out since it can make us attempt to
660 * drop references for extents that were already dropped before.
661 */
662 if (unlikely(btrfs_disk_key_objectid(&root->root_item.drop_progress))) {
663 struct btrfs_key cpu_key;
664
665 btrfs_disk_key_to_cpu(&cpu_key, &root->root_item.drop_progress);
666 btrfs_err(fs_info,
667 "cannot relocate partially dropped subvolume %llu, drop progress key " BTRFS_KEY_FMT,
668 objectid, BTRFS_KEY_FMT_VALUE(&cpu_key));
669 return ERR_PTR(-EUCLEAN);
670 }
671
672 /* called by btrfs_init_reloc_root */
673 ret = btrfs_copy_root(trans, root, root->commit_root, &eb,
674 BTRFS_TREE_RELOC_OBJECTID);
675 if (ret)
676 return ERR_PTR(ret);
677
678 /*
679 * Set the last_snapshot field to the generation of the commit
680 * root - like this ctree.c:btrfs_block_can_be_shared() behaves
681 * correctly (returns true) when the relocation root is created
682 * either inside the critical section of a transaction commit
683 * (through transaction.c:qgroup_account_snapshot()) and when
684 * it's created before the transaction commit is started.
685 */
686 commit_root_gen = btrfs_header_generation(root->commit_root);
687 btrfs_set_root_last_snapshot(&root->root_item, commit_root_gen);
688 } else {
689 /*
690 * called by btrfs_reloc_post_snapshot_hook.
691 * the source tree is a reloc tree, all tree blocks
692 * modified after it was created have RELOC flag
693 * set in their headers. so it's OK to not update
694 * the 'last_snapshot'.
695 */
696 ret = btrfs_copy_root(trans, root, root->node, &eb,
697 BTRFS_TREE_RELOC_OBJECTID);
698 if (ret)
699 return ERR_PTR(ret);
700 }
701
702 /*
703 * We have changed references at this point, we must abort the
704 * transaction if anything fails (i.e. 'goto abort').
705 */
706
707 memcpy(root_item, &root->root_item, sizeof(*root_item));
708 btrfs_set_root_bytenr(root_item, eb->start);
709 btrfs_set_root_level(root_item, btrfs_header_level(eb));
710 btrfs_set_root_generation(root_item, trans->transid);
711
712 if (btrfs_root_id(root) == objectid) {
713 btrfs_set_root_refs(root_item, 0);
714 memset(&root_item->drop_progress, 0,
715 sizeof(struct btrfs_disk_key));
716 btrfs_set_root_drop_level(root_item, 0);
717 }
718
719 btrfs_tree_unlock(eb);
720 free_extent_buffer(eb);
721
722 ret = btrfs_insert_root(trans, fs_info->tree_root,
723 &root_key, root_item);
724 if (unlikely(ret)) {
725 btrfs_abort_transaction(trans, ret);
726 return ERR_PTR(ret);
727 }
728
729 reloc_root = btrfs_read_tree_root(fs_info->tree_root, &root_key);
730 if (IS_ERR(reloc_root)) {
731 btrfs_abort_transaction(trans, PTR_ERR(reloc_root));
732 return ERR_CAST(reloc_root);
733 }
734 set_bit(BTRFS_ROOT_SHAREABLE, &reloc_root->state);
735 btrfs_set_root_last_trans(reloc_root, trans->transid);
736 return reloc_root;
737 }
738
739 /*
740 * create reloc tree for a given fs tree. reloc tree is just a
741 * snapshot of the fs tree with special root objectid.
742 *
743 * The reloc_root comes out of here with two references, one for
744 * root->reloc_root, and another for being on the rc->reloc_roots list.
745 */
btrfs_init_reloc_root(struct btrfs_trans_handle * trans,struct btrfs_root * root)746 int btrfs_init_reloc_root(struct btrfs_trans_handle *trans,
747 struct btrfs_root *root)
748 {
749 struct btrfs_fs_info *fs_info = root->fs_info;
750 struct btrfs_root *reloc_root;
751 struct reloc_control *rc;
752 struct btrfs_block_rsv *rsv;
753 bool clear_rsv = false;
754 int ret = 0;
755
756 rc = get_reloc_control(fs_info);
757 if (!rc)
758 return 0;
759
760 /*
761 * The subvolume has reloc tree but the swap is finished, no need to
762 * create/update the dead reloc tree
763 */
764 if (reloc_root_is_dead(root))
765 goto out;
766
767 /*
768 * This is subtle but important. We do not do
769 * record_root_in_transaction for reloc roots, instead we record their
770 * corresponding fs root, and then here we update the last trans for the
771 * reloc root. This means that we have to do this for the entire life
772 * of the reloc root, regardless of which stage of the relocation we are
773 * in.
774 */
775 if (root->reloc_root) {
776 btrfs_set_root_last_trans(root->reloc_root, trans->transid);
777 goto out;
778 }
779
780 /*
781 * We are merging reloc roots, we do not need new reloc trees. Also
782 * reloc trees never need their own reloc tree.
783 */
784 if (!rc->create_reloc_tree || btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
785 goto out;
786
787 if (!trans->reloc_reserved) {
788 rsv = trans->block_rsv;
789 trans->block_rsv = rc->block_rsv;
790 clear_rsv = true;
791 }
792 reloc_root = create_reloc_root(trans, root, btrfs_root_id(root));
793 if (clear_rsv)
794 trans->block_rsv = rsv;
795 if (IS_ERR(reloc_root)) {
796 ret = PTR_ERR(reloc_root);
797 goto out;
798 }
799
800 ret = __add_reloc_root(reloc_root, rc);
801 ASSERT(ret != -EEXIST);
802 if (ret) {
803 /* Pairs with create_reloc_root */
804 btrfs_put_root(reloc_root);
805 goto out;
806 }
807 root->reloc_root = btrfs_grab_root(reloc_root);
808 out:
809 put_reloc_control(rc);
810
811 return ret;
812 }
813
814 /*
815 * update root item of reloc tree
816 */
btrfs_update_reloc_root(struct btrfs_trans_handle * trans,struct btrfs_root * root)817 int btrfs_update_reloc_root(struct btrfs_trans_handle *trans,
818 struct btrfs_root *root)
819 {
820 struct btrfs_fs_info *fs_info = root->fs_info;
821 struct btrfs_root *reloc_root;
822 struct btrfs_root_item *root_item;
823 struct reloc_control *rc;
824 int ret;
825
826 if (!have_reloc_root(root))
827 return 0;
828
829 reloc_root = root->reloc_root;
830 root_item = &reloc_root->root_item;
831
832 /*
833 * We are probably ok here, but __del_reloc_root() will drop its ref of
834 * the root. We have the ref for root->reloc_root, but just in case
835 * hold it while we update the reloc root.
836 */
837 btrfs_grab_root(reloc_root);
838
839 rc = get_reloc_control(fs_info);
840 /* root->reloc_root will stay until current relocation finished */
841 if (rc && rc->merge_reloc_tree && btrfs_root_refs(root_item) == 0) {
842 set_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
843 /*
844 * Mark the tree as dead before we change reloc_root so
845 * have_reloc_root will not touch it from now on.
846 */
847 smp_wmb();
848 __del_reloc_root(reloc_root);
849 }
850
851 if (reloc_root->commit_root != reloc_root->node) {
852 __update_reloc_root(reloc_root);
853 btrfs_set_root_node(root_item, reloc_root->node);
854 free_extent_buffer(reloc_root->commit_root);
855 reloc_root->commit_root = btrfs_root_node(reloc_root);
856 }
857
858 ret = btrfs_update_root(trans, fs_info->tree_root,
859 &reloc_root->root_key, root_item);
860 btrfs_put_root(reloc_root);
861 if (rc)
862 put_reloc_control(rc);
863
864 return ret;
865 }
866
867 /*
868 * get new location of data
869 */
get_new_location(struct inode * reloc_inode,u64 * new_bytenr,u64 bytenr,u64 num_bytes)870 static int get_new_location(struct inode *reloc_inode, u64 *new_bytenr,
871 u64 bytenr, u64 num_bytes)
872 {
873 struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
874 struct btrfs_fs_info *fs_info = root->fs_info;
875 BTRFS_PATH_AUTO_FREE(path);
876 struct btrfs_file_extent_item *fi;
877 struct extent_buffer *leaf;
878 int ret;
879
880 path = btrfs_alloc_path();
881 if (!path)
882 return -ENOMEM;
883
884 bytenr -= BTRFS_I(reloc_inode)->reloc_block_group_start;
885 ret = btrfs_lookup_file_extent(NULL, root, path,
886 btrfs_ino(BTRFS_I(reloc_inode)), bytenr, 0);
887 if (ret < 0)
888 return ret;
889 if (ret > 0)
890 return -ENOENT;
891
892 leaf = path->nodes[0];
893 fi = btrfs_item_ptr(leaf, path->slots[0],
894 struct btrfs_file_extent_item);
895 if (unlikely(btrfs_file_extent_type(leaf, fi) == BTRFS_FILE_EXTENT_INLINE)) {
896 btrfs_print_leaf(leaf);
897 btrfs_err(fs_info,
898 "unexpected inline file extent item for data reloc inode %llu key offset %llu",
899 btrfs_ino(BTRFS_I(reloc_inode)), bytenr);
900 return -EUCLEAN;
901 }
902
903 /*
904 * The cluster-boundary key searched above is always written by
905 * relocation with offset 0: either by insert_prealloc_file_extent()
906 * (memsets the stack item to 0) or by the front portion of a partial
907 * writeback (offset=0 by construction). A non-zero value here means
908 * the on-disk leaf does not match what relocation wrote, i.e.
909 * corruption. The other encoding fields are caught earlier by
910 * tree-checker's check_extent_data_item().
911 */
912 if (unlikely(btrfs_file_extent_offset(leaf, fi))) {
913 btrfs_print_leaf(leaf);
914 btrfs_err(fs_info,
915 "unexpected non-zero offset in file extent item for data reloc inode %llu key offset %llu offset %llu",
916 btrfs_ino(BTRFS_I(reloc_inode)), bytenr,
917 btrfs_file_extent_offset(leaf, fi));
918 return -EUCLEAN;
919 }
920
921 if (num_bytes != btrfs_file_extent_disk_num_bytes(leaf, fi))
922 return -EINVAL;
923
924 *new_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
925 return 0;
926 }
927
928 /*
929 * update file extent items in the tree leaf to point to
930 * the new locations.
931 */
932 static noinline_for_stack
replace_file_extents(struct btrfs_trans_handle * trans,struct reloc_control * rc,struct btrfs_root * root,struct extent_buffer * leaf)933 int replace_file_extents(struct btrfs_trans_handle *trans,
934 struct reloc_control *rc,
935 struct btrfs_root *root,
936 struct extent_buffer *leaf)
937 {
938 struct btrfs_fs_info *fs_info = root->fs_info;
939 struct btrfs_key key;
940 struct btrfs_file_extent_item *fi;
941 struct btrfs_inode *inode = NULL;
942 u64 parent;
943 u64 bytenr;
944 u64 new_bytenr = 0;
945 u64 num_bytes;
946 u64 end;
947 u32 nritems;
948 u32 i;
949 int ret = 0;
950 bool first = true;
951
952 if (rc->stage != UPDATE_DATA_PTRS)
953 return 0;
954
955 /* reloc trees always use full backref */
956 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
957 parent = leaf->start;
958 else
959 parent = 0;
960
961 nritems = btrfs_header_nritems(leaf);
962 for (i = 0; i < nritems; i++) {
963 struct btrfs_ref ref = { 0 };
964
965 cond_resched();
966 btrfs_item_key_to_cpu(leaf, &key, i);
967 if (key.type != BTRFS_EXTENT_DATA_KEY)
968 continue;
969 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
970 if (btrfs_file_extent_type(leaf, fi) ==
971 BTRFS_FILE_EXTENT_INLINE)
972 continue;
973 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
974 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
975 if (bytenr == 0)
976 continue;
977 if (!in_range(bytenr, rc->block_group->start,
978 rc->block_group->length))
979 continue;
980
981 /*
982 * if we are modifying block in fs tree, wait for read_folio
983 * to complete and drop the extent cache
984 */
985 if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID) {
986 if (first) {
987 inode = btrfs_find_first_inode(root, key.objectid);
988 first = false;
989 } else if (inode && btrfs_ino(inode) < key.objectid) {
990 btrfs_add_delayed_iput(inode);
991 inode = btrfs_find_first_inode(root, key.objectid);
992 }
993 if (inode && btrfs_ino(inode) == key.objectid) {
994 struct extent_state *cached_state = NULL;
995
996 end = key.offset +
997 btrfs_file_extent_num_bytes(leaf, fi);
998 WARN_ON(!IS_ALIGNED(key.offset,
999 fs_info->sectorsize));
1000 WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
1001 end--;
1002 /* Take mmap lock to serialize with reflinks. */
1003 if (!down_read_trylock(&inode->i_mmap_lock))
1004 continue;
1005 ret = btrfs_try_lock_extent(&inode->io_tree, key.offset,
1006 end, &cached_state);
1007 if (!ret) {
1008 up_read(&inode->i_mmap_lock);
1009 continue;
1010 }
1011
1012 btrfs_drop_extent_map_range(inode, key.offset, end, true);
1013 btrfs_unlock_extent(&inode->io_tree, key.offset, end,
1014 &cached_state);
1015 up_read(&inode->i_mmap_lock);
1016 }
1017 }
1018
1019 ret = get_new_location(rc->data_inode, &new_bytenr,
1020 bytenr, num_bytes);
1021 if (ret) {
1022 /*
1023 * Don't have to abort since we've not changed anything
1024 * in the file extent yet.
1025 */
1026 break;
1027 }
1028
1029 btrfs_set_file_extent_disk_bytenr(leaf, fi, new_bytenr);
1030
1031 key.offset -= btrfs_file_extent_offset(leaf, fi);
1032 ref.action = BTRFS_ADD_DELAYED_REF;
1033 ref.bytenr = new_bytenr;
1034 ref.num_bytes = num_bytes;
1035 ref.parent = parent;
1036 ref.owning_root = btrfs_root_id(root);
1037 ref.ref_root = btrfs_header_owner(leaf);
1038 btrfs_init_data_ref(&ref, key.objectid, key.offset,
1039 btrfs_root_id(root), false);
1040 ret = btrfs_inc_extent_ref(trans, &ref);
1041 if (unlikely(ret)) {
1042 btrfs_abort_transaction(trans, ret);
1043 break;
1044 }
1045
1046 ref.action = BTRFS_DROP_DELAYED_REF;
1047 ref.bytenr = bytenr;
1048 ref.num_bytes = num_bytes;
1049 ref.parent = parent;
1050 ref.owning_root = btrfs_root_id(root);
1051 ref.ref_root = btrfs_header_owner(leaf);
1052 btrfs_init_data_ref(&ref, key.objectid, key.offset,
1053 btrfs_root_id(root), false);
1054 ret = btrfs_free_extent(trans, &ref);
1055 if (unlikely(ret)) {
1056 btrfs_abort_transaction(trans, ret);
1057 break;
1058 }
1059 }
1060 if (inode)
1061 btrfs_add_delayed_iput(inode);
1062 return ret;
1063 }
1064
memcmp_node_keys(const struct extent_buffer * eb,int slot,const struct btrfs_path * path,int level)1065 static noinline_for_stack int memcmp_node_keys(const struct extent_buffer *eb,
1066 int slot, const struct btrfs_path *path,
1067 int level)
1068 {
1069 struct btrfs_disk_key key1;
1070 struct btrfs_disk_key key2;
1071 btrfs_node_key(eb, &key1, slot);
1072 btrfs_node_key(path->nodes[level], &key2, path->slots[level]);
1073 return memcmp(&key1, &key2, sizeof(key1));
1074 }
1075
1076 /*
1077 * try to replace tree blocks in fs tree with the new blocks
1078 * in reloc tree. tree blocks haven't been modified since the
1079 * reloc tree was create can be replaced.
1080 *
1081 * if a block was replaced, level of the block + 1 is returned.
1082 * if no block got replaced, 0 is returned. if there are other
1083 * errors, a negative error number is returned.
1084 */
1085 static noinline_for_stack
replace_path(struct btrfs_trans_handle * trans,struct reloc_control * rc,struct btrfs_root * dest,struct btrfs_root * src,struct btrfs_path * path,struct btrfs_key * next_key,int lowest_level,int max_level)1086 int replace_path(struct btrfs_trans_handle *trans, struct reloc_control *rc,
1087 struct btrfs_root *dest, struct btrfs_root *src,
1088 struct btrfs_path *path, struct btrfs_key *next_key,
1089 int lowest_level, int max_level)
1090 {
1091 struct btrfs_fs_info *fs_info = dest->fs_info;
1092 struct extent_buffer *eb;
1093 struct extent_buffer *parent;
1094 struct btrfs_ref ref = { 0 };
1095 struct btrfs_key key;
1096 u64 old_bytenr;
1097 u64 new_bytenr;
1098 u64 old_ptr_gen;
1099 u64 new_ptr_gen;
1100 u64 last_snapshot;
1101 u32 blocksize;
1102 bool cow = false;
1103 int level;
1104 int ret;
1105 int slot;
1106
1107 ASSERT(btrfs_root_id(src) == BTRFS_TREE_RELOC_OBJECTID);
1108 ASSERT(btrfs_root_id(dest) != BTRFS_TREE_RELOC_OBJECTID);
1109
1110 last_snapshot = btrfs_root_last_snapshot(&src->root_item);
1111 again:
1112 slot = path->slots[lowest_level];
1113 btrfs_node_key_to_cpu(path->nodes[lowest_level], &key, slot);
1114
1115 eb = btrfs_lock_root_node(dest);
1116 level = btrfs_header_level(eb);
1117
1118 if (level < lowest_level) {
1119 btrfs_tree_unlock(eb);
1120 free_extent_buffer(eb);
1121 return 0;
1122 }
1123
1124 if (cow) {
1125 ret = btrfs_cow_block(trans, dest, eb, NULL, 0, &eb,
1126 BTRFS_NESTING_COW);
1127 if (ret) {
1128 btrfs_tree_unlock(eb);
1129 free_extent_buffer(eb);
1130 return ret;
1131 }
1132 }
1133
1134 if (next_key) {
1135 next_key->objectid = (u64)-1;
1136 next_key->type = (u8)-1;
1137 next_key->offset = (u64)-1;
1138 }
1139
1140 parent = eb;
1141 while (1) {
1142 level = btrfs_header_level(parent);
1143 ASSERT(level >= lowest_level);
1144
1145 ret = btrfs_bin_search(parent, 0, &key, &slot);
1146 if (ret < 0)
1147 break;
1148 if (ret && slot > 0)
1149 slot--;
1150
1151 if (next_key && slot + 1 < btrfs_header_nritems(parent))
1152 btrfs_node_key_to_cpu(parent, next_key, slot + 1);
1153
1154 old_bytenr = btrfs_node_blockptr(parent, slot);
1155 blocksize = fs_info->nodesize;
1156 old_ptr_gen = btrfs_node_ptr_generation(parent, slot);
1157
1158 if (level <= max_level) {
1159 eb = path->nodes[level];
1160 new_bytenr = btrfs_node_blockptr(eb,
1161 path->slots[level]);
1162 new_ptr_gen = btrfs_node_ptr_generation(eb,
1163 path->slots[level]);
1164 } else {
1165 new_bytenr = 0;
1166 new_ptr_gen = 0;
1167 }
1168
1169 if (WARN_ON(new_bytenr > 0 && new_bytenr == old_bytenr)) {
1170 ret = level;
1171 break;
1172 }
1173
1174 if (new_bytenr == 0 || old_ptr_gen > last_snapshot ||
1175 memcmp_node_keys(parent, slot, path, level)) {
1176 if (level <= lowest_level) {
1177 ret = 0;
1178 break;
1179 }
1180
1181 eb = btrfs_read_node_slot(parent, slot);
1182 if (IS_ERR(eb)) {
1183 ret = PTR_ERR(eb);
1184 break;
1185 }
1186 btrfs_tree_lock(eb);
1187 if (cow) {
1188 ret = btrfs_cow_block(trans, dest, eb, parent,
1189 slot, &eb,
1190 BTRFS_NESTING_COW);
1191 if (ret) {
1192 btrfs_tree_unlock(eb);
1193 free_extent_buffer(eb);
1194 break;
1195 }
1196 }
1197
1198 btrfs_tree_unlock(parent);
1199 free_extent_buffer(parent);
1200
1201 parent = eb;
1202 continue;
1203 }
1204
1205 if (!cow) {
1206 btrfs_tree_unlock(parent);
1207 free_extent_buffer(parent);
1208 cow = true;
1209 goto again;
1210 }
1211
1212 btrfs_node_key_to_cpu(path->nodes[level], &key,
1213 path->slots[level]);
1214 btrfs_release_path(path);
1215
1216 path->lowest_level = level;
1217 set_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &src->state);
1218 ret = btrfs_search_slot(trans, src, &key, path, 0, 1);
1219 clear_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &src->state);
1220 path->lowest_level = 0;
1221 if (ret) {
1222 if (ret > 0)
1223 ret = -ENOENT;
1224 break;
1225 }
1226
1227 /*
1228 * Info qgroup to trace both subtrees.
1229 *
1230 * We must trace both trees.
1231 * 1) Tree reloc subtree
1232 * If not traced, we will leak data numbers
1233 * 2) Fs subtree
1234 * If not traced, we will double count old data
1235 *
1236 * We don't scan the subtree right now, but only record
1237 * the swapped tree blocks.
1238 * The real subtree rescan is delayed until we have new
1239 * CoW on the subtree root node before transaction commit.
1240 */
1241 ret = btrfs_qgroup_add_swapped_blocks(dest,
1242 rc->block_group, parent, slot,
1243 path->nodes[level], path->slots[level],
1244 last_snapshot);
1245 if (ret < 0)
1246 break;
1247 /*
1248 * swap blocks in fs tree and reloc tree.
1249 */
1250 btrfs_set_node_blockptr(parent, slot, new_bytenr);
1251 btrfs_set_node_ptr_generation(parent, slot, new_ptr_gen);
1252
1253 btrfs_set_node_blockptr(path->nodes[level],
1254 path->slots[level], old_bytenr);
1255 btrfs_set_node_ptr_generation(path->nodes[level],
1256 path->slots[level], old_ptr_gen);
1257
1258 ref.action = BTRFS_ADD_DELAYED_REF;
1259 ref.bytenr = old_bytenr;
1260 ref.num_bytes = blocksize;
1261 ref.parent = path->nodes[level]->start;
1262 ref.owning_root = btrfs_root_id(src);
1263 ref.ref_root = btrfs_root_id(src);
1264 btrfs_init_tree_ref(&ref, level - 1, 0, true);
1265 ret = btrfs_inc_extent_ref(trans, &ref);
1266 if (unlikely(ret)) {
1267 btrfs_abort_transaction(trans, ret);
1268 break;
1269 }
1270
1271 ref.action = BTRFS_ADD_DELAYED_REF;
1272 ref.bytenr = new_bytenr;
1273 ref.num_bytes = blocksize;
1274 ref.parent = 0;
1275 ref.owning_root = btrfs_root_id(dest);
1276 ref.ref_root = btrfs_root_id(dest);
1277 btrfs_init_tree_ref(&ref, level - 1, 0, true);
1278 ret = btrfs_inc_extent_ref(trans, &ref);
1279 if (unlikely(ret)) {
1280 btrfs_abort_transaction(trans, ret);
1281 break;
1282 }
1283
1284 /* We don't know the real owning_root, use 0. */
1285 ref.action = BTRFS_DROP_DELAYED_REF;
1286 ref.bytenr = new_bytenr;
1287 ref.num_bytes = blocksize;
1288 ref.parent = path->nodes[level]->start;
1289 ref.owning_root = 0;
1290 ref.ref_root = btrfs_root_id(src);
1291 btrfs_init_tree_ref(&ref, level - 1, 0, true);
1292 ret = btrfs_free_extent(trans, &ref);
1293 if (unlikely(ret)) {
1294 btrfs_abort_transaction(trans, ret);
1295 break;
1296 }
1297
1298 /* We don't know the real owning_root, use 0. */
1299 ref.action = BTRFS_DROP_DELAYED_REF;
1300 ref.bytenr = old_bytenr;
1301 ref.num_bytes = blocksize;
1302 ref.parent = 0;
1303 ref.owning_root = 0;
1304 ref.ref_root = btrfs_root_id(dest);
1305 btrfs_init_tree_ref(&ref, level - 1, 0, true);
1306 ret = btrfs_free_extent(trans, &ref);
1307 if (unlikely(ret)) {
1308 btrfs_abort_transaction(trans, ret);
1309 break;
1310 }
1311
1312 btrfs_unlock_up_safe(path, 0);
1313
1314 ret = level;
1315 break;
1316 }
1317 btrfs_tree_unlock(parent);
1318 free_extent_buffer(parent);
1319 return ret;
1320 }
1321
1322 /*
1323 * helper to find next relocated block in reloc tree
1324 */
1325 static noinline_for_stack
walk_up_reloc_tree(struct btrfs_root * root,struct btrfs_path * path,int * level)1326 int walk_up_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
1327 int *level)
1328 {
1329 struct extent_buffer *eb;
1330 int i;
1331 u64 last_snapshot;
1332 u32 nritems;
1333
1334 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
1335
1336 for (i = 0; i < *level; i++) {
1337 free_extent_buffer(path->nodes[i]);
1338 path->nodes[i] = NULL;
1339 }
1340
1341 for (i = *level; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
1342 eb = path->nodes[i];
1343 nritems = btrfs_header_nritems(eb);
1344 while (path->slots[i] + 1 < nritems) {
1345 path->slots[i]++;
1346 if (btrfs_node_ptr_generation(eb, path->slots[i]) <=
1347 last_snapshot)
1348 continue;
1349
1350 *level = i;
1351 return 0;
1352 }
1353 free_extent_buffer(path->nodes[i]);
1354 path->nodes[i] = NULL;
1355 }
1356 return 1;
1357 }
1358
1359 /*
1360 * walk down reloc tree to find relocated block of lowest level
1361 */
1362 static noinline_for_stack
walk_down_reloc_tree(struct btrfs_root * root,struct btrfs_path * path,int * level)1363 int walk_down_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
1364 int *level)
1365 {
1366 struct extent_buffer *eb = NULL;
1367 int i;
1368 u64 ptr_gen = 0;
1369 u64 last_snapshot;
1370 u32 nritems;
1371
1372 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
1373
1374 for (i = *level; i > 0; i--) {
1375 eb = path->nodes[i];
1376 nritems = btrfs_header_nritems(eb);
1377 while (path->slots[i] < nritems) {
1378 ptr_gen = btrfs_node_ptr_generation(eb, path->slots[i]);
1379 if (ptr_gen > last_snapshot)
1380 break;
1381 path->slots[i]++;
1382 }
1383 if (path->slots[i] >= nritems) {
1384 if (i == *level)
1385 break;
1386 *level = i + 1;
1387 return 0;
1388 }
1389 if (i == 1) {
1390 *level = i;
1391 return 0;
1392 }
1393
1394 eb = btrfs_read_node_slot(eb, path->slots[i]);
1395 if (IS_ERR(eb))
1396 return PTR_ERR(eb);
1397 BUG_ON(btrfs_header_level(eb) != i - 1);
1398 path->nodes[i - 1] = eb;
1399 path->slots[i - 1] = 0;
1400 }
1401 return 1;
1402 }
1403
1404 /*
1405 * invalidate extent cache for file extents whose key in range of
1406 * [min_key, max_key)
1407 */
invalidate_extent_cache(struct btrfs_root * root,const struct btrfs_key * min_key,const struct btrfs_key * max_key)1408 static int invalidate_extent_cache(struct btrfs_root *root,
1409 const struct btrfs_key *min_key,
1410 const struct btrfs_key *max_key)
1411 {
1412 struct btrfs_fs_info *fs_info = root->fs_info;
1413 struct btrfs_inode *inode = NULL;
1414 u64 objectid;
1415 u64 start, end;
1416 u64 ino;
1417
1418 objectid = min_key->objectid;
1419 while (1) {
1420 struct extent_state *cached_state = NULL;
1421
1422 cond_resched();
1423 if (inode)
1424 iput(&inode->vfs_inode);
1425
1426 if (objectid > max_key->objectid)
1427 break;
1428
1429 inode = btrfs_find_first_inode(root, objectid);
1430 if (!inode)
1431 break;
1432 ino = btrfs_ino(inode);
1433
1434 if (ino > max_key->objectid) {
1435 iput(&inode->vfs_inode);
1436 break;
1437 }
1438
1439 objectid = ino + 1;
1440 if (!S_ISREG(inode->vfs_inode.i_mode))
1441 continue;
1442
1443 if (unlikely(min_key->objectid == ino)) {
1444 if (min_key->type > BTRFS_EXTENT_DATA_KEY)
1445 continue;
1446 if (min_key->type < BTRFS_EXTENT_DATA_KEY)
1447 start = 0;
1448 else {
1449 start = min_key->offset;
1450 WARN_ON(!IS_ALIGNED(start, fs_info->sectorsize));
1451 }
1452 } else {
1453 start = 0;
1454 }
1455
1456 if (unlikely(max_key->objectid == ino)) {
1457 if (max_key->type < BTRFS_EXTENT_DATA_KEY)
1458 continue;
1459 if (max_key->type > BTRFS_EXTENT_DATA_KEY) {
1460 end = (u64)-1;
1461 } else {
1462 if (max_key->offset == 0)
1463 continue;
1464 end = max_key->offset;
1465 WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
1466 end--;
1467 }
1468 } else {
1469 end = (u64)-1;
1470 }
1471
1472 /* the lock_extent waits for read_folio to complete */
1473 btrfs_lock_extent(&inode->io_tree, start, end, &cached_state);
1474 btrfs_drop_extent_map_range(inode, start, end, true);
1475 btrfs_unlock_extent(&inode->io_tree, start, end, &cached_state);
1476 }
1477 return 0;
1478 }
1479
find_next_key(struct btrfs_path * path,int level,struct btrfs_key * key)1480 static int find_next_key(struct btrfs_path *path, int level,
1481 struct btrfs_key *key)
1482
1483 {
1484 while (level < BTRFS_MAX_LEVEL) {
1485 if (!path->nodes[level])
1486 break;
1487 if (path->slots[level] + 1 <
1488 btrfs_header_nritems(path->nodes[level])) {
1489 btrfs_node_key_to_cpu(path->nodes[level], key,
1490 path->slots[level] + 1);
1491 return 0;
1492 }
1493 level++;
1494 }
1495 return 1;
1496 }
1497
1498 /*
1499 * Insert current subvolume into reloc_control::dirty_subvol_roots
1500 */
insert_dirty_subvol(struct btrfs_trans_handle * trans,struct reloc_control * rc,struct btrfs_root * root)1501 static int insert_dirty_subvol(struct btrfs_trans_handle *trans,
1502 struct reloc_control *rc,
1503 struct btrfs_root *root)
1504 {
1505 struct btrfs_root *reloc_root = root->reloc_root;
1506 struct btrfs_root_item *reloc_root_item;
1507 int ret;
1508
1509 /* @root must be a subvolume tree root with a valid reloc tree */
1510 ASSERT(btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID);
1511 ASSERT(reloc_root);
1512
1513 reloc_root_item = &reloc_root->root_item;
1514 memset(&reloc_root_item->drop_progress, 0,
1515 sizeof(reloc_root_item->drop_progress));
1516 btrfs_set_root_drop_level(reloc_root_item, 0);
1517 btrfs_set_root_refs(reloc_root_item, 0);
1518 ret = btrfs_update_reloc_root(trans, root);
1519 if (ret)
1520 return ret;
1521
1522 if (list_empty(&root->reloc_dirty_list)) {
1523 btrfs_grab_root(root);
1524 list_add_tail(&root->reloc_dirty_list, &rc->dirty_subvol_roots);
1525 }
1526
1527 return 0;
1528 }
1529
clear_reloc_root(struct btrfs_root * root)1530 static void clear_reloc_root(struct btrfs_root *root)
1531 {
1532 root->reloc_root = NULL;
1533 /*
1534 * Need barrier to ensure clear_bit() only happens after
1535 * root->reloc_root = NULL. Pairs with have_reloc_root().
1536 */
1537 smp_wmb();
1538 clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
1539 }
1540
1541 /* Drop the reloc trees of a relocation that is being deferred and retried. */
abort_reloc_roots(struct reloc_control * rc,struct list_head * list)1542 static void abort_reloc_roots(struct reloc_control *rc, struct list_head *list)
1543 {
1544 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
1545 struct btrfs_root *reloc_root, *tmp;
1546
1547 list_for_each_entry_safe(reloc_root, tmp, list, root_list) {
1548 struct btrfs_root *root;
1549
1550 root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset, false);
1551 if (!IS_ERR(root)) {
1552 if (root->reloc_root == reloc_root) {
1553 clear_reloc_root(root);
1554 btrfs_put_root(reloc_root);
1555 }
1556 btrfs_put_root(root);
1557 }
1558
1559 btrfs_set_root_refs(&reloc_root->root_item, 0);
1560 memset(&reloc_root->root_item.drop_progress, 0, sizeof(struct btrfs_disk_key));
1561 btrfs_set_root_drop_level(&reloc_root->root_item, 0);
1562
1563 list_del_init(&reloc_root->root_list);
1564 list_add_tail(&reloc_root->reloc_dirty_list, &rc->dirty_subvol_roots);
1565 }
1566 }
1567
clean_dirty_subvols(struct reloc_control * rc)1568 static int clean_dirty_subvols(struct reloc_control *rc)
1569 {
1570 struct btrfs_root *root;
1571 struct btrfs_root *next;
1572 int ret = 0;
1573 int ret2;
1574
1575 list_for_each_entry_safe(root, next, &rc->dirty_subvol_roots,
1576 reloc_dirty_list) {
1577 if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID) {
1578 /* Merged subvolume, cleanup its reloc root */
1579 struct btrfs_root *reloc_root = root->reloc_root;
1580
1581 list_del_init(&root->reloc_dirty_list);
1582 clear_reloc_root(root);
1583 if (reloc_root) {
1584 /*
1585 * btrfs_drop_snapshot drops our ref we hold for
1586 * ->reloc_root. If it fails however we must
1587 * drop the ref ourselves.
1588 */
1589 ret2 = btrfs_drop_snapshot(reloc_root, false, true);
1590 if (ret2 < 0) {
1591 btrfs_put_root(reloc_root);
1592 if (!ret)
1593 ret = ret2;
1594 }
1595 }
1596 btrfs_put_root(root);
1597 } else {
1598 /* Orphan reloc tree, just clean it up */
1599 ret2 = btrfs_drop_snapshot(root, false, true);
1600 if (ret2 < 0) {
1601 btrfs_put_root(root);
1602 if (!ret)
1603 ret = ret2;
1604 }
1605 }
1606 }
1607 return ret;
1608 }
1609
1610 /*
1611 * merge the relocated tree blocks in reloc tree with corresponding
1612 * fs tree.
1613 */
merge_reloc_root(struct reloc_control * rc,struct btrfs_root * root)1614 static noinline_for_stack int merge_reloc_root(struct reloc_control *rc,
1615 struct btrfs_root *root)
1616 {
1617 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
1618 struct btrfs_key key;
1619 struct btrfs_key next_key;
1620 struct btrfs_trans_handle *trans = NULL;
1621 struct btrfs_root *reloc_root;
1622 struct btrfs_root_item *root_item;
1623 struct btrfs_path *path;
1624 struct extent_buffer *leaf;
1625 int reserve_level;
1626 int level;
1627 int max_level;
1628 bool replaced = false;
1629 int ret = 0;
1630 u32 min_reserved;
1631
1632 path = btrfs_alloc_path();
1633 if (!path)
1634 return -ENOMEM;
1635 path->reada = READA_FORWARD;
1636
1637 reloc_root = root->reloc_root;
1638 root_item = &reloc_root->root_item;
1639
1640 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
1641 level = btrfs_root_level(root_item);
1642 refcount_inc(&reloc_root->node->refs);
1643 path->nodes[level] = reloc_root->node;
1644 path->slots[level] = 0;
1645 } else {
1646 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
1647
1648 level = btrfs_root_drop_level(root_item);
1649 BUG_ON(level == 0);
1650 path->lowest_level = level;
1651 ret = btrfs_search_slot(NULL, reloc_root, &key, path, 0, 0);
1652 path->lowest_level = 0;
1653 if (ret < 0) {
1654 btrfs_free_path(path);
1655 return ret;
1656 }
1657
1658 btrfs_node_key_to_cpu(path->nodes[level], &next_key,
1659 path->slots[level]);
1660 WARN_ON(memcmp(&key, &next_key, sizeof(key)));
1661
1662 btrfs_unlock_up_safe(path, 0);
1663 }
1664
1665 /*
1666 * In merge_reloc_root(), we modify the upper level pointer to swap the
1667 * tree blocks between reloc tree and subvolume tree. Thus for tree
1668 * block COW, we COW at most from level 1 to root level for each tree.
1669 *
1670 * Thus the needed metadata size is at most root_level * nodesize,
1671 * and * 2 since we have two trees to COW.
1672 */
1673 reserve_level = max_t(int, 1, btrfs_root_level(root_item));
1674 min_reserved = (reserve_level << fs_info->nodesize_bits) * 2;
1675 memset(&next_key, 0, sizeof(next_key));
1676
1677 while (1) {
1678 ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv,
1679 min_reserved,
1680 BTRFS_RESERVE_FLUSH_LIMIT);
1681 if (ret)
1682 goto out;
1683 trans = btrfs_start_transaction(root, 0);
1684 if (IS_ERR(trans)) {
1685 ret = PTR_ERR(trans);
1686 trans = NULL;
1687 goto out;
1688 }
1689
1690 /*
1691 * At this point we no longer have a reloc_control, so we can't
1692 * depend on btrfs_init_reloc_root to update our last_trans.
1693 *
1694 * But that's ok, we started the trans handle on our
1695 * corresponding fs_root, which means it's been added to the
1696 * dirty list. At commit time we'll still call
1697 * btrfs_update_reloc_root() and update our root item
1698 * appropriately.
1699 */
1700 btrfs_set_root_last_trans(reloc_root, trans->transid);
1701 trans->block_rsv = rc->block_rsv;
1702
1703 replaced = false;
1704 max_level = level;
1705
1706 ret = walk_down_reloc_tree(reloc_root, path, &level);
1707 if (ret < 0)
1708 goto out;
1709 if (ret > 0)
1710 break;
1711
1712 if (!find_next_key(path, level, &key) &&
1713 btrfs_comp_cpu_keys(&next_key, &key) >= 0) {
1714 ret = 0;
1715 } else {
1716 ret = replace_path(trans, rc, root, reloc_root, path,
1717 &next_key, level, max_level);
1718 }
1719 if (ret < 0)
1720 goto out;
1721 if (ret > 0) {
1722 level = ret;
1723 btrfs_node_key_to_cpu(path->nodes[level], &key,
1724 path->slots[level]);
1725 replaced = true;
1726 }
1727
1728 ret = walk_up_reloc_tree(reloc_root, path, &level);
1729 if (ret > 0)
1730 break;
1731
1732 BUG_ON(level == 0);
1733 /*
1734 * save the merging progress in the drop_progress.
1735 * this is OK since root refs == 1 in this case.
1736 */
1737 btrfs_node_key(path->nodes[level], &root_item->drop_progress,
1738 path->slots[level]);
1739 btrfs_set_root_drop_level(root_item, level);
1740
1741 btrfs_end_transaction_throttle(trans);
1742 trans = NULL;
1743
1744 btrfs_btree_balance_dirty(fs_info);
1745
1746 if (replaced && rc->stage == UPDATE_DATA_PTRS)
1747 invalidate_extent_cache(root, &key, &next_key);
1748 }
1749
1750 /*
1751 * handle the case only one block in the fs tree need to be
1752 * relocated and the block is tree root.
1753 */
1754 leaf = btrfs_lock_root_node(root);
1755 ret = btrfs_cow_block(trans, root, leaf, NULL, 0, &leaf,
1756 BTRFS_NESTING_COW);
1757 btrfs_tree_unlock(leaf);
1758 free_extent_buffer(leaf);
1759 out:
1760 btrfs_free_path(path);
1761
1762 if (ret == 0) {
1763 ret = insert_dirty_subvol(trans, rc, root);
1764 if (ret)
1765 btrfs_abort_transaction(trans, ret);
1766 }
1767
1768 if (trans)
1769 btrfs_end_transaction_throttle(trans);
1770
1771 btrfs_btree_balance_dirty(fs_info);
1772
1773 if (replaced && rc->stage == UPDATE_DATA_PTRS)
1774 invalidate_extent_cache(root, &key, &next_key);
1775
1776 return ret;
1777 }
1778
1779 static noinline_for_stack
prepare_to_merge(struct reloc_control * rc,int err)1780 int prepare_to_merge(struct reloc_control *rc, int err)
1781 {
1782 struct btrfs_root *root = rc->extent_root;
1783 struct btrfs_fs_info *fs_info = root->fs_info;
1784 struct btrfs_root *reloc_root;
1785 struct btrfs_trans_handle *trans;
1786 LIST_HEAD(reloc_roots);
1787 u64 num_bytes = 0;
1788 int ret;
1789
1790 mutex_lock(&fs_info->reloc_mutex);
1791 rc->merging_rsv_size += fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
1792 rc->merging_rsv_size += rc->nodes_relocated * 2;
1793 mutex_unlock(&fs_info->reloc_mutex);
1794
1795 again:
1796 if (!err) {
1797 num_bytes = rc->merging_rsv_size;
1798 ret = btrfs_block_rsv_add(fs_info, rc->block_rsv, num_bytes,
1799 BTRFS_RESERVE_FLUSH_ALL);
1800 if (ret)
1801 err = ret;
1802 }
1803
1804 trans = btrfs_join_transaction(rc->extent_root);
1805 if (IS_ERR(trans)) {
1806 if (!err)
1807 btrfs_block_rsv_release(fs_info, rc->block_rsv,
1808 num_bytes, NULL);
1809 return PTR_ERR(trans);
1810 }
1811
1812 if (!err) {
1813 if (num_bytes != rc->merging_rsv_size) {
1814 btrfs_end_transaction(trans);
1815 btrfs_block_rsv_release(fs_info, rc->block_rsv,
1816 num_bytes, NULL);
1817 goto again;
1818 }
1819 }
1820
1821 rc->merge_reloc_tree = true;
1822
1823 while (!list_empty(&rc->reloc_roots)) {
1824 reloc_root = list_first_entry(&rc->reloc_roots,
1825 struct btrfs_root, root_list);
1826 list_del_init(&reloc_root->root_list);
1827
1828 root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
1829 false);
1830 if (IS_ERR(root)) {
1831 /*
1832 * Even if we have an error we need this reloc root
1833 * back on our list so we can clean up properly.
1834 */
1835 list_add(&reloc_root->root_list, &reloc_roots);
1836 btrfs_abort_transaction(trans, (int)PTR_ERR(root));
1837 if (!err)
1838 err = PTR_ERR(root);
1839 break;
1840 }
1841
1842 if (unlikely(root->reloc_root != reloc_root)) {
1843 if (root->reloc_root) {
1844 btrfs_err(fs_info,
1845 "reloc tree mismatch, root %lld has reloc root key (%lld %u %llu) gen %llu, expect reloc root key (%lld %u %llu) gen %llu",
1846 btrfs_root_id(root),
1847 btrfs_root_id(root->reloc_root),
1848 root->reloc_root->root_key.type,
1849 root->reloc_root->root_key.offset,
1850 btrfs_root_generation(
1851 &root->reloc_root->root_item),
1852 btrfs_root_id(reloc_root),
1853 reloc_root->root_key.type,
1854 reloc_root->root_key.offset,
1855 btrfs_root_generation(
1856 &reloc_root->root_item));
1857 } else {
1858 btrfs_err(fs_info,
1859 "reloc tree mismatch, root %lld has no reloc root, expect reloc root key (%lld %u %llu) gen %llu",
1860 btrfs_root_id(root),
1861 btrfs_root_id(reloc_root),
1862 reloc_root->root_key.type,
1863 reloc_root->root_key.offset,
1864 btrfs_root_generation(
1865 &reloc_root->root_item));
1866 }
1867 list_add(&reloc_root->root_list, &reloc_roots);
1868 btrfs_put_root(root);
1869 btrfs_abort_transaction(trans, -EUCLEAN);
1870 if (!err)
1871 err = -EUCLEAN;
1872 break;
1873 }
1874
1875 /*
1876 * set reference count to 1, so btrfs_recover_relocation
1877 * knows it should resumes merging
1878 */
1879 if (!err)
1880 btrfs_set_root_refs(&reloc_root->root_item, 1);
1881 ret = btrfs_update_reloc_root(trans, root);
1882
1883 /*
1884 * Even if we have an error we need this reloc root back on our
1885 * list so we can clean up properly.
1886 */
1887 list_add(&reloc_root->root_list, &reloc_roots);
1888 btrfs_put_root(root);
1889
1890 if (unlikely(ret)) {
1891 btrfs_abort_transaction(trans, ret);
1892 if (!err)
1893 err = ret;
1894 break;
1895 }
1896 }
1897
1898 list_splice(&reloc_roots, &rc->reloc_roots);
1899
1900 if (!err)
1901 err = btrfs_commit_transaction(trans);
1902 else
1903 btrfs_end_transaction(trans);
1904 return err;
1905 }
1906
merge_reloc_roots(struct reloc_control * rc)1907 static noinline_for_stack int merge_reloc_roots(struct reloc_control *rc)
1908 {
1909 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
1910 struct btrfs_root *root;
1911 struct btrfs_root *reloc_root;
1912 LIST_HEAD(reloc_roots);
1913 bool found = false;
1914 int ret = 0;
1915 again:
1916 root = rc->extent_root;
1917
1918 /*
1919 * this serializes us with btrfs_record_root_in_transaction,
1920 * we have to make sure nobody is in the middle of
1921 * adding their roots to the list while we are
1922 * doing this splice
1923 */
1924 mutex_lock(&fs_info->reloc_mutex);
1925 list_splice_init(&rc->reloc_roots, &reloc_roots);
1926 mutex_unlock(&fs_info->reloc_mutex);
1927
1928 while (!list_empty(&reloc_roots)) {
1929 found = true;
1930 reloc_root = list_first_entry(&reloc_roots, struct btrfs_root, root_list);
1931
1932 root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
1933 false);
1934 if (btrfs_root_refs(&reloc_root->root_item) > 0) {
1935 if (WARN_ON(IS_ERR(root))) {
1936 /*
1937 * For recovery we read the fs roots on mount,
1938 * and if we didn't find the root then we marked
1939 * the reloc root as a garbage root. For normal
1940 * relocation obviously the root should exist in
1941 * memory. However there's no reason we can't
1942 * handle the error properly here just in case.
1943 */
1944 ret = PTR_ERR(root);
1945 goto out;
1946 }
1947 if (WARN_ON(root->reloc_root != reloc_root)) {
1948 /*
1949 * This can happen if on-disk metadata has some
1950 * corruption, e.g. bad reloc tree key offset.
1951 */
1952 ret = -EINVAL;
1953 btrfs_put_root(root);
1954 goto out;
1955 }
1956 ret = merge_reloc_root(rc, root);
1957 if (ret) {
1958 /*
1959 * Clear the reloc root since below we will call
1960 * free_reloc_roots(), otherwise we leave
1961 * root->reloc_root pointing to a freed reloc
1962 * root and trigger a use-after-free during
1963 * unmount or elsewhere.
1964 */
1965 clear_reloc_root(root);
1966 btrfs_put_root(root);
1967 /*
1968 * We are adding the reloc_root to the local
1969 * reloc_roots list, so we add a ref for this
1970 * list which will be dropped below by the call
1971 * to free_reloc_roots().
1972 */
1973 if (list_empty(&reloc_root->root_list)) {
1974 list_add_tail(&reloc_root->root_list,
1975 &reloc_roots);
1976 btrfs_grab_root(reloc_root);
1977 }
1978 /* Now drop the ref for root->reloc_root. */
1979 btrfs_put_root(reloc_root);
1980 goto out;
1981 }
1982 btrfs_put_root(root);
1983 } else {
1984 if (!IS_ERR(root)) {
1985 if (root->reloc_root == reloc_root) {
1986 clear_reloc_root(root);
1987 /* Drop the ref for root->reloc_root. */
1988 btrfs_put_root(reloc_root);
1989 }
1990 btrfs_put_root(root);
1991 }
1992
1993 list_del_init(&reloc_root->root_list);
1994 /* Don't forget to queue this reloc root for cleanup */
1995 list_add_tail(&reloc_root->reloc_dirty_list,
1996 &rc->dirty_subvol_roots);
1997 }
1998 }
1999
2000 if (found) {
2001 found = false;
2002 goto again;
2003 }
2004 out:
2005 if (btrfs_is_zoned(fs_info) && ret == -EAGAIN) {
2006 abort_reloc_roots(rc, &reloc_roots);
2007
2008 /* New reloc root may be added. */
2009 mutex_lock(&fs_info->reloc_mutex);
2010 list_splice_init(&rc->reloc_roots, &reloc_roots);
2011 mutex_unlock(&fs_info->reloc_mutex);
2012 abort_reloc_roots(rc, &reloc_roots);
2013 } else if (ret) {
2014 btrfs_handle_fs_error(fs_info, ret, NULL);
2015 free_reloc_roots(&reloc_roots);
2016
2017 /* new reloc root may be added */
2018 mutex_lock(&fs_info->reloc_mutex);
2019 list_splice_init(&rc->reloc_roots, &reloc_roots);
2020 mutex_unlock(&fs_info->reloc_mutex);
2021 free_reloc_roots(&reloc_roots);
2022 }
2023
2024 /*
2025 * We used to have
2026 *
2027 * BUG_ON(!RB_EMPTY_ROOT(&rc->reloc_root_tree.rb_root));
2028 *
2029 * here, but it's wrong. If we fail to start the transaction in
2030 * prepare_to_merge() we will have only 0 ref reloc roots, none of which
2031 * have actually been removed from the reloc_root_tree rb tree. This is
2032 * fine because we're bailing here, and we hold a reference on the root
2033 * for the list that holds it, so these roots will be cleaned up when we
2034 * do the reloc_dirty_list afterwards. Meanwhile the root->reloc_root
2035 * will be cleaned up on unmount.
2036 *
2037 * The remaining nodes will be cleaned up by put_reloc_control().
2038 */
2039 return ret;
2040 }
2041
free_block_list(struct rb_root * blocks)2042 static void free_block_list(struct rb_root *blocks)
2043 {
2044 struct tree_block *block;
2045 struct rb_node *rb_node;
2046 while ((rb_node = rb_first(blocks))) {
2047 block = rb_entry(rb_node, struct tree_block, rb_node);
2048 rb_erase(rb_node, blocks);
2049 kfree(block);
2050 }
2051 }
2052
record_reloc_root_in_trans(struct btrfs_trans_handle * trans,struct btrfs_root * reloc_root)2053 static int record_reloc_root_in_trans(struct btrfs_trans_handle *trans,
2054 struct btrfs_root *reloc_root)
2055 {
2056 struct btrfs_fs_info *fs_info = reloc_root->fs_info;
2057 struct btrfs_root *root;
2058 int ret;
2059
2060 if (btrfs_get_root_last_trans(reloc_root) == trans->transid)
2061 return 0;
2062
2063 root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset, false);
2064
2065 /*
2066 * This should succeed, since we can't have a reloc root without having
2067 * already looked up the actual root and created the reloc root for this
2068 * root.
2069 *
2070 * However if there's some sort of corruption where we have a ref to a
2071 * reloc root without a corresponding root this could return ENOENT.
2072 */
2073 if (IS_ERR(root)) {
2074 DEBUG_WARN("error %ld reading root for reloc root", PTR_ERR(root));
2075 return PTR_ERR(root);
2076 }
2077 if (unlikely(root->reloc_root != reloc_root)) {
2078 DEBUG_WARN("unexpected reloc root found");
2079 btrfs_err(fs_info,
2080 "root %llu has two reloc roots associated with it",
2081 reloc_root->root_key.offset);
2082 btrfs_put_root(root);
2083 return -EUCLEAN;
2084 }
2085 ret = btrfs_record_root_in_trans(trans, root);
2086 btrfs_put_root(root);
2087
2088 return ret;
2089 }
2090
2091 static noinline_for_stack
select_reloc_root(struct btrfs_trans_handle * trans,struct reloc_control * rc,struct btrfs_backref_node * node,struct btrfs_backref_edge * edges[])2092 struct btrfs_root *select_reloc_root(struct btrfs_trans_handle *trans,
2093 struct reloc_control *rc,
2094 struct btrfs_backref_node *node,
2095 struct btrfs_backref_edge *edges[])
2096 {
2097 struct btrfs_backref_node *next;
2098 struct btrfs_root *root;
2099 int index = 0;
2100 int ret;
2101
2102 next = walk_up_backref(node, edges, &index);
2103 root = next->root;
2104
2105 /*
2106 * If there is no root, then our references for this block are
2107 * incomplete, as we should be able to walk all the way up to a block
2108 * that is owned by a root.
2109 *
2110 * This path is only for SHAREABLE roots, so if we come upon a
2111 * non-SHAREABLE root then we have backrefs that resolve improperly.
2112 *
2113 * Both of these cases indicate file system corruption, or a bug in the
2114 * backref walking code.
2115 */
2116 if (unlikely(!root)) {
2117 btrfs_err(trans->fs_info,
2118 "bytenr %llu doesn't have a backref path ending in a root",
2119 node->bytenr);
2120 return ERR_PTR(-EUCLEAN);
2121 }
2122 if (unlikely(!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))) {
2123 btrfs_err(trans->fs_info,
2124 "bytenr %llu has multiple refs with one ending in a non-shareable root",
2125 node->bytenr);
2126 return ERR_PTR(-EUCLEAN);
2127 }
2128
2129 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID) {
2130 ret = record_reloc_root_in_trans(trans, root);
2131 if (ret)
2132 return ERR_PTR(ret);
2133 goto found;
2134 }
2135
2136 ret = btrfs_record_root_in_trans(trans, root);
2137 if (ret)
2138 return ERR_PTR(ret);
2139 root = root->reloc_root;
2140
2141 /*
2142 * We could have raced with another thread which failed, so
2143 * root->reloc_root may not be set, return ENOENT in this case.
2144 */
2145 if (!root)
2146 return ERR_PTR(-ENOENT);
2147
2148 if (unlikely(next->new_bytenr)) {
2149 /*
2150 * We just created the reloc root, so we shouldn't have
2151 * ->new_bytenr set yet. If it is then we have multiple roots
2152 * pointing at the same bytenr which indicates corruption, or
2153 * we've made a mistake in the backref walking code.
2154 */
2155 ASSERT(next->new_bytenr == 0);
2156 btrfs_err(trans->fs_info,
2157 "bytenr %llu possibly has multiple roots pointing at the same bytenr %llu",
2158 node->bytenr, next->bytenr);
2159 return ERR_PTR(-EUCLEAN);
2160 }
2161
2162 next->new_bytenr = root->node->start;
2163 btrfs_put_root(next->root);
2164 next->root = btrfs_grab_root(root);
2165 ASSERT(next->root);
2166 mark_block_processed(rc, next);
2167 found:
2168 next = node;
2169 /* setup backref node path for btrfs_reloc_cow_block */
2170 while (1) {
2171 rc->backref_cache.path[next->level] = next;
2172 if (--index < 0)
2173 break;
2174 next = edges[index]->node[UPPER];
2175 }
2176 return root;
2177 }
2178
2179 /*
2180 * Select a tree root for relocation.
2181 *
2182 * Return NULL if the block is not shareable. We should use do_relocation() in
2183 * this case.
2184 *
2185 * Return a tree root pointer if the block is shareable.
2186 * Return -ENOENT if the block is root of reloc tree.
2187 */
2188 static noinline_for_stack
select_one_root(struct btrfs_backref_node * node)2189 struct btrfs_root *select_one_root(struct btrfs_backref_node *node)
2190 {
2191 struct btrfs_backref_node *next;
2192 struct btrfs_root *root;
2193 struct btrfs_root *fs_root = NULL;
2194 struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
2195 int index = 0;
2196
2197 next = node;
2198 while (1) {
2199 cond_resched();
2200 next = walk_up_backref(next, edges, &index);
2201 root = next->root;
2202
2203 /*
2204 * This can occur if we have incomplete extent refs leading all
2205 * the way up a particular path, in this case return -EUCLEAN.
2206 */
2207 if (unlikely(!root))
2208 return ERR_PTR(-EUCLEAN);
2209
2210 /* No other choice for non-shareable tree */
2211 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
2212 return root;
2213
2214 if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID)
2215 fs_root = root;
2216
2217 if (next != node)
2218 return NULL;
2219
2220 next = walk_down_backref(edges, &index);
2221 if (!next || next->level <= node->level)
2222 break;
2223 }
2224
2225 if (!fs_root)
2226 return ERR_PTR(-ENOENT);
2227 return fs_root;
2228 }
2229
calcu_metadata_size(struct reloc_control * rc,struct btrfs_backref_node * node)2230 static noinline_for_stack u64 calcu_metadata_size(struct reloc_control *rc,
2231 struct btrfs_backref_node *node)
2232 {
2233 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2234 struct btrfs_backref_node *next = node;
2235 struct btrfs_backref_edge *edge;
2236 struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
2237 u64 num_bytes = 0;
2238 int index = 0;
2239
2240 BUG_ON(node->processed);
2241
2242 while (next) {
2243 cond_resched();
2244 while (1) {
2245 if (next->processed)
2246 break;
2247
2248 num_bytes += fs_info->nodesize;
2249
2250 if (list_empty(&next->upper))
2251 break;
2252
2253 edge = list_first_entry(&next->upper, struct btrfs_backref_edge,
2254 list[LOWER]);
2255 edges[index++] = edge;
2256 next = edge->node[UPPER];
2257 }
2258 next = walk_down_backref(edges, &index);
2259 }
2260 return num_bytes;
2261 }
2262
refill_metadata_space(struct btrfs_trans_handle * trans,struct reloc_control * rc,u64 num_bytes)2263 static int refill_metadata_space(struct btrfs_trans_handle *trans,
2264 struct reloc_control *rc, u64 num_bytes)
2265 {
2266 struct btrfs_fs_info *fs_info = trans->fs_info;
2267 int ret;
2268
2269 trans->block_rsv = rc->block_rsv;
2270 rc->reserved_bytes += num_bytes;
2271
2272 /*
2273 * We are under a transaction here so we can only do limited flushing.
2274 * If we get an enospc just kick back -EAGAIN so we know to drop the
2275 * transaction and try to refill when we can flush all the things.
2276 */
2277 ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv, num_bytes,
2278 BTRFS_RESERVE_FLUSH_LIMIT);
2279 if (ret) {
2280 u64 tmp = fs_info->nodesize * RELOCATION_RESERVED_NODES;
2281
2282 while (tmp <= rc->reserved_bytes)
2283 tmp <<= 1;
2284 /*
2285 * only one thread can access block_rsv at this point,
2286 * so we don't need hold lock to protect block_rsv.
2287 * we expand more reservation size here to allow enough
2288 * space for relocation and we will return earlier in
2289 * enospc case.
2290 */
2291 rc->block_rsv->size = tmp + fs_info->nodesize *
2292 RELOCATION_RESERVED_NODES;
2293 return -EAGAIN;
2294 }
2295
2296 return 0;
2297 }
2298
reserve_metadata_space(struct btrfs_trans_handle * trans,struct reloc_control * rc,struct btrfs_backref_node * node)2299 static int reserve_metadata_space(struct btrfs_trans_handle *trans,
2300 struct reloc_control *rc,
2301 struct btrfs_backref_node *node)
2302 {
2303 u64 num_bytes;
2304
2305 num_bytes = calcu_metadata_size(rc, node) * 2;
2306 return refill_metadata_space(trans, rc, num_bytes);
2307 }
2308
2309 /*
2310 * relocate a block tree, and then update pointers in upper level
2311 * blocks that reference the block to point to the new location.
2312 *
2313 * if called by link_to_upper, the block has already been relocated.
2314 * in that case this function just updates pointers.
2315 */
do_relocation(struct btrfs_trans_handle * trans,struct reloc_control * rc,struct btrfs_backref_node * node,struct btrfs_key * key,struct btrfs_path * path,int lowest)2316 static int do_relocation(struct btrfs_trans_handle *trans,
2317 struct reloc_control *rc,
2318 struct btrfs_backref_node *node,
2319 struct btrfs_key *key,
2320 struct btrfs_path *path, int lowest)
2321 {
2322 struct btrfs_backref_node *upper;
2323 struct btrfs_backref_edge *edge;
2324 struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
2325 struct btrfs_root *root;
2326 struct extent_buffer *eb;
2327 u32 blocksize;
2328 u64 bytenr;
2329 int slot;
2330 int ret = 0;
2331
2332 /*
2333 * If we are lowest then this is the first time we're processing this
2334 * block, and thus shouldn't have an eb associated with it yet.
2335 */
2336 ASSERT(!lowest || !node->eb);
2337
2338 path->lowest_level = node->level + 1;
2339 rc->backref_cache.path[node->level] = node;
2340 list_for_each_entry(edge, &node->upper, list[LOWER]) {
2341 cond_resched();
2342
2343 upper = edge->node[UPPER];
2344 root = select_reloc_root(trans, rc, upper, edges);
2345 if (IS_ERR(root)) {
2346 ret = PTR_ERR(root);
2347 goto next;
2348 }
2349
2350 if (upper->eb && !upper->locked) {
2351 if (!lowest) {
2352 ret = btrfs_bin_search(upper->eb, 0, key, &slot);
2353 if (ret < 0)
2354 goto next;
2355 BUG_ON(ret);
2356 bytenr = btrfs_node_blockptr(upper->eb, slot);
2357 if (node->eb->start == bytenr)
2358 goto next;
2359 }
2360 btrfs_backref_drop_node_buffer(upper);
2361 }
2362
2363 if (!upper->eb) {
2364 ret = btrfs_search_slot(trans, root, key, path, 0, 1);
2365 if (ret) {
2366 if (ret > 0)
2367 ret = -ENOENT;
2368
2369 btrfs_release_path(path);
2370 break;
2371 }
2372
2373 if (!upper->eb) {
2374 upper->eb = path->nodes[upper->level];
2375 path->nodes[upper->level] = NULL;
2376 } else {
2377 BUG_ON(upper->eb != path->nodes[upper->level]);
2378 }
2379
2380 upper->locked = 1;
2381 path->locks[upper->level] = 0;
2382
2383 slot = path->slots[upper->level];
2384 btrfs_release_path(path);
2385 } else {
2386 ret = btrfs_bin_search(upper->eb, 0, key, &slot);
2387 if (ret < 0)
2388 goto next;
2389 BUG_ON(ret);
2390 }
2391
2392 bytenr = btrfs_node_blockptr(upper->eb, slot);
2393 if (lowest) {
2394 if (unlikely(bytenr != node->bytenr)) {
2395 btrfs_err(root->fs_info,
2396 "lowest leaf/node mismatch: bytenr %llu node->bytenr %llu slot %d upper %llu",
2397 bytenr, node->bytenr, slot,
2398 upper->eb->start);
2399 ret = -EIO;
2400 goto next;
2401 }
2402 } else {
2403 if (node->eb->start == bytenr)
2404 goto next;
2405 }
2406
2407 blocksize = root->fs_info->nodesize;
2408 eb = btrfs_read_node_slot(upper->eb, slot);
2409 if (IS_ERR(eb)) {
2410 ret = PTR_ERR(eb);
2411 goto next;
2412 }
2413 btrfs_tree_lock(eb);
2414
2415 if (!node->eb) {
2416 ret = btrfs_cow_block(trans, root, eb, upper->eb,
2417 slot, &eb, BTRFS_NESTING_COW);
2418 btrfs_tree_unlock(eb);
2419 free_extent_buffer(eb);
2420 if (ret < 0)
2421 goto next;
2422 /*
2423 * We've just COWed this block, it should have updated
2424 * the correct backref node entry.
2425 */
2426 ASSERT(node->eb == eb);
2427 } else {
2428 struct btrfs_ref ref = {
2429 .action = BTRFS_ADD_DELAYED_REF,
2430 .bytenr = node->eb->start,
2431 .num_bytes = blocksize,
2432 .parent = upper->eb->start,
2433 .owning_root = btrfs_header_owner(upper->eb),
2434 .ref_root = btrfs_header_owner(upper->eb),
2435 };
2436
2437 btrfs_set_node_blockptr(upper->eb, slot,
2438 node->eb->start);
2439 btrfs_set_node_ptr_generation(upper->eb, slot,
2440 trans->transid);
2441 btrfs_mark_buffer_dirty(trans, upper->eb);
2442
2443 btrfs_init_tree_ref(&ref, node->level,
2444 btrfs_root_id(root), false);
2445 ret = btrfs_inc_extent_ref(trans, &ref);
2446 if (!ret)
2447 ret = btrfs_drop_subtree(trans, root, eb,
2448 upper->eb);
2449 if (unlikely(ret))
2450 btrfs_abort_transaction(trans, ret);
2451 }
2452 next:
2453 if (!upper->pending)
2454 btrfs_backref_drop_node_buffer(upper);
2455 else
2456 btrfs_backref_unlock_node_buffer(upper);
2457 if (ret)
2458 break;
2459 }
2460
2461 if (!ret && node->pending) {
2462 btrfs_backref_drop_node_buffer(node);
2463 list_del_init(&node->list);
2464 node->pending = 0;
2465 }
2466
2467 path->lowest_level = 0;
2468
2469 /*
2470 * We should have allocated all of our space in the block rsv and thus
2471 * shouldn't ENOSPC.
2472 */
2473 ASSERT(ret != -ENOSPC);
2474 return ret;
2475 }
2476
link_to_upper(struct btrfs_trans_handle * trans,struct reloc_control * rc,struct btrfs_backref_node * node,struct btrfs_path * path)2477 static int link_to_upper(struct btrfs_trans_handle *trans,
2478 struct reloc_control *rc,
2479 struct btrfs_backref_node *node,
2480 struct btrfs_path *path)
2481 {
2482 struct btrfs_key key;
2483
2484 btrfs_node_key_to_cpu(node->eb, &key, 0);
2485 return do_relocation(trans, rc, node, &key, path, 0);
2486 }
2487
finish_pending_nodes(struct btrfs_trans_handle * trans,struct reloc_control * rc,struct btrfs_path * path,int err)2488 static int finish_pending_nodes(struct btrfs_trans_handle *trans,
2489 struct reloc_control *rc,
2490 struct btrfs_path *path, int err)
2491 {
2492 LIST_HEAD(list);
2493 struct btrfs_backref_cache *cache = &rc->backref_cache;
2494 struct btrfs_backref_node *node;
2495 int level;
2496 int ret;
2497
2498 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2499 while (!list_empty(&cache->pending[level])) {
2500 node = list_first_entry(&cache->pending[level],
2501 struct btrfs_backref_node, list);
2502 list_move_tail(&node->list, &list);
2503 BUG_ON(!node->pending);
2504
2505 if (!err) {
2506 ret = link_to_upper(trans, rc, node, path);
2507 if (ret < 0)
2508 err = ret;
2509 }
2510 }
2511 list_splice_init(&list, &cache->pending[level]);
2512 }
2513 return err;
2514 }
2515
2516 /*
2517 * mark a block and all blocks directly/indirectly reference the block
2518 * as processed.
2519 */
update_processed_blocks(struct reloc_control * rc,struct btrfs_backref_node * node)2520 static void update_processed_blocks(struct reloc_control *rc,
2521 struct btrfs_backref_node *node)
2522 {
2523 struct btrfs_backref_node *next = node;
2524 struct btrfs_backref_edge *edge;
2525 struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
2526 int index = 0;
2527
2528 while (next) {
2529 cond_resched();
2530 while (1) {
2531 if (next->processed)
2532 break;
2533
2534 mark_block_processed(rc, next);
2535
2536 if (list_empty(&next->upper))
2537 break;
2538
2539 edge = list_first_entry(&next->upper, struct btrfs_backref_edge,
2540 list[LOWER]);
2541 edges[index++] = edge;
2542 next = edge->node[UPPER];
2543 }
2544 next = walk_down_backref(edges, &index);
2545 }
2546 }
2547
tree_block_processed(u64 bytenr,struct reloc_control * rc)2548 static int tree_block_processed(u64 bytenr, struct reloc_control *rc)
2549 {
2550 u32 blocksize = rc->extent_root->fs_info->nodesize;
2551
2552 if (btrfs_test_range_bit(&rc->processed_blocks, bytenr,
2553 bytenr + blocksize - 1, EXTENT_DIRTY, NULL))
2554 return 1;
2555 return 0;
2556 }
2557
get_tree_block_key(struct btrfs_fs_info * fs_info,struct tree_block * block)2558 static int get_tree_block_key(struct btrfs_fs_info *fs_info,
2559 struct tree_block *block)
2560 {
2561 struct btrfs_tree_parent_check check = {
2562 .level = block->level,
2563 .owner_root = block->owner,
2564 .transid = block->key.offset
2565 };
2566 struct extent_buffer *eb;
2567
2568 eb = read_tree_block(fs_info, block->bytenr, &check);
2569 if (IS_ERR(eb))
2570 return PTR_ERR(eb);
2571
2572 if (block->level == 0)
2573 btrfs_item_key_to_cpu(eb, &block->key, 0);
2574 else
2575 btrfs_node_key_to_cpu(eb, &block->key, 0);
2576 free_extent_buffer(eb);
2577 block->key_ready = true;
2578 return 0;
2579 }
2580
2581 /*
2582 * helper function to relocate a tree block
2583 */
relocate_tree_block(struct btrfs_trans_handle * trans,struct reloc_control * rc,struct btrfs_backref_node * node,struct btrfs_key * key,struct btrfs_path * path)2584 static int relocate_tree_block(struct btrfs_trans_handle *trans,
2585 struct reloc_control *rc,
2586 struct btrfs_backref_node *node,
2587 struct btrfs_key *key,
2588 struct btrfs_path *path)
2589 {
2590 struct btrfs_root *root;
2591 int ret = 0;
2592
2593 if (!node)
2594 return 0;
2595
2596 /*
2597 * If we fail here we want to drop our backref_node because we are going
2598 * to start over and regenerate the tree for it.
2599 */
2600 ret = reserve_metadata_space(trans, rc, node);
2601 if (ret)
2602 goto out;
2603
2604 BUG_ON(node->processed);
2605 root = select_one_root(node);
2606 if (IS_ERR(root)) {
2607 ret = PTR_ERR(root);
2608
2609 /* See explanation in select_one_root for the -EUCLEAN case. */
2610 ASSERT(ret == -ENOENT);
2611 if (ret == -ENOENT) {
2612 ret = 0;
2613 update_processed_blocks(rc, node);
2614 }
2615 goto out;
2616 }
2617
2618 if (root) {
2619 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
2620 /*
2621 * This block was the root block of a root, and this is
2622 * the first time we're processing the block and thus it
2623 * should not have had the ->new_bytenr modified.
2624 *
2625 * However in the case of corruption we could have
2626 * multiple refs pointing to the same block improperly,
2627 * and thus we would trip over these checks. ASSERT()
2628 * for the developer case, because it could indicate a
2629 * bug in the backref code, however error out for a
2630 * normal user in the case of corruption.
2631 */
2632 ASSERT(node->new_bytenr == 0);
2633 if (unlikely(node->new_bytenr)) {
2634 btrfs_err(root->fs_info,
2635 "bytenr %llu has improper references to it",
2636 node->bytenr);
2637 ret = -EUCLEAN;
2638 goto out;
2639 }
2640 ret = btrfs_record_root_in_trans(trans, root);
2641 if (ret)
2642 goto out;
2643 /*
2644 * Another thread could have failed, need to check if we
2645 * have reloc_root actually set.
2646 */
2647 if (!root->reloc_root) {
2648 ret = -ENOENT;
2649 goto out;
2650 }
2651 root = root->reloc_root;
2652 node->new_bytenr = root->node->start;
2653 btrfs_put_root(node->root);
2654 node->root = btrfs_grab_root(root);
2655 ASSERT(node->root);
2656 } else {
2657 btrfs_err(root->fs_info,
2658 "bytenr %llu resolved to a non-shareable root",
2659 node->bytenr);
2660 ret = -EUCLEAN;
2661 goto out;
2662 }
2663 if (!ret)
2664 update_processed_blocks(rc, node);
2665 } else {
2666 ret = do_relocation(trans, rc, node, key, path, 1);
2667 }
2668 out:
2669 if (ret || node->level == 0)
2670 btrfs_backref_cleanup_node(&rc->backref_cache, node);
2671 return ret;
2672 }
2673
relocate_cowonly_block(struct btrfs_trans_handle * trans,struct reloc_control * rc,struct tree_block * block,struct btrfs_path * path)2674 static int relocate_cowonly_block(struct btrfs_trans_handle *trans,
2675 struct reloc_control *rc, struct tree_block *block,
2676 struct btrfs_path *path)
2677 {
2678 struct btrfs_fs_info *fs_info = trans->fs_info;
2679 struct btrfs_root *root;
2680 u64 num_bytes;
2681 int nr_levels;
2682 int ret;
2683
2684 root = btrfs_get_fs_root(fs_info, block->owner, true);
2685 if (IS_ERR(root))
2686 return PTR_ERR(root);
2687
2688 nr_levels = max(btrfs_header_level(root->node) - block->level, 0) + 1;
2689
2690 num_bytes = (nr_levels << fs_info->nodesize_bits);
2691 ret = refill_metadata_space(trans, rc, num_bytes);
2692 if (ret) {
2693 btrfs_put_root(root);
2694 return ret;
2695 }
2696 path->lowest_level = block->level;
2697 if (root == root->fs_info->chunk_root)
2698 btrfs_reserve_chunk_metadata(trans, false);
2699
2700 ret = btrfs_search_slot(trans, root, &block->key, path, 0, 1);
2701 path->lowest_level = 0;
2702 btrfs_release_path(path);
2703
2704 if (root == root->fs_info->chunk_root)
2705 btrfs_trans_release_chunk_metadata(trans);
2706 if (ret > 0)
2707 ret = 0;
2708 btrfs_put_root(root);
2709
2710 return ret;
2711 }
2712
2713 /*
2714 * relocate a list of blocks
2715 */
2716 static noinline_for_stack
relocate_tree_blocks(struct btrfs_trans_handle * trans,struct reloc_control * rc,struct rb_root * blocks)2717 int relocate_tree_blocks(struct btrfs_trans_handle *trans,
2718 struct reloc_control *rc, struct rb_root *blocks)
2719 {
2720 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
2721 struct btrfs_backref_node *node;
2722 struct btrfs_path *path;
2723 struct tree_block *block;
2724 struct tree_block *next;
2725 int ret = 0;
2726
2727 path = btrfs_alloc_path();
2728 if (!path) {
2729 ret = -ENOMEM;
2730 goto out_free_blocks;
2731 }
2732
2733 /* Kick in readahead for tree blocks with missing keys */
2734 rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
2735 if (!block->key_ready)
2736 btrfs_readahead_tree_block(fs_info, block->bytenr,
2737 block->owner, 0,
2738 block->level, NULL);
2739 }
2740
2741 /* Get first keys */
2742 rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
2743 if (!block->key_ready) {
2744 ret = get_tree_block_key(fs_info, block);
2745 if (ret)
2746 goto out_free_path;
2747 }
2748 }
2749
2750 /* Do tree relocation */
2751 rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
2752 /*
2753 * For COWonly blocks, or the data reloc tree, we only need to
2754 * COW down to the block, there's no need to generate a backref
2755 * tree.
2756 */
2757 if (block->owner &&
2758 (!btrfs_is_fstree(block->owner) ||
2759 block->owner == BTRFS_DATA_RELOC_TREE_OBJECTID)) {
2760 ret = relocate_cowonly_block(trans, rc, block, path);
2761 if (ret)
2762 break;
2763 continue;
2764 }
2765
2766 node = build_backref_tree(trans, rc, &block->key,
2767 block->level, block->bytenr);
2768 if (IS_ERR(node)) {
2769 ret = PTR_ERR(node);
2770 goto out;
2771 }
2772
2773 ret = relocate_tree_block(trans, rc, node, &block->key,
2774 path);
2775 if (ret < 0)
2776 break;
2777 }
2778 out:
2779 ret = finish_pending_nodes(trans, rc, path, ret);
2780
2781 out_free_path:
2782 btrfs_free_path(path);
2783 out_free_blocks:
2784 free_block_list(blocks);
2785 return ret;
2786 }
2787
prealloc_file_extent_cluster(struct reloc_control * rc)2788 static noinline_for_stack int prealloc_file_extent_cluster(struct reloc_control *rc)
2789 {
2790 const struct file_extent_cluster *cluster = &rc->cluster;
2791 struct btrfs_inode *inode = BTRFS_I(rc->data_inode);
2792 u64 alloc_hint = 0;
2793 u64 start;
2794 u64 end;
2795 u64 offset = inode->reloc_block_group_start;
2796 u64 num_bytes;
2797 int nr;
2798 int ret = 0;
2799 u64 prealloc_start = cluster->start - offset;
2800 u64 prealloc_end = cluster->end - offset;
2801 u64 cur_offset = prealloc_start;
2802
2803 /*
2804 * For blocksize < folio size case (either bs < page size or large folios),
2805 * beyond i_size, all blocks are filled with zero.
2806 *
2807 * If the current cluster covers the above range, btrfs_do_readpage()
2808 * will skip the read, and relocate_one_folio() will later writeback
2809 * the padding zeros as new data, causing data corruption.
2810 *
2811 * Here we have to invalidate the cache covering our cluster.
2812 */
2813 ret = filemap_invalidate_inode(&inode->vfs_inode, true, prealloc_start,
2814 prealloc_end);
2815 if (ret < 0)
2816 return ret;
2817
2818 BUG_ON(cluster->start != cluster->boundary[0]);
2819 ret = btrfs_alloc_data_chunk_ondemand(inode,
2820 prealloc_end + 1 - prealloc_start);
2821 if (ret)
2822 return ret;
2823
2824 btrfs_inode_lock(inode, 0);
2825 for (nr = 0; nr < cluster->nr; nr++) {
2826 struct extent_state *cached_state = NULL;
2827
2828 start = cluster->boundary[nr] - offset;
2829 if (nr + 1 < cluster->nr)
2830 end = cluster->boundary[nr + 1] - 1 - offset;
2831 else
2832 end = cluster->end - offset;
2833
2834 btrfs_lock_extent(&inode->io_tree, start, end, &cached_state);
2835 num_bytes = end + 1 - start;
2836 ret = btrfs_prealloc_file_range(&inode->vfs_inode, 0, start,
2837 num_bytes, num_bytes,
2838 end + 1, &alloc_hint);
2839 cur_offset = end + 1;
2840 btrfs_unlock_extent(&inode->io_tree, start, end, &cached_state);
2841 if (ret)
2842 break;
2843 }
2844 btrfs_inode_unlock(inode, 0);
2845
2846 if (cur_offset < prealloc_end)
2847 btrfs_free_reserved_data_space_noquota(inode,
2848 prealloc_end + 1 - cur_offset);
2849 return ret;
2850 }
2851
setup_relocation_extent_mapping(struct reloc_control * rc)2852 static noinline_for_stack int setup_relocation_extent_mapping(struct reloc_control *rc)
2853 {
2854 struct btrfs_inode *inode = BTRFS_I(rc->data_inode);
2855 struct extent_map *em;
2856 struct extent_state *cached_state = NULL;
2857 u64 offset = inode->reloc_block_group_start;
2858 u64 start = rc->cluster.start - offset;
2859 u64 end = rc->cluster.end - offset;
2860 int ret = 0;
2861
2862 em = btrfs_alloc_extent_map();
2863 if (!em)
2864 return -ENOMEM;
2865
2866 em->start = start;
2867 em->len = end + 1 - start;
2868 em->disk_bytenr = rc->cluster.start;
2869 em->disk_num_bytes = em->len;
2870 em->ram_bytes = em->len;
2871 em->flags |= EXTENT_FLAG_PINNED;
2872
2873 btrfs_lock_extent(&inode->io_tree, start, end, &cached_state);
2874 ret = btrfs_replace_extent_map_range(inode, em, false);
2875 btrfs_unlock_extent(&inode->io_tree, start, end, &cached_state);
2876 btrfs_free_extent_map(em);
2877
2878 return ret;
2879 }
2880
2881 /*
2882 * Allow error injection to test balance/relocation cancellation
2883 */
btrfs_should_cancel_balance(const struct btrfs_fs_info * fs_info)2884 noinline int btrfs_should_cancel_balance(const struct btrfs_fs_info *fs_info)
2885 {
2886 return atomic_read(&fs_info->balance_cancel_req) ||
2887 atomic_read(&fs_info->reloc_cancel_req) ||
2888 fatal_signal_pending(current);
2889 }
2890 ALLOW_ERROR_INJECTION(btrfs_should_cancel_balance, TRUE);
2891
get_cluster_boundary_end(const struct file_extent_cluster * cluster,int cluster_nr)2892 static u64 get_cluster_boundary_end(const struct file_extent_cluster *cluster,
2893 int cluster_nr)
2894 {
2895 /* Last extent, use cluster end directly */
2896 if (cluster_nr >= cluster->nr - 1)
2897 return cluster->end;
2898
2899 /* Use next boundary start*/
2900 return cluster->boundary[cluster_nr + 1] - 1;
2901 }
2902
relocate_one_folio(struct reloc_control * rc,struct file_ra_state * ra,int * cluster_nr,u64 * file_offset_ret)2903 static int relocate_one_folio(struct reloc_control *rc,
2904 struct file_ra_state *ra,
2905 int *cluster_nr, u64 *file_offset_ret)
2906 {
2907 const struct file_extent_cluster *cluster = &rc->cluster;
2908 struct inode *inode = rc->data_inode;
2909 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
2910 const u64 orig_file_offset = *file_offset_ret;
2911 u64 offset = BTRFS_I(inode)->reloc_block_group_start;
2912 const pgoff_t last_index = (cluster->end - offset) >> PAGE_SHIFT;
2913 const pgoff_t index = orig_file_offset >> PAGE_SHIFT;
2914 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
2915 struct folio *folio;
2916 u64 folio_start;
2917 u64 folio_end;
2918 u64 cur;
2919 int ret;
2920 const bool use_rst = btrfs_need_stripe_tree_update(fs_info, rc->block_group->flags);
2921
2922 ASSERT(index <= last_index);
2923 again:
2924 folio = filemap_lock_folio(inode->i_mapping, index);
2925 if (IS_ERR(folio)) {
2926
2927 /*
2928 * On relocation we're doing readahead on the relocation inode,
2929 * but if the filesystem is backed by a RAID stripe tree we can
2930 * get ENOENT (e.g. due to preallocated extents not being
2931 * mapped in the RST) from the lookup.
2932 *
2933 * But readahead doesn't handle the error and submits invalid
2934 * reads to the device, causing a assertion failures.
2935 */
2936 if (!use_rst)
2937 page_cache_sync_readahead(inode->i_mapping, ra, NULL,
2938 index, last_index + 1 - index);
2939 folio = __filemap_get_folio(inode->i_mapping, index,
2940 FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
2941 mask);
2942 if (IS_ERR(folio))
2943 return PTR_ERR(folio);
2944 }
2945
2946 if (folio_test_readahead(folio) && !use_rst)
2947 page_cache_async_readahead(inode->i_mapping, ra, NULL,
2948 folio, last_index + 1 - index);
2949
2950 if (!folio_test_uptodate(folio)) {
2951 btrfs_read_folio(NULL, folio);
2952 folio_lock(folio);
2953 if (unlikely(!folio_test_uptodate(folio))) {
2954 ret = -EIO;
2955 goto release_folio;
2956 }
2957 if (folio->mapping != inode->i_mapping) {
2958 folio_unlock(folio);
2959 folio_put(folio);
2960 goto again;
2961 }
2962 }
2963
2964 /*
2965 * We could have lost folio private when we dropped the lock to read the
2966 * folio above, make sure we set_folio_extent_mapped() here so we have any
2967 * of the subpage blocksize stuff we need in place.
2968 */
2969 ret = set_folio_extent_mapped(folio);
2970 if (ret < 0)
2971 goto release_folio;
2972
2973 folio_start = folio_pos(folio);
2974 folio_end = folio_start + folio_size(folio) - 1;
2975
2976 /*
2977 * Start from the cluster, as for subpage case, the cluster can start
2978 * inside the folio.
2979 */
2980 cur = max(folio_start, cluster->boundary[*cluster_nr] - offset);
2981 while (cur <= folio_end) {
2982 struct extent_state *cached_state = NULL;
2983 u64 extent_start = cluster->boundary[*cluster_nr] - offset;
2984 u64 extent_end = get_cluster_boundary_end(cluster,
2985 *cluster_nr) - offset;
2986 u64 clamped_start = max(folio_start, extent_start);
2987 u64 clamped_end = min(folio_end, extent_end);
2988 u32 clamped_len = clamped_end + 1 - clamped_start;
2989
2990 /* Reserve metadata for this range */
2991 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
2992 clamped_len, clamped_len,
2993 false);
2994 if (ret)
2995 goto release_folio;
2996
2997 /* Mark the range delalloc and dirty for later writeback */
2998 btrfs_lock_extent(&BTRFS_I(inode)->io_tree, clamped_start,
2999 clamped_end, &cached_state);
3000 ret = btrfs_set_extent_delalloc(BTRFS_I(inode), clamped_start,
3001 clamped_end, 0, &cached_state);
3002 if (ret) {
3003 btrfs_clear_extent_bit(&BTRFS_I(inode)->io_tree,
3004 clamped_start, clamped_end,
3005 EXTENT_LOCKED | EXTENT_BOUNDARY,
3006 &cached_state);
3007 btrfs_delalloc_release_metadata(BTRFS_I(inode),
3008 clamped_len, true);
3009 btrfs_delalloc_release_extents(BTRFS_I(inode),
3010 clamped_len);
3011 goto release_folio;
3012 }
3013 btrfs_folio_set_dirty(fs_info, folio, clamped_start, clamped_len);
3014
3015 /*
3016 * Set the boundary if it's inside the folio.
3017 * Data relocation requires the destination extents to have the
3018 * same size as the source.
3019 * EXTENT_BOUNDARY bit prevents current extent from being merged
3020 * with previous extent.
3021 */
3022 if (in_range(cluster->boundary[*cluster_nr] - offset,
3023 folio_start, folio_size(folio))) {
3024 u64 boundary_start = cluster->boundary[*cluster_nr] -
3025 offset;
3026 u64 boundary_end = boundary_start +
3027 fs_info->sectorsize - 1;
3028
3029 btrfs_set_extent_bit(&BTRFS_I(inode)->io_tree,
3030 boundary_start, boundary_end,
3031 EXTENT_BOUNDARY, NULL);
3032 }
3033 btrfs_unlock_extent(&BTRFS_I(inode)->io_tree, clamped_start, clamped_end,
3034 &cached_state);
3035 btrfs_delalloc_release_extents(BTRFS_I(inode), clamped_len);
3036 cur += clamped_len;
3037
3038 /* Crossed extent end, go to next extent */
3039 if (cur >= extent_end) {
3040 (*cluster_nr)++;
3041 /* Just finished the last extent of the cluster, exit. */
3042 if (*cluster_nr >= cluster->nr)
3043 break;
3044 }
3045 }
3046 folio_unlock(folio);
3047 folio_put(folio);
3048
3049 balance_dirty_pages_ratelimited(inode->i_mapping);
3050 btrfs_throttle(fs_info);
3051 if (btrfs_should_cancel_balance(fs_info))
3052 ret = -ECANCELED;
3053 *file_offset_ret = folio_end + 1;
3054 return ret;
3055
3056 release_folio:
3057 folio_unlock(folio);
3058 folio_put(folio);
3059 return ret;
3060 }
3061
relocate_file_extent_cluster(struct reloc_control * rc)3062 static int relocate_file_extent_cluster(struct reloc_control *rc)
3063 {
3064 struct inode *inode = rc->data_inode;
3065 const struct file_extent_cluster *cluster = &rc->cluster;
3066 u64 offset = BTRFS_I(inode)->reloc_block_group_start;
3067 u64 cur_file_offset = cluster->start - offset;
3068 struct file_ra_state AUTO_KFREE(ra);
3069 int cluster_nr = 0;
3070 int ret = 0;
3071
3072 if (!cluster->nr)
3073 return 0;
3074
3075 ra = kzalloc_obj(*ra, GFP_NOFS);
3076 if (!ra)
3077 return -ENOMEM;
3078
3079 ret = prealloc_file_extent_cluster(rc);
3080 if (ret)
3081 return ret;
3082
3083 file_ra_state_init(ra, inode->i_mapping);
3084
3085 ret = setup_relocation_extent_mapping(rc);
3086 if (ret)
3087 return ret;
3088
3089 while (cur_file_offset < cluster->end - offset) {
3090 ret = relocate_one_folio(rc, ra, &cluster_nr, &cur_file_offset);
3091 if (ret)
3092 break;
3093 }
3094 if (ret == 0)
3095 WARN_ON(cluster_nr != cluster->nr);
3096 return ret;
3097 }
3098
relocate_data_extent(struct reloc_control * rc,const struct btrfs_key * extent_key)3099 static noinline_for_stack int relocate_data_extent(struct reloc_control *rc,
3100 const struct btrfs_key *extent_key)
3101 {
3102 struct inode *inode = rc->data_inode;
3103 struct file_extent_cluster *cluster = &rc->cluster;
3104 int ret;
3105 struct btrfs_root *root = BTRFS_I(inode)->root;
3106
3107 if (cluster->nr > 0 && extent_key->objectid != cluster->end + 1) {
3108 ret = relocate_file_extent_cluster(rc);
3109 if (ret)
3110 return ret;
3111 cluster->nr = 0;
3112 }
3113
3114 /*
3115 * Under simple quotas, we set root->relocation_src_root when we find
3116 * the extent. If adjacent extents have different owners, we can't merge
3117 * them while relocating. Handle this by storing the owning root that
3118 * started a cluster and if we see an extent from a different root break
3119 * cluster formation (just like the above case of non-adjacent extents).
3120 *
3121 * Without simple quotas, relocation_src_root is always 0, so we should
3122 * never see a mismatch, and it should have no effect on relocation
3123 * clusters.
3124 */
3125 if (cluster->nr > 0 && cluster->owning_root != root->relocation_src_root) {
3126 u64 tmp = root->relocation_src_root;
3127
3128 /*
3129 * root->relocation_src_root is the state that actually affects
3130 * the preallocation we do here, so set it to the root owning
3131 * the cluster we need to relocate.
3132 */
3133 root->relocation_src_root = cluster->owning_root;
3134 ret = relocate_file_extent_cluster(rc);
3135 if (ret)
3136 return ret;
3137 cluster->nr = 0;
3138 /* And reset it back for the current extent's owning root. */
3139 root->relocation_src_root = tmp;
3140 }
3141
3142 if (!cluster->nr) {
3143 cluster->start = extent_key->objectid;
3144 cluster->owning_root = root->relocation_src_root;
3145 }
3146 else
3147 BUG_ON(cluster->nr >= MAX_EXTENTS);
3148 cluster->end = extent_key->objectid + extent_key->offset - 1;
3149 cluster->boundary[cluster->nr] = extent_key->objectid;
3150 cluster->nr++;
3151
3152 if (cluster->nr >= MAX_EXTENTS) {
3153 ret = relocate_file_extent_cluster(rc);
3154 if (ret)
3155 return ret;
3156 cluster->nr = 0;
3157 }
3158 return 0;
3159 }
3160
3161 /*
3162 * helper to add a tree block to the list.
3163 * the major work is getting the generation and level of the block
3164 */
add_tree_block(struct reloc_control * rc,const struct btrfs_key * extent_key,struct btrfs_path * path,struct rb_root * blocks)3165 static int add_tree_block(struct reloc_control *rc,
3166 const struct btrfs_key *extent_key,
3167 struct btrfs_path *path,
3168 struct rb_root *blocks)
3169 {
3170 struct extent_buffer *eb;
3171 struct btrfs_extent_item *ei;
3172 struct btrfs_tree_block_info *bi;
3173 struct tree_block *block;
3174 struct rb_node *rb_node;
3175 u32 item_size;
3176 int level = -1;
3177 u64 generation;
3178 u64 owner = 0;
3179
3180 eb = path->nodes[0];
3181 item_size = btrfs_item_size(eb, path->slots[0]);
3182
3183 if (extent_key->type == BTRFS_METADATA_ITEM_KEY ||
3184 item_size >= sizeof(*ei) + sizeof(*bi)) {
3185 unsigned long ptr = 0, end;
3186
3187 ei = btrfs_item_ptr(eb, path->slots[0],
3188 struct btrfs_extent_item);
3189 end = (unsigned long)ei + item_size;
3190 if (extent_key->type == BTRFS_EXTENT_ITEM_KEY) {
3191 bi = (struct btrfs_tree_block_info *)(ei + 1);
3192 level = btrfs_tree_block_level(eb, bi);
3193 ptr = (unsigned long)(bi + 1);
3194 } else {
3195 level = (int)extent_key->offset;
3196 ptr = (unsigned long)(ei + 1);
3197 }
3198 generation = btrfs_extent_generation(eb, ei);
3199
3200 /*
3201 * We're reading random blocks without knowing their owner ahead
3202 * of time. This is ok most of the time, as all reloc roots and
3203 * fs roots have the same lock type. However normal trees do
3204 * not, and the only way to know ahead of time is to read the
3205 * inline ref offset. We know it's an fs root if
3206 *
3207 * 1. There's more than one ref.
3208 * 2. There's a SHARED_DATA_REF_KEY set.
3209 * 3. FULL_BACKREF is set on the flags.
3210 *
3211 * Otherwise it's safe to assume that the ref offset == the
3212 * owner of this block, so we can use that when calling
3213 * read_tree_block.
3214 */
3215 if (btrfs_extent_refs(eb, ei) == 1 &&
3216 !(btrfs_extent_flags(eb, ei) &
3217 BTRFS_BLOCK_FLAG_FULL_BACKREF) &&
3218 ptr < end) {
3219 struct btrfs_extent_inline_ref *iref;
3220 int type;
3221
3222 iref = (struct btrfs_extent_inline_ref *)ptr;
3223 type = btrfs_get_extent_inline_ref_type(eb, iref,
3224 BTRFS_REF_TYPE_BLOCK);
3225 if (type == BTRFS_REF_TYPE_INVALID)
3226 return -EINVAL;
3227 if (type == BTRFS_TREE_BLOCK_REF_KEY)
3228 owner = btrfs_extent_inline_ref_offset(eb, iref);
3229 }
3230 } else {
3231 btrfs_print_leaf(eb);
3232 btrfs_err(rc->block_group->fs_info,
3233 "unrecognized tree backref at tree block %llu slot %u",
3234 eb->start, path->slots[0]);
3235 btrfs_release_path(path);
3236 return -EUCLEAN;
3237 }
3238
3239 btrfs_release_path(path);
3240
3241 BUG_ON(level == -1);
3242
3243 block = kmalloc_obj(*block, GFP_NOFS);
3244 if (!block)
3245 return -ENOMEM;
3246
3247 block->bytenr = extent_key->objectid;
3248 block->key.objectid = rc->extent_root->fs_info->nodesize;
3249 block->key.offset = generation;
3250 block->level = level;
3251 block->key_ready = false;
3252 block->owner = owner;
3253
3254 rb_node = rb_simple_insert(blocks, &block->simple_node);
3255 if (rb_node)
3256 btrfs_backref_panic(rc->extent_root->fs_info, block->bytenr,
3257 -EEXIST);
3258
3259 return 0;
3260 }
3261
3262 /*
3263 * helper to add tree blocks for backref of type BTRFS_SHARED_DATA_REF_KEY
3264 */
__add_tree_block(struct reloc_control * rc,u64 bytenr,u32 blocksize,struct rb_root * blocks)3265 static int __add_tree_block(struct reloc_control *rc,
3266 u64 bytenr, u32 blocksize,
3267 struct rb_root *blocks)
3268 {
3269 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3270 BTRFS_PATH_AUTO_FREE(path);
3271 struct btrfs_key key;
3272 int ret;
3273 bool skinny = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
3274
3275 if (tree_block_processed(bytenr, rc))
3276 return 0;
3277
3278 if (rb_simple_search(blocks, bytenr))
3279 return 0;
3280
3281 path = btrfs_alloc_path();
3282 if (!path)
3283 return -ENOMEM;
3284 again:
3285 key.objectid = bytenr;
3286 if (skinny) {
3287 key.type = BTRFS_METADATA_ITEM_KEY;
3288 key.offset = (u64)-1;
3289 } else {
3290 key.type = BTRFS_EXTENT_ITEM_KEY;
3291 key.offset = blocksize;
3292 }
3293
3294 path->search_commit_root = true;
3295 path->skip_locking = true;
3296 ret = btrfs_search_slot(NULL, rc->extent_root, &key, path, 0, 0);
3297 if (ret < 0)
3298 return ret;
3299
3300 if (ret > 0 && skinny) {
3301 if (path->slots[0]) {
3302 path->slots[0]--;
3303 btrfs_item_key_to_cpu(path->nodes[0], &key,
3304 path->slots[0]);
3305 if (key.objectid == bytenr &&
3306 (key.type == BTRFS_METADATA_ITEM_KEY ||
3307 (key.type == BTRFS_EXTENT_ITEM_KEY &&
3308 key.offset == blocksize)))
3309 ret = 0;
3310 }
3311
3312 if (ret) {
3313 skinny = false;
3314 btrfs_release_path(path);
3315 goto again;
3316 }
3317 }
3318 if (WARN_ON(ret)) {
3319 ASSERT(ret == 1);
3320 btrfs_print_leaf(path->nodes[0]);
3321 btrfs_err(fs_info,
3322 "tree block extent item (%llu) is not found in extent tree",
3323 bytenr);
3324 return -EINVAL;
3325 }
3326
3327 return add_tree_block(rc, &key, path, blocks);
3328 }
3329
delete_block_group_cache(struct btrfs_block_group * block_group,struct inode * inode,u64 ino)3330 static int delete_block_group_cache(struct btrfs_block_group *block_group,
3331 struct inode *inode,
3332 u64 ino)
3333 {
3334 struct btrfs_fs_info *fs_info = block_group->fs_info;
3335 struct btrfs_root *root = fs_info->tree_root;
3336 struct btrfs_trans_handle *trans;
3337 struct btrfs_inode *btrfs_inode;
3338 int ret = 0;
3339
3340 if (inode)
3341 goto truncate;
3342
3343 btrfs_inode = btrfs_iget(ino, root);
3344 if (IS_ERR(btrfs_inode))
3345 return -ENOENT;
3346 inode = &btrfs_inode->vfs_inode;
3347
3348 truncate:
3349 ret = btrfs_check_trunc_cache_free_space(fs_info,
3350 &fs_info->global_block_rsv);
3351 if (ret)
3352 goto out;
3353
3354 trans = btrfs_join_transaction(root);
3355 if (IS_ERR(trans)) {
3356 ret = PTR_ERR(trans);
3357 goto out;
3358 }
3359
3360 ret = btrfs_truncate_free_space_cache(trans, block_group, inode);
3361
3362 btrfs_end_transaction(trans);
3363 btrfs_btree_balance_dirty(fs_info);
3364 out:
3365 iput(inode);
3366 return ret;
3367 }
3368
3369 /*
3370 * Locate the free space cache EXTENT_DATA in root tree leaf and delete the
3371 * cache inode, to avoid free space cache data extent blocking data relocation.
3372 */
delete_v1_space_cache(struct extent_buffer * leaf,struct btrfs_block_group * block_group,u64 data_bytenr)3373 static int delete_v1_space_cache(struct extent_buffer *leaf,
3374 struct btrfs_block_group *block_group,
3375 u64 data_bytenr)
3376 {
3377 u64 space_cache_ino;
3378 struct btrfs_file_extent_item *ei;
3379 struct btrfs_key key;
3380 bool found = false;
3381 int i;
3382
3383 if (btrfs_header_owner(leaf) != BTRFS_ROOT_TREE_OBJECTID)
3384 return 0;
3385
3386 for (i = 0; i < btrfs_header_nritems(leaf); i++) {
3387 u8 type;
3388
3389 btrfs_item_key_to_cpu(leaf, &key, i);
3390 if (key.type != BTRFS_EXTENT_DATA_KEY)
3391 continue;
3392 ei = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
3393 type = btrfs_file_extent_type(leaf, ei);
3394
3395 if ((type == BTRFS_FILE_EXTENT_REG ||
3396 type == BTRFS_FILE_EXTENT_PREALLOC) &&
3397 btrfs_file_extent_disk_bytenr(leaf, ei) == data_bytenr) {
3398 found = true;
3399 space_cache_ino = key.objectid;
3400 break;
3401 }
3402 }
3403 if (!found)
3404 return -ENOENT;
3405
3406 return delete_block_group_cache(block_group, NULL, space_cache_ino);
3407 }
3408
3409 /*
3410 * helper to find all tree blocks that reference a given data extent
3411 */
add_data_references(struct reloc_control * rc,const struct btrfs_key * extent_key,struct btrfs_path * path,struct rb_root * blocks)3412 static noinline_for_stack int add_data_references(struct reloc_control *rc,
3413 const struct btrfs_key *extent_key,
3414 struct btrfs_path *path,
3415 struct rb_root *blocks)
3416 {
3417 struct btrfs_backref_walk_ctx ctx = { 0 };
3418 struct ulist_iterator leaf_uiter;
3419 struct ulist_node *ref_node = NULL;
3420 const u32 blocksize = rc->extent_root->fs_info->nodesize;
3421 int ret = 0;
3422
3423 btrfs_release_path(path);
3424
3425 ctx.bytenr = extent_key->objectid;
3426 ctx.skip_inode_ref_list = true;
3427 ctx.fs_info = rc->extent_root->fs_info;
3428
3429 ret = btrfs_find_all_leafs(&ctx);
3430 if (ret < 0)
3431 return ret;
3432
3433 ULIST_ITER_INIT(&leaf_uiter);
3434 while ((ref_node = ulist_next(ctx.refs, &leaf_uiter))) {
3435 struct btrfs_tree_parent_check check = { 0 };
3436 struct extent_buffer *eb;
3437
3438 eb = read_tree_block(ctx.fs_info, ref_node->val, &check);
3439 if (IS_ERR(eb)) {
3440 ret = PTR_ERR(eb);
3441 break;
3442 }
3443 ret = delete_v1_space_cache(eb, rc->block_group,
3444 extent_key->objectid);
3445 free_extent_buffer(eb);
3446 if (ret < 0)
3447 break;
3448 ret = __add_tree_block(rc, ref_node->val, blocksize, blocks);
3449 if (ret < 0)
3450 break;
3451 }
3452 if (ret < 0)
3453 free_block_list(blocks);
3454 ulist_free(ctx.refs);
3455 return ret;
3456 }
3457
3458 /*
3459 * helper to find next unprocessed extent
3460 */
3461 static noinline_for_stack
find_next_extent(struct reloc_control * rc,struct btrfs_path * path,struct btrfs_key * extent_key)3462 int find_next_extent(struct reloc_control *rc, struct btrfs_path *path,
3463 struct btrfs_key *extent_key)
3464 {
3465 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3466 struct btrfs_key key;
3467 struct extent_buffer *leaf;
3468 u64 start, end, last;
3469 int ret;
3470
3471 last = rc->block_group->start + rc->block_group->length;
3472 while (1) {
3473 bool block_found;
3474
3475 cond_resched();
3476 if (rc->search_start >= last) {
3477 ret = 1;
3478 break;
3479 }
3480
3481 key.objectid = rc->search_start;
3482 key.type = BTRFS_EXTENT_ITEM_KEY;
3483 key.offset = 0;
3484
3485 path->search_commit_root = true;
3486 path->skip_locking = true;
3487 ret = btrfs_search_slot(NULL, rc->extent_root, &key, path,
3488 0, 0);
3489 if (ret < 0)
3490 break;
3491 next:
3492 leaf = path->nodes[0];
3493 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
3494 ret = btrfs_next_leaf(rc->extent_root, path);
3495 if (ret != 0)
3496 break;
3497 leaf = path->nodes[0];
3498 }
3499
3500 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3501 if (key.objectid >= last) {
3502 ret = 1;
3503 break;
3504 }
3505
3506 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
3507 key.type != BTRFS_METADATA_ITEM_KEY) {
3508 path->slots[0]++;
3509 goto next;
3510 }
3511
3512 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
3513 key.objectid + key.offset <= rc->search_start) {
3514 path->slots[0]++;
3515 goto next;
3516 }
3517
3518 if (key.type == BTRFS_METADATA_ITEM_KEY &&
3519 key.objectid + fs_info->nodesize <=
3520 rc->search_start) {
3521 path->slots[0]++;
3522 goto next;
3523 }
3524
3525 block_found = btrfs_find_first_extent_bit(&rc->processed_blocks,
3526 key.objectid, &start, &end,
3527 EXTENT_DIRTY, NULL);
3528
3529 if (block_found && start <= key.objectid) {
3530 btrfs_release_path(path);
3531 rc->search_start = end + 1;
3532 } else {
3533 if (key.type == BTRFS_EXTENT_ITEM_KEY)
3534 rc->search_start = key.objectid + key.offset;
3535 else
3536 rc->search_start = key.objectid +
3537 fs_info->nodesize;
3538 memcpy(extent_key, &key, sizeof(key));
3539 return 0;
3540 }
3541 }
3542 btrfs_release_path(path);
3543 return ret;
3544 }
3545
set_reloc_control(struct reloc_control * rc)3546 static void set_reloc_control(struct reloc_control *rc)
3547 {
3548 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3549
3550 mutex_lock(&fs_info->reloc_mutex);
3551 spin_lock(&fs_info->reloc_ctl_lock);
3552 fs_info->reloc_ctl = rc;
3553 spin_unlock(&fs_info->reloc_ctl_lock);
3554 mutex_unlock(&fs_info->reloc_mutex);
3555 }
3556
unset_reloc_control(struct reloc_control * rc)3557 static void unset_reloc_control(struct reloc_control *rc)
3558 {
3559 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3560
3561 mutex_lock(&fs_info->reloc_mutex);
3562 spin_lock(&fs_info->reloc_ctl_lock);
3563 fs_info->reloc_ctl = NULL;
3564 spin_unlock(&fs_info->reloc_ctl_lock);
3565 mutex_unlock(&fs_info->reloc_mutex);
3566 }
3567
3568 static noinline_for_stack
prepare_to_relocate(struct reloc_control * rc)3569 int prepare_to_relocate(struct reloc_control *rc)
3570 {
3571 struct btrfs_trans_handle *trans;
3572 int ret;
3573
3574 rc->block_rsv = btrfs_alloc_block_rsv(rc->extent_root->fs_info,
3575 BTRFS_BLOCK_RSV_TEMP);
3576 if (!rc->block_rsv)
3577 return -ENOMEM;
3578
3579 memset(&rc->cluster, 0, sizeof(rc->cluster));
3580 rc->search_start = rc->block_group->start;
3581 rc->extents_found = 0;
3582 rc->nodes_relocated = 0;
3583 rc->merging_rsv_size = 0;
3584 rc->reserved_bytes = 0;
3585 rc->block_rsv->size = rc->extent_root->fs_info->nodesize *
3586 RELOCATION_RESERVED_NODES;
3587 ret = btrfs_block_rsv_refill(rc->extent_root->fs_info,
3588 rc->block_rsv, rc->block_rsv->size,
3589 BTRFS_RESERVE_FLUSH_ALL);
3590 if (ret)
3591 return ret;
3592
3593 rc->create_reloc_tree = true;
3594 set_reloc_control(rc);
3595
3596 trans = btrfs_join_transaction(rc->extent_root);
3597 if (IS_ERR(trans)) {
3598 unset_reloc_control(rc);
3599 /*
3600 * extent tree is not a ref_cow tree and has no reloc_root to
3601 * cleanup. And callers are responsible to free the above
3602 * block rsv.
3603 */
3604 return PTR_ERR(trans);
3605 }
3606
3607 ret = btrfs_commit_transaction(trans);
3608 if (ret)
3609 unset_reloc_control(rc);
3610
3611 return ret;
3612 }
3613
relocate_block_group(struct reloc_control * rc)3614 static noinline_for_stack int relocate_block_group(struct reloc_control *rc)
3615 {
3616 struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
3617 struct rb_root blocks = RB_ROOT;
3618 struct btrfs_key key;
3619 struct btrfs_trans_handle *trans = NULL;
3620 BTRFS_PATH_AUTO_FREE(path);
3621 struct btrfs_extent_item *ei;
3622 u64 flags;
3623 int ret;
3624 int err = 0;
3625 int progress = 0;
3626
3627 path = btrfs_alloc_path();
3628 if (!path)
3629 return -ENOMEM;
3630 path->reada = READA_FORWARD;
3631
3632 ret = prepare_to_relocate(rc);
3633 if (ret) {
3634 err = ret;
3635 goto out_free;
3636 }
3637
3638 while (1) {
3639 rc->reserved_bytes = 0;
3640 ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv,
3641 rc->block_rsv->size,
3642 BTRFS_RESERVE_FLUSH_ALL);
3643 if (ret) {
3644 err = ret;
3645 break;
3646 }
3647 progress++;
3648 trans = btrfs_start_transaction(rc->extent_root, 0);
3649 if (IS_ERR(trans)) {
3650 err = PTR_ERR(trans);
3651 trans = NULL;
3652 break;
3653 }
3654 restart:
3655 if (rc->backref_cache.last_trans != trans->transid)
3656 btrfs_backref_release_cache(&rc->backref_cache);
3657 rc->backref_cache.last_trans = trans->transid;
3658
3659 ret = find_next_extent(rc, path, &key);
3660 if (ret < 0)
3661 err = ret;
3662 if (ret != 0)
3663 break;
3664
3665 rc->extents_found++;
3666
3667 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3668 struct btrfs_extent_item);
3669 flags = btrfs_extent_flags(path->nodes[0], ei);
3670
3671 /*
3672 * If we are relocating a simple quota owned extent item, we
3673 * need to note the owner on the reloc data root so that when
3674 * we allocate the replacement item, we can attribute it to the
3675 * correct eventual owner (rather than the reloc data root).
3676 */
3677 if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE) {
3678 struct btrfs_root *root = BTRFS_I(rc->data_inode)->root;
3679 u64 owning_root_id = btrfs_get_extent_owner_root(fs_info,
3680 path->nodes[0],
3681 path->slots[0]);
3682
3683 root->relocation_src_root = owning_root_id;
3684 }
3685
3686 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
3687 ret = add_tree_block(rc, &key, path, &blocks);
3688 } else if (rc->stage == UPDATE_DATA_PTRS &&
3689 (flags & BTRFS_EXTENT_FLAG_DATA)) {
3690 ret = add_data_references(rc, &key, path, &blocks);
3691 } else {
3692 btrfs_release_path(path);
3693 ret = 0;
3694 }
3695 if (ret < 0) {
3696 err = ret;
3697 break;
3698 }
3699
3700 if (!RB_EMPTY_ROOT(&blocks)) {
3701 ret = relocate_tree_blocks(trans, rc, &blocks);
3702 if (ret < 0) {
3703 if (ret != -EAGAIN) {
3704 err = ret;
3705 break;
3706 }
3707 rc->extents_found--;
3708 rc->search_start = key.objectid;
3709 }
3710 }
3711
3712 btrfs_end_transaction_throttle(trans);
3713 btrfs_btree_balance_dirty(fs_info);
3714 trans = NULL;
3715
3716 if (rc->stage == MOVE_DATA_EXTENTS &&
3717 (flags & BTRFS_EXTENT_FLAG_DATA)) {
3718 rc->found_file_extent = true;
3719 ret = relocate_data_extent(rc, &key);
3720 if (ret < 0) {
3721 err = ret;
3722 break;
3723 }
3724 }
3725 if (btrfs_should_cancel_balance(fs_info)) {
3726 err = -ECANCELED;
3727 break;
3728 }
3729 }
3730 if (trans && progress && err == -ENOSPC) {
3731 ret = btrfs_force_chunk_alloc(trans, rc->block_group->flags);
3732 if (ret == 1) {
3733 err = 0;
3734 progress = 0;
3735 goto restart;
3736 }
3737 }
3738
3739 btrfs_release_path(path);
3740 btrfs_clear_extent_bit(&rc->processed_blocks, 0, (u64)-1, EXTENT_DIRTY, NULL);
3741
3742 if (trans) {
3743 btrfs_end_transaction_throttle(trans);
3744 btrfs_btree_balance_dirty(fs_info);
3745 }
3746
3747 if (!err && !btrfs_fs_incompat(fs_info, REMAP_TREE)) {
3748 ret = relocate_file_extent_cluster(rc);
3749 if (ret < 0)
3750 err = ret;
3751 }
3752
3753 rc->create_reloc_tree = false;
3754 set_reloc_control(rc);
3755
3756 btrfs_backref_release_cache(&rc->backref_cache);
3757 btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
3758
3759 /*
3760 * Even in the case when the relocation is cancelled, we should all go
3761 * through prepare_to_merge() and merge_reloc_roots().
3762 *
3763 * For error (including cancelled balance), prepare_to_merge() will
3764 * mark all reloc trees orphan, then queue them for cleanup in
3765 * merge_reloc_roots()
3766 */
3767 err = prepare_to_merge(rc, err);
3768
3769 ret = merge_reloc_roots(rc);
3770 if (ret && !err)
3771 err = ret;
3772
3773 rc->merge_reloc_tree = false;
3774 unset_reloc_control(rc);
3775 btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
3776
3777 /* get rid of pinned extents */
3778 ret = btrfs_commit_current_transaction(rc->extent_root);
3779 if (ret && !err)
3780 err = ret;
3781 out_free:
3782 ret = clean_dirty_subvols(rc);
3783 if (ret < 0 && !err)
3784 err = ret;
3785 btrfs_free_block_rsv(fs_info, rc->block_rsv);
3786 return err;
3787 }
3788
__insert_orphan_inode(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 objectid)3789 static int __insert_orphan_inode(struct btrfs_trans_handle *trans,
3790 struct btrfs_root *root, u64 objectid)
3791 {
3792 BTRFS_PATH_AUTO_FREE(path);
3793 struct btrfs_inode_item *item;
3794 struct extent_buffer *leaf;
3795 int ret;
3796
3797 path = btrfs_alloc_path();
3798 if (!path)
3799 return -ENOMEM;
3800
3801 ret = btrfs_insert_empty_inode(trans, root, path, objectid);
3802 if (ret)
3803 return ret;
3804
3805 leaf = path->nodes[0];
3806 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item);
3807 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3808 btrfs_set_inode_generation(leaf, item, 1);
3809 btrfs_set_inode_size(leaf, item, 0);
3810 btrfs_set_inode_mode(leaf, item, S_IFREG | 0600);
3811 btrfs_set_inode_flags(leaf, item, BTRFS_INODE_NOCOMPRESS |
3812 BTRFS_INODE_PREALLOC);
3813 return 0;
3814 }
3815
delete_orphan_inode(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 objectid)3816 static void delete_orphan_inode(struct btrfs_trans_handle *trans,
3817 struct btrfs_root *root, u64 objectid)
3818 {
3819 BTRFS_PATH_AUTO_FREE(path);
3820 struct btrfs_key key;
3821 int ret = 0;
3822
3823 path = btrfs_alloc_path();
3824 if (!path) {
3825 ret = -ENOMEM;
3826 goto out;
3827 }
3828
3829 key.objectid = objectid;
3830 key.type = BTRFS_INODE_ITEM_KEY;
3831 key.offset = 0;
3832 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3833 if (ret) {
3834 if (ret > 0)
3835 ret = -ENOENT;
3836 goto out;
3837 }
3838 ret = btrfs_del_item(trans, root, path);
3839 out:
3840 if (ret)
3841 btrfs_abort_transaction(trans, ret);
3842 }
3843
3844 /*
3845 * helper to create inode for data relocation.
3846 * the inode is in data relocation tree and its link count is 0
3847 */
create_reloc_inode(const struct btrfs_block_group * group)3848 static noinline_for_stack struct inode *create_reloc_inode(
3849 const struct btrfs_block_group *group)
3850 {
3851 struct btrfs_fs_info *fs_info = group->fs_info;
3852 struct btrfs_inode *inode = NULL;
3853 struct btrfs_trans_handle *trans;
3854 struct btrfs_root *root;
3855 u64 objectid;
3856 int ret = 0;
3857
3858 root = btrfs_grab_root(fs_info->data_reloc_root);
3859 trans = btrfs_start_transaction(root, 6);
3860 if (IS_ERR(trans)) {
3861 btrfs_put_root(root);
3862 return ERR_CAST(trans);
3863 }
3864
3865 ret = btrfs_get_free_objectid(root, &objectid);
3866 if (ret)
3867 goto out;
3868
3869 ret = __insert_orphan_inode(trans, root, objectid);
3870 if (ret)
3871 goto out;
3872
3873 inode = btrfs_iget(objectid, root);
3874 if (IS_ERR(inode)) {
3875 delete_orphan_inode(trans, root, objectid);
3876 ret = PTR_ERR(inode);
3877 inode = NULL;
3878 goto out;
3879 }
3880 inode->reloc_block_group_start = group->start;
3881
3882 ret = btrfs_orphan_add(trans, inode);
3883 out:
3884 btrfs_put_root(root);
3885 btrfs_end_transaction(trans);
3886 btrfs_btree_balance_dirty(fs_info);
3887 if (ret) {
3888 if (inode)
3889 iput(&inode->vfs_inode);
3890 return ERR_PTR(ret);
3891 }
3892 return &inode->vfs_inode;
3893 }
3894
3895 /*
3896 * Mark start of chunk relocation that is cancellable. Check if the cancellation
3897 * has been requested meanwhile and don't start in that case.
3898 * NOTE: if this returns an error, reloc_chunk_end() must not be called.
3899 *
3900 * Return:
3901 * 0 success
3902 * -EINPROGRESS operation is already in progress, that's probably a bug
3903 * -ECANCELED cancellation request was set before the operation started
3904 */
reloc_chunk_start(struct btrfs_fs_info * fs_info)3905 static int reloc_chunk_start(struct btrfs_fs_info *fs_info)
3906 {
3907 if (test_and_set_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags)) {
3908 /* This should not happen */
3909 btrfs_err(fs_info, "reloc already running, cannot start");
3910 return -EINPROGRESS;
3911 }
3912
3913 if (atomic_read(&fs_info->reloc_cancel_req) > 0) {
3914 btrfs_info(fs_info, "chunk relocation canceled on start");
3915 /* On cancel, clear all requests. */
3916 clear_and_wake_up_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags);
3917 atomic_set(&fs_info->reloc_cancel_req, 0);
3918 return -ECANCELED;
3919 }
3920 return 0;
3921 }
3922
3923 /*
3924 * Mark end of chunk relocation that is cancellable and wake any waiters.
3925 * NOTE: call only if a previous call to reloc_chunk_start() succeeded.
3926 */
reloc_chunk_end(struct btrfs_fs_info * fs_info)3927 static void reloc_chunk_end(struct btrfs_fs_info *fs_info)
3928 {
3929 ASSERT(test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags));
3930 /* Requested after start, clear bit first so any waiters can continue */
3931 if (atomic_read(&fs_info->reloc_cancel_req) > 0)
3932 btrfs_info(fs_info, "chunk relocation canceled during operation");
3933 clear_and_wake_up_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags);
3934 atomic_set(&fs_info->reloc_cancel_req, 0);
3935 }
3936
alloc_reloc_control(struct btrfs_fs_info * fs_info)3937 static struct reloc_control *alloc_reloc_control(struct btrfs_fs_info *fs_info)
3938 {
3939 struct reloc_control *rc;
3940
3941 rc = kzalloc_obj(*rc, GFP_NOFS);
3942 if (!rc)
3943 return NULL;
3944
3945 INIT_LIST_HEAD(&rc->reloc_roots);
3946 INIT_LIST_HEAD(&rc->dirty_subvol_roots);
3947 btrfs_backref_init_cache(fs_info, &rc->backref_cache, true);
3948 rc->reloc_root_tree.rb_root = RB_ROOT;
3949 spin_lock_init(&rc->reloc_root_tree.lock);
3950 btrfs_extent_io_tree_init(fs_info, &rc->processed_blocks, IO_TREE_RELOC_BLOCKS);
3951 refcount_set(&rc->refs, 1);
3952
3953 return rc;
3954 }
3955
3956 /*
3957 * Print the block group being relocated
3958 */
describe_relocation(struct btrfs_block_group * block_group)3959 static void describe_relocation(struct btrfs_block_group *block_group)
3960 {
3961 char buf[128] = "NONE";
3962
3963 btrfs_describe_block_groups(block_group->flags, buf, sizeof(buf));
3964
3965 btrfs_info(block_group->fs_info, "relocating block group %llu flags %s",
3966 block_group->start, buf);
3967 }
3968
stage_to_string(enum reloc_stage stage)3969 static const char *stage_to_string(enum reloc_stage stage)
3970 {
3971 if (stage == MOVE_DATA_EXTENTS)
3972 return "move data extents";
3973 if (stage == UPDATE_DATA_PTRS)
3974 return "update data pointers";
3975 return "unknown";
3976 }
3977
add_remap_tree_entries(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_key * entries,unsigned int num_entries)3978 static int add_remap_tree_entries(struct btrfs_trans_handle *trans, struct btrfs_path *path,
3979 struct btrfs_key *entries, unsigned int num_entries)
3980 {
3981 int ret;
3982 struct btrfs_fs_info *fs_info = trans->fs_info;
3983 struct btrfs_item_batch batch;
3984 u32 *data_sizes;
3985 u32 max_items;
3986
3987 max_items = BTRFS_LEAF_DATA_SIZE(trans->fs_info) / sizeof(struct btrfs_item);
3988
3989 data_sizes = kzalloc_objs(u32, min_t(u32, num_entries, max_items), GFP_NOFS);
3990 if (!data_sizes)
3991 return -ENOMEM;
3992
3993 while (true) {
3994 batch.keys = entries;
3995 batch.data_sizes = data_sizes;
3996 batch.total_data_size = 0;
3997 batch.nr = min_t(u32, num_entries, max_items);
3998
3999 ret = btrfs_insert_empty_items(trans, fs_info->remap_root, path, &batch);
4000 btrfs_release_path(path);
4001
4002 if (ret || num_entries <= max_items)
4003 break;
4004
4005 num_entries -= max_items;
4006 entries += max_items;
4007 }
4008
4009 kfree(data_sizes);
4010
4011 return ret;
4012 }
4013
4014 struct space_run {
4015 u64 start;
4016 u64 end;
4017 };
4018
parse_bitmap(u64 block_size,const unsigned long * bitmap,unsigned long size,u64 address,struct space_run * space_runs,unsigned int * num_space_runs)4019 static void parse_bitmap(u64 block_size, const unsigned long *bitmap,
4020 unsigned long size, u64 address, struct space_run *space_runs,
4021 unsigned int *num_space_runs)
4022 {
4023 unsigned long pos, end;
4024 u64 run_start, run_length;
4025
4026 pos = find_first_bit(bitmap, size);
4027 if (pos == size)
4028 return;
4029
4030 while (true) {
4031 end = find_next_zero_bit(bitmap, size, pos);
4032
4033 run_start = address + (pos * block_size);
4034 run_length = (end - pos) * block_size;
4035
4036 if (*num_space_runs != 0 &&
4037 space_runs[*num_space_runs - 1].end == run_start) {
4038 space_runs[*num_space_runs - 1].end += run_length;
4039 } else {
4040 space_runs[*num_space_runs].start = run_start;
4041 space_runs[*num_space_runs].end = run_start + run_length;
4042
4043 (*num_space_runs)++;
4044 }
4045
4046 if (end == size)
4047 break;
4048
4049 pos = find_next_bit(bitmap, size, end + 1);
4050 if (pos == size)
4051 break;
4052 }
4053 }
4054
adjust_block_group_remap_bytes(struct btrfs_trans_handle * trans,struct btrfs_block_group * bg,s64 diff)4055 static void adjust_block_group_remap_bytes(struct btrfs_trans_handle *trans,
4056 struct btrfs_block_group *bg, s64 diff)
4057 {
4058 struct btrfs_fs_info *fs_info = trans->fs_info;
4059 bool bg_already_dirty = true;
4060 bool mark_unused = false;
4061
4062 spin_lock(&bg->lock);
4063 bg->remap_bytes += diff;
4064 if (bg->used == 0 && bg->remap_bytes == 0)
4065 mark_unused = true;
4066 spin_unlock(&bg->lock);
4067
4068 if (mark_unused)
4069 btrfs_mark_bg_unused(bg);
4070
4071 spin_lock(&trans->transaction->dirty_bgs_lock);
4072 if (list_empty(&bg->dirty_list)) {
4073 list_add_tail(&bg->dirty_list, &trans->transaction->dirty_bgs);
4074 bg_already_dirty = false;
4075 btrfs_get_block_group(bg);
4076 }
4077 spin_unlock(&trans->transaction->dirty_bgs_lock);
4078
4079 /* Modified block groups are accounted for in the delayed_refs_rsv. */
4080 if (!bg_already_dirty)
4081 btrfs_inc_delayed_refs_rsv_bg_updates(fs_info);
4082 }
4083
4084 /* Private structure for I/O from copy_remapped_data(). */
4085 struct reloc_io_private {
4086 struct completion done;
4087 refcount_t pending_refs;
4088 blk_status_t status;
4089 };
4090
reloc_endio(struct btrfs_bio * bbio)4091 static void reloc_endio(struct btrfs_bio *bbio)
4092 {
4093 struct reloc_io_private *priv = bbio->private;
4094
4095 if (bbio->bio.bi_status)
4096 WRITE_ONCE(priv->status, bbio->bio.bi_status);
4097
4098 if (refcount_dec_and_test(&priv->pending_refs))
4099 complete(&priv->done);
4100
4101 bio_put(&bbio->bio);
4102 }
4103
copy_remapped_data_io(struct btrfs_fs_info * fs_info,struct reloc_io_private * priv,struct page ** pages,u64 addr,u64 length,blk_opf_t op)4104 static int copy_remapped_data_io(struct btrfs_fs_info *fs_info,
4105 struct reloc_io_private *priv,
4106 struct page **pages, u64 addr, u64 length,
4107 blk_opf_t op)
4108 {
4109 struct btrfs_bio *bbio;
4110 int i;
4111
4112 init_completion(&priv->done);
4113 refcount_set(&priv->pending_refs, 1);
4114 priv->status = 0;
4115
4116 bbio = btrfs_bio_alloc(BIO_MAX_VECS, op, BTRFS_I(fs_info->btree_inode),
4117 addr, reloc_endio, priv);
4118 bbio->bio.bi_iter.bi_sector = (addr >> SECTOR_SHIFT);
4119 bbio->is_remap = true;
4120
4121 i = 0;
4122 do {
4123 size_t bytes = min_t(u64, length, PAGE_SIZE);
4124
4125 if (bio_add_page(&bbio->bio, pages[i], bytes, 0) < bytes) {
4126 refcount_inc(&priv->pending_refs);
4127 btrfs_submit_bbio(bbio, 0);
4128
4129 bbio = btrfs_bio_alloc(BIO_MAX_VECS, op,
4130 BTRFS_I(fs_info->btree_inode),
4131 addr, reloc_endio, priv);
4132 bbio->bio.bi_iter.bi_sector = (addr >> SECTOR_SHIFT);
4133 bbio->is_remap = true;
4134 continue;
4135 }
4136
4137 i++;
4138 addr += bytes;
4139 length -= bytes;
4140 } while (length);
4141
4142 refcount_inc(&priv->pending_refs);
4143 btrfs_submit_bbio(bbio, 0);
4144
4145 if (!refcount_dec_and_test(&priv->pending_refs))
4146 wait_for_completion_io(&priv->done);
4147
4148 return blk_status_to_errno(READ_ONCE(priv->status));
4149 }
4150
copy_remapped_data(struct btrfs_fs_info * fs_info,u64 old_addr,u64 new_addr,u64 length)4151 static int copy_remapped_data(struct btrfs_fs_info *fs_info, u64 old_addr,
4152 u64 new_addr, u64 length)
4153 {
4154 int ret;
4155 const u64 copy_len = min_t(u64, length, SZ_1M);
4156 struct page **pages;
4157 struct reloc_io_private priv;
4158 const unsigned int nr_pages = DIV_ROUND_UP(copy_len, PAGE_SIZE);
4159
4160 pages = kzalloc_objs(struct page *, nr_pages, GFP_NOFS);
4161 if (!pages)
4162 return -ENOMEM;
4163
4164 ret = btrfs_alloc_page_array(nr_pages, pages, GFP_NOFS);
4165 if (ret) {
4166 ret = -ENOMEM;
4167 goto end;
4168 }
4169
4170 /* Copy 1MB at a time, to avoid using too much memory. */
4171 do {
4172 u64 to_copy = min_t(u64, length, copy_len);
4173
4174 /* Limit to one bio. */
4175 to_copy = min_t(u64, to_copy, BIO_MAX_VECS << PAGE_SHIFT);
4176
4177 ret = copy_remapped_data_io(fs_info, &priv, pages, old_addr,
4178 to_copy, REQ_OP_READ);
4179 if (ret)
4180 goto end;
4181
4182 ret = copy_remapped_data_io(fs_info, &priv, pages, new_addr,
4183 to_copy, REQ_OP_WRITE);
4184 if (ret)
4185 goto end;
4186
4187 if (to_copy == length)
4188 break;
4189
4190 old_addr += to_copy;
4191 new_addr += to_copy;
4192 length -= to_copy;
4193 } while (true);
4194
4195 ret = 0;
4196 end:
4197 for (int i = 0; i < nr_pages; i++) {
4198 if (pages[i])
4199 __free_page(pages[i]);
4200 }
4201 kfree(pages);
4202
4203 return ret;
4204 }
4205
add_remap_item(struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 new_addr,u64 length,u64 old_addr)4206 static int add_remap_item(struct btrfs_trans_handle *trans,
4207 struct btrfs_path *path, u64 new_addr, u64 length,
4208 u64 old_addr)
4209 {
4210 struct btrfs_fs_info *fs_info = trans->fs_info;
4211 struct btrfs_remap_item remap = { 0 };
4212 struct btrfs_key key;
4213 struct extent_buffer *leaf;
4214 int ret;
4215
4216 key.objectid = old_addr;
4217 key.type = BTRFS_REMAP_KEY;
4218 key.offset = length;
4219
4220 ret = btrfs_insert_empty_item(trans, fs_info->remap_root, path,
4221 &key, sizeof(struct btrfs_remap_item));
4222 if (ret)
4223 return ret;
4224
4225 leaf = path->nodes[0];
4226 btrfs_set_stack_remap_address(&remap, new_addr);
4227 write_extent_buffer(leaf, &remap, btrfs_item_ptr_offset(leaf, path->slots[0]),
4228 sizeof(struct btrfs_remap_item));
4229
4230 btrfs_release_path(path);
4231
4232 return 0;
4233 }
4234
add_remap_backref_item(struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 new_addr,u64 length,u64 old_addr)4235 static int add_remap_backref_item(struct btrfs_trans_handle *trans,
4236 struct btrfs_path *path, u64 new_addr,
4237 u64 length, u64 old_addr)
4238 {
4239 struct btrfs_fs_info *fs_info = trans->fs_info;
4240 struct btrfs_remap_item remap = { 0 };
4241 struct btrfs_key key;
4242 struct extent_buffer *leaf;
4243 int ret;
4244
4245 key.objectid = new_addr;
4246 key.type = BTRFS_REMAP_BACKREF_KEY;
4247 key.offset = length;
4248
4249 ret = btrfs_insert_empty_item(trans, fs_info->remap_root, path, &key,
4250 sizeof(struct btrfs_remap_item));
4251 if (ret)
4252 return ret;
4253
4254 leaf = path->nodes[0];
4255 btrfs_set_stack_remap_address(&remap, old_addr);
4256 write_extent_buffer(leaf, &remap, btrfs_item_ptr_offset(leaf, path->slots[0]),
4257 sizeof(struct btrfs_remap_item));
4258
4259 btrfs_release_path(path);
4260
4261 return 0;
4262 }
4263
move_existing_remap(struct btrfs_fs_info * fs_info,struct btrfs_path * path,struct btrfs_block_group * bg,u64 new_addr,u64 length,u64 old_addr)4264 static int move_existing_remap(struct btrfs_fs_info *fs_info,
4265 struct btrfs_path *path,
4266 struct btrfs_block_group *bg, u64 new_addr,
4267 u64 length, u64 old_addr)
4268 {
4269 struct btrfs_trans_handle *trans;
4270 struct extent_buffer *leaf;
4271 struct btrfs_remap_item *remap_ptr;
4272 struct btrfs_remap_item remap = { 0 };
4273 struct btrfs_key key, ins;
4274 u64 dest_addr, dest_length, min_size;
4275 struct btrfs_block_group *dest_bg;
4276 int ret;
4277 const bool is_data = (bg->flags & BTRFS_BLOCK_GROUP_DATA);
4278 struct btrfs_space_info *sinfo = bg->space_info;
4279 bool mutex_taken = false;
4280 bool bg_needs_free_space;
4281
4282 spin_lock(&sinfo->lock);
4283 btrfs_space_info_update_bytes_may_use(sinfo, length);
4284 spin_unlock(&sinfo->lock);
4285
4286 if (is_data)
4287 min_size = fs_info->sectorsize;
4288 else
4289 min_size = fs_info->nodesize;
4290
4291 ret = btrfs_reserve_extent(fs_info->fs_root, length, length, min_size,
4292 0, 0, &ins, is_data, false);
4293 if (unlikely(ret)) {
4294 spin_lock(&sinfo->lock);
4295 btrfs_space_info_update_bytes_may_use(sinfo, -length);
4296 spin_unlock(&sinfo->lock);
4297 return ret;
4298 }
4299
4300 if (ins.offset < length) {
4301 spin_lock(&sinfo->lock);
4302 btrfs_space_info_update_bytes_may_use(sinfo, ins.offset - length);
4303 spin_unlock(&sinfo->lock);
4304 }
4305
4306 dest_addr = ins.objectid;
4307 dest_length = ins.offset;
4308
4309 dest_bg = btrfs_lookup_block_group(fs_info, dest_addr);
4310
4311 if (!is_data && !IS_ALIGNED(dest_length, fs_info->nodesize)) {
4312 u64 new_length = ALIGN_DOWN(dest_length, fs_info->nodesize);
4313
4314 btrfs_free_reserved_extent(fs_info, dest_addr + new_length,
4315 dest_length - new_length, 0);
4316
4317 dest_length = new_length;
4318 }
4319
4320 trans = btrfs_join_transaction(fs_info->remap_root);
4321 if (IS_ERR(trans)) {
4322 ret = PTR_ERR(trans);
4323 trans = NULL;
4324 goto end;
4325 }
4326
4327 mutex_lock(&fs_info->remap_mutex);
4328 mutex_taken = true;
4329
4330 /* Find old remap entry. */
4331 key.objectid = old_addr;
4332 key.type = BTRFS_REMAP_KEY;
4333 key.offset = length;
4334
4335 ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, 0, 1);
4336 if (ret == 1) {
4337 /*
4338 * Not a problem if the remap entry wasn't found: that means
4339 * that another transaction has deallocated the data.
4340 * move_existing_remaps() loops until the BG contains no
4341 * remaps, so we can just return 0 in this case.
4342 */
4343 btrfs_release_path(path);
4344 ret = 0;
4345 goto end;
4346 } else if (unlikely(ret)) {
4347 goto end;
4348 }
4349
4350 ret = copy_remapped_data(fs_info, new_addr, dest_addr, dest_length);
4351 if (unlikely(ret))
4352 goto end;
4353
4354 /* Change data of old remap entry. */
4355 leaf = path->nodes[0];
4356 remap_ptr = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_remap_item);
4357 btrfs_set_remap_address(leaf, remap_ptr, dest_addr);
4358 btrfs_mark_buffer_dirty(trans, leaf);
4359
4360 if (dest_length != length) {
4361 key.offset = dest_length;
4362 btrfs_set_item_key_safe(trans, path, &key);
4363 }
4364
4365 btrfs_release_path(path);
4366
4367 if (dest_length != length) {
4368 /* Add remap item for remainder. */
4369 ret = add_remap_item(trans, path, new_addr + dest_length,
4370 length - dest_length, old_addr + dest_length);
4371 if (unlikely(ret))
4372 goto end;
4373 }
4374
4375 /* Change or remove old backref. */
4376 key.objectid = new_addr;
4377 key.type = BTRFS_REMAP_BACKREF_KEY;
4378 key.offset = length;
4379
4380 ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, -1, 1);
4381 if (unlikely(ret)) {
4382 if (ret == 1) {
4383 btrfs_release_path(path);
4384 ret = -ENOENT;
4385 }
4386 goto end;
4387 }
4388
4389 leaf = path->nodes[0];
4390
4391 if (dest_length == length) {
4392 ret = btrfs_del_item(trans, fs_info->remap_root, path);
4393 if (unlikely(ret)) {
4394 btrfs_release_path(path);
4395 goto end;
4396 }
4397 } else {
4398 key.objectid += dest_length;
4399 key.offset -= dest_length;
4400 btrfs_set_item_key_safe(trans, path, &key);
4401 btrfs_set_stack_remap_address(&remap, old_addr + dest_length);
4402
4403 write_extent_buffer(leaf, &remap,
4404 btrfs_item_ptr_offset(leaf, path->slots[0]),
4405 sizeof(struct btrfs_remap_item));
4406 }
4407
4408 btrfs_release_path(path);
4409
4410 /* Add new backref. */
4411 ret = add_remap_backref_item(trans, path, dest_addr, dest_length, old_addr);
4412 if (unlikely(ret))
4413 goto end;
4414
4415 adjust_block_group_remap_bytes(trans, bg, -dest_length);
4416
4417 ret = btrfs_add_to_free_space_tree(trans, new_addr, dest_length);
4418 if (unlikely(ret))
4419 goto end;
4420
4421 adjust_block_group_remap_bytes(trans, dest_bg, dest_length);
4422
4423 mutex_lock(&dest_bg->free_space_lock);
4424 bg_needs_free_space = test_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE,
4425 &dest_bg->runtime_flags);
4426 mutex_unlock(&dest_bg->free_space_lock);
4427
4428 if (bg_needs_free_space) {
4429 ret = btrfs_add_block_group_free_space(trans, dest_bg);
4430 if (unlikely(ret))
4431 goto end;
4432 }
4433
4434 ret = btrfs_remove_from_free_space_tree(trans, dest_addr, dest_length);
4435 if (unlikely(ret)) {
4436 btrfs_remove_from_free_space_tree(trans, new_addr, dest_length);
4437 goto end;
4438 }
4439
4440 ret = 0;
4441
4442 end:
4443 if (mutex_taken)
4444 mutex_unlock(&fs_info->remap_mutex);
4445
4446 btrfs_dec_block_group_reservations(fs_info, dest_addr);
4447
4448 if (unlikely(ret)) {
4449 btrfs_free_reserved_extent(fs_info, dest_addr, dest_length, 0);
4450
4451 if (trans) {
4452 btrfs_abort_transaction(trans, ret);
4453 btrfs_end_transaction(trans);
4454 }
4455 } else {
4456 btrfs_free_reserved_bytes(dest_bg, dest_length, 0);
4457
4458 ret = btrfs_commit_transaction(trans);
4459 }
4460
4461 btrfs_put_block_group(dest_bg);
4462
4463 return ret;
4464 }
4465
move_existing_remaps(struct btrfs_fs_info * fs_info,struct btrfs_block_group * bg,struct btrfs_path * path)4466 static int move_existing_remaps(struct btrfs_fs_info *fs_info,
4467 struct btrfs_block_group *bg,
4468 struct btrfs_path *path)
4469 {
4470 int ret;
4471 struct btrfs_key key;
4472 struct extent_buffer *leaf;
4473 struct btrfs_remap_item *remap;
4474 u64 old_addr;
4475
4476 /* Look for backrefs in remap tree. */
4477 while (bg->remap_bytes > 0) {
4478 key.objectid = bg->start;
4479 key.type = BTRFS_REMAP_BACKREF_KEY;
4480 key.offset = 0;
4481
4482 ret = btrfs_search_slot(NULL, fs_info->remap_root, &key, path, 0, 0);
4483 if (ret < 0)
4484 return ret;
4485
4486 leaf = path->nodes[0];
4487
4488 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4489 ret = btrfs_next_leaf(fs_info->remap_root, path);
4490 if (ret < 0) {
4491 btrfs_release_path(path);
4492 return ret;
4493 }
4494
4495 if (ret) {
4496 btrfs_release_path(path);
4497 break;
4498 }
4499
4500 leaf = path->nodes[0];
4501 }
4502
4503 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4504
4505 if (key.type != BTRFS_REMAP_BACKREF_KEY) {
4506 path->slots[0]++;
4507
4508 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4509 ret = btrfs_next_leaf(fs_info->remap_root, path);
4510 if (ret < 0) {
4511 btrfs_release_path(path);
4512 return ret;
4513 }
4514
4515 if (ret) {
4516 btrfs_release_path(path);
4517 break;
4518 }
4519
4520 leaf = path->nodes[0];
4521 }
4522
4523 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4524 }
4525
4526 remap = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_remap_item);
4527 old_addr = btrfs_remap_address(leaf, remap);
4528
4529 btrfs_release_path(path);
4530
4531 ret = move_existing_remap(fs_info, path, bg, key.objectid,
4532 key.offset, old_addr);
4533 if (ret)
4534 return ret;
4535 }
4536
4537 ASSERT(bg->remap_bytes == 0);
4538
4539 return 0;
4540 }
4541
create_remap_tree_entries(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_block_group * bg)4542 static int create_remap_tree_entries(struct btrfs_trans_handle *trans,
4543 struct btrfs_path *path,
4544 struct btrfs_block_group *bg)
4545 {
4546 struct btrfs_fs_info *fs_info = trans->fs_info;
4547 struct btrfs_free_space_info *fsi;
4548 struct btrfs_key key, found_key;
4549 struct extent_buffer *leaf;
4550 struct btrfs_root *space_root;
4551 u32 extent_count;
4552 struct space_run *space_runs = NULL;
4553 unsigned int num_space_runs = 0;
4554 struct btrfs_key *entries = NULL;
4555 unsigned int max_entries, num_entries;
4556 int ret;
4557
4558 mutex_lock(&bg->free_space_lock);
4559
4560 if (test_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE, &bg->runtime_flags)) {
4561 mutex_unlock(&bg->free_space_lock);
4562
4563 ret = btrfs_add_block_group_free_space(trans, bg);
4564 if (ret)
4565 return ret;
4566
4567 mutex_lock(&bg->free_space_lock);
4568 }
4569
4570 fsi = btrfs_search_free_space_info(trans, bg, path, 0);
4571 if (IS_ERR(fsi)) {
4572 mutex_unlock(&bg->free_space_lock);
4573 return PTR_ERR(fsi);
4574 }
4575
4576 extent_count = btrfs_free_space_extent_count(path->nodes[0], fsi);
4577
4578 btrfs_release_path(path);
4579
4580 space_runs = kmalloc_objs(*space_runs, extent_count, GFP_NOFS);
4581 if (!space_runs) {
4582 mutex_unlock(&bg->free_space_lock);
4583 return -ENOMEM;
4584 }
4585
4586 key.objectid = bg->start;
4587 key.type = 0;
4588 key.offset = 0;
4589
4590 space_root = btrfs_free_space_root(bg);
4591
4592 ret = btrfs_search_slot(trans, space_root, &key, path, 0, 0);
4593 if (ret < 0) {
4594 mutex_unlock(&bg->free_space_lock);
4595 goto out;
4596 }
4597
4598 ret = 0;
4599
4600 while (true) {
4601 leaf = path->nodes[0];
4602
4603 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4604
4605 if (found_key.objectid >= bg->start + bg->length)
4606 break;
4607
4608 if (found_key.type == BTRFS_FREE_SPACE_EXTENT_KEY) {
4609 if (num_space_runs != 0 &&
4610 space_runs[num_space_runs - 1].end == found_key.objectid) {
4611 space_runs[num_space_runs - 1].end =
4612 found_key.objectid + found_key.offset;
4613 } else {
4614 ASSERT(num_space_runs < extent_count);
4615
4616 space_runs[num_space_runs].start = found_key.objectid;
4617 space_runs[num_space_runs].end =
4618 found_key.objectid + found_key.offset;
4619
4620 num_space_runs++;
4621 }
4622 } else if (found_key.type == BTRFS_FREE_SPACE_BITMAP_KEY) {
4623 void *bitmap;
4624 unsigned long offset;
4625 u32 data_size;
4626
4627 offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
4628 data_size = btrfs_item_size(leaf, path->slots[0]);
4629
4630 if (data_size != 0) {
4631 bitmap = kmalloc(data_size, GFP_NOFS);
4632 if (!bitmap) {
4633 mutex_unlock(&bg->free_space_lock);
4634 ret = -ENOMEM;
4635 goto out;
4636 }
4637
4638 read_extent_buffer(leaf, bitmap, offset, data_size);
4639
4640 parse_bitmap(fs_info->sectorsize, bitmap,
4641 data_size * BITS_PER_BYTE,
4642 found_key.objectid, space_runs,
4643 &num_space_runs);
4644
4645 ASSERT(num_space_runs <= extent_count);
4646
4647 kfree(bitmap);
4648 }
4649 }
4650
4651 path->slots[0]++;
4652
4653 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4654 ret = btrfs_next_leaf(space_root, path);
4655 if (ret != 0) {
4656 if (ret == 1)
4657 ret = 0;
4658 break;
4659 }
4660 leaf = path->nodes[0];
4661 }
4662 }
4663
4664 btrfs_release_path(path);
4665
4666 mutex_unlock(&bg->free_space_lock);
4667
4668 max_entries = extent_count + 2;
4669 entries = kmalloc_objs(*entries, max_entries, GFP_NOFS);
4670 if (!entries) {
4671 ret = -ENOMEM;
4672 goto out;
4673 }
4674
4675 num_entries = 0;
4676
4677 if (num_space_runs == 0) {
4678 entries[num_entries].objectid = bg->start;
4679 entries[num_entries].type = BTRFS_IDENTITY_REMAP_KEY;
4680 entries[num_entries].offset = bg->length;
4681 num_entries++;
4682 } else {
4683 if (space_runs[0].start > bg->start) {
4684 entries[num_entries].objectid = bg->start;
4685 entries[num_entries].type = BTRFS_IDENTITY_REMAP_KEY;
4686 entries[num_entries].offset = space_runs[0].start - bg->start;
4687 num_entries++;
4688 }
4689
4690 for (unsigned int i = 1; i < num_space_runs; i++) {
4691 entries[num_entries].objectid = space_runs[i - 1].end;
4692 entries[num_entries].type = BTRFS_IDENTITY_REMAP_KEY;
4693 entries[num_entries].offset =
4694 space_runs[i].start - space_runs[i - 1].end;
4695 num_entries++;
4696 }
4697
4698 if (space_runs[num_space_runs - 1].end < bg->start + bg->length) {
4699 entries[num_entries].objectid =
4700 space_runs[num_space_runs - 1].end;
4701 entries[num_entries].type = BTRFS_IDENTITY_REMAP_KEY;
4702 entries[num_entries].offset =
4703 bg->start + bg->length - space_runs[num_space_runs - 1].end;
4704 num_entries++;
4705 }
4706
4707 if (num_entries == 0)
4708 goto out;
4709 }
4710
4711 bg->identity_remap_count = num_entries;
4712
4713 ret = add_remap_tree_entries(trans, path, entries, num_entries);
4714
4715 out:
4716 kfree(entries);
4717 kfree(space_runs);
4718
4719 return ret;
4720 }
4721
find_next_identity_remap(struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 bg_end,u64 last_start,u64 * start,u64 * length)4722 static int find_next_identity_remap(struct btrfs_trans_handle *trans,
4723 struct btrfs_path *path, u64 bg_end,
4724 u64 last_start, u64 *start, u64 *length)
4725 {
4726 int ret;
4727 struct btrfs_key key, found_key;
4728 struct btrfs_root *remap_root = trans->fs_info->remap_root;
4729 struct extent_buffer *leaf;
4730
4731 key.objectid = last_start;
4732 key.type = BTRFS_IDENTITY_REMAP_KEY;
4733 key.offset = 0;
4734
4735 ret = btrfs_search_slot(trans, remap_root, &key, path, 0, 0);
4736 if (ret < 0)
4737 goto out;
4738
4739 leaf = path->nodes[0];
4740 while (true) {
4741 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4742 ret = btrfs_next_leaf(remap_root, path);
4743
4744 if (ret != 0) {
4745 if (ret == 1)
4746 ret = -ENOENT;
4747 goto out;
4748 }
4749
4750 leaf = path->nodes[0];
4751 }
4752
4753 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4754
4755 if (found_key.objectid >= bg_end) {
4756 ret = -ENOENT;
4757 goto out;
4758 }
4759
4760 if (found_key.type == BTRFS_IDENTITY_REMAP_KEY) {
4761 *start = found_key.objectid;
4762 *length = found_key.offset;
4763 ret = 0;
4764 goto out;
4765 }
4766
4767 path->slots[0]++;
4768 }
4769
4770 out:
4771 btrfs_release_path(path);
4772
4773 return ret;
4774 }
4775
remove_chunk_stripes(struct btrfs_trans_handle * trans,struct btrfs_chunk_map * chunk_map,struct btrfs_path * path)4776 static int remove_chunk_stripes(struct btrfs_trans_handle *trans,
4777 struct btrfs_chunk_map *chunk_map,
4778 struct btrfs_path *path)
4779 {
4780 struct btrfs_fs_info *fs_info = trans->fs_info;
4781 struct btrfs_key key;
4782 struct extent_buffer *leaf;
4783 struct btrfs_chunk *chunk;
4784 int ret;
4785
4786 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4787 key.type = BTRFS_CHUNK_ITEM_KEY;
4788 key.offset = chunk_map->start;
4789
4790 btrfs_reserve_chunk_metadata(trans, false);
4791
4792 ret = btrfs_search_slot(trans, fs_info->chunk_root, &key, path, 0, 1);
4793 if (ret) {
4794 if (ret == 1) {
4795 btrfs_release_path(path);
4796 ret = -ENOENT;
4797 }
4798 btrfs_trans_release_chunk_metadata(trans);
4799 return ret;
4800 }
4801
4802 leaf = path->nodes[0];
4803
4804 chunk = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_chunk);
4805 btrfs_set_chunk_num_stripes(leaf, chunk, 0);
4806 btrfs_set_chunk_sub_stripes(leaf, chunk, 0);
4807
4808 btrfs_truncate_item(trans, path, offsetof(struct btrfs_chunk, stripe), 1);
4809
4810 btrfs_mark_buffer_dirty(trans, leaf);
4811
4812 btrfs_release_path(path);
4813 btrfs_trans_release_chunk_metadata(trans);
4814
4815 return 0;
4816 }
4817
btrfs_last_identity_remap_gone(struct btrfs_chunk_map * chunk_map,struct btrfs_block_group * bg)4818 int btrfs_last_identity_remap_gone(struct btrfs_chunk_map *chunk_map,
4819 struct btrfs_block_group *bg)
4820 {
4821 struct btrfs_fs_info *fs_info = bg->fs_info;
4822 struct btrfs_trans_handle *trans;
4823 int ret;
4824 unsigned int num_items;
4825 BTRFS_PATH_AUTO_FREE(path);
4826
4827 path = btrfs_alloc_path();
4828 if (!path)
4829 return -ENOMEM;
4830
4831 /*
4832 * One item for each entry we're removing in the dev extents tree, and
4833 * another for each device. DUP chunks are all on one device,
4834 * everything else has one device per stripe.
4835 */
4836 if (bg->flags & BTRFS_BLOCK_GROUP_DUP)
4837 num_items = chunk_map->num_stripes + 1;
4838 else
4839 num_items = 2 * chunk_map->num_stripes;
4840
4841 trans = btrfs_start_transaction_fallback_global_rsv(fs_info->tree_root, num_items);
4842 if (IS_ERR(trans))
4843 return PTR_ERR(trans);
4844
4845 ret = btrfs_remove_dev_extents(trans, chunk_map);
4846 if (unlikely(ret)) {
4847 btrfs_abort_transaction(trans, ret);
4848 btrfs_end_transaction(trans);
4849 return ret;
4850 }
4851
4852 mutex_lock(&trans->fs_info->chunk_mutex);
4853 for (unsigned int i = 0; i < chunk_map->num_stripes; i++) {
4854 ret = btrfs_update_device(trans, chunk_map->stripes[i].dev);
4855 if (unlikely(ret)) {
4856 mutex_unlock(&trans->fs_info->chunk_mutex);
4857 btrfs_abort_transaction(trans, ret);
4858 btrfs_end_transaction(trans);
4859 return ret;
4860 }
4861 }
4862 mutex_unlock(&trans->fs_info->chunk_mutex);
4863
4864 write_lock(&trans->fs_info->mapping_tree_lock);
4865 btrfs_chunk_map_device_clear_bits(chunk_map, CHUNK_ALLOCATED);
4866 write_unlock(&trans->fs_info->mapping_tree_lock);
4867
4868 btrfs_remove_bg_from_sinfo(bg);
4869
4870 spin_lock(&bg->lock);
4871 clear_bit(BLOCK_GROUP_FLAG_STRIPE_REMOVAL_PENDING, &bg->runtime_flags);
4872 spin_unlock(&bg->lock);
4873
4874 ret = remove_chunk_stripes(trans, chunk_map, path);
4875 if (unlikely(ret)) {
4876 btrfs_abort_transaction(trans, ret);
4877 btrfs_end_transaction(trans);
4878 return ret;
4879 }
4880
4881 ret = btrfs_commit_transaction(trans);
4882 if (ret)
4883 return ret;
4884
4885 return 0;
4886 }
4887
adjust_identity_remap_count(struct btrfs_trans_handle * trans,struct btrfs_block_group * bg,int delta)4888 static void adjust_identity_remap_count(struct btrfs_trans_handle *trans,
4889 struct btrfs_block_group *bg, int delta)
4890 {
4891 struct btrfs_fs_info *fs_info = trans->fs_info;
4892 bool bg_already_dirty = true;
4893 bool mark_fully_remapped = false;
4894
4895 WARN_ON(delta < 0 && -delta > bg->identity_remap_count);
4896
4897 spin_lock(&bg->lock);
4898
4899 bg->identity_remap_count += delta;
4900
4901 if (bg->identity_remap_count == 0 &&
4902 !test_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &bg->runtime_flags)) {
4903 set_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &bg->runtime_flags);
4904 mark_fully_remapped = true;
4905 }
4906
4907 spin_unlock(&bg->lock);
4908
4909 spin_lock(&trans->transaction->dirty_bgs_lock);
4910 if (list_empty(&bg->dirty_list)) {
4911 list_add_tail(&bg->dirty_list, &trans->transaction->dirty_bgs);
4912 bg_already_dirty = false;
4913 btrfs_get_block_group(bg);
4914 }
4915 spin_unlock(&trans->transaction->dirty_bgs_lock);
4916
4917 /* Modified block groups are accounted for in the delayed_refs_rsv. */
4918 if (!bg_already_dirty)
4919 btrfs_inc_delayed_refs_rsv_bg_updates(fs_info);
4920
4921 if (mark_fully_remapped)
4922 btrfs_mark_bg_fully_remapped(bg, trans);
4923 }
4924
add_remap_entry(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_block_group * src_bg,u64 old_addr,u64 new_addr,u64 length)4925 static int add_remap_entry(struct btrfs_trans_handle *trans,
4926 struct btrfs_path *path,
4927 struct btrfs_block_group *src_bg, u64 old_addr,
4928 u64 new_addr, u64 length)
4929 {
4930 struct btrfs_fs_info *fs_info = trans->fs_info;
4931 struct btrfs_key key, new_key;
4932 int ret;
4933 int identity_count_delta = 0;
4934
4935 key.objectid = old_addr;
4936 key.type = (u8)-1;
4937 key.offset = (u64)-1;
4938
4939 ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, -1, 1);
4940 if (ret < 0)
4941 goto end;
4942
4943 if (path->slots[0] == 0) {
4944 ret = -ENOENT;
4945 goto end;
4946 }
4947
4948 path->slots[0]--;
4949
4950 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4951
4952 if (key.type != BTRFS_IDENTITY_REMAP_KEY ||
4953 key.objectid > old_addr ||
4954 key.objectid + key.offset <= old_addr) {
4955 ret = -ENOENT;
4956 goto end;
4957 }
4958
4959 /* Shorten or delete identity mapping entry. */
4960 if (key.objectid == old_addr) {
4961 ret = btrfs_del_item(trans, fs_info->remap_root, path);
4962 if (ret)
4963 goto end;
4964
4965 identity_count_delta--;
4966 } else {
4967 new_key.objectid = key.objectid;
4968 new_key.type = BTRFS_IDENTITY_REMAP_KEY;
4969 new_key.offset = old_addr - key.objectid;
4970
4971 btrfs_set_item_key_safe(trans, path, &new_key);
4972 }
4973
4974 btrfs_release_path(path);
4975
4976 /* Create new remap entry. */
4977 ret = add_remap_item(trans, path, new_addr, length, old_addr);
4978 if (ret)
4979 goto end;
4980
4981 /* Add entry for remainder of identity mapping, if necessary. */
4982 if (key.objectid + key.offset != old_addr + length) {
4983 new_key.objectid = old_addr + length;
4984 new_key.type = BTRFS_IDENTITY_REMAP_KEY;
4985 new_key.offset = key.objectid + key.offset - old_addr - length;
4986
4987 ret = btrfs_insert_empty_item(trans, fs_info->remap_root,
4988 path, &new_key, 0);
4989 if (ret)
4990 goto end;
4991
4992 btrfs_release_path(path);
4993
4994 identity_count_delta++;
4995 }
4996
4997 /* Add backref. */
4998 ret = add_remap_backref_item(trans, path, new_addr, length, old_addr);
4999 if (ret)
5000 goto end;
5001
5002 if (identity_count_delta != 0)
5003 adjust_identity_remap_count(trans, src_bg, identity_count_delta);
5004
5005 end:
5006 btrfs_release_path(path);
5007
5008 return ret;
5009 }
5010
mark_chunk_remapped(struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 start)5011 static int mark_chunk_remapped(struct btrfs_trans_handle *trans,
5012 struct btrfs_path *path, u64 start)
5013 {
5014 struct btrfs_fs_info *fs_info = trans->fs_info;
5015 struct btrfs_chunk_map *chunk_map;
5016 struct btrfs_key key;
5017 u64 type;
5018 int ret;
5019 struct extent_buffer *leaf;
5020 struct btrfs_chunk *chunk;
5021
5022 read_lock(&fs_info->mapping_tree_lock);
5023
5024 chunk_map = btrfs_find_chunk_map_nolock(fs_info, start, 1);
5025 if (!chunk_map) {
5026 read_unlock(&fs_info->mapping_tree_lock);
5027 return -ENOENT;
5028 }
5029
5030 chunk_map->type |= BTRFS_BLOCK_GROUP_REMAPPED;
5031 type = chunk_map->type;
5032
5033 read_unlock(&fs_info->mapping_tree_lock);
5034
5035 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5036 key.type = BTRFS_CHUNK_ITEM_KEY;
5037 key.offset = start;
5038
5039 ret = btrfs_search_slot(trans, fs_info->chunk_root, &key, path, 0, 1);
5040 if (ret == 1) {
5041 ret = -ENOENT;
5042 goto end;
5043 } else if (ret < 0)
5044 goto end;
5045
5046 leaf = path->nodes[0];
5047
5048 chunk = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_chunk);
5049 btrfs_set_chunk_type(leaf, chunk, type);
5050 btrfs_mark_buffer_dirty(trans, leaf);
5051
5052 ret = 0;
5053 end:
5054 btrfs_free_chunk_map(chunk_map);
5055 btrfs_release_path(path);
5056
5057 return ret;
5058 }
5059
do_remap_reloc_trans(struct btrfs_fs_info * fs_info,struct btrfs_block_group * src_bg,struct btrfs_path * path,u64 * last_start)5060 static int do_remap_reloc_trans(struct btrfs_fs_info *fs_info,
5061 struct btrfs_block_group *src_bg,
5062 struct btrfs_path *path, u64 *last_start)
5063 {
5064 struct btrfs_trans_handle *trans;
5065 struct btrfs_root *extent_root;
5066 struct btrfs_key ins;
5067 struct btrfs_block_group *dest_bg = NULL;
5068 u64 start = 0, remap_length = 0;
5069 u64 length, new_addr, min_size;
5070 int ret;
5071 const bool is_data = (src_bg->flags & BTRFS_BLOCK_GROUP_DATA);
5072 bool no_more = false;
5073 bool made_reservation = false, bg_needs_free_space;
5074 struct btrfs_space_info *sinfo = src_bg->space_info;
5075
5076 extent_root = btrfs_extent_root(fs_info, src_bg->start);
5077 if (unlikely(!extent_root)) {
5078 btrfs_err(fs_info,
5079 "missing extent root for block group at offset %llu",
5080 src_bg->start);
5081 return -EUCLEAN;
5082 }
5083
5084 trans = btrfs_start_transaction(extent_root, 0);
5085 if (IS_ERR(trans))
5086 return PTR_ERR(trans);
5087
5088 mutex_lock(&fs_info->remap_mutex);
5089
5090 ret = find_next_identity_remap(trans, path, src_bg->start + src_bg->length,
5091 *last_start, &start, &remap_length);
5092 if (ret == -ENOENT) {
5093 no_more = true;
5094 goto next;
5095 } else if (ret) {
5096 mutex_unlock(&fs_info->remap_mutex);
5097 btrfs_end_transaction(trans);
5098 return ret;
5099 }
5100
5101 /* Try to reserve enough space for block. */
5102 spin_lock(&sinfo->lock);
5103 btrfs_space_info_update_bytes_may_use(sinfo, remap_length);
5104 spin_unlock(&sinfo->lock);
5105
5106 if (is_data)
5107 min_size = fs_info->sectorsize;
5108 else
5109 min_size = fs_info->nodesize;
5110
5111 /*
5112 * We're using btrfs_reserve_extent() to allocate a contiguous
5113 * logical address range, but this will become a remap item rather than
5114 * an extent in the extent tree.
5115 *
5116 * Short allocations are fine: it means that we chop off the beginning
5117 * of the identity remap that we're processing, and will tackle the
5118 * rest of it the next time round.
5119 */
5120 ret = btrfs_reserve_extent(fs_info->fs_root, remap_length, remap_length,
5121 min_size, 0, 0, &ins, is_data, false);
5122 if (ret) {
5123 spin_lock(&sinfo->lock);
5124 btrfs_space_info_update_bytes_may_use(sinfo, -remap_length);
5125 spin_unlock(&sinfo->lock);
5126
5127 mutex_unlock(&fs_info->remap_mutex);
5128 btrfs_end_transaction(trans);
5129 return ret;
5130 }
5131
5132 if (ins.offset < remap_length) {
5133 spin_lock(&sinfo->lock);
5134 btrfs_space_info_update_bytes_may_use(sinfo, ins.offset - remap_length);
5135 spin_unlock(&sinfo->lock);
5136 }
5137
5138 made_reservation = true;
5139
5140 new_addr = ins.objectid;
5141 length = ins.offset;
5142
5143 if (!is_data && !IS_ALIGNED(length, fs_info->nodesize)) {
5144 u64 new_length = ALIGN_DOWN(length, fs_info->nodesize);
5145
5146 btrfs_free_reserved_extent(fs_info, new_addr + new_length,
5147 length - new_length, 0);
5148
5149 length = new_length;
5150 }
5151
5152 dest_bg = btrfs_lookup_block_group(fs_info, new_addr);
5153
5154 mutex_lock(&dest_bg->free_space_lock);
5155 bg_needs_free_space = test_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE,
5156 &dest_bg->runtime_flags);
5157 mutex_unlock(&dest_bg->free_space_lock);
5158
5159 if (bg_needs_free_space) {
5160 ret = btrfs_add_block_group_free_space(trans, dest_bg);
5161 if (ret) {
5162 btrfs_abort_transaction(trans, ret);
5163 goto fail;
5164 }
5165 }
5166
5167 ret = copy_remapped_data(fs_info, start, new_addr, length);
5168 if (ret) {
5169 btrfs_abort_transaction(trans, ret);
5170 goto fail;
5171 }
5172
5173 ret = btrfs_remove_from_free_space_tree(trans, new_addr, length);
5174 if (ret) {
5175 btrfs_abort_transaction(trans, ret);
5176 goto fail;
5177 }
5178
5179 ret = add_remap_entry(trans, path, src_bg, start, new_addr, length);
5180 if (ret) {
5181 btrfs_abort_transaction(trans, ret);
5182 goto fail;
5183 }
5184
5185 adjust_block_group_remap_bytes(trans, dest_bg, length);
5186 btrfs_free_reserved_bytes(dest_bg, length, 0);
5187
5188 spin_lock(&sinfo->lock);
5189 sinfo->bytes_readonly += length;
5190 spin_unlock(&sinfo->lock);
5191
5192 next:
5193 if (dest_bg)
5194 btrfs_put_block_group(dest_bg);
5195
5196 if (made_reservation)
5197 btrfs_dec_block_group_reservations(fs_info, new_addr);
5198
5199 mutex_unlock(&fs_info->remap_mutex);
5200
5201 if (src_bg->identity_remap_count == 0) {
5202 bool mark_fully_remapped = false;
5203
5204 spin_lock(&src_bg->lock);
5205 if (!test_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &src_bg->runtime_flags)) {
5206 mark_fully_remapped = true;
5207 set_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &src_bg->runtime_flags);
5208 }
5209 spin_unlock(&src_bg->lock);
5210
5211 if (mark_fully_remapped)
5212 btrfs_mark_bg_fully_remapped(src_bg, trans);
5213 }
5214
5215 ret = btrfs_end_transaction(trans);
5216 if (ret)
5217 return ret;
5218
5219 if (no_more)
5220 return 1;
5221
5222 *last_start = start;
5223
5224 return 0;
5225
5226 fail:
5227 if (dest_bg)
5228 btrfs_put_block_group(dest_bg);
5229
5230 btrfs_free_reserved_extent(fs_info, new_addr, length, 0);
5231
5232 mutex_unlock(&fs_info->remap_mutex);
5233 btrfs_end_transaction(trans);
5234
5235 return ret;
5236 }
5237
do_remap_reloc(struct btrfs_fs_info * fs_info,struct btrfs_path * path,struct btrfs_block_group * bg)5238 static int do_remap_reloc(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
5239 struct btrfs_block_group *bg)
5240 {
5241 u64 last_start = bg->start;
5242 int ret;
5243
5244 while (true) {
5245 ret = do_remap_reloc_trans(fs_info, bg, path, &last_start);
5246 if (ret) {
5247 if (ret == 1)
5248 ret = 0;
5249 break;
5250 }
5251 }
5252
5253 return ret;
5254 }
5255
btrfs_translate_remap(struct btrfs_fs_info * fs_info,u64 * logical,u64 * length)5256 int btrfs_translate_remap(struct btrfs_fs_info *fs_info, u64 *logical, u64 *length)
5257 {
5258 int ret;
5259 struct btrfs_key key, found_key;
5260 struct extent_buffer *leaf;
5261 struct btrfs_remap_item *remap;
5262 BTRFS_PATH_AUTO_FREE(path);
5263
5264 path = btrfs_alloc_path();
5265 if (!path)
5266 return -ENOMEM;
5267
5268 key.objectid = *logical;
5269 key.type = (u8)-1;
5270 key.offset = (u64)-1;
5271
5272 ret = btrfs_search_slot(NULL, fs_info->remap_root, &key, path, 0, 0);
5273 if (ret < 0)
5274 return ret;
5275
5276 leaf = path->nodes[0];
5277 if (path->slots[0] == 0)
5278 return -ENOENT;
5279
5280 path->slots[0]--;
5281
5282 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5283
5284 if (found_key.type != BTRFS_REMAP_KEY &&
5285 found_key.type != BTRFS_IDENTITY_REMAP_KEY) {
5286 return -ENOENT;
5287 }
5288
5289 if (found_key.objectid > *logical ||
5290 found_key.objectid + found_key.offset <= *logical) {
5291 return -ENOENT;
5292 }
5293
5294 if (*logical + *length > found_key.objectid + found_key.offset)
5295 *length = found_key.objectid + found_key.offset - *logical;
5296
5297 if (found_key.type == BTRFS_IDENTITY_REMAP_KEY)
5298 return 0;
5299
5300 remap = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_remap_item);
5301 *logical += btrfs_remap_address(leaf, remap) - found_key.objectid;
5302
5303 return 0;
5304 }
5305
start_block_group_remapping(struct btrfs_fs_info * fs_info,struct btrfs_path * path,struct btrfs_block_group * bg)5306 static int start_block_group_remapping(struct btrfs_fs_info *fs_info,
5307 struct btrfs_path *path,
5308 struct btrfs_block_group *bg)
5309 {
5310 struct btrfs_trans_handle *trans;
5311 bool bg_already_dirty = true;
5312 int ret, ret2;
5313
5314 ret = btrfs_cache_block_group(bg, true);
5315 if (ret)
5316 return ret;
5317
5318 trans = btrfs_start_transaction(fs_info->remap_root, 0);
5319 if (IS_ERR(trans))
5320 return PTR_ERR(trans);
5321
5322 /* We need to run delayed refs, to make sure FST is up to date. */
5323 ret = btrfs_run_delayed_refs(trans, U64_MAX);
5324 if (ret) {
5325 btrfs_end_transaction(trans);
5326 return ret;
5327 }
5328
5329 mutex_lock(&fs_info->remap_mutex);
5330
5331 if (bg->flags & BTRFS_BLOCK_GROUP_REMAPPED) {
5332 ret = 0;
5333 goto end;
5334 }
5335
5336 ret = create_remap_tree_entries(trans, path, bg);
5337 if (unlikely(ret)) {
5338 btrfs_abort_transaction(trans, ret);
5339 goto end;
5340 }
5341
5342 spin_lock(&bg->lock);
5343 bg->flags |= BTRFS_BLOCK_GROUP_REMAPPED;
5344 spin_unlock(&bg->lock);
5345
5346 spin_lock(&trans->transaction->dirty_bgs_lock);
5347 if (list_empty(&bg->dirty_list)) {
5348 list_add_tail(&bg->dirty_list, &trans->transaction->dirty_bgs);
5349 bg_already_dirty = false;
5350 btrfs_get_block_group(bg);
5351 }
5352 spin_unlock(&trans->transaction->dirty_bgs_lock);
5353
5354 /* Modified block groups are accounted for in the delayed_refs_rsv. */
5355 if (!bg_already_dirty)
5356 btrfs_inc_delayed_refs_rsv_bg_updates(fs_info);
5357
5358 ret = mark_chunk_remapped(trans, path, bg->start);
5359 if (unlikely(ret)) {
5360 btrfs_abort_transaction(trans, ret);
5361 goto end;
5362 }
5363
5364 ret = btrfs_remove_block_group_free_space(trans, bg);
5365 if (unlikely(ret)) {
5366 btrfs_abort_transaction(trans, ret);
5367 goto end;
5368 }
5369
5370 btrfs_remove_free_space_cache(bg);
5371
5372 end:
5373 mutex_unlock(&fs_info->remap_mutex);
5374
5375 ret2 = btrfs_end_transaction(trans);
5376 if (!ret)
5377 ret = ret2;
5378
5379 return ret;
5380 }
5381
do_nonremap_reloc(struct btrfs_fs_info * fs_info,bool verbose,struct reloc_control * rc)5382 static int do_nonremap_reloc(struct btrfs_fs_info *fs_info, bool verbose,
5383 struct reloc_control *rc)
5384 {
5385 int ret;
5386
5387 while (1) {
5388 enum reloc_stage finishes_stage;
5389
5390 mutex_lock(&fs_info->cleaner_mutex);
5391 ret = relocate_block_group(rc);
5392 mutex_unlock(&fs_info->cleaner_mutex);
5393
5394 finishes_stage = rc->stage;
5395 /*
5396 * We may have gotten ENOSPC after we already dirtied some
5397 * extents. If writeout happens while we're relocating a
5398 * different block group we could end up hitting the
5399 * BUG_ON(rc->stage == UPDATE_DATA_PTRS) in
5400 * btrfs_reloc_cow_block. Make sure we write everything out
5401 * properly so we don't trip over this problem, and then break
5402 * out of the loop if we hit an error.
5403 */
5404 if (rc->stage == MOVE_DATA_EXTENTS && rc->found_file_extent) {
5405 int wb_ret;
5406
5407 wb_ret = btrfs_wait_ordered_range(BTRFS_I(rc->data_inode),
5408 0, (u64)-1);
5409 if (wb_ret && ret == 0)
5410 ret = wb_ret;
5411 invalidate_mapping_pages(rc->data_inode->i_mapping, 0, -1);
5412 rc->stage = UPDATE_DATA_PTRS;
5413 }
5414
5415 if (ret < 0)
5416 return ret;
5417
5418 if (rc->extents_found == 0)
5419 break;
5420
5421 if (verbose)
5422 btrfs_info(fs_info, "found %llu extents, stage: %s",
5423 rc->extents_found, stage_to_string(finishes_stage));
5424 }
5425
5426 WARN_ON(rc->block_group->pinned > 0);
5427 WARN_ON(rc->block_group->reserved > 0);
5428 WARN_ON(rc->block_group->used > 0);
5429
5430 return 0;
5431 }
5432
5433 /*
5434 * function to relocate all extents in a block group.
5435 */
btrfs_relocate_block_group(struct btrfs_fs_info * fs_info,u64 group_start,bool verbose)5436 int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
5437 bool verbose)
5438 {
5439 struct btrfs_block_group *bg;
5440 struct btrfs_root *extent_root = btrfs_extent_root(fs_info, group_start);
5441 struct reloc_control *rc;
5442 struct inode *inode;
5443 struct btrfs_path *path = NULL;
5444 int ret;
5445 bool bg_is_ro = false;
5446
5447 if (unlikely(!extent_root)) {
5448 btrfs_err(fs_info,
5449 "missing extent root for block group at offset %llu",
5450 group_start);
5451 return -EUCLEAN;
5452 }
5453
5454 /*
5455 * This only gets set if we had a half-deleted snapshot on mount. We
5456 * cannot allow relocation to start while we're still trying to clean up
5457 * these pending deletions.
5458 */
5459 ret = wait_on_bit(&fs_info->flags, BTRFS_FS_UNFINISHED_DROPS, TASK_INTERRUPTIBLE);
5460 if (ret)
5461 return ret;
5462
5463 /* We may have been woken up by close_ctree, so bail if we're closing. */
5464 if (btrfs_fs_closing(fs_info))
5465 return -EINTR;
5466
5467 bg = btrfs_lookup_block_group(fs_info, group_start);
5468 if (!bg)
5469 return -ENOENT;
5470
5471 /*
5472 * Relocation of a data block group creates ordered extents. Without
5473 * sb_start_write(), we can freeze the filesystem while unfinished
5474 * ordered extents are left. Such ordered extents can cause a deadlock
5475 * e.g. when syncfs() is waiting for their completion but they can't
5476 * finish because they block when joining a transaction, due to the
5477 * fact that the freeze locks are being held in write mode.
5478 */
5479 if (bg->flags & BTRFS_BLOCK_GROUP_DATA)
5480 ASSERT(sb_write_started(fs_info->sb));
5481
5482 if (btrfs_pinned_by_swapfile(fs_info, bg)) {
5483 btrfs_put_block_group(bg);
5484 return -ETXTBSY;
5485 }
5486
5487 rc = alloc_reloc_control(fs_info);
5488 if (!rc) {
5489 btrfs_put_block_group(bg);
5490 return -ENOMEM;
5491 }
5492
5493 rc->extent_root = extent_root;
5494 /* Block group ref now owned by rc, put_reloc_control() will drop it. */
5495 rc->block_group = bg;
5496
5497 ret = reloc_chunk_start(fs_info);
5498 if (ret < 0)
5499 goto out_put_rc;
5500
5501 ret = btrfs_inc_block_group_ro(rc->block_group, true);
5502 if (ret)
5503 goto out;
5504 bg_is_ro = true;
5505
5506 path = btrfs_alloc_path();
5507 if (!path) {
5508 ret = -ENOMEM;
5509 goto out;
5510 }
5511
5512 inode = lookup_free_space_inode(rc->block_group, path);
5513 btrfs_release_path(path);
5514
5515 if (!IS_ERR(inode))
5516 ret = delete_block_group_cache(rc->block_group, inode, 0);
5517 else
5518 ret = PTR_ERR(inode);
5519
5520 if (ret && ret != -ENOENT)
5521 goto out;
5522
5523 if (!btrfs_fs_incompat(fs_info, REMAP_TREE)) {
5524 rc->data_inode = create_reloc_inode(rc->block_group);
5525 if (IS_ERR(rc->data_inode)) {
5526 ret = PTR_ERR(rc->data_inode);
5527 rc->data_inode = NULL;
5528 goto out;
5529 }
5530 }
5531
5532 if (verbose)
5533 describe_relocation(rc->block_group);
5534
5535 btrfs_wait_block_group_reservations(rc->block_group);
5536 btrfs_wait_nocow_writers(rc->block_group);
5537 btrfs_wait_ordered_roots(fs_info, U64_MAX, rc->block_group);
5538
5539 ret = btrfs_zone_finish(rc->block_group);
5540 WARN_ON(ret && ret != -EAGAIN);
5541
5542 if (should_relocate_using_remap_tree(bg)) {
5543 if (bg->remap_bytes != 0) {
5544 ret = move_existing_remaps(fs_info, bg, path);
5545 if (ret)
5546 goto out;
5547 }
5548 ret = start_block_group_remapping(fs_info, path, bg);
5549 if (ret)
5550 goto out;
5551
5552 ret = do_remap_reloc(fs_info, path, rc->block_group);
5553 if (ret)
5554 goto out;
5555
5556 btrfs_delete_unused_bgs(fs_info);
5557 } else {
5558 ret = do_nonremap_reloc(fs_info, verbose, rc);
5559 }
5560
5561 out:
5562 if (ret && bg_is_ro)
5563 btrfs_dec_block_group_ro(rc->block_group);
5564 if (!btrfs_fs_incompat(fs_info, REMAP_TREE))
5565 iput(rc->data_inode);
5566 btrfs_free_path(path);
5567 reloc_chunk_end(fs_info);
5568 out_put_rc:
5569 put_reloc_control(rc);
5570 return ret;
5571 }
5572
mark_garbage_root(struct btrfs_root * root)5573 static noinline_for_stack int mark_garbage_root(struct btrfs_root *root)
5574 {
5575 struct btrfs_fs_info *fs_info = root->fs_info;
5576 struct btrfs_trans_handle *trans;
5577 int ret, err;
5578
5579 trans = btrfs_start_transaction(fs_info->tree_root, 0);
5580 if (IS_ERR(trans))
5581 return PTR_ERR(trans);
5582
5583 memset(&root->root_item.drop_progress, 0,
5584 sizeof(root->root_item.drop_progress));
5585 btrfs_set_root_drop_level(&root->root_item, 0);
5586 btrfs_set_root_refs(&root->root_item, 0);
5587 ret = btrfs_update_root(trans, fs_info->tree_root,
5588 &root->root_key, &root->root_item);
5589
5590 err = btrfs_end_transaction(trans);
5591 if (err)
5592 return err;
5593 return ret;
5594 }
5595
release_recovered_fs_roots(struct list_head * roots,bool drop_reloc_refs)5596 static void release_recovered_fs_roots(struct list_head *roots, bool drop_reloc_refs)
5597 {
5598 struct btrfs_root *root;
5599 struct btrfs_root *next;
5600
5601 list_for_each_entry_safe(root, next, roots, reloc_dirty_list) {
5602 list_del_init(&root->reloc_dirty_list);
5603 if (drop_reloc_refs) {
5604 struct btrfs_root *reloc_root = root->reloc_root;
5605
5606 ASSERT(reloc_root);
5607 root->reloc_root = NULL;
5608 btrfs_put_root(reloc_root);
5609 }
5610 btrfs_put_root(root);
5611 }
5612 }
5613
5614 /*
5615 * recover relocation interrupted by system crash.
5616 *
5617 * this function resumes merging reloc trees with corresponding fs trees.
5618 * this is important for keeping the sharing of tree blocks
5619 */
btrfs_recover_relocation(struct btrfs_fs_info * fs_info)5620 int btrfs_recover_relocation(struct btrfs_fs_info *fs_info)
5621 {
5622 LIST_HEAD(reloc_roots);
5623 LIST_HEAD(recovered_roots);
5624 struct btrfs_key key;
5625 struct btrfs_root *fs_root;
5626 struct btrfs_root *reloc_root;
5627 struct btrfs_path *path;
5628 struct extent_buffer *leaf;
5629 struct reloc_control *rc = NULL;
5630 struct btrfs_trans_handle *trans;
5631 int ret2;
5632 int ret = 0;
5633
5634 path = btrfs_alloc_path();
5635 if (!path)
5636 return -ENOMEM;
5637 path->reada = READA_BACK;
5638
5639 key.objectid = BTRFS_TREE_RELOC_OBJECTID;
5640 key.type = BTRFS_ROOT_ITEM_KEY;
5641 key.offset = (u64)-1;
5642
5643 while (1) {
5644 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key,
5645 path, 0, 0);
5646 if (ret < 0)
5647 goto out;
5648 if (ret > 0) {
5649 if (path->slots[0] == 0)
5650 break;
5651 path->slots[0]--;
5652 }
5653 ret = 0;
5654 leaf = path->nodes[0];
5655 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5656 btrfs_release_path(path);
5657
5658 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID ||
5659 key.type != BTRFS_ROOT_ITEM_KEY)
5660 break;
5661
5662 reloc_root = btrfs_read_tree_root(fs_info->tree_root, &key);
5663 if (IS_ERR(reloc_root)) {
5664 ret = PTR_ERR(reloc_root);
5665 goto out;
5666 }
5667
5668 set_bit(BTRFS_ROOT_SHAREABLE, &reloc_root->state);
5669 list_add(&reloc_root->root_list, &reloc_roots);
5670
5671 if (btrfs_root_refs(&reloc_root->root_item) > 0) {
5672 fs_root = btrfs_get_fs_root(fs_info,
5673 reloc_root->root_key.offset, false);
5674 if (IS_ERR(fs_root)) {
5675 ret = PTR_ERR(fs_root);
5676 if (ret != -ENOENT)
5677 goto out;
5678 ret = mark_garbage_root(reloc_root);
5679 if (ret < 0)
5680 goto out;
5681 ret = 0;
5682 } else {
5683 btrfs_put_root(fs_root);
5684 }
5685 }
5686
5687 if (key.offset == 0)
5688 break;
5689
5690 key.offset--;
5691 }
5692 btrfs_release_path(path);
5693
5694 if (list_empty(&reloc_roots))
5695 goto out;
5696
5697 rc = alloc_reloc_control(fs_info);
5698 if (!rc) {
5699 ret = -ENOMEM;
5700 goto out;
5701 }
5702
5703 rc->extent_root = btrfs_extent_root(fs_info, 0);
5704 if (unlikely(!rc->extent_root)) {
5705 btrfs_err(fs_info, "missing extent root for extent at bytenr 0");
5706 ret = -EUCLEAN;
5707 goto out;
5708 }
5709
5710 ret = reloc_chunk_start(fs_info);
5711 if (ret < 0)
5712 goto out_end;
5713
5714 set_reloc_control(rc);
5715
5716 trans = btrfs_join_transaction(rc->extent_root);
5717 if (IS_ERR(trans)) {
5718 ret = PTR_ERR(trans);
5719 goto out_unset;
5720 }
5721
5722 rc->merge_reloc_tree = true;
5723
5724 while (!list_empty(&reloc_roots)) {
5725 reloc_root = list_first_entry(&reloc_roots, struct btrfs_root, root_list);
5726 list_del(&reloc_root->root_list);
5727
5728 if (btrfs_root_refs(&reloc_root->root_item) == 0) {
5729 list_add_tail(&reloc_root->root_list,
5730 &rc->reloc_roots);
5731 continue;
5732 }
5733
5734 fs_root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
5735 false);
5736 if (IS_ERR(fs_root)) {
5737 ret = PTR_ERR(fs_root);
5738 list_add_tail(&reloc_root->root_list, &reloc_roots);
5739 btrfs_end_transaction(trans);
5740 goto out_drop_reloc_refs;
5741 }
5742
5743 ret = __add_reloc_root(reloc_root, rc);
5744 ASSERT(ret != -EEXIST);
5745 if (ret) {
5746 list_add_tail(&reloc_root->root_list, &reloc_roots);
5747 btrfs_put_root(fs_root);
5748 btrfs_end_transaction(trans);
5749 goto out_drop_reloc_refs;
5750 }
5751 ASSERT(list_empty(&fs_root->reloc_dirty_list));
5752 fs_root->reloc_root = btrfs_grab_root(reloc_root);
5753 list_add_tail(&fs_root->reloc_dirty_list, &recovered_roots);
5754 }
5755
5756 ret = btrfs_commit_transaction(trans);
5757 if (ret)
5758 goto out_drop_reloc_refs;
5759 release_recovered_fs_roots(&recovered_roots, false);
5760
5761 ret = merge_reloc_roots(rc);
5762 if (ret)
5763 goto out_unset;
5764
5765 unset_reloc_control(rc);
5766
5767 trans = btrfs_join_transaction(rc->extent_root);
5768 if (IS_ERR(trans)) {
5769 ret = PTR_ERR(trans);
5770 goto out_clean;
5771 }
5772 ret = btrfs_commit_transaction(trans);
5773 out_clean:
5774 ret2 = clean_dirty_subvols(rc);
5775 if (ret2 < 0 && !ret)
5776 ret = ret2;
5777 out_drop_reloc_refs:
5778 release_recovered_fs_roots(&recovered_roots, true);
5779 out_unset:
5780 unset_reloc_control(rc);
5781 reloc_chunk_end(fs_info);
5782 out_end:
5783 put_reloc_control(rc);
5784 out:
5785 free_reloc_roots(&reloc_roots);
5786
5787 btrfs_free_path(path);
5788
5789 if (ret == 0 && !btrfs_fs_incompat(fs_info, REMAP_TREE)) {
5790 /* cleanup orphan inode in data relocation tree */
5791 fs_root = btrfs_grab_root(fs_info->data_reloc_root);
5792 ASSERT(fs_root);
5793 ret = btrfs_orphan_cleanup(fs_root);
5794 btrfs_put_root(fs_root);
5795 }
5796 return ret;
5797 }
5798
5799 /*
5800 * helper to add ordered checksum for data relocation.
5801 *
5802 * cloning checksum properly handles the nodatasum extents.
5803 * it also saves CPU time to re-calculate the checksum.
5804 */
btrfs_reloc_clone_csums(struct btrfs_ordered_extent * ordered)5805 int btrfs_reloc_clone_csums(struct btrfs_ordered_extent *ordered)
5806 {
5807 struct btrfs_inode *inode = ordered->inode;
5808 struct btrfs_fs_info *fs_info = inode->root->fs_info;
5809 u64 disk_bytenr = ordered->file_offset + inode->reloc_block_group_start;
5810 struct btrfs_root *csum_root = btrfs_csum_root(fs_info, disk_bytenr);
5811 LIST_HEAD(list);
5812 int ret;
5813
5814 if (unlikely(!csum_root)) {
5815 btrfs_mark_ordered_extent_error(ordered);
5816 btrfs_err(fs_info,
5817 "missing csum root for extent at bytenr %llu",
5818 disk_bytenr);
5819 return -EUCLEAN;
5820 }
5821
5822 ret = btrfs_lookup_csums_list(csum_root, disk_bytenr,
5823 disk_bytenr + ordered->num_bytes - 1,
5824 &list, false);
5825 if (ret < 0) {
5826 btrfs_mark_ordered_extent_error(ordered);
5827 return ret;
5828 }
5829
5830 while (!list_empty(&list)) {
5831 struct btrfs_ordered_sum *sums =
5832 list_first_entry(&list, struct btrfs_ordered_sum, list);
5833
5834 list_del_init(&sums->list);
5835
5836 /*
5837 * We need to offset the new_bytenr based on where the csum is.
5838 * We need to do this because we will read in entire prealloc
5839 * extents but we may have written to say the middle of the
5840 * prealloc extent, so we need to make sure the csum goes with
5841 * the right disk offset.
5842 *
5843 * We can do this because the data reloc inode refers strictly
5844 * to the on disk bytes, so we don't have to worry about
5845 * disk_len vs real len like with real inodes since it's all
5846 * disk length.
5847 */
5848 sums->logical = ordered->disk_bytenr + sums->logical - disk_bytenr;
5849 btrfs_add_ordered_sum(ordered, sums);
5850 }
5851
5852 return 0;
5853 }
5854
btrfs_reloc_cow_block(struct btrfs_trans_handle * trans,struct btrfs_root * root,const struct extent_buffer * buf,struct extent_buffer * cow)5855 int btrfs_reloc_cow_block(struct btrfs_trans_handle *trans,
5856 struct btrfs_root *root,
5857 const struct extent_buffer *buf,
5858 struct extent_buffer *cow)
5859 {
5860 struct btrfs_fs_info *fs_info = root->fs_info;
5861 struct reloc_control *rc;
5862 struct btrfs_backref_node *node;
5863 bool first_cow = false;
5864 int level;
5865 int ret = 0;
5866
5867 rc = get_reloc_control(fs_info);
5868 if (!rc)
5869 return 0;
5870
5871 BUG_ON(rc->stage == UPDATE_DATA_PTRS && btrfs_is_data_reloc_root(root));
5872
5873 level = btrfs_header_level(buf);
5874 if (btrfs_header_generation(buf) <=
5875 btrfs_root_last_snapshot(&root->root_item))
5876 first_cow = true;
5877
5878 if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID && rc->create_reloc_tree) {
5879 WARN_ON(!first_cow && level == 0);
5880
5881 node = rc->backref_cache.path[level];
5882
5883 /*
5884 * If node->bytenr != buf->start and node->new_bytenr !=
5885 * buf->start then we've got the wrong backref node for what we
5886 * expected to see here and the cache is incorrect.
5887 */
5888 if (unlikely(node->bytenr != buf->start && node->new_bytenr != buf->start)) {
5889 btrfs_err(fs_info,
5890 "bytenr %llu was found but our backref cache was expecting %llu or %llu",
5891 buf->start, node->bytenr, node->new_bytenr);
5892 ret = -EUCLEAN;
5893 goto out;
5894 }
5895
5896 btrfs_backref_drop_node_buffer(node);
5897 refcount_inc(&cow->refs);
5898 node->eb = cow;
5899 node->new_bytenr = cow->start;
5900
5901 if (!node->pending) {
5902 list_move_tail(&node->list,
5903 &rc->backref_cache.pending[level]);
5904 node->pending = 1;
5905 }
5906
5907 if (first_cow)
5908 mark_block_processed(rc, node);
5909
5910 if (first_cow && level > 0)
5911 rc->nodes_relocated += buf->len;
5912 }
5913
5914 if (level == 0 && first_cow && rc->stage == UPDATE_DATA_PTRS)
5915 ret = replace_file_extents(trans, rc, root, cow);
5916 out:
5917 put_reloc_control(rc);
5918
5919 return ret;
5920 }
5921
5922 /*
5923 * called before creating snapshot. it calculates metadata reservation
5924 * required for relocating tree blocks in the snapshot
5925 */
btrfs_reloc_pre_snapshot(struct btrfs_pending_snapshot * pending,u64 * bytes_to_reserve)5926 void btrfs_reloc_pre_snapshot(struct btrfs_pending_snapshot *pending,
5927 u64 *bytes_to_reserve)
5928 {
5929 struct btrfs_root *root = pending->root;
5930 struct reloc_control *rc = root->fs_info->reloc_ctl;
5931
5932 if (!rc || !have_reloc_root(root))
5933 return;
5934
5935 if (!rc->merge_reloc_tree)
5936 return;
5937
5938 root = root->reloc_root;
5939 BUG_ON(btrfs_root_refs(&root->root_item) == 0);
5940 /*
5941 * relocation is in the stage of merging trees. the space
5942 * used by merging a reloc tree is twice the size of
5943 * relocated tree nodes in the worst case. half for cowing
5944 * the reloc tree, half for cowing the fs tree. the space
5945 * used by cowing the reloc tree will be freed after the
5946 * tree is dropped. if we create snapshot, cowing the fs
5947 * tree may use more space than it frees. so we need
5948 * reserve extra space.
5949 */
5950 *bytes_to_reserve += rc->nodes_relocated;
5951 }
5952
5953 /*
5954 * called after snapshot is created. migrate block reservation
5955 * and create reloc root for the newly created snapshot
5956 *
5957 * This is similar to btrfs_init_reloc_root(), we come out of here with two
5958 * references held on the reloc_root, one for root->reloc_root and one for
5959 * rc->reloc_roots.
5960 */
btrfs_reloc_post_snapshot(struct btrfs_trans_handle * trans,struct btrfs_pending_snapshot * pending)5961 int btrfs_reloc_post_snapshot(struct btrfs_trans_handle *trans,
5962 struct btrfs_pending_snapshot *pending)
5963 {
5964 struct btrfs_root *root = pending->root;
5965 struct btrfs_root *reloc_root;
5966 struct btrfs_root *new_root;
5967 struct reloc_control *rc;
5968 int ret = 0;
5969
5970 rc = get_reloc_control(trans->fs_info);
5971 if (!rc)
5972 return 0;
5973
5974 if (!have_reloc_root(root))
5975 goto out;
5976
5977 rc->merging_rsv_size += rc->nodes_relocated;
5978
5979 if (rc->merge_reloc_tree) {
5980 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
5981 rc->block_rsv,
5982 rc->nodes_relocated, true);
5983 if (ret)
5984 goto out;
5985 }
5986
5987 new_root = pending->snap;
5988 reloc_root = create_reloc_root(trans, root->reloc_root, btrfs_root_id(new_root));
5989 if (IS_ERR(reloc_root)) {
5990 ret = PTR_ERR(reloc_root);
5991 goto out;
5992 }
5993
5994 ret = __add_reloc_root(reloc_root, rc);
5995 ASSERT(ret != -EEXIST);
5996 if (ret) {
5997 /* Pairs with create_reloc_root */
5998 btrfs_put_root(reloc_root);
5999 goto out;
6000 }
6001 new_root->reloc_root = btrfs_grab_root(reloc_root);
6002 out:
6003 put_reloc_control(rc);
6004
6005 return ret;
6006 }
6007
6008 /*
6009 * Get the current bytenr for the block group which is being relocated.
6010 *
6011 * Return U64_MAX if no running relocation.
6012 */
btrfs_get_reloc_bg_bytenr(struct btrfs_fs_info * fs_info)6013 u64 btrfs_get_reloc_bg_bytenr(struct btrfs_fs_info *fs_info)
6014 {
6015 u64 logical = U64_MAX;
6016
6017 mutex_lock(&fs_info->reloc_mutex);
6018 if (fs_info->reloc_ctl && fs_info->reloc_ctl->block_group)
6019 logical = fs_info->reloc_ctl->block_group->start;
6020 mutex_unlock(&fs_info->reloc_mutex);
6021
6022 return logical;
6023 }
6024
insert_remap_item(struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 old_addr,u64 length,u64 new_addr)6025 static int insert_remap_item(struct btrfs_trans_handle *trans, struct btrfs_path *path,
6026 u64 old_addr, u64 length, u64 new_addr)
6027 {
6028 int ret;
6029 struct btrfs_fs_info *fs_info = trans->fs_info;
6030 struct btrfs_key key;
6031 struct btrfs_remap_item remap = { 0 };
6032
6033 if (old_addr == new_addr) {
6034 /* Add new identity remap item. */
6035 key.objectid = old_addr;
6036 key.type = BTRFS_IDENTITY_REMAP_KEY;
6037 key.offset = length;
6038
6039 ret = btrfs_insert_empty_item(trans, fs_info->remap_root, path,
6040 &key, 0);
6041 if (ret)
6042 return ret;
6043 } else {
6044 /* Add new remap item. */
6045 key.objectid = old_addr;
6046 key.type = BTRFS_REMAP_KEY;
6047 key.offset = length;
6048
6049 ret = btrfs_insert_empty_item(trans, fs_info->remap_root,
6050 path, &key, sizeof(struct btrfs_remap_item));
6051 if (ret)
6052 return ret;
6053
6054 btrfs_set_stack_remap_address(&remap, new_addr);
6055
6056 write_extent_buffer(path->nodes[0], &remap,
6057 btrfs_item_ptr_offset(path->nodes[0], path->slots[0]),
6058 sizeof(struct btrfs_remap_item));
6059
6060 btrfs_release_path(path);
6061
6062 /* Add new backref item. */
6063 key.objectid = new_addr;
6064 key.type = BTRFS_REMAP_BACKREF_KEY;
6065 key.offset = length;
6066
6067 ret = btrfs_insert_empty_item(trans, fs_info->remap_root,
6068 path, &key,
6069 sizeof(struct btrfs_remap_item));
6070 if (ret)
6071 return ret;
6072
6073 btrfs_set_stack_remap_address(&remap, old_addr);
6074
6075 write_extent_buffer(path->nodes[0], &remap,
6076 btrfs_item_ptr_offset(path->nodes[0], path->slots[0]),
6077 sizeof(struct btrfs_remap_item));
6078 }
6079
6080 btrfs_release_path(path);
6081
6082 return 0;
6083 }
6084
6085 /*
6086 * Punch a hole in the remap item or identity remap item pointed to by path,
6087 * for the range [hole_start, hole_start + hole_length).
6088 */
remove_range_from_remap_tree(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_block_group * bg,u64 hole_start,u64 hole_length)6089 static int remove_range_from_remap_tree(struct btrfs_trans_handle *trans,
6090 struct btrfs_path *path,
6091 struct btrfs_block_group *bg,
6092 u64 hole_start, u64 hole_length)
6093 {
6094 int ret;
6095 struct btrfs_fs_info *fs_info = trans->fs_info;
6096 struct extent_buffer *leaf = path->nodes[0];
6097 struct btrfs_key key;
6098 u64 hole_end, new_addr, remap_start, remap_length, remap_end;
6099 u64 overlap_length;
6100 bool is_identity_remap;
6101 int identity_count_delta = 0;
6102
6103 hole_end = hole_start + hole_length;
6104
6105 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6106
6107 is_identity_remap = (key.type == BTRFS_IDENTITY_REMAP_KEY);
6108
6109 remap_start = key.objectid;
6110 remap_length = key.offset;
6111 remap_end = remap_start + remap_length;
6112
6113 if (is_identity_remap) {
6114 new_addr = remap_start;
6115 } else {
6116 struct btrfs_remap_item *remap_ptr;
6117
6118 remap_ptr = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_remap_item);
6119 new_addr = btrfs_remap_address(leaf, remap_ptr);
6120 }
6121
6122 /* Delete old item. */
6123 ret = btrfs_del_item(trans, fs_info->remap_root, path);
6124 btrfs_release_path(path);
6125 if (ret)
6126 return ret;
6127
6128 if (is_identity_remap) {
6129 identity_count_delta = -1;
6130 } else {
6131 /* Remove backref. */
6132 key.objectid = new_addr;
6133 key.type = BTRFS_REMAP_BACKREF_KEY;
6134 key.offset = remap_length;
6135
6136 ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, -1, 1);
6137 if (ret) {
6138 if (ret == 1) {
6139 btrfs_release_path(path);
6140 ret = -ENOENT;
6141 }
6142 return ret;
6143 }
6144
6145 ret = btrfs_del_item(trans, fs_info->remap_root, path);
6146
6147 btrfs_release_path(path);
6148
6149 if (ret)
6150 return ret;
6151 }
6152
6153 /* If hole_start > remap_start, re-add the start of the remap item. */
6154 if (hole_start > remap_start) {
6155 ret = insert_remap_item(trans, path, remap_start,
6156 hole_start - remap_start, new_addr);
6157 if (ret)
6158 return ret;
6159
6160 if (is_identity_remap)
6161 identity_count_delta++;
6162 }
6163
6164 /* If hole_end < remap_end, re-add the end of the remap item. */
6165 if (hole_end < remap_end) {
6166 ret = insert_remap_item(trans, path, hole_end,
6167 remap_end - hole_end,
6168 hole_end - remap_start + new_addr);
6169 if (ret)
6170 return ret;
6171
6172 if (is_identity_remap)
6173 identity_count_delta++;
6174 }
6175
6176 if (identity_count_delta != 0)
6177 adjust_identity_remap_count(trans, bg, identity_count_delta);
6178
6179 overlap_length = min_t(u64, hole_end, remap_end) -
6180 max_t(u64, hole_start, remap_start);
6181
6182 if (!is_identity_remap) {
6183 struct btrfs_block_group *dest_bg;
6184
6185 dest_bg = btrfs_lookup_block_group(fs_info, new_addr);
6186 if (unlikely(!dest_bg))
6187 return -EUCLEAN;
6188
6189 adjust_block_group_remap_bytes(trans, dest_bg, -overlap_length);
6190 btrfs_put_block_group(dest_bg);
6191 ret = btrfs_add_to_free_space_tree(trans,
6192 hole_start - remap_start + new_addr,
6193 overlap_length);
6194 if (ret)
6195 return ret;
6196 }
6197
6198 ret = overlap_length;
6199
6200 return ret;
6201 }
6202
6203 /*
6204 * Return 1 if remove_range_from_remap_tree() has been called successfully,
6205 * 0 if block group wasn't remapped, and a negative number on error.
6206 */
btrfs_remove_extent_from_remap_tree(struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 bytenr,u64 num_bytes)6207 int btrfs_remove_extent_from_remap_tree(struct btrfs_trans_handle *trans,
6208 struct btrfs_path *path,
6209 u64 bytenr, u64 num_bytes)
6210 {
6211 struct btrfs_fs_info *fs_info = trans->fs_info;
6212 struct btrfs_key key, found_key;
6213 struct extent_buffer *leaf;
6214 struct btrfs_block_group *bg;
6215 int ret, length;
6216
6217 if (!(btrfs_super_incompat_flags(fs_info->super_copy) &
6218 BTRFS_FEATURE_INCOMPAT_REMAP_TREE))
6219 return 0;
6220
6221 bg = btrfs_lookup_block_group(fs_info, bytenr);
6222 if (!bg)
6223 return 0;
6224
6225 mutex_lock(&fs_info->remap_mutex);
6226
6227 if (!(bg->flags & BTRFS_BLOCK_GROUP_REMAPPED)) {
6228 mutex_unlock(&fs_info->remap_mutex);
6229 btrfs_put_block_group(bg);
6230 return 0;
6231 }
6232
6233 do {
6234 key.objectid = bytenr;
6235 key.type = (u8)-1;
6236 key.offset = (u64)-1;
6237
6238 ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, -1, 1);
6239 if (ret < 0)
6240 goto end;
6241
6242 leaf = path->nodes[0];
6243 if (path->slots[0] == 0) {
6244 ret = -ENOENT;
6245 goto end;
6246 }
6247
6248 path->slots[0]--;
6249
6250 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6251
6252 if (found_key.type != BTRFS_IDENTITY_REMAP_KEY &&
6253 found_key.type != BTRFS_REMAP_KEY) {
6254 ret = -ENOENT;
6255 goto end;
6256 }
6257
6258 if (bytenr < found_key.objectid ||
6259 bytenr >= found_key.objectid + found_key.offset) {
6260 ret = -ENOENT;
6261 goto end;
6262 }
6263
6264 length = remove_range_from_remap_tree(trans, path, bg, bytenr, num_bytes);
6265 if (length < 0) {
6266 ret = length;
6267 goto end;
6268 }
6269
6270 bytenr += length;
6271 num_bytes -= length;
6272 } while (num_bytes > 0);
6273
6274 ret = 1;
6275
6276 end:
6277 mutex_unlock(&fs_info->remap_mutex);
6278
6279 btrfs_put_block_group(bg);
6280 btrfs_release_path(path);
6281
6282 return ret;
6283 }
6284