btrfs: move btrfs_account_ro_block_groups_free_space into space-info.c
[linux-block.git] / fs / btrfs / backref.c
CommitLineData
c1d7c514 1// SPDX-License-Identifier: GPL-2.0
a542ad1b
JS
2/*
3 * Copyright (C) 2011 STRATO. All rights reserved.
a542ad1b
JS
4 */
5
f54de068 6#include <linux/mm.h>
afce772e 7#include <linux/rbtree.h>
00142756 8#include <trace/events/btrfs.h>
a542ad1b
JS
9#include "ctree.h"
10#include "disk-io.h"
11#include "backref.h"
8da6d581
JS
12#include "ulist.h"
13#include "transaction.h"
14#include "delayed-ref.h"
b916a59a 15#include "locking.h"
1b60d2ec 16#include "misc.h"
f3a84ccd 17#include "tree-mod-log.h"
c7f13d42 18#include "fs.h"
07e81dc9 19#include "accessors.h"
a542ad1b 20
877c1476
FM
21/* Just arbitrary numbers so we can be sure one of these happened. */
22#define BACKREF_FOUND_SHARED 6
23#define BACKREF_FOUND_NOT_SHARED 7
dc046b10 24
976b1908
JS
25struct extent_inode_elem {
26 u64 inum;
27 u64 offset;
28 struct extent_inode_elem *next;
29};
30
73980bec
JM
31static int check_extent_in_eb(const struct btrfs_key *key,
32 const struct extent_buffer *eb,
33 const struct btrfs_file_extent_item *fi,
34 u64 extent_item_pos,
c995ab3c
ZB
35 struct extent_inode_elem **eie,
36 bool ignore_offset)
976b1908 37{
8ca15e05 38 u64 offset = 0;
976b1908
JS
39 struct extent_inode_elem *e;
40
c995ab3c
ZB
41 if (!ignore_offset &&
42 !btrfs_file_extent_compression(eb, fi) &&
8ca15e05
JB
43 !btrfs_file_extent_encryption(eb, fi) &&
44 !btrfs_file_extent_other_encoding(eb, fi)) {
45 u64 data_offset;
46 u64 data_len;
976b1908 47
8ca15e05
JB
48 data_offset = btrfs_file_extent_offset(eb, fi);
49 data_len = btrfs_file_extent_num_bytes(eb, fi);
50
51 if (extent_item_pos < data_offset ||
52 extent_item_pos >= data_offset + data_len)
53 return 1;
54 offset = extent_item_pos - data_offset;
55 }
976b1908
JS
56
57 e = kmalloc(sizeof(*e), GFP_NOFS);
58 if (!e)
59 return -ENOMEM;
60
61 e->next = *eie;
62 e->inum = key->objectid;
8ca15e05 63 e->offset = key->offset + offset;
976b1908
JS
64 *eie = e;
65
66 return 0;
67}
68
f05c4746
WS
69static void free_inode_elem_list(struct extent_inode_elem *eie)
70{
71 struct extent_inode_elem *eie_next;
72
73 for (; eie; eie = eie_next) {
74 eie_next = eie->next;
75 kfree(eie);
76 }
77}
78
73980bec
JM
79static int find_extent_in_eb(const struct extent_buffer *eb,
80 u64 wanted_disk_byte, u64 extent_item_pos,
c995ab3c
ZB
81 struct extent_inode_elem **eie,
82 bool ignore_offset)
976b1908
JS
83{
84 u64 disk_byte;
85 struct btrfs_key key;
86 struct btrfs_file_extent_item *fi;
87 int slot;
88 int nritems;
89 int extent_type;
90 int ret;
91
92 /*
93 * from the shared data ref, we only have the leaf but we need
94 * the key. thus, we must look into all items and see that we
95 * find one (some) with a reference to our extent item.
96 */
97 nritems = btrfs_header_nritems(eb);
98 for (slot = 0; slot < nritems; ++slot) {
99 btrfs_item_key_to_cpu(eb, &key, slot);
100 if (key.type != BTRFS_EXTENT_DATA_KEY)
101 continue;
102 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
103 extent_type = btrfs_file_extent_type(eb, fi);
104 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
105 continue;
106 /* don't skip BTRFS_FILE_EXTENT_PREALLOC, we can handle that */
107 disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
108 if (disk_byte != wanted_disk_byte)
109 continue;
110
c995ab3c 111 ret = check_extent_in_eb(&key, eb, fi, extent_item_pos, eie, ignore_offset);
976b1908
JS
112 if (ret < 0)
113 return ret;
114 }
115
116 return 0;
117}
118
86d5f994 119struct preftree {
ecf160b4 120 struct rb_root_cached root;
6c336b21 121 unsigned int count;
86d5f994
EN
122};
123
ecf160b4 124#define PREFTREE_INIT { .root = RB_ROOT_CACHED, .count = 0 }
86d5f994
EN
125
126struct preftrees {
127 struct preftree direct; /* BTRFS_SHARED_[DATA|BLOCK]_REF_KEY */
128 struct preftree indirect; /* BTRFS_[TREE_BLOCK|EXTENT_DATA]_REF_KEY */
129 struct preftree indirect_missing_keys;
130};
131
3ec4d323
EN
132/*
133 * Checks for a shared extent during backref search.
134 *
135 * The share_count tracks prelim_refs (direct and indirect) having a
136 * ref->count >0:
137 * - incremented when a ref->count transitions to >0
138 * - decremented when a ref->count transitions to <1
139 */
140struct share_check {
877c1476
FM
141 struct btrfs_backref_share_check_ctx *ctx;
142 struct btrfs_root *root;
3ec4d323 143 u64 inum;
73e339e6 144 u64 data_bytenr;
6976201f 145 u64 data_extent_gen;
73e339e6
FM
146 /*
147 * Counts number of inodes that refer to an extent (different inodes in
148 * the same root or different roots) that we could find. The sharedness
149 * check typically stops once this counter gets greater than 1, so it
150 * may not reflect the total number of inodes.
151 */
3ec4d323 152 int share_count;
73e339e6
FM
153 /*
154 * The number of times we found our inode refers to the data extent we
155 * are determining the sharedness. In other words, how many file extent
156 * items we could find for our inode that point to our target data
157 * extent. The value we get here after finishing the extent sharedness
158 * check may be smaller than reality, but if it ends up being greater
159 * than 1, then we know for sure the inode has multiple file extent
160 * items that point to our inode, and we can safely assume it's useful
161 * to cache the sharedness check result.
162 */
163 int self_ref_count;
4fc7b572 164 bool have_delayed_delete_refs;
3ec4d323
EN
165};
166
167static inline int extent_is_shared(struct share_check *sc)
168{
169 return (sc && sc->share_count > 1) ? BACKREF_FOUND_SHARED : 0;
170}
171
b9e9a6cb
WS
172static struct kmem_cache *btrfs_prelim_ref_cache;
173
174int __init btrfs_prelim_ref_init(void)
175{
176 btrfs_prelim_ref_cache = kmem_cache_create("btrfs_prelim_ref",
e0c476b1 177 sizeof(struct prelim_ref),
b9e9a6cb 178 0,
fba4b697 179 SLAB_MEM_SPREAD,
b9e9a6cb
WS
180 NULL);
181 if (!btrfs_prelim_ref_cache)
182 return -ENOMEM;
183 return 0;
184}
185
e67c718b 186void __cold btrfs_prelim_ref_exit(void)
b9e9a6cb 187{
5598e900 188 kmem_cache_destroy(btrfs_prelim_ref_cache);
b9e9a6cb
WS
189}
190
86d5f994
EN
191static void free_pref(struct prelim_ref *ref)
192{
193 kmem_cache_free(btrfs_prelim_ref_cache, ref);
194}
195
196/*
197 * Return 0 when both refs are for the same block (and can be merged).
198 * A -1 return indicates ref1 is a 'lower' block than ref2, while 1
199 * indicates a 'higher' block.
200 */
201static int prelim_ref_compare(struct prelim_ref *ref1,
202 struct prelim_ref *ref2)
203{
204 if (ref1->level < ref2->level)
205 return -1;
206 if (ref1->level > ref2->level)
207 return 1;
208 if (ref1->root_id < ref2->root_id)
209 return -1;
210 if (ref1->root_id > ref2->root_id)
211 return 1;
212 if (ref1->key_for_search.type < ref2->key_for_search.type)
213 return -1;
214 if (ref1->key_for_search.type > ref2->key_for_search.type)
215 return 1;
216 if (ref1->key_for_search.objectid < ref2->key_for_search.objectid)
217 return -1;
218 if (ref1->key_for_search.objectid > ref2->key_for_search.objectid)
219 return 1;
220 if (ref1->key_for_search.offset < ref2->key_for_search.offset)
221 return -1;
222 if (ref1->key_for_search.offset > ref2->key_for_search.offset)
223 return 1;
224 if (ref1->parent < ref2->parent)
225 return -1;
226 if (ref1->parent > ref2->parent)
227 return 1;
228
229 return 0;
230}
231
ccc8dc75 232static void update_share_count(struct share_check *sc, int oldcount,
73e339e6 233 int newcount, struct prelim_ref *newref)
3ec4d323
EN
234{
235 if ((!sc) || (oldcount == 0 && newcount < 1))
236 return;
237
238 if (oldcount > 0 && newcount < 1)
239 sc->share_count--;
240 else if (oldcount < 1 && newcount > 0)
241 sc->share_count++;
73e339e6 242
877c1476 243 if (newref->root_id == sc->root->root_key.objectid &&
73e339e6
FM
244 newref->wanted_disk_byte == sc->data_bytenr &&
245 newref->key_for_search.objectid == sc->inum)
246 sc->self_ref_count += newref->count;
3ec4d323
EN
247}
248
86d5f994
EN
249/*
250 * Add @newref to the @root rbtree, merging identical refs.
251 *
3ec4d323 252 * Callers should assume that newref has been freed after calling.
86d5f994 253 */
00142756
JM
254static void prelim_ref_insert(const struct btrfs_fs_info *fs_info,
255 struct preftree *preftree,
3ec4d323
EN
256 struct prelim_ref *newref,
257 struct share_check *sc)
86d5f994 258{
ecf160b4 259 struct rb_root_cached *root;
86d5f994
EN
260 struct rb_node **p;
261 struct rb_node *parent = NULL;
262 struct prelim_ref *ref;
263 int result;
ecf160b4 264 bool leftmost = true;
86d5f994
EN
265
266 root = &preftree->root;
ecf160b4 267 p = &root->rb_root.rb_node;
86d5f994
EN
268
269 while (*p) {
270 parent = *p;
271 ref = rb_entry(parent, struct prelim_ref, rbnode);
272 result = prelim_ref_compare(ref, newref);
273 if (result < 0) {
274 p = &(*p)->rb_left;
275 } else if (result > 0) {
276 p = &(*p)->rb_right;
ecf160b4 277 leftmost = false;
86d5f994
EN
278 } else {
279 /* Identical refs, merge them and free @newref */
280 struct extent_inode_elem *eie = ref->inode_list;
281
282 while (eie && eie->next)
283 eie = eie->next;
284
285 if (!eie)
286 ref->inode_list = newref->inode_list;
287 else
288 eie->next = newref->inode_list;
00142756
JM
289 trace_btrfs_prelim_ref_merge(fs_info, ref, newref,
290 preftree->count);
3ec4d323
EN
291 /*
292 * A delayed ref can have newref->count < 0.
293 * The ref->count is updated to follow any
294 * BTRFS_[ADD|DROP]_DELAYED_REF actions.
295 */
296 update_share_count(sc, ref->count,
73e339e6 297 ref->count + newref->count, newref);
86d5f994
EN
298 ref->count += newref->count;
299 free_pref(newref);
300 return;
301 }
302 }
303
73e339e6 304 update_share_count(sc, 0, newref->count, newref);
6c336b21 305 preftree->count++;
00142756 306 trace_btrfs_prelim_ref_insert(fs_info, newref, NULL, preftree->count);
86d5f994 307 rb_link_node(&newref->rbnode, parent, p);
ecf160b4 308 rb_insert_color_cached(&newref->rbnode, root, leftmost);
86d5f994
EN
309}
310
311/*
312 * Release the entire tree. We don't care about internal consistency so
313 * just free everything and then reset the tree root.
314 */
315static void prelim_release(struct preftree *preftree)
316{
317 struct prelim_ref *ref, *next_ref;
318
ecf160b4 319 rbtree_postorder_for_each_entry_safe(ref, next_ref,
92876eec
FM
320 &preftree->root.rb_root, rbnode) {
321 free_inode_elem_list(ref->inode_list);
86d5f994 322 free_pref(ref);
92876eec 323 }
86d5f994 324
ecf160b4 325 preftree->root = RB_ROOT_CACHED;
6c336b21 326 preftree->count = 0;
86d5f994
EN
327}
328
d5c88b73
JS
329/*
330 * the rules for all callers of this function are:
331 * - obtaining the parent is the goal
332 * - if you add a key, you must know that it is a correct key
333 * - if you cannot add the parent or a correct key, then we will look into the
334 * block later to set a correct key
335 *
336 * delayed refs
337 * ============
338 * backref type | shared | indirect | shared | indirect
339 * information | tree | tree | data | data
340 * --------------------+--------+----------+--------+----------
341 * parent logical | y | - | - | -
342 * key to resolve | - | y | y | y
343 * tree block logical | - | - | - | -
344 * root for resolving | y | y | y | y
345 *
346 * - column 1: we've the parent -> done
347 * - column 2, 3, 4: we use the key to find the parent
348 *
349 * on disk refs (inline or keyed)
350 * ==============================
351 * backref type | shared | indirect | shared | indirect
352 * information | tree | tree | data | data
353 * --------------------+--------+----------+--------+----------
354 * parent logical | y | - | y | -
355 * key to resolve | - | - | - | y
356 * tree block logical | y | y | y | y
357 * root for resolving | - | y | y | y
358 *
359 * - column 1, 3: we've the parent -> done
360 * - column 2: we take the first key from the block to find the parent
e0c476b1 361 * (see add_missing_keys)
d5c88b73
JS
362 * - column 4: we use the key to find the parent
363 *
364 * additional information that's available but not required to find the parent
365 * block might help in merging entries to gain some speed.
366 */
00142756
JM
367static int add_prelim_ref(const struct btrfs_fs_info *fs_info,
368 struct preftree *preftree, u64 root_id,
e0c476b1 369 const struct btrfs_key *key, int level, u64 parent,
3ec4d323
EN
370 u64 wanted_disk_byte, int count,
371 struct share_check *sc, gfp_t gfp_mask)
8da6d581 372{
e0c476b1 373 struct prelim_ref *ref;
8da6d581 374
48ec4736
LB
375 if (root_id == BTRFS_DATA_RELOC_TREE_OBJECTID)
376 return 0;
377
b9e9a6cb 378 ref = kmem_cache_alloc(btrfs_prelim_ref_cache, gfp_mask);
8da6d581
JS
379 if (!ref)
380 return -ENOMEM;
381
382 ref->root_id = root_id;
7ac8b88e 383 if (key)
d5c88b73 384 ref->key_for_search = *key;
7ac8b88e 385 else
d5c88b73 386 memset(&ref->key_for_search, 0, sizeof(ref->key_for_search));
8da6d581 387
3301958b 388 ref->inode_list = NULL;
8da6d581
JS
389 ref->level = level;
390 ref->count = count;
391 ref->parent = parent;
392 ref->wanted_disk_byte = wanted_disk_byte;
3ec4d323
EN
393 prelim_ref_insert(fs_info, preftree, ref, sc);
394 return extent_is_shared(sc);
8da6d581
JS
395}
396
86d5f994 397/* direct refs use root == 0, key == NULL */
00142756
JM
398static int add_direct_ref(const struct btrfs_fs_info *fs_info,
399 struct preftrees *preftrees, int level, u64 parent,
3ec4d323
EN
400 u64 wanted_disk_byte, int count,
401 struct share_check *sc, gfp_t gfp_mask)
86d5f994 402{
00142756 403 return add_prelim_ref(fs_info, &preftrees->direct, 0, NULL, level,
3ec4d323 404 parent, wanted_disk_byte, count, sc, gfp_mask);
86d5f994
EN
405}
406
407/* indirect refs use parent == 0 */
00142756
JM
408static int add_indirect_ref(const struct btrfs_fs_info *fs_info,
409 struct preftrees *preftrees, u64 root_id,
86d5f994 410 const struct btrfs_key *key, int level,
3ec4d323
EN
411 u64 wanted_disk_byte, int count,
412 struct share_check *sc, gfp_t gfp_mask)
86d5f994
EN
413{
414 struct preftree *tree = &preftrees->indirect;
415
416 if (!key)
417 tree = &preftrees->indirect_missing_keys;
00142756 418 return add_prelim_ref(fs_info, tree, root_id, key, level, 0,
3ec4d323 419 wanted_disk_byte, count, sc, gfp_mask);
86d5f994
EN
420}
421
ed58f2e6 422static int is_shared_data_backref(struct preftrees *preftrees, u64 bytenr)
423{
424 struct rb_node **p = &preftrees->direct.root.rb_root.rb_node;
425 struct rb_node *parent = NULL;
426 struct prelim_ref *ref = NULL;
9c6c723f 427 struct prelim_ref target = {};
ed58f2e6 428 int result;
429
430 target.parent = bytenr;
431
432 while (*p) {
433 parent = *p;
434 ref = rb_entry(parent, struct prelim_ref, rbnode);
435 result = prelim_ref_compare(ref, &target);
436
437 if (result < 0)
438 p = &(*p)->rb_left;
439 else if (result > 0)
440 p = &(*p)->rb_right;
441 else
442 return 1;
443 }
444 return 0;
445}
446
8da6d581 447static int add_all_parents(struct btrfs_root *root, struct btrfs_path *path,
ed58f2e6 448 struct ulist *parents,
449 struct preftrees *preftrees, struct prelim_ref *ref,
44853868 450 int level, u64 time_seq, const u64 *extent_item_pos,
b25b0b87 451 bool ignore_offset)
8da6d581 452{
69bca40d
AB
453 int ret = 0;
454 int slot;
455 struct extent_buffer *eb;
456 struct btrfs_key key;
7ef81ac8 457 struct btrfs_key *key_for_search = &ref->key_for_search;
8da6d581 458 struct btrfs_file_extent_item *fi;
ed8c4913 459 struct extent_inode_elem *eie = NULL, *old = NULL;
8da6d581 460 u64 disk_byte;
7ef81ac8
JB
461 u64 wanted_disk_byte = ref->wanted_disk_byte;
462 u64 count = 0;
7ac8b88e 463 u64 data_offset;
8da6d581 464
69bca40d
AB
465 if (level != 0) {
466 eb = path->nodes[level];
467 ret = ulist_add(parents, eb->start, 0, GFP_NOFS);
3301958b
JS
468 if (ret < 0)
469 return ret;
8da6d581 470 return 0;
69bca40d 471 }
8da6d581
JS
472
473 /*
ed58f2e6 474 * 1. We normally enter this function with the path already pointing to
475 * the first item to check. But sometimes, we may enter it with
476 * slot == nritems.
477 * 2. We are searching for normal backref but bytenr of this leaf
478 * matches shared data backref
cfc0eed0 479 * 3. The leaf owner is not equal to the root we are searching
480 *
ed58f2e6 481 * For these cases, go to the next leaf before we continue.
8da6d581 482 */
ed58f2e6 483 eb = path->nodes[0];
484 if (path->slots[0] >= btrfs_header_nritems(eb) ||
cfc0eed0 485 is_shared_data_backref(preftrees, eb->start) ||
486 ref->root_id != btrfs_header_owner(eb)) {
f3a84ccd 487 if (time_seq == BTRFS_SEQ_LAST)
21633fc6
QW
488 ret = btrfs_next_leaf(root, path);
489 else
490 ret = btrfs_next_old_leaf(root, path, time_seq);
491 }
8da6d581 492
b25b0b87 493 while (!ret && count < ref->count) {
8da6d581 494 eb = path->nodes[0];
69bca40d
AB
495 slot = path->slots[0];
496
497 btrfs_item_key_to_cpu(eb, &key, slot);
498
499 if (key.objectid != key_for_search->objectid ||
500 key.type != BTRFS_EXTENT_DATA_KEY)
501 break;
502
ed58f2e6 503 /*
504 * We are searching for normal backref but bytenr of this leaf
cfc0eed0 505 * matches shared data backref, OR
506 * the leaf owner is not equal to the root we are searching for
ed58f2e6 507 */
cfc0eed0 508 if (slot == 0 &&
509 (is_shared_data_backref(preftrees, eb->start) ||
510 ref->root_id != btrfs_header_owner(eb))) {
f3a84ccd 511 if (time_seq == BTRFS_SEQ_LAST)
ed58f2e6 512 ret = btrfs_next_leaf(root, path);
513 else
514 ret = btrfs_next_old_leaf(root, path, time_seq);
515 continue;
516 }
69bca40d
AB
517 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
518 disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
7ac8b88e 519 data_offset = btrfs_file_extent_offset(eb, fi);
69bca40d
AB
520
521 if (disk_byte == wanted_disk_byte) {
522 eie = NULL;
ed8c4913 523 old = NULL;
7ac8b88e 524 if (ref->key_for_search.offset == key.offset - data_offset)
525 count++;
526 else
527 goto next;
69bca40d
AB
528 if (extent_item_pos) {
529 ret = check_extent_in_eb(&key, eb, fi,
530 *extent_item_pos,
c995ab3c 531 &eie, ignore_offset);
69bca40d
AB
532 if (ret < 0)
533 break;
534 }
ed8c4913
JB
535 if (ret > 0)
536 goto next;
4eb1f66d
TI
537 ret = ulist_add_merge_ptr(parents, eb->start,
538 eie, (void **)&old, GFP_NOFS);
ed8c4913
JB
539 if (ret < 0)
540 break;
541 if (!ret && extent_item_pos) {
542 while (old->next)
543 old = old->next;
544 old->next = eie;
69bca40d 545 }
f05c4746 546 eie = NULL;
8da6d581 547 }
ed8c4913 548next:
f3a84ccd 549 if (time_seq == BTRFS_SEQ_LAST)
21633fc6
QW
550 ret = btrfs_next_item(root, path);
551 else
552 ret = btrfs_next_old_item(root, path, time_seq);
8da6d581
JS
553 }
554
69bca40d
AB
555 if (ret > 0)
556 ret = 0;
f05c4746
WS
557 else if (ret < 0)
558 free_inode_elem_list(eie);
69bca40d 559 return ret;
8da6d581
JS
560}
561
562/*
563 * resolve an indirect backref in the form (root_id, key, level)
564 * to a logical address
565 */
e0c476b1
JM
566static int resolve_indirect_ref(struct btrfs_fs_info *fs_info,
567 struct btrfs_path *path, u64 time_seq,
ed58f2e6 568 struct preftrees *preftrees,
e0c476b1 569 struct prelim_ref *ref, struct ulist *parents,
b25b0b87 570 const u64 *extent_item_pos, bool ignore_offset)
8da6d581 571{
8da6d581 572 struct btrfs_root *root;
8da6d581
JS
573 struct extent_buffer *eb;
574 int ret = 0;
575 int root_level;
576 int level = ref->level;
7ac8b88e 577 struct btrfs_key search_key = ref->key_for_search;
8da6d581 578
49d11bea
JB
579 /*
580 * If we're search_commit_root we could possibly be holding locks on
581 * other tree nodes. This happens when qgroups does backref walks when
582 * adding new delayed refs. To deal with this we need to look in cache
583 * for the root, and if we don't find it then we need to search the
584 * tree_root's commit root, thus the btrfs_get_fs_root_commit_root usage
585 * here.
586 */
587 if (path->search_commit_root)
588 root = btrfs_get_fs_root_commit_root(fs_info, path, ref->root_id);
589 else
590 root = btrfs_get_fs_root(fs_info, ref->root_id, false);
8da6d581
JS
591 if (IS_ERR(root)) {
592 ret = PTR_ERR(root);
9326f76f
JB
593 goto out_free;
594 }
595
39dba873
JB
596 if (!path->search_commit_root &&
597 test_bit(BTRFS_ROOT_DELETING, &root->state)) {
598 ret = -ENOENT;
599 goto out;
600 }
601
f5ee5c9a 602 if (btrfs_is_testing(fs_info)) {
d9ee522b
JB
603 ret = -ENOENT;
604 goto out;
605 }
606
9e351cc8
JB
607 if (path->search_commit_root)
608 root_level = btrfs_header_level(root->commit_root);
f3a84ccd 609 else if (time_seq == BTRFS_SEQ_LAST)
21633fc6 610 root_level = btrfs_header_level(root->node);
9e351cc8
JB
611 else
612 root_level = btrfs_old_root_level(root, time_seq);
8da6d581 613
c75e8394 614 if (root_level + 1 == level)
8da6d581
JS
615 goto out;
616
7ac8b88e 617 /*
618 * We can often find data backrefs with an offset that is too large
619 * (>= LLONG_MAX, maximum allowed file offset) due to underflows when
620 * subtracting a file's offset with the data offset of its
621 * corresponding extent data item. This can happen for example in the
622 * clone ioctl.
623 *
624 * So if we detect such case we set the search key's offset to zero to
625 * make sure we will find the matching file extent item at
626 * add_all_parents(), otherwise we will miss it because the offset
627 * taken form the backref is much larger then the offset of the file
628 * extent item. This can make us scan a very large number of file
629 * extent items, but at least it will not make us miss any.
630 *
631 * This is an ugly workaround for a behaviour that should have never
632 * existed, but it does and a fix for the clone ioctl would touch a lot
633 * of places, cause backwards incompatibility and would not fix the
634 * problem for extents cloned with older kernels.
635 */
636 if (search_key.type == BTRFS_EXTENT_DATA_KEY &&
637 search_key.offset >= LLONG_MAX)
638 search_key.offset = 0;
8da6d581 639 path->lowest_level = level;
f3a84ccd 640 if (time_seq == BTRFS_SEQ_LAST)
7ac8b88e 641 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
21633fc6 642 else
7ac8b88e 643 ret = btrfs_search_old_slot(root, &search_key, path, time_seq);
538f72cd 644
ab8d0fc4
JM
645 btrfs_debug(fs_info,
646 "search slot in root %llu (level %d, ref count %d) returned %d for key (%llu %u %llu)",
c1c9ff7c
GU
647 ref->root_id, level, ref->count, ret,
648 ref->key_for_search.objectid, ref->key_for_search.type,
649 ref->key_for_search.offset);
8da6d581
JS
650 if (ret < 0)
651 goto out;
652
653 eb = path->nodes[level];
9345457f 654 while (!eb) {
fae7f21c 655 if (WARN_ON(!level)) {
9345457f
JS
656 ret = 1;
657 goto out;
658 }
659 level--;
660 eb = path->nodes[level];
8da6d581
JS
661 }
662
ed58f2e6 663 ret = add_all_parents(root, path, parents, preftrees, ref, level,
b25b0b87 664 time_seq, extent_item_pos, ignore_offset);
8da6d581 665out:
00246528 666 btrfs_put_root(root);
9326f76f 667out_free:
da61d31a
JB
668 path->lowest_level = 0;
669 btrfs_release_path(path);
8da6d581
JS
670 return ret;
671}
672
4dae077a
JM
673static struct extent_inode_elem *
674unode_aux_to_inode_list(struct ulist_node *node)
675{
676 if (!node)
677 return NULL;
678 return (struct extent_inode_elem *)(uintptr_t)node->aux;
679}
680
5614dc3a
FM
681static void free_leaf_list(struct ulist *ulist)
682{
683 struct ulist_node *node;
684 struct ulist_iterator uiter;
685
686 ULIST_ITER_INIT(&uiter);
687 while ((node = ulist_next(ulist, &uiter)))
688 free_inode_elem_list(unode_aux_to_inode_list(node));
689
690 ulist_free(ulist);
691}
692
8da6d581 693/*
52042d8e 694 * We maintain three separate rbtrees: one for direct refs, one for
86d5f994
EN
695 * indirect refs which have a key, and one for indirect refs which do not
696 * have a key. Each tree does merge on insertion.
697 *
698 * Once all of the references are located, we iterate over the tree of
699 * indirect refs with missing keys. An appropriate key is located and
700 * the ref is moved onto the tree for indirect refs. After all missing
701 * keys are thus located, we iterate over the indirect ref tree, resolve
702 * each reference, and then insert the resolved reference onto the
703 * direct tree (merging there too).
704 *
705 * New backrefs (i.e., for parent nodes) are added to the appropriate
706 * rbtree as they are encountered. The new backrefs are subsequently
707 * resolved as above.
8da6d581 708 */
e0c476b1
JM
709static int resolve_indirect_refs(struct btrfs_fs_info *fs_info,
710 struct btrfs_path *path, u64 time_seq,
86d5f994 711 struct preftrees *preftrees,
b25b0b87 712 const u64 *extent_item_pos,
c995ab3c 713 struct share_check *sc, bool ignore_offset)
8da6d581
JS
714{
715 int err;
716 int ret = 0;
8da6d581
JS
717 struct ulist *parents;
718 struct ulist_node *node;
cd1b413c 719 struct ulist_iterator uiter;
86d5f994 720 struct rb_node *rnode;
8da6d581
JS
721
722 parents = ulist_alloc(GFP_NOFS);
723 if (!parents)
724 return -ENOMEM;
725
726 /*
86d5f994
EN
727 * We could trade memory usage for performance here by iterating
728 * the tree, allocating new refs for each insertion, and then
729 * freeing the entire indirect tree when we're done. In some test
730 * cases, the tree can grow quite large (~200k objects).
8da6d581 731 */
ecf160b4 732 while ((rnode = rb_first_cached(&preftrees->indirect.root))) {
86d5f994
EN
733 struct prelim_ref *ref;
734
735 ref = rb_entry(rnode, struct prelim_ref, rbnode);
736 if (WARN(ref->parent,
737 "BUG: direct ref found in indirect tree")) {
738 ret = -EINVAL;
739 goto out;
740 }
741
ecf160b4 742 rb_erase_cached(&ref->rbnode, &preftrees->indirect.root);
6c336b21 743 preftrees->indirect.count--;
86d5f994
EN
744
745 if (ref->count == 0) {
746 free_pref(ref);
8da6d581 747 continue;
86d5f994
EN
748 }
749
877c1476 750 if (sc && ref->root_id != sc->root->root_key.objectid) {
86d5f994 751 free_pref(ref);
dc046b10
JB
752 ret = BACKREF_FOUND_SHARED;
753 goto out;
754 }
ed58f2e6 755 err = resolve_indirect_ref(fs_info, path, time_seq, preftrees,
756 ref, parents, extent_item_pos,
b25b0b87 757 ignore_offset);
95def2ed
WS
758 /*
759 * we can only tolerate ENOENT,otherwise,we should catch error
760 * and return directly.
761 */
762 if (err == -ENOENT) {
3ec4d323
EN
763 prelim_ref_insert(fs_info, &preftrees->direct, ref,
764 NULL);
8da6d581 765 continue;
95def2ed 766 } else if (err) {
86d5f994 767 free_pref(ref);
95def2ed
WS
768 ret = err;
769 goto out;
770 }
8da6d581
JS
771
772 /* we put the first parent into the ref at hand */
cd1b413c
JS
773 ULIST_ITER_INIT(&uiter);
774 node = ulist_next(parents, &uiter);
8da6d581 775 ref->parent = node ? node->val : 0;
4dae077a 776 ref->inode_list = unode_aux_to_inode_list(node);
8da6d581 777
86d5f994 778 /* Add a prelim_ref(s) for any other parent(s). */
cd1b413c 779 while ((node = ulist_next(parents, &uiter))) {
86d5f994
EN
780 struct prelim_ref *new_ref;
781
b9e9a6cb
WS
782 new_ref = kmem_cache_alloc(btrfs_prelim_ref_cache,
783 GFP_NOFS);
8da6d581 784 if (!new_ref) {
86d5f994 785 free_pref(ref);
8da6d581 786 ret = -ENOMEM;
e36902d4 787 goto out;
8da6d581
JS
788 }
789 memcpy(new_ref, ref, sizeof(*ref));
790 new_ref->parent = node->val;
4dae077a 791 new_ref->inode_list = unode_aux_to_inode_list(node);
3ec4d323
EN
792 prelim_ref_insert(fs_info, &preftrees->direct,
793 new_ref, NULL);
8da6d581 794 }
86d5f994 795
3ec4d323 796 /*
52042d8e 797 * Now it's a direct ref, put it in the direct tree. We must
3ec4d323
EN
798 * do this last because the ref could be merged/freed here.
799 */
800 prelim_ref_insert(fs_info, &preftrees->direct, ref, NULL);
86d5f994 801
8da6d581 802 ulist_reinit(parents);
9dd14fd6 803 cond_resched();
8da6d581 804 }
e36902d4 805out:
5614dc3a
FM
806 /*
807 * We may have inode lists attached to refs in the parents ulist, so we
808 * must free them before freeing the ulist and its refs.
809 */
810 free_leaf_list(parents);
8da6d581
JS
811 return ret;
812}
813
d5c88b73
JS
814/*
815 * read tree blocks and add keys where required.
816 */
e0c476b1 817static int add_missing_keys(struct btrfs_fs_info *fs_info,
38e3eebf 818 struct preftrees *preftrees, bool lock)
d5c88b73 819{
e0c476b1 820 struct prelim_ref *ref;
d5c88b73 821 struct extent_buffer *eb;
86d5f994
EN
822 struct preftree *tree = &preftrees->indirect_missing_keys;
823 struct rb_node *node;
d5c88b73 824
ecf160b4 825 while ((node = rb_first_cached(&tree->root))) {
86d5f994 826 ref = rb_entry(node, struct prelim_ref, rbnode);
ecf160b4 827 rb_erase_cached(node, &tree->root);
86d5f994
EN
828
829 BUG_ON(ref->parent); /* should not be a direct ref */
830 BUG_ON(ref->key_for_search.type);
d5c88b73 831 BUG_ON(!ref->wanted_disk_byte);
86d5f994 832
1b7ec85e
JB
833 eb = read_tree_block(fs_info, ref->wanted_disk_byte,
834 ref->root_id, 0, ref->level - 1, NULL);
64c043de 835 if (IS_ERR(eb)) {
86d5f994 836 free_pref(ref);
64c043de 837 return PTR_ERR(eb);
4eb150d6
QW
838 }
839 if (!extent_buffer_uptodate(eb)) {
86d5f994 840 free_pref(ref);
416bc658
JB
841 free_extent_buffer(eb);
842 return -EIO;
843 }
4eb150d6 844
38e3eebf
JB
845 if (lock)
846 btrfs_tree_read_lock(eb);
d5c88b73
JS
847 if (btrfs_header_level(eb) == 0)
848 btrfs_item_key_to_cpu(eb, &ref->key_for_search, 0);
849 else
850 btrfs_node_key_to_cpu(eb, &ref->key_for_search, 0);
38e3eebf
JB
851 if (lock)
852 btrfs_tree_read_unlock(eb);
d5c88b73 853 free_extent_buffer(eb);
3ec4d323 854 prelim_ref_insert(fs_info, &preftrees->indirect, ref, NULL);
9dd14fd6 855 cond_resched();
d5c88b73
JS
856 }
857 return 0;
858}
859
8da6d581
JS
860/*
861 * add all currently queued delayed refs from this head whose seq nr is
862 * smaller or equal that seq to the list
863 */
00142756
JM
864static int add_delayed_refs(const struct btrfs_fs_info *fs_info,
865 struct btrfs_delayed_ref_head *head, u64 seq,
b25b0b87 866 struct preftrees *preftrees, struct share_check *sc)
8da6d581 867{
c6fc2454 868 struct btrfs_delayed_ref_node *node;
d5c88b73 869 struct btrfs_key key;
0e0adbcf 870 struct rb_node *n;
01747e92 871 int count;
b1375d64 872 int ret = 0;
8da6d581 873
d7df2c79 874 spin_lock(&head->lock);
e3d03965 875 for (n = rb_first_cached(&head->ref_tree); n; n = rb_next(n)) {
0e0adbcf
JB
876 node = rb_entry(n, struct btrfs_delayed_ref_node,
877 ref_node);
8da6d581
JS
878 if (node->seq > seq)
879 continue;
880
881 switch (node->action) {
882 case BTRFS_ADD_DELAYED_EXTENT:
883 case BTRFS_UPDATE_DELAYED_HEAD:
884 WARN_ON(1);
885 continue;
886 case BTRFS_ADD_DELAYED_REF:
01747e92 887 count = node->ref_mod;
8da6d581
JS
888 break;
889 case BTRFS_DROP_DELAYED_REF:
01747e92 890 count = node->ref_mod * -1;
8da6d581
JS
891 break;
892 default:
290342f6 893 BUG();
8da6d581
JS
894 }
895 switch (node->type) {
896 case BTRFS_TREE_BLOCK_REF_KEY: {
86d5f994 897 /* NORMAL INDIRECT METADATA backref */
8da6d581 898 struct btrfs_delayed_tree_ref *ref;
943553ef
FM
899 struct btrfs_key *key_ptr = NULL;
900
901 if (head->extent_op && head->extent_op->update_key) {
902 btrfs_disk_key_to_cpu(&key, &head->extent_op->key);
903 key_ptr = &key;
904 }
8da6d581
JS
905
906 ref = btrfs_delayed_node_to_tree_ref(node);
00142756 907 ret = add_indirect_ref(fs_info, preftrees, ref->root,
943553ef 908 key_ptr, ref->level + 1,
01747e92
EN
909 node->bytenr, count, sc,
910 GFP_ATOMIC);
8da6d581
JS
911 break;
912 }
913 case BTRFS_SHARED_BLOCK_REF_KEY: {
86d5f994 914 /* SHARED DIRECT METADATA backref */
8da6d581
JS
915 struct btrfs_delayed_tree_ref *ref;
916
917 ref = btrfs_delayed_node_to_tree_ref(node);
86d5f994 918
01747e92
EN
919 ret = add_direct_ref(fs_info, preftrees, ref->level + 1,
920 ref->parent, node->bytenr, count,
3ec4d323 921 sc, GFP_ATOMIC);
8da6d581
JS
922 break;
923 }
924 case BTRFS_EXTENT_DATA_REF_KEY: {
86d5f994 925 /* NORMAL INDIRECT DATA backref */
8da6d581 926 struct btrfs_delayed_data_ref *ref;
8da6d581
JS
927 ref = btrfs_delayed_node_to_data_ref(node);
928
929 key.objectid = ref->objectid;
930 key.type = BTRFS_EXTENT_DATA_KEY;
931 key.offset = ref->offset;
dc046b10
JB
932
933 /*
4fc7b572
FM
934 * If we have a share check context and a reference for
935 * another inode, we can't exit immediately. This is
936 * because even if this is a BTRFS_ADD_DELAYED_REF
937 * reference we may find next a BTRFS_DROP_DELAYED_REF
938 * which cancels out this ADD reference.
939 *
940 * If this is a DROP reference and there was no previous
941 * ADD reference, then we need to signal that when we
942 * process references from the extent tree (through
943 * add_inline_refs() and add_keyed_refs()), we should
944 * not exit early if we find a reference for another
945 * inode, because one of the delayed DROP references
946 * may cancel that reference in the extent tree.
dc046b10 947 */
4fc7b572
FM
948 if (sc && count < 0)
949 sc->have_delayed_delete_refs = true;
dc046b10 950
00142756 951 ret = add_indirect_ref(fs_info, preftrees, ref->root,
01747e92
EN
952 &key, 0, node->bytenr, count, sc,
953 GFP_ATOMIC);
8da6d581
JS
954 break;
955 }
956 case BTRFS_SHARED_DATA_REF_KEY: {
86d5f994 957 /* SHARED DIRECT FULL backref */
8da6d581 958 struct btrfs_delayed_data_ref *ref;
8da6d581
JS
959
960 ref = btrfs_delayed_node_to_data_ref(node);
86d5f994 961
01747e92
EN
962 ret = add_direct_ref(fs_info, preftrees, 0, ref->parent,
963 node->bytenr, count, sc,
964 GFP_ATOMIC);
8da6d581
JS
965 break;
966 }
967 default:
968 WARN_ON(1);
969 }
3ec4d323
EN
970 /*
971 * We must ignore BACKREF_FOUND_SHARED until all delayed
972 * refs have been checked.
973 */
974 if (ret && (ret != BACKREF_FOUND_SHARED))
d7df2c79 975 break;
8da6d581 976 }
3ec4d323
EN
977 if (!ret)
978 ret = extent_is_shared(sc);
4fc7b572 979
d7df2c79
JB
980 spin_unlock(&head->lock);
981 return ret;
8da6d581
JS
982}
983
984/*
985 * add all inline backrefs for bytenr to the list
3ec4d323
EN
986 *
987 * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
8da6d581 988 */
00142756
JM
989static int add_inline_refs(const struct btrfs_fs_info *fs_info,
990 struct btrfs_path *path, u64 bytenr,
86d5f994 991 int *info_level, struct preftrees *preftrees,
b25b0b87 992 struct share_check *sc)
8da6d581 993{
b1375d64 994 int ret = 0;
8da6d581
JS
995 int slot;
996 struct extent_buffer *leaf;
997 struct btrfs_key key;
261c84b6 998 struct btrfs_key found_key;
8da6d581
JS
999 unsigned long ptr;
1000 unsigned long end;
1001 struct btrfs_extent_item *ei;
1002 u64 flags;
1003 u64 item_size;
1004
1005 /*
1006 * enumerate all inline refs
1007 */
1008 leaf = path->nodes[0];
dadcaf78 1009 slot = path->slots[0];
8da6d581 1010
3212fa14 1011 item_size = btrfs_item_size(leaf, slot);
8da6d581
JS
1012 BUG_ON(item_size < sizeof(*ei));
1013
1014 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
1015 flags = btrfs_extent_flags(leaf, ei);
261c84b6 1016 btrfs_item_key_to_cpu(leaf, &found_key, slot);
8da6d581
JS
1017
1018 ptr = (unsigned long)(ei + 1);
1019 end = (unsigned long)ei + item_size;
1020
261c84b6
JB
1021 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
1022 flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
8da6d581 1023 struct btrfs_tree_block_info *info;
8da6d581
JS
1024
1025 info = (struct btrfs_tree_block_info *)ptr;
1026 *info_level = btrfs_tree_block_level(leaf, info);
8da6d581
JS
1027 ptr += sizeof(struct btrfs_tree_block_info);
1028 BUG_ON(ptr > end);
261c84b6
JB
1029 } else if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
1030 *info_level = found_key.offset;
8da6d581
JS
1031 } else {
1032 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
1033 }
1034
1035 while (ptr < end) {
1036 struct btrfs_extent_inline_ref *iref;
1037 u64 offset;
1038 int type;
1039
1040 iref = (struct btrfs_extent_inline_ref *)ptr;
3de28d57
LB
1041 type = btrfs_get_extent_inline_ref_type(leaf, iref,
1042 BTRFS_REF_TYPE_ANY);
1043 if (type == BTRFS_REF_TYPE_INVALID)
af431dcb 1044 return -EUCLEAN;
3de28d57 1045
8da6d581
JS
1046 offset = btrfs_extent_inline_ref_offset(leaf, iref);
1047
1048 switch (type) {
1049 case BTRFS_SHARED_BLOCK_REF_KEY:
00142756
JM
1050 ret = add_direct_ref(fs_info, preftrees,
1051 *info_level + 1, offset,
3ec4d323 1052 bytenr, 1, NULL, GFP_NOFS);
8da6d581
JS
1053 break;
1054 case BTRFS_SHARED_DATA_REF_KEY: {
1055 struct btrfs_shared_data_ref *sdref;
1056 int count;
1057
1058 sdref = (struct btrfs_shared_data_ref *)(iref + 1);
1059 count = btrfs_shared_data_ref_count(leaf, sdref);
86d5f994 1060
00142756 1061 ret = add_direct_ref(fs_info, preftrees, 0, offset,
3ec4d323 1062 bytenr, count, sc, GFP_NOFS);
8da6d581
JS
1063 break;
1064 }
1065 case BTRFS_TREE_BLOCK_REF_KEY:
00142756
JM
1066 ret = add_indirect_ref(fs_info, preftrees, offset,
1067 NULL, *info_level + 1,
3ec4d323 1068 bytenr, 1, NULL, GFP_NOFS);
8da6d581
JS
1069 break;
1070 case BTRFS_EXTENT_DATA_REF_KEY: {
1071 struct btrfs_extent_data_ref *dref;
1072 int count;
1073 u64 root;
1074
1075 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1076 count = btrfs_extent_data_ref_count(leaf, dref);
1077 key.objectid = btrfs_extent_data_ref_objectid(leaf,
1078 dref);
1079 key.type = BTRFS_EXTENT_DATA_KEY;
1080 key.offset = btrfs_extent_data_ref_offset(leaf, dref);
dc046b10 1081
a0a5472a 1082 if (sc && key.objectid != sc->inum &&
4fc7b572 1083 !sc->have_delayed_delete_refs) {
dc046b10
JB
1084 ret = BACKREF_FOUND_SHARED;
1085 break;
1086 }
1087
8da6d581 1088 root = btrfs_extent_data_ref_root(leaf, dref);
86d5f994 1089
00142756
JM
1090 ret = add_indirect_ref(fs_info, preftrees, root,
1091 &key, 0, bytenr, count,
3ec4d323 1092 sc, GFP_NOFS);
4fc7b572 1093
8da6d581
JS
1094 break;
1095 }
1096 default:
1097 WARN_ON(1);
1098 }
1149ab6b
WS
1099 if (ret)
1100 return ret;
8da6d581
JS
1101 ptr += btrfs_extent_inline_ref_size(type);
1102 }
1103
1104 return 0;
1105}
1106
1107/*
1108 * add all non-inline backrefs for bytenr to the list
3ec4d323
EN
1109 *
1110 * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
8da6d581 1111 */
98cc4222 1112static int add_keyed_refs(struct btrfs_root *extent_root,
e0c476b1 1113 struct btrfs_path *path, u64 bytenr,
86d5f994 1114 int info_level, struct preftrees *preftrees,
3ec4d323 1115 struct share_check *sc)
8da6d581 1116{
98cc4222 1117 struct btrfs_fs_info *fs_info = extent_root->fs_info;
8da6d581
JS
1118 int ret;
1119 int slot;
1120 struct extent_buffer *leaf;
1121 struct btrfs_key key;
1122
1123 while (1) {
1124 ret = btrfs_next_item(extent_root, path);
1125 if (ret < 0)
1126 break;
1127 if (ret) {
1128 ret = 0;
1129 break;
1130 }
1131
1132 slot = path->slots[0];
1133 leaf = path->nodes[0];
1134 btrfs_item_key_to_cpu(leaf, &key, slot);
1135
1136 if (key.objectid != bytenr)
1137 break;
1138 if (key.type < BTRFS_TREE_BLOCK_REF_KEY)
1139 continue;
1140 if (key.type > BTRFS_SHARED_DATA_REF_KEY)
1141 break;
1142
1143 switch (key.type) {
1144 case BTRFS_SHARED_BLOCK_REF_KEY:
86d5f994 1145 /* SHARED DIRECT METADATA backref */
00142756
JM
1146 ret = add_direct_ref(fs_info, preftrees,
1147 info_level + 1, key.offset,
3ec4d323 1148 bytenr, 1, NULL, GFP_NOFS);
8da6d581
JS
1149 break;
1150 case BTRFS_SHARED_DATA_REF_KEY: {
86d5f994 1151 /* SHARED DIRECT FULL backref */
8da6d581
JS
1152 struct btrfs_shared_data_ref *sdref;
1153 int count;
1154
1155 sdref = btrfs_item_ptr(leaf, slot,
1156 struct btrfs_shared_data_ref);
1157 count = btrfs_shared_data_ref_count(leaf, sdref);
00142756
JM
1158 ret = add_direct_ref(fs_info, preftrees, 0,
1159 key.offset, bytenr, count,
3ec4d323 1160 sc, GFP_NOFS);
8da6d581
JS
1161 break;
1162 }
1163 case BTRFS_TREE_BLOCK_REF_KEY:
86d5f994 1164 /* NORMAL INDIRECT METADATA backref */
00142756
JM
1165 ret = add_indirect_ref(fs_info, preftrees, key.offset,
1166 NULL, info_level + 1, bytenr,
3ec4d323 1167 1, NULL, GFP_NOFS);
8da6d581
JS
1168 break;
1169 case BTRFS_EXTENT_DATA_REF_KEY: {
86d5f994 1170 /* NORMAL INDIRECT DATA backref */
8da6d581
JS
1171 struct btrfs_extent_data_ref *dref;
1172 int count;
1173 u64 root;
1174
1175 dref = btrfs_item_ptr(leaf, slot,
1176 struct btrfs_extent_data_ref);
1177 count = btrfs_extent_data_ref_count(leaf, dref);
1178 key.objectid = btrfs_extent_data_ref_objectid(leaf,
1179 dref);
1180 key.type = BTRFS_EXTENT_DATA_KEY;
1181 key.offset = btrfs_extent_data_ref_offset(leaf, dref);
dc046b10 1182
a0a5472a 1183 if (sc && key.objectid != sc->inum &&
4fc7b572 1184 !sc->have_delayed_delete_refs) {
dc046b10
JB
1185 ret = BACKREF_FOUND_SHARED;
1186 break;
1187 }
1188
8da6d581 1189 root = btrfs_extent_data_ref_root(leaf, dref);
00142756
JM
1190 ret = add_indirect_ref(fs_info, preftrees, root,
1191 &key, 0, bytenr, count,
3ec4d323 1192 sc, GFP_NOFS);
8da6d581
JS
1193 break;
1194 }
1195 default:
1196 WARN_ON(1);
1197 }
1149ab6b
WS
1198 if (ret)
1199 return ret;
1200
8da6d581
JS
1201 }
1202
1203 return ret;
1204}
1205
583f4ac5
FM
1206/*
1207 * The caller has joined a transaction or is holding a read lock on the
1208 * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1209 * snapshot field changing while updating or checking the cache.
1210 */
1211static bool lookup_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1212 struct btrfs_root *root,
1213 u64 bytenr, int level, bool *is_shared)
1214{
1215 struct btrfs_backref_shared_cache_entry *entry;
1216
1217 if (!ctx->use_path_cache)
1218 return false;
1219
1220 if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1221 return false;
1222
1223 /*
1224 * Level -1 is used for the data extent, which is not reliable to cache
1225 * because its reference count can increase or decrease without us
1226 * realizing. We cache results only for extent buffers that lead from
1227 * the root node down to the leaf with the file extent item.
1228 */
1229 ASSERT(level >= 0);
1230
1231 entry = &ctx->path_cache_entries[level];
1232
1233 /* Unused cache entry or being used for some other extent buffer. */
1234 if (entry->bytenr != bytenr)
1235 return false;
1236
1237 /*
1238 * We cached a false result, but the last snapshot generation of the
1239 * root changed, so we now have a snapshot. Don't trust the result.
1240 */
1241 if (!entry->is_shared &&
1242 entry->gen != btrfs_root_last_snapshot(&root->root_item))
1243 return false;
1244
1245 /*
1246 * If we cached a true result and the last generation used for dropping
1247 * a root changed, we can not trust the result, because the dropped root
1248 * could be a snapshot sharing this extent buffer.
1249 */
1250 if (entry->is_shared &&
1251 entry->gen != btrfs_get_last_root_drop_gen(root->fs_info))
1252 return false;
1253
1254 *is_shared = entry->is_shared;
1255 /*
1256 * If the node at this level is shared, than all nodes below are also
1257 * shared. Currently some of the nodes below may be marked as not shared
1258 * because we have just switched from one leaf to another, and switched
1259 * also other nodes above the leaf and below the current level, so mark
1260 * them as shared.
1261 */
1262 if (*is_shared) {
1263 for (int i = 0; i < level; i++) {
1264 ctx->path_cache_entries[i].is_shared = true;
1265 ctx->path_cache_entries[i].gen = entry->gen;
1266 }
1267 }
1268
1269 return true;
1270}
1271
1272/*
1273 * The caller has joined a transaction or is holding a read lock on the
1274 * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
1275 * snapshot field changing while updating or checking the cache.
1276 */
1277static void store_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
1278 struct btrfs_root *root,
1279 u64 bytenr, int level, bool is_shared)
1280{
1281 struct btrfs_backref_shared_cache_entry *entry;
1282 u64 gen;
1283
1284 if (!ctx->use_path_cache)
1285 return;
1286
1287 if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
1288 return;
1289
1290 /*
1291 * Level -1 is used for the data extent, which is not reliable to cache
1292 * because its reference count can increase or decrease without us
1293 * realizing. We cache results only for extent buffers that lead from
1294 * the root node down to the leaf with the file extent item.
1295 */
1296 ASSERT(level >= 0);
1297
1298 if (is_shared)
1299 gen = btrfs_get_last_root_drop_gen(root->fs_info);
1300 else
1301 gen = btrfs_root_last_snapshot(&root->root_item);
1302
1303 entry = &ctx->path_cache_entries[level];
1304 entry->bytenr = bytenr;
1305 entry->is_shared = is_shared;
1306 entry->gen = gen;
1307
1308 /*
1309 * If we found an extent buffer is shared, set the cache result for all
1310 * extent buffers below it to true. As nodes in the path are COWed,
1311 * their sharedness is moved to their children, and if a leaf is COWed,
1312 * then the sharedness of a data extent becomes direct, the refcount of
1313 * data extent is increased in the extent item at the extent tree.
1314 */
1315 if (is_shared) {
1316 for (int i = 0; i < level; i++) {
1317 entry = &ctx->path_cache_entries[i];
1318 entry->is_shared = is_shared;
1319 entry->gen = gen;
1320 }
1321 }
1322}
1323
8da6d581
JS
1324/*
1325 * this adds all existing backrefs (inline backrefs, backrefs and delayed
1326 * refs) for the given bytenr to the refs list, merges duplicates and resolves
1327 * indirect refs to their parent bytenr.
1328 * When roots are found, they're added to the roots list
1329 *
f3a84ccd
FM
1330 * If time_seq is set to BTRFS_SEQ_LAST, it will not search delayed_refs, and
1331 * behave much like trans == NULL case, the difference only lies in it will not
21633fc6
QW
1332 * commit root.
1333 * The special case is for qgroup to search roots in commit_transaction().
1334 *
3ec4d323
EN
1335 * @sc - if !NULL, then immediately return BACKREF_FOUND_SHARED when a
1336 * shared extent is detected.
1337 *
1338 * Otherwise this returns 0 for success and <0 for an error.
1339 *
c995ab3c
ZB
1340 * If ignore_offset is set to false, only extent refs whose offsets match
1341 * extent_item_pos are returned. If true, every extent ref is returned
1342 * and extent_item_pos is ignored.
1343 *
8da6d581
JS
1344 * FIXME some caching might speed things up
1345 */
1346static int find_parent_nodes(struct btrfs_trans_handle *trans,
1347 struct btrfs_fs_info *fs_info, u64 bytenr,
097b8a7c 1348 u64 time_seq, struct ulist *refs,
dc046b10 1349 struct ulist *roots, const u64 *extent_item_pos,
c995ab3c 1350 struct share_check *sc, bool ignore_offset)
8da6d581 1351{
29cbcf40 1352 struct btrfs_root *root = btrfs_extent_root(fs_info, bytenr);
8da6d581
JS
1353 struct btrfs_key key;
1354 struct btrfs_path *path;
8da6d581 1355 struct btrfs_delayed_ref_root *delayed_refs = NULL;
d3b01064 1356 struct btrfs_delayed_ref_head *head;
8da6d581
JS
1357 int info_level = 0;
1358 int ret;
e0c476b1 1359 struct prelim_ref *ref;
86d5f994 1360 struct rb_node *node;
f05c4746 1361 struct extent_inode_elem *eie = NULL;
86d5f994
EN
1362 struct preftrees preftrees = {
1363 .direct = PREFTREE_INIT,
1364 .indirect = PREFTREE_INIT,
1365 .indirect_missing_keys = PREFTREE_INIT
1366 };
8da6d581 1367
56f5c199
FM
1368 /* Roots ulist is not needed when using a sharedness check context. */
1369 if (sc)
1370 ASSERT(roots == NULL);
1371
8da6d581 1372 key.objectid = bytenr;
8da6d581 1373 key.offset = (u64)-1;
261c84b6
JB
1374 if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1375 key.type = BTRFS_METADATA_ITEM_KEY;
1376 else
1377 key.type = BTRFS_EXTENT_ITEM_KEY;
8da6d581
JS
1378
1379 path = btrfs_alloc_path();
1380 if (!path)
1381 return -ENOMEM;
e84752d4 1382 if (!trans) {
da61d31a 1383 path->search_commit_root = 1;
e84752d4
WS
1384 path->skip_locking = 1;
1385 }
8da6d581 1386
f3a84ccd 1387 if (time_seq == BTRFS_SEQ_LAST)
21633fc6
QW
1388 path->skip_locking = 1;
1389
8da6d581 1390again:
d3b01064
LZ
1391 head = NULL;
1392
98cc4222 1393 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8da6d581
JS
1394 if (ret < 0)
1395 goto out;
fcba0120
JB
1396 if (ret == 0) {
1397 /* This shouldn't happen, indicates a bug or fs corruption. */
1398 ASSERT(ret != 0);
1399 ret = -EUCLEAN;
1400 goto out;
1401 }
8da6d581 1402
21633fc6 1403 if (trans && likely(trans->type != __TRANS_DUMMY) &&
f3a84ccd 1404 time_seq != BTRFS_SEQ_LAST) {
7a3ae2f8 1405 /*
9665ebd5
JB
1406 * We have a specific time_seq we care about and trans which
1407 * means we have the path lock, we need to grab the ref head and
1408 * lock it so we have a consistent view of the refs at the given
1409 * time.
7a3ae2f8
JS
1410 */
1411 delayed_refs = &trans->transaction->delayed_refs;
1412 spin_lock(&delayed_refs->lock);
f72ad18e 1413 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
7a3ae2f8
JS
1414 if (head) {
1415 if (!mutex_trylock(&head->mutex)) {
d278850e 1416 refcount_inc(&head->refs);
7a3ae2f8
JS
1417 spin_unlock(&delayed_refs->lock);
1418
1419 btrfs_release_path(path);
1420
1421 /*
1422 * Mutex was contended, block until it's
1423 * released and try again
1424 */
1425 mutex_lock(&head->mutex);
1426 mutex_unlock(&head->mutex);
d278850e 1427 btrfs_put_delayed_ref_head(head);
7a3ae2f8
JS
1428 goto again;
1429 }
d7df2c79 1430 spin_unlock(&delayed_refs->lock);
00142756 1431 ret = add_delayed_refs(fs_info, head, time_seq,
b25b0b87 1432 &preftrees, sc);
155725c9 1433 mutex_unlock(&head->mutex);
d7df2c79 1434 if (ret)
7a3ae2f8 1435 goto out;
d7df2c79
JB
1436 } else {
1437 spin_unlock(&delayed_refs->lock);
d3b01064 1438 }
8da6d581 1439 }
8da6d581
JS
1440
1441 if (path->slots[0]) {
1442 struct extent_buffer *leaf;
1443 int slot;
1444
dadcaf78 1445 path->slots[0]--;
8da6d581 1446 leaf = path->nodes[0];
dadcaf78 1447 slot = path->slots[0];
8da6d581
JS
1448 btrfs_item_key_to_cpu(leaf, &key, slot);
1449 if (key.objectid == bytenr &&
261c84b6
JB
1450 (key.type == BTRFS_EXTENT_ITEM_KEY ||
1451 key.type == BTRFS_METADATA_ITEM_KEY)) {
00142756 1452 ret = add_inline_refs(fs_info, path, bytenr,
b25b0b87 1453 &info_level, &preftrees, sc);
8da6d581
JS
1454 if (ret)
1455 goto out;
98cc4222 1456 ret = add_keyed_refs(root, path, bytenr, info_level,
3ec4d323 1457 &preftrees, sc);
8da6d581
JS
1458 if (ret)
1459 goto out;
1460 }
1461 }
8da6d581 1462
56f5c199
FM
1463 /*
1464 * If we have a share context and we reached here, it means the extent
1465 * is not directly shared (no multiple reference items for it),
1466 * otherwise we would have exited earlier with a return value of
1467 * BACKREF_FOUND_SHARED after processing delayed references or while
1468 * processing inline or keyed references from the extent tree.
1469 * The extent may however be indirectly shared through shared subtrees
1470 * as a result from creating snapshots, so we determine below what is
1471 * its parent node, in case we are dealing with a metadata extent, or
1472 * what's the leaf (or leaves), from a fs tree, that has a file extent
1473 * item pointing to it in case we are dealing with a data extent.
1474 */
1475 ASSERT(extent_is_shared(sc) == 0);
1476
877c1476
FM
1477 /*
1478 * If we are here for a data extent and we have a share_check structure
1479 * it means the data extent is not directly shared (does not have
1480 * multiple reference items), so we have to check if a path in the fs
1481 * tree (going from the root node down to the leaf that has the file
1482 * extent item pointing to the data extent) is shared, that is, if any
1483 * of the extent buffers in the path is referenced by other trees.
1484 */
1485 if (sc && bytenr == sc->data_bytenr) {
6976201f
FM
1486 /*
1487 * If our data extent is from a generation more recent than the
1488 * last generation used to snapshot the root, then we know that
1489 * it can not be shared through subtrees, so we can skip
1490 * resolving indirect references, there's no point in
1491 * determining the extent buffers for the path from the fs tree
1492 * root node down to the leaf that has the file extent item that
1493 * points to the data extent.
1494 */
1495 if (sc->data_extent_gen >
1496 btrfs_root_last_snapshot(&sc->root->root_item)) {
1497 ret = BACKREF_FOUND_NOT_SHARED;
1498 goto out;
1499 }
1500
877c1476
FM
1501 /*
1502 * If we are only determining if a data extent is shared or not
1503 * and the corresponding file extent item is located in the same
1504 * leaf as the previous file extent item, we can skip resolving
1505 * indirect references for a data extent, since the fs tree path
1506 * is the same (same leaf, so same path). We skip as long as the
1507 * cached result for the leaf is valid and only if there's only
1508 * one file extent item pointing to the data extent, because in
1509 * the case of multiple file extent items, they may be located
1510 * in different leaves and therefore we have multiple paths.
1511 */
1512 if (sc->ctx->curr_leaf_bytenr == sc->ctx->prev_leaf_bytenr &&
1513 sc->self_ref_count == 1) {
1514 bool cached;
1515 bool is_shared;
1516
1517 cached = lookup_backref_shared_cache(sc->ctx, sc->root,
1518 sc->ctx->curr_leaf_bytenr,
1519 0, &is_shared);
1520 if (cached) {
1521 if (is_shared)
1522 ret = BACKREF_FOUND_SHARED;
1523 else
1524 ret = BACKREF_FOUND_NOT_SHARED;
1525 goto out;
1526 }
1527 }
1528 }
1529
86d5f994 1530 btrfs_release_path(path);
8da6d581 1531
38e3eebf 1532 ret = add_missing_keys(fs_info, &preftrees, path->skip_locking == 0);
d5c88b73
JS
1533 if (ret)
1534 goto out;
1535
ecf160b4 1536 WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect_missing_keys.root.rb_root));
8da6d581 1537
86d5f994 1538 ret = resolve_indirect_refs(fs_info, path, time_seq, &preftrees,
b25b0b87 1539 extent_item_pos, sc, ignore_offset);
8da6d581
JS
1540 if (ret)
1541 goto out;
1542
ecf160b4 1543 WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect.root.rb_root));
8da6d581 1544
86d5f994
EN
1545 /*
1546 * This walks the tree of merged and resolved refs. Tree blocks are
1547 * read in as needed. Unique entries are added to the ulist, and
1548 * the list of found roots is updated.
1549 *
1550 * We release the entire tree in one go before returning.
1551 */
ecf160b4 1552 node = rb_first_cached(&preftrees.direct.root);
86d5f994
EN
1553 while (node) {
1554 ref = rb_entry(node, struct prelim_ref, rbnode);
1555 node = rb_next(&ref->rbnode);
c8195a7b
ZB
1556 /*
1557 * ref->count < 0 can happen here if there are delayed
1558 * refs with a node->action of BTRFS_DROP_DELAYED_REF.
1559 * prelim_ref_insert() relies on this when merging
1560 * identical refs to keep the overall count correct.
1561 * prelim_ref_insert() will merge only those refs
1562 * which compare identically. Any refs having
1563 * e.g. different offsets would not be merged,
1564 * and would retain their original ref->count < 0.
1565 */
98cfee21 1566 if (roots && ref->count && ref->root_id && ref->parent == 0) {
8da6d581
JS
1567 /* no parent == root of tree */
1568 ret = ulist_add(roots, ref->root_id, 0, GFP_NOFS);
f1723939
WS
1569 if (ret < 0)
1570 goto out;
8da6d581
JS
1571 }
1572 if (ref->count && ref->parent) {
8a56457f
JB
1573 if (extent_item_pos && !ref->inode_list &&
1574 ref->level == 0) {
976b1908 1575 struct extent_buffer *eb;
707e8a07 1576
581c1760 1577 eb = read_tree_block(fs_info, ref->parent, 0,
1b7ec85e 1578 0, ref->level, NULL);
64c043de
LB
1579 if (IS_ERR(eb)) {
1580 ret = PTR_ERR(eb);
1581 goto out;
4eb150d6
QW
1582 }
1583 if (!extent_buffer_uptodate(eb)) {
416bc658 1584 free_extent_buffer(eb);
c16c2e2e
WS
1585 ret = -EIO;
1586 goto out;
416bc658 1587 }
38e3eebf 1588
ac5887c8 1589 if (!path->skip_locking)
38e3eebf 1590 btrfs_tree_read_lock(eb);
976b1908 1591 ret = find_extent_in_eb(eb, bytenr,
c995ab3c 1592 *extent_item_pos, &eie, ignore_offset);
38e3eebf 1593 if (!path->skip_locking)
ac5887c8 1594 btrfs_tree_read_unlock(eb);
976b1908 1595 free_extent_buffer(eb);
f5929cd8
FDBM
1596 if (ret < 0)
1597 goto out;
1598 ref->inode_list = eie;
92876eec
FM
1599 /*
1600 * We transferred the list ownership to the ref,
1601 * so set to NULL to avoid a double free in case
1602 * an error happens after this.
1603 */
1604 eie = NULL;
976b1908 1605 }
4eb1f66d
TI
1606 ret = ulist_add_merge_ptr(refs, ref->parent,
1607 ref->inode_list,
1608 (void **)&eie, GFP_NOFS);
f1723939
WS
1609 if (ret < 0)
1610 goto out;
3301958b
JS
1611 if (!ret && extent_item_pos) {
1612 /*
9f05c09d
JB
1613 * We've recorded that parent, so we must extend
1614 * its inode list here.
1615 *
1616 * However if there was corruption we may not
1617 * have found an eie, return an error in this
1618 * case.
3301958b 1619 */
9f05c09d
JB
1620 ASSERT(eie);
1621 if (!eie) {
1622 ret = -EUCLEAN;
1623 goto out;
1624 }
3301958b
JS
1625 while (eie->next)
1626 eie = eie->next;
1627 eie->next = ref->inode_list;
1628 }
f05c4746 1629 eie = NULL;
92876eec
FM
1630 /*
1631 * We have transferred the inode list ownership from
1632 * this ref to the ref we added to the 'refs' ulist.
1633 * So set this ref's inode list to NULL to avoid
1634 * use-after-free when our caller uses it or double
1635 * frees in case an error happens before we return.
1636 */
1637 ref->inode_list = NULL;
8da6d581 1638 }
9dd14fd6 1639 cond_resched();
8da6d581
JS
1640 }
1641
1642out:
8da6d581 1643 btrfs_free_path(path);
86d5f994
EN
1644
1645 prelim_release(&preftrees.direct);
1646 prelim_release(&preftrees.indirect);
1647 prelim_release(&preftrees.indirect_missing_keys);
1648
f05c4746
WS
1649 if (ret < 0)
1650 free_inode_elem_list(eie);
8da6d581
JS
1651 return ret;
1652}
1653
1654/*
1655 * Finds all leafs with a reference to the specified combination of bytenr and
1656 * offset. key_list_head will point to a list of corresponding keys (caller must
1657 * free each list element). The leafs will be stored in the leafs ulist, which
1658 * must be freed with ulist_free.
1659 *
1660 * returns 0 on success, <0 on error
1661 */
19b546d7
QW
1662int btrfs_find_all_leafs(struct btrfs_trans_handle *trans,
1663 struct btrfs_fs_info *fs_info, u64 bytenr,
1664 u64 time_seq, struct ulist **leafs,
1665 const u64 *extent_item_pos, bool ignore_offset)
8da6d581 1666{
8da6d581
JS
1667 int ret;
1668
8da6d581 1669 *leafs = ulist_alloc(GFP_NOFS);
98cfee21 1670 if (!*leafs)
8da6d581 1671 return -ENOMEM;
8da6d581 1672
afce772e 1673 ret = find_parent_nodes(trans, fs_info, bytenr, time_seq,
c995ab3c 1674 *leafs, NULL, extent_item_pos, NULL, ignore_offset);
8da6d581 1675 if (ret < 0 && ret != -ENOENT) {
976b1908 1676 free_leaf_list(*leafs);
8da6d581
JS
1677 return ret;
1678 }
1679
1680 return 0;
1681}
1682
1683/*
1684 * walk all backrefs for a given extent to find all roots that reference this
1685 * extent. Walking a backref means finding all extents that reference this
1686 * extent and in turn walk the backrefs of those, too. Naturally this is a
1687 * recursive process, but here it is implemented in an iterative fashion: We
1688 * find all referencing extents for the extent in question and put them on a
1689 * list. In turn, we find all referencing extents for those, further appending
1690 * to the list. The way we iterate the list allows adding more elements after
1691 * the current while iterating. The process stops when we reach the end of the
1692 * list. Found roots are added to the roots list.
1693 *
1694 * returns 0 on success, < 0 on error.
1695 */
e0c476b1
JM
1696static int btrfs_find_all_roots_safe(struct btrfs_trans_handle *trans,
1697 struct btrfs_fs_info *fs_info, u64 bytenr,
c995ab3c
ZB
1698 u64 time_seq, struct ulist **roots,
1699 bool ignore_offset)
8da6d581
JS
1700{
1701 struct ulist *tmp;
1702 struct ulist_node *node = NULL;
cd1b413c 1703 struct ulist_iterator uiter;
8da6d581
JS
1704 int ret;
1705
1706 tmp = ulist_alloc(GFP_NOFS);
1707 if (!tmp)
1708 return -ENOMEM;
1709 *roots = ulist_alloc(GFP_NOFS);
1710 if (!*roots) {
1711 ulist_free(tmp);
1712 return -ENOMEM;
1713 }
1714
cd1b413c 1715 ULIST_ITER_INIT(&uiter);
8da6d581 1716 while (1) {
afce772e 1717 ret = find_parent_nodes(trans, fs_info, bytenr, time_seq,
c995ab3c 1718 tmp, *roots, NULL, NULL, ignore_offset);
8da6d581
JS
1719 if (ret < 0 && ret != -ENOENT) {
1720 ulist_free(tmp);
1721 ulist_free(*roots);
580c079b 1722 *roots = NULL;
8da6d581
JS
1723 return ret;
1724 }
cd1b413c 1725 node = ulist_next(tmp, &uiter);
8da6d581
JS
1726 if (!node)
1727 break;
1728 bytenr = node->val;
bca1a290 1729 cond_resched();
8da6d581
JS
1730 }
1731
1732 ulist_free(tmp);
1733 return 0;
1734}
1735
9e351cc8
JB
1736int btrfs_find_all_roots(struct btrfs_trans_handle *trans,
1737 struct btrfs_fs_info *fs_info, u64 bytenr,
c995ab3c 1738 u64 time_seq, struct ulist **roots,
c7bcbb21 1739 bool skip_commit_root_sem)
9e351cc8
JB
1740{
1741 int ret;
1742
8949b9a1 1743 if (!trans && !skip_commit_root_sem)
9e351cc8 1744 down_read(&fs_info->commit_root_sem);
e0c476b1 1745 ret = btrfs_find_all_roots_safe(trans, fs_info, bytenr,
c7bcbb21 1746 time_seq, roots, false);
8949b9a1 1747 if (!trans && !skip_commit_root_sem)
9e351cc8
JB
1748 up_read(&fs_info->commit_root_sem);
1749 return ret;
1750}
1751
84a7949d
FM
1752struct btrfs_backref_share_check_ctx *btrfs_alloc_backref_share_check_ctx(void)
1753{
1754 struct btrfs_backref_share_check_ctx *ctx;
1755
1756 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1757 if (!ctx)
1758 return NULL;
1759
1760 ulist_init(&ctx->refs);
84a7949d
FM
1761
1762 return ctx;
1763}
1764
1765void btrfs_free_backref_share_ctx(struct btrfs_backref_share_check_ctx *ctx)
1766{
1767 if (!ctx)
1768 return;
1769
1770 ulist_release(&ctx->refs);
84a7949d
FM
1771 kfree(ctx);
1772}
1773
8eedadda
FM
1774/*
1775 * Check if a data extent is shared or not.
6e353e3b 1776 *
ceb707da 1777 * @inode: The inode whose extent we are checking.
b8f164e3
FM
1778 * @bytenr: Logical bytenr of the extent we are checking.
1779 * @extent_gen: Generation of the extent (file extent item) or 0 if it is
1780 * not known.
61dbb952 1781 * @ctx: A backref sharedness check context.
2c2ed5aa 1782 *
8eedadda 1783 * btrfs_is_data_extent_shared uses the backref walking code but will short
2c2ed5aa
MF
1784 * circuit as soon as it finds a root or inode that doesn't match the
1785 * one passed in. This provides a significant performance benefit for
1786 * callers (such as fiemap) which want to know whether the extent is
1787 * shared but do not need a ref count.
1788 *
03628cdb
FM
1789 * This attempts to attach to the running transaction in order to account for
1790 * delayed refs, but continues on even when no running transaction exists.
bb739cf0 1791 *
2c2ed5aa
MF
1792 * Return: 0 if extent is not shared, 1 if it is shared, < 0 on error.
1793 */
ceb707da 1794int btrfs_is_data_extent_shared(struct btrfs_inode *inode, u64 bytenr,
b8f164e3 1795 u64 extent_gen,
61dbb952 1796 struct btrfs_backref_share_check_ctx *ctx)
dc046b10 1797{
ceb707da 1798 struct btrfs_root *root = inode->root;
bb739cf0
EN
1799 struct btrfs_fs_info *fs_info = root->fs_info;
1800 struct btrfs_trans_handle *trans;
dc046b10
JB
1801 struct ulist_iterator uiter;
1802 struct ulist_node *node;
f3a84ccd 1803 struct btrfs_seq_list elem = BTRFS_SEQ_LIST_INIT(elem);
dc046b10 1804 int ret = 0;
3ec4d323 1805 struct share_check shared = {
877c1476
FM
1806 .ctx = ctx,
1807 .root = root,
ceb707da 1808 .inum = btrfs_ino(inode),
73e339e6 1809 .data_bytenr = bytenr,
6976201f 1810 .data_extent_gen = extent_gen,
3ec4d323 1811 .share_count = 0,
73e339e6 1812 .self_ref_count = 0,
4fc7b572 1813 .have_delayed_delete_refs = false,
3ec4d323 1814 };
12a824dc 1815 int level;
dc046b10 1816
73e339e6
FM
1817 for (int i = 0; i < BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE; i++) {
1818 if (ctx->prev_extents_cache[i].bytenr == bytenr)
1819 return ctx->prev_extents_cache[i].is_shared;
1820 }
1821
84a7949d 1822 ulist_init(&ctx->refs);
dc046b10 1823
a6d155d2 1824 trans = btrfs_join_transaction_nostart(root);
bb739cf0 1825 if (IS_ERR(trans)) {
03628cdb
FM
1826 if (PTR_ERR(trans) != -ENOENT && PTR_ERR(trans) != -EROFS) {
1827 ret = PTR_ERR(trans);
1828 goto out;
1829 }
bb739cf0 1830 trans = NULL;
dc046b10 1831 down_read(&fs_info->commit_root_sem);
bb739cf0
EN
1832 } else {
1833 btrfs_get_tree_mod_seq(fs_info, &elem);
1834 }
1835
12a824dc
FM
1836 /* -1 means we are in the bytenr of the data extent. */
1837 level = -1;
dc046b10 1838 ULIST_ITER_INIT(&uiter);
61dbb952 1839 ctx->use_path_cache = true;
dc046b10 1840 while (1) {
12a824dc
FM
1841 bool is_shared;
1842 bool cached;
1843
84a7949d 1844 ret = find_parent_nodes(trans, fs_info, bytenr, elem.seq, &ctx->refs,
b6296858 1845 NULL, NULL, &shared, false);
877c1476
FM
1846 if (ret == BACKREF_FOUND_SHARED ||
1847 ret == BACKREF_FOUND_NOT_SHARED) {
1848 /* If shared must return 1, otherwise return 0. */
1849 ret = (ret == BACKREF_FOUND_SHARED) ? 1 : 0;
12a824dc 1850 if (level >= 0)
61dbb952 1851 store_backref_shared_cache(ctx, root, bytenr,
877c1476 1852 level, ret == 1);
dc046b10
JB
1853 break;
1854 }
1855 if (ret < 0 && ret != -ENOENT)
1856 break;
2c2ed5aa 1857 ret = 0;
b8f164e3 1858
63c84b46
FM
1859 /*
1860 * If our data extent was not directly shared (without multiple
1861 * reference items), than it might have a single reference item
1862 * with a count > 1 for the same offset, which means there are 2
1863 * (or more) file extent items that point to the data extent -
1864 * this happens when a file extent item needs to be split and
1865 * then one item gets moved to another leaf due to a b+tree leaf
1866 * split when inserting some item. In this case the file extent
1867 * items may be located in different leaves and therefore some
1868 * of the leaves may be referenced through shared subtrees while
1869 * others are not. Since our extent buffer cache only works for
1870 * a single path (by far the most common case and simpler to
1871 * deal with), we can not use it if we have multiple leaves
1872 * (which implies multiple paths).
1873 */
84a7949d 1874 if (level == -1 && ctx->refs.nnodes > 1)
61dbb952 1875 ctx->use_path_cache = false;
63c84b46 1876
12a824dc 1877 if (level >= 0)
61dbb952 1878 store_backref_shared_cache(ctx, root, bytenr,
12a824dc 1879 level, false);
84a7949d 1880 node = ulist_next(&ctx->refs, &uiter);
dc046b10
JB
1881 if (!node)
1882 break;
1883 bytenr = node->val;
12a824dc 1884 level++;
61dbb952 1885 cached = lookup_backref_shared_cache(ctx, root, bytenr, level,
12a824dc
FM
1886 &is_shared);
1887 if (cached) {
1888 ret = (is_shared ? 1 : 0);
1889 break;
1890 }
18bf591b 1891 shared.share_count = 0;
4fc7b572 1892 shared.have_delayed_delete_refs = false;
dc046b10
JB
1893 cond_resched();
1894 }
bb739cf0 1895
73e339e6
FM
1896 /*
1897 * Cache the sharedness result for the data extent if we know our inode
1898 * has more than 1 file extent item that refers to the data extent.
1899 */
1900 if (ret >= 0 && shared.self_ref_count > 1) {
1901 int slot = ctx->prev_extents_cache_slot;
1902
1903 ctx->prev_extents_cache[slot].bytenr = shared.data_bytenr;
1904 ctx->prev_extents_cache[slot].is_shared = (ret == 1);
1905
1906 slot = (slot + 1) % BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE;
1907 ctx->prev_extents_cache_slot = slot;
1908 }
1909
bb739cf0 1910 if (trans) {
dc046b10 1911 btrfs_put_tree_mod_seq(fs_info, &elem);
bb739cf0
EN
1912 btrfs_end_transaction(trans);
1913 } else {
dc046b10 1914 up_read(&fs_info->commit_root_sem);
bb739cf0 1915 }
03628cdb 1916out:
84a7949d 1917 ulist_release(&ctx->refs);
877c1476
FM
1918 ctx->prev_leaf_bytenr = ctx->curr_leaf_bytenr;
1919
dc046b10
JB
1920 return ret;
1921}
1922
f186373f
MF
1923int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
1924 u64 start_off, struct btrfs_path *path,
1925 struct btrfs_inode_extref **ret_extref,
1926 u64 *found_off)
1927{
1928 int ret, slot;
1929 struct btrfs_key key;
1930 struct btrfs_key found_key;
1931 struct btrfs_inode_extref *extref;
73980bec 1932 const struct extent_buffer *leaf;
f186373f
MF
1933 unsigned long ptr;
1934
1935 key.objectid = inode_objectid;
962a298f 1936 key.type = BTRFS_INODE_EXTREF_KEY;
f186373f
MF
1937 key.offset = start_off;
1938
1939 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1940 if (ret < 0)
1941 return ret;
1942
1943 while (1) {
1944 leaf = path->nodes[0];
1945 slot = path->slots[0];
1946 if (slot >= btrfs_header_nritems(leaf)) {
1947 /*
1948 * If the item at offset is not found,
1949 * btrfs_search_slot will point us to the slot
1950 * where it should be inserted. In our case
1951 * that will be the slot directly before the
1952 * next INODE_REF_KEY_V2 item. In the case
1953 * that we're pointing to the last slot in a
1954 * leaf, we must move one leaf over.
1955 */
1956 ret = btrfs_next_leaf(root, path);
1957 if (ret) {
1958 if (ret >= 1)
1959 ret = -ENOENT;
1960 break;
1961 }
1962 continue;
1963 }
1964
1965 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1966
1967 /*
1968 * Check that we're still looking at an extended ref key for
1969 * this particular objectid. If we have different
1970 * objectid or type then there are no more to be found
1971 * in the tree and we can exit.
1972 */
1973 ret = -ENOENT;
1974 if (found_key.objectid != inode_objectid)
1975 break;
962a298f 1976 if (found_key.type != BTRFS_INODE_EXTREF_KEY)
f186373f
MF
1977 break;
1978
1979 ret = 0;
1980 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1981 extref = (struct btrfs_inode_extref *)ptr;
1982 *ret_extref = extref;
1983 if (found_off)
1984 *found_off = found_key.offset;
1985 break;
1986 }
1987
1988 return ret;
1989}
1990
48a3b636
ES
1991/*
1992 * this iterates to turn a name (from iref/extref) into a full filesystem path.
1993 * Elements of the path are separated by '/' and the path is guaranteed to be
1994 * 0-terminated. the path is only given within the current file system.
1995 * Therefore, it never starts with a '/'. the caller is responsible to provide
1996 * "size" bytes in "dest". the dest buffer will be filled backwards. finally,
1997 * the start point of the resulting string is returned. this pointer is within
1998 * dest, normally.
1999 * in case the path buffer would overflow, the pointer is decremented further
2000 * as if output was written to the buffer, though no more output is actually
2001 * generated. that way, the caller can determine how much space would be
2002 * required for the path to fit into the buffer. in that case, the returned
2003 * value will be smaller than dest. callers must check this!
2004 */
96b5bd77
JS
2005char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
2006 u32 name_len, unsigned long name_off,
2007 struct extent_buffer *eb_in, u64 parent,
2008 char *dest, u32 size)
a542ad1b 2009{
a542ad1b
JS
2010 int slot;
2011 u64 next_inum;
2012 int ret;
661bec6b 2013 s64 bytes_left = ((s64)size) - 1;
a542ad1b
JS
2014 struct extent_buffer *eb = eb_in;
2015 struct btrfs_key found_key;
d24bec3a 2016 struct btrfs_inode_ref *iref;
a542ad1b
JS
2017
2018 if (bytes_left >= 0)
2019 dest[bytes_left] = '\0';
2020
2021 while (1) {
d24bec3a 2022 bytes_left -= name_len;
a542ad1b
JS
2023 if (bytes_left >= 0)
2024 read_extent_buffer(eb, dest + bytes_left,
d24bec3a 2025 name_off, name_len);
b916a59a 2026 if (eb != eb_in) {
0c0fe3b0 2027 if (!path->skip_locking)
ac5887c8 2028 btrfs_tree_read_unlock(eb);
a542ad1b 2029 free_extent_buffer(eb);
b916a59a 2030 }
c234a24d
DS
2031 ret = btrfs_find_item(fs_root, path, parent, 0,
2032 BTRFS_INODE_REF_KEY, &found_key);
8f24b496
JS
2033 if (ret > 0)
2034 ret = -ENOENT;
a542ad1b
JS
2035 if (ret)
2036 break;
d24bec3a 2037
a542ad1b
JS
2038 next_inum = found_key.offset;
2039
2040 /* regular exit ahead */
2041 if (parent == next_inum)
2042 break;
2043
2044 slot = path->slots[0];
2045 eb = path->nodes[0];
2046 /* make sure we can use eb after releasing the path */
b916a59a 2047 if (eb != eb_in) {
0c0fe3b0
FM
2048 path->nodes[0] = NULL;
2049 path->locks[0] = 0;
b916a59a 2050 }
a542ad1b 2051 btrfs_release_path(path);
a542ad1b 2052 iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
d24bec3a
MF
2053
2054 name_len = btrfs_inode_ref_name_len(eb, iref);
2055 name_off = (unsigned long)(iref + 1);
2056
a542ad1b
JS
2057 parent = next_inum;
2058 --bytes_left;
2059 if (bytes_left >= 0)
2060 dest[bytes_left] = '/';
2061 }
2062
2063 btrfs_release_path(path);
2064
2065 if (ret)
2066 return ERR_PTR(ret);
2067
2068 return dest + bytes_left;
2069}
2070
2071/*
2072 * this makes the path point to (logical EXTENT_ITEM *)
2073 * returns BTRFS_EXTENT_FLAG_DATA for data, BTRFS_EXTENT_FLAG_TREE_BLOCK for
2074 * tree blocks and <0 on error.
2075 */
2076int extent_from_logical(struct btrfs_fs_info *fs_info, u64 logical,
69917e43
LB
2077 struct btrfs_path *path, struct btrfs_key *found_key,
2078 u64 *flags_ret)
a542ad1b 2079{
29cbcf40 2080 struct btrfs_root *extent_root = btrfs_extent_root(fs_info, logical);
a542ad1b
JS
2081 int ret;
2082 u64 flags;
261c84b6 2083 u64 size = 0;
a542ad1b 2084 u32 item_size;
73980bec 2085 const struct extent_buffer *eb;
a542ad1b
JS
2086 struct btrfs_extent_item *ei;
2087 struct btrfs_key key;
2088
261c84b6
JB
2089 if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2090 key.type = BTRFS_METADATA_ITEM_KEY;
2091 else
2092 key.type = BTRFS_EXTENT_ITEM_KEY;
a542ad1b
JS
2093 key.objectid = logical;
2094 key.offset = (u64)-1;
2095
29cbcf40 2096 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
a542ad1b
JS
2097 if (ret < 0)
2098 return ret;
a542ad1b 2099
29cbcf40 2100 ret = btrfs_previous_extent_item(extent_root, path, 0);
850a8cdf
WS
2101 if (ret) {
2102 if (ret > 0)
2103 ret = -ENOENT;
2104 return ret;
580f0a67 2105 }
850a8cdf 2106 btrfs_item_key_to_cpu(path->nodes[0], found_key, path->slots[0]);
261c84b6 2107 if (found_key->type == BTRFS_METADATA_ITEM_KEY)
da17066c 2108 size = fs_info->nodesize;
261c84b6
JB
2109 else if (found_key->type == BTRFS_EXTENT_ITEM_KEY)
2110 size = found_key->offset;
2111
580f0a67 2112 if (found_key->objectid > logical ||
261c84b6 2113 found_key->objectid + size <= logical) {
ab8d0fc4
JM
2114 btrfs_debug(fs_info,
2115 "logical %llu is not within any extent", logical);
a542ad1b 2116 return -ENOENT;
4692cf58 2117 }
a542ad1b
JS
2118
2119 eb = path->nodes[0];
3212fa14 2120 item_size = btrfs_item_size(eb, path->slots[0]);
a542ad1b
JS
2121 BUG_ON(item_size < sizeof(*ei));
2122
2123 ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
2124 flags = btrfs_extent_flags(eb, ei);
2125
ab8d0fc4
JM
2126 btrfs_debug(fs_info,
2127 "logical %llu is at position %llu within the extent (%llu EXTENT_ITEM %llu) flags %#llx size %u",
c1c9ff7c
GU
2128 logical, logical - found_key->objectid, found_key->objectid,
2129 found_key->offset, flags, item_size);
69917e43
LB
2130
2131 WARN_ON(!flags_ret);
2132 if (flags_ret) {
2133 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
2134 *flags_ret = BTRFS_EXTENT_FLAG_TREE_BLOCK;
2135 else if (flags & BTRFS_EXTENT_FLAG_DATA)
2136 *flags_ret = BTRFS_EXTENT_FLAG_DATA;
2137 else
290342f6 2138 BUG();
69917e43
LB
2139 return 0;
2140 }
a542ad1b
JS
2141
2142 return -EIO;
2143}
2144
2145/*
2146 * helper function to iterate extent inline refs. ptr must point to a 0 value
2147 * for the first call and may be modified. it is used to track state.
2148 * if more refs exist, 0 is returned and the next call to
e0c476b1 2149 * get_extent_inline_ref must pass the modified ptr parameter to get the
a542ad1b
JS
2150 * next ref. after the last ref was processed, 1 is returned.
2151 * returns <0 on error
2152 */
e0c476b1
JM
2153static int get_extent_inline_ref(unsigned long *ptr,
2154 const struct extent_buffer *eb,
2155 const struct btrfs_key *key,
2156 const struct btrfs_extent_item *ei,
2157 u32 item_size,
2158 struct btrfs_extent_inline_ref **out_eiref,
2159 int *out_type)
a542ad1b
JS
2160{
2161 unsigned long end;
2162 u64 flags;
2163 struct btrfs_tree_block_info *info;
2164
2165 if (!*ptr) {
2166 /* first call */
2167 flags = btrfs_extent_flags(eb, ei);
2168 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
6eda71d0
LB
2169 if (key->type == BTRFS_METADATA_ITEM_KEY) {
2170 /* a skinny metadata extent */
2171 *out_eiref =
2172 (struct btrfs_extent_inline_ref *)(ei + 1);
2173 } else {
2174 WARN_ON(key->type != BTRFS_EXTENT_ITEM_KEY);
2175 info = (struct btrfs_tree_block_info *)(ei + 1);
2176 *out_eiref =
2177 (struct btrfs_extent_inline_ref *)(info + 1);
2178 }
a542ad1b
JS
2179 } else {
2180 *out_eiref = (struct btrfs_extent_inline_ref *)(ei + 1);
2181 }
2182 *ptr = (unsigned long)*out_eiref;
cd857dd6 2183 if ((unsigned long)(*ptr) >= (unsigned long)ei + item_size)
a542ad1b
JS
2184 return -ENOENT;
2185 }
2186
2187 end = (unsigned long)ei + item_size;
6eda71d0 2188 *out_eiref = (struct btrfs_extent_inline_ref *)(*ptr);
3de28d57
LB
2189 *out_type = btrfs_get_extent_inline_ref_type(eb, *out_eiref,
2190 BTRFS_REF_TYPE_ANY);
2191 if (*out_type == BTRFS_REF_TYPE_INVALID)
af431dcb 2192 return -EUCLEAN;
a542ad1b
JS
2193
2194 *ptr += btrfs_extent_inline_ref_size(*out_type);
2195 WARN_ON(*ptr > end);
2196 if (*ptr == end)
2197 return 1; /* last */
2198
2199 return 0;
2200}
2201
2202/*
2203 * reads the tree block backref for an extent. tree level and root are returned
2204 * through out_level and out_root. ptr must point to a 0 value for the first
e0c476b1 2205 * call and may be modified (see get_extent_inline_ref comment).
a542ad1b
JS
2206 * returns 0 if data was provided, 1 if there was no more data to provide or
2207 * <0 on error.
2208 */
2209int tree_backref_for_extent(unsigned long *ptr, struct extent_buffer *eb,
6eda71d0
LB
2210 struct btrfs_key *key, struct btrfs_extent_item *ei,
2211 u32 item_size, u64 *out_root, u8 *out_level)
a542ad1b
JS
2212{
2213 int ret;
2214 int type;
a542ad1b
JS
2215 struct btrfs_extent_inline_ref *eiref;
2216
2217 if (*ptr == (unsigned long)-1)
2218 return 1;
2219
2220 while (1) {
e0c476b1 2221 ret = get_extent_inline_ref(ptr, eb, key, ei, item_size,
6eda71d0 2222 &eiref, &type);
a542ad1b
JS
2223 if (ret < 0)
2224 return ret;
2225
2226 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
2227 type == BTRFS_SHARED_BLOCK_REF_KEY)
2228 break;
2229
2230 if (ret == 1)
2231 return 1;
2232 }
2233
2234 /* we can treat both ref types equally here */
a542ad1b 2235 *out_root = btrfs_extent_inline_ref_offset(eb, eiref);
a1317f45
FM
2236
2237 if (key->type == BTRFS_EXTENT_ITEM_KEY) {
2238 struct btrfs_tree_block_info *info;
2239
2240 info = (struct btrfs_tree_block_info *)(ei + 1);
2241 *out_level = btrfs_tree_block_level(eb, info);
2242 } else {
2243 ASSERT(key->type == BTRFS_METADATA_ITEM_KEY);
2244 *out_level = (u8)key->offset;
2245 }
a542ad1b
JS
2246
2247 if (ret == 1)
2248 *ptr = (unsigned long)-1;
2249
2250 return 0;
2251}
2252
ab8d0fc4
JM
2253static int iterate_leaf_refs(struct btrfs_fs_info *fs_info,
2254 struct extent_inode_elem *inode_list,
2255 u64 root, u64 extent_item_objectid,
2256 iterate_extent_inodes_t *iterate, void *ctx)
a542ad1b 2257{
976b1908 2258 struct extent_inode_elem *eie;
4692cf58 2259 int ret = 0;
4692cf58 2260
976b1908 2261 for (eie = inode_list; eie; eie = eie->next) {
ab8d0fc4
JM
2262 btrfs_debug(fs_info,
2263 "ref for %llu resolved, key (%llu EXTEND_DATA %llu), root %llu",
2264 extent_item_objectid, eie->inum,
2265 eie->offset, root);
976b1908 2266 ret = iterate(eie->inum, eie->offset, root, ctx);
4692cf58 2267 if (ret) {
ab8d0fc4
JM
2268 btrfs_debug(fs_info,
2269 "stopping iteration for %llu due to ret=%d",
2270 extent_item_objectid, ret);
4692cf58
JS
2271 break;
2272 }
a542ad1b
JS
2273 }
2274
a542ad1b
JS
2275 return ret;
2276}
2277
2278/*
2279 * calls iterate() for every inode that references the extent identified by
4692cf58 2280 * the given parameters.
a542ad1b
JS
2281 * when the iterator function returns a non-zero value, iteration stops.
2282 */
2283int iterate_extent_inodes(struct btrfs_fs_info *fs_info,
4692cf58 2284 u64 extent_item_objectid, u64 extent_item_pos,
7a3ae2f8 2285 int search_commit_root,
c995ab3c
ZB
2286 iterate_extent_inodes_t *iterate, void *ctx,
2287 bool ignore_offset)
a542ad1b 2288{
a542ad1b 2289 int ret;
da61d31a 2290 struct btrfs_trans_handle *trans = NULL;
7a3ae2f8
JS
2291 struct ulist *refs = NULL;
2292 struct ulist *roots = NULL;
4692cf58
JS
2293 struct ulist_node *ref_node = NULL;
2294 struct ulist_node *root_node = NULL;
f3a84ccd 2295 struct btrfs_seq_list seq_elem = BTRFS_SEQ_LIST_INIT(seq_elem);
cd1b413c
JS
2296 struct ulist_iterator ref_uiter;
2297 struct ulist_iterator root_uiter;
a542ad1b 2298
ab8d0fc4 2299 btrfs_debug(fs_info, "resolving all inodes for extent %llu",
4692cf58 2300 extent_item_objectid);
a542ad1b 2301
da61d31a 2302 if (!search_commit_root) {
30a9da5d 2303 trans = btrfs_attach_transaction(fs_info->tree_root);
bfc61c36
FM
2304 if (IS_ERR(trans)) {
2305 if (PTR_ERR(trans) != -ENOENT &&
2306 PTR_ERR(trans) != -EROFS)
2307 return PTR_ERR(trans);
2308 trans = NULL;
2309 }
2310 }
2311
2312 if (trans)
f3a84ccd 2313 btrfs_get_tree_mod_seq(fs_info, &seq_elem);
bfc61c36 2314 else
9e351cc8 2315 down_read(&fs_info->commit_root_sem);
a542ad1b 2316
4692cf58 2317 ret = btrfs_find_all_leafs(trans, fs_info, extent_item_objectid,
f3a84ccd 2318 seq_elem.seq, &refs,
c995ab3c 2319 &extent_item_pos, ignore_offset);
4692cf58
JS
2320 if (ret)
2321 goto out;
a542ad1b 2322
cd1b413c
JS
2323 ULIST_ITER_INIT(&ref_uiter);
2324 while (!ret && (ref_node = ulist_next(refs, &ref_uiter))) {
e0c476b1 2325 ret = btrfs_find_all_roots_safe(trans, fs_info, ref_node->val,
f3a84ccd 2326 seq_elem.seq, &roots,
c995ab3c 2327 ignore_offset);
4692cf58
JS
2328 if (ret)
2329 break;
cd1b413c
JS
2330 ULIST_ITER_INIT(&root_uiter);
2331 while (!ret && (root_node = ulist_next(roots, &root_uiter))) {
ab8d0fc4
JM
2332 btrfs_debug(fs_info,
2333 "root %llu references leaf %llu, data list %#llx",
2334 root_node->val, ref_node->val,
2335 ref_node->aux);
2336 ret = iterate_leaf_refs(fs_info,
2337 (struct extent_inode_elem *)
995e01b7
JS
2338 (uintptr_t)ref_node->aux,
2339 root_node->val,
2340 extent_item_objectid,
2341 iterate, ctx);
4692cf58 2342 }
976b1908 2343 ulist_free(roots);
a542ad1b
JS
2344 }
2345
976b1908 2346 free_leaf_list(refs);
4692cf58 2347out:
bfc61c36 2348 if (trans) {
f3a84ccd 2349 btrfs_put_tree_mod_seq(fs_info, &seq_elem);
3a45bb20 2350 btrfs_end_transaction(trans);
9e351cc8
JB
2351 } else {
2352 up_read(&fs_info->commit_root_sem);
7a3ae2f8
JS
2353 }
2354
a542ad1b
JS
2355 return ret;
2356}
2357
e3059ec0
DS
2358static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
2359{
2360 struct btrfs_data_container *inodes = ctx;
2361 const size_t c = 3 * sizeof(u64);
2362
2363 if (inodes->bytes_left >= c) {
2364 inodes->bytes_left -= c;
2365 inodes->val[inodes->elem_cnt] = inum;
2366 inodes->val[inodes->elem_cnt + 1] = offset;
2367 inodes->val[inodes->elem_cnt + 2] = root;
2368 inodes->elem_cnt += 3;
2369 } else {
2370 inodes->bytes_missing += c - inodes->bytes_left;
2371 inodes->bytes_left = 0;
2372 inodes->elem_missed += 3;
2373 }
2374
2375 return 0;
2376}
2377
a542ad1b
JS
2378int iterate_inodes_from_logical(u64 logical, struct btrfs_fs_info *fs_info,
2379 struct btrfs_path *path,
e3059ec0 2380 void *ctx, bool ignore_offset)
a542ad1b
JS
2381{
2382 int ret;
4692cf58 2383 u64 extent_item_pos;
69917e43 2384 u64 flags = 0;
a542ad1b 2385 struct btrfs_key found_key;
7a3ae2f8 2386 int search_commit_root = path->search_commit_root;
a542ad1b 2387
69917e43 2388 ret = extent_from_logical(fs_info, logical, path, &found_key, &flags);
4692cf58 2389 btrfs_release_path(path);
a542ad1b
JS
2390 if (ret < 0)
2391 return ret;
69917e43 2392 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
3627bf45 2393 return -EINVAL;
a542ad1b 2394
4692cf58 2395 extent_item_pos = logical - found_key.objectid;
7a3ae2f8
JS
2396 ret = iterate_extent_inodes(fs_info, found_key.objectid,
2397 extent_item_pos, search_commit_root,
e3059ec0 2398 build_ino_list, ctx, ignore_offset);
a542ad1b
JS
2399
2400 return ret;
2401}
2402
ad6240f6 2403static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
875d1daa 2404 struct extent_buffer *eb, struct inode_fs_paths *ipath);
d24bec3a 2405
875d1daa 2406static int iterate_inode_refs(u64 inum, struct inode_fs_paths *ipath)
a542ad1b 2407{
aefc1eb1 2408 int ret = 0;
a542ad1b
JS
2409 int slot;
2410 u32 cur;
2411 u32 len;
2412 u32 name_len;
2413 u64 parent = 0;
2414 int found = 0;
875d1daa
DS
2415 struct btrfs_root *fs_root = ipath->fs_root;
2416 struct btrfs_path *path = ipath->btrfs_path;
a542ad1b 2417 struct extent_buffer *eb;
a542ad1b
JS
2418 struct btrfs_inode_ref *iref;
2419 struct btrfs_key found_key;
2420
aefc1eb1 2421 while (!ret) {
c234a24d
DS
2422 ret = btrfs_find_item(fs_root, path, inum,
2423 parent ? parent + 1 : 0, BTRFS_INODE_REF_KEY,
2424 &found_key);
2425
a542ad1b
JS
2426 if (ret < 0)
2427 break;
2428 if (ret) {
2429 ret = found ? 0 : -ENOENT;
2430 break;
2431 }
2432 ++found;
2433
2434 parent = found_key.offset;
2435 slot = path->slots[0];
3fe81ce2
FDBM
2436 eb = btrfs_clone_extent_buffer(path->nodes[0]);
2437 if (!eb) {
2438 ret = -ENOMEM;
2439 break;
2440 }
a542ad1b
JS
2441 btrfs_release_path(path);
2442
a542ad1b
JS
2443 iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
2444
3212fa14 2445 for (cur = 0; cur < btrfs_item_size(eb, slot); cur += len) {
a542ad1b
JS
2446 name_len = btrfs_inode_ref_name_len(eb, iref);
2447 /* path must be released before calling iterate()! */
ab8d0fc4
JM
2448 btrfs_debug(fs_root->fs_info,
2449 "following ref at offset %u for inode %llu in tree %llu",
4fd786e6
MT
2450 cur, found_key.objectid,
2451 fs_root->root_key.objectid);
ad6240f6 2452 ret = inode_to_path(parent, name_len,
875d1daa 2453 (unsigned long)(iref + 1), eb, ipath);
aefc1eb1 2454 if (ret)
a542ad1b 2455 break;
a542ad1b
JS
2456 len = sizeof(*iref) + name_len;
2457 iref = (struct btrfs_inode_ref *)((char *)iref + len);
2458 }
2459 free_extent_buffer(eb);
2460 }
2461
2462 btrfs_release_path(path);
2463
2464 return ret;
2465}
2466
875d1daa 2467static int iterate_inode_extrefs(u64 inum, struct inode_fs_paths *ipath)
d24bec3a
MF
2468{
2469 int ret;
2470 int slot;
2471 u64 offset = 0;
2472 u64 parent;
2473 int found = 0;
875d1daa
DS
2474 struct btrfs_root *fs_root = ipath->fs_root;
2475 struct btrfs_path *path = ipath->btrfs_path;
d24bec3a
MF
2476 struct extent_buffer *eb;
2477 struct btrfs_inode_extref *extref;
d24bec3a
MF
2478 u32 item_size;
2479 u32 cur_offset;
2480 unsigned long ptr;
2481
2482 while (1) {
2483 ret = btrfs_find_one_extref(fs_root, inum, offset, path, &extref,
2484 &offset);
2485 if (ret < 0)
2486 break;
2487 if (ret) {
2488 ret = found ? 0 : -ENOENT;
2489 break;
2490 }
2491 ++found;
2492
2493 slot = path->slots[0];
3fe81ce2
FDBM
2494 eb = btrfs_clone_extent_buffer(path->nodes[0]);
2495 if (!eb) {
2496 ret = -ENOMEM;
2497 break;
2498 }
d24bec3a
MF
2499 btrfs_release_path(path);
2500
3212fa14 2501 item_size = btrfs_item_size(eb, slot);
2849a854 2502 ptr = btrfs_item_ptr_offset(eb, slot);
d24bec3a
MF
2503 cur_offset = 0;
2504
2505 while (cur_offset < item_size) {
2506 u32 name_len;
2507
2508 extref = (struct btrfs_inode_extref *)(ptr + cur_offset);
2509 parent = btrfs_inode_extref_parent(eb, extref);
2510 name_len = btrfs_inode_extref_name_len(eb, extref);
ad6240f6 2511 ret = inode_to_path(parent, name_len,
875d1daa 2512 (unsigned long)&extref->name, eb, ipath);
d24bec3a
MF
2513 if (ret)
2514 break;
2515
2849a854 2516 cur_offset += btrfs_inode_extref_name_len(eb, extref);
d24bec3a
MF
2517 cur_offset += sizeof(*extref);
2518 }
d24bec3a
MF
2519 free_extent_buffer(eb);
2520
2521 offset++;
2522 }
2523
2524 btrfs_release_path(path);
2525
2526 return ret;
2527}
2528
a542ad1b
JS
2529/*
2530 * returns 0 if the path could be dumped (probably truncated)
2531 * returns <0 in case of an error
2532 */
d24bec3a 2533static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
875d1daa 2534 struct extent_buffer *eb, struct inode_fs_paths *ipath)
a542ad1b 2535{
a542ad1b
JS
2536 char *fspath;
2537 char *fspath_min;
2538 int i = ipath->fspath->elem_cnt;
2539 const int s_ptr = sizeof(char *);
2540 u32 bytes_left;
2541
2542 bytes_left = ipath->fspath->bytes_left > s_ptr ?
2543 ipath->fspath->bytes_left - s_ptr : 0;
2544
740c3d22 2545 fspath_min = (char *)ipath->fspath->val + (i + 1) * s_ptr;
96b5bd77
JS
2546 fspath = btrfs_ref_to_path(ipath->fs_root, ipath->btrfs_path, name_len,
2547 name_off, eb, inum, fspath_min, bytes_left);
a542ad1b
JS
2548 if (IS_ERR(fspath))
2549 return PTR_ERR(fspath);
2550
2551 if (fspath > fspath_min) {
745c4d8e 2552 ipath->fspath->val[i] = (u64)(unsigned long)fspath;
a542ad1b
JS
2553 ++ipath->fspath->elem_cnt;
2554 ipath->fspath->bytes_left = fspath - fspath_min;
2555 } else {
2556 ++ipath->fspath->elem_missed;
2557 ipath->fspath->bytes_missing += fspath_min - fspath;
2558 ipath->fspath->bytes_left = 0;
2559 }
2560
2561 return 0;
2562}
2563
2564/*
2565 * this dumps all file system paths to the inode into the ipath struct, provided
2566 * is has been created large enough. each path is zero-terminated and accessed
740c3d22 2567 * from ipath->fspath->val[i].
a542ad1b 2568 * when it returns, there are ipath->fspath->elem_cnt number of paths available
740c3d22 2569 * in ipath->fspath->val[]. when the allocated space wasn't sufficient, the
01327610 2570 * number of missed paths is recorded in ipath->fspath->elem_missed, otherwise,
a542ad1b
JS
2571 * it's zero. ipath->fspath->bytes_missing holds the number of bytes that would
2572 * have been needed to return all paths.
2573 */
2574int paths_from_inode(u64 inum, struct inode_fs_paths *ipath)
2575{
ad6240f6
DS
2576 int ret;
2577 int found_refs = 0;
2578
875d1daa 2579 ret = iterate_inode_refs(inum, ipath);
ad6240f6
DS
2580 if (!ret)
2581 ++found_refs;
2582 else if (ret != -ENOENT)
2583 return ret;
2584
875d1daa 2585 ret = iterate_inode_extrefs(inum, ipath);
ad6240f6
DS
2586 if (ret == -ENOENT && found_refs)
2587 return 0;
2588
2589 return ret;
a542ad1b
JS
2590}
2591
a542ad1b
JS
2592struct btrfs_data_container *init_data_container(u32 total_bytes)
2593{
2594 struct btrfs_data_container *data;
2595 size_t alloc_bytes;
2596
2597 alloc_bytes = max_t(size_t, total_bytes, sizeof(*data));
f54de068 2598 data = kvmalloc(alloc_bytes, GFP_KERNEL);
a542ad1b
JS
2599 if (!data)
2600 return ERR_PTR(-ENOMEM);
2601
2602 if (total_bytes >= sizeof(*data)) {
2603 data->bytes_left = total_bytes - sizeof(*data);
2604 data->bytes_missing = 0;
2605 } else {
2606 data->bytes_missing = sizeof(*data) - total_bytes;
2607 data->bytes_left = 0;
2608 }
2609
2610 data->elem_cnt = 0;
2611 data->elem_missed = 0;
2612
2613 return data;
2614}
2615
2616/*
2617 * allocates space to return multiple file system paths for an inode.
2618 * total_bytes to allocate are passed, note that space usable for actual path
2619 * information will be total_bytes - sizeof(struct inode_fs_paths).
2620 * the returned pointer must be freed with free_ipath() in the end.
2621 */
2622struct inode_fs_paths *init_ipath(s32 total_bytes, struct btrfs_root *fs_root,
2623 struct btrfs_path *path)
2624{
2625 struct inode_fs_paths *ifp;
2626 struct btrfs_data_container *fspath;
2627
2628 fspath = init_data_container(total_bytes);
2629 if (IS_ERR(fspath))
afc6961f 2630 return ERR_CAST(fspath);
a542ad1b 2631
f54de068 2632 ifp = kmalloc(sizeof(*ifp), GFP_KERNEL);
a542ad1b 2633 if (!ifp) {
f54de068 2634 kvfree(fspath);
a542ad1b
JS
2635 return ERR_PTR(-ENOMEM);
2636 }
2637
2638 ifp->btrfs_path = path;
2639 ifp->fspath = fspath;
2640 ifp->fs_root = fs_root;
2641
2642 return ifp;
2643}
2644
2645void free_ipath(struct inode_fs_paths *ipath)
2646{
4735fb28
JJ
2647 if (!ipath)
2648 return;
f54de068 2649 kvfree(ipath->fspath);
a542ad1b
JS
2650 kfree(ipath);
2651}
a37f232b 2652
d68194b2 2653struct btrfs_backref_iter *btrfs_backref_iter_alloc(struct btrfs_fs_info *fs_info)
a37f232b
QW
2654{
2655 struct btrfs_backref_iter *ret;
2656
d68194b2 2657 ret = kzalloc(sizeof(*ret), GFP_NOFS);
a37f232b
QW
2658 if (!ret)
2659 return NULL;
2660
2661 ret->path = btrfs_alloc_path();
c15c2ec0 2662 if (!ret->path) {
a37f232b
QW
2663 kfree(ret);
2664 return NULL;
2665 }
2666
2667 /* Current backref iterator only supports iteration in commit root */
2668 ret->path->search_commit_root = 1;
2669 ret->path->skip_locking = 1;
2670 ret->fs_info = fs_info;
2671
2672 return ret;
2673}
2674
2675int btrfs_backref_iter_start(struct btrfs_backref_iter *iter, u64 bytenr)
2676{
2677 struct btrfs_fs_info *fs_info = iter->fs_info;
29cbcf40 2678 struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
a37f232b
QW
2679 struct btrfs_path *path = iter->path;
2680 struct btrfs_extent_item *ei;
2681 struct btrfs_key key;
2682 int ret;
2683
2684 key.objectid = bytenr;
2685 key.type = BTRFS_METADATA_ITEM_KEY;
2686 key.offset = (u64)-1;
2687 iter->bytenr = bytenr;
2688
29cbcf40 2689 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
a37f232b
QW
2690 if (ret < 0)
2691 return ret;
2692 if (ret == 0) {
2693 ret = -EUCLEAN;
2694 goto release;
2695 }
2696 if (path->slots[0] == 0) {
2697 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
2698 ret = -EUCLEAN;
2699 goto release;
2700 }
2701 path->slots[0]--;
2702
2703 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2704 if ((key.type != BTRFS_EXTENT_ITEM_KEY &&
2705 key.type != BTRFS_METADATA_ITEM_KEY) || key.objectid != bytenr) {
2706 ret = -ENOENT;
2707 goto release;
2708 }
2709 memcpy(&iter->cur_key, &key, sizeof(key));
2710 iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2711 path->slots[0]);
2712 iter->end_ptr = (u32)(iter->item_ptr +
3212fa14 2713 btrfs_item_size(path->nodes[0], path->slots[0]));
a37f232b
QW
2714 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
2715 struct btrfs_extent_item);
2716
2717 /*
2718 * Only support iteration on tree backref yet.
2719 *
2720 * This is an extra precaution for non skinny-metadata, where
2721 * EXTENT_ITEM is also used for tree blocks, that we can only use
2722 * extent flags to determine if it's a tree block.
2723 */
2724 if (btrfs_extent_flags(path->nodes[0], ei) & BTRFS_EXTENT_FLAG_DATA) {
2725 ret = -ENOTSUPP;
2726 goto release;
2727 }
2728 iter->cur_ptr = (u32)(iter->item_ptr + sizeof(*ei));
2729
2730 /* If there is no inline backref, go search for keyed backref */
2731 if (iter->cur_ptr >= iter->end_ptr) {
29cbcf40 2732 ret = btrfs_next_item(extent_root, path);
a37f232b
QW
2733
2734 /* No inline nor keyed ref */
2735 if (ret > 0) {
2736 ret = -ENOENT;
2737 goto release;
2738 }
2739 if (ret < 0)
2740 goto release;
2741
2742 btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key,
2743 path->slots[0]);
2744 if (iter->cur_key.objectid != bytenr ||
2745 (iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
2746 iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY)) {
2747 ret = -ENOENT;
2748 goto release;
2749 }
2750 iter->cur_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2751 path->slots[0]);
2752 iter->item_ptr = iter->cur_ptr;
3212fa14 2753 iter->end_ptr = (u32)(iter->item_ptr + btrfs_item_size(
a37f232b
QW
2754 path->nodes[0], path->slots[0]));
2755 }
2756
2757 return 0;
2758release:
2759 btrfs_backref_iter_release(iter);
2760 return ret;
2761}
c39c2ddc
QW
2762
2763/*
2764 * Go to the next backref item of current bytenr, can be either inlined or
2765 * keyed.
2766 *
2767 * Caller needs to check whether it's inline ref or not by iter->cur_key.
2768 *
2769 * Return 0 if we get next backref without problem.
2770 * Return >0 if there is no extra backref for this bytenr.
2771 * Return <0 if there is something wrong happened.
2772 */
2773int btrfs_backref_iter_next(struct btrfs_backref_iter *iter)
2774{
2775 struct extent_buffer *eb = btrfs_backref_get_eb(iter);
29cbcf40 2776 struct btrfs_root *extent_root;
c39c2ddc
QW
2777 struct btrfs_path *path = iter->path;
2778 struct btrfs_extent_inline_ref *iref;
2779 int ret;
2780 u32 size;
2781
2782 if (btrfs_backref_iter_is_inline_ref(iter)) {
2783 /* We're still inside the inline refs */
2784 ASSERT(iter->cur_ptr < iter->end_ptr);
2785
2786 if (btrfs_backref_has_tree_block_info(iter)) {
2787 /* First tree block info */
2788 size = sizeof(struct btrfs_tree_block_info);
2789 } else {
2790 /* Use inline ref type to determine the size */
2791 int type;
2792
2793 iref = (struct btrfs_extent_inline_ref *)
2794 ((unsigned long)iter->cur_ptr);
2795 type = btrfs_extent_inline_ref_type(eb, iref);
2796
2797 size = btrfs_extent_inline_ref_size(type);
2798 }
2799 iter->cur_ptr += size;
2800 if (iter->cur_ptr < iter->end_ptr)
2801 return 0;
2802
2803 /* All inline items iterated, fall through */
2804 }
2805
2806 /* We're at keyed items, there is no inline item, go to the next one */
29cbcf40
JB
2807 extent_root = btrfs_extent_root(iter->fs_info, iter->bytenr);
2808 ret = btrfs_next_item(extent_root, iter->path);
c39c2ddc
QW
2809 if (ret)
2810 return ret;
2811
2812 btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key, path->slots[0]);
2813 if (iter->cur_key.objectid != iter->bytenr ||
2814 (iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
2815 iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY))
2816 return 1;
2817 iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
2818 path->slots[0]);
2819 iter->cur_ptr = iter->item_ptr;
3212fa14 2820 iter->end_ptr = iter->item_ptr + (u32)btrfs_item_size(path->nodes[0],
c39c2ddc
QW
2821 path->slots[0]);
2822 return 0;
2823}
584fb121
QW
2824
2825void btrfs_backref_init_cache(struct btrfs_fs_info *fs_info,
2826 struct btrfs_backref_cache *cache, int is_reloc)
2827{
2828 int i;
2829
2830 cache->rb_root = RB_ROOT;
2831 for (i = 0; i < BTRFS_MAX_LEVEL; i++)
2832 INIT_LIST_HEAD(&cache->pending[i]);
2833 INIT_LIST_HEAD(&cache->changed);
2834 INIT_LIST_HEAD(&cache->detached);
2835 INIT_LIST_HEAD(&cache->leaves);
2836 INIT_LIST_HEAD(&cache->pending_edge);
2837 INIT_LIST_HEAD(&cache->useless_node);
2838 cache->fs_info = fs_info;
2839 cache->is_reloc = is_reloc;
2840}
b1818dab
QW
2841
2842struct btrfs_backref_node *btrfs_backref_alloc_node(
2843 struct btrfs_backref_cache *cache, u64 bytenr, int level)
2844{
2845 struct btrfs_backref_node *node;
2846
2847 ASSERT(level >= 0 && level < BTRFS_MAX_LEVEL);
2848 node = kzalloc(sizeof(*node), GFP_NOFS);
2849 if (!node)
2850 return node;
2851
2852 INIT_LIST_HEAD(&node->list);
2853 INIT_LIST_HEAD(&node->upper);
2854 INIT_LIST_HEAD(&node->lower);
2855 RB_CLEAR_NODE(&node->rb_node);
2856 cache->nr_nodes++;
2857 node->level = level;
2858 node->bytenr = bytenr;
2859
2860 return node;
2861}
47254d07
QW
2862
2863struct btrfs_backref_edge *btrfs_backref_alloc_edge(
2864 struct btrfs_backref_cache *cache)
2865{
2866 struct btrfs_backref_edge *edge;
2867
2868 edge = kzalloc(sizeof(*edge), GFP_NOFS);
2869 if (edge)
2870 cache->nr_edges++;
2871 return edge;
2872}
023acb07
QW
2873
2874/*
2875 * Drop the backref node from cache, also cleaning up all its
2876 * upper edges and any uncached nodes in the path.
2877 *
2878 * This cleanup happens bottom up, thus the node should either
2879 * be the lowest node in the cache or a detached node.
2880 */
2881void btrfs_backref_cleanup_node(struct btrfs_backref_cache *cache,
2882 struct btrfs_backref_node *node)
2883{
2884 struct btrfs_backref_node *upper;
2885 struct btrfs_backref_edge *edge;
2886
2887 if (!node)
2888 return;
2889
2890 BUG_ON(!node->lowest && !node->detached);
2891 while (!list_empty(&node->upper)) {
2892 edge = list_entry(node->upper.next, struct btrfs_backref_edge,
2893 list[LOWER]);
2894 upper = edge->node[UPPER];
2895 list_del(&edge->list[LOWER]);
2896 list_del(&edge->list[UPPER]);
2897 btrfs_backref_free_edge(cache, edge);
2898
023acb07
QW
2899 /*
2900 * Add the node to leaf node list if no other child block
2901 * cached.
2902 */
2903 if (list_empty(&upper->lower)) {
2904 list_add_tail(&upper->lower, &cache->leaves);
2905 upper->lowest = 1;
2906 }
2907 }
2908
2909 btrfs_backref_drop_node(cache, node);
2910}
13fe1bdb
QW
2911
2912/*
2913 * Release all nodes/edges from current cache
2914 */
2915void btrfs_backref_release_cache(struct btrfs_backref_cache *cache)
2916{
2917 struct btrfs_backref_node *node;
2918 int i;
2919
2920 while (!list_empty(&cache->detached)) {
2921 node = list_entry(cache->detached.next,
2922 struct btrfs_backref_node, list);
2923 btrfs_backref_cleanup_node(cache, node);
2924 }
2925
2926 while (!list_empty(&cache->leaves)) {
2927 node = list_entry(cache->leaves.next,
2928 struct btrfs_backref_node, lower);
2929 btrfs_backref_cleanup_node(cache, node);
2930 }
2931
2932 cache->last_trans = 0;
2933
2934 for (i = 0; i < BTRFS_MAX_LEVEL; i++)
2935 ASSERT(list_empty(&cache->pending[i]));
2936 ASSERT(list_empty(&cache->pending_edge));
2937 ASSERT(list_empty(&cache->useless_node));
2938 ASSERT(list_empty(&cache->changed));
2939 ASSERT(list_empty(&cache->detached));
2940 ASSERT(RB_EMPTY_ROOT(&cache->rb_root));
2941 ASSERT(!cache->nr_nodes);
2942 ASSERT(!cache->nr_edges);
2943}
1b60d2ec
QW
2944
2945/*
2946 * Handle direct tree backref
2947 *
2948 * Direct tree backref means, the backref item shows its parent bytenr
2949 * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
2950 *
2951 * @ref_key: The converted backref key.
2952 * For keyed backref, it's the item key.
2953 * For inlined backref, objectid is the bytenr,
2954 * type is btrfs_inline_ref_type, offset is
2955 * btrfs_inline_ref_offset.
2956 */
2957static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
2958 struct btrfs_key *ref_key,
2959 struct btrfs_backref_node *cur)
2960{
2961 struct btrfs_backref_edge *edge;
2962 struct btrfs_backref_node *upper;
2963 struct rb_node *rb_node;
2964
2965 ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
2966
2967 /* Only reloc root uses backref pointing to itself */
2968 if (ref_key->objectid == ref_key->offset) {
2969 struct btrfs_root *root;
2970
2971 cur->is_reloc_root = 1;
2972 /* Only reloc backref cache cares about a specific root */
2973 if (cache->is_reloc) {
2974 root = find_reloc_root(cache->fs_info, cur->bytenr);
f78743fb 2975 if (!root)
1b60d2ec
QW
2976 return -ENOENT;
2977 cur->root = root;
2978 } else {
2979 /*
2980 * For generic purpose backref cache, reloc root node
2981 * is useless.
2982 */
2983 list_add(&cur->list, &cache->useless_node);
2984 }
2985 return 0;
2986 }
2987
2988 edge = btrfs_backref_alloc_edge(cache);
2989 if (!edge)
2990 return -ENOMEM;
2991
2992 rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
2993 if (!rb_node) {
2994 /* Parent node not yet cached */
2995 upper = btrfs_backref_alloc_node(cache, ref_key->offset,
2996 cur->level + 1);
2997 if (!upper) {
2998 btrfs_backref_free_edge(cache, edge);
2999 return -ENOMEM;
3000 }
3001
3002 /*
3003 * Backrefs for the upper level block isn't cached, add the
3004 * block to pending list
3005 */
3006 list_add_tail(&edge->list[UPPER], &cache->pending_edge);
3007 } else {
3008 /* Parent node already cached */
3009 upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
3010 ASSERT(upper->checked);
3011 INIT_LIST_HEAD(&edge->list[UPPER]);
3012 }
3013 btrfs_backref_link_edge(edge, cur, upper, LINK_LOWER);
3014 return 0;
3015}
3016
3017/*
3018 * Handle indirect tree backref
3019 *
3020 * Indirect tree backref means, we only know which tree the node belongs to.
3021 * We still need to do a tree search to find out the parents. This is for
3022 * TREE_BLOCK_REF backref (keyed or inlined).
3023 *
3024 * @ref_key: The same as @ref_key in handle_direct_tree_backref()
3025 * @tree_key: The first key of this tree block.
1a9fd417 3026 * @path: A clean (released) path, to avoid allocating path every time
1b60d2ec
QW
3027 * the function get called.
3028 */
3029static int handle_indirect_tree_backref(struct btrfs_backref_cache *cache,
3030 struct btrfs_path *path,
3031 struct btrfs_key *ref_key,
3032 struct btrfs_key *tree_key,
3033 struct btrfs_backref_node *cur)
3034{
3035 struct btrfs_fs_info *fs_info = cache->fs_info;
3036 struct btrfs_backref_node *upper;
3037 struct btrfs_backref_node *lower;
3038 struct btrfs_backref_edge *edge;
3039 struct extent_buffer *eb;
3040 struct btrfs_root *root;
1b60d2ec
QW
3041 struct rb_node *rb_node;
3042 int level;
3043 bool need_check = true;
3044 int ret;
3045
56e9357a 3046 root = btrfs_get_fs_root(fs_info, ref_key->offset, false);
1b60d2ec
QW
3047 if (IS_ERR(root))
3048 return PTR_ERR(root);
92a7cc42 3049 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
1b60d2ec
QW
3050 cur->cowonly = 1;
3051
3052 if (btrfs_root_level(&root->root_item) == cur->level) {
3053 /* Tree root */
3054 ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
876de781
QW
3055 /*
3056 * For reloc backref cache, we may ignore reloc root. But for
3057 * general purpose backref cache, we can't rely on
3058 * btrfs_should_ignore_reloc_root() as it may conflict with
3059 * current running relocation and lead to missing root.
3060 *
3061 * For general purpose backref cache, reloc root detection is
3062 * completely relying on direct backref (key->offset is parent
3063 * bytenr), thus only do such check for reloc cache.
3064 */
3065 if (btrfs_should_ignore_reloc_root(root) && cache->is_reloc) {
1b60d2ec
QW
3066 btrfs_put_root(root);
3067 list_add(&cur->list, &cache->useless_node);
3068 } else {
3069 cur->root = root;
3070 }
3071 return 0;
3072 }
3073
3074 level = cur->level + 1;
3075
3076 /* Search the tree to find parent blocks referring to the block */
3077 path->search_commit_root = 1;
3078 path->skip_locking = 1;
3079 path->lowest_level = level;
3080 ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
3081 path->lowest_level = 0;
3082 if (ret < 0) {
3083 btrfs_put_root(root);
3084 return ret;
3085 }
3086 if (ret > 0 && path->slots[level] > 0)
3087 path->slots[level]--;
3088
3089 eb = path->nodes[level];
3090 if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
3091 btrfs_err(fs_info,
3092"couldn't find block (%llu) (level %d) in tree (%llu) with key (%llu %u %llu)",
3093 cur->bytenr, level - 1, root->root_key.objectid,
3094 tree_key->objectid, tree_key->type, tree_key->offset);
3095 btrfs_put_root(root);
3096 ret = -ENOENT;
3097 goto out;
3098 }
3099 lower = cur;
3100
3101 /* Add all nodes and edges in the path */
3102 for (; level < BTRFS_MAX_LEVEL; level++) {
3103 if (!path->nodes[level]) {
3104 ASSERT(btrfs_root_bytenr(&root->root_item) ==
3105 lower->bytenr);
876de781
QW
3106 /* Same as previous should_ignore_reloc_root() call */
3107 if (btrfs_should_ignore_reloc_root(root) &&
3108 cache->is_reloc) {
1b60d2ec
QW
3109 btrfs_put_root(root);
3110 list_add(&lower->list, &cache->useless_node);
3111 } else {
3112 lower->root = root;
3113 }
3114 break;
3115 }
3116
3117 edge = btrfs_backref_alloc_edge(cache);
3118 if (!edge) {
3119 btrfs_put_root(root);
3120 ret = -ENOMEM;
3121 goto out;
3122 }
3123
3124 eb = path->nodes[level];
3125 rb_node = rb_simple_search(&cache->rb_root, eb->start);
3126 if (!rb_node) {
3127 upper = btrfs_backref_alloc_node(cache, eb->start,
3128 lower->level + 1);
3129 if (!upper) {
3130 btrfs_put_root(root);
3131 btrfs_backref_free_edge(cache, edge);
3132 ret = -ENOMEM;
3133 goto out;
3134 }
3135 upper->owner = btrfs_header_owner(eb);
92a7cc42 3136 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
1b60d2ec
QW
3137 upper->cowonly = 1;
3138
3139 /*
3140 * If we know the block isn't shared we can avoid
3141 * checking its backrefs.
3142 */
3143 if (btrfs_block_can_be_shared(root, eb))
3144 upper->checked = 0;
3145 else
3146 upper->checked = 1;
3147
3148 /*
3149 * Add the block to pending list if we need to check its
3150 * backrefs, we only do this once while walking up a
3151 * tree as we will catch anything else later on.
3152 */
3153 if (!upper->checked && need_check) {
3154 need_check = false;
3155 list_add_tail(&edge->list[UPPER],
3156 &cache->pending_edge);
3157 } else {
3158 if (upper->checked)
3159 need_check = true;
3160 INIT_LIST_HEAD(&edge->list[UPPER]);
3161 }
3162 } else {
3163 upper = rb_entry(rb_node, struct btrfs_backref_node,
3164 rb_node);
3165 ASSERT(upper->checked);
3166 INIT_LIST_HEAD(&edge->list[UPPER]);
3167 if (!upper->owner)
3168 upper->owner = btrfs_header_owner(eb);
3169 }
3170 btrfs_backref_link_edge(edge, lower, upper, LINK_LOWER);
3171
3172 if (rb_node) {
3173 btrfs_put_root(root);
3174 break;
3175 }
3176 lower = upper;
3177 upper = NULL;
3178 }
3179out:
3180 btrfs_release_path(path);
3181 return ret;
3182}
3183
3184/*
3185 * Add backref node @cur into @cache.
3186 *
3187 * NOTE: Even if the function returned 0, @cur is not yet cached as its upper
3188 * links aren't yet bi-directional. Needs to finish such links.
fc997ed0 3189 * Use btrfs_backref_finish_upper_links() to finish such linkage.
1b60d2ec
QW
3190 *
3191 * @path: Released path for indirect tree backref lookup
3192 * @iter: Released backref iter for extent tree search
3193 * @node_key: The first key of the tree block
3194 */
3195int btrfs_backref_add_tree_node(struct btrfs_backref_cache *cache,
3196 struct btrfs_path *path,
3197 struct btrfs_backref_iter *iter,
3198 struct btrfs_key *node_key,
3199 struct btrfs_backref_node *cur)
3200{
3201 struct btrfs_fs_info *fs_info = cache->fs_info;
3202 struct btrfs_backref_edge *edge;
3203 struct btrfs_backref_node *exist;
3204 int ret;
3205
3206 ret = btrfs_backref_iter_start(iter, cur->bytenr);
3207 if (ret < 0)
3208 return ret;
3209 /*
3210 * We skip the first btrfs_tree_block_info, as we don't use the key
3211 * stored in it, but fetch it from the tree block
3212 */
3213 if (btrfs_backref_has_tree_block_info(iter)) {
3214 ret = btrfs_backref_iter_next(iter);
3215 if (ret < 0)
3216 goto out;
3217 /* No extra backref? This means the tree block is corrupted */
3218 if (ret > 0) {
3219 ret = -EUCLEAN;
3220 goto out;
3221 }
3222 }
3223 WARN_ON(cur->checked);
3224 if (!list_empty(&cur->upper)) {
3225 /*
3226 * The backref was added previously when processing backref of
3227 * type BTRFS_TREE_BLOCK_REF_KEY
3228 */
3229 ASSERT(list_is_singular(&cur->upper));
3230 edge = list_entry(cur->upper.next, struct btrfs_backref_edge,
3231 list[LOWER]);
3232 ASSERT(list_empty(&edge->list[UPPER]));
3233 exist = edge->node[UPPER];
3234 /*
3235 * Add the upper level block to pending list if we need check
3236 * its backrefs
3237 */
3238 if (!exist->checked)
3239 list_add_tail(&edge->list[UPPER], &cache->pending_edge);
3240 } else {
3241 exist = NULL;
3242 }
3243
3244 for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
3245 struct extent_buffer *eb;
3246 struct btrfs_key key;
3247 int type;
3248
3249 cond_resched();
3250 eb = btrfs_backref_get_eb(iter);
3251
3252 key.objectid = iter->bytenr;
3253 if (btrfs_backref_iter_is_inline_ref(iter)) {
3254 struct btrfs_extent_inline_ref *iref;
3255
3256 /* Update key for inline backref */
3257 iref = (struct btrfs_extent_inline_ref *)
3258 ((unsigned long)iter->cur_ptr);
3259 type = btrfs_get_extent_inline_ref_type(eb, iref,
3260 BTRFS_REF_TYPE_BLOCK);
3261 if (type == BTRFS_REF_TYPE_INVALID) {
3262 ret = -EUCLEAN;
3263 goto out;
3264 }
3265 key.type = type;
3266 key.offset = btrfs_extent_inline_ref_offset(eb, iref);
3267 } else {
3268 key.type = iter->cur_key.type;
3269 key.offset = iter->cur_key.offset;
3270 }
3271
3272 /*
3273 * Parent node found and matches current inline ref, no need to
3274 * rebuild this node for this inline ref
3275 */
3276 if (exist &&
3277 ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
3278 exist->owner == key.offset) ||
3279 (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
3280 exist->bytenr == key.offset))) {
3281 exist = NULL;
3282 continue;
3283 }
3284
3285 /* SHARED_BLOCK_REF means key.offset is the parent bytenr */
3286 if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
3287 ret = handle_direct_tree_backref(cache, &key, cur);
3288 if (ret < 0)
3289 goto out;
3290 continue;
3291 } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
3292 ret = -EINVAL;
3293 btrfs_print_v0_err(fs_info);
3294 btrfs_handle_fs_error(fs_info, ret, NULL);
3295 goto out;
3296 } else if (key.type != BTRFS_TREE_BLOCK_REF_KEY) {
3297 continue;
3298 }
3299
3300 /*
3301 * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref offset
3302 * means the root objectid. We need to search the tree to get
3303 * its parent bytenr.
3304 */
3305 ret = handle_indirect_tree_backref(cache, path, &key, node_key,
3306 cur);
3307 if (ret < 0)
3308 goto out;
3309 }
3310 ret = 0;
3311 cur->checked = 1;
3312 WARN_ON(exist);
3313out:
3314 btrfs_backref_iter_release(iter);
3315 return ret;
3316}
fc997ed0
QW
3317
3318/*
3319 * Finish the upwards linkage created by btrfs_backref_add_tree_node()
3320 */
3321int btrfs_backref_finish_upper_links(struct btrfs_backref_cache *cache,
3322 struct btrfs_backref_node *start)
3323{
3324 struct list_head *useless_node = &cache->useless_node;
3325 struct btrfs_backref_edge *edge;
3326 struct rb_node *rb_node;
3327 LIST_HEAD(pending_edge);
3328
3329 ASSERT(start->checked);
3330
3331 /* Insert this node to cache if it's not COW-only */
3332 if (!start->cowonly) {
3333 rb_node = rb_simple_insert(&cache->rb_root, start->bytenr,
3334 &start->rb_node);
3335 if (rb_node)
3336 btrfs_backref_panic(cache->fs_info, start->bytenr,
3337 -EEXIST);
3338 list_add_tail(&start->lower, &cache->leaves);
3339 }
3340
3341 /*
3342 * Use breadth first search to iterate all related edges.
3343 *
3344 * The starting points are all the edges of this node
3345 */
3346 list_for_each_entry(edge, &start->upper, list[LOWER])
3347 list_add_tail(&edge->list[UPPER], &pending_edge);
3348
3349 while (!list_empty(&pending_edge)) {
3350 struct btrfs_backref_node *upper;
3351 struct btrfs_backref_node *lower;
fc997ed0
QW
3352
3353 edge = list_first_entry(&pending_edge,
3354 struct btrfs_backref_edge, list[UPPER]);
3355 list_del_init(&edge->list[UPPER]);
3356 upper = edge->node[UPPER];
3357 lower = edge->node[LOWER];
3358
3359 /* Parent is detached, no need to keep any edges */
3360 if (upper->detached) {
3361 list_del(&edge->list[LOWER]);
3362 btrfs_backref_free_edge(cache, edge);
3363
3364 /* Lower node is orphan, queue for cleanup */
3365 if (list_empty(&lower->upper))
3366 list_add(&lower->list, useless_node);
3367 continue;
3368 }
3369
3370 /*
3371 * All new nodes added in current build_backref_tree() haven't
3372 * been linked to the cache rb tree.
3373 * So if we have upper->rb_node populated, this means a cache
3374 * hit. We only need to link the edge, as @upper and all its
3375 * parents have already been linked.
3376 */
3377 if (!RB_EMPTY_NODE(&upper->rb_node)) {
3378 if (upper->lowest) {
3379 list_del_init(&upper->lower);
3380 upper->lowest = 0;
3381 }
3382
3383 list_add_tail(&edge->list[UPPER], &upper->lower);
3384 continue;
3385 }
3386
3387 /* Sanity check, we shouldn't have any unchecked nodes */
3388 if (!upper->checked) {
3389 ASSERT(0);
3390 return -EUCLEAN;
3391 }
3392
3393 /* Sanity check, COW-only node has non-COW-only parent */
3394 if (start->cowonly != upper->cowonly) {
3395 ASSERT(0);
3396 return -EUCLEAN;
3397 }
3398
3399 /* Only cache non-COW-only (subvolume trees) tree blocks */
3400 if (!upper->cowonly) {
3401 rb_node = rb_simple_insert(&cache->rb_root, upper->bytenr,
3402 &upper->rb_node);
3403 if (rb_node) {
3404 btrfs_backref_panic(cache->fs_info,
3405 upper->bytenr, -EEXIST);
3406 return -EUCLEAN;
3407 }
3408 }
3409
3410 list_add_tail(&edge->list[UPPER], &upper->lower);
3411
3412 /*
3413 * Also queue all the parent edges of this uncached node
3414 * to finish the upper linkage
3415 */
3416 list_for_each_entry(edge, &upper->upper, list[LOWER])
3417 list_add_tail(&edge->list[UPPER], &pending_edge);
3418 }
3419 return 0;
3420}
1b23ea18
QW
3421
3422void btrfs_backref_error_cleanup(struct btrfs_backref_cache *cache,
3423 struct btrfs_backref_node *node)
3424{
3425 struct btrfs_backref_node *lower;
3426 struct btrfs_backref_node *upper;
3427 struct btrfs_backref_edge *edge;
3428
3429 while (!list_empty(&cache->useless_node)) {
3430 lower = list_first_entry(&cache->useless_node,
3431 struct btrfs_backref_node, list);
3432 list_del_init(&lower->list);
3433 }
3434 while (!list_empty(&cache->pending_edge)) {
3435 edge = list_first_entry(&cache->pending_edge,
3436 struct btrfs_backref_edge, list[UPPER]);
3437 list_del(&edge->list[UPPER]);
3438 list_del(&edge->list[LOWER]);
3439 lower = edge->node[LOWER];
3440 upper = edge->node[UPPER];
3441 btrfs_backref_free_edge(cache, edge);
3442
3443 /*
3444 * Lower is no longer linked to any upper backref nodes and
3445 * isn't in the cache, we can free it ourselves.
3446 */
3447 if (list_empty(&lower->upper) &&
3448 RB_EMPTY_NODE(&lower->rb_node))
3449 list_add(&lower->list, &cache->useless_node);
3450
3451 if (!RB_EMPTY_NODE(&upper->rb_node))
3452 continue;
3453
3454 /* Add this guy's upper edges to the list to process */
3455 list_for_each_entry(edge, &upper->upper, list[LOWER])
3456 list_add_tail(&edge->list[UPPER],
3457 &cache->pending_edge);
3458 if (list_empty(&upper->upper))
3459 list_add(&upper->list, &cache->useless_node);
3460 }
3461
3462 while (!list_empty(&cache->useless_node)) {
3463 lower = list_first_entry(&cache->useless_node,
3464 struct btrfs_backref_node, list);
3465 list_del_init(&lower->list);
3466 if (lower == node)
3467 node = NULL;
49ecc679 3468 btrfs_backref_drop_node(cache, lower);
1b23ea18
QW
3469 }
3470
3471 btrfs_backref_cleanup_node(cache, node);
3472 ASSERT(list_empty(&cache->useless_node) &&
3473 list_empty(&cache->pending_edge));
3474}