1 // SPDX-License-Identifier: GPL-2.0+
3 * BTRFS filesystem implementation for U-Boot
5 * 2017 Marek Behun, CZ.NIC, marek.behun@nic.cz
10 static int verify_dir_item(struct btrfs_dir_item *item, u32 start, u32 total)
12 u16 max_len = BTRFS_NAME_LEN;
15 if (item->type >= BTRFS_FT_MAX) {
16 printf("%s: invalid dir item type: %i\n", __func__, item->type);
20 if (item->type == BTRFS_FT_XATTR)
21 max_len = 255; /* XATTR_NAME_MAX */
23 end = start + sizeof(*item) + item->name_len;
24 if (item->name_len > max_len || end > total) {
25 printf("%s: invalid dir item name len: %u\n", __func__,
33 static struct btrfs_dir_item *
34 btrfs_match_dir_item_name(struct btrfs_path *path, const char *name,
37 struct btrfs_dir_item *item;
38 u32 total_len, cur = 0, this_len;
41 item = btrfs_path_item_ptr(path, struct btrfs_dir_item);
43 total_len = btrfs_path_item_size(path);
45 while (cur < total_len) {
46 btrfs_dir_item_to_cpu(item);
47 this_len = sizeof(*item) + item->name_len + item->data_len;
48 name_ptr = (const char *) (item + 1);
50 if (verify_dir_item(item, cur, total_len))
52 if (item->name_len == name_len && !memcmp(name_ptr, name,
57 item = (struct btrfs_dir_item *) ((u8 *) item + this_len);
63 int btrfs_lookup_dir_item(const struct btrfs_root *root, u64 dir,
64 const char *name, int name_len,
65 struct btrfs_dir_item *item)
67 struct btrfs_path path;
69 struct btrfs_dir_item *res = NULL;
72 key.type = BTRFS_DIR_ITEM_KEY;
73 key.offset = btrfs_name_hash(name, name_len);
75 if (btrfs_search_tree(root, &key, &path))
78 if (btrfs_comp_keys_type(&key, btrfs_path_leaf_key(&path)))
81 res = btrfs_match_dir_item_name(&path, name, name_len);
85 btrfs_free_path(&path);
89 int btrfs_readdir(const struct btrfs_root *root, u64 dir,
90 btrfs_readdir_callback_t callback)
92 struct btrfs_path path;
93 struct btrfs_key key, *found_key;
94 struct btrfs_dir_item *item;
98 key.type = BTRFS_DIR_INDEX_KEY;
101 if (btrfs_search_tree(root, &key, &path))
105 found_key = btrfs_path_leaf_key(&path);
106 if (btrfs_comp_keys_type(&key, found_key))
109 item = btrfs_path_item_ptr(&path, struct btrfs_dir_item);
110 btrfs_dir_item_to_cpu(item);
112 if (verify_dir_item(item, 0, sizeof(*item) + item->name_len))
114 if (item->type == BTRFS_FT_XATTR)
117 if (callback(root, item))
119 } while (!(res = btrfs_next_slot(&path)));
121 btrfs_free_path(&path);
123 return res < 0 ? -1 : 0;