Skip to content
systemcoding.dev
Embedded

Put a Cortex-M to Sleep With WFI Between Interrupts

Replace a busy main loop with __WFI so a Cortex-M sleeps until the next interrupt, and close the lost-wakeup race with a PRIMASK guard.

7 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Arm, C and Nordic Semiconductor logos.

A main loop that spins on while (1) { } waiting for interrupts keeps the core running at full speed to do nothing. A Cortex-M has an instruction made for this case. WFI, wait for interrupt, stops the core until an interrupt is taken, and on most parts that lets the chip gate the core clock and draw much less current. The change is one line, and it is almost always correct, but there is one subtle mistake that makes a device sleep through an event and appear to hang. This post shows the one-line version, the mistake, and the safe pattern, on an STM32F411 with CMSIS and arm-none-eabi-gcc 13.3. The behaviour of WFI comes from the Armv7-M Architecture Reference Manual, which defines it, and the Cortex-M4 Devices Generic User Guide.

The simplest version

Say a button interrupt sets a flag and the main loop reacts to it. A busy version:

busy.cc
#include "stm32f4xx.h"

volatile uint8_t button_flag;

void EXTI15_10_IRQHandler(void)
{
    EXTI->PR = EXTI_PR_PR13;
    button_flag = 1;
}

int main(void)
{
    board_init();
    for (;;) {
        if (button_flag) {
            button_flag = 0;
            GPIOA->ODR ^= GPIO_ODR_OD5;
        }
    }
}

The for loop executes millions of times a second doing nothing. Adding __WFI() makes the core stop at the end of each pass:

wfi_naive.cc
int main(void)
{
    board_init();
    for (;;) {
        if (button_flag) {
            button_flag = 0;
            GPIOA->ODR ^= GPIO_ODR_OD5;
        }
        __WFI();
    }
}

__WFI() is the CMSIS intrinsic that emits the wfi instruction. With SLEEPDEEP clear, which is the reset state of SCB->SCR, the core enters sleep: it stops executing, and the processor clock can be gated by the chip. The core wakes when an enabled interrupt with enough priority is taken, runs the handler, and then continues with the instruction after wfi. Any interrupt wakes it, including SysTick, so on a system with a 1 ms tick the loop runs at least a thousand times a second, which is still a large saving over spinning.

The lost wake-up

The naive version has a race. Look at the gap between testing the flag and executing wfi:

Text
main loop                       interrupt
---------                       ---------
if (button_flag)   // 0
                                button_flag = 1
__WFI();                        (handler already finished)
// sleeps, flag is set but nobody looks until the next interrupt

If the interrupt fires after the if has read 0 and before the wfi executes, the handler runs and returns, and then the core executes wfi and goes to sleep. The event has been handled once, but the main loop has not seen it, and the core is asleep with no interrupt coming. The button press is acted on only when some other interrupt arrives, which may be never. On a device with SysTick running the delay is at most a tick, so the bug hides. On a device that sleeps with the tick off, it looks like a hang that only appears at random.

The window is two instructions wide, so a test run rarely catches it, and a deployed fleet always does.

The fix: mask, check, wait, unmask

The architecture gives a clean way out. WFI wakes on an interrupt that becomes pending even when the interrupt is masked by PRIMASK. The Armv7-M manual lists, among the wake-up events for WFI, an interrupt that is masked by PRIMASK becoming pending. So you can close the window by masking interrupts, checking the flag, and sleeping with interrupts still masked. A pending interrupt wakes the core, and the handler runs as soon as you unmask:

wfi_safe.cc
int main(void)
{
    board_init();
    for (;;) {
        __disable_irq();
        if (!button_flag) {
            __WFI();            // wakes if an interrupt is, or becomes, pending
        }
        __enable_irq();         // the handler runs here if one was pending

        if (button_flag) {
            button_flag = 0;
            GPIOA->ODR ^= GPIO_ODR_OD5;
        }
    }
}

Walk through the three orderings. If the interrupt fires before __disable_irq(), the handler has already set the flag, the test sees it and skips the wfi. If it fires between the test and wfi, the interrupt cannot be taken because PRIMASK is set, but it becomes pending, and wfi returns at once because a pending interrupt is a wake-up event. If it fires during the sleep, it wakes the core. In every case, __enable_irq() lets the pending handler run, and the flag is set when the code checks it.

There is a subtle point in the third line of the loop. After __enable_irq(), the handler runs before the next instruction completes, because a pending enabled interrupt is taken as soon as PRIMASK clears. The following if (button_flag) therefore sees the new value. A compiler barrier is already implied by the __enable_irq() intrinsic, which CMSIS defines with a "memory" clobber.

Sleep-on-event: WFE

WFE waits for an event instead. An event is an interrupt, or a signal from another processor, or a software SEV, or an external event pin, and it differs from WFI in one way: there is an event register, one bit that remembers whether an event has occurred since the last WFE. If the bit is already set when WFE executes, it clears the bit and returns without sleeping. That closes the race by design, without masking interrupts, for events delivered by SEV or by an interrupt with SEVONPEND set in SCB->SCR:

wfe.cc
int main(void)
{
    board_init();
    SCB->SCR |= SCB_SCR_SEVONPEND_Msk;   // a pending interrupt sets the event register
    for (;;) {
        __WFE();
        if (button_flag) {
            button_flag = 0;
            GPIOA->ODR ^= GPIO_ODR_OD5;
        }
    }
}

With SEVONPEND set, an interrupt that becomes pending, even one disabled in the NVIC, sets the event bit and wakes WFE. Note the difference from WFI: with SEVONPEND, the core wakes without taking the interrupt, so a handler never runs unless the interrupt is enabled. Use WFE when you want to wake and poll, and WFI when you want the handler to run.

What WFI does not do

  • It does not choose a deep mode. With SLEEPDEEP clear it is the shallowest sleep. Setting SLEEPDEEP first enters deep sleep, which the vendor's power controller maps to Stop or Standby.

  • It does not turn off peripherals. Timers, UARTs and ADCs keep running and drawing current, and any of them can wake the core. A free-running timer that interrupts every millisecond wakes the chip a thousand times a second.

  • It may return at once. A pending interrupt makes wfi a no-op, so a loop must tolerate returning immediately.

  • It does not save the debugger connection. On many parts the debug clock stops with the core clock in deeper modes, and even in plain sleep a debugger may report that the core is unresponsive. That behaviour is configured by vendor registers.

Check what the chip does at the moment of wfi by watching the supply current. A loop that sleeps correctly shows a current that drops during sleep and rises briefly for each interrupt.

Text
supply current (conceptual trace):
 busy loop:        constant high
 loop with WFI:    low between interrupts, short spikes at each interrupt

Sleeping from inside a handler

Some designs do all their work in interrupts and want the core asleep whenever no handler runs. Cortex-M has a bit for that, SLEEPONEXIT in SCB->SCR: when the last handler returns, the core goes straight back to sleep instead of returning to thread mode. The main loop then runs once and the system lives entirely in handlers. A separate post covers it, and it needs the same care about shared flags, since there is no main loop left to poll them.

A test you can do on paper

Before putting the guard in real code, check it by walking the three possible orderings, as above, and then check the unusual one: an interrupt that arrives while the handler of another interrupt is still running. The second interrupt cannot run until the first returns, because PRIMASK is not involved. When the first handler returns to the main loop, which has interrupts masked at that point, the second becomes pending, and the wfi that follows sees it and returns at once. Nothing is lost.

The last thing to check is the cost. __disable_irq() and __enable_irq() are single instructions, cpsid i and cpsie i, so the guard adds two cycles to each pass of the loop. That is nothing against the saving from sleeping, and it makes the loop correct. The pattern is general: any time a program tests a condition and then waits for a change in it, the test and the wait have to be atomic with respect to the thing that changes the condition.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.