A walkthrough of lab6-yumelody: the four-stage pipelined RISC-V processor in Processor.ms, the two caches it fetches and loads through, and the test harness that grades it. Every snippet is your own committed code. Each section names the lecture it builds on, shows the data flow as diagrams, and ends with recall questions.
Read this section first. The later sections are the same five ideas applied to your code.
time = instructions × cycles per instruction × clock period. Every design choice in the lab trades one factor against another.
| cycle 0 | cycle 1 | cycle 2 | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| i1 | fetch · decode · execute · write | |||||||||||
| i2 | fetch · decode · execute · write | |||||||||||
| i3 | fetch · decode · execute · write | |||||||||||
Cycles per instruction is 1. The clock must be as long as the whole path.
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| i1 | F | D | E | W | ||
| i2 | F | D | E | W | ||
| i3 | F | D | E | W |
Each instruction still takes four steps, so its latency is no better. Throughput is better: one finishes per short cycle, as long as nothing interferes.
Pipelining buys a shorter clock and pays in extra cycles whenever instructions depend on each other. The chart below is that bill. Move the sliders to see which cost dominates.
Each load-use pair and each taken branch costs one cycle in your design. A miss costs the whole penalty. A small miss rate times a large penalty quickly becomes the biggest term, which is why the cache matters as much as the pipeline.
Fast storage is small and large storage is slow. Programs reuse recent addresses and their neighbours, so a small copy of recent data answers most requests.
Rough orders of magnitude on a log scale. Each grid line is 10× slower than the one to its left.
The cost of a cache is summarised by one formula: average access time = hit time + miss rate × miss penalty. With your numbers the hit time is 1 cycle and a clean miss adds 33.
The two right-hand points are Beveren's random workload, which has no locality. Real programs sit near the left edge, which is the whole reason caches work. Halving the miss rate matters far more than shaving the hit time.
| Make the cache… | Hit time | Miss rate | Miss penalty | Why |
|---|---|---|---|---|
| Larger (more sets) | ↑ slightly worse | ↓ better | same | More lines fit, but bigger arrays are slower to read |
| Longer lines | same | ↓ better for sequential access, ↑ worse if lines get too few | ↑ worse | Neighbours come along for free, but each miss moves more data |
| More associative (more ways) | ↑ worse | ↓ better | same | Removes conflict misses, adds comparators and a way mux |
Misses come in three kinds. Compulsory: the first touch of a line. Capacity: the program uses more lines than the cache holds. Conflict: the lines would fit, but too many share one set. Your two-way cache exists to attack the third kind, and the trace in section 5 shows one being removed.
When one step needs something a previous step has not finished producing, there are only three things you can do. Every hazard in the lab is solved with one of them.
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| lw x1 | F | D | E | W | ||
| use x1 | F | D | D | E | W |
Always correct, always costs time. Used when the value does not exist anywhere yet: load-use, and every cache miss.
| 0 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|
| add x1 | F | D | E ↓ | W | |
| use x1 | F | D ← | E | W |
Costs no cycles, costs wires and muxes. Possible whenever the value exists somewhere, even if it is not yet in its official home.
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| branch | F | D | E | W | ||
| pc+4 | F | D✗ | ||||
| target | D | E | W |
Free when the guess is right. When wrong, throw away the work before it changes any permanent state. Used for the next PC.
The rule that makes guessing safe generalises: speculative work must not touch permanent state until it is confirmed. In your processor only writeback and the data cache change permanent state, and a branch is resolved before anything behind it reaches them.
Cutting logic into N stages divides the logic delay by N, but register overhead does not shrink and every hazard costs more cycles. There is an optimum.
This is the same trade-off as Lab 6's grading. A longer bypass path lowers cycles per instruction and stretches the clock. Resolving branches earlier cuts the annul cost and adds logic to an earlier stage. Neither number means anything alone. Only their product does.
The lab has about 900 lines of hardware, but only five patterns. Each reappears in Lectures 16 to 22 and well beyond processors.
| Pattern | In this lab | The general form | Where it returns |
|---|---|---|---|
| Valid bit | Maybe on every pipeline register, NotValid lines | Carry "is this real?" next to the data so empty slots flow like full ones | Page-table valid bits (L17), TLB entries (L18) |
| Ready / valid handshake | reqEnabled and Valid(req), isValid(data) | The producer says when it has something, the consumer says when it can take it. Slowness propagates backward as backpressure | Device I/O (L19), every queue and network protocol |
| State machine around a slow resource | Ready → Lookup → Writeback → Fill | Remember the request, wait in a named state, finish when the resource answers | Page-fault handling (L17), system calls (L16) |
| Speculate and squash | Fetch pc + 4, annul on redirect | Do the likely thing now, keep the ability to undo until it is confirmed | Exceptions redirect and squash the same way (L19) |
| Cache with a write policy | Tag match, Clean / Dirty, LRU eviction | Small fast copy, a rule for which entry to drop, a rule for when to write changes back | TLB (L18), cache coherence states (L21), OS page cache |
Lab 4 gave you a processor that finishes one instruction per clock cycle, with a long clock period because fetch, decode, execute, memory and writeback all sit on one combinational path. Lab 5 gave you caches. Lab 6 joins them: the same decode and execute functions are split across pipeline registers so the clock can be short, and instruction and data memory become caches in front of a slow main memory.
flowchart LR
subgraph P[Processor.ms]
F[Fetch module
pc, ignoreInstr] -->|f2d method| D[Decode
decode fn + bypass]
D -->|d2e register| E[Execute
execute fn]
E -->|e2w register| W[Writeback]
W -->|rf.wr| RF[(RegisterFile)]
RF -->|rd1 rd2| D
E -.->|dstE dataE| D
W -.->|dstW dataW| D
E -.->|annul redirectPc| F
end
F <--> IC[iCache
TwoWayCache]
E -->|dCache.req| DC[dCache
CacheWrapper TwoWayCache]
DC -->|dCache.data| W
IC <--> IM[(iMem MainMemory)]
DC <--> DM[(dMem MainMemory)]
| File | What it holds | Came from | Lecture |
|---|---|---|---|
| Decode.ms, Execute.ms, ALU.ms | Pure combinational functions: instruction bits to DecodedInst, then to ExecInst | Lab 4 (ALU from Lab 2) | L10 RISC-V, L11 Single Cycle Processor |
| CacheTypes.ms, CacheHelpers.ms | Cache geometry, address slicing, sub-word load and store helpers | Lab 5 | L12 Memory Hierarchy, L13 Caches |
| DirectMappedCache.ms, TwoWayCache.ms | The two cache modules, each a four-state machine | Lab 5 | L13 Caches |
| MainMemory.ms, SRAM.ms | Slow line-based memory, one-cycle SRAM arrays, CacheWrapper for MMIO | Provided | L12 |
| Processor.ms | Fetch module and the pipelined Processor | New in Lab 6 | L14, L15 Pipelined Processors |
| FetchTB.ms, Beveren.ms, test.py, sw/ | Testbenches and RISC-V test programs | Provided |
Everything in this lab is written with five constructs. If any one is fuzzy, the pipeline code will not read correctly.
| Construct | Meaning in hardware | Where you see it |
|---|---|---|
| Reg#(T) x(init) | A D flip-flop bank. Reading x gives the value at the start of the cycle. x <= v takes effect at the next clock edge. | pc, d2e, e2w, state |
| rule | Combinational logic evaluated every cycle that computes next-state values. Plain variables inside a rule are wires, and assignment order is just wiring order. | rule tick in the processor and caches |
| input T x default = v | A wire into a module, driven by the parent. If nobody drives it this cycle it takes the default. | cache.req, fetch.in, rf.wr |
| method T m | A combinational output of a module, computed from its registers and inputs this cycle. | cache.data, reqEnabled, fetch.f2d |
| Maybe#(T) | A value plus a valid bit. Valid(v) or Invalid, tested with isValid, unwrapped with fromMaybe(default, m). | Every pipeline register and every request |
rule tick computes writeback first, then execute, then decode, the variables dstW, dataE and annul are wires running backward from later stages to earlier ones in the same cycle. That ordering is how bypassing and annulment get built.Recall
d2e <= Valid(x); and two lines later reads d2e. Which value does it see?The old one. Register writes land at the clock edge. The read anywhere in the rule returns the value held at the start of the cycle.
d2e and e2w typed Reg#(Maybe#(…)) instead of plain structs?The valid bit lets a stage hold a bubble. Invalid is the NOP that stalls and annulments insert, and the stage logic is skipped when the register is invalid.
cache.req in a cycle where the rule does not assign it?It takes its declared default, Invalid, so the cache sees no request.
The pipeline reuses two functions unchanged. decode(inst) returns a DecodedInst with the instruction type, ALU function, source register indices, destination and immediate. execute turns that plus two register values and the PC into an ExecInst.
Three facts about ExecInst drive the pipeline design:
data is the register result for every type except LOAD. A load's result does not exist until memory answers, one stage later. This is the reason a load followed immediately by a use must stall.nextPc differs from pc + 4 only for taken branches and jumps, and it is known only in execute. Fetch has already guessed pc + 4 by then, so those cases need a redirect.dst is a Maybe#(RIndx). Stores and branches have Invalid, which the pipeline turns into register 0 so they never match a source register.Lecture 12's point is that large memory is slow and fast memory is small, and programs reuse nearby addresses, so a small fast copy of recently used lines serves most accesses. Lecture 13 gives the mechanism: split each address into fields that say which set to look in, which line it must be, and which word of the line.
Your geometry in CacheTypes.ms is 64 sets and 16 words per line. That is 64 bytes per line and 4 KB of data per way.
The 64 sets. The index picks one. The tag then decides whether the line stored there is the one you asked for.
Writing the slices with logWordsPerLine and logCacheSets instead of literal numbers means the cache still works if the geometry constants change.
The cache stores whole 32-bit words. lb, lh, sb and sh touch part of a word, selected by the byte offset.
Worked example: the word is 0xAABBCCDD and the request is Lb at byte offset 2. Shift right by 16 to get 0x0000AABB, take the low byte 0xBB, sign-extend to 0xFFFFFFBB. For Sb of 0x11 at offset 2, the mask is 0xFF00FFFF and the result is 0xAA11CCDD.
Recall
20, 6, 4, 2. Byte offset is log2(4 bytes per word). Word offset is log2(16 words per line). Index is log2(64 sets). The tag is what is left of 32.
0x4000 and 0x6000: same set or different? Same line?Same set. Bits [11:6] are 0 for both. The tags differ (4 and 6), so they are different lines competing for set 0. sw/fullasmtests/cache.S uses exactly this pair to force evictions.
It rebuilds it from the stored tag and the current index: LineAddr oldAddr = {t, getIndex(curReq.addr)}. The index is shared by everything in the set, so only the tag has to be stored.
Lw return word and not shifted?Word loads must be 4-byte aligned, so the byte offset is 0 and both are equal. Using word keeps the shifter off the path for the common case.
The tag, data and status arrays are SRAMs. An SRAM here takes a request in one cycle and shows read data in the next cycle, for that cycle only. That one-cycle delay is why the cache needs a state machine at all: it must remember the request (curReq) while it waits for the arrays.
| Path | States | Main-memory requests |
|---|---|---|
| Hit | Ready → Lookup → Ready | None |
| Miss, victim clean or not valid | Ready → Lookup → Fill → Ready | One read |
| Miss, victim dirty | Ready → Lookup → Writeback → Fill → Ready | One write, then one read |
The two traces below follow the request sequence from sw/fullasmtests/cache.S. Both addresses map to set 0. Compare the direct-mapped table with the two-way table to see what associativity buys.
cache.S stores and loads at 0x4000 and 0x6000All three arrays are read at the same index. The index comes from r, the incoming request, because curReq will not hold it until next cycle.
Dirty. The tag array is not rewritten because the tag has not changed.Writeback. Main memory already holds that data, so writing it would waste about 33 cycles. Beveren fails a cache that makes this extra request.Writeback waits on mainMem.reqEnabled, which means the write finished and memory can take the read. Fill waits on mainMem.data. A store miss merges the new word into the fetched line before saving it, so the line enters the cache already Dirty. This is the allocate-on-write policy from Lecture 13.
MainMemory sets latency = wordsPerLine + 16, which is 32, counts cyclesLeft down from 32, and raises validOut one cycle after the count reaches 1. The line shows up 33 cycles after the request. A dirty miss pays that twice.data method: answer as early as possibleThe method is combinational. A load hit returns data in the Lookup cycle, one cycle after the request. A load miss returns data in the same cycle main memory delivers the line, without waiting for the line to be written into the SRAM. Stores never produce valid data. Beveren checks for exactly one valid cycle per load.
Recall
s != NotValid part of isHit?After reset the tag array holds arbitrary bits that could equal a real tag. The status array is what says whether the tag and data mean anything. The enum encoding (NotValid = 2'b10) is chosen so lines start out not valid.
Hit: 1 (request in cycle t, data in t+1). Clean miss: Lookup at t+1 sends the memory read, data arrives 33 cycles later at t+34.
The store changes one word (or one byte) of a 16-word line. The other 15 words must be correct in the cache, because the whole line is later written back as one unit.
data returned a register that the rule filled in?Every load would cost one more cycle, and the value could stay valid for more than one cycle. Beveren reports both: it fails on valid data in consecutive cycles and on total cycle count.
A direct-mapped cache has one candidate line per set, so two hot addresses with the same index evict each other forever. Lecture 13 calls these conflict misses. Two ways give each set two candidates. The cost is two tag comparisons and a policy for choosing the victim.
| Change from direct-mapped | Your code |
|---|---|
| Arrays become vectors of two | Vector#(2, SRAM#(logCacheSets, Line)) dataArrays; (same for tags and status) |
| One LRU bit per set, held in registers | Vector#(cacheSets, RegU#(Bit#(1))) lru; |
| Hit is per way | function Bool isHit(Integer way) |
| Remember the victim across Writeback and Fill | Reg#(Bit#(1)) victimWay(0); |
The LRU bit stores the way to evict next. A hit in way 0 sets it to 1, a hit in way 1 sets it to 0, and a fill into a way points the bit at the other way. With two ways, one bit is exact LRU.
This is the one part of your two-way cache that matters most for the pipeline. The direct-mapped cache accepts a request only in Ready, so the best it can do is one access every two cycles. Your two-way cache also accepts a new request during a load hit:
A load hit does not write the SRAMs, so their request ports are free in that cycle and the next lookup can start immediately. A store hit uses the ports to write the modified line, so it cannot overlap. With this, the instruction cache delivers one instruction per cycle as long as fetches hit. With the direct-mapped cache as iCache, f2d would be valid only every other cycle.
Beveren sends pseudo-random loads and stores over a 16 KB address range and compares every load against a reference memory. At the end it requires exact hit and miss counts. The expected numbers show the effect of associativity directly.
The range holds 256 lines. The direct-mapped cache holds 64 of them and the two-way cache 128, so uniformly random access hits about 25% and 50% of the time. The cycle counts must be within 10% of the expected values.
Recall
lru[idx] == 1, miss. Which way is evicted and what is lru[idx] after the fill?Way 1 is evicted. After the fill the bit is 0, because way 1 is now the most recently used.
Each SRAM has one request port. A store hit uses the data and status ports to write. A load hit leaves all ports idle, so the next read can be issued in the same cycle.
victimWay a register when victim is computed in Lookup?The SRAM outputs that determine the victim are valid only in the Lookup cycle. Fill happens 33 or more cycles later and still needs to know which way to write.
There are only 64 bits. Registers can be read and written in the same cycle with no request protocol, which keeps the hit path simple.
Lecture 14's argument: clock period is set by the slowest combinational path, so cut the path with registers and several instructions can be in flight at once. Throughput rises as long as the instructions do not interfere. Your processor has four stages.
| Stage | State it starts from | Work | State it writes |
|---|---|---|---|
| Fetch | pc, fetch.in | Choose next PC, send it to the iCache | pc, iCache SRAM lookup |
| Decode | pc + iCache.data (f2d) | decode, read register file, apply bypasses, detect hazards | d2e |
| Execute | d2e | execute, send dCache request, resolve branches | e2w |
| Writeback | e2w + dCache.data | Pick ALU or load data, write the register file | rf, instrs |
There is no separate F2D register. The iCache's one-cycle SRAM read plays that role: pc holds the address, and the instruction arrives on iCache.data the cycle after the request. The f2d method pairs them.
D2E carries register values already read and bypassed, so execute never touches the register file. E2W carries only what writeback needs: the destination, the ALU result, and the type so it knows whether to wait for load data.
rule tickThe rule is written writeback, execute, decode, then fetch control. Each block defines wires that the blocks below it read.
| Block | Wires it produces | Read by |
|---|---|---|
| Writeback | dstW, dataW, dDataStall | Decode (bypass), Execute and Decode (freeze) |
| Execute | dstE, dataE, annul, redirectPc, dReqStall | Decode (bypass, kill), Fetch (redirect) |
| Decode | hazardStall | Fetch (stall) |
The diagrams below come from a cycle-accurate model of your rule with caches that always hit. Each grid is the pipeline diagram from lecture for one short program, followed by the hazard events in the order they happen.
A data hazard exists when decode reads a register that an older instruction still in the pipeline has not written yet. Lecture 15 gives two tools. Stalling holds the reader in decode until the value is in the register file. Bypassing routes the value from where it already exists to where it is needed. Your processor bypasses whenever the value exists and stalls only when it does not.
An instruction in decode needs a register. What happens depends only on what kind of instruction produces it and how far ahead that instruction is.
| Producer | Producer is in execute | Producer is in writeback | Producer has left the pipeline |
|---|---|---|---|
ALU-type (add, addi, lui, jal link…) | Forward from execute. 0 cycles lost | Forward from writeback. 0 cycles lost | Read the register file |
| Load, cache hit | Wait 1 cycle. The value does not exist yet | Forward from writeback. 0 cycles lost | Read the register file |
| Load, cache miss | Wait 1 cycle | Whole pipeline waits until the line arrives | Read the register file |
The general rule: forward if the value exists anywhere, wait only if it does not exist yet.
The pair (dst, Maybe data) has three meanings. Destination 0 means this stage writes nothing. A non-zero destination with valid data means the value can be bypassed. A non-zero destination with invalid data means the value is coming but does not exist yet, so a reader must wait.
rf.rd1 reads a register, which returns the old value until the clock edge.!= 0 test keeps writes to x0 from being forwarded. x0 must always read as zero.When a load is in execute, its result will not exist until writeback. A dependent instruction in decode stalls for one cycle. The load then moves to writeback, dCache.data becomes valid on a hit, and the value comes through the writeback bypass.
See the Load-use diagram in section 7. sw/pipetests/02_all_data_hazards.S has four chained addi x1, x1, 1 (bypass from execute every cycle) followed by four chained lw x1, 0(x1) (one stall each). The expected final value is x1 = 0x110.
Recall
addi x1,x0,5 then add x2,x1,x1. Any stall? Where does x1 come from?No stall. When add is in decode, addi is in execute with dstE = 1 and dataE = Valid(5). Both operands take the execute bypass.
lw x1,0(x2) then addi x3,x1,1. How many bubbles, and which wire finally delivers x1?One bubble. In the first decode cycle dstE = 1 with dataE invalid, so hazardStall. Next cycle the load is in writeback and dataW carries the cache data.
x5: one in execute, one in writeback. Decode reads x5. Which value?The one in execute. It is the younger instruction, and the if / else if order gives it priority.
hazardStall not get counted when annul is also true?The instruction in decode is on the wrong path and is being thrown away. Its dependency is irrelevant, and the lost cycle is already counted as an annulment.
No. Its dst is Invalid, so dstE is 0 and no source comparison passes.
Fetch has to pick the next PC before it knows what the current instruction is. Your fetch always guesses pc + 4. The real next PC is known in execute. If the guess was wrong, the instruction behind the branch is from the wrong path and must be removed before it changes any state.
Two things happen in that same cycle. Decode sees annul and writes Invalid into d2e, which kills the wrong-path instruction. Fetch receives Redirect and requests redirectPc from the iCache.
j costs one red cell. Nothing past decode can change registers or memory, so killing d2e is enough.annul has priority over every stall in the fetch control. That is safe because annul can only be true when execute actually ran, which already requires !dDataStall and !dReqStall.
Recall
Fetch already guessed pc + 4, which is correct for a not-taken branch. redirect stays false and nothing is annulled.
d2e? What about the instruction being fetched?The fetch request issued in the annul cycle is for the redirect target, so nothing wrong is in flight behind decode. This holds when the iCache can accept the request. Section 10 covers the case where it cannot.
99. Predicting not-taken is wrong on every taken iteration. This is the motivation for the branch predictors that the bpred_* tests in sw/fullasmtests exercise.
jal writes pc + 4 to rd and is also annulling. Does the link value still get written?Yes. Annulment kills the instruction behind the jump. The jump itself goes on to e2w with data = pc + 4 and writes it in writeback.
ignoreInstrFetch is its own module so the testbench can drive it alone. The processor tells it one of three things each cycle.
| FetchAction | Meaning | nextPc |
|---|---|---|
| Dequeue | Decode consumed the instruction at f2d | pc + 4 |
| Stall | Decode did not consume it, or there was none | pc |
| Redirect | Discard whatever is fetched and go elsewhere | in.redirectPc |
pc always names the instruction that decode is looking at or waiting for. The request sent to the iCache is for nextPc, so the data arriving next cycle matches the new pc.Stall the same address is requested again. This is required because SRAM output lasts one cycle. Re-requesting makes the instruction reappear next cycle.iCache.data is invalid, so f2d is invalid, the processor sends Stall, and fetch requests address 0. That first request is how the pipeline starts.ignoreInstr existsSuppose the iCache is in the middle of a miss for address A when execute redirects to B. pc becomes B immediately, but the cache cannot take a new request and will eventually answer with the instruction at A. Without protection, f2d would pair A's instruction with pc = B and decode would run a wrong-path instruction under the wrong PC.
| Cycle | iCache | fetch.in | pc after | ignoreInstr after | f2d |
|---|---|---|---|---|---|
| t | Fill for A, not reqEnabled | Redirect B | B | True | Invalid |
| t+1 … t+k−1 | Still filling A | Stall | B | True | Invalid |
| t+k | Returns inst at A, valid | Stall | B | True | Invalid, masked by ignoreInstr |
| t+k+1 | Ready, accepts request for B | Stall | B | False | Invalid |
| t+k+2 | Lookup for B | Dequeue | B+4 | False | Valid, inst at B |
The flag is set only when a redirect arrives and no request could be issued. It is cleared the moment a request for the current pc goes out, since from then on the next answer is the right one.
Recall
nextPc and not pc?The SRAM answers one cycle later. By then pc has been updated to nextPc, so the data and pc line up in f2d.
Stall because of a load-use hazard. What does fetch do, and why is the instruction not lost?nextPc = pc, and the same address is requested again. The instruction disappears from iCache.data at the end of this cycle and reappears next cycle from the new lookup.
!isValid(fetch.f2d) a reason to send Stall?Nothing was consumed, so the PC must not advance. This covers iCache misses, reset, and the cycles masked by ignoreInstr.
One instruction every two cycles. reqEnabled is false during Lookup, so after each hit there is a cycle where no request goes out.
A stage that cannot proceed holds everything behind it and lets everything ahead of it drain. A bubble fills the gap between them.
That one sentence covers every stall in the processor. The table shows what the instruction in each stage does during each kind of event.
| Event | Fetch | Decode | Execute | Writeback | Bubble enters |
|---|---|---|---|---|---|
| Normal cycle | advances | advances | advances | completes | none |
| iCache miss | waits for the line | empty | advances | completes | execute |
Load-use (hazardStall) | holds | holds | advances | completes | execute |
Taken branch (annul) | redirected | killed | advances | completes | execute |
dCache busy (dReqStall) | holds | holds | holds | completes | writeback |
Load data missing (dDataStall) | holds | holds | holds | holds | none |
With real caches the data memory can be slow in two different places, and each needs its own stall.
| Signal | Raised in | Condition | Effect |
|---|---|---|---|
| dReqStall | Execute | A load or store wants to send a request but dCache.reqEnabled is false | Instruction stays in d2e, e2w gets a bubble, decode and fetch hold |
| dDataStall | Writeback | A load is in e2w and dCache.data is not valid | Whole pipeline freezes: no stage writes its register |
The freezing is done by guards. Execute runs only if (!dDataStall). Decode runs only if (!dDataStall && !dReqStall). A block that does not run assigns nothing, so its register keeps its value.
dDataStall for the whole fill, because the load is in writeback waiting for data and nothing may pass it.dReqStall until the cache is ready.dReqStall writeback still completes the instruction it holds. Only the stages behind it wait.The dCache miss diagram in section 7 shows dDataStall freezing all four stages. The model shortens the fill to 4 cycles. The real one is about 33.
CacheWrapper#(TwoWayCache) dCache(dMem). The wrapper passes every request to the cache and also watches for Sw to three addresses: 0x4000_0000 prints a character, 0x4000_0004 prints an integer, and 0x4000_1000 prints PASSED or FAILED and ends the simulation. This is the first appearance of memory-mapped I/O, which Lecture 19 treats in general.Recall
dDataStall. The load sits in e2w. Execute and decode are guarded off and fetch receives Stall, so all four stages hold.
add. Does the add wait?No. The store moves on and the add needs no memory. Only the next load or store would wait, in execute, on dReqStall.
e2w be set to Invalid during dReqStall?The instruction in writeback finishes this cycle. If e2w kept its value, that instruction would be written back and counted a second time.
dataE left invalid for a load even when the cache will hit?In execute the request is only being sent. No data exists anywhere yet, hit or miss. It first appears on dCache.data in the next cycle.
flowchart LR S[sw/*.S assembly] -->|make -C sw| V[.vmh memory image] V -->|symlink| M[mem.vmh] M --> P[./Processor simulation] P -->|unimp reaches writeback| DUMP[register dump on stdout] P -->|Sw to 0x4000_1000| PF[PASSED or FAILED] DUMP --> T[test.py compares with .expected] PF --> T
mem.vmh, so the instruction and data caches see one program image.| Command | What runs | What it proves |
|---|---|---|
| make test_fetch && ./test_fetch | FetchTB.ms drives Fetch alone with random actions and checks every f2d against a reference memory | Four stages of difficulty: no stalls, stalls, annuls, both |
| make test_DirectMappedBeveren | Random loads and stores against the direct-mapped cache | Correct data, exact hit and miss counts, cycle bound |
| make test_TwoWayBeveren | Same against the two-way cache | Also proves LRU: counts must be 49,646 and 50,379 |
| make test_CacheTesterPrimer | Your own request list and expected responses | Targeted cache scenarios |
| make prog_test a | All microtests, one instruction type each | Decode and execute still correct inside the pipeline |
| make prog_test p | The four pipeline tests | Hazard handling |
| make prog_test f | Full assembly tests including cache.S and bpred_* | Whole-program behaviour, self-checking through MMIO |
| make prog_test s1 | sort_base benchmark | Cycle count for the performance grade |
| make synth | Synthesis of Processor.ms | Clock period |
Each test program ends in unimp. The decoder marks it Unsupported, and it flows down the pipeline like any instruction. When it reaches writeback, the provided block prints the counters, the PC and all 32 registers, then stops. test.py keeps the lines after "Dumping the state" and compares them with the .expected file line by line.
The check happens in writeback and not in decode for a reason. Every instruction ahead of unimp has completed by then, and an unimp on a wrong path is annulled before it gets there. 03_all_control_hazards.S depends on this: there is an unimp directly after every jump.
| Pipeline test | Program shape | Fails if |
|---|---|---|
| 01_no_hazards | Independent instructions | Basic stage hand-off is wrong |
| 02_all_data_hazards | Chained addi x1,x1,±1, then chained lw x1,0(x1) through a pointer table at 0x100 | A bypass is missing or stale, or load-use does not stall. Expected x1 = 0x110, pc = 0x44 |
| 03_all_control_hazards | j a; unimp; a: j b; unimp; … | A wrong-path unimp survives annulment and ends the test early |
| 04_all_hazards | addi, addi, lw x2, jr x2 | A jump target that comes from a load through a stall and bypass is wrong |
Trace it with the tools above. 0x400 has index 16 and 0x500 has index 20, so the two loads go to different sets and both miss on a cold dCache. Each miss freezes the pipeline through dDataStall. The add needs x3 from the second load, which is a load-use dependency, and x2 from the first load, which has already been written by the time it is needed. The result is x4 = 18.
The commented block at the top of rule tick prints one line per cycle with the PC in each stage or NOP for a bubble. Uncommenting it gives the same picture as the grids in section 7, from the real simulation.
Recall
03_all_control_hazards put unimp right after each jump?It is the instruction fetched on the wrong path. If annulment fails, that unimp reaches writeback and stops the test with the wrong PC in the dump.
The victim choice and the LRU updates. Wrong evictions never corrupt data, because the cache is always consistent with memory. They only change which requests hit.
An extra main-memory request, such as writing back a clean line, or a data method that waits a cycle before answering.
It stores a test number to 0x4000_1000. CacheWrapper sees the Sw, prints FAILED n or PASSED for zero, and ends the simulation.
Lecture 9 and Lecture 14 give the equation the lab is graded on:
time = instructions × cycles per instruction × clock period
Pipelining shortens the clock period. Every bubble raises cycles per instruction above 1. Your five counters split the bubbles by cause.
| Counter | Counts cycles where | How to reduce it |
|---|---|---|
| instrs | An instruction completed writeback | Fixed by the program |
| stalls_hazard | Decode held for a value that did not exist yet | Already at the minimum: only load-use |
| annulments | A taken branch or jump killed the instruction in decode | Branch prediction |
| stalls_ddata | A load waited in writeback for dCache data | Fewer misses: associativity, larger lines |
| stalls_dreq | A load or store waited in execute for the dCache to be ready | Faster store handling |
Cycles also go to iCache misses, which appear as cycles with an invalid f2d and are not counted separately. Roughly: total cycles ≈ instrs + stalls_hazard + annulments + stalls_ddata + stalls_dreq + iCache miss cycles + a few to fill and drain the pipeline.
The clock period is set by the longest path between registers. The bypass network makes execute's result feed decode's muxes in the same cycle, so the path from d2e through the ALU and bypass mux into d2e is a likely critical path. More bypassing lowers cycles per instruction and can lengthen the clock. That trade-off is the subject of the design project.
Unsupported check in writeback is the simplest version of it. The MMIO addresses in CacheWrapper are the simplest I/O device.getTag and getIndex slice. A TLB miss is another reason to stall.cache.S (I -> M, M -> I -> S) name coherence states. Your NotValid, Clean, Dirty are the single-processor version of that protocol.cache.data is valid: load hit in Lookup, load fill when memory data arrives. Never for stores.dst matches and data is invalid.ignoreInstr prevents.dReqStall versus dDataStall: where each is raised and what each freezes.unimp ends a test and why the check is in writeback.