Lab 6 Pipeline Atlas

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.

fetchdecodeexecutewritebackannulledbypass
About the lecture materialThe 6.191 lecture and lab-handout pages need an MIT login that I could not use, so the lecture links here go by the public schedule titles and the concepts are explained from your code. Lab 6 rests on Lectures 11 to 15. Lectures 16 to 22 (operating systems, virtual memory, exceptions, synchronization) belong mostly to Lab 7, and section 13 marks the points where they attach to this processor.

0The big picture: five ideas that outlive this lab

Read this section first. The later sections are the same five ideas applied to your code.

Idea 1 · Performance is one product of three numbers

time = instructions × cycles per instruction × clock period. Every design choice in the lab trades one factor against another.

Single-cycle: one instruction per long cycle
cycle 0cycle 1cycle 2
i1fetch · decode · execute · write
i2fetch · decode · execute · write
i3fetch · decode · execute · write

Cycles per instruction is 1. The clock must be as long as the whole path.

Pipelined: one instruction per short cycle
012345
i1FDEW
i2FDEW
i3FDEW

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.

Model

Where the cycles go in a pipeline like yours

cycles per instruction
speed-up over a single-cycle processor with ideal memory

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.

Idea 2 · Keep a small fast copy of what you will need again

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.

Chart

Average access time against miss rate, with a 33-cycle penalty

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.

Every cache design choice moves one of the three terms

Make the cache…Hit timeMiss rateMiss penaltyWhy
Larger (more sets)↑ slightly worse↓ bettersameMore lines fit, but bigger arrays are slower to read
Longer linessame↓ better for sequential access, ↑ worse if lines get too few↑ worseNeighbours come along for free, but each miss moves more data
More associative (more ways)↑ worse↓ bettersameRemoves 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.

Idea 3 · Three answers to every dependency: wait, forward, or guess

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.

Wait (stall)
012345
lw x1FDEW
use x1FDDEW

Always correct, always costs time. Used when the value does not exist anywhere yet: load-use, and every cache miss.

Forward (bypass)
01234
add x1FDE ↓W
use x1FD ←EW

Costs no cycles, costs wires and muxes. Possible whenever the value exists somewhere, even if it is not yet in its official home.

Guess (speculate, then squash)
012345
branchFDEW
pc+4FD✗
targetDEW

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.

Idea 4 · More stages is not always faster

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.

Model

Time per instruction against pipeline depth

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.

Idea 5 · A handful of patterns build everything

The lab has about 900 lines of hardware, but only five patterns. Each reappears in Lectures 16 to 22 and well beyond processors.

PatternIn this labThe general formWhere it returns
Valid bitMaybe on every pipeline register, NotValid linesCarry "is this real?" next to the data so empty slots flow like full onesPage-table valid bits (L17), TLB entries (L18)
Ready / valid handshakereqEnabled and Valid(req), isValid(data)The producer says when it has something, the consumer says when it can take it. Slowness propagates backward as backpressureDevice I/O (L19), every queue and network protocol
State machine around a slow resourceReady → Lookup → Writeback → FillRemember the request, wait in a named state, finish when the resource answersPage-fault handling (L17), system calls (L16)
Speculate and squashFetch pc + 4, annul on redirectDo the likely thing now, keep the ability to undo until it is confirmedExceptions redirect and squash the same way (L19)
Cache with a write policyTag match, Clean / Dirty, LRU evictionSmall fast copy, a rule for which entry to drop, a rule for when to write changes backTLB (L18), cache coherence states (L21), OS page cache

1What the lab builds

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)]
Solid arrows are the forward data path. Dotted arrows are the feedback wires that solve hazards.
FileWhat it holdsCame fromLecture
Decode.ms, Execute.ms, ALU.msPure combinational functions: instruction bits to DecodedInst, then to ExecInstLab 4 (ALU from Lab 2)L10 RISC-V, L11 Single Cycle Processor
CacheTypes.ms, CacheHelpers.msCache geometry, address slicing, sub-word load and store helpersLab 5L12 Memory Hierarchy, L13 Caches
DirectMappedCache.ms, TwoWayCache.msThe two cache modules, each a four-state machineLab 5L13 Caches
MainMemory.ms, SRAM.msSlow line-based memory, one-cycle SRAM arrays, CacheWrapper for MMIOProvidedL12
Processor.msFetch module and the pipelined ProcessorNew in Lab 6L14, L15 Pipelined Processors
FetchTB.ms, Beveren.ms, test.py, sw/Testbenches and RISC-V test programsProvided

2Minispec you need from Lectures 6–7

Everything in this lab is written with five constructs. If any one is fuzzy, the pipeline code will not read correctly.

ConstructMeaning in hardwareWhere 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
ruleCombinational 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 = vA 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 mA 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
The one idea that makes the pipeline rule readableInside a rule, a register read always sees the old value, and a variable sees whatever was assigned above it in the text. So when 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

A rule does 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.

Why are 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.

What happens to cache.req in a cycle where the rule does not assign it?

It takes its declared default, Invalid, so the cache sees no request.

3The single-cycle core (Lecture 11, Lab 4)

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:

4Cache addressing (Lectures 12–13)

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.

Try it

Split any address the way your helpers do

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.

Sub-word loads and stores

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

How many bits are tag, index, word offset and byte offset, and why?

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.

On a dirty eviction, how does the cache know the address to write the old line back to?

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.

Why does 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.

5The cache state machine (Lab 5)

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.

PathStatesMain-memory requests
HitReady → Lookup → ReadyNone
Miss, victim clean or not validReady → Lookup → Fill → ReadyOne read
Miss, victim dirtyReady → Lookup → Writeback → Fill → ReadyOne 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.

Flow

Set 0 while cache.S stores and loads at 0x4000 and 0x6000

Ready: latch the request and read the arrays

All 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.

Lookup: compare, then hit or start a miss

Writeback and Fill

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.

Why the miss penalty is about 33 cyclesMainMemory 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.

The data method: answer as early as possible

The 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

Why is 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.

How many cycles from request to data for a load hit? For a clean miss?

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.

On a store miss, why read the line from memory at all?

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.

What would go wrong if 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.

6Two-way cache and LRU

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-mappedYour code
Arrays become vectors of twoVector#(2, SRAM#(logCacheSets, Line)) dataArrays; (same for tags and status)
One LRU bit per set, held in registersVector#(cacheSets, RegU#(Bit#(1))) lru;
Hit is per wayfunction Bool isHit(Integer way)
Remember the victim across Writeback and FillReg#(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.

Back-to-back load hits

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.

What Beveren measures

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

Both ways valid, 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.

Why can a load hit overlap with the next request but a store hit cannot?

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.

Why is 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.

Why keep LRU bits in registers and not an SRAM?

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.

7The pipeline in one rule (Lecture 14)

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.

StageState it starts fromWorkState it writes
Fetchpc, fetch.inChoose next PC, send it to the iCachepc, iCache SRAM lookup
Decodepc + iCache.data (f2d)decode, read register file, apply bypasses, detect hazardsd2e
Executed2eexecute, send dCache request, resolve branchese2w
Writebacke2w + dCache.dataPick ALU or load data, write the register filerf, 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.

Order inside rule tick

The rule is written writeback, execute, decode, then fetch control. Each block defines wires that the blocks below it read.

BlockWires it producesRead by
WritebackdstW, dataW, dDataStallDecode (bypass), Execute and Decode (freeze)
ExecutedstE, dataE, annul, redirectPc, dReqStallDecode (bypass, kill), Fetch (redirect)
DecodehazardStallFetch (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.

Flow

Your pipeline on four short programs, one column per clock cycle

8Data hazards: bypass and stall (Lecture 15)

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.

The whole policy in one table

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.

ProducerProducer is in executeProducer is in writebackProducer has left the pipeline
ALU-type (add, addi, lui, jal link…)Forward from execute. 0 cycles lostForward from writeback. 0 cycles lostRead the register file
Load, cache hitWait 1 cycle. The value does not exist yetForward from writeback. 0 cycles lostRead the register file
Load, cache missWait 1 cycleWhole pipeline waits until the line arrivesRead the register file

The general rule: forward if the value exists anywhere, wait only if it does not exist yet.

Where values exist

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.

Decode picks the newest value

The only data stall with warm caches: load then use

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.

Two instructions ahead both write 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.

Why does 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.

A store is in execute. Can it trigger a bypass or hazard stall in decode?

No. Its dst is Invalid, so dstE is 0 and no source comparison passes.

9Control hazards: annul and redirect

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.

The penalty is one cycleWhen the branch is in execute, exactly one wrong-path instruction exists, the one in decode. The target is requested in that same cycle and reaches decode in the next. See the Jump chain diagram in section 7: each 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

Why is a not-taken branch free in this design?

Fetch already guessed pc + 4, which is correct for a not-taken branch. redirect stays false and nothing is annulled.

Why is it enough to invalidate 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.

A loop branch is taken 99 times out of 100. How many cycles does it waste?

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.

10The Fetch module and ignoreInstr

Fetch is its own module so the testbench can drive it alone. The processor tells it one of three things each cycle.

FetchActionMeaningnextPc
DequeueDecode consumed the instruction at f2dpc + 4
StallDecode did not consume it, or there was nonepc
RedirectDiscard whatever is fetched and go elsewherein.redirectPc

Why ignoreInstr exists

Suppose 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.

CycleiCachefetch.inpc afterignoreInstr afterf2d
tFill for A, not reqEnabledRedirect BBTrueInvalid
t+1 … t+k−1Still filling AStallBTrueInvalid
t+kReturns inst at A, validStallBTrueInvalid, masked by ignoreInstr
t+k+1Ready, accepts request for BStallBFalseInvalid
t+k+2Lookup for BDequeueB+4FalseValid, 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

Why does fetch request 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.

The processor sends 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.

Why is !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.

With a direct-mapped iCache, what would the fetch rate be on hits?

One instruction every two cycles. reqEnabled is false during Lookup, so after each hit there is a cycle where no request goes out.

11Cache-induced stalls

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.

EventFetchDecodeExecuteWritebackBubble enters
Normal cycleadvancesadvancesadvancescompletesnone
iCache misswaits for the lineemptyadvancescompletesexecute
Load-use (hazardStall)holdsholdsadvancescompletesexecute
Taken branch (annul)redirectedkilledadvancescompletesexecute
dCache busy (dReqStall)holdsholdsholdscompleteswriteback
Load data missing (dDataStall)holdsholdsholdsholdsnone

With real caches the data memory can be slow in two different places, and each needs its own stall.

SignalRaised inConditionEffect
dReqStallExecuteA load or store wants to send a request but dCache.reqEnabled is falseInstruction stays in d2e, e2w gets a bubble, decode and fetch hold
dDataStallWritebackA load is in e2w and dCache.data is not validWhole 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.

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.

MMIO goes through the same requestThe data cache is declared as 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

A load misses. Which stall signal is high for most of the miss, and which stages are frozen?

dDataStall. The load sits in e2w. Execute and decode are guarded off and fetch receives Stall, so all four stages hold.

A store misses and the next instruction is an 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.

Why must 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.

Why is 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.

12How the lab is tested

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
Both main memories load the same mem.vmh, so the instruction and data caches see one program image.
CommandWhat runsWhat it proves
make test_fetch && ./test_fetchFetchTB.ms drives Fetch alone with random actions and checks every f2d against a reference memoryFour stages of difficulty: no stalls, stalls, annuls, both
make test_DirectMappedBeverenRandom loads and stores against the direct-mapped cacheCorrect data, exact hit and miss counts, cycle bound
make test_TwoWayBeverenSame against the two-way cacheAlso proves LRU: counts must be 49,646 and 50,379
make test_CacheTesterPrimerYour own request list and expected responsesTargeted cache scenarios
make prog_test aAll microtests, one instruction type eachDecode and execute still correct inside the pipeline
make prog_test pThe four pipeline testsHazard handling
make prog_test fFull assembly tests including cache.S and bpred_*Whole-program behaviour, self-checking through MMIO
make prog_test s1sort_base benchmarkCycle count for the performance grade
make synthSynthesis of Processor.msClock period

How a micro or pipeline test ends

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 testProgram shapeFails if
01_no_hazardsIndependent instructionsBasic stage hand-off is wrong
02_all_data_hazardsChained addi x1,x1,±1, then chained lw x1,0(x1) through a pointer table at 0x100A bypass is missing or stale, or load-use does not stall. Expected x1 = 0x110, pc = 0x44
03_all_control_hazardsj a; unimp; a: j b; unimp; …A wrong-path unimp survives annulment and ends the test early
04_all_hazardsaddi, addi, lw x2, jr x2A jump target that comes from a load through a stall and bypass is wrong

Your discussion-question program

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.

Debugging aid already in the file

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

Why does 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.

Beveren says data is correct but the hit count is wrong for the two-way cache. Where do you look?

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.

Beveren says counts are right but it took too many cycles. What is the usual cause?

An extra main-memory request, such as writing back a clean line, or a data method that waits a cycle before answering.

How does a full assembly test report failure without a register dump?

It stores a test number to 0x4000_1000. CacheWrapper sees the Sw, prints FAILED n or PASSED for zero, and ends the simulation.

13Performance accounting

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.

CounterCounts cycles whereHow to reduce it
instrsAn instruction completed writebackFixed by the program
stalls_hazardDecode held for a value that did not exist yetAlready at the minimum: only load-use
annulmentsA taken branch or jump killed the instruction in decodeBranch prediction
stalls_ddataA load waited in writeback for dCache dataFewer misses: associativity, larger lines
stalls_dreqA load or store waited in execute for the dCache to be readyFaster 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.

Where Lectures 16 to 22 attach to this processor
  • L16 Operating Systems, L19 Exceptions and I/O: an exception is handled like your annulment, with the redirect target being the handler address and the faulting PC saved. The Unsupported check in writeback is the simplest version of it. The MMIO addresses in CacheWrapper are the simplest I/O device.
  • L17–18 Virtual Memory: a TLB sits in front of each cache and translates the address your getTag and getIndex slice. A TLB miss is another reason to stall.
  • L20 Synchronization, L21 Cache Coherence, L22 Parallel Processing: the comments in cache.S (I -> M, M -> I -> S) name coherence states. Your NotValid, Clean, Dirty are the single-processor version of that protocol.
Know this cold