refactor: kernel space yield() for controllable, flexible task switching
[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 struct hstr vfs_empty = HSTR("", 0);
43
44 struct v_dnode*
45 vfs_d_alloc();
46
47 void
48 vfs_d_free(struct v_dnode* dnode);
49
50 struct v_superblock*
51 vfs_sb_alloc();
52
53 void
54 vfs_sb_free(struct v_superblock* sb);
55
56 void
57 vfs_init()
58 {
59     // 为他们专门创建一个蛋糕堆,而不使用valloc,这样我们可以最小化内碎片的产生
60     dnode_pile = cake_new_pile("dnode_cache", sizeof(struct v_dnode), 1, 0);
61     inode_pile = cake_new_pile("inode_cache", sizeof(struct v_inode), 1, 0);
62     file_pile = cake_new_pile("file_cache", sizeof(struct v_file), 1, 0);
63     fd_pile = cake_new_pile("fd_cache", sizeof(struct v_fd), 1, 0);
64     superblock_pile =
65       cake_new_pile("sb_cache", sizeof(struct v_superblock), 1, 0);
66
67     dnode_cache = vzalloc(DNODE_HASHTABLE_SIZE * sizeof(struct hbucket));
68
69     hstr_rehash(&vfs_ddot, HSTR_FULL_HASH);
70     hstr_rehash(&vfs_dot, HSTR_FULL_HASH);
71
72     // 创建一个根superblock,用来蕴含我们的根目录。
73     root_sb = vfs_sb_alloc();
74     root_sb->root = vfs_d_alloc();
75     root_sb->root->inode = vfs_i_alloc();
76 }
77
78 inline struct hbucket*
79 __dcache_get_bucket(struct v_dnode* parent, unsigned int hash)
80 {
81     // 与parent的指针值做加法,来减小碰撞的可能性。
82     hash += (uint32_t)parent;
83     // 确保低位更加随机
84     hash = hash ^ (hash >> DNODE_HASHBITS);
85     return &dnode_cache[hash & DNODE_HASH_MASK];
86 }
87
88 struct v_dnode*
89 vfs_dcache_lookup(struct v_dnode* parent, struct hstr* str)
90 {
91     if (!str->len || HSTR_EQ(str, &vfs_dot))
92         return parent;
93
94     if (HSTR_EQ(str, &vfs_ddot)) {
95         return parent->parent ? parent->parent : parent;
96     }
97
98     struct hbucket* slot = __dcache_get_bucket(parent, str->hash);
99
100     struct v_dnode *pos, *n;
101     hashtable_bucket_foreach(slot, pos, n, hash_list)
102     {
103         if (pos->name.hash == str->hash) {
104             return pos;
105         }
106     }
107     return NULL;
108 }
109
110 void
111 vfs_dcache_add(struct v_dnode* parent, struct v_dnode* dnode)
112 {
113     struct hbucket* bucket = __dcache_get_bucket(parent, dnode->name.hash);
114     hlist_add(&bucket->head, &dnode->hash_list);
115 }
116
117 int
118 __vfs_walk(struct v_dnode* start,
119            const char* path,
120            struct v_dnode** dentry,
121            struct hstr* component,
122            int walk_options)
123 {
124     int errno = 0;
125     int i = 0, j = 0;
126
127     if (path[0] == PATH_DELIM || !start) {
128         if ((walk_options & VFS_WALK_FSRELATIVE) && start) {
129             start = start->super_block->root;
130         } else {
131             start = root_sb->root;
132         }
133         i++;
134     }
135
136     struct v_dnode* dnode;
137     struct v_dnode* current_level = start;
138
139     char name_content[VFS_NAME_MAXLEN];
140     struct hstr name = HSTR(name_content, 0);
141
142     char current = path[i++], lookahead;
143     while (current) {
144         lookahead = path[i++];
145         if (current != PATH_DELIM) {
146             if (j >= VFS_NAME_MAXLEN - 1) {
147                 return ENAMETOOLONG;
148             }
149             if (!VFS_VALID_CHAR(current)) {
150                 return EINVAL;
151             }
152             name_content[j++] = current;
153             if (lookahead) {
154                 goto cont;
155             }
156         }
157
158         // handling cases like /^.*(\/+).*$/
159         if (lookahead == PATH_DELIM) {
160             goto cont;
161         }
162
163         name_content[j] = 0;
164         name.len = j;
165         hstr_rehash(&name, HSTR_FULL_HASH);
166
167         if (!lookahead && (walk_options & VFS_WALK_PARENT)) {
168             if (component) {
169                 component->hash = name.hash;
170                 component->len = j;
171                 strcpy(component->value, name_content);
172             }
173             break;
174         }
175
176         dnode = vfs_dcache_lookup(current_level, &name);
177
178         if (!dnode) {
179             dnode = vfs_d_alloc();
180             dnode->name = HHSTR(valloc(VFS_NAME_MAXLEN), j, name.hash);
181
182             strcpy(dnode->name.value, name_content);
183
184             errno =
185               current_level->inode->ops.dir_lookup(current_level->inode, dnode);
186
187             if (errno == ENOENT && (walk_options & VFS_WALK_MKPARENT)) {
188                 if (!current_level->inode->ops.mkdir) {
189                     errno = ENOTSUP;
190                 } else {
191                     errno = current_level->inode->ops.mkdir(
192                       current_level->inode, dnode);
193                 }
194             }
195
196             if (errno) {
197                 goto error;
198             }
199
200             vfs_dcache_add(current_level, dnode);
201
202             dnode->parent = current_level;
203             llist_append(&current_level->children, &dnode->siblings);
204         }
205
206         j = 0;
207         current_level = dnode;
208     cont:
209         current = lookahead;
210     };
211
212     *dentry = current_level;
213     return 0;
214
215 error:
216     vfree(dnode->name.value);
217     vfs_d_free(dnode);
218     *dentry = NULL;
219     return errno;
220 }
221
222 #define VFS_MAX_SYMLINK 16
223
224 int
225 vfs_walk(struct v_dnode* start,
226          const char* path,
227          struct v_dnode** dentry,
228          struct hstr* component,
229          int options)
230 {
231     struct v_dnode* interim;
232     char* pathname = path;
233     int errno = __vfs_walk(start, path, &interim, component, options);
234     int counter = 0;
235
236     while (!errno) {
237         if (counter >= VFS_MAX_SYMLINK) {
238             errno = ELOOP;
239             continue;
240         }
241         if ((interim->inode->itype & VFS_IFSYMLINK) &&
242             !(options & VFS_WALK_NOFOLLOW) &&
243             interim->inode->ops.read_symlink) {
244             errno = interim->inode->ops.read_symlink(interim->inode, &pathname);
245             if (errno) {
246                 break;
247             }
248         } else {
249             break;
250         }
251         errno = __vfs_walk(start, pathname, &interim, component, options);
252         counter++;
253     }
254
255     *dentry = errno ? 0 : interim;
256
257     return errno;
258 }
259
260 int
261 vfs_mount(const char* target, const char* fs_name, bdev_t device)
262 {
263     int errno;
264     struct v_dnode* mnt;
265
266     if (!(errno = vfs_walk(__current->cwd, target, &mnt, NULL, 0))) {
267         errno = vfs_mount_at(fs_name, device, mnt);
268     }
269
270     return errno;
271 }
272
273 int
274 vfs_unmount(const char* target)
275 {
276     int errno;
277     struct v_dnode* mnt;
278
279     if (!(errno = vfs_walk(__current->cwd, target, &mnt, NULL, 0))) {
280         errno = vfs_unmount_at(mnt);
281     }
282
283     return errno;
284 }
285
286 int
287 vfs_mount_at(const char* fs_name, bdev_t device, struct v_dnode* mnt_point)
288 {
289     struct filesystem* fs = fsm_get(fs_name);
290     if (!fs)
291         return ENODEV;
292     struct v_superblock* sb = vfs_sb_alloc();
293     sb->dev = device;
294     sb->fs_id = fs_id++;
295
296     int errno = 0;
297     if (!(errno = fs->mount(sb, mnt_point))) {
298         sb->fs = fs;
299         sb->root = mnt_point;
300         mnt_point->super_block = sb;
301         llist_append(&root_sb->sb_list, &sb->sb_list);
302     }
303
304     return errno;
305 }
306
307 int
308 vfs_unmount_at(struct v_dnode* mnt_point)
309 {
310     int errno = 0;
311     struct v_superblock* sb = mnt_point->super_block;
312     if (!sb) {
313         return EINVAL;
314     }
315     if (!(errno = sb->fs->unmount(sb))) {
316         struct v_dnode* fs_root = sb->root;
317         llist_delete(&fs_root->siblings);
318         llist_delete(&sb->sb_list);
319         vfs_sb_free(sb);
320     }
321     return errno;
322 }
323
324 int
325 vfs_open(struct v_dnode* dnode, struct v_file** file)
326 {
327     if (!dnode->inode || !dnode->inode->ops.open) {
328         return ENOTSUP;
329     }
330
331     struct v_inode* inode = dnode->inode;
332     struct v_file* vfile = cake_grab(file_pile);
333     memset(vfile, 0, sizeof(*vfile));
334
335     vfile->dnode = dnode;
336     vfile->inode = inode;
337     vfile->ref_count = 1;
338     vfile->ops = inode->default_fops;
339
340     if ((inode->itype & VFS_IFFILE) && !inode->pg_cache) {
341         struct pcache* pcache = vzalloc(sizeof(struct pcache));
342         pcache_init(pcache);
343         inode->pg_cache = pcache;
344     }
345
346     int errno = inode->ops.open(inode, vfile);
347     if (errno) {
348         cake_release(file_pile, vfile);
349     } else {
350         dnode->ref_count++;
351         inode->open_count++;
352         *file = vfile;
353     }
354
355     return errno;
356 }
357
358 int
359 vfs_link(struct v_dnode* to_link, struct v_dnode* name)
360 {
361     int errno;
362     if (to_link->super_block->root != name->super_block->root) {
363         errno = EXDEV;
364     } else if (!to_link->inode->ops.link) {
365         errno = ENOTSUP;
366     } else if (!(errno = to_link->inode->ops.link(to_link->inode, name))) {
367         name->inode = to_link->inode;
368         to_link->inode->link_count++;
369     }
370
371     return errno;
372 }
373
374 int
375 vfs_close(struct v_file* file)
376 {
377     int errno = 0;
378     if (!file->ops.close || !(errno = file->ops.close(file))) {
379         file->dnode->ref_count--;
380         file->inode->open_count--;
381         pcache_commit_all(file);
382         cake_release(file_pile, file);
383     }
384     return errno;
385 }
386
387 int
388 vfs_fsync(struct v_file* file)
389 {
390     int errno = ENOTSUP;
391     pcache_commit_all(file);
392     if (file->ops.sync) {
393         errno = file->ops.sync(file);
394     }
395     if (!errno && file->inode->ops.sync) {
396         return file->inode->ops.sync(file->inode);
397     }
398     return errno;
399 }
400
401 int
402 vfs_alloc_fdslot(int* fd)
403 {
404     for (size_t i = 0; i < VFS_MAX_FD; i++) {
405         if (!__current->fdtable->fds[i]) {
406             *fd = i;
407             return 0;
408         }
409     }
410     return EMFILE;
411 }
412
413 struct v_superblock*
414 vfs_sb_alloc()
415 {
416     struct v_superblock* sb = cake_grab(superblock_pile);
417     memset(sb, 0, sizeof(*sb));
418     llist_init_head(&sb->sb_list);
419     return sb;
420 }
421
422 void
423 vfs_sb_free(struct v_superblock* sb)
424 {
425     cake_release(superblock_pile, sb);
426 }
427
428 struct v_dnode*
429 vfs_d_alloc()
430 {
431     struct v_dnode* dnode = cake_grab(dnode_pile);
432     memset(dnode, 0, sizeof(*dnode));
433     llist_init_head(&dnode->children);
434     dnode->name = vfs_empty;
435     return dnode;
436 }
437
438 void
439 vfs_d_free(struct v_dnode* dnode)
440 {
441     if (dnode->ops.destruct) {
442         dnode->ops.destruct(dnode);
443     }
444     cake_release(dnode_pile, dnode);
445 }
446
447 struct v_inode*
448 vfs_i_alloc()
449 {
450     struct v_inode* inode = cake_grab(inode_pile);
451     memset(inode, 0, sizeof(*inode));
452     return inode;
453 }
454
455 void
456 vfs_i_free(struct v_inode* inode)
457 {
458     cake_release(inode_pile, inode);
459 }
460
461 /* ---- System call definition and support ---- */
462
463 #define FLOCATE_CREATE_EMPTY 1
464
465 #define DO_STATUS(errno) SYSCALL_ESTATUS(__current->k_status = errno)
466 #define DO_STATUS_OR_RETURN(errno) ({ errno < 0 ? DO_STATUS(errno) : errno; })
467
468 #define TEST_FD(fd) (fd >= 0 && fd < VFS_MAX_FD)
469
470 int
471 __vfs_getfd(int fd, struct v_fd** fd_s)
472 {
473     if (TEST_FD(fd) && (*fd_s = __current->fdtable->fds[fd])) {
474         return 0;
475     }
476     return EBADF;
477 }
478
479 int
480 __vfs_try_locate_file(const char* path,
481                       struct v_dnode** fdir,
482                       struct v_dnode** file,
483                       int options)
484 {
485     char name_str[VFS_NAME_MAXLEN];
486     struct hstr name = HSTR(name_str, 0);
487     int errno;
488     if ((errno =
489            vfs_walk(__current->cwd, path, fdir, &name, VFS_WALK_PARENT))) {
490         return errno;
491     }
492
493     errno = vfs_walk(*fdir, name.value, file, NULL, 0);
494     if (errno != ENOENT || !(options & FLOCATE_CREATE_EMPTY)) {
495         return errno;
496     }
497
498     if (!(errno = (*fdir)->inode->ops.create((*fdir)->inode))) {
499         struct v_dnode* file_new;
500         file_new = vfs_d_alloc();
501         file_new->name = HHSTR(valloc(VFS_NAME_MAXLEN), name.len, name.hash);
502         strcpy(file_new->name.value, name_str);
503         *file = file_new;
504
505         llist_append(&(*fdir)->children, &file_new->siblings);
506     }
507
508     return errno;
509 }
510
511 int
512 vfs_do_open(const char* path, int options)
513 {
514     int errno, fd;
515     struct v_dnode *dentry, *file;
516     struct v_file* ofile = 0;
517
518     errno = __vfs_try_locate_file(path, &dentry, &file, 0);
519
520     if (errno != ENOENT && (options & FO_CREATE)) {
521         errno = dentry->inode->ops.create(dentry->inode);
522     }
523
524     if (!errno && (errno = vfs_open(file, &ofile))) {
525         return errno;
526     }
527
528     struct v_inode* o_inode = ofile->inode;
529     if (!(o_inode->itype & VFS_IFSEQDEV) && !(options & FO_DIRECT)) {
530         // XXX Change here accordingly when signature of pcache_r/w changed.
531         ofile->ops.read = pcache_read;
532         ofile->ops.write = pcache_write;
533     }
534
535     if (!errno && !(errno = vfs_alloc_fdslot(&fd))) {
536         struct v_fd* fd_s = vzalloc(sizeof(*fd_s));
537         ofile->f_pos = ofile->inode->fsize & -((options & FO_APPEND) != 0);
538         fd_s->file = ofile;
539         fd_s->flags = options;
540         __current->fdtable->fds[fd] = fd_s;
541         return fd;
542     }
543
544     return errno;
545 }
546
547 __DEFINE_LXSYSCALL2(int, open, const char*, path, int, options)
548 {
549     int errno = vfs_do_open(path, options);
550     return DO_STATUS_OR_RETURN(errno);
551 }
552
553 __DEFINE_LXSYSCALL1(int, close, int, fd)
554 {
555     struct v_fd* fd_s;
556     int errno = 0;
557     if ((errno = __vfs_getfd(fd, &fd_s))) {
558         goto done_err;
559     }
560
561     if (fd_s->file->ref_count > 1) {
562         fd_s->file->ref_count--;
563     } else if ((errno = vfs_close(fd_s->file))) {
564         goto done_err;
565     }
566
567     vfree(fd_s);
568     __current->fdtable->fds[fd] = 0;
569
570 done_err:
571     return DO_STATUS(errno);
572 }
573
574 void
575 __vfs_readdir_callback(struct dir_context* dctx,
576                        const char* name,
577                        const int len,
578                        const int dtype)
579 {
580     struct dirent* dent = (struct dirent*)dctx->cb_data;
581     strncpy(dent->d_name, name, DIRENT_NAME_MAX_LEN);
582     dent->d_nlen = len;
583     dent->d_type = dtype;
584 }
585
586 __DEFINE_LXSYSCALL2(int, readdir, int, fd, struct dirent*, dent)
587 {
588     struct v_fd* fd_s;
589     int errno;
590
591     if ((errno = __vfs_getfd(fd, &fd_s))) {
592         goto done;
593     }
594
595     if (!(fd_s->file->inode->itype & VFS_IFDIR)) {
596         errno = ENOTDIR;
597     } else {
598         struct dir_context dctx =
599           (struct dir_context){ .cb_data = dent,
600                                 .index = dent->d_offset,
601                                 .read_complete_callback =
602                                   __vfs_readdir_callback };
603         if (dent->d_offset == 0) {
604             __vfs_readdir_callback(&dctx, vfs_dot.value, vfs_dot.len, 0);
605         } else if (dent->d_offset == 1) {
606             __vfs_readdir_callback(&dctx, vfs_ddot.value, vfs_ddot.len, 0);
607         } else {
608             dctx.index -= 2;
609             if ((errno = fd_s->file->ops.readdir(fd_s->file, &dctx))) {
610                 goto done;
611             }
612         }
613         errno = 0;
614         dent->d_offset++;
615     }
616
617 done:
618     return DO_STATUS(errno);
619 }
620
621 __DEFINE_LXSYSCALL1(int, mkdir, const char*, path)
622 {
623     struct v_dnode *parent, *dir;
624     struct hstr component = HSTR(valloc(VFS_NAME_MAXLEN), 0);
625     int errno =
626       vfs_walk(__current->cwd, path, &parent, &component, VFS_WALK_PARENT);
627     if (errno) {
628         goto done;
629     }
630
631     if ((parent->super_block->fs->types & FSTYPE_ROFS)) {
632         errno = ENOTSUP;
633     } else if (!parent->inode->ops.mkdir) {
634         errno = ENOTSUP;
635     } else if (!(parent->inode->itype & VFS_IFDIR)) {
636         errno = ENOTDIR;
637     } else {
638         dir = vfs_d_alloc();
639         dir->name = component;
640         if (!(errno = parent->inode->ops.mkdir(parent->inode, dir))) {
641             llist_append(&parent->children, &dir->siblings);
642         } else {
643             vfs_d_free(dir);
644             vfree(component.value);
645         }
646     }
647
648 done:
649     return DO_STATUS(errno);
650 }
651
652 __DEFINE_LXSYSCALL3(int, read, int, fd, void*, buf, size_t, count)
653 {
654     int errno = 0;
655     struct v_fd* fd_s;
656     if ((errno = __vfs_getfd(fd, &fd_s))) {
657         goto done;
658     }
659
660     struct v_file* file = fd_s->file;
661     if ((file->inode->itype & VFS_IFDIR)) {
662         errno = EISDIR;
663         goto done;
664     }
665
666     __SYSCALL_INTERRUPTIBLE(
667       { errno = file->ops.read(file, buf, count, file->f_pos); })
668
669     if (errno > 0) {
670         file->f_pos += errno;
671         return errno;
672     }
673
674 done:
675     return DO_STATUS(errno);
676 }
677
678 __DEFINE_LXSYSCALL3(int, write, int, fd, void*, buf, size_t, count)
679 {
680     int errno = 0;
681     struct v_fd* fd_s;
682     if ((errno = __vfs_getfd(fd, &fd_s))) {
683         goto done;
684     }
685
686     struct v_file* file = fd_s->file;
687     if ((file->inode->itype & VFS_IFDIR)) {
688         errno = EISDIR;
689         goto done;
690     }
691
692     __SYSCALL_INTERRUPTIBLE(
693       { errno = file->ops.write(file, buf, count, file->f_pos); })
694
695     if (errno > 0) {
696         file->f_pos += errno;
697         return errno;
698     }
699
700 done:
701     return DO_STATUS(errno);
702 }
703
704 __DEFINE_LXSYSCALL3(int, lseek, int, fd, int, offset, int, options)
705 {
706     int errno = 0;
707     struct v_fd* fd_s;
708     if ((errno = __vfs_getfd(fd, &fd_s))) {
709         goto done;
710     }
711
712     struct v_file* file = fd_s->file;
713     size_t fpos = file->f_pos;
714     switch (options) {
715         case FSEEK_CUR:
716             fpos = (size_t)((int)file->f_pos + offset);
717             break;
718         case FSEEK_END:
719             fpos = (size_t)((int)file->inode->fsize + offset);
720             break;
721         case FSEEK_SET:
722             fpos = offset;
723             break;
724     }
725     if (!file->ops.seek || !(errno = file->ops.seek(file, fpos))) {
726         file->f_pos = fpos;
727     }
728
729 done:
730     return DO_STATUS(errno);
731 }
732
733 int
734 vfs_get_path(struct v_dnode* dnode, char* buf, size_t size, int depth)
735 {
736     if (!dnode) {
737         return 0;
738     }
739
740     if (depth > 64) {
741         return ELOOP;
742     }
743
744     size_t len = vfs_get_path(dnode->parent, buf, size, depth + 1);
745
746     if (len >= size) {
747         return len;
748     }
749
750     size_t cpy_size = MIN(dnode->name.len, size - len);
751     strncpy(buf + len, dnode->name.value, cpy_size);
752     len += cpy_size;
753
754     if (len < size) {
755         buf[len++] = PATH_DELIM;
756     }
757
758     return len;
759 }
760
761 int
762 vfs_readlink(struct v_dnode* dnode, char* buf, size_t size)
763 {
764     char* link;
765     if (dnode->inode->ops.read_symlink) {
766         int errno = dnode->inode->ops.read_symlink(dnode->inode, &link);
767         strncpy(buf, link, size);
768         return errno;
769     }
770     return 0;
771 }
772
773 __DEFINE_LXSYSCALL3(int, realpathat, int, fd, char*, buf, size_t, size)
774 {
775     int errno;
776     struct v_fd* fd_s;
777     if ((errno = __vfs_getfd(fd, &fd_s))) {
778         goto done;
779     }
780
781     struct v_dnode* dnode;
782     errno = vfs_get_path(fd_s->file->dnode, buf, size, 0);
783
784     if (errno >= 0) {
785         return errno;
786     }
787
788 done:
789     return DO_STATUS(errno);
790 }
791
792 __DEFINE_LXSYSCALL3(int, readlink, const char*, path, char*, buf, size_t, size)
793 {
794     int errno;
795     struct v_dnode* dnode;
796     if (!(errno =
797             vfs_walk(__current->cwd, path, &dnode, NULL, VFS_WALK_NOFOLLOW))) {
798         errno = vfs_readlink(dnode, buf, size);
799     }
800
801     if (errno >= 0) {
802         return errno;
803     }
804
805     return DO_STATUS(errno);
806 }
807
808 __DEFINE_LXSYSCALL4(int,
809                     readlinkat,
810                     int,
811                     dirfd,
812                     const char*,
813                     pathname,
814                     char*,
815                     buf,
816                     size_t,
817                     size)
818 {
819     int errno;
820     struct v_fd* fd_s;
821     if ((errno = __vfs_getfd(dirfd, &fd_s))) {
822         goto done;
823     }
824
825     struct v_dnode* dnode;
826     if (!(errno = vfs_walk(
827             fd_s->file->dnode, pathname, &dnode, NULL, VFS_WALK_NOFOLLOW))) {
828         errno = vfs_readlink(fd_s->file->dnode, buf, size);
829     }
830
831     if (errno >= 0) {
832         return errno;
833     }
834
835 done:
836     return DO_STATUS(errno);
837 }
838
839 __DEFINE_LXSYSCALL1(int, rmdir, const char*, pathname)
840 {
841     int errno;
842     struct v_dnode* dnode;
843     if ((errno = vfs_walk(__current->cwd, pathname, &dnode, NULL, 0))) {
844         goto done;
845     }
846     if ((dnode->super_block->fs->types & FSTYPE_ROFS)) {
847         errno = EROFS;
848         goto done;
849     }
850
851     if (dnode->inode->open_count) {
852         errno = EBUSY;
853         goto done;
854     }
855
856     if ((dnode->inode->itype & VFS_IFDIR)) {
857         errno = dnode->inode->ops.rmdir(dnode->inode);
858     } else {
859         errno = ENOTDIR;
860     }
861
862 done:
863     return DO_STATUS(errno);
864 }
865
866 int
867 __vfs_do_unlink(struct v_inode* inode)
868 {
869     int errno;
870     if (inode->open_count) {
871         errno = EBUSY;
872     } else if (!(inode->itype & VFS_IFDIR)) {
873         // TODO handle symbolic link and type other than regular file
874         errno = inode->ops.unlink(inode);
875         if (!errno) {
876             inode->link_count--;
877         }
878     } else {
879         errno = EISDIR;
880     }
881
882     return errno;
883 }
884
885 __DEFINE_LXSYSCALL1(int, unlink, const char*, pathname)
886 {
887     int errno;
888     struct v_dnode* dnode;
889     if ((errno = vfs_walk(__current->cwd, pathname, &dnode, NULL, 0))) {
890         goto done;
891     }
892     if ((dnode->super_block->fs->types & FSTYPE_ROFS)) {
893         errno = EROFS;
894         goto done;
895     }
896
897     errno = __vfs_do_unlink(dnode->inode);
898
899 done:
900     return DO_STATUS(errno);
901 }
902
903 __DEFINE_LXSYSCALL2(int, unlinkat, int, fd, const char*, pathname)
904 {
905     int errno;
906     struct v_fd* fd_s;
907     if ((errno = __vfs_getfd(fd, &fd_s))) {
908         goto done;
909     }
910
911     struct v_dnode* dnode;
912     if (!(errno = vfs_walk(fd_s->file->dnode, pathname, &dnode, NULL, 0))) {
913         errno = __vfs_do_unlink(dnode->inode);
914     }
915
916 done:
917     return DO_STATUS(errno);
918 }
919
920 __DEFINE_LXSYSCALL2(int, link, const char*, oldpath, const char*, newpath)
921 {
922     int errno;
923     struct v_dnode *dentry, *to_link, *name_dentry, *name_file;
924
925     errno = __vfs_try_locate_file(oldpath, &dentry, &to_link, 0);
926     if (!errno) {
927         errno = __vfs_try_locate_file(
928           newpath, &name_dentry, &name_file, FLOCATE_CREATE_EMPTY);
929         if (!errno) {
930             errno = EEXIST;
931         } else if (name_file) {
932             errno = vfs_link(to_link, name_file);
933         }
934     }
935     return DO_STATUS(errno);
936 }
937
938 __DEFINE_LXSYSCALL1(int, fsync, int, fildes)
939 {
940     int errno;
941     struct v_fd* fd_s;
942     if (!(errno = __vfs_getfd(fildes, &fd_s))) {
943         errno = vfs_fsync(fd_s->file);
944     }
945
946     return DO_STATUS(errno);
947 }
948
949 int
950 vfs_dup_fd(struct v_fd* old, struct v_fd** new)
951 {
952     int errno = 0;
953     struct v_fd* copied = cake_grab(fd_pile);
954
955     memcpy(copied, old, sizeof(struct v_fd));
956     old->file->ref_count++;
957
958     *new = copied;
959
960     return errno;
961 }
962
963 int
964 vfs_dup2(int oldfd, int newfd)
965 {
966     if (newfd == oldfd) {
967         return newfd;
968     }
969
970     int errno;
971     struct v_fd *oldfd_s, *newfd_s;
972     if ((errno = __vfs_getfd(oldfd, &oldfd_s))) {
973         goto done;
974     }
975
976     if (!TEST_FD(newfd)) {
977         errno = EBADF;
978         goto done;
979     }
980
981     newfd_s = __current->fdtable->fds[newfd];
982     if (newfd_s && (errno = vfs_close(newfd_s))) {
983         goto done;
984     }
985
986     if (!(errno = vfs_dup_fd(oldfd_s, &newfd_s))) {
987         __current->fdtable->fds[newfd] = newfd_s;
988         return newfd;
989     }
990
991 done:
992     return DO_STATUS(errno);
993 }
994
995 __DEFINE_LXSYSCALL2(int, dup2, int, oldfd, int, newfd)
996 {
997     return vfs_dup2(oldfd, newfd);
998 }
999
1000 __DEFINE_LXSYSCALL1(int, dup, int, oldfd)
1001 {
1002     int errno, newfd;
1003     struct v_fd *oldfd_s, *newfd_s;
1004     if ((errno = __vfs_getfd(oldfd, &oldfd_s))) {
1005         goto done;
1006     }
1007
1008     if (!(errno = vfs_alloc_fdslot(&newfd)) &&
1009         !(errno = vfs_dup_fd(oldfd_s, &newfd_s))) {
1010         __current->fdtable->fds[newfd] = newfd_s;
1011         return newfd;
1012     }
1013
1014 done:
1015     return DO_STATUS(errno);
1016 }
1017
1018 __DEFINE_LXSYSCALL2(int,
1019                     symlink,
1020                     const char*,
1021                     pathname,
1022                     const char*,
1023                     link_target)
1024 {
1025     int errno;
1026     struct v_dnode* dnode;
1027     if ((errno = vfs_walk(__current->cwd, pathname, &dnode, NULL, 0))) {
1028         goto done;
1029     }
1030     if ((dnode->super_block->fs->types & FSTYPE_ROFS)) {
1031         errno = EROFS;
1032         goto done;
1033     }
1034     if (!dnode->inode->ops.symlink) {
1035         errno = ENOTSUP;
1036         goto done;
1037     }
1038
1039     errno = dnode->inode->ops.symlink(dnode->inode, link_target);
1040
1041 done:
1042     return DO_STATUS(errno);
1043 }
1044
1045 int
1046 __vfs_do_chdir(struct v_dnode* dnode)
1047 {
1048     int errno = 0;
1049     if (!(dnode->inode->itype & VFS_IFDIR)) {
1050         errno = ENOTDIR;
1051         goto done;
1052     }
1053
1054     if (__current->cwd) {
1055         __current->cwd->ref_count--;
1056     }
1057
1058     dnode->ref_count++;
1059     __current->cwd = dnode;
1060
1061 done:
1062     return errno;
1063 }
1064
1065 __DEFINE_LXSYSCALL1(int, chdir, const char*, path)
1066 {
1067     struct v_dnode* dnode;
1068     int errno = 0;
1069
1070     if ((errno = vfs_walk(__current->cwd, path, &dnode, NULL, 0))) {
1071         goto done;
1072     }
1073
1074     errno = __vfs_do_chdir(dnode);
1075
1076 done:
1077     return DO_STATUS(errno);
1078 }
1079
1080 __DEFINE_LXSYSCALL1(int, fchdir, int, fd)
1081 {
1082     struct v_fd* fd_s;
1083     int errno = 0;
1084
1085     if ((errno = __vfs_getfd(fd, &fd_s))) {
1086         goto done;
1087     }
1088
1089     errno = __vfs_do_chdir(fd_s->file->dnode);
1090
1091 done:
1092     return DO_STATUS(errno);
1093 }
1094
1095 __DEFINE_LXSYSCALL2(char*, getcwd, char*, buf, size_t, size)
1096 {
1097     int errno = 0;
1098     char* ret_ptr = 0;
1099     if (size < 2) {
1100         errno = ERANGE;
1101         goto done;
1102     }
1103
1104     size_t len = 0;
1105
1106     if (!__current->cwd) {
1107         *buf = PATH_DELIM;
1108         len = 1;
1109     } else {
1110         len = vfs_get_path(__current->cwd, buf, size, 0);
1111         if (len == size) {
1112             errno = ERANGE;
1113             goto done;
1114         }
1115     }
1116
1117     buf[len + 1] = '\0';
1118
1119     ret_ptr = buf;
1120
1121 done:
1122     __current->k_status = errno;
1123     return ret_ptr;
1124 }