vbos/fs/vfs/uapi.c
Michael Shaw 171ea49050 fs: make buf on write const
Signed-off-by: Michael Shaw <m@michaelsshaw.com>
2026-07-19 20:33:52 -04:00

147 lines
2.8 KiB
C

/* SPDX-License-Identifier: GPL-2.0-only */
#include <arch/proc.h>
#include <kernel/proc.h>
#include <kernel/types.h>
#include <kernel/syscall.h>
#include <lib/errno.h>
#include <lib/string.h>
static struct file *check_fd(int fd)
{
struct proc *proc = get_cur_proc();
if (fd >= proc->fd_array_size)
return NULL;
struct file *f = proc->fdt + fd;
if (!f->dirent)
return NULL;
return f;
}
static ssize_t do_read(dirent_t *dirent, void *buf, size_t nbyte, off_t offset)
{
return vfs_read(dirent->inode, buf, nbyte, offset);
}
static ssize_t do_write(dirent_t *dirent, const void *buf, size_t nbyte, off_t offset)
{
return vfs_write(dirent->inode, buf, nbyte, offset);
}
static ssize_t sys_pread(int fd, void *buf, size_t nbyte, off_t offset)
{
struct file *f = check_fd(fd);
if (!f)
return -EBADF;
return do_read(f->dirent, buf, nbyte, offset);
}
static ssize_t sys_read(int fd, void *buf, size_t nbyte)
{
struct file *f = check_fd(fd);
if (!f)
return -EBADF;
return do_read(f->dirent, buf, nbyte, f->offset);
}
static ssize_t sys_pwrite(int fd, const void *buf, size_t nbyte, off_t offset)
{
struct file *f = check_fd(fd);
if (!f)
return -EBADF;
return do_write(f->dirent, buf, nbyte, offset);
}
static ssize_t sys_write(int fd, const void *buf, size_t nbyte)
{
struct file *f = check_fd(fd);
if (!f)
return -EBADF;
return do_write(f->dirent, buf, nbyte, f->offset);
}
static int sys_open(const char *path, int flags)
{
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)
{
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()
{
syscall_insert(sys_pread, SYS_pread);
syscall_insert(sys_read, SYS_read);
syscall_insert(sys_pwrite, SYS_pwrite);
syscall_insert(sys_write, SYS_write);
syscall_insert(sys_open, SYS_open);
syscall_insert(sys_close, SYS_close);
}