Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

This book is a guided tour of the Armv8-M architecture (the M-profile: Cortex-M23, M33, M35P, M52, M55, M85). It is written for engineers who already know A-profile well: AArch64 exception levels, the GIC, TrustZone-A with an EL3 monitor, and translation tables. Rather than starting from zero, each section explains the M-profile mechanism and then contrasts it with what you already know.

Draft. The content was drafted with AI assistance and cross-checked by a separate AI review pass. It has not yet been reviewed line by line against the Armv8-M Architecture Reference Manual (Arm DDI0553). Treat every claim as something to confirm in the manual before relying on it, and please report errors.

Chapters

ChapterWhat it covers
1. Programmer’s model & resetBaseline vs Mainline vs v8.1-M, core and special registers, modes and privilege, MSP/PSP and stack limits, reset and the system address map
2. Exception & interrupt modelException numbers and priorities, the NVIC, hardware stacking and EXC_RETURN, tail-chaining, lazy FP, faults, SVC/PendSV in an RTOS
3. Memory model, MPU & barriersDefault memory map and memory types, PMSAv8 regions, DMB/DSB/ISB, exclusives and monitors, cache maintenance
4. TrustZone for Armv8-M & TF-MAddress-based security state, SAU/IDAU, SG/BXNS/FNC_RETURN, banked state, CMSE, stack sealing, TF-M vs OP-TEE + TF-A

One register to orient you

On exception entry the core writes a magic value, EXC_RETURN, into LR. A handler returns by branching to it; there is no ERET. Chapter 2 explains each field.

Bits31:2423:76543210
FieldPREFIX 0xFFRES1SDCRSFTypeModeSPSELRES0ES

How to use this book

Each section is a short reading (2–3 minutes), followed by:

  • a Coming from A-profile note that names the closest A-profile concept and where it differs, and
  • a Checkpoint of 2–3 multiple-choice questions.

Answering questions

Click or tap an option to commit to it. The answer and an explanation then appear. The explanation says why the correct option is right and why the most tempting wrong option is wrong, and points to the relevant part of the Armv8-M ARM (DDI0553).

Your answers are stored only in your browser, so they survive reloads but not a change of browser or device. Use Try again under a question to clear it.

Without JavaScript the options are a plain list, and each answer sits in a collapsed Answer box.

Suggested order

The chapters build on each other: exceptions assume the programmer’s model, and TrustZone assumes both exceptions and the MPU. If you already know TrustZone-A well, it is still worth reading chapter 2 first, because the Secure/Non-secure transitions in chapter 4 are defined in terms of EXC_RETURN and the stack frame.

1. Programmer’s model & reset

Covers the Armv8-M family and its optional extensions, the T32-only core register set and special registers, Thread/Handler modes and privilege, the banked stack pointers with their limit checks, and how the core comes out of reset into a fixed, memory-mapped system address map.

Sections

  1. The Armv8-M family map
  2. T32-only execution and core registers
  3. Special registers: masks and CONTROL
  4. Modes, privilege and the two stack pointers
  5. Stack limit checking: MSPLIM and PSPLIM
  6. Reset, the vector table and the system address map

1.1 The Armv8-M family map

Armv8-M is one architecture with a small mandatory core and a set of optional extensions. There are no exception levels and no AArch64. Instead you get a fixed set of feature switches that an implementation includes or leaves out:

  • Baseline is the minimum. It is the Armv6-M feature set plus additions such as hardware divide (SDIV/UDIV), CBZ/CBNZ, MOVW/MOVT, exclusive accesses and load-acquire/store-release. It has a single fault exception (HardFault) and only PRIMASK for interrupt masking.
  • Main Extension turns Baseline into Mainline. It adds the full 32-bit T32 instruction set (including IT), the configurable faults MemManage, BusFault and UsageFault (plus their status registers), BASEPRI and FAULTMASK.
  • Security Extension (TrustZone for Armv8-M) is optional on both Baseline and Mainline.
  • DSP Extension and Floating-point Extension both require the Main Extension.

Armv8.1-M builds on Mainline with features that include the M-profile Vector Extension (MVE, marketed as Helium; it requires the Main Extension), the Low Overhead Branch extension (WLS/DLS/LE loops), PACBTI (pointer authentication and branch target identification), a Privileged eXecute-Never MPU attribute, CLRM/VSCCLRM register clearing, and PMU and RAS support.

CoreArchitecture
Cortex-M23v8-M Baseline, optional Security Extension
Cortex-M33v8-M Mainline, optional Security Ext, DSP, single-precision FP
Cortex-M35PLike M33, with physical (tamper/side-channel) resistance
Cortex-M52v8.1-M Mainline; MVE and PACBTI are configuration options
Cortex-M55v8.1-M Mainline; MVE (integer, or integer and FP) as a configuration option
Cortex-M85v8.1-M Mainline; MVE and PACBTI as configuration options

In practice, your first questions about a part are: Baseline or Mainline? Is the Security Extension present? Which v8.1-M features are there? The answers determine which registers, faults and instructions exist. Check the core’s configuration (and the ID registers in the SCS), not just its name.

Coming from A-profile: On A-profile, ID_AA64* registers plus the FEAT_* naming tell you what is implemented. On M-profile, the Baseline/Mainline split takes away whole blocks of the programmer’s model, including fault exceptions and mask registers, not just a few instructions.

Checkpoint

Q1.1.1 You port an RTOS from a Cortex-M33 to a Cortex-M23. Its critical sections use MSR BASEPRI, r0 so that high-priority interrupts are never masked. What do you need to change?

  • A. Nothing. BASEPRI is part of the mandatory programmer’s model.
  • B. Replace BASEPRI with FAULTMASK, which Baseline provides instead.
  • C. Use PRIMASK, which masks all configurable-priority exceptions. Baseline has no BASEPRI, so selective masking by priority level is not available.
  • D. Use the Security Extension so that Secure interrupts stay unmasked.
Answer

C. BASEPRI and FAULTMASK come with the Main Extension, and the Cortex-M23 implements Baseline. PRIMASK is the only mask register Baseline offers, and it is all-or-nothing for configurable priorities. FAULTMASK is also Mainline-only, so it cannot be the substitute.

Read more: Armv8-M ARM (DDI0553), Programmers’ model: special-purpose mask registers; Main Extension feature list

Q1.1.2 Which of these features cannot be implemented without the Main Extension?

  • A. The Security Extension
  • B. Stack pointer limit registers for the Secure state
  • C. Load-acquire/store-release instructions
  • D. The DSP Extension
Answer

D. The DSP Extension (and the FP Extension and MVE) depend on the Main Extension. The Security Extension, Secure stack limits and load-acquire/store-release are all available on Baseline. For example, the Cortex-M23 implements TrustZone and Secure stack limit checking.

Read more: Armv8-M ARM (DDI0553), Introduction: Armv8-M architecture extensions

Q1.1.3 A loop compiled with DLS lr, r2 … LE lr, loop runs on a Cortex-M33. What do you expect?

  • A. It runs correctly, because low-overhead loops are part of v8-M Mainline.
  • B. The instructions are not available: the Low Overhead Branch extension is Armv8.1-M, so on a v8.0-M core these encodings are UNDEFINED and fault.
  • C. It runs, but without the zero-overhead benefit.
  • D. It works only if the DSP Extension is implemented.
Answer

B. The Low Overhead Branch extension (WLS/DLS/LE) was introduced in Armv8.1-M. The Cortex-M33 is Armv8.0-M Mainline, so executing them gives an UNDEFINSTR UsageFault (or HardFault if UsageFault is disabled). The tempting assumption is that every Mainline core has these instructions, but they need a v8.1-M core such as the M52, M55 or M85.

Read more: Armv8-M ARM (DDI0553), Armv8.1-M Low Overhead Branch Extension

1.2 T32-only execution and core registers

Armv8-M executes only T32 (Thumb) instructions. A32 state does not exist. The architecture still keeps a Thumb state bit, EPSR.T. It must be 1 whenever an instruction executes. If T is 0 when the core tries to execute an instruction, the result is an INVSTATE UsageFault (Mainline) or a HardFault (Baseline, which has no UsageFault).

T is written by:

  • interworking branches, from bit[0] of the target address: BX, BLX, and POP/LDM/LDR into PC
  • vector table fetches on exception entry and on reset, from bit[0] of the vector entry
  • exception return, which restores EPSR.T from bit[24] of the stacked xPSR

For example, if a vector table entry has bit[0] clear, the exception entry itself completes and the core branches to the handler with T = 0. The fault happens when it tries to execute the handler’s first instruction. UsageFault is disabled out of reset (SHCSR.USGFAULTENA = 0), so on Mainline this fault escalates to HardFault.

Core registers

  • R0-R12 are general purpose. Many 16-bit encodings can only reach R0-R7.
  • R13 = SP. It is banked: MSP and PSP, and with the Security Extension a Secure and a Non-secure copy of each.
  • R14 = LR. On exception entry the hardware loads it with an EXC_RETURN value instead of a real return address.
  • R15 = PC.

xPSR is three views of one register:

APSR : N Z C V, Q (Main Ext), GE[3:0] (DSP Ext)
IPSR : exception number of the active exception (0 = Thread mode)
EPSR : T bit, ICI/IT state (v8.1-M adds further execution-state fields)

MRS can read APSR, IPSR or the combined views. EPSR fields read as zero through MRS, and MSR writes to them are ignored. Software therefore cannot read T or write it with MSR. Only interworking branches, exception entry and exception return change it.

Coming from A-profile: In AArch64, saved PSTATE lives in SPSR_ELx and the syndrome in ESR_ELx, and there is no interworking. On M-profile, bit[0] of every code pointer matters. A vector address with bit[0] clear is not an alignment hint. It is a fault waiting to happen.

Checkpoint

Q1.2.1 On a Mainline core straight out of reset, the SysTick vector entry holds 0x00001200 (bit[0] clear). SysTick fires. What happens?

  • A. The handler runs correctly. The hardware ignores bit[0] of vector entries.
  • B. The exception entry is aborted and the core enters Lockup.
  • C. The core switches to A32 state and executes the handler as A32 code.
  • D. The core enters the handler with EPSR.T = 0, and its first instruction raises an INVSTATE UsageFault. UsageFault is disabled at reset, so this escalates to HardFault.
Answer

D. Vector fetches copy bit[0] into EPSR.T. Entry completes, and the fault happens when the core attempts the handler’s first instruction. UsageFault is disabled by default, so it escalates to HardFault. There is no A32 state on M-profile. Lockup would only follow if the HardFault vector were also broken, or if the fault happened at HardFault/NMI priority.

Read more: Armv8-M ARM (DDI0553), Exception entry: vector table and EPSR.T; UsageFault INVSTATE

Q1.2.2 A debug routine runs MRS r0, XPSR from C to check that the core is in Thumb state, by testing bit 24 (EPSR.T). What does it observe?

  • A. Bit 24 reads 0, because EPSR fields read as zero through MRS.
  • B. Bit 24 reads 1, because the core is always in Thumb state.
  • C. The MRS instruction faults, because EPSR is accessible only to a debugger.
  • D. Bit 24 reflects the Thumb state only in Handler mode.
Answer

A. The architecture defines EPSR bits as reading as zero when accessed with MRS, so software cannot observe T this way. It is tempting to expect 1 because the core is in fact executing T32. A debugger can see the real value through the debug register interface, and stacked xPSR values in an exception frame also contain T.

Read more: Armv8-M ARM (DDI0553), xPSR / EPSR description and MRS pseudocode

Q1.2.3 On exception entry, what does LR hold when the handler starts?

  • A. The address of the interrupted instruction
  • B. An EXC_RETURN value that encodes return information such as mode, stack and security state. Loading it into PC performs the exception return.
  • C. Zero. The return address is only on the stack.
  • D. The vector table address of the handler
Answer

B. The hardware writes an EXC_RETURN value (top byte 0xFF) into LR. Writing it to PC in Handler mode (BX LR, or POP {pc}) triggers the exception return sequence. The real return address is in the stacked frame, so expecting it in LR (the ELR-like assumption) is wrong.

Read more: Armv8-M ARM (DDI0553), EXC_RETURN

1.3 Special registers: masks and CONTROL

System state that A-profile keeps in PSTATE and sysregs is split, on M-profile, between a few special registers and memory-mapped SCS registers. You access the special registers only with MRS/MSR, and the masks also with CPS.

  • PRIMASK (all implementations): bit[0] = 1 raises execution priority to 0, which masks every configurable-priority exception. NMI and HardFault are not masked. CPSID i / CPSIE i set and clear it.

  • FAULTMASK (Mainline): bit[0] = 1 raises execution priority to -1, which masks HardFault as well. NMI is not masked. CPSID f / CPSIE f. Exception return (other than from NMI) clears it automatically.

  • With the Security Extension, PRIMASK and FAULTMASK are banked per Security state, and the priority level the Non-secure copies boost to depends on AIRCR.PRIS and AIRCR.BFHFNMINS. Those rules are not covered here.

  • BASEPRI (Mainline): a non-zero value raises execution priority to that value, so exceptions whose group priority value is greater than or equal to it cannot preempt. 0 disables BASEPRI masking. BASEPRI_MAX is a write alias that updates BASEPRI only if the new value raises the masking level.

  • CONTROL:

    bit0 nPRIV  Thread mode is unprivileged when 1
    bit1 SPSEL  Thread mode uses PSP when 1 (MSP when 0)
    bit2 FPCA   FP context active (FP Ext)
    bit3 SFPA   Secure FP context active (FP + Security Ext)
    (PACBTI adds enable bits above bit3)
    

When unprivileged software writes PRIMASK, FAULTMASK, BASEPRI or CONTROL with MSR, the write is ignored, and CPS behaves as a NOP. Neither faults.

Synchronization:

  • An MSR or CPS that raises execution priority (masking) takes effect for the following instructions without a barrier.
  • An MSR or CPS that lowers execution priority needs an ISB before an already-pending exception is guaranteed to be taken.
  • After MSR CONTROL that changes SPSEL or nPRIV, software must issue an ISB so that the instructions after it are guaranteed to use the new stack pointer or privilege level.

Coming from A-profile: PRIMASK and FAULTMASK are not DAIF bits. They mask by raising the execution priority, so they interact with the NVIC priority scheme instead of acting as per-class enable bits. Unprivileged writes do not trap the way an EL0 MSR DAIF with SCTLR_EL1.UMA = 0 does. They are silently ignored.

Checkpoint

Q1.3.1 An unprivileged Thread-mode task runs CPSID i and then enters a ‘critical section’. What actually happens?

  • A. A UsageFault (UNDEFINSTR) is raised, because CPS is a privileged instruction.
  • B. PRIMASK is set, because CPS is not privilege-checked.
  • C. CPSID is treated as a NOP. PRIMASK is unchanged, interrupts stay enabled and no fault is raised, so the critical section is not protected.
  • D. A HardFault is raised immediately.
Answer

C. For unprivileged execution, the architecture defines CPS as having no effect, and MSR writes to the mask registers are ignored. A-profile experience suggests a trap, but there is none. This is a silent correctness bug, so unprivileged code must request masking through an SVC.

Read more: Armv8-M ARM (DDI0553), CPS and MSR instruction descriptions (privilege checks)

Q1.3.2 Privileged code executes MSR CONTROL, r0 to set SPSEL = 1, then immediately pushes registers. What is the architecturally correct sequence?

  • A. MSR CONTROL, r0 followed by ISB, then the push
  • B. MSR CONTROL, r0 followed by DMB, then the push
  • C. MSR CONTROL, r0 followed by DSB, then the push
  • D. No barrier is needed, because MSR to CONTROL is self-synchronizing.
Answer

A. A change to CONTROL.SPSEL or nPRIV is guaranteed to affect subsequent instructions only after a context synchronization event, which is the ISB. DMB and DSB order or complete memory accesses, but they are not context synchronization events, so they are the wrong tool here. Some cores happen to work without the ISB, but the architecture does not guarantee it.

Read more: Armv8-M ARM (DDI0553), CONTROL register; MSR; context synchronization

Q1.3.3 A Mainline core uses 3 priority bits, so priority values are 0x00, 0x20, … 0xE0, and PRIGROUP is at its reset value (all implemented bits are group priority). With BASEPRI = 0x40, which pending interrupt can still preempt the current Thread-mode code?

  • A. An interrupt at priority 0x40
  • B. An interrupt at priority 0x20
  • C. An interrupt at priority 0x60
  • D. None of them. Any non-zero BASEPRI masks all configurable interrupts.
Answer

B. BASEPRI raises execution priority to 0x40, and only an exception with a lower group priority value (higher urgency) can preempt. So 0x40 and 0x60 are masked and 0x20 is not. Expecting 0x40 to pass is the usual off-by-one mistake: equal priority never preempts.

Read more: Armv8-M ARM (DDI0553), BASEPRI and execution priority

1.4 Modes, privilege and the two stack pointers

Armv8-M replaces exception levels with two orthogonal ideas:

  • Mode: Thread mode runs application or RTOS task code. Handler mode is the mode while executing an exception handler. The core enters Handler mode on exception entry and returns to Thread mode when the last active exception returns. IPSR is non-zero in Handler mode.
  • Privilege: Handler mode is always privileged. Thread mode is privileged or unprivileged, according to CONTROL.nPRIV.

Unprivileged Thread code cannot clear nPRIV itself, because the write is ignored. The way up is an exception, typically SVC. The handler, which is privileged, does the work or modifies CONTROL and then returns. That is the RTOS equivalent of an EL0 to EL1 syscall.

The stack pointer is banked:

  • MSP (Main stack): always used in Handler mode. Also used in Thread mode when CONTROL.SPSEL = 0, which is the reset state.
  • PSP (Process stack): used in Thread mode when CONTROL.SPSEL = 1.

With the Security Extension, each Security state has its own MSP, PSP and CONTROL.SPSEL/nPRIV, and the core uses the copies of the current state.

A typical RTOS layout:

  • Each task runs in Thread mode on its own PSP.
  • Every handler and the kernel run on MSP.
  • On exception entry the hardware pushes the caller-saved frame (R0-R3, R12, LR, return address, xPSR, plus FP state if used) onto whichever stack was active. A Secure-to-Non-secure exception also stacks the callee-saved registers and an integrity signature.
  • The EXC_RETURN value records which stack that was, so the exception return pops from the right one.
  • A context switch (usually in PendSV) saves the remaining callee-saved registers to the old task’s PSP, updates PSP, and returns.

You name the banked registers explicitly with MRS/MSR as MSP and PSP, and with the Security Extension as MSP_NS/PSP_NS from Secure state. Plain SP (R13) always refers to the currently selected one.

Coming from A-profile: Think of MSP as SP_EL1 used by handlers, and PSP as SP_EL0 for tasks. The difference is that the hardware itself stacks the caller-saved context on entry and selects the stack from CONTROL and EXC_RETURN. No vector code saves registers manually or switches SPSel.

Checkpoint

Q1.4.1 A task running unprivileged in Thread mode on PSP takes an interrupt. Inside the ISR, which stack pointer does PUSH {r4, lr} use, and at what privilege?

  • A. PSP, privileged, because the ISR inherits the interrupted context’s stack
  • B. MSP, unprivileged, because privilege is inherited from the interrupted task
  • C. PSP, unprivileged, because CONTROL is unchanged by exception entry
  • D. MSP, privileged, because Handler mode always uses MSP and is always privileged
Answer

D. Handler mode always selects the main stack, and Handler mode is always privileged, whatever CONTROL.nPRIV says. The hardware-stacked frame went onto PSP, because that was the active stack at the time of the exception, but the handler’s own pushes go to MSP.

Read more: Armv8-M ARM (DDI0553), Modes, privilege and stacks; CONTROL.SPSEL

Q1.4.2 What is the architecturally intended way for unprivileged Thread-mode code to obtain a privileged service?

  • A. Execute MSR CONTROL with nPRIV = 0 and then an ISB
  • B. Write to the SCS to request privilege
  • C. Execute an SVC. The privileged SVCall handler performs the operation, or changes CONTROL.nPRIV, before returning.
  • D. Execute an SMC
Answer

C. Unprivileged writes to CONTROL are ignored, so the only way in is an exception, and SVC is the synchronous system-call exception. SMC does not exist on M-profile, where Security state changes use SG/BXNS/BLXNS instead. Unprivileged SCS accesses fault (apart from narrow cases such as STIR), so they cannot grant privilege.

Read more: Armv8-M ARM (DDI0553), SVCall exception; CONTROL.nPRIV

1.5 Stack limit checking: MSPLIM and PSPLIM

Armv8-M introduces hardware stack limit registers, so stack overflow detection no longer depends on an MPU guard region. Each register holds the lowest permitted address for its stack. Stacks grow down. Bits[2:0] are RES0, so a limit is 8-byte aligned.

If an instruction that updates SP, or the push during exception entry, would set the stack pointer below its limit, the core raises a stack overflow fault:

  • On Mainline it is a synchronous UsageFault with UFSR.STKOF set. It escalates to HardFault if UsageFault is not enabled.
  • On Baseline, which has no UsageFault, it is a HardFault.

The violating update is not allowed to move the stack pointer below the limit. This lets you detect the overflow before the stack overwrites the memory below it. The check is on SP updates, not on every access: a store through another base register, or an SP-relative access without writeback, that reaches below the limit is not checked, and an MSR write to MSP or PSP is not limit-checked either.

Which limit registers exist depends on the profile:

Secure MSPLIM/PSPLIMNon-secure MSPLIM/PSPLIM
MainlineYes (with Security Ext)Yes
BaselineYes (with Security Ext)Not implemented (RAZ/WI)

So a Baseline core like the Cortex-M23 checks stack limits only for Secure software, and a Baseline core without the Security Extension has no stack limit checking at all. Non-secure stacks on such cores still need MPU guard regions or software checking.

Operationally:

  • An RTOS on Mainline programs PSPLIM per task in the context switch, together with PSP.
  • Boot code sets MSPLIM once for the main stack.
  • Like the other special registers, they are written with MSR from privileged code.

Coming from A-profile: On A-profile you detect overflow with an unmapped guard page: a translation fault on any access into it, at page granularity. Here the check compares new SP values against a register at 8-byte granularity. It also covers M-profile’s hardware exception stacking, but unlike a guard page it does not catch accesses that do not update SP.

Checkpoint

Q1.5.1 A Cortex-M23 with the Security Extension runs a Non-secure RTOS. Its authors want hardware stack overflow detection for Non-secure task stacks. What does the architecture give them?

  • A. Nothing from the stack limit registers. On Baseline only the Secure MSPLIM/PSPLIM exist, and the Non-secure ones are RAZ/WI, so they need MPU guard regions or software checks.
  • B. PSPLIM_NS, which raises a STKOF UsageFault on overflow
  • C. PSPLIM_NS, which raises a HardFault on overflow, because Baseline has no UsageFault
  • D. Stack limits apply automatically at the boundary of the SAU region that contains the stack.
Answer

A. Armv8-M Baseline implements stack limit registers only for the Secure state. The Non-secure ones are not implemented. Expecting PSPLIM_NS to produce a HardFault mixes up two true facts: Baseline does use HardFault for STKOF, but only Secure stacks are checked.

Read more: Armv8-M ARM (DDI0553), Stack limit registers (MSPLIM, PSPLIM) and Baseline differences

Q1.5.2 On a Mainline core with UsageFault enabled, a task’s SUB sp, sp, #256 would move PSP below PSPLIM. What is the architected outcome?

  • A. The SUB completes, and a BusFault is raised later when the stack write reaches unmapped memory.
  • B. PSP is clamped to PSPLIM silently and execution continues.
  • C. A synchronous UsageFault with UFSR.STKOF is raised, and the violating stack pointer update is not allowed to move SP below the limit.
  • D. An asynchronous imprecise fault is raised after the instruction retires.
Answer

C. Stack limit violations are detected synchronously on the instruction that would breach the limit, and they are reported as UsageFault STKOF on Mainline. The ‘later BusFault’ option describes what can happen without limit checking, and there is no silent clamping that lets execution continue.

Read more: Armv8-M ARM (DDI0553), Stack limit checking; UFSR.STKOF

1.6 Reset, the vector table and the system address map

Reset. The core reads the vector table at the address held in VTOR. Its reset value is IMPLEMENTATION DEFINED and is often a configuration input. With the Security Extension, the Secure VTOR (VTOR_S) is the one used at reset.

word 0 : initial value of SP_main (MSP; MSP_S with Security Ext)
word 1 : reset vector (bit[0] must be 1 -> EPSR.T)
word 2+: NMI, HardFault, ... , external interrupts

After reset the core is in Thread mode, privileged, using MSP (CONTROL = 0), and in Secure state if the Security Extension is implemented. PRIMASK, FAULTMASK and BASEPRI are 0. The MPU is disabled and the configurable faults are disabled. Caches, where present, are normally off until software enables them. Because the reset vector is just an address and MSP is already loaded, the reset handler can be a C function (it still has to initialise .data/.bss before relying on them).

On Baseline, VTOR is an implementation option; on the Cortex-M23 it is a configuration choice. Relocating the table at runtime is a privileged write to VTOR. If you first copied the table into RAM, put a DMB (or DSB) between the copy and the VTOR write, because the Normal-memory stores are not ordered against the Device store. Follow the VTOR write with DSB so that it has completed before a later exception entry.

Fixed address map (default attributes apply when the MPU is off):

RangeRegion
0x00000000-0x1FFFFFFFCode (Normal, executable)
0x20000000-0x3FFFFFFFSRAM (Normal, executable)
0x40000000-0x5FFFFFFFPeripheral (Device, XN)
0x60000000-0x9FFFFFFFExternal RAM (Normal, executable)
0xA0000000-0xDFFFFFFFExternal device (Device, XN)
0xE0000000-0xE00FFFFFPPB (SCS at 0xE000E000-0xE000EFFF; XN)
0xE0100000-0xFFFFFFFFVendor_SYS (Device, XN)

The SCS holds the SCB, NVIC, SysTick, MPU, SAU, the fault status registers and debug control. PPB accesses are always little-endian and always use the default memory map, whatever the MPU says. SCS accesses are privileged-only: an unprivileged access causes a BusFault, with narrow exceptions such as STIR when CCR.USERSETMPEND is set. (Some other PPB components, such as ITM stimulus ports, can be configured for unprivileged access.)

System control is memory-mapped for two reasons: C code can configure the system with plain loads and stores, and a debugger can access the same registers over the debug access port while the core runs. The PPB is Device-nGnRnE memory. To guarantee that a configuration change, such as enabling the MPU, is in effect for the following instructions, use DSB followed by ISB.

Coming from A-profile: Where AArch64 uses MSR SCTLR_EL1/VBAR_EL1 followed by an ISB, M-profile uses stores to the SCS. Because the change is now a memory store, you first need a DSB to guarantee that the Device store has completed, and only then the ISB to refetch. DSB then ISB is the pairing to remember.

Checkpoint

Q1.6.1 Which sequence correctly describes what an Armv8-M Mainline core with the Security Extension does on reset?

  • A. It loads PC from word 0 and SP from word 1, then starts in Handler mode on MSP, Non-secure.
  • B. It branches to address 0x00000000 in Thread mode, unprivileged on PSP, and software must load SP first.
  • C. It loads PC from word 1 and starts in Handler mode with IPSR = 1 (Reset), on MSP, Secure.
  • D. It loads MSP from word 0 and PC from word 1 (EPSR.T from bit[0]) of the table at the reset VTOR, then starts in Thread mode, privileged, on MSP, in Secure state.
Answer

D. Word 0 is the initial SP_main and word 1 is the reset vector. Execution starts in privileged Thread mode on MSP, in Secure state when TrustZone is present. Treating reset as an exception that leaves you in Handler mode is tempting, but the reset handler runs in Thread mode. The table is not executed as code at address 0 either.

Read more: Armv8-M ARM (DDI0553), Reset behavior; vector table

Q1.6.2 With the MPU disabled, a corrupted function pointer holding 0x40001001 makes a Mainline core execute BLX r3, so it branches to 0x40001000 (the Peripheral region) with EPSR.T = 1. What happens?

  • A. The core executes whatever the peripheral returns as instructions.
  • B. An instruction fetch from an execute-never region is attempted, which raises a MemManage fault (IACCVIOL). If MemManage is not enabled, it escalates to HardFault.
  • C. It is undefined, because the default map gives no attributes when the MPU is off.
  • D. An INVSTATE UsageFault is raised, because the Peripheral region cannot hold T32 code.
Answer

B. The default system address map applies when the MPU is off, and it marks the Peripheral, Device and system regions as execute-never. The fetch therefore faults as an instruction access violation (MemManage, which escalates if disabled). INVSTATE depends only on EPSR.T, which is 1 here because bit[0] of the target was set, so it is a distractor.

Read more: Armv8-M ARM (DDI0553), System address map and default memory attributes

Q1.6.3 Privileged code enables the MPU by writing MPU_CTRL in the SCS, and the next instruction relies on the new protection. Which sequence is architecturally sufficient?

  • A. Store to MPU_CTRL, then DSB, then ISB
  • B. Store to MPU_CTRL, then DMB
  • C. Store to MPU_CTRL only, because SCS accesses are Device-nGnRnE and therefore immediately effective for the instruction stream
  • D. Store to MPU_CTRL, then ISB, then DSB
Answer

A. The DSB ensures that the SCS store has completed, and the ISB then flushes and refetches subsequent instructions so that they see the new MPU configuration. Device-nGnRnE ordering does not make the side effect visible to instructions already fetched, and a DMB only orders memory accesses. ISB before DSB gets the order wrong, because the context synchronization could happen before the write completes.

Read more: Armv8-M ARM (DDI0553), Memory barriers (DSB, ISB) and SCS register side effects; MPU_CTRL

2. Exception & interrupt model

How Armv8-M numbers, prioritises, enters, returns from and escalates exceptions: the vector table, NVIC, hardware stacking, EXC_RETURN, tail-chaining, lazy FP preservation, the fault registers, and how FreeRTOS builds on SVC and PendSV.

Sections

  1. Exception numbers, the vector table and priority grouping
  2. The NVIC, interrupt state and execution priority
  3. Exception entry, the stack frame and EXC_RETURN
  4. Tail-chaining, late-arrival and lazy FP state preservation
  5. Faults, escalation and fault status registers
  6. How an RTOS uses SVC and PendSV

2.1 Exception numbers, the vector table and priority grouping

Every exception has an exception number. The number indexes the vector table, and IPSR holds it while the PE is in Handler mode.

 #    Exception     Priority
 1    Reset         -4 (fixed)
 2    NMI           -2 (fixed)
 3    HardFault     -1 (fixed; Secure HardFault is -3
                        when AIRCR.BFHFNMINS == 1)
 4    MemManage     configurable   Main Ext. only
 5    BusFault      configurable   Main Ext. only
 6    UsageFault    configurable   Main Ext. only
 7    SecureFault   configurable   Main + Security Ext.
 11   SVCall        configurable
 12   DebugMonitor  configurable   Main Ext. only
 14   PendSV        configurable
 15   SysTick       configurable
 16+n external interrupt n (IRQn)

The vector table is a table of words at the address in VTOR, which is banked per Security state (VTOR_S, VTOR_NS). Word 0 holds the initial SP_main value: the PE loads it from the Secure table at reset (or from the only table without the Security Extension); for the Non-secure table, Secure software normally sets MSP_NS itself. Word n holds the handler address for exception n. Hardware fetches the vector itself, so there is no shared vector entry that software has to demultiplex. Bit[0] of each vector is copied to EPSR.T, so it must be 1 (Thumb).

Priority: a lower number means a higher priority. A configurable priority is an 8-bit field, but only an IMPLEMENTATION DEFINED number of its most significant bits is implemented (at least 3 with the Main Extension, 2 on Baseline). The unimplemented low bits are RAZ/WI.

Grouping (Main Extension only): AIRCR.PRIGROUP splits each priority value into a group priority, bits [7:PRIGROUP+1], and a subpriority, bits [PRIGROUP:0]. Writes to AIRCR must include VECTKEY = 0x05FA in bits [31:16].

  • Only the group priority decides preemption. A pending exception preempts only if its group priority is strictly higher than the current execution priority.
  • The subpriority, then the exception number (lower wins), only decide which of several pending exceptions with the same group priority is taken first.
  • On Baseline PRIGROUP is RES0, and with only bits [7:6] implemented the whole implemented field acts as the group priority.

Coming from A-profile: In A-profile the GIC’s priority mask (ICC_PMR) and binary point (ICC_BPRn) decide masking and preemption, and every IRQ arrives at the same IRQ entry of the VBAR_ELx table (one per source EL/stack), so software must read ICC_IAR to find out which interrupt it is. Here PRIGROUP plays the binary-point role, and the hardware fetches a separate handler address for each exception number.

Checkpoint

Q2.1.1 Assume at least 4 priority bits are implemented and AIRCR.PRIGROUP = 5, so the group priority is bits [7:6]. IRQ A (priority 0x50) is active. IRQ B (priority 0x40) becomes pending. What happens?

  • A. B preempts A immediately, because 0x40 is numerically lower than 0x50
  • B. B preempts A only if B has the lower exception number
  • C. B does not preempt A, because both have group priority 1. B is taken when A returns (typically by tail-chaining), ahead of other pending exceptions at that group priority with a higher subpriority value
  • D. B is discarded, because exceptions in the same priority group cannot both be pending
Answer

C. 0x40 = 0b01_000000 and 0x50 = 0b01_010000. With PRIGROUP = 5 both have group priority 0b01, and preemption needs a strictly higher group priority. Subpriority only orders pending exceptions. The tempting answer, ‘lower number preempts’, compares the full 8-bit value and ignores grouping.

Read more: Armv8-M ARM (DDI0553), Exception model: priority grouping, AIRCR.PRIGROUP

Q2.1.2 You are porting startup code from a Cortex-M33 (Mainline) to a Cortex-M23 (Armv8-M Baseline). Which of these exception handlers can still be taken on Baseline?

  • A. MemManage
  • B. SVCall
  • C. UsageFault
  • D. DebugMonitor
Answer

B. SVCall exists in both profiles. MemManage, BusFault, UsageFault and DebugMonitor need the Main Extension. On Baseline, the fault conditions that would raise MemManage, BusFault or UsageFault are reported as HardFault, and Baseline has only halting debug, so there are no DebugMonitor exceptions. A UsageFault handler installed on Baseline does nothing, because that vector is never used.

Read more: Armv8-M ARM (DDI0553), Exception numbers; Main Extension

Q2.1.3 A vector table entry for an IRQ holds an even address (bit[0] = 0). What does the architecture say happens when that IRQ is taken?

  • A. The handler executes in A32 state
  • B. The PE enters lockup immediately while fetching the vector
  • C. The PE silently sets bit[0] and executes the handler normally
  • D. EPSR.T is cleared, and executing the handler’s first instruction raises an INVSTATE UsageFault (or HardFault if it escalates)
Answer

D. Bit[0] of the vector is copied into EPSR.T. M-profile has no A32 state, so executing with T = 0 raises an INVSTATE UsageFault. If that UsageFault is disabled or cannot be taken, or on Baseline, it is reported as HardFault. It is a classic bring-up symptom of a toolchain that does not mark handler symbols as Thumb. The A32 answer is what an A-profile engineer might assume, but M-profile can only execute T32.

Read more: Armv8-M ARM (DDI0553), Exception entry: vector table; UFSR.INVSTATE

2.2 The NVIC, interrupt state and execution priority

The NVIC is part of the PE’s System Control Space (SCS), at 0xE000E100 onward. It is not a separate distributor or redistributor. Each external interrupt has a bit or byte in these registers:

  • NVIC_ISERn / NVIC_ICERn: write 1 to enable or disable the interrupt. Reads return the enable state.
  • NVIC_ISPRn / NVIC_ICPRn: write 1 to set or clear the pending state. Software can pend a disabled interrupt.
  • NVIC_IABRn: read-only active bits.
  • NVIC_IPRn: one priority byte per interrupt. Byte access works with the Main Extension; on Baseline parts such as Cortex-M23, use word accesses.
  • NVIC_ITNSn (Security Extension): 1 targets the interrupt at Non-secure state. ITNS is RAZ/WI to Non-secure accesses, and in the other NVIC registers the bits of Secure-targeted interrupts are RAZ/WI from Non-secure state.

The system exceptions are controlled through the SCB instead: SHPRn sets priorities, SHCSR holds enables plus active and some pending bits, and ICSR holds PENDSVSET, PENDSTSET and similar bits.

No acknowledge or EOI step. Taking an exception moves it from pending to active automatically. The exception return deactivates it. For a level-sensitive source that is still asserted after the return, the NVIC sets the pending state again.

Execution priority is the highest of these:

  • the group priority of every active exception;
  • PRIMASK = 1, which boosts the execution priority to 0 and so masks every configurable-priority exception;
  • BASEPRI (Main Extension), whose non-zero value boosts the execution priority to that value. BASEPRI = 0 has no effect;
  • FAULTMASK = 1 (Main Extension), which boosts it to -1. FAULTMASK is cleared on exception return, except on return from NMI.

With the Security Extension these masks are banked per Security state, the FAULTMASK and HardFault levels depend on AIRCR.BFHFNMINS, and AIRCR.PRIS changes how Non-secure priorities map. That detail is left out here.

Synchronisation: NVIC/SCS registers are accessed with loads and stores. To guarantee that a change (for example an ICER disable) is in effect for the instructions that follow it, issue DSB and then ISB. The DSB waits until the store has completed, and the ISB flushes the pipeline so that later instructions are fetched and executed under the new state. A DMB is not enough, because it only orders memory accesses against each other and does not wait for completion.

Coming from A-profile: With the GIC you read ICC_IAR to acknowledge an interrupt and write ICC_EOIR (and ICC_DIR when EOImode = 1) to finish it. On M-profile, exception entry and exception return do that work, so a handler is an ordinary AAPCS function with no interrupt-controller handshake.

Checkpoint

Q2.2.1 A handler for a level-sensitive peripheral interrupt returns without clearing the interrupt condition in the peripheral. What happens on Armv8-M?

  • A. The interrupt stays active forever, blocking itself and lower priorities, because no EOI was written
  • B. The interrupt is pending again after the return, so the handler runs again (often by tail-chaining), repeatedly while the line stays asserted
  • C. Nothing, because NVIC interrupts are edge-triggered and the condition is ignored until a new edge
  • D. A UsageFault is raised for returning with an unserviced interrupt
Answer

B. The exception return deactivates the interrupt. A level input that is still asserted then sets the pending state again, and the handler re-enters, often without any Thread-mode instruction executing in between. ‘Active forever’ is the GIC mental model where a missing EOI leaves the interrupt active, but M-profile has no EOI step.

Read more: Armv8-M ARM (DDI0553), NVIC: interrupt states; Exception return

Q2.2.2 Code in Thread mode on a Mainline core executes MOVS r0, #0; MSR BASEPRI, r0. What is the effect on interrupt masking?

  • A. All configurable-priority exceptions are masked, because priority 0 is the highest
  • B. Only exceptions with priority 0 are masked
  • C. Nothing is masked, because BASEPRI = 0 disables the BASEPRI boost
  • D. NMI and HardFault are also masked
Answer

C. A BASEPRI value of zero means no boost. Only a non-zero value raises the execution priority to that level. Masking everything configurable is the job of PRIMASK = 1, and only FAULTMASK reaches -1. FreeRTOS relies on this when it leaves a critical section by writing 0 to BASEPRI.

Read more: Armv8-M ARM (DDI0553), Special registers: BASEPRI, PRIMASK, FAULTMASK

Q2.2.3 IRQ 37 is pending but disabled. Software writes the IRQ’s bit in NVIC_ICER1, and later writes the same bit in NVIC_ISER1. What happens?

  • A. The interrupt is taken once it is enabled (if priority allows), because writing ICER disables the interrupt but does not clear its pending state
  • B. Nothing, because writing ICER also clears the pending bit
  • C. The ISER write faults because the interrupt is still pending
  • D. The interrupt is taken immediately when ICER is written
Answer

A. Enable and pending are independent state. ICER only clears the enable. Discarding a pending interrupt needs a write to ICPR, and for a level source the peripheral must also stop asserting the line, otherwise it pends again. Assuming ICER clears the pending state causes spurious interrupts when drivers re-enable an interrupt.

Read more: Armv8-M ARM (DDI0553), NVIC_ICERn, NVIC_ICPRn

2.3 Exception entry, the stack frame and EXC_RETURN

On exception entry the PE stacks the caller-saved state, so the handler can be a plain AAPCS function. The frame goes on the stack that was in use at the moment of the exception:

  • the Process stack (PSP) if the PE was in Thread mode with CONTROL.SPSEL = 1;
  • otherwise the Main stack (MSP).

Both are the stack pointers of the interrupted context’s Security state. The handler always runs on the MSP of the Security state that the exception is taken to.

basic frame (lowest address first)
+0x00 R0   +0x04 R1   +0x08 R2   +0x0C R3
+0x10 R12  +0x14 LR   +0x18 ReturnAddress
+0x1C RETPSR
extended frame adds S0-S15, FPSCR, then a
reserved word (VPR on v8.1-M with MVE)
  • Alignment: the frame is always 8-byte aligned (CCR.STKALIGN is RES1 in v8-M). If SP was only 4-byte aligned, the PE inserts one padding word and sets RETPSR[9] (SPREALIGN), so the return can undo it.
  • In addition to stacking, the PE writes the exception number to IPSR and switches to Handler mode. It loads LR with an EXC_RETURN value and branches to the vector.
  • If a Secure context is interrupted by a Non-secure exception, the PE also stacks the additional state context (an integrity signature, a reserved word and R4-R11), then clears the registers. EXC_RETURN.DCRS records this. With Secure FP context and FPCCR.TS = 1, S16-S31 are stacked as well.

EXC_RETURN = 0xFF in bits [31:24], bits [23:7] RES1, bit[1] RES0:

  • bit[0] ES: Security state the exception was taken to (1 = Secure)
  • bit[2] SPSEL: frame on Main (0) or Process (1) stack
  • bit[3] Mode: return to Thread (1) or Handler (0)
  • bit[4] FType: 1 = basic frame, 0 = extended frame with FP state
  • bit[5] DCRS: 1 = default rules (callee-saved registers not stacked), 0 = callee-saved registers were stacked
  • bit[6] S: frame on Secure (1) or Non-secure (0) stack

Without the Security Extension, ES and S read as 0 and DCRS as 1.

Return: there is no ERET. An exception return happens when an EXC_RETURN value is loaded into PC in Handler mode, by BX LR, POP {..., PC}, LDM or LDR PC. An inconsistent EXC_RETURN raises a fault, usually an INVPC UsageFault, or a SecureFault (for example INVER) for Security-state inconsistencies.

Coming from A-profile: In A-profile, ELR_ELx and SPSR_ELx are system registers and the handler must save its own GPRs before ERET. On M-profile, hardware puts ReturnAddress and RETPSR in memory on the stack with R0-R3/R12/LR, and LR holds only a special token that describes that frame.

Checkpoint

Q2.3.1 An exception is taken from Thread mode on MSP with SP = 0x2000_1004 and no FP context active. Where is the basic frame placed, and what does RETPSR record?

  • A. 0x2000_0FE4 to 0x2000_1003, with RETPSR[9] = 0
  • B. An UNALIGNED UsageFault is raised, because the stack must be 8-byte aligned before entry
  • C. The frame is placed only if CCR.STKALIGN was set by software, otherwise at 0x2000_0FE4
  • D. 0x2000_0FE0 to 0x2000_0FFF with one padding word above it, and RETPSR[9] (SPREALIGN) = 1
Answer

D. 0x2000_1004 - 32 = 0x2000_0FE4, which is not 8-byte aligned. The PE inserts a 4-byte pad, so the frame starts at 0x2000_0FE0, and it sets RETPSR[9]. On return the PE adds the pad back to restore the original SP. CCR.STKALIGN is RES1 in v8-M, so software cannot turn this off.

Read more: Armv8-M ARM (DDI0553), Exception entry: stack alignment, RETPSR

Q2.3.2 The FreeRTOS Armv8-M Non-secure port seeds each new task with EXC_RETURN = 0xFFFFFFBC. Decode bits [6:0].

  • A. S = 0 (Non-secure stack), DCRS = 1, FType = 1 (basic frame), Mode = 1 (Thread), SPSEL = 1 (PSP), ES = 0 (exception taken to Non-secure)
  • B. S = 1, DCRS = 0, FType = 0 (extended frame), Mode = 0 (Handler), SPSEL = 0 (MSP), ES = 1
  • C. S = 0, DCRS = 1, FType = 1, Mode = 1, SPSEL = 0 (MSP), ES = 0
  • D. It is not a valid EXC_RETURN, because bit[7] must be 0
Answer

A. 0xBC = 0b1011_1100: bit6 S = 0, bit5 DCRS = 1, bit4 FType = 1, bit3 Mode = 1, bit2 SPSEL = 1, bit1 = 0, bit0 ES = 0. That means return to Non-secure Thread mode on PSP with a basic frame. Bit[7] is RES1, so the last option is backwards. The tempting misreading swaps the polarity of FType: FType = 1 means the basic frame without FP state.

Read more: Armv8-M ARM (DDI0553), EXC_RETURN payload

Q2.3.3 Why can an exception handler written as an ordinary C function (no special attribute) return correctly on Armv8-M?

  • A. The compiler detects the vector table and emits an ERET in place of the function’s return
  • B. The C epilogue (BX LR or POP {..., PC}) loads the EXC_RETURN value from LR into PC in Handler mode, which the hardware treats as an exception return, and R0-R3/R12 were already stacked
  • C. The NVIC watches for the handler’s stack pointer to return to its entry value
  • D. Handlers must call a library routine that writes an EOI register before returning
Answer

B. Hardware stacked every caller-saved register, and LR holds EXC_RETURN. The AAPCS epilogue therefore performs the exception return without modification. M-profile has no ERET instruction, and there is no EOI register to write.

Read more: Armv8-M ARM (DDI0553), Exception return

2.4 Tail-chaining, late-arrival and lazy FP state preservation

Tail-chaining: a handler executes its exception return, and at that point a pending exception has a group priority higher than the execution priority of the context being returned to. The architecture permits the PE to enter the new handler directly, without unstacking the frame and stacking it again. The frame on the stack still describes the original interrupted context. Cortex-M implementations do this.

Late-arrival: a higher-priority exception arrives while the PE is still stacking for a lower-priority one. The PE can keep the frame being stacked and fetch the vector of the higher-priority exception. The lower-priority exception stays pending and is usually tail-chained afterwards.

Lazy FP preservation (Floating-point Extension, which requires the Main Extension). The controls are in FPCCR, some of whose bits are banked per Security state:

  • ASPEN: when 1, executing an FP instruction sets CONTROL.FPCA. With FPCA = 1 at entry, the PE builds an extended frame (EXC_RETURN.FType = 0). If ASPEN = 0, software manages FPCA and FP context itself.
  • LSPEN: when 1 (and FPCA = 1 at entry), the PE reserves space for S0-S15 and FPSCR in the frame but does not write them. It records that address in FPCAR and sets LSPACT = 1.
  • If the handler then executes an FP instruction while LSPACT = 1, the PE first stores the interrupted context’s FP registers into the reserved space. It then clears LSPACT, and the instruction proceeds.
  • On return with an extended frame: if LSPACT is still 1, the FP registers were never saved and still hold the interrupted context’s values. The PE clears LSPACT and does not reload them. Otherwise it unstacks them from the frame.

Integer-only handlers therefore pay for the reserved stack space but not for the memory traffic. The interrupted stack must still have room for the extended frame.

Coming from A-profile: In A-profile, lazy FP/SIMD switching is an OS policy that traps FP accesses through CPACR_EL1.FPEN and handles the trap in software. On M-profile the PE does it in hardware, within the exception entry and return, using FPCAR and LSPACT.

Checkpoint

Q2.4.1 FPCCR.ASPEN = 1, LSPEN = 1. A Thread executed a VADD.F32 (so CONTROL.FPCA = 1) and is interrupted by an IRQ whose handler uses no FP instructions. What happens to S0-S15 and FPSCR?

  • A. They are written to the stack on entry and read back on return
  • B. They are not preserved at all, because the handler does not use FP
  • C. Space is reserved in an extended frame, FPCAR points to it and LSPACT is set. The registers are never written, and on return LSPACT is cleared without reloading them
  • D. They are copied to a dedicated FP shadow bank inside the FPU
Answer

C. With LSPEN = 1, entry only reserves space and arms LSPACT. Because the handler never touched FP, the live registers still hold the Thread’s values, and the return only clears LSPACT. Eager save and restore is what happens with LSPEN = 0. The ‘not preserved’ option ignores that FPCA = 1 still forces an extended frame.

Read more: Armv8-M ARM (DDI0553), Lazy Floating-point context preservation; FPCCR, FPCAR

Q2.4.2 In the same setup, the IRQ handler later executes a VMUL.F32. What happens immediately before that instruction executes?

  • A. The PE stores the interrupted context’s FP registers into the space at FPCAR and clears LSPACT, then executes the VMUL
  • B. A NOCP UsageFault is raised so that software can save the FP context
  • C. Nothing, because the handler simply overwrites the Thread’s S registers
  • D. The PE writes the handler’s FP registers to FPCAR
Answer

A. The first FP instruction executed while LSPACT = 1 triggers the deferred save of the interrupted context, then the instruction executes. Faulting so that software saves the context is the A-profile trap-and-save model; NOCP on M-profile indicates the coprocessor is disabled or inaccessible, not a lazy-save trap.

Read more: Armv8-M ARM (DDI0553), Lazy Floating-point context preservation; UFSR.NOCP

Q2.4.3 Handler A (group priority 0x40) interrupted Thread mode and is now returning. IRQ B (group priority 0x80) is pending, and no masks are set. What happens?

  • A. B waits until at least one Thread instruction has executed
  • B. B is taken by tail-chaining: the PE enters B’s handler without unstacking and restacking the Thread’s frame
  • C. B is not taken, because 0x80 is lower priority than the returning handler A
  • D. The Thread’s frame is unstacked, then a new frame is stacked for B
Answer

B. At the return, B is compared with the execution priority of the context being returned to, which is Thread mode with no boost. B beats that, so it is tail-chained and reuses the existing frame. Comparing against A is the tempting mistake, because A is no longer active at that point.

Read more: Armv8-M ARM (DDI0553), Exception return; tail-chaining

2.5 Faults, escalation and fault status registers

Enabling. HardFault is always enabled. SHCSR.MEMFAULTENA, BUSFAULTENA, USGFAULTENA and, with the Security Extension, SECUREFAULTENA enable the configurable faults (Main Extension).

Escalation. A synchronous configurable fault escalates to HardFault, with HFSR.FORCED = 1, when either of these holds:

  • the fault is disabled;
  • its priority is not high enough to preempt the current execution priority, for example a UsageFault inside a handler of equal or higher priority, or with FAULTMASK set.

HFSR.VECTTBL indicates a BusFault on a vector table read during exception processing, which is always reported as HardFault. On Baseline, all of these fault conditions go to HardFault.

Status. The CFSR status bits are still set when a fault escalates, so always read them in a HardFault handler.

CFSR  0xE000ED28
  [31:16] UFSR  UNDEFINSTR INVSTATE INVPC NOCP
                STKOF UNALIGNED DIVBYZERO
  [15:8]  BFSR  IBUSERR PRECISERR IMPRECISERR
                UNSTKERR STKERR LSPERR BFARVALID
  [7:0]   MMFSR IACCVIOL DACCVIOL MUNSTKERR
                MSTKERR MLSPERR MMARVALID
MMFAR / BFAR: fault address, valid only
              when MMARVALID / BFARVALID = 1

The status bits are write-one-to-clear. UNALIGNED and DIVBYZERO trap ordinary unaligned accesses and divides by zero only when CCR.UNALIGN_TRP and CCR.DIV_0_TRP are set. Unaligned LDM/STM/LDRD/STRD, exclusive and load-acquire/store-release accesses always fault. STKOF reports a violation of the v8-M stack limit registers, MSPLIM and PSPLIM.

Precise vs imprecise BusFault.

  • A precise BusFault (PRECISERR) is synchronous. The stacked ReturnAddress identifies the faulting instruction, and BFAR is usually valid.
  • An imprecise BusFault (IMPRECISERR) is asynchronous, typically a buffered store whose bus error came back later. The stacked ReturnAddress points somewhere after the store, and BFAR is not valid.
  • An asynchronous BusFault becomes pending and is taken when its priority allows. It is not escalated on priority grounds the way a synchronous fault is. If BusFault is disabled, it is reported as HardFault instead.

Coming from A-profile: There is no ESR_ELx/FAR_ELx pair with an exception-class field. Status is split across CFSR’s three sub-registers plus HFSR, and an imprecise BusFault behaves like an asynchronous SError: the reported PC is not the faulting instruction.

Checkpoint

Q2.5.1 SHCSR.USGFAULTENA = 0. Thread code executes a UDF instruction. What does the HardFault handler observe?

  • A. Nothing, because a disabled UsageFault means the UDF executes as a NOP
  • B. CFSR is zero, because only HFSR records escalated faults
  • C. HFSR.DEBUGEVT = 1, because UDF is treated as a breakpoint
  • D. HardFault is taken with HFSR.FORCED = 1, and CFSR.UFSR.UNDEFINSTR = 1 identifies the original cause
Answer

D. A disabled configurable fault escalates to HardFault and sets HFSR.FORCED. The UFSR bit is still set, which is why a HardFault handler should always dump CFSR. ‘CFSR stays zero’ is the tempting assumption, but the sub-register status bits are recorded whether or not the fault escalated.

Read more: Armv8-M ARM (DDI0553), HFSR, CFSR, SHCSR; fault escalation

Q2.5.2 BFSR shows IMPRECISERR = 1 and BFARVALID = 0. What is the correct conclusion?

  • A. The stacked ReturnAddress identifies the faulting load or store
  • B. The fault was asynchronous, for example a buffered store. The stacked ReturnAddress is somewhere after the faulting access, and no fault address was recorded
  • C. The fault came from an instruction fetch
  • D. The MPU blocked the access, so MMFAR holds the address
Answer

B. IMPRECISERR means the bus error was reported asynchronously relative to the instruction that caused it, so neither the stacked PC nor BFAR pins it down. An instruction-fetch error sets IBUSERR, and an MPU violation is a MemManage fault, not a BusFault.

Read more: Armv8-M ARM (DDI0553), BFSR: PRECISERR, IMPRECISERR, BFARVALID

2.6 How an RTOS uses SVC and PendSV

The FreeRTOS Cortex-M ports, including the v8-M CM33/CM23 ports you may have brought up, use SVC and PendSV as follows.

Starting the first task: SVC. vStartFirstTask resets MSP from word 0 of the vector table at VTOR, enables interrupts, and executes SVC. The SVCall handler loads the first task’s saved context and points PSP (and PSPLIM on v8-M) at its frame. It then returns with an EXC_RETURN such as 0xFFFFFFBC (Non-secure Thread, PSP). That single exception return switches to Thread mode, selects PSP, pops the task’s crafted frame and jumps to its entry point. The crafted frame has RETPSR.T = 1, PC = task function and LR = the task-exit trap. Using an exception return does all of this in one architected step.

Context switching: PendSV at the lowest priority. SysTick and other ISRs request a switch by writing ICSR.PENDSVSET. When a task yields, portYIELD follows that write with DSB; ISB: the DSB makes the write complete, and the ISB makes sure the now-pending PendSV is taken before the next instruction when it is not masked. PendSV runs at the lowest priority, so it is taken only once no other handler is active, typically by tail-chaining out of the last ISR. At that point the frame on PSP is the task’s frame, and no ISR is delayed by the switch.

The handler does the following:

  • saves R4-R11, EXC_RETURN and (v8-M) PSPLIM below the hardware frame;
  • if EXC_RETURN.FType == 0, also saves S16-S31; that VSTM is an FP instruction, so it triggers any pending lazy save of S0-S15;
  • stores PSP in the TCB and calls vTaskSwitchContext;
  • restores the next task’s registers and returns through its EXC_RETURN.

Critical sections raise BASEPRI to configMAX_SYSCALL_INTERRUPT_PRIORITY (Mainline). ISRs with a higher priority (a numerically lower value) are never masked, so they must not call FreeRTOS APIs. With configASSERT defined, vPortValidateInterruptPriority asserts on this. Baseline has no BASEPRI, so the CM23 port uses PRIMASK.

Coming from A-profile: There is no EL1 kernel entry vector and no TPIDR/SP_EL0 swap. The OS uses the M-profile exception return itself as its context-switch primitive: PendSV plays the role of a deferred-reschedule IRQ, and SVC the role of the first ERET to EL0.

Checkpoint

Q2.6.1 Why does FreeRTOS run PendSV at the lowest configurable priority?

  • A. Because PendSV is the only exception allowed to write PSP
  • B. Because the architecture fixes PendSV at the lowest priority
  • C. So that the switch is deferred until no other handler is active, typically tail-chained from the last ISR. The frame on PSP is then the interrupted task’s, and no ISR is delayed by the context switch
  • D. Because a lower priority makes PendSV non-preemptible
Answer

C. At the lowest priority, PendSV can only run when it would return to Thread mode, so it swaps the task context cleanly and never nests inside an ISR. PendSV’s priority is configurable (SHPR3), not fixed, and any privileged code can write PSP. A low priority makes a handler more preemptible, not less.

Read more: Armv8-M ARM (DDI0553), PendSV, SHPR3, ICSR.PENDSVSET; FreeRTOS ARM_CM33 port.c

Q2.6.2 What is the essential reason the port starts the first task with SVC rather than simply jumping to the task function from main?

  • A. Privileged Thread mode cannot write CONTROL.SPSEL, so only an exception can select PSP
  • B. SVC is the only way to enable interrupts on Armv8-M
  • C. Without SVC, the MPU would block execution of task code
  • D. An exception return loads the task’s crafted frame (PC, RETPSR, R0, LR, …) and selects Thread mode, PSP and Security state from EXC_RETURN in one step, exactly as every later context switch does
Answer

D. Using an exception return makes the first task start the same way as every later switch, from a frame the PendSV/SVC path understands, and it loads xPSR from the frame’s RETPSR in the same step. Privileged Thread code can write CONTROL.SPSEL with MSR, so that tempting option is false. Interrupts are enabled with CPSIE or MSR, not SVC.

Read more: Armv8-M ARM (DDI0553), EXC_RETURN; CONTROL register; FreeRTOS ARM_CM33 port.c

Q2.6.3 In a FreeRTOS PendSV handler on Cortex-M33, why does the code test bit[4] of the EXC_RETURN value in LR before saving S16-S31?

  • A. FType = 0 means the hardware built an extended frame because the task had live FP context (CONTROL.FPCA = 1), so the callee-saved S16-S31 must also be saved
  • B. Bit[4] is SPSEL; it tells the handler which stack the task used
  • C. Bit[4] indicates whether the task was Secure
  • D. S16-S31 must always be saved, and the test only selects the instruction encoding
Answer

A. EXC_RETURN.FType = 0 indicates an extended frame. The hardware (lazily) handles S0-S15 and FPSCR, but S16-S31 are callee-saved and belong to the task, so the switch code must save them. Tasks that never used FP skip that cost. SPSEL is bit[2] and the S bit is bit[6].

Read more: Armv8-M ARM (DDI0553), EXC_RETURN.FType; FreeRTOS ARM_CM33 portasm.c

3. Memory model, MPU & barriers

Covers the Armv8-M default memory map and memory types, the PMSAv8 MPU (RBAR/RLAR/MAIR, overlap faults, PRIVDEFENA/HFNMIENA, banked Secure/Non-secure MPUs), DMB/DSB/ISB semantics and where they are needed, LDREX/STREX monitor behaviour across exceptions, and L1 cache maintenance for DMA coherency.

Sections

  1. The default memory map and v8-M memory types
  2. PMSAv8 regions: MPU_RBAR, MPU_RLAR, MPU_MAIRn
  3. MPU control, overlap faults and the banked Secure/Non-secure MPUs
  4. DMB, DSB, ISB: semantics and where they are needed
  5. Exclusives: LDREX/STREX, CLREX and the monitors
  6. L1 caches, cache maintenance and DMA coherency

3.1 The default memory map and v8-M memory types

On A-profile, memory attributes come from the translation tables. With stage 1 translation disabled, data accesses are treated as Device-nGnRnE. M-profile instead has a fixed system address map that gives every address a memory type, cacheability and execute permission. This map applies when the MPU is disabled. It is also the background map that the MPU can fall back to.

RangeRegionDefault attributes
0x00000000-0x1FFFFFFFCodeNormal, Write-Through, executable
0x20000000-0x3FFFFFFFSRAMNormal, Write-Back Write-Allocate, executable
0x40000000-0x5FFFFFFFPeripheralDevice-nGnRE, XN
0x60000000-0x9FFFFFFFRAMNormal (WBWA below 0x80000000, WT above), executable
0xA0000000-0xDFFFFFFFDeviceDevice-nGnRE, XN
0xE0000000-0xFFFFFFFFSystemPPB is Device-nGnRnE, Vendor_SYS is Device-nGnRE; the whole region is XN

Two rules about the System region matter later:

  • The System region is always execute-never, whatever the MPU says.
  • Accesses to the PPB (0xE0000000-0xE00FFFFF) always use the default map, and the MPU does not apply to them. The PPB holds the SCS, which contains the SCB, NVIC, SysTick and MPU registers. So an MPU region cannot lock privileged code out of the MPU registers. Most PPB accesses still require privilege.

The memory types are the same as in v8-A:

  • Normal memory has inner and outer cacheability (Non-cacheable, Write-Through, Write-Back, with allocation hints) and a shareability. The hardware may merge, reorder and speculatively access it.
  • Device memory comes in four types: Device-nGnRnE, Device-nGnRE, Device-nGRE and Device-GRE. G, R and E mean Gathering, Reordering and Early write acknowledgement. Speculative data accesses to Device memory are not permitted.

Do not plan on executing from Device memory. Every Device region in the default map is XN, and an MPU region that you give a Device attribute should be marked XN as well.

Coming from A-profile: With stage 1 translation off, an AArch64 core treats data accesses as Device-nGnRnE. An Armv8-M core with the MPU off still has cacheable Normal SRAM and code regions, because the default map gives them real attributes.

Checkpoint

Q3.1.1 The MPU is disabled. Firmware branches to a function that it copied to address 0x40001000 in a peripheral-region SRAM. What happens?

  • A. The code runs normally, because XN applies only when the MPU is enabled
  • B. The instruction fetch faults (MemManage on Mainline if it is enabled, otherwise HardFault; HardFault on Baseline), because the Peripheral region is XN in the default memory map
  • C. The code runs, but slowly, because Device memory cannot be prefetched
  • D. The fetch is treated as Normal Non-cacheable and succeeds
Answer

B. The default system address map makes the Peripheral region (0x40000000-0x5FFFFFFF) execute-never, with or without the MPU. If MemManage is disabled in SHCSR, the fault escalates to HardFault. The tempting wrong idea is that XN is only an MPU attribute, but the default map has its own XN regions.

Read more: Armv8-M ARM (DDI0553), the system address map / default memory map

Q3.1.2 A privileged task programs an MPU region over 0xE000E000 with privileged no-access, then enables the MPU. What happens on its next write to the NVIC?

  • A. MemManage fault, because the region denies access
  • B. The write succeeds only if PRIVDEFENA is 1
  • C. HardFault, because the MPU region overlaps the background region
  • D. The write succeeds, because accesses to the PPB always use the default memory map and the MPU does not check them
Answer

D. The MPU does not apply to PPB accesses. They always use the default map, which is how the SCS stays reachable for privileged code. PRIVDEFENA only matters for addresses that match no MPU region, and it does not decide this case.

Read more: Armv8-M ARM (DDI0553), the PPB and MPU interaction in the system address map

3.2 PMSAv8 regions: MPU_RBAR, MPU_RLAR, MPU_MAIRn

The Armv8-M MPU (PMSAv8) describes each region with a base and an inclusive limit, both at 32-byte granularity. This replaces the Armv7-M (PMSAv7) scheme, in which a region was a power of two in size, aligned to its size, and split into eight subregions.

You select a region with MPU_RNR, then write two registers:

MPU_RBAR: BASE[31:5] | SH[4:3] | AP[2:1] | XN[0]
MPU_RLAR: LIMIT[31:5] | PXN[4] (v8.1-M) | AttrIndx[3:1] | EN[0]
  • Address range: The region covers BASE:00000 up to and including LIMIT:11111. A 200-byte buffer therefore takes 224 bytes at any 32-byte-aligned base. PMSAv7 would have needed 256 bytes aligned to 256.
  • AP[2:1]: AP[2] makes the region read-only. AP[1] allows unprivileged access. So 00 is privileged read/write, 01 is read/write at any privilege, 10 is privileged read-only, and 11 is read-only at any privilege. No encoding gives privileged read/write together with unprivileged read-only, which PMSAv7 did allow.
  • SH: 00 Non-shareable, 10 Outer Shareable, 11 Inner Shareable. 01 is reserved. SH has no effect for Device memory, which is always treated as Shareable.
  • AttrIndx: Selects one of eight attribute bytes in MPU_MAIR0 (Attr0-3) and MPU_MAIR1 (Attr4-7). These are encoded like AArch64 MAIR_ELx. 0b0000dd00 is Device, where dd = 00 nGnRnE, 01 nGnRE, 10 nGRE, 11 GRE. Otherwise the high nibble gives outer and the low nibble inner Normal attributes. For example, 0x44 is Normal Non-cacheable and 0xFF is Write-Back Non-transient Read/Write-Allocate.

On Mainline, the alias registers MPU_RBAR_A1..A3 and MPU_RLAR_A1..A3 access the region numbered MPU_RNR[7:2]:n. Within an aligned group of four regions, you can program all four with one block store and without rewriting MPU_RNR.

Coming from A-profile: Think of each region as one identity-mapped translation-table block descriptor with an arbitrary span at 32-byte granularity. AttrIndx into MAIR works just like the 3-bit AttrIndx in an AArch64 descriptor.

Checkpoint

Q3.2.1 A 1000-byte stack starts at 0x20001020. What is the smallest PMSAv8 region that covers it, and how is it programmed?

  • A. BASE=0x20001020, LIMIT=0x20001408, because LIMIT is the exclusive end of the stack
  • B. Not possible: the region must be 1024 bytes and aligned to 1024
  • C. BASE=0x20001020, LIMIT field=0x20001400 (inclusive end 0x2000141F), which gives 1024 bytes, 24 more than the stack, because 1000 is not a multiple of 32
  • D. BASE=0x20001000, LIMIT=0x200013FF, because BASE must be aligned to the region size
Answer

C. The stack’s last byte is 0x20001407. LIMIT is inclusive with bits[4:0] taken as 0x1F, so the 32-byte granule 0x20001400 must be the limit, and the region covers 1024 bytes. No alignment to the region size is needed. The power-of-two answer and the size-aligned answer both describe PMSAv7 rules, which Armv8-M dropped.

Read more: Armv8-M ARM (DDI0553), MPU_RBAR / MPU_RLAR register descriptions

Q3.2.2 MPU_MAIR0.Attr1 = 0x04 and a region uses AttrIndx=1 with SH=0b11. What is the effective memory type?

  • A. Device-nGnRE. SH has no effect for Device memory
  • B. Normal Inner Shareable, Inner Write-Through
  • C. Device-nGnRnE, Inner Shareable
  • D. Normal Non-cacheable
Answer

A. 0x04 is 0b0000_0100: the high nibble 0000 selects Device, and dd=01 selects nGnRE. SH has no effect for Device memory. Reading 0x04 as a pair of Normal nibbles is the usual mistake, but a high nibble of 0000 means Device.

Read more: Armv8-M ARM (DDI0553), MPU_MAIR0 / MPU_MAIR1 attribute encoding

3.3 MPU control, overlap faults and the banked Secure/Non-secure MPUs

MPU_CTRL has three bits:

  • ENABLE[0] turns the MPU on.
  • HFNMIENA[1] controls whether the MPU stays enabled when execution priority is negative (HardFault, NMI, or FAULTMASK set). If it is 0, the MPU is ignored at those priorities and the default map is used. HFNMIENA=1 with ENABLE=0 is UNPREDICTABLE.
  • PRIVDEFENA[2] makes the default map act as a background region for privileged accesses that match no enabled region. When the MPU is applied, an unprivileged access that matches no region faults.

Overlaps: In PMSAv7, overlapping regions were allowed and the higher-numbered region won. In PMSAv8, an access whose address matches more than one enabled region generates a MemManage fault. Baseline has no MemManage exception, so there it is a HardFault. The RTOS trick of putting a small, more permissive region on top of a larger one no longer works. You have to divide the address space into regions that do not overlap.

Security Extension: When it is implemented, the MPU is banked. There are separate Secure and Non-secure MPUs, each with its own MPU_TYPE, MPU_CTRL, MPU_RNR, MPU_RBAR, MPU_RLAR and MPU_MAIRn. They can have different region counts, read from each bank’s MPU_TYPE.DREGION. Secure software reaches the Non-secure copy through the SCS Non-secure alias (MPU_TYPE_NS at 0xE002ED90, MPU_CTRL_NS at 0xE002ED94, and so on). The SAU/IDAU decides the security attribute of an address. The MPU for the security state decides access permissions and memory attributes. These are two separate checks.

A common reconfiguration sequence, used by CMSIS, is: DMB so that earlier explicit accesses are ordered before the MPU register writes, an optional disable, program the regions, set ENABLE, then DSB followed by ISB. The next section explains the barrier rules behind this sequence.

Coming from A-profile: On TrustZone-A, the output address space comes from the translation regime and the NS bit in Secure-state descriptors, and EL3 firmware context-switches the unbanked AArch64 EL1 registers. v8-M instead banks the whole MPU in hardware and takes address security from the SAU/IDAU, not from MPU attributes.

Checkpoint

Q3.3.1 An RTOS ported from v7-M configures region 0 as all of SRAM (privileged RW) and region 5 as a 1 KB task stack inside it (unprivileged RW), both enabled. On Armv8-M Mainline, what happens when the unprivileged task writes to its stack?

  • A. The write succeeds, because the higher-numbered region 5 takes priority
  • B. The write faults with MemManage, because the address matches two enabled regions
  • C. The write succeeds, because PMSAv8 combines overlapping regions by taking the most permissive
  • D. The write faults only if PRIVDEFENA=0
Answer

B. In PMSAv8, an access that matches more than one enabled region is a MemManage fault, whatever the region numbers. The rule that the higher region number wins is PMSAv7 behaviour, which is exactly what a v7-M port would wrongly expect.

Read more: Armv8-M ARM (DDI0553), PMSAv8 region matching / MPU fault conditions

Q3.3.2 MPU_CTRL = ENABLE=1, PRIVDEFENA=1, HFNMIENA=0. Which access is guaranteed to fault?

  • A. A privileged load from an address no region covers
  • B. Any access by the HardFault handler to an address no region covers
  • C. An unprivileged Thread-mode load (FAULTMASK clear) from an address no region covers
  • D. A privileged load inside an enabled region with AP=0b00
Answer

C. PRIVDEFENA gives only privileged accesses a background region, so an unprivileged access that matches no region faults while the MPU is applied. The HardFault handler runs at negative priority with HFNMIENA=0, so the MPU is ignored and its access uses the default map instead of faulting.

Read more: Armv8-M ARM (DDI0553), MPU_CTRL register description

Q3.3.3 With the Security Extension, Secure firmware needs to set up the Non-secure world’s MPU. How does it do that?

  • A. It writes the MPU_xxx_NS registers in the Non-secure alias of the SCS (0xE002ED90 onwards)
  • B. It writes the normal MPU addresses after setting CONTROL.NS
  • C. It cannot: only Non-secure code can program the Non-secure MPU
  • D. It sets the NS bit in each MPU_RBAR entry
Answer

A. The MPU is banked by security state, and Secure code reaches the Non-secure bank through the SCS Non-secure alias at 0xE002xxxx. CONTROL has no NS bit, and MPU_RBAR has none either, because security comes from the SAU/IDAU, not from MPU regions.

Read more: Armv8-M ARM (DDI0553), banked MPU registers / SCS Non-secure alias

3.4 DMB, DSB, ISB: semantics and where they are needed

Normal memory accesses are weakly ordered in v8-M, as in v8-A. A particular core, such as the in-order Cortex-M33, may appear to keep accesses in order, but the architecture does not guarantee it. The three barriers are:

  • DMB orders explicit memory accesses. Accesses before it are observed before accesses after it. It does not wait for completion, and it does not ensure that side effects of SCS writes have taken effect, or affect instruction fetch.
  • DSB is stronger. No instruction after it in program order executes until it completes. It completes when every explicit memory access before it has completed and all earlier cache and branch-predictor maintenance has completed.
  • ISB is a context synchronization event. Instructions after it are fetched again from cache or memory, so they see the effects of context-changing operations completed before it, such as a CONTROL write or an MPU update that a DSB has completed.

The places where Arm requires or recommends them (see also AN321):

  • After reconfiguring the MPU: DSB so the SCS writes complete, then ISB so the next instructions are fetched and checked under the new regions.
  • After MSR CONTROL (SPSEL, nPRIV, FPCA and so on): ISB, so later instructions use the new stack pointer or privilege.
  • When relocating VTOR: the vector table copy must be complete before the VTOR write, and the VTOR write must complete before an exception can use it. Use copy, DSB, write VTOR, DSB.
  • Before WFI/WFE, when the wake-up condition depends on a memory-mapped write having taken effect (for example clearing a peripheral IRQ flag or arming a timer): DSB.
  • After enabling or disabling an interrupt in the NVIC (ISER/ICER), when the change must apply before the next instruction: DSB then ISB. For example, after a disable, the IRQ must not be taken after the ISB.

Coming from A-profile: These barriers work like AArch64 DMB/DSB/ISB, but v8-M defines only the SY option, with no ISH/OSH/LD/ST variants. Most system control (MPU, VTOR, NVIC, cache maintenance) consists of Device-nGnRnE stores to the SCS rather than MSR to system registers, which is why a DSB to complete the store usually comes before the ISB. CONTROL, BASEPRI and similar registers are still MSR special registers.

Checkpoint

Q3.4.1 After writing new MPU_RBAR/RLAR values and setting MPU_CTRL.ENABLE, which sequence architecturally guarantees that the next instruction is fetched and executed under the new MPU configuration?

  • A. ISB only
  • B. DMB then ISB
  • C. DSB then ISB
  • D. DSB only
Answer

C. The DSB ensures that the stores to the MPU registers have completed, and the ISB then refetches later instructions so they see the new context. DMB only orders memory accesses relative to each other and does not wait for the MPU write to complete. DSB alone does not refetch instructions already fetched under the old configuration.

Read more: Armv8-M ARM (DDI0553), memory barriers (DSB/ISB) and MPU programming requirements

Q3.4.2 In an ISR, code clears a peripheral’s interrupt status bit with a store to Device memory and then returns. Sometimes the ISR is entered again straight away even though the source was cleared. What fixes this architecturally?

  • A. Add a DSB after the store, before exception return, so the clear completes before the interrupt is sampled again
  • B. Add an ISB after the store
  • C. Change the peripheral region to Device-nGnRnE
  • D. Add a DMB before the store
Answer

A. The store may still be in flight, for example in a write buffer, when the exception returns, so the interrupt is still pending or asserted. A DSB waits for the store to complete. On some SoCs a read-back of the peripheral register is also needed, because bus or peripheral latency can delay deassertion of the line. An ISB does not wait for outstanding memory writes. nGnRnE removes early acknowledgement, but the PE still does not wait for the store without a DSB.

Read more: Armv8-M ARM (DDI0553), DSB semantics; Arm AN321, Cortex-M Programming Guide to Memory Barrier Instructions

Q3.4.3 Firmware switches from MSP to PSP with MSR CONTROL, r0 (SPSEL=1). What does Arm require next, before code that depends on the new SP?

  • A. Nothing, because MSR CONTROL takes effect immediately
  • B. DSB
  • C. DMB
  • D. ISB
Answer

D. A change to CONTROL is a context change, and later instructions are only guaranteed to see it after a context synchronization event such as an ISB. CMSIS __set_CONTROL includes one for this reason. A DSB waits for memory accesses but is not a context synchronization event.

Read more: Armv8-M ARM (DDI0553), CONTROL register / MSR and context synchronization

3.5 Exclusives: LDREX/STREX, CLREX and the monitors

Armv8-M provides LDREX/STREX in byte, halfword and word forms, in Baseline as well as Mainline. (v6-M had no exclusives.) There is no doubleword form. CLREX clears the local monitor. Armv8-M also adds load-acquire/store-release, LDA/STL, and the exclusive forms LDAEX/STLEX. There is no LSE (no CAS or LDADD) as there is in v8.1-A.

The monitor model is the same as on A-profile:

  • The local monitor is per PE. Exclusive accesses to Non-shareable memory are checked only against the local monitor.
  • The global monitor belongs to the memory system. Exclusives to Shareable memory are checked against both monitors. Many single-core MCUs have no global monitor. In that case exclusives to Shareable regions may not behave as intended (depending on the core and bus, STREX can always fail), which is why lock variables are often placed in Non-shareable memory.

STREX writes 0 on success and 1 on failure. The architecture also allows it to fail without a conflicting access, so the code must loop.

Exceptions: In Armv8-M, exception entry and exception return both clear the local monitor, as if a CLREX had run. Suppose a thread is preempted between its LDREX and STREX. When it resumes, its STREX fails and it retries. An ISR that does its own LDREX/STREX also cannot inherit the thread’s reservation. This means an RTOS context switch does not need an explicit CLREX for correctness. CLREX is still useful for abandoning a reservation in thread code.

Exception entry only clears the local monitor. It does not reset any global monitor state that other bus masters see. Exclusives are also not a substitute for barriers. If the lock protects data, you need a DMB after acquiring and before releasing, or LDAEX to acquire and STL to release. LDREX/STREX by themselves give no ordering.

Coming from A-profile: On AArch64, an exception return also clears the local monitor, and Linux arm64 relies on this instead of a CLREX on context switch. In v8-M, both entry and return clear it as part of the exception model. The bigger difference is the missing LSE atomics: every RMW on v8-M is an exclusive loop.

Checkpoint

Q3.5.1 A thread executes LDREX, is preempted by an IRQ whose handler does nothing to the monitor, and then resumes and executes STREX to the same address. What happens?

  • A. The STREX always succeeds, because no other agent wrote the location
  • B. It depends on whether the ISR touched the same address
  • C. The STREX faults
  • D. The STREX fails (returns 1), because exception entry and return cleared the local monitor
Answer

D. Armv8-M clears the local monitor on both exception entry and exception return, so the reservation is lost and the retry loop runs again. The tempting idea that it succeeds because nobody wrote the location ignores that the architecture clears the monitor anyway. This is also why no CLREX is needed in the context switch path.

Read more: Armv8-M ARM (DDI0553), exception entry/return pseudocode (ClearExclusiveLocal) and the synchronization primitives chapter

Q3.5.2 A spinlock uses an LDREX/STREX loop to take the lock and a plain STR of 0 to release it. Protected data is updated in the critical section. What is missing for correctness on Armv8-M Mainline?

  • A. A DMB after a successful acquire and a DMB before the releasing STR (or LDAEX to acquire and STL to release)
  • B. A CLREX after every STREX
  • C. An ISB after the STREX
  • D. Nothing: exclusives imply full ordering
Answer

A. LDREX/STREX give atomicity but no ordering, so data accesses could be reordered across the lock operations. A DMB, or acquire/release semantics, prevents that. CLREX only abandons a reservation and does nothing for ordering.

Read more: Armv8-M ARM (DDI0553), synchronization and semaphores; load-acquire/store-release

3.6 L1 caches, cache maintenance and DMA coherency

Caches are optional. Armv8.1-M cores such as the Cortex-M55 and Cortex-M85 can have L1 I- and D-caches, and these are not coherent with DMA masters. The Armv7E-M Cortex-M7 uses the same interface. There are no cache maintenance instructions like the A-profile DC/IC. Maintenance is done with stores to memory-mapped SCB registers (Mainline):

  • ICIALLU: invalidate the whole I-cache to the Point of Unification.
  • ICIMVAU / DCCMVAU: invalidate an I-cache line, or clean a D-cache line, by address to the PoU.
  • DCIMVAC: invalidate a D-cache line by address to the Point of Coherency.
  • DCCMVAC: clean a D-cache line by address to the PoC.
  • DCCIMVAC: clean and invalidate a D-cache line by address to the PoC.

Set/way variants (DCISW, DCCSW, DCCISW) are for whole-cache operations at init. Each by-address operation acts on one line, so loop over the buffer using the minimum line size from CTR.DminLine. Finish with a DSB, which guarantees that the maintenance has completed. For I-cache changes, add an ISB.

The DMA rules:

  • Memory to device (CPU wrote the buffer, DMA reads it): DCCMVAC over the buffer, then DSB, then start the DMA. Otherwise dirty data is still in the cache and the DMA reads stale memory.
  • Device to memory (DMA writes, CPU reads): invalidate before you start the DMA, so a dirty line cannot be evicted on top of the DMA data. Invalidate again (DCIMVAC, then DSB) after completion and before reading. Normal cacheable memory may be speculatively read into the cache while the DMA is running, so the first invalidate is not enough.
  • Align buffers to the cache line size and make their size a multiple of it. Otherwise invalidating a shared line throws away unrelated CPU data, or cleaning it writes stale data over DMA data.

The portable alternative is to map DMA buffers through the MPU as Normal Non-cacheable (MAIR 0x44). Some cores, for example the Cortex-M7, do not cache Shareable Normal regions by default, but that is implementation behaviour and not an architectural guarantee.

Self-modifying or loaded code needs: DCCMVAU over the code, DSB, ICIALLU, DSB, ISB.

Coming from A-profile: The concepts (PoC/PoU, clean vs invalidate, speculative line fills) are the same as on A-profile, but the operations are SCB register stores instead of DC CIVAC and similar instructions. These MCUs usually lack the hardware I/O coherency that an A-profile SoC gets from an SMMU and a coherent interconnect (CCI/CMN).

Checkpoint

Q3.6.1 On a Cortex-M55 with the D-cache enabled, a DMA engine writes received data into a cacheable SRAM buffer. The driver invalidated the buffer before starting the DMA and then reads it after the completion interrupt without further maintenance. Occasionally stale data appears. Why?

  • A. The pre-DMA invalidate should have been a clean
  • B. Normal cacheable memory can be speculatively read into the cache during the transfer, so an invalidate after completion is also needed
  • C. The DMA completion interrupt needs an ISB
  • D. DCIMVAC only works on the I-cache
Answer

B. Normal memory allows speculative reads, so lines of the buffer can be allocated again while the DMA runs, and the CPU then reads those stale lines. You need an invalidate after completion, followed by a DSB. Cleaning before the DMA would write possibly stale CPU data over the buffer, so it is the wrong fix for an RX buffer.

Read more: Armv8-M ARM (DDI0553), cache maintenance operations; Cortex-M55 TRM, L1 cache

Q3.6.2 The CPU fills a TX buffer in Write-Back cacheable SRAM and then starts a DMA that reads it. What is the correct sequence?

  • A. DCIMVAC over the buffer, then start the DMA
  • B. DMB, then start the DMA
  • C. DCCMVAC over the buffer, DSB, then start the DMA
  • D. ICIALLU, ISB, then start the DMA
Answer

C. The data may be dirty in the D-cache. Cleaning to the PoC pushes it to memory, and the DSB ensures that the clean has completed before the store that starts the DMA. Invalidating would throw away the dirty data, and a DMB orders accesses but does not make cached data visible to a non-coherent master.

Read more: Armv8-M ARM (DDI0553), SCB cache maintenance registers (DCCMVAC)

Q3.6.3 Why must DMA buffers that are maintained with DCIMVAC start on a cache line boundary and have a size that is a multiple of the cache line size?

  • A. Because DCIMVAC faults on unaligned addresses
  • B. Because the MPU requires 32-byte aligned regions
  • C. Because the DMA engine cannot write across a cache line
  • D. Because invalidating a line that the buffer shares with other variables discards the CPU’s dirty updates to those variables
Answer

D. Maintenance acts on whole lines, so a partial line also holds neighbouring data, and invalidating it silently loses dirty CPU writes to that data. DCIMVAC does not fault on unaligned addresses. It acts on the line that contains the address, which is exactly why the line-sharing problem happens.

Read more: Armv8-M ARM (DDI0553), cache maintenance by address

4. TrustZone for Armv8-M & TF-M

How the Armv8-M Security Extension splits one PE into Secure and Non-secure states using address attribution, and the hardware transitions, banked state and exception rules that build on that split. It finishes with the CMSE toolchain contract, stack sealing, and how TF-M maps onto what you know from OP-TEE and TF-A.

Sections

  1. The Security Extension model: state follows the address
  2. Attribution: SAU, IDAU and the TT instructions
  3. Crossing the boundary: SG, BXNS, BLXNS and FNC_RETURN
  4. Banked state and exceptions across Security states
  5. CMSE toolchain contract and stack sealing
  6. TF-M: the Secure side, compared with OP-TEE + TF-A

4.1 The Security Extension model: state follows the address

The Armv8-M Security Extension (TrustZone for Armv8-M) is optional in both Baseline and Mainline. When it is implemented, the PE is in one of two Security states, Secure or Non-secure. Both states have Thread mode and Handler mode. Handler mode is always privileged, and Thread mode is privileged or unprivileged according to that state’s banked CONTROL.nPRIV. There are no exception levels, no Monitor mode, no SMC, no EL3 and no SCR_EL3.NS.

The architecture ties the Security state to the security attribute of the address the instruction is fetched from. Secure code runs from Secure memory and Non-secure code from Non-secure memory. The state can change only through mechanisms the architecture defines:

  • NS to S: a branch to an SG instruction placed in Non-secure-callable (NSC) memory.
  • S to NS: BXNS or BLXNS.
  • Non-secure code returning to Secure code by branching to the FNC_RETURN value left by BLXNS.
  • Exception entry and exception return (EXC_RETURN).

Any other attempt to fetch across the boundary faults instead of switching state. In Mainline that fault is a SecureFault, recorded in SFSR (for example INVEP, invalid entry point, or INVTRAN, invalid transition). Baseline has no SecureFault exception, so these faults escalate to the Secure HardFault.

Because hardware performs the switch, a call across the boundary costs little more than a function call through a veneer. No monitor software saves and restores the other world’s state, because the registers that need separation are banked per state (see section 4). The general-purpose registers R0 to R12 and LR are not banked. Software has to clear them, which is why the CMSE toolchain rules in section 5 exist.

At reset, a PE with the Security Extension starts in Secure state and fetches its vector table through VTOR_S. SAU_CTRL resets with ENABLE=0 and ALLNS=0, so the SAU attributes all memory as Secure (apart from the address ranges the architecture exempts from attribution, such as most of the PPB). Secure boot code must program the SAU (and possibly the IDAU and the system’s memory and peripheral protection controllers) and set up Non-secure state before branching to it with BXNS or BLXNS.

Coming from A-profile: On A-profile, SCR_EL3.NS selects the Security state of the lower ELs and EL3 software flips it during a world switch, typically on SMC. On v8-M nothing like SCR exists: the memory map selects the world and the PE checks every crossing in hardware.

Checkpoint

Q4.1.1 You look for the Armv8-M equivalent of SCR_EL3.NS to find out how the PE decides it is in Secure state. Which statement is correct?

  • A. CONTROL.NS selects the Security state, and only Secure privileged code can write it
  • B. The Security state follows the security attribute of the address the instruction is fetched from, and it changes only through SG, BXNS/BLXNS, a return to FNC_RETURN, or exception entry and return
  • C. A Secure monitor running in Handler mode changes the state when software executes SVC #0xFF
  • D. xPSR has an NS bit that the PE updates on every exception return
Answer

B. Armv8-M has no software-writable world-select bit. Executing from Secure memory means Secure state, and the only ways to cross are SG in NSC memory, BXNS/BLXNS, a branch to FNC_RETURN, and exception entry and return. CONTROL is the tempting distractor because it is a system register with mode-like bits (nPRIV, SPSEL), but it has no Security-state bit.

Read more: Armv8-M ARM (DDI0553), Security Extension: Security states and Security state transitions

Q4.1.2 A Mainline core with the Security Extension leaves reset. Secure boot code has not touched the SAU yet. What is the state of the system?

  • A. The PE is in Non-secure state, and all memory is Non-secure until Secure firmware enables the SAU
  • B. The PE is in Secure state, and only the IDAU attribution applies because the SAU is disabled
  • C. The PE is in Non-secure state, and it traps to Secure on the first SG
  • D. The PE is in Secure state, and because SAU_CTRL resets with ENABLE=0 and ALLNS=0 the SAU marks all memory Secure, which outranks any less-secure IDAU result
Answer

D. The PE resets into Secure state. With the SAU disabled and ALLNS=0, the SAU reports every (non-exempt) address as Secure. The SAU and IDAU results combine with the more secure one winning, so everything is Secure. The tempting distractor says the IDAU alone decides, but that only happens when ALLNS=1, because then the SAU reports Non-secure everywhere and the IDAU result is the one that counts.

Read more: Armv8-M ARM (DDI0553), SAU_CTRL and security attribution

4.2 Attribution: SAU, IDAU and the TT instructions

Two units attribute every address, and the PE combines their results:

  • The IDAU (Implementation Defined Attribution Unit) is a fixed or SoC-configured map outside the architecturally defined SAU. Its contents are IMPLEMENTATION DEFINED, and the signal interface is defined by the core (for example the Cortex-M33 IDAU interface), not by the architecture.
  • The SAU (Security Attribution Unit) is programmable from Secure privileged code. The number of regions is in SAU_TYPE.SREGION. You select a region with SAU_RNR, then program SAU_RBAR (base address) and SAU_RLAR (limit address, an NSC bit and ENABLE). Regions have 32-byte granularity. You turn the SAU on with SAU_CTRL.ENABLE. While the SAU is disabled, SAU_CTRL.ALLNS chooses whether it reports everything Secure (0) or everything Non-secure (1).

When the SAU is enabled, an address that no enabled region covers is Secure. Each unit returns one of three attributes, and the more secure result wins, ordered Secure > Non-secure-callable > Non-secure. Outside the architecturally exempt ranges, an address ends up Non-secure only when both units agree that it is Non-secure.

NSC memory is Secure memory with one exception: Non-secure code may branch into it, but only onto an SG instruction. NSC exists so that only regions you deliberately mark can act as entry points. Without it, any halfword pair in Secure code or data that happened to encode SG could become an entry point. Keep NSC regions small and fill them only with veneers.

The PE combines attribution with the MPU of the current state. The MPU is banked into a Secure and a Non-secure instance. The TT family of instructions lets software query both:

  • TT: MPU region and permissions for the current state, at the current privilege.
  • TTT: the same, but checks unprivileged permissions.
  • TTA and TTAT: query the Non-secure MPU (the alternate state), privileged and unprivileged respectively. These two are valid only in Secure state.

The result word reports MPU region and validity (MREGION, MRVALID), R and RW permissions and, in Secure state, SAU and IDAU region information, the S attribute, and the combined NSR and NSRW flags (MPU permission AND Non-secure attribution). Secure code uses these to validate pointers it receives from Non-secure callers.

Coming from A-profile: A TZASC filters bus transactions by an NS bit someone else already decided; the SAU instead decides the attribute the PE itself uses, for both instruction fetch and data access, and adds an NSC attribute that has no A-profile counterpart. TT/TTA play a role similar to AT S1E* address-translation queries, but they return region numbers and permissions instead of a PA.

Checkpoint

Q4.2.1 For a given address, the SAU result is Non-secure and the IDAU result is Non-secure-callable. What is the final attribution?

  • A. Non-secure-callable, because the more secure of the two results wins
  • B. Non-secure, because the programmable SAU overrides the IDAU
  • C. Secure, because a mismatch between the two units always defaults to Secure
  • D. UNPREDICTABLE, because the two units must agree
Answer

A. The combination rule takes the more secure attribute, ordered Secure > NSC > NS. NSC is more secure than NS, so NSC wins. The tempting idea that the programmable SAU overrides the IDAU is wrong: the SAU can only raise the security of an address the IDAU marks as less secure, never lower it.

Read more: Armv8-M ARM (DDI0553), Security attribution: SAU and IDAU

Q4.2.2 The SAU is enabled with regions covering only flash 0x00200000-0x003FFFFF (NS) and SRAM 0x20020000-0x2003FFFF (NS). The IDAU marks the whole of 0x20000000-0x2FFFFFFF as Non-secure. How is address 0x20000100 attributed?

  • A. Non-secure, because the IDAU says Non-secure and no SAU region contradicts it
  • B. Non-secure-callable, because it is next to an NS region
  • C. Secure, because an address that no enabled SAU region covers is Secure when the SAU is enabled, and the more secure result wins
  • D. It depends on whether the access is an instruction fetch or a data access
Answer

C. With SAU_CTRL.ENABLE=1, the SAU reports any address outside its enabled regions as Secure, so the combined result is Secure. The tempting reading is that “no SAU region” means the SAU has no opinion and the IDAU decides. That only applies to a disabled SAU with ALLNS=1.

Read more: Armv8-M ARM (DDI0553), SAU_CTRL, SAU_RLAR

Q4.2.3 A Secure entry function receives a buffer pointer from unprivileged Non-secure thread code. It must confirm that this code could legitimately write the whole buffer itself. Which instruction gives the right check per address?

  • A. TT, because it uses the caller’s privilege automatically
  • B. TTAT, which queries the Non-secure MPU with unprivileged permissions and also reports the Security attribute
  • C. TTT, which checks the Secure MPU with unprivileged permissions
  • D. TTA, which checks Non-secure privileged permissions
Answer

B. The question is whether Non-secure unprivileged code may write the buffer. That needs the alternate-state (Non-secure) MPU at unprivileged level, and attribution must show the address as Non-secure (NSRW). TTAT does exactly that, and it is valid only in Secure state. TTA is tempting, but it checks privileged permissions, so an unprivileged NS thread could get Secure code to write memory that only NS privileged code may write.

Read more: Armv8-M ARM (DDI0553), TT, TTT, TTA, TTAT instructions

4.3 Crossing the boundary: SG, BXNS, BLXNS and FNC_RETURN

NS to S (calling a Secure entry point). Non-secure code branches, typically with BL, to an address in NSC memory. The first instruction there must be SG (encoding 0xE97FE97F). When SG runs in Non-secure state from NSC memory, the PE:

  1. switches to Secure state, and
  2. clears LR[0], which marks the return target as Non-secure.

The veneer then branches to the real function body in Secure memory. If Non-secure code branches or falls through anywhere else in Secure or NSC memory (a Secure address that is not NSC, or an NSC address that does not hold SG), the PE raises a SecureFault with SFSR.INVEP (Mainline) or a Secure HardFault (Baseline). Executed in Secure state, SG acts as a NOP.

Returning from the entry function. The function returns with BXNS LR. BXNS moves to Non-secure state when bit 0 of the target is 0, and stays Secure when bit 0 is 1. Because SG cleared LR[0] only when the caller was Non-secure, the same entry function returns correctly whether the caller was Secure or Non-secure. Before BXNS, the code must clear every register that might hold Secure data.

S to NS (calling Non-secure code such as a callback). Secure code uses BLXNS Rm with Rm[0]=0. The PE:

  • pushes the real return address and partial PSR onto the current Secure stack,
  • sets LR to the magic value FNC_RETURN (0xFEFFFFFE/0xFEFFFFFF), and
  • branches into Non-secure state.

Non-secure code never sees the Secure return address. When it returns by branching to FNC_RETURN (an ordinary BX LR, or for example POP {pc}), the PE recognises the value, pops the return address from the Secure stack, checks the partial PSR, and resumes in Secure state.

An ordinary BX/BLX from Secure state to a Non-secure address is not a transition. It faults: SecureFault with SFSR.INVTRAN on Mainline, Secure HardFault on Baseline.

Coming from A-profile: There is no SMC function ID, no dispatcher and no context save in a monitor. An SG veneer is the entry point, and FNC_RETURN does the job of the ERET back into the caller, with the real return address kept where Non-secure code cannot reach it.

Checkpoint

Q4.3.1 Non-secure code reads a Secure function’s address from a symbol file and issues BL directly to that address. The address is in ordinary Secure memory, not NSC. What happens on Mainline?

  • A. The function runs in Secure state, but with Non-secure privilege
  • B. The function runs in Non-secure state, so its accesses to Secure data fault
  • C. A MemManage fault is raised to the Non-secure handler
  • D. A SecureFault is raised with SFSR.INVEP set, because Non-secure code may enter Secure state only through an SG instruction in NSC memory
Answer

D. Non-secure code fetching from a Secure address that is not a valid entry point (SG in NSC memory) raises SecureFault with INVEP, an invalid entry point. On Baseline it becomes a Secure HardFault. The MemManage distractor matches the A-profile habit of treating this as a translation or permission fault. On v8-M it is an attribution failure, and SecureFault is always handled in Secure state.

Read more: Armv8-M ARM (DDI0553), SG instruction; SFSR (INVEP)

Q4.3.2 One Secure entry function is called from both Secure and Non-secure code. How does its single BXNS LR return always go to the right state?

  • A. The PE tracks the caller’s Security state in CONTROL_S and restores it on any BX
  • B. BXNS always goes to Non-secure state, so Secure callers must use a separate non-veneer symbol
  • C. SG clears LR[0] when it runs in Non-secure state, so BXNS sees bit 0 = 0 and goes Non-secure, while a Secure caller’s BL leaves LR[0] = 1 and BXNS stays Secure
  • D. The veneer pushes an EXC_RETURN value that records the caller’s state
Answer

C. BXNS uses the target’s bit 0: 0 means switch to Non-secure, 1 means stay Secure. SG clears LR[0] only on a Non-secure to Secure entry, so LR itself carries the caller’s state. The distractor “BXNS always goes NS” is tempting because of the mnemonic, but BXNS with bit 0 = 1 is an ordinary Secure branch.

Read more: Armv8-M ARM (DDI0553), BXNS, SG

Q4.3.3 Secure code calls a Non-secure callback with BLXNS. Where is the Secure return address while the callback runs?

  • A. On the current Secure stack, pushed by BLXNS together with a partial PSR, while LR holds FNC_RETURN
  • B. In LR, with bit 0 cleared, so the callback can BXNS back
  • C. In a banked LR_S register that Non-secure code cannot read
  • D. On the Non-secure stack, protected by an integrity signature
Answer

A. BLXNS pushes the real return address (and partial PSR) onto the Secure stack and loads LR with FNC_RETURN, so the Secure return address never reaches Non-secure code. The Non-secure branch to FNC_RETURN pops that frame. A banked LR is tempting by analogy with A-profile banked ELR_ELx, but LR is not banked in v8-M. Because the hardware trusts whatever frame sits on the Secure stack, an unsealed Secure stack is a weakness (section 5).

Read more: Armv8-M ARM (DDI0553), BLXNS, FNC_RETURN

4.4 Banked state and exceptions across Security states

Banked per Security state:

  • Stack pointers: MSP_S/MSP_NS and PSP_S/PSP_NS.
  • Stack limits: MSPLIM/PSPLIM. Without the Main Extension (Baseline) only the Secure limits are implemented.
  • CONTROL: nPRIV and SPSEL are banked. FPCA is shared, and SFPA appears only in the Secure view.
  • Mask registers: PRIMASK, plus BASEPRI and FAULTMASK (Mainline only).
  • VTOR_S/VTOR_NS, the MPU, and several SCB registers and fields (for example parts of SHCSR, CCR and SCR).
  • SysTick, when two are implemented. With a single SysTick, ICSR.STTNS assigns it to one state.

Secure code reaches the Non-secure copies with MRS/MSR on names such as MSP_NS and CONTROL_NS, and, for memory-mapped registers, through the Non-secure alias of the System Control Space at 0xE002E000-0xE002EFFF. For example, 0xE002ED08 is VTOR_NS. The normal 0xE000Exxx addresses reach the bank of the current state. R0 to R12, LR and the FP registers are shared.

Exception targeting. NVIC_ITNS sets, per external interrupt, whether it targets Non-secure state. Several system exceptions are banked (SVCall, PendSV, SysTick, MemManage, UsageFault). AIRCR.BFHFNMINS=1 makes BusFault and NMI Non-secure and lets faults target a Non-secure HardFault; Secure faults still go to the Secure HardFault. AIRCR.PRIS remaps Non-secure programmable priorities into the lower-priority half, so a Secure exception configured in the upper half can always preempt Non-secure ones. Only Secure privileged code can write ITNS, BFHFNMINS and PRIS.

Secure background, Non-secure handler. In this case the PE pushes the normal caller-saved frame plus an additional state context onto the Secure stack: an integrity signature (0xFEFA125B, or 0xFEFA125A when an extended FP frame applies), a reserved word, and R4 to R11. It then clears the registers so the Non-secure handler sees no Secure values. EXC_RETURN records the situation:

  • ES (bit 0): the state the exception was taken to.
  • S (bit 6): the frame is on a Secure stack.
  • DCRS (bit 5): 0 means the callee-saved registers are already on the stack; 1 means default stacking rules.

On return, a bad integrity signature raises a SecureFault with INVIS (Secure HardFault on Baseline).

Coming from A-profile: On A-profile, EL3 firmware saves and restores the other world’s context in software, and the GIC (Group 0/1S/1NS) routes interrupts to a world. On v8-M, the NVIC with ITNS does the routing, and exception entry hardware protects the Secure context.

Checkpoint

Q4.4.1 Secure Thread code is running when an interrupt arrives whose NVIC_ITNS bit is 1. The interrupt is taken. Which description of entry is correct?

  • A. The PE pushes the standard 8-word frame onto the Non-secure stack and keeps R4-R11 live, because AAPCS makes the handler preserve them
  • B. The PE pushes the standard frame plus the additional state context (integrity signature, R4-R11) onto the Secure stack, clears the registers, and sets EXC_RETURN with ES=0, S=1, DCRS=0
  • C. The PE first takes the exception in Secure state, and Secure firmware must forward it to Non-secure
  • D. The interrupt stays pending until Secure code executes BXNS
Answer

B. A Secure background state with a Non-secure target is the case where hardware stacks the callee-saved registers and the integrity signature on the Secure stack, then clears registers so nothing leaks. EXC_RETURN encodes this as ES=0 (taken to NS), S=1 (frame on a Secure stack) and DCRS=0 (callee registers already stacked). Relying on AAPCS callee-save is tempting, but the Non-secure handler is untrusted and could simply read R4-R11.

Read more: Armv8-M ARM (DDI0553), exception entry, additional state context, EXC_RETURN

Q4.4.2 Secure boot firmware must set the Non-secure vector table base before launching the Non-secure image. Which access is correct?

  • A. Write VTOR at 0xE000ED08 from Secure state, because Secure state has access to both banks there
  • B. Execute MSR VTOR_NS, Rn
  • C. Write AIRCR.BFHFNMINS=1, which makes 0xE000ED08 refer to the Non-secure VTOR
  • D. Write the Non-secure alias at 0xE002ED08 from Secure state, which reaches VTOR_NS
Answer

D. Banked memory-mapped SCS registers reached at 0xE000Exxx hit the bank of the current state, so a Secure write to 0xE000ED08 changes VTOR_S. The Non-secure bank is reached through the 0xE002Exxx alias, which only Secure code can use (it is RAZ/WI from Non-secure state). MSR VTOR_NS does not exist, because VTOR is memory-mapped and not a special register (the _NS special-register names cover the stack pointers, CONTROL, the masks and the stack limits).

Read more: Armv8-M ARM (DDI0553), System Control Space, Non-secure alias; VTOR

Q4.4.3 What is the effect of setting AIRCR.PRIS = 1?

  • A. Secure exceptions are routed to Non-secure state
  • B. Non-secure code can now set its exception priorities to values numerically lower than any Secure exception
  • C. Non-secure programmable priorities are mapped into the lower-priority half of the priority range, so any Secure exception configured in the upper half can preempt every Non-secure exception
  • D. SecureFault is given priority -1
Answer

C. PRIS (“prioritize Secure exceptions”) remaps the effective priority of Non-secure exceptions into the bottom half of the range. Non-secure software then cannot configure a priority that blocks Secure exceptions placed in the upper half. A Secure exception that Secure software itself places in the lower half gets no such guarantee. The option claiming Non-secure code can go numerically below every Secure exception describes the opposite, which is the risk PRIS exists to remove.

Read more: Armv8-M ARM (DDI0553), AIRCR (PRIS, BFHFNMINS)

4.5 CMSE toolchain contract and stack sealing

The Cortex-M Security Extensions (CMSE) ACLE spec defines how C code runs at the boundary. You compile with -mcmse and include <arm_cmse.h>.

  • __attribute__((cmse_nonsecure_entry)) marks a Secure entry function. The compiler emits a special symbol (__acle_se_foo). The linker generates an SG plus B.W veneer for it in a dedicated section (e.g. .gnu.sgstubs) that you place in an NSC region. The linker also emits an import library so the Non-secure image can link against the veneer addresses. Before the compiler-generated BXNS LR, the entry function clears every caller-saved register that does not carry the return value (from R0-R3 and R12, the flags, and FP registers as applicable). Callee-saved registers are restored as usual.
  • cmse_nonsecure_call on a function-pointer type makes a call use BLXNS. The compiler saves the registers that must survive, clears every register not used for arguments (callee-saved ones included, since Non-secure code can read them), and clears bit 0 of the target. cmse_nsfptr_create() and cmse_is_nsfptr() manage bit 0 of the pointer.
  • cmse_check_address_range(p, size, flags) and cmse_check_pointed_object() use the TT family. The flags include CMSE_NONSECURE, CMSE_MPU_READWRITE and CMSE_MPU_UNPRIV. The functions return NULL when the check fails. This defends against a confused-deputy attack, where Non-secure code passes a pointer into Secure memory. Check the whole range. Copy the data into Secure memory before using it, because Non-secure code (another thread or an interrupt) can change shared memory after the check.

Stack sealing (Arm security advisory, 2020). FNC_RETURN unstacking and EXC_RETURN with S=1 trust that the current Secure stack holds a frame from an earlier transition. Suppose a Secure stack holds no such frame, for example a fresh Secure thread stack or the Secure MSP when Secure code is idle. Non-secure code could then fake a function return or exception return. The PE would pop whatever words sit above the stack pointer and could resume Secure execution at an address Non-secure code influences. The integrity signature check covers only some exception-return paths, and only rejects data that does not happen to match it.

Mitigation: reserve the top 8 bytes of every Secure stack, write the seal value 0xFEF5EDA5 into both words, and start the stack pointer below the seal. A bogus return then pops the seal. It is not a valid integrity signature, and as a return address it points into the Execute Never system region, so the attempt faults instead of jumping. CMSIS provides __TZ_set_STACKSEAL_S() for this.

Coming from A-profile: This is the v8-M version of the rules for sanitising registers and validating pointers at an SMC boundary in OP-TEE or TF-A. The compiler takes over the register sanitising that the secure-world exit path (OP-TEE’s and BL31’s context switch) does in software on A-profile.

Checkpoint

Q4.5.1 A Secure entry function int read_key(uint8_t *out, size_t n) writes into out. A Non-secure caller passes out = 0x30001000, which is Secure RAM holding Secure data. What is the correct defence?

  • A. Validate with cmse_check_address_range(out, n, CMSE_NONSECURE | CMSE_MPU_READWRITE) (adding CMSE_MPU_UNPRIV if the caller is unprivileged), reject on NULL, and only then write
  • B. No check is needed, because the Non-secure MPU blocks the Secure write
  • C. Check only that out itself is Non-secure with one TT instruction
  • D. Mark out as volatile so the compiler emits Non-secure accesses
Answer

A. The entry function runs in Secure state with Secure permissions, so it can write Secure RAM. This is a confused-deputy problem, and the whole range must be checked as Non-secure and writable at the caller’s privilege. The tempting “NS MPU will block it” is wrong, because Secure accesses are checked against the Secure MPU and attribution, not the Non-secure MPU. Checking only the first address misses a range that runs into Secure memory.

Read more: ARM CMSE ACLE specification, cmse_check_address_range; TT instructions

Q4.5.2 Why does a cmse_nonsecure_entry function clear R0-R3, R12 and the flags (except return-value registers) before BXNS, when AAPCS already says those registers are caller-saved scratch?

  • A. The hardware faults with INVTRAN if those registers are non-zero at BXNS
  • B. Caller-saved registers can still hold Secure intermediate values such as keys and pointers, and LR, R0-R12 and the FP registers are not banked, so without clearing the Non-secure caller would read them
  • C. AAPCS requires a function to zero its scratch registers on return
  • D. Clearing them pre-fills the arguments for the next SG call
Answer

B. The general-purpose and FP registers are shared between Security states, so any Secure value left in them stays visible after BXNS. The compiler clears them to stop the leak. The first distractor is tempting because it sounds like a hardware rule, but BXNS performs no register-content check. INVTRAN concerns branches that are not transitions.

Read more: ARM CMSE ACLE specification, entry function return; BXNS

Q4.5.3 Which scenario is the 2020 stack-sealing issue, and how does the seal address it?

  • A. Non-secure code overflows PSP_NS into Secure RAM. The seal acts as a guard word that the PE checks
  • B. An SG instruction is accidentally present in Secure code. The seal marks the valid veneers
  • C. Secure code returns with BX instead of BXNS. The seal makes BX fault
  • D. Non-secure code issues a fake FNC_RETURN or Secure-frame EXC_RETURN while the current Secure stack holds no real frame, so the PE pops arbitrary words. With 0xFEF5EDA5 at the stack top, the pop yields neither a valid integrity signature nor an executable return address, so it faults
Answer

D. The hardware trusts that the current Secure stack holds a frame from a real earlier transition. Sealing an empty Secure stack makes any forged return pop the seal and fault. The stack-overflow distractor is tempting, but overflow is what MSPLIM and PSPLIM handle. The seal is not a guard word that the PE checks on every push.

Read more: Arm Armv8-M Secure stack sealing advisory (2020); CMSIS __TZ_set_STACKSEAL_S

4.6 TF-M: the Secure side, compared with OP-TEE + TF-A

Trusted Firmware-M (TF-M) is the reference Secure Processing Environment (SPE) for Armv8-M. It implements PSA Firmware Framework-M (FF-M), which defines these pieces:

  • SPM (Secure Partition Manager): TF-M’s core. It runs privileged in Secure state and owns partition isolation (Secure MPU, and peripheral and memory protection controllers), the scheduling and messaging of IPC-model partitions, and interrupt delivery to partitions.
  • Secure partitions: isolated services described by a manifest. They divide into the PSA Root of Trust (e.g. Crypto, Internal Trusted Storage, Initial Attestation, Platform) and the Application RoT (e.g. Protected Storage). Partitions use the IPC model (own thread, psa_connect/psa_call messages, signals) or, since FF-M 1.1, the SFN (Secure Function) model.
  • Isolation levels:
    • Level 1: the SPE is isolated from the NSPE only.
    • Level 2: also isolates the PSA RoT from the Application RoT. In TF-M, ARoT partitions run unprivileged behind the Secure MPU.
    • Level 3: also isolates every partition from every other partition.
  • APIs: PSA Crypto, PSA Internal Trusted Storage and Protected Storage, PSA Initial Attestation and Firmware Update, called from the Non-secure side.

The Non-secure interface. Non-secure code (for example a FreeRTOS or Zephyr application) calls the PSA client APIs. On a single-core TrustZone system these go through TF-M’s NS interface layer to an SG veneer in NSC memory, and the SPM routes the request to the target partition. Multi-core platforms where the NSPE runs on a separate core use a mailbox instead of veneers. Secure boot is normally TF-M’s BL2, which is based on MCUboot.

Mapping to OP-TEE + TF-A. On A-profile, BL31 at EL3 is the secure monitor: it handles SMC, switches worlds and saves context. OP-TEE OS is the S-EL1 trusted OS, and TAs are its isolated services. On Armv8-M, no software plays the secure monitor role. The PE’s hardware does it: SG and NSC entry, BXNS/BLXNS, FNC_RETURN, exception stacking with the additional state context, and banked registers. TF-M’s SPM corresponds to OP-TEE OS, and partitions correspond to TAs. TF-M’s BL2 roughly plays the role of TF-A’s BL2. Note that the A-profile “SPM” (Hafnium SPMC, under FF-A) is a different framework, despite the shared name.

Coming from A-profile: Your OP-TEE/TF-A model maps across with one big change: the EL3 dispatcher (SMC handling, opteed SPD, context save) disappears into hardware. Everything you would review in BL31’s world-switch code becomes CMSE veneer, register-clearing and stack-sealing review.

Checkpoint

Q4.6.1 In a TF-M system on an Armv8-M Mainline core, which component plays the role that TF-A BL31 plays for OP-TEE on A-profile (world switch and state preservation)?

  • A. TF-M’s SPM, running in Secure Handler mode as the monitor
  • B. A Secure SVC handler that every Non-secure call must trap into
  • C. None in software: the Security Extension hardware switches state (SG/BXNS/BLXNS, FNC_RETURN, exception stacking) and banked registers preserve per-state context
  • D. TF-M’s BL2 bootloader, which stays resident as the dispatcher
Answer

C. Armv8-M has no monitor: crossings are hardware-checked branches and exception mechanisms, and the state that needs separating is banked. TF-M’s SPM corresponds to OP-TEE OS, the trusted kernel that isolates and schedules services. Calling the SPM the monitor is the most tempting mapping, but the SPM does not perform the world switch.

Read more: TF-M documentation (SPM design); Armv8-M ARM (DDI0553), Security state transitions

Q4.6.2 What does PSA FF-M isolation Level 2 add on top of Level 1?

  • A. Isolation of the PSA Root of Trust (SPM and PSA RoT partitions) from Application RoT partitions, typically by running ARoT partitions unprivileged behind the Secure MPU
  • B. Isolation of each Secure partition from every other Secure partition
  • C. Isolation of the SPE from the NSPE using the SAU
  • D. Encryption of Secure RAM with keys from Initial Attestation
Answer

A. Level 1 separates only Secure from Non-secure. Level 2 also protects the PSA RoT from the Application RoT. Level 3 goes further and isolates every partition from every other. The “each partition from every other” option is the tempting answer, but it describes Level 3.

Read more: Arm PSA Firmware Framework-M (FF-M), isolation levels

Q4.6.3 A FreeRTOS task on the Non-secure side calls psa_cipher_encrypt() on a single-core Armv8-M TF-M system that uses the IPC model. Which sequence is correct?

  • A. The task executes SMC, and the PE vectors to the Secure SPM at a fixed address
  • B. The NS PSA client library goes through TF-M’s NS interface to an SG veneer in NSC memory, which enters Secure state, and the SPM delivers the request as a message to the Crypto partition
  • C. The task writes a request to a shared mailbox, and the Secure core polls it
  • D. The task triggers a Secure SVC directly, and the Crypto partition runs in Non-secure Handler mode
Answer

B. On single-core TrustZone-M systems, Non-secure requests enter through SG veneers placed in NSC memory, and the SPM then routes the request to the target partition (as a message in the IPC model). SMC does not exist on M-profile. The mailbox path is tempting but applies to TF-M’s multi-core configurations, where the NSPE runs on a different core from the SPE.

Read more: TF-M documentation (NS interface, IPC model); PSA FF-M