feat: readdir fix and demo
[lunaix-os.git] / lunaix-os / kernel / fs / vfs.c
1 /**
2  * @file vfs.c
3  * @author Lunaixsky (zelong56@gmail.com)
4  * @brief Lunaix virtual file system - an abstraction layer for all file system.
5  * @version 0.1
6  * @date 2022-07-24
7  *
8  * @copyright Copyright (c) 2022
9  *
10  */
11
12 #include <klibc/string.h>
13 #include <lunaix/dirent.h>
14 #include <lunaix/foptions.h>
15 #include <lunaix/fs.h>
16 #include <lunaix/mm/cake.h>
17 #include <lunaix/mm/page.h>
18 #include <lunaix/mm/valloc.h>
19 #include <lunaix/process.h>
20 #include <lunaix/spike.h>
21 #include <lunaix/syscall.h>
22
23 #define PATH_DELIM '/'
24 #define DNODE_HASHTABLE_BITS 10
25 #define DNODE_HASHTABLE_SIZE (1 << DNODE_HASHTABLE_BITS)
26 #define DNODE_HASH_MASK (DNODE_HASHTABLE_SIZE - 1)
27 #define DNODE_HASHBITS (32 - DNODE_HASHTABLE_BITS)
28
29 static struct cake_pile* dnode_pile;
30 static struct cake_pile* inode_pile;
31 static struct cake_pile* file_pile;
32 static struct cake_pile* superblock_pile;
33 static struct cake_pile* fd_pile;
34
35 static struct v_superblock* root_sb;
36 static struct hbucket* dnode_cache;
37
38 static int fs_id = 0;
39
40 struct v_dnode*
41 vfs_d_alloc();
42
43 void
44 vfs_d_free(struct v_dnode* dnode);
45
46 struct v_superblock*
47 vfs_sb_alloc();
48
49 void
50 vfs_sb_free(struct v_superblock* sb);
51
52 void
53 vfs_init()
54 {
55     // 为他们专门创建一个蛋糕堆,而不使用valloc,这样我们可以最小化内碎片的产生
56     dnode_pile = cake_new_pile("dnode_cache", sizeof(struct v_dnode), 1, 0);
57     inode_pile = cake_new_pile("inode_cache", sizeof(struct v_inode), 1, 0);
58     file_pile = cake_new_pile("file_cache", sizeof(struct v_file), 1, 0);
59     fd_pile = cake_new_pile("fd_cache", sizeof(struct v_fd), 1, 0);
60     superblock_pile =
61       cake_new_pile("sb_cache", sizeof(struct v_superblock), 1, 0);
62
63     dnode_cache = vzalloc(DNODE_HASHTABLE_SIZE * sizeof(struct hbucket));
64
65     // 创建一个根superblock,用来蕴含我们的根目录。
66     root_sb = vfs_sb_alloc();
67     root_sb->root = vfs_d_alloc();
68 }
69
70 inline struct hbucket*
71 __dcache_get_bucket(struct v_dnode* parent, unsigned int hash)
72 {
73     // 与parent的指针值做加法,来减小碰撞的可能性。
74     hash += (uint32_t)parent;
75     // 确保低位更加随机
76     hash = hash ^ (hash >> DNODE_HASHBITS);
77     return &dnode_cache[hash & DNODE_HASH_MASK];
78 }
79
80 struct v_dnode*
81 vfs_dcache_lookup(struct v_dnode* parent, struct hstr* str)
82 {
83     if (!str->len)
84         return parent;
85
86     struct hbucket* slot = __dcache_get_bucket(parent, str->hash);
87
88     struct v_dnode *pos, *n;
89     hashtable_bucket_foreach(slot, pos, n, hash_list)
90     {
91         if (pos->name.hash == str->hash) {
92             return pos;
93         }
94     }
95     return NULL;
96 }
97
98 void
99 vfs_dcache_add(struct v_dnode* parent, struct v_dnode* dnode)
100 {
101     struct hbucket* bucket = __dcache_get_bucket(parent, dnode->name.hash);
102     hlist_add(&bucket->head, &dnode->hash_list);
103 }
104
105 int
106 vfs_walk(struct v_dnode* start,
107          const char* path,
108          struct v_dnode** dentry,
109          struct hstr* component,
110          int walk_options)
111 {
112     int errno = 0;
113     int i = 0, j = 0;
114
115     if (path[0] == PATH_DELIM || !start) {
116         if ((walk_options & VFS_WALK_FSRELATIVE) && start) {
117             start = start->super_block->root;
118         } else {
119             start = root_sb->root;
120         }
121         i++;
122     }
123
124     struct v_dnode* dnode;
125     struct v_dnode* current_level = start;
126
127     char name_content[VFS_NAME_MAXLEN];
128     struct hstr name = HSTR(name_content, 0);
129
130     char current = path[i++], lookahead;
131     while (current) {
132         lookahead = path[i++];
133         if (current != PATH_DELIM) {
134             if (j >= VFS_NAME_MAXLEN - 1) {
135                 return ENAMETOOLONG;
136             }
137             if (!VFS_VALID_CHAR(current)) {
138                 return VFS_EINVLD;
139             }
140             name_content[j++] = current;
141             if (lookahead) {
142                 goto cont;
143             }
144         }
145
146         // handling cases like /^.*(\/+).*$/
147         if (lookahead == PATH_DELIM) {
148             goto cont;
149         }
150
151         name_content[j] = 0;
152         name.len = j;
153         hstr_rehash(&name, HSTR_FULL_HASH);
154
155         if (!lookahead && (walk_options & VFS_WALK_PARENT)) {
156             if (component) {
157                 component->hash = name.hash;
158                 component->len = j;
159                 strcpy(component->value, name_content);
160             }
161             break;
162         }
163
164         dnode = vfs_dcache_lookup(current_level, &name);
165
166         if (!dnode) {
167             dnode = vfs_d_alloc();
168             dnode->name = HSTR(valloc(VFS_NAME_MAXLEN), j);
169             dnode->name.hash = name.hash;
170
171             strcpy(dnode->name.value, name_content);
172
173             errno =
174               current_level->inode->ops.dir_lookup(current_level->inode, dnode);
175
176             if (errno == ENOENT && (walk_options & VFS_WALK_MKPARENT)) {
177                 if (!current_level->inode->ops.mkdir) {
178                     errno = ENOTSUP;
179                 } else {
180                     errno = current_level->inode->ops.mkdir(
181                       current_level->inode, dnode);
182                 }
183             }
184
185             if (errno) {
186                 goto error;
187             }
188
189             vfs_dcache_add(current_level, dnode);
190
191             dnode->parent = current_level;
192             llist_append(&current_level->children, &dnode->siblings);
193         }
194
195         j = 0;
196         current_level = dnode;
197     cont:
198         current = lookahead;
199     };
200
201     *dentry = current_level;
202     return 0;
203
204 error:
205     vfree(dnode->name.value);
206     vfs_d_free(dnode);
207     return errno;
208 }
209
210 int
211 vfs_mount(const char* target, const char* fs_name, bdev_t device)
212 {
213     int errno;
214     struct v_dnode* mnt;
215
216     if (!(errno = vfs_walk(NULL, target, &mnt, NULL, 0))) {
217         errno = vfs_mount_at(fs_name, device, mnt);
218     }
219
220     return errno;
221 }
222
223 int
224 vfs_unmount(const char* target)
225 {
226     int errno;
227     struct v_dnode* mnt;
228
229     if (!(errno = vfs_walk(NULL, target, &mnt, NULL, 0))) {
230         errno = vfs_unmount_at(mnt);
231     }
232
233     return errno;
234 }
235
236 int
237 vfs_mount_at(const char* fs_name, bdev_t device, struct v_dnode* mnt_point)
238 {
239     struct filesystem* fs = fsm_get(fs_name);
240     if (!fs)
241         return VFS_ENOFS;
242     struct v_superblock* sb = vfs_sb_alloc();
243     sb->dev = device;
244     sb->fs_id = fs_id++;
245
246     int errno = 0;
247     if (!(errno = fs->mount(sb, mnt_point))) {
248         sb->fs = fs;
249         sb->root = mnt_point;
250         mnt_point->super_block = sb;
251         llist_append(&root_sb->sb_list, &sb->sb_list);
252     }
253
254     return errno;
255 }
256
257 int
258 vfs_unmount_at(struct v_dnode* mnt_point)
259 {
260     int errno = 0;
261     struct v_superblock* sb = mnt_point->super_block;
262     if (!sb) {
263         return VFS_EBADMNT;
264     }
265     if (!(errno = sb->fs->unmount(sb))) {
266         struct v_dnode* fs_root = sb->root;
267         llist_delete(&fs_root->siblings);
268         llist_delete(&sb->sb_list);
269         vfs_sb_free(sb);
270     }
271     return errno;
272 }
273
274 int
275 vfs_open(struct v_dnode* dnode, struct v_file** file)
276 {
277     if (!dnode->inode || !dnode->inode->ops.open) {
278         return ENOTSUP;
279     }
280
281     struct v_file* vfile = cake_grab(file_pile);
282     memset(vfile, 0, sizeof(*vfile));
283
284     int errno = dnode->inode->ops.open(dnode->inode, vfile);
285     if (errno) {
286         cake_release(file_pile, vfile);
287     } else {
288         *file = vfile;
289     }
290     return errno;
291 }
292
293 int
294 vfs_close(struct v_file* file)
295 {
296     if (!file->ops.close) {
297         return ENOTSUP;
298     }
299
300     int errno = file->ops.close(file);
301     if (!errno) {
302         cake_release(file_pile, file);
303     }
304     return errno;
305 }
306
307 int
308 vfs_fsync(struct v_file* file)
309 {
310     int errno = ENOTSUP;
311     if (file->ops.sync) {
312         errno = file->ops.sync(file);
313     }
314     if (!errno && file->inode->ops.sync) {
315         return file->inode->ops.sync(file->inode);
316     }
317     return errno;
318 }
319
320 int
321 vfs_alloc_fdslot(int* fd)
322 {
323     for (size_t i = 0; i < VFS_MAX_FD; i++) {
324         if (!__current->fdtable->fds[i]) {
325             *fd = i;
326             return 0;
327         }
328     }
329     return EMFILE;
330 }
331
332 struct v_superblock*
333 vfs_sb_alloc()
334 {
335     struct v_superblock* sb = cake_grab(superblock_pile);
336     memset(sb, 0, sizeof(*sb));
337     llist_init_head(&sb->sb_list);
338     return sb;
339 }
340
341 void
342 vfs_sb_free(struct v_superblock* sb)
343 {
344     cake_release(superblock_pile, sb);
345 }
346
347 struct v_dnode*
348 vfs_d_alloc()
349 {
350     struct v_dnode* dnode = cake_grab(dnode_pile);
351     llist_init_head(&dnode->children);
352 }
353
354 void
355 vfs_d_free(struct v_dnode* dnode)
356 {
357     if (dnode->ops.destruct) {
358         dnode->ops.destruct(dnode);
359     }
360     cake_release(dnode_pile, dnode);
361 }
362
363 struct v_inode*
364 vfs_i_alloc()
365 {
366     struct v_inode* inode = cake_grab(inode_pile);
367     memset(inode, 0, sizeof(*inode));
368
369     return inode;
370 }
371
372 void
373 vfs_i_free(struct v_inode* inode)
374 {
375     cake_release(inode_pile, inode);
376 }
377
378 __DEFINE_LXSYSCALL2(int, open, const char*, path, int, options)
379 {
380     char name_str[VFS_NAME_MAXLEN];
381     struct hstr name = HSTR(name_str, 0);
382     struct v_dnode *dentry, *file;
383     int errno, fd;
384     if ((errno = vfs_walk(NULL, path, &dentry, &name, VFS_WALK_PARENT))) {
385         return -1;
386     }
387
388     vfs_walk(dentry, name.value, &file, NULL, 0);
389
390     struct v_file* opened_file = 0;
391     if (!file) {
392         if ((options & FO_CREATE)) {
393             errno = dentry->inode->ops.create(dentry->inode, opened_file);
394         } else {
395             errno = ENOENT;
396         }
397     } else {
398         errno = vfs_open(file, &opened_file);
399     }
400
401     __current->k_status = errno;
402
403     if (!errno && !(errno = vfs_alloc_fdslot(&fd))) {
404         struct v_fd* fd_s = vzalloc(sizeof(*fd_s));
405         fd_s->file = opened_file;
406         fd_s->pos = file->inode->fsize & -((options & FO_APPEND) == 0);
407         __current->fdtable->fds[fd] = fd_s;
408     }
409
410     return SYSCALL_ESTATUS(errno);
411 }
412
413 __DEFINE_LXSYSCALL1(int, close, int, fd)
414 {
415     struct v_fd* fd_s;
416     int errno;
417     if (fd < 0 || fd >= VFS_MAX_FD || !(fd_s = __current->fdtable->fds[fd])) {
418         errno = EBADF;
419     } else if (!(errno = vfs_close(fd_s->file))) {
420         vfree(fd_s);
421         __current->fdtable->fds[fd] = 0;
422     }
423
424     __current->k_status = errno;
425
426     return SYSCALL_ESTATUS(errno);
427 }
428
429 void
430 __vfs_readdir_callback(struct dir_context* dctx,
431                        const char* name,
432                        const int len,
433                        const int dtype)
434 {
435     struct dirent* dent = (struct dirent*)dctx->cb_data;
436     strncpy(dent->d_name, name, DIRENT_NAME_MAX_LEN);
437     dent->d_nlen = len;
438     dent->d_type = dtype;
439 }
440
441 __DEFINE_LXSYSCALL2(int, readdir, int, fd, struct dirent*, dent)
442 {
443     struct v_fd* fd_s;
444     int errno;
445     if (fd < 0 || fd >= VFS_MAX_FD || !(fd_s = __current->fdtable->fds[fd])) {
446         errno = EBADF;
447     } else if (!(fd_s->file->inode->itype & VFS_INODE_TYPE_DIR)) {
448         errno = ENOTDIR;
449     } else {
450         struct dir_context dctx =
451           (struct dir_context){ .cb_data = dent,
452                                 .index = dent->d_offset,
453                                 .read_complete_callback =
454                                   __vfs_readdir_callback };
455         if (!(errno = fd_s->file->ops.readdir(fd_s->file, &dctx))) {
456             dent->d_offset++;
457         }
458     }
459
460     __current->k_status = errno;
461     return SYSCALL_ESTATUS(errno);
462 }
463
464 __DEFINE_LXSYSCALL1(int, mkdir, const char*, path)
465 {
466     struct v_dnode *parent, *dir;
467     struct hstr component = HSTR(valloc(VFS_NAME_MAXLEN), 0);
468     int errno = vfs_walk(NULL, path, &parent, &component, VFS_WALK_PARENT);
469     if (errno) {
470         goto done;
471     }
472
473     if (!parent->inode->ops.mkdir) {
474         errno = ENOTSUP;
475     } else if (!(parent->inode->itype & VFS_INODE_TYPE_DIR)) {
476         errno = ENOTDIR;
477     } else {
478         dir = vfs_d_alloc();
479         dir->name = component;
480         if (!(errno = parent->inode->ops.mkdir(parent->inode, dir))) {
481             llist_append(&parent->children, &dir->siblings);
482         } else {
483             vfs_d_free(dir);
484             vfree(component.value);
485         }
486     }
487
488 done:
489     __current->k_status = errno;
490     return SYSCALL_ESTATUS(errno);
491 }
492
493 __DEFINE_LXSYSCALL3(size_t, read, int, fd, void*, buf, size_t, count)
494 {
495     // TODO
496 }
497
498 __DEFINE_LXSYSCALL3(size_t, write, int, fd, void*, buf, size_t, count)
499 {
500     // TODO
501 }