Try Embedded

CPU fundamentals for embedded

Pipelines, caches, DMA coherency, barriers and buses.

Why firmware engineers need CPU internals

On a simple microcontroller, one instruction roughly equals one cycle and memory is memory. On anything with a pipeline, a cache, a write buffer or more than one bus master, that model breaks, and the bugs it causes (DMA reading stale data, a register write "not taking effect", timing that changes when code moves) are only explainable with a better model.

Pipelines

A pipeline overlaps instructions: while one executes, the next is decoded and the one after is fetched.

CorePipeline stages
Cortex-M0+2
Cortex-M3 / M43 (fetch, decode, execute)
Cortex-M76, dual-issue (two instructions per cycle when possible)

Consequences:

  • Branches cost extra cycles because fetched instructions after a taken branch are thrown away. The M7 has a branch predictor; smaller cores do not.
  • Cycle counts depend on neighbours. The same instruction can take different time depending on what precedes it. For exact timing, measure with the cycle counter (DWT->CYCCNT) rather than counting instructions.
  • Flash wait states stall the pipeline. Vendors add prefetch buffers and small "accelerator" caches (ART on STM32) to hide them.

Caches

Cortex-M7 (and larger application cores) have separate instruction and data caches. A cache keeps copies of recently used memory in fast SRAM, organised in lines (32 bytes on M7).

The data cache is usually write-back: a write updates the cache line, and memory is updated later when the line is evicted or explicitly cleaned. This is where DMA goes wrong, because the DMA controller reads and writes memory directly and does not see the cache.

SituationProblemFix
CPU fills a buffer, DMA sends it (memory to peripheral)Data still sits dirty in the cache; DMA sends old memory contentsClean the cache lines for the buffer before starting DMA (SCB_CleanDCache_by_Addr)
DMA receives into a buffer, CPU reads itCPU reads stale cached copiesInvalidate the lines after DMA completes, and before if the CPU might have cached them (SCB_InvalidateDCache_by_Addr)

Two details that cause real bugs:

  • Buffers must be aligned to and sized in whole cache lines (32 bytes). Invalidating a line that also contains another variable throws away that variable's pending writes.
  • The alternative is to place DMA buffers in a region the MPU marks non-cacheable, or in memory the DMA and CPU share coherently (DTCM on some M7 parts). Simpler and safer, at the cost of slower CPU access to those buffers.

Memory ordering and barriers

To go faster, the core and the bus may complete memory accesses in a different order than the program issued them. On a single core with normal memory this is invisible. It becomes visible when the "other side" is hardware or another bus master.

Arm provides three barrier instructions:

BarrierGuaranteesUse
DMB (data memory barrier)Memory accesses before it are observed before those after itOrdering between writing a buffer and writing the register or flag that hands it over (DMA, another core)
DSB (data synchronisation barrier)All memory accesses before it have completed before any instruction after it executesAfter disabling an interrupt or clearing a flag in a peripheral, before WFI, after changing the MPU
ISB (instruction synchronisation barrier)Flushes the pipeline so later instructions are fetched freshAfter changing CONTROL, VTOR, MPU or writing code to RAM

Typical example: clearing an interrupt flag at the very end of an ISR. The write can still be in the bus's write buffer when the handler returns, so the interrupt appears pending again and fires twice. A __DSB() after the clear (or clearing it earlier) prevents it.

DMA1_Stream0->CR &= ~DMA_SxCR_EN;     /* stop DMA */
__DSB();                               /* make sure the write reached the peripheral */
NVIC_DisableIRQ(DMA1_Stream0_IRQn);
__DSB();
__ISB();                               /* recommended after disabling an IRQ */

volatile stops the compiler reordering accesses; barriers stop the hardware reordering them. Both may be needed.

Buses and bus matrices

A microcontroller has several bus masters (the CPU's instruction and data ports, one or more DMA controllers, Ethernet, USB) and many slaves (flash, several SRAM blocks, peripheral bridges). A bus matrix connects them so different masters can access different slaves at the same time.

Practical consequences:

  • Put DMA buffers and CPU data in different SRAM blocks where possible, so they do not compete for the same port.
  • Peripheral buses are slow. APB peripherals sit behind a bridge at a divided clock; each register access costs several CPU cycles. A loop that polls a status register runs at bus speed, not CPU speed.
  • Not every master reaches every memory. On some parts DMA cannot access the core-coupled memory (CCM or DTCM), so a DMA buffer placed there silently does nothing.

Measuring cycles

Cortex-M3 and above have a free-running cycle counter in the DWT unit:

CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CYCCNT = 0;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;

uint32_t start = DWT->CYCCNT;
filter_block(samples, 256);
uint32_t cycles = DWT->CYCCNT - start;    /* unsigned subtraction handles wrap-around */

The same unsigned-subtraction trick that handles a millisecond tick wrapping also handles the cycle counter wrapping every few seconds:

#include <stdio.h>
#include <stdint.h>

int main(void) {
  uint32_t start = 0xFFFFFF00u;     /* just before the counter wraps */
  uint32_t end   = 0x00000140u;     /* just after */
  printf("elapsed = %u cycles\n", end - start);
  return 0;
}

Interview question: Explain cache coherency problems with DMA and how to solve them.

Answer: DMA accesses memory directly while the CPU may work on copies in its data cache. For transmit, the CPU's latest data may be in dirty cache lines, so clean (write back) the buffer's lines before starting DMA. For receive, the CPU may hold stale lines, so invalidate the buffer's lines after the transfer (and typically before it starts, so no dirty line is evicted on top of the new data). Buffers must be cache-line aligned and sized to avoid corrupting neighbouring data. The alternative is to put DMA buffers in a non-cacheable MPU region or coherent memory.

Interview question: When do you need DMB, DSB or ISB on a Cortex-M?

Answer: DMB to order memory accesses as seen by another observer, for example writing a buffer then a flag or doorbell read by DMA or another core. DSB when an access must have completed before continuing: after clearing an interrupt flag at the end of an ISR, before WFI, after disabling an interrupt or changing a peripheral's configuration that later code depends on. ISB after changing something that affects instruction fetch or execution context, such as CONTROL, VTOR or the MPU, or after writing code to RAM, so later instructions are refetched.

Build it: does the motor loop fit in the CPU?

This is step 1 of the module project, the electronic speed controller (ESC) that spins one motor of a racing drone. Every PWM period an interrupt reads the current, runs the control maths and updates the motor's timer. If that interrupt takes longer than the period, the motor stutters and the drone falls. Before writing it, check the cycle budget.

Lab: A cycle budget for the control interrupt

  • cycles_per_period(cpu_hz, isr_hz) returns how many CPU cycles there are between two interrupts, cpu_hz / isr_hz, rounded down.
  • isr_cycles(instr, wait_states, loads) estimates the interrupt's cost: ENTRY_CYCLES + EXIT_CYCLES (stacking and unstacking the registers) + one cycle per instruction + wait_states extra cycles for each of the loads instructions that read flash (constant tables).
  • load_pct(cost, budget) returns the share of the CPU the interrupt takes, cost * 100 / budget, rounded down.
  • fits(cpu_hz, isr_hz, instr, wait_states, loads) returns true when the load is at most MAX_LOAD_PCT (70 %), keeping room for the rest of the firmware.

Going deeper

Interview question: How do you know whether a quadcopter's 1 kHz control loop will fit on a chosen MCU?

Answer: Prototype the loop and measure its worst-case execution time on the target with caches and flash wait states as they will be, using a cycle counter or a GPIO and a scope. Add interrupt load and the other tasks, then keep a large margin (under about 50 % use) for growth. Look at the generated code for unexpected division or floating-point emulation.

Interview question: What is tightly coupled memory (TCM) and when would you use it?

Answer: TCM is RAM connected directly to the core on Cortex-M7 and some other cores, accessed in a single cycle without going through caches or the main bus matrix. Instruction TCM (ITCM) holds time-critical code such as interrupt handlers and control loops so their timing is deterministic; data TCM (DTCM) holds the stack and hot data. On some parts DMA cannot reach it, so DMA buffers belong elsewhere.

Interview question: What is the difference between a write-through and a write-back cache?

Answer: A write-through cache writes every store both to the cache and to memory, so memory is always up to date but writes are slower. A write-back cache writes only to the cache and updates memory when the line is evicted or cleaned, which is faster but means memory can hold stale data. With DMA reading memory, write-back caches need explicit cleaning before transfers; write-through only needs invalidation for reads.

Explain it: In your own words, explain why a DMA transfer can send stale data on a Cortex-M7 with the data cache enabled.

Answer: With a write-back data cache, when the CPU fills a buffer its writes go into cache lines and are not necessarily written to RAM yet. The DMA controller reads RAM directly and knows nothing about the cache, so it can send the old contents of RAM instead of what the CPU wrote. Cleaning the buffer's cache lines before starting the DMA forces the dirty data out to RAM; alternatively the buffer can be placed in memory configured as non-cacheable.