Direct-Mapped Cache
Hard · Sequential · SystemVerilog · VHDL
A premium problem. Subscribe to open it in the editor, run the testbench and see where your design lands.
Design a direct-mapped, write-back cache between a CPU and a memory.
A cache keeps copies of recently used memory words so that most accesses never wait for the slow memory. In a direct-mapped cache each address can live in exactly one line, picked by its low bits, so two addresses that share those bits evict each other. A write-back cache writes a word only into its line and marks the line dirty; memory is updated when a dirty line is evicted.
The low INDEX_BITS bits of an address are its index and the remaining bits its tag. Each index has one line, which holds a word, a tag, a valid bit and a dirty bit.
A request is a cycle with cpu_re (a read) or cpu_we (a write of cpu_wdata) high, never both; while cpu_stall is high the CPU holds its request unchanged. A request hits when the line at its index is valid and holds its tag. In a cycle with a hit, cpu_stall is low: a read hit puts the line's word on cpu_rdata, and a write hit stores cpu_wdata in the line and marks it dirty. cpu_stall is high in every cycle with a request that misses. In every cycle other than a read hit, cpu_rdata may take any value.
A miss is handled through the memory, one request at a time. If the line is valid and dirty, the cache first writes its word back to the address its tag and index form, with mem_we high and the address and word on mem_addr and mem_wdata. It then fills the line from cpu_addr, with mem_re high and mem_addr = cpu_addr. Each memory request starts in the cycle after the miss is seen or after the previous request completes, and is held until it completes in a cycle with mem_ack high; in that cycle mem_rdata carries the word of a fill. When the fill completes, the line takes the request's tag and becomes valid: after a read it holds mem_rdata and is clean, after a write it holds cpu_wdata and is dirty. mem_we and mem_re are low while no memory request is outstanding.
rst_n is a synchronous, active-low reset that invalidates every line and abandons a miss in progress.
- FIFOs & memory
- State machines