vbos/fs/vfs/dcache.c
Michael Shaw 0e8fd71d64 dcache: use common types and new CLEANUP macros
Signed-off-by: Michael Shaw <m@michaelsshaw.com>
2026-07-24 22:29:47 -04:00

86 lines
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 u64 dcache_hash(struct dc_entry *parent, const char *name)
{
u64 h = (u64)parent;
while (*name)
h = ((h << 5) - h) + (u8)*name++;
return h;
}
static spinlock_t *dcache_lock_for(struct dc_entry *parent, const char *name)
{
u64 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);
u64 h = dcache_hash(parent, name);
spinlock_acquire(lock);
for (int i = 0; i < DCACHE_SIZE; i++) {
u32 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)
{
CLEANUP_SLOCK spinlock_t *lock = dcache_lock_for(parent, name);
u64 h = dcache_hash(parent, name);
struct dc_entry *result = NULL;
for (int i = 0; i < DCACHE_SIZE; i++) {
u32 b = (h + i) & (DCACHE_SIZE - 1);
struct dc_entry *s = &dcache[b];
if (!s->parent)
return NULL;
if (s->parent != DC_TOMBSTONE && s->parent == parent && !strcmp(s->d_name, name))
return s;
}
return NULL;
}