OSDN Git Service

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