3 * @author Lunaixsky (zelong56@gmail.com)
4 * @brief TwiFS - A pseudo file system for kernel state exposure.
8 * @copyright Copyright (c) 2022
11 #include <klibc/string.h>
12 #include <lunaix/clock.h>
13 #include <lunaix/fs.h>
14 #include <lunaix/fs/twifs.h>
15 #include <lunaix/mm/cake.h>
16 #include <lunaix/mm/valloc.h>
18 static struct twifs_node fs_root;
20 static struct cake_pile* twi_pile;
23 __twifs_dirlookup(struct v_inode* inode, struct v_dnode* dnode);
26 __twifs_openfile(struct v_inode* inode, struct v_file* file);
29 __twifs_get_node(struct twifs_node* parent, struct hstr* name);
34 twi_pile = cake_new_pile("twifs_node", sizeof(struct twifs_node), 1, 0);
36 struct filesystem* twifs = vzalloc(sizeof(struct filesystem));
37 twifs->fs_name = HSTR("twifs", 5);
38 twifs->mount = __twifs_mount;
42 memset(&fs_root, 0, sizeof(fs_root));
43 llist_init_head(&fs_root.children);
46 twifs_toplevel_node("kernel", 6);
47 twifs_toplevel_node("dev", 3);
48 twifs_toplevel_node("bus", 3);
52 twifs_child_node(struct twifs_node* parent, const char* name, int name_len)
54 struct hstr hname = HSTR(name, name_len);
55 hstr_rehash(&hname, HSTR_FULL_HASH);
57 struct twifs_node* node = __twifs_get_node(parent, &hname);
62 node = cake_grab(twi_pile);
63 memset(node, 0, sizeof(*node));
66 llist_init_head(&node->children);
67 llist_append(&parent->children, &node->siblings);
73 twifs_toplevel_node(const char* name, int name_len)
75 return twifs_child_node(&fs_root, name, name_len);
79 __twifs_mount(struct v_superblock* vsb, struct v_dnode* mount_point)
81 mount_point->inode = __twifs_create_inode(&fs_root);
85 __twifs_create_inode(struct twifs_node* twi_node)
87 struct v_inode* inode = vfs_i_alloc();
88 *inode = (struct v_inode){ .ctime = 0,
89 .itype = twi_node->itype,
95 inode->ops.dir_lookup = __twifs_dirlookup;
96 inode->ops.open = __twifs_openfile;
100 __twifs_get_node(struct twifs_node* parent, struct hstr* name)
102 struct twifs_node *pos, *n;
103 llist_for_each(pos, n, &parent->children, siblings)
105 if (HSTR_EQ(&pos->name, name)) {
113 __twifs_dirlookup(struct v_inode* inode, struct v_dnode* dnode)
115 struct twifs_node* twi_node = (struct twifs_node*)inode->data;
117 struct twifs_node* child_node = __twifs_get_node(twi_node, &dnode->name);
119 dnode->inode = __twifs_create_inode(child_node);
126 __twifs_iterate_dir(struct v_file* file, struct dir_context* dctx)
128 struct twifs_node* twi_node = (struct twifs_node*)(file->inode->data);
130 struct twifs_node *pos, *n;
132 llist_for_each(pos, n, &twi_node->children, siblings)
134 if (counter++ >= dctx->index) {
135 dctx->index = counter;
136 dctx->read_complete_callback(dctx, pos->name.value, pos->itype);
141 return VFS_EENDOFDIR;
145 __twifs_openfile(struct v_inode* inode, struct v_file* file)
147 struct twifs_node* twi_node = (struct twifs_node*)inode->data;
149 file->ops = twi_node->fops;