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 and addr[7:2] is the tag. Each line has a valid bit, a tag and a data byte.
  • Request. The CPU raises req with we, addr and wdata, and keeps them until ack is 1. ack is combinational, so a request that is acknowledged completes in that same clock; the cache acts on its inputs at the clock edge. With req = 0 nothing happens: ack, mem_rd and mem_we are 0.
  • Read hit. The line is valid and its tag matches: ack = 1 and rdata is the line's data, in the same clock. Memory is not read.
  • Read miss. ack = 0 and mem_rd = 1, with mem_addr = addr. At the clock edge the cache loads mem_rdata (memory reads combinationally from mem_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 with mem_addr = addr and mem_wdata = wdata, and ack = 1 in the same clock. If the line is valid with a matching tag it is updated with wdata too; 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.