vbos/fs/vfs/dcache.c
Michael Shaw 5ae890b3b0 dcache: add initial dcache
Signed-off-by: Michael Shaw <m@michaelsshaw.com>
2026-07-23 02:14:28 -04:00

90 lines
2.2 KiB
C

/* SPDX-License-Identifier: GPL-2.0-only */
#include <kernel/common.h>
#include <fs/dcache.h>
#include <fs/inode.h>
#include <lib/string.h>
#define DC_TOMBSTONE ((struct dc_entry *)1)
struct dc_entry dcache[DCACHE_SIZE];
static spinlock_t dcache_locks[DCACHE_NLOCKS];
static unsigned long dcache_hash(struct dc_entry *parent, const char *name)
{
unsigned long h = (unsigned long)parent;
while (*name)
h = ((h << 5) - h) + (unsigned char)*name++;
return h;
}
static spinlock_t *dcache_lock_for(struct dc_entry *parent, const char *name)
{
unsigned long h = dcache_hash(parent, name);
return &dcache_locks[h & (DCACHE_NLOCKS - 1)];
}
void dcache_init(void)
{
for (int i = 0; i < DCACHE_SIZE; i++)
dcache[i].parent = NULL;
for (int i = 0; i < DCACHE_NLOCKS; i++)
dcache_locks[i] = 0;
}
void dcache_insert(struct dc_entry *parent, dirent_t *dirent, const char *name)
{
spinlock_t *lock = dcache_lock_for(parent, name);
unsigned long h = dcache_hash(parent, name);
spinlock_acquire(lock);
for (int i = 0; i < DCACHE_SIZE; i++) {
unsigned int b = (h + i) & (DCACHE_SIZE - 1);
struct dc_entry *s = &dcache[b];
if (!s->parent || s->parent == DC_TOMBSTONE || s->dirent->refcount == 0) {
if (s->dirent)
dirent_free(s->dirent);
s->parent = parent;
s->dirent = dirent;
memcpy(s->d_name, name, FILE_NAME_MAX_LEN + 1);
spinlock_release(lock);
return;
}
}
spinlock_release(lock);
}
void dcache_remove(struct dc_entry *d)
{
spinlock_t *lock = dcache_lock_for(d->parent, d->d_name);
spinlock_acquire(lock);
dirent_free(d->dirent);
d->dirent = NULL;
d->parent = DC_TOMBSTONE;
spinlock_release(lock);
}
struct dc_entry *dcache_lookup(struct dc_entry *parent, const char *name)
{
spinlock_t *lock = dcache_lock_for(parent, name);
unsigned long h = dcache_hash(parent, name);
struct dc_entry *result = NULL;
spinlock_acquire(lock);
for (int i = 0; i < DCACHE_SIZE; i++) {
unsigned int b = (h + i) & (DCACHE_SIZE - 1);
struct dc_entry *s = &dcache[b];
if (!s->parent)
goto out;
if (s->parent != DC_TOMBSTONE && s->parent == parent && !strcmp(s->d_name, name)) {
result = s;
goto out;
}
}
out:
spinlock_release(lock);
return result;
}