feat: lseek(2), read(2), write(2) implementation
[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     *dentry = NULL;
208     return errno;
209 }
210
211 int
212 vfs_mount(const char* target, const char* fs_name, bdev_t device)
213 {
214     int errno;
215     struct v_dnode* mnt;
216
217     if (!(errno = vfs_walk(NULL, target, &mnt, NULL, 0))) {
218         errno = vfs_mount_at(fs_name, device, mnt);
219     }
220
221     return errno;
222 }
223
224 int
225 vfs_unmount(const char* target)
226 {
227     int errno;
228     struct v_dnode* mnt;
229
230     if (!(errno = vfs_walk(NULL, target, &mnt, NULL, 0))) {
231         errno = vfs_unmount_at(mnt);
232     }
233
234     return errno;
235 }
236
237 int
238 vfs_mount_at(const char* fs_name, bdev_t device, struct v_dnode* mnt_point)
239 {
240     struct filesystem* fs = fsm_get(fs_name);
241     if (!fs)
242         return VFS_ENOFS;
243     struct v_superblock* sb = vfs_sb_alloc();
244     sb->dev = device;
245     sb->fs_id = fs_id++;
246
247     int errno = 0;
248     if (!(errno = fs->mount(sb, mnt_point))) {
249         sb->fs = fs;
250         sb->root = mnt_point;
251         mnt_point->super_block = sb;
252         llist_append(&root_sb->sb_list, &sb->sb_list);
253     }
254
255     return errno;
256 }
257
258 int
259 vfs_unmount_at(struct v_dnode* mnt_point)
260 {
261     int errno = 0;
262     struct v_superblock* sb = mnt_point->super_block;
263     if (!sb) {
264         return VFS_EBADMNT;
265     }
266     if (!(errno = sb->fs->unmount(sb))) {
267         struct v_dnode* fs_root = sb->root;
268         llist_delete(&fs_root->siblings);
269         llist_delete(&sb->sb_list);
270         vfs_sb_free(sb);
271     }
272     return errno;
273 }
274
275 int
276 vfs_open(struct v_dnode* dnode, struct v_file** file)
277 {
278     if (!dnode->inode || !dnode->inode->ops.open) {
279         return ENOTSUP;
280     }
281
282     struct v_file* vfile = cake_grab(file_pile);
283     memset(vfile, 0, sizeof(*vfile));
284
285     int errno = dnode->inode->ops.open(dnode->inode, vfile);
286     if (errno) {
287         cake_release(file_pile, vfile);
288     } else {
289         *file = vfile;
290     }
291     return errno;
292 }
293
294 int
295 vfs_close(struct v_file* file)
296 {
297     if (!file->ops.close) {
298         return ENOTSUP;
299     }
300
301     int errno = file->ops.close(file);
302     if (!errno) {
303         cake_release(file_pile, file);
304     }
305     return errno;
306 }
307
308 int
309 vfs_fsync(struct v_file* file)
310 {
311     int errno = ENOTSUP;
312     if (file->ops.sync) {
313         errno = file->ops.sync(file);
314     }
315     if (!errno && file->inode->ops.sync) {
316         return file->inode->ops.sync(file->inode);
317     }
318     return errno;
319 }
320
321 int
322 vfs_alloc_fdslot(int* fd)
323 {
324     for (size_t i = 0; i < VFS_MAX_FD; i++) {
325         if (!__current->fdtable->fds[i]) {
326             *fd = i;
327             return 0;
328         }
329     }
330     return EMFILE;
331 }
332
333 struct v_superblock*
334 vfs_sb_alloc()
335 {
336     struct v_superblock* sb = cake_grab(superblock_pile);
337     memset(sb, 0, sizeof(*sb));
338     llist_init_head(&sb->sb_list);
339     return sb;
340 }
341
342 void
343 vfs_sb_free(struct v_superblock* sb)
344 {
345     cake_release(superblock_pile, sb);
346 }
347
348 struct v_dnode*
349 vfs_d_alloc()
350 {
351     struct v_dnode* dnode = cake_grab(dnode_pile);
352     llist_init_head(&dnode->children);
353 }
354
355 void
356 vfs_d_free(struct v_dnode* dnode)
357 {
358     if (dnode->ops.destruct) {
359         dnode->ops.destruct(dnode);
360     }
361     cake_release(dnode_pile, dnode);
362 }
363
364 struct v_inode*
365 vfs_i_alloc()
366 {
367     struct v_inode* inode = cake_grab(inode_pile);
368     memset(inode, 0, sizeof(*inode));
369
370     return inode;
371 }
372
373 void
374 vfs_i_free(struct v_inode* inode)
375 {
376     cake_release(inode_pile, inode);
377 }
378
379 __DEFINE_LXSYSCALL2(int, open, const char*, path, int, options)
380 {
381     char name_str[VFS_NAME_MAXLEN];
382     struct hstr name = HSTR(name_str, 0);
383     struct v_dnode *dentry, *file;
384     int errno, fd;
385     if ((errno = vfs_walk(NULL, path, &dentry, &name, VFS_WALK_PARENT))) {
386         return -1;
387     }
388
389     vfs_walk(dentry, name.value, &file, NULL, 0);
390
391     struct v_file* opened_file = 0;
392     if (!file) {
393         if ((options & FO_CREATE)) {
394             errno = dentry->inode->ops.create(dentry->inode, opened_file);
395         } else {
396             errno = ENOENT;
397         }
398     } else {
399         errno = vfs_open(file, &opened_file);
400     }
401
402     __current->k_status = errno;
403
404     if (!errno && !(errno = vfs_alloc_fdslot(&fd))) {
405         struct v_fd* fd_s = vzalloc(sizeof(*fd_s));
406         fd_s->file = opened_file;
407         fd_s->pos = file->inode->fsize & -((options & FO_APPEND) != 0);
408         __current->fdtable->fds[fd] = fd_s;
409     }
410
411     return SYSCALL_ESTATUS(errno);
412 }
413
414 #define GET_FD(fd, fd_s)                                                       \
415     (fd >= 0 && fd < VFS_MAX_FD && (fd_s = __current->fdtable->fds[fd]))
416
417 __DEFINE_LXSYSCALL1(int, close, int, fd)
418 {
419     struct v_fd* fd_s;
420     int errno;
421     if (!GET_FD(fd, fd_s)) {
422         errno = EBADF;
423     } else if (!(errno = vfs_close(fd_s->file))) {
424         vfree(fd_s);
425         __current->fdtable->fds[fd] = 0;
426     }
427
428     __current->k_status = errno;
429
430     return SYSCALL_ESTATUS(errno);
431 }
432
433 void
434 __vfs_readdir_callback(struct dir_context* dctx,
435                        const char* name,
436                        const int len,
437                        const int dtype)
438 {
439     struct dirent* dent = (struct dirent*)dctx->cb_data;
440     strncpy(dent->d_name, name, DIRENT_NAME_MAX_LEN);
441     dent->d_nlen = len;
442     dent->d_type = dtype;
443 }
444
445 __DEFINE_LXSYSCALL2(int, readdir, int, fd, struct dirent*, dent)
446 {
447     struct v_fd* fd_s;
448     int errno;
449     if (!GET_FD(fd, fd_s)) {
450         errno = EBADF;
451     } else if (!(fd_s->file->inode->itype & VFS_INODE_TYPE_DIR)) {
452         errno = ENOTDIR;
453     } else {
454         struct dir_context dctx =
455           (struct dir_context){ .cb_data = dent,
456                                 .index = dent->d_offset,
457                                 .read_complete_callback =
458                                   __vfs_readdir_callback };
459         if (!(errno = fd_s->file->ops.readdir(fd_s->file, &dctx))) {
460             dent->d_offset++;
461         }
462     }
463
464     __current->k_status = errno;
465     return SYSCALL_ESTATUS(errno);
466 }
467
468 __DEFINE_LXSYSCALL1(int, mkdir, const char*, path)
469 {
470     struct v_dnode *parent, *dir;
471     struct hstr component = HSTR(valloc(VFS_NAME_MAXLEN), 0);
472     int errno = vfs_walk(NULL, path, &parent, &component, VFS_WALK_PARENT);
473     if (errno) {
474         goto done;
475     }
476
477     if (!parent->inode->ops.mkdir) {
478         errno = ENOTSUP;
479     } else if (!(parent->inode->itype & VFS_INODE_TYPE_DIR)) {
480         errno = ENOTDIR;
481     } else {
482         dir = vfs_d_alloc();
483         dir->name = component;
484         if (!(errno = parent->inode->ops.mkdir(parent->inode, dir))) {
485             llist_append(&parent->children, &dir->siblings);
486         } else {
487             vfs_d_free(dir);
488             vfree(component.value);
489         }
490     }
491
492 done:
493     __current->k_status = errno;
494     return SYSCALL_ESTATUS(errno);
495 }
496
497 __DEFINE_LXSYSCALL3(int, read, int, fd, void*, buf, size_t, count)
498 {
499     int errno = 0;
500     struct v_fd* fd_s;
501     if (!GET_FD(fd, fd_s)) {
502         errno = EBADF;
503     } else {
504         struct v_file* file = fd_s->file;
505         file->f_pos = fd_s->pos;
506         if ((errno = file->ops.read(file, buf, count)) >= 0) {
507             fd_s->pos += errno;
508         }
509     }
510
511     __current->k_status = errno;
512     return SYSCALL_ESTATUS(errno);
513 }
514
515 __DEFINE_LXSYSCALL3(int, write, int, fd, void*, buf, size_t, count)
516 {
517     int errno = 0;
518     struct v_fd* fd_s;
519     if (!GET_FD(fd, fd_s)) {
520         errno = EBADF;
521     } else {
522         struct v_file* file = fd_s->file;
523         file->f_pos = fd_s->pos;
524         if ((errno = file->ops.write(file, buf, count)) >= 0) {
525             fd_s->pos += errno;
526         }
527     }
528
529     __current->k_status = errno;
530     return SYSCALL_ESTATUS(errno);
531 }
532
533 __DEFINE_LXSYSCALL3(int, lseek, int, fd, int, offset, int, options)
534 {
535     int errno = 0;
536     struct v_fd* fd_s;
537     if (!GET_FD(fd, fd_s)) {
538         errno = EBADF;
539     } else {
540         size_t fpos = fd_s->file->f_pos;
541         switch (options) {
542             case FSEEK_CUR:
543                 fpos = (size_t)((int)fd_s->file->f_pos + offset);
544                 break;
545             case FSEEK_END:
546                 fpos = (size_t)((int)fd_s->file->inode->fsize + offset);
547                 break;
548             case FSEEK_SET:
549                 fpos = offset;
550                 break;
551
552             default:
553                 break;
554         }
555         fd_s->pos = fpos;
556     }
557
558     __current->k_status = errno;
559     return SYSCALL_ESTATUS(errno);
560 }