diff --git a/fs/vfs/uapi.c b/fs/vfs/uapi.c index b26bb25..8b400c1 100644 --- a/fs/vfs/uapi.c +++ b/fs/vfs/uapi.c @@ -1,7 +1,10 @@ /* SPDX-License-Identifier: GPL-2.0-only */ +#include +#include #include #include #include +#include static ssize_t sys_pread(int fd, void *buf, size_t nbyte, off_t offset) { @@ -25,12 +28,72 @@ static ssize_t sys_write(int fd, const void *buf, size_t nbyte) static int sys_open(const char *path, int flags) { - return -ENOSYS; + struct proc *proc = get_cur_proc(); + + dirent_t *f; + int res = vfs_open(path, &f); + + if (res < 0) + return res; + + spinlock_acquire(&proc->fd_lock); + + int fdno = -1; + + for (int i = 0; i < proc->fd_array_size; i++) { + struct file *fd = proc->fdt + i; + if (!fd->dirent) { + memset(fd, 0, sizeof(struct file)); + fd->dirent = f; + fd->flags = flags; + fd->refcount = 1; + fdno = i; + } + } + + if (fdno == -1) { + size_t osize = proc->fd_array_size; + size_t newsize = MIN(osize * 2, 32); + void *new = krealloc(proc->fdt, newsize, ALLOC_KERN); + if (!new) { + vfs_close(f); + return -ENOMEM; + } + + proc->fdt = new; + + memset(proc->fdt + osize, 0, osize); + struct file *fd = proc->fdt + osize; + fd->dirent = f; + fd->flags = flags; + fd->refcount = 1; + fdno = osize; + } + + spinlock_release(&proc->fd_lock); + + return fdno; } static int sys_close(int fd) { - return -ENOSYS; + struct proc *proc = get_cur_proc(); + + if (fd >= proc->fd_array_size) + return -EBADF; + + struct file *f = proc->fdt + fd; + if (!f->dirent) + return -EBADF; + + spinlock_acquire(&proc->fd_lock); + + vfs_close(f->dirent); + memset(f, 0, sizeof(struct file)); + + spinlock_acquire(&proc->fd_lock); + + return 0; } void vfs_uapi_init() diff --git a/include/kernel/proc.h b/include/kernel/proc.h index eae39cb..b1d1eed 100644 --- a/include/kernel/proc.h +++ b/include/kernel/proc.h @@ -6,6 +6,7 @@ #include #include #include +#include #include @@ -29,6 +30,14 @@ struct proc_alloc { size_t len; }; +struct file { + dirent_t *dirent; + u64 flags; + u64 offset; + u64 refcount; + spinlock_t lock; +}; + struct proc; struct thread { tid_t tid; @@ -62,6 +71,10 @@ struct proc { uaddr_t entry; + spinlock_t fd_lock; + size_t fd_array_size; + struct file *fdt; + struct ehdr *ehdr; struct phdr *phdrs; size_t n_phdrs;