Top 100 IC Design Engineer Interview Questions and Answers
The questions most likely to come up in your IC Design Engineer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.
Curated: · Written: · Reviewed: —
Q&A-1Walk me through taking a 100 MHz AXI-Lite register block from spec to tapeout, and explain why timing can pass in synthesis but fail after place and route?
The 90-second answer
I would freeze the interface first, then build RTL and verification in parallel, then close timing twice: once on the synthesized netlist and again after place and route on extracted parasitics. For a concrete case, take a 64-bit AXI-Lite slave with a 4 KB SRAM, one 100 MHz clock, and a separate reset domain. Tapeout is not one step. It is a chain of artefacts, and each stage has a check that can stop the block.
Architecture, RTL, and verification
The spec I freeze covers the register map (address, width, reset value, read and write side effects), AXI handshake behaviour, clock and reset domains, and what the block will not do. Here that means single transfers only, no bursts. Two decisions matter later. Reset is asynchronous assert and synchronous deassert in each domain, with a synchroniser on the crossing. Any signal crossing domains goes through a two-flop synchroniser for a single bit or a FIFO for a bus. A direct multi-bit crossing is a bug, not a shortcut.
// Two-flop synchroniser into the 100 MHz domain
module sync2 (
input logic clk,
input logic rst_n,
input logic src,
output logic dst
);
logic stage1_q;
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
stage1_q <= 1'b0;
dst <= 1'b0;
end else begin
stage1_q <= src;
dst <= stage1_q;
end
end
endmoduleRTL stays synthesizable: no delays, no latches, no initial blocks except where the SRAM flow allows them. Lint and CDC checks run on every commit. Verification runs alongside RTL, with directed tests for each register and each AXI error response, plus random tests if the team has them. Coverage is the contract: line and functional coverage for every CSR, every reset sequence, and reset asserted mid-transaction. That last test catches the failures a clean testbench reset hides.
Synthesis, place and route, and timing closure
Synthesis maps RTL to the standard cell library. I supply SDC constraints: create the clock, set input and output delays, and mark the synchroniser paths as false paths so STA does not chase them. At 100 MHz the period is 10 ns. After clock uncertainty and margin, about 9.5 ns remains for logic plus wire delay.
| Corner | What it models | What I check |
|---|---|---|
| SS, 0.9 V, 125 C | Slow cells, worst setup | WNS and TNS for setup |
| FF, 1.1 V, -40 C | Fast cells, worst hold | Hold slack, fixed with buffers |
| Typical | Nominal | Early warning only |
This is the mechanism behind the common surprise. Synthesis uses estimated wire delays. Place and route puts real cells in real locations, builds the clock tree, and routes real wires. After routing I extract parasitics and re-run STA. A path that passed synthesis can fail here because the wire is longer than estimated, the clock skew changed, or congestion forced a detour. That is why timing closure after place and route is the real closure. Fixing it means restructuring logic, adding a pipeline register, or moving the block in the floorplan, not editing the constraint to make the report pass.
Signoff
Signoff is a checklist: clean STA at all corners on extracted parasitics, clean DRC and LVS, antenna, IR drop, and electromigration within limits, and DFT scan chains inserted before place and route so they can be placed legally and simulated. If scan fails, the part cannot be tested in production, so it blocks tapeout even when the logic is correct. The trade-off is compute and schedule against respin risk. A flow that skips extracted STA reaches tapeout faster and can miss a wire delay failure that only appears on silicon. For a first tapeout I keep the full flow and reserve spare cells and metal tracks, so a small ECO fix does not force a full re-route.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2How do you calculate setup and hold slack in static timing analysis, and what do you do first when a path fails timing?
The 90-second answer
Static timing analysis checks every register-to-register path against the clock without simulating data. Setup asks whether data arrives in time for the next capture edge. Hold asks whether data stays stable long enough after the current capture edge. Slack is the margin on each check. Positive slack passes. Negative slack fails, and the most negative path is the critical path.
For setup, the launch flop sends data on one edge and the capture flop samples it on a later edge. Arrival time is the launch edge time plus clock-to-Q delay plus combinational delay through the logic. Required time is the capture edge time minus the capture flop setup time, adjusted for clock skew and uncertainty. Setup slack is required minus arrival.
For hold, the same launch edge must not race through to the capture flop before that flop has finished sampling the previous value. Arrival time uses the minimum clock-to-Q and minimum combinational delay. Required time is the capture edge time plus the capture flop hold time, again adjusted for skew and uncertainty. Hold slack is arrival minus required.
Worked trace
Assume a 1 GHz clock, period 1000 ps, launch edge at 0 ps, capture edge at 1000 ps for setup and at 0 ps for hold, setup time 50 ps, hold time 30 ps, and no skew or uncertainty.
| Check | Arrival calculation | Required calculation | Slack | Result |
|---|---|---|---|---|
| Setup | 0 + 80 (clock-to-Q) + 840 (logic) = 920 ps | 1000 - 50 = 950 ps | 950 - 920 = +30 ps | Pass |
| Hold | 0 + 60 (min clock-to-Q) + 120 (min logic) = 180 ps | 0 + 30 = 30 ps | 180 - 30 = +150 ps | Pass |
| Hold, fast corner | 0 + 40 + 50 = 90 ps | 0 + 30 = 30 ps | 90 - 30 = +60 ps | Pass, tighter |
Setup is normally checked at the slow corner, worst temperature and voltage, because delays are largest there. Hold is checked at the fast corner, because delays are smallest there and data can arrive too early. A path can pass setup at slow corner and fail hold at fast corner, which is why both checks run on every corner.
# SDC excerpt: define the clock STA checks against
create_clock -name clk -period 1.0 [get_ports clk]
set_clock_uncertainty -setup 0.05 [get_clocks clk]
set_clock_uncertainty -hold 0.02 [get_clocks clk]
report_timing -setup -max_paths 10
report_timing -hold -max_paths 10Closing a failing path
First, read the timing report for the failing path. Note the startpoint, endpoint, slack, and which cells and nets dominate the delay. Check the constraints before touching the design. A false path or a multicycle path that was never constrained will report a violation that synthesis and place-and-route will also chase, wasting effort. Confirm the clock period, uncertainty, and any clock skew assumptions match the intended design.
Then fix the check that failed, because setup and hold fixes pull in opposite directions.
| Failure | First fixes | What to avoid |
|---|---|---|
| Setup, negative slack | Upsize or swap to a faster cell on the long path, reduce fanout, restructure logic to shorten depth, move flops closer, use a lower threshold voltage cell if the library allows it, pipeline the logic if the architecture permits | Adding delay, which makes setup worse |
| Hold, negative slack | Insert buffers or delay cells on the short path, swap to a slower cell, move flops apart, reduce clock skew in the direction that helps hold | Upsizing cells, which makes the path faster and hold worse |
For setup, sizing and restructuring usually close a small violation of a few tens of picoseconds. A large violation, say more than 10% of the clock period, points at architecture. Pipelining, splitting a wide datapath, or moving work to a different clock domain is the real fix, and it needs a design change rather than a cell swap.
For hold, the fix is almost always to slow the path down. Hold violations often appear after a setup fix upsized cells or after clock tree synthesis balanced skew, so recheck hold after every setup-driven change.
Timing closure is done when setup and hold slack are positive on every corner, mode, and voltage-temperature combination the product must meet, with margin left for silicon variation that the corner models do not cover.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3How do setup and hold violations differ, why can't slowing the clock fix a hold violation, and how would you fix each one?
The 90-second answer
Setup and hold check opposite ends of the same launch-to-capture path. Setup asks whether data arrives early enough to be captured at the next clock edge. Hold asks whether data stays stable long enough after the current clock edge that launched it. Slowing the clock lengthens the period, so it gives setup more time. It does nothing for hold, because the launch edge and the capture edge in a hold check are the same edge. The interval between them is clock skew, not the period.
For a single-cycle path, with skew defined as capture clock delay minus launch clock delay:
setup slack = period + skew - (tCQ + tcomb + tsetup)
hold slack = (tCQ + tcomb) - thold - skewSetup slack must be >= 0. Hold slack must be >= 0. Period appears only in the first equation.
Worked numbers
Hypothetical 1 GHz design, period 1000 ps. Two different paths in the same block:
| Path | Corner | tCQ + tcomb (ps) | tsetup / thold (ps) | Skew (ps) | Slack (ps) | Result |
|---|---|---|---|---|---|---|
| Long logic path | Slow, low V, high T | 1010 | 40 setup | -30 | 1000 - 30 - 1010 = -40 | Setup fail |
| Short bypass path | Fast, high V, low T | 55 | 50 hold | 15 | 55 - 50 - 15 = -10 | Hold fail |
The long path fails setup because combinational delay plus clock-to-Q eats the whole period, and the capture clock arrives 30 ps early relative to launch. The short path fails hold because it is too fast. Data changes 55 ps after launch, but the capture flip-flop needs the old data to remain stable until 50 ps after its clock edge, which arrives 15 ps late due to skew. It captures the new value one cycle early. That is a functional bug even at arbitrarily low frequency.
Why slowing the clock cannot fix hold
Drop the frequency to 100 MHz and the period becomes 10000 ps. Setup slack for the long path becomes 8960 ps. Hold slack for the short path stays at -10 ps. The launch and capture edges move together. Only skew, minimum clock-to-Q, minimum combinational delay, and hold time matter. This is why hold failures survive a clock divider in the lab and why they often appear only after an ECO shortens a path, a scan mux is bypassed, or clock gating changes skew.
Corners also differ. Setup is worst at slow process, low voltage, and high temperature, where delays are largest. Hold is worst at fast process, high voltage, and low temperature, where delays are smallest, plus on-chip variation that makes launch and capture clocks diverge. A path clean at nominal can fail hold at the fast corner and setup at the slow corner in the same STA run.
Fixes
Setup fixes attack the long path. Reduce logic depth or split it with a pipeline register so no stage exceeds the period. Optimize the critical path first: larger drive strength on high-fanout nets, upsizing, threshold voltage swaps, and placement to shorten wires. Reduce negative skew or add positive skew to the capture clock where clock power allows. Lower clock uncertainty and jitter budget if the source allows it. In constraints, this shows up as a real period and uncertainty budget:
create_clock -name core_clk -period 1.0 [get_ports clk]
set_clock_uncertainty 0.05 [get_clocks core_clk]
# setup ECO: pipeline or resize the -40 ps path, do not just relax the clockHold fixes attack the short path by making it slower, not faster. Insert delay or lockup buffers on the fast path until hold slack is positive at the fast corner, as in the example above where 30 ps of buffering moves slack from -10 ps to +20 ps. Reduce positive skew on the capture clock or increase launch delay. Fix the root cause when a mux, clock gate, or ECO created an unintended shortcut, and recheck scan shift mode, where hold checks run with a different clock and often fail first. Never fix hold by slowing the clock, adding a false path, or multicycle exception unless the design truly guarantees the data is not sampled that cycle. Those exceptions hide the early capture and move the failure into silicon.
In an interview I would close by naming the STA report I would ask for: worst setup path and worst hold path per corner and mode, with launch and capture clock delays, OCV derates, and clock uncertainty shown separately. If those numbers are not in the report, the slack number alone is not enough to choose a fix.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Why can't you cross a 32-bit bus with a two-flop synchronizer on each bit, and how does an asynchronous FIFO with Gray-coded pointers solve it?
The 90-second answer
A two-flop synchronizer per bit does not make a multi-bit bus safe. Each bit can resolve in a different destination cycle because routing delays differ, so the destination can capture half the old word and half the new word. That is incoherence, and extra flops do not fix it.
For a streaming bus I use an asynchronous FIFO. Data is written into dual-port memory in the source domain and read in the destination domain. Only the read and write pointers cross domains, and they cross as Gray code through two-flop synchronizers. Gray code changes by one bit per increment, so a pointer sampled while it is changing is either the old count or the new count, never a mixture of bits.
Metastability
If asynchronous data changes inside the setup or hold window of a flip-flop, the flop can go metastable. Its output is neither a clean 0 nor a clean 1 for a short time, then it resolves to one of them. The chance of a failure falls exponentially with the time allowed to resolve:
MTBF = exp(t_r / tau) / (T0 * f_clk * f_data)t_r is the resolution time given to the first flop, tau and T0 come from the standard cell library for that flop, and f_clk and f_data are the clock and data rates. With hypothetical library figures tau = 0.1 ns, T0 = 0.01 ns, f_clk = 100 MHz, f_data = 10 MHz, and t_r = 10 ns (one destination period), the exponent is 100. A second flop therefore makes a single-bit failure negligible in practice. It adds two destination cycles of latency. It does not make 32 bits arrive together.
A synchronizer is two flops in series, no logic between them, with the first flop sampling the asynchronous signal and the second flop sampling the first. Only the second output is used downstream.
Why Gray code matters for the pointers
Binary pointers can change in several bits at once. A count from 7 (0111) to 8 (1000) flips four bits. If those bits are skewed, the synchronized value can be any mixture, such as 0100 or 1111, and full or empty will be wrong.
Gray code changes one bit per step:
| Count | Binary | Gray |
|---|---|---|
| 7 | 0111 | 0100 |
| 8 | 1000 | 1100 |
| 9 | 1001 | 1101 |
From 7 to 8 only the most significant bit changes. A skewed sample is 7 or 8. The FIFO may think it is one entry emptier or fuller than it really is for a cycle. That is safe. It will not overwrite unread data or read empty memory, provided full and empty are computed conservatively from the synchronized pointers.
The FIFO structure
// Gray pointer synchronized into the destination domain
module gray_sync #(parameter PTR_WIDTH = 4) (
input logic clk_dst,
input logic rst_n_dst,
input logic [PTR_WIDTH-1:0] gray_async,
output logic [PTR_WIDTH-1:0] gray_sync_out
);
logic [PTR_WIDTH-1:0] stage1;
always_ff @(posedge clk_dst or negedge rst_n_dst) begin
if (!rst_n_dst) begin
stage1 <= '0;
gray_sync_out <= '0;
end else begin
stage1 <= gray_async;
gray_sync_out <= stage1;
end
end
endmoduleThe write pointer is converted to Gray code in the source domain, synchronized into the destination domain, converted back to binary, and used to compute empty. The read pointer travels the other way to compute full. The memory itself is dual port, so the two clocks never drive the same storage element at the same time.
When not to use a FIFO
For a single control bit, a two-flop synchronizer is the right answer. For a 32-bit configuration register that changes rarely, a toggle handshake is cheaper: the source holds the bus stable, toggles a request, the destination synchronizes the toggle, samples the bus, and toggles an acknowledge. That costs several cycles per word and cannot sustain a stream. The FIFO costs memory area and pointer latency, but it sustains one word per clock on each side once it is primed, which is what a 100 MHz source feeding a 125 MHz destination needs.
Two checks I would run before tapeout: CDC lint to confirm the only crossings are the Gray pointers and the memory read path, and a test with simultaneous read and write at full and empty boundaries to confirm the FIFO never overflows or underflows.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5A two-flop synchronizer samples a 10 MHz async signal at 100 MHz. How would you estimate its MTBF, and what happens if the clock rises to 200 MHz?
The 90-second answer
I would start from the probability that the first flop is still unresolved when the second flop samples it. That probability falls exponentially with the time allowed for resolution, $t_r$, divided by the flop time constant, $\tau$:
$$ \mathrm{MTBF} = \frac{\exp(t_r/\tau)}{T_0 \cdot f_{clk} \cdot f_{data}} $$
$f_{clk}$ is the destination clock, $f_{data}$ is how often the asynchronous input actually changes, and $T_0$ is the aperture constant. $\tau$ and $T_0$ are properties of the flop cell at the chosen voltage and corner, taken from the vendor data or SPICE. For a two-flop chain, $t_r$ is close to one clock period minus clock-to-Q, setup time, skew and jitter. For a single flop it is only the small setup margin, which is why the second flop matters so much.
Worked example
Use hypothetical but plausible figures for a 28 nm flop at nominal voltage: $\tau = 35\ \mathrm{ps}$, $T_0 = 15\ \mathrm{ps}$, $f_{data} = 10\ \mathrm{MHz}$. At $f_{clk} = 100\ \mathrm{MHz}$ the period is 10 ns. Assume $t_r = 9.0\ \mathrm{ns}$ for the two-flop chain after overhead, and $t_r = 4.0\ \mathrm{ns}$ if the clock rises to 200 MHz and the period halves.
import math
tau, T0 = 35e-12, 15e-12
f_data = 10e6
for f_clk, tr in [(100e6, 9.0e-9), (200e6, 4.0e-9)]:
mtbf_s = math.exp(tr / tau) / (T0 * f_clk * f_data)
print(f_clk/1e6, f"{mtbf_s:.3g} s")| Clock | $t_r$ | $t_r/\tau$ | MTBF |
|---|---|---|---|
| 100 MHz | 9.0 ns | 257 | $\sim 10^{107}$ s |
| 200 MHz | 4.0 ns | 114 | $\sim 10^{45}$ s |
Both numbers are far beyond the life of the product, so in practice other failure mechanisms would dominate. The point of the comparison is the direction and size of the change. Doubling the clock cut MTBF by about 62 orders of magnitude.
Why the clock effect is mostly exponential
Raising $f_{clk}$ appears twice. In the denominator it doubles the sampling rate, which by itself would halve MTBF. It also halves the period, so $t_r$ shrinks. That change sits in the exponent. Losing 5 ns of resolution time divides MTBF by $\exp(5\ \mathrm{ns} / 35\ \mathrm{ps})$, roughly $10^{62}$. The linear term is negligible next to that. This is the main trap in the calculation: treating a faster clock as a modest linear penalty when it actually removes resolution time.
Resolution time is therefore the design lever. Each extra $\tau$ of $t_r$ multiplies MTBF by $e$, about 2.72. Each extra 350 ps here, which is 10$\tau$, multiplies it by about $2.2 \times 10^4$. Adding a third flop adds roughly another full period of $t_r$ and buys a similar exponential factor, at the cost of latency. Jitter and skew subtract directly from $t_r$, so the worst-case values belong in the estimate, not the average period.
Process and voltage
Process parameters enter through $\tau$ and $T_0$. A stronger flop with higher drive current and lower threshold voltage regenerates faster, so $\tau$ falls and the aperture narrows. Lowering supply voltage, especially toward threshold, slows the regenerative pair and $\tau$ rises sharply. Slow process corner and high temperature push the same way. The worst case for MTBF is therefore usually low voltage, slow corner, high temperature, and it can be orders of magnitude worse than the nominal number above. $f_{data}$ also matters linearly: a line toggling at 10 MHz presents ten times as many chances to hit the aperture as the same line toggling at 1 MHz.
Limits of the model
The formula assumes input transitions are uniformly distributed against the clock. It does not make a multi-bit bus safe, because different bits can resolve in different cycles and the bus can be sampled incoherently. That needs Gray coding or a handshake. It also does not fix a pulse narrower than the destination period, and it does not cover reset recovery violations. In layout and synthesis I would keep the first flop driving only the second flop, with no combinational logic or fanout between them, and mark the pair so tools do not retime or optimise it away.
Given a real design I would ask for $\tau$ and $T_0$ at the worst corner, the measured $f_{data}$, and the jitter budget before quoting an MTBF. Without those, the number is only illustrative.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Why is reset asserted asynchronously but deasserted synchronously through a two-flop synchronizer in each clock domain?
The 90-second answer
Reset is asserted asynchronously and deasserted synchronously through a two-flop synchronizer in each clock domain. Asynchronous assertion means the reset takes effect immediately, even if the clock is stopped. Synchronous deassertion means the release is sampled by the domain clock, so flops do not see a reset edge close to a clock edge.
The two flops handle metastability on release. When the common reset goes high near a clock edge, the first flop can go metastable. The second flop gives it another clock cycle to resolve before the reset reaches the logic. The cost is two cycles of latency on release, which reset sequencing already allows for.
// One instance per clock domain
module reset_sync (
input logic clk,
input logic async_rst_n,
output logic rst_n
);
logic [1:0] sync;
always_ff @(posedge clk or negedge async_rst_n) begin
if (!async_rst_n)
sync <= 2'b00;
else
sync <= {sync[0], 1'b1};
end
assign rst_n = sync[1];
endmoduleTrace for a domain clock period of 10 ns, with reset released just before a clock edge:
| Time | async_rst_n | clk edge | sync[1:0] | rst_n | Domain state |
|---|---|---|---|---|---|
| 0 ns | 0 | none | 00 | 0 | In reset |
| 5 ns | 1 | none | 00 | 0 | Still in reset, waiting for clock |
| 10 ns | 1 | rising | 01 | 0 | First flop samples release |
| 20 ns | 1 | rising | 11 | 1 | Second flop releases domain |
Assertion is immediate because negedge async_rst_n is in the sensitivity list. Both flops clear at 0 ns without a clock edge. Deassertion takes two edges because the value propagates through the shift register.
In a multi-domain chip, each domain gets its own instance. The common asynchronous reset fans out to every synchronizer. Each synchronizer uses its local clock, so a domain with a gated clock stays in reset until that clock runs. That is the sequencing rule: release a domain only after its power rail is good and its clock is stable.
| Property | Assertion | Deassertion |
|---|---|---|
| Timing | Asynchronous, immediate | Synchronous, after two local clock edges |
| Clock needed | No | Yes |
| Main risk handled | Clock stopped or supply collapsing | Metastability and recovery violation |
A single flop would pass a metastable value to the domain on the first edge after release. Two flops are the standard fix, and they are also what STA checks for recovery and removal timing on the reset pins.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Compare clock gating and power gating for a microcontroller block, and what isolation and retention do you need before you power it down?
The 90-second answer
Clock gating stops the clock reaching idle logic. It removes dynamic power only. Leakage in the transistors stays, because the supply stays on. Power gating cuts the supply to a whole domain with header or footer switches. It removes dynamic and leakage, at the cost of losing state unless you retain it, plus wake-up time and inrush current.
I would use clock gating everywhere by default, and reserve power gating for blocks that sit idle for milliseconds or longer, such as a radio, a flash controller, or a peripheral bus that a microcontroller only wakes for a transfer. If a block wakes every few microseconds, the energy spent recharging its supply and restoring state can exceed the leakage saved.
| Clock gating | Power gating | |
|---|---|---|
| Power saved | Dynamic: P = alpha * C * V^2 * f. No clock edges, no switching. | Dynamic plus static: Pstatic = V * Ileak also goes to near zero when the rail collapses. |
| State | Preserved. Flip-flops hold data. | Lost unless retention flops, retention SRAM, or save and restore is added. |
| Wake-up | One cycle, or a few cycles for the gated clock to re-enable cleanly. | Microseconds to milliseconds: ramp the rail, restore state, re-synchronise clocks and resets. |
| Main risks | Glitches on the gated clock, extra timing paths, test and debug difficulty. | IR drop and inrush on wake-up, X-propagation across the boundary, floating inputs back-powering the domain. |
| Verification | Clock gating checks, timing with gated clocks, DFT for gated clocks. | Power intent in UPF or CPF, power-aware simulation, isolation and retention checks, wake-up sequencing. |
Worked figures
Take a hypothetical peripheral block at 1.0 V, 100 MHz, drawing 8 mW dynamic and 2 mW leakage when active. Idle 95% of the time.
Clock gating at 95% effectiveness on the idle period leaves dynamic at roughly 0.4 mW average, but leakage stays at 2 mW. Average is about 2.4 mW.
Power gating the same block, with a wake-up cost of 20 uJ per wake and 100 wakes per second, adds 2 mW of wake energy. That wipes out the saving. At 10 wakes per second the cost is 0.2 mW and average power drops to roughly 0.2 mW plus the small residual leakage through the switches. The break-even idle time is wake energy divided by leakage saved: 20 uJ / 2 mW = 10 ms. Below that, do not power gate.
Isolation
Every signal crossing from an always-on domain into a gated domain, and back, needs a defined state when the gated rail is off.
Outputs from the gated domain must pass through isolation cells, usually level shifters with an enable, so they drive a known value, typically 0, into the always-on logic. Without them the always-on flops sample X or a floating value, and that X can propagate into firmware-visible state.
Inputs into the gated domain need isolation or always-on buffers as well. A live input driving a powered-down flop can back-power the domain through ESD diodes, partially turn on transistors, and corrupt retention or cause excess current. The same applies to bidirectional pads and bus keepers.
Clocks and resets crossing the boundary need special care. A gated clock must be glitch-free, usually generated with a latch-based clock gate so the enable changes only while the clock is low. Resets into the domain should be asserted by the always-on side and held until the rail is stable, otherwise flops come up in an unknown state.
# Power intent for one gated peripheral domain
create_supply_set PD_PERIPH -function {power VDD_PERIPH} \
-function {ground VSS} -function {retention VDD_RET}
create_power_switch PS_PERIPH -domain PD_PERIPH \
-input_supply_set {power VDD_AON} -output_supply_set {power VDD_PERIPH}
set_isolation iso_out -domain PD_PERIPH -isolation_signal en_iso \
-isolation_supply_set VDD_AON -clamp_value 0
set_isolation iso_in -domain PD_PERIPH -isolation_signal en_iso \
-isolation_supply_set VDD_AON -clamp_value 0
set_retention ret_flops -domain PD_PERIPH -retention_supply_set VDD_RET \
-save_signal save_ret -restore_signal restore_retRetention
Retention is a spectrum, and the choice drives area and leakage.
Always-on flops for a small control register file cost area but wake instantly. Retention flops keep their value on a separate low-voltage rail, often 0.5 to 0.7 V for SRAM-like retention, and need that rail guaranteed during power-down. Retention SRAM keeps contents but not the address decoder state, so pointers and valid bits still need saving.
For larger state, such as a 32 KB SRAM, save and restore to a small always-on buffer or to flash may be cheaper than retention voltage on the whole array. That adds firmware or hardware sequencing, and the restore path must be verified, because a partially restored SRAM that reports valid data is worse than a cleanly invalidated one.
Failure modes I check in review
Inrush and IR drop on wake-up: turning on a large domain at once can droop the shared rail and cause timing failures in neighbouring always-on logic. Stagger the switches or size them for the peak current, and check the droop in transient simulation.
Uncontrolled wake-up order: if firmware releases a reset or enables a clock before the rail crosses the retention voltage, flops can capture garbage. The power controller should sequence rail good, then reset release, then clock enable.
Simulation that ignores power: RTL simulation will happily pass while silicon fails on X-propagation. Power-aware simulation with the UPF, plus formal checks that isolation and retention signals are correctly connected, catches most of this before tape-out.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8A peripheral block is idle 99% of the time but must retain its state. How do clock gating and power gating differ in the power they save, and which would you choose?
The 90-second answer
Clock gating and power gating attack different parts of the power budget. Clock gating stops the clock to idle registers, so it removes dynamic power from that block while leakage continues. Power gating disconnects the supply to the block, so it removes leakage as well as dynamic power, but the logic loses state unless retention is added. For a block that is idle 99% of the time and must keep its state, I would start with clock gating, measure the remaining sleep current, and move to power gating with retention flops only if leakage still breaks the budget.
Dynamic power is paid when nodes switch:
Pdyn = alpha * C * Vdd^2 * f
Here alpha is activity factor, C is switched capacitance, Vdd is supply voltage and f is clock frequency. Voltage appears squared, so a small voltage reduction saves more dynamic power than the same percentage frequency reduction. Leakage is paid whenever the supply is on. Subthreshold leakage flows through a nominally off transistor and rises exponentially with temperature and with lower threshold voltage. Gate leakage flows through the gate oxide and rises with voltage. In sleep, with f effectively zero for the gated block, leakage is the remaining term.
Worked example, hypothetical figures
Take a peripheral block with alpha*C = 0.2 nF, running at 100 MHz and 0.90 V when active. Its dynamic power is 0.2e-9 * 0.81 * 1e8 = 16.2 mW. Suppose its leakage at 25 C is 1.5 mW and at 85 C is 6 mW. With clock gating in idle, dynamic power falls to near zero for that block, but the 1.5 mW to 6 mW leakage remains. If the whole sensor hub has a sleep budget of 2 mW at 85 C, clock gating alone fails. Power gating can cut the block leakage to the leakage of the power switch and any retention flops, perhaps 0.2 mW in this example, at the cost of retention area and a wake up delay while the virtual rail recharges.
| Clock gating | Power gating | |
|---|---|---|
| Dynamic power in idle | Removed for gated registers | Removed |
| Leakage in idle | Unchanged | Removed except switch and retention flops |
| State retention | Kept, supply stays on | Lost unless retention flops or SRAM are used |
| Wake up | Next clock edge, after enable setup | Rail ramp, isolation release, then clock, often microseconds |
| Main risks | Glitch on gated clock, enable timing | Inrush current, floating outputs, level shifting at domain boundary |
How each is implemented
Clock gating uses an integrated clock gating cell. The enable is latched on the opposite clock phase so the gated clock has no glitch, and the enable must meet setup to the clock. It is cheap in area and has no state cost. Its limit is clear. It does nothing for leakage, and combinational logic downstream of gated registers can still toggle if inputs change, so operand isolation may also be needed.
Power gating inserts a header PMOS switch or a footer NMOS switch between the real supply and a virtual rail for the block. The switch is sized large so the voltage drop in active mode stays small. When the block sleeps, the controller turns the switch off. Three details decide whether this works in a real SoC. First, outputs to always on logic need isolation cells, otherwise a floating output can drive a gate into a crowbar state. Second, inputs from a different voltage domain need level shifters. Third, waking a large block at once causes inrush current and supply droop, so the rail is brought up in stages or the block is woken before the deadline that depends on it.
Retention flops keep state on a separate always on supply or on a retention rail. They cost area and they leak, but far less than keeping the whole block powered. Multi-Vt placement helps the same budget from the other side. High threshold transistors leak much less than low threshold devices of the same size, so non critical paths should use them and low threshold devices should be reserved for paths that need the speed.
For the stated block, my choice depends on the measured split. If leakage at the worst temperature is a small fraction of the sleep budget, clock gating is the right answer because it keeps state for free and wakes instantly. If leakage dominates, as it does in the example at 85 C, I would power gate with retention flops, budget the wake up time in the power state machine, and verify isolation and inrush in simulation before tapeout.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9How does dynamic voltage and frequency scaling work, and how would you choose voltage-frequency operating points for a microcontroller SoC?
The 90-second answer
DVFS trades performance for energy by moving a core between discrete voltage-frequency operating points, called OPPs. Raising voltage raises speed because gate delay falls as the overdrive (Vdd - Vth) grows. Raising frequency raises dynamic power roughly as Vdd squared times f, so voltage is the expensive knob. A DVFS controller watches utilisation, temperature and sometimes workload type, then asks the voltage regulator and clock generator to step to a higher or lower OPP. The step must be sequenced, voltage first on the way up and frequency first on the way down, or the core runs at a frequency its transistors cannot sustain at the old voltage.
Why voltage dominates
For a CMOS gate, a useful first-order model is:
Delay ∝ C_load * Vdd / (Vdd - Vth)^alpha , alpha ≈ 1.3 to 2
P_dynamic = alpha_activity * C * Vdd^2 * f
P_leakage ≈ Vdd * I_leak(Vdd, T, process) # I_leak rises steeply with Vdd and TAt Vdd close to Vth, a small voltage increase buys a large delay reduction. Well above Vth, delay improves slowly while P_dynamic keeps growing quadratically. That is why the top OPP costs so much energy per cycle and why DVFS tables are steep at the top end.
Worked example, hypothetical but labelled as such. Take a microcontroller core with Vth ≈ 0.35 V, normalised to OPP 1:
| OPP | Vdd (V) | f (MHz) | Vdd^2 * f (relative) | Relative P_dynamic | Typical use |
|---|---|---|---|---|---|
| 1 | 0.75 | 48 | 27.0 | 1.0x | Sleep-adjacent sensing, UART/SPI at low rate |
| 2 | 0.90 | 96 | 77.8 | 2.9x | Normal processing |
| 3 | 1.05 | 144 | 158.8 | 5.9x | Burst processing, crypto |
| 4 | 1.20 | 192 | 276.5 | 10.2x | Peak, short bursts only |
Doubling frequency from 48 to 96 MHz while raising voltage from 0.75 to 0.90 V costs 2.9x dynamic power, not 2x. Going to 192 MHz costs over 10x. Energy per task can still fall at a higher OPP if the task finishes sooner and the block then power-gates, which is the race-to-idle argument. It fails when leakage during the burst, regulator inefficiency at high current, or thermal limits eat the saving.
Choosing the operating points
I build the table from silicon data, not from the datasheet headline frequency. Characterise fmax versus Vdd across process, voltage and temperature corners, including the slow-cold corner where mobility falls and the fast-hot corner where leakage peaks. Add timing margin, typically 10 to 15 percent on the critical path at each OPP, and verify with static timing analysis at that exact voltage. The lowest OPP is usually set by SRAM retention and analogue blocks, not by logic. SRAM often needs 0.70 to 0.80 V to retain state in a modern low-power process, so logic cannot scale below that unless the SRAM is power-gated or uses assist circuits.
Then I check the system constraints. Regulator efficiency at the current each OPP draws, transition time (a buck converter may need 50 to 500 microseconds to settle, so OPP changes cannot track cycle-by-cycle load), and voltage droop under a sudden activity spike. A droop that pulls Vdd 80 mV below target at OPP 4 can cause a timing failure that never appears in a quiet test. I also add hysteresis in the policy so the controller does not oscillate between OPPs every few milliseconds.
Failure modes I look for: a frequency step before voltage settles on the way up, which shows up as rare crashes only under load; a low OPP that passes logic timing but corrupts SRAM at cold; and a policy that picks the top OPP for a sustained workload and then throttles thermally, giving worse average performance than a slightly lower sustained OPP. The fix in each case is the same discipline: measure fmax versus Vdd on real silicon, sequence transitions correctly, and keep the top OPP for bursts the thermal and power budget can actually sustain.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10How do you write SDC constraints for a clock, input and output delays, false paths, and multicycle paths, and what does each one tell the timer?
The 90-second answer
SDC constraints tell static timing analysis what the outside world looks like and which paths are real single-cycle paths. Without them the timer invents its own assumptions, usually a 10 ns clock on every pin and no exceptions, and the reported slack is meaningless.
I write four things for a block like a 100 MHz microcontroller peripheral. A create_clock on the real clock pin. set_input_delay and set_output_delay on data pins relative to that clock. set_false_path for paths that never need to meet timing, such as reset release or a test mux. set_multicycle_path for a path that is allowed more than one clock period, such as a divider enable or a slow register file read.
# SDC, checked against Synopsys Design Compiler / PrimeTime syntax
create_clock -name clk -period 10.000 [get_ports clk] # 100 MHz
set_clock_uncertainty -setup 0.150 [get_clocks clk]
set_clock_uncertainty -hold 0.050 [get_clocks clk]
set_clock_transition 0.100 [get_clocks clk]
# External source/sink: 3 ns of board or upstream logic before the pin,
# 2 ns of downstream logic after the pin, both referenced to clk.
set_input_delay -clock clk -max 3.000 [get_ports {data_in[*]}]
set_input_delay -clock clk -min 0.500 [get_ports {data_in[*]}]
set_output_delay -clock clk -max 2.000 [get_ports {data_out[*]}]
set_output_delay -clock clk -min 0.200 [get_ports {data_out[*]}]
# Reset is asynchronous and checked by recovery/removal, not setup.
set_false_path -from [get_ports rst_n]
# Enable register updates every 4th cycle: 4 x 10 ns budget for setup.
set_multicycle_path -setup -end 4 -from [get_cells u_div/q_reg] -to [get_cells u_datapath/*]
set_multicycle_path -hold -end 3 -from [get_cells u_div/q_reg] -to [get_cells u_datapath/*]create_clock defines the period the timer uses for every setup check. set_input_delay -max is the latest a data bit can arrive at the input pin and still be captured. If the upstream flop launches on the same clock, that value is its clock-to-Q plus trace delay. set_output_delay -max is the latest the downstream flop can capture data launched from our output pin, so it is the period minus downstream setup time minus trace delay. The -min values do the same job for hold, using the fastest upstream or downstream delay. Omitting -min makes hold checks on I/O paths optimistic, which is how a design passes synthesis and fails in silicon on a fast corner.
A false path removes a check entirely. It is correct for reset, for a scan chain in functional mode, or for a configuration register written once at boot through a path that is not timed in normal operation. It is wrong for a real data path that is merely hard to fix. A multicycle path keeps the check but stretches the budget. At 100 MHz a -end 4 setup check allows 40 ns of combinational delay instead of 10 ns. The matching hold check must move to 3 cycles, because hold is checked one cycle earlier than the capturing edge. Forgetting that line is the classic multicycle bug: setup passes, hold fails by roughly one period.
| Exception | Setup budget at 100 MHz | Hold check | When I use it |
|---|---|---|---|
| None, single cycle | 10 ns | Next edge | Normal datapath |
| False path | No check | No check | Reset, test-only mux, async control |
| Multicycle, N=4 | 40 ns | 3 cycles after launch | Divider enable, multi-cycle ALU, slow SRAM read |
Two failure modes show up in review. First, a clock defined only on a port with no create_generated_clock for a divider output. The timer then treats the divided clock as the 100 MHz primary and reports false violations, or worse, misses real ones. Second, input delays copied from a template with no link to the actual upstream clock-to-Q. If the upstream part is 4.5 ns and the constraint says 3 ns, the timer assumes 1.5 ns of margin that does not exist and the input path fails at the input pin in PrimeTime after place and route, even though synthesis looked clean.
I sanity check the file by reporting clocks, listing unconstrained paths, and confirming every data pin has both -max and -min delays. If report_timing shows a path starting at an input pin with zero input delay, the constraint file is incomplete, not the design.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Walk me through floorplanning a 10 mm x 10 mm SoC with a large SRAM macro, a PLL and high-speed IO, and how your macro, power grid and IO choices affect timing and power?
The 90-second answer
Floorplanning fixes the large, hard to move parts of the die before detailed placement: die outline, IO ring, power domains, macro positions and the main clock routes. Standard cells then fill the channels left between them. I do it in that order because moving a macro late changes wire length, IR drop and congestion at the same time, while moving a standard cell late is usually a local fix.
For a 10 mm x 10 mm SoC I assume a 1.0 V core supply, separate always-on and switched power domains, one large SRAM macro, one PLL, slow GPIO and one high-speed serial interface. Change any of those and the plan changes.
Macro placement
I place the SRAM first, close to the CPU or DMA that accesses it most, and orient it so its interface pins face the logic. A macro pushed into a corner to save area forces the bus to cross the die, adding routing length, repeaters and switching capacitance on every access. That extra wire delay and capacitance can be the difference between meeting a 1 ns cycle at 1 GHz and missing it, once cell delay, clock skew and congestion are included. I would not quote a fixed ps per um number for this, since it depends on metal layer, buffering and process, and I would instead compare the two placements with extracted parasitics after a trial route.
The PLL goes near its reference IO pin and away from noisy digital macros, with guard rings and a quiet local supply. A PLL beside a switching power macro picks up supply noise as jitter, and later timing repair cannot remove jitter already present at the source. Analog or RF macros get their own supply island and keep-out for the same reason.
Macros in the same switched domain sit together. Splitting one domain across the die forces long power switch routes, long isolation wiring and a grid that must feed both halves at full current.
Power grid
I plan the grid as a mesh whose strap pitch and width come from IR drop, not from a tidy pattern. Worked example, with hypothetical figures: a domain drawing 2 A at 1.0 V, with a 50 mV drop budget, 5 percent, can tolerate at most 25 mohm of total series resistance on the path that carries that current, since 2 A x 25 mohm = 50 mV. That budget must also cover via resistance, package resistance and transient current, so the on-die grid alone needs to be well under 25 mohm. If a trial grid measures higher, I tighten the pitch, widen straps, add vias or add a second feed point before routing starts.
I feed the grid from several points around the perimeter rather than one corner, so current does not cross the whole die. Decoupling capacitors go near macro pins and along the grid, because a capacitor 2 mm away does little for a fast transient. Power switches for a gated domain sit on the domain boundary, with isolation cells on outputs that leave the domain.
| Decision | Timing effect | Power effect | Failure if wrong |
|---|---|---|---|
| SRAM near CPU | Shorter bus, fewer repeaters | Less wire capacitance per access | Missed cycle at high frequency |
| PLL near reference IO | Low jitter, short reference route | Small direct cost, but jitter forces voltage margin | Serial link fails eye mask |
| Grid fed from two sides | Stable voltage, less derating | Lower IR drop and current density | Local droop, SRAM read failure |
| IO grouped by speed | Short high-speed routes, controlled skew | Less crosstalk and simultaneous switching noise | EMI and signal integrity rework |
IO placement
Slow GPIO fills gaps. High-speed differential pairs go on one edge, close to their PHY macro, with matched length and a clear return path. I keep them away from the PLL and from banks that switch all at once, because simultaneous switching noise on a shared IO supply couples into the receiver. Power and ground IO pins are interleaved with signal pins in proportion to the current the bank will source, not collected in one block at the end.
Bump or BGA escape constrains this too. A high-speed pair on the wrong edge may have to cross the die under the SRAM macro, which is long and hard to shield. Moving the PHY macro to that edge is cheaper than fixing the route later.
Checks before I call it done
I run a congestion estimate on the channels, an IR drop estimate on the grid and a clock skew estimate from the PLL to the farthest flop. I also check antenna rules on long macro pins, latch-up guard rings around IO and thermal hotspots where a power macro sits against dense logic. A floorplan that passes those estimates rarely needs its macro map redone. One that fails them will fail in place and route, where every fix costs more.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Walk me through place and route and clock tree synthesis, and how you would fix skew, transition, and congestion violations after CTS?
The 90-second answer
Place and route turns a placed netlist into physical metal that meets timing, and clock tree synthesis (CTS) is the step inside it that builds the clock network. Synthesis gives gates with no coordinates. Placement assigns each cell an (x, y) and orientation, legalizes overlaps, then optimizes for wirelength and timing. Routing draws the wires on metal layers, first globally to pick corridors, then in detail to satisfy design rules. CTS runs after an initial placement, builds a buffered tree from the clock source to every sequential pin, and tries to hit three targets at every endpoint: a planned insertion delay, low skew between endpoints, and transition time (slew) inside the library limit. If I only fix skew and ignore transition and congestion, the tree passes its own report and fails after detail routing.
# Illustrative CTS constraints, Synopsys ICC2 / Cadence Tempus style
create_clock -name clk -period 2.0 [get_ports clk] ;# 500 MHz
set_clock_transition 0.05 [get_ports clk] ;# source slew, ns
set_clock_uncertainty 0.08 [all_clocks]
set_max_transition 0.12 [all_clocks] ;# max slew on clock net, ns
set_max_fanout 32 [all_clocks]Definitions that decide the fixes
Insertion delay is the delay from the clock source to a capture pin through the tree. Skew is capture insertion minus launch insertion for a path. Transition time is the 10% to 90% rise or fall time of a clock edge at a pin. A slow transition inflates the cell delay of the flop and its fanout, and makes the edge more sensitive to noise and threshold variation, so a tree can have zero skew and still be slow.
Worked trace, hypothetical 500 MHz block, period 2.0 ns. Launch insertion 1.10 ns, capture insertion 1.18 ns, so skew is +80 ps. Setup and hold use different paths, a long path for setup and a short path for hold, which is why the combinational delays differ.
Setup slack = T - t_cq - t_comb - t_setup + skew Hold slack = t_cq + t_comb - t_hold - skew
| Path | t_cq | t_comb | t_setup / t_hold | Slack calculation | Result |
|---|---|---|---|---|---|
| Setup, long path | 0.10 ns | 0.70 ns | 0.05 ns setup | 2.00 - 0.10 - 0.70 - 0.05 + 0.08 | +1.23 ns, passes |
| Hold, short path | 0.05 ns | 0.01 ns | 0.02 ns hold | 0.05 + 0.01 - 0.02 - 0.08 | -0.04 ns, fails |
Positive skew helps setup on that path and hurts hold by the same 80 ps. That is why CTS balances to a target window, often 50 to 100 ps for a high performance core in a modern node, rather than chasing zero everywhere. Zero skew at the expense of long detoured buffers can cost transition and power.
Congestion
Congestion is routing demand exceeding routing capacity in a region, reported per Gcell or tile. Placement creates it by packing too many high fanout nets, clock buffers, or macro blockages into a narrow corridor. The router then detours wires, adds vias, and lengthens nets. Detours raise capacitance, so a clock net that met slew in CTS misses it after routing, and data nets lose slack. I read the congestion map before I touch the router. Hot spots under a macro or beside a power stripe usually mean the placer needs a density or spacing constraint there, not a router effort knob.
How I fix each failure
Skew violation: check whether the endpoints share a common tree segment. If one branch is long, add or move buffers, enable useful skew only with the timing owner, or rebalance with a different target. Do not fix a hold failure from skew by slowing the clock. Hold is edge to edge on the same edge, so period does not appear in the equation.
Transition violation: find the buffer driving the slow pin. Shorten the wire, upsize the driver, split the fanout, or move the buffer closer. Upsizing alone can fix slew and break skew, so rerun CTS optimization after the change.
Congestion: spread placement, add routing tracks by moving macros or blockages, reserve layers for the clock, and route the clock first with shielding if the node requires it. If congestion sits on the clock tree, fix placement and rerun CTS. Patching detail routes around a congested tree leaves the slew problem in place.
After detail routing I rerun STA with extracted RC. A path that passed in CTS and fails post-route is usually a data net detour or a clock slew change, and the fix belongs in placement or CTS, not in a post-route buffer insertion that the next ECO will undo.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13How do IR drop and electromigration cause failures in a power network, and how would you detect and fix them during layout?
The 90-second answer
IR drop and electromigration both live in the power delivery network, but they fail differently. IR drop is instantaneous: current through a resistive wire, via or metal segment drops voltage, so the cell at the end sees less than VDD. That slows gates, shrinks noise margin and can fail timing or SRAM retention at the worst corner. Electromigration is cumulative: sustained current density moves metal atoms until a void opens the wire or a hillock shorts to a neighbour. One is a voltage budget problem you see in extraction. The other is a lifetime problem you see in current density maps.
Assume a 28 nm or 16 nm digital block, a top metal power mesh, and signoff at worst-case temperature and voltage. I would check both before tapeout, because fixing either after routing means ripping up the mesh.
IR drop: mechanism and failure
For a segment, $V_{drop} = I \times R$, with $R = \rho L / A$. On chip, $R$ is dominated by vias and narrow lower metals, and $I$ is not DC. It peaks when many cells switch together, for example a clock buffer tree or a wide bus after reset. Static IR analysis uses a worst-case current per cell. Dynamic IR analysis uses switching activity from simulation or vectorless estimates and finds transient droop that static analysis misses.
A 50 mV droop on a 0.9 V rail is not cosmetic. Gate delay rises as voltage falls, so a path that passed synthesis at 0.9 V can fail setup at the far end of the mesh. SRAM and flops also lose margin. A local droop under a large buffer can cause that buffer to switch slowly and couple noise into neighbours. Global droop, from package and bondwire resistance, hits the whole die and looks like a voltage scaling error.
Worked example, labelled hypothetical: a 100 um run of upper metal power rail, 1.0 um wide and 0.4 um thick, carries 5 mA in a peak window. Copper resistivity at 125 C is about $2.2 \times 10^{-8}$ ohm-m.
| Quantity | Value |
|---|---|
| --- | --- |
| --- | --- |
| Cross-section $A$ | $1.0 \times 0.4$ um$^2$ = $4.0 \times 10^{-13}$ m$^2$ |
| Resistance $R = \rho L/A$ | about 5.5 ohm |
| Drop at 5 mA | about 27.5 mV |
| Drop if current peaks at 10 mA | about 55 mV |
That last row is the point. Average current passes, peak current fails. Widening to 2.0 um halves $R$ and the drop, at the cost of routing congestion and capacitance. In a real mesh many such segments run in parallel, so the effective resistance is lower, but the same $I \times R$ arithmetic applies per branch.
Electromigration: mechanism and failure
Electromigration is driven by electron wind. Momentum transfer pushes metal atoms downstream. Voids form at via bottoms, line ends and other flux divergence points where atoms leave faster than they arrive. Hillocks form where atoms pile up. A void eventually opens the net. A hillock can short to an adjacent line.
Lifetime follows Black's equation:
# Black's equation, illustrative A calibrated to give ~8 years at the stated point
import math
def mtf_years(j, T_C, n=2.0, Ea=0.9, A=1e9):
k = 8.617e-5 # eV/K
T = T_C + 273.15
# MTF = A * j^-n * exp(Ea / (k*T)), j in A/cm^2, A in s*(A/cm^2)^n
return A * (j ** -n) * math.exp(Ea / (k * T)) / (365.25 * 24 * 3600)
print(round(mtf_years(1e6, 125), 1)) # ~7.9 years
print(round(mtf_years(5e5, 125), 1)) # ~31.7 years, 4x longer when n=2The exact $A$ and $E_a$ come from the foundry model for that metal and via type. The trend matters: lifetime falls as $j^{-n}$ with $n$ near 2, and exponentially with temperature. Doubling current density cuts life by about four times. A wire that is fine at 85 C can fail in the field at 125 C.
Current density is $j = I/A$. The same 5 mA in the segment above gives $j = 5 \times 10^{-3} / 4.0 \times 10^{-13} = 1.25 \times 10^{10}$ A/m$^2$, which is $1.25 \times 10^6$ A/cm$^2$. That sits above typical DC limits for lower metals, which are often near $10^6$ A/cm$^2$ depending on foundry rules, and near the limit for upper metals. AC or pulsed current helps, because voids can heal during off periods, but a clock net or always-on rail sees near-DC stress.
Detection in layout
| Check | What it reports | What it misses |
|---|---|---|
| Parasitic extraction plus static IR | Worst-case DC drop per cell and per net | Transient peaks from coincident switching |
| Dynamic IR with activity | Time-varying droop, di/dt hotspots | Depends on activity quality |
| EM rule check on extracted layout | $j$ per segment, via current, lifetime estimate | Needs correct foundry limits per metal, via and temperature |
| Post-layout simulation at low V | Functional and timing failure under droop | Only covers vectors you ran |
I run EM checks on the extracted netlist, not on the schematic intent, because via placement and jogs create the hotspots. I look first at vias, because a single via carrying the full current of a wide wire is a classic failure site. I also check long parallel runs, where a void has room to grow, and any segment where routing forced a neck-down.
Fixes, and when each applies
For IR drop: widen the mesh, add parallel paths, move vias closer to the load, add on-die decoupling capacitance near large switching blocks, and stagger buffer insertion so current peaks spread in time. For a clock tree, distributing buffers and avoiding a single trunk feeding many sinks cuts both peak current and local droop.
For electromigration: widen the wire or add parallel wires, use via arrays instead of single vias, avoid neck-downs, and move high-current nets to upper metals with larger cross-section and better thermal paths. If current cannot drop, reduce duty cycle or move the net to a pulsed regime where the foundry allows higher AC limits. Copper and alloy choices are foundry decisions, not layout decisions, but layout must respect the limits for the chosen stack.
Trade-off: widening fixes both problems at once, since larger $A$ lowers $R$ and $j$ together. The cost is area, routing blockage and extra capacitance on signal nets. On power nets that cost is usually worth it. On signal nets I would not widen blindly, because capacitance slows the signal and can create a timing problem while solving an EM problem that a via array would have solved.
Signoff is both checks clean at the worst corner, with margin left for model error. If IR passes but EM fails on a via, I fix the via. If EM passes but dynamic IR shows a 60 mV droop under a macro, I add decap and split the feed. Treating them as one problem hides which fix actually worked.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Why is the pull-down transistor in a 6T SRAM cell sized larger than the access transistor?
The 90-second answer
The pull-down NMOS is the lower device in each inverter. The access NMOS connects that storage node to the bitline when the wordline is high. During a read, the bitline is precharged to VDD and the access device tries to pull the stored 1 down through the access transistor. The pull-down has to hold that node high against that current. If the access device is stronger, the node falls past the inverter trip point and the cell flips. That is a read upset.
The cell ratio is defined as:
CR = W_pulldown / W_accessKeeping CR above 1, typically 1.2 to 1.5 in a mainstream 6T cell, makes the pull-down stronger than the access device. The stored 1 then sags only a little during the read, the differential on the bitlines develops, and the sense amplifier can restore the data without the latch changing state.
Worked trace, Q = 1, QB = 0, VDD = 0.8 V
Values below are hypothetical and chosen to show the mechanism.
| Step | BL | BLB | Q | QB | What happens |
|---|---|---|---|---|---|
| Precharge | 0.80 V | 0.80 V | 0.80 V | 0 V | Both bitlines high |
| Wordline on | 0.77 V | 0.45 V | 0.74 V | 0.06 V | Access device pulls Q down, pull-down holds it |
| Sense point | 0.76 V | 0.66 V | 0.73 V | 0.07 V | Differential reaches about 100 mV, sense amp fires |
| After sense | 0.80 V | 0 V | 0.80 V | 0 V | Full swing restored, Q still 1 |
With CR = 1.0, the same trace would show Q falling toward 0.4 V, close to the trip point at about 0.4 V for this hypothetical inverter. Process variation can then push it over. With CR = 1.4, Q stays near 0.74 V and the margin is comfortable.
| Cell ratio | Pull-down width | Access width | Read behaviour |
|---|---|---|---|
| 1.0 | 120 nm | 120 nm | Q sags close to trip point, read upset risk |
| 1.4 | 168 nm | 120 nm | Q sags about 60 mV, stable read |
| 2.0 | 240 nm | 120 nm | Very stable read, larger cell and slower write |
The trade-off is on the write side. A stronger pull-down also makes the cell harder to flip when the write driver forces the opposite bitline low. That is why CR is not made arbitrarily large. Designers pick the smallest CR that keeps read static noise margin positive across process, voltage and temperature corners, then use write assist such as a negative bitline voltage if write margin becomes the limiter at low VDD.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15Walk me through how a CMOS inverter switches, how threshold voltage and subthreshold conduction set leakage, and how you would size transistors when delay and power pull in opposite directions?
The 90-second answer
A CMOS inverter is two switches in series between VDD and ground. The PMOS pulls the output high, the NMOS pulls it low, and in steady state one is off, so there is no direct VDD to ground path. Switching is charging or discharging the load capacitance through the on transistor. Delay is roughly the time to move that charge, power is the energy spent moving it every cycle plus the leakage that flows while the off transistor should be off.
Threshold voltage, Vt, is the gate voltage at which the device moves from subthreshold to strong inversion. Below Vt the transistor is not truly off. It conducts a subthreshold current that falls exponentially as Vgs drops below Vt. That current is the main source of standby leakage in modern processes, and it is why Vt choice is a power decision as much as a speed decision.
Sizing trades resistance against capacitance. A wider transistor has lower on resistance, so it drives the load faster, but it also has more gate and diffusion capacitance, so it costs more dynamic energy per transition and more leakage area. Past a point, making it wider buys almost no delay and costs power linearly.
Switching, with numbers
Take a hypothetical 65 nm inverter at VDD = 1.0 V, load C_L = 5 fF, effective on resistance R = 2 kΩ for a minimum NMOS. The 50% delay is about 0.69 × R × C_L = 0.69 × 2000 × 5e-15 ≈ 6.9 ps. Dynamic energy per 0 to 1 transition is C_L × VDD² = 5 fJ, and average dynamic power at activity α = 0.1 and f = 1 GHz is α × C_L × VDD² × f = 0.5 µW for that one gate. The PMOS is usually sized about 2 to 3 times wider than the NMOS in the same process because hole mobility is lower, which keeps rise and fall times roughly matched. If the PMOS is left at minimum width, the rising edge can be two to three times slower than the falling edge and the clock to Q of a flop built from such gates becomes data dependent.
# Illustrative sweep, C scales with W, R scales as 1/W plus a fixed parasitic
VDD, f, alpha = 1.0, 1e9, 0.1
C_fixed = 2e-15 # wiring and next stage gate, not scaled
for W in [1, 2, 4, 8]:
C = C_fixed + W * 1e-15
R = 4000 / W + 500 # ohms, includes a fixed parasitic term
delay = 0.69 * R * C
power = alpha * C * VDD**2 * f
print(W, f"{delay*1e12:.1f} ps", f"{power*1e6:.2f} uW")| Width (×) | Delay (ps) | Dynamic power (µW) | Comment |
|---|---|---|---|
| 1 | 10.4 | 0.30 | Minimum area, slowest |
| 2 | 8.3 | 0.40 | Good delay return |
| 4 | 7.3 | 0.60 | Diminishing return |
| 8 | 6.9 | 1.00 | Power up 3.3× for 1.5× speed over ×1 |
The fixed parasitic is the point. Without it, delay would be flat with width because R falls as fast as C rises. With wiring, next stage input capacitance and diffusion parasitics that do not scale perfectly, delay improves at first and then saturates. Logical effort formalises this: size a gate so its input capacitance is comparable to the load it drives, rather than making every gate large.
Vt and subthreshold conduction
In subthreshold, drain current is diffusion current, not drift:
I_sub ≈ I_0 × exp((Vgs − Vt) / (n × V_T)) × (1 − exp(−Vds / V_T))
where V_T is the thermal voltage, about 26 mV at room temperature, and n is the subthreshold slope factor, typically 1.2 to 1.5. The subthreshold swing S = n × V_T × ln(10) is therefore about 70 to 90 mV per decade in a real device, against an ideal limit of 60 mV per decade at 300 K. Every 70 to 90 mV you lower Vt, off current rises by roughly a factor of ten at Vgs = 0.
That exponential is the whole low power problem. A low Vt device might be 30% faster at the same VDD because it has more overdrive, Vgs − Vt, and therefore more on current. It can also leak 10 to 100 times more. A high Vt device is the opposite. Most standard cell libraries therefore offer at least two or three Vt flavours of the same gate. The usual assignment is low Vt on the critical timing path, standard or high Vt everywhere else, because leakage is summed over every transistor on the die while delay only matters on a few paths.
Two effects make this worse in practice. Drain induced barrier lowering means a short channel device loses Vt as Vds rises, so leakage at VDD is higher than a long channel model predicts. Body effect raises Vt when the source is not at the bulk potential, which matters in stacked devices and in triple well structures. Temperature makes it worse again: Vt falls with temperature while V_T rises, so leakage at 125 °C can be orders of magnitude above the 25 °C value. A part that meets its standby budget at room temperature can fail it in a hot enclosure, which is why leakage is signed off at the worst temperature corner, not nominal.
Sizing decisions and failure modes
Upsizing a gate on a failing path is the first move, but it loads the previous stage. The previous stage now sees a larger input capacitance, so its delay rises. If you upsize a whole chain by the same factor, you can move the bottleneck without fixing it. The fix is to size for the fanout: a gate driving one input can stay small, a gate driving a long wire or a flop clock pin needs to be larger. Clock buffers are the extreme case, sized for slew and for the total clock capacitance, not for minimum delay of a single gate.
Oversizing also raises short circuit power. If input rise and fall times are slow, both transistors are on briefly and a direct path current flows. That energy is wasted as heat and it grows when a large gate is driven by a weak, slow predecessor. Keeping transition times controlled, usually by not letting a large gate be driven by a minimum gate, matters as much as the gate size itself.
Vt variation is the subtle failure. Random dopant fluctuation and line edge roughness make Vt vary from transistor to transistor, with a standard deviation of a few millivolts for minimum devices in older nodes and more in FinFET at small widths. In subthreshold that few millivolts is a large fractional change in leakage, and in strong inversion it changes on current and therefore delay. Minimum width devices have the worst variation, which is one reason SRAM cells and sense amplifiers are not built from minimum devices even when area would allow it. Near threshold operation, where VDD is close to Vt, makes this worse: a 20 mV Vt shift is a large fraction of the overdrive, so delay variation explodes. That is why near threshold logic needs careful margin and why it is rarely used for a full microcontroller core without characterisation across process corners.
In short: size for the load, pick Vt per path rather than per die, and check leakage at the hot corner with the actual Vt distribution. A design that is fast at nominal and leaky at 125 °C, or fast on a typical die and slow on a low Vt corner, has not been sized, it has been guessed." ,
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Walk me through writing synthesizable SystemVerilog for a 16-bit counter with enable and synchronous reset, and what coding choices keep it synthesizable and verifiable?
The 90-second answer
I would put all state in one always_ff block, compute the next value in always_comb, and keep every construct in the synthesizable subset. That split makes the netlist predictable: the tool infers flip-flops for q, an adder and a mux for the next-state logic, and nothing else. I would avoid delays, initial blocks, multiple drivers, and blocking assignments in sequential logic, because each one either fails synthesis or simulates differently from what synthesis built.
module counter16 #(
parameter int WIDTH = 16
)(
input logic clk,
input logic rst, // synchronous, active high
input logic en,
output logic [WIDTH-1:0] q,
output logic overflow
);
logic [WIDTH-1:0] next_q;
always_comb begin
next_q = q;
if (en) next_q = q + 1'b1;
end
always_ff @(posedge clk) begin
if (rst) q <= '0;
else q <= next_q;
end
assign overflow = en && (q == '1);
// Verification aids, ignored by synthesis
assert property (@(posedge clk) rst |-> ##1 (q == '0))
else $error("reset did not clear q");
cover property (@(posedge clk) overflow);
endmoduleWhy this shape synthesizes cleanly
always_ff tells the tool and the linter that this block drives registers and must use nonblocking assignments. always_comb does the opposite job: it must assign next_q on every path, so the default assignment at the top prevents a latch. If I removed that default and only assigned inside if (en), synthesis would infer a latch for next_q, which changes area, timing, and testability.
| Construct | Synthesis result | Risk if misused |
|---|---|---|
always_ff with <= | Flip-flops, one driver | Blocking = can race with other blocks in simulation |
always_comb with = | Combinational logic | Missing default assignment infers a latch |
initial, #10, while (1) | Ignored or rejected | Simulation passes, netlist differs or synthesis fails |
Unsized literals, e.g. q + 1 | Width set by context | Truncation or sign extension surprises at 16 bits |
Reset style is a deliberate choice here. Most standard-cell libraries provide flip-flops with asynchronous reset, not synchronous reset. A synchronous reset in RTL therefore usually becomes a mux or AND gate in front of the D input, adding area and delay on the data path, and it is sampled only on clk. An asynchronous reset maps directly to the library flop, but it needs recovery and removal checks and, in a real SoC, a reset synchronizer per clock domain. I would pick synchronous reset for a block that is always in a clocked domain and where that extra logic is acceptable, and asynchronous reset where the flop mapping matters more.
Worked trace
Assume WIDTH = 4 for readability. overflow is combinational from the value of q before the clock edge, so it is high during the cycle in which q is 15 and en is high, and q wraps to 0 at the end of that cycle.
| Cycle | rst | en | q before edge | overflow | q after edge |
|---|---|---|---|---|---|
| 0 | 1 | 0 | 0 | 0 | 0 |
| 1 | 0 | 1 | 0 | 0 | 1 |
| 2 | 0 | 1 | 1 | 0 | 2 |
| 3 | 0 | 0 | 2 | 0 | 2 |
| 4 | 0 | 1 | 2 | 0 | 3 |
| 5 to 13 | 0 | 1 | 3 to 13 | 0 | 4 to 14 |
| 14 | 0 | 1 | 14 | 0 | 15 |
| 15 | 0 | 1 | 15 | 1 | 0 |
| 16 | 0 | 1 | 0 | 0 | 1 |
Cycle 15 is the check an interviewer will probe. If the system needs a registered pulse aligned with the wrapped value instead, I would register overflow in the same always_ff block and state that timing in the spec.
Verification practices that catch RTL bugs early
Lint first: check for multiple drivers, inferred latches, width mismatches, and unused signals before simulation. Then assertions for the invariants that matter, such as reset clearing q and overflow only when en is high and q is all ones. Coverage should hit the wrap, a long disabled stretch, and reset asserted mid-count. A self-checking testbench that models the expected count catches off-by-one errors that waveform inspection misses, especially around the wrap cycle.
Two habits prevent most synthesis surprises. Keep the module free of system tasks, file I/O, and timing controls, and keep parameters sized explicitly, for example parameter int WIDTH = 16 with logic [WIDTH-1:0]. When a construct is only for simulation, guard it with `ifdef SYNTHESIS or move it to the testbench, so the synthesized netlist and the simulated RTL describe the same hardware.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Walk me through a UVM verification environment and how you would use it to verify a complex peripheral such as a DMA controller?
The 90-second answer
UVM, IEEE 1800.2, is a SystemVerilog class library for building reusable, randomized testbenches. The DUT sits in the middle. Around it you place agents that drive and observe each protocol, a scoreboard that compares DUT behaviour against a reference model, and sequences that generate stimulus. The test decides which sequences run, the environment wires everything together, and the simulator runs the UVM phases from build and connect through run to final and report.
Components, and what each one owns
An agent is the reusable unit for one interface. It contains a driver, which converts sequence items into pin wiggles, a monitor, which samples pins and publishes transactions over TLM ports, and a sequencer, which arbitrates items from sequences. Active agents drive. Passive agents only monitor, which is useful when the DUT is the initiator, as with a DMA engine issuing AXI reads.
The environment instantiates agents, the scoreboard, and the reference model, and connects TLM ports. The scoreboard receives observed transactions from monitors and expected transactions from the reference model, then compares them. The reference model is a cycle-abstract SystemVerilog model of the spec, written independently from the RTL where staffing allows. That independence is what catches spec misreadings that RTL and testbench would otherwise share.
Sequences are the stimulus. A base sequence holds common setup, such as programming descriptors. Constrained-random sequences randomize fields within legal ranges and add constraints for interesting corners. Functional coverage bins record what was actually hit, so a passing run with an empty bin is treated as an incomplete run.
For a register-heavy peripheral, the register abstraction layer mirrors the CSR map. It generates reads and writes, applies frontdoor or backdoor access, and predicts the effect of a write so the scoreboard can check the DUT response without hand-coding every register sequence.
Applying it to a DMA peripheral
I would start from the spec and build a verification plan before writing sequences. For a DMA block with an APB control port, AXI master ports, and an interrupt line, the plan lists descriptor formats, channel arbitration, burst lengths, alignment rules, error responses, and reset behaviour. Each line becomes a directed test, a constrained-random constraint, or a coverage bin.
The APB agent programs descriptors through the RAL. The AXI agent acts as a responder with configurable backpressure and error injection, because a DMA that only works with a zero-wait-state memory will fail in the SoC. A second passive AXI agent monitors the DUT as initiator. The reference model tracks descriptor fetches, data movement, and completion status, and predicts the interrupt.
A constrained-random sequence for one transfer looks like this:
class dma_xfer_seq extends uvm_sequence #(axi_txn);
rand int unsigned len;
rand bit [63:0] src, dst;
constraint c_len { len inside {[1:1024]}; }
constraint c_align { src[1:0] == 0; dst[1:0] == 0; }
constraint c_no_overlap { !(src < dst + len*4 && dst < src + len*4); }
function new(string name = "dma_xfer_seq");
super.new(name);
endfunction
endclassThe overlap constraint matters. Without it, random tests spend their time on a case the spec may forbid, and a failure there tells you nothing about the RTL.
A worked trace for a single run shows how the pieces check each other:
| Time | Event | Check |
|---|---|---|
| 0 ns | APB write programs descriptor, start bit set | RAL predicts CSR state |
| 120 ns | AXI read of descriptor, 64 bytes | Reference model queues expected data beats |
| 400 ns | AXI write burst, 8 beats, 2 wait states inserted | Monitor publishes beats, scoreboard compares payload and address |
| 900 ns | Last beat accepted, channel done bit set | Scoreboard checks interrupt asserted within spec window |
| 950 ns | AXI slave returns SLVERR on next descriptor | Reference model predicts error status, no interrupt, channel halts |
Directed tests cover the cases random stimulus reaches slowly: descriptor crossing a 4 KB boundary, zero-length transfer, back-to-back channels, reset asserted mid-burst, and clock stopped while a transfer is pending. Random tests then explore combinations of burst length, alignment, and backpressure.
Failure modes I watch for
Race conditions between driver and monitor sampling on the same edge. Clocking blocks with input skew, or sampling on the opposite edge, remove most of them. A second failure is a reference model that mirrors the RTL bug because the same person wrote both from the same misreading. Keeping the model at transaction level, and reviewing it against the spec separately, reduces that risk. A third is coverage that bins only legal, easy cases. I bin error responses, backpressure depth, and arbitration outcomes explicitly, and I require the coverage report in the regression sign-off.
UVM pays off when the block has several protocols, a large register map, or a design that will be reused across SoCs. For a small, fixed-function block with one simple interface, a directed SystemVerilog testbench with assertions often reaches the same confidence with less code to maintain. The decision is about reuse and randomization value, and I would state that trade-off to the interviewer before committing to the full environment.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18How would you structure a SystemVerilog testbench for a digital block with stimulus generation, a reference model, checkers, and constrained random testing?
The 90-second answer
I would separate the testbench into four pieces that communicate only through the DUT pins and a transaction queue: a driver that generates stimulus, a monitor that samples the pins, a reference model that predicts the output, and checkers that compare prediction against reality on every cycle. Constrained random stimulus then drives the driver, and the scoreboard flags any mismatch with the cycle and the transaction that caused it.
For a simple block I would write this in plain SystemVerilog with a clocking block and immediate assertions. I would move to UVM only when the same environment must be reused across several blocks or needs a protocol library such as AXI or APB.
// Checked against SystemVerilog 2017, VCS / Xcelium style
module tb_fifo;
logic clk = 0, rst_n, wr_en, rd_en;
logic [7:0] wr_data, rd_data;
logic full, empty;
logic [7:0] model[$];
logic [7:0] expected;
fifo8 dut (.clk(clk), .rst_n(rst_n), .wr_en(wr_en),
.wr_data(wr_data), .rd_data(rd_data),
.full(full), .empty(empty));
always #5 clk = ~clk;
// Reference model: push on write, pop on read
always @(posedge clk) begin
if (!rst_n) model.delete();
else begin
if (rd_en && !empty) begin
expected = model.pop_front();
assert (rd_data == expected)
else $error("rd_data=%h expected=%h", rd_data, expected);
end
if (wr_en && !full) model.push_back(wr_data);
end
end
// Protocol checker: never write when full, never read when empty
assert property (@(posedge clk) disable iff (!rst_n)
(wr_en |-> !full) && (rd_en |-> !empty));
initial begin
rst_n = 0; wr_en = 0; rd_en = 0;
repeat (4) @(posedge clk);
rst_n = 1;
repeat (1000) begin
@(posedge clk);
// Constrained random: bias toward legal operations
wr_en <= ($urandom_range(0, 2) != 0);
rd_en <= ($urandom_range(0, 2) != 0);
wr_data <= $urandom_range(0, 255);
end
$finish;
end
endmoduleThe driver in a larger bench would be a class with a send() task that drives on the clock edge through a clocking block, so stimulus never races the DUT sampling. The monitor does the opposite: it samples on the same edge and pushes a transaction struct into a mailbox. The scoreboard pops that struct, feeds it to the reference model, and compares the model output with the monitored output.
What each piece owns
| Piece | Owns | Must not own |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Stimulus driver | Reset sequence, legal and illegal transactions, backpressure | Predicting the correct output |
| Reference model | Cycle-accurate or transaction-level expected behaviour | Reading DUT internal state |
| Checker | Protocol rules, X propagation, latency bounds | Generating stimulus |
| Coverage | Bins for full, empty, back-to-back, reset mid-transaction | Pass or fail judgement |
A worked trace shows why the split matters. Suppose the FIFO holds one entry, 8'hA5, and the driver randomly asserts rd_en and wr_en together. The monitor captures both signals on that edge. The model pops A5 and pushes the new write data, so the next read must return the new data. If the DUT returns the old data again, the checker reports the exact cycle, the popped value, and the pushed value. Without the model that failure looks like a random mismatch in a waveform.
Random testing that actually finds bugs
Pure random stimulus wastes most cycles on illegal or uninteresting cases. I constrain the distribution: weight legal operations higher, force corner cases with a directed sequence every N cycles, and add a seed sweep. A typical run uses 20 seeds at 10,000 cycles each. Coverage then tells me whether full, empty, simultaneous read and write, and reset during a transaction were hit. If a bin stays empty after 200,000 cycles, the constraint is wrong, not the DUT.
Failure modes I check for explicitly: the model and DUT both wrong in the same way because the model was copied from the RTL, so I write the model from the spec; X values on outputs after reset, caught by an assert (!$isunknown(rd_data)) checker; and race conditions between driver and DUT, avoided by driving through a clocking block with a small output skew.
Directed tests still come first for reset, overflow, and underflow. Random testing then explores the combinations directed tests miss, and coverage proves the exploration happened.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19Write SystemVerilog assertions for a valid/ready handshake protocol, and explain when you would use immediate, concurrent, and cover properties instead?
The 90-second answer
Assume a single clock, active-high valid/ready handshake, valid must stay asserted with stable payload until ready, and reset is synchronous active-low rst_n. I would write concurrent assertions for protocol rules that must hold every cycle, immediate assertions for procedural checks inside a checker or testbench process, and cover properties to prove the testbench actually reached the interesting cases. Mixing them up is the common failure: a cover that never hits looks like a pass, and an immediate assertion in a clocked process can race the DUT.
// Checked against IEEE 1800-2017, VCS/Xcelium/Questa simulation and formal
module handshake_checker (
input logic clk, rst_n, valid, ready,
input logic [7:0] data
);
// Concurrent: stability under backpressure
property p_stable;
@(posedge clk) disable iff (!rst_n)
(valid && !ready) |=> (valid && $stable(data));
endproperty
a_stable: assert property (p_stable)
else $error("valid dropped or data changed while stalled");
// Concurrent: no X on the handshake when active
property p_known;
@(posedge clk) disable iff (!rst_n)
valid |-> !$isunknown({ready, data});
endproperty
a_known: assert property (p_known);
// Cover: hit, stall, and recovery are distinct bins
c_hit: cover property (@(posedge clk) disable iff (!rst_n) valid && ready);
c_stall: cover property (@(posedge clk) disable iff (!rst_n) valid && !ready);
c_recover: cover property (@(posedge clk) disable iff (!rst_n)
(valid && !ready) ##1 (valid && ready));
// Immediate: procedural, inside a checker process
always @(posedge clk) begin
if (rst_n && valid && ready) begin
assert (data != 8'hxx) else $error("X data accepted at %0t", $time);
end
if (rst_n && valid && !ready) begin
assert ($stable(data)) else $error("payload changed during stall");
end
end
endmoduleWhy the three forms differ
| Form | Where it lives | Sampling and timing | Use it for | Trap |
|---|---|---|---|---|
Immediate assert(expr) | Procedural code, always, initial, checker process | Evaluated when the statement executes, in the active region | One-off checks tied to a transaction, queue pop, or TB state | Races with DUT nonblocking updates if placed in the same always block |
Concurrent assert property | Module or checker scope, declarative | Sampled in the preponed region on the clock edge, sequences with ##, ` | ->, | =>` |
Cover cover property | Same scope as concurrent | Same sampling as concurrent | Reachability of hit, stall, reset mid-transfer, back-to-back beats | A hit proves stimulus reached a state, never that the DUT is correct |
Concurrent assertions are the default for a protocol. The sequence language expresses the rule directly: valid && !ready |=> valid says the source cannot withdraw. ##[1:$] ready bounds or leaves open the wait for acceptance. disable iff (!rst_n) aborts the sequence on reset, which matters because a transfer interrupted by reset should not be judged as a stall violation. Without it, formal tools report a failure on the reset cycle that the spec explicitly allows.
Immediate assertions earn their place when the check needs procedural context a property cannot see, such as a scoreboard queue, a forked driver, or a check after a #10 delay. They also give a precise $error message with TB variables. Keep them out of the DUT for synthesis flows, and be careful with timing: an immediate assertion in an always @(posedge clk) block reads values after the DUT has updated in the same timestep, so a checker clocked on the same edge can see the new value rather than the value the DUT sampled. Sampling the inputs into the checker on the edge, or using concurrent properties, removes that race.
Assumptions, formal, and failure modes
For formal verification I add assume property for the environment, for example that ready is not X and that reset is eventually released. In simulation those assumptions become constraints on the driver instead, because an assume in a simulator can silently mask a TB bug. I never put assume in RTL that ships.
Three failures show up in review. First, vacuity: the cover list above is checked in the coverage report, and I require c_stall and c_recover to hit before I trust a_stable. Second, an unbounded ##[1:$] in formal can make a liveness property unprovable, so I bound it in formal runs, for example ##[1:16] ready, and keep the unbounded form only for simulation. Third, $stable(data) only checks the previous sampled value, so a glitch between edges is invisible. That is acceptable for a synchronous protocol and wrong for an asynchronous input, which needs a synchronizer check instead.
In an interview I would close by naming the tool flow: simulation with VCS or Xcelium for the assertions above, coverage closure on the cover properties, then the same properties bound for JasperGold or VC Formal with assumptions replacing the TB driver.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20How do you define functional coverage for a peripheral, choose coverpoints and bins, and drive it to closure without chasing unreachable bins?
The 90-second answer
Functional coverage records whether tests exercised behaviours the specification cares about. Code coverage only records that lines or branches executed. I build the model from spec clauses before writing tests, then use uncovered bins to decide what to test next.
Take a UART receiver. The risky behaviours are not "a byte arrived". They are baud rates near the divider limits, a parity error coinciding with a framing error, and back-to-back frames with no idle gap. Each becomes a coverpoint, and each bin is a distinct outcome a bug could hide in.
covergroup uart_cg @(posedge clk);
option.per_instance = 1;
cp_baud_div: coverpoint baud_div {
bins fast = {[1:16]};
bins mid = {[17:255]};
bins slow = {[256:4095]};
illegal_bins zero = {0};
}
cp_rx_status: coverpoint {rx_valid, parity_err, framing_err} {
bins clean = {3'b100};
bins parity_only = {3'b110};
bins framing_only = {3'b101};
bins both_errors = {3'b111};
bins idle = {3'b000};
}
cp_gap: coverpoint idle_cycles {
bins zero_gap = {0};
bins one_gap = {1};
bins long_gap = {[2:$]};
}
cross_baud_status: cross cp_baud_div, cp_rx_status;
cross_gap_status: cross cp_gap, cp_rx_status;
endgroupThe divider labels follow the hardware. A small baud_div divides the reference clock less, so the baud rate is high. A large divider gives a slow baud rate. Getting that backwards in a coverage model sends directed tests to the wrong corner.
Three choices decide whether this model works. Bins must be coarse enough to hit in a regression but fine enough to separate behaviours. A single bins all = default bin would report 100% while missing every error case. Crosses must be selective. Crossing baud (3 bins) with status (5 bins) gives 15 bins, which is manageable. Crossing every signal in the block would give thousands of bins, most unreachable, and the team would spend closure chasing noise. Illegal bins matter too. baud_div == 0 should never occur if the register is protected, so it is marked illegal. If a test hits it, the testbench or the DUT has a bug, and the simulator flags it instead of silently counting it as covered.
| Bin | Why it exists | How it gets hit |
|---|---|---|
both_errors at fast baud | The sampling window is shortest at the highest baud rate, so coincident parity and framing errors stress the receiver there | Directed test with forced parity and stop-bit errors at a divider in [1:16] |
zero_gap with clean | Back-to-back frames stress the FIFO push path | Constrained random with idle_cycles == 0 forced |
parity_only at slow baud | A long frame gives the error injection logic many cycles to act on, which can mask a race that only appears at low rates | Random baud in [256:4095] plus injected parity error |
Closure is a loop, not a percentage
After each run I sort uncovered bins by risk, not by count. A missing both_errors bin outranks ten missing idle bins. For each bin I ask whether the current configuration can reach it. If a bin needs parity checking enabled but the test set ran with parity disabled, the fix is a configuration change, not a new test. If the bin is reachable, I add a directed test for the first hit and then constrain the random test to keep it hit, so it stays covered across regressions.
Some bins are genuinely unreachable. A tie-off may fix baud_div to 16 in a product variant, making the slow bin impossible. I do not delete that bin to reach 100%. I either scope the covergroup per configuration, mark the bin as ignored with a comment naming the tie-off, or waive it in the coverage report with a reviewer sign-off. Deleting bins hides the gap from the next engineer who reuses the environment.
Two failure modes show up repeatedly. The first is bin explosion from an unfiltered cross, where closure stalls at 92% because 400 bins depend on a mode the DUT cannot enter. The fix is to split the cross or add ignore_bins for the impossible combinations, with the reason recorded. The second is 100% functional coverage with a bug still present, because the bins were defined around the implementation instead of the spec. That is why I review the covergroup against the spec clause list, and pair it with assertions for properties that must always hold, such as "no byte is accepted when framing_err is set". Coverage tells me what was tried. Assertions tell me whether it was correct.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21When would you use formal verification instead of simulation for an RTL block, and what are its strengths and limits?
The 90-second answer
Formal verification proves properties of RTL exhaustively over all reachable states, instead of checking the traces a testbench happens to generate. You write assertions in SystemVerilog Assertions, plus assumptions that constrain the environment, and the tool either proves the assertions hold for every input sequence or returns a counterexample trace. I use it for control logic where the bug is a rare interleaving that simulation is unlikely to hit, and I keep simulation for datapath, performance and anything with real timing.
How it works
The tool builds a model of the design and the assertions, then searches the state space. Two engines cover most work. Bounded model checking unrolls the design for k cycles and checks for a violation within that bound. It is good at finding bugs fast, but a pass at k = 20 says nothing about cycle 21. Inductive proof tries to prove the property for all cycles by finding an inductive invariant, often with lemmas the engineer supplies. That gives an unbounded guarantee when it converges, which is why a simple handshake or FIFO pointer property is a classic formal target.
// Checked with JasperGold / VC Formal, SystemVerilog 2017 SVA
module fifo_ctrl import uvm_pkg::*; #(parameter DEPTH = 16) (
input logic clk, rst_n,
input logic wr_en, rd_en,
output logic full, empty
);
// Environment assumptions: keep inputs legal, or the proof is vacuous
assume property (@(posedge clk) rst_n |-> !wr_en || !full);
assume property (@(posedge clk) rst_n |-> !rd_en || !empty);
// Properties to prove
assert property (@(posedge clk) rst_n && full |-> !wr_en);
assert property (@(posedge clk) rst_n && empty |-> !rd_en);
assert property (@(posedge clk) rst_n |-> !(full && empty));
// Cover proves the scenario is reachable, catching vacuity
cover property (@(posedge clk) rst_n && !full && wr_en && rd_en);
endmoduleIf the cover never fires, the assumptions may have made the design unreachable and the assertions passed for the wrong reason. That check is not optional.
Where it wins over simulation
Simulation answers: did this stimulus sequence fail? Formal answers: does any legal sequence fail? For a 4-state arbiter, a DMA descriptor walker, or an AXI handshake, the failing sequence may need simultaneous grant, backpressure and reset release in a precise order. Random UVM tests can run for days and miss it. Formal finds it in minutes because it explores the interleavings systematically.
| Simulation (UVM) | Formal | |
|---|---|---|
| Coverage | Only exercised traces | All reachable states within proof bound |
| Best fit | Datapath, throughput, software interaction, timing-aware behaviour | Control, protocols, arbitration, FIFO pointers, state machines |
| Failure output | Failing test, waveform | Counterexample trace, replayable in simulation |
| Main cost | Testbench build, runtime, coverage closure | Assertion and assumption modelling, state explosion |
| Blind spot | Rare corner cases | Analogue, timing, large multipliers, X behaviour without X-prop setup |
A concrete scale check helps set expectations. A 32-bit counter has 2^32 states, so naive exhaustive search is hopeless, yet induction proves count_q <= count_q + 1 style properties easily because the invariant is simple. A 32x32 multiplier in the datapath is the opposite case. The state space explodes and simulation with directed vectors is cheaper and more direct.
Limits and failure modes
State explosion is the hard limit. Wide datapaths, large memories, and deep pipelines make proofs time out or return inconclusive. Engineers cut the problem down with abstraction, black-boxing memories, and proving the control around the datapath separately. That abstraction is itself a risk. If the black box hides a real interaction, the proof proves a model, not the chip.
Assumptions are the second failure mode. Over-constrain the inputs and you prove a design that never sees the illegal input that real hardware can produce, for example a reset glitch or a bus master that violates the protocol. Under-constrain them and the tool spends its budget on impossible traces or reports false counterexamples. I review assumptions like RTL, because a bug there invalidates the result silently.
Formal also does not replace simulation for clocks, resets and metastability. A property clocked on one domain says nothing about a synchronizer, and formal tools model flops as ideal unless X-propagation and multi-clock setup are explicitly enabled. CDC, analogue blocks, PLL behaviour and timing closure stay with simulation, STA and dedicated analysis.
My decision rule
I reach for formal first when the block is control-heavy, the state space is manageable, and a missed corner case would be expensive, such as a bus arbiter, a power state controller, or a FIFO. I reach for simulation first when the question is throughput, latency under load, or interaction with firmware. In practice the strongest flow uses both. Formal proves the handshake can never deadlock, simulation measures how fast it runs, and the counterexample from formal becomes a regression test in the UVM environment.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-22Which verification method compiles a large SoC onto emulator hardware so firmware can run at near real speed, and how does it differ from simulation?
The 90-second answer
Emulation. It compiles the RTL onto emulator hardware, usually FPGA based accelerators or a dedicated ASIC emulator, and runs the design at megahertz speeds instead of the kilohertz speeds of an event driven simulator. That speed is the whole point. Firmware, drivers, and an operating system can boot and run on the emulated SoC, and long traffic patterns can execute in seconds rather than hours.
Simulation remains the debug tool. It runs in software, so every internal signal is visible and can be forced or sampled. Emulation gives limited visibility, often only a few probes, and a compile can take many hours. Formal verification is different again. It proves properties about the RTL without stimulus, so it suits control logic and protocol invariants.
| Method | How it runs | Typical speed for a large SoC | Visibility | Best use |
|---|---|---|---|---|
| Simulation | Software event driven model | 10 kHz to 1 MHz | Full waveforms, force and release | Directed tests, corner cases, debug |
| Emulation | RTL compiled to hardware | 1 MHz to 100 MHz | Limited probes | Firmware boot, drivers, long traffic, performance |
| Formal | Proof engine over RTL model | No runtime, proof time varies | Counterexample trace | Reset, arbitration, handshake invariants |
A concrete speed check
Take a hypothetical DMA test that moves 1 GB through memory at 64 bytes per cycle. That is about 16.7 million cycles.
| Platform | Assumed clock | Time for 16.7 million cycles |
|---|---|---|
| Emulator | 10 MHz | About 1.7 seconds |
| Simulator | 100 kHz | About 167 seconds |
The simulator figure excludes testbench and software overhead, which usually makes the gap larger. The emulator also runs the real firmware stack, so driver timing and interrupt behaviour are exercised as they will be on silicon. A simulator can run the same test, but the operating system boot alone can consume most of the run.
How the three combine
Formal runs early on blocks with manageable state, such as an interconnect arbiter or a reset controller. Simulation then covers subsystem behaviour with full visibility. Emulation takes over once the RTL is stable enough to justify a compile, which for a design of tens of millions of gates can take 12 to 24 hours. If an emulator failure needs internal waveforms, I reproduce it in simulation. If a control corner case keeps escaping random tests, I write a property and prove it. That division keeps each method on the work it does best.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-23Your two-stage op amp passes nominal AC with 62° phase margin, yet transient settling fails at the slow, cold corner and Monte Carlo offset exceeds spec — how do you diagnose the discrepancy and fix it without losing bandwidth?
The 90-second answer
I would trust all three results and treat the disagreement as the diagnosis. AC at nominal tells me the linearised loop is stable at that bias, temperature and process point. It does not guarantee the same poles at the slow, cold corner, and it says nothing about large signal slew or mismatch offset. Transient at that corner is showing me the real settling, and Monte Carlo is showing me that offset, not nominal gain, will set yield. The fix has to move bias current, compensation and offset together, because changing one moves the others.
First I rerun the analyses at the failing corner instead of arguing about nominal. Same netlist, process slow, temperature -40 C, supply at its minimum, and I extract DC bias, AC phase margin and transient settling from that one setup. If phase margin has fallen from 62 degrees to under 40 degrees there, the nominal AC number was never the design margin.
| Condition | DC bias check | AC result | Transient result |
|---|---|---|---|
| Nominal, 27 C, 1.8 V | Output 0.9 V, all devices saturated | 62 degrees phase margin, GBW 18 MHz | Settles to 0.1% in 180 ns |
| Slow, -40 C, 1.62 V | Tail current down 22%, cascode headroom 180 mV | 38 degrees phase margin, GBW 12 MHz | Rings, settles in 420 ns |
| Slow, -40 C, Monte Carlo mismatch | Input pair delta Vt drawn per run | Gain spread small | Offset sigma 1.8 mV |
The mechanism is consistent. At cold, mobility rises but threshold voltage also rises, and in a typical 180 nm CMOS PDK the net effect in this bias topology is lower transconductance per current and a shifted bias point. The Miller pole moves down in frequency while the output pole moves up, so phase margin collapses. Large signal settling then degrades twice: slew rate falls because tail current fell, and linear settling slows because bandwidth fell.
Exact working on the two failures
Slew rate for the first stage is approximately I_tail / C_c. With C_c = 2 pF and nominal I_tail = 20 uA, SR = 10 V/us. A 0.5 V step needs 50 ns just to slew. At the cold corner I_tail = 15.6 uA, so SR = 7.8 V/us and slew alone takes 64 ns. Linear settling time constant is tau = 1 / (2 pi x GBW). At 12 MHz, tau = 13.3 ns, and settling to 0.1% needs about 6.9 tau, or 92 ns, after slew. Combined, that explains most of the 420 ns once ringing from 38 degrees phase margin is included. No amount of nominal AC margin fixes a bias current that the corner has already removed.
For offset, the arithmetic decides the fix. Spec is 5 mV, measured sigma is 1.8 mV, so the spec sits at 2.78 sigma. For a Gaussian distribution that is about 5,400 ppm failing on a two sided limit, roughly 1 in 185 parts. That is not a marginal pass. I need sigma at or below 1.67 mV for a 3 sigma design, and preferably below 1.25 mV for 4 sigma. Enlarging the input pair helps because delta Vt sigma scales as 1 / sqrt(WL), but doubling area only cuts sigma by 1.41. If I cannot afford that area, I add offset trim or chopping and accept the charge injection and clock feedthrough that come with it.
* Spectre Monte Carlo, mismatch separated from global process
VDD (vdd 0) dc=1.62
VIN (vin 0) dc=0.81 ac=1
XAMP (vin vdd 0 out) opamp_2stage
* Corner check first, then statistics on the same corner
.ac dec 100 10 100Meg
.tran tran=1n stop=2u
* montecarlo numruns=1000 seed=42 mismatch=1 global=0 { tran tran=1n stop=2u }The Monte Carlo setup matters as much as the run count. With mismatch enabled and global disabled, I isolate offset. With global enabled and mismatch disabled, I isolate gain and bandwidth spread. If the PDK model card does not expose separate global and mismatch parameters, the histogram I get is fiction. With 1,000 runs I can estimate sigma and see roughly a 3 sigma tail. I cannot claim 4 sigma yield from 1,000 runs, because I would expect fewer than one failure in the sample.
The fix and its trade-off
I would raise tail current at the cold corner with a bias circuit that tracks mobility, rather than simply increasing nominal current and paying the power cost everywhere. I would increase C_c only enough to restore phase margin at the slow corner, then recover bandwidth with a feedforward zero or cascode compensation, because a larger C_c alone lowers GBW and slew further. For offset I would size the input pair for the sigma target above and add a one time trim range of plus or minus 3 sigma, calibrated at test, instead of chasing offset with area alone.
That sequence is the judgement. Nominal AC is a starting point, corner AC is the stability proof, corner transient is the settling proof, and separated Monte Carlo is the yield proof. Treating any one of them as sufficient is how a design passes simulation and fails silicon.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-24Walk me through designing a two-stage Miller-compensated op amp for 80 dB DC gain, 10 MHz gain-bandwidth and 60 degrees phase margin, covering offset and compensation choices?
The 90-second answer
I would start from the load and the stability target. For a hypothetical 1.8 V design with a 5 pF load, 80 dB DC gain, 10 MHz gain-bandwidth product (GBW) and at least 60 degrees phase margin, I would use a two-stage Miller-compensated op amp: a differential input pair with current-mirror load, a common-source second stage, and a compensation capacitor Cc between the output and the first-stage output. The first stage sets GBW through its transconductance, the two stages split the gain, and Cc creates pole splitting so the dominant pole is low and the non-dominant pole is pushed out.
# Hypothetical design check, 1.8 V process, CL >> Cc assumed
import math
Cc = 2e-12
GBW = 10e6
CL = 5e-12
# GBW = gm1 / (2*pi*Cc)
gm1 = 2 * math.pi * Cc * GBW
# Non-dominant pole approx. p2 = gm2 / CL (rad/s). Target p2 = 3 * 2*pi*GBW.
gm2 = 3 * 2 * math.pi * GBW * CL
# Slew rate approx. I_tail / Cc; 10 V/us needs:
I_tail = 10e6 * Cc
# Phase margin approx. 90 deg - atan(GBW / f_p2), before other poles
pm = 90 - math.degrees(math.atan(GBW / (3 * GBW)))
print(f"gm1 = {gm1*1e6:.0f} uS, gm2 = {gm2*1e3:.2f} mS, I_tail = {I_tail*1e6:.0f} uA, PM = {pm:.1f} deg")That gives gm1 about 126 uS, gm2 about 0.94 mS, a tail current near 20 uA for 10 V/us slew, and about 71.6 degrees of phase margin before other poles are counted. I would then size for gain, check offset by mismatch, and verify phase margin across corners and load, because nominal numbers alone do not close the design.
Gain, bandwidth and compensation
DC gain is the product of the stage gains: A0 = (gm1 * Rout1) * (gm2 * Rout2). Splitting roughly 40 dB per stage keeps each stage in a comfortable range and avoids forcing one stage to carry all the gain with a very large output resistance. Rout is set by transistor output resistance in parallel with any load, so gain falls if the second stage drives a low resistance or if devices enter triode near the rails.
With Miller compensation, the dominant pole is approximately p1 = 1 / (2pi * Rout1 * Cc * A2), where A2 is the second-stage gain. The ideal GBW expression, gm1 / (2pi*Cc), does not contain CL. Usable bandwidth and phase margin do depend on CL, through the non-dominant pole near the output, approximately p2 = gm2 / CL in rad/s when CL >> Cc. The price of a larger Cc is slew rate, about I_tail / Cc for the input stage, plus area.
Phase margin is approximately 90 degrees minus atan(GBW/p2), minus contributions from other poles. If p2 is only equal to GBW, that term alone costs 45 degrees. Pushing p2 to three times GBW costs atan(1/3), about 18.4 degrees, leaving about 71.6 degrees before other poles. That is why gm2 must be sized from the load, not just from DC gain.
Cc also creates a right-half-plane zero near gm2 / Cc. A nulling resistor in series with Cc, set near Rz = 1/gm2, can cancel that zero. I would include it when the zero hurts phase margin, and check that it does not create a left-half-plane zero that wastes bandwidth or a layout-dependent mismatch. A cascode or feedforward compensation scheme can improve bandwidth but adds complexity and sensitivity to matching, so for a basic design Miller compensation with a nulling resistor is the defensible default.
| Quantity | Design relation | What it trades against |
|---|---|---|
| GBW | gm1 / (2piCc) | Input pair current and Cc area |
| DC gain | gm1Rout1 * gm2Rout2 | Output resistance, headroom, load |
| Non-dominant pole | gm2 / CL | Second-stage current, power |
| Slew rate | I_tail / Cc | Tail current, Cc value |
| Phase margin | 90 deg - atan(GBW/p2) - other poles | Load range, parasitic poles |
Offset
Input-referred offset comes mainly from input-pair threshold mismatch and current-mirror mismatch, plus load mismatch referred back through the gain. Pelgrom scaling is the guide: sigma for threshold mismatch falls as 1/sqrt(W*L), so larger input devices and longer channels reduce offset at the cost of capacitance, which lowers bandwidth and increases area. Common-centroid layout, interdigitated fingers, dummy devices and symmetric routing reduce systematic gradients across the die.
If a system budget required an offset far below what sizing and layout give, I would consider chopper stabilization or auto-zeroing. Both add switches, clock feedthrough, ripple and complexity, and chopping can fold noise into the band. For a basic op amp I would first meet the stated offset target with area and layout, then add calibration only if the system budget demands it.
Verification and failure modes
I would check DC gain, GBW, phase margin and slew in open loop and in the intended feedback configuration, across process corners, temperature, supply variation and the full load range. Monte Carlo simulation is where offset and phase margin spread show up, since mismatch moves both the input pair and the mirror. Transient tests at the actual feedback factor matter because a unity-gain buffer is usually the worst case for stability, while a large feedback factor can hide a marginal design.
The common failure is a design that meets 60 degrees at nominal load and fails with a larger capacitor, a lower gm2 at the slow corner, or extra parasitic capacitance at the first-stage output. I would guard against that by designing p2 with margin, extracting layout parasitics before signoff, and rechecking phase margin with the extracted load rather than the schematic value.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-25How does a successive approximation ADC convert a sample, and why would you choose it over a flash ADC for a 10-bit, low-power sensor interface?
The 90-second answer
A successive approximation ADC, or SAR, converts one sample by testing bits from most significant to least significant. It reuses a single comparator and a digital-to-analog converter, so it uses far less area and power than flash. Flash compares the input against every reference level at once, which makes it fast but expensive as resolution rises. For a 10-bit, low-power sensor I would choose SAR, because 1023 flash comparators would dominate the design for a sample rate the SAR can reach with a modest internal clock.
How SAR converts
The ADC first holds the input on a sample-and-hold capacitor. The SAR register then sets the MSB trial value. The DAC produces that trial voltage, the comparator checks whether the input is above or below it, and the register keeps or clears the bit. The same process repeats for each lower bit. A 10-bit conversion therefore needs 10 decisions, and the DAC must settle before each comparison.
Worked trace for a 4-bit SAR with a 1.6 V reference and a 0.95 V input. One LSB is 0.1 V.
| Step | Trial code | DAC output | Decision |
|---|---|---|---|
| MSB | 1000 | 0.80 V | Input is higher, keep 1 |
| Next | 1100 | 1.20 V | Input is lower, clear 0 |
| Next | 1010 | 1.00 V | Input is lower, clear 0 |
| LSB | 1001 | 0.90 V | Input is higher, keep 1 |
The result is 1001, or 9 decimal. Each decision narrows the range for the next one, which is why the order matters and why an early settling error can corrupt every later bit.
Flash for comparison
Flash places 2^N - 1 comparators in parallel across a resistor ladder. All comparators compare in the same clock cycle, their outputs form a thermometer code, and an encoder produces the binary result. Conversion takes one clock, so flash suits high sample rates and low latency. The cost is hardware. At 10 bits, flash needs 1023 comparators, plus the ladder and encoder. At 8 bits it needs 255, which is why flash is common at lower resolutions and higher speeds.
| Property | SAR | Flash |
|---|---|---|
| Comparators | 1 | 2^N - 1 |
| Conversion time | N cycles | 1 cycle |
| Area and power | Low, scales gently with N | High, grows quickly with N |
| Typical use | 8 to 16 bits, low to medium speed | 6 to 8 bits, high speed |
Applying the choice
For 10 MS/s with a 10-bit SAR, the conversion clock must run at least 10 times the sample rate, so about 100 MHz before allowing time for sampling and settling. That is a reasonable internal clock for a sensor interface. Flash would convert in one cycle, but the design would pay for 1023 comparators, their offsets, and the reference ladder to gain speed the sensor does not need. SAR also fits the power budget because only one comparator switches per decision and the capacitor DAC dominates the analog area.
I would move toward flash only if the sample rate rose enough that N SAR cycles became impractical, or if the system needed a result in a single clock. At higher resolutions, SAR remains attractive because its hardware grows roughly with N, while flash hardware doubles with each added bit.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-26How do R-2R, segmented, and current-steering DACs differ in linearity and speed, and when would you choose each one?
The 90-second answer
Pick the architecture by which error you can afford. An R-2R ladder gives you a compact, fast, inherently monotonic converter whose linearity is set by resistor ratio matching. A segmented DAC trades area for the best linearity and lowest glitch energy by building the MSBs from identical unary elements. A current-steering DAC is the high speed member of that family: it switches constant current sources into a load, so the output settles without the RC charging of a voltage DAC, at the cost of current source matching, compliance voltage and clock feedthrough.
R-2R ladder
Every bit sees the same Thevenin resistance because each 2R resistor in parallel with R+R to ground equals R. The output current or voltage therefore halves per bit, and only two resistor values are needed. That makes a 12 to 16 bit R-2R practical without 4095 matched resistors. Linearity depends on the ratio of the two values. With laser trimmed or well laid out poly resistors, ratio errors of 0.01% to 0.1% are typical, which bounds INL and DNL. Speed is limited by the ladder RC time constant and by switch charge injection, so it suits audio and instrumentation at a few MS/s to tens of MS/s rather than RF.
The failure mode is ratio drift with temperature and voltage coefficient mismatch. A 100 ppm per degree C mismatch over 100 degrees C moves a ratio by 1%, which destroys a 12 bit transfer curve. Common centroid layout and matched resistor types are the fix, and they consume area.
Segmented DAC
Split the code into unary MSBs and binary LSBs. For a 12 bit DAC with 6 unary MSBs and 6 binary LSBs, the MSB section needs 63 unit elements (2^6 - 1) and the LSB section needs 6 binary weighted elements weighted 1, 2, 4, 8, 16 and 32 units. Total unit equivalents are 63 + 63 = 126, against 4095 for a fully unary design. That arithmetic is the point: area grows as 2 to the power of the unary bits, so segmentation is what makes high resolution feasible.
Unary elements are identical, so their mismatch averages out and major code transitions switch several elements at once in a thermometer pattern. That gives low DNL, no missing codes, and much lower glitch impulse than a binary DAC where the midscale transition flips every bit. The cost is decoder logic, routing of 63 lines, and larger capacitance on the output node, which can slow settling unless the elements are current sources.
Current-steering DAC
Each element is a current source, usually a cascode pair, steered to the output or to a dummy load by a differential switch pair. Because the total current is constant, the supply sees no code dependent transient. The output is a current into a resistor or transimpedance amplifier, so bandwidth is set by the load and the switch, not by charging a large capacitor bank. That is why current steering dominates wideband transmitters above 100 MS/s.
Linearity is set by current source matching and by output impedance. A cascode raises output impedance so that load voltage swing does not modulate the current. The limits are compliance: the cascode needs headroom, typically 0.5 to 1 V in a modern CMOS process, and switch mismatch creates code dependent glitch energy at the output. Dynamic element matching, which rotates which physical element is used for each code, spreads mismatch into noise and is standard in 14 bit and above converters.
| Architecture | Linearity set by | Speed limit | Area driver | Typical use |
|---|---|---|---|---|
| R-2R ladder | Resistor ratio accuracy | Ladder RC, switch injection | Two resistor values, switches | Audio, precision control, 10 to 16 bit |
| Segmented voltage | Unary element matching | Output capacitance, decoder delay | 2 to the power of unary bits | 12 to 16 bit, low glitch |
| Current steering | Current source matching, cascode impedance | Switch timing, load bandwidth | Current sources, cascode headroom | RF transmit, 100 MS/s and above |
A concrete check: take a 10 bit DAC segmented as 4 unary MSBs and 6 binary LSBs. Each unary element carries 64 LSB of current. If unit current mismatch is 0.1% RMS, a thermometer step turns on exactly one additional unary element, so the RMS DNL at that step is 0.001 x 64 = 0.064 LSB. The full 15 element segment has RMS error sqrt(15) x 0.001 x 64 = 0.25 LSB, which is an INL contribution, not a step error. In a plain binary design the midscale step turns the MSB off and all LSBs on, so DNL there is the difference between the MSB error and the sum of the LSB errors, a larger and less predictable combination. That single step calculation is why segmentation, not just matching, buys DNL.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-27How would you partition a mixed-signal SoC floorplan to keep digital switching noise from degrading a 12-bit ADC and PLL, covering power domains, grounding, and isolation?
The 90-second answer
I would treat the analog island as a victim that has to survive the digital block at its worst activity, not at idle. That means separate supply pins and on-chip regulation for AVDD, a quiet reference, and the PLL, a physical moat and guard structures between analog and digital, and a single controlled join between AVSS and DVSS. Digital current returns in DVSS and its own grid. Analog current returns in AVSS. If those returns share a narrow path, the voltage drop from a digital transient appears across the ADC input or reference and shows up as code noise or a spur.
Partitioning starts in the floorplan. I place the ADC, its reference, and the PLL together on one edge near their package pins, with the noisy digital core and SRAM banks on the other side. Between them I leave a gap filled with substrate contacts and guard rings tied to AVSS, and I put the digital block in a deep n-well where the process allows it. The analog island gets its own power grid, fed through a low-pass filter or LDO from AVDD, with local decoupling close to each analog macro. The digital grid gets bulk decoupling at the macro level. Crossing signals between domains go through level shifters, and any signal that can be driven while the receiving domain is off goes through an isolation cell.
Why the coupling happens
There are four paths I check, and each one needs a different fix.
| Coupling path | Mechanism | Mitigation I would verify |
|---|---|---|
| Shared supply impedance | Digital di/dt drops voltage across package and grid inductance, modulating AVDD and the ADC reference | Separate pins, on-chip LDO or RC filter for AVDD, decoupling placed within a few hundred microns of the ADC |
| Shared ground impedance | Digital return current raises AVSS locally, shifting the ADC input common mode | Separate AVSS and DVSS nets, single low-impedance join at the pad ring, no digital return crossing the analog island |
| Substrate injection | Switching currents inject charge into the substrate, which couples into analog wells and the PLL | Guard rings, substrate contacts, deep n-well isolation, physical distance, keep high-current drivers away from the PLL |
| Capacitive and magnetic coupling | Clock and bus edges couple into high-impedance analog nodes and bondwires | Route analog inputs away from digital buses, shield or differential-route sensitive nets, keep the PLL clock inside the island |
A quick estimate shows why the supply path dominates. Suppose 50 mA of digital current switches in 1 ns through 1 nH of package and bondwire inductance. The bounce is L times di/dt, so 1 nH times 50 mA per ns gives 50 mV. On a 1.8 V ADC with a 12-bit range, one LSB is about 440 microvolts. Even if the on-chip filter attenuates that bounce by 40 dB, roughly 0.5 mV remains, which is already above one LSB. That is why I would not rely on a single off-chip capacitor and why the reference needs its own filtered pin and local decoupling.
Isolation and power domains
Every power domain that can be gated needs three things at its boundary: a level shifter if the voltages differ, an isolation cell if the domain can be off while the other side is live, and retention only where state must survive. Without the isolation cell, an off domain can clamp a shared bus, back-drive current through ESD diodes, or propagate X values into the analog control logic when it powers back up. I would also sequence the domains so AVDD and the reference come up before the ADC is enabled, and I would hold the ADC in reset until the PLL reports lock.
How I would prove it works
I would measure ADC SNR and ENOB with the digital block idle, then with it running a worst-case pattern such as all SRAM banks switching and the bus at full activity. A spur at the digital clock frequency or its harmonics in the ADC spectrum points to supply or substrate coupling. I would repeat that across voltage and temperature corners, because decoupling capacitance and LDO performance move with process. On the PLL side, I would check jitter with digital activity on and off. If jitter rises only when a specific block switches, that block is the aggressor and I would move its drivers, add decoupling, or reroute its return path before I touched the PLL itself.
The failure mode I worry about most is a design that passes with the digital block idle and fails in the product, where firmware runs the core, DMA, and radio together. Partitioning has to be validated under simultaneous activity, not inferred from a quiet bench test.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-28Walk me through layout design rules, DRC and LVS, and how you would debug a DRC or LVS failure you find after layout?
The 90-second answer
Design rules are the foundry's contract for what can be manufactured reliably. They specify minimum width, spacing, enclosure, extension and density for every layer, plus device rules for well spacing, antenna length and latch-up guard rings. DRC checks the polygons you drew against those geometric rules. LVS checks that the circuit you drew is the circuit you intended, by extracting devices and nets from layout and comparing them to the schematic netlist. A clean DRC with a failed LVS usually means the geometry is manufacturable but the connectivity is wrong. A clean LVS with a failed DRC means the connectivity is right but the shapes cannot be printed or will fail in silicon.
What the rules actually constrain
Rules come from the PDK for a specific process, for example a 28 nm CMOS flow, and they are layer specific. Metal 1 might require 0.07 um width and 0.07 um spacing in that hypothetical deck, while a via requires enclosure by metal on both sides. Poly rules control gate length and spacing, which set transistor behaviour. Implant and well rules control where nMOS and pMOS devices can sit and how far apart wells must be. Density and antenna rules are less obvious. Density rules keep chemical mechanical polishing from dishing the wafer, and antenna rules limit the total gate area connected to a long metal run so plasma charging during fabrication does not punch through a thin gate oxide.
You do not memorise the deck. You work from the PDK rule deck in the EDA tool, and you check the rule name and layer when a marker appears, because the fix for a spacing error differs from the fix for an enclosure error.
| Check | Question it answers | Typical failure | First place to look |
|---|---|---|---|
| DRC | Can this geometry be built? | M1 spacing 0.05 um where 0.07 um is required, via without enclosure, missing well contact | Marker coordinates, the two offending polygons, the rule description |
| LVS | Is this the schematic circuit? | Short between two nets, open net, transistor bulk tied to the wrong supply, device width mismatch | Extracted netlist versus schematic, device by device, net by net |
| Density / antenna | Will it survive fabrication and polishing? | Low density region, long metal antenna on a gate | Density map, antenna report per net |
How I debug a failure
For DRC, I open the marker, not the whole layout. The tool reports the layer, rule name and coordinates. I zoom to that point, highlight the offending polygons and read the rule in plain language. A spacing marker between two M1 polygons usually means I need to move one shape or narrow it. An enclosure marker on a via usually means the via sits too close to the metal edge, so I enlarge the metal or move the via. I fix the smallest area possible, because moving a block can create a new spacing error elsewhere, then I re-run DRC on the affected cell before running the full chip.
For LVS, I work from the mismatch report rather than hunting visually. LVS extracts transistors from poly, diffusion and implant shapes, then builds nets from metal and contact connectivity. It compares device count, device type, width and length, and net connectivity against the schematic. If it reports a short, I find the two schematic nets named in the report and look for a metal shape or contact that joins them in layout. If it reports an open, I look for a missing contact, a metal gap, or a label that does not match. The classic trap is the bulk connection. An nMOS device needs its p-well tied to ground and a pMOS device needs its n-well tied to VDD. If that well contact is missing or tied to the wrong rail, extraction creates a floating bulk or a parasitic device, and LVS fails even though the drain and source look correct.
A worked trace helps. Suppose LVS reports net VDD shorted to net OUT in an inverter cell. I check the extracted netlist first. It shows a pMOS drain connected to both nets through a shared diffusion region. In layout I find the pMOS and nMOS diffusion placed too close, or a metal shape bridging the output node to the supply rail. I separate the shapes, add the required spacing, and re-extract. If the report instead says device count mismatch: schematic 2, layout 3, I suspect a parasitic transistor formed by an unintended poly crossing diffusion, often a dummy fill shape or a guard ring that was drawn as active poly. Removing or converting that shape to a non-device layer clears it.
I never sign off on one check alone. DRC clean and LVS clean together, plus density and antenna reports clean, is the point where layout goes to parasitic extraction for timing and IR drop. If either check fails, the fix goes back to layout, and both checks run again, because a geometry fix can change connectivity and a connectivity fix can create a new spacing violation.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-29Walk me through parasitic extraction after place and route, and how interconnect resistance and capacitance change timing and signal integrity?
The 90-second answer
Parasitic extraction converts the placed and routed layout into the resistances and capacitances the timing engine actually sees. Synthesis used wireload estimates. After routing, the extractor reads the layout polygons with the foundry parasitic technology file, which gives metal resistivity, thickness, and dielectric constants per layer. For every routed segment it computes resistance from length, width, and sheet resistance, plus capacitance from plate area, fringe, and coupling to neighbouring nets and ground. It emits an RC network per net, usually as SPEF, and an extracted netlist for static timing analysis.
That RC network changes two things. First, delay and slew: a net is no longer a zero delay node, so the driver sees load capacitance, the far end sees Elmore delay through the distributed resistance, and a degraded input slew makes the receiving cell slower. Setup slack shrinks, sometimes by tens of picoseconds on a long route. Second, signal integrity: coupling capacitance to an aggressor net injects noise, can push out victim delay, and can glitch a victim that should stay quiet. A path that passed synthesis can fail after extraction for both reasons, which is why signoff STA runs on extracted parasitics.
How extraction builds the network
The extractor also splits nets at vias and layer changes, because via resistance and interlayer capacitance differ sharply from in-layer values. Output format matters for accuracy. A lumped model puts all R and C at one node and underestimates far end delay on a long line. A pi or T model, or a full RC tree, preserves where capacitance sits relative to resistance. For most on-chip digital nets, RC extraction is the signoff model. RLC is reserved for package, board, and high speed IO where inductance and return path geometry matter at multi gigabit rates.
Worked delay, hypothetical figures
Take a 2 mm intermediate metal route, labelled as an example rather than a foundry number: R' = 50 ohm/mm, C' = 200 fF/mm, driven through a 20 ohm driver, with a 50 fF gate load at the far end.
| Quantity | Value |
|---|---|
| R wire | 100 ohm |
| C wire | 400 fF |
| Lumped RC | 40 ps |
| Elmore delay, uniform distributed line | about 20 ps |
| Extra delay from far end load, R times Cload | 5 ps |
Elmore delay for an RC tree is the sum over each resistor of R times the capacitance downstream of it. That is why the distributed figure is roughly half the lumped RC for a uniform line, and why moving capacitance to the far end hurts more than the same capacitance near the driver. The same wire also degrades slew. If the 10 to 90 percent rise time stretches from 20 ps to 60 ps, the receiving cell delay rises even before the Elmore term is added, and the timing tool models that through its cell delay tables indexed by input slew and output load.
Timing and signal integrity effects
| Effect | Mechanism | Typical fix |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Setup delay pushout | Wire RC plus slew degradation on the launch or capture path | Buffer insertion, wider metal, shorter route, stronger driver |
| Crosstalk delay | Coupling C to a switching aggressor, Miller factor up to 2 when victim and aggressor move in opposite directions | Increase spacing, reorder routes, shield critical victim |
| Glitch or false switching | Aggressor transition couples charge onto a quiet victim through Cc | Spacing, shielding, stronger keeper or driver on victim |
| Hold risk on short nets | Extraction reveals a path is faster than the wireload model assumed | Add delay cells or buffers, recheck with max and min corners |
Extraction corners are separate from process corners. Timing signoff typically runs a max R, max C corner for setup and a min R, min C corner for hold, because the worst case for each check differs. Coupling is included in SI aware STA, where the tool considers aggressor slew and direction instead of treating every neighbour as ground.
Failure modes I watch for
A common one is a missing or stale parasitic tech file after a metal stack change, which silently produces optimistic SPEF. Another is extracting before routing is fully clean, so ECO routes added later carry no parasitics. Long unbuffered routes on a high speed clock net are the third: average delay looks acceptable, but slew at the far end violates the cell library limit and creates a large, nonlinear delay that a simple RC estimate missed.
Fixes follow the mechanism. Buffer a long net to split R and C into smaller segments. Widen the wire to cut R, accepting more C to ground. Space or shield a victim to cut Cc. Move the block in the floorplan to shorten the route in the first place. Then re-extract and rerun STA, because each fix changes the RC tree the previous result was based on.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-30How does scan chain insertion make internal logic testable, and what happens during shift and capture?
The 90-second answer
Scan insertion turns ordinary flip-flops into a shift register you can load and unload from the chip boundary. Each flop gets a mux in front of its D input: when scan enable is high, D comes from the previous flop in the chain; when it is low, D comes from normal logic. That one mux makes every internal node controllable and observable from scan_in and scan_out, which is what ATPG needs to generate patterns for stuck-at faults.
Two modes do the work. In shift mode, SE = 1, you clock a test pattern in one bit per cycle. In capture mode, SE = 0 for one cycle, the logic evaluates that pattern combinationally and the flops capture the response. Shift the response out while shifting the next pattern in. A chain of N flops takes N shift cycles plus one capture cycle per pattern.
// One scan flop, checked against IEEE 1500 / Synopsys DC scan style netlists
module scan_dff (
input logic clk, se, si, d,
output logic q, so
);
logic mux_in;
assign mux_in = se ? si : d;
always_ff @(posedge clk)
q <= mux_in;
assign so = q;
endmoduleWorked trace: 4-flop chain
Chain order is q0 -> q1 -> q2 -> q3, with scan_in feeding q0. Suppose the pattern to load is 1 0 1 1 (first bit enters q0) and combinational logic between the flops produces a captured response of 0 1 0 0.
| Cycle | SE | scan_in | q0 q1 q2 q3 after edge | What happens |
|---|---|---|---|---|
| 1 | 1 | 1 | 1 0 0 0 | shift |
| 2 | 1 | 0 | 0 1 0 0 | shift |
| 3 | 1 | 1 | 1 0 1 0 | shift |
| 4 | 1 | 1 | 1 1 0 1 | shift, pattern loaded |
| 5 | 0 | x | 0 1 0 0 | capture, logic response latched |
| 6-9 | 1 | next pattern bits | response shifts out on scan_out | shift out |
That is 5 cycles to apply and capture one vector, plus 4 to unload it, overlapped with loading the next vector in a real tester. Test time is roughly patterns times chain length, which is why long chains get split into multiple chains to cut shift time and why compression (EDT, Huffman style) is added on large SoCs.
Coverage and what limits it
Stuck-at coverage is detected faults divided by total faults ATPG models, usually reported after excluding untestable faults. A block with 100,000 modeled faults and 98,500 detected faults is at 98.5% stuck-at coverage. Transition fault coverage is lower and matters for timing defects, because it needs a launch cycle and a capture cycle at speed with SE deasserted between them.
Coverage stalls on DFT rule violations, and the fix is in RTL, not in ATPG. A gated clock with no test clock override cannot be shifted. A combinational loop or a latch inferred from an incomplete case cannot be scanned. An asynchronous set or reset that is not synchronised for test, or a clock mux glitch, creates unknown values that ATPG marks untestable. A multi-clock block needs each domain to have a controllable test clock and a reset that ATPG can initialise. I run DFT rule checks before synthesis, fix violations in RTL, then re-run ATPG and inspect the untestable fault list by name. Chasing the last percent by waiving faults without reading them hides real escapes, especially on reset and clock control logic that functional simulation rarely exercises.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-31How would you architect MBIST and LBIST for a SoC with 8 MB SRAM and 2M logic gates, and trade fault coverage against test time, power, and at-speed capture?
The 90-second answer
I would split the problem by structure. Memories get MBIST because a scan chain cannot efficiently exercise a 6T SRAM cell, its sense amplifier, or a weak write driver. Random logic gets LBIST because scan ATPG at the tester is too slow and expensive for a 2M gate block in volume production. The two share a test controller, a clock and power plan, and a signature readout, but they run under different constraints.
For the 8 MB SRAM, say eight 1 MB macros, I would use a march algorithm with spare row and column repair, run it at functional voltage and at the low voltage corner, and compress the result to a pass or fail plus a failing address. For logic, I would insert scan, add a PRPG to drive the scan chains and a MISR to compact the responses, then run LBIST at speed for a fixed number of cycles and compare the final MISR signature against the golden signature from fault simulation. Fault coverage decides whether that cycle count is enough. If coverage is 97% for stuck-at faults, the remaining 3% is not random noise. It is usually hard to control logic, clock gating, or reset logic, and I would fix the DFT rule violations rather than simply run longer.
| Item | MBIST | LBIST |
|---|---|---|
| Target | SRAM, ROM, register files, CAM | Random logic, control, datapath |
| Stimulus | March or checkerboard patterns through a dedicated port | PRPG pseudo random patterns shifted through scan chains |
| Response | Comparator per cycle, address capture on mismatch | MISR compaction, final signature compare |
| Typical coverage | >99% for cell defects with a full march, lower for analog assist circuits | 95 to 98% stuck-at after fault simulation, transition fault coverage lower |
| Main cost | Area for controller and muxing, test time per macro | Scan flops, PRPG and MISR area, power during shift and capture |
MBIST in practice
A march test writes and reads each cell under several data backgrounds. March C- does 10 operations per cell and catches most stuck-at, transition, coupling, and address decoder faults in a 6T array. For a 1 MB macro with 32-bit width, that is 262,144 addresses times 10 operations, about 2.6M cycles per macro before repair. At a 100 MHz BIST clock that is 26 ms per macro. Eight macros in parallel cut wall time but raise peak current, so I would stagger them or limit parallel banks based on the power grid and IR drop budget.
Repair matters. A spare row and spare column scheme can fix a single bad row or column without discarding the die. The MBIST controller records the failing address, tries the spare, and retests. If a second row fails, the macro is flagged and the die is scrapped or downgraded. I would also run MBIST at the lowest operating voltage, because a cell that passes at 0.9 V can fail at 0.7 V in a low power mode due to a weak pull up or a slow write.
// Simplified LBIST signature check, checked against a golden value
// from fault simulation. Signature is read after the fixed cycle count.
module lbist_check(input logic clk, input logic [31:0] misr_sig,
input logic [31:0] golden_sig, output logic pass);
assign pass = (misr_sig == golden_sig);
endmoduleLBIST and fault coverage
Fault coverage is detected faults divided by total faults considered. Suppose fault simulation injects 100,000 stuck-at faults into the logic block. If 96,500 are detected by the LBIST patterns, coverage is 96.5%. The undetected 3,500 faults need classification. Some are redundant and can never be detected. Some sit in logic that is gated off during test. Some need a specific sequence that a PRPG hits only after millions of cycles. Running LBIST for 1M cycles might reach 96.5%, while 10M cycles might reach 97.2%. That extra 0.7% costs test time and power on every die, so the trade is economic as well as technical.
At speed capture is the other constraint. LBIST can shift at a low clock to save power, then capture at the functional clock to catch transition faults and timing defects. That capture pulse is where a marginal path fails. If the design cannot meet timing at speed during test, the signature will mismatch even though the logic is functionally correct. I would constrain the test clock paths, keep the capture clock close to the functional clock, and verify the signature in simulation with timing aware models before silicon.
Failure modes I watch for
A common one is clock gating left enabled during LBIST. The PRPG drives scan flops, but a gated clock stops part of the chain, so the MISR signature depends on the gating state and becomes unstable. The fix is a test mode that forces clocks on or bypasses gating, verified by a DFT rule check.
Another is power. Shifting thousands of scan flops at once can draw far more current than functional operation. I would measure the shift current in simulation, limit the number of chains shifting in parallel, and insert wait states if the supply droop moves the delay beyond the test clock period.
Finally, a signature mismatch does not tell you which fault caused it. I would keep the failing address from MBIST and, for LBIST, keep the ability to dump the MISR value and rerun with deterministic ATPG patterns on a failing die. That turns a bare pass or fail into a diagnosable result, which is what makes BIST useful in production rather than just a checkbox at tapeout.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-32A board passes continuity but fails functional test. How would you use JTAG boundary scan to locate an open or short on a net, and what faults would it still miss?
The 90-second answer
JTAG, standardised as IEEE 1149.1, gives every compliant chip a Test Access Port (TAP) and a serial shift path that can reach pins and, through scan chains, internal flops. On a board you daisy-chain devices by connecting TDO to the next TDI, with TCK and TMS common. You shift an instruction into the Instruction Register (IR), then shift data through the Data Register (DR) selected by that instruction. Boundary scan puts a controllable, observable cell on each digital pin, so you can drive a pin from the chip, sample a pin into the chip, and walk a known pattern across interconnect without the functional logic running.
That separation is the point. Functional logic can be broken, in reset, or unclocked, and the TAP still works from TCK alone. You test board wiring with the core idle, then test the chip itself by shifting patterns into internal scan chains.
How the TAP moves
TMS decides the next state on each rising edge of TCK. A reset sequence is five cycles with TMS high, which forces Test-Logic-Reset from any state. From there you navigate to Shift-IR or Shift-DR, shift LSB first, then exit to Update-DR, where the parallel outputs change.
The four pins you must get right are TCK (clock), TMS (state control, sampled on TCK rising edge), TDI (serial in), and TDO (serial out, changes on TCK falling edge in most implementations). TRSTn is optional and often tied inactive because a stuck reset can lock the TAP.
Board interconnect test
Each boundary cell has a capture mux and a launch flop. In EXTEST, the launch flops drive the pins and the capture flops observe them. In SAMPLE/PRELOAD, the cells capture live pin values or preload a value without driving, so you can check timing or set up a state before releasing the chip.
Worked trace, two devices in a chain, Device A upstream of Device B. Total boundary length is 64 bits. You want B to drive a 1 on its pin 3 and A to capture it.
| Step | Action | Result |
|---|---|---|
| 1 | Shift EXTEST opcode into both IRs, Update-IR | Both TAPs select the boundary register |
| 2 | Shift 64-bit pattern: B pin 3 = 1, all other drive bits = 0, capture bits = don't care | Pattern sits in shift path |
| 3 | Update-DR | B pin 3 drives high, other pins drive low |
| 4 | Shift 64 bits again with TDI = 0 | Capture flops shift out on TDO |
| 5 | Compare shifted-out stream to expected | A capture bit for the net from B pin 3 should read 1 |
If that bit reads 0, the net is open, shorted to ground, or B is not driving. If it reads 1 on a neighbour net as well, suspect a solder bridge. Repeating with walking-1 and walking-0 patterns across all pins finds shorts between pairs, which a single all-ones pattern can miss.
The common instructions are:
| Instruction | Selects | Use |
|---|---|---|
| IDCODE | Device ID register | Verify chain order and that every device answers |
| BYPASS | Single bypass flop per device | Shorten the chain so other devices pass data through in 1 cycle each |
| EXTEST | Boundary register | Drive pins, capture pins, test interconnect |
| INTEST | Boundary register plus internal scan | Drive internal logic from the boundary and capture responses |
| SAMPLE/PRELOAD | Boundary register | Capture or preload without driving |
IDCODE first matters. If the shifted-out ID does not match the expected part number, every later result is suspect. A missing device breaks the chain and shifts all downstream bits by its length.
Chip test through the same port
INTEST and internal scan reuse the idea inside the chip. Test flops replace or augment functional flops, muxed so a scan enable selects the shift path. You shift a vector in, pulse the functional clock once, shift the response out, and compare it to simulation. That is how you get stuck-at coverage for logic that has no pin access. Memory BIST and logic BIST often hang off the TAP as well, so one controller can run scan, then BIST, then report a signature.
Cost is time. A 1,000-cell chain at 10 MHz TCK needs 100 microseconds per shift, plus capture cycles. A pattern set of 10,000 vectors is about a second for that chain, before you count multiple chains or a board with ten devices. That is fine for manufacturing test and debug, and far too slow for at-speed functional test.
Where it stops working
Boundary scan sees digital pins and scannable flops. It does not see inside an SRAM array unless BIST covers it, it does not measure analog behaviour, and it does not prove the chip works at its functional clock rate. A path can pass scan at 10 MHz TCK and fail timing at 1 GHz because scan shift timing, clock skew, and power supply behaviour differ from functional mode.
High-speed and AC-coupled links need extensions. IEEE 1149.6 adds boundary cells that can drive and sample AC-coupled signals and detect opens on differential pairs, but coverage is still limited and the cells must be designed in. Power delivery, clock jitter, PLL lock, and signal integrity on a 25 Gb/s lane are outside 1149.1 entirely. You need eye diagrams, BERT, and a scope or protocol analyser for those.
Other limits show up on real boards. TCK frequency is limited by chain length and signal integrity, often 10 to 50 MHz in practice rather than the headline maximum. A device without a TAP, or with TAP disabled by a fuse, breaks the chain unless you use BYPASS or a breakout. Stuck-at faults that need a specific clock domain running, faults in clock trees, and faults that only appear under load or temperature will pass a room-temperature scan test. Scan also cannot test non-scannable logic such as some asynchronous logic, latches without scan, or flops that were excluded to save area, so coverage depends on the scan insertion report, not on the presence of JTAG alone.
Security is a practical limit too. An enabled TAP on a shipped product can allow firmware extraction or fault injection, so many SoCs fuse off debug access after test. That protects the product and removes your debug path in the field, which is a trade-off to decide before tapeout, not after a failure in the lab.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-33Walk me through designing an AXI interconnect for a 64-bit SoC bus at 200 MHz, covering bursts, QoS and arbitration, and how you would hit bandwidth and latency targets?
The 90-second answer
I would start from traffic, not topology. For each master I would list sustained and peak bandwidth, burst length, latency deadline, and ordering requirements. Then I would size the interconnect so sustained demand fits below peak with headroom, and use QoS and arbitration to protect latency-critical masters when demand exceeds supply.
Assume a 64-bit AXI4 interconnect at 200 MHz. Peak data bandwidth is:
64 bits x 200 MHz / 8 = 12.8 GB/s
That is before wait states, address overhead, and turnaround. If masters demand 9 GB/s sustained, about 30% headroom remains. If they demand 12 GB/s sustained, arbitration cannot fix it. I would widen the bus, raise the clock, split a hot slave onto a separate port, or move a master to a point-to-point path.
Bursts
AXI4 describes a burst with AxLEN, AxSIZE, and AxBURST. AxLEN encodes beats minus one, so a value of 15 means 16 beats. AxSIZE encodes log2 of bytes per beat. AxBURST selects INCR, WRAP, or FIXED. A long INCR burst amortises one address phase over many data beats, so it approaches peak bandwidth. Short bursts pay more address overhead per beat.
I would check three details per master. Maximum burst length, because it affects buffering and how long other masters wait. WRAP use for cache line fills, where the interconnect must preserve the wrapped sequence. FIXED use for FIFO-like slaves, where addresses must not be widened or split in a way that changes the pattern. If a burst crosses an address boundary the interconnect cannot handle as one transaction, it may need to split it, and that changes the beat count seen by the slave.
// Illustrative QoS assignment for a 64-bit AXI4 interconnect
// AxQOS is 4 bits in AXI4 (AMBA IHI 0022). Values are design choices.
assign cpu_awqos = 4'hF; // latency critical
assign dma_awqos = 4'h8; // throughput oriented
assign disp_awqos = 4'h2; // needs a minimum share, not top priority
assign cpu_arqos = 4'hF;
assign dma_arqos = 4'h8;
assign disp_arqos = 4'h2;QoS and arbitration
Masters drive AxQOS on the address channels. The interconnect maps that field to an internal priority. QoS alone does not reserve bandwidth, so I would pair it with an arbitration policy and a starvation guard.
| Policy | Behaviour | Use case |
|---|---|---|
| Fixed priority | Highest priority master wins whenever it requests | Only when other masters can tolerate indefinite delay |
| Round robin | Masters take turns in order | Fair sharing among similar masters |
| Weighted round robin | Turns proportional to a weight | Predictable shares, weights need tuning |
| QoS plus aging | QoS sets base priority, wait time raises it | Protects deadlines while limiting starvation |
I would use QoS plus aging in this example. CPU and DMA get high AxQOS. Display gets lower AxQOS but a guaranteed minimum share, so a long DMA transfer cannot starve it indefinitely. Aging promotes any master that has waited beyond a threshold, for example 64 cycles in this hypothetical design, regardless of AxQOS. That bounds worst-case arbitration delay if the arbiter implements aging correctly.
Meeting bandwidth and latency targets
Long bursts and many outstanding transactions raise bandwidth but increase the wait for a short transaction queued behind them. I would set a latency budget per master, for example 200 cycles worst case for the CPU in this hypothetical design, then allocate it.
| Contributor | Hypothetical figure | Control |
|---|---|---|
| Arbitration wait | up to 64 cycles | Aging threshold and QoS mapping |
| Burst already in progress | up to 16 cycles | Max burst length per arbitration round |
| Slave response after grant | up to 20 cycles | Slave wait states and clock ratio |
| Sum of the three rows | up to 100 cycles | Leaves margin under the 200 cycle budget |
The burst row assumes the slave accepts one beat per cycle for 16 beats and adds no extra wait states. If the slave inserts wait states, that row grows and the budget must be rechecked. If the budget is missed, I would first limit burst length per arbitration round, then check whether the chosen interconnect supports interleaving bursts from independent transactions. Interleaving is implementation dependent. Where supported, it generally requires independent IDs, because transactions sharing an ID must preserve ordering. With a single ID per master, head-of-line blocking can still occur.
Failure modes to test
QoS starvation: a low AxQOS master never wins under sustained load. Aging or a minimum share should prevent that, and a counter for cycles waiting for AWREADY or ARREADY per master will show it.
Buffer deadlock: some interconnect implementations can deadlock if a master waits for a read response before issuing a write while shared buffering is exhausted. That behaviour is implementation specific, not a general AXI rule. I would check the vendor documentation for separate read and write buffering, and test mixed read and write traffic on the same ID.
Narrow transfers: a 32-bit master on a 64-bit bus uses byte strobes (WSTRB) and may achieve half the peak bandwidth per beat. Whether the interconnect packs narrow transfers into wider beats depends on the implementation, and packing must preserve ordering and strobes. I would measure achieved bandwidth with narrow traffic rather than assuming packing.
I would close the loop with performance counters in simulation and on an emulator: wait cycles per channel, latency distribution per master, and achieved GB/s per slave. Those numbers separate an arbitration problem from a burst length problem from a slow slave.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-34In a mesh network-on-chip, why does XY routing prevent deadlock?
The 90-second answer
XY routing prevents deadlock in a mesh because it makes the channel dependency graph acyclic. A packet moves in X first, then in Y, and it never turns back to X. Once it leaves the X dimension it cannot re-enter it, so packets cannot form the circular wait that deadlock requires.
Deadlock in a NoC is not a software bug. It is four packets, each holding a router input buffer and waiting for the next buffer in a cycle. If every packet waits for a buffer held by the next packet, none can move. Breaking the cycle in the routing rule removes the possibility, regardless of traffic pattern or buffer size.
How the cycle forms
Consider a 2x2 mesh with routers A, B, C and D. A packet from A to D can go right then up, or up then right. If routing allowed either choice adaptively, packets could occupy buffers in a ring: A waits for B, B waits for D, D waits for C, C waits for A. Each router holds one packet and needs the next router to free a buffer. No router can free a buffer because its packet cannot move.
XY routing removes the up-then-right path for a packet that started by going right. The rule is fixed by destination coordinates, not by congestion.
// XY routing decision, checked against SystemVerilog-2017
// dx and dy are signed offsets from current router to destination
always_comb begin
if (dx != 0)
next_port = (dx > 0) ? EAST : WEST;
else if (dy != 0)
next_port = (dy > 0) ? NORTH : SOUTH;
else
next_port = LOCAL;
endThe priority matters. X is served first. A packet with dx = 2 and dy = -1 goes east twice, then south once. It never goes south, then east, then south again.
Worked trace
Source router (0,0), destination (2,1), one packet, buffers of depth 2 per port:
| Step | Router | dx, dy | Next port | Reason |
|---|---|---|---|---|
| 1 | (0,0) | 2, 1 | East | dx is non-zero, X first |
| 2 | (1,0) | 1, 1 | East | dx is still non-zero |
| 3 | (2,0) | 0, 1 | North | X done, Y remains |
| 4 | (2,1) | 0, 0 | Local | Destination reached |
Every hop reduces |dx| + |dy| by exactly one. Distance to destination falls monotonically, so a packet cannot loop back to a router it already visited. That monotonic decrease is the property an interviewer is listening for.
Why this guarantees progress
A channel dependency exists when a packet holding channel C1 can next request channel C2. With XY routing, dependencies only point in one direction in the turn model: east and west channels are requested before north and south channels, never the reverse. A dependency graph with no cycles cannot contain a circular wait. If a packet is blocked, some other packet in the system is not blocked, that packet moves, frees its buffer, and the blockage clears.
This holds even with credit-based flow control and small buffers. Credits stop a sender from overrunning a full buffer, but credits alone do not prevent deadlock. A credit system can still deadlock if routing allows a cycle, because every sender in the cycle is waiting for a credit that will never return. Routing is what removes the cycle. Flow control then only has to handle congestion, not correctness.
The limit is worth naming. XY routing is deterministic, so two flows that share the same X-first path contend for the same links. Adaptive routing can spread that load, but it must preserve an acyclic dependency graph, for example by restricting turns or by assigning virtual channels to different turn classes. If I proposed adaptive routing in a design review, I would show the dependency graph and prove it acyclic before discussing bandwidth gains.
Verification follows from the same argument. A cycle-accurate model with random traffic and buffers forced to depth 1 should still drain every packet. Depth 1 is the harshest case because it leaves no slack to hide a cycle. If packets drain at depth 1 under XY routing, they drain at any depth.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-35Walk me through designing a DMA controller for a SoC, covering burst size, arbitration, cache coherency, and interrupt generation?
The 90-second answer
I would start from the data path, not the channel count. A DMA controller needs a descriptor or register set per channel, a burst engine that moves data without the CPU, an arbiter that shares the interconnect fairly, a coherency policy that matches the cache topology, and interrupts that tell firmware when work is done, half done, or failed. Burst size, arbitration and coherency pull against each other, so I size them together.
Assume a 32-bit AXI or AHB interconnect at 100 MHz, 8-byte data width, a CPU with a write-back L1 cache, and peripherals such as UART, SPI and a memory copy engine. Each channel holds source address, destination address, length, burst length, direction and a control register. Firmware programs the channel, sets the enable bit, and the DMA fetches data in bursts until the count reaches zero.
Burst size
Burst size is the number of beats transferred per grant. Larger bursts cut arbitration overhead and improve throughput, but they block other masters for longer and need a deeper FIFO to absorb the data.
| Burst | Bytes per grant (8 B/beat) | Grants for 4 KiB | Worst block for another master |
|---|---|---|---|
| 1 beat | 8 | 512 | 1 beat, about 10 ns at 100 MHz |
| 8 beats | 64 | 64 | 8 beats, about 80 ns |
| 16 beats | 128 | 32 | 16 beats, about 160 ns |
| 64 beats | 512 | 8 | 64 beats, about 640 ns |
I would make burst size programmable per channel, default to 8 or 16 beats, and cap it so a latency sensitive peripheral such as UART receive can still get a grant within its FIFO deadline. A 64 beat burst looks efficient on a bandwidth graph and then starves the UART until its 16 byte FIFO overruns. The FIFO depth must cover at least one full burst plus the interconnect latency, otherwise the burst engine stalls mid burst and throughput collapses.
// Burst engine, simplified. Checked against IEEE 1800-2017 syntax.
module dma_burst_engine (
input logic clk,
input logic rst_n,
input logic grant,
input logic [3:0] burst_len, // beats per burst, 1 to 16
input logic [31:0] remaining,
output logic burst_done,
output logic [3:0] beats_left
);
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
beats_left <= burst_len;
burst_done <= 1'b0;
end else if (grant) begin
burst_done <= (beats_left == 4'd1) || (remaining <= 32'd1);
beats_left <= (beats_left == 4'd1) ? burst_len : beats_left - 4'd1;
end else begin
burst_done <= 1'b0;
end
end
endmoduleArbitration
Round robin is the baseline. Each requesting channel gets one burst in turn, which bounds latency to (number of active channels minus 1) bursts. Weighted round robin adds a weight per channel, so a memory copy channel can take four bursts for every one burst given to a slow UART channel. Priority arbitration is simpler and dangerous: a channel that always requests, such as a streaming ADC, can lock out everything else. I would use weighted round robin with a programmable weight and a starvation counter that forces a grant after a threshold, and I would expose the current grant in a status register so firmware can debug contention.
Cache coherency
This is where DMA designs fail in the field. With a write-back cache, the CPU may hold dirty lines that the DMA cannot see. If firmware writes a buffer and starts DMA without a cache clean, the DMA reads stale memory. If the DMA writes received data and the CPU reads it without an invalidate, the CPU reads stale cache lines. Two fixes exist. A snooping interconnect watches cache accesses and keeps the DMA view coherent, at cost in interconnect complexity and power. The cheaper route for a microcontroller SoC is explicit maintenance: firmware cleans the cache to the point of coherency before a DMA read, and invalidates after a DMA write, using the cache maintenance instructions and a memory barrier. I would document the buffer alignment rule, typically 32 or 64 bytes matching the cache line, and add a hardware interlock that refuses to start a channel whose buffer is misaligned if the SoC has no snooping.
Interrupt generation
Interrupts close the loop. I would generate four events per channel: transfer complete, half transfer, error, and descriptor or address fault. Half transfer lets firmware process streaming data in two halves without polling. The interrupt is level sensitive until firmware acknowledges it by clearing the status bit, and the status register must be readable before the interrupt line is asserted so the handler knows which event fired. I would also add an interrupt mask per channel and a combined interrupt line per channel group, so firmware can mask a noisy channel without losing the others. A common bug is asserting the interrupt before the final data beat is visible to the CPU. The completion interrupt must be raised only after the last write has been acknowledged on the interconnect, otherwise the handler reads incomplete data.
The failure modes I would test first are stale cache data after a DMA write, UART overrun under a long burst from another channel, and a lost interrupt when firmware clears status before reading the event bits. Each one shows up only under load, which is why I would verify with a traffic generator on all channels at once, not one channel at a time.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-36How do MESI and directory-based coherence keep private caches consistent in a multicore SoC, and what happens when two cores write the same cache line?
The 90-second answer
Each core has a private L1 and usually a private L2. The shared L3 and main memory hold the canonical copy, but a core reads and writes its own cache without going to memory on every access. Coherence is the protocol that makes those private copies behave as if there were one copy.
MESI is the common starting point. Every cache line sits in one of four states: Modified, Exclusive, Shared, or Invalid. Modified means this core has the only dirty copy. Exclusive means this core has the only clean copy. Shared means several cores hold clean copies. Invalid means the line is absent or stale.
A read miss that finds no other copy fetches the line in Exclusive state. A read miss that finds other copies fetches it in Shared state. A write miss must first obtain exclusive ownership. That forces every other copy to Invalid. That invalidation is the coherence action. The interconnect broadcasts or forwards the request, the other cache controllers respond, and the writer proceeds only after it has ownership.
Worked trace: two cores, one 64-byte line
Assume cores A and B, line X initially in memory, clean.
| Step | Core A | Core B | Line state after step | What the interconnect does |
|---|---|---|---|---|
| 1 | Read X | - | A: Exclusive | Fetch from L3/memory, no other copy exists |
| 2 | - | Read X | A: Shared, B: Shared | Snoop A, downgrade A from Exclusive to Shared, supply data |
| 3 | Write X | - | A: Modified, B: Invalid | Invalidate B, wait for B's acknowledgement, then grant write |
| 4 | - | Read X | A: Shared, B: Shared | Snoop A, write back dirty data if needed, downgrade A to Shared |
Step 3 is where consistency is enforced. A cannot write while B still holds a valid copy, because B could later read stale data or overwrite A's write. The acknowledgement from B is what makes the transition safe.
Snooping versus directory
| Approach | How it finds sharers | Cost | Typical use |
|---|---|---|---|
| Snooping | Broadcasts the request on the interconnect, every cache controller checks its tags | Traffic grows with core count, roughly O(n) per miss | 2 to 8 cores, shared L3, AMBA CHI or AXI with snoop channels |
| Directory | A directory entry per line records which cores hold it, only those cores are contacted | Extra storage and a directory lookup on misses, traffic grows with sharer count | Larger core counts, distributed L3, NUMA style fabrics |
In a current multicore SoC the interconnect, often Arm CHI, carries the coherence transactions. A snoop filter in the shared L3 or at the interconnect tracks which lines are present in private caches, so the system can avoid broadcasting to every core when a line is only in one cache. The directory or filter is a performance optimisation. Correctness still comes from the state transitions and the acknowledgements.
Failure modes an interviewer will probe
False sharing: two cores write different variables that happen to sit in the same 64-byte line. Each write invalidates the other core's copy, so the line ping-pongs between cores. The fix is layout, padding or aligning hot variables to separate lines, and it shows up as high coherence traffic in performance counters.
Deadlock and ordering: coherence messages and data messages share the interconnect. If a core holds a line while waiting for a channel that is blocked by a core waiting for that line, the fabric stalls. Real protocols separate virtual channels and define transaction ordering to prevent that cycle. Coherence also does not give you memory ordering for free. Two cores can each see their own writes in program order while disagreeing about the order of writes from the other core. That is why the architecture defines barriers and acquire/release operations on top of coherence, for example DMB and DSB on Arm, and why a device driver that only checks cache state will still race.
A concrete check I would run in verification: a directed test where core A writes X, core B spins on a flag in a different line, then reads X. If B ever reads the old value after the flag is visible, the invalidation path or the barrier semantics are broken. Randomised tests with multiple cores hammering a small set of lines catch the state machine errors that directed tests miss, especially the downgrade from Modified to Shared and the writeback on eviction.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-37Walk me through how memory-mapped I/O and address decoding turn a CPU load/store into a peripheral register access, and how you would design that register map?
The 90-second answer
Memory-mapped I/O puts peripheral registers in the same physical address space as RAM and flash. A CPU load or store to that address is decoded by the interconnect, routed to the peripheral, and completed as a bus transaction. Software does not call a driver function per bit. It writes a pointer to the register address and the compiler emits a load or store.
Three pieces decide if it works: the address map, the decoder, and the register semantics. The map assigns each peripheral a base address and a window size. The decoder compares the high address bits on every transaction and asserts chip select only for the owner. The register file then decodes the low offset bits to pick a flip-flop bank, applies write enables and read muxing, and returns data or an error to the CPU.
Assume a 32-bit APB or AXI-Lite slave at 0x4000_1000 with a 4 KiB window. The CPU address splits as high bits for selection and low bits for offset.
| Address bits | Use | Width for this example |
|---|---|---|
[31:12] | Compare against base [31:12] | 20 bits |
[11:2] | Register offset inside window | 10 bits, 1024 words |
[1:0] | Byte lane, from strb | 2 bits |
Worked trace
Software writes 0xA5 to the control register at offset 0x04.
| Step | Value |
|---|---|
| CPU store address | 0x4000_1004 |
Decoder compare [31:12] | 0x40001 matches base, psel = 1 |
Offset decode [11:2] | 0x001, selects register 1 |
Bus write data / strb | 0x0000_00A5 / 4'b0001 |
| Register action | Byte 0 of CTRL becomes 0xA5, other bytes unchanged |
| Bus response | pslverr = 0, pready = 1, store completes |
If the address were 0x4000_2004, the high compare fails, no slave asserts pready, and the interconnect returns an error after its timeout. That is how a missing peripheral becomes a bus fault instead of silent corruption.
Decoder in RTL
Full decoding compares every high bit. Partial decoding compares fewer bits to save gates, but the peripheral then responds at multiple aliased addresses and can collide with a later peripheral.
// SystemVerilog, checked against IEEE 1800-2017 syntax
module uart_regfile #(
parameter logic [31:0] BASE = 32'h4000_1000,
parameter int unsigned WINDOW = 4096 // bytes
)(
input logic pclk,
input logic presetn,
input logic [31:0] paddr,
input logic psel,
input logic penable,
input logic pwrite,
input logic [31:0] pwdata,
input logic [3:0] pstrb,
output logic [31:0] prdata,
output logic pready,
output logic pslverr
);
localparam int unsigned AW = $clog2(WINDOW); // 12
logic hit;
logic [31:0] ctrl_q;
logic [31:0] status_q;
assign hit = psel && (paddr[31:AW] == BASE[31:AW]);
assign pready = hit; // zero wait state for this simple block
assign pslverr = psel && !hit;
always_ff @(posedge pclk or negedge presetn) begin
if (!presetn) begin
ctrl_q <= 32'h0;
status_q <= 32'h0;
end else if (hit && penable && pwrite) begin
unique case (paddr[AW-1:2])
10'd1: for (int i = 0; i < 4; i++)
if (pstrb[i]) ctrl_q[8*i +: 8] <= pwdata[8*i +: 8];
10'd2: status_q <= status_q & ~pwdata; // write-1-to-clear
default: ;
endcase
end
end
always_comb begin
unique case (paddr[AW-1:2])
10'd0: prdata = 32'h5541_5254; // ID, read-only
10'd1: prdata = ctrl_q;
10'd2: prdata = status_q;
default: prdata = 32'h0;
endcase
end
endmoduleRegister design
Access type is part of the hardware contract, not a comment in the header file.
| Offset | Register | Access | Reset | Behaviour |
|---|---|---|---|---|
0x00 | ID | RO | 0x55415254 | Writes ignored or error, choose one and document it |
0x04 | CTRL | RW | 0x0000_0000 | pstrb controls byte writes, reserved bits read as zero |
0x08 | STATUS | W1C for flags, RO for live bits | 0x0000_0000 | Writing 1 clears the flag, writing 0 leaves it alone |
0x0C | FIFO | WO / RO | 0x0000_0000 | Read pops one entry, empty read returns error or zero by design |
Three details cause most field bugs. First, reserved bits: software read-modify-write code must not assume they are zero after a future revision adds a field there, so hardware should ignore writes to them and return zero on reads. Second, W1C versus RW: a plain RW status register loses an interrupt flag if software reads it, modifies one bit, and writes it back after hardware set another flag. W1C avoids that race. Third, side effects: read-clear and write-clear registers break naive debug reads and DMA polling, so the spec must state the effect of every access, including reads by a debugger.
Software side
// C11, bare-metal firmware
#define UART_BASE 0x40001000u
#define UART_CTRL (*(volatile uint32_t *)(UART_BASE + 0x04u))
#define UART_STATUS (*(volatile uint32_t *)(UART_BASE + 0x08u))
UART_CTRL = (1u << 0); // enable, byte writes handled by hardware strb
while ((UART_STATUS & (1u << 1)) == 0u) { /* poll tx_ready */ }
__DMB(); // order prior stores before signalling another agentvolatile stops the compiler caching the register in a CPU register or deleting a poll loop. It does not order accesses against DMA or another core. That needs a barrier such as __DMB() on Arm, or a C11 atomic with explicit ordering. Unaligned accesses are the other trap: a 32-bit register file that only supports word access will return pslverr for a byte store to 0x4000_1005, and firmware that casts to uint8_t * will fault.
When I review a register block, I check the map for holes, the decoder for full versus partial compare, and each register for its access type and reset value. Those three checks catch aliasing, lost interrupts, and software that works in simulation because the testbench never wrote a reserved bit or read a write-only register.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-38What must a peripheral driver do first during initialization before configuring a memory-mapped hardware block?
The 90-second answer
Enable the peripheral clock before touching any of its registers. On most SoCs the peripheral sits behind a clock gate in the reset and clock controller. Until that gate opens, the register block has no clock, reads return zero or fault, and writes are discarded. Software that configures baud rate, pin muxing, or interrupt enables first will appear to succeed and then fail in ways that look like a hardware fault.
That rule applies to a UART, SPI controller, I2C controller, timer, or DMA block. The register addresses are decoded on the system bus, but the peripheral side of that decode is unclocked until the clock enable bit is set. A driver therefore starts by setting the enable bit in the clock controller, waiting for the peripheral to come out of reset if the SoC provides a status bit, and only then writing the peripheral registers.
What the sequence looks like
/* Cortex-M style clock controller, checked against STM32F4 reference manual. */
void uart_init(uint32_t baud)
{
RCC->APB1ENR |= RCC_APB1ENR_USART2EN; /* 1. open the clock gate */
RCC->APB1ENR; /* read back, allow clock to propagate */
USART2->CR1 = 0; /* 2. now configure the block */
USART2->BRR = 417; /* 48 MHz / 115200 baud, rounded */
USART2->CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE;
}The read back of APB1ENR is a small detail that matters on some parts. It forces the write to complete on the bus before the next instruction issues, so the peripheral is clocked by the time its own registers are written. Skipping it usually still works, and it fails intermittently on slower bus bridges.
What happens if the order is reversed
| Order | What software observes | Likely misdiagnosis |
|---|---|---|
| Clock enabled, then registers written | Baud rate, pin mux, and interrupt enables take effect | None, this is the working path |
| Registers written, then clock enabled | Writes discarded, reads return 0, no TX or RX activity | Dead pin, wrong pin mux, or broken hardware |
| Clock enabled, peripheral left in reset | Same symptoms as above on parts with a per-peripheral reset bit | Driver bug in the baud calculation |
The middle row is the classic bring-up trap. A scope shows no signal on TX, the engineer checks the pin mux and the baud divisor, and both look correct because the values never reached the hardware. Enabling the clock first removes that whole class of false leads.
Two related points come up as follow-ups. First, the same ordering applies in reverse on shutdown. Disable the peripheral and its interrupts before closing the clock gate, or a pending interrupt can fire into a block that is no longer clocked. Second, low power modes often gate the clock automatically. A driver that wakes the peripheral from sleep must re-check that the clock is still enabled before resuming transfers, because the gate state may have changed while the CPU was asleep.
For a quick check on target, read a known register such as the peripheral ID or version register right after enabling the clock. A non-zero value confirms the clock gate is open and the bus decode works, before any configuration is attempted.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-39Walk me through SPI modes 0 to 3, how CPOL and CPHA set sampling, and how you would design a synthesizable SPI slave in RTL?
The 90-second answer
SPI has no clock in the protocol itself. The master generates SCLK, asserts CS, and the pair (CPOL, CPHA) fixes two things: the level SCLK rests at when CS is idle, and whether the first SCLK edge after CS is a sampling edge or a data-change edge. That pair gives four modes. A slave is then a shift register clocked or enabled by SCLK edges, gated by CS, with MISO tri-stated whenever CS is deasserted. The hard part in RTL is that SCLK is asynchronous to the SoC clock, so a design that samples SCLK with a 100 MHz system clock will fail at high SCLK rates or corrupt the first bit.
| Mode | CPOL | CPHA | SCLK idle | Sample on | Change on | Common use |
|---|---|---|---|---|---|---|
| 0 | 0 | 0 | low | rising (1st) | falling | many flash and sensors |
| 1 | 0 | 1 | low | falling (2nd) | rising | some displays |
| 2 | 1 | 0 | high | falling (1st) | rising | some ADCs |
| 3 | 1 | 1 | high | rising (2nd) | falling | many MCUs as slave |
CPOL only sets the idle level. CPHA decides the phase. With CPHA=0 the slave must have the first data bit valid on MOSI and MISO before the first edge, because that edge samples it. With CPHA=1 the first edge is a change edge, the transmitter puts bit 0 on the line, and the second edge samples it. Get CPHA wrong and every byte shifts by one bit, which looks like a working link with garbage data at the end.
Chip select and framing
CS is active low in almost every mainstream device, though the protocol does not require it. The slave treats CS as the frame boundary. While CS is high, SCLK edges are ignored, the bit counter is held at zero, and MISO is high impedance. When CS falls, the counter resets and the slave drives the first MISO bit if CPHA=1, or waits to be sampled if CPHA=0. When CS rises mid-byte, the partial byte is discarded and the counter resets. That reset on CS is what lets a master abort a transfer without a protocol error state.
Multiple slaves share MOSI and SCLK. Only the selected slave drives MISO. If two slaves drive at once, the bus contends and neither value is trustworthy. The master must also respect setup and hold times around CS: typically 10 to 50 ns from CS fall to first SCLK edge in a datasheet, and a similar gap after the last edge before CS rises. In RTL I would not rely on those numbers, I would make the slave tolerate a first edge arriving a few system cycles after CS.
Slave RTL that survives an asynchronous SCLK
Two structures work. The clean one for a peripheral that must run at 50 MHz SCLK or faster is to use SCLK itself as the clock for the shift register, with CS as an asynchronous reset. The register file or FIFO behind it runs on the system clock, and the crossing is handled with a small async FIFO or a toggle handshake for each byte. The alternative, synchronizing SCLK into the system clock with two flops and decoding edges, needs the system clock to be at least 4 to 8 times SCLK to catch every edge reliably, and it adds latency to MISO.
For a register slave at moderate speed, the SCLK-clocked shift register is simpler to verify:
// Checked against IEEE 1800-2017 syntax. CPOL/CPHA are parameters so one
// module covers all four modes; SAMPLE_RISE is true when sampling is on posedge.
module spi_slave #(
parameter int CPOL = 0,
parameter int CPHA = 0,
parameter int WIDTH = 8
)(
input logic sclk,
input logic cs_n,
input logic mosi,
output logic miso,
output logic [WIDTH-1:0] rx_data,
input logic [WIDTH-1:0] tx_data,
output logic byte_done
);
localparam bit SAMPLE_RISE = (CPOL == CPHA);
logic [WIDTH-1:0] shift;
logic [$clog2(WIDTH):0] cnt;
logic sample_edge, change_edge;
assign sample_edge = SAMPLE_RISE ? sclk : ~sclk;
assign change_edge = ~sample_edge;
assign miso = cs_n ? 1'bz : shift[WIDTH-1];
assign rx_data = shift;
// Shift register clocked by the sampling edge, reset by CS.
always @(posedge sample_edge or posedge cs_n) begin
if (cs_n) begin
shift <= tx_data;
cnt <= '0;
end else begin
shift <= {shift[WIDTH-2:0], mosi};
cnt <= cnt + 1'b1;
end
end
// Present the next MISO bit on the change edge.
always @(posedge change_edge or posedge cs_n) begin
if (cs_n) shift <= tx_data;
else shift <= {shift[WIDTH-2:0], 1'b0};
end
assign byte_done = cs_n ? 1'b0 : (cnt == WIDTH);
endmoduleThat sketch separates sampling from driving. In production code I would merge the two shift operations into one register with a mux on the edge type, because two registers both driving shift will not synthesize cleanly. The point to make in an interview is the structure: one edge samples MOSI and shifts, the other edge advances MISO, CS resets the count, and MISO is tri-stated outside the frame.
Failure modes I would test for
A master that changes mode mid-product is the classic bug. The slave samples on the wrong edge and the first bit is lost. I would add a configuration register for CPOL and CPHA, or generate the module per mode, and verify all four modes against a master model that checks the exact bit sequence, including the first bit.
CS glitches are the second. A 5 ns glitch on CS resets the counter mid-byte and the slave returns a partial word. The fix is to qualify CS with a short deglitch filter or require CS to be stable for a few SCLK periods before accepting a frame, and to flag a frame error if CS rises before WIDTH bits.
The third is the clock domain crossing on rx_data and byte_done. If firmware reads rx_data on the system clock while the shift register is still shifting, it gets a torn value. I would push each completed byte into a 2-entry async FIFO with Gray-coded pointers, or hold rx_data stable until the next CS fall and document that contract. A toggle handshake per byte is enough at 10 MHz SCLK, a FIFO pays off above that.
Finally, MISO contention during reset. If the slave powers up with MISO driven low while CS is high, it fights the selected slave. The tri-state must be combinational on CS, not registered, so MISO goes high impedance as soon as CS rises, even if the system clock is stopped.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-40After a target resets mid-transaction and holds SDA low, how do you recover the I2C bus, and how do you tell that apart from a target legitimately stretching SCL?
The 90-second answer
I would first check which line is stuck. Clock stretching holds SCL low. A reset target stuck mid-byte usually holds SDA low. That distinction decides the fix, because the master treats them differently.
I2C lines are open-drain with pull-ups. A device can only pull a line low or release it. START is SDA falling while SCL is high, STOP is SDA rising while SCL is high, and data changes on SDA while SCL is low. The master addresses a target with a 7-bit address plus a read/write bit, MSB first, and the target ACKs by pulling SDA low on the ninth clock. Multi-master arbitration uses the same wired-AND behaviour: a master sending a 1 but reading 0 loses and backs off.
For recovery, the master releases SDA and clocks SCL up to nine times while watching SDA. Each clock advances the stuck target by one bit. When SDA goes high, the target has reached a byte boundary. The master then issues STOP to reset its state machine.
// Bit-banged recovery, SDA/SCL as open-drain GPIOs
void i2c_recover(void) {
sda_release();
for (int i = 0; i < 9 && sda_read() == 0; i++) {
scl_release();
delay_us(5);
scl_pull_low();
delay_us(5);
}
// STOP: SDA low, SCL high, SDA high
sda_pull_low();
scl_release();
delay_us(5);
sda_release();
}Stretching is not a stuck bus
A target stretches the clock by holding SCL low after the ACK clock, for example while an ADC finishes converting. The master must wait, sampling SCL, until the target releases it. A fixed timeout that is shorter than that operation will abort a healthy transfer. If a sensor needs 20 ms to convert and the master times out at 5 ms, recovery will fire on every read and the driver will report a dead bus that is actually working.
| Observation | Likely cause | Master action |
|---|---|---|
| SCL low, SDA released or ACK level | Clock stretching | Wait until SCL rises, within a timeout above the slowest target operation |
| SDA low, SCL free | Target reset mid-byte, holding SDA | Run the 9-clock recovery, then STOP |
| SDA low after 9 clocks | Target still holding SDA, or damaged | Assert target reset if wired, else power cycle that device |
| SCL low for seconds with no progress | Target hung in stretch, or short to ground | Timeout, recovery attempt, then reset or power cycle |
The timeout therefore needs a real figure from the target data sheet, not a guess. I would set it above the worst-case stretch time, often tens of milliseconds for a converting sensor, and log how often it fires. Frequent timeouts point to a target that needs a longer conversion wait or a lower bus speed, not to a bus that needs resetting more often. After recovery, I would retry the transaction from START and check that the target ACKs its address again before trusting the bus.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-41How does a UART receiver use start-bit detection and 16x oversampling to sample data reliably despite clock mismatch, and how does RTS/CTS prevent FIFO overruns?
The 90-second answer
UART has no shared clock. The receiver finds the start of a frame from the line itself, then samples the rest of that frame using its own baud clock. Framing, oversampling and flow control all follow from that.
For 8N1 (8 data bits, no parity, 1 stop bit) sending 0x41, the wire order is:
| Field | Value | Length |
|---|---|---|
| Idle | 1 | indefinite |
| Start | 0 | 1 bit time |
| Data bits, LSB first | 1, 0, 0, 0, 0, 0, 1, 0 | 8 bit times |
| Stop | 1 | 1 bit time |
0x41 is 0100_0001 in binary, so it appears on the wire as 1,0,0,0,0,0,1,0. The receiver sees the falling edge into start, waits half a bit time, and checks the line is still low. That rejects a short glitch. It then samples each data bit near its centre and checks the stop bit is high. A low stop bit is a framing error and usually means the clocks have drifted too far apart or the line was held low for too long.
Oversampling and clock tolerance
A common design runs the receiver at 16 times the baud rate. At 115200 baud that is a 1.8432 MHz tick. A 4-bit counter counts 0 to 15 within each bit time and the sample is taken at count 8, the centre. Many implementations vote on counts 7, 8 and 9 and take the majority value, which rejects a narrow spike that corrupts a single sample.
Because there is no clock to correct drift, error accumulates from the start edge to the last bit sampled. In 8N1 the stop bit centre is 9.5 bit times after the start edge. If the receiver period differs from the transmitter period by a fraction e, the sampling point has moved by about 9.5 x e bit times. It must stay inside the stop bit, so the move must be under half a bit time. That gives a total mismatch budget of roughly 5 percent, and in practice designers keep each end within about 2 percent to leave margin for divider rounding and sampling uncertainty.
Divider rounding is the usual way this budget gets spent. A 16 MHz clock divided by 16 for 16x oversampling at 115200 baud gives 16e6 / (16 x 115200) = 8.68. Rounding to 9 produces 111111 baud, an error of 3.6 percent on that end alone. A fractional divider, a lower oversampling ratio, or a clock that divides cleanly fixes it. Flow control cannot fix this problem. If the sampling point lands in the wrong bit, framing errors occur no matter how well the peer is throttled.
A compact sampling core looks like this:
// tick pulses 16 times per bit time; sample at phase 8
module uart_sampler (
input logic clk, rst_n, rx, tick,
output logic sample_valid,
output logic sample_bit
);
logic [3:0] phase;
logic [2:0] vote;
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
phase <= 0;
vote <= 3'b111;
sample_valid <= 0;
sample_bit <= 1;
end else begin
sample_valid <= 0;
if (tick) begin
phase <= phase + 1;
vote <= {vote[1:0], rx};
if (phase == 4'd7)
sample_bit <= (vote[1] + vote[0] + rx) >= 2;
if (phase == 4'd8)
sample_valid <= 1;
end
end
end
endmoduleThe framing logic around it shifts in the sampled bits, checks parity if enabled, and flags a framing error when the stop sample is low.
Flow control
UART itself has no flow control. If the receiver FIFO fills, further bytes are lost and the driver only finds out if it checks an overrun flag. Two options close that gap.
| RTS/CTS hardware | XON/XOFF software | |
|---|---|---|
| Mechanism | Receiver drives RTS low when its FIFO passes a high watermark, transmitter must stop when CTS is low | Receiver sends byte 0x13 to pause and 0x11 to resume |
| Binary data | Safe, control is on separate wires | Unsafe if the payload can contain 0x11 or 0x13 |
| Reaction time | Fast, limited by wire delay and peer response | Slower, the pause byte must be transmitted and parsed |
| Cost | Two extra wires in each direction | No extra wires |
For a new design I would use RTS/CTS with hysteresis. Deassert RTS at a high watermark and reassert it at a lower one, leaving headroom for bytes already in flight. With a 64-byte FIFO, a high watermark at 48 leaves 16 bytes, about 1.4 ms at 115200 baud, for the transmitter to drain its FIFO and stop. XON/XOFF suits a legacy 3-wire cable carrying text, but it should not be used for a binary protocol unless those byte values are escaped, which breaks transparency.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-42When several interrupts are pending, what rule does an interrupt controller use to choose which one to present to the CPU first?
The 90-second answer
The controller presents the pending source with the highest programmed priority. If two sources share that priority, the tie-break is fixed by the design, usually the lowest IRQ number. That is the whole arbitration rule.
Assume a Cortex-M NVIC, where a lower priority number means higher urgency, or a RISC-V PLIC, where a higher priority number means higher urgency. The numbering differs. The rule does not.
// Simplified priority encoder for illustration.
// pending[p] is set, priority[p] is the programmed value.
// Lower priority value wins here, as on Cortex-M.
always_comb begin
sel_id = '0;
sel_valid = 1'b0;
best_pri = '1;
for (int i = 0; i < NUM_IRQ; i++) begin
if (pending[i] && (priority[i] < best_pri)) begin
best_pri = priority[i];
sel_id = i[IDW-1:0];
sel_valid = 1'b1;
end
end
endThe encoder runs combinationally, or in one clock cycle in a pipelined implementation, after the request has been synchronized and latched as pending. A peripheral that is still asserting a level request will set pending again if the handler clears the bit before the source is deasserted. That re-entry is a common hardware and firmware bug.
Worked trace. Hypothetical priorities on a Cortex-M style controller: UART is 3, SPI is 1, Timer is 2. Lower number wins.
| Pending sources | Presented to CPU | Reason |
|---|---|---|
| UART, Timer | Timer | Priority 2 beats priority 3 |
| UART, Timer, SPI | SPI | Priority 1 beats priority 2 |
| SPI handler running, UART arrives | SPI continues | UART cannot preempt a higher priority handler |
| Timer handler running, SPI arrives | SPI preempts Timer | Priority 1 beats the running priority 2 |
Nesting and latency, the follow-ups. Nesting is what happens after that first choice. With nesting enabled, a pending source whose preemption priority is higher than the handler currently running preempts it. The CPU stacks the interrupted context, fetches the new vector, and runs the new handler. On return, the earlier handler resumes. With nesting disabled, or with interrupts masked in a critical section, even a higher priority source waits.
Worst-case latency is therefore not a property of the encoder alone. It is synchronization time, plus arbitration, plus the time to finish the current instruction, plus stacking and vector fetch, plus any blocking time in a lower priority handler or masked section. A candidate who can state the priority rule, then add that blocking term, has answered the question and shown where the real latency comes from.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-43Your 100 MHz Cortex-M ISR must capture a 1 kHz sensor sample within 5 µs, but a shared SPI transfer and a lower-priority UART ISR can block it. How do you design the ISR, bound its latency and jitter, and protect shared resources?
The 90-second answer
I would make the ISR do only work that cannot wait, and move everything else to deferred processing. For a 1 kHz sensor sample on a 100 MHz Cortex-M, the ISR reads the data register or FIFO, timestamps it, pushes it into a single-producer ring buffer, clears the peripheral flag, and sets a pending flag for a task or main-loop handler. It never waits on a bus, allocates memory, prints, or takes a mutex. That keeps the non-preemptible window short, which is what bounds latency and jitter.
Worst-case latency is not the average entry time. It is entry time plus the longest time interrupts are masked plus the longest lower-priority ISR that cannot be preempted plus bus or flash stalls. I budget all four, then verify with a GPIO toggle and a cycle counter, not by inspection.
Latency and jitter budget
Assume a 100 MHz core, so one cycle is 10 ns and a 5 µs deadline is 500 cycles. Hypothetical but realistic figures for a Cortex-M4 with zero-wait-state SRAM and flash prefetch enabled:
| Contributor | Typical | Worst case | Control |
|---|---|---|---|
| Hardware stacking and NVIC entry | 12 cycles | 12 cycles | Fixed by architecture |
| Masked section in main or driver code | 20 cycles | 200 cycles | Keep critical sections under 2 µs, audit them |
| Lower-priority ISR already running | 0 cycles | 150 cycles | Short ISRs, preemption enabled |
| Flash wait states or cache miss on first instruction | 0 cycles | 60 cycles | Place ISR in SRAM or enable prefetch |
| ISR body: read FIFO, timestamp, enqueue | 80 cycles | 110 cycles | No floating point, no library calls |
| Total to sample captured | 112 cycles, 1.12 µs | 532 cycles, 5.32 µs | Fails worst case until masked section shrinks |
That last row is the design conversation. If the worst case exceeds 500 cycles, I do not tune the ISR body first. I shorten the masked section, raise the sensor interrupt priority so it preempts the UART ISR, and move the ISR vector and handler to SRAM. Jitter is the spread between best and worst case, here roughly 4.2 µs before those fixes and under 1 µs after, because the remaining variation is mostly the preempted lower-priority ISR.
Measurement closes the loop. Toggle a GPIO on entry and on exit, capture both on a logic analyser or oscilloscope, and record the DWT CYCCNT delta in the ISR for a histogram over 100k interrupts. A bimodal histogram usually means a cache miss or a DMA burst stealing the bus. A long tail usually means a masked section or a higher-priority ISR running long.
Deferred processing
#define RING_SIZE 64
static volatile uint16_t ring[RING_SIZE];
static volatile uint8_t head, tail; /* head: ISR writes, tail: task reads */
static volatile uint32_t dropped;
void SENSOR_IRQHandler(void)
{
uint16_t sample = SENSOR->DATA; /* read before clearing flag */
uint32_t now = DWT->CYCCNT;
uint8_t next = (head + 1) & (RING_SIZE - 1);
if (next != tail) {
ring[head] = sample;
head = next;
} else {
dropped++; /* overrun: count it, do not block */
}
SENSOR->ICR = 1; /* clear source after data is captured */
(void)now;
}
/* Deferred half, runs in task or main loop */
void sensor_task(void)
{
while (tail != head) {
uint16_t sample = ring[tail];
tail = (tail + 1) & (RING_SIZE - 1);
process_sample(sample); /* filtering, scaling, logging */
}
}The ring is single-producer, single-consumer, so the ISR and the task never lock it. head is written only by the ISR and tail only by the consumer, and both are volatile so the compiler does not cache them. If the consumer falls behind, the buffer fills and dropped counts the loss instead of corrupting data. Sizing is arithmetic: at 1 kHz, a 64-entry buffer absorbs 64 ms of consumer stall. If the task can stall 200 ms during a flash write, the buffer needs 256 entries or the design needs DMA into a larger buffer with a half-transfer interrupt.
Shared resource protection
The SPI bus shared with a display or flash chip is the classic trap. An ISR must never call the blocking SPI driver, because that driver may sleep, take a mutex, or wait for a transfer-complete interrupt that the current priority masks. Two safe patterns exist. First, the ISR sets a flag and the task owns the bus, using a mutex with priority inheritance so a low-priority task holding the bus does not block a high-priority task indefinitely. Second, if the ISR truly must touch the bus, the bus is reserved for ISRs only, transfers are polled and bounded, and no task uses it.
For short shared variables, such as a 32-bit tick counter read by main code, a critical section is cheaper than a mutex. On Cortex-M, lower priority numbers mean higher urgency. Setting BASEPRI to a threshold masks interrupts at that priority and lower urgency, while higher urgency interrupts still run. If the ISRs that touch the variable run at priority 2, setting BASEPRI to 2 masks priority 2 and below without disabling everything:
uint32_t read_tick(void)
{
uint32_t tick;
uint32_t basepri = __get_BASEPRI();
__set_BASEPRI(2 << (8 - __NVIC_PRIO_BITS)); /* mask priority 2 and lower urgency */
__DSB();
tick = tick_count;
__set_BASEPRI(basepri);
return tick;
}__disable_irq() is the blunt version. It also masks a safety-critical fault or watchdog interrupt, so I reserve it for sections of a few instructions and never across a peripheral wait.
Failure modes I check for
Clearing the interrupt flag before reading the data register loses a sample if a new conversion completes in between. Reading a multi-byte register byte by byte while the ISR updates it gives a torn value, which the BASEPRI section prevents. A reentrant ISR, where the same interrupt fires before the previous instance finishes, corrupts the ring, so the peripheral must either be masked on entry or the handler must detect overrun. Finally, a priority inversion where a low-priority task holds the SPI mutex while a medium-priority task runs and the sensor task waits, is fixed by priority inheritance or by keeping the bus out of the ISR path entirely. Each of these shows up in the CYCCNT histogram or the dropped counter before it shows up in the field, which is why both are part of the design rather than diagnostics added later.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-44How does an RTOS scheduler pick the next task, and how do priority inheritance and priority ceiling stop priority inversion on a shared peripheral?
The 90-second answer
A preemptive fixed-priority RTOS keeps tasks in a ready queue ordered by priority. On every tick, interrupt return, or blocking call, the scheduler runs the highest-priority ready task and preempts the current one if a higher-priority task becomes ready. That gives bounded latency for the high-priority task, which is why it suits a microcontroller handling a sensor ISR, a control loop, and background logging on one core.
Priority inversion breaks that guarantee. A low-priority task holds a mutex for a shared SPI bus. A medium-priority task preempts the low one. A high-priority task then blocks on the same mutex. The high-priority task now waits for the medium-priority task, which has nothing to do with the bus. The classic case was the 1997 Mars Pathfinder resets, where the low-priority meteorological task held a bus mutex while a medium-priority task starved it.
Two protocols fix the unbounded part. Priority inheritance temporarily raises the holder to the blocked task's priority. Priority ceiling raises the holder to a preset ceiling, the highest priority of any task that can take that mutex, as soon as it locks it. I use inheritance for dynamic, application-level mutexes and ceiling where I can assign ceilings statically and also need deadlock prevention.
Worked trace
Assume priorities 1 (low) to 3 (high), one mutex bus_mtx, and a 1 kHz tick.
| Time | Event | Without protocol | With priority inheritance |
|---|---|---|---|
| t0 | L locks bus_mtx, starts SPI transfer | L runs | L runs at priority 1 |
| t1 | M becomes ready | M preempts L, L stalls mid-transfer | M preempts L, L stalls mid-transfer |
| t2 | H becomes ready, calls take on bus_mtx | H blocks, M keeps running | H blocks, L inherits priority 3 |
| t3 | Scheduler choice | M runs until it blocks or finishes | L runs at 3, M waits, L finishes transfer |
| t4 | L unlocks bus_mtx | H finally runs, after M | H unblocks and preempts L, L drops back to 1 |
Inheritance does not make H run sooner than L finishing the transfer. It stops M from extending the wait by an arbitrary amount. The bound becomes the length of L's critical section, not the length of M's work.
Inheritance versus ceiling
| Property | Priority inheritance | Priority ceiling |
|---|---|---|
| When priority rises | Only when a higher-priority task blocks on the mutex | On lock, to the mutex ceiling |
| Ceiling assignment | None needed | Must be set to max priority of all potential lockers |
| Deadlock with nested locks | Possible if tasks lock in different orders | Prevented if ceilings are assigned correctly, since a task can only lock when no higher ceiling is held |
| Cost | Priority changes on block and unblock, can chain through several mutexes | One raise per lock, but a low task may run at high priority even when no high task is waiting |
| Main risk | Transitive chains and priority boosting bugs in the kernel | Wrong ceiling, or a task locking a mutex it was not accounted for |
FreeRTOS mutexes implement inheritance. A binary semaphore does not, which is a common firmware bug: code replaces a mutex with a binary semaphore for a shared peripheral and loses the boost.
/* FreeRTOS, Cortex-M4 at 168 MHz, checked against FreeRTOS 11 */
static SemaphoreHandle_t bus_mtx;
void spi_transfer(uint8_t *buf, size_t len)
{
xSemaphoreTake(bus_mtx, portMAX_DELAY); /* holder inherits H priority if H blocks here */
spi_dma_start(buf, len);
xSemaphoreGive(bus_mtx); /* priority restored on give */
}Where it still fails
Inheritance only helps while the holder actually holds the mutex. If L is preempted by an ISR that runs for 2 ms, H still waits. Keep ISRs short, defer work to a task, and never block inside an ISR. If L holds two mutexes and H blocks on the second, the boost chains, and a bug in one unlock path leaves L boosted indefinitely. I check that with a trace: log task priority changes on lock and unlock during bring-up, and assert that no task runs above its base priority for longer than its longest critical section.
Ceiling has the opposite failure. If a new task at priority 4 starts using bus_mtx and the ceiling was set to 3, the protocol is silently wrong. I treat the ceiling as part of the mutex creation call and review it whenever a task is added.
For very short critical sections, a few hundred cycles of register save and restore, I skip the mutex entirely and disable interrupts or use a lock-free ring buffer. That removes the scheduling problem instead of managing it, at the cost of masking latency for every interrupt during the section. On a part where the control ISR has a 50 us deadline, that trade is usually unacceptable, so the mutex plus inheritance is the right tool.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-45How do you decide whether a set of periodic firmware tasks with hard deadlines will meet those deadlines on a single-core microcontroller, and what scheduling test do you apply?
The 90-second answer
For a single-core microcontroller running preemptive fixed-priority scheduling, I state the model first: independent periodic or sporadic tasks, each with a worst-case execution time C, period T, and deadline D. I assume D equals T unless told otherwise, and I add blocking B for the longest nonpreemptive section or ISR that can delay the task. Utilization is U = sum(C_i / T_i). If U exceeds 1, no scheduler can save the set on one core. If U is below 1, I still need a test, because priority order and blocking decide who misses.
Rate Monotonic assigns priority by period, shortest period first. Its Liu and Layland bound is sufficient but not necessary: U <= n(2^(1/n) - 1), which falls from 100% for one task toward 69% as n grows. Passing proves schedulability. Failing proves nothing. Earliest Deadline First is optimal on a uniprocessor for this model and is schedulable when U <= 1, but it costs dynamic queueing and gives less predictable behaviour under overload than fixed priorities, which is why firmware often stays with fixed priorities and runs exact response time analysis.
Exact analysis iterates the worst-case response time for task i:
R_i = C_i + B_i + sum over higher-priority j of ceil(R_j / T_j) * C_j
Start with R_i = C_i + B_i, repeat until R_i stops changing or exceeds D_i. If every R_i <= D_i, the set is schedulable under the model. If any R_i exceeds D_i, that task can miss in the worst case.
Worked trace
Take three tasks, all D = T, no blocking yet. Priorities follow periods.
| Task | C (ms) | T = D (ms) | C/T |
|---|---|---|---|
| A, sensor ISR handler | 1 | 5 | 0.20 |
| B, control loop | 2 | 10 | 0.20 |
| C, logging | 3 | 20 | 0.15 |
U = 0.55. The RM bound for n = 3 is 3 * (2^(1/3) - 1) = 0.78, so the bound already passes. Response time for C, the lowest priority task:
| Iteration | Calculation | R_C (ms) |
|---|---|---|
| 1 | 3 + ceil(3/5)*1 + ceil(3/10)*2 | 6 |
| 2 | 3 + ceil(6/5)*1 + ceil(6/10)*2 | 7 |
| 3 | 3 + ceil(7/5)*1 + ceil(7/10)*2 | 7 |
R_C = 7 ms, well under its 20 ms deadline. A and B converge faster and also pass.
Now change the load so the bound fails but the set still works. A: C = 3, T = 5. B: C = 2, T = 10. C: C = 1, T = 20. U = 0.60 + 0.20 + 0.05 = 0.85, above the 0.78 bound. The same iteration for C gives R_C = 9 ms, still under 20 ms. A candidate who stops at the bound would wrongly reject a schedulable set. That gap is the main reason I use the bound only as a quick screen.
import math
def response_time(C, T, B=0, higher=()):
R = C + B
while True:
new_R = C + B + sum(math.ceil(R / Tj) * Cj for Cj, Tj in higher)
if new_R == R:
return R
if new_R > 10**9:
return new_R
R = new_R
# Task C above, with A and B as higher priority
print(response_time(1, 20, higher=[(3, 5), (2, 10)])) # 9Where the model breaks in hardware
Blocking is the usual surprise. A task that disables interrupts for 200 microseconds, or a shared SPI bus guarded by a mutex, adds B to every lower-priority task. Without priority ceiling or inheritance, a low-priority task holding the bus while a medium-priority task runs can delay a high-priority task far beyond its C. I measure B from the longest critical section and the longest ISR, including DMA completion handlers, not from the average.
WCET is the other weak point. A number taken from a bench run at room temperature with warm cache will understate the worst case. I want WCET from static analysis or from measurement across voltage and temperature corners, with cache and flash wait states included, then a margin on top. Jitter on release, such as a timer tick that fires late, also eats into D and should be added to the interference term when the datasheet gives it.
Under overload, fixed priority degrades in a controlled way: low-priority logging starves first and the control loop keeps running. EDF can cascade misses across all tasks once U passes 1. For a motor controller or a sensor node, that predictability is often worth more than the extra utilisation EDF offers. If the design needs EDF, I would still run the same response time check with deadlines in place of periods and watch the queue depth at runtime, because a missed deadline that is detected late is a missed deadline either way.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-46How do stack, heap, and static allocation differ in embedded C and C++, and why does heap fragmentation matter on a microcontroller?
The 90-second answer
On a microcontroller you do not get a virtual memory safety net. A typical Cortex-M4 part might have 64 KB of SRAM and 256 KB of flash, and every byte of RAM is accounted for at link time. Static allocation lives in .bss or .data and costs a fixed amount forever. The stack grows down from the top of SRAM for call frames and local variables. The heap sits between them, managed by malloc and new, and it is the only region whose size changes at runtime.
That runtime flexibility is the problem. malloc can fail, it can take an unbounded amount of time, and repeated allocation and free fragments the heap so a later request fails even though the total free bytes look sufficient. In firmware that runs for years I avoid the heap after initialisation, or I allocate from a fixed pool at startup and never free.
| Region | Lifetime | Size known at | Main failure mode |
|---|---|---|---|
| Static / global | Whole program | Link time | SRAM budget blown at build, no runtime failure |
| Stack | Function call | Compile time, worst case | Silent overflow into heap or adjacent data |
| Heap | Until free / delete | Runtime only | Exhaustion, fragmentation, nondeterministic timing |
Static first, stack second, heap last.
A receive buffer for a UART or SPI driver has a known maximum length, so it should be static. A local array inside a function is on the stack, and its size counts against every interrupt that can preempt that function. If a task has a 2 KB stack and calls a function with a 1 KB local buffer, plus an ISR that uses 512 bytes on the same stack, you are already close to overflow with no compiler warning.
// Checked against GCC 13 for ARM, -O2, Cortex-M4
#include <array>
#include <cstdint>
// Static: 256 bytes in .bss, zero heap use, zero stack use
static std::array<uint8_t, 256> rx_buf;
// Stack: 256 bytes only while this function runs
void handle_packet() {
std::array<uint8_t, 256> tmp{};
// ...
}
// Avoid in production firmware:
// auto* p = new uint8_t[256]; // heap, may throw or return nullptrFor C++ the same rule applies to std::vector, std::string, and std::map. Each one can allocate on the heap. A fixed-capacity alternative such as std::array or a static ring buffer keeps the allocation visible in the memory map.
Fragmentation, with numbers.
Suppose an 8 KB heap starts empty. Firmware allocates 1 KB, 2 KB, and 1 KB, then frees the first and third blocks. Total free space is now 6 KB, but it is split into a 1 KB hole, a 1 KB hole, and 4 KB at the end. A later request for 3 KB succeeds from the tail, but a request for 2 KB after another 3 KB allocation can fail even though more than 2 KB is free in aggregate. The allocator cannot merge nonadjacent holes, and on a small heap there is no compaction.
Detection is practical, not theoretical. I check the linker map for static usage, set the stack limit and use an MPU guard region or stack canary to catch overflow, and track heap high-water mark and largest free block, not just total free bytes. If the largest free block shrinks over a soak test while total free stays flat, fragmentation is progressing. The fix is a pool allocator: carve the heap into fixed-size blocks at startup, hand them out without splitting, and return them to the same pool. That bounds worst-case allocation time and makes fragmentation impossible within a pool, at the cost of internal waste when a block is larger than the request.
The interview follow-up is usually about determinism. Static and stack use are bounded and analysable. Heap use depends on runtime history, which is why safety-critical firmware bans dynamic allocation after startup or confines it to a pool with a proven high-water mark.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-47Walk me through designing a bootloader that loads firmware from external flash, verifies its integrity before execution, and recovers safely if an update is interrupted or corrupt?
The 90-second answer
I would split it into an immutable first stage in ROM and a field-updatable second stage, and I would never execute an image that has not passed verification in the slot it will run from. Assume a Cortex-M class MCU with 512 KB internal flash, a 16 MB external SPI NOR for staging, and a hardware SHA-256 accelerator. The ROM code runs from reset, checks a boot-mode strap and a recovery flag, copies or verifies the second stage, and only then jumps to the application. If verification fails, it does not try the same image again. It falls back to the last known-good slot, or to a recovery mode over UART or SPI that can accept a new image.
The layout decides most of the recovery behaviour:
| Region | Contents | Rule |
|---|---|---|
| ROM | Stage 1, recovery protocol, public key hash | Immutable, runs with no flash wait states assumed |
| Slot A, 256 KB | Application image plus header | Runs only if header CRC, hash and signature pass |
| Slot B, 256 KB | Application image plus header | Update target while A runs |
| Metadata, 2 sectors | Slot state, sequence, anti-rollback counter | Two copies, updated alternately |
| External NOR | Staged image, optional log | Never executed directly unless XIP is required |
Each image header carries length, load address, SHA-256 of the payload, signature over header plus hash, version, and a monotonic version number. CRC32 alone catches a torn write or a bit flip. It does not catch a deliberately modified image, so the signature check is separate. The ROM holds only the hash of the signing public key, fused or in OTP. The private key stays offline in an HSM. Anti-rollback is a counter in OTP or replay-protected flash that the bootloader increments only after a new image has booted successfully once. An older signed image then fails even though its signature is valid.
Update and commit sequence
The update writes only the inactive slot. Erase happens before program, and the commit record is written last, in a separate metadata sector. That ordering is the atomicity mechanism. If power is lost during erase or program, the active slot is untouched and the commit record still points to it. If power is lost while writing the commit record, the two metadata copies disagree. The bootloader picks the copy with a valid CRC and the higher sequence, and treats a torn commit as not committed.
// Checked against a Cortex-M33 style bootloader, C11, no RTOS.
typedef enum { BOOT_OK, BOOT_FALLBACK, BOOT_RECOVERY } boot_result_t;
boot_result_t boot(void) {
slot_t active = metadata_active_slot(); // CRC-checked, higher sequence wins
if (verify_slot(active) == VERIFY_OK) {
jump_to_slot(active);
return BOOT_OK;
}
slot_t other = other_slot(active);
if (verify_slot(other) == VERIFY_OK) {
metadata_commit(other); // only after verify passes
jump_to_slot(other);
return BOOT_FALLBACK;
}
recovery_mode(); // UART/SPI, watchdog still fed
return BOOT_RECOVERY;
}verify_slot checks header CRC first, then streams the payload through SHA-256, then checks the signature. Streaming matters. Loading a 256 KB image into SRAM to hash it would need most of a 384 KB SRAM and leave nothing for the stack. With a hardware accelerator at roughly 20 MB/s, hashing 256 KB takes about 13 ms. With a software SHA-256 at about 1 MB/s on a 100 MHz core, the same check takes about 260 ms. That number sets the watchdog timeout and the user-visible boot delay, so I would measure it on the target rather than guess.
Failure modes I would test explicitly
| Fault injected | Expected behaviour |
|---|---|
| Power cut during erase of inactive slot | Next reset boots active slot, staged image ignored |
| Power cut during commit record write | CRC picks the older valid metadata copy |
| Single bit flip in payload | Hash mismatch, slot rejected, fallback runs |
| Valid signature, older version | Anti-rollback counter rejects it |
| Image programmed to wrong load address | Header load address checked against slot base before jump |
| Flash wear or stuck bit in metadata | Alternate metadata sector used, event logged if a log area exists |
Two details get missed. First, executing from flash while programming the same flash bank can stall or corrupt reads on many parts, so the update path either runs from SRAM or uses a separate bank. Second, the recovery mode must have its own timeout and watchdog handling. A bootloader that waits forever on UART with the watchdog disabled will brick a unit that loses power during recovery. I would feed the watchdog only after a byte is received, and return to the fallback check after a fixed timeout.
If the product needs XIP from external NOR instead of internal A/B slots, the same structure holds but the fallback slot must be internal. External flash can be replaced or can fail to initialise, and a bootloader that depends on it for its own recovery path has no recovery path.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-48Walk me through hardware-software co-design, and how you would partition a function between hardware and software?
The 90-second answer
Hardware-software co-design means deciding the partition before RTL and firmware harden around it, then designing the interface between them as carefully as either side. I start from the function's constraints, not from a preference for hardware or software: deadline and jitter, throughput, power budget, how often the algorithm changes, and what happens when it fails.
Take a concrete case: a motor drive that samples phase current at 20 kHz, filters it, runs a PI current loop, and must react to an overcurrent within one sample period, 50 microseconds. The PI math itself is trivial in software. The hard parts are sampling on time, filtering without adding delay, and guaranteeing the loop runs even when the CPU is busy with communications.
My default partition for that case: hardware owns the time-critical, regular, data-parallel work (ADC triggering, DMA, FIR filter, PWM compare, overcurrent trip), software owns policy and anything irregular (PI gains, mode changes, fault logging, tuning). The boundary is a small register interface plus a DMA buffer, not a shared variable.
How I decide
| Criterion | Pushes to hardware | Pushes to software |
|---|---|---|
| Latency and jitter | Deadline under a few microseconds, or jitter breaks control stability | Deadline is milliseconds, jitter is tolerable |
| Throughput | Sustained data rate where the CPU would spend most cycles on arithmetic | Bursty or low rate, CPU has idle cycles |
| Power | Block can clock-gate or power-gate between events, CPU wake-up costs more | Work is rare, waking a dedicated block costs more than a short CPU burst |
| Change rate | Algorithm frozen, verified once | Gains, thresholds, protocol handling change in the field |
| Verification | Behaviour is simple enough to verify in RTL and formal checks | Behaviour needs logging, exceptions, and easy patching |
Arithmetic makes the trade-off checkable. A 64-tap FIR at 20 kHz needs 64 multiply-accumulates per sample, which is 1.28 million MACs per second. Hypothetical figure for this worked example: if the compiled loop on a 48 MHz Cortex-M4 sustains 24 million MACs per second, that load is about 5% of the CPU, before the PI loop, ADC handling, and interrupts. That looks fine on average. The problem is worst case: a 200 microsecond communication interrupt during a sample delays the filter output, and the current loop sees stale data. A small hardware FIR computes one output per sample and never misses a sample because DMA feeds it. Its cost is group delay: a 64-tap linear-phase FIR delays by (64-1)/2 = 31.5 samples, which is 31.5 / 20,000 = 1.575 ms at 20 kHz. I would compensate for that known delay in the PI tuning rather than discover it as phase lag in closed loop.
If the sample rate were 200 Hz instead of 20 kHz, the same arithmetic is 0.05% of that hypothetical MAC rate and I would keep it in software. The partition follows the numbers, not the technology.
The interface is where co-design succeeds or fails
I would define three things in the spec before either side is coded. First, ownership: hardware owns the sample buffer and the filter state, software never writes them except through a documented control register. Second, synchronisation: a frame counter that increments after each new filtered value is written, so software can tell a fresh sample from a stale one without a race. Third, failure behaviour: if software misses two loop deadlines, hardware holds the last PWM value and trips on overcurrent independently, rather than waiting for the CPU.
A minimal version of that contract in firmware looks like this, checked against a 48 MHz Cortex-M4 with CMSIS-style register access:
// Returns false if no stable sample was obtained in 3 attempts.
// Assumes FRAME_CNT increments only after FILTERED_I is updated.
static inline bool read_filtered_current(int32_t *out)
{
for (int attempt = 0; attempt < 3; attempt++) {
uint32_t frame_before = HW->FRAME_CNT;
int32_t value = (int32_t)HW->FILTERED_I;
uint32_t frame_after = HW->FRAME_CNT;
if (frame_before == frame_after) {
*out = value;
return true;
}
}
return false;
}Every retry is checked the same way. If the frame changed during a read, that value is discarded, not returned. If three attempts all straddle an update, the caller knows it has no stable sample and can skip that control cycle instead of acting on a torn or stale value. A 32-bit read on this bus is atomic, but atomicity alone does not stop the value changing between the frame check and the read.
Failure modes I would name in the interview
One is partition creep: firmware starts doing filtering in software because it is easier during bring-up, and the hardware block is never enabled. The fix is to freeze the partition in the architecture spec and make the hardware path the default at reset.
Another is a software-only safety path. If overcurrent protection depends on an interrupt being serviced, a priority inversion or a long critical section can delay it past the transistor's safe time. That is why the comparator trips PWM in hardware and only then interrupts the CPU.
A third is unverifiable hardware. A hardware accelerator that cannot be bypassed, observed, or fed test vectors is a debug trap. I would include a bypass mux, a test mode that loads the filter buffer from the CPU, and status registers for overflow and missed frames. If I cannot observe it on a logic analyser or from firmware, I do not ship it.
The follow-up I expect is about changing the algorithm later. My answer: keep the hardware to the stable, regular kernel (filtering, CRC, FFT butterfly, DMA) and keep coefficients, thresholds, and state machines in software where possible. That gives most of the performance and power benefit without freezing the product behaviour in silicon.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-49A microcontroller SoC must retain SRAM in deep sleep but cut the core rail, and wake on an RTC alarm or GPIO edge. How would you sequence its rails and choose between retention and powerdown for SRAM?
The 90-second answer
I would put the PMU and wake controller in an always-on domain that never loses power, and treat the core, SRAM, and analog blocks as switchable domains. The always-on domain runs from the battery through its own regulator, so cutting the core rail in deep sleep cannot kill the RTC or the wake logic. Sequencing then becomes a contract: each rail comes up only after the previous rail reports power-good, and reset to the core is released only after the last rail is stable.
For this chip I would use four rails. VDD_AON at 1.0 V feeds the PMU, RTC, and wake controller. VDD_IO at 1.8 V feeds the pads. VDD_CORE at 0.9 V feeds the CPU and bus fabric. VDD_SRAM runs at 0.9 V when active and drops to a retention voltage near 0.75 V in deep sleep. VDD_ANA at 1.2 V feeds the ADC and PLL and comes up last, after digital rails have settled, because the PLL needs a clean, stable supply before it locks.
| Step | Action | Wait condition |
|---|---|---|
| 1 | Enable VDD_AON | Regulator power-good |
| 2 | Enable VDD_IO | Power-good, timeout 1 ms |
| 3 | Enable VDD_SRAM to retention | Power-good |
| 4 | Enable VDD_CORE, start core clock | Power-good |
| 5 | Enable VDD_ANA, start PLL | PLL lock |
| 6 | Release core reset | All power-good stable for 16 always-on clocks |
If any step times out, the FSM pulls rails down in reverse order and sets a fault flag instead of releasing reset into a half-powered chip. Shutdown reverses the sequence. Clocks stop first, isolation cells clamp outputs from the dying domain, then VDD_CORE collapses, then VDD_ANA, and VDD_SRAM drops to retention or off. Isolation matters because a powered-down core can otherwise back-drive a pad or leak through a shared net.
// Advance only on power-good; abort on timeout
typedef enum logic [2:0] {IO, SRAM, CORE, ANA, RUN, FAULT} state_t;
state_t state, next;
logic [15:0] cnt;
always_ff @(posedge aon_clk or negedge aon_rst_n) begin
if (!aon_rst_n) begin state <= IO; cnt <= 0; end
else if (cnt == TIMEOUT) state <= FAULT;
else begin cnt <= cnt + 1; state <= next; end
endRetention versus powerdown for SRAM
This is the main trade-off in the design. Retention keeps the array powered at 0.75 V, so firmware wakes in about 50 microseconds with stack and variables intact. Powerdown cuts the array entirely, so wake takes about 5 ms for re-initialisation and all data is lost. Retention costs leakage and a minimum-voltage constraint that must hold at the hot corner. Powerdown costs wake time and forces firmware to save state to flash before entry.
| Choice | Deep-sleep current, hypothetical | Wake latency | Firmware cost |
|---|---|---|---|
| Retention at 0.75 V | 8 uA | 50 us | None, state survives |
| Powerdown | 1.5 uA | 5 ms | Save and restore state |
With a 2000 mAh battery, a device that runs at 12 mA for 5% of the time and deep-sleeps for 95% averages 12 mA x 0.05 + 8 uA x 0.95 = 608 uA with retention, or about 3290 hours. With powerdown the average is 600 uA + 1.4 uA, barely different, because run current dominates. That arithmetic tells me retention is worth it unless the duty cycle drops below roughly 0.1%, where the 6.5 uA saving starts to matter.
Wake-up sources
The RTC alarm is a level source held until acknowledged. The GPIO edge is an edge source that needs a two-flop synchronizer into the always-on clock domain before it can set a wake flag. Each source gets a mask bit and a status bit that survives deep sleep. When a wake fires, the PMU re-sequences the rails, restores clocks, deasserts isolation, and only then releases the core and raises an interrupt with the source ID encoded. If a wake arrives while entry is in progress, the FSM either finishes entry and wakes immediately or aborts before the core rail is cut. I would document that choice, because firmware will race it either way.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-50Walk me through PLL design, jitter, phase noise and loop bandwidth, and how jitter affects a digital system?
The 90-second answer
A PLL locks a VCO to a reference by comparing phase, filtering the error, and driving the VCO control voltage until the divided output matches the reference in frequency and phase. Jitter is the time-domain variation of the output edges from their ideal positions. Phase noise is the same phenomenon viewed in the frequency domain, as noise power around the carrier. Loop bandwidth sets the crossover where the loop stops following the reference and starts letting the VCO run free, so it decides which noise source dominates.
Loop bandwidth trade-off
Inside the bandwidth, output noise tracks the reference, multiplied by the division ratio. Outside it, the loop cannot correct the VCO, so VCO noise dominates. A wide bandwidth, for example 1 MHz on a 25 MHz reference divided to 100 MHz, suppresses VCO noise quickly and gives fast lock, but it passes more reference and charge-pump noise and can pass reference spurs. A narrow bandwidth, for example 10 kHz, filters reference noise well but leaves VCO phase noise uncorrected for longer, slows lock, and makes the loop more sensitive to supply pushing on the VCO.
Design starts from the output requirement, then works backwards. Pick the division ratio from reference and target frequencies. Set bandwidth at roughly one tenth to one twentieth of the reference frequency as a starting point, then check phase margin, typically 45 to 60 degrees, and simulate the integrated phase noise. Integrate the phase noise spectrum over the band of interest to get rms jitter:
import numpy as np
# Hypothetical spectrum: -120 dBc/Hz flat from 10 kHz to 10 MHz
L = 10**(-120/10) # linear, per Hz
bw = 10e6 - 10e3
phi_rms = np.sqrt(2 * L * bw) # rad, single sideband convention
f_out = 100e6
jitter_rms = phi_rms / (2 * np.pi * f_out)
print(f"{jitter_rms*1e12:.1f} ps rms") # about 7.1 ps rms| Choice | Reference noise | VCO noise | Lock time | Typical use |
|---|---|---|---|---|
| Wide bandwidth | Passed to output | Suppressed | Fast | Jitter-sensitive serial link, VCO is noisy |
| Narrow bandwidth | Filtered | Dominates output | Slow | Clean reference, quiet VCO, low power |
How jitter hits a digital system
Jitter eats timing margin directly. A 100 MHz clock has a 10 ns period. If peak-to-peak jitter is 100 ps, that is 1% of the period gone before setup, hold, skew and voltage variation are counted. Random jitter has Gaussian tails, so a 1 ps rms value can produce roughly 14 ps peak-to-peak at a bit error rate of 1e-12, using a 7 sigma excursion. Deterministic jitter from supply ripple or reference spurs does not average out and shows up as periodic spurs in the phase noise plot.
For sampling, aperture jitter limits signal-to-noise ratio. With input frequency f and rms jitter sigma_t, SNR is -20 log10(2 pi f sigma_t). At f = 100 MHz and sigma_t = 1 ps, that gives about 64 dB, which caps an ADC near 10 bits regardless of its nominal resolution. For a serial link, jitter closes the eye at the receiver sampler and raises bit error rate, which is why the same PLL can pass a core timing check and still fail a PCIe or Ethernet eye mask.
Failure modes I check in review: bandwidth set so high that reference spurs pass through, charge pump mismatch creating a spur at the reference rate, and VCO pushing from digital supply noise that no loop setting can fix because the noise sits inside the bandwidth. The fix there is isolation and a clean regulator, not a wider loop.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-51How do process, voltage, and temperature corners change setup and hold timing, and how would you set up the corner matrix for signoff?
The 90-second answer
I would never sign off setup and hold from the same corner. Setup fails when the launching clock is early, the data path is slow, and the capturing clock is late. Hold fails in the opposite direction, when the data path is fast and the capturing clock is early. Process, voltage, and temperature move cell delay and interconnect delay in the same direction for both checks, so the slow corner that exposes setup hides hold, and the fast corner that exposes hold hides setup. I therefore build separate setup and hold scenarios, each with its own library, operating condition, and RC corner, and I require every scenario to pass before tapeout.
Process sets threshold voltage and mobility. SS is slow, FF is fast, TT is nominal. Voltage sets drive current roughly as (Vdd - Vt) to a power near 1 to 2, so a 10% drop in Vdd costs far more delay at low voltage than at nominal. Temperature normally reduces mobility, so hot is slower, but Vt also falls with temperature. In FinFET and other low voltage processes the Vt effect can win near threshold, which is temperature inversion: cold becomes slower than hot for setup at low Vdd. That is why a modern signoff matrix includes a cold setup corner instead of assuming hot is always worst.
| Scenario | Process | Voltage | Temperature | RC corner | Purpose |
|---|---|---|---|---|---|
| setup_worst | SS | 0.90 x nominal | 125 C | worst | main setup check |
| setup_cold | SS | 0.90 x nominal | -40 C | worst | catches temperature inversion |
| setup_nominal | TT | nominal | 25 C | typical | debug and correlation |
| hold_worst | FF | 1.10 x nominal | -40 C | best | main hold check |
| hold_hot | FF | 1.10 x nominal | 125 C | best | catches fast hot hold paths |
| sram_lowv | SS | minimum SRAM Vdd | 125 C and -40 C | worst | read and retention timing |
Libraries and RC corners must match the scenario. Running an SS library with a best RC corner, or an FF library with worst RC, creates a corner that cannot exist in silicon and can hide a real failure. I also add on-chip variation derates, AOCV or POCV, so gates on the same die are not all assumed to shift together. Without that, a nominally passing path can fail when one stage is slow and the next is fast.
A PrimeTime style MMMC setup looks like this:
create_library_set -name lib_ss -timing {ss_0p90v_125c.lib}
create_library_set -name lib_ff -timing {ff_1p10v_m40c.lib}
create_rc_corner -name rc_worst -qx_tech_file worst.qxtech
create_rc_corner -name rc_best -qx_tech_file best.qxtech
create_scenario -name setup_worst -library_set lib_ss -rc_corner rc_worst -setup true
create_scenario -name hold_worst -library_set lib_ff -rc_corner rc_best -hold true
set_clock_uncertainty -setup 0.20 [get_clocks core_clk]
set_clock_uncertainty -hold 0.05 [get_clocks core_clk]Uncertainty is not padding. It covers clock jitter, residual skew after CTS, and modelling error. I set it from the clock specification and CTS report, then check that reported skew plus jitter stays inside it.
Worked example at 200 MHz, period 5.00 ns, setup_worst:
| Term | Value (ns) |
|---|---|
| Clock period | 5.00 |
| Clock to Q, min plus typical | 0.40 |
| Combinational and interconnect delay | 3.90 |
| Setup time at capture flop | 0.15 |
| Uncertainty | 0.20 |
| Setup slack | 5.00 - 0.40 - 3.90 - 0.15 - 0.20 = 0.35 |
The same path in hold_worst uses minimum delays, about 40% of worst in this example, and hold slack is clock to Q min plus data min minus hold time minus clock skew. If that number goes negative, slowing the clock does nothing, because both launch and capture move together. The fix is to add delay in the data path, rebalance CTS skew, or move the flop, not to change frequency.
Signoff also means checking the things STA does not report as slack. I require zero unconstrained paths between synchronous flops, no false path or multicycle exception without a design reason I can defend, max transition, capacitance, and fanout clean in every scenario, and clock skew inside budget after extraction. I compare pre-route and post-route slack to catch a path that only passes because parasitics were missing. If a path passes setup_worst by 0.35 ns but fails setup_cold, that is the corner that decides the design, and I fix it there rather than averaging corners together.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-52Two versions of a chip use the same wafer: version A is 100 mm² at 90% yield and version B is 200 mm² at 80% yield. Which costs less per good die, and how do yield and DFM explain the difference?
The 90-second answer
Yield is the fraction of started dies that pass wafer sort. Cost per good die is wafer cost divided by the number of good dies on that wafer. Version B loses twice: it fits fewer dies on the wafer because it is larger, and a smaller fraction of those dies pass. DFM, design for manufacturability, is how the layout is kept inside the patterns the fab can print and etch repeatably. Rules for minimum width and spacing, metal density, via use and antenna limits are DFM rules. A design that breaks them may pass LVS and still manufacture poorly.
The arithmetic for the two versions
Assume a $9,000 wafer for both versions, with gross dies before test of 640 for version A and 310 for version B. Those gross figures already include partial dies lost at the wafer edge.
| Version | Gross dies | Yield | Good dies | Cost per good die |
|---|---|---|---|---|
| A, 100 mm² | 640 | 90% | 576 | $9,000 / 576 = $15.63 |
| B, 200 mm² | 310 | 80% | 248 | $9,000 / 248 = $36.29 |
Version B costs about 2.3 times as much per good die, even though its area is only twice as large. The extra factor comes from the yield drop from 90% to 80%. If version B had kept 90% yield, it would still cost $9,000 / 279 = $32.26 per good die. The yield loss adds the rest of the gap. That is the point to make in an interview: area and yield multiply, they do not add.
Yield itself has two causes. Defect yield is lost to particles, opens and shorts. Parametric yield is lost when a defect free die fails electrical test, for example SRAM that fails at low voltage or logic that misses timing at a slow corner. A larger die presents more area for a random defect to land on, so defect yield usually falls as area grows. Parametric yield is more about margin. A cell sized with no margin for threshold voltage variation will fail at one corner even with no defect present.
Where DFM changes the bill
| Design choice | Effect on manufacturing | What it costs |
|---|---|---|
| Minimum width and spacing on a critical net | Narrow lines bridge or open more often | Widening the net costs a little routing area and removes a systematic failure |
| Single via on a critical net | One defect on that via kills the die | A redundant via costs almost no area |
| Low metal density in a region | Polishing becomes uneven across the wafer | Dummy fill adds mask data, not die area |
| Long metal antenna on a gate | Plasma charging can damage the gate oxide | A diode or a routing change fixes it before tapeout |
| SRAM sized to the nominal corner only | Fails at low voltage or slow process | Larger cells or assist circuits add area but raise parametric yield |
How the candidate should judge a fix
Look at the wafer sort Pareto first. If one failure bin dominates, the loss is likely parametric and the fix is margin, such as SRAM sizing or a relaxed voltage target. If failures scatter across bins and wafers, the loss is likely defect driven and the fix is usually less area or fewer defect sensitive patterns. If failures cluster in one wafer region or one metal layer, suspect a pattern or density problem and check the DFM rules for that layer.
Every fix has a price. Redundant vias, wider spacing and larger SRAM cells all add area, which lowers gross dies. Fill and rule clean up usually cost no area. The comparison that matters is cost per good die after the fix, not yield in isolation. A change that raises yield from 80% to 88% while adding 5% area is normally a clear win. A change that raises yield by 1% while adding 20% area is not.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-53After layout, STA shows a 120 ps setup violation on one path and a logic bug needs one AND gate added. How do you decide between a metal-only ECO and a cell-based ECO, and walk me through the ECO flow?
The 90-second answer
An ECO is a surgical change to a finished layout, not a re-run of place and route. You keep the placement, clock tree and most routing, change only what the fix needs, then re-extract parasitics and re-sign off timing, DRC and LVS on the changed nets. The split that decides cost and schedule is what you are allowed to touch.
A metal-only ECO changes only metal and via masks. Transistors, diffusion and poly stay identical, so the mask shop only remakes the top metal layers. It can reroute a net, add a buffer from a spare cell that was placed empty during layout, or swap a via. It cannot create a new transistor or a cell that was not already in the library footprint.
A cell-based ECO also changes cells. You can insert, delete, swap or move standard cells, then reroute the affected nets. It fixes real logic bugs and larger timing problems, but it touches more masks, needs a fresh ECO placement and routing pass, and carries a higher risk of new DRC, antenna and hold violations.
Choosing between them
Start from the failing path, not from the tool. Post-layout STA with extracted RC gives the endpoint, launch flop, slack and the net and cell delays along the path. A logic bug is different: the netlist itself is wrong, so no amount of rerouting fixes it.
| Fix needed | Metal-only ECO | Cell-based ECO |
|---|---|---|
| Reroute a congested or high-R net | Yes, first choice | Yes |
| Add a hold buffer | Yes, if a spare cell sits near the net | Yes |
| Upsize a driver to cut setup delay | Limited, spare cells only | Yes, swap to a stronger cell |
| Add a missing AND or OR gate | No, unless a spare gate was pre-placed | Yes |
| Change a flop to a scan or reset variant | No | Yes |
| Masks remade | Top metal and via layers only | Metal plus the layers the new cells use |
| Typical turnaround | Days, mostly ECO route and signoff | Longer, ECO place, route, CTS check and signoff |
The spare cell decision is made months earlier. Layout teams scatter spare buffers, inverters and a few gates, often 1 to 3 percent of the cell count in a timing critical block, and reserve routing tracks above them. Without a spare near the failing net, a metal-only fix may need a long detour that adds capacitance and makes setup worse.
Worked example
Suppose extracted STA reports a setup slack of -120 ps at the slow corner on a 1 ns path, and the same block has a logic bug where a qualifier gate is missing. Hypothetical numbers, but the trace is the point.
| Step | Result |
|---|---|
| Path delay before fix | 1.120 ns, slack -120 ps |
| Cell delay on the critical net | 180 ps, mostly a long M3 route |
| Metal-only attempt | Reroute on a shorter track, path delay 1.045 ns, slack -45 ps |
| Spare buffer inserted for hold | Adds 35 ps, setup slack -80 ps, hold now clean |
| Cell-based fix | Swap driver to a 2x cell, add the missing gate in a spare site, reroute, path delay 0.970 ns, slack +30 ps |
The metal-only route closed most of the gap but left setup failing. That is the signal to escalate. The cell-based fix also absorbed the logic bug, which metal-only could not do without a pre-placed spare gate.
The ECO flow
In practice the ECO netlist is a diff against the taped-out netlist. The tool freezes cells and routes outside the ECO window, places new cells only in spare sites or by moving a small cluster, and routes the new nets with the same design rules and antenna rules. If a clock buffer changes, skew on that branch shifts, so ECO CTS or at least a skew check on the affected tree is mandatory. A setup fix that inserts delay on a shared net can create a hold violation downstream, which is why hold is rechecked on every ECO iteration, not at the end.
Failure modes that bite
Spare exhaustion is the common one. The ECO tool reports no legal site within the routing window, and the fix becomes a long route that fails EM or antenna checks. Congestion is next: ECO nets routed through an already dense channel push neighbours over transition or crosstalk limits after extraction, even though the ECO route itself looked clean before extraction. The third is netlist mismatch. If the ECO Verilog does not match the placed netlist cell for cell, LVS passes on the ECO database but the merged tapeout database differs, and the bug returns in silicon.
Detection is boring and effective: compare the ECO netlist to the layout netlist before routing, run extracted STA on all corners and modes after every ECO route, and run DRC and LVS on the full block, not only the ECO window. If any of those fail, the ECO has grown into a partial re-implementation and should be replanned as one, with a fresh placement for the affected region rather than another patch.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-54How do clock skew, jitter, and uncertainty differ, and how are they budgeted in static timing analysis?
The 90-second answer
Skew is the difference between clock arrival at the capture flop and clock arrival at the launch flop. Jitter is how much a single clock edge moves from its ideal position from cycle to cycle. Uncertainty is the margin the timer subtracts for setup, and adds for hold, to cover jitter and residual clock error it does not model per path.
For launch flop Q and capture flop D, with skew defined as t_capture_clk - t_launch_clk:
setup slack = T - (t_cq + t_logic + t_setup) + skew - uncertainty_setup
hold slack = (t_cq + t_logic - t_hold) - skew - uncertainty_holdSkew appears explicitly because the timer knows clock arrival at each flop after clock tree synthesis. Jitter does not appear as its own term. It is folded into uncertainty.
| Term | Meaning | Controlled by |
|---|---|---|
| Skew | t_capture_clk - t_launch_clk for one flop pair | CTS balancing and clock tree topology |
| Jitter | Edge position varies cycle to cycle | PLL, crystal, supply noise |
| Uncertainty | Global margin applied to the clock | SDC, set from the jitter specification plus margin |
Worked example
Hypothetical figures for a 1000 ps period:
| Item | Value |
|---|---|
| Launch clock arrival | 120 ps |
| Capture clock arrival | 90 ps |
| Skew (90 - 120) | -30 ps |
t_cq + t_logic + t_setup | 820 ps |
| Setup uncertainty | 80 ps |
| Setup slack | 1000 - 820 - 30 - 80 = 70 ps |
Negative skew costs 30 ps on setup here. Balancing that pair to 5 ps skew would raise slack to 95 ps without changing logic. The same positive skew that helps setup hurts hold, because hold slack subtracts skew. That sign flip is why CTS cannot simply maximise skew.
Budgeting it
Uncertainty is set once per clock in SDC, with separate setup and hold values:
set_clock_uncertainty -setup 0.080 [get_clocks clk]
set_clock_uncertainty -hold 0.030 [get_clocks clk]The values come from the clock source jitter specification and the project's margin policy. They are not derived from the skew the timer already models. Adding skew again inside uncertainty would double count it. Pre-CTS analysis sometimes uses a larger uncertainty to stand in for unknown skew, then reduces it after CTS when real clock arrivals are available.
Setting uncertainty to zero leaves jitter unbudgeted, so a path that passes at nominal can fail at a corner where jitter is larger. Setting it far above the specification hides real logic delay and forces a slower clock than needed. The defensible number is tied to a measured jitter spec, split between setup and hold, and checked against post-CTS skew reports.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-55A 32-bit multiplier at 200 MHz misses its power budget by 25% with only 80 ps of setup slack: how do you quantify glitch power and choose between clock gating, logic restructuring and operand isolation without breaking timing or creating a runt clock?
The 90-second answer
Glitch power is dynamic power from transitions that do not change the intended output. With Pdyn = alpha * C * Vdd^2 * f, a glitch raises alpha for no useful work. It comes from reconvergent fanout: one signal reaches a gate through two paths of different delay, so the gate briefly sees a wrong input combination and switches, then switches again when the late path arrives. The pulse width is roughly the arrival skew. RTL simulation will not show it. Gate level simulation with SDF and power analysis from a VCD or SAIF activity file will.
In your scenario the three techniques are not interchangeable. Clock gating removes clock power from idle flops but does nothing for a hazard inside active logic. Operand isolation stops idle data toggling into the multiplier array, which is where fanout multiplies the waste. Logic restructuring removes the hazard at its source by balancing arrivals, but it costs delay and area on a path that has only 80 ps of slack. The senior decision is to measure where the glitch activity sits, then spend slack only where the power return justifies it.
Exact working on the multiplier
Assume, as a labelled hypothetical, a 32-bit multiplier at 1.0 V, 200 MHz, effective switched capacitance 2.0 pF, useful activity 0.10 and glitch activity 0.06.
| Component | Calculation | Power |
|---|---|---|
| Useful | 0.10 * 2.0e-12 * 1.0^2 * 200e6 | 40 mW |
| Glitch | 0.06 * 2.0e-12 * 1.0^2 * 200e6 | 24 mW |
| Total | 40 + 24 | 64 mW |
Glitch power is 60% of useful power on that block. If the block is idle 90% of cycles and operand isolation cuts glitch activity to 0.01 during idle, average glitch power falls from 24 mW to about 2.4 mW plus the small active term. That alone can close a 25% block level miss. Clock gating the output register bank saves clock network power, often 30 to 50% of flop power, but if the array inputs still toggle the array still burns the 24 mW.
Why restructuring is the risky one here
Suppose a reconvergent node has arrivals at 120 ps and 210 ps, so skew is 90 ps and the glitch pulse is about 90 ps wide. Balancing it with a buffer on the fast path adds roughly 90 ps of delay to that path. With only 80 ps of setup slack at the worst corner, that buffer can create a timing violation after place and route, when wire delay changes the skew again. Restructuring also changes cell sizes, which changes output slew and downstream arrival times. It is the right fix for a hot, always active hazard, and the wrong first move for an idle 90% of the time block.
Clock gating failure mode
A combinational enable that changes near the clock edge produces a runt pulse: the gated clock rises late or falls early, the flop sees a short clock high time, and setup or hold fails intermittently. The enable must be latched on the opposite phase inside an integrated clock gating cell, and it must meet setup to that latch. Synthesis infers this from a registered enable pattern. Hand built AND gating in RTL is a common source of silicon debug.
// Checked against SystemVerilog-2017. Intent for synthesis to infer an ICG cell.
module gated_bank (
input logic clk,
input logic rst_n,
input logic enable,
input logic [31:0] d,
output logic [31:0] q
);
logic gated_clk;
// Synthesis maps this enable pattern to an integrated clock gating cell
// with a negative level sensitive latch. Do not replace with assign gated_clk = clk & enable;
always_latch begin
if (!clk)
gated_clk = enable;
end
always_ff @(posedge gated_clk or negedge rst_n) begin
if (!rst_n)
q <= 32'b0;
else
q <= d;
end
endmoduleOperand isolation placement
Place the isolation gate at the multiplier boundary, not far upstream. If it sits three logic levels away, the interconnect and intermediate gates still toggle. The isolation gate adds delay on the active path, so check it against the 80 ps slack at the slow corner. Force inputs to zero when disabled so the partial product array sees a constant. The enable must be decoded early enough that it settles before the data changes, otherwise the isolation gate output itself glitches.
The order that survives tapeout is measure first, isolate idle data, gate idle clocks, and restructure only the paths where glitch activity is large and the block is active. That keeps the timing cost where the power return is highest and avoids spending the last 80 ps of slack on a hazard that isolation would have removed.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-56How do D, T and JK flip-flops differ on a clock edge, why does a D flop need both setup and hold time, and when would you just implement T or JK behaviour with a D flop?
The 90-second answer
D, T and JK are input encodings for the same edge-triggered storage core. A D flop stores whatever is on D at the rising edge. A T flop toggles Q when T is 1 and holds Q when T is 0. A JK flop sets Q when J is 1 and Q is 0, resets Q when K is 1 and Q is 1, and toggles when both are 1. In a standard-cell flow you write the behaviour in RTL and synthesis maps it to a D cell plus a small amount of combinational logic. You rarely instantiate a native JK cell.
Setup and hold protect opposite sides of the edge. Setup requires D to be stable before the edge so the internal latch can resolve. Hold requires D to stay stable for a short time after the edge so the new value does not race through before the clocked element has closed. Miss setup and the flop captures the previous value, or goes metastable if D changes inside the aperture. Miss hold and it captures the new value a cycle early. Slowing the clock can repair setup. It cannot repair hold, because launch and capture edges move together.
What each type does at the edge
| Type | Q next | Behaviour | Typical RTL |
|---|---|---|---|
| D | D | Stores the input | q <= d; |
| T | Q xor T | Toggles on T=1, holds on T=0 | q <= q ^ t; |
| JK | J if Q=0, K if Q=1, toggle if J=K=1 | Set, reset or toggle selected by current Q | q <= (q ? ~k : j); |
| SR | S sets, R resets | S=R=1 is undefined in most cells | Avoid for synchronous logic |
The JK row shows why synthesis prefers D. The JK function needs a mux or XOR in front of the storage element anyway, so a JK cell is a D cell with extra gates and no timing advantage. The same applies to T. A counter written as a T flop becomes an XOR gate feeding a D flop, which the timer can optimise as one path.
// 4-bit counter written as T behaviour, implemented as D flops
module counter_t (
input logic clk, rst_n, en,
output logic [3:0] count
);
logic [3:0] t;
assign t[0] = en;
assign t[1] = en & count[0];
assign t[2] = en & count[0] & count[1];
assign t[3] = en & count[0] & count[1] & count[2];
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n) count <= 4'b0;
else count <= count ^ t;
end
endmoduleEach bit is a D flop. The XOR is the T encoding. If you described the same counter with JK flops, the netlist after synthesis would look almost identical.
Setup and hold with real numbers
For a launch flop driving a capture flop:
setup slack = Tclk - (tCQ + tlogic + tsetup - tskew)
hold slack = (tCQ + tlogic) - thold + tskewTake a hypothetical 200 MHz path. Tclk is 5.00 ns, clock-to-Q is 0.15 ns, combinational delay is 3.20 ns, setup is 0.08 ns, hold is 0.05 ns, and skew is 0.10 ns with the capture clock arriving late.
| Check | Calculation | Slack |
|---|---|---|
| Setup | 5.00 - (0.15 + 3.20 + 0.08 - 0.10) | 1.67 ns |
| Hold | (0.15 + 3.20) - 0.05 + 0.10 | 3.40 ns |
Setup is a maximum delay check. It fails at the slow, low-voltage corner when tlogic grows. Hold is a minimum delay check. It fails when a path becomes too fast, for example after an ECO removes a buffer, or when skew moves the capture edge earlier. That is why hold fixes add buffers or change clock skew, while setup fixes resize gates, reduce logic depth or lower the clock frequency.
When to choose what
Use a scan D flop as the default. The scan mux lets ATPG shift patterns through the chain, and the library characterises setup, hold, clock-to-Q and recovery for that exact cell. Use a high-Vt variant when leakage dominates and timing has margin, and a low-Vt variant when the path is timing critical. Use a retention flop only when the supply domain can collapse and the value must survive. A plain flop loses state on power gating, so retention is a functional requirement, not a power optimisation.
Pick T or JK behaviour in RTL when it makes the intent clear, such as a toggle or counter. Let synthesis build the D implementation. Reach for a native JK or SR cell only if the library team has characterised one for a specific datapath and you have STA and power data showing a benefit. In mainstream SoC design that case is rare.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-57How do combinational hazards produce glitches, and how would you redesign a two-level gate network to be hazard-free?
The 90-second answer
A combinational hazard is a glitch on the output of a gate network when an input changes, even though the steady-state output should not change. It happens because different paths through the network have different delays. One path turns off before the other turns on, so for a short interval no path is active and the output falls, or the reverse and it rises.
The classic case is a static-1 hazard. Take F = AB + A'C. When B = C = 1, the output should stay at 1 whatever A does. If A goes 0 to 1, the A'C term turns off after the inverter delay, while the AB term turns on immediately. For roughly the inverter delay, both AND gates are off and F pulses to 0.
| Time | A | B | C | Ideal F | Actual F | Why |
|---|---|---|---|---|---|---|
| t0 | 0 | 1 | 1 | 1 | 1 | A'C active |
| t1 | 1 | 1 | 1 | 1 | 1 | AB turns on at once |
| t2 | 1 | 1 | 1 | 1 | 0 | A'C now off, gap between paths |
| t3 | 1 | 1 | 1 | 1 | 1 | AB path settled, glitch ends |
The fix is to add the consensus term BC: F = AB + A'C + BC. When B = C = 1, the BC term holds F at 1 during the transition, so the gap never reaches the output. In a Karnaugh map, the rule is the same: if two adjacent 1s are covered by different product terms, add a third term covering both, or choose a cover where one term covers the pair.
// Checked against IEEE 1800-2017 syntax; synthesis behaviour varies by tool.
module hazard_example (
input logic a, b, c,
output logic f_hazard, f_safe
);
assign f_hazard = (a & b) | (~a & c);
assign f_safe = (a & b) | (~a & c) | (b & c); // consensus term BC
endmoduleThe three types, and why they matter differently
| Type | Steady state | Glitch | Typical cause |
|---|---|---|---|
| Static-1 | 1 | brief 0 | Two 1-paths switch with unequal delay |
| Static-0 | 0 | brief 1 | Dual of the above, two 0-paths switch |
| Dynamic | 0 | brief 1, sometimes multiple pulses | Three or more levels, path delays differ by more than one gate delay |
Static hazards are the ones you fix with a redundant term. Dynamic hazards are harder: the output should stay 0 but pulses to 1, and a single consensus term may not cover it. In practice you avoid the structure that creates them, meaning deep multi-level asynchronous logic, rather than patching it term by term.
Designing hazard-free logic in a real flow
First, ask whether the glitch can be seen. In a fully synchronous block, a glitch that settles well before the next clock edge is usually harmless because the flip-flop samples the settled value. It becomes a bug when the output feeds asynchronous logic: a reset, a clock gate enable, a latch, an asynchronous set, or a decode that triggers something on a level rather than a clock edge. It also becomes a bug if the glitch is wide enough to cross a sampling edge, which is a timing problem rather than a logic problem.
Second, remove the hazard at the source where the output is asynchronous. Add the consensus term, or restructure so a single product term covers the adjacent minterms. Check the Karnaugh map or the prime implicant cover for adjacent 1s (or 0s for static-0) split across terms.
Third, protect the redundant term through synthesis. This is the step people miss. A synthesis tool sees BC as logically redundant and will optimise it away, recreating the hazard in the netlist even though the RTL looks safe. Instantiate the redundant gate explicitly, mark it to be kept, and confirm it survives in the post-synthesis netlist. If the tool still removes it, implement that gate in a way the optimiser cannot fold into the main cone, and re-check after place and route, because routing delays change which path is slower.
Fourth, prefer the structural fix when you can. Registering the output moves the problem into the synchronous domain, where STA already accounts for settling time. That costs a cycle and area, so it is overkill for an internal decode but is the right call for anything leaving the block or driving a clock or reset.
A glitch of 0.2 ns from a 0.15 ns inverter plus gate mismatch will not fail a 10 ns synchronous path, and the same glitch will reset a chip if it lands on an asynchronous clear. That difference, not the existence of the glitch, decides how much effort the fix deserves.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-58What is the standard way to make an FSM recover safely from an illegal state, and how do you implement it in RTL?
The 90-second answer
Give every unused encoding a default transition to a known safe state, usually IDLE, and make the next-state logic fully specified so synthesis cannot invent its own behaviour for those encodings. In RTL that is a case statement with a default branch that assigns IDLE. The machine then reaches IDLE in one clock cycle after entering an illegal state, with outputs deasserted in IDLE so no spurious enable or write strobe fires during recovery.
That one rule covers the usual causes of illegal states. A single-event upset can flip a state bit, a reset glitch can leave the register in an undefined encoding, and debug forcing can load a value the designer never intended. With binary encoding, any state count that is not a power of two leaves unused codes. Three states in two bits leaves one unused code. Five states in three bits leaves three.
| Encoding stored | Legal state? | Next state after one clock | Output during recovery |
|---|---|---|---|
2'b00 | IDLE | IDLE or READ/WRITE per inputs | busy=0 |
2'b01 | READ | IDLE when done | busy=1 |
2'b10 | WRITE | IDLE when done | busy=1 |
2'b11 | No | IDLE | busy=0, err=1 |
Implementation
typedef enum logic [1:0] {IDLE = 2'b00, READ = 2'b01, WRITE = 2'b10} state_t;
state_t state_q, state_d;
logic err_q;
always_comb begin
state_d = IDLE;
case (state_q)
IDLE: state_d = req ? (wr ? WRITE : READ) : IDLE;
READ: state_d = done ? IDLE : READ;
WRITE: state_d = done ? IDLE : WRITE;
default: state_d = IDLE;
endcase
if (rst) state_d = IDLE;
end
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
state_q <= IDLE;
err_q <= 1'b0;
end else begin
state_q <= state_d;
err_q <= (state_q != IDLE) && (state_q != READ) && (state_q != WRITE);
end
endThe combinational block assigns state_d on every path, so no latch is inferred. The sequential block only registers the result. Outputs are decoded from state_q, and IDLE drives them to their inactive values.
Why the default matters
Without a default branch, an incomplete case can infer a latch or let the synthesis tool choose an arbitrary next state for the unused code. That choice may differ between synthesis and simulation, and it may hold the machine in the illegal encoding indefinitely. A fully specified case removes that ambiguity. Formal tools can then prove the property that the state is always a legal encoding after reset, and a simulation test can force 2'b11 and check that the machine returns to IDLE within one cycle and pulses err_q.
Encoding choice does not change the recovery rule. Binary encoding is the default for a small controller because it uses few flops and a little decode logic. One-hot encoding uses one flop per state and simplifies decode, but it still needs the same default if a bit upset creates a pattern with zero or two bits set. The safe-state default is the part that guarantees recovery in either encoding.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-59How do fixed-priority, round-robin, and weighted arbitration differ, and how would you bound worst-case latency for a low-priority master on a shared SoC bus?
The 90-second answer
I would ask how many masters there are, the maximum burst length each can issue, and whether any master has a hard deadline. Those three numbers decide the scheme. Fixed priority is cheapest and gives the lowest latency to the top master, but a low priority master can starve if higher masters keep requesting. Round robin gives every requesting master a turn in circular order, so with N masters the worst wait is bounded by the other N-1 masters each finishing one burst. Weighted round robin keeps that bound and lets a DMA engine take, say, 4 slots for every 1 slot given to a peripheral, at the cost of a longer bound for the peripheral.
For a shared SoC bus I would normally use weighted round robin with a per-master burst cap, plus aging for any QoS class that must not miss a deadline. The cap is what makes the bound real. The arbiter can only change grants at a transaction boundary. It cannot split an AXI burst in the middle, and it cannot break a locked sequence. So the bound assumes masters are configured, or the interconnect is configured, to issue bursts no longer than the cap. A master that issues an unbounded burst breaks the bound regardless of the arbitration algorithm.
Schemes compared
| Scheme | How the next grant is picked | Fairness | Worst case for lowest master | Hardware cost | | --- | --- | --- | | Fixed priority | Highest numbered requesting master wins every cycle | None. Starvation is possible | Unbounded if higher masters never idle | One priority encoder, smallest | | Round robin | Pointer moves to the master after the last grant, next requester in circular order wins | Every requester gets a grant within one full round | (N-1) x max burst + arbitration cycles | Pointer plus rotating priority encoder | | Weighted round robin | Each master gets a weight, for example 4, 2, 1. A counter spends the weight before the pointer moves on | Proportional to weight over a window of sum(weights) grants | (sum of weights of others) x max burst, roughly | Weight counters, still small | | TDMA | Fixed slots in a repeating frame, master may only drive in its slot | Equal or weighted by slot count | One frame length, but idle slots are wasted | Frame counter, wastes bandwidth when a master is idle | | Dynamic priority with aging | Priority rises the longer a request waits, or QoS field is compared first | Good for mixed deadlines, harder to verify | Bounded only if aging rate and burst cap are both specified | Comparators on age counters, most logic |
Centralized arbitration, one arbiter collecting all requests, is what I would build for an on-chip bus of up to about 16 masters. Distributed schemes such as token passing or self-prioritized daisy chains spread the logic but make the bound depend on token travel time and on every node behaving, which is harder to close in timing and to verify.
Worked bound
Take 8 masters at 200 MHz, so one cycle is 5 ns. Cap every burst at 16 beats, and allow 2 cycles of arbitration and grant latency per burst. The arbiter grants at burst boundaries only.
Round robin worst case for one master, assuming all 7 others request continuously:
wait = 7 x (16 + 2) cycles = 126 cycles = 630 nsWeighted round robin with weights 4, 2, 1, 1, 1, 1, 1, 1 for the 8 masters gives a window of 12 grants. The weight-1 master waits for the other 11 grants:
wait = 11 x 18 cycles = 198 cycles = 990 nsThat is the price of giving the DMA engine 4 slots. If that peripheral has a 2 microsecond deadline, 990 ns still passes. If it has a 500 ns deadline, weighted round robin with those weights fails and I would either raise its weight, shorten the allowed burst length to 8 beats, or move it to a separate bus segment. If a master is allowed to issue a 256-beat burst, the same calculation gives 11 x 258 cycles, about 14.2 microseconds, and no arbitration scheme on that shared bus can meet a 2 microsecond deadline for the other masters.
Round robin core
// 8 masters, one-hot requests, grant is one-hot or zero.
// Checked against a reference model in UVM with random request patterns.
module rr_arbiter #(
parameter int N = 8
)(
input logic clk,
input logic rst_n,
input logic [N-1:0] req,
output logic [N-1:0] grant
);
logic [2:0] last; // index of last granted master
logic [2:0] winner; // index of master granted this cycle
logic found;
always_comb begin
grant = '0;
winner = last;
found = 1'b0;
// Scan circularly from last+1, first requester wins.
for (int i = 0; i < N; i++) begin
int idx = (int'(last) + 1 + i) % N;
if (!found && req[idx]) begin
grant[idx] = 1'b1;
winner = idx[2:0];
found = 1'b1;
end
end
end
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n)
last <= 3'd0;
else if (found)
last <= winner;
end
endmoduleIn production I would add the burst counter and the weight counters around this core, and I would register the grant if the request to grant path misses timing at 200 MHz. The combinational scan above is fine for 8 masters, but at 32 masters the scan chain becomes the critical path, so I would switch to a tree of priority encoders or pipeline the arbitration.
Failure modes I would test for
A grant that stays asserted after the master drops its request, because the arbiter sampled req late. A pointer that does not advance when the granted master is the only requester, which looks harmless but breaks the circular scan after a reset. Two masters granted in the same cycle after a reset release, which corrupts the bus. And a master that never deasserts valid, which is why a watchdog timeout that forces the pointer on at the next transaction boundary is not optional. I would check each of these with directed tests plus constrained random traffic, and I would assert in the testbench that grant is always one-hot or zero and that no master waits more than the computed bound while continuously requesting and respecting the burst cap.
The short version I would give in the interview: fixed priority for latency, round robin for fairness, weighted round robin when bandwidth must be split unevenly, and in every case the bound comes from a stated burst cap and a stated number of masters, not from the arbitration algorithm alone.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-60Walk me through designing an asynchronous FIFO for crossing between two clock domains, including Gray-coded pointers and how you generate full and empty flags?
The 90-second answer
An asynchronous FIFO is a dual-port memory with independent write and read clocks, plus pointers that are safe to sample across domains. I would use a power-of-two depth, say 16 entries of 32 bits, because the wrap logic then falls out of the pointer width. Each side keeps a binary pointer for addressing and a Gray-coded version for crossing. Only the Gray pointer crosses, through two flops in the receiving domain. Full is computed in the write domain from the synchronized read pointer. Empty is computed in the read domain from the synchronized write pointer. Both flags are registered, and both are conservative because the synchronized pointer is stale by two destination clocks, so the FIFO reports full a little early and empty a little early. That wastes a couple of slots but never overflows or underflows.
Structure
Let AW = log2(DEPTH). Pointers are AW+1 bits. The low AW bits address the memory. The extra bit is a wrap bit that toggles each time the pointer passes the end of the memory. Two pointers with the same low bits but different wrap bits are one full lap apart.
// Checked against IEEE 1800-2017 style synthesizable RTL.
// DEPTH must be a power of two. WIDTH is the data width.
module async_fifo #(
parameter int DEPTH = 16,
parameter int WIDTH = 32
)(
input logic wr_clk,
input logic rd_clk,
input logic wr_rst_n, // async assert, sync release per domain
input logic rd_rst_n,
input logic wr_en,
input logic [WIDTH-1:0] wr_data,
output logic full,
input logic rd_en,
output logic [WIDTH-1:0] rd_data,
output logic empty
);
localparam int AW = $clog2(DEPTH);
logic [WIDTH-1:0] mem [DEPTH];
logic [AW:0] wr_bin, wr_gray;
logic [AW:0] rd_bin, rd_gray;
logic [AW:0] wr_bin_next, wr_gray_next;
logic [AW:0] rd_bin_next, rd_gray_next;
logic [AW:0] wr_gray_sync1, wr_gray_sync2; // into rd_clk domain
logic [AW:0] rd_gray_sync1, rd_gray_sync2; // into wr_clk domain
logic full_next, empty_next;
function automatic logic [AW:0] bin2gray(input logic [AW:0] b);
return b ^ (b >> 1);
endfunction
// Write side: advance only when not full. full is a register,
// so this next-pointer logic has no combinational loop.
assign wr_bin_next = wr_bin + (wr_en && !full);
assign wr_gray_next = bin2gray(wr_bin_next);
always_ff @(posedge wr_clk or negedge wr_rst_n)
if (!wr_rst_n) begin wr_bin <= '0; wr_gray <= '0; end
else begin wr_bin <= wr_bin_next; wr_gray <= wr_gray_next; end
always_ff @(posedge wr_clk)
if (wr_en && !full) mem[wr_bin[AW-1:0]] <= wr_data;
// Read side: advance only when not empty. empty is a register.
assign rd_bin_next = rd_bin + (rd_en && !empty);
assign rd_gray_next = bin2gray(rd_bin_next);
always_ff @(posedge rd_clk or negedge rd_rst_n)
if (!rd_rst_n) begin rd_bin <= '0; rd_gray <= '0; end
else begin rd_bin <= rd_bin_next; rd_gray <= rd_gray_next; end
assign rd_data = mem[rd_bin[AW-1:0]]; // FWFT style; register it if timing needs it
// Two-flop synchronizers: Gray code crosses, binary never does
always_ff @(posedge rd_clk or negedge rd_rst_n)
if (!rd_rst_n) begin wr_gray_sync1 <= '0; wr_gray_sync2 <= '0; end
else begin wr_gray_sync1 <= wr_gray; wr_gray_sync2 <= wr_gray_sync1; end
always_ff @(posedge wr_clk or negedge wr_rst_n)
if (!wr_rst_n) begin rd_gray_sync1 <= '0; rd_gray_sync2 <= '0; end
else begin rd_gray_sync1 <= rd_gray; rd_gray_sync2 <= rd_gray_sync1; end
// Registered flags, evaluated against the next pointer value.
// Full: next write Gray equals synced read Gray with top two bits inverted.
assign full_next = (wr_gray_next == {~rd_gray_sync2[AW:AW-1], rd_gray_sync2[AW-2:0]});
always_ff @(posedge wr_clk or negedge wr_rst_n)
if (!wr_rst_n) full <= 1'b0;
else full <= full_next;
// Empty: next read Gray equals synced write Gray exactly.
assign empty_next = (rd_gray_next == wr_gray_sync2);
always_ff @(posedge rd_clk or negedge rd_rst_n)
if (!rd_rst_n) empty <= 1'b1;
else empty <= empty_next;
endmoduleThe memory itself is written in one clock domain and read in the other. In an ASIC flow that is usually a dual-port SRAM macro or a register file with two ports in synthesis. The pointers and flag logic stay in flops so the crossing is contained to the synchronizer registers.
Why Gray code, and why the flag equations look like that
A binary pointer changes several bits at once, for example 0111 to 1000. If the receiving flops sample during that transition, each bit can resolve independently and the sampled word can be any mix, including a value the pointer never held. Gray code changes exactly one bit per increment, so a metastable sample resolves to either the old value or the new value. Both are safe, only one cycle stale.
Full and empty compare Gray values directly, which avoids converting the synchronized pointer back to binary in the other domain. For empty, equality of the next read Gray pointer and the synchronized write Gray pointer means the read side has caught up with everything the write side has published. For full, the write side has lapped the read side by one full memory cycle. In Gray code a one-lap difference shows up as the top two bits inverted and the rest equal, hence the concatenation in the full_next assignment. Evaluating against the next pointer and registering the result makes the flag assert on the same edge the pointer takes the last slot, rather than one cycle later. The registered form also breaks the loop that a combinational flag would create, since the next pointer depends on the current registered flag, not on the flag being computed.
Worked trace, depth 8
Assume AW = 3, pointers are 4 bits, write clock faster than read clock.
| Step | wr_bin | wr_gray | rd_bin | rd_gray | Occupancy (true) | full | empty |
|---|---|---|---|---|---|---|---|
| reset | 0000 | 0000 | 0000 | 0000 | 0 | 0 | 1 |
| 8 writes, no reads | 1000 | 1100 | 0000 | 0000 | 8 | 1 | 0 |
| 1 read | 1000 | 1100 | 0001 | 0001 | 7 | 0 | 0 |
| 7 more reads | 1000 | 1100 | 1000 | 1100 | 0 | 0 | 1 |
| 1 more write | 1001 | 1101 | 1000 | 1100 | 1 | 0 | 0 |
At the full point, wr_gray = 1100 and the synchronized rd_gray = 0000. Inverting the top two bits of the read value gives 1100, which matches. At empty, both Gray pointers are 1100 after the wrap bit has toggled, so equality holds even though the binary pointers have wrapped past zero.
Trade-offs and failure modes
Throughput is one word per clock on each side, independent of the other clock, as long as the average rates match. The cost is latency and wasted capacity. Each flag lags by two destination clocks, so after the last read the write side may still see full for two write clocks, and after the first write the read side may still see empty for two read clocks. With a 16-deep FIFO that is acceptable. With a 4-deep FIFO it eats half the usable depth, which is why I would not pick a shallow FIFO for a bursty interface.
Three mistakes show up in review. First, synchronizing the binary pointer and converting it back. That reintroduces the multi-bit sampling hazard the Gray code exists to remove. Second, a non-power-of-two depth. The wrap-bit comparison assumes the low bits cycle through every address exactly once per lap, so depth 12 breaks both the address wrap and the full equation. Third, resetting only one domain, or releasing reset without a synchronizer in each domain. The pointer in the reset domain can start moving while the other side still samples zeros, and the flags can glitch. I assert both resets together and release each through its own two-flop reset synchronizer.
A subtler one is decoding the synchronized Gray pointer combinationally to compute occupancy for a debug counter. That is fine for debug, but the result is stale and must never gate wr_en or rd_en. Only the two registered flag equations above may control acceptance, because they are the ones proven conservative under pointer staleness.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-61How does CRC detect errors in a serial frame, and where would you use it instead of a simple checksum in a protocol you are designing?
The 90-second answer
CRC treats the frame as a polynomial over GF(2) and appends a remainder that makes the whole codeword divisible by a fixed generator polynomial. The receiver repeats the division. A zero remainder means the received polynomial is divisible by the generator, so the frame is accepted. A non-zero remainder means corruption occurred somewhere in the frame.
That is detection, not correction. CRC tells you the frame is bad so you can drop it and request a retransmission. It does not tell you which bit flipped, and it is not authentication. Anyone can recompute a valid CRC for forged data.
How the hardware computes it
For a generator of degree n, the transmitter appends n zero bits to the message, divides by the generator, and sends the n-bit remainder. Division in GF(2) uses XOR instead of subtraction, with no carries. In hardware that division is an LFSR. Each input bit is XORed with the outgoing feedback bit and shifted through the tap positions defined by the polynomial.
Worked example with CRC-3, generator x^3 + x + 1 (binary 1011), message 1101:
| Step | Operation | Register / result |
|---|---|---|
| 1 | Append three zeros | 1101000 |
| 2 | XOR divide by 1011 from the left | remainder 001 |
| 3 | Transmit message plus remainder | 1101 001 |
| 4 | Receiver divides 1101001 by 1011 | remainder 000, accept |
| 5 | Flip one bit, receive 1101011, divide | remainder non-zero, reject |
A single flipped bit always changes the remainder, because the error polynomial x^k is never divisible by a generator that has a non-zero constant term. Burst errors up to n bits long are also always detected. For longer bursts and random corruption, the chance of an undetected error is roughly 2^-n for a well chosen polynomial. CRC-16 gives about 1 in 65,536, CRC-32 about 1 in 4.3 billion, under the assumption the error pattern is not adversarial.
Polynomial choice sets the Hamming distance for a given frame length. CRC-32 (Ethernet, IEEE 802.3, polynomial 0x04C11DB7, reflected 0xEDB88320) is chosen to keep distance 4 out to several kilobytes. CRC-16 variants trade that distance for a shorter check field. CAN uses CRC-15 with polynomial x^15 + x^14 + x^10 + x^8 + x^7 + x^4 + x^3, sized for CAN frames up to 130 bits.
// CRC-16/CCITT-FALSE, poly 0x1021, init 0xFFFF, MSB first
// One bit per clock. Parallel version XORs 8 bits per clock in real RTL.
module crc16_lfsr (
input logic clk,
input logic rst_n,
input logic data_in,
input logic data_valid,
input logic init,
output logic [15:0] crc_out
);
logic [15:0] crc_q;
logic fb;
assign fb = data_in ^ crc_q[15];
assign crc_out = crc_q;
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n || init)
crc_q <= 16'hFFFF;
else if (data_valid)
crc_q <= {crc_q[14:0], 1'b0} ^ (fb ? 16'h1021 : 16'h0000);
end
endmoduleInit value, reflected input and output, and final XOR are part of the standard. CRC-16/CCITT-FALSE uses init 0xFFFF and no reflection. CRC-16/MODBUS uses init 0xFFFF, reflected polynomial 0xA001, and a final XOR of zero. Mixing those up is the most common bring-up bug. The check value for ASCII 123456789 is 0x29B1 for CCITT-FALSE and 0x4B37 for MODBUS. Run that vector in simulation before you debug the wire.
Where it appears in serial protocols
| Protocol | Check | Why CRC fits |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Ethernet | CRC-32 over destination, source, length and payload | Long frames, high bit rate, hardware FCS at line rate |
| CAN / CAN FD | CRC-15 / CRC-17 or 21 over bit-stuffed frame | Short frames, safety related, fast error flag and retransmit |
| USB | CRC-5 token, CRC-16 data | Small token check catches address errors cheaply |
| PCIe | LCRC-32 per TLP, plus sequence CRC | Protects packets across a link that already has replay |
| Modbus RTU, CCITT serial links | CRC-16 | Two byte overhead acceptable on low rate links |
I2C and SPI have no standard CRC in the base protocol. I2C relies on ACK and the application protocol. SPI relies on the application framing. If you add a CRC there, both ends must agree on polynomial, init, reflection and byte order, and you must decide whether it covers address, command and data or data only.
CRC versus checksum and parity
| Method | Overhead | Detects | Misses |
|---|---|---|---|
| --- | --- | --- | --- |
| Single parity bit | 1 bit | Any odd number of bit flips in the protected block | Any even number, including a swapped byte pair |
| 16-bit sum or XOR checksum | 16 bits | Most single errors, some bursts | Errors that cancel in the sum, byte swaps, many burst patterns |
| CRC-16 | 16 bits | All bursts up to 16 bits, all single and double errors within the designed distance | Patterns that happen to be multiples of the generator, about 1 in 65,536 random patterns |
| SECDED ECC | 8 bits per 64 data bits plus logic | Corrects single errors, detects double errors | Triple errors can alias as single errors |
A checksum is cheaper in gates and easier to compute in software, but its miss rate depends on the data pattern. CRC costs an LFSR, which is a handful of XOR gates and flip-flops, and it runs at one bit per clock or eight bits per clock with a parallel LFSR. At 1 Gb/s Ethernet rates that parallel form is mandatory. The gate cost is small compared with the cost of a retransmitted frame on a noisy link.
Failure modes to name in an interview
Truncation and framing errors can pass if the receiver computes CRC over a different bit count than the transmitter sent. Bit stuffing in CAN and USB must be removed before the CRC check, or the check fails on every frame. A receiver that checks CRC but ignores a non-zero remainder under a timeout or reset condition will accept corrupt data. CRC also fails silently if the generator is implemented with the wrong tap for a reflected standard. That produces a valid looking but wrong remainder on both ends only if both ends share the bug, which is why the 123456789 check value matters.
Use CRC when you need cheap, fast detection of random channel errors and you have a retry mechanism. Use ECC when the data must be corrected in place, as in SRAM. Use a MAC or signature when the threat is deliberate forgery, because CRC is linear and an attacker can adjust the remainder to match modified data with a few XOR operations.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-62How do Hamming and SECDED error correcting codes work for memory, and what latency and area do they add?
The 90-second answer
Memory ECC stores redundant check bits alongside data on write and recomputes them on read. A mismatch tells the controller that a bit flipped, and for a single-bit flip, which one. Hamming codes correct single errors. SECDED extends Hamming with an overall parity bit, so it corrects single errors and detects double errors. That extra detection is why SECDED is the default for SRAM and DRAM in SoCs. Plain parity or a short Hamming code appears in cheap microcontrollers where a double error can be ignored or handled by reset.
In a Hamming code, parity bits sit at positions 1, 2, 4, 8 and so on. Each parity bit covers the positions whose index has that bit set. On read, the syndrome is the binary number formed by the failing parity checks. The syndrome value is the index of the bad bit, so correction is a lookup and an XOR flip.
SECDED adds one overall parity bit over the data plus Hamming bits. The syndrome alone cannot tell a single error from a double error. The overall parity resolves it. Single error: syndrome nonzero, overall parity fails. Double error: syndrome nonzero, overall parity passes. No error: both pass. A triple error can alias to a single error pattern, which is a known limit of distance-4 codes and one reason scrubbing and interleaving matter.
Worked trace, Hamming(7,4)
Data bits 1, 1, 0, 1 go into positions 3, 5, 6, 7. Positions 1, 2, 4 hold p1, p2, p4, using even parity.
p1 covers positions 1, 3, 5, 7: 1 XOR 1 XOR 1 = 1, so p1 = 1. p2 covers positions 2, 3, 6, 7: 1 XOR 0 XOR 1 = 0, so p2 = 0. p4 covers positions 4, 5, 6, 7: 1 XOR 0 XOR 1 = 0, so p4 = 0.
The stored word, positions 1 to 7, is 1 0 1 0 1 0 1.
| Stored word | Data bits | Syndrome on read | Interpretation |
|---|---|---|---|
| 1 0 1 0 1 0 1 | 1 1 0 1 | 000 | No error |
| 1 0 1 0 1 1 1 | 1 1 0 1 | 110 (6) | Position 6 flipped, flip it back |
| 1 0 1 0 1 1 0 | 1 1 0 0 | 001 (1) | Positions 6 and 7 flipped. Hamming miscorrects position 1. SECDED overall parity would flag this as a double error instead |
The third row is the point. Hamming(7,4) has minimum distance 3, so it cannot distinguish a double error from a single error at another position. SECDED raises the distance to 4.
Check-bit count
The Hamming bound is 2^r >= n + r + 1, where n is data bits and r is Hamming parity bits. SECDED adds one overall bit.
| Data width | Hamming bits | SECDED total width | Storage overhead |
|---|---|---|---|
| 32 bits | 6 | 39 bits | 21.9% |
| 64 bits | 7 | 72 bits | 12.5% |
That overhead is why ECC cost falls as word width grows. A 32-bit SRAM macro pays roughly a fifth more bit cells, plus the encoder and decoder. A 64-bit macro pays an eighth. The logic itself is small next to the array, typically a few hundred gates per port for encode and decode, but it sits in the read path.
// SECDED decode, simplified. cw = {overall, hamming[5:0], data[31:0]}
function automatic logic [5:0] syndrome(input logic [38:0] cw);
// XOR of positions where each parity bit is set; returns 0 if clean
syndrome = 6'b0;
for (int i = 1; i <= 38; i++)
if (cw[i]) syndrome ^= i[5:0];
return syndrome;
endfunction
// On read: if syndrome != 0 and overall parity fails, flip bit[syndrome].
// If syndrome != 0 and overall parity passes, raise uncorrectable error.Latency and where it bites
Encode on write is combinational XOR trees, usually hidden under the write cycle. Decode on read is the problem. The decoder must finish before data reaches the bus or core. In a 1 GHz design with a 1 ns cycle, a decoder adding 0.3 to 0.5 ns of logic delay (typical for a 64-bit SECDED decoder in a modern CMOS node, labelled here as a design example rather than a foundry number) can consume half the budget left after the SRAM access time. Options are to pipeline the read, accept a lower frequency, or move decode off the critical path by returning data early and replaying on error, which complicates the protocol.
Area also includes the error reporting path. A correctable error counter, an uncorrectable error interrupt, and a scrub engine that reads and rewrites lines periodically so a latent single error does not accumulate into a double. Without scrubbing, two independent single upsets in the same word defeat SECDED. Interleaving bits from one logical word across physical columns helps when a particle strike flips adjacent cells.
Failure modes to name in the interview
A double error must never be silently corrected. The controller should poison the data, raise a machine check or bus error, and log the address. A stuck check bit looks like a permanent data error, so MBIST needs ECC-aware patterns that distinguish the two. And ECC does not protect the address path or the data bus between SRAM and consumer. A flipped address bit fetches the wrong line with perfectly valid ECC, which is why end-to-end protection or bus parity is a separate decision.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-63Walk me through low-power verification for a power-gated SoC domain, covering CPF/UPF, isolation, retention, and power-aware simulation, and how you catch a bug that functional simulation misses?
The 90-second answer
Low-power verification checks behaviour when a supply collapses, not only when a clock stops. I start from the power intent file, IEEE 1801 UPF, which declares supply sets, power switches, isolation cells, retention flops and level shifters. The simulator and the low-power checker both consume that file. Functional simulation without it treats a powered-down domain as alive, so it misses X propagation on wakeup, lost state, and illegal drive from a dead domain into an always-on domain.
Assume a microcontroller SoC with an always-on bus fabric and a power-gated peripheral domain, PD_PERIPH, on VDD_PERIPH. The intent file is the contract for synthesis, place and route, and verification. If RTL, UPF and netlist disagree, verification is checking the wrong chip.
Power intent in practice
create_supply_set -name SS_AON -domain PD_AON \
-power_expr {VDD_AON} -ground_expr {VSS}
create_supply_set -name SS_PERIPH -domain PD_PERIPH \
-power_expr {VDD_PERIPH} -ground_expr {VSS}
create_power_switch PS_PERIPH -domain PD_PERIPH \
-input_supply_set {SS_AON} -output_supply_set {SS_PERIPH} \
-control_port {pwr_en} -on_state {pwr_en} \
-off_state {!pwr_en} -output_supply_expr {VDD_PERIPH}
set_isolation iso_periph -domain PD_PERIPH \
-isolation_signal {iso_en} -isolation_supply_set {SS_AON} \
-isolation_sense high -clamp_value 0
add_isolation_cell -domain PD_PERIPH -isolation_signal {iso_en} \
-elements {u_periph/u_dma}
set_retention ret_dma -domain PD_PERIPH \
-retention_signal {ret_en} -retention_sense high \
-save_signal {save_en} -save_sense high \
-restore_signal {restore_en} -restore_sense high \
-retention_supply_set {SS_AON}
add_retention_cell -domain PD_PERIPH -elements {u_periph/u_dma/state_q}Isolation clamps outputs of PD_PERIPH to 0 when the domain is off, so the always-on fabric does not sample X. Retention flops keep selected state across the collapse. Level shifters handle crossings where the on voltage differs from the always-on voltage. Every crossing needs one of those three, and the checker flags a crossing with none.
Retention is not free. Hypothetical figures for a 28 nm design at 0.9 V, 25 C: a normal flop leaks about 0.5 nA, a retention flop about 0.8 nA, and an isolation cell adds about 0.2 nA plus roughly 15 ps delay. Retaining 2,000 flops therefore costs about 0.6 uA extra leakage in the always-on supply, which matters when the sleep budget is 5 uA total. That is why only the DMA descriptor state is retained in this example, not the whole peripheral.
Power-aware simulation
In power-aware mode the simulator reads the UPF, models power switches, and propagates X when a flop loses supply without retention or when an unisolated input drives a live domain. In power-unaware mode the same testbench passes and the bug ships. I run both. Power-unaware runs are faster and useful for early functional debug. Power-aware runs are the signoff check for wakeup and shutdown sequences. On a 2M gate block, expect power-aware simulation to run 3 to 5 times slower than power-unaware, and gate-level power-aware simulation another order of magnitude slower again.
A shutdown and wakeup trace I check, with hypothetical timing for a 100 MHz peripheral clock:
| Step | Action | Check |
|---|---|---|
| 1 | Firmware quiesces DMA, deasserts requests | No outstanding AXI transaction into PD_PERIPH |
| 2 | iso_en asserted, then save_en pulse | Outputs clamped to 0, retention flops capture state |
| 3 | pwr_en deasserted, VDD_PERIPH collapses | Simulator marks domain off, internal nodes go X |
| 4 | pwr_en asserted, supply ramps in about 20 us | No flop samples until supply valid and reset released |
| 5 | restore_en pulse, iso_en deasserted | Retained state restored in 2 cycles, outputs released in order |
The subtle failure is ordering. If isolation is released before the supply is stable, the always-on domain samples X and may latch a spurious interrupt. If save_en fires after the power switch opens, retention flops save X. If an asynchronous reset crosses from the always-on domain into PD_PERIPH without isolation, the reset can glitch the dead domain and corrupt retained state on restore. None of those appear in a power-unaware run because the supply never collapses.
What else catches it
Simulation alone is weak here because it only covers sequences the testbench drives. I add three checks. First, low-power lint and structural checks on the netlist: every PD_PERIPH output has isolation, every input has a level shifter or isolation as needed, retention flops match the UPF list, and no always-on flop is powered by a switched supply. Second, formal or assertion checks for protocol rules: no transaction issued while pwr_en is low, iso_en asserted before pwr_en falls, restore_en completes before any clock enable in the domain. Third, gate-level power-aware simulation after place and route, because synthesis can move a flop across a domain boundary or drop a retention cell during optimisation.
assert property (@(posedge aon_clk) disable iff (!aon_rst_n)
!pwr_en |-> iso_en)
else $error("Isolation must be asserted before PD_PERIPH power falls");
assert property (@(posedge aon_clk) disable iff (!aon_rst_n)
$rose(restore_done) |-> ##1 (periph_clk_en == 1'b1));The trade-off is coverage against runtime. Power-aware simulation with X propagation is slower and noisier, and it needs a clean UPF or it floods the log with false X sources. I keep the UPF under version control with the RTL, review it like RTL, and treat any mismatch between UPF and the synthesised netlist as a blocking bug. That discipline is what makes the verification result mean anything at tapeout.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-64How do CPF and UPF express power intent differently, and how do you use power domains, isolation cells and retention cells when a 1.0 V always-on domain drives a power-gated 0.8 V block?
The 90-second answer
CPF and UPF both describe power intent outside RTL: which logic shares a supply, which domains can be switched off, and what must happen at a boundary when a domain is off. IEEE 1801 standardises UPF as the main Tcl based language and includes CPF as an alternative syntax annex, so the concepts map one to one. A team picks one format for a flow and does not mix them, because synthesis, place and route and low power verification each parse the file they were configured for.
A power domain is a set of elements powered by one supply net that can be powered, retained or gated as a unit. In a microcontroller SoC, an always on domain at 1.0 V holds the power controller, wakeup logic and bus fabric. A core domain at 0.8 V holds the CPU and caches and can be power gated. The always on domain must stay alive to sequence power up, so its flops and buffers use always on cells that tolerate the gated domain being absent.
Isolation cells sit on outputs leaving a gated domain. When the 0.8 V domain is off, its outputs would float or sit at an unknown level and could drive 1.0 V logic into crowbar current or propagate X values. An isolation cell clamps that output to a defined value, 0, 1 or high impedance, while the isolation enable is asserted. The enable must be asserted before the supply collapses and released only after the supply is stable. Isolation does not replace a level shifter. When both domains are on, a 0.8 V output driving 1.0 V logic still needs a level shifter to meet input voltage and noise margin requirements.
Retention cells are flops that keep state while the main supply is off. A retention flop has a shadow storage element powered from an always on retention supply that saves Q on power down and restores it on power up. You pay for every retained flop, so you retain only architectural state software expects to survive, such as core registers and configuration, and let caches and pipeline flops reset.
# UPF (IEEE 1801), Tcl syntax
create_supply_net VDD_AON
create_supply_net VDD_CORE
create_supply_net VSS
create_power_domain PD_AON -elements {u_pwr_ctrl u_wakeup} \
-supply_net {VDD VDD_AON} -ground_net {VSS VSS}
create_power_domain PD_CORE -elements {u_cpu u_l1} \
-supply_net {VDD VDD_CORE} -ground_net {VSS VSS}
set_isolation -domain PD_CORE -isolation_signal iso_en \
-isolation_sense high -clamp_value 0 -location boundary
set_retention -domain PD_CORE -retention_signal ret_en \
-save_signal save_en -restore_signal restore_en \
-retention_sense high -location boundary
set_level_shifter -domain PD_CORE -applies_to outputs -location boundary# CPF, library based syntax, cell names come from the stdcell library
create_power_domain PD_CORE
-elements {u_cpu u_l1}
-supply_net {VDD VDD_CORE}
-ground_net {VSS VSS}
-isolation_cell ISO_BUF_X1
-retention_cell DFF_RET_X1
-level_shifter_cell LSH_BUF_X1
set_isolation PD_CORE -isolation_signal iso_en \
-isolation_sense high -clamp_value 0
set_retention PD_CORE -retention_signal ret_en \
-save_signal save_en -restore_signal restore_en \
-retention_sense highCell names such as ISO_BUF_X1, DFF_RET_X1 and LSH_BUF_X1 are illustrative. The actual names, clamp options and timing arcs are defined by the foundry standard cell library for the node, and the power intent file must reference that library.
| Item | UPF | CPF |
|---|---|---|
| Syntax | Tcl commands | Library based commands |
| Domain | create_power_domain with supply nets | create_power_domain with supply nets and cell types |
| Isolation | set_isolation with clamp value and sense | set_isolation plus -isolation_cell in the domain |
| Retention | set_retention with save and restore signals | set_retention plus -retention_cell in the domain |
| Level shift | set_level_shifter | -level_shifter_cell in the domain |
Costs are concrete in a typical 28 nm library, figures here are a labelled hypothetical example for sizing the trade off. A retention DFF is roughly 1.4 to 1.6 times the area of a normal DFF and adds about 20 to 40 ps of clock to Q delay, plus a small leakage load on the always on retention supply. An isolation buffer is roughly 2 to 3 times the area of a plain buffer and adds about 30 to 60 ps. If the core domain is 2 mm2 and leaks, say, 8 mW at 0.8 V in the on state, power gating it for 99 percent of the time cuts that leakage contribution to roughly 0.08 mW average plus the retention supply leakage for the retained flops, which might be 0.2 mW. Retaining 5,000 flops instead of 50,000 is therefore a direct leakage decision, not just an area one.
| Step | Signal | Condition before next step |
|---|---|---|
| 1 | iso_en asserted | Outputs clamped to 0, no X propagation |
| 2 | save_en asserted | Retention flops have captured Q |
| 3 | ret_en deasserted, VDD_CORE gated | Core supply below 0.1 V |
| 4 | VDD_CORE restored to 0.8 V | Supply stable for at least the specified settling time |
| 5 | restore_en asserted | Q restored into the flops |
| 6 | iso_en deasserted | Normal outputs resume |
The failure modes are concrete. If isolation is released before the 0.8 V supply reaches its target, the always on logic sees a slow or unknown input and can draw shoot through current. If save is asserted after the supply starts to collapse, retained flops lose state and the core wakes with corrupt registers. If a signal crosses from the gated domain without isolation, simulation shows X propagation into the always on domain and silicon can show a failure that only appears in sleep and wakeup testing. Low power verification with the power intent file, plus a simulation of the sequence above, catches all three before tapeout.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-65How would you design reset domains for a chip with a core clock and an asynchronous peripheral clock, and which crossing structure would you use for a control signal versus a data stream?
The 90-second answer
I would give each clock its own reset domain. A clock domain is the flops timed against one clock in STA. A reset domain is the flops released by one synchronised reset. With a core clock and an asynchronous peripheral clock, I use two reset synchronisers, one per clock, fed from the same asynchronous reset input. No flop is reset by a signal synchronised to the other clock.
Assert stays asynchronous. If the peripheral clock is gated or stopped, its flops still clear. Deassert goes through two flops clocked by the destination clock. The first flop may sample reset release close to a clock edge and go metastable. The second flop gives it a full destination cycle to settle before logic sees the release. That is why the synchroniser must sit after the clock gate. A synchroniser clocked by a gated clock that is off at release never leaves reset.
// IEEE 1800-2017 semantics, synthesizable with a standard cell library.
module reset_sync (
input logic clk,
input logic async_rst_n,
output logic sync_rst_n
);
logic [1:0] sync;
always_ff @(posedge clk or negedge async_rst_n) begin
if (!async_rst_n) sync <= 2'b00;
else sync <= {sync[0], 1'b1};
end
assign sync_rst_n = sync[1];
endmoduleFor crossings, the signal type decides the structure. A single level, such as an interrupt request held until acknowledged, uses two flops in the destination domain. A stream of words uses an asynchronous FIFO with Gray-coded pointers. A short pulse or a config value that must be captured atomically uses a handshake, where the source holds the value until the destination acknowledges it.
| Signal | Structure | Why it fits | Main limit |
|---|---|---|---|
| Interrupt level, held until cleared | Two-flop synchroniser | One bit, level sensitive, latency of two destination cycles is fine | Misses a pulse shorter than the destination period |
| 32-bit data stream, core to peripheral | Asynchronous FIFO | Handles rate mismatch and multiple bits without per-bit synchronisers | Costs memory and Gray pointer logic, depth must cover bursts |
| Config register update | Handshake with acknowledge | Destination captures a stable multi-bit value on a known edge | Slower, needs source to wait for acknowledge |
Applied to the two domains
In SDC I declare the clocks asynchronous to each other with set_clock_groups -asynchronous. STA then reports no core-to-peripheral timing path. If one appears, it means a combinational crossing slipped in, and I fix the RTL rather than buffer the path.
The peripheral reset also gates the FIFO write enable. While rst_peri_n is low, the core cannot push data into a FIFO whose read side is held in reset. The same gating applies to the interrupt level. The core masks that interrupt until its own reset synchroniser has released, so a stale level from the peripheral does not fire during startup.
The failure I check first in simulation is reset release with the peripheral clock gated. I release reset while the gate is closed, then open the gate and confirm the peripheral leaves reset within two peripheral cycles. I also release reset near each clock edge in turn. That sweep catches recovery violations on the synchroniser flops that a single nominal release misses.
A two-flop synchroniser on a pulse is the other trap in this design. A 10 ns pulse from a 200 MHz core into a 10 MHz peripheral domain has a high chance of falling between peripheral edges and being missed entirely. If the peripheral must see every pulse, I convert it to a toggle that the destination samples, or I use the handshake. The choice depends on whether the pulse carries information per event or is just a level that stays asserted until serviced.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-66How does slowing an aggressor's slew rate reduce crosstalk on a nearby victim net?
The 90-second answer
Crosstalk is a glitch induced on a quiet victim net by a switching aggressor net. Most of it on a chip or board is capacitive. The aggressor's electric field couples through the mutual capacitance between the two conductors, and the changing voltage pushes current into the victim. Slowing the aggressor edge reduces that current directly, because the injected current is proportional to how fast the voltage changes.
I_injected = C_m * dV_aggressor / dt
C_m is the mutual capacitance set by spacing and geometry. dV/dt is the slew rate. If you halve the slew rate, you halve the injected current for the same spacing. That is the whole rule, and it is why slew-rate control is the first knob I reach for when a victim glitch is too large and the layout cannot move.
Worked numbers
Take a labelled hypothetical. Two parallel traces have C_m = 0.1 pF. The aggressor swings 1.8 V. The victim is terminated in 50 ohms, so the glitch voltage is roughly the injected current times that resistance while the edge is in progress.
| Edge time | dV/dt | I_injected | Approx. glitch into 50 ohms |
|---|---|---|---|
| 100 ps | 18 V/ns | 1.8 mA | 90 mV |
| 500 ps | 3.6 V/ns | 0.36 mA | 18 mV |
| 1 ns | 1.8 V/ns | 0.18 mA | 9 mV |
Going from a 100 ps edge to a 1 ns edge cuts the glitch by a factor of ten. No spacing change, no extra shield track. The arithmetic is linear because C_m and the swing stay fixed.
What it costs
A slower edge is not free. It consumes setup margin because the receiver takes longer to cross its threshold. It also spends more time with both receiver transistors partly on, which raises short-circuit power in that gate. So I do not slow every output. I slow the ones that run long and close to a sensitive net, such as a clock, a single-ended bus, or a digital output routed beside an analog input.
In practice I implement it with a programmable slew-rate IO cell, a weaker driver strength, or a small series resistor at the driver. A series resistor also helps with reflections, but I check it against the receiver threshold window so the edge still settles in time. Then I probe the victim while toggling the aggressor in the worst pattern, all aggressors switching the same way at once, and confirm the glitch stays below the noise margin. If it does not, the next step is spacing or a grounded shield, because those reduce C_m itself rather than only the rate at which it is excited.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-67How do differential signaling, common-mode rejection, and termination interact on a high-speed serial link, and when would you choose differential over single-ended despite its cost?
The 90-second answer
Differential signaling sends the same information on two conductors as opposite voltages, $V_P$ and $V_N$. The receiver decides on $V_{diff}=V_P-V_N$, not on either voltage against ground. Noise that couples equally into both traces appears in the common mode, $V_{cm}=(V_P+V_N)/2$, and is subtracted out. Termination then stops that signal from reflecting and reappearing as jitter or a second edge. I would choose it for a board-to-board or cable link above a few hundred Mbps, or any link that must survive ground shift and EMI, and I would avoid it for a short on-chip net where the extra pin, pair routing and receiver cost buy nothing.
Why rejection works, and where it stops
A single-ended receiver compares one trace to its local ground. A 200 mV ground bounce or a nearby aggressor lands directly in the decision. A differential receiver amplifies only the difference. If the pair is tightly coupled, the same aggressor induces nearly the same voltage on $V_P$ and $V_N$, so it cancels in $V_{diff}$.
Common-mode rejection ratio quantifies the residue. With a hypothetical 40 dB CMRR, a 200 mV common-mode step becomes $200\text{ mV}/10^{40/20}=2\text{ mV}$ of equivalent differential error. Against a 400 mV differential swing, that leaves margin. The catch is that CMRR is not infinite and it falls with frequency, because the two input transistors, bond wires and package paths are never perfectly matched.
Three limits bite in practice:
- Common-mode range. The receiver input stage still has to stay in its linear range. A large $V_{cm}$ shift, for example from a ground offset between two boards, can saturate the input pair even though $V_{diff}$ is correct.
- Skew and asymmetry. If $V_P$ and $V_N$ arrive at different times, or one trace has extra vias, the pair radiates and converts differential energy into common mode. That is mode conversion, and no amount of receiver CMRR recovers a signal already degraded on the trace.
- Imbalance at discontinuities. A connector, a test via or a stub that touches only one leg reflects one leg more than the other.
Termination: the arithmetic
Terminate the receiver end with the pair's differential characteristic impedance, $Z_{diff}$. For many board-level standards that is 100 $\Omega$ differential, for USB it is 90 $\Omega$ differential, and the exact value comes from the standard, not from habit. Terminate at the receiver only for a point-to-point link. Terminating both ends halves the voltage the receiver sees and wastes power, and it is only correct for a multidrop bus where the far end is not a single receiver.
The reflection coefficient at a load is $\Gamma=(Z_L-Z_0)/(Z_L+Z_0)$. Worked example on a 100 $\Omega$ pair:
| Receiver termination | $\Gamma$ | What the receiver sees |
|---|---|---|
| 100 $\Omega$ (matched) | 0 | One clean edge, no re-reflection |
| 50 $\Omega$ (too low) | -0.33 | Edge undershoots, reflected wave returns inverted |
| Open (missing) | +1 | Edge doubles at the load, then bounces back to the source |
| 200 $\Omega$ (too high) | +0.33 | Overshoot and a delayed echo |
An unterminated open is the classic failure. The first edge looks fine on a slow scope, then the reflection returns after the round-trip delay, $2L/v_p$, and lands inside the next bit period as jitter or a false crossing. At 5 Gbps the unit interval is 200 ps, so even a 15 mm stub on FR-4, where $v_p\approx 150\text{ mm/ns}$, has a round trip near 200 ps. That stub is a full bit of interference.
When differential wins, and when it does not
| Situation | Choice | Reason |
|---|---|---|
| --- | --- | --- |
| Cable or backplane, >100 Mbps | Differential | Noise, ground offset and EMI dominate; single-ended ground reference is unreliable |
| On-chip, short, low speed | Single-ended | No cable, controlled ground, saves pins and receiver power |
| Low voltage swing at high speed | Differential | Small $V_{diff}$ gives low EMI and low power, but only works because the receiver rejects the common mode |
| Multidrop bus | Depends on standard | Termination topology differs; do not copy point-to-point rules |
On chip, I would still use differential for a PLL clock or a sensitive ADC reference input, not for speed but because the pair rejects substrate noise that couples into both legs. The cost there is area for the receiver and careful symmetric layout, which is worth it when the victim is analog.
How I would debug a failing pair
Measure $V_{diff}$ and $V_{cm}$ separately with a differential probe, not one probe on $V_P$ against ground. If $V_{diff}$ is clean but the link fails, check $V_{cm}$ against the receiver's specified input range across process, voltage and temperature. If $V_{diff}$ shows a step one bit later, suspect a reflection and check the termination value and any stub length against the bit period. If emissions fail while the eye passes, check pair symmetry and skew, because the link can work and still radiate as common mode.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-68A 10 Gb/s link sees 20 dB of loss at Nyquist and a closed eye. How do TX pre-emphasis and RX CTLE each help, and what jitter remains after equalization?
The 90-second answer
At 10 Gb/s the Nyquist frequency is 5 GHz. If the PCB and connector lose 20 dB at 5 GHz, the high frequency content of the signal arrives at 10% of its transmitted amplitude. Low frequencies pass with much less loss, so edges slow down and each bit bleeds into the next one. That is intersymbol interference, and it closes the eye at the receiver sampler.
Transmitter pre-emphasis and receiver CTLE both boost high frequencies, but they do it on opposite sides of the loss. Pre-emphasis adds overshoot before the channel, so the channel removes part of it and leaves a faster edge. A CTLE boosts high frequencies after the channel, so it restores the edge that was lost. I would normally use both, with the CTLE doing most of the work and pre-emphasis kept modest, because each one has a cost that grows quickly.
Pre-emphasis: boost before the loss
A simple transmitter FIR has a main tap and a smaller negative tap on the previous bit. When the data changes, the driver briefly drives harder in the direction of the new bit, then settles to the normal level. The channel low-pass filters that overshoot, so the received edge rises faster than it would without pre-emphasis.
# 2-tap TX FIR, checked against Python 3.11
# taps = [1.0, -0.25]: main tap plus 25% of previous bit subtracted
def fir(bits, taps):
out = []
for i in range(len(bits)):
acc = taps[0] * bits[i]
if i > 0:
acc += taps[1] * bits[i - 1]
out.append(acc)
return out
bits = [1, 1, -1, -1, 1]
print([round(x, 3) for x in fir(bits, [1.0, -0.25])])
# [1.0, 0.75, -1.25, -0.75, 1.25]The isolated transition from 1 to -1 produces -1.25 instead of -1.0, a 25% overshoot. The cost is peak voltage. The driver must stay within its supply and remain linear, so pushing pre-emphasis too far clips the overshoot and can make the eye worse. It also raises power in the driver.
CTLE: boost after the loss
A continuous-time linear equalizer is an analog shelving filter in the receiver front end. It passes low frequencies at roughly unity gain and boosts high frequencies by a set amount, for example 8 dB. That directly counters a channel that loses 20 dB at Nyquist, although in practice the CTLE alone rarely needs to supply all 20 dB.
The cost is noise. The CTLE amplifies high frequency noise and crosstalk by the same amount it amplifies the signal. If I set the boost too high, the eye looks taller on a scope but the bit error rate stops improving because the sampler is now deciding on amplified noise. That is the main trade-off between the two approaches: pre-emphasis spends transmitter voltage headroom, CTLE spends receiver noise margin.
| Approach | Where it acts | What it costs | When I lean on it |
|---|---|---|---|
| TX pre-emphasis | Before the channel | Peak voltage and driver linearity | Channel loss is moderate and the driver has headroom |
| RX CTLE | After the channel | Noise and crosstalk amplification | Channel loss is large and receiver noise is low |
Jitter left after equalization
Equalization removes most of the deterministic jitter caused by ISI, but it does not remove random jitter from thermal noise at the sampler. A simple budget makes the remaining margin concrete. At 10 Gb/s, 1 UI is 100 ps. Suppose, as a labelled hypothetical example, equalization leaves 12 ps of deterministic jitter and the sampler sees 1.5 ps rms of random jitter. At BER 1e-12 the random tail is roughly 7 times the rms value, so total jitter is about 12 + 7 x 1.5 = 22.5 ps. The eye opening is then 100 - 22.5 = 77.5 ps, before subtracting sampler aperture. If the sampler needs 10 ps, about 67 ps remains for CDR tracking error and voltage noise. That remaining time is the margin I would quote, and it tells me whether more CTLE boost is worth trying or whether it is just amplifying noise.
On silicon I would keep both the FIR taps and the CTLE boost programmable. The channel in a customer system rarely matches the evaluation board, and the right split between pre-emphasis and CTLE is found by sweeping both and watching BER, not by fixing one setting from simulation alone.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-69A differential pair shows a 2 mV offset that varies across the die. How would common-centroid placement and a guard ring reduce that offset and substrate noise, and what area trade-off do you accept?
The 90-second answer
A 2 mV offset that changes with position on the die points to a systematic gradient, not only random mismatch. Threshold voltage, mobility, and temperature vary across the wafer and across a large block. If the two input transistors sit side by side, each samples a different point on that gradient, so the pair sees a systematic offset. Common-centroid placement interleaves the fingers so both transistors average the same position. A guard ring around the pair, or around the whole analog block, gives substrate noise a low impedance path to ground before it reaches the sensitive junctions. The cost is area and extra routing, and neither technique removes random mismatch.
Why side-by-side placement creates offset
Pelgrom's law describes the random part:
sigma(VT) = A_VT / sqrt(W * L)
With a hypothetical A_VT = 5 mV·um for a 180 nm process and WL = 10 um², sigma(VT) is about 1.58 mV. That random term is present even in a perfect layout. The gradient term is separate. Suppose VT changes by 0.02 mV/um across the block and the two devices are 20 um apart. The systematic difference is 0.4 mV. Move the pair farther from its reference, or make the block larger, and that term grows. A layout that averages the gradient removes the systematic part, leaving only the random part to be handled by sizing.
Common centroid in practice
Split each transistor into equal fingers and arrange them as A B B A, where A is one side of the pair and B is the other. With a 10 um pitch, A occupies positions 0 and 30 um, B occupies 10 and 20 um. Both average to 15 um, so a linear gradient cancels. A 2-D A B / B A pattern does the same for gradients in both directions.
| Layout | A centroid | B centroid | Gradient offset at 0.02 mV/um |
|---|---|---|---|
A A B B | 5 um | 25 um | 0.4 mV |
A B B A | 15 um | 15 um | 0 mV |
The cancellation only holds if the fingers match in width, length, orientation, and surroundings. Add dummy fingers at both ends of the array so the outer fingers see the same etch and stress environment as the inner ones. Route the two drains and gates symmetrically, with the same metal length and via count. If the routing is asymmetric, parasitic mismatch can exceed the gradient you just removed.
Guard rings for substrate noise
Digital switching injects current into the substrate. Some of that current reaches the junctions of nearby analog devices and modulates their threshold voltage. A guard ring is a continuous ring of substrate or well contacts tied to a quiet ground. In a p-substrate process, a p+ ring tied to ground around an n-well block collects stray electrons. A second ring of the opposite type can be added where latchup risk is high.
Place the ring close to the sensitive block, tie it with many contacts to a low impedance analog ground, and keep it continuous. A gap in the ring is a leak path. Follow the foundry rules for ring width, contact spacing, and spacing to active devices. Those rules also set the latchup trigger current the ring must handle.
Trade-off and limits
Common centroid and guard rings cost area, add parasitic capacitance, and complicate routing. They do not reduce random mismatch. If Monte Carlo after extraction still shows offset above spec, increase device area, since sigma falls as 1/sqrt(area), or use chopping or auto-zeroing in the circuit. Guard rings also do not block noise that arrives through the supply or reference pins. That path needs decoupling and separate supply routing. Use the layout techniques for the systematic and substrate parts, and use area or circuit techniques for the random part.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-70What does a guard ring around a sensitive analog block do to reduce substrate noise coupling, and what is it tied to?
The 90-second answer
A guard ring is a ring of substrate contacts placed around the analog block. It gives substrate current a low impedance path to a quiet ground before that current reaches the analog transistors. Tie it to the analog ground, not the noisy digital ground, or it injects the noise it was meant to collect.
Why the analog block needs it
In a p-substrate process, digital NMOS junctions couple switching current into the shared substrate. That current spreads through the substrate and reaches the bulk connections under the analog block. The local substrate potential then moves, and body effect turns that movement into a shift in threshold voltage. A comparator threshold moves, a PLL picks up jitter, and an ADC loses effective bits when the digital block is busy.
The guard ring does not stop the digital block from injecting current. It intercepts the lateral part of that current. Substrate contacts in the ring present many parallel paths to ground, so current that would have flowed under the analog devices flows into the ring instead. Effectiveness depends on contact density, ring width, and how quiet the ground it ties to really is at the frequency of interest.
What decides whether it works
| Choice | Effect |
|---|---|
| --- | --- |
| Ring tied to analog ground | Collected current leaves on a quiet reference |
| Ring tied to digital ground | Ring becomes a noise source coupled into the block |
| Single narrow ring | Helps at low frequency, less effective for fast edges |
| Double ring or wide ring with dense contacts | Lower impedance collection path, better high frequency coverage |
| Ring plus deep n-well around the analog p-well | Blocks the direct p-well path as well as collecting lateral current |
A simple estimate shows why contact density matters. Suppose a switching edge injects 5 mA into the substrate near the analog block. If the ring path to ground presents 20 ohms, the ring sits about 100 mV above ground during that edge, and some of that voltage still couples inward. If denser contacts and a wider ring bring the path to 2 ohms, the same current produces about 10 mV. Those figures are illustrative, but the ratio is the point. The ring is an impedance divider, not a wall.
On silicon I would check it by toggling a known digital pattern while the analog block runs a fixed test. An ADC converting a fixed input should produce the same code histogram with the pattern off and on. If the histogram shifts or spreads only when the pattern runs, substrate or supply coupling is still reaching the block, and the first things to inspect are the ring tie point, the analog supply decoupling, and the distance between the noisy macro and the analog region.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-71Walk me through thermal design for a 10 mm by 10 mm SoC dissipating 6 W, covering power density, hotspots, and thermal vias?
The 90-second answer
I start from the junction temperature limit and work backwards to the ambient. For a 10 mm by 10 mm SoC at 6 W, I assume a 85 C ambient, a 125 C maximum junction, and a package with a heatsink. That gives a total thermal budget of (125 - 85) / 6 = 6.7 C/W from junction to ambient. I then split that budget across die, package, interface material, and heatsink, and check the worst hotspot separately, because the average will pass while one block overheats.
Average power density here is only 6 W / 100 mm2 = 0.06 W/mm2, which looks harmless. The problem is distribution. If the CPU cluster dissipates 3 W in 3 mm by 3 mm, its local density is 0.33 W/mm2, more than five times the average. Heat spreads laterally in silicon poorly, so that block sets the peak temperature and the leakage current, not the chip average.
Power density and hotspots
I build a power map from activity data, not from a single TDP number. Each block gets a worst case power at the target voltage and frequency, plus a realistic sustained power. The gap matters for transient hotspots. A 3 W burst for 10 ms raises a small block far less than the same power held for 10 s, because the die and package have thermal capacitance.
Leakage makes this a feedback loop. At 125 C, subthreshold leakage in a modern FinFET process can be several times its 25 C value. If leakage is 1 W at 25 C and triples at high temperature, total power rises, temperature rises further, and the design can enter thermal runaway unless DVFS or a thermal sensor caps voltage and frequency. I check that loop at the hot corner, not at nominal.
For hotspots I use three levers. First, floorplan: keep high power blocks away from each other and away from the die edge if the edge is the main heat exit, and place a hotspot near a thermal via cluster or a thick copper pour. Second, spread the power: split a wide datapath, duplicate a hotspot block, or move SRAM banks apart. Third, cap it in operation: a per block thermal sensor that throttles clock or voltage before the global limit is reached.
Thermal vias
A thermal via is a metal filled hole that carries heat vertically from the die or a local copper spreader to a lower copper plane, the substrate, or a heat spreader. In a flip chip package they sit under the die. In a wirebond package they connect a die attach pad or backside metal to the substrate ground plane.
The resistance of one via is roughly L / (k A), where L is length, k is thermal conductivity, and A is cross section. Copper has k near 385 W/mK, silicon dioxide near 1.4 W/mK, so a copper via is about 275 times more conductive per unit area than oxide. That is why a modest array dominates the vertical path.
Worked example, labelled as hypothetical: a 200 um deep via, 50 um diameter, copper filled. Area = pi * (25e-6)^2 = 1.96e-9 m2. Resistance = 200e-6 / (385 * 1.96e-9) = 265 K/W for one via. That sounds high, and it is. Put 100 in parallel and the array is 2.65 K/W. At 3 W from the hotspot, that array alone drops about 8 C. Put 400 in parallel and it drops to 0.66 K/W, about 2 C at 3 W. The lesson is that via count, diameter, and voiding control the result, and a single via does almost nothing.
# Python 3, checked arithmetic for the example above
import math
L = 200e-6 # m
k_cu = 385 # W/mK
d = 50e-6 # m
A = math.pi * (d/2)**2
R_one = L / (k_cu * A)
for n in (1, 100, 400):
print(n, round(R_one/n, 2), "K/W")| Path element | Typical share of 6.7 C/W budget | What I check |
|---|---|---|
| Die to package | 1.0 to 2.0 C/W | Via array under hotspot, voiding by X-ray |
| Package to board or heatsink | 2.0 to 3.0 C/W | TIM thickness, heatsink contact pressure |
| Board to ambient | 2.0 to 3.0 C/W | Copper area, airflow, neighbouring parts |
Failure modes I design against
Voided vias. Electroplated copper vias can contain voids that cut cross section and raise resistance two to three times. I specify fill requirements and verify with cross section or X-ray on first silicon, because electrical test will not catch it.
Thermal vias that carry current. If the same vias are used as power or ground vias, they must also pass electromigration and IR drop rules. A via that is fine thermally can fail electrically at high current density. I keep thermal and power via counts separate in the signoff checklist.
Hotspot induced timing drift. A block 20 C hotter than its neighbour leaks more and its transistors slow down. If STA assumed uniform temperature, that path can fail in the field. I feed the thermal map back into timing corners for the hottest blocks.
I close the loop with measurement. On silicon I read on die temperature sensors under each major block, compare them with the thermal model at known power, and update the model before the next spin. If the model is off by more than about 5 C at the hotspot, I trust the sensor data and rework the via placement or the floorplan, rather than raising the heatsink size and hoping the hotspot moves.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-72Your first silicon powers up and JTAG reads the correct IDCODE, but the ROM produces no UART output: walk me through the checks you would run in order to find the cause?
The 90-second answer
JTAG reading the correct IDCODE already rules out a dead die, a missing supply and a broken TAP. The fault is downstream of that: either a clock or reset domain the ROM needs is not running, the ROM is not executing from where I think it is, or the UART path itself is misconfigured. I check those in hardware order, power, clock, reset, boot source, UART, and I use a scope or logic analyser before I change any firmware. That order matters because a stuck reset or a dead UART clock makes a correct ROM look broken.
1. Confirm power and clocks
I measure each rail at the chip pins, not just at the supply, and I check the current with clocks gated. A rail at 0.95 V instead of 1.0 V, or a domain drawing zero current, points to a regulator, a power switch or a short on that rail. Then I verify each clock the ROM and UART need. The core clock, the bus clock and the UART clock often come from different sources, so a working core clock does not prove the UART clock toggles.
I read the clock status register over JTAG and, where a test pin exists, I measure frequency and duty cycle directly. If the PLL is the source, I read its lock bit and fall back to the internal oscillator or an external crystal to separate a PLL problem from a logic problem.
// Checks run over JTAG before any UART test
uint32_t clk = read32(CLOCK_STATUS); // one bit per domain, 1 = toggling
uint32_t rst = read32(RESET_STATUS); // one bit per domain, 1 = still asserted
uint32_t pll = read32(PLL_STATUS); // bit 0 = locked
if ((clk & CORE_CLK) == 0) fail("core clock dead");
if ((clk & UART_CLK) == 0) fail("UART clock dead, check divider and gating");
if (rst != 0) fail("reset still asserted in a domain");
if ((pll & 1) == 0) fail("PLL not locked, try internal oscillator");2. Confirm reset and boot source
Next I check that reset deasserts in every domain, in the order the design specifies, and that the external reset pin is not held low by the board. A reset synchronizer that never releases, or a power-on reset circuit that retriggers, leaves the ROM in reset while JTAG still works because the TAP has its own reset.
I then read the boot configuration fuses and strapping pins. If the ROM is configured to boot from external flash and no flash is fitted, or a boot pin selects a different image, the ROM will wait silently. Reading those bits over JTAG, and forcing the internal SRAM boot path if the design allows it, separates a boot configuration error from a UART error.
3. Test the UART path itself
With clocks, reset and boot source proven, I put a logic analyser on the TX pin. Three outcomes point to different causes:
| Observation on TX pin | Likely cause | Next check |
|---|---|---|
| No transitions at all | ROM not running, TX pin muxed elsewhere, or UART clock dead | Halt core over JTAG, read PC and pin mux register |
| Transitions at wrong baud rate | Wrong clock source or divider value | Measure bit period, compare with expected 115200 baud |
| Correct banner but garbled | Clock mismatch, wrong voltage level, or ground issue | Check baud tolerance, signal levels and common ground |
Halting the core over JTAG is the decisive step. If the program counter sits in the ROM entry point, the ROM is running and the problem is UART configuration. If it sits at a fault handler or at zero, the problem is boot source, reset or memory. If it sits in a loop waiting for a flash response, the ROM is waiting for a device that is not there.
JTAG register access versus UART console
I use JTAG first because it works before any firmware runs and can halt the core, but it is slow and gives no continuous log. Once the UART works, I switch to the UART console for running tests, because it streams output at full speed and survives a core halt. The trade-off is that the UART depends on the very clocks and pin mux I am trying to prove, so it cannot be the first debug tool on first silicon.
After the banner appears, I run a small SRAM March test, read the fuse and trim values, and only then enable peripherals one at a time. I log rail voltages, clock frequencies, register dumps and the test image version for each run, so a later failure can be traced to a specific change rather than to first silicon in general.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-73Walk me through how you would use scan debug and laser voltage probing to isolate a failing node in a digital block, and when would you choose one over the other?
The 90-second answer
I would start with scan debug because it tells me the first cycle where a bad die diverges from a good die, and that narrows the search from millions of gates to a small cone of logic. If scan shows the state is correct but the part still fails at speed, I switch to laser voltage probing because it observes a node while the clock is running. Scan answers which cycle and which flops are wrong. Laser probing answers whether a particular node toggles, and when, during that cycle.
The choice depends on what I already know. If the failure reproduces in scan capture, scan is faster and cheaper. If the failure only appears at full speed, or the block has no scan access in that mode, laser probing is the tool that can still see it.
Scan debug: find the first divergent cycle
Scan chains let me shift the internal state of flops out through a scan output pin after a capture cycle. I run the same failing pattern on a known good unit and a known bad unit, capture on the cycle where the test first reports a mismatch, and shift both states out.
| Capture cycle | Good unit | Bad unit | Result |
|---|---|---|---|
| --- | --- | --- | --- |
| 100 | State A | State A | Match |
| 101 | State B | State B | Match |
| 102 | State C | State D | First mismatch |
The flops that differ at cycle 102, plus the combinational logic feeding them, form the suspect cone. I then work backwards from those flops through the netlist. If the input to a differing flop is correct on both units but the flop output differs, I suspect the flop, its clock, or its reset. If the input already differs, I move one level back and repeat the comparison at the previous cycle.
Scan needs design for testability. Every flop that matters needs a scan chain, and the test pattern must be reproducible in scan mode. That is the main limit. A timing failure caused by a slow clock path may pass in scan capture because scan capture often runs slower than functional speed. Scan also cannot easily observe analog blocks, SRAM contents beyond what MBIST exposes, or a node that is not a flop output.
Laser voltage probing: watch a node at speed
Laser voltage probing uses a focused laser through the backside or through a decapsulated package. When the laser hits a switching transistor, the reflected light changes and the probe reports whether that node toggled. I compare the waveform on the bad unit against the waveform on a good unit for the same pattern and clock.
If a node that should toggle every cycle stays quiet on the bad unit, the fault is upstream of that node or in its driver. If the node toggles but late, I have a timing or drive strength problem rather than a logic problem. If the node toggles correctly, I move downstream toward the flop that scan flagged.
Laser probing works at functional speed, which is why it catches clock tree, IR drop, and marginal path problems that scan capture can miss. It is slow. Probing one node can take minutes, and probing hundreds of nodes across a block is impractical. It also needs optical access, a good reference waveform, and a pattern that reaches the node at a known cycle.
Choosing between them
| Scan debug | Laser voltage probing | |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Speed of operation | Capture speed, often below functional speed | Full functional speed |
| Coverage | All scanned flops in the block | One node at a time |
| What it finds | First wrong cycle and wrong flops | Whether a node toggles, and its timing |
| Main cost | Needs scan chains and a reproducible pattern | Slow, needs optical access and a reference waveform |
| Blind spot | Timing faults that pass at capture speed | Large search space without a suspect cone |
In practice I use them in sequence. Scan gives me the cone. Laser probing, or emission microscopy if I suspect leakage or a short, tests nodes inside that cone at speed. If laser probing shows a node toggling late on the bad unit, I check the STA report for that path at the failing voltage and temperature corner, including clock skew. A fix there is often a metal ECO that buffers or resizes the path. If the node never toggles and the cone points to a single gate, I move to physical analysis on that site, such as decapsulation and SEM, to look for a metal bridge or a via defect.
That sequence keeps the expensive, slow technique for the small part of the chip that scan has already cleared the rest of.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-74What does converting a functional flip-flop to a scan flip-flop cost in area, timing and power, and what testability does it buy?
The 90-second answer
A scan flip-flop buys controllability and observability for internal logic. A plain flip-flop can only be driven through the functional logic in front of it, so a stuck-at fault deep inside a block may never be activated or observed. A scan flip-flop adds a mux in front of the D input and a scan input. In functional mode the mux selects the normal D input. In test mode the mux selects the scan input, and all scan flops in a chain shift test data in on one clock and shift responses out on the next. That single change is what lets ATPG generate a test for almost any stuck-at fault in random logic.
The cost is paid on every flop converted. The mux adds delay in the functional path, the extra input and routing add area, and shift mode toggles flops that would be quiet in functional mode.
// Checked against IEEE 1800-2017 syntax. One flop of a scan chain.
module scan_dff (
input logic clk,
input logic d, // functional data
input logic scan_in, // data from previous flop in chain
input logic scan_en, // 0 = functional, 1 = shift
output logic q
);
logic d_mux;
assign d_mux = scan_en ? scan_in : d;
always_ff @(posedge clk)
q <= d_mux;
endmodule| Property | Plain flip-flop | Scan flip-flop | Consequence |
|---|---|---|---|
| Functional path | D to Q only | D through mux to Q | Setup time grows by the mux delay, typically a few percent of a clock period on flop heavy paths |
| Area | Baseline cell | Extra mux, scan input pin and routing, commonly 1.2 to 1.4 times the plain cell | Chain routing and lockup cells add more area between clock domains |
| Functional power | Toggles only when D changes | Same, plus a small extra capacitance on the mux | Small increase in normal operation |
| Test power | Not applicable | Many flops toggle on every shift clock | Shift power can exceed functional power and must be checked against IR drop |
| Testability | Faults may be uncontrollable or unobservable | Faults can be shifted in, captured and shifted out | Stuck-at coverage above 99% is routine for random logic |
Worked trace
Take a chain of three flops, Q1 Q2 Q3, with scan_en = 1 and scan_in driven to 1, 0, 1 on successive clocks.
| Shift clock | scan_in | Q1 after edge | Q2 after edge | Q3 after edge |
|---|---|---|---|---|
| 1 | 1 | 1 | old Q1 | old Q2 |
| 2 | 0 | 0 | 1 | old Q1 |
| 3 | 1 | 1 | 0 | 1 |
After three clocks the pattern 1, 0, 1 sits in the chain. scan_en then drops to 0 for one capture clock, the functional logic computes from those values, and scan_en rises again to shift the responses out. That shift, capture, shift sequence is the whole basis of scan testing.
The tradeoff in one rule
You spend a small amount of timing margin, area and test power on every flop to avoid spending far more on field returns and debug time for untestable logic. The spend is not uniform. Flops on the critical path feel the mux delay most, so timing driven scan insertion and lockup cells are used there. Large SRAM arrays are usually left out of scan and covered by MBIST instead, because scanning every bit would add area and test time with little gain. Clock gated domains need a test override so the chain can shift while the functional clock is gated, otherwise the flops you paid area for cannot be tested.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-75How would you trade power, performance and area to hit a PPA target on a 200 MHz SoC block, and what would you change first if you were 25% over power with no timing slack left?
The 90-second answer
I would start from the power budget at the worst corner, not from the RTL. PPA is a three way constraint: performance sets the voltage and frequency you must hold at slow, hot, low voltage, power sets how much capacitance you can switch at that voltage, and area sets how much capacitance and leakage you can afford. My first move is to split the budget by block and by power type, dynamic and leakage, then attack the term with the largest exponent. Voltage usually wins because dynamic power scales with V squared times f, and f itself falls roughly with V on a DVFS curve.
Assume a hypothetical 28 nm block at 200 MHz, 0.90 V nominal, 36 mW dynamic for the main datapath. That figure comes from P = alpha x C x V^2 x f with alpha = 0.15, switched capacitance C = 1.5 nF, V = 0.90 V and f = 200 MHz: 0.15 x 1.5e-9 x 0.81 x 2e8 = 36 mW. If the target is 27 mW with no slack to give, I do not start by shrinking gates. I look for activity and voltage.
| Lever | What it changes | Typical gain in this example | Cost |
|---|---|---|---|
| Drop to 0.75 V, 140 MHz DVFS point | V^2 x f | 36 mW to about 18 mW | Misses 200 MHz spec, needs software to accept lower throughput |
| Clock gate idle datapath, alpha 0.15 to 0.08 | alpha | 36 mW to about 19 mW at same V and f | Enable timing, test coverage for gated clocks |
| Operand isolation on a multiplier | alpha on that block | 20 to 30% on that block | Extra mux area, possible timing hit on operand path |
| Move non critical paths to high Vt | Leakage, small delay cost | Leakage down 3x to 10x on those cells | Setup slack loss on moved paths |
| Shrink SRAM or share it between modes | C and leakage | Area and leakage fall together | Bandwidth contention, extra arbitration logic |
How I would sequence the work
First, get numbers I can trust. Run power analysis on a realistic workload, not a toggle free netlist. Activity from gate level simulation or a power aware flow tells me which blocks actually switch. I separate dynamic from leakage by corner. Leakage at 125 C can be an order of magnitude above 25 C for low Vt, so a design that passes power at nominal can fail at hot. That check decides the Vt mix before I touch architecture.
Second, fix the voltage frequency point. If the product has a battery mode, I define two points and design SRAM and the PLL for the lower one. SRAM Vmin usually sets the floor, not logic. At 0.75 V the SRAM may need read assist or a slower access mode, and that assist costs area and a small delay. Ignoring it gives a clean logic number and a chip that fails to boot at low voltage.
Third, cut activity before cutting capacitance. Clock gating is cheap in area and does not change the critical path if the enable is timed as a normal signal and the gated clock uses an integrated clock gating cell. Operand isolation helps when a multiplier or filter sits idle with changing inputs. Both reduce alpha without touching V or f, so timing stays intact. That matters when slack is already near zero.
Failure modes I watch for
Clock gating can create a runt clock if the enable changes near the clock edge, which corrupts flops and can look like a random functional bug. The fix is the integrated gating cell and a timing check on the enable, not a hand built AND gate.
High Vt on a path that was critical at slow corner moves the failure to setup at low voltage. I re run STA after any Vt swap, across the full corner matrix, and I keep low Vt only on paths that need it.
DVFS transitions cause a second class of bug. If frequency rises before voltage settles, flops see a short clock period at low voltage and fail. The hardware needs a sequenced transition or a margin in the timing model, and firmware needs to respect it.
Area cuts that remove decoupling capacitance or widen a power grid can raise IR drop. The block then meets power on paper and fails in silicon when current spikes. I check IR drop and electromigration after any floorplan change that saves area.
If I had to pick one change first with 25% over power and 80 ps of slack, I would gate and isolate activity, then move non critical logic to high Vt, and only then renegotiate the voltage frequency point with the product team. That order preserves the 200 MHz promise while I find the 25%.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-76How does shrinking the technology node change gate delay, power, density and cost per die, and where does that scaling stop helping a design?
The 90-second answer
Shrinking the node, at fixed architecture and activity, makes each transistor smaller, faster and cheaper to switch, and packs roughly twice as many of them into the same area. That was Dennard scaling. It stopped being free around 90 nm, when supply voltage could no longer fall with gate length. Since then each generation buys less delay and less dynamic power, leakage and interconnect have become the limit, and wafer and mask cost rise faster than the area saving. A new node is a PPA and cost trade, not an automatic win.
Why Dennard worked, and why it broke
Dennard scaling scaled gate length $L$, voltage $V$ and dimensions by $s \approx 0.7$ per generation, and kept electric field constant:
| Quantity | Scaling with $s$ | Effect per generation |
|---|---|---|
| Gate delay, $CV/I$ | $s$ | about 30% faster |
| Capacitance per gate | $s$ | smaller load |
| Dynamic power per gate, $\alpha C V^2 f$ | $s^2$ | about half |
| Density | $1/s^2$ | about 2x gates/mm$^2$ |
| Power density | constant | the point of the exercise |
Voltage had to fall to keep field and power density constant. It cannot fall indefinitely. Threshold voltage $V_t$ must stay well above the subthreshold swing limit, roughly 60 mV/decade at room temperature, or off-state leakage explodes. Below about 1 V, $V_t$ scaling stalls, short-channel effects worsen, and SRAM stability collapses. FinFETs at 16/14 nm and gate-all-around devices at 3 nm restored electrostatic control, which helped leakage and short-channel behaviour, but they did not restore voltage scaling.
| Node (representative) | Nominal core $V_{DD}$ | What changed |
|---|---|---|
| 180 nm | 1.8 V | Planar, Dennard still close |
| 90 nm | 1.2 V | Leakage and $V_t$ scaling start to bind |
| 28 nm | 0.9 V | Low leakage planar and early FinFET variants |
| 7 nm | 0.75 V | FinFET, voltage scaling largely stalled |
| 3 nm | 0.70 V | Gate-all-around, mainly density and leakage per device |
These are typical core voltages, not PDK guarantees. A low-power process option at the same node can sit 100 to 200 mV lower.
Delay: transistors improve, wires do not
Gate delay falls with $L$ and $V_{DD}$, but wire resistance per unit length rises as wires get thinner, while wire capacitance per unit length barely falls. The result is that interconnect RC, not gate delay, dominates long paths in advanced nodes. Designers pay for repeaters, wider upper metal, and careful floorplanning, and a block that was gate-limited at 28 nm can be wire-limited at 7 nm at the same clock. Clock frequency therefore rises much more slowly than transistor count. SRAM access time and analog blocks scale worst of all: a 6T SRAM cell shrinks slowly because stability ratios and minimum feature rules dominate, and a bandgap, LDO or ADC does not shrink with digital density.
Power: dynamic falls, leakage takes over
Dynamic power per gate still benefits from smaller $C$ and lower $V$, since $P_{dyn} = \alpha C V^2 f$. Leakage does not. Subthreshold current depends exponentially on $V_t$, and gate tunnelling grows as oxide thins. At 28 nm and below, leakage can be a large share of total power for a mostly idle microcontroller SoC, which is why multi-$V_t$ libraries, power gating and body biasing matter more than a small $V_{DD}$ reduction. Lowering $V_{DD}$ by 100 mV near 0.8 V cuts dynamic power by roughly $1 - (0.7/0.8)^2 \approx 23%$, but it also cuts speed and SRAM margin, so the operating point is set by the slowest corner, not the nominal one.
Density and cost: area falls, wafer cost rises faster
Density gains per generation have slowed from 2x to roughly 1.6 to 1.8x for logic, and less for SRAM and I/O. Wafer cost rises every generation because of EUV lithography, more masks, tighter process control and larger wafers in the past. Cost per good die is what matters:
$$\text{Cost per good die} = \frac{\text{wafer cost}}{\text{gross dies per wafer} \times \text{yield}}$$
Worked example, hypothetical figures for illustration: a 300 mm wafer costing $12,000, die area 100 mm$^2$, defect density 0.1/cm$^2$. Gross dies are about 640 after edge loss, Poisson yield is $e^{-0.1} \approx 0.905$, so about 579 good dies and $12,000/579 \approx $20.70$ per good die. Shrink the same design to 50 mm$^2$ on a $16,000 wafer: gross dies about 1,319, yield $e^{-0.05} \approx 0.951$, about 1,254 good dies, $16,000/1254 \approx $12.80$ per good die. The wafer cost 33% more, yet the die is cheaper because area halved. That arithmetic flips when the design is small, when yield is low, or when mask and NRE cost dominate at low volume. A 3 nm mask set can cost several million dollars before the first wafer, so a low-volume product often stays on a mature node such as 28 nm or 40 nm, where wafer cost is far lower and analog and embedded flash are available.
When not to move nodes
Stay on the older node when the block is analog-heavy, when leakage at temperature fails spec, when the die is already small enough that wafer cost dominates, or when the design is interconnect or SRAM limited and the new node buys little frequency. Move when logic density, dynamic power at a given throughput, or die cost at volume is the binding constraint, and budget the effort for interconnect, leakage and SRAM compiler recharacterisation rather than assuming the RTL ports unchanged.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-77How do drive strengths and threshold voltage options in a standard cell library trade speed, leakage and area, and how would you choose cells for a timing-critical path versus an idle block?
The 90-second answer
A standard cell library is a pre-characterized set of logic cells that synthesis and place-and-route can pick from. For each cell the vendor ships a Liberty timing and power model, a LEF physical abstract, a Verilog model for simulation, and SPICE decks for signoff. Synthesis maps RTL to cells from that library, then sizes and buffers them against the timing, slew, fanout and leakage constraints in the SDC.
Two axes inside the library decide most of the trade-off. Drive strength is the output transistor width for a fixed logic function: BUF_X1, BUF_X2, BUF_X4, BUF_X8. A stronger cell drives a larger load with lower output slew and lower cell delay, but its input capacitance grows with width, so it loads the previous stage more, burns more dynamic power, and takes more area. Threshold voltage is set by implant or workfunction. Low-Vt (LVT) switches faster at the same voltage, standard-Vt (SVT) is the middle option, and high-Vt (HVT) leaks less but is slower. Most libraries offer all three for the same gate, which is why a netlist can mix them.
My default policy: SVT X1/X2 for general logic, LVT only where STA shows the path needs it, HVT for logic that sits idle most of the time, and the smallest drive that meets slew and delay at the worst corner. I let synthesis do that with set_dont_use and leakage reporting, then check the result in STA and power reports rather than hand-picking every cell.
| Option | Delay at fixed Vdd | Subthreshold leakage | Typical use |
|---|---|---|---|
| LVT | Lowest | Highest | Short critical paths, clock buffers |
| SVT | Middle | Middle | Default logic, most datapath and control |
| HVT | Highest | Lowest | Idle registers, configuration logic, rarely toggled state |
The size of each gap is library and corner specific. I read it from the .lib cell_rise, cell_fall and leakage values at the corner being signed off, not from a rule of thumb.
Drive strength, worked through
The table below is a hypothetical illustration of the direction of the trade-off, not data from any specific library. It shows a buffer driving a 50 fF load at 0.9 V.
| Cell | Input cap | Delay into 50 fF | Dynamic energy per toggle |
|---|---|---|---|
BUF_X1 | 1.2 fF | 85 ps | 4.5 fJ |
BUF_X2 | 2.4 fF | 55 ps | 9 fJ |
BUF_X4 | 4.8 fF | 38 ps | 18 fJ |
BUF_X8 | 9.6 fF | 28 ps | 36 fJ |
Moving from X1 to X4 saves 47 ps on this stage in the illustration. The previous stage now sees 4.8 fF instead of 1.2 fF, which can cost it delay, and the buffer burns more energy every toggle. Upsizing past the point where the load is already driven is pure loss. That is why synthesis sizes against a target slew and why a chain of X8 buffers is a sign the floorplan or architecture is wrong, not a fix.
# Design Compiler / Genus style: restrict the cell pool, then check leakage in reports
set_dont_use [get_lib_cells */*LVT*]
set_dont_use [get_lib_cells */*HVT*]
set_max_transition 0.05 [current_design] ;# 50 ps slew target, example valueIn practice I run two syntheses. The first is SVT-only, which gives a clean power baseline. The second allows LVT on paths flagged by STA, by removing the set_dont_use restriction for those cells or by using a path-specific library selection the tool supports, and I compare leakage and area before accepting it. If LVT is allowed everywhere, leakage rises for a small timing gain, and the power team will reject it.
Failure modes I watch for
LVT everywhere fails leakage signoff at the hot corner, because subthreshold current rises steeply with temperature. HVT on a critical path fails setup at the slow corner and cannot be recovered by upsizing alone, since the Vt penalty stays. Oversized drivers cause antenna violations during routing, worse IR drop on the local supply, and long input slew into the next gate, which raises its delay and can create hold problems after CTS. Mixing Vt options also complicates multi-corner STA: each corner needs its own library set, and a path that passes with LVT at TT can still fail with SVT at SS low voltage, so the corner matrix has to include the Vt mix actually used.
The rule I defend in review: start SVT, add LVT surgically, use HVT where activity is near zero, and never let drive strength substitute for a shorter path.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-78What happens to slew rate and edge time when you increase the drive strength of an output pad driving a fixed capacitive load?
The 90-second answer
Increasing drive strength increases the current the output stage can source or sink, so into a fixed capacitive load the pad voltage moves faster. Slew rate goes up and edge time goes down. The load does not change. The driver simply charges or discharges it in less time.
The rule is I = C x dV/dt. Rearranged, dV/dt = I / C. With C fixed, more current means a larger dV/dt. That is the whole decision in one step. A stronger pad is not needed for a slow pin, and a weak pad cannot be fixed by wishing the load were smaller.
A worked example
Take a hypothetical 1.8 V output driving a fixed 10 pF load. The numbers below are illustrative, not a library specification.
| Drive strength | Peak current | Slew rate, I / C | Edge time for 1.8 V |
|---|---|---|---|
| Weak | 5 mA | 0.5 V/ns | 3.6 ns |
| Medium | 10 mA | 1.0 V/ns | 1.8 ns |
| Strong | 20 mA | 2.0 V/ns | 0.9 ns |
Trace the medium case: 10 mA / 10 pF = 1.0 V/ns, and 1.8 V / 1.0 V/ns = 1.8 ns. Doubling the current to 20 mA doubles the slew rate and halves the edge time. Halving the current does the reverse.
What you pay for the faster edge
The faster edge costs dynamic power on every transition, P = C x V^2 x f, and it raises di/dt through the package inductance, which can add ringing and overshoot on a board trace. It also couples more switching noise into the supply and substrate. So the correct choice is the weakest drive strength that still meets the receiver edge requirement at the slow, low voltage corner. A stronger setting buys speed the receiver may not need and creates noise the rest of the chip has to tolerate.
ESD devices and pad metal add their own capacitance to C, which is why they belong in the load figure. If that extra capacitance is ignored, the calculated edge time will look faster than the measured one.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-79How do you design ESD protection for a high-speed IO pin to survive a 2 kV HBM strike without adding so much capacitance that the eye closes, and how do you prove it with TLP?
The 90-second answer
I would start from the strike, not the clamp. A JEDEC HBM event (JS-001) charges a 100 pF capacitor to the rated voltage and discharges it through 1500 ohms into the pin. At 2 kV the peak current is roughly 2000 / 1500 = 1.33 A, the stored energy is 0.5 x 100 pF x (2 kV)^2 = 200 microjoules, and the waveform rises in under 10 ns and decays over roughly 150 ns. The pin must sink that current for tens of nanoseconds while keeping the voltage below gate oxide and junction breakdown of the receiver, and below the latchup trigger of the core supply.
For a high speed IO I would use a low capacitance primary clamp close to the pad, a series resistor or transmission line segment to drop voltage and isolate the receiver, and a secondary clamp at the receiver. The primary device choice is the trade. A diode to VDD and VSS is fast and small but leaks and its capacitance adds directly to the pin. A grounded gate NMOS (GGNMOS) has lower capacitance per amp of current but needs a trigger circuit and can fail by secondary breakdown if the current is non uniform. A silicon controlled rectifier (SCR) carries the most current per area and has a low holding voltage, which helps for 2 kV and above, but that low holding voltage risks latchup and it snaps back, so it is a poor fit for a pin that must stay below VDD during normal operation. For a 10 Gb/s class pin I would normally pick a diode string or a diode plus GGNMOS hybrid, sized by TLP, and accept a larger area than a pure SCR solution.
Sizing by TLP, not by the HBM rating alone
Transmission line pulsing (TLP) is how I prove the clamp. I force current in 100 ns pulses, step by step, and record voltage. The trace shows three regions that decide the design.
| Region | What I read | Design decision |
|---|---|---|
| Leakage region | Current below about 1 mA, voltage follows the diode or MOS characteristic | Leakage must stay under the IO leakage budget at 125 C, often 1 microamp or less per pin |
| Trigger region | Voltage rises to Vt1, then snaps back to Vh | Vt1 must sit above the normal swing plus overshoot, and below oxide breakdown. For a 1.8 V IO, Vt1 around 3.5 to 4.5 V is typical |
| On region | Voltage rises slowly with current, slope is Ron | Ron times peak current is the residual voltage. At 1.33 A, Ron of 1 ohm adds 1.33 V, which can kill the receiver |
It2, the current at the second breakdown point where the device fails, is the number I compare with the HBM peak. A device with It2 of 3 A in TLP has margin over a 1.33 A HBM peak, but the margin shrinks if the current is uneven across fingers. That is why I use multiple fingers with ballasting resistors, typically 1 to 5 ohms per finger, and I check the layout for uniform current paths to the VSS ring. A single wide finger often fails at the edge first.
The capacitance budget is arithmetic, not opinion. A 0.2 pF clamp on a 50 ohm line with a 20 ps edge adds a reflection that the equalizer must absorb. I would keep the total pin capacitance, pad plus clamp plus routing, under about 0.5 pF for a multi gigabit pin and verify it with extracted S parameters, not with a schematic estimate. If the eye closes, I move the primary clamp to a diode string with higher series resistance and let the secondary GGNMOS at the receiver take the remainder, rather than enlarging the primary device.
Failure modes I check before tapeout
Latchup is the one that escapes simulation. If the holding voltage of an SCR or the snapback of a GGNMOS falls below VDD plus margin, a normal overshoot can trigger a sustained short. I check Vh against the maximum supply, including tolerance, and I run the JEDEC latchup test condition of 1.5 times VDD on the pins. CDM is the other escape. A charged device event is faster, under 1 ns, and a clamp that passes HBM can still fail CDM because the trigger circuit is too slow. I would add a local diode at the receiver for CDM and verify with a CDM simulation or a very fast TLP pulse, and I would keep the path from pad to VSS short and wide.
Ratings I would quote to a customer need the standard attached. HBM 2 kV per JS-001 and CDM 500 V per JS-002 are common targets for a microcontroller IO, with 4 kV HBM for pins that leave the board. I would state the pin list, because power pins, analog pins and digital IO use different structures and different ratings, and a single chip level number hides that. Qualification is on packaged parts, not on a test structure alone, so I would plan for HBM and CDM testing on the actual package and keep the TLP data as the design record that links the rating to the device size.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-80A 1.8 V GPIO must drive a 3.3 V I2C bus and a 0.9 V core must read a 1.8 V sensor register: when is a level shifter required, and how would you choose between a passive MOSFET shifter and an active translator for each crossing?
The 90-second answer
A level shifter is required when the driven high or low level does not meet the receiver input thresholds, or when the voltage exceeds the receiver absolute maximum rating. Check four numbers first: driver VOH and VOL against receiver VIH and VIL, plus the supply rails themselves. A 1.8 V driver into a 3.3 V input fails on paper before any other consideration: a 3.3 V CMOS input typically needs VIH of at least 0.7 x 3.3 V = 2.31 V, so a 1.8 V high is read as low, or at best as an indeterminate level that burns shoot-through current in the input stage. The reverse direction, 3.3 V into a 1.8 V input, is worse because it can forward-bias the input protection diode and back-power the 1.8 V rail.
For the two crossings in the question I would not use the same part. The 1.8 V GPIO to 3.3 V I2C bus is open-drain and bidirectional, so a passive NMOS shifter with pull-ups to each rail works and is cheap. The 0.9 V core reading a 1.8 V sensor register is unidirectional and push-pull, so I would use an active translator with a fixed direction pin, or a cross-coupled shifter if the signal is slow and the domain is always on. The choice turns on direction, speed, and what happens when one rail is off.
| Approach | How it works | Best for | Main limit |
|---|---|---|---|
| Passive NMOS, one device | NMOS passes low both ways. Pull-up to the high rail on the high side, pull-up to the low rail on the low side. Gate tied to the low rail. | I2C, SPI with open-drain or slow bidirectional lines | Rise time set by pull-up and bus capacitance. No drive strength on the high side. |
| Active translator, e.g. TXS0102 class | Direction-sensing or direction-pinned buffer with separate supplies on each side, VCCA and VCCB. | Push-pull GPIO, UART, SPI at tens of MHz | Direction sensing fails on some push-pull patterns. Needs both rails present or a defined off state. |
| Cross-coupled PMOS or capacitive | Two PMOS devices cross-coupled between rails, or a capacitor coupling the edge. | Slow control signals, clock enables, always-on to gated domain | Slow, area hungry, poor for data buses. Capacitive type has no DC path, so it cannot hold a static level. |
Worked check for the I2C crossing. The I2C specification limits bus capacitance to 400 pF in all modes. Rise time limits are 1000 ns in standard mode and 300 ns in fast mode. Take the worst case, 400 pF, with a 4.7 kΩ pull-up to 3.3 V on the high side. Rise time to VIH is roughly 0.85 x R x C = 0.85 x 4700 x 400e-12 = 1.6 µs. That fails even standard mode, so 4.7 kΩ is not a valid choice at full bus capacitance. To meet 1000 ns, R must be at most 1000e-9 / (0.85 x 400e-12) = 2.94 kΩ. A 2.2 kΩ pull-up gives 0.85 x 2200 x 400e-12 = 748 ns, which passes standard mode but fails fast mode. Fast mode would need R at most 300e-9 / (0.85 x 400e-12) = 882 Ω, and the sink current would be 3.3 V / 882 Ω = 3.74 mA, above the 3 mA I2C sink limit. So at 400 pF, fast mode cannot be met with a simple pull-up. The fixes are to reduce bus capacitance, split the bus, or use an active buffer with a stronger pull-up stage. The passive shifter adds no drive: the pull-up does all the work on the rising edge, and the NMOS only pulls down.
Failure modes I check in review. First, back-powering. If the 3.3 V side is live and the 1.8 V side is off, current can flow through the shifter or the input diode and lift the dead rail, which then powers logic in an undefined state. The datasheet for the translator must state the behaviour with one supply at 0 V, and the power sequencing must match it. Second, contention on a direction-sensing part. A TXS0102 style device infers direction from which side drives. If both sides drive push-pull at once, or if a slow edge sits near the threshold, the part can oscillate or pass a runt pulse. That is why I prefer a direction-pinned part for a push-pull GPIO. Third, leakage when the source domain is power gated. A cross-coupled shifter tied to a gated rail can leak or clamp the live side. In that case the shifter belongs in the always-on domain, with an isolation cell at the boundary, and the gated side must see a defined low or high through a pull resistor.
For the 0.9 V core reading the 1.8 V sensor, the same threshold check applies in reverse. A 0.9 V CMOS input with VIH near 0.63 V will read a 1.8 V high correctly, but the sensor output stage and the core input protection must tolerate 1.8 V. If the core input is a thin-oxide device rated to 1.0 V absolute maximum, direct connection is not allowed even though the logic levels look compatible. That distinction, logic compatibility versus device rating, is the one interviewers probe, and it decides whether a shifter is a logic fix or a reliability fix.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-81For a 3.3 V, 300 mA sensor rail from 5 V with a 100 mA load step and a 50 mV droop limit, how do an LDO and a buck compare on efficiency, and what output capacitance do you need if the loop responds in 2 µs?
The 90-second answer
I would compare the two on where the extra voltage goes. An LDO passes the load current through a transistor and drops 5 V minus 3.3 V across it, so its efficiency is close to Vout/Vin. A buck switches an inductor and can reach about 90% at this load, but it adds switching ripple and needs an inductor and loop compensation. For a sensor rail, I would pick the buck if heat or battery life matters, and the LDO if the sensor is noise sensitive and the extra heat is acceptable.
For the transient, the output capacitor supplies the extra 100 mA until the loop reacts. With a 2 µs response and a 50 mV droop budget, the required capacitance is 4 µF before derating. I would fit 10 µF nominal and check the capacitor ESR and the regulator stability range.
Efficiency calculation
Assume Vin = 5 V, Vout = 3.3 V and Iout = 300 mA. Output power is 0.99 W.
| Regulator | Efficiency | Input power | Loss | Input current |
|---|---|---|---|---|
| LDO | 3.3/5 = 66% | 1.50 W | 0.51 W | 300 mA |
| Buck | 90% assumed | 1.10 W | 0.11 W | 220 mA |
The LDO input current is the load current plus its quiescent current, typically tens of microamps for a modern part, so quiescent current does not change this result. The buck input current follows from Pout/(efficiency x Vin). The LDO therefore dissipates about 0.4 W more than the buck at full load. That difference is the main trade-off. The buck pays for it with ripple at the switching frequency, a larger inductor, and a compensation network. The LDO pays with heat and a higher input current.
At light load the gap narrows. A buck has fixed switching and gate drive losses, so its efficiency falls as load current drops. An LDO efficiency stays near Vout/Vin until quiescent current becomes a large fraction of load current. I would check the efficiency curves at the sensor's normal current, not only at 300 mA.
Capacitor sizing for the load step
During the 2 µs before the loop responds, the capacitor supplies the 100 mA step. Charge removed is ΔI x t, and droop is charge divided by capacitance:
Cout >= ΔI x t_response / ΔV = 0.1 A x 2 µs / 0.05 V = 4 µF
A ceramic capacitor with 10 mΩ ESR adds only 1 mV of instantaneous step (0.1 A x 0.01 ohm), so ESR is not the limit here. I would choose 10 µF nominal because a 10 µF MLCC can lose half its capacitance under 3.3 V DC bias, plus tolerance and temperature variation. With 5 µF effective, droop is about 40 mV, inside the 50 mV budget.
The topology changes how fast the loop can respond. An LDO has no inductor to slew, so a 2 µs response is realistic with a stable capacitor in the range the datasheet specifies. A buck response is limited by inductor current slew, di/dt = (Vin - Vout)/L, and by crossover frequency, usually a fifth to a tenth of the switching frequency. If the buck cannot respond in 2 µs, the capacitor must grow or the droop budget must grow.
Checks I would still run
Dropout matters if Vin falls. At 5 V the LDO has 1.7 V of headroom, so dropout is not a concern in this case. I would confirm the dropout voltage at 300 mA and at temperature extremes if Vin can sag.
Stability with MLCCs needs a check with the actual capacitor value after DC bias derating. Some LDOs require a minimum capacitance or a minimum ESR, and a buck compensated for a high ESR electrolytic can ring with a low ESR ceramic. I would verify phase margin or at least the step response overshoot with the fitted part, and confirm the buck ripple does not exceed the sensor supply specification.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-82What is the formula for estimating battery life from a battery's mAh rating and a device's average current draw?
The 90-second answer
Battery life in hours is battery capacity in milliamp-hours divided by average load current in milliamps. That is the whole rule. Everything else in a power budget is a correction to one of those two numbers.
life_hours = usable_capacity_mAh / average_current_mAUsable capacity is not the headline rating. Multiply the rated mAh by the depth of discharge you will actually use and by converter efficiency if the current is quoted at the load rail rather than at the battery. Average current is the time weighted mean over a full use cycle, not the peak current.
Worked example, with labelled assumptions: a 2000 mAh cell, 80% depth of discharge, 85% efficient buck converter, and a device averaging 40 mA referred to the battery.
| Term | Value |
|---|---|
| Rated capacity | 2000 mAh |
| Usable after depth of discharge | 2000 x 0.80 = 1600 mAh |
| Average current at battery | 40 mA |
| Estimated life | 1600 / 40 = 40 hours |
If the 40 mA was measured on a 3.3 V rail after the converter, refer it back to the battery first. Power is conserved apart from losses, so battery current is load power divided by battery voltage and efficiency. A 40 mA load at 3.3 V is 132 mW. At 3.7 V battery voltage and 85% efficiency, battery current is 132 / (3.7 x 0.85) = 42 mA. Life becomes 1600 / 42 = 38 hours. Quoting the rail current directly would overstate life by about 5% in this case, and by more when the battery voltage falls toward 3.0 V near empty.
# Python 3, checked against the worked example above.
capacity_mah = 2000
depth_of_discharge = 0.80
avg_current_ma = 40.0
usable_mah = capacity_mah * depth_of_discharge
life_hours = usable_mah / avg_current_ma
print(f"{life_hours:.1f} hours") # 40.0 hoursA power budget is that calculation done per subsystem and per mode. List each block, its current in active mode and in sleep, and the fraction of time spent in each mode. Multiply current by duty cycle, sum across blocks, and compare the total against the capacity. The table below shows the shape for a handheld device, with currents referred to the battery.
| Mode | SoC | Radio | Display and sensors | PMIC and gauge | Mode total |
|---|---|---|---|---|---|
| Active, screen on | 120 mA | 30 mA | 80 mA | 2 mA | 232 mA |
| Active, screen off | 60 mA | 20 mA | 5 mA | 2 mA | 87 mA |
| Standby | 1.0 mA | 0.3 mA | 0.05 mA | 0.15 mA | 1.5 mA |
Standby at 1.5 mA gives 1600 / 1.5 = 1067 hours, about 44 days. That figure only holds if the PMIC and gauge quiescent currents in the last column are real measured values. A gauge left in active mode at 500 uA instead of sleep at 15 uA would cut standby life by roughly a quarter on its own.
Two corrections interviewers probe next. First, peak current is separate from average. A radio pulse at 500 mA can drag an aged or cold cell below the converter undervoltage lockout even when the average is 40 mA, so bulk capacitance and lockout margin matter. Second, capacity fades. Budgeting on end of life capacity, often 80% of the initial rating after several hundred cycles, gives a runtime claim the product can still meet later in its life.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-83Walk me through designing a sensor interface for a 5 mV full-scale bridge sensor that needs 0.01% accuracy at 10 Hz bandwidth, covering signal conditioning, ADC choice, and noise?
The 90-second answer
Start from the error budget, not the block diagram. A 5 mV full-scale bridge that must resolve 0.01% of full scale needs 500 nV resolution at the sensor terminals, and total noise plus drift over temperature must stay below roughly one third of that if you want margin. That single number drives gain, ADC resolution, bandwidth, and every noise source in front of it.
I would use ratiometric excitation, a chopper-stabilised instrumentation amplifier with gain 200, a first-order anti-alias filter, and a delta-sigma ADC running oversampled, followed by digital decimation to 10 Hz. Ratiometric means the ADC reference comes from the same excitation that drives the bridge, so excitation drift cancels to first order. Chopping removes the amplifier offset and 1/f noise that would otherwise swamp a 500 nV target. The delta-sigma gives 16 to 18 effective bits at low bandwidth without a precision external reference or a long SAR conversion that lets the input settle between multiplexed channels.
Signal conditioning
Excitation choice is a trade between signal, power, and self-heating. A 1 kΩ bridge at 2.5 V draws 2.5 mA and dissipates 6.25 mW in the sensor. That heating shifts resistance and creates a slow drift after power-up. Pulsing excitation at, say, 10% duty cycle during conversion cuts average power to 0.6 mW and lets the bridge cool between samples, at the cost of needing the amplifier to settle within the pulse. I would pulse it if the system power budget is tight, and I would keep the excitation and reference traces paired and Kelvin-connected to the bridge so lead resistance does not enter the ratio.
The instrumentation amplifier needs input-referred noise below about 100 nV rms in the 10 Hz band, common-mode rejection above 100 dB at 50 and 60 Hz, and input bias current low enough that source imbalance does not convert to offset. With a 1 kΩ bridge, 1 µA of bias mismatch through a 100 Ω imbalance gives 100 µV, which is fatal. Specify bias current in nanoamps, or buffer the bridge with a high-impedance stage. Gain of 200 turns 5 mV into 1.0 V, which fits a 2.5 V ADC reference with headroom for offset and overrange. Do not put all the gain in the amplifier if its distortion at high gain hurts linearity. Split gain between a low-noise preamplifier and a second stage, and check total harmonic distortion at the actual output swing, not at a small test signal.
The anti-alias filter looks almost trivial at 10 Hz bandwidth, and that is the trap. A delta-sigma modulator samples at 1 MHz, so noise and interference near 1 MHz and its harmonics alias into the band. A single-pole RC at 1 kHz before the ADC attenuates that region while adding negligible phase error at 10 Hz. A second pole costs little and buys 40 dB per decade above cutoff. Keep the filter resistor small enough that its thermal noise, referred through the gain, stays in budget, and keep the capacitor a C0G type, since a high-K ceramic changes value with voltage and temperature and moves the cutoff.
ADC selection
| Architecture | Strength here | Weakness here | Verdict |
|---|---|---|---|
| Delta-sigma | 16 to 18 ENOB at low bandwidth, noise shaping, no external reference if ratiometric | Latency of several modulator cycles, limited multiplexing rate | First choice for this spec |
| SAR | Fast multiplexing, low latency, good for many channels | Needs a settled input each conversion, ENOB falls as bandwidth rises, reference must be precise | Use if you must scan 8 channels at 1 kHz each |
| Flash or pipeline | Very fast | Power and area far beyond a sensor node, 10 bits is already generous | Reject |
The delta-sigma choice has a concrete failure mode: its digital filter has a sinc response with notches at multiples of the output rate. If you set the output rate to 100 Hz, the notches sit at 100, 200, 300 Hz and reject 50 Hz poorly. Set the output rate to 120 Hz or 100 Hz deliberately depending on mains frequency in the target market, or add a notch in firmware. That decision belongs in the datasheet, not in a field fix.
Noise budget, with numbers
Label these as design targets for a worked example. ADC full scale 2.5 V, 16 bits, so one LSB is 38 µV at the ADC input and 190 nV referred to the sensor after gain 200. Quantisation noise is LSB divided by sqrt(12), about 55 nV referred to the sensor, which is already a tenth of the 500 nV target. That is why 16 bits is the floor and 12 bits would fail on quantisation alone.
import math
lsb_sensor = 2.5 / 2**16 / 200 # V, referred to bridge
quant = lsb_sensor / math.sqrt(12)
amp = 80e-9 # V rms, IA in 10 Hz band
thermal = math.sqrt(4 * 1.38e-23 * 300 * 1000 * 10) # 1 kOhm bridge, 10 Hz
total = math.sqrt(quant**2 + amp**2 + thermal**2)
print(f"LSB {lsb_sensor*1e9:.0f} nV, total {total*1e9:.0f} nV rms")That prints roughly 190 nV LSB and 100 nV rms total, leaving margin for reference noise, filter resistor noise, and digital supply coupling. If the measured noise is 3 times higher, the usual culprits in order are excitation noise entering through the reference pins, ground bounce from the MCU switching during conversion, and leakage on the PCB across the high-impedance input. Fix the first with a dedicated low-noise regulator and RC filtering on excitation, the second by pausing digital activity or by synchronising conversion to a quiet window, and the third with a guard ring and a solder mask opening kept small around the input node.
What I would verify before tapeout
Simulate the amplifier and filter together across process, voltage, and temperature, including Monte Carlo on resistor and capacitor values, because a 1% filter resistor moves the cutoff and a 1% bridge mismatch moves offset. Measure ENOB and noise spectral density on the evaluation board with the sensor replaced by a low-noise source, then with the real sensor, to separate electronics noise from sensor noise. Test with excitation pulsed and continuous, since self-heating shows up as a slow exponential after each power cycle and looks exactly like drift. Finally, run the interface at the worst-case supply ripple the system allows, because a sensor interface that meets spec on a bench supply and fails on the product supply has failed the only test that matters.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-84A BLE receiver loses 6 dB sensitivity when the on-chip buck converter runs at 2 MHz, but not when it is off. How would you explain that coupling path and choose between moving the converter frequency and adding a dedicated LDO for the PLL?
The 90-second answer
The buck is not interfering through the air. It is reaching the PLL through the supply. A 2 MHz buck with, say, 50 mV peak to peak ripple at its output puts a 2 MHz tone on every rail that shares that output impedance. If the VCO or charge pump supply follows that tone, the oscillator frequency is modulated at 2 MHz. That creates sidebands at carrier plus and minus 2 MHz and raises phase noise in the receive band. During reception those sidebands mix a strong blocker into the channel, which is reciprocal mixing, and the sensitivity falls even though the LNA itself is unchanged.
I would first prove that path before changing anything. Measure the PLL supply with a scope or on chip monitor with the converter on and off, and measure phase noise or TX spectrum at the same time. If the 2 MHz spur on the supply and the sidebands on the carrier appear and disappear together, the supply path is confirmed. If sensitivity still falls with the PLL on a clean bench supply, I would look at substrate and ground bounce next.
# Hypothetical figures, labelled as an example
ripple_mv = 50.0 # buck output ripple at 2 MHz
psrr_db = 40.0 # LDO rejection at 2 MHz, from its datasheet curve
residual_mv = ripple_mv / (10 ** (psrr_db / 20))
print(f"{residual_mv:.2f} mV") # 0.50 mV after the LDOA 40 dB rejection at 2 MHz turns 50 mV into 0.5 mV. Whether that is enough depends on the VCO pushing figure, in MHz per volt. At a hypothetical 10 MHz/V, 0.5 mV gives 5 kHz of frequency modulation, which is far less harmful than the 500 kHz modulation from the raw 50 mV. The arithmetic is the point. DC PSRR from a datasheet headline is not the number to use. Rejection at the switching frequency is.
Two fixes, and when each wins
| Approach | What it changes | Main cost | When I choose it |
|---|---|---|---|
| Move the buck frequency | Puts the ripple tone and its harmonics outside the 2.4 GHz band and away from the channel plan | New frequency may land on a clock harmonic or break the converter design | First move, because it costs no silicon area if the converter can retune |
| Dedicated LDO for PLL and VCO | Attenuates the tone before it reaches the oscillator, regardless of its frequency | Area, quiescent current, dropout headroom, and its own PSRR falls with frequency | When the frequency cannot move, or the spur must be suppressed in every operating mode |
Moving the frequency sounds free and often is not. A buck designed for 2 MHz may lose efficiency or stability at 3.7 MHz, and 3.7 MHz harmonics can still land near a clock harmonic or inside the band after mixing in a nonlinear stage. I would check the converter efficiency and stability across load, and list harmonics up to the RF band, before committing.
The LDO is more predictable. It works at any buck frequency and also filters load transients from the digital core. Its limits are physical. A low dropout LDO needs headroom, so the buck must run higher, which costs efficiency. Its PSRR at 2 MHz might be 40 dB while its DC PSRR is 70 dB, so I would read the PSRR versus frequency curve, not the headline. It also needs its own decoupling capacitor close to the PLL pins, sized for the 2 MHz tone, typically a few microfarads on chip or off chip depending on the process. Without that capacitor the LDO output impedance at 2 MHz can be high enough to pass the ripple anyway.
In practice I would do both in a limited way. Keep the buck frequency in a planned slot that avoids the band, and give the PLL a dedicated LDO with verified rejection at that frequency. That gives margin if the converter changes mode, for example pulse skipping at light load, which creates a lower frequency tone that a frequency plan alone does not fix.
What I would verify
Sensitivity, phase noise and TX sidebands with the converter on, off, and in each power mode, with the digital core idle and active. A delta that appears only in one mode points to that mode's ripple spectrum. I would also check the PA burst case separately, because PA current pulses can pull the same supply through a different impedance, and a fix that works in receive can fail during transmit.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-85An attacker replaces the external flash on your MCU with a modified bootloader. How does a ROM root of trust using a fused public-key hash detect it, and where should the private signing key live?
The 90-second answer
The ROM is the root of trust because mask ROM cannot be rewritten by an attacker who controls flash. At reset it loads the bootloader from flash into SRAM, hashes it, and verifies the signature against a public key whose hash was fused into OTP at the factory. A modified bootloader will not match a valid signature, so the ROM refuses to jump to it. The private signing key never lives on the device. It stays in a factory HSM, and only the public key hash reaches the chip.
What the ROM checks
The factory flow matters here. The signing key is generated and held offline. The corresponding public key is hashed with SHA-256, and that 32-byte hash is programmed into eFuse or OTP. OTP bits can be blown once and cannot be cleared by software or by erasing flash. On the device, the ROM contains the verification code and the expected hash. It does not need to store the full public key, which saves OTP area and makes a partial read of the fuses less useful.
On reset the ROM does four things in order. It reads the fused hash and the anti-rollback counter. It copies the stage-1 image from external flash to SRAM, because executing directly from attacker-controlled flash would let the attacker change code after verification. It hashes the copied image and checks the ECDSA P-256 signature over that hash. It checks the image version against the counter, then jumps to the entry point only if every check passes.
// ROM code, checked against C11. Runs from mask ROM before flash code.
int boot_stage1(const image_t *img, const uint8_t *sig) {
uint8_t digest[32];
if (img->len > SRAM_SIZE) return -1;
memcpy((void *)SRAM_BASE, img->data, img->len);
sha256((const void *)SRAM_BASE, img->len, digest);
if (img->version < otp_rollback_counter()) return -1;
if (!ecdsa_p256_verify(otp_pubkey_hash(), digest, sig)) return -1;
return 0; // caller jumps to SRAM entry only when this returns 0
}| Flash contents | Hash and signature result | ROM action |
|---|---|---|
| Genuine bootloader, current version | Signature verifies, version at or above counter | Copy to SRAM and execute |
| Modified bootloader, attacker has no signing key | Hash changes, signature fails | Halt, or boot a recovery image if one is present |
| Genuine but old bootloader with a known bug | Signature verifies, version below counter | Refuse, which blocks rollback |
| Truncated or oversized image | Length check fails before hashing | Refuse without executing any of it |
Where keys live on the device
The signing key is not a device key. Device keys are different. A device may need a unique AES key for firmware decryption or for authenticating itself to a server. That key should be generated inside the chip or injected over a secure factory channel, then stored in OTP-backed registers inside an always-on security island. The main CPU never gets a bus path to read those registers. It sends a command through a mailbox, for example "decrypt this block" or "sign this digest", and the accelerator returns the result.
| Option for device key storage | How it works | Main trade-off |
|---|---|---|
| OTP or eFuse in a security island | Key is blown once, readable only by the accelerator | No field update, so a leaked key cannot be replaced |
| Encrypted flash with a hardware-wrapped key | Data key is encrypted by a key held in OTP | Larger capacity, but the OTP key still needs the same isolation |
| External secure element on SPI or I2C | Separate chip holds and uses the key | Extra component and cost, and the bus between chips needs authentication |
For a microcontroller SoC, the first option is usually enough for a root device key. Encrypted flash adds value when the firmware image itself must stay confidential, not only authentic. A secure element makes sense when the SoC vendor does not offer an isolated key store, or when certification of that element is required by the customer.
Limits worth naming
Secure boot proves the bootloader came from the holder of the signing key. It does not prove the bootloader is free of bugs, and it does not stop an attacker who has physical access from probing debug ports. Production parts should therefore disable JTAG and SWD, or gate them behind a signed unlock, after provisioning. The rollback counter also needs care. It should advance only after the new image has booted successfully, otherwise a failed update could lock the device out of the old working image. Those two choices, debug lockdown and counter policy, are where a design that looks correct on paper often fails in the field.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-86How does secure boot verify a bootloader's signature and stop an attacker rolling back to an older vulnerable version?
The 90-second answer
Secure boot starts from code that cannot be changed after fabrication. A mask ROM bootloader runs first, reads a public key hash from one-time programmable eFuses, and verifies the next stage image before executing it. Each stage verifies the following one, so trust is a chain from silicon to firmware.
Signature verification has three steps. The ROM hashes the image bytes, usually with SHA-256, then checks that hash against a signature made with the vendor private key. The check uses the public key whose hash is fused in the device. If the signature fails, the ROM halts or falls back to a recovery image and never jumps to the unverified code.
Rollback protection stops replay of an older, correctly signed but vulnerable image. The signed manifest carries a version number. The chip keeps a monotonic counter in eFuses or replay protected storage that only moves forward. The ROM refuses any image whose version is below the counter. After a new version boots successfully, firmware increments the counter, so the old version cannot be used again.
How the chain is built in hardware
The ROM is small and fixed, so it contains only the hash, signature check, flash loader and counter check. A hardware crypto accelerator or ROM code performs ECDSA P-256 or RSA-2048 verification. RSA verification is a modular exponentiation with a small public exponent, which is cheap in hardware. ECDSA needs point multiplication and a random nonce at signing time, but verification is also feasible in a small accelerator.
Key provisioning happens at test. The vendor generates the key pair offline, signs the stage 2 image, and fuses only the SHA-256 hash of the public key, or the public key itself if eFuse space allows. Fusing the hash means a fault that reads the eFuse does not reveal a usable key. The private key never leaves the signing server.
Each stage can carry its own key. Stage 2, running from internal SRAM, verifies the application image with a key it extracts from a signed certificate in stage 2. That keeps the ROM simple and lets the vendor rotate application keys without new silicon.
Rollback trace
Assume the fused counter is 3 after version 3 has booted once. The counter is stored as eFuse bits that can only be blown, or as a counter in a secure element with replay protection.
| Image presented | Signed version | Counter | ROM decision |
|---|---|---|---|
| Stage 2 v3 | 3 | 3 | Verify signature, execute |
| Stage 2 v2, replayed from flash | 2 | 3 | Signature passes, version check fails, halt |
| Stage 2 v4 | 4 | 3 | Verify signature, execute, then increment counter to 4 |
| Stage 2 v4 with one flipped bit | 4 | 3 | Hash mismatch, signature fails, halt |
The increment must happen only after the new image has run its self tests. If the counter moved before the image proved itself, a bad update would brick the device by blocking the last known good version. Many designs increment in two steps: a pending version is recorded, and the counter commits after a successful boot flag is set.
Failure modes an interviewer will probe
Replay is the main one. A signature alone does not stop it, because the old image is genuine. The version check is what stops it, and it must cover every component that can be downgraded, including the bootloader, firmware and configuration data. If only the application version is checked, an attacker can keep a new application and pair it with an old bootloader that has a known bug.
Fault injection is the second. Voltage or clock glitches during the compare can skip the branch that halts on failure. Defences include redundant checks, a hardware state machine that only releases reset to the CPU after verification completes, and sensors that zeroise keys on tamper. Secure debug must also be disabled by eFuse after provisioning, otherwise JTAG can load code past the ROM.
Key compromise is the third. A leaked private key breaks every device in the field, so production signing needs an HSM, dual control and a revocation plan. Revocation in fused hardware is hard, which is why the chain uses intermediate keys: the ROM trusts a root hash, stage 2 can reject an intermediate certificate, and the root stays offline.
For an IC design engineer the takeaway is partitioning. Put the immutable check and the counter in hardware that software cannot bypass, keep the ROM small enough to verify formally, and make the boot state machine, not a software flag, the gate that releases the core from reset.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-87How do JTAG and SWD debug interfaces work, and how would you secure them in production without losing field failure analysis?
The 90-second answer
JTAG and SWD are two transports to the same debug fabric on many Arm SoCs. JTAG uses TCK, TMS, TDI and TDO, with optional TRSTn, and a 16-state TAP controller. SWD uses SWCLK and SWDIO, plus optional SWO for trace, and reaches a Debug Port (DP) and Access Ports (APs). The APs are what give memory access. On a Cortex-M or Cortex-A part, MEM-AP can read system memory and flash, and the core debug registers can halt the core and inspect registers.
For production I would design a lifecycle with development, production and RMA states, rather than a single on/off fuse. Development leaves JTAG and SWD open for bring-up. Production blocks unauthenticated AP access. RMA allows a scoped, authenticated session for a returned unit. The exact bits and names differ by vendor, so I would implement this against the specific product manual and verify it on fused samples.
| Feature | JTAG | SWD |
|---|---|---|
| Pins | TCK, TMS, TDI, TDO, optional TRSTn | SWCLK, SWDIO, optional SWO |
| Best for | Boundary scan, board test, multi-device chains | Cortex-M/A debug, small packages |
| Protocol | TAP state machine, instruction and data shift registers | Packet based, with turn-around and parity |
| Trace | Via auxiliary trace port or probe | SWO output, Manchester or NRZ depending on configuration |
| Risk if left open | Memory read/write, flash extraction, secure boot bypass | Same AP access, reachable with two wires |
How access works
On JTAG, the TAP controller moves through Test-Logic-Reset, Run-Test/Idle and shift states. The instruction register selects IDCODE, BYPASS, boundary scan, or a core debug instruction. On SWD, the DP handles the wire protocol and forwards requests to MEM-AP for system memory or to core debug registers. A typical session reads DPIDR, then uses MEM-AP to read flash. If MEM-AP remains enabled in production, that read succeeds. That is the exposure to close.
Some vendors provide product-specific mechanisms for this. Examples include readout protection levels on STM32 parts and lifecycle or debug disable fuses on NXP and TI parts. Arm also defines debug authentication concepts in newer architecture versions, but support and naming vary by core and by silicon vendor. I would not assume a generic Arm feature. I would check the target product's reference manual for the exact fuse, the exact state encoding, and whether the fuse gates the TAP, the DP, the AP, or all three.
// Example of an authenticated unlock design, not a standard protocol
bool debug_unlock(const uint8_t challenge[32], const uint8_t response[32],
uint32_t serial, uint32_t expiry) {
if (lifecycle != LIFECYCLE_PRODUCTION) return false;
if (expiry < current_time()) return false;
uint8_t expected[32];
hmac_sha256(device_key, challenge, serial, expiry, expected);
return constant_time_equal(expected, response);
}The probe sends a challenge. The target computes an HMAC with a per-device key stored in OTP with AP read protection. The probe returns the response. Only then does firmware or hardware enable the AP for that session. The key is unique per die, generated at test from a TRNG, and the backend holds the corresponding verification material in an HSM. A leaked probe image then unlocks only the serial numbers and expiry windows it was issued for.
Securing production while keeping failure analysis
First, block unauthenticated AP access in production and test the block directly. I would attempt a MEM-AP flash read with an open probe on production-fused samples and confirm it fails. I would repeat the test after a warm reset, because a reset path that restores a default debug state would reopen the port.
Second, separate board test from core debug where the product allows it. Boundary scan can remain available for interconnect test while core AP access is locked. Whether that separation exists depends on how the TAP instruction decode is fused, so I would confirm it in the manual and on silicon.
Third, plan the RMA path before tapeout. A full erase on return destroys the fault state. A scoped RMA mode that permits memory read, blocks flash write, expires after a fixed window, and records access in a counter gives failure analysis a window without reopening the fleet.
Failure modes to test for include a fuse that gates JTAG instructions but not SWD access to the same DP, a certificate check that omits expiry or serial number, and a bootloader that re-enables debug after reset. These are design risks to check on the specific part, not universal behaviours. The test plan should cover JTAG and SWD separately, cold reset and warm reset, and both authenticated and unauthenticated probes.
The trade-off is key management and test time. Per-device keys add programming time and a backend that must handle key rotation if a batch is compromised. Disabling debug entirely is simpler and may suit a low-cost part with no field returns. For an automotive or industrial SoC where one field failure costs more than the key infrastructure, authenticated debug is the better spend.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-88Your Cortex-M7 firmware misses its 1 kHz ISR deadline at 100 MHz. How would you use performance counters and profiling to find whether cycles, cache misses, or interrupt latency are to blame?
The 90-second answer
I would split the 20 microsecond deadline, which is 2,000 cycles at 100 MHz, into three parts: latency before the handler runs, cycles inside the handler, and extra cycles when the handler stalls on memory. The DWT CYCCNT on a Cortex-M3, M4 or M7 gives me the second part directly. It does not give me cache miss counts on an M7. The Cortex-M7 DWT has CYCCNT and four comparators for breakpoints and watchpoints, and no PMU event counters. Cache and bus event counters are a Cortex-A53 or A55 feature, and on RISC-V they come through mhpmcounter. On an M0 or M0+ there is no CYCCNT at all, so I would fall back to a timer peripheral or trace.
For entry latency I would not trust a software timestamp alone. I would toggle a GPIO as the first instruction in the ISR and compare it on a scope or logic analyser against the timer output pin that raised the interrupt. That shows the real delay from compare event to handler, including stacking, priority preemption and any time spent with interrupts masked. If that number is large, the problem is a long critical section, a lower priority ISR holding the bus, or a priority assignment that lets a long handler block this one.
// Cortex-M7, CMSIS. DWT->CYCCNT is a 32-bit free-running counter.
#include "core_cm7.h"
static inline uint32_t cycles_now(void) { return DWT->CYCCNT; }
void sensor_isr(void) {
uint32_t start = cycles_now();
process_frame();
uint32_t elapsed = cycles_now() - start; // unsigned subtraction handles one wrap
record(elapsed);
}At 100 MHz the counter wraps every 42.9 seconds. Unsigned subtraction handles a single wrap. A handler running longer than that would already be broken.
A worked trace, with hypothetical figures labelled as such:
| Interval | Cycles | Share of 2,000 | Reading |
|---|---|---|---|
| Timer event to handler entry, scope measured | 180 | 9% | Latency is not the problem |
| Handler, warm cache | 900 | 45% | Core execution dominates |
| Handler, cold flash and SRAM buffers | 2,480 | 124% | Misses the deadline |
| Handler after DTCM buffers and prefetch on | 1,150 | 58% | Meets it with margin |
The last two rows are the point. On an M7 I cannot read a miss counter to prove the cold run is memory bound. I prove it by experiment. I run the same frame with the I-cache and D-cache disabled, then enabled, then with the TX and RX buffers moved from SRAM to DTCM, then with the cache flushed before each run. If CYCCNT tracks those changes and the arithmetic is unchanged, the stalls are in the memory system. I would also check buffer alignment against the cache line size from SCB_CTR, because a DMA buffer straddling a line boundary forces extra maintenance and can corrupt a neighbouring buffer when the driver cleans or invalidates.
For location inside the handler I would use sampling or trace, and I would be explicit about what each costs. On an M7 there is no periodic PC sampling interrupt in the DWT. I can sample with SysTick: a 10 kHz SysTick handler reads the stacked PC from the exception frame and records it. That gives a histogram of hot functions. It aliases if the sampling period divides the 1 kHz task period, so I would choose a period that is not a divisor of 1 ms and cross-check the histogram total against CYCCNT. ETM or ITM trace gives exact flow and data, but needs a probe, trace bandwidth and pins or a serial wire viewer buffer, and the trace logic costs area and power in the SoC. Counters and sampling are cheap enough to leave in a debug build. Trace is for the bench.
| Method | Gives | Cost | Blind spot |
|---|---|---|---|
| CYCCNT on M3, M4, M7 | Handler cycles, wrap-safe deltas | One register | No reason for the cycles |
| GPIO plus scope | True entry latency | One pin, bench equipment | No per instruction detail |
| SysTick PC sampling | Hot functions and loops | Periodic interrupt jitter | Aliasing, coarse attribution |
| ETM or ITM trace | Exact instruction flow | Probe, bandwidth, area, power | Observer effect, not for production |
| PMU on Cortex-A53, A55 | Misses, stalls, branch events | Programmable counters | Not present on Cortex-M7 |
Failure modes I would name: profiling code that masks interrupts while it snapshots counters, which inflates entry latency for every other ISR; a SysTick sampling handler that itself consumes the budget it is measuring; cache maintenance done in the ISR instead of before DMA starts, which adds hundreds of cycles; and assuming a counter exists on a core variant that does not implement it. I would snapshot CYCCNT, re-enable interrupts, and process the result at lower priority. On an A53 I would also remember that PMU counters can count speculative instructions, so a high instruction count does not always mean retired work.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-89A Cortex-M4 firmware image is 12 KB over flash at -O2 and its 1 kHz ISR is close to its deadline. Which optimizations would you try first to shrink size without slowing the ISR, and why?
The 90-second answer
I would keep the ISR at -O2 and shrink the rest of the image first. The main trade-off is that -Os makes the whole image smaller by favouring compact code, but it also makes hot loops and interrupt handlers slower. In this situation the deadline is the binding constraint, so I would not apply -Os globally. I would use -O2 for the ISR and its callees, and -Os plus dead code removal for drivers, protocol stacks and rarely used configuration code that do not run in the ISR.
The mechanism is straightforward. At -O2, GCC and Clang inline small functions, unroll loops with known trip counts, and keep values in registers across calls. That removes call and loop overhead, so cycles fall, but the same body is copied at each call site and each unrolled iteration, so flash grows. At -Os, the compiler prefers shared code, smaller loop bodies and fewer copies. Flash falls, but the ISR may pay extra branches, reloads and spills. Function and data sections with garbage collection are different. -ffunction-sections -fdata-sections -Wl,--gc-sections does not change how a live function is compiled. It lets the linker discard whole unused functions and tables, so size falls with no cycle cost for code that remains.
| Change | Effect on flash | Effect on ISR timing |
|---|---|---|
-O2 to -Os everywhere | Often 10 to 25% smaller on driver-heavy firmware | Often slower, sometimes 5 to 20% more cycles in a tight loop |
Add --gc-sections | Removes unused drivers and tables, commonly 2 to 8 KB in a 64 KB image | No change to a live ISR |
-flto with -Os for non-hot code | Cross-module inlining and dead code removal, further size reduction | No change if the ISR is excluded, unpredictable if it is not |
| Force inline a 20 instruction helper called 6 times | Adds roughly 100 instructions of flash | Saves call and return overhead on each call |
Those ranges are typical for a Cortex-M4 image built with Arm GCC, not a promise. I would confirm them from the map file for this build.
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -O2 \
-ffunction-sections -fdata-sections -Wl,--gc-sections \
-o firmware.elf firmware.c isr.c drivers.c
arm-none-eabi-size firmware.elf
arm-none-eabi-objdump -h firmware.elfA worked check makes the choice concrete. Assume the -O2 image is 76 KB against a 64 KB flash limit, so 12 KB must go. The map file shows 5 KB of unused protocol code and 3 KB of unused tables. Garbage collection removes 8 KB with no timing change, leaving 68 KB. Rebuilding only the non-hot files at -Os shrinks them by, say, 6 KB, which brings the image to 62 KB. The ISR object stays at -O2, so its cycle count is unchanged. I would verify that last point by toggling a GPIO at ISR entry and exit, or by reading the DWT cycle counter, and compare the same build before and after. If the ISR had grown, I would move its file back to -O2 and look for a larger unused section instead.
The failure mode to avoid is shrinking the ISR to meet a flash limit and then missing the 1 kHz deadline under worst case load. Average cycles from a simulator will not catch that. Measure the ISR with interrupts and the busiest DMA transfer active, and check stack use after any inlining change, because inlined call chains can raise the high-water mark. If the image still does not fit, the next step is to remove a feature or move a table to external flash, not to push the ISR to -O3. -O3 would likely grow flash further and make the worst case harder to bound, which is the opposite of what this design needs.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-90What does saturation do when a fixed-point DSP result overflows, and how does that differ from letting the value wrap around?
The 90-second answer
Saturation clamps an overflowing result to the largest value the format can represent. Wrap lets it roll over to the opposite end of the range. In a signed 16-bit Q1.15 value, which spans -1.0 to just under +1.0, adding 0.75 and 0.50 gives a true result of 1.25. Saturation returns 32767, the code for +0.99997. Wrap returns the code for -0.75, because 40960 in binary does not fit in 16 bits and the excess bit is discarded.
That sign flip is why saturation is the default for DSP samples. A wrapped sample looks like a full-scale impulse of the opposite polarity. A saturated sample is clipped for one sample and the signal stays bounded.
Where the numbers come from
Fixed point stores a real value as an integer scaled by a power of two. In Q1.15, the stored integer is divided by 32768. So 24576 means 0.75, 16384 means 0.50, and their sum as integers is 40960. That exceeds the signed 16-bit maximum of 32767, so the operation overflows. Scaling is the shift used to bring a wider result back into the chosen format, for example shifting a 32-bit Q2.30 product right by 15 to store it as Q1.15. Saturation is applied after that shift, before the value is narrowed.
Saturating in C
The safe pattern is to widen before the operation, clamp, then narrow. Checking after a 16-bit add is too late because the value has already wrapped.
#include <stdint.h>
static inline int16_t sat_add_q15(int16_t a, int16_t b)
{
int32_t r = (int32_t)a + (int32_t)b;
if (r > 32767) return 32767; /* clamp to +0.99997 */
if (r < -32768) return -32768; /* clamp to -1.0 */
return (int16_t)r;
}The same idea appears in RTL. The adder computes one extra bit, and a mux selects the limit value when that bit shows overflow. That costs a comparator and a mux per adder, which is cheap compared with the cost of a wrapped sample ringing through an IIR filter.
Worked trace
| a (Q1.15) | b (Q1.15) | True sum | Wrapped result | Saturated result |
|---|---|---|---|---|
| 0.75 | 0.50 | 1.25 | -0.75 | +0.99997 |
| -0.75 | -0.50 | -1.25 | +0.75 | -1.0 |
| 0.25 | 0.50 | 0.75 | 0.75 | 0.75 |
The first two rows show the difference. Wrap produces a large error of the wrong sign. Saturation produces a smaller error in the right direction, and the next sample can return to normal immediately.
When wrap is acceptable
Wrap is the intended behaviour only where modulo arithmetic is the point, such as a phase accumulator in a numerically controlled oscillator. For audio samples, filter states, and any value feeding a DAC or a control loop, saturate. If intermediate sums in a filter legitimately exceed the output range, keep the accumulator wider, saturate at that wider width, and scale once at the output. Saturating only the output while the accumulator still wraps leaves the filter state corrupted, so the output can sit at full scale long after the input has recovered.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-91When would you justify adding a single-precision FPU to a battery-powered microcontroller, and what would you check before paying its area and power cost?
The 90-second answer
I would not add an FPU because the algorithm uses floating point in a desktop prototype. I would add it only if the shipped workload, measured on the target process and voltage, cannot meet its throughput, latency or energy budget with fixed point or with a DSP block, and the FPU closes that gap for less die cost and battery cost than the alternatives.
Start with the workload, not the unit. Count operations per second, the required latency for one result, and the numeric range and precision the control loop or estimator actually needs. A single precision FPU in a modern microcontroller typically adds roughly 0.3 to 1.0 mm² in a mature 40 to 90 nm process, plus leakage and dynamic power when it runs, and it forces wider register files, extra bypassing and often a wider load/store path. That cost is paid even if the FPU is idle 99% of the time, unless you clock gate it aggressively and accept wake latency. If the part is battery powered and sleeps most of the time, that leakage and the verification cost for denormals, NaNs, rounding modes and exceptions can dominate.
Then compare three credible implementations on the same algorithm.
| Option | Strength | Weakness | Typical fit |
|---|---|---|---|
| Fixed point Q format on the integer core | No extra area, deterministic timing, good energy per operation | You own scaling, saturation and loss of precision, compiler support is manual | Control loops, filters and sensor fusion with bounded range |
| Software floating point library | Zero hardware cost, full IEEE behaviour if the library provides it | 20 to 100 cycles per operation on a small core, large code size, poor worst case timing | Rare, non urgent conversions and configuration math |
| Single precision FPU with FMA | 1 to 5 cycles per operation, compiler auto vectorisation is simpler, wide dynamic range | Area, leakage, verification, and a second clock and power domain to manage | Sustained floating point throughput, Kalman filters, motor control with wide range |
A worked example makes the decision concrete. Suppose a motor controller at 20 kHz needs a 32 tap FIR plus a Park transform, about 80 floating point multiply accumulates per sample. That is 1.6 million FMA per second. On a 100 MHz Cortex-M0 class core, a software FMA might take 40 cycles, so 64 million cycles per second just for that math, before interrupts and ADC handling. It will miss the 50 µs sample period. A Q15 fixed point version on the same core might take 3 cycles per tap with saturation handling, about 5 million cycles per second, and fits. If the range of the current measurement varies over four decades and the team cannot prove a safe Q format across temperature and fault conditions, the fixed point saving disappears in risk. That is where a small FPU with FMA, clock gated between samples, becomes justified.
Mechanism and failure modes
An IEEE 754 single precision unit stores sign, 8 bit exponent and 23 bit mantissa. The expensive parts are the mantissa multiplier, the alignment and normalisation shifters, and the rounding logic. A fused multiply add computes a*b + c with one rounding, which improves accuracy and saves a pass through the register file. Pipelining that to 3 to 5 stages gives throughput of one result per cycle but adds latency, so a dependent chain of operations still stalls. Denormal handling is the classic trap. If you flush denormals to zero for speed, a filter that decays slowly can stall at a non zero value or lose its decay rate. If you handle denormals in hardware, the worst case timing path grows and the FPU may take extra cycles on rare inputs, which breaks a hard real time budget that assumed one cycle per operation.
Fixed point has its own failure mode. Overflow wraps or saturates, and the error grows when you cascade biquads. I would model the fixed point version in Python or C with the exact Q format, feed it recorded worst case inputs, and check headroom in dB before I rejected the FPU. If headroom is under 6 dB, I would not ship fixed point.
// Q31 multiply with saturation, checked against a float reference in test
static inline int32_t q31_mul(int32_t a, int32_t b) {
int64_t r = (int64_t)a * (int64_t)b; // Q62 result
r = r >> 31; // back to Q31
if (r > INT32_MAX) return INT32_MAX;
if (r < INT32_MIN) return INT32_MIN;
return (int32_t)r;
}When I would say no, and when I would say yes
I would say no for a sensor node that wakes at 1 Hz, does a few dozen floating point operations, and spends its life in stop mode. There the FPU leakage, the extra power domain and the test cost buy nothing. I would say yes for a sustained estimator or a control loop where the FPU lets me run at a lower core clock, for example 48 MHz instead of 120 MHz, and the voltage can drop from 1.2 V to 0.9 V. Dynamic power scales with C * V^2 * f, so that voltage drop can save more energy than the FPU consumes. I would also say yes if the product needs double precision for a short burst and the alternative is a software library that blows the deadline, but I would then check whether a single precision FPU plus a double precision software fallback meets the accuracy spec.
Before tapeout I would require three numbers: cycles per sample at worst case input, energy per sample at the target voltage, and die area including the register file and clock gating logic. If the FPU does not improve at least one of those by a factor that matters to the product, I would keep the integer core and spend the area on SRAM or a small DSP slice instead.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-92Compare RISC and CISC architectures, and how does that choice change the decode, pipeline, area and power trade-offs in the core you design?
The 90-second answer
RISC pushes complexity into the compiler and the pipeline. CISC pushes it into decode and control. That single decision drives most of the core you will draw: how wide the fetch and decode stages are, how many registers you expose, how deep you pipeline, and where verification effort lands.
In a RISC core such as Arm Cortex-M or RISC-V, instructions are fixed length, few in number, and operate directly on registers. The control logic stays small, so you can afford a 3 to 5 stage pipeline, dual issue, and a large register file without the decode logic dominating area. The compiler does the work of scheduling, register allocation and instruction selection, and code size grows because one high level operation becomes several instructions.
In a CISC core such as x86, instructions vary from 1 to 15 bytes, can address memory directly, and can perform a whole sequence such as a string copy in one opcode. Decode must find instruction boundaries before it can do anything else, handle prefixes and ModR/M bytes, and then translate the instruction into micro-operations. That logic is large, hard to verify, and sits in front of the pipeline, so it limits fetch width and clock rate unless you spend area on parallel decoders and a micro-op cache.
For an IC design the trade is not RISC is efficient and CISC is not. Modern x86 cores decode into RISC-like micro-ops and then execute on a wide out-of-order engine, and modern Arm cores add complex instructions for atomics and SIMD. The question is where you pay, in silicon area, in power per task, or in software.
| Dimension | RISC tendency | CISC tendency | IC consequence |
|---|---|---|---|
| Instruction format | Fixed 16 or 32 bit, load-store | Variable length, memory operands | CISC needs length decode before fetch can proceed |
| Decode | One decoder, shallow control | Multi-level decode, microcode or micro-op translation | CISC decode area and verification grow faster with ISA extensions |
| Pipeline | Shorter, easier to keep in order | Deeper front end, often decoupled from execution | RISC reaches a given clock with less front-end buffering |
| Code density | Lower, more instructions per task | Higher, fewer instructions per task | CISC saves instruction cache and flash area, RISC may need larger I-cache |
| Compiler burden | High, relies on scheduling and register allocation | Lower for simple code, still high for vector code | RISC performance depends more on toolchain quality |
What that looks like in instructions
; CISC style: one instruction copies and increments
REP MOVSB ; copy DS:SI to ES:DI, CX times, update SI, DI, CX
; RISC style: the same work is explicit
loop: LDRB R3, [R0], #1
STRB R3, [R1], #1
SUBS R2, R2, #1
BNE loopThe CISC form is compact and the hardware handles the loop, the addressing and the count. The RISC form exposes every step, so the compiler and the branch predictor carry the burden, and the core can pipeline each step at one per cycle.
Decode and pipeline cost, with figures
Take a hypothetical 200 MHz core executing a 10 instruction loop body. A RISC version issues 10 instructions at IPC 1.5, so about 6.7 cycles per iteration plus branch overhead. A CISC version issues 4 instructions, but decode takes 2 cycles to resolve lengths and translate to 10 micro-ops, and the micro-op queue drains at IPC 2. The CISC core wins on fetch bandwidth and I-cache misses, and loses on front-end latency and on the area of the length decoders, which in published x86 designs are a substantial fraction of the front end. If your workload is control code with frequent branches, that front-end latency shows up as bubbles. If your workload is a tight loop over flash, code density wins.
Implications you design for
Area and power follow the front end. A wide CISC decoder with a micro-op cache can burn more power per cycle even when the core is stalled on a cache miss, because decode ran ahead and filled buffers. A RISC core spends that area on the register file, the load-store queue and the branch predictor, which helps IPC on predictable code. For a microcontroller where leakage dominates and the core sleeps 99% of the time, the smaller RISC control logic is usually the safer choice, and the extra flash for larger code is cheap compared with a large decoder that leaks.
Verification follows complexity too. Fixed length RISC decode is a table you can cover with directed tests and formal checks on illegal encodings. Variable length CISC decode has state that depends on every preceding byte, so corner cases multiply, and a bug there can hang fetch with no recovery. That is why many CISC implementations add a slow path for rare instructions and a fast path for common ones, and why the slow path needs its own tests.
Choose RISC when you control the toolchain, need predictable timing and low leakage, and can accept larger code. Choose CISC when code size, existing binaries or a small instruction cache matter more than front-end simplicity, and budget the area and verification for decode. In both cases, measure energy per task at your actual workload, not IPC alone, because a core that finishes in fewer cycles but burns twice the power per cycle has lost.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-93Walk me through the data, control, and structural hazards in a pipelined processor, and how you would mitigate each one in RTL?
The 90-second answer
A pipeline hazard is a situation where the next instruction cannot proceed in the next cycle without risking a wrong result, so the hardware must stall, flush, or reorder work. I classify them by cause, because the fix follows the cause.
Data hazards: an instruction needs a result that an earlier instruction has not produced yet. Control hazards: the next instruction address is unknown, usually after a branch or jump. Structural hazards: hardware needed by two stages at once is present in only one copy, for example one memory port for instruction fetch and data access.
For a classic 5-stage pipeline (IF, ID, EX, MEM, WB) at 200 MHz, the mitigations are forwarding for data, prediction or delayed slots for control, and duplicated or partitioned resources for structural conflicts. Each fix costs area, power, or complexity, so I would not stall for a hazard that forwarding removes in a few gates.
Data hazards: RAW, WAR, WAW
The common case is read-after-write. In ADD R1, R2, R3 followed by SUB R4, R1, R5, SUB needs R1 in ID while ADD writes it in WB. Without help, the compiler inserts a NOP and the pipeline loses a cycle per dependent pair.
Forwarding (bypassing) passes the ALU result from EX/MEM directly to the EX input of the next instruction. That removes the stall for ALU-to-ALU dependencies. A load-use dependency still stalls one cycle, because the data is not available until after MEM, and forwarding cannot create it earlier.
// Forward from MEM stage to EX stage when the register matches
if (MEM_RegWrite && (MEM_Rd != 5'd0) && (MEM_Rd == EX_Rs1))
EX_operand_a = MEM_ALU_result;
else if (WB_RegWrite && (WB_Rd != 5'd0) && (WB_Rd == EX_Rs1))
EX_operand_a = WB_write_data;
else
EX_operand_a = regfile_read_a;WAR and WAW hazards do not occur in a simple in-order 5-stage design with a register file read in ID and write in WB, because instructions stay in order. They appear once you add out-of-order execution, register renaming, or multiple write ports, and then the scoreboard or renaming logic must track them.
Worked trace for LW R1, 0(R2) then ADD R3, R1, R4:
| Cycle | IF | ID | EX | MEM | WB | Action | |---|---|---|---|---|---| | 1 | LW | | | | | | | 2 | ADD | LW | | | | | | 3 | | ADD | LW | | | ADD held in ID | | 4 | | ADD | NOP | LW | | Load-use stall, 1 cycle | | 5 | | | ADD | NOP | LW | Forward MEM result to EX | | 6 | | | | ADD | NOP | |
Control hazards
A taken branch resolves in EX in this design, so the two instructions fetched after it are wrong. Options, in increasing complexity:
- Stall or flush: flush IF and ID on a taken branch. Simple, costs 2 cycles per taken branch. At 20% taken branches, that adds about 0.4 cycles per instruction on average.
- Branch prediction: a 2-bit saturating counter per entry in a small branch target buffer predicts taken or not taken in ID. A mispredict costs the same 2-cycle flush, but the rate drops from 20% to roughly 5% for predictable loops, so the average penalty falls to about 0.1 cycles per instruction.
- Delayed branch slot: the instruction after the branch always executes, which the compiler must fill with useful work. It saves hardware but complicates the compiler and the ISA.
Prediction is the usual choice in a modern core. The cost is prediction tables, recovery logic to restore the correct PC and pipeline state on a mispredict, and careful handling of speculative side effects such as cache misses.
Structural hazards
These come from resource contention, not from data or control flow. Examples: a single-port SRAM used for both instruction fetch and data access, a single multiplier shared by two issue slots, or a register file with one write port and two instructions completing in the same cycle.
Mitigations are duplication, partitioning, or arbitration. A Harvard split (separate instruction and data memories) removes the fetch versus data conflict entirely. For a shared functional unit, an arbiter grants it to one instruction and stalls the other, which is correct but lowers throughput under contention. In a superscalar design I would size the number of ports from the issue width: a 4-wide issue core needs a register file that can sustain 4 reads and 2 writes per cycle, or the file becomes the bottleneck regardless of the ALU count.
Choosing between fixes
Forwarding is cheap and should always be present. Prediction pays for itself when branches are frequent, and its area is modest compared with the performance loss from flushing. Structural duplication pays when the shared resource sits on the critical path every cycle, as with instruction fetch. Where a resource is used rarely, arbitration with a stall is cheaper than a second copy. The failure mode to watch is a fix that hides the hazard in simulation but breaks under a corner case: a forwarding path that misses the load-use case, a predictor that does not flush speculative writes on recovery, or an arbiter that starves a low-priority master. I would check each of those with directed tests before tapeout.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-94What does an out-of-order superscalar core do with a stalled instruction, and why must it still retire instructions in order?
The 90-second answer
An out-of-order superscalar core can execute a later instruction before an earlier one if the later instruction's operands are ready. It still retires instructions in program order. That split is the whole design: execution is flexible, retirement is strict.
Superscalar sets the width. A 4-wide core can fetch, decode and dispatch up to four instructions in one cycle, and it can issue up to four to execution units. Out-of-order sets the order in which those dispatched instructions actually run. If instruction 2 is a load that misses cache and stalls for 100 cycles, instruction 3 and 4 that depend only on registers already ready do not wait for it. They execute, write their results to physical registers, and then wait at retirement until instruction 2 completes.
Retirement stays in order for a practical reason. The architectural register file, exception handling and memory ordering that software observes must match program order. If a younger instruction retired first, a branch mispredict or a fault in an older instruction could not be undone cleanly, and a later instruction could overwrite a register that an older instruction still needed to read as its source.
A concrete trace
| Cycle | Event | Retired |
|---|---|---|
| 0 | I1 load, I2 add, I3 add, I4 store dispatched | none |
| 1 | I1 misses in L1, waits for L2 | none |
| 2 | I3 executes, result held in physical register | none |
| 3 | I4 executes, result held in physical register | none |
| 100 | I1 data returns, I2 executes | none |
| 101 | I1, I2, I3, I4 retire in program order | I1 to I4 |
I2 in this trace depends on I1, so it also waits. I3 and I4 do not. An in-order core would leave I3 and I4 in the pipeline behind I1 and lose those cycles.
What makes it possible, and what it costs
Three structures carry the mechanism. The reorder buffer (ROB) holds dispatched instructions in program order until retirement. Register renaming maps each architectural register write to a fresh physical register, so I3 can write its destination without destroying a value an older instruction still needs. The issue queue wakes instructions when their source operands arrive through the bypass network.
Those structures are the area and power cost. A 256-entry ROB plus a physical register file with several read and write ports is large compared with the small pipeline registers of an in-order core, and the wakeup logic that compares every completing result against waiting instructions switches on speculative work that may later be flushed after a branch mispredict. The payoff is higher instructions per cycle when independent work exists to run during a stall. When code is mostly dependent, the extra structures add area and dynamic power with little throughput gain.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-95How do you quantify branch misprediction cost in a 5-stage in-order pipeline and choose between a larger predictor, speculative fetch, and a deeper pipeline?
The 90-second answer
Branch prediction hides the fact that fetch cannot wait for execute to resolve a conditional branch. Without it, a 5-stage in-order pipeline would stall or flush on every taken branch and lose fetch bandwidth. With it, fetch proceeds down the predicted path and the core pays only when that guess is wrong.
Quantify it as a CPI stack, not as a mispredict rate in isolation:
CPI = CPI_ideal + (branches/instr) x (mispredicts/branch) x (penalty cycles)
IPC = 1 / CPIWorked example, labelled as hypothetical: 20% of instructions are branches, 18% of branches mispredict, penalty is 4 cycles (branch resolves in execute, younger instructions are flushed and fetch restarts), and CPI_ideal is 1.00 for a single-issue in-order core (IPC 1.00).
| Term | Value |
|---|---|
| Mispredicts per instruction | 0.20 x 0.18 = 0.036 |
| CPI added | 0.036 x 4 = 0.144 |
| Total CPI | 1.00 + 0.144 = 1.144 |
| Resulting IPC | 0.87, about 13% below ideal |
Halving the mispredict rate to 9% cuts the added CPI to 0.072 and raises IPC to 0.93. Deepening the pipeline raises the penalty even if the predictor is unchanged: at the original rate, moving the penalty from 4 to 6 cycles adds 0.072 CPI. That is why predictor area can dominate performance, and why pipeline depth and predictor quality have to be traded together.
How the hardware decides
A 2-bit saturating counter is the baseline. It has four states, strongly taken, weakly taken, weakly not taken, strongly not taken, and changes state only on a taken or not-taken outcome. It tolerates a single anomalous outcome without flipping prediction.
// 2-bit saturating counter, checked against a simple trace below
typedef enum logic [1:0] {SNT, WNT, WT, ST} state_t;
module bimodal_counter (
input logic clk,
input logic rst_n,
input logic taken,
output logic predict_taken
);
state_t state;
always_ff @(posedge clk) begin
if (!rst_n) begin
state <= WT;
end else begin
unique case (state)
SNT: state <= taken ? WNT : SNT;
WNT: state <= taken ? WT : SNT;
WT: state <= taken ? ST : WNT;
ST: state <= taken ? ST : WT;
endcase
end
end
assign predict_taken = (state == WT) || (state == ST);
endmoduleTrace for one counter after reset:
| Branch outcome | State before | Prediction | State after |
|---|---|---|---|
| Taken | WT | Taken, correct | ST |
| Not taken | ST | Taken, wrong | WT |
| Not taken | WT | Taken, wrong | WNT |
| Not taken | WNT | Not taken, correct | SNT |
Direction alone is insufficient. Fetch also needs a target. A branch target buffer (BTB) stores the target address for taken branches, indexed by PC. A return stack buffer handles returns, which are poorly predicted by PC history because many call sites return to different addresses. Indirect branches, common in virtual calls and interpreters, need an indirect target predictor or they fall back to a slow path.
| Predictor | What it uses | Strength | Cost and risk |
|---|---|---|---|
| Bimodal, 2-bit counters | PC only | Cheap, fast lookup | Fails on correlated branches |
| Gshare | PC XOR global history | Captures correlation, moderate size | History register must be checkpointed and restored on flush |
| Local history | Per-branch history table | Good for data-dependent branches | Extra table lookup can sit on the fetch critical path |
| Perceptron or TAGE | Multiple tables, weighted history, longest match | Lowest mispredict rate on hard workloads | Large SRAM, more power, longer lookup, harder to verify |
Trade-offs an IC designer has to close
Predictor lookup is on the fetch critical path. A large TAGE table that needs two SRAM accesses can force a lower clock or an extra fetch bubble, erasing its mispredict benefit. Many designs split prediction into a fast first-level predictor for the next cycle and a slower second level that corrects later.
Recovery is the other half. On a mispredict, the core must discard instructions fetched down the wrong path, restore the global history and PC checkpoint taken at fetch, and restart fetch at the correct target. If the checkpoint is wrong, the machine can corrupt architectural state, not just lose cycles. The same flush logic must handle interrupts, exceptions and context switches, which also need predictor state either flushed or tagged by address space identifier, otherwise one process pollutes another process prediction.
Speculative fetch beyond a predicted branch can hide memory latency but it fetches instructions that may never retire. That wastes fetch bandwidth and power, can pollute caches with wrong-path data, and creates a side channel: wrong-path loads can leave cache state that reveals the predicted path. Modern designs restrict speculative loads or track them for security.
For a microcontroller SoC, a 4K-entry bimodal predictor plus a small BTB is usually enough, and the area and leakage saved matter more than the last point of mispredict rate. For a wide out-of-order core, the penalty is larger, branch density in compiled code is higher, and a gshare or perceptron predictor plus a return stack is justified despite the SRAM and the timing work. The decision metric is IPC per watt and IPC per mm2 after the flush and lookup costs, not mispredict rate alone.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-96Walk me through how virtual memory, the MMU, TLB and page tables work on an application processor, and why a bare-metal microcontroller usually skips them?
The 90-second answer
Virtual memory gives each process a private, contiguous view of address space. The CPU emits a virtual address (VA). The MMU translates it to a physical address (PA) that the memory controller and peripherals actually decode. The translation is cached in the TLB. On a miss, hardware or software walks the page tables to refill it.
Assume a 32-bit VA, 4 KB pages, as on ARMv7-A / Cortex-A53 in AArch64 with 4 KB granule. That splits the VA as 20 bits of virtual page number (VPN) plus 12 bits of page offset. The offset passes through unchanged. Only the VPN needs translation.
VA[31:12] = VPN VA[11:0] = offset (unchanged)
PA[31:12] = PPN PA[11:0] = offsetA page table entry (PTE) holds the physical page number (PPN), plus valid, read/write, user/supervisor, cacheability and dirty/accessed bits. A two-level walk uses the top bits of the VPN to index a root table, then a second-level table, then the PTE. ARMv7-A with 4 KB pages and 4 KB sections is a common variant. AArch64 uses up to four levels, but the idea is identical: a tree of tables whose leaves are PTEs.
Worked trace. Hypothetical figures, labelled as such. VA = 0x7F3A_8124, page size 4 KB.
| Step | Value | Action |
|---|---|---|
| 1 | VPN = 0x7F3A8, offset = 0x124 | Split VA |
| 2 | TLB lookup on (ASID, VPN) | Hit: PPN = 0x2B1C4 |
| 3 | PA = 0x2B1C4_124 | Concatenate PPN and offset, send to interconnect |
| 4 | TLB miss instead | Walk page tables, refill TLB, retry |
The TLB is a content-addressable cache keyed by VPN plus an address-space ID (ASID) so a context switch does not flush it. A 64-entry TLB covering 4 KB pages reaches 256 KB. With 2 MB large pages, the same 64 entries reach 128 MB, which is why kernels map DRAM and device memory with large pages. A miss costs a walk of 2 to 4 memory accesses. At roughly 100 cycles per DRAM access, that is 200 to 400 cycles if the walk itself misses cache, against a TLB hit of 1 cycle in the pipeline. That asymmetry is the whole design pressure: keep the working set in the TLB, use large pages for hot regions, and keep page tables in cache.
A page fault is not always fatal. If the PTE is present but not writable, or the page is swapped out, the kernel can fix it and resume the instruction. If no mapping exists, the kernel kills the process. The MMU raises the fault, the OS handler runs, and the faulting instruction is either restarted or skipped depending on the architecture.
Why a bare-metal microcontroller skips it. A Cortex-M0/M3/M4 has no MMU. It has an optional MPU, typically 8 regions, which only checks permissions and region attributes. It does not translate addresses. The core, flash, SRAM and peripherals share one physical address map fixed at design time. That saves the TLB, page table walker, ASID logic and the power and area they cost, and it gives deterministic, single-cycle-ish access timing that firmware and DMA rely on.
| Application processor (Cortex-A) | Microcontroller (Cortex-M) | |
|---|---|---|
| Address translation | MMU + TLB + page tables | None, MPU for protection only |
| Processes | Multiple, isolated, demand paging | Single bare-metal or RTOS image |
| DRAM | External, gigabytes, paged | Internal SRAM, kilobytes to a few MB |
| Determinism | Page faults add unbounded latency | Fixed map, no translation stalls |
| Cost | Walker, TLB CAM, table memory | Address decoder only |
The trade-off shows up in DMA and peripherals. On an MMU system, a device sees physical addresses, so the driver must pin pages, use an IOMMU, or bounce through a contiguous buffer. On a microcontroller, DMA writes directly to the SRAM address the CPU uses. That simplicity is why MMU-less parts dominate where latency and power are tight, and why an MMU appears as soon as you need process isolation, demand paging, or a Linux-class OS. The MPU on Cortex-M is the middle ground: it catches a wild pointer writing to a peripheral, without paying for translation.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-97A CPU writes a 4 KB TX buffer in a write-back cache and starts DMA to send it, but DMA sends stale data: why does that happen, and what must the driver do before ringing the doorbell?
The 90-second answer
The DMA engine reads DRAM, while the CPU writes through a write-back cache. A store from the CPU normally updates the cache line first. The dirty line can stay in cache for a long time before it is written back to DRAM. If the driver rings the DMA doorbell before that write-back happens, the DMA reads the old bytes still in DRAM and sends them.
The fix is to clean the cache lines covering the TX buffer before starting DMA. Cleaning writes each dirty line to the point of coherency, usually DRAM, and leaves the line clean in cache. A data synchronization barrier after the clean guarantees the writes have completed before the doorbell register is written. Without the barrier, the doorbell write can reach the DMA controller while the clean is still in flight.
Worked trace
Assume a 64-byte cache line and a 4 KB buffer at 0x8000_0000. The buffer occupies 64 lines.
| Step | Action | Cache | DRAM | Result |
|---|---|---|---|---|
| 1 | CPU writes new frame to buffer | 64 dirty lines with new data | Old frame | — |
| 2 | Driver writes DMA descriptor, no clean | Descriptor may be dirty in cache | Old descriptor and old frame | — |
| 3 | Driver rings doorbell | Unchanged | Unchanged | DMA starts |
| 4 | DMA reads buffer from DRAM | Still holds new frame | Old frame | Old frame sent |
| 5 | Correct sequence: clean buffer and descriptor, DSB, then doorbell | Lines clean, new data present | New frame and descriptor | DMA reads new frame |
Step 4 is the failure the question describes. The CPU did nothing wrong and the DMA did nothing wrong. Each side saw a different copy because no operation forced the cache copy to DRAM.
Code pattern, Cortex-A with CMSIS
#include "cmsis.h"
#define TX_SIZE 4096u
static uint8_t tx_buf[TX_SIZE] __attribute__((aligned(64)));
static dma_desc_t desc __attribute__((aligned(64)));
void send_frame(void)
{
fill_frame(tx_buf); /* CPU writes through cache */
desc.src = (uint32_t)tx_buf;
desc.len = TX_SIZE;
__SCB_CleanDCacheBuffer(TX_SIZE, tx_buf);
__SCB_CleanDCacheBuffer(sizeof(desc), &desc);
__DSB(); /* clean complete before doorbell */
dma_kick(&desc); /* write doorbell register */
}The descriptor needs the same treatment as the payload. It is often a small struct the CPU just wrote, so it sits dirty in cache while DMA fetches it from DRAM. Cleaning only the buffer leaves a stale descriptor, and the DMA can start with an old source address or length.
Alignment also matters. Clean operates on whole cache lines. If the buffer starts in the middle of a line, that line also contains bytes belonging to another variable. Cleaning it is still safe because clean writes the line out without discarding it. The buffer should still be aligned to the line size, 64 bytes on many Cortex-A parts, so the driver cleans exactly the lines it owns and the size calculation stays simple.
Manual clean versus uncached buffer
| Approach | How it works | Main cost | Best fit |
|---|---|---|---|
| Clean before each transfer | Driver flushes buffer lines to DRAM, then starts DMA | CPU time proportional to buffer size, driver must remember every transfer | Large buffers, DMA used occasionally, CPU processes the data in cache between transfers |
| Place buffer in uncached memory | Buffer region is marked non-cacheable, so CPU stores go straight to DRAM | Every CPU access to the buffer misses cache and goes to DRAM | Small buffers, descriptors, or data the CPU touches once |
For a 4 KB frame sent at, say, 10 Hz, cleaning 64 lines is cheap and the CPU keeps fast cached access while building the frame. For a descriptor touched on every transfer, uncached memory often wins because the clean call overhead exceeds the cost of one DRAM access.
One ownership rule prevents a subtler failure. Once the buffer is cleaned and DMA starts, the CPU must not write the buffer again until the DMA completion interrupt arrives. A second write after the clean creates a new dirty line that DMA will not see, and the transfer sends a torn frame. Double buffering solves this when the producer cannot pause: the CPU builds the next frame in a second buffer while DMA sends the first.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-98What does a watchdog timer do if the processor stops feeding it before the timeout expires?
The 90-second answer
A watchdog timer is a countdown timer that resets the processor if software does not restart it in time. Firmware calls a pet or feed routine regularly during normal operation. Each pet reloads the counter. If the processor hangs, crashes, or stops reaching that routine, the counter reaches zero and the watchdog asserts reset. The processor then restarts from its reset entry point.
That single rule is the whole fault recovery mechanism. The watchdog does not fix the fault. It forces a known starting state so the system can boot again instead of staying hung.
How it behaves in practice
Assume a watchdog timeout of 500 ms and firmware pets it every 100 ms from the main loop. The trace looks like this:
| Time | Event | Counter | Result |
|---|---|---|---|
| 0 ms | Pet | Reloaded to 500 ms | Normal operation |
| 100 ms | Pet | Reloaded to 500 ms | Normal operation |
| 200 ms | Pet | Reloaded to 500 ms | Normal operation |
| 300 ms | Processor hangs in a loop | Counts down from 500 ms | No pet arrives |
| 800 ms | Counter reaches zero | Expired | Watchdog asserts reset |
| 800 ms onward | Processor restarts | Reloaded on boot | Firmware runs from reset entry |
The timeout must be longer than the longest normal gap between pets. If firmware normally pets every 100 ms but a busy period can delay it to 300 ms, a 500 ms timeout gives margin without waiting too long to recover. A timeout that is too short causes false resets during normal work. A timeout that is too long delays recovery after a real hang.
// Checked against typical memory-mapped watchdog registers.
// Pet from the main loop, after real work completes.
void main_loop(void) {
while (1) {
read_sensors();
run_control();
watchdog_pet(); // reloads the watchdog counter
}
}What to watch for
Petting from a timer interrupt can hide a fault. The interrupt may keep firing and petting the watchdog even though the main loop is stuck. Petting from the main loop, after the work for that iteration has finished, catches more faults.
The watchdog clock should keep running when the main processor clock stops. If the watchdog shares the hung clock domain, it may never expire. Many microcontrollers provide a separate low power oscillator for this reason, and the watchdog reset should be recorded in a reset reason register so firmware can tell a watchdog reset apart from a power on reset.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-99Tapeout is in six weeks, you are over power and area, and a customer feature is not verified: how do you decide what to cut, keep, or defer?
The 90-second answer
I would freeze the tapeout contract first, then rank every remaining feature against three numbers: PPA cost, verification closure, and respin risk. A feature that is unverified at six weeks out is not a feature, it is a schedule risk with a mask charge attached. I would protect only what blocks silicon from working: reset, clock, power sequencing, boot ROM, JTAG, SRAM integrity, and the customer interface that was sold as mandatory. Everything else gets cut, fused off, or moved to firmware if the hardware hook already exists.
The decision is not "cut power until we pass." It is which cut buys the most margin per unit of risk. Disabling a clock domain that is 15% of dynamic power and has no timing path to signoff is cheap. Re-architecting a datapath to save 5% is expensive and can break timing closure you already have.
How I rank it
I put each item in a table with the lead architect and the verification owner in the room, not in a spreadsheet after the meeting.
| Item | PPA or schedule cost (hypothetical example) | Closure state | Decision |
|---|---|---|---|
| Boot, reset, PLL lock, SRAM BIST | Blocks all operation | Signed off at SS/TT/FF | Keep, no discussion |
| New DMA burst mode | +0.4 mm², +120 mW at 200 MHz, 3 weeks of verification left | 62% functional coverage, no formal proof of arbitration | Cut or fuse off |
| Clock gating on idle peripherals | -180 mW, +0.05 mm², 2 days to re-run power intent | UPF already models the domains | Keep, do it first |
| Larger SRAM for cache | +1.1 mm², leakage up 22%, yield down | Timing clean, DRC clean | Defer to next revision |
| DVFS point at 200 MHz / 0.9 V | Meets spec, fails power by 25% | STA clean at 80 ps slack | Keep frequency, drop the extra point |
That last row is the typical conflict. If you are 25% over power with no timing slack, you do not chase the last DVFS point. You remove the operating point, or you lower the voltage for the existing point and re-signoff, or you gate the block that only runs in that mode. Chasing all three, frequency, voltage, and a new feature, is how you miss tapeout and still miss power.
Risk management when the date does not move
I use three freeze gates and I make the cost of missing each one explicit.
At feature freeze, any RTL change must name its verification owner and its closure date. If coverage is below the agreed threshold, say 95% of the agreed coverpoints for that block, and the block has no fuse or strap to disable it, it does not go in. A fuse is not a luxury here. One spare fuse per major block, plus a strap to force a safe default, turns a respin into a metal or fuse change in the field for some failures.
At timing freeze, I allow only ECOs that can be re-timed in hours, not days. A metal-only ECO that swaps a via or a cell on a non-critical path is acceptable. A cell-based ECO that ripples placement near the PLL or SRAM macro can invalidate IR drop and electromigration results you already signed off. That is the subtle failure mode: the ECO fixes setup by 120 ps and creates a new EM violation on the power grid that you find after tapeout.
The arithmetic I put in front of management
Label the figures as estimates, but make them concrete. Suppose a respin costs $1.2M in mask and 4 months of schedule, and a slipped customer launch costs more than that in penalty. Then a feature that saves 0.3 mm² but has a 30% chance of forcing a respin has an expected cost of $360k plus schedule risk, before you count engineering time. Cutting it now costs a roadmap conversation. Keeping it costs a coin flip on the mask.
I also quantify the PPA cut the same way. If dynamic power is 1.25 W against a 1.0 W budget at 200 MHz, clock gating that removes 180 mW of idle activity, operand isolation that removes 90 mW of glitch power in the multiplier, and dropping one DVFS point that saves 70 mW gets you to roughly 0.91 W without touching the critical path. That is a defensible plan. "We will optimize later" is not.
What I would say in the room
We keep the silicon working, we cut the unverified feature, we fuse it off if the interface must stay, and we spend the remaining weeks on signoff corners, power intent, and DRC closure. The deferred feature goes on the respin list with its verification plan already written, so the next tapeout does not repeat this argument. If the customer feature is contractual, I escalate with the costed options: pay for the respin risk, accept a fuse-off default, or slip the date. I do not silently absorb an unverified block into a tapeout to avoid that conversation.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-100How would you decide between a metal fix, a firmware workaround, and a respin for a silicon bug found after tapeout?
The 90-second answer
I would not start with the fix. I would start by pinning down the bug: exact trigger condition, affected units and corners, whether it corrupts data or only degrades performance, and whether a workaround exists that customers can ship without breaking their own deadlines. Then I compare three options on the same axes: can it actually implement the correction, what does it cost in mask money and schedule, and what residual risk does it leave in the field.
A metal fix is the middle option. It changes only the top metal layers and vias, so it can reroute nets, repurpose spare gates or filler cells, change a ROM or fuse setting, and add a gate where a spare cell already exists. It cannot change implants, diffusion, or polysilicon, so it cannot create a transistor where the layout has none. That constraint decides most cases before cost does.
| Option | What it can change | Typical cost and time* | Leaves behind |
|---|---|---|---|
| Firmware workaround | Sequencing, straps, fuses, feature disable, driver retry | No mask cost, days to weeks of validation | Errata sheet, performance or power penalty, customer code dependency |
| Metal fix | Metal and via layers, spare-cell logic, ROM/fuse content | Roughly 10-30% of a full mask set, 4-8 weeks plus requalification | New mask revision, still needs full regression on changed nets |
| Respin | Any layer, including implants and poly | Full mask set, 3-6 months to new silicon | Cleanest fix, largest schedule and NRE hit |
*Hypothetical figures for a mature-node SoC, labelled as such. Get the foundry quote and the customer launch date before using them.
Worked example
Suppose silicon hangs the I2C controller when a target stretches SCL for more than 100 cycles, and the hang needs a reset. A firmware workaround polls the bus and resets the peripheral after 200 cycles. That costs a timer interrupt every 200 cycles of stretch, adds maybe 2% CPU at worst-case stretch rates, and fails if the stretch happens while the CPU is in deep sleep. A metal fix could add a timeout counter using a spare gate and a spare counter cell, if the floorplan left them. If no spare cell exists near the I2C block, the metal fix is not available at any price, and the choice collapses to workaround or respin.
The arithmetic matters when volume is high. Say a respin costs $800k in masks and delays launch by 4 months, while a metal fix costs $150k and delays by 6 weeks. If the workaround loses a bid because a competitor can claim a clean errata sheet, the respin may pay for itself. If the part is a low-volume industrial MCU with 20k units a year, the workaround plus a documented errata often wins. I put both numbers in front of product management with the trigger condition attached, because a bug that needs a rare corner case is a different business decision from one that hits every unit at cold temperature.
Firmware workaround, concretely
For the I2C hang, the driver workaround looks like this. The point is that it is testable and bounded, not a vague retry loop.
// Checked against a Cortex-M class core at 100 MHz, hypothetical timing
#define I2C_STRETCH_TIMEOUT_CYCLES 200
static void i2c_poll_stretch_timeout(void)
{
if (i2c_scl_stretched_cycles() > I2C_STRETCH_TIMEOUT_CYCLES) {
i2c_peripheral_reset();
errata_counter[ERRATA_I2C_STRETCH]++;
i2c_replay_last_transfer();
}
}I would also check the failure modes that kill workarounds in the field: the workaround depends on a clock that stops in sleep, it races with DMA, it masks the bug during validation because the test never stretches SCL that long, or it silently drops a transfer instead of replaying it. Each of those pushes the decision toward metal or respin, because a workaround that only works in the lab is worse than no workaround.
Respin becomes the only honest answer when the bug corrupts data with no detectable signature, when it breaks a safety or security property, or when the workaround costs more power or performance than the product can afford. I would say that explicitly, with the measured penalty, rather than letting the schedule decide by default.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.