Files
my-os-project2/kernel/fs/kvfs/kvfs.c
2025-08-16 20:35:00 +02:00

108 lines
2.6 KiB
C

#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include "spinlock/spinlock.h"
#include "errors.h"
#include "hal/hal.h"
#include "hshtb.h"
#include "kprintf.h"
#include "vfs/vfs.h"
#include "dlmalloc/malloc.h"
#include "util/util.h"
int32_t kvfs_read(struct VfsMountPoint *vmp, const char *key, uint8_t *const buffer, size_t n, size_t off) {
KvfsNode *node = NULL;
spinlock_acquire(&vmp->spinlock);
HSHTB_GET(&vmp->fs.kvfs, nodes, (char *)key, key_, node);
spinlock_release(&vmp->spinlock);
if (node == NULL) {
return E_NOENTRY;
}
spinlock_acquire(&node->spinlock);
vmp->backingsd->read(vmp->backingsd, buffer, n, off);
spinlock_release(&node->spinlock);
return E_OK;
}
int32_t kvfs_write(struct VfsMountPoint *vmp, const char *key, const uint8_t *const buffer, size_t n, size_t off) {
KvfsNode *node = NULL;
spinlock_acquire(&vmp->spinlock);
HSHTB_GET(&vmp->fs.kvfs, nodes, (char *)key, key_, node);
spinlock_release(&vmp->spinlock);
if (node == NULL) {
return E_NOENTRY;
}
spinlock_acquire(&node->spinlock);
vmp->backingsd->write(vmp->backingsd, buffer, n, off);
spinlock_release(&node->spinlock);
return E_OK;
}
int32_t kvfs_remove(struct VfsMountPoint *vmp, const char *key) {
KvfsNode *node = NULL;
spinlock_acquire(&vmp->spinlock);
HSHTB_GET(&vmp->fs.kvfs, nodes, (char *)key, key_, node);
spinlock_release(&vmp->spinlock);
if (node == NULL) {
return E_NOENTRY;
}
spinlock_acquire(&node->spinlock);
hal_memset(node, 0, sizeof(*node));
spinlock_release(&node->spinlock);
return E_OK;
}
int32_t kvfs_cleanup(struct VfsMountPoint *vmp) {
int32_t err = vmp->backingsd->cleanup(vmp->backingsd);
if (err != E_OK) {
return err;
}
return E_OK;
}
int32_t kvfs_create(struct VfsMountPoint *vmp, const char *path, int32_t type) {
(void)type;
KvfsNode *node = NULL;
spinlock_acquire(&vmp->spinlock);
HSHTB_ALLOC(&vmp->fs.kvfs, nodes, (char *)path, key_, node);
spinlock_release(&vmp->spinlock);
if (node == NULL) {
return E_NOMEMORY;
}
return E_OK;
}
bool kvfs_check(void) {
int32_t ret;
ret = vfs_create("tmpvars", "hello", VFS_CREATE_FILE);
if (ret != E_OK) return false;
char *hello = "WAWAWAWA!!!";
ret = vfs_write("tmpvars", "hello", hello, hal_strlen(hello)+1, 0);
if (ret != E_OK) return false;
char buf[20];
ret = vfs_read("tmpvars", "hello", buf, sizeof(buf), 0);
if (ret != E_OK) return false;
vfs_remove("tmpvars", "hello");
if (ret != E_OK) return false;
ret = vfs_read("tmpvars", "hello", buf, sizeof(buf), 0);
if (ret != E_NOENTRY) return false;
return true;
}