Skip to content

Commit 40ce39a

Browse files
committed
Switch victim cache from FIFO to LRU
The previous victim cache implementation used a simple FIFO replacement policy, which is often suboptimal for cache performance. This commit implements an LRU (Least Recently Used) replacement policy to improve cache hit rates: - On a cache miss requiring eviction, the block with the oldest timestamp (minimum instret value) is now selected for replacement. - Timestamps are updated both on victim cache hits and when a block is newly evicted from the icache into the victim cache.
1 parent 8bfe59c commit 40ce39a

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

riscv.c

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,7 @@ static void mmu_fetch(hart_t *vm, uint32_t addr, uint32_t *value)
410410
*vblk = tmp;
411411
blk->tag = tag;
412412
vblk->tag = (tmp.tag << ICACHE_INDEX_BITS) | idx;
413+
vm->icache.v_used[i] = vm->instret;
413414

414415
uint32_t ofs = addr & ICACHE_BLOCK_MASK;
415416
*value = *(const uint32_t *) (blk->base + ofs);
@@ -450,11 +451,19 @@ static void mmu_fetch(hart_t *vm, uint32_t addr, uint32_t *value)
450451

451452
/* Move the current icache block into the victim cache before replacement */
452453
if (blk->valid) {
453-
victim_cache_block_t *vblk = &vm->icache.v_block[vm->icache.v_next];
454+
uint32_t lru_min = vm->icache.v_used[0];
455+
int lru_index = 0;
456+
for (int i = 1; i < VCACHE_BLOCKS; i++) {
457+
if (vm->icache.v_used[i] < lru_min) {
458+
lru_min = vm->icache.v_used[i];
459+
lru_index = i;
460+
}
461+
}
462+
victim_cache_block_t *vblk = &vm->icache.v_block[lru_index];
454463
*vblk = *blk;
455464
vblk->tag = (blk->tag << ICACHE_INDEX_BITS) | idx;
456465
vblk->valid = true;
457-
vm->icache.v_next = (vm->icache.v_next + 1) % VCACHE_BLOCKS;
466+
vm->icache.v_used[lru_index] = vm->instret;
458467
}
459468

460469
/* fill into the icache */

riscv.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ typedef icache_block_t victim_cache_block_t;
127127
typedef struct {
128128
icache_block_t i_block[ICACHE_BLOCKS];
129129
victim_cache_block_t v_block[VCACHE_BLOCKS];
130-
uint32_t v_next;
130+
uint32_t v_used[VCACHE_BLOCKS];
131131
} icache_t;
132132

133133
struct __hart_internal {

0 commit comments

Comments
 (0)