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