</>EmbeddedInterview

What is the MPU and how is it used?

MediumMicrocontrollers & ARM Cortex-M

Short answer: The Memory Protection Unit lets software define a small number of memory regions (typically 8 or 16) with access permissions (privileged/unprivileged read, write, execute-never) and memory attributes (cacheable, bufferable, shareable, device). An access that violates the rules raises a MemManage fault instead of silently corrupting memory. It does not translate addresses (no virtual memory).

Uses

  • Stack overflow detection: a no-access guard region just below each stack.
  • NULL pointer detection: a no-access region at address 0 (after relocating the vector table).
  • Execute-never RAM and read-only flash, which stops many code-injection and accidental-overwrite bugs.
  • Task isolation: unprivileged tasks can access only their own stack/data and the peripherals they need (FreeRTOS-MPU, Zephyr user mode, safety RTOSes).
  • Cache control on Cortex-M7: make DMA buffers non-cacheable or write-through, and mark external memory and peripheral regions correctly.

Region rules

Armv7-M (M3/M4/M7) Armv8-M (M23/M33/M55/M85)
Region definition base + size base + limit
Size power of two, 32 B to 4 GB, base aligned to size any multiple of 32 bytes
Subregions 8 subregions per region can be disabled none
Overlap allowed; higher region number wins not allowed
Attributes TEX/C/B/S bits index into MAIR attribute registers

Example (Armv7-M): make a 32-byte guard at the bottom of a task stack

MPU->RNR  = 7;                                   /* region 7 */
MPU->RBAR = (uint32_t)task_stack;                /* must be 32-byte aligned */
MPU->RASR = (0u << MPU_RASR_AP_Pos)              /* no access */
          | MPU_RASR_XN_Msk
          | (4u << MPU_RASR_SIZE_Pos)            /* size = 2^(4+1) = 32 bytes */
          | MPU_RASR_ENABLE_Msk;
MPU->CTRL = MPU_CTRL_ENABLE_Msk | MPU_CTRL_PRIVDEFENA_Msk;  /* default map for privileged code */
__DSB();
__ISB();

PRIVDEFENA keeps the default memory map for privileged code, so you only need regions for what you want to restrict.

Limitations: few regions (an RTOS reprograms some on every context switch), the v7-M alignment rules waste memory, and MPU programming is easy to get subtly wrong, so test violations deliberately.