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