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