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