btrfs-progs: backref: push state tracking into a helper structure
[platform/upstream/btrfs-progs.git] / backref.c
1 /*
2  * Copyright (C) 2011 STRATO.  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 "kerncompat.h"
20 #include "ctree.h"
21 #include "disk-io.h"
22 #include "backref.h"
23 #include "kernel-shared/ulist.h"
24 #include "transaction.h"
25 #include "internal.h"
26
27 #define pr_debug(...) do { } while (0)
28
29 struct extent_inode_elem {
30         u64 inum;
31         u64 offset;
32         struct extent_inode_elem *next;
33 };
34
35 static int check_extent_in_eb(struct btrfs_key *key, struct extent_buffer *eb,
36                                 struct btrfs_file_extent_item *fi,
37                                 u64 extent_item_pos,
38                                 struct extent_inode_elem **eie)
39 {
40         u64 offset = 0;
41         struct extent_inode_elem *e;
42
43         if (!btrfs_file_extent_compression(eb, fi) &&
44             !btrfs_file_extent_encryption(eb, fi) &&
45             !btrfs_file_extent_other_encoding(eb, fi)) {
46                 u64 data_offset;
47                 u64 data_len;
48
49                 data_offset = btrfs_file_extent_offset(eb, fi);
50                 data_len = btrfs_file_extent_num_bytes(eb, fi);
51
52                 if (extent_item_pos < data_offset ||
53                     extent_item_pos >= data_offset + data_len)
54                         return 1;
55                 offset = extent_item_pos - data_offset;
56         }
57
58         e = kmalloc(sizeof(*e), GFP_NOFS);
59         if (!e)
60                 return -ENOMEM;
61
62         e->next = *eie;
63         e->inum = key->objectid;
64         e->offset = key->offset + offset;
65         *eie = e;
66
67         return 0;
68 }
69
70 static void free_inode_elem_list(struct extent_inode_elem *eie)
71 {
72         struct extent_inode_elem *eie_next;
73
74         for (; eie; eie = eie_next) {
75                 eie_next = eie->next;
76                 kfree(eie);
77         }
78 }
79
80 static int find_extent_in_eb(struct extent_buffer *eb, u64 wanted_disk_byte,
81                                 u64 extent_item_pos,
82                                 struct extent_inode_elem **eie)
83 {
84         u64 disk_byte;
85         struct btrfs_key key;
86         struct btrfs_file_extent_item *fi;
87         int slot;
88         int nritems;
89         int extent_type;
90         int ret;
91
92         /*
93          * from the shared data ref, we only have the leaf but we need
94          * the key. thus, we must look into all items and see that we
95          * find one (some) with a reference to our extent item.
96          */
97         nritems = btrfs_header_nritems(eb);
98         for (slot = 0; slot < nritems; ++slot) {
99                 btrfs_item_key_to_cpu(eb, &key, slot);
100                 if (key.type != BTRFS_EXTENT_DATA_KEY)
101                         continue;
102                 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
103                 extent_type = btrfs_file_extent_type(eb, fi);
104                 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
105                         continue;
106                 /* don't skip BTRFS_FILE_EXTENT_PREALLOC, we can handle that */
107                 disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
108                 if (disk_byte != wanted_disk_byte)
109                         continue;
110
111                 ret = check_extent_in_eb(&key, eb, fi, extent_item_pos, eie);
112                 if (ret < 0)
113                         return ret;
114         }
115
116         return 0;
117 }
118
119 /*
120  * this structure records all encountered refs on the way up to the root
121  */
122 struct __prelim_ref {
123         struct list_head list;
124         u64 root_id;
125         struct btrfs_key key_for_search;
126         int level;
127         int count;
128         struct extent_inode_elem *inode_list;
129         u64 parent;
130         u64 wanted_disk_byte;
131 };
132
133 struct pref_state {
134         struct list_head pending;
135 };
136
137 static void init_pref_state(struct pref_state *prefstate)
138 {
139         INIT_LIST_HEAD(&prefstate->pending);
140 }
141
142 /*
143  * the rules for all callers of this function are:
144  * - obtaining the parent is the goal
145  * - if you add a key, you must know that it is a correct key
146  * - if you cannot add the parent or a correct key, then we will look into the
147  *   block later to set a correct key
148  *
149  * delayed refs
150  * ============
151  *        backref type | shared | indirect | shared | indirect
152  * information         |   tree |     tree |   data |     data
153  * --------------------+--------+----------+--------+----------
154  *      parent logical |    y   |     -    |    -   |     -
155  *      key to resolve |    -   |     y    |    y   |     y
156  *  tree block logical |    -   |     -    |    -   |     -
157  *  root for resolving |    y   |     y    |    y   |     y
158  *
159  * - column 1:       we've the parent -> done
160  * - column 2, 3, 4: we use the key to find the parent
161  *
162  * on disk refs (inline or keyed)
163  * ==============================
164  *        backref type | shared | indirect | shared | indirect
165  * information         |   tree |     tree |   data |     data
166  * --------------------+--------+----------+--------+----------
167  *      parent logical |    y   |     -    |    y   |     -
168  *      key to resolve |    -   |     -    |    -   |     y
169  *  tree block logical |    y   |     y    |    y   |     y
170  *  root for resolving |    -   |     y    |    y   |     y
171  *
172  * - column 1, 3: we've the parent -> done
173  * - column 2:    we take the first key from the block to find the parent
174  *                (see __add_missing_keys)
175  * - column 4:    we use the key to find the parent
176  *
177  * additional information that's available but not required to find the parent
178  * block might help in merging entries to gain some speed.
179  */
180
181 static int __add_prelim_ref(struct pref_state *prefstate, u64 root_id,
182                             struct btrfs_key *key, int level,
183                             u64 parent, u64 wanted_disk_byte, int count,
184                             gfp_t gfp_mask)
185 {
186         struct list_head *head = &prefstate->pending;
187         struct __prelim_ref *ref;
188
189         if (root_id == BTRFS_DATA_RELOC_TREE_OBJECTID)
190                 return 0;
191
192         ref = kmalloc(sizeof(*ref), gfp_mask);
193         if (!ref)
194                 return -ENOMEM;
195
196         ref->root_id = root_id;
197         if (key)
198                 ref->key_for_search = *key;
199         else
200                 memset(&ref->key_for_search, 0, sizeof(ref->key_for_search));
201
202         ref->inode_list = NULL;
203         ref->level = level;
204         ref->count = count;
205         ref->parent = parent;
206         ref->wanted_disk_byte = wanted_disk_byte;
207         list_add_tail(&ref->list, head);
208
209         return 0;
210 }
211
212 static int add_all_parents(struct btrfs_root *root, struct btrfs_path *path,
213                            struct ulist *parents, struct __prelim_ref *ref,
214                            int level, u64 time_seq, const u64 *extent_item_pos,
215                            u64 total_refs)
216 {
217         int ret = 0;
218         int slot;
219         struct extent_buffer *eb;
220         struct btrfs_key key;
221         struct btrfs_key *key_for_search = &ref->key_for_search;
222         struct btrfs_file_extent_item *fi;
223         struct extent_inode_elem *eie = NULL, *old = NULL;
224         u64 disk_byte;
225         u64 wanted_disk_byte = ref->wanted_disk_byte;
226         u64 count = 0;
227
228         if (level != 0) {
229                 eb = path->nodes[level];
230                 ret = ulist_add(parents, eb->start, 0, GFP_NOFS);
231                 if (ret < 0)
232                         return ret;
233                 return 0;
234         }
235
236         /*
237          * We normally enter this function with the path already pointing to
238          * the first item to check. But sometimes, we may enter it with
239          * slot==nritems. In that case, go to the next leaf before we continue.
240          */
241         if (path->slots[0] >= btrfs_header_nritems(path->nodes[0]))
242                 ret = btrfs_next_leaf(root, path);
243
244         while (!ret && count < total_refs) {
245                 eb = path->nodes[0];
246                 slot = path->slots[0];
247
248                 btrfs_item_key_to_cpu(eb, &key, slot);
249
250                 if (key.objectid != key_for_search->objectid ||
251                     key.type != BTRFS_EXTENT_DATA_KEY)
252                         break;
253
254                 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
255                 disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
256
257                 if (disk_byte == wanted_disk_byte) {
258                         eie = NULL;
259                         old = NULL;
260                         count++;
261                         if (extent_item_pos) {
262                                 ret = check_extent_in_eb(&key, eb, fi,
263                                                 *extent_item_pos,
264                                                 &eie);
265                                 if (ret < 0)
266                                         break;
267                         }
268                         if (ret > 0)
269                                 goto next;
270                         ret = ulist_add_merge_ptr(parents, eb->start,
271                                                   eie, (void **)&old, GFP_NOFS);
272                         if (ret < 0)
273                                 break;
274                         if (!ret && extent_item_pos) {
275                                 while (old->next)
276                                         old = old->next;
277                                 old->next = eie;
278                         }
279                         eie = NULL;
280                 }
281 next:
282                 ret = btrfs_next_item(root, path);
283         }
284
285         if (ret > 0)
286                 ret = 0;
287         else if (ret < 0)
288                 free_inode_elem_list(eie);
289         return ret;
290 }
291
292 /*
293  * resolve an indirect backref in the form (root_id, key, level)
294  * to a logical address
295  */
296 static int __resolve_indirect_ref(struct btrfs_fs_info *fs_info,
297                                   struct btrfs_path *path, u64 time_seq,
298                                   struct __prelim_ref *ref,
299                                   struct ulist *parents,
300                                   const u64 *extent_item_pos, u64 total_refs)
301 {
302         struct btrfs_root *root;
303         struct btrfs_key root_key;
304         struct extent_buffer *eb;
305         int ret = 0;
306         int root_level;
307         int level = ref->level;
308
309         root_key.objectid = ref->root_id;
310         root_key.type = BTRFS_ROOT_ITEM_KEY;
311         root_key.offset = (u64)-1;
312
313         root = btrfs_read_fs_root(fs_info, &root_key);
314         if (IS_ERR(root)) {
315                 ret = PTR_ERR(root);
316                 goto out;
317         }
318
319         root_level = btrfs_root_level(&root->root_item);
320
321         if (root_level + 1 == level)
322                 goto out;
323
324         path->lowest_level = level;
325         ret = btrfs_search_slot(NULL, root, &ref->key_for_search, path, 0, 0);
326
327         pr_debug("search slot in root %llu (level %d, ref count %d) returned "
328                  "%d for key (%llu %u %llu)\n",
329                  ref->root_id, level, ref->count, ret,
330                  ref->key_for_search.objectid, ref->key_for_search.type,
331                  ref->key_for_search.offset);
332         if (ret < 0)
333                 goto out;
334
335         eb = path->nodes[level];
336         while (!eb) {
337                 if (!level) {
338                         ret = 1;
339                         WARN_ON(1);
340                         goto out;
341                 }
342                 level--;
343                 eb = path->nodes[level];
344         }
345
346         ret = add_all_parents(root, path, parents, ref, level, time_seq,
347                               extent_item_pos, total_refs);
348 out:
349         path->lowest_level = 0;
350         btrfs_release_path(path);
351         return ret;
352 }
353
354 /*
355  * resolve all indirect backrefs from the list
356  */
357 static int __resolve_indirect_refs(struct btrfs_fs_info *fs_info,
358                                    struct pref_state *prefstate,
359                                    struct btrfs_path *path, u64 time_seq,
360                                    const u64 *extent_item_pos, u64 total_refs)
361 {
362         struct list_head *head = &prefstate->pending;
363         int err;
364         int ret = 0;
365         struct __prelim_ref *ref;
366         struct __prelim_ref *ref_safe;
367         struct __prelim_ref *new_ref;
368         struct ulist *parents;
369         struct ulist_node *node;
370         struct ulist_iterator uiter;
371
372         parents = ulist_alloc(GFP_NOFS);
373         if (!parents)
374                 return -ENOMEM;
375
376         /*
377          * _safe allows us to insert directly after the current item without
378          * iterating over the newly inserted items.
379          * we're also allowed to re-assign ref during iteration.
380          */
381         list_for_each_entry_safe(ref, ref_safe, head, list) {
382                 if (ref->parent)        /* already direct */
383                         continue;
384                 if (ref->count == 0)
385                         continue;
386                 err = __resolve_indirect_ref(fs_info, path, time_seq, ref,
387                                              parents, extent_item_pos,
388                                              total_refs);
389                 /*
390                  * we can only tolerate ENOENT,otherwise,we should catch error
391                  * and return directly.
392                  */
393                 if (err == -ENOENT) {
394                         continue;
395                 } else if (err) {
396                         ret = err;
397                         goto out;
398                 }
399
400                 /* we put the first parent into the ref at hand */
401                 ULIST_ITER_INIT(&uiter);
402                 node = ulist_next(parents, &uiter);
403                 ref->parent = node ? node->val : 0;
404                 ref->inode_list = node ?
405                         (struct extent_inode_elem *)(uintptr_t)node->aux : NULL;
406
407                 /* additional parents require new refs being added here */
408                 while ((node = ulist_next(parents, &uiter))) {
409                         new_ref = kmalloc(sizeof(*new_ref), GFP_NOFS);
410                         if (!new_ref) {
411                                 ret = -ENOMEM;
412                                 goto out;
413                         }
414                         memcpy(new_ref, ref, sizeof(*ref));
415                         new_ref->parent = node->val;
416                         new_ref->inode_list = (struct extent_inode_elem *)
417                                                         (uintptr_t)node->aux;
418                         list_add(&new_ref->list, &ref->list);
419                 }
420                 ulist_reinit(parents);
421         }
422 out:
423         ulist_free(parents);
424         return ret;
425 }
426
427 static inline int ref_for_same_block(struct __prelim_ref *ref1,
428                                      struct __prelim_ref *ref2)
429 {
430         if (ref1->level != ref2->level)
431                 return 0;
432         if (ref1->root_id != ref2->root_id)
433                 return 0;
434         if (ref1->key_for_search.type != ref2->key_for_search.type)
435                 return 0;
436         if (ref1->key_for_search.objectid != ref2->key_for_search.objectid)
437                 return 0;
438         if (ref1->key_for_search.offset != ref2->key_for_search.offset)
439                 return 0;
440         if (ref1->parent != ref2->parent)
441                 return 0;
442
443         return 1;
444 }
445
446 /*
447  * read tree blocks and add keys where required.
448  */
449 static int __add_missing_keys(struct btrfs_fs_info *fs_info,
450                               struct pref_state *prefstate)
451 {
452         struct list_head *head = &prefstate->pending;
453         struct list_head *pos;
454         struct extent_buffer *eb;
455
456         list_for_each(pos, head) {
457                 struct __prelim_ref *ref;
458                 ref = list_entry(pos, struct __prelim_ref, list);
459
460                 if (ref->parent)
461                         continue;
462                 if (ref->key_for_search.type)
463                         continue;
464                 BUG_ON(!ref->wanted_disk_byte);
465                 eb = read_tree_block(fs_info, ref->wanted_disk_byte, 0);
466                 if (!extent_buffer_uptodate(eb)) {
467                         free_extent_buffer(eb);
468                         return -EIO;
469                 }
470                 if (btrfs_header_level(eb) == 0)
471                         btrfs_item_key_to_cpu(eb, &ref->key_for_search, 0);
472                 else
473                         btrfs_node_key_to_cpu(eb, &ref->key_for_search, 0);
474                 free_extent_buffer(eb);
475         }
476         return 0;
477 }
478
479 /*
480  * merge two lists of backrefs and adjust counts accordingly
481  *
482  * mode = 1: merge identical keys, if key is set
483  *    FIXME: if we add more keys in __add_prelim_ref, we can merge more here.
484  *           additionally, we could even add a key range for the blocks we
485  *           looked into to merge even more (-> replace unresolved refs by those
486  *           having a parent).
487  * mode = 2: merge identical parents
488  */
489 static void __merge_refs(struct pref_state *prefstate, int mode)
490 {
491         struct list_head *head = &prefstate->pending;
492         struct list_head *pos1;
493
494         list_for_each(pos1, head) {
495                 struct list_head *n2;
496                 struct list_head *pos2;
497                 struct __prelim_ref *ref1;
498
499                 ref1 = list_entry(pos1, struct __prelim_ref, list);
500
501                 for (pos2 = pos1->next, n2 = pos2->next; pos2 != head;
502                      pos2 = n2, n2 = pos2->next) {
503                         struct __prelim_ref *ref2;
504                         struct __prelim_ref *xchg;
505                         struct extent_inode_elem *eie;
506
507                         ref2 = list_entry(pos2, struct __prelim_ref, list);
508
509                         if (mode == 1) {
510                                 if (!ref_for_same_block(ref1, ref2))
511                                         continue;
512                                 if (!ref1->parent && ref2->parent) {
513                                         xchg = ref1;
514                                         ref1 = ref2;
515                                         ref2 = xchg;
516                                 }
517                         } else {
518                                 if (ref1->parent != ref2->parent)
519                                         continue;
520                         }
521
522                         eie = ref1->inode_list;
523                         while (eie && eie->next)
524                                 eie = eie->next;
525                         if (eie)
526                                 eie->next = ref2->inode_list;
527                         else
528                                 ref1->inode_list = ref2->inode_list;
529                         ref1->count += ref2->count;
530
531                         list_del(&ref2->list);
532                         kfree(ref2);
533                 }
534
535         }
536 }
537
538 /*
539  * add all inline backrefs for bytenr to the list
540  */
541 static int __add_inline_refs(struct btrfs_fs_info *fs_info,
542                              struct pref_state *prefstate,
543                              struct btrfs_path *path, u64 bytenr,
544                              int *info_level, u64 *total_refs)
545 {
546         int ret = 0;
547         int slot;
548         struct extent_buffer *leaf;
549         struct btrfs_key key;
550         struct btrfs_key found_key;
551         unsigned long ptr;
552         unsigned long end;
553         struct btrfs_extent_item *ei;
554         u64 flags;
555         u64 item_size;
556         /*
557          * enumerate all inline refs
558          */
559         leaf = path->nodes[0];
560         slot = path->slots[0];
561
562         item_size = btrfs_item_size_nr(leaf, slot);
563         BUG_ON(item_size < sizeof(*ei));
564
565         ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
566         flags = btrfs_extent_flags(leaf, ei);
567         *total_refs += btrfs_extent_refs(leaf, ei);
568         btrfs_item_key_to_cpu(leaf, &found_key, slot);
569
570         ptr = (unsigned long)(ei + 1);
571         end = (unsigned long)ei + item_size;
572
573         if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
574             flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
575                 struct btrfs_tree_block_info *info;
576
577                 info = (struct btrfs_tree_block_info *)ptr;
578                 *info_level = btrfs_tree_block_level(leaf, info);
579                 ptr += sizeof(struct btrfs_tree_block_info);
580                 BUG_ON(ptr > end);
581         } else if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
582                 *info_level = found_key.offset;
583         } else {
584                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
585         }
586
587         while (ptr < end) {
588                 struct btrfs_extent_inline_ref *iref;
589                 u64 offset;
590                 int type;
591
592                 iref = (struct btrfs_extent_inline_ref *)ptr;
593                 type = btrfs_extent_inline_ref_type(leaf, iref);
594                 offset = btrfs_extent_inline_ref_offset(leaf, iref);
595
596                 switch (type) {
597                 case BTRFS_SHARED_BLOCK_REF_KEY:
598                         ret = __add_prelim_ref(prefstate, 0, NULL,
599                                                 *info_level + 1, offset,
600                                                 bytenr, 1, GFP_NOFS);
601                         break;
602                 case BTRFS_SHARED_DATA_REF_KEY: {
603                         struct btrfs_shared_data_ref *sdref;
604                         int count;
605
606                         sdref = (struct btrfs_shared_data_ref *)(iref + 1);
607                         count = btrfs_shared_data_ref_count(leaf, sdref);
608                         ret = __add_prelim_ref(prefstate, 0, NULL, 0, offset,
609                                                bytenr, count, GFP_NOFS);
610                         break;
611                 }
612                 case BTRFS_TREE_BLOCK_REF_KEY:
613                         ret = __add_prelim_ref(prefstate, offset, NULL,
614                                                *info_level + 1, 0,
615                                                bytenr, 1, GFP_NOFS);
616                         break;
617                 case BTRFS_EXTENT_DATA_REF_KEY: {
618                         struct btrfs_extent_data_ref *dref;
619                         int count;
620                         u64 root;
621
622                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
623                         count = btrfs_extent_data_ref_count(leaf, dref);
624                         key.objectid = btrfs_extent_data_ref_objectid(leaf,
625                                                                       dref);
626                         key.type = BTRFS_EXTENT_DATA_KEY;
627                         key.offset = btrfs_extent_data_ref_offset(leaf, dref);
628                         root = btrfs_extent_data_ref_root(leaf, dref);
629                         ret = __add_prelim_ref(prefstate, root, &key, 0, 0,
630                                                bytenr, count, GFP_NOFS);
631                         break;
632                 }
633                 default:
634                         WARN_ON(1);
635                 }
636                 if (ret)
637                         return ret;
638                 ptr += btrfs_extent_inline_ref_size(type);
639         }
640
641         return 0;
642 }
643
644 /*
645  * add all non-inline backrefs for bytenr to the list
646  */
647 static int __add_keyed_refs(struct btrfs_fs_info *fs_info,
648                             struct pref_state *prefstate,
649                             struct btrfs_path *path, u64 bytenr,
650                             int info_level)
651 {
652         struct btrfs_root *extent_root = fs_info->extent_root;
653         int ret;
654         int slot;
655         struct extent_buffer *leaf;
656         struct btrfs_key key;
657
658         while (1) {
659                 ret = btrfs_next_item(extent_root, path);
660                 if (ret < 0)
661                         break;
662                 if (ret) {
663                         ret = 0;
664                         break;
665                 }
666
667                 slot = path->slots[0];
668                 leaf = path->nodes[0];
669                 btrfs_item_key_to_cpu(leaf, &key, slot);
670
671                 if (key.objectid != bytenr)
672                         break;
673                 if (key.type < BTRFS_TREE_BLOCK_REF_KEY)
674                         continue;
675                 if (key.type > BTRFS_SHARED_DATA_REF_KEY)
676                         break;
677
678                 switch (key.type) {
679                 case BTRFS_SHARED_BLOCK_REF_KEY:
680                         ret = __add_prelim_ref(prefstate, 0, NULL,
681                                                 info_level + 1, key.offset,
682                                                 bytenr, 1, GFP_NOFS);
683                         break;
684                 case BTRFS_SHARED_DATA_REF_KEY: {
685                         struct btrfs_shared_data_ref *sdref;
686                         int count;
687
688                         sdref = btrfs_item_ptr(leaf, slot,
689                                               struct btrfs_shared_data_ref);
690                         count = btrfs_shared_data_ref_count(leaf, sdref);
691                         ret = __add_prelim_ref(prefstate, 0, NULL, 0, key.offset,
692                                                 bytenr, count, GFP_NOFS);
693                         break;
694                 }
695                 case BTRFS_TREE_BLOCK_REF_KEY:
696                         ret = __add_prelim_ref(prefstate, key.offset, NULL,
697                                                info_level + 1, 0,
698                                                bytenr, 1, GFP_NOFS);
699                         break;
700                 case BTRFS_EXTENT_DATA_REF_KEY: {
701                         struct btrfs_extent_data_ref *dref;
702                         int count;
703                         u64 root;
704
705                         dref = btrfs_item_ptr(leaf, slot,
706                                               struct btrfs_extent_data_ref);
707                         count = btrfs_extent_data_ref_count(leaf, dref);
708                         key.objectid = btrfs_extent_data_ref_objectid(leaf,
709                                                                       dref);
710                         key.type = BTRFS_EXTENT_DATA_KEY;
711                         key.offset = btrfs_extent_data_ref_offset(leaf, dref);
712                         root = btrfs_extent_data_ref_root(leaf, dref);
713                         ret = __add_prelim_ref(prefstate, root, &key, 0, 0,
714                                                bytenr, count, GFP_NOFS);
715                         break;
716                 }
717                 default:
718                         WARN_ON(1);
719                 }
720                 if (ret)
721                         return ret;
722
723         }
724
725         return ret;
726 }
727
728 /*
729  * this adds all existing backrefs (inline backrefs, backrefs and delayed
730  * refs) for the given bytenr to the refs list, merges duplicates and resolves
731  * indirect refs to their parent bytenr.
732  * When roots are found, they're added to the roots list
733  *
734  * FIXME some caching might speed things up
735  */
736 static int find_parent_nodes(struct btrfs_trans_handle *trans,
737                              struct btrfs_fs_info *fs_info, u64 bytenr,
738                              u64 time_seq, struct ulist *refs,
739                              struct ulist *roots, const u64 *extent_item_pos)
740 {
741         struct btrfs_key key;
742         struct btrfs_path *path;
743         int info_level = 0;
744         int ret;
745         struct pref_state prefstate;
746         struct __prelim_ref *ref;
747         struct extent_inode_elem *eie = NULL;
748         u64 total_refs = 0;
749
750         init_pref_state(&prefstate);
751
752         key.objectid = bytenr;
753         key.offset = (u64)-1;
754         if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
755                 key.type = BTRFS_METADATA_ITEM_KEY;
756         else
757                 key.type = BTRFS_EXTENT_ITEM_KEY;
758
759         path = btrfs_alloc_path();
760         if (!path)
761                 return -ENOMEM;
762
763         ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
764         if (ret < 0)
765                 goto out;
766         BUG_ON(ret == 0);
767
768         if (path->slots[0]) {
769                 struct extent_buffer *leaf;
770                 int slot;
771
772                 path->slots[0]--;
773                 leaf = path->nodes[0];
774                 slot = path->slots[0];
775                 btrfs_item_key_to_cpu(leaf, &key, slot);
776                 if (key.objectid == bytenr &&
777                     (key.type == BTRFS_EXTENT_ITEM_KEY ||
778                      key.type == BTRFS_METADATA_ITEM_KEY)) {
779                         ret = __add_inline_refs(fs_info, &prefstate, path,
780                                                 bytenr, &info_level,
781                                                 &total_refs);
782                         if (ret)
783                                 goto out;
784                         ret = __add_keyed_refs(fs_info, &prefstate, path,
785                                                bytenr, info_level);
786                         if (ret)
787                                 goto out;
788                 }
789         }
790         btrfs_release_path(path);
791
792         ret = __add_missing_keys(fs_info, &prefstate);
793         if (ret)
794                 goto out;
795
796         __merge_refs(&prefstate, 1);
797
798         ret = __resolve_indirect_refs(fs_info, &prefstate, path, time_seq,
799                                       extent_item_pos, total_refs);
800         if (ret)
801                 goto out;
802
803         __merge_refs(&prefstate, 2);
804
805         while (!list_empty(&prefstate.pending)) {
806                 ref = list_first_entry(&prefstate.pending,
807                                        struct __prelim_ref, list);
808                 WARN_ON(ref->count < 0);
809                 if (roots && ref->count && ref->root_id && ref->parent == 0) {
810                         /* no parent == root of tree */
811                         ret = ulist_add(roots, ref->root_id, 0, GFP_NOFS);
812                         if (ret < 0)
813                                 goto out;
814                 }
815                 if (ref->count && ref->parent) {
816                         if (extent_item_pos && !ref->inode_list &&
817                             ref->level == 0) {
818                                 struct extent_buffer *eb;
819
820                                 eb = read_tree_block(fs_info, ref->parent, 0);
821                                 if (!extent_buffer_uptodate(eb)) {
822                                         free_extent_buffer(eb);
823                                         ret = -EIO;
824                                         goto out;
825                                 }
826                                 ret = find_extent_in_eb(eb, bytenr,
827                                                         *extent_item_pos, &eie);
828                                 free_extent_buffer(eb);
829                                 if (ret < 0)
830                                         goto out;
831                                 ref->inode_list = eie;
832                         }
833                         ret = ulist_add_merge_ptr(refs, ref->parent,
834                                                   ref->inode_list,
835                                                   (void **)&eie, GFP_NOFS);
836                         if (ret < 0)
837                                 goto out;
838                         if (!ret && extent_item_pos) {
839                                 /*
840                                  * we've recorded that parent, so we must extend
841                                  * its inode list here
842                                  */
843                                 BUG_ON(!eie);
844                                 while (eie->next)
845                                         eie = eie->next;
846                                 eie->next = ref->inode_list;
847                         }
848                         eie = NULL;
849                 }
850                 list_del(&ref->list);
851                 kfree(ref);
852         }
853
854 out:
855         btrfs_free_path(path);
856         while (!list_empty(&prefstate.pending)) {
857                 ref = list_first_entry(&prefstate.pending,
858                                        struct __prelim_ref, list);
859                 list_del(&ref->list);
860                 kfree(ref);
861         }
862         if (ret < 0)
863                 free_inode_elem_list(eie);
864         return ret;
865 }
866
867 static void free_leaf_list(struct ulist *blocks)
868 {
869         struct ulist_node *node = NULL;
870         struct extent_inode_elem *eie;
871         struct ulist_iterator uiter;
872
873         ULIST_ITER_INIT(&uiter);
874         while ((node = ulist_next(blocks, &uiter))) {
875                 if (!node->aux)
876                         continue;
877                 eie = (struct extent_inode_elem *)(uintptr_t)node->aux;
878                 free_inode_elem_list(eie);
879                 node->aux = 0;
880         }
881
882         ulist_free(blocks);
883 }
884
885 /*
886  * Finds all leafs with a reference to the specified combination of bytenr and
887  * offset. key_list_head will point to a list of corresponding keys (caller must
888  * free each list element). The leafs will be stored in the leafs ulist, which
889  * must be freed with ulist_free.
890  *
891  * returns 0 on success, <0 on error
892  */
893 static int btrfs_find_all_leafs(struct btrfs_trans_handle *trans,
894                                 struct btrfs_fs_info *fs_info, u64 bytenr,
895                                 u64 time_seq, struct ulist **leafs,
896                                 const u64 *extent_item_pos)
897 {
898         int ret;
899
900         *leafs = ulist_alloc(GFP_NOFS);
901         if (!*leafs)
902                 return -ENOMEM;
903
904         ret = find_parent_nodes(trans, fs_info, bytenr,
905                                 time_seq, *leafs, NULL, extent_item_pos);
906         if (ret < 0 && ret != -ENOENT) {
907                 free_leaf_list(*leafs);
908                 return ret;
909         }
910
911         return 0;
912 }
913
914 /*
915  * walk all backrefs for a given extent to find all roots that reference this
916  * extent. Walking a backref means finding all extents that reference this
917  * extent and in turn walk the backrefs of those, too. Naturally this is a
918  * recursive process, but here it is implemented in an iterative fashion: We
919  * find all referencing extents for the extent in question and put them on a
920  * list. In turn, we find all referencing extents for those, further appending
921  * to the list. The way we iterate the list allows adding more elements after
922  * the current while iterating. The process stops when we reach the end of the
923  * list. Found roots are added to the roots list.
924  *
925  * returns 0 on success, < 0 on error.
926  */
927 static int __btrfs_find_all_roots(struct btrfs_trans_handle *trans,
928                                   struct btrfs_fs_info *fs_info, u64 bytenr,
929                                   u64 time_seq, struct ulist **roots)
930 {
931         struct ulist *tmp;
932         struct ulist_node *node = NULL;
933         struct ulist_iterator uiter;
934         int ret;
935
936         tmp = ulist_alloc(GFP_NOFS);
937         if (!tmp)
938                 return -ENOMEM;
939         *roots = ulist_alloc(GFP_NOFS);
940         if (!*roots) {
941                 ulist_free(tmp);
942                 return -ENOMEM;
943         }
944
945         ULIST_ITER_INIT(&uiter);
946         while (1) {
947                 ret = find_parent_nodes(trans, fs_info, bytenr,
948                                         time_seq, tmp, *roots, NULL);
949                 if (ret < 0 && ret != -ENOENT) {
950                         ulist_free(tmp);
951                         ulist_free(*roots);
952                         return ret;
953                 }
954                 node = ulist_next(tmp, &uiter);
955                 if (!node)
956                         break;
957                 bytenr = node->val;
958                 cond_resched();
959         }
960
961         ulist_free(tmp);
962         return 0;
963 }
964
965 int btrfs_find_all_roots(struct btrfs_trans_handle *trans,
966                          struct btrfs_fs_info *fs_info, u64 bytenr,
967                          u64 time_seq, struct ulist **roots)
968 {
969         return __btrfs_find_all_roots(trans, fs_info, bytenr, time_seq, roots);
970 }
971
972 /*
973  * this makes the path point to (inum INODE_ITEM ioff)
974  */
975 int inode_item_info(u64 inum, u64 ioff, struct btrfs_root *fs_root,
976                         struct btrfs_path *path)
977 {
978         struct btrfs_key key;
979         return btrfs_find_item(fs_root, path, inum, ioff,
980                         BTRFS_INODE_ITEM_KEY, &key);
981 }
982
983 static int inode_ref_info(u64 inum, u64 ioff, struct btrfs_root *fs_root,
984                                 struct btrfs_path *path,
985                                 struct btrfs_key *found_key)
986 {
987         return btrfs_find_item(fs_root, path, inum, ioff,
988                         BTRFS_INODE_REF_KEY, found_key);
989 }
990
991 int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
992                           u64 start_off, struct btrfs_path *path,
993                           struct btrfs_inode_extref **ret_extref,
994                           u64 *found_off)
995 {
996         int ret, slot;
997         struct btrfs_key key;
998         struct btrfs_key found_key;
999         struct btrfs_inode_extref *extref;
1000         struct extent_buffer *leaf;
1001         unsigned long ptr;
1002
1003         key.objectid = inode_objectid;
1004         key.type = BTRFS_INODE_EXTREF_KEY;
1005         key.offset = start_off;
1006
1007         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1008         if (ret < 0)
1009                 return ret;
1010
1011         while (1) {
1012                 leaf = path->nodes[0];
1013                 slot = path->slots[0];
1014                 if (slot >= btrfs_header_nritems(leaf)) {
1015                         /*
1016                          * If the item at offset is not found,
1017                          * btrfs_search_slot will point us to the slot
1018                          * where it should be inserted. In our case
1019                          * that will be the slot directly before the
1020                          * next INODE_REF_KEY_V2 item. In the case
1021                          * that we're pointing to the last slot in a
1022                          * leaf, we must move one leaf over.
1023                          */
1024                         ret = btrfs_next_leaf(root, path);
1025                         if (ret) {
1026                                 if (ret >= 1)
1027                                         ret = -ENOENT;
1028                                 break;
1029                         }
1030                         continue;
1031                 }
1032
1033                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1034
1035                 /*
1036                  * Check that we're still looking at an extended ref key for
1037                  * this particular objectid. If we have different
1038                  * objectid or type then there are no more to be found
1039                  * in the tree and we can exit.
1040                  */
1041                 ret = -ENOENT;
1042                 if (found_key.objectid != inode_objectid)
1043                         break;
1044                 if (found_key.type != BTRFS_INODE_EXTREF_KEY)
1045                         break;
1046
1047                 ret = 0;
1048                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1049                 extref = (struct btrfs_inode_extref *)ptr;
1050                 *ret_extref = extref;
1051                 if (found_off)
1052                         *found_off = found_key.offset;
1053                 break;
1054         }
1055
1056         return ret;
1057 }
1058
1059 /*
1060  * this iterates to turn a name (from iref/extref) into a full filesystem path.
1061  * Elements of the path are separated by '/' and the path is guaranteed to be
1062  * 0-terminated. the path is only given within the current file system.
1063  * Therefore, it never starts with a '/'. the caller is responsible to provide
1064  * "size" bytes in "dest". the dest buffer will be filled backwards. finally,
1065  * the start point of the resulting string is returned. this pointer is within
1066  * dest, normally.
1067  * in case the path buffer would overflow, the pointer is decremented further
1068  * as if output was written to the buffer, though no more output is actually
1069  * generated. that way, the caller can determine how much space would be
1070  * required for the path to fit into the buffer. in that case, the returned
1071  * value will be smaller than dest. callers must check this!
1072  */
1073 char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
1074                         u32 name_len, unsigned long name_off,
1075                         struct extent_buffer *eb_in, u64 parent,
1076                         char *dest, u32 size)
1077 {
1078         int slot;
1079         u64 next_inum;
1080         int ret;
1081         s64 bytes_left = ((s64)size) - 1;
1082         struct extent_buffer *eb = eb_in;
1083         struct btrfs_key found_key;
1084         struct btrfs_inode_ref *iref;
1085
1086         if (bytes_left >= 0)
1087                 dest[bytes_left] = '\0';
1088
1089         while (1) {
1090                 bytes_left -= name_len;
1091                 if (bytes_left >= 0)
1092                         read_extent_buffer(eb, dest + bytes_left,
1093                                            name_off, name_len);
1094                 if (eb != eb_in)
1095                         free_extent_buffer(eb);
1096                 ret = inode_ref_info(parent, 0, fs_root, path, &found_key);
1097                 if (ret > 0)
1098                         ret = -ENOENT;
1099                 if (ret)
1100                         break;
1101
1102                 next_inum = found_key.offset;
1103
1104                 /* regular exit ahead */
1105                 if (parent == next_inum)
1106                         break;
1107
1108                 slot = path->slots[0];
1109                 eb = path->nodes[0];
1110                 /* make sure we can use eb after releasing the path */
1111                 if (eb != eb_in)
1112                         eb->refs++;
1113                 btrfs_release_path(path);
1114                 iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1115
1116                 name_len = btrfs_inode_ref_name_len(eb, iref);
1117                 name_off = (unsigned long)(iref + 1);
1118
1119                 parent = next_inum;
1120                 --bytes_left;
1121                 if (bytes_left >= 0)
1122                         dest[bytes_left] = '/';
1123         }
1124
1125         btrfs_release_path(path);
1126
1127         if (ret)
1128                 return ERR_PTR(ret);
1129
1130         return dest + bytes_left;
1131 }
1132
1133 /*
1134  * this makes the path point to (logical EXTENT_ITEM *)
1135  * returns BTRFS_EXTENT_FLAG_DATA for data, BTRFS_EXTENT_FLAG_TREE_BLOCK for
1136  * tree blocks and <0 on error.
1137  */
1138 int extent_from_logical(struct btrfs_fs_info *fs_info, u64 logical,
1139                         struct btrfs_path *path, struct btrfs_key *found_key,
1140                         u64 *flags_ret)
1141 {
1142         int ret;
1143         u64 flags;
1144         u64 size = 0;
1145         u32 item_size;
1146         struct extent_buffer *eb;
1147         struct btrfs_extent_item *ei;
1148         struct btrfs_key key;
1149
1150         if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1151                 key.type = BTRFS_METADATA_ITEM_KEY;
1152         else
1153                 key.type = BTRFS_EXTENT_ITEM_KEY;
1154         key.objectid = logical;
1155         key.offset = (u64)-1;
1156
1157         ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
1158         if (ret < 0)
1159                 return ret;
1160
1161         ret = btrfs_previous_extent_item(fs_info->extent_root, path, 0);
1162         if (ret) {
1163                 if (ret > 0)
1164                         ret = -ENOENT;
1165                 return ret;
1166         }
1167         btrfs_item_key_to_cpu(path->nodes[0], found_key, path->slots[0]);
1168         if (found_key->type == BTRFS_METADATA_ITEM_KEY)
1169                 size = fs_info->nodesize;
1170         else if (found_key->type == BTRFS_EXTENT_ITEM_KEY)
1171                 size = found_key->offset;
1172
1173         if (found_key->objectid > logical ||
1174             found_key->objectid + size <= logical) {
1175                 pr_debug("logical %llu is not within any extent\n", logical);
1176                 return -ENOENT;
1177         }
1178
1179         eb = path->nodes[0];
1180         item_size = btrfs_item_size_nr(eb, path->slots[0]);
1181         BUG_ON(item_size < sizeof(*ei));
1182
1183         ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
1184         flags = btrfs_extent_flags(eb, ei);
1185
1186         pr_debug("logical %llu is at position %llu within the extent (%llu "
1187                  "EXTENT_ITEM %llu) flags %#llx size %u\n",
1188                  logical, logical - found_key->objectid, found_key->objectid,
1189                  found_key->offset, flags, item_size);
1190
1191         if (flags_ret) {
1192                 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
1193                         *flags_ret = BTRFS_EXTENT_FLAG_TREE_BLOCK;
1194                 else if (flags & BTRFS_EXTENT_FLAG_DATA)
1195                         *flags_ret = BTRFS_EXTENT_FLAG_DATA;
1196                 else
1197                         BUG_ON(1);
1198                 return 0;
1199         } else {
1200                 WARN_ON(1);
1201                 return -EIO;
1202         }
1203 }
1204
1205 /*
1206  * helper function to iterate extent inline refs. ptr must point to a 0 value
1207  * for the first call and may be modified. it is used to track state.
1208  * if more refs exist, 0 is returned and the next call to
1209  * __get_extent_inline_ref must pass the modified ptr parameter to get the
1210  * next ref. after the last ref was processed, 1 is returned.
1211  * returns <0 on error
1212  */
1213 static int __get_extent_inline_ref(unsigned long *ptr, struct extent_buffer *eb,
1214                                    struct btrfs_key *key,
1215                                    struct btrfs_extent_item *ei, u32 item_size,
1216                                    struct btrfs_extent_inline_ref **out_eiref,
1217                                    int *out_type)
1218 {
1219         unsigned long end;
1220         u64 flags;
1221         struct btrfs_tree_block_info *info;
1222
1223         if (!*ptr) {
1224                 /* first call */
1225                 flags = btrfs_extent_flags(eb, ei);
1226                 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1227                         if (key->type == BTRFS_METADATA_ITEM_KEY) {
1228                                 /* a skinny metadata extent */
1229                                 *out_eiref =
1230                                      (struct btrfs_extent_inline_ref *)(ei + 1);
1231                         } else {
1232                                 WARN_ON(key->type != BTRFS_EXTENT_ITEM_KEY);
1233                                 info = (struct btrfs_tree_block_info *)(ei + 1);
1234                                 *out_eiref =
1235                                    (struct btrfs_extent_inline_ref *)(info + 1);
1236                         }
1237                 } else {
1238                         *out_eiref = (struct btrfs_extent_inline_ref *)(ei + 1);
1239                 }
1240                 *ptr = (unsigned long)*out_eiref;
1241                 if ((unsigned long)(*ptr) >= (unsigned long)ei + item_size)
1242                         return -ENOENT;
1243         }
1244
1245         end = (unsigned long)ei + item_size;
1246         *out_eiref = (struct btrfs_extent_inline_ref *)(*ptr);
1247         *out_type = btrfs_extent_inline_ref_type(eb, *out_eiref);
1248
1249         *ptr += btrfs_extent_inline_ref_size(*out_type);
1250         WARN_ON(*ptr > end);
1251         if (*ptr == end)
1252                 return 1; /* last */
1253
1254         return 0;
1255 }
1256
1257 /*
1258  * reads the tree block backref for an extent. tree level and root are returned
1259  * through out_level and out_root. ptr must point to a 0 value for the first
1260  * call and may be modified (see __get_extent_inline_ref comment).
1261  * returns 0 if data was provided, 1 if there was no more data to provide or
1262  * <0 on error.
1263  */
1264 int tree_backref_for_extent(unsigned long *ptr, struct extent_buffer *eb,
1265                             struct btrfs_key *key, struct btrfs_extent_item *ei,
1266                             u32 item_size, u64 *out_root, u8 *out_level)
1267 {
1268         int ret;
1269         int type;
1270         struct btrfs_tree_block_info *info;
1271         struct btrfs_extent_inline_ref *eiref;
1272
1273         if (*ptr == (unsigned long)-1)
1274                 return 1;
1275
1276         while (1) {
1277                 ret = __get_extent_inline_ref(ptr, eb, key, ei, item_size,
1278                                               &eiref, &type);
1279                 if (ret < 0)
1280                         return ret;
1281
1282                 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1283                     type == BTRFS_SHARED_BLOCK_REF_KEY)
1284                         break;
1285
1286                 if (ret == 1)
1287                         return 1;
1288         }
1289
1290         /* we can treat both ref types equally here */
1291         info = (struct btrfs_tree_block_info *)(ei + 1);
1292         *out_root = btrfs_extent_inline_ref_offset(eb, eiref);
1293         *out_level = btrfs_tree_block_level(eb, info);
1294
1295         if (ret == 1)
1296                 *ptr = (unsigned long)-1;
1297
1298         return 0;
1299 }
1300
1301 static int iterate_leaf_refs(struct extent_inode_elem *inode_list,
1302                                 u64 root, u64 extent_item_objectid,
1303                                 iterate_extent_inodes_t *iterate, void *ctx)
1304 {
1305         struct extent_inode_elem *eie;
1306         int ret = 0;
1307
1308         for (eie = inode_list; eie; eie = eie->next) {
1309                 pr_debug("ref for %llu resolved, key (%llu EXTEND_DATA %llu), "
1310                          "root %llu\n", extent_item_objectid,
1311                          eie->inum, eie->offset, root);
1312                 ret = iterate(eie->inum, eie->offset, root, ctx);
1313                 if (ret) {
1314                         pr_debug("stopping iteration for %llu due to ret=%d\n",
1315                                  extent_item_objectid, ret);
1316                         break;
1317                 }
1318         }
1319
1320         return ret;
1321 }
1322
1323 /*
1324  * calls iterate() for every inode that references the extent identified by
1325  * the given parameters.
1326  * when the iterator function returns a non-zero value, iteration stops.
1327  */
1328 int iterate_extent_inodes(struct btrfs_fs_info *fs_info,
1329                                 u64 extent_item_objectid, u64 extent_item_pos,
1330                                 int search_commit_root,
1331                                 iterate_extent_inodes_t *iterate, void *ctx)
1332 {
1333         int ret;
1334         struct btrfs_trans_handle *trans = NULL;
1335         struct ulist *refs = NULL;
1336         struct ulist *roots = NULL;
1337         struct ulist_node *ref_node = NULL;
1338         struct ulist_node *root_node = NULL;
1339         struct ulist_iterator ref_uiter;
1340         struct ulist_iterator root_uiter;
1341
1342         pr_debug("resolving all inodes for extent %llu\n",
1343                         extent_item_objectid);
1344
1345         ret = btrfs_find_all_leafs(trans, fs_info, extent_item_objectid,
1346                                    0, &refs, &extent_item_pos);
1347         if (ret)
1348                 goto out;
1349
1350         ULIST_ITER_INIT(&ref_uiter);
1351         while (!ret && (ref_node = ulist_next(refs, &ref_uiter))) {
1352                 ret = __btrfs_find_all_roots(trans, fs_info, ref_node->val,
1353                                              0, &roots);
1354                 if (ret)
1355                         break;
1356                 ULIST_ITER_INIT(&root_uiter);
1357                 while (!ret && (root_node = ulist_next(roots, &root_uiter))) {
1358                         pr_debug("root %llu references leaf %llu, data list "
1359                                  "%#llx\n", root_node->val, ref_node->val,
1360                                  ref_node->aux);
1361                         ret = iterate_leaf_refs((struct extent_inode_elem *)
1362                                                 (uintptr_t)ref_node->aux,
1363                                                 root_node->val,
1364                                                 extent_item_objectid,
1365                                                 iterate, ctx);
1366                 }
1367                 ulist_free(roots);
1368         }
1369
1370         free_leaf_list(refs);
1371 out:
1372         return ret;
1373 }
1374
1375 int iterate_inodes_from_logical(u64 logical, struct btrfs_fs_info *fs_info,
1376                                 struct btrfs_path *path,
1377                                 iterate_extent_inodes_t *iterate, void *ctx)
1378 {
1379         int ret;
1380         u64 extent_item_pos;
1381         u64 flags = 0;
1382         struct btrfs_key found_key;
1383         int search_commit_root = 0;
1384
1385         ret = extent_from_logical(fs_info, logical, path, &found_key, &flags);
1386         btrfs_release_path(path);
1387         if (ret < 0)
1388                 return ret;
1389         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
1390                 return -EINVAL;
1391
1392         extent_item_pos = logical - found_key.objectid;
1393         ret = iterate_extent_inodes(fs_info, found_key.objectid,
1394                                         extent_item_pos, search_commit_root,
1395                                         iterate, ctx);
1396
1397         return ret;
1398 }
1399
1400 typedef int (iterate_irefs_t)(u64 parent, u32 name_len, unsigned long name_off,
1401                               struct extent_buffer *eb, void *ctx);
1402
1403 static int iterate_inode_refs(u64 inum, struct btrfs_root *fs_root,
1404                               struct btrfs_path *path,
1405                               iterate_irefs_t *iterate, void *ctx)
1406 {
1407         int ret = 0;
1408         int slot;
1409         u32 cur;
1410         u32 len;
1411         u32 name_len;
1412         u64 parent = 0;
1413         int found = 0;
1414         struct extent_buffer *eb;
1415         struct btrfs_item *item;
1416         struct btrfs_inode_ref *iref;
1417         struct btrfs_key found_key;
1418
1419         while (!ret) {
1420                 ret = inode_ref_info(inum, parent ? parent+1 : 0, fs_root, path,
1421                                      &found_key);
1422                 if (ret < 0)
1423                         break;
1424                 if (ret) {
1425                         ret = found ? 0 : -ENOENT;
1426                         break;
1427                 }
1428                 ++found;
1429
1430                 parent = found_key.offset;
1431                 slot = path->slots[0];
1432                 eb = btrfs_clone_extent_buffer(path->nodes[0]);
1433                 if (!eb) {
1434                         ret = -ENOMEM;
1435                         break;
1436                 }
1437                 extent_buffer_get(eb);
1438                 btrfs_release_path(path);
1439
1440                 item = btrfs_item_nr(slot);
1441                 iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1442
1443                 for (cur = 0; cur < btrfs_item_size(eb, item); cur += len) {
1444                         name_len = btrfs_inode_ref_name_len(eb, iref);
1445                         /* path must be released before calling iterate()! */
1446                         pr_debug("following ref at offset %u for inode %llu in "
1447                                  "tree %llu\n", cur, found_key.objectid,
1448                                  fs_root->objectid);
1449                         ret = iterate(parent, name_len,
1450                                       (unsigned long)(iref + 1), eb, ctx);
1451                         if (ret)
1452                                 break;
1453                         len = sizeof(*iref) + name_len;
1454                         iref = (struct btrfs_inode_ref *)((char *)iref + len);
1455                 }
1456                 free_extent_buffer(eb);
1457         }
1458
1459         btrfs_release_path(path);
1460
1461         return ret;
1462 }
1463
1464 static int iterate_inode_extrefs(u64 inum, struct btrfs_root *fs_root,
1465                                  struct btrfs_path *path,
1466                                  iterate_irefs_t *iterate, void *ctx)
1467 {
1468         int ret;
1469         int slot;
1470         u64 offset = 0;
1471         u64 parent;
1472         int found = 0;
1473         struct extent_buffer *eb;
1474         struct btrfs_inode_extref *extref;
1475         struct extent_buffer *leaf;
1476         u32 item_size;
1477         u32 cur_offset;
1478         unsigned long ptr;
1479
1480         while (1) {
1481                 ret = btrfs_find_one_extref(fs_root, inum, offset, path, &extref,
1482                                             &offset);
1483                 if (ret < 0)
1484                         break;
1485                 if (ret) {
1486                         ret = found ? 0 : -ENOENT;
1487                         break;
1488                 }
1489                 ++found;
1490
1491                 slot = path->slots[0];
1492                 eb = btrfs_clone_extent_buffer(path->nodes[0]);
1493                 if (!eb) {
1494                         ret = -ENOMEM;
1495                         break;
1496                 }
1497                 extent_buffer_get(eb);
1498
1499                 btrfs_release_path(path);
1500
1501                 leaf = path->nodes[0];
1502                 item_size = btrfs_item_size_nr(leaf, slot);
1503                 ptr = btrfs_item_ptr_offset(leaf, slot);
1504                 cur_offset = 0;
1505
1506                 while (cur_offset < item_size) {
1507                         u32 name_len;
1508
1509                         extref = (struct btrfs_inode_extref *)(ptr + cur_offset);
1510                         parent = btrfs_inode_extref_parent(eb, extref);
1511                         name_len = btrfs_inode_extref_name_len(eb, extref);
1512                         ret = iterate(parent, name_len,
1513                                       (unsigned long)&extref->name, eb, ctx);
1514                         if (ret)
1515                                 break;
1516
1517                         cur_offset += btrfs_inode_extref_name_len(leaf, extref);
1518                         cur_offset += sizeof(*extref);
1519                 }
1520                 free_extent_buffer(eb);
1521
1522                 offset++;
1523         }
1524
1525         btrfs_release_path(path);
1526
1527         return ret;
1528 }
1529
1530 static int iterate_irefs(u64 inum, struct btrfs_root *fs_root,
1531                          struct btrfs_path *path, iterate_irefs_t *iterate,
1532                          void *ctx)
1533 {
1534         int ret;
1535         int found_refs = 0;
1536
1537         ret = iterate_inode_refs(inum, fs_root, path, iterate, ctx);
1538         if (!ret)
1539                 ++found_refs;
1540         else if (ret != -ENOENT)
1541                 return ret;
1542
1543         ret = iterate_inode_extrefs(inum, fs_root, path, iterate, ctx);
1544         if (ret == -ENOENT && found_refs)
1545                 return 0;
1546
1547         return ret;
1548 }
1549
1550 /*
1551  * returns 0 if the path could be dumped (probably truncated)
1552  * returns <0 in case of an error
1553  */
1554 static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
1555                          struct extent_buffer *eb, void *ctx)
1556 {
1557         struct inode_fs_paths *ipath = ctx;
1558         char *fspath;
1559         char *fspath_min;
1560         int i = ipath->fspath->elem_cnt;
1561         const int s_ptr = sizeof(char *);
1562         u32 bytes_left;
1563
1564         bytes_left = ipath->fspath->bytes_left > s_ptr ?
1565                                         ipath->fspath->bytes_left - s_ptr : 0;
1566
1567         fspath_min = (char *)ipath->fspath->val + (i + 1) * s_ptr;
1568         fspath = btrfs_ref_to_path(ipath->fs_root, ipath->btrfs_path, name_len,
1569                                    name_off, eb, inum, fspath_min, bytes_left);
1570         if (IS_ERR(fspath))
1571                 return PTR_ERR(fspath);
1572
1573         if (fspath > fspath_min) {
1574                 ipath->fspath->val[i] = (u64)(unsigned long)fspath;
1575                 ++ipath->fspath->elem_cnt;
1576                 ipath->fspath->bytes_left = fspath - fspath_min;
1577         } else {
1578                 ++ipath->fspath->elem_missed;
1579                 ipath->fspath->bytes_missing += fspath_min - fspath;
1580                 ipath->fspath->bytes_left = 0;
1581         }
1582
1583         return 0;
1584 }
1585
1586 /*
1587  * this dumps all file system paths to the inode into the ipath struct, provided
1588  * is has been created large enough. each path is zero-terminated and accessed
1589  * from ipath->fspath->val[i].
1590  * when it returns, there are ipath->fspath->elem_cnt number of paths available
1591  * in ipath->fspath->val[]. When the allocated space wasn't sufficient, the
1592  * number of missed paths is recorded in ipath->fspath->elem_missed, otherwise,
1593  * it's zero. ipath->fspath->bytes_missing holds the number of bytes that would
1594  * have been needed to return all paths.
1595  */
1596 int paths_from_inode(u64 inum, struct inode_fs_paths *ipath)
1597 {
1598         return iterate_irefs(inum, ipath->fs_root, ipath->btrfs_path,
1599                              inode_to_path, ipath);
1600 }
1601
1602 struct btrfs_data_container *init_data_container(u32 total_bytes)
1603 {
1604         struct btrfs_data_container *data;
1605         size_t alloc_bytes;
1606
1607         alloc_bytes = max_t(size_t, total_bytes, sizeof(*data));
1608         data = vmalloc(alloc_bytes);
1609         if (!data)
1610                 return ERR_PTR(-ENOMEM);
1611
1612         if (total_bytes >= sizeof(*data)) {
1613                 data->bytes_left = total_bytes - sizeof(*data);
1614                 data->bytes_missing = 0;
1615         } else {
1616                 data->bytes_missing = sizeof(*data) - total_bytes;
1617                 data->bytes_left = 0;
1618         }
1619
1620         data->elem_cnt = 0;
1621         data->elem_missed = 0;
1622
1623         return data;
1624 }
1625
1626 /*
1627  * allocates space to return multiple file system paths for an inode.
1628  * total_bytes to allocate are passed, note that space usable for actual path
1629  * information will be total_bytes - sizeof(struct inode_fs_paths).
1630  * the returned pointer must be freed with free_ipath() in the end.
1631  */
1632 struct inode_fs_paths *init_ipath(s32 total_bytes, struct btrfs_root *fs_root,
1633                                         struct btrfs_path *path)
1634 {
1635         struct inode_fs_paths *ifp;
1636         struct btrfs_data_container *fspath;
1637
1638         fspath = init_data_container(total_bytes);
1639         if (IS_ERR(fspath))
1640                 return (void *)fspath;
1641
1642         ifp = kmalloc(sizeof(*ifp), GFP_NOFS);
1643         if (!ifp) {
1644                 kfree(fspath);
1645                 return ERR_PTR(-ENOMEM);
1646         }
1647
1648         ifp->btrfs_path = path;
1649         ifp->fspath = fspath;
1650         ifp->fs_root = fs_root;
1651
1652         return ifp;
1653 }
1654
1655 void free_ipath(struct inode_fs_paths *ipath)
1656 {
1657         if (!ipath)
1658                 return;
1659         vfree(ipath->fspath);
1660         kfree(ipath);
1661 }