Skip to content
Tech Interview Prep
Technical interview guide

Power Management & Low-Power Design

The sleep modes, clock strategies, and wake mechanisms that let a battery-powered device run for months or years on a small cell.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: Current Zephyr system/device/runtime PM; CMSIS-Core 6 WFI/WFE; CMSIS-RTOS and FreeRTOS tickless guidance reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-10

Compare integrated clock gating (ICG) and power gating across power reduction, latency, and area, and explain how an ICG prevents output glitches.

Answer

Clock gating and power gating target fundamentally different power dissipation components and impose vastly different latency, area, and state retention overheads.

Architectural Trade-offs

  1. Power Reduction Mechanism:

    • Clock Gating (ICG): Eliminates dynamic power ($P_{dyn} = Α C V^2 f$) by suppressing toggling along downstream clock trees and flip-flop inputs. Static leakage power ($P_{leak} = I_{leak} V_{dd}$) remains unchanged because the logic domain remains fully powered.
    • Power Gating: Cuts off both dynamic power and static leakage by inserting high-threshold sleep transistors (header PMOS or footer NMOS) that disconnect power rails ($V_{dd}$ or $V_{ss}$). Leakage drops by 95% to >99% depending on the off-state subthreshold conduction of the sleep switches.
  2. Latency & Energy Overhead:

    • ICG: Enters and exits gating in 0 to 1 clock cycles with negligible energy penalty (no inrush charging).
    • Power Gating: Wakeup incurs dozens to thousands of clock cycles (microseconds) to sequence daisy-chained sleep switches, manage rail inrush current ($di/dt$), unclamp isolation cells, restore retention registers or re-initialize register state, and reset PLLs.
  3. Area and Physical Implementation Overhead:

    • ICG: Standard cell overhead is localized to the gating cell itself.
    • Power Gating: Requires dedicated power switches, isolation cells (ISO) at power-domain boundaries to prevent floating inputs from causing crowbar current in always-on domains, level shifters (LS), retention flip-flops (RFF), and an active Power Management Unit (PMU) sequence controller.
AttributeIntegrated Clock Gating (ICG)Power Gating (MTCMOS)
Targeted PowerDynamic power only ($P_{dyn}$)Dynamic and static leakage ($P_{dyn} + P_{leak}$)
Exit Latency0 to 1 clock cycle10 to 10,000+ clock cycles (state restoration + rail settle)
Break-Even TimeSub-cycle to single cycleTens of microseconds to milliseconds
Required CellsLatch-based ICG cellSleep transistors, isolation cells, level shifters, retention flops
State RetentionInherent (supply voltage maintained)Requires balloon latches / retention flops or memory save/restore

Glitch Prevention in Clock Gating Logic

Directly AND-ing an unsynchronized enable signal with a clock signal causes clock truncation and spurious output pulses (glitches) whenever the enable changes while the clock is high.

Naïve AND Gating (Hazardous):
CLK   : __/‾\__/‾\__/‾\__
EN    : _____/‾‾‾\______   (Transitions during CLK high)
GCLK  : ________/\________ (Runt pulse / glitch triggers false latching!)

An Integrated Clock Gating (ICG) cell solves this by placing an active-low transparent latch ahead of the AND gate:

                  +--------------+
                  | Latch        |
        EN ------>| D          Q |---> EN_LATCHED --+
                  |              |                  |  +-----+
                  |   LE_n (ENB) |                  +--|     |
   CLK ---+------>| (Active-Low) |                     | AND |---> GCLK
          |       +--------------+                     |     |
          +--------------------------------------------|     |
                                                       +-----+
  1. Latch Behavior: When CLK is low, the latch is transparent (LE_n is active), allowing EN to propagate to EN_LATCHED.
  2. Setup and Hold Window: When CLK transitions from low to high, the latch closes (holds state). Any subsequent transition on EN while CLK is high cannot propagate to the AND gate input.
  3. Glitch Immunity: Because EN_LATCHED is guaranteed stable whenever CLK is high, the output GCLK = CLK & EN_LATCHED cannot produce runt pulses or false edges.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Design and validate low-power behavior for clock gating.

Answer

Assumptions first. A single clock domain feeds a block that has a real idle condition, an idle detector or software-visible clock controller drives the gate, and at least one wake source must keep running. If the wake source shares the gated clock, the design is broken before validation starts.

Core answer. Gate at the finest granularity whose logic shares one idle condition, use an integrated clock-gating (ICG) cell rather than a bare AND gate, drive the enable from a hardware idle FSM or a documented low-power handshake, and keep the wake path on an always-on clock. Validate in three layers: RTL assertions, gate-level simulation with SDF, then silicon current measurement per state.

Why gating causes the hazard. The clock is the only thing that advances a flop. Remove it mid-transaction and the FSM freezes wherever it was: a posted write sits in the write buffer and never lands, a UART shifter stops between the last data bit and the stop bit, a timer counter stops counting. Nothing errors: the block just stops, and the failure surfaces later as a timeout or a framing error.

A handshake fixes this by making the requester wait for the device to drain. On an AMBA Q-Channel, the controller drops QREQn; the device asserts QACCEPTn only once it has no outstanding work and no pending wake, and only then may the clock be gated. QDENY lets the device refuse, and QACTIVE is how it asks for the clock back.

Granularity trade-off.

levelsavingcost
leaf ICG per flop grouphighest, captures short idlesarea, clock-tree synthesis, verification effort
block-level gatecheap, one enablemisses idles shorter than the block's
domain-level (Q-Channel)covers a whole subsystemhandshake latency, more control logic

Clock gating saves dynamic power only; leakage stays. Power gating saves leakage too but costs retention, isolation and a wake latency of hundreds of ns to microseconds, against a couple of cycles for clock gating. Decide on idle duration: if the block idles for less than the power-gating wake cost, gate the clock and leave the domain powered.

Worked arithmetic (hypothetical). A block draws 40 mW dynamic at 200 MHz; the clock tree is 12 mW of that and flop toggling another 8 mW. Idle 85% of the time, gating removes 20 mW during idle, so the average saving is 0.85 x 20 = 17 mW, 42% of the block. Wake costs 2 cycles = 10 ns. At 50k wakes/s that is 0.5 ms/s, 0.05% duty: free. At one wake per 200 ns, gating costs more than it saves.

Failure modes and detection.

failuredetection
write never landsreadback after ungate; AXI BVALID timeout
UART final bit truncatedreceiver framing-error counter
timer stopscompare against an always-on timer
wake source gatedwatchdog; clock-running monitor
glitch on gated clockgate-level sim with SDF; SVA that enable is stable from negedge to negedge

Validation. Assertions: enable stable across the clock high phase, and no gate while a transaction is outstanding. Gate-level simulation with SDF catches hold violations on the enable path. Then measure current in each state on silicon and confirm every wake source still fires.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How do isolation cells and level shifters operate across multi-voltage power domains, and how are their clamp states and rules declared in UPF?

Answer

Across multi-voltage and power-gated designs, isolation cells and level shifters prevent floating inputs and voltage mismatches from causing crowbar current or logic corruption.

Operational Mechanisms

  1. Isolation Cells (ISOs): When a source power domain powers down ($V_{DD} \to 0\text{ V}$), internal CMOS gate outputs float into high-impedance ($Z$) or indeterminate voltage ranges ($V_{SS} < V < V_{DD}$). If connected directly to an active domain, receiving CMOS gates see intermediate voltages that simultaneously turn on both PMOS pull-up and NMOS pull-down networks, drawing destructive static shoot-through (crowbar) current and causing spurious transitions. An isolation cell sits at the boundary, powered by an always-on supply rail ($V_{DD_AON}$). When an active-low or active-high isolation enable (iso_en) asserts prior to power-down, the cell disconnects the floating input and clamps the output to a deterministic logic level (0, 1, or latch/hold).

  2. Level Shifters (LSs): When signals traverse between domains operating at different non-zero voltages (e.g., $0.75\text{ V} \leftrightarrow 1.2\text{ V}$):

    • Low-to-High (L2H): A $0.75\text{ V}$ logic high cannot fully turn off a $1.2\text{ V}$ PMOS gate ($V_{GS} = -0.45\text{ V}$, well above $V_{tp}$). This creates continuous leakage. L2H shifters use dual-rail differential cross-coupled PMOS latches to achieve full rail-to-rail swing.
    • High-to-Low (H2L): Primarily standard inverters/buffers tied to the lower receiver supply rail, guarding against oxide breakdown or input-diode forward-biasing.
    • Enable-Level-Shifter (ELS): Combines isolation clamping and voltage level translation into a single dual-rail standard cell to minimize silicon area and latency.

UPF Intent Specification (IEEE 1801)

In UPF, isolation and level-shifting strategies are bound to power domains, specifying location, clamp values, and control signals:

TCL
# Define Isolation Strategy for Domain PD_CPU to PD_ALWAYS_ON
set_isolation iso_cpu_out \
    -domain PD_CPU \
    -isolation_power_net VDD_AON \
    -isolation_ground_net VSS \
    -clamp_value 0 \
    -applies_to outputs \
    -location parent

# Specify Isolation Control Logic
set_isolation_control iso_cpu_out \
    -domain PD_CPU \
    -isolation_signal pwr_ctrl/cpu_iso_en \
    -isolation_sense high

# Define Level Shifter Strategy between mismatched voltage domains
set_level_shifter ls_cpu_to_soc \
    -domain PD_CPU \
    -applies_to outputs \
    -rule low_to_high \
    -location destination \
    -input_supply_set SS_CPU \
    -output_supply_set SS_AON

Comparison & Failure Boundaries

Interface CellPrimary FunctionActive Supply RailsFailure if OmittedTypical UPF Directive
Isolation Cell (ISO)Clamps unpowered signals to stable stateAlways-On Supply ($V_{DD_AON}$)Crowbar leakage in receiver; spurious logic assertsset_isolation, set_isolation_control
Level Shifter (LS)Translates non-zero voltage thresholdsDual-rail: $V_{DD_SRC}$ & $V_{DD_DST}$DC shoot-through current; incomplete rail swingset_level_shifter
Enable Level Shifter (ELS)Translates voltage and clamps upon shutdownDual-rail: $V_{DD_SRC}$ & $V_{DD_AON}$Both shoot-through and floating rail leakageset_isolation + set_level_shifter

Critical Sequencing and Verification Traps

  • Sequencing Protocol: Isolation enable (iso_en) must be asserted before the domain power switch turns off, and held high until the domain supply stabilizes after power-up. Asserting isolation too late causes instantaneous crowbar spikes across hundreds of boundary receivers.
  • Clamp Selection Bugs: Reset signals must clamp to active-asserted states (typically 0), while ready/valid handshakes (e.g., AXI AWREADY) must clamp low (0) to prevent unpowered domains from falsely acknowledging bus transactions. Clamping to the incorrect polarity hangs system buses.
  • Supply Net Binding: Placing isolation cells inside the child domain (-location self) without dual-rail routing leads EDA tools to tie cell power to the switched rail, causing the isolation cell itself to lose power and float.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

How do voltage level shifters function across multi-voltage power domains, what are the primary circuit topologies, and what timing and sequencing hazards must firmware and hardware coordinate?

Answer

A CMOS input's threshold is a fraction of its own rail, not an absolute voltage. Drive a 0.8 V high into a 1.8 V inverter and the PMOS pull-up never fully cuts off: static crowbar current and a node parked at an indeterminate level. Drive 1.8 V into a gate whose oxide is rated for 0.8 V and you eat the breakdown margin. Both directions need translation, but they are not equally hard: high-to-low is a buffer problem, low-to-high is a contention problem.

Assumptions: unidirectional static-CMOS signals, VDD_L = 0.8 V core, VDD_H = 1.8 V IO, nominal rails unless a corner is named.

Topologies and when each wins

TopologyDirectionStatic currentDelay vs plain bufferPick it when
Inverter on VDD_L, thick-oxide inputsH→L~01–2×default; cheapest
Cascoded / clamped inverterH→L~01.5–2×VDD_H exceeds the thin-oxide rating
Cross-coupled PMOS (ratioed)L→H~0 once settled2–10×unidirectional, low toggle rate, area cheap
Current-mirror / differential cascodeL→Hbias current1.5–3×VDD_L swings widely (DVFS), skew matters
Pass-FET / transmission gateboth~0~1×VDD_H − VDD_L < Vtn, bidirectional
Enable-gated shiftereither~0+ enable delaysource domain can power down

The choice that bites hardest is enable-gated vs always-on. An always-on cross-coupled shifter keeps its input stage tied to VDD_L. If VDD_L collapses, the input floats, the cross-coupled pair sits at its contention point, and the cell both burns crowbar current and can drive the destination to an indeterminate level. An enable-gated cell forces the output to a clamped value and cuts the input stage, at the cost of an enable pin, an extra gate of delay, and a control signal that must be generated in the always-on domain.

Worked trace: cross-coupled low-to-high shifter

Start with In = 0, In_B = VDD_L. NMOS_2 is on, so node B sits at 0; node B is PMOS_1's gate, so PMOS_1 is on and Out = VDD_H; Out is PMOS_2's gate, so PMOS_2 is off. Stable.

Now In rises to VDD_L. NMOS_1 turns on and pulls node A (PMOS_2's gate) down. PMOS_2 starts to conduct and pulls Out up. Out rising turns PMOS_1 off, which releases node A. That is positive feedback: node A falls → PMOS_2 stronger → Out rises → PMOS_1 weaker. The race resolves for the input only if NMOS_1 can hold node A below VDD_H − |Vtp| while PMOS_1 is still fully on.

That ratio is the sizing constraint. Illustrative corner: VDD_L = 0.72 V, VDD_H = 1.98 V, Vtn = |Vtp| = 0.35 V. NMOS overdrive = 0.37 V; PMOS |overdrive| = 1.63 V. Saturation drive scales as (W/L)·Vov², so the pull-down NMOS needs W_N/W_P ≈ (1.63/0.37)² ≈ 19 to win. That is why these cells are wide, slow and asymmetric: the pull-down path is fast, the pull-up path waits on contention.

Timing hazards

  • Delay asymmetry and bus skew. Rise and fall delays differ because the pull-up resolves through contention. On an N-bit bus with one shifter per bit and a shared destination clock, bit-to-bit skew equals the spread in shifter delay. Characterise the cell with both rails as timing arcs and run STA at min-VDD_L/max-VDD_H and the reverse corner.
  • Ramp-time indeterminacy. During power-up the cross-coupled pair can latch either way. Detect with a power-state simulation across PVT that scans the value captured by the destination flop.
  • Crowbar when the source collapses. Detect in UPF/CPF power-state simulation, then on silicon as IDDQ or a rail that will not reach target.

Sequencing and handoff

Power-down of the source domain, in order: (1) assert isolation from the always-on domain so destination-side inputs clamp to 0 or 1; (2) disable the shifter's input stage; (3) ramp the source rail down; (4) assert retention if needed. Power-up is the reverse, and isolation is released only after the source rail is in spec and the shifter output is known. The isolation control itself must come from a domain that never powers down: otherwise you have a chicken-and-egg problem.

A level shifter translates levels; it does not synchronise. Same or related clocks: the shifter alone is enough. Unrelated clocks, single bit: add a two-flop synchroniser in the destination domain. Unrelated clocks, multi-bit: use a handshake or an async FIFO. A bare bus of shifters will capture torn data.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How are power switches implemented and sized when a domain is power gated (header versus footer, coarse versus fine-grained) and how does daisy-chained turn-on control inrush without blowing the wake-up latency or IR-drop budget?

Answer

The 90-second answer. A power switch is a large high-Vth transistor between the always-on rail and the domain's virtual rail. Header switches are PMOS in the VDD path (virtual VDD, VVDD); footer switches are NMOS in the VSS path (virtual VSS, VVSS). Coarse-grained gating wraps one switch network around the whole domain; fine-grained gating distributes switch cells inside the domain, per block or per column. Sizing is set by the on-state IR-drop budget, and turn-on is staged, a daisy chain of enable groups, so inrush stays inside the rail's di/dt limit. Those two requirements fight the wake-up latency budget, and the whole network has to be declared in UPF or power-aware simulation will keep running the domain while it is supposed to be dead.

Header versus footer

Header (PMOS in VDD)Footer (NMOS in VSS)
On-resistance at equal width~2-3x higher (hole mobility)lower, so smaller switch area
Rail integrityVSS stays solid, ground reference cleanVVSS lifts during turn-on; body effect raises Vth and Ron as VVSS rises
Gate drivepull gate to VSS to turn on; needs a level shifter if the controller sits in another domainpull gate to VDD
Where it winsmost SoC domains, especially where ground bounce would corrupt retention or isolation cellsdense arrays where area dominates and nothing in the domain is ground-referenced

Coarse versus fine-grained

Coarse-grained: fewer, larger switches, one control net, low total Ron, small area overhead (a few percent of domain area). Inrush is concentrated, so staging is mandatory. Fine-grained: many small switches interleaved with standard cells, so current enters near the loads and IR drop is flatter; it also enables partial gating of one block. The cost is switch-cell area plus control distribution routing, and each switch adds its own off-state leakage and gate area.

Sizing from the droop budget (illustrative, 0.9 V domain)

Peak on-current 200 mA, droop budget 5% = 45 mV:

Ron_total <= Vdroop / Ipeak = 45 mV / 200 mA = 0.225 ohm unit HVT header PMOS ~ 2 ohm -> N >= 2 / 0.225 ~= 9, use 10 for margin

All ten on at once with 5 nF of domain capacitance: R = 0.2 ohm, RC = 1 ns, peak inrush ~ 0.9 V / 0.2 ohm = 4.5 A. That is the problem. Daisy-chain into 10 stages, one switch per stage, 30 ns apart: the first stage alone limits current to 0.9 / 2 = 450 mA, and each later stage only adds width once the rail has partly charged. Peak inrush drops roughly an order of magnitude; wake latency grows by 10 x 30 ns = 300 ns of staging. More stages means lower di/dt and a longer wake: that is the whole trade.

Power intent

create_power_switch sw_gpu
-domain PD_GPU
-input_supply_port {vin VDD}
-output_supply_port {vout VDD_GPU}
-control_port {sleep_ctrl GPU_PWR_EN}
-on_state {on vin {sleep_ctrl}}
-off_state {off {!sleep_ctrl}}
-ack_port {ack VDD_GPU_ACK {sleep_ctrl}}

The switch is a UPF object, not documentation: the simulator uses its on/off state to collapse VDD_GPU, drive the domain's outputs to X unless isolation clamps them, and gate retention restore. The ack port is what the power controller waits on before releasing isolation: sampling it before the rail settles is a classic bring-up bug.

Failure modes and how they show up

  • Inrush over budget: dynamic IR drop on the always-on grid browns out a neighbouring domain. Caught by dynamic IR-drop/power-grid simulation and on-die droop monitors.
  • Footer ground bounce: VVSS lift shifts the reference for isolation and retention cells, causing false capture. Caught by SPICE of the switch network with the domain decap and retention cell models.
  • Too few stages or undersized switches: functional fail at the slow-hot corner, since Ron rises with temperature. Caught by IR analysis at the worst-case current corner, not typical.
  • Switch missing or mis-modelled in UPF: power-aware sim keeps the domain alive during off and isolation/retention bugs stay hidden. Caught by X-propagation checks asserting the domain goes X when off.

When not to gate: if the domain wakes more often than its break-even time, or must keep state it cannot afford to restore, clock-gate it or use a shallower state instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

How do retention flip-flops (SRPG) work, and how must power-down and restore sequences be orchestrated across power domains?

Answer

The answer in 90 seconds

A retention flip-flop is a normal master–slave DFF on a switchable rail ($VDD_{SW}$) plus a small shadow ("balloon") latch on an always-on rail ($VDD_{AON}$). Before you cut $VDD_{SW}$ you gate the clock, pulse save so the balloon captures the flop's state, and assert isolation on every output leaving the domain. Then you open the power switches. On wake you ramp the switches back, wait for power-good, pulse restore to push the balloon back into the flop, de-isolate, and release the clock. The ordering is the whole game: isolation before collapse, clock gated before save, restore after the rail is stable.

What is actually inside the flop

The functional master–slave pair uses thin-oxide, low-$V_t$ devices for speed and is powered by $VDD_{SW}$. The balloon is a cross-coupled inverter pair (or a second small latch) on $VDD_{AON}$, built from high-$V_t$ devices so its own leakage is small. A retention control: commonly active-low RETN, or a SAVE/RESTORE pair; polarity is library-specific, check the datasheet: drives transmission gates that connect the balloon to the slave node. Retention flops are commonly quoted at roughly 30–50% larger than a plain DFF, and they retain flop state only: latches, SRAM, and analog blocks need their own retention scheme (SRAM retention mode at reduced $VDD$, or a battery-backed rail).

Sequence and ordering constraints

#ActionMust hold before itViolated → what breaks
1Quiesce: stop issuing work, drain outstanding transactions—Domain powers down mid-transaction; state is lost
2Clock gate, wait for the gated clock to actually stopClock controller acknowledgeA clock edge racing the save edge captures a mid-transition value
3Assert save (RETN low)Clock stopped, $VDD_{SW}$ at nominalBalloon captures stale or metastable state
4Assert isolation (ISO_EN) on all outputsBefore step 5Floating inputs on the receiving domain → crowbar current, indeterminate logic
5Assert sleep; header/footer switches open; $VDD_{SW}$ collapsesSteps 2–4 doneBalloon never written; domain state lost
6Wake: de-assert sleep; switches turn on in stages—All-at-once turn-on → $di/dt$ IR drop on $VDD_{AON}$ corrupts balloons
7Wait for power-good$VDD_{SW}$ at nominalRestoring into a ramping rail loses the value or leaves the flop metastable
8Pulse restoreStep 7—
9De-isolateStep 8Consumers latch garbage
10Release clock gatingStep 9—

Two constraints that bite in multi-domain SoCs. First, inputs need clamping too: an always-on driver holding a high into a powered-down domain forward-biases the input ESD diode and back-powers $VDD_{SW}$. Second, a domain can only be powered down once every domain that consumes its outputs has isolated them: the PMU sequences domains in dependency order, not in parallel.

Expressing it in UPF

TCL
# UPF (IEEE 1801). Exact syntax varies by tool version.
create_power_domain PD_CPU -include_scope

create_power_switch sw_cpu -domain PD_CPU \
  -output_supply_port {vout VDD_SW} \
  -input_supply_port  {vin  VDD_AON} \
  -control_port       {sleep ctrl_sleep} \
  -on_state  {on  vin {!ctrl_sleep}} \
  -off_state {off {ctrl_sleep}}

set_retention ret_cpu -domain PD_CPU \
  -retention_power_net VDD_AON -retention_ground_net VSS
set_retention_control ret_cpu -domain PD_CPU \
  -save_signal    {RETN low} \
  -restore_signal {RETN high}

set_isolation iso_cpu -domain PD_CPU \
  -isolation_power_net VDD_AON -clamp_value 0 -applies_to outputs
set_isolation_control iso_cpu -domain PD_CPU \
  -isolation_signal ISO_EN -isolation_sense high -location parent

-location parent places the isolation cell in the always-on parent domain, so it still clamps when PD_CPU is dead. Level shifters (set_level_shifter) are required on every signal crossing $VDD_{SW}$ ↔ $VDD_{AON}$.

Why retention flops instead of save/restore to SRAM

Worked example, labelled hypothetical: a 50,000-flop domain at 1 GHz.

  • Retention flops: 1 cycle save + 1 cycle restore = 2 ns of sequencing.
  • Serial scan to a retention SRAM at 1 bit/cycle: 50,000 cycles = 50 µs out, 50 µs in.
  • Even at 32 bits/cycle: 1,563 cycles ≈ 1.6 µs each way, ~3.1 µs round trip.

So retention flops buy roughly three orders of magnitude of wake latency, at 30–50% more flop area. In practice the wake latency is dominated by the power-switch ramp (hundreds of ns to a few µs, set by switch sizing and on-die decap), not by the restore pulse, which is why daisy-chained switches matter more than restore timing.

Failure modes to name

  • Back-powering: always-on driver into a dead domain; detect by measuring $VDD_{SW}$ during sleep. It should sit near 0 V, not at $VDD_{AON} - V_{diode}$.
  • Balloon leakage: high-$V_t$ still leaks; if $VDD_{AON}$ is itself gated or droops, state is lost. $VDD_{AON}$ must be a true always-on rail.
  • Inrush $di/dt$: all switches closing at once drops $VDD_{AON}$ enough to corrupt balloons in other domains. Detect with on-die droop monitors; fix with staged switch groups.
  • Isolation asserted too late: downstream domain sees floating inputs and burns crowbar current. Detect as elevated $I_{DD}$ in the receiving domain during the sleep window.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate low-power behavior for retained state.

Answer

Assumptions. An MCU with a VBAT-backed retention domain (backup registers or retained SRAM), a reset-cause register, and a brownout detector (PVD/BOR). Retained state is small: tens to hundreds of bytes: calibration constants, a boot counter, pairing keys. Not a filesystem.

Core answer. Treat retained RAM as untrusted input, not as memory. Every boot, before anything reads it: read the reset cause, then validate a self-describing record (magic, schema version, length, CRC-32) and use it only if all four pass. Otherwise run fallback initialization. Commit in the order payload → header → CRC last, so a power loss mid-write leaves a CRC mismatch rather than a plausible-looking half-record.

Why it works: uninitialized retention RAM is not zeroed. It holds whatever the last powered domain left, which after a cold POR or a VBAT droop is arbitrary. A magic word alone only proves some firmware wrote here once; it does not prove the bytes are intact or from this schema. The CRC is what turns "bytes exist" into "bytes are the ones we wrote." Writing the CRC last makes the commit atomic from the reader's point of view: the record is valid exactly when the CRC matches, and the CRC is the last field to become correct.

C
// C11, arm-none-eabi-gcc 13.2, STM32F4 (20 x 32-bit backup regs = 80 B)
typedef struct {
    uint32_t magic;    // 0x52535431
    uint16_t version;  // schema
    uint16_t len;
    uint32_t seq;      // boot counter
    uint8_t  payload[48];
    uint32_t crc;      // CRC-32 over magic..payload
} retained_t;

bool retained_load(retained_t *r) {
    if (r->magic   != 0x52535431)      return false;
    if (r->version != SCHEMA_VERSION)  return false;
    if (r->len     >  sizeof r->payload) return false;
    return crc32((uint8_t *)r, offsetof(retained_t, crc)) == r->crc;
}

Trace of a torn write: retained RAM holds a valid record, crc = 0xABCD. Firmware begins a commit, overwrites the payload bytes, then VDD collapses before the crc store. Next boot: magic matches, version matches, but CRC over the new payload ≠ 0xABCD → retained_load returns false → fallback init. The half-written record is never accepted.

Trade-offs.

choicecostdeciding criterion
CRC-16-CCITT vs CRC-32~2x cycles; 64 B ≈ 0.8 µs at 80 MHzCRC-16 residual 2^-16, CRC-32 2^-32; use CRC-32 once the record exceeds a few hundred bytes
backup registers vs retained SRAM80 B @ ~1 µA vs KBs @ ~1–2 µAregisters if state fits in tens of bytes and must survive VBAT; SRAM if you need KBs and can keep the retention domain powered
single copy + CRC vs A/B copies2x space, 2x commit timeA/B if losing state means re-provisioning (keys, calibration); single copy if defaults are cheap

Validation.

  • Brownout: programmable supply ramping VDD through the PVD threshold at 1 V/ms and 10 V/ms; assert the PVD ISR commits before BOR, and after recovery the record is valid-old or fallback. Never accepted-corrupt. 1000 ramps.
  • Retention across resets: 10^4 sleep/wake cycles; the retained boot counter must increment exactly once per cycle and CRC pass rate must be 100%.
  • Fault injection: corrupt one random byte before each reset; expect the fallback path every time, counted on a non-retained counter or UART log.
  • Torn write: GPIO-triggered reset at a random delay inside the commit loop; expect zero accepted-corrupt records.

Failure modes.

  • Torn update: CRC mismatch on load; cost one fallback init (~ms).
  • Stale pointer: never store raw pointers; store offsets/IDs and range-check on load.
  • Wrong schema: version mismatch; migrate or discard.
  • Secret lifetime: keys outlive the intended window across reset; keep a key-epoch counter in retained state and zeroize on epoch change; verify by reading the region after reset.
  • Attacker-controlled warm reset: reset cause is untrusted input; re-run every security check on each boot regardless of cause.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design and validate low-power behavior for power states.

Answer

Core answer (first 90 seconds)

Assume a coin-cell sensor node: Cortex-M4 at 80 MHz, one sensor sample per second, radio off, CR2032 (220 mAh) with a 2-year target. That fixes the budget: 220 mAh / 17,520 h ≈ 12.6 µA average, and every decision below is made against that number.

Design: run in Stop 2 between samples, not Standby. Stop 2 keeps SRAM and the RTC alive at ~1.1 µA and wakes in ~5 µs; Standby drops to ~0.3 µA but loses SRAM and needs a full boot. The 0.8 µA Standby saves per second is dwarfed by the ~10 µA·s a 2 ms re-init costs at 5 mA: re-init would have to finish in under 0.16 ms to break even. So Stop 2 wins, and the deciding criterion is re-init energy versus leakage saved, not the headline sleep current.

Validate by measuring, not by reading the datasheet: a Joulescope or Nordic PPK2 on the supply, average current over ≥100 duty cycles, a GPIO toggle on wake into a scope for latency, and a canary pattern in SRAM to prove retention.

State table (figures are datasheet-typical for an STM32L4-class part; treat as illustrative)

stateretainedpoweredclockswake sourceslatencymin residency
Activeallcore + SRAM + periphPLL 80 MHz———
Stop 2SRAM, RTC, backup regs1.2 V domainMSI 4 MHzRTC, EXTI, LPUART~5 µs~10 µs
Standbybackup regs onlybackup domainLSI/LSEWKUP pin, RTC~50 µs + boot~1 ms

Minimum residency matters: wake before the regulator and oscillator settle and you pay the wake cost without doing useful work, so net energy goes up.

Failure modes and how each is detected

  • Marketing name mismatch: "Stop 2" in the datasheet, the reference manual, and the HAL enum can select different oscillator sets. Wrong pick → wake latency ~10× expected. Detect: measure latency; tens of µs instead of single-digit means the wrong mode.
  • Silicon revision: errata are revision-specific. Read the errata sheet for the exact die revision (e.g. "rev Y"), not the family. Detect: reproduce on the actual part. A bench unit on another rev won't show it.
  • SRAM bank lost: some modes power down a subset of banks; a DMA buffer or stack in a lost bank corrupts on wake. Detect: write a known pattern before sleep, checksum after wake.
  • Oscillator restart: running before the PLL/oscillator ready flag is set gives UART baud errors and flash timing violations. Detect: poll the ready flag; scope the first instruction after wake.
  • Undocumented erratum / floating pins: an unused GPIO left as a floating input oscillates and adds µA. Detect: sleep current above datasheet typical → bisect by configuring unused pins as analog or output-low.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design and validate low-power behavior for energy model.

Answer

Assumptions. A battery-powered node with a duty-cycled MCU and a radio, a fixed reporting interval, and a lifetime target in years. If the design is dominated by one always-on load (a display, a heater) skip the model and measure that load directly.

Core answer. Build a state-and-transition energy model, E = Σ Pᵢ·tᵢ + Σ E_trans, with every current measured at the battery terminal, then validate it by integrating a current trace against the model per phase, not in aggregate. The model predicts duty cycles you have not built yet; the trace tells you which term the model got wrong. Aggregate comparison hides exactly the error you care about.

Mechanism. The model is a list of states (sleep, active, radio TX, sensor conversion) each with a current and a residence time, plus the transitions between them. Transitions are not free because the hardware pays to leave and re-enter: RC oscillator startup and PLL lock on wake, radio ramp from idle to TX, regulator settling after a load step. Those costs are short and large, so they vanish in a 60-second average and dominate a 20-millisecond active window. That is why the model needs both terms and why validation has to be phase-aligned.

Worked model (hypothetical figures, 3.0 V rail, one 60 s cycle):

Python
# hypothetical figures, 3.0 V rail
states = [  # (name, current_A, time_s)
    ("sleep",  20e-6, 60.0),
    ("active",  4e-3, 15e-3),
    ("tx",      8e-3,  3e-3),
    ("wake",  1.5e-3,  2e-3),
]
V = 3.0
E = sum(I * t for _, I, t in states) * V
print(E * 1e6, "uJ/cycle")   # 3861.0 uJ/cycle
phasecurrenttimechargeshare
sleep20 µA60 s1200 µC93.2%
active4 mA15 ms60 µC4.7%
tx8 mA3 ms24 µC1.9%
wake1.5 mA2 ms3 µC0.2%

Total 1287 µC per cycle → 21.45 µA average → 5.3 years on a 1000 mAh cell. Note what the model just told you: at a 1-in-3000 duty cycle, sleep is 93% of the charge and the radio is under 2%. "The radio dominates" is an assumption, not a fact: the model is what decides it.

Validation. Toggle a GPIO at each phase boundary so the firmware's state is visible in the trace, then capture current with a profiler that samples at ≥10 kHz (Nordic Power Profiler Kit II, Joulescope JS110) and integrate I(t)·V per phase. Compare phase by phase. If the model says 20 µA sleep and the trace says 23 µA, that 15% error is a 14% lifetime error, because sleep carries 93% of the charge, so validate the dominant term first and to the tightest tolerance. Validate the wake edge by zooming the trace at the GPIO rising edge and integrating just that window against the model's E_trans.

Trade-offs. Datasheet summation is faster and needs no hardware, but it omits board leakage and every transition cost, so it is only good enough to pick an architecture. Pure measurement is ground truth but cannot predict an unbuilt design or sweep duty cycles. Model-plus-spot-validation is what I would ship. Do not build the full state model when one load dominates: measure that load and stop.

Failure modes, with detection.

  • Average hides burst. A 21 µA average can conceal a 15 mA peak that browns out a coin cell. Detect by checking peak against the cell's max pulse current, measured with a high-bandwidth profiler, never a multimeter.
  • Regulator loss omitted. LDO quiescent and DC-DC efficiency at microamp loads are real terms. Detect by measuring at the battery terminal, not the MCU rail; the difference is the regulator.
  • Transition energy omitted. Detect by integrating the wake edge alone and comparing to E_trans.
  • Instrumentation burden. An attached debugger or UART keeps the MCU out of deep sleep. Detect by measuring with the debugger detached and diffing the two traces.
  • Duty-cycle drift. Retries and missed ACKs raise the real cycle rate. Detect by logging actual cycles over 24 h and re-running the model with the measured rate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design and validate low-power behavior for break-even time.

Answer

Core answer (first 60–120 seconds). Break-even time is the idle duration at which the energy saved by entering a low-power state equals the energy spent entering and leaving it. Per state:

T_be = E_transition / (P_active − P_sleep)

Gate the sleep on predicted idle exceeding T_be plus the wake latency, with a guard band for prediction error. Then validate against measured rail energy, not the datasheet.

Assumptions. Single Cortex-M4 at 80 MHz, 3.3 V rail, tickless kernel, idle predictor = moving average of interrupt inter-arrival times.

Derivation. Active current 12 mA → 39.6 mW. Stop-mode current 20 µA → 66 µW. Entry+exit energy 7 µJ (regulator settle, RC-oscillator startup, flash wake). P_saved = 39.6 − 0.066 ≈ 39.5 mW, so T_be = 7 µJ / 39.5 mW ≈ 177 µs. Wake latency is 20 µs, so schedule Stop only when predicted idle ≥ 177 µs + 20 µs, and only if the deadline slack covers the 20 µs.

stateI_stateE_transitionT_bewake latency
Run12 mA———
Sleep (WFI)4 mA0.5 µJ19 µs1 µs
Stop20 µA7 µJ177 µs20 µs
Standby2 µA40 µJ1.0 ms2 ms

Standby is the trap: its 2 ms wake latency exceeds its 1.0 ms break-even, so latency binds before energy does. Pick the shallowest state whose T_be fits the predicted idle.

Validation. Measure the rail with a Joulescope or Nordic PPK2, not the datasheet. Log predicted vs actual idle per wake and the wake reason. If measured energy per wake exceeds the model, the transition energy is underestimated: usually regulator settle, which datasheets omit. Build an idle histogram: if most sleeps land below 2×T_be, the predictor is thrashing.

Failure modes and detection.

  • Oscillation: predictor flips between Run and Stop; detect via a transitions-per-second counter, fix with hysteresis and a minimum sleep duration.
  • Early wake: an interrupt fires before the predicted idle; detect by comparing actual to predicted idle per wake.
  • Leakage vs temperature: Stop-mode leakage roughly doubles every 10–15 °C, so 20 µA at 25 °C becomes ~200 µA at 85 °C and T_be rises ~10×; detect by correlating rail current with die temperature.
  • Deadline miss: the 20 µs wake eats slack; count deadline misses per state and demote the state when the count is nonzero.

Trade-offs. Deeper states save more per microsecond but cost more to enter and exit and wake slower, so the deciding criterion is predicted idle versus T_be + latency, not the lowest current. Alternatives: tickless idle versus a fixed tick (a 1 kHz tick wakes you every 1 ms, above Stop's break-even but below Standby's), and DVFS versus sleep. DVFS cuts active power but does nothing for idle, so they compose rather than compete.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design and validate low-power behavior for idle policy.

Answer

Core answer

Idle policy is a prediction with a safety constraint, not a lookup. On each idle entry you predict the time to the next event, then choose the deepest idle state whose exit latency fits inside that prediction and whose energy break-even is met. The prediction is never trusted on its own: device PM QoS latency constraints, scheduler wakeup latency, and pending timers veto states that are too deep. You validate by measuring residency, wakeup-latency p99 and power against a workload with known timer patterns, not by reading the governor source.

Mechanism

The decision has four inputs: predicted idle duration, per-state exit latency, per-state entry+exit energy, and the minimum latency constraint from devices and the scheduler. With NOHZ_IDLE the tick is stopped, so the next timer event is the dominant input. The governor (Linux menu or teo; teo models the timer wheel directly, which handles timers armed after the decision better) computes the prediction, filters states by exit_latency <= min(constraint, predicted), then picks the lowest-energy survivor. Prediction error is asymmetric: too short wastes energy on a deep entry, too long misses deadlines.

Worked trace

Platform with three states (figures illustrative):

stateexit latencyentry+exit energypowerbreak-even
C12 µs~0200 mW—
C390 µs20 µJ5 mW~100 µs
C6300 µs200 µJ1 mW~1 ms

Break-even = entry+exit energy / power saved: C3 = 20 µJ / 195 mW ≈ 100 µs; C6 = 200 µJ / 199 mW ≈ 1 ms.

Predicted idle 800 µs, device PM QoS constraint 200 µs. C6 fails both the latency filter (300 > 200) and break-even (1 ms > 800 µs). C3 passes both. Choose C3.

Actual wakeup at 150 µs: C3 costs 5 mW × 150 µs + 20 µJ = 20.75 µJ; C1 costs 200 mW × 150 µs = 30 µJ. C3 still wins. Actual wakeup at 60 µs: C3 = 20.3 µJ, C1 = 12 µJ. C1 wins. That is the cost of a short-direction misprediction.

Validation

Trace with ftrace: enable power:cpu_idle, timer:timer_start, irq_handler_entry; read per-state usage and time under /sys/devices/system/cpu/cpu0/cpuidle/stateN/. Measure wakeup latency with a periodic CLOCK_MONOTONIC timer, reporting p50/p99, and power with RAPL (/sys/class/powercap/intel-rapl:0/energy_uj). Run three workloads: fixed-period (1 ms tick), bursty, and adversarial (timer armed then cancelled).

Failure modes and detection

  • Timer reprogrammed after the decision: the chosen state is now too deep. Detect by ordering timer_start against cpu_idle in the trace; watch wakeup-latency p99.
  • Veto ignored: chosen state's exit latency exceeds the PM QoS constraint. Detect by asserting state.latency <= pm_qos_resume_latency_us at entry and logging violations.
  • Race with new work: a task wakes between prediction and entry, so the entry is wasted. Detect by counting irq_handler_entry within a few µs of cpu_idle; a high rate means the prediction is racing the scheduler.
  • Stale latency constraint: a cached constraint is used after the device updated it. Detect with a version counter on the constraint and a mismatch log.
  • Multicore: a package state needs all cores idle; one busy core blocks it, or a deep per-core state adds package exit latency for the others. Detect by comparing per-package residency against per-core residency.

Trade-offs

teo over menu when timers are armed after idle entry; menu is fine for steady periodic load. A static "always C1" policy is trivially safe and wastes the power budget. Hardware autonomous selection (Intel HWP, AMD CPPC) moves the decision into the CPU: less software control, harder to validate, but lower entry overhead. Decide on the wakeup-latency SLA: below ~100 µs, cap at C1/C3; with slack, allow C6.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design and validate low-power behavior for WFI semantics.

Answer

Assume a Cortex-M class MCU (ARMv7-M or ARMv8-M), bare metal or an RTOS idle loop, and the real question: does the core actually sleep, and does it wake for the right reason?

WFI is a hint, not a command. The architecture permits the core to keep executing. What it does is suspend execution until a WFI wakeup event: per the ARMv7-M ARM, an enabled exception with sufficient priority to be taken, a debug entry request, or reset. Whether that becomes a clock-gated Sleep or a regulator-off Deep Sleep is decided by SLEEPDEEP in the System Control Register (SCR, 0xE000ED10), not by WFI. So the shape of the code is: program SCR, arm the wake source, DSB, WFI, then re-check work in a loop, because WFI can return without any handler having run.

Alternatives, and what decides between them

  • WFI vs WFE. WFI wakes on an interrupt and takes the handler. WFE wakes on an event (SEV, or a pending interrupt if SEVONPEND is set) and need not take a handler. Use WFE when a peer core or DMA is signalling and you do not want handler overhead.
  • Sleep vs Deep Sleep. SLEEPDEEP=0 keeps the clock domain alive: wake in a handful of cycles, but mA. SLEEPDEEP=1 gates clocks and often the regulator: wake in microseconds to tens of microseconds, µA, and SRAM/peripheral state may be lost unless retention is configured. The deciding criteria are wake-latency budget and average current, not preference.
  • Tick vs tickless. SLEEPONEXIT=1 re-enters sleep on exception return; that is what makes tickless idle work without a wakeup per tick.

Why it matters, with hypothetical numbers. A 3.3 V part drawing 8 mA active and 2 µA in deep sleep, 20 µs to wake. A 1 kHz tick: (20 µs × 8 mA + 980 µs × 2 µA) / 1 ms ≈ 162 µA average. Tickless at 100 ms: (20 µs × 8 mA + 99.98 ms × 2 µA) / 100 ms ≈ 3.6 µA. Roughly 45×. That gap is why this gets validated rather than assumed.

Failure modes, each with how you catch it

  • Masked wake source. With PRIMASK set and the only wake source masked, the exception is not "enabled and of sufficient priority to be taken", so it is not a WFI wakeup event: the core sleeps until reset or debug. Catch it with a watchdog, and scope a GPIO toggled immediately before WFI.
  • Spurious return. WFI returns with no handler run (debug event, already-pending event). Count WFI entries against ISR entries; if they diverge over a soak, the re-check loop is wrong.
  • Missing barrier. WFI is not a memory barrier. A store to the NVIC or a peripheral may not be visible before sleep. DSB before WFI, ISB after. Symptom: intermittent missed wake under load.
  • Debug attached. With a debugger connected the core may not enter deep sleep. Symptom: bench current is higher than production.

Validation procedure

  1. Measure supply current with a µA-capable meter or a shunt plus scope, and compare against the arithmetic above.
  2. Toggle a GPIO before WFI and in the ISR; scope the duty cycle to confirm the sleep fraction.
  3. Instrument counters for WFI entries and ISR entries and assert they match across a soak.
  4. Run three negative tests (PRIMASK set, debugger attached, wake source disabled) and confirm each gives the documented outcome rather than a hang.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design and validate low-power behavior for WFE semantics.

Answer

Assume a Cortex-M33 (ARMv8-M Mainline) at 64 MHz, single core, with a peer core or DMA that can signal work, and an idle loop that must drop core current between items. The question is which wait primitive to build the loop on, and how to prove it actually sleeps.

Core answer. WFE is the right primitive when the wake source is an event, not an interrupt. The event register is a one-bit latch per PE. WFE: if the latch is set, clear it and return immediately. No sleep; if clear, enter the low-power state and stay until a wake-up event. Wake-up events are SEV from any PE, exception entry or exit, a debug event, and, with SEVONPEND set in the SCR, an interrupt entering the pending state even when that interrupt is disabled.

Design:

C
/* Cortex-M33, ARMv8-M, CMSIS */
__SEV(); __WFE();          /* clear a stale latch without sleeping */
for (;;) {
    while (ring_empty(&q)) __WFE();
    process(ring_pop(&q));
}

Producer, on the peer core or in the DMA completion path:

C
ring_push(&q, item);
__SEV();                   /* sets the latch on every PE */

The condition test is the authority; WFE is only a hint to sleep. WFE can return for reasons that have nothing to do with your queue (a debug event, an unrelated SEV, an exception exit) so the loop must re-test.

Trade-offs.

primitivewakes oncost per wakeuse when
WFESEV, exception entry/exit, debug, pending IRQ if SEVONPENDno vector fetch, no stackingproducer is a peer PE or a peripheral that can assert an event
WFIany interrupt becoming pending, PRIMASK ignoredfull exception entry: stacking + vector fetchthe wake source already has an NVIC line and you want the ISR
interrupt-driventhe interrupt itselfsame as WFIwork is tiny and latency must be deterministic

Choose WFE when the producer cannot raise your NVIC line (a peer core, a DMA, a mailbox) and you want to keep the exception path free. Choose WFI when a peripheral already owns an interrupt and the ISR is where the work belongs.

Failure modes.

Stale latch. An unrelated SEV or a previous exception exit leaves the latch set, so WFE returns immediately and the loop spins at full current. Detect it by measuring sleep duty cycle: if the core never enters the low-power state, the latch is being set spuriously. The __SEV(); __WFE(); prologue clears it once.

Lost wake-up. The producer sets the condition and issues SEV between the consumer's test and its WFE. The latch saves you (SEV sets it, so WFE returns immediately) but only if the producer actually issues SEV after every state change. A producer that only writes a flag sleeps the consumer forever. Detect with a timeout on the idle loop.

Thundering herd. SEV is a broadcast: it sets the latch on every PE. One item wakes all N waiters; N−1 re-test, find nothing, and sleep again. Detect by counting wake-ups against items processed. ARMv8-M has no targeted SEV, so either accept the herd or give each core its own mailbox.

Debug event. Halting debug entry and exit set the latch, so attaching a probe makes the loop spin. Expected, not a bug, but it invalidates any current measurement taken with the probe attached.

Validation. Toggle a GPIO on WFE entry and exit and scope the duty cycle against a known event rate. Inject SEV from the peer core at random offsets relative to the consumer's test and assert every item is processed exactly once. Issue SEV with no work and confirm the loop returns to sleep within one iteration. Disable an interrupt, make it pending, and confirm WFE still wakes with SEVONPEND set. For current: on a Cortex-M33 at 64 MHz, Sleep mode drops core current from roughly 4 mA running to roughly 1.5 mA (illustrative figures. Measure your own part), so a 10% duty cycle at a 1 kHz event rate is where the saving actually shows up.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design and validate low-power behavior for lost wakeup.

Answer

Clarify and assume. Single-core Cortex-M4F (STM32L4 class), FreeRTOS 10.5 with tickless idle, producer is a UART DMA-complete ISR that posts a task notification, consumer is a task blocked on that notification. The failure: the task checks for work, finds none, and the ISR fires before the sleep instruction retires. The interrupt is serviced, the flag is set, and the core then sleeps with work pending. It wakes only on the next unrelated interrupt, so latency goes from microseconds to the next tick or worse.

Design. Close the window by making the check and the sleep atomic with respect to the producer. On Cortex-M, WFI wakes on any NVIC-enabled interrupt even when PRIMASK=1, so mask, check, sleep, unmask:

C
__disable_irq();                 // PRIMASK = 1
if (work_pending(&q) == 0) {
    __WFI();                     // wakes on a pending IRQ even while masked
}
__enable_irq();                  // pending IRQ is taken here

The producer's ISR can land in three places: before __disable_irq (flag set, check sees it, no sleep), between mask and WFI (interrupt latched pending in the NVIC, WFI returns immediately), or after __enable_irq (taken at once). No window remains. The mask lasts a handful of cycles, so the added worst-case IRQ latency is roughly 10-20 cycles at 80 MHz, well under a microsecond.

Alternatives. WFE with the event register is the hardware latch: the producer executes __SEV() after setting the flag, and a prior SEV makes WFE return immediately, so no masking is needed. Lower latency, but it only works if every producer path issues SEV, and the event register is not a substitute for reading the flag. FreeRTOS tickless idle wraps the same idea in the kernel: portSUPPRESS_TICKS_AND_SLEEP calls eTaskConfirmSleepModeStatus() inside a critical section and reprograms the tick before sleeping. Prefer it over a hand-rolled WFI, because it also bounds the sleep to the next timer expiry. Don't use local masking when the producer is on another core or another chip: masking your own PRIMASK does nothing for a remote doorbell, and you need a memory barrier plus a shared flag instead.

Failure modes and detection.

  • Interrupt unmasked too late (enabled after WFI): symptom is a hang that only appears under load. Detect with a counter incremented when the flag is set immediately after WFI returns without an ISR having run.
  • Flag cleared after the producer set it: a read-modify-write race loses the item. Detect by comparing posted against consumed counts.
  • Memory ordering on multicore: the flag write must be visible before the doorbell, so use a release store (__atomic_store_n(..., __ATOMIC_RELEASE) or DMB). Symptom is a rare hang on the second core only.
  • Custom idle bypassing the scheduler: a driver WFI skips tick reprogramming, so the sleep is unbounded. Detect with a watchdog and a tick counter that stops advancing.

Validate. Sweep the producer's phase across the check-sleep window: a hardware timer injects the UART ISR at delays from 0 to 50 µs in 1 µs steps, 10k iterations each, and assert the consumer never sleeps with work pending. Then measure current. STM32L4 datasheet typicals are about 10 mA in run at 80 MHz and about 1.1 µA in STOP2 at 3.3 V, so a lost wakeup that forces a full tick-rate wake shows up as a step from microamps to milliamps on the supply rail. Finish with a 24 h soak, watchdog armed, confirming the posted and consumed counters match.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and validate low-power behavior for asynchronous resume.

Answer

Core answer (first 90 seconds)

Assume Linux 6.x, a driver for a device that is runtime-PM managed and can also wake the system, and a resume path entered either by the driver (pm_request_resume()) or by the device's own interrupt. The rule: a resume request is not a resume. pm_request_resume() and pm_runtime_get() return before ->runtime_resume has run, so no register access is legal until completion is observed. I make completion observable (the PM core already keeps dev->power.completion, the completion dpm_wait() waits on) and I admit register access only through a runtime-PM reference taken at the point of use, never at request time. Validation is forcing the race and showing the reference closes it.

Why it behaves this way

runtime_status in sysfs is one of unsupported, active, suspended, suspending, resuming, error. suspending and resuming are software bookkeeping, not hardware states: the device is either powered or it is not. Gating register access on "not suspending" is therefore wrong; gate it on "resume completed", which is what taking a reference gives you.

The core coalesces concurrent requests: pm_request_resume() sets power.request_pending/power.request and schedules one work item, so two requests produce one ->runtime_resume. Ordering comes from dpm_wait_for_superior(), a child's callback does not start until its parent's completion fires, and async_synchronize_full() at the end of dpm_resume() is the barrier that says all async resumes are done.

Admission table

callsleeps?takes a ref?starts a resume?
pm_runtime_get_sync()yesyesyes, waits
pm_runtime_resume_and_get()yesyes, dropped on erroryes, waits
pm_runtime_get()noyesqueues
pm_request_resume()nonoqueues
pm_runtime_get_if_in_use()noonly if already activeno

The code

C
/* probe, before device_add() */
device_enable_async_suspend(&pdev->dev);
pm_runtime_set_autosuspend_delay(&pdev->dev, 200);   /* ms */
pm_runtime_use_autosuspend(&pdev->dev);
pm_runtime_set_active(&pdev->dev);                   /* on out of reset */
pm_runtime_enable(&pdev->dev);

static irqreturn_t foo_hard_irq(int irq, void *data)
{
        struct foo *f = data;
        pm_runtime_get(f->dev);      /* atomic; queues resume, no sleep */
        return IRQ_WAKE_THREAD;
}

static irqreturn_t foo_thread(int irq, void *data)
{
        struct foo *f = data;
        int ret = pm_runtime_resume_and_get(f->dev);  /* 5.10+ */
        if (ret)
                return IRQ_NONE;
        val = readl(f->base + FOO_STATUS);   /* safe: resume completed */
        ...
        pm_runtime_mark_last_busy(f->dev);
        pm_runtime_put_autosuspend(f->dev);
        return IRQ_HANDLED;
}

The hard handler must not read registers: it can run while runtime_status is resuming. pm_runtime_get() is atomic-safe; pm_runtime_resume_and_get() sleeps, so it belongs in the threaded half.

Validation

CONFIG_PM_DEBUG gives /sys/power/pm_test; writing devices makes a suspend stop after the device phase and resume immediately, exercising the resume path without a real S3. CONFIG_PM_ADVANCED_DEBUG gives power/async (toggle async_suspend at runtime), power/runtime_status, power/runtime_usage, power/runtime_error, power/runtime_suspended_time. Trace with power:device_pm_callback_start / power:device_pm_callback_end and check no register access lands between them.

Failure modes and detection

  • First access lost. A hard IRQ reads config space while the device is in D3hot; PCIe returns 0xffffffff for the vendor ID. Detect: runtime_status is resuming at the access, and ftrace shows the read between callback start and end.
  • Two resumes. Driver request plus wakeup IRQ. The core coalesces them, but a driver-side "resume in progress" flag can double-complete. Detect: runtime_usage drifts from the number of live references.
  • Callback never returns. dpm_wait() uses wait_for_completion() with no timeout, so one hung ->resume hangs system resume forever. Detect: khungtaskd, default hung_task_timeout_secs = 120.
  • Parent not ready. Calling pm_runtime_get_sync() on a child from the parent's resume path deadlocks against dpm_wait_for_superior(). Detect: lockdep; parent runtime_active_kids is 0 while the child is active.
  • Leaked reference on error. pm_runtime_get_sync() fails and the error path skips pm_runtime_put(), so usage_count stays elevated and the device never autosuspends. Detect: runtime_usage stays > 0 and runtime_suspended_time stops climbing. pm_runtime_resume_and_get() exists to remove this class.

Trade-off

Async resume turns system resume from the sum of device times into the longest dependency chain: 40 devices at 15 ms each is ~600 ms synchronous versus ~60 ms if the deepest parent-child chain is four devices (illustrative). You pay in ordering enforced by completion waits rather than code order, and in interleaved traces. Don't enable async_suspend for a device whose resume depends on another device's resume unless that dependency is a parent-child link: the core only orders what the device tree says. Autosuspend delay is the other knob: too short and you thrash, too long and you lose the power; 100 ms–2 s is the usual band, set per device from measured idle gaps.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design and validate low-power behavior for frequency scaling.

Answer

What I'd say in the first 90 seconds

Assume a Linux SoC: the CPU cluster clock comes from a PLL, the core rail is set by an external PMIC over I2C, there's an OPP table of validated (frequency, voltage) pairs, and at least one peripheral whose protocol depends on a clock. The design is three rules and one invariant.

Rule 1: an operating point is a pair, never a frequency. You pick from the vendor's OPP table and never run a frequency at a voltage below its paired minimum.

Rule 2: ordering. Going up: raise voltage, wait for it to settle, then raise the clock. Going down: lower the clock, then lower the voltage. The reason is that the maximum frequency a transistor can switch at is a function of its supply voltage. Raise the clock first and the core runs above the timing limit of the current voltage for the whole regulator settle window: a silent timing violation, not a clean failure.

Rule 3: serialize and confirm. One transition at a time, and don't switch the mux onto a PLL until its lock bit reads locked.

The invariant: the timebase and any clock-dependent peripheral protocol must not be derived from the scalable PLL, or must be re-divided inside the same critical section as the switch.

The ordering, in code

C
/* up: voltage first, wait for settle, then clock */
regulator_set_voltage(core, opp->uV, opp->uV);
udelay(regulator_set_voltage_time(core, old_uV, opp->uV));
clk_set_rate(cpu_clk, opp->hz);
while (!(readl(pll_base + PLL_STAT) & PLL_LOCK))   /* SoC lock bit */
        cpu_relax();

/* down: clock first, then voltage */
clk_set_rate(cpu_clk, opp->hz);
regulator_set_voltage(core, opp->uV, opp->uV);

regulator_set_voltage returns when the PMIC acknowledges the I2C write, not when the rail has settled; the slew is what regulator_set_voltage_time covers. Skip that wait and the clock goes up while the rail is still climbing.

What breaks, and how you'd see it

failuremechanismdetection
flash wait statesflash can't be read at the new clock without more wait states, so the core fetches garbage. On an STM32F4, 168 MHz needs 5 wait states at 2.7–3.6 Vhard fault or corrupted instruction stream; the latency field must be programmed before the switch, not after
PLL unlockmux switched before lock, so the core runs on a drifting clockhang or random faults; poll the lock bit with a timeout and fall back to the old rate
serial corruptionthe UART divisor was computed from the old clock, so baud is off by the ratioframing/overrun bits in the UART status register; scope TX
tick driftclocksource derived from the scalable PLLclocksource watchdog / NTP drift; use a fixed-rate timer: the ARM generic timer's CNTFRQ is independent of the CPU clock
deadline misstransition latency lands in the wakeup pathcyclictest max latency while a thread hammers the frequency; ftrace cpu_frequency
concurrent transitiontwo callers race on the same PLL and regulatorlockdep, clk-core WARN; serialize with a mutex

The trade-off that decides the design

Dynamic power scales as C·V²·f. Halving frequency from 1.2 GHz/1.0 V to 600 MHz/0.9 V gives (0.9/1.0)² × (0.6/1.2) = 0.405: about 60% less dynamic power. But if the work takes twice as long, energy is 0.405 × 2 = 0.81, only 19% saved. So frequency scaling saves energy only when the work doesn't stretch proportionally; for a bursty workload, race-to-idle at the top OPP and then idle beats sitting at a low OPP. And a transition costs roughly 10–100 µs, dominated by regulator settle, so rate-limit: transitioning faster than that spends more energy in the PMIC than it saves.

Validation

  • Frequency: read back the achieved rate (/sys/kernel/debug/clk/clk_summary) and compare to the requested OPP. A mux that silently ignores the request is common.
  • Voltage: PMIC register readback plus a scope on the rail, to confirm the settle wait is long enough.
  • Latency: cyclictest with a background thread forcing transitions at the rate limit; the max latency is your deadline budget.
  • Energy: a shunt (INA226) or power analyzer, joules per fixed workload, at each OPP.
  • Stress: transition at max rate for hours under load, then check dmesg for WARN/lockdep and confirm no missed deadlines.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and validate low-power behavior for tickless time.

Answer

Assumptions I'd state first. Cortex-M4 class MCU, 32.768 kHz LSE crystal, RTOS with tickless idle enabled (FreeRTOS configUSE_TICKLESS_IDLE, Zephyr CONFIG_TICKLESS_KERNEL), 1 kHz tick, sleep windows from 10 ms to 10 s, wake sources are an RTC compare, a GPIO, and a UART RX.

Core answer. The tick is not the time base. SysTick on Cortex-M is clocked from the core clock, which is gated in STOP/deep sleep, so it stops counting the instant you enter the low-power state. Time has to come from a timer that keeps running: the RTC (32-bit seconds plus prescaler, e.g. STM32L4) or a low-power timer (16-bit LPTIM on STM32L4, 24-bit RTC on nRF52). Tickless means you suppress the periodic tick, program one wake at the next deadline, and on wake reconstruct elapsed ticks from the counter delta.

Three things make that correct.

Wrap-safe delta. Counters wrap; unsigned subtraction does the right thing if you mask to the counter width:

C
/* 24-bit down-counter (nRF52 RTC, Cortex-M SysTick) */
static inline uint32_t elapsed(uint32_t start, uint32_t now)
{
    return (start - now) & 0xFFFFFFu;   /* wrap is free in unsigned math */
}

Trace: start = 0x00000010, now = 0x00FFFFF0. start - now = 0xFF000020; masked = 0x000020 = 32 counts. At 32.768 kHz that is 976.6 µs. The counter physically decremented 16 steps to zero, one wrap step, then 15 more: 32. Correct.

Maximum interval. A 24-bit counter at 32.768 kHz wraps every 2^24 / 32768 = 512 s. If the next deadline is further out you cannot program it in one shot; you chain wakeups or fall back to the RTC's 32-bit seconds. A 16-bit LPTIM at 32.768 kHz wraps every 2 s: fine for sub-second windows, useless for a 30 s poll.

Calibration. LSE is ±20 ppm at 25 °C, worse over temperature. 20 ppm is 1.7 s/day. If you need wall-clock accuracy, calibrate LSE against a TCXO or the host clock and store the correction.

Early wake. A GPIO or UART can fire before the programmed compare. On wake, read the counter and compute remaining = deadline - now; never subtract the interval you programmed, or you lose the early-wake delta.

Failure modes and how I'd catch each.

failuremechanismdetection
off-by-one tickelapsed computed as now - start vs now - start + 1sleep 1000 × 1 ms, compare total against a TCXO reference; a constant N-tick offset shows up
counter wrap24-bit wraps at 512 s24 h soak, log (start, now, elapsed), assert elapsed < 2^24
timer stops in deep stateSysTick gated in STOP2toggle a GPIO in the wake ISR, scope actual vs requested sleep
rounding accumulates10 ms at 32.768 kHz = 327.68 ticks, truncated to 327 → 0.021 ms lost per sleep100,000 sleeps = 2.1 s drift; compare RTC seconds to a monotonic host clock over 24 h
ISR latency double countedreading the counter after the ISR and also adding a fixed ISR costinstrument with DWT->CYCCNT, assert measured == counter delta

Trade-offs. Tickless idle (suppress only when idle) keeps the tick for timeouts and is a one-line config change; full tickless (Linux NO_HZ_FULL, Zephyr CONFIG_TICKLESS_KERNEL) removes every periodic wakeup but needs a oneshot timer and exact accounting. RTC is 32-bit and cheap but coarse; LPTIM is finer but draws more. Choose by the deepest sleep state: if the core clock is gated, SysTick is out; RTC for windows over a second, LPTIM below.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate low-power behavior for deadline constraints.

Answer

Assumptions. Linux 6.x on a quad Cortex-A53 gateway, battery powered. One periodic job every 100 ms that must complete within 20 ms and takes 8 ms of CPU at 1.2 GHz, plus asynchronous sensor interrupts. The SoC exposes WFI, cluster power-down, CPU-off (MCPM) and suspend-to-idle.

Core answer. The deadline sets an exit-latency budget; the power policy is whatever deepest idle state fits inside that budget with margin. Budget = 20 ms deadline − 8 ms work = 12 ms. I set the PM QoS constraint to 3 ms rather than 12 ms, because exit latency is a distribution and I want p99.9 headroom, then let the cpuidle governor pick the deepest state under it.

Mechanism: hold /dev/cpu_dma_latency open with 3000 written to it (microseconds) for the whole job window. That registers a PM QoS request; the cpuidle governor compares each state's exit latency against it and refuses anything deeper. Closing the fd releases the constraint. The governor also skips states whose target residency exceeds the predicted idle duration, so a 92 ms idle window is what actually makes the deep states reachable.

statetarget residencyexit latency typ / p99power
WFI03 µs / 10 µs250 mW
cluster power-down1 ms200 µs / 600 µs60 mW
CPU-off (MCPM)5 ms1.2 ms / 3 ms15 mW
suspend-to-idle20 ms6 ms / 12 ms8 mW

With the 3 ms constraint, S2I is excluded and CPU-off is the deepest reachable state. Job completion becomes 3 ms exit + 8 ms work = 11 ms, leaving 9 ms of margin against the 20 ms deadline.

Trade-offs. The idle window is 92 ms. CPU-off costs 15 mW × 92 ms = 1.38 mJ; S2I costs 8 mW × 92 ms = 0.736 mJ. That 0.64 mJ per cycle is 6.4 mW average: real, but it buys a p99 exit of 12 ms that consumes the entire slack, so one late wake per thousand cycles is a missed deadline. The rule flips when slack exceeds roughly 20 ms: a 500 ms job period with the same 8 ms of work makes S2I the right default and the constraint unnecessary.

DVFS is the other half. At 400 MHz the 8 ms job becomes 24 ms and misses the deadline before any idle state is considered, so the frequency floor is set by the deadline, not by energy. Idle-state depth is where the energy comes from; frequency is where the deadline is defended.

Failure modes and detection.

  • Constraint released early. A client closes the cpu_dma_latency fd before the job finishes; the governor immediately drops into S2I. Detect with ftrace pm_qos_update_target and power:cpu_idle events, and assert constraint-held duration ≥ job window.
  • Wake source not armed. The timer IRQ is not a wakeup source, so the SoC sleeps past the deadline. Detect via /sys/kernel/debug/wakeup_sources: check active_count and last_change for the timer.
  • Transition variance. Datasheet typicals are not p99.9. Histogram measured exit latency from ftrace timestamps and compare p99.9 against slack, not the typical.
  • Urgent asynchronous event. A high-priority sensor IRQ lands during a deep state and inherits the wake path. Measure IRQ-to-thread latency with cyclictest and the irqsoff tracer.
  • Clock stabilization excluded. Datasheet exit latency usually stops where the core can execute; it excludes PLL relock and regulator ramp, which add tens to hundreds of microseconds on this class of part. Measure wake IRQ to first instruction at target frequency.

Validation. Run the real workload with the constraint in place, record chosen state per idle window, and gate on p99.9 job completion < 20 ms plus energy per job from an external INA219-class monitor. A policy that passes on typicals and fails on p99.9 is not validated.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate low-power behavior for DMA boundaries.

Answer

Clarify and assumptions. I'll take a non-coherent DMA master on an ARM64 SoC running Linux 6.x, a dmaengine client driver, and both runtime PM and system suspend in play. "Low-power boundary" is the point where the DMA controller's clock and power get gated. The invariant that has to hold across it: no descriptor in flight, device writes visible to the CPU, CPU writes visible to the device, and no completion IRQ that can fire after teardown.

The ordering is the design. Quiesce, drain, cache maintenance, then power down: never the reverse. Each step exists because the one before it doesn't imply it.

  • Quiesce: stop submitting new descriptors. dmaengine_terminate_sync() terminates the channel and blocks until it is idle; dmaengine_terminate_async() returns immediately and is the usual source of the late-write bug. Use the sync form in a suspend path, and note it can sleep, so not from atomic context.
  • Drain: the engine may still have posted writes sitting in a write buffer. On ARM64 a dsb sy after reading the channel status orders that read ahead of anything that follows, so you don't gate the clock while a write is still on the bus.
  • Cache maintenance: on a non-coherent device, dma_sync_single_for_cpu() invalidates the buffer so the CPU sees device writes; dma_sync_single_for_device() cleans it so the device sees CPU writes. If the buffer came from dma_alloc_coherent(), the mapping is already non-cacheable and there is nothing to do here.

Trade-offs. Coherent allocation versus streaming mapping. dma_alloc_coherent() hands you uncached memory: no manual maintenance, no alignment trap, but every CPU access is slow, so it's wrong for a buffer the CPU touches per transfer. dma_map_single() plus explicit sync keeps the buffer cached and fast for the CPU, at the cost of getting the sync direction and alignment right at every boundary. The deciding criterion is whether the CPU reads or writes this buffer on the hot path: a descriptor ring the CPU rarely touches wants coherent; payload the CPU processes wants streaming with sync.

Failure modes and how each is detected.

failuremechanismdetection
late DMA writeclock gated while a write is still postedread channel status/residue and confirm idle before gating; assert it
dirty data lostinvalidate before cleanchecksum the buffer across the boundary
partial cache linebuffer not 64-byte aligned, invalidate drops adjacent dirty dataassert addr % 64 == 0 && len % 64 == 0 in debug builds
IRQ after teardowncompletion callback fires after free_irq()dmaengine_terminate_sync() guarantees no callback after it returns; free the IRQ after that
stale descriptor on resumedescriptor memory freed while suspended, channel resumes and reads itdon't free descriptors across suspend; re-init the channel on resume

Validation. The test is a suspend with a transfer in flight. Start a transfer, immediately trigger runtime PM autosuspend (or echo mem > /sys/power/state), resume, then check the buffer contents and dmesg for oops. The assertion that makes it a test rather than a hope: before terminating, dmaengine_tx_status() must not report DMA_IN_PROGRESS for the outstanding cookie, and after dmaengine_terminate_sync() returns the residue must be zero. Run it under KASAN so the IRQ-after-teardown case faults instead of corrupting silently, and with ftrace dma_* events to see the ordering.

C
/* Linux 6.x, dmaengine client, non-coherent ARM64 */
static int mydev_suspend(struct device *dev)
{
    struct mydev *d = dev_get_drvdata(dev);

    mutex_lock(&d->lock);
    d->suspended = true;                 /* stop new submissions */

    if (d->cookie) {
        /* contract: returns only when the channel is idle */
        dmaengine_terminate_sync(d->chan);
        d->cookie = 0;
    }

    /* coherent buffers need nothing here; streaming buffers do */
    dma_sync_single_for_cpu(dev, d->dma_addr, d->len, DMA_FROM_DEVICE);

    mutex_unlock(&d->lock);
    return 0;
}

On resume the mirror image applies: re-init the channel, then dma_sync_single_for_device() before the first new transfer, so the device never reads a stale cached line.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate low-power behavior for watchdog in sleep.

Answer

Assumptions. STM32F4-class MCU, Stop mode (core clock stopped, LSI and RTC alive), and a requirement that a firmware hang during sleep eventually resets the part. Which clock domain survives the mode decides the watchdog.

Core answer. Use the IWDG, not the WWDG. The IWDG counts on the LSI, which keeps running in Stop mode, so it keeps counting with the CPU halted. The WWDG is clocked from PCLK; when the APB clock stops in Stop mode the WWDG stops counting and can never fire. In Standby the VDD domain is powered down and the IWDG is not clocked either: it cannot supervise Standby.

Sizing: T = 4 × 2^PR × (RLR + 1) / f_LSI. PR=6 selects /256 (PR=7 is also /256; PR=4 is /64: a common misread). RLR=4095 gives 4 × 256 × 4096 = 4,194,304 LSI cycles:

f_LSItimeout
17 kHz (datasheet min)247 s
32 kHz (nominal)131 s
47 kHz (datasheet max)89 s

The F4 datasheet gives LSI 17–47 kHz, a 2.8× swing. Design against the fast end: the guaranteed minimum timeout is 89 s, not 131 s.

C
/* STM32F4, CMSIS. Register offsets per RM0090. */
#define IWDG_UNLOCK 0x5555u
#define IWDG_START  0xCCCCu
#define IWDG_RELOAD 0xAAAAu

static void iwdg_init(void)          /* 131 s nominal, 89 s worst case */
{
    IWDG->KR = IWDG_START;           /* LSI on, counter running */
    IWDG->KR = IWDG_UNLOCK;          /* open PR/RLR for writing */
    IWDG->PR = 6u;                   /* /256 */
    IWDG->RLR = 4095u;
    while (IWDG->SR & (IWDG_SR_PVU | IWDG_SR_RVU)) { }  /* wait for sync */
    IWDG->KR = IWDG_RELOAD;          /* load RLR, restart countdown */
}

static inline void iwdg_feed(void) { IWDG->KR = IWDG_RELOAD; }

Two designs:

  • No-feed. If the sleep window is shorter than the worst-case-fast timeout (60 s sleep vs 89 s minimum), never feed during sleep. Lowest power, but detection latency is up to 131 s and a hung wake handler is not caught.
  • Supervised wake. The RTC wakeup timer (LSE 32.768 kHz, ±20 ppm) wakes the core every 5 s, the handler feeds the IWDG, the core returns to Stop. Set WUCKSEL=100 (ck_spre, 1 Hz) and WUT=4 for a 5 s period. IWDG at PR=3 (/32), RLR=14999 → 32 × 15000 = 480,000 cycles → 15.0 s at 32 kHz, 10.2 s at 47 kHz. Worst-case margin over the 5 s wake period is 5.2 s.

Trace of the supervised design, handler hangs at the first wake (32 kHz nominal):

teventIWDG count
0.000 swork done, feed, enter Stop0
5.000 sRTC wakeup, handler starts160,000
5.000 shandler hangs, no feed160,000
10.000 sRTC wakeup, nothing runs320,000
20.000 scount reaches 480,000 → reset480,000

The same 480,000 counts is reached at 15.2 s on a 47 kHz LSI and 28.2 s on a 17 kHz one, so detection latency after the last feed is 10.2–28.2 s. Either way the hang is caught within one timeout, not never.

Cost of supervised wake: 200 µs of core at ~1 mA every 5 s = 200e-6/5 × 1 mA = 40 nA average, negligible next to the RTC and LSI keep-alive current (datasheet-dependent, order 1 µA). No-feed is simpler and lower power but blind during sleep; supervised wake costs a little average current and code complexity for a bounded detection latency.

Failure modes and detection.

  • Sleep reset loop. Timeout shorter than the sleep window, or LSI faster than assumed → reset, boot, sleep, reset. Detect by reading IWDGRSTF in RCC_CSR on every boot and counting in an RTC backup register:
C
static uint32_t boot_count(void)
{
    uint32_t iwdg = (RCC->CSR & RCC_CSR_IWDGRSTF) ? 1u : 0u;
    RCC->CSR |= RCC_CSR_RMVF;        /* clear all reset flags */
    return iwdg;
}

Trace: boot 1 → IWDGRSTF set, backup reg 0→1; boot 2 → set, 1→2; boot 3 → set, 2→3. A counter climbing every cycle with IWDGRSTF set each time is the signature; a one-off is just a reset.

  • Feed-before-sleep hides a stall. Feeding on a timer just before WFI leaves the watchdog fresh even though the work never finished. Feed only after the work is confirmed complete.
  • Oscillator tolerance. The 17–47 kHz spread is a 2.8× timeout swing. Measure LSI against LSE at boot and compute the real timeout.
  • Locked configuration. IWDG_PR/IWDG_RLR are write-protected once started; unlock with 0x5555, start with 0xCCCC, reload with 0xAAAA. Configure before starting or you need a reset to change the window.
  • Reset-cause misread. IWDGRSTF, POR and software reset share RCC_CSR; read and clear the flags or you blame the wrong source.

Validation. Force a hang in the sleep path and confirm a reset lands inside the expected window; toggle a GPIO at each feed and measure the period on a scope. Measure LSI against LSE to bound the timeout. Measure average current in Stop with the IWDG running and stopped. Run 24 h and count boots in the backup register: zero unexpected boots is the pass condition.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and validate low-power behavior for radio duty cycling.

Answer

Core answer. Duty cycling is a budget problem, not a tuning problem. Pick the fraction of time the radio is on from the latency the application tolerates, then prove energy per delivered event: average current hides everything that matters. I'd assume a battery end device (coin cell or AA), a star or small mesh of ≤100 nodes, and a latency budget in seconds, not milliseconds. Design order: choose the MAC class first, because it fixes the duty cycle more than any parameter you tune afterwards. Validate with a coulomb counter for energy and a packet sniffer for the on-air trace, then soak under injected loss.

Mechanism. Average radio current is (on-time fraction × active current) + (sleep fraction × sleep current). Three MAC classes cover most designs:

  • Scheduled: IEEE 802.15.4 TSCH (802.15.4e): 10 ms timeslots, channel hopping, a node wakes only in its assigned slots. Duty cycle well under 1%, paid for with time sync and a guard time.
  • Asynchronous wake-and-check: ContikiMAC: the receiver wakes on a fixed cadence (8 Hz, i.e. 125 ms, by default) and listens for a strobe; the sender repeats the packet until ACKed. Duty cycle is set by the wake rate.
  • Connection-oriented: BLE: the connection interval fixes the wake cadence and each connection event carries a few packets.

LoRaWAN Class A is a fourth shape: two receive windows at 1 s and 2 s after each uplink, with the transmit side capped by regulation (EU868 default sub-band, 1% duty cycle).

Worked arithmetic (illustrative). BLE peripheral, connection interval 100 ms, 2 ms per connection event, radio 5.3 mA TX / 5.4 mA RX, sleep 1.5 µA with the RTC running. Duty cycle = 2/100 = 2%. Average = 0.02 × 5.3 mA + 0.98 × 0.0015 mA ≈ 0.108 mA. On a CR2032 (~200 mAh usable at this drain) that is ~1850 h ≈ 77 days. Halve the interval to 50 ms: 4% duty, ≈ 0.213 mA, ~39 days. Life is linear in wake rate: that is the whole trade.

Clock drift. The listen window must cover relative drift since the last sync. Two ±20 ppm crystals give 40 ppm relative: over a 1 s wake interval that is 40 µs, irrelevant. A ±500 ppm internal RC oscillator over the same interval is 500 µs, so the strobe or guard time must be extended by that much. This is why TSCH resynchronizes on every enhanced beacon, and why a preamble-sampling sender sizes its preamble from the receiver's worst-case drift, not its nominal wake interval.

Failure modes and detection.

FailureMechanismDetectCost
Reconnect stormCoordinator reboots; every node rejoins at once, radio ~100% onjoin attempts/min per nodeminutes at full power; flattens a coin cell
Missed beaconsDrift exceeds guard time → resync loopmissed-beacon counter, resync rateenergy/hour spikes
Buffer overflowParent holds indirect frames only for macTransactionPersistenceTime (802.15.4 default 0x1F4 = 500 superframe durations ≈ 7.68 s at 250 kbps)dropped-frame counter at the parentsilent downlink loss
Retry amplification30% PER with 3 retries ≈ 3× radio energy per delivered frameretransmit counter, energy per delivered bytelinear energy blowup
Keepalive pins the radioMQTT keepalive (client-chosen; 60 s in most libraries) forces a PINGREQ within 1.5× keepalive, so max sleep < keepalivewake count/hour vs. sensor events/hourduty cycle set by protocol, not by sensing

Validation. Two instruments: a current profiler / coulomb counter (Nordic PPK2, Otii Arc) for energy per event, and a sniffer (802.15.4 or BLE) for the on-air trace. Then soak 24–72 h with an attenuator and noise source forcing loss, recording p99 join time, missed-beacon rate, and energy per delivered uplink. Average current alone will not show the reconnect storm.

When not to duty cycle. Mains-powered gateways, closed-loop control under ~10 ms, or any node where sensor warm-up dominates the radio: there the radio is not the budget, and duty cycling only adds latency.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate low-power behavior for battery model.

Answer

Clarify and assume. Battery-powered device with a pulsed load. I'll pin the system and say the numbers move if yours differ: single-cell Li-ion, 3.7 V nominal, 2000 mAh, protection cutoff 3.0 V; a 3.0 V MCU rail fed by an LDO with 250 mV dropout at peak; a radio drawing 2 A for 5 ms every 10 s; 20 µA sleep; operating range -10 to +45 °C.

Core answer. Model the load profile, not the capacity. The naive runtime is 2000 mAh / (1 mA average + 20 µA) ≈ 82 days, and it is wrong because the binding constraint is instantaneous voltage, not charge. Two mechanisms decide it.

Pulsed-load stranding. Terminal voltage is OCV minus I·ESR. A cell is ~80 mΩ at 25 °C but ~250 mΩ at -10 °C. At 2 A that is a 0.5 V sag, so a cell sitting at 3.75 V OCV presents 3.25 V under pulse and trips the cutoff. The charge between 3.0 V and 3.75 V OCV is still in the cell: it is stranded, not consumed.

Regulator dropout vs. cutoff. The LDO needs Vin ≥ 3.0 + 0.25 = 3.25 V. That is above the 3.0 V protection cutoff, so the regulator cutoff binds first and the protection FET never trips. A validation that only asks "does protection trip at 3.0 V" passes while the product dies early.

Worked example. A simplified model makes the stranding checkable. OCV(SOC) is a table at 25 °C; ESR(T) is a table. The cell stops when OCV − I·ESR < 3.25 V, i.e. OCV < 3.25 + 2·ESR.

Python
# Simplified Li-ion model. Checked with Python 3.12.
OCV = [(0, 3.00), (5, 3.35), (10, 3.45), (20, 3.55), (30, 3.62),
       (40, 3.68), (50, 3.74), (60, 3.80), (70, 3.87), (80, 3.95),
       (90, 4.05), (100, 4.20)]
ESR = {-10: 0.250, 0: 0.150, 25: 0.080, 45: 0.060}  # ohm

def soc_at_ocv(v):
    for (s0, v0), (s1, v1) in zip(OCV, OCV[1:]):
        if v0 <= v <= v1:
            return s0 + (s1 - s0) * (v - v0) / (v1 - v0)
    return 0.0

I_PULSE, T_PULSE, T_PERIOD = 2.0, 0.005, 10.0
I_SLEEP_MA = 0.020
I_AVG_MA = I_PULSE * T_PULSE / T_PERIOD * 1000 + I_SLEEP_MA   # 1.02 mA
V_REG_MIN = 3.0 + 0.25   # LDO 3.0 V out, 250 mV dropout
CAP_MAH = 2000

for T, esr in ESR.items():
    v_cut = V_REG_MIN + I_PULSE * esr      # OCV at which pulse hits regulator floor
    soc_cut = soc_at_ocv(v_cut)
    usable_mah = CAP_MAH * (1 - soc_cut / 100)
    days = usable_mah / I_AVG_MA / 24
    print(f"{T:>4} C  ESR={esr*1000:5.0f} mOhm  Vcut={v_cut:.3f} V  "
          f"SOC_cut={soc_cut:5.1f}%  usable={usable_mah:6.0f} mAh  {days:5.1f} days")

Output:

 -10 C  ESR=  250 mOhm  Vcut=3.750 V  SOC_cut= 51.7%  usable=   967 mAh   39.5 days
   0 C  ESR=  150 mOhm  Vcut=3.550 V  SOC_cut= 20.0%  usable=  1600 mAh   65.4 days
  25 C  ESR=   80 mOhm  Vcut=3.410 V  SOC_cut=  8.0%  usable=  1840 mAh   75.2 days
  45 C  ESR=   60 mOhm  Vcut=3.370 V  SOC_cut=  6.0%  usable=  1880 mAh   76.8 days

At -10 °C the cell stops with 51.7% of its charge still in it: 967 mAh usable instead of 2000, and 39.5 days instead of 82. The 25 °C row is the sanity check: 8% stranded, 75 days, close to the naive number.

Trade-off. The pulse is 2 A × 5 ms = 37 mJ, once per 10 s, so 3.7 mW average. The cell holds 7.4 Wh ≈ 26.6 kJ, which makes the pulse about 1.4 parts per million of the stored energy. A bigger cell buys nothing here. The fix is an energy buffer: a bulk cap sized C = I·t/ΔV = 2 × 0.005 / 0.1 = 100 mF for 100 mV droop, i.e. a supercap with its own leakage and cost, or a lower-ESR cell. Deciding criterion: if pulse energy is a tiny fraction of cell energy, buffer it; if it is a large fraction, size the cell.

Validation. Characterize the cell with pulse discharges at -10/0/25/45 °C to get ESR(SOC, T) and OCV(SOC), feed those into the model, then run the worst-case duty cycle in a cold chamber and compare predicted against measured time-to-cutoff. Cross-check coulomb count against OCV at rest to catch estimator drift.

Failure modes and detection.

  • Cold brownout: reset at -10 °C under pulse. Detect with a brownout reset counter plus a min-voltage log.
  • Regulator cutoff binding above protection: the device stops when the pulse pulls the rail to 3.25 V, while the cell OCV is still 3.41 V at 25 °C. Detect by logging terminal voltage at shutdown and comparing against both limits.
  • Estimator drift: coulomb-counter offset, and OCV correction is invalid under load. Detect with periodic rest-and-recalibrate and compare.
  • Aging: ESR commonly rises toward 2× by end of life, so a fresh-cell design browns out after a few hundred cycles. Detect with accelerated cycling and an ESR trend.
  • Leakage: a 20 µA spec against 200 µA of board leakage is 10× shelf drain. Detect by measuring quiescent current across a board sample.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate low-power behavior for measurement setup.

Answer

Clarify before measuring. "Low power" isn't a number until you say which claim you're defending: average energy (battery life), peak current (brownout margin), or the sleep floor (leakage). Each needs a different instrument. I'll assume a 3.0 V coin-cell sensor: 2 µA sleep, a 12 mA radio TX burst for 3 ms every 10 s, 6 mA RX for 2 ms, MCU active 1.5 mA for 5 ms.

Core answer. Use two instruments, not one. A wide-dynamic-range analyzer (PPK2-class, roughly 1 µA–1 A, 100 kHz sampling) captures the whole trace; a fixed low-range measurement pins the sleep floor. Correlate the current trace against GPIO state markers on a logic analyzer so every current level is attributed to a code path. Then validate by cross-checking the integrated charge against a coulomb count over hours.

The arithmetic that decides the instrument. Charge per 10 s cycle: 12 mA × 3 ms = 36 µC, 6 mA × 2 ms = 12 µC, 1.5 mA × 5 ms = 7.5 µC, total 55.5 µC → 5.55 µA average. Add 2 µA sleep → 7.55 µA. On a 220 mAh cell that's 220000 µAh / 7.55 µA ≈ 29,100 h ≈ 3.3 years. Dynamic range needed: 12 mA / 2 µA = 6000:1, about 75.6 dB. That single number rules out most instruments.

Why a bench DMM fails here. On its 200 µA range a DMM has a shunt of a few hundred ohms (100 mV burden / 200 µA = 500 Ω). At 12 mA that's 6 V across the shunt: the board browns out. On the 200 mA range the resolution is 0.1 mA, so 2 µA is below the last digit. And at 3–10 readings/s it samples a 3 ms pulse essentially never: you either read the average by luck or miss the pulse entirely. That's aliasing: Nyquist wants ≥ 2× the shortest event, and ≥ 10× to see its shape, so a 3 ms burst wants ≥ 3.3 kHz.

instrumentrangesample rateseesmisses
bench DMMone range at a time3–10 Hzsteady sleep current3 ms pulses; µA on the mA range
PPK2-class analyzer~1 µA–1 A, autorange100 kHzfull tracesub-µA leakage floor
coulomb counterintegratescontinuousaverage energypeaks, pulse shape
shunt + scopeset by shuntMHzpulse shapesleep floor (buried in noise)

Deciding criterion is the claim: average energy → coulomb counter or long integration; peak/brownout → ≥ 100 kHz; sleep floor → fixed low range with nA resolution.

Failure modes and how to detect each.

  • Autorange loses the pulse: the range switch takes time and the pulse lands in the gap. Capture the same workload fixed-range and compare integrated charge; a mismatch means autorange ate the pulse.
  • Probe powers the board: if the analyzer supply and the debugger both ground the board, current bypasses the shunt. Run on battery only and compare.
  • Debug blocks sleep: SWD keeps the core clocked, so sleep reads mA not µA. Measure with the debugger detached.
  • LED load: a power LED draws ~2 mA, more than the entire budget. Remove it and re-measure.
  • Regulator excluded: measuring at the MCU VDD omits the LDO's quiescent current and efficiency. Decide which node the claim is about, then measure both.
  • Aliasing: sweep the sample rate and check the integral converges.

Validation. Integrate the analyzer trace over 24 h and compare to the coulomb counter; they should agree within a few percent. The real check is the cell: discharge one and compare against the 3.3-year prediction.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and validate low-power behavior for environmental validation.

Answer

Clarify first. "Environmental validation" here means proving a battery-powered sensor node holds its power budget across the temperature, humidity and supply corners it will actually see, not just on the bench at 25 °C. I'll assume a coin-cell node (CR2032, ~220 mAh usable), sampling a temp/humidity sensor every 5 minutes and transmitting a short LoRa packet hourly. State your own numbers if they differ; the method is the same.

The budget decides the design. 220 mAh over 10 years is 220 / (10 × 8760) = 2.5 µA average. That is the whole design constraint. Everything else is allocating it:

ConsumerDutyContribution to average
MCU Stop modealways0.4 µA @ 25 °C, ~3–4 µA @ 85 °C
LDO quiescentalways1 µA
Sensor standbyalways0.5 µA
Sample + convert20 ms / 5 min~0.1 µA
Radio TX60 ms / hour~1.5 µA

At 25 °C that sums near 3.5 µA, already over budget, so the design has to buy margin back. The levers: drop the LDO for a direct-battery or load-switched rail (saves the 1 µA), and cut TX rate or payload. At 85 °C the MCU alone eats the budget, which is the real design problem, not the 25 °C number.

Design choices and their costs. A 32.768 kHz crystal gives ±20 ppm over temperature but takes ~1 s to start, so you pay a 1 s wake each sample; an internal RC wakes in ~10 µs but drifts ±2% and needs periodic recalibration against the radio's clock. For a 5-minute period the crystal's startup is negligible and its accuracy wins. A brownout detector must stay enabled: it costs ~0.5 µA but without it a cold-start TX pulse at −40 °C (where CR2032 internal resistance rises to tens of ohms) resets the MCU mid-transmission. Add a 100 µF bulk cap across the cell to ride out the TX pulse.

Validation: corners, not points. Run the unit in a thermal chamber (e.g. ESPEC) with a programmable supply that has real output impedance, and measure current with a Nordic PPK2 (~200 nA resolution) or Otii Arc.

CornerWhy it matters
−40 °C, 2.0 Voscillator startup, brownout on TX
25 °C, 3.0 Vbaseline budget
85 °C, 3.6 Vsleep leakage, retention, self-discharge
85 °C / 85% RHcondensation, leakage paths

Failure modes and how you catch them. Chamber wiring adds a leakage path that flatters or ruins the reading: measure with the harness in place and again with it disconnected. Condensation shorts the board at high RH; soak 24 h and watch for a step in sleep current. A battery simulator with near-zero output impedance hides the brownout that a real coin cell causes: set the simulator's series resistance to the cell's datasheet value at that temperature. An oscillator that hasn't settled reads as a missed wake: log wake timestamps and check the interval distribution. And screen marginal units: run at least 10 parts, because sleep current varies several µA between dies and the worst one sets your field life.

The deciding criterion: if the 85 °C sleep current plus leakage exceeds ~2 µA, no amount of firmware tuning saves a 10-year life. You either move to a larger cell, cut the duty cycle, or accept a shorter service interval. Validate that number first.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and validate low-power behavior for energy evidence.

Answer

Assumptions first. I'd ask: which SoC, which power states does it actually expose, what is the wake period and the response deadline, and what energy per event does the product budget allow? Take a concrete case: an ARM Cortex-A53 gateway on Linux 6.6, a sensor sampled every 100 ms over I2C, a 20 ms end-to-end response deadline, and a 2000 mAh Li-ion cell with a one-year target. That target is 2000 mAh × 3.7 V / 8760 h ≈ 0.85 mW average, which tells you immediately that the design is decided by the sleep state, not by the active code.

The design. Build a state ladder and a policy that picks a rung per idle window. Currents below are illustrative for this device; the point is that each rung is measured, not assumed.

stateentrycurrentwake latency
run (active burst)—~120 mW—
WFI / shallow cpuidleautomatic~35 mW<10 µs
s2idle (suspend-to-idle)echo freeze > /sys/power/state~8 mW~2 ms
deep suspend (PSCI SYSTEM_SUSPEND)echo mem > /sys/power/state~1.2 mW~15 ms

The cpuidle governor (menu or teo) handles the shallow rungs. The sensor driver arms runtime PM autosuspend with autosuspend_delay_ms set just above the 5 ms burst, and a userspace policy writes mem only when the next scheduled wake is further out than the break-even point.

Why the break-even decides it. Deep suspend costs ~15 ms of resume at 120 mW ≈ 1.8 mJ per cycle. It saves 8 − 1.2 = 6.8 mW while asleep, so it pays only when the idle window exceeds 1.8 mJ / 6.8 mW ≈ 265 ms. At a 100 ms period it is a net loss: 0.05 × 120 + 0.95 × 8 ≈ 13.6 mW for s2idle, versus 0.05 × 120 + 0.95 × 1.2 + 18 ≈ 25 mW if you suspend every cycle. So the honest answer is "s2idle at 100 ms, deep suspend only past ~265 ms", and if 13.6 mW still misses the 0.85 mW budget, the fix is a longer period or a lower-power MCU, not a cleverer governor.

Validation. Measure, then reconcile against the kernel's own accounting. A shunt-based instrument (Nordic PPK2, Joulescope JS110) sampled at ≥100 kHz resolves the 5 ms burst; integrate V·I to get energy per event, and report energy per event and p99 wake latency, never average current. Then cross-check: /sys/devices/system/cpu/cpu0/cpuidle/state*/time and usage give residency per state, /sys/power/suspend_stats gives success/fail counts and last_failed_dev, /sys/kernel/debug/wakeup_sources gives active_count and active_since. If measured energy exceeds residency × state power, a wakeup source is firing early.

Failure modes and how each shows up. Wrong build: a debug config or a polling driver: config hash mismatch against the release manifest, and cpuidle usage counters flat. Debugger attached: SWD keeps the core clocked: the current floor rises only while the probe is connected. Average hides peak: a 200 mA burst every 100 ms averages away: check the instantaneous histogram against the cell's pulse rating. Stale state label: /sys/power/state says mem but a wakeup source was armed, so the SoC stayed in s2idle: suspend_stats and residency time disagree with measured current. Wake loop: a source fires immediately and the device never reaches the target state: active_count climbing and suspend entries per second far above the schedule. Functional loss unobserved: a rail was cut and the RTC or sensor calibration went with it: post-resume self-test, a retained-state CRC, and a deadline-miss counter.

Acceptance. Evidence is valid only when it is tied to a configuration hash, the workload, the wake cause, the measured latency, and a successful recovery: otherwise you have a number, not a result.

Curated: · Written: · Reviewed:

Difficulty: Hard