5.3.11 · D4 · HinglishAdvanced Microarchitecture

ExercisesSpeculative execution

3,924 words18 min read↑ Read in English

5.3.11 · D4 · Hardware › Advanced Microarchitecture › Speculative execution

Yeh page ek self-test ladder hai. Har rung pehle se mushkil questions poochhti hai Speculative execution ke baare mein — "kya tum part ka naam jaante ho?" se lekar "kya tum mitigation design kar sakte ho?" tak. Solution cover karo, khud try karo, phir reveal karo.

Shuru karne se pehle, ek one-screen refresher un vocabulary words ka jo hum baar baar use karte rahenge. Agar koi word unfamiliar lage, toh yahi exercises usse drill karengi.

Hum sab kuch cycles mein measure karte hain (CPU clock ki ek tick) aur CPI mein = cycles per instruction. Jo numbers hum compute karte hain woh ===VERIFY=== mein check hote hain.


Building the penalty formula (read this first)

Neeche har exercise ek galat guess ko cycles mein price karta hai, isliye pehle hume samajhna hoga ki yeh price aata kahan se hai. Pipeline ko stages wale conveyor belt ki tarah socho; ek branch instruction belt ke door wale end ke paas ride karti hai, lekin woh instructions jo isko "gate" karti hain woh iske bilkul peeche fetch ho chuki hain aur belt pe stream kar rahi hain.

Ab hamare paas woh do quantities hain jo har exercise use karta hai: aur , wali machine par.


Level 1 — Recognition

(Kya tum pieces ko naam de aur classify kar sakte ho?)

Exercise 1.1

Har item ko architectural ya microarchitectural state mein sort karo: (a) general-purpose register rax, (b) ROB, (c) L1 data cache, (d) main memory, (e) branch-predictor counter table.

Recall Solution

Test yeh hai: kya ek normal program ise directly read kar sakta hai?

  • Architectural (program dekh sakta hai): (a) rax, (d) main memory.
  • Microarchitectural (hidden helper): (b) ROB, (c) L1 cache, (e) predictor table.

Cache wala sneaky wala hai: ek program cache ko directly read nahi kar sakta, lekin woh memory accesses ko time kar sakta hai aur infer kar sakta hai ki kya cached hai. Woh timing leak har Spectre-style side-channel attack ka seed hai.

Exercise 1.2

Speculation ke har stage ko uske purpose se match karo:

  1. Predict — 2. Checkpoint — 3. Execute — 4. Verify — 5. Commit/Squash. Purposes: (A) guessed path se instructions run karo; (B) branch outcome guess karo; (C) architectural state ko real banao ya undo karo; (D) state save karo taaki hum roll back kar sakein; (E) real branch result ko guess se compare karo.
Recall Solution

1→B, 2→D, 3→A, 4→E, 5→C. Order matters: tum execute se pehle checkpoint karte ho, kyunki tum us state par roll back nahi kar sakte jo tune kabhi save hi nahi ki.


Level 2 — Application

(Numbers ko machinery mein plug karo.)

Levels 2–3 ke liye upar ki derivation ki baseline machine use karo: pipeline depth , penalty cycles, stall cost cycles.

Exercise 2.1

Ek program branches run karta hai. Predictor accurate hai. Mispredictions par kitne cycles waste hote hain?

Recall Solution

Mispredicted branches: . Har ek cycles cost karta hai → cycles. Answer: cycles waste.

Exercise 2.2

Parent note ka loop:

for (int i = 0; i < 100; i++) sum += array[i];

i < 100 branch baar taken hoti hai aur ek baar not-taken (exit). Do alag design strategies aur unke apne stall costs consider karo:

  • (a) "in-order, drain-on-branch" — ek purane zamaane ka in-order core jo rename ya reorder nahi kar sakta, isliye har branch par isse re-steer karne se pehle poori pipeline drain karni padti hai. -stage belt drain karna per branch full pipeline depth cycles cost karta hai. (Yeh hamari modern se zyada strong stall hai: yeh machine useful work ke saath resolve bhi overlap nahi kar sakti.)
  • (b) speculation modern machine par — sirf single misprediction (loop exit) par -cycle penalty pay karo.

(a) aur (b) ke liye total stall cycles compute karo, phir ratio (a)/(b) do.

Recall Solution

Yahan 15 kyun lekin baaki jagah ? redirect ek modern out-of-order front end assume karta hai jo sirf ek quick re-steer chahta hai. (a) machine deliberately ek alag, purani design hai jo har branch par sare 15 stages drain karti hai — uske paas koi sasta redirect nahi, isliye uska per-branch stall poori depth ke barabar hai. Hum worst realistic non-speculative machine ko speculation ke against compare karte hain poora payoff dikhane ke liye. (a) stall cycles. (b) stall cycles. Ratio . Speculation yahan ~ stall cost remove karta hai kyunki loop almost perfectly predictable hai.

Exercise 2.3

Random data par ek branch (rand() % 2 == 0) time correctly predict hoti hai. Is branch ke execution par average penalty kya hai, aur yeh simply cycles (upar define ki) stall karne se kaise compare hoti hai jab tak branch resolve na ho?

Recall Solution

Expected penalty cycles per branch. Plain stall sirf cycles cost karti hai. Yahan speculation cycles average par badtar hai. 50/50 branch ke liye, na speculate karna jeetta hai.


Level 3 — Analysis

(Trade-offs aur rates ke baare mein reason karo.)

Exercise 3.1

Ek branch-heavy program har instructions mein ek branch execute karta hai. Predictor accuracy hai, penalty cycles. Mispredictions se add hone wala extra CPI (cycles per instruction) compute karo.

Recall Solution

Instructions ka fraction jo branches hain: . Un mein se mispredict karte hain. Extra cycles per instruction: Toh roughly extra cycles per instruction — real, lekin har branch par stall karne se bahut sasta.

Exercise 3.2

Usi workload ke liye do predictor designs offer ki gayi hain (har instructions mein branch):

  • Design A: accuracy , pipeline depth → penalty .
  • Design B: accuracy , pipeline depth → penalty . Kaun sa per instruction kam misprediction overhead add karta hai?
Recall Solution

Extra CPI .

  • A: CPI.
  • B: CPI. Design B jeetta hai (). Deeper pipeline (bada penalty) bahut kam miss rate se more than offset hai. Deep pipelines tab hi pay off karte hain jab predictor itna acha ho.

Exercise 3.3

Parent note speculation ko ROB ke through out-of-order execution se link karta hai. 2–3 sentences mein explain karo kyun ROB woh cheez hai jo rollback ko possible banata hai, aur kya break hota agar speculative results seedha rax mein likhe jaate.

Recall Solution

ROB speculative results ko program order mein rakhta hai lekin abhi tak commit nahi kiye — ek staging area. Misprediction par, CPU galat ROB entries discard kar deta hai; architectural registers kabhi touch nahi hue, isliye undo karne ko kuch nahi. Agar results seedha rax mein likhe jaate, ek galat guess real value ko garbage se overwrite kar deta aur restore karne ke liye koi clean copy nahi hoti — speculation program corrupt kar deta. ROB woh checkpoint hai jo computed ko committed se alag karta hai.


Level 4 — Synthesis

(Ideas ko ek security/design argument mein combine karo.)

Exercise 4.1 — The Spectre gadget

Ek malicious program ek secret byte padhna chahta hai jise padhne ki permission nahi hai. Woh neeche wala sequence use karta hai. Har step ko architectural ya microarchitectural label karo, aur explain karo kyun secret tab bhi leak hota hai jab step 3 squash ho jaata hai.

  1. Branch predictor ko "in-bounds" expect karne ki training do.
  2. Ek out-of-bounds index pass karo taaki guard branch forbidden path mein mispredict kare.
  3. Speculatively secret load karo, phir probe[secret * 256] load karo.
  4. Branch resolve hoti hai → step 3 ka sab kuch squash ho jaata hai.
  5. Attacker probe[0], probe[256], ... ke reads time karta hai dekhne ke liye kaun fast hai.
Recall Solution
  • Steps 1, 3, 5 microarchitectural state par operate karte hain (predictor + cache). Step 4 ka squash architectural state restore karta hai.
  • Leak survive karta hai kyunki squash sirf architectural effects undo karta hai (registers, memory). Woh cache line jo step 3 ne speculation ke dauran pull ki woh jaanbujh kar peeche chhodi jaati hai (yeh normal caching hai). probe[secret*256] cached rehta hai.
  • Step 5 mein attacker sare possible probe slots padhta hai; woh ek fast (cached) slot secret reveal karta hai. Neeche timing sketch dekho.

Figure — Speculative execution
Figure s02 — aath probe slots (indices 0–7) ka ek bar chart jisme vertical axis par measured access time cycles mein hai. Saat bars lavender mein 120 cycles ke paas tall khade hain (evicted, slow); index 3 par ek bar mint mein approximately 42 cycles tak girta hai (still cached, fast). Ek dashed coral "cache-hit threshold" line 70 cycles par unhe separate karti hai, aur ek coral arrow short bar par point karta hai padhte hue "fast = cached ⇒ secret is 3". Ek single fast slot ka index leaked secret value hai.

Yahi cache side channels ka poora point hai: architectural rollback ek security boundary nahi hai kyunki woh cache undo karna bhool jaata hai.

Exercise 4.2 — Kaun sa fix, aur kyun

Har mitigation ko us exact step se match karo jise woh disrupt karta hai: (A) lfence speculation barrier — (B) context switch par predictor flush karna — (C) indirect branches ke liye retpoline. Steps: (i) ek privilege boundary ke across predictor train karna; (ii) speculatively secret-dependent load issue karna; (iii) ek indirect/call *reg branch ke through speculate karna.

Recall Solution
  • A → (ii): lfence execution ko speculatively iske past proceed karne se rokta hai, isliye secret-dependent load speculation ke under kabhi issue nahi hota.
  • B → (i): contexts ke beech predictor clear karna attacker ki training ko victim mein carry hone se rokta hai.
  • C → (iii): ek retpoline ek indirect jump ko ek controlled ret-based trampoline se replace karta hai jise predictor attacker target par steer nahi kar sakta. Har fix ek alag stage attack karta hai — isliye real CPUs kai ek saath deploy karte hain.

Level 5 — Mastery

(Ek poora decision design aur defend karo.)

Exercise 5.1 — Speculate-or-stall decision rule

Woh general condition derive karo jiske under speculation stall karne ke muqable worth it hai. Hamare do quantities reuse karte hue: = predictor accuracy, = misprediction penalty (cycles, yahan), = stall cost agar hum speculate nahi karte (cycles, yahan). Phir break-even accuracy nikalo, aur batao exactly us accuracy par kya hota hai.

Recall Solution

Speculate karne ki expected cost (tum sirf tab penalty pay karte ho jab galat ho; sahi guesses cost ). Stall karne ki cost (hamesha pay karna padta hai). Speculation tab jeetti hai jab Break-even: . Tie case : yahan exactly — speculate karna aur stall karna average par same cost karte hain, isliye koi bhi behtar nahi aur choice wash hai (real designs tab security exposure se bachne ke liye stall prefer karti hain). Strictly se upar, speculate karo; strictly neeche, stall karo.

Figure — Speculative execution
Figure s03 — ek line plot jisme horizontal axis par predictor accuracy (0 se 1) aur vertical axis par expected cost in cycles per branch hai. Ek flat coral line constant stall cost par baithti hai; ek sloped lavender line trace karti hai, par se girti hui par tak. Dono lines mint-dashed break-even par milti hain, ek slate dot se mark ki hui. Crossing ke daayein mint-shaded region "speculate wins" label hai; baayein region "stalling wins" label hai.

Exercise 5.2 — Ek bura branch redesign karo

Tum ek hot branch profile karte ho: accuracy , baar execute, , aur stall karna cost karta. (a) Speculation stall karne ke muqable kitne cycles waste karta hai? (b) Do software rewrites naam batao (parent note se) aur kaho kaun sa branch entirely remove karta hai.

Recall Solution

(a) Speculate karte hue: cycles/branch → cycles. Stall karte hue: cycles. Speculation extra cycles waste karta hai. (5.1 ke saath consistent: , isliye speculation harti hai.) (b) Data sort karo taaki branch biased/predictable ho, ya branchless code likho (cmov, bitwise select). Branchless rewrite branch entirely remove karta hai, isliye mispredict karne ko kuch bachta hi nahi — yahi sabse pakka fix hai.

Exercise 5.3 — Sab kuch jodo

Ek paragraph mein, Instruction-level parallelism (ILP), superscalar width, aur speculation ko connect karo: ek wider superscalar machine ko better speculation ki zaroorat kyun hoti hai?

Recall Solution

Ek superscalar core ILP exploit karne ke liye har cycle mein kai instructions issue karta hai — lekin branches har kuch instructions mein hoti hain, isliye ek wide machine almost har cycle mein ek branch hit karta hai. Accurate speculation ke bina woh constantly stall karta, aur uske extra issue slots idle baithte (wahi hazard jisko chhupaane ke liye speculation exist karta hai). Wider issue har stall ki cost badhata hai (zyada idle slots) aur branch encounter rate badhata hai, isliye predictor accuracy ke har 1% ka payoff width ke saath badhta hai. Wide + deep machines aur strong predictors isliye inseparable hain.