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