86 lines
2 KiB
C
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 lock_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 lock_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)
|
|
{
|
|
lock_t *lock = dcache_lock_for(parent, name);
|
|
u64 h = dcache_hash(parent, name);
|
|
|
|
spin_lock(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);
|
|
spin_unlock(lock);
|
|
return;
|
|
}
|
|
}
|
|
spin_unlock(lock);
|
|
}
|
|
|
|
void dcache_remove(struct dc_entry *d)
|
|
{
|
|
lock_t *lock = dcache_lock_for(d->parent, d->d_name);
|
|
|
|
spin_lock(lock);
|
|
dirent_free(d->dirent);
|
|
d->dirent = NULL;
|
|
d->parent = DC_TOMBSTONE;
|
|
spin_unlock(lock);
|
|
}
|
|
|
|
struct dc_entry *dcache_lookup(struct dc_entry *parent, const char *name)
|
|
{
|
|
CLEANUP_SLOCK lock_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;
|
|
}
|