~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/btrfs/relocation.c

Version: ~ [ linux-5.17-rc1 ] ~ [ linux-5.16.2 ] ~ [ linux-5.15.16 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.93 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.173 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.225 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.262 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.297 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.299 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.18.140 ] ~ [ linux-3.16.85 ] ~ [ linux-3.14.79 ] ~ [ linux-3.12.74 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp