1 // SPDX-License-Identifier: GPL-2.0+
2 
3 #include "ctree.h"
4 
5 int btrfs_find_last_root(struct btrfs_root *root, u64 objectid,
6 			struct btrfs_root_item *item, struct btrfs_key *key)
7 {
8 	struct btrfs_path *path;
9 	struct btrfs_key search_key;
10 	struct btrfs_key found_key;
11 	struct extent_buffer *l;
12 	int ret;
13 	int slot;
14 
15 	path = btrfs_alloc_path();
16 	if (!path)
17 		return -ENOMEM;
18 
19 	search_key.objectid = objectid;
20 	search_key.type = BTRFS_ROOT_ITEM_KEY;
21 	search_key.offset = (u64)-1;
22 
23 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
24 	if (ret < 0)
25 		goto out;
26 	if (path->slots[0] == 0) {
27 		ret = -ENOENT;
28 		goto out;
29 	}
30 
31 	BUG_ON(ret == 0);
32 	l = path->nodes[0];
33 	slot = path->slots[0] - 1;
34 	btrfs_item_key_to_cpu(l, &found_key, slot);
35 	if (found_key.type != BTRFS_ROOT_ITEM_KEY ||
36 	    found_key.objectid != objectid) {
37 		ret = -ENOENT;
38 		goto out;
39 	}
40 	read_extent_buffer(l, item, btrfs_item_ptr_offset(l, slot),
41 			   sizeof(*item));
42 	memcpy(key, &found_key, sizeof(found_key));
43 	ret = 0;
44 out:
45 	btrfs_free_path(path);
46 	return ret;
47 }
48