</>EmbeddedInterview

What is the difference between WFI and WFE?

HardMicrocontrollers & ARM Cortex-M

Short answer: WFI (Wait For Interrupt) puts the core to sleep until an interrupt (or debug request or reset) arrives. WFE (Wait For Event) sleeps until an event: an interrupt, an event signalled by another core with SEV, an external event input, or a pending event that is already latched. If the event register is already set when WFE executes, it clears it and continues immediately without sleeping.

WFI WFE
Wakes on interrupts (even if masked by PRIMASK, the core still wakes) events: interrupts (with SEVONPEND, even disabled ones), SEV from another core, external event line
Event register not used if set, WFE clears it and does not sleep
Typical use idle loops, low-power waiting for an interrupt multi-core spinlocks, waiting for another core, low-overhead polling

Why the event register exists: to avoid a race. If core B executes SEV just before core A executes WFE, the event is latched, so A does not miss it and sleep forever.

Spinlock usage on Arm (multi-core)

retry:
    LDAXR   w1, [x0]        // load-acquire exclusive
    CBNZ    w1, wait        // lock held by someone else
    STXR    w2, w3, [x0]    // try to take it
    CBNZ    w2, retry
    RET
wait:
    WFE                     // sleep until the holder releases and signals
    B       retry

The unlock is a store-release; clearing the exclusive monitor of a waiting core generates an event automatically on Armv8 (older code used an explicit SEV).

Masked interrupts and WFI: a common idiom for race-free sleep is __disable_irq(); if (!work_pending) __WFI(); __enable_irq();. The core still wakes on the interrupt (it is pending), and the ISR runs after __enable_irq(), so a wake-up between the check and the sleep is not lost.

SEVONPEND (SCB->SCR): makes any newly pending interrupt, even a disabled one, generate an event for WFE. Useful to wake on a peripheral flag without running an ISR.

Practical rule: use WFI for "sleep until something needs attention" in idle loops (RTOS idle hooks use it); use WFE for synchronisation between cores and in lock implementations.