GNU Linux-libre 4.19.264-gnu1
[releases.git] / fs / btrfs / backref.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2011 STRATO.  All rights reserved.
4  */
5
6 #include <linux/mm.h>
7 #include <linux/rbtree.h>
8 #include <trace/events/btrfs.h>
9 #include "ctree.h"
10 #include "disk-io.h"
11 #include "backref.h"
12 #include "ulist.h"
13 #include "transaction.h"
14 #include "delayed-ref.h"
15 #include "locking.h"
16
17 /* Just an arbitrary number so we can be sure this happened */
18 #define BACKREF_FOUND_SHARED 6
19
20 struct extent_inode_elem {
21         u64 inum;
22         u64 offset;
23         struct extent_inode_elem *next;
24 };
25
26 static int check_extent_in_eb(const struct btrfs_key *key,
27                               const struct extent_buffer *eb,
28                               const struct btrfs_file_extent_item *fi,
29                               u64 extent_item_pos,
30                               struct extent_inode_elem **eie,
31                               bool ignore_offset)
32 {
33         u64 offset = 0;
34         struct extent_inode_elem *e;
35
36         if (!ignore_offset &&
37             !btrfs_file_extent_compression(eb, fi) &&
38             !btrfs_file_extent_encryption(eb, fi) &&
39             !btrfs_file_extent_other_encoding(eb, fi)) {
40                 u64 data_offset;
41                 u64 data_len;
42
43                 data_offset = btrfs_file_extent_offset(eb, fi);
44                 data_len = btrfs_file_extent_num_bytes(eb, fi);
45
46                 if (extent_item_pos < data_offset ||
47                     extent_item_pos >= data_offset + data_len)
48                         return 1;
49                 offset = extent_item_pos - data_offset;
50         }
51
52         e = kmalloc(sizeof(*e), GFP_NOFS);
53         if (!e)
54                 return -ENOMEM;
55
56         e->next = *eie;
57         e->inum = key->objectid;
58         e->offset = key->offset + offset;
59         *eie = e;
60
61         return 0;
62 }
63
64 static void free_inode_elem_list(struct extent_inode_elem *eie)
65 {
66         struct extent_inode_elem *eie_next;
67
68         for (; eie; eie = eie_next) {
69                 eie_next = eie->next;
70                 kfree(eie);
71         }
72 }
73
74 static int find_extent_in_eb(const struct extent_buffer *eb,
75                              u64 wanted_disk_byte, u64 extent_item_pos,
76                              struct extent_inode_elem **eie,
77                              bool ignore_offset)
78 {
79         u64 disk_byte;
80         struct btrfs_key key;
81         struct btrfs_file_extent_item *fi;
82         int slot;
83         int nritems;
84         int extent_type;
85         int ret;
86
87         /*
88          * from the shared data ref, we only have the leaf but we need
89          * the key. thus, we must look into all items and see that we
90          * find one (some) with a reference to our extent item.
91          */
92         nritems = btrfs_header_nritems(eb);
93         for (slot = 0; slot < nritems; ++slot) {
94                 btrfs_item_key_to_cpu(eb, &key, slot);
95                 if (key.type != BTRFS_EXTENT_DATA_KEY)
96                         continue;
97                 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
98                 extent_type = btrfs_file_extent_type(eb, fi);
99                 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
100                         continue;
101                 /* don't skip BTRFS_FILE_EXTENT_PREALLOC, we can handle that */
102                 disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
103                 if (disk_byte != wanted_disk_byte)
104                         continue;
105
106                 ret = check_extent_in_eb(&key, eb, fi, extent_item_pos, eie, ignore_offset);
107                 if (ret < 0)
108                         return ret;
109         }
110
111         return 0;
112 }
113
114 struct preftree {
115         struct rb_root root;
116         unsigned int count;
117 };
118
119 #define PREFTREE_INIT   { .root = RB_ROOT, .count = 0 }
120
121 struct preftrees {
122         struct preftree direct;    /* BTRFS_SHARED_[DATA|BLOCK]_REF_KEY */
123         struct preftree indirect;  /* BTRFS_[TREE_BLOCK|EXTENT_DATA]_REF_KEY */
124         struct preftree indirect_missing_keys;
125 };
126
127 /*
128  * Checks for a shared extent during backref search.
129  *
130  * The share_count tracks prelim_refs (direct and indirect) having a
131  * ref->count >0:
132  *  - incremented when a ref->count transitions to >0
133  *  - decremented when a ref->count transitions to <1
134  */
135 struct share_check {
136         u64 root_objectid;
137         u64 inum;
138         int share_count;
139         bool have_delayed_delete_refs;
140 };
141
142 static inline int extent_is_shared(struct share_check *sc)
143 {
144         return (sc && sc->share_count > 1) ? BACKREF_FOUND_SHARED : 0;
145 }
146
147 static struct kmem_cache *btrfs_prelim_ref_cache;
148
149 int __init btrfs_prelim_ref_init(void)
150 {
151         btrfs_prelim_ref_cache = kmem_cache_create("btrfs_prelim_ref",
152                                         sizeof(struct prelim_ref),
153                                         0,
154                                         SLAB_MEM_SPREAD,
155                                         NULL);
156         if (!btrfs_prelim_ref_cache)
157                 return -ENOMEM;
158         return 0;
159 }
160
161 void __cold btrfs_prelim_ref_exit(void)
162 {
163         kmem_cache_destroy(btrfs_prelim_ref_cache);
164 }
165
166 static void free_pref(struct prelim_ref *ref)
167 {
168         kmem_cache_free(btrfs_prelim_ref_cache, ref);
169 }
170
171 /*
172  * Return 0 when both refs are for the same block (and can be merged).
173  * A -1 return indicates ref1 is a 'lower' block than ref2, while 1
174  * indicates a 'higher' block.
175  */
176 static int prelim_ref_compare(struct prelim_ref *ref1,
177                               struct prelim_ref *ref2)
178 {
179         if (ref1->level < ref2->level)
180                 return -1;
181         if (ref1->level > ref2->level)
182                 return 1;
183         if (ref1->root_id < ref2->root_id)
184                 return -1;
185         if (ref1->root_id > ref2->root_id)
186                 return 1;
187         if (ref1->key_for_search.type < ref2->key_for_search.type)
188                 return -1;
189         if (ref1->key_for_search.type > ref2->key_for_search.type)
190                 return 1;
191         if (ref1->key_for_search.objectid < ref2->key_for_search.objectid)
192                 return -1;
193         if (ref1->key_for_search.objectid > ref2->key_for_search.objectid)
194                 return 1;
195         if (ref1->key_for_search.offset < ref2->key_for_search.offset)
196                 return -1;
197         if (ref1->key_for_search.offset > ref2->key_for_search.offset)
198                 return 1;
199         if (ref1->parent < ref2->parent)
200                 return -1;
201         if (ref1->parent > ref2->parent)
202                 return 1;
203
204         return 0;
205 }
206
207 static void update_share_count(struct share_check *sc, int oldcount,
208                                int newcount)
209 {
210         if ((!sc) || (oldcount == 0 && newcount < 1))
211                 return;
212
213         if (oldcount > 0 && newcount < 1)
214                 sc->share_count--;
215         else if (oldcount < 1 && newcount > 0)
216                 sc->share_count++;
217 }
218
219 /*
220  * Add @newref to the @root rbtree, merging identical refs.
221  *
222  * Callers should assume that newref has been freed after calling.
223  */
224 static void prelim_ref_insert(const struct btrfs_fs_info *fs_info,
225                               struct preftree *preftree,
226                               struct prelim_ref *newref,
227                               struct share_check *sc)
228 {
229         struct rb_root *root;
230         struct rb_node **p;
231         struct rb_node *parent = NULL;
232         struct prelim_ref *ref;
233         int result;
234
235         root = &preftree->root;
236         p = &root->rb_node;
237
238         while (*p) {
239                 parent = *p;
240                 ref = rb_entry(parent, struct prelim_ref, rbnode);
241                 result = prelim_ref_compare(ref, newref);
242                 if (result < 0) {
243                         p = &(*p)->rb_left;
244                 } else if (result > 0) {
245                         p = &(*p)->rb_right;
246                 } else {
247                         /* Identical refs, merge them and free @newref */
248                         struct extent_inode_elem *eie = ref->inode_list;
249
250                         while (eie && eie->next)
251                                 eie = eie->next;
252
253                         if (!eie)
254                                 ref->inode_list = newref->inode_list;
255                         else
256                                 eie->next = newref->inode_list;
257                         trace_btrfs_prelim_ref_merge(fs_info, ref, newref,
258                                                      preftree->count);
259                         /*
260                          * A delayed ref can have newref->count < 0.
261                          * The ref->count is updated to follow any
262                          * BTRFS_[ADD|DROP]_DELAYED_REF actions.
263                          */
264                         update_share_count(sc, ref->count,
265                                            ref->count + newref->count);
266                         ref->count += newref->count;
267                         free_pref(newref);
268                         return;
269                 }
270         }
271
272         update_share_count(sc, 0, newref->count);
273         preftree->count++;
274         trace_btrfs_prelim_ref_insert(fs_info, newref, NULL, preftree->count);
275         rb_link_node(&newref->rbnode, parent, p);
276         rb_insert_color(&newref->rbnode, root);
277 }
278
279 /*
280  * Release the entire tree.  We don't care about internal consistency so
281  * just free everything and then reset the tree root.
282  */
283 static void prelim_release(struct preftree *preftree)
284 {
285         struct prelim_ref *ref, *next_ref;
286
287         rbtree_postorder_for_each_entry_safe(ref, next_ref, &preftree->root,
288                                              rbnode)
289                 free_pref(ref);
290
291         preftree->root = RB_ROOT;
292         preftree->count = 0;
293 }
294
295 /*
296  * the rules for all callers of this function are:
297  * - obtaining the parent is the goal
298  * - if you add a key, you must know that it is a correct key
299  * - if you cannot add the parent or a correct key, then we will look into the
300  *   block later to set a correct key
301  *
302  * delayed refs
303  * ============
304  *        backref type | shared | indirect | shared | indirect
305  * information         |   tree |     tree |   data |     data
306  * --------------------+--------+----------+--------+----------
307  *      parent logical |    y   |     -    |    -   |     -
308  *      key to resolve |    -   |     y    |    y   |     y
309  *  tree block logical |    -   |     -    |    -   |     -
310  *  root for resolving |    y   |     y    |    y   |     y
311  *
312  * - column 1:       we've the parent -> done
313  * - column 2, 3, 4: we use the key to find the parent
314  *
315  * on disk refs (inline or keyed)
316  * ==============================
317  *        backref type | shared | indirect | shared | indirect
318  * information         |   tree |     tree |   data |     data
319  * --------------------+--------+----------+--------+----------
320  *      parent logical |    y   |     -    |    y   |     -
321  *      key to resolve |    -   |     -    |    -   |     y
322  *  tree block logical |    y   |     y    |    y   |     y
323  *  root for resolving |    -   |     y    |    y   |     y
324  *
325  * - column 1, 3: we've the parent -> done
326  * - column 2:    we take the first key from the block to find the parent
327  *                (see add_missing_keys)
328  * - column 4:    we use the key to find the parent
329  *
330  * additional information that's available but not required to find the parent
331  * block might help in merging entries to gain some speed.
332  */
333 static int add_prelim_ref(const struct btrfs_fs_info *fs_info,
334                           struct preftree *preftree, u64 root_id,
335                           const struct btrfs_key *key, int level, u64 parent,
336                           u64 wanted_disk_byte, int count,
337                           struct share_check *sc, gfp_t gfp_mask)
338 {
339         struct prelim_ref *ref;
340
341         if (root_id == BTRFS_DATA_RELOC_TREE_OBJECTID)
342                 return 0;
343
344         ref = kmem_cache_alloc(btrfs_prelim_ref_cache, gfp_mask);
345         if (!ref)
346                 return -ENOMEM;
347
348         ref->root_id = root_id;
349         if (key) {
350                 ref->key_for_search = *key;
351                 /*
352                  * We can often find data backrefs with an offset that is too
353                  * large (>= LLONG_MAX, maximum allowed file offset) due to
354                  * underflows when subtracting a file's offset with the data
355                  * offset of its corresponding extent data item. This can
356                  * happen for example in the clone ioctl.
357                  * So if we detect such case we set the search key's offset to
358                  * zero to make sure we will find the matching file extent item
359                  * at add_all_parents(), otherwise we will miss it because the
360                  * offset taken form the backref is much larger then the offset
361                  * of the file extent item. This can make us scan a very large
362                  * number of file extent items, but at least it will not make
363                  * us miss any.
364                  * This is an ugly workaround for a behaviour that should have
365                  * never existed, but it does and a fix for the clone ioctl
366                  * would touch a lot of places, cause backwards incompatibility
367                  * and would not fix the problem for extents cloned with older
368                  * kernels.
369                  */
370                 if (ref->key_for_search.type == BTRFS_EXTENT_DATA_KEY &&
371                     ref->key_for_search.offset >= LLONG_MAX)
372                         ref->key_for_search.offset = 0;
373         } else {
374                 memset(&ref->key_for_search, 0, sizeof(ref->key_for_search));
375         }
376
377         ref->inode_list = NULL;
378         ref->level = level;
379         ref->count = count;
380         ref->parent = parent;
381         ref->wanted_disk_byte = wanted_disk_byte;
382         prelim_ref_insert(fs_info, preftree, ref, sc);
383         return extent_is_shared(sc);
384 }
385
386 /* direct refs use root == 0, key == NULL */
387 static int add_direct_ref(const struct btrfs_fs_info *fs_info,
388                           struct preftrees *preftrees, int level, u64 parent,
389                           u64 wanted_disk_byte, int count,
390                           struct share_check *sc, gfp_t gfp_mask)
391 {
392         return add_prelim_ref(fs_info, &preftrees->direct, 0, NULL, level,
393                               parent, wanted_disk_byte, count, sc, gfp_mask);
394 }
395
396 /* indirect refs use parent == 0 */
397 static int add_indirect_ref(const struct btrfs_fs_info *fs_info,
398                             struct preftrees *preftrees, u64 root_id,
399                             const struct btrfs_key *key, int level,
400                             u64 wanted_disk_byte, int count,
401                             struct share_check *sc, gfp_t gfp_mask)
402 {
403         struct preftree *tree = &preftrees->indirect;
404
405         if (!key)
406                 tree = &preftrees->indirect_missing_keys;
407         return add_prelim_ref(fs_info, tree, root_id, key, level, 0,
408                               wanted_disk_byte, count, sc, gfp_mask);
409 }
410
411 static int add_all_parents(struct btrfs_root *root, struct btrfs_path *path,
412                            struct ulist *parents, struct prelim_ref *ref,
413                            int level, u64 time_seq, const u64 *extent_item_pos,
414                            u64 total_refs, bool ignore_offset)
415 {
416         int ret = 0;
417         int slot;
418         struct extent_buffer *eb;
419         struct btrfs_key key;
420         struct btrfs_key *key_for_search = &ref->key_for_search;
421         struct btrfs_file_extent_item *fi;
422         struct extent_inode_elem *eie = NULL, *old = NULL;
423         u64 disk_byte;
424         u64 wanted_disk_byte = ref->wanted_disk_byte;
425         u64 count = 0;
426
427         if (level != 0) {
428                 eb = path->nodes[level];
429                 ret = ulist_add(parents, eb->start, 0, GFP_NOFS);
430                 if (ret < 0)
431                         return ret;
432                 return 0;
433         }
434
435         /*
436          * We normally enter this function with the path already pointing to
437          * the first item to check. But sometimes, we may enter it with
438          * slot==nritems. In that case, go to the next leaf before we continue.
439          */
440         if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
441                 if (time_seq == SEQ_LAST)
442                         ret = btrfs_next_leaf(root, path);
443                 else
444                         ret = btrfs_next_old_leaf(root, path, time_seq);
445         }
446
447         while (!ret && count < total_refs) {
448                 eb = path->nodes[0];
449                 slot = path->slots[0];
450
451                 btrfs_item_key_to_cpu(eb, &key, slot);
452
453                 if (key.objectid != key_for_search->objectid ||
454                     key.type != BTRFS_EXTENT_DATA_KEY)
455                         break;
456
457                 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
458                 disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
459
460                 if (disk_byte == wanted_disk_byte) {
461                         eie = NULL;
462                         old = NULL;
463                         count++;
464                         if (extent_item_pos) {
465                                 ret = check_extent_in_eb(&key, eb, fi,
466                                                 *extent_item_pos,
467                                                 &eie, ignore_offset);
468                                 if (ret < 0)
469                                         break;
470                         }
471                         if (ret > 0)
472                                 goto next;
473                         ret = ulist_add_merge_ptr(parents, eb->start,
474                                                   eie, (void **)&old, GFP_NOFS);
475                         if (ret < 0)
476                                 break;
477                         if (!ret && extent_item_pos) {
478                                 while (old->next)
479                                         old = old->next;
480                                 old->next = eie;
481                         }
482                         eie = NULL;
483                 }
484 next:
485                 if (time_seq == SEQ_LAST)
486                         ret = btrfs_next_item(root, path);
487                 else
488                         ret = btrfs_next_old_item(root, path, time_seq);
489         }
490
491         if (ret > 0)
492                 ret = 0;
493         else if (ret < 0)
494                 free_inode_elem_list(eie);
495         return ret;
496 }
497
498 /*
499  * resolve an indirect backref in the form (root_id, key, level)
500  * to a logical address
501  */
502 static int resolve_indirect_ref(struct btrfs_fs_info *fs_info,
503                                 struct btrfs_path *path, u64 time_seq,
504                                 struct prelim_ref *ref, struct ulist *parents,
505                                 const u64 *extent_item_pos, u64 total_refs,
506                                 bool ignore_offset)
507 {
508         struct btrfs_root *root;
509         struct btrfs_key root_key;
510         struct extent_buffer *eb;
511         int ret = 0;
512         int root_level;
513         int level = ref->level;
514         int index;
515
516         root_key.objectid = ref->root_id;
517         root_key.type = BTRFS_ROOT_ITEM_KEY;
518         root_key.offset = (u64)-1;
519
520         index = srcu_read_lock(&fs_info->subvol_srcu);
521
522         root = btrfs_get_fs_root(fs_info, &root_key, false);
523         if (IS_ERR(root)) {
524                 srcu_read_unlock(&fs_info->subvol_srcu, index);
525                 ret = PTR_ERR(root);
526                 goto out;
527         }
528
529         if (btrfs_is_testing(fs_info)) {
530                 srcu_read_unlock(&fs_info->subvol_srcu, index);
531                 ret = -ENOENT;
532                 goto out;
533         }
534
535         if (path->search_commit_root)
536                 root_level = btrfs_header_level(root->commit_root);
537         else if (time_seq == SEQ_LAST)
538                 root_level = btrfs_header_level(root->node);
539         else
540                 root_level = btrfs_old_root_level(root, time_seq);
541
542         if (root_level + 1 == level) {
543                 srcu_read_unlock(&fs_info->subvol_srcu, index);
544                 goto out;
545         }
546
547         path->lowest_level = level;
548         if (time_seq == SEQ_LAST)
549                 ret = btrfs_search_slot(NULL, root, &ref->key_for_search, path,
550                                         0, 0);
551         else
552                 ret = btrfs_search_old_slot(root, &ref->key_for_search, path,
553                                             time_seq);
554
555         /* root node has been locked, we can release @subvol_srcu safely here */
556         srcu_read_unlock(&fs_info->subvol_srcu, index);
557
558         btrfs_debug(fs_info,
559                 "search slot in root %llu (level %d, ref count %d) returned %d for key (%llu %u %llu)",
560                  ref->root_id, level, ref->count, ret,
561                  ref->key_for_search.objectid, ref->key_for_search.type,
562                  ref->key_for_search.offset);
563         if (ret < 0)
564                 goto out;
565
566         eb = path->nodes[level];
567         while (!eb) {
568                 if (WARN_ON(!level)) {
569                         ret = 1;
570                         goto out;
571                 }
572                 level--;
573                 eb = path->nodes[level];
574         }
575
576         ret = add_all_parents(root, path, parents, ref, level, time_seq,
577                               extent_item_pos, total_refs, ignore_offset);
578 out:
579         path->lowest_level = 0;
580         btrfs_release_path(path);
581         return ret;
582 }
583
584 static struct extent_inode_elem *
585 unode_aux_to_inode_list(struct ulist_node *node)
586 {
587         if (!node)
588                 return NULL;
589         return (struct extent_inode_elem *)(uintptr_t)node->aux;
590 }
591
592 /*
593  * We maintain three seperate rbtrees: one for direct refs, one for
594  * indirect refs which have a key, and one for indirect refs which do not
595  * have a key. Each tree does merge on insertion.
596  *
597  * Once all of the references are located, we iterate over the tree of
598  * indirect refs with missing keys. An appropriate key is located and
599  * the ref is moved onto the tree for indirect refs. After all missing
600  * keys are thus located, we iterate over the indirect ref tree, resolve
601  * each reference, and then insert the resolved reference onto the
602  * direct tree (merging there too).
603  *
604  * New backrefs (i.e., for parent nodes) are added to the appropriate
605  * rbtree as they are encountered. The new backrefs are subsequently
606  * resolved as above.
607  */
608 static int resolve_indirect_refs(struct btrfs_fs_info *fs_info,
609                                  struct btrfs_path *path, u64 time_seq,
610                                  struct preftrees *preftrees,
611                                  const u64 *extent_item_pos, u64 total_refs,
612                                  struct share_check *sc, bool ignore_offset)
613 {
614         int err;
615         int ret = 0;
616         struct ulist *parents;
617         struct ulist_node *node;
618         struct ulist_iterator uiter;
619         struct rb_node *rnode;
620
621         parents = ulist_alloc(GFP_NOFS);
622         if (!parents)
623                 return -ENOMEM;
624
625         /*
626          * We could trade memory usage for performance here by iterating
627          * the tree, allocating new refs for each insertion, and then
628          * freeing the entire indirect tree when we're done.  In some test
629          * cases, the tree can grow quite large (~200k objects).
630          */
631         while ((rnode = rb_first(&preftrees->indirect.root))) {
632                 struct prelim_ref *ref;
633
634                 ref = rb_entry(rnode, struct prelim_ref, rbnode);
635                 if (WARN(ref->parent,
636                          "BUG: direct ref found in indirect tree")) {
637                         ret = -EINVAL;
638                         goto out;
639                 }
640
641                 rb_erase(&ref->rbnode, &preftrees->indirect.root);
642                 preftrees->indirect.count--;
643
644                 if (ref->count == 0) {
645                         free_pref(ref);
646                         continue;
647                 }
648
649                 if (sc && sc->root_objectid &&
650                     ref->root_id != sc->root_objectid) {
651                         free_pref(ref);
652                         ret = BACKREF_FOUND_SHARED;
653                         goto out;
654                 }
655                 err = resolve_indirect_ref(fs_info, path, time_seq, ref,
656                                            parents, extent_item_pos,
657                                            total_refs, ignore_offset);
658                 /*
659                  * we can only tolerate ENOENT,otherwise,we should catch error
660                  * and return directly.
661                  */
662                 if (err == -ENOENT) {
663                         prelim_ref_insert(fs_info, &preftrees->direct, ref,
664                                           NULL);
665                         continue;
666                 } else if (err) {
667                         free_pref(ref);
668                         ret = err;
669                         goto out;
670                 }
671
672                 /* we put the first parent into the ref at hand */
673                 ULIST_ITER_INIT(&uiter);
674                 node = ulist_next(parents, &uiter);
675                 ref->parent = node ? node->val : 0;
676                 ref->inode_list = unode_aux_to_inode_list(node);
677
678                 /* Add a prelim_ref(s) for any other parent(s). */
679                 while ((node = ulist_next(parents, &uiter))) {
680                         struct prelim_ref *new_ref;
681
682                         new_ref = kmem_cache_alloc(btrfs_prelim_ref_cache,
683                                                    GFP_NOFS);
684                         if (!new_ref) {
685                                 free_pref(ref);
686                                 ret = -ENOMEM;
687                                 goto out;
688                         }
689                         memcpy(new_ref, ref, sizeof(*ref));
690                         new_ref->parent = node->val;
691                         new_ref->inode_list = unode_aux_to_inode_list(node);
692                         prelim_ref_insert(fs_info, &preftrees->direct,
693                                           new_ref, NULL);
694                 }
695
696                 /*
697                  * Now it's a direct ref, put it in the the direct tree. We must
698                  * do this last because the ref could be merged/freed here.
699                  */
700                 prelim_ref_insert(fs_info, &preftrees->direct, ref, NULL);
701
702                 ulist_reinit(parents);
703                 cond_resched();
704         }
705 out:
706         ulist_free(parents);
707         return ret;
708 }
709
710 /*
711  * read tree blocks and add keys where required.
712  */
713 static int add_missing_keys(struct btrfs_fs_info *fs_info,
714                             struct preftrees *preftrees, bool lock)
715 {
716         struct prelim_ref *ref;
717         struct extent_buffer *eb;
718         struct preftree *tree = &preftrees->indirect_missing_keys;
719         struct rb_node *node;
720
721         while ((node = rb_first(&tree->root))) {
722                 ref = rb_entry(node, struct prelim_ref, rbnode);
723                 rb_erase(node, &tree->root);
724
725                 BUG_ON(ref->parent);    /* should not be a direct ref */
726                 BUG_ON(ref->key_for_search.type);
727                 BUG_ON(!ref->wanted_disk_byte);
728
729                 eb = read_tree_block(fs_info, ref->wanted_disk_byte, 0,
730                                      ref->level - 1, NULL);
731                 if (IS_ERR(eb)) {
732                         free_pref(ref);
733                         return PTR_ERR(eb);
734                 } else if (!extent_buffer_uptodate(eb)) {
735                         free_pref(ref);
736                         free_extent_buffer(eb);
737                         return -EIO;
738                 }
739                 if (lock)
740                         btrfs_tree_read_lock(eb);
741                 if (btrfs_header_level(eb) == 0)
742                         btrfs_item_key_to_cpu(eb, &ref->key_for_search, 0);
743                 else
744                         btrfs_node_key_to_cpu(eb, &ref->key_for_search, 0);
745                 if (lock)
746                         btrfs_tree_read_unlock(eb);
747                 free_extent_buffer(eb);
748                 prelim_ref_insert(fs_info, &preftrees->indirect, ref, NULL);
749                 cond_resched();
750         }
751         return 0;
752 }
753
754 /*
755  * add all currently queued delayed refs from this head whose seq nr is
756  * smaller or equal that seq to the list
757  */
758 static int add_delayed_refs(const struct btrfs_fs_info *fs_info,
759                             struct btrfs_delayed_ref_head *head, u64 seq,
760                             struct preftrees *preftrees, u64 *total_refs,
761                             struct share_check *sc)
762 {
763         struct btrfs_delayed_ref_node *node;
764         struct btrfs_key key;
765         struct rb_node *n;
766         int count;
767         int ret = 0;
768
769         spin_lock(&head->lock);
770         for (n = rb_first(&head->ref_tree); n; n = rb_next(n)) {
771                 node = rb_entry(n, struct btrfs_delayed_ref_node,
772                                 ref_node);
773                 if (node->seq > seq)
774                         continue;
775
776                 switch (node->action) {
777                 case BTRFS_ADD_DELAYED_EXTENT:
778                 case BTRFS_UPDATE_DELAYED_HEAD:
779                         WARN_ON(1);
780                         continue;
781                 case BTRFS_ADD_DELAYED_REF:
782                         count = node->ref_mod;
783                         break;
784                 case BTRFS_DROP_DELAYED_REF:
785                         count = node->ref_mod * -1;
786                         break;
787                 default:
788                         BUG_ON(1);
789                 }
790                 *total_refs += count;
791                 switch (node->type) {
792                 case BTRFS_TREE_BLOCK_REF_KEY: {
793                         /* NORMAL INDIRECT METADATA backref */
794                         struct btrfs_delayed_tree_ref *ref;
795                         struct btrfs_key *key_ptr = NULL;
796
797                         if (head->extent_op && head->extent_op->update_key) {
798                                 btrfs_disk_key_to_cpu(&key, &head->extent_op->key);
799                                 key_ptr = &key;
800                         }
801
802                         ref = btrfs_delayed_node_to_tree_ref(node);
803                         ret = add_indirect_ref(fs_info, preftrees, ref->root,
804                                                key_ptr, ref->level + 1,
805                                                node->bytenr, count, sc,
806                                                GFP_ATOMIC);
807                         break;
808                 }
809                 case BTRFS_SHARED_BLOCK_REF_KEY: {
810                         /* SHARED DIRECT METADATA backref */
811                         struct btrfs_delayed_tree_ref *ref;
812
813                         ref = btrfs_delayed_node_to_tree_ref(node);
814
815                         ret = add_direct_ref(fs_info, preftrees, ref->level + 1,
816                                              ref->parent, node->bytenr, count,
817                                              sc, GFP_ATOMIC);
818                         break;
819                 }
820                 case BTRFS_EXTENT_DATA_REF_KEY: {
821                         /* NORMAL INDIRECT DATA backref */
822                         struct btrfs_delayed_data_ref *ref;
823                         ref = btrfs_delayed_node_to_data_ref(node);
824
825                         key.objectid = ref->objectid;
826                         key.type = BTRFS_EXTENT_DATA_KEY;
827                         key.offset = ref->offset;
828
829                         /*
830                          * If we have a share check context and a reference for
831                          * another inode, we can't exit immediately. This is
832                          * because even if this is a BTRFS_ADD_DELAYED_REF
833                          * reference we may find next a BTRFS_DROP_DELAYED_REF
834                          * which cancels out this ADD reference.
835                          *
836                          * If this is a DROP reference and there was no previous
837                          * ADD reference, then we need to signal that when we
838                          * process references from the extent tree (through
839                          * add_inline_refs() and add_keyed_refs()), we should
840                          * not exit early if we find a reference for another
841                          * inode, because one of the delayed DROP references
842                          * may cancel that reference in the extent tree.
843                          */
844                         if (sc && count < 0)
845                                 sc->have_delayed_delete_refs = true;
846
847                         ret = add_indirect_ref(fs_info, preftrees, ref->root,
848                                                &key, 0, node->bytenr, count, sc,
849                                                GFP_ATOMIC);
850                         break;
851                 }
852                 case BTRFS_SHARED_DATA_REF_KEY: {
853                         /* SHARED DIRECT FULL backref */
854                         struct btrfs_delayed_data_ref *ref;
855
856                         ref = btrfs_delayed_node_to_data_ref(node);
857
858                         ret = add_direct_ref(fs_info, preftrees, 0, ref->parent,
859                                              node->bytenr, count, sc,
860                                              GFP_ATOMIC);
861                         break;
862                 }
863                 default:
864                         WARN_ON(1);
865                 }
866                 /*
867                  * We must ignore BACKREF_FOUND_SHARED until all delayed
868                  * refs have been checked.
869                  */
870                 if (ret && (ret != BACKREF_FOUND_SHARED))
871                         break;
872         }
873         if (!ret)
874                 ret = extent_is_shared(sc);
875
876         spin_unlock(&head->lock);
877         return ret;
878 }
879
880 /*
881  * add all inline backrefs for bytenr to the list
882  *
883  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
884  */
885 static int add_inline_refs(const struct btrfs_fs_info *fs_info,
886                            struct btrfs_path *path, u64 bytenr,
887                            int *info_level, struct preftrees *preftrees,
888                            u64 *total_refs, struct share_check *sc)
889 {
890         int ret = 0;
891         int slot;
892         struct extent_buffer *leaf;
893         struct btrfs_key key;
894         struct btrfs_key found_key;
895         unsigned long ptr;
896         unsigned long end;
897         struct btrfs_extent_item *ei;
898         u64 flags;
899         u64 item_size;
900
901         /*
902          * enumerate all inline refs
903          */
904         leaf = path->nodes[0];
905         slot = path->slots[0];
906
907         item_size = btrfs_item_size_nr(leaf, slot);
908         BUG_ON(item_size < sizeof(*ei));
909
910         ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
911         flags = btrfs_extent_flags(leaf, ei);
912         *total_refs += btrfs_extent_refs(leaf, ei);
913         btrfs_item_key_to_cpu(leaf, &found_key, slot);
914
915         ptr = (unsigned long)(ei + 1);
916         end = (unsigned long)ei + item_size;
917
918         if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
919             flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
920                 struct btrfs_tree_block_info *info;
921
922                 info = (struct btrfs_tree_block_info *)ptr;
923                 *info_level = btrfs_tree_block_level(leaf, info);
924                 ptr += sizeof(struct btrfs_tree_block_info);
925                 BUG_ON(ptr > end);
926         } else if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
927                 *info_level = found_key.offset;
928         } else {
929                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
930         }
931
932         while (ptr < end) {
933                 struct btrfs_extent_inline_ref *iref;
934                 u64 offset;
935                 int type;
936
937                 iref = (struct btrfs_extent_inline_ref *)ptr;
938                 type = btrfs_get_extent_inline_ref_type(leaf, iref,
939                                                         BTRFS_REF_TYPE_ANY);
940                 if (type == BTRFS_REF_TYPE_INVALID)
941                         return -EUCLEAN;
942
943                 offset = btrfs_extent_inline_ref_offset(leaf, iref);
944
945                 switch (type) {
946                 case BTRFS_SHARED_BLOCK_REF_KEY:
947                         ret = add_direct_ref(fs_info, preftrees,
948                                              *info_level + 1, offset,
949                                              bytenr, 1, NULL, GFP_NOFS);
950                         break;
951                 case BTRFS_SHARED_DATA_REF_KEY: {
952                         struct btrfs_shared_data_ref *sdref;
953                         int count;
954
955                         sdref = (struct btrfs_shared_data_ref *)(iref + 1);
956                         count = btrfs_shared_data_ref_count(leaf, sdref);
957
958                         ret = add_direct_ref(fs_info, preftrees, 0, offset,
959                                              bytenr, count, sc, GFP_NOFS);
960                         break;
961                 }
962                 case BTRFS_TREE_BLOCK_REF_KEY:
963                         ret = add_indirect_ref(fs_info, preftrees, offset,
964                                                NULL, *info_level + 1,
965                                                bytenr, 1, NULL, GFP_NOFS);
966                         break;
967                 case BTRFS_EXTENT_DATA_REF_KEY: {
968                         struct btrfs_extent_data_ref *dref;
969                         int count;
970                         u64 root;
971
972                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
973                         count = btrfs_extent_data_ref_count(leaf, dref);
974                         key.objectid = btrfs_extent_data_ref_objectid(leaf,
975                                                                       dref);
976                         key.type = BTRFS_EXTENT_DATA_KEY;
977                         key.offset = btrfs_extent_data_ref_offset(leaf, dref);
978
979                         if (sc && sc->inum && key.objectid != sc->inum &&
980                             !sc->have_delayed_delete_refs) {
981                                 ret = BACKREF_FOUND_SHARED;
982                                 break;
983                         }
984
985                         root = btrfs_extent_data_ref_root(leaf, dref);
986
987                         ret = add_indirect_ref(fs_info, preftrees, root,
988                                                &key, 0, bytenr, count,
989                                                sc, GFP_NOFS);
990
991                         break;
992                 }
993                 default:
994                         WARN_ON(1);
995                 }
996                 if (ret)
997                         return ret;
998                 ptr += btrfs_extent_inline_ref_size(type);
999         }
1000
1001         return 0;
1002 }
1003
1004 /*
1005  * add all non-inline backrefs for bytenr to the list
1006  *
1007  * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
1008  */
1009 static int add_keyed_refs(struct btrfs_fs_info *fs_info,
1010                           struct btrfs_path *path, u64 bytenr,
1011                           int info_level, struct preftrees *preftrees,
1012                           struct share_check *sc)
1013 {
1014         struct btrfs_root *extent_root = fs_info->extent_root;
1015         int ret;
1016         int slot;
1017         struct extent_buffer *leaf;
1018         struct btrfs_key key;
1019
1020         while (1) {
1021                 ret = btrfs_next_item(extent_root, path);
1022                 if (ret < 0)
1023                         break;
1024                 if (ret) {
1025                         ret = 0;
1026                         break;
1027                 }
1028
1029                 slot = path->slots[0];
1030                 leaf = path->nodes[0];
1031                 btrfs_item_key_to_cpu(leaf, &key, slot);
1032
1033                 if (key.objectid != bytenr)
1034                         break;
1035                 if (key.type < BTRFS_TREE_BLOCK_REF_KEY)
1036                         continue;
1037                 if (key.type > BTRFS_SHARED_DATA_REF_KEY)
1038                         break;
1039
1040                 switch (key.type) {
1041                 case BTRFS_SHARED_BLOCK_REF_KEY:
1042                         /* SHARED DIRECT METADATA backref */
1043                         ret = add_direct_ref(fs_info, preftrees,
1044                                              info_level + 1, key.offset,
1045                                              bytenr, 1, NULL, GFP_NOFS);
1046                         break;
1047                 case BTRFS_SHARED_DATA_REF_KEY: {
1048                         /* SHARED DIRECT FULL backref */
1049                         struct btrfs_shared_data_ref *sdref;
1050                         int count;
1051
1052                         sdref = btrfs_item_ptr(leaf, slot,
1053                                               struct btrfs_shared_data_ref);
1054                         count = btrfs_shared_data_ref_count(leaf, sdref);
1055                         ret = add_direct_ref(fs_info, preftrees, 0,
1056                                              key.offset, bytenr, count,
1057                                              sc, GFP_NOFS);
1058                         break;
1059                 }
1060                 case BTRFS_TREE_BLOCK_REF_KEY:
1061                         /* NORMAL INDIRECT METADATA backref */
1062                         ret = add_indirect_ref(fs_info, preftrees, key.offset,
1063                                                NULL, info_level + 1, bytenr,
1064                                                1, NULL, GFP_NOFS);
1065                         break;
1066                 case BTRFS_EXTENT_DATA_REF_KEY: {
1067                         /* NORMAL INDIRECT DATA backref */
1068                         struct btrfs_extent_data_ref *dref;
1069                         int count;
1070                         u64 root;
1071
1072                         dref = btrfs_item_ptr(leaf, slot,
1073                                               struct btrfs_extent_data_ref);
1074                         count = btrfs_extent_data_ref_count(leaf, dref);
1075                         key.objectid = btrfs_extent_data_ref_objectid(leaf,
1076                                                                       dref);
1077                         key.type = BTRFS_EXTENT_DATA_KEY;
1078                         key.offset = btrfs_extent_data_ref_offset(leaf, dref);
1079
1080                         if (sc && sc->inum && key.objectid != sc->inum &&
1081                             !sc->have_delayed_delete_refs) {
1082                                 ret = BACKREF_FOUND_SHARED;
1083                                 break;
1084                         }
1085
1086                         root = btrfs_extent_data_ref_root(leaf, dref);
1087                         ret = add_indirect_ref(fs_info, preftrees, root,
1088                                                &key, 0, bytenr, count,
1089                                                sc, GFP_NOFS);
1090                         break;
1091                 }
1092                 default:
1093                         WARN_ON(1);
1094                 }
1095                 if (ret)
1096                         return ret;
1097
1098         }
1099
1100         return ret;
1101 }
1102
1103 /*
1104  * this adds all existing backrefs (inline backrefs, backrefs and delayed
1105  * refs) for the given bytenr to the refs list, merges duplicates and resolves
1106  * indirect refs to their parent bytenr.
1107  * When roots are found, they're added to the roots list
1108  *
1109  * If time_seq is set to SEQ_LAST, it will not search delayed_refs, and behave
1110  * much like trans == NULL case, the difference only lies in it will not
1111  * commit root.
1112  * The special case is for qgroup to search roots in commit_transaction().
1113  *
1114  * @sc - if !NULL, then immediately return BACKREF_FOUND_SHARED when a
1115  * shared extent is detected.
1116  *
1117  * Otherwise this returns 0 for success and <0 for an error.
1118  *
1119  * If ignore_offset is set to false, only extent refs whose offsets match
1120  * extent_item_pos are returned.  If true, every extent ref is returned
1121  * and extent_item_pos is ignored.
1122  *
1123  * FIXME some caching might speed things up
1124  */
1125 static int find_parent_nodes(struct btrfs_trans_handle *trans,
1126                              struct btrfs_fs_info *fs_info, u64 bytenr,
1127                              u64 time_seq, struct ulist *refs,
1128                              struct ulist *roots, const u64 *extent_item_pos,
1129                              struct share_check *sc, bool ignore_offset)
1130 {
1131         struct btrfs_key key;
1132         struct btrfs_path *path;
1133         struct btrfs_delayed_ref_root *delayed_refs = NULL;
1134         struct btrfs_delayed_ref_head *head;
1135         int info_level = 0;
1136         int ret;
1137         struct prelim_ref *ref;
1138         struct rb_node *node;
1139         struct extent_inode_elem *eie = NULL;
1140         /* total of both direct AND indirect refs! */
1141         u64 total_refs = 0;
1142         struct preftrees preftrees = {
1143                 .direct = PREFTREE_INIT,
1144                 .indirect = PREFTREE_INIT,
1145                 .indirect_missing_keys = PREFTREE_INIT
1146         };
1147
1148         key.objectid = bytenr;
1149         key.offset = (u64)-1;
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
1155         path = btrfs_alloc_path();
1156         if (!path)
1157                 return -ENOMEM;
1158         if (!trans) {
1159                 path->search_commit_root = 1;
1160                 path->skip_locking = 1;
1161         }
1162
1163         if (time_seq == SEQ_LAST)
1164                 path->skip_locking = 1;
1165
1166         /*
1167          * grab both a lock on the path and a lock on the delayed ref head.
1168          * We need both to get a consistent picture of how the refs look
1169          * at a specified point in time
1170          */
1171 again:
1172         head = NULL;
1173
1174         ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
1175         if (ret < 0)
1176                 goto out;
1177         if (ret == 0) {
1178                 /* This shouldn't happen, indicates a bug or fs corruption. */
1179                 ASSERT(ret != 0);
1180                 ret = -EUCLEAN;
1181                 goto out;
1182         }
1183
1184 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
1185         if (trans && likely(trans->type != __TRANS_DUMMY) &&
1186             time_seq != SEQ_LAST) {
1187 #else
1188         if (trans && time_seq != SEQ_LAST) {
1189 #endif
1190                 /*
1191                  * look if there are updates for this ref queued and lock the
1192                  * head
1193                  */
1194                 delayed_refs = &trans->transaction->delayed_refs;
1195                 spin_lock(&delayed_refs->lock);
1196                 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
1197                 if (head) {
1198                         if (!mutex_trylock(&head->mutex)) {
1199                                 refcount_inc(&head->refs);
1200                                 spin_unlock(&delayed_refs->lock);
1201
1202                                 btrfs_release_path(path);
1203
1204                                 /*
1205                                  * Mutex was contended, block until it's
1206                                  * released and try again
1207                                  */
1208                                 mutex_lock(&head->mutex);
1209                                 mutex_unlock(&head->mutex);
1210                                 btrfs_put_delayed_ref_head(head);
1211                                 goto again;
1212                         }
1213                         spin_unlock(&delayed_refs->lock);
1214                         ret = add_delayed_refs(fs_info, head, time_seq,
1215                                                &preftrees, &total_refs, sc);
1216                         mutex_unlock(&head->mutex);
1217                         if (ret)
1218                                 goto out;
1219                 } else {
1220                         spin_unlock(&delayed_refs->lock);
1221                 }
1222         }
1223
1224         if (path->slots[0]) {
1225                 struct extent_buffer *leaf;
1226                 int slot;
1227
1228                 path->slots[0]--;
1229                 leaf = path->nodes[0];
1230                 slot = path->slots[0];
1231                 btrfs_item_key_to_cpu(leaf, &key, slot);
1232                 if (key.objectid == bytenr &&
1233                     (key.type == BTRFS_EXTENT_ITEM_KEY ||
1234                      key.type == BTRFS_METADATA_ITEM_KEY)) {
1235                         ret = add_inline_refs(fs_info, path, bytenr,
1236                                               &info_level, &preftrees,
1237                                               &total_refs, sc);
1238                         if (ret)
1239                                 goto out;
1240                         ret = add_keyed_refs(fs_info, path, bytenr, info_level,
1241                                              &preftrees, sc);
1242                         if (ret)
1243                                 goto out;
1244                 }
1245         }
1246
1247         btrfs_release_path(path);
1248
1249         ret = add_missing_keys(fs_info, &preftrees, path->skip_locking == 0);
1250         if (ret)
1251                 goto out;
1252
1253         WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect_missing_keys.root));
1254
1255         ret = resolve_indirect_refs(fs_info, path, time_seq, &preftrees,
1256                                     extent_item_pos, total_refs, sc, ignore_offset);
1257         if (ret)
1258                 goto out;
1259
1260         WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect.root));
1261
1262         /*
1263          * This walks the tree of merged and resolved refs. Tree blocks are
1264          * read in as needed. Unique entries are added to the ulist, and
1265          * the list of found roots is updated.
1266          *
1267          * We release the entire tree in one go before returning.
1268          */
1269         node = rb_first(&preftrees.direct.root);
1270         while (node) {
1271                 ref = rb_entry(node, struct prelim_ref, rbnode);
1272                 node = rb_next(&ref->rbnode);
1273                 /*
1274                  * ref->count < 0 can happen here if there are delayed
1275                  * refs with a node->action of BTRFS_DROP_DELAYED_REF.
1276                  * prelim_ref_insert() relies on this when merging
1277                  * identical refs to keep the overall count correct.
1278                  * prelim_ref_insert() will merge only those refs
1279                  * which compare identically.  Any refs having
1280                  * e.g. different offsets would not be merged,
1281                  * and would retain their original ref->count < 0.
1282                  */
1283                 if (roots && ref->count && ref->root_id && ref->parent == 0) {
1284                         if (sc && sc->root_objectid &&
1285                             ref->root_id != sc->root_objectid) {
1286                                 ret = BACKREF_FOUND_SHARED;
1287                                 goto out;
1288                         }
1289
1290                         /* no parent == root of tree */
1291                         ret = ulist_add(roots, ref->root_id, 0, GFP_NOFS);
1292                         if (ret < 0)
1293                                 goto out;
1294                 }
1295                 if (ref->count && ref->parent) {
1296                         if (extent_item_pos && !ref->inode_list &&
1297                             ref->level == 0) {
1298                                 struct extent_buffer *eb;
1299
1300                                 eb = read_tree_block(fs_info, ref->parent, 0,
1301                                                      ref->level, NULL);
1302                                 if (IS_ERR(eb)) {
1303                                         ret = PTR_ERR(eb);
1304                                         goto out;
1305                                 } else if (!extent_buffer_uptodate(eb)) {
1306                                         free_extent_buffer(eb);
1307                                         ret = -EIO;
1308                                         goto out;
1309                                 }
1310                                 if (!path->skip_locking) {
1311                                         btrfs_tree_read_lock(eb);
1312                                         btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
1313                                 }
1314                                 ret = find_extent_in_eb(eb, bytenr,
1315                                                         *extent_item_pos, &eie, ignore_offset);
1316                                 if (!path->skip_locking)
1317                                         btrfs_tree_read_unlock_blocking(eb);
1318                                 free_extent_buffer(eb);
1319                                 if (ret < 0)
1320                                         goto out;
1321                                 ref->inode_list = eie;
1322                         }
1323                         ret = ulist_add_merge_ptr(refs, ref->parent,
1324                                                   ref->inode_list,
1325                                                   (void **)&eie, GFP_NOFS);
1326                         if (ret < 0)
1327                                 goto out;
1328                         if (!ret && extent_item_pos) {
1329                                 /*
1330                                  * We've recorded that parent, so we must extend
1331                                  * its inode list here.
1332                                  *
1333                                  * However if there was corruption we may not
1334                                  * have found an eie, return an error in this
1335                                  * case.
1336                                  */
1337                                 ASSERT(eie);
1338                                 if (!eie) {
1339                                         ret = -EUCLEAN;
1340                                         goto out;
1341                                 }
1342                                 while (eie->next)
1343                                         eie = eie->next;
1344                                 eie->next = ref->inode_list;
1345                         }
1346                         eie = NULL;
1347                 }
1348                 cond_resched();
1349         }
1350
1351 out:
1352         btrfs_free_path(path);
1353
1354         prelim_release(&preftrees.direct);
1355         prelim_release(&preftrees.indirect);
1356         prelim_release(&preftrees.indirect_missing_keys);
1357
1358         if (ret < 0)
1359                 free_inode_elem_list(eie);
1360         return ret;
1361 }
1362
1363 static void free_leaf_list(struct ulist *blocks)
1364 {
1365         struct ulist_node *node = NULL;
1366         struct extent_inode_elem *eie;
1367         struct ulist_iterator uiter;
1368
1369         ULIST_ITER_INIT(&uiter);
1370         while ((node = ulist_next(blocks, &uiter))) {
1371                 if (!node->aux)
1372                         continue;
1373                 eie = unode_aux_to_inode_list(node);
1374                 free_inode_elem_list(eie);
1375                 node->aux = 0;
1376         }
1377
1378         ulist_free(blocks);
1379 }
1380
1381 /*
1382  * Finds all leafs with a reference to the specified combination of bytenr and
1383  * offset. key_list_head will point to a list of corresponding keys (caller must
1384  * free each list element). The leafs will be stored in the leafs ulist, which
1385  * must be freed with ulist_free.
1386  *
1387  * returns 0 on success, <0 on error
1388  */
1389 static int btrfs_find_all_leafs(struct btrfs_trans_handle *trans,
1390                                 struct btrfs_fs_info *fs_info, u64 bytenr,
1391                                 u64 time_seq, struct ulist **leafs,
1392                                 const u64 *extent_item_pos, bool ignore_offset)
1393 {
1394         int ret;
1395
1396         *leafs = ulist_alloc(GFP_NOFS);
1397         if (!*leafs)
1398                 return -ENOMEM;
1399
1400         ret = find_parent_nodes(trans, fs_info, bytenr, time_seq,
1401                                 *leafs, NULL, extent_item_pos, NULL, ignore_offset);
1402         if (ret < 0 && ret != -ENOENT) {
1403                 free_leaf_list(*leafs);
1404                 return ret;
1405         }
1406
1407         return 0;
1408 }
1409
1410 /*
1411  * walk all backrefs for a given extent to find all roots that reference this
1412  * extent. Walking a backref means finding all extents that reference this
1413  * extent and in turn walk the backrefs of those, too. Naturally this is a
1414  * recursive process, but here it is implemented in an iterative fashion: We
1415  * find all referencing extents for the extent in question and put them on a
1416  * list. In turn, we find all referencing extents for those, further appending
1417  * to the list. The way we iterate the list allows adding more elements after
1418  * the current while iterating. The process stops when we reach the end of the
1419  * list. Found roots are added to the roots list.
1420  *
1421  * returns 0 on success, < 0 on error.
1422  */
1423 static int btrfs_find_all_roots_safe(struct btrfs_trans_handle *trans,
1424                                      struct btrfs_fs_info *fs_info, u64 bytenr,
1425                                      u64 time_seq, struct ulist **roots,
1426                                      bool ignore_offset)
1427 {
1428         struct ulist *tmp;
1429         struct ulist_node *node = NULL;
1430         struct ulist_iterator uiter;
1431         int ret;
1432
1433         tmp = ulist_alloc(GFP_NOFS);
1434         if (!tmp)
1435                 return -ENOMEM;
1436         *roots = ulist_alloc(GFP_NOFS);
1437         if (!*roots) {
1438                 ulist_free(tmp);
1439                 return -ENOMEM;
1440         }
1441
1442         ULIST_ITER_INIT(&uiter);
1443         while (1) {
1444                 ret = find_parent_nodes(trans, fs_info, bytenr, time_seq,
1445                                         tmp, *roots, NULL, NULL, ignore_offset);
1446                 if (ret < 0 && ret != -ENOENT) {
1447                         ulist_free(tmp);
1448                         ulist_free(*roots);
1449                         *roots = NULL;
1450                         return ret;
1451                 }
1452                 node = ulist_next(tmp, &uiter);
1453                 if (!node)
1454                         break;
1455                 bytenr = node->val;
1456                 cond_resched();
1457         }
1458
1459         ulist_free(tmp);
1460         return 0;
1461 }
1462
1463 int btrfs_find_all_roots(struct btrfs_trans_handle *trans,
1464                          struct btrfs_fs_info *fs_info, u64 bytenr,
1465                          u64 time_seq, struct ulist **roots,
1466                          bool ignore_offset)
1467 {
1468         int ret;
1469
1470         if (!trans)
1471                 down_read(&fs_info->commit_root_sem);
1472         ret = btrfs_find_all_roots_safe(trans, fs_info, bytenr,
1473                                         time_seq, roots, ignore_offset);
1474         if (!trans)
1475                 up_read(&fs_info->commit_root_sem);
1476         return ret;
1477 }
1478
1479 /**
1480  * btrfs_check_shared - tell us whether an extent is shared
1481  *
1482  * btrfs_check_shared uses the backref walking code but will short
1483  * circuit as soon as it finds a root or inode that doesn't match the
1484  * one passed in. This provides a significant performance benefit for
1485  * callers (such as fiemap) which want to know whether the extent is
1486  * shared but do not need a ref count.
1487  *
1488  * This attempts to attach to the running transaction in order to account for
1489  * delayed refs, but continues on even when no running transaction exists.
1490  *
1491  * Return: 0 if extent is not shared, 1 if it is shared, < 0 on error.
1492  */
1493 int btrfs_check_shared(struct btrfs_root *root, u64 inum, u64 bytenr)
1494 {
1495         struct btrfs_fs_info *fs_info = root->fs_info;
1496         struct btrfs_trans_handle *trans;
1497         struct ulist *tmp = NULL;
1498         struct ulist *roots = NULL;
1499         struct ulist_iterator uiter;
1500         struct ulist_node *node;
1501         struct seq_list elem = SEQ_LIST_INIT(elem);
1502         int ret = 0;
1503         struct share_check shared = {
1504                 .root_objectid = root->objectid,
1505                 .inum = inum,
1506                 .share_count = 0,
1507                 .have_delayed_delete_refs = false,
1508         };
1509
1510         tmp = ulist_alloc(GFP_NOFS);
1511         roots = ulist_alloc(GFP_NOFS);
1512         if (!tmp || !roots) {
1513                 ret = -ENOMEM;
1514                 goto out;
1515         }
1516
1517         trans = btrfs_join_transaction_nostart(root);
1518         if (IS_ERR(trans)) {
1519                 if (PTR_ERR(trans) != -ENOENT && PTR_ERR(trans) != -EROFS) {
1520                         ret = PTR_ERR(trans);
1521                         goto out;
1522                 }
1523                 trans = NULL;
1524                 down_read(&fs_info->commit_root_sem);
1525         } else {
1526                 btrfs_get_tree_mod_seq(fs_info, &elem);
1527         }
1528
1529         ULIST_ITER_INIT(&uiter);
1530         while (1) {
1531                 ret = find_parent_nodes(trans, fs_info, bytenr, elem.seq, tmp,
1532                                         roots, NULL, &shared, false);
1533                 if (ret == BACKREF_FOUND_SHARED) {
1534                         /* this is the only condition under which we return 1 */
1535                         ret = 1;
1536                         break;
1537                 }
1538                 if (ret < 0 && ret != -ENOENT)
1539                         break;
1540                 ret = 0;
1541                 node = ulist_next(tmp, &uiter);
1542                 if (!node)
1543                         break;
1544                 bytenr = node->val;
1545                 shared.share_count = 0;
1546                 shared.have_delayed_delete_refs = false;
1547                 cond_resched();
1548         }
1549
1550         if (trans) {
1551                 btrfs_put_tree_mod_seq(fs_info, &elem);
1552                 btrfs_end_transaction(trans);
1553         } else {
1554                 up_read(&fs_info->commit_root_sem);
1555         }
1556 out:
1557         ulist_free(tmp);
1558         ulist_free(roots);
1559         return ret;
1560 }
1561
1562 int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
1563                           u64 start_off, struct btrfs_path *path,
1564                           struct btrfs_inode_extref **ret_extref,
1565                           u64 *found_off)
1566 {
1567         int ret, slot;
1568         struct btrfs_key key;
1569         struct btrfs_key found_key;
1570         struct btrfs_inode_extref *extref;
1571         const struct extent_buffer *leaf;
1572         unsigned long ptr;
1573
1574         key.objectid = inode_objectid;
1575         key.type = BTRFS_INODE_EXTREF_KEY;
1576         key.offset = start_off;
1577
1578         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1579         if (ret < 0)
1580                 return ret;
1581
1582         while (1) {
1583                 leaf = path->nodes[0];
1584                 slot = path->slots[0];
1585                 if (slot >= btrfs_header_nritems(leaf)) {
1586                         /*
1587                          * If the item at offset is not found,
1588                          * btrfs_search_slot will point us to the slot
1589                          * where it should be inserted. In our case
1590                          * that will be the slot directly before the
1591                          * next INODE_REF_KEY_V2 item. In the case
1592                          * that we're pointing to the last slot in a
1593                          * leaf, we must move one leaf over.
1594                          */
1595                         ret = btrfs_next_leaf(root, path);
1596                         if (ret) {
1597                                 if (ret >= 1)
1598                                         ret = -ENOENT;
1599                                 break;
1600                         }
1601                         continue;
1602                 }
1603
1604                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1605
1606                 /*
1607                  * Check that we're still looking at an extended ref key for
1608                  * this particular objectid. If we have different
1609                  * objectid or type then there are no more to be found
1610                  * in the tree and we can exit.
1611                  */
1612                 ret = -ENOENT;
1613                 if (found_key.objectid != inode_objectid)
1614                         break;
1615                 if (found_key.type != BTRFS_INODE_EXTREF_KEY)
1616                         break;
1617
1618                 ret = 0;
1619                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1620                 extref = (struct btrfs_inode_extref *)ptr;
1621                 *ret_extref = extref;
1622                 if (found_off)
1623                         *found_off = found_key.offset;
1624                 break;
1625         }
1626
1627         return ret;
1628 }
1629
1630 /*
1631  * this iterates to turn a name (from iref/extref) into a full filesystem path.
1632  * Elements of the path are separated by '/' and the path is guaranteed to be
1633  * 0-terminated. the path is only given within the current file system.
1634  * Therefore, it never starts with a '/'. the caller is responsible to provide
1635  * "size" bytes in "dest". the dest buffer will be filled backwards. finally,
1636  * the start point of the resulting string is returned. this pointer is within
1637  * dest, normally.
1638  * in case the path buffer would overflow, the pointer is decremented further
1639  * as if output was written to the buffer, though no more output is actually
1640  * generated. that way, the caller can determine how much space would be
1641  * required for the path to fit into the buffer. in that case, the returned
1642  * value will be smaller than dest. callers must check this!
1643  */
1644 char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
1645                         u32 name_len, unsigned long name_off,
1646                         struct extent_buffer *eb_in, u64 parent,
1647                         char *dest, u32 size)
1648 {
1649         int slot;
1650         u64 next_inum;
1651         int ret;
1652         s64 bytes_left = ((s64)size) - 1;
1653         struct extent_buffer *eb = eb_in;
1654         struct btrfs_key found_key;
1655         int leave_spinning = path->leave_spinning;
1656         struct btrfs_inode_ref *iref;
1657
1658         if (bytes_left >= 0)
1659                 dest[bytes_left] = '\0';
1660
1661         path->leave_spinning = 1;
1662         while (1) {
1663                 bytes_left -= name_len;
1664                 if (bytes_left >= 0)
1665                         read_extent_buffer(eb, dest + bytes_left,
1666                                            name_off, name_len);
1667                 if (eb != eb_in) {
1668                         if (!path->skip_locking)
1669                                 btrfs_tree_read_unlock_blocking(eb);
1670                         free_extent_buffer(eb);
1671                 }
1672                 ret = btrfs_find_item(fs_root, path, parent, 0,
1673                                 BTRFS_INODE_REF_KEY, &found_key);
1674                 if (ret > 0)
1675                         ret = -ENOENT;
1676                 if (ret)
1677                         break;
1678
1679                 next_inum = found_key.offset;
1680
1681                 /* regular exit ahead */
1682                 if (parent == next_inum)
1683                         break;
1684
1685                 slot = path->slots[0];
1686                 eb = path->nodes[0];
1687                 /* make sure we can use eb after releasing the path */
1688                 if (eb != eb_in) {
1689                         if (!path->skip_locking)
1690                                 btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
1691                         path->nodes[0] = NULL;
1692                         path->locks[0] = 0;
1693                 }
1694                 btrfs_release_path(path);
1695                 iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1696
1697                 name_len = btrfs_inode_ref_name_len(eb, iref);
1698                 name_off = (unsigned long)(iref + 1);
1699
1700                 parent = next_inum;
1701                 --bytes_left;
1702                 if (bytes_left >= 0)
1703                         dest[bytes_left] = '/';
1704         }
1705
1706         btrfs_release_path(path);
1707         path->leave_spinning = leave_spinning;
1708
1709         if (ret)
1710                 return ERR_PTR(ret);
1711
1712         return dest + bytes_left;
1713 }
1714
1715 /*
1716  * this makes the path point to (logical EXTENT_ITEM *)
1717  * returns BTRFS_EXTENT_FLAG_DATA for data, BTRFS_EXTENT_FLAG_TREE_BLOCK for
1718  * tree blocks and <0 on error.
1719  */
1720 int extent_from_logical(struct btrfs_fs_info *fs_info, u64 logical,
1721                         struct btrfs_path *path, struct btrfs_key *found_key,
1722                         u64 *flags_ret)
1723 {
1724         int ret;
1725         u64 flags;
1726         u64 size = 0;
1727         u32 item_size;
1728         const struct extent_buffer *eb;
1729         struct btrfs_extent_item *ei;
1730         struct btrfs_key key;
1731
1732         if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1733                 key.type = BTRFS_METADATA_ITEM_KEY;
1734         else
1735                 key.type = BTRFS_EXTENT_ITEM_KEY;
1736         key.objectid = logical;
1737         key.offset = (u64)-1;
1738
1739         ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
1740         if (ret < 0)
1741                 return ret;
1742
1743         ret = btrfs_previous_extent_item(fs_info->extent_root, path, 0);
1744         if (ret) {
1745                 if (ret > 0)
1746                         ret = -ENOENT;
1747                 return ret;
1748         }
1749         btrfs_item_key_to_cpu(path->nodes[0], found_key, path->slots[0]);
1750         if (found_key->type == BTRFS_METADATA_ITEM_KEY)
1751                 size = fs_info->nodesize;
1752         else if (found_key->type == BTRFS_EXTENT_ITEM_KEY)
1753                 size = found_key->offset;
1754
1755         if (found_key->objectid > logical ||
1756             found_key->objectid + size <= logical) {
1757                 btrfs_debug(fs_info,
1758                         "logical %llu is not within any extent", logical);
1759                 return -ENOENT;
1760         }
1761
1762         eb = path->nodes[0];
1763         item_size = btrfs_item_size_nr(eb, path->slots[0]);
1764         BUG_ON(item_size < sizeof(*ei));
1765
1766         ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
1767         flags = btrfs_extent_flags(eb, ei);
1768
1769         btrfs_debug(fs_info,
1770                 "logical %llu is at position %llu within the extent (%llu EXTENT_ITEM %llu) flags %#llx size %u",
1771                  logical, logical - found_key->objectid, found_key->objectid,
1772                  found_key->offset, flags, item_size);
1773
1774         WARN_ON(!flags_ret);
1775         if (flags_ret) {
1776                 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
1777                         *flags_ret = BTRFS_EXTENT_FLAG_TREE_BLOCK;
1778                 else if (flags & BTRFS_EXTENT_FLAG_DATA)
1779                         *flags_ret = BTRFS_EXTENT_FLAG_DATA;
1780                 else
1781                         BUG_ON(1);
1782                 return 0;
1783         }
1784
1785         return -EIO;
1786 }
1787
1788 /*
1789  * helper function to iterate extent inline refs. ptr must point to a 0 value
1790  * for the first call and may be modified. it is used to track state.
1791  * if more refs exist, 0 is returned and the next call to
1792  * get_extent_inline_ref must pass the modified ptr parameter to get the
1793  * next ref. after the last ref was processed, 1 is returned.
1794  * returns <0 on error
1795  */
1796 static int get_extent_inline_ref(unsigned long *ptr,
1797                                  const struct extent_buffer *eb,
1798                                  const struct btrfs_key *key,
1799                                  const struct btrfs_extent_item *ei,
1800                                  u32 item_size,
1801                                  struct btrfs_extent_inline_ref **out_eiref,
1802                                  int *out_type)
1803 {
1804         unsigned long end;
1805         u64 flags;
1806         struct btrfs_tree_block_info *info;
1807
1808         if (!*ptr) {
1809                 /* first call */
1810                 flags = btrfs_extent_flags(eb, ei);
1811                 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1812                         if (key->type == BTRFS_METADATA_ITEM_KEY) {
1813                                 /* a skinny metadata extent */
1814                                 *out_eiref =
1815                                      (struct btrfs_extent_inline_ref *)(ei + 1);
1816                         } else {
1817                                 WARN_ON(key->type != BTRFS_EXTENT_ITEM_KEY);
1818                                 info = (struct btrfs_tree_block_info *)(ei + 1);
1819                                 *out_eiref =
1820                                    (struct btrfs_extent_inline_ref *)(info + 1);
1821                         }
1822                 } else {
1823                         *out_eiref = (struct btrfs_extent_inline_ref *)(ei + 1);
1824                 }
1825                 *ptr = (unsigned long)*out_eiref;
1826                 if ((unsigned long)(*ptr) >= (unsigned long)ei + item_size)
1827                         return -ENOENT;
1828         }
1829
1830         end = (unsigned long)ei + item_size;
1831         *out_eiref = (struct btrfs_extent_inline_ref *)(*ptr);
1832         *out_type = btrfs_get_extent_inline_ref_type(eb, *out_eiref,
1833                                                      BTRFS_REF_TYPE_ANY);
1834         if (*out_type == BTRFS_REF_TYPE_INVALID)
1835                 return -EUCLEAN;
1836
1837         *ptr += btrfs_extent_inline_ref_size(*out_type);
1838         WARN_ON(*ptr > end);
1839         if (*ptr == end)
1840                 return 1; /* last */
1841
1842         return 0;
1843 }
1844
1845 /*
1846  * reads the tree block backref for an extent. tree level and root are returned
1847  * through out_level and out_root. ptr must point to a 0 value for the first
1848  * call and may be modified (see get_extent_inline_ref comment).
1849  * returns 0 if data was provided, 1 if there was no more data to provide or
1850  * <0 on error.
1851  */
1852 int tree_backref_for_extent(unsigned long *ptr, struct extent_buffer *eb,
1853                             struct btrfs_key *key, struct btrfs_extent_item *ei,
1854                             u32 item_size, u64 *out_root, u8 *out_level)
1855 {
1856         int ret;
1857         int type;
1858         struct btrfs_extent_inline_ref *eiref;
1859
1860         if (*ptr == (unsigned long)-1)
1861                 return 1;
1862
1863         while (1) {
1864                 ret = get_extent_inline_ref(ptr, eb, key, ei, item_size,
1865                                               &eiref, &type);
1866                 if (ret < 0)
1867                         return ret;
1868
1869                 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1870                     type == BTRFS_SHARED_BLOCK_REF_KEY)
1871                         break;
1872
1873                 if (ret == 1)
1874                         return 1;
1875         }
1876
1877         /* we can treat both ref types equally here */
1878         *out_root = btrfs_extent_inline_ref_offset(eb, eiref);
1879
1880         if (key->type == BTRFS_EXTENT_ITEM_KEY) {
1881                 struct btrfs_tree_block_info *info;
1882
1883                 info = (struct btrfs_tree_block_info *)(ei + 1);
1884                 *out_level = btrfs_tree_block_level(eb, info);
1885         } else {
1886                 ASSERT(key->type == BTRFS_METADATA_ITEM_KEY);
1887                 *out_level = (u8)key->offset;
1888         }
1889
1890         if (ret == 1)
1891                 *ptr = (unsigned long)-1;
1892
1893         return 0;
1894 }
1895
1896 static int iterate_leaf_refs(struct btrfs_fs_info *fs_info,
1897                              struct extent_inode_elem *inode_list,
1898                              u64 root, u64 extent_item_objectid,
1899                              iterate_extent_inodes_t *iterate, void *ctx)
1900 {
1901         struct extent_inode_elem *eie;
1902         int ret = 0;
1903
1904         for (eie = inode_list; eie; eie = eie->next) {
1905                 btrfs_debug(fs_info,
1906                             "ref for %llu resolved, key (%llu EXTEND_DATA %llu), root %llu",
1907                             extent_item_objectid, eie->inum,
1908                             eie->offset, root);
1909                 ret = iterate(eie->inum, eie->offset, root, ctx);
1910                 if (ret) {
1911                         btrfs_debug(fs_info,
1912                                     "stopping iteration for %llu due to ret=%d",
1913                                     extent_item_objectid, ret);
1914                         break;
1915                 }
1916         }
1917
1918         return ret;
1919 }
1920
1921 /*
1922  * calls iterate() for every inode that references the extent identified by
1923  * the given parameters.
1924  * when the iterator function returns a non-zero value, iteration stops.
1925  */
1926 int iterate_extent_inodes(struct btrfs_fs_info *fs_info,
1927                                 u64 extent_item_objectid, u64 extent_item_pos,
1928                                 int search_commit_root,
1929                                 iterate_extent_inodes_t *iterate, void *ctx,
1930                                 bool ignore_offset)
1931 {
1932         int ret;
1933         struct btrfs_trans_handle *trans = NULL;
1934         struct ulist *refs = NULL;
1935         struct ulist *roots = NULL;
1936         struct ulist_node *ref_node = NULL;
1937         struct ulist_node *root_node = NULL;
1938         struct seq_list tree_mod_seq_elem = SEQ_LIST_INIT(tree_mod_seq_elem);
1939         struct ulist_iterator ref_uiter;
1940         struct ulist_iterator root_uiter;
1941
1942         btrfs_debug(fs_info, "resolving all inodes for extent %llu",
1943                         extent_item_objectid);
1944
1945         if (!search_commit_root) {
1946                 trans = btrfs_attach_transaction(fs_info->extent_root);
1947                 if (IS_ERR(trans)) {
1948                         if (PTR_ERR(trans) != -ENOENT &&
1949                             PTR_ERR(trans) != -EROFS)
1950                                 return PTR_ERR(trans);
1951                         trans = NULL;
1952                 }
1953         }
1954
1955         if (trans)
1956                 btrfs_get_tree_mod_seq(fs_info, &tree_mod_seq_elem);
1957         else
1958                 down_read(&fs_info->commit_root_sem);
1959
1960         ret = btrfs_find_all_leafs(trans, fs_info, extent_item_objectid,
1961                                    tree_mod_seq_elem.seq, &refs,
1962                                    &extent_item_pos, ignore_offset);
1963         if (ret)
1964                 goto out;
1965
1966         ULIST_ITER_INIT(&ref_uiter);
1967         while (!ret && (ref_node = ulist_next(refs, &ref_uiter))) {
1968                 ret = btrfs_find_all_roots_safe(trans, fs_info, ref_node->val,
1969                                                 tree_mod_seq_elem.seq, &roots,
1970                                                 ignore_offset);
1971                 if (ret)
1972                         break;
1973                 ULIST_ITER_INIT(&root_uiter);
1974                 while (!ret && (root_node = ulist_next(roots, &root_uiter))) {
1975                         btrfs_debug(fs_info,
1976                                     "root %llu references leaf %llu, data list %#llx",
1977                                     root_node->val, ref_node->val,
1978                                     ref_node->aux);
1979                         ret = iterate_leaf_refs(fs_info,
1980                                                 (struct extent_inode_elem *)
1981                                                 (uintptr_t)ref_node->aux,
1982                                                 root_node->val,
1983                                                 extent_item_objectid,
1984                                                 iterate, ctx);
1985                 }
1986                 ulist_free(roots);
1987         }
1988
1989         free_leaf_list(refs);
1990 out:
1991         if (trans) {
1992                 btrfs_put_tree_mod_seq(fs_info, &tree_mod_seq_elem);
1993                 btrfs_end_transaction(trans);
1994         } else {
1995                 up_read(&fs_info->commit_root_sem);
1996         }
1997
1998         return ret;
1999 }
2000
2001 int iterate_inodes_from_logical(u64 logical, struct btrfs_fs_info *fs_info,
2002                                 struct btrfs_path *path,
2003                                 iterate_extent_inodes_t *iterate, void *ctx,
2004                                 bool ignore_offset)
2005 {
2006         int ret;
2007         u64 extent_item_pos;
2008         u64 flags = 0;
2009         struct btrfs_key found_key;
2010         int search_commit_root = path->search_commit_root;
2011
2012         ret = extent_from_logical(fs_info, logical, path, &found_key, &flags);
2013         btrfs_release_path(path);
2014         if (ret < 0)
2015                 return ret;
2016         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
2017                 return -EINVAL;
2018
2019         extent_item_pos = logical - found_key.objectid;
2020         ret = iterate_extent_inodes(fs_info, found_key.objectid,
2021                                         extent_item_pos, search_commit_root,
2022                                         iterate, ctx, ignore_offset);
2023
2024         return ret;
2025 }
2026
2027 typedef int (iterate_irefs_t)(u64 parent, u32 name_len, unsigned long name_off,
2028                               struct extent_buffer *eb, void *ctx);
2029
2030 static int iterate_inode_refs(u64 inum, struct btrfs_root *fs_root,
2031                               struct btrfs_path *path,
2032                               iterate_irefs_t *iterate, void *ctx)
2033 {
2034         int ret = 0;
2035         int slot;
2036         u32 cur;
2037         u32 len;
2038         u32 name_len;
2039         u64 parent = 0;
2040         int found = 0;
2041         struct extent_buffer *eb;
2042         struct btrfs_item *item;
2043         struct btrfs_inode_ref *iref;
2044         struct btrfs_key found_key;
2045
2046         while (!ret) {
2047                 ret = btrfs_find_item(fs_root, path, inum,
2048                                 parent ? parent + 1 : 0, BTRFS_INODE_REF_KEY,
2049                                 &found_key);
2050
2051                 if (ret < 0)
2052                         break;
2053                 if (ret) {
2054                         ret = found ? 0 : -ENOENT;
2055                         break;
2056                 }
2057                 ++found;
2058
2059                 parent = found_key.offset;
2060                 slot = path->slots[0];
2061                 eb = btrfs_clone_extent_buffer(path->nodes[0]);
2062                 if (!eb) {
2063                         ret = -ENOMEM;
2064                         break;
2065                 }
2066                 extent_buffer_get(eb);
2067                 btrfs_tree_read_lock(eb);
2068                 btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
2069                 btrfs_release_path(path);
2070
2071                 item = btrfs_item_nr(slot);
2072                 iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2073
2074                 for (cur = 0; cur < btrfs_item_size(eb, item); cur += len) {
2075                         name_len = btrfs_inode_ref_name_len(eb, iref);
2076                         /* path must be released before calling iterate()! */
2077                         btrfs_debug(fs_root->fs_info,
2078                                 "following ref at offset %u for inode %llu in tree %llu",
2079                                 cur, found_key.objectid, fs_root->objectid);
2080                         ret = iterate(parent, name_len,
2081                                       (unsigned long)(iref + 1), eb, ctx);
2082                         if (ret)
2083                                 break;
2084                         len = sizeof(*iref) + name_len;
2085                         iref = (struct btrfs_inode_ref *)((char *)iref + len);
2086                 }
2087                 btrfs_tree_read_unlock_blocking(eb);
2088                 free_extent_buffer(eb);
2089         }
2090
2091         btrfs_release_path(path);
2092
2093         return ret;
2094 }
2095
2096 static int iterate_inode_extrefs(u64 inum, struct btrfs_root *fs_root,
2097                                  struct btrfs_path *path,
2098                                  iterate_irefs_t *iterate, void *ctx)
2099 {
2100         int ret;
2101         int slot;
2102         u64 offset = 0;
2103         u64 parent;
2104         int found = 0;
2105         struct extent_buffer *eb;
2106         struct btrfs_inode_extref *extref;
2107         u32 item_size;
2108         u32 cur_offset;
2109         unsigned long ptr;
2110
2111         while (1) {
2112                 ret = btrfs_find_one_extref(fs_root, inum, offset, path, &extref,
2113                                             &offset);
2114                 if (ret < 0)
2115                         break;
2116                 if (ret) {
2117                         ret = found ? 0 : -ENOENT;
2118                         break;
2119                 }
2120                 ++found;
2121
2122                 slot = path->slots[0];
2123                 eb = btrfs_clone_extent_buffer(path->nodes[0]);
2124                 if (!eb) {
2125                         ret = -ENOMEM;
2126                         break;
2127                 }
2128                 extent_buffer_get(eb);
2129
2130                 btrfs_tree_read_lock(eb);
2131                 btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
2132                 btrfs_release_path(path);
2133
2134                 item_size = btrfs_item_size_nr(eb, slot);
2135                 ptr = btrfs_item_ptr_offset(eb, slot);
2136                 cur_offset = 0;
2137
2138                 while (cur_offset < item_size) {
2139                         u32 name_len;
2140
2141                         extref = (struct btrfs_inode_extref *)(ptr + cur_offset);
2142                         parent = btrfs_inode_extref_parent(eb, extref);
2143                         name_len = btrfs_inode_extref_name_len(eb, extref);
2144                         ret = iterate(parent, name_len,
2145                                       (unsigned long)&extref->name, eb, ctx);
2146                         if (ret)
2147                                 break;
2148
2149                         cur_offset += btrfs_inode_extref_name_len(eb, extref);
2150                         cur_offset += sizeof(*extref);
2151                 }
2152                 btrfs_tree_read_unlock_blocking(eb);
2153                 free_extent_buffer(eb);
2154
2155                 offset++;
2156         }
2157
2158         btrfs_release_path(path);
2159
2160         return ret;
2161 }
2162
2163 static int iterate_irefs(u64 inum, struct btrfs_root *fs_root,
2164                          struct btrfs_path *path, iterate_irefs_t *iterate,
2165                          void *ctx)
2166 {
2167         int ret;
2168         int found_refs = 0;
2169
2170         ret = iterate_inode_refs(inum, fs_root, path, iterate, ctx);
2171         if (!ret)
2172                 ++found_refs;
2173         else if (ret != -ENOENT)
2174                 return ret;
2175
2176         ret = iterate_inode_extrefs(inum, fs_root, path, iterate, ctx);
2177         if (ret == -ENOENT && found_refs)
2178                 return 0;
2179
2180         return ret;
2181 }
2182
2183 /*
2184  * returns 0 if the path could be dumped (probably truncated)
2185  * returns <0 in case of an error
2186  */
2187 static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
2188                          struct extent_buffer *eb, void *ctx)
2189 {
2190         struct inode_fs_paths *ipath = ctx;
2191         char *fspath;
2192         char *fspath_min;
2193         int i = ipath->fspath->elem_cnt;
2194         const int s_ptr = sizeof(char *);
2195         u32 bytes_left;
2196
2197         bytes_left = ipath->fspath->bytes_left > s_ptr ?
2198                                         ipath->fspath->bytes_left - s_ptr : 0;
2199
2200         fspath_min = (char *)ipath->fspath->val + (i + 1) * s_ptr;
2201         fspath = btrfs_ref_to_path(ipath->fs_root, ipath->btrfs_path, name_len,
2202                                    name_off, eb, inum, fspath_min, bytes_left);
2203         if (IS_ERR(fspath))
2204                 return PTR_ERR(fspath);
2205
2206         if (fspath > fspath_min) {
2207                 ipath->fspath->val[i] = (u64)(unsigned long)fspath;
2208                 ++ipath->fspath->elem_cnt;
2209                 ipath->fspath->bytes_left = fspath - fspath_min;
2210         } else {
2211                 ++ipath->fspath->elem_missed;
2212                 ipath->fspath->bytes_missing += fspath_min - fspath;
2213                 ipath->fspath->bytes_left = 0;
2214         }
2215
2216         return 0;
2217 }
2218
2219 /*
2220  * this dumps all file system paths to the inode into the ipath struct, provided
2221  * is has been created large enough. each path is zero-terminated and accessed
2222  * from ipath->fspath->val[i].
2223  * when it returns, there are ipath->fspath->elem_cnt number of paths available
2224  * in ipath->fspath->val[]. when the allocated space wasn't sufficient, the
2225  * number of missed paths is recorded in ipath->fspath->elem_missed, otherwise,
2226  * it's zero. ipath->fspath->bytes_missing holds the number of bytes that would
2227  * have been needed to return all paths.
2228  */
2229 int paths_from_inode(u64 inum, struct inode_fs_paths *ipath)
2230 {
2231         return iterate_irefs(inum, ipath->fs_root, ipath->btrfs_path,
2232                              inode_to_path, ipath);
2233 }
2234
2235 struct btrfs_data_container *init_data_container(u32 total_bytes)
2236 {
2237         struct btrfs_data_container *data;
2238         size_t alloc_bytes;
2239
2240         alloc_bytes = max_t(size_t, total_bytes, sizeof(*data));
2241         data = kvmalloc(alloc_bytes, GFP_KERNEL);
2242         if (!data)
2243                 return ERR_PTR(-ENOMEM);
2244
2245         if (total_bytes >= sizeof(*data)) {
2246                 data->bytes_left = total_bytes - sizeof(*data);
2247                 data->bytes_missing = 0;
2248         } else {
2249                 data->bytes_missing = sizeof(*data) - total_bytes;
2250                 data->bytes_left = 0;
2251         }
2252
2253         data->elem_cnt = 0;
2254         data->elem_missed = 0;
2255
2256         return data;
2257 }
2258
2259 /*
2260  * allocates space to return multiple file system paths for an inode.
2261  * total_bytes to allocate are passed, note that space usable for actual path
2262  * information will be total_bytes - sizeof(struct inode_fs_paths).
2263  * the returned pointer must be freed with free_ipath() in the end.
2264  */
2265 struct inode_fs_paths *init_ipath(s32 total_bytes, struct btrfs_root *fs_root,
2266                                         struct btrfs_path *path)
2267 {
2268         struct inode_fs_paths *ifp;
2269         struct btrfs_data_container *fspath;
2270
2271         fspath = init_data_container(total_bytes);
2272         if (IS_ERR(fspath))
2273                 return ERR_CAST(fspath);
2274
2275         ifp = kmalloc(sizeof(*ifp), GFP_KERNEL);
2276         if (!ifp) {
2277                 kvfree(fspath);
2278                 return ERR_PTR(-ENOMEM);
2279         }
2280
2281         ifp->btrfs_path = path;
2282         ifp->fspath = fspath;
2283         ifp->fs_root = fs_root;
2284
2285         return ifp;
2286 }
2287
2288 void free_ipath(struct inode_fs_paths *ipath)
2289 {
2290         if (!ipath)
2291                 return;
2292         kvfree(ipath->fspath);
2293         kfree(ipath);
2294 }