RTL Design #53 · 2026-11-15 · Direct-mapped cache · Medium · about 30 min
Build a direct-mapped write-through cache
Write dmcache, a small direct-mapped, write-through data cache that sits between a CPU and a memory.
- Geometry. 4 lines, each holding one 8-bit word. The address is 8 bits:
addr[1:0]is the index andaddr[7:2]is the tag. Each line has a valid bit, a tag and a data byte. - Request. The CPU raises
reqwithwe,addrandwdata, and keeps them untilackis 1.ackis combinational, so a request that is acknowledged completes in that same clock; the cache acts on its inputs at the clock edge. Withreq= 0 nothing happens:ack,mem_rdandmem_weare 0. - Read hit. The line is valid and its tag matches:
ack= 1 andrdatais the line's data, in the same clock. Memory is not read. - Read miss.
ack= 0 andmem_rd= 1, withmem_addr=addr. At the clock edge the cache loadsmem_rdata(memory reads combinationally frommem_addr) into the line with the new tag, marks it valid, and replaces whatever was there. The CPU repeats the request, which now hits: a miss costs two clocks in all. - Write. Write-through, no write allocate.
mem_we= 1 withmem_addr=addrandmem_wdata=wdata, andack= 1 in the same clock. If the line is valid with a matching tag it is updated withwdatatoo; otherwise the cache is left unchanged. - Reset. Synchronous, active low. It invalidates every line. Memory is not touched.
Example, with the same read request held (memory holds 0x37 at 0x12, line empty): in the first clock ack = 0 and mem_rd = 1; in the second ack = 1, rdata = 0x37 and mem_rd = 0.
testbench.sv runs a short scenario and prints PASS when it works. Submit runs hidden checks on hits and misses, conflicting addresses, writes, reset, and random traffic compared with a reference model.
Write and run your answer in the browser. The hidden tests check it, and it’s free.