How an RTOS Context Switch Works on Cortex-M With PendSV
Follow a FreeRTOS context switch on Cortex-M4F from the yield request to the PendSV handler, and see which registers hardware stacks and which software saves.

A context switch is the moment one task stops and another starts, and on Cortex-M it takes about thirty instructions, nearly all of them in one exception handler. Understanding that handler turns a pile of mysterious RTOS behavior (why the stack of a sleeping task holds a strange pattern, why interrupt priorities matter, why portYIELD() does not switch immediately) into a short, readable story. This post walks the FreeRTOS Kernel V11.3.3 Cortex-M4F port, the GCC ARM_CM4F variant, from the request to switch to the return into the next task. The cornerstone guide on RTOS design for microcontrollers gives the wider context; here we stay on one core and one handler.
Why a context switch needs an exception
A task is, from the CPU's point of view, a set of register values and a stack. To switch tasks the kernel must store the registers of the outgoing task, pick a new task and load its registers. Doing that from ordinary code is awkward, because the code doing the saving is itself using registers. An exception makes it clean: on entry, the hardware saves part of the context automatically, and on return it restores it, so the handler only has to deal with the rest.
Cortex-M splits the work like this:
| Registers | Who saves them | Where |
|---|---|---|
R0-R3, R12, LR, PC, xPSR | Hardware, on exception entry | Stack in use at the time, the task's own stack |
S0-S15, FPSCR (FPU, if the task used it) | Hardware, with lazy stacking | Same stack |
R4-R11 | Software, in the handler | The task's stack |
S16-S31 (FPU) | Software, in the handler | The task's stack |
The ARMv7-M Architecture Reference Manual defines this stacking in the exception entry section. The key consequence: the handler must save and restore only R4-R11 (plus EXC_RETURN and the high FPU registers), and the final bx r14 with a special return value makes the hardware unstack the rest.
Why PendSV and not SysTick
You could switch tasks from inside the SysTick handler, and some small kernels do. FreeRTOS uses a separate, dedicated exception, PendSV (pendable service call), configured at the lowest possible interrupt priority. The reason is interrupt latency. If a peripheral interrupt arrives while the tick handler runs, you want it serviced promptly. If the switch ran inside a high-priority handler, it would delay every lower interrupt. With PendSV at the lowest priority, the switch runs only when no other interrupt is active, so it never preempts an ISR.
The port sets both priorities during xPortStartScheduler:
portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;Both values come from portMIN_INTERRUPT_PRIORITY, the numerically highest and logically lowest priority your part implements. The kernel never needs the tick or the switch to preempt your peripheral interrupts.
Requesting a switch
portYIELD() does not switch tasks. It pends the exception by setting bit 28 of the Interrupt Control and State Register:
#define portNVIC_PENDSVSET_BIT ( 1UL << 28UL )
#define portYIELD() \
{ \
portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT; \
__asm volatile ( "dsb" ::: "memory" ); \
__asm volatile ( "isb" ); \
}That is a simplified view of the macro in portmacro.h. In a task context the exception is taken immediately after the write, because PendSV is the highest-priority pending exception that outranks thread mode. From inside an interrupt handler, the exception stays pending until the handler returns and no higher-priority interrupt is active. This is why portYIELD_FROM_ISR(xWoken) is the last line of an ISR: it sets the pending bit, and the switch happens on exit.
The tick handler uses the same mechanism. xPortSysTickHandler calls xTaskIncrementTick(), and if that reports that a switch is needed, it sets the PendSV bit.
The handler, line by line
This is the core of xPortPendSVHandler in the ARM_CM4F port, in the order the processor runs it:
mrs r0, psp ; r0 = the task's stack pointer
isb
ldr r3, =pxCurrentTCB ; r3 = address of the current-TCB pointer
ldr r2, [r3] ; r2 = the current TCB
tst r14, #0x10 ; bit 4 clear in EXC_RETURN means FPU context in use
it eq
vstmdbeq r0!, {s16-s31} ; save high FPU registers
stmdb r0!, {r4-r11, r14} ; save core registers and EXC_RETURN
str r0, [r2] ; TCB's first member = new top of stack
stmdb sp!, {r0, r3} ; keep r0 and r3 on the main stack
mov r0, #configMAX_SYSCALL_INTERRUPT_PRIORITY
msr basepri, r0 ; mask kernel-aware interrupts
dsb
isb
bl vTaskSwitchContext ; choose the next task, update pxCurrentTCB
mov r0, #0
msr basepri, r0 ; unmask
ldmia sp!, {r0, r3}
ldr r1, [r3] ; r1 = the (new) current TCB
ldr r0, [r1] ; r0 = its saved stack pointer
ldmia r0!, {r4-r11, r14} ; restore core registers and EXC_RETURN
tst r14, #0x10
it eq
vldmiaeq r0!, {s16-s31} ; restore high FPU registers
msr psp, r0 ; point PSP at the new task
isb
bx r14 ; hardware unstacks R0-R3, R12, LR, PC, xPSRFour details deserve attention.
The stack pointer lives in the first TCB member. str r0, [r2] works because pxTopOfStack is the first field of the task control block. The kernel and the assembly agree on that layout, which is why you must not reorder the struct.
**EXC_RETURN is saved too.** R14 holds a special value on exception entry. Bit 4 is clear when the task used the FPU, which tells the handler whether to save S16-S31. Saving it per task lets one task use the FPU and another not.
**BASEPRI guards the C call.** vTaskSwitchContext touches the ready lists, so interrupts that may call kernel functions must not run during it. Writing configMAX_SYSCALL_INTERRUPT_PRIORITY into BASEPRI masks exactly those, while leaving higher-priority, kernel-unaware interrupts running.
Two stacks are in play. The handler runs on the main stack (MSP), while tasks use the process stack (PSP). That is why mrs r0, psp appears first, and why stmdb sp!, {r0, r3} is safe: sp here is MSP.
What a sleeping task's stack looks like
Because the handler pushes registers downward from the task's stack pointer, a task that has been switched out holds a fixed frame: the hardware-saved eight words at the high end, the R4-R11 and EXC_RETURN block below them, and FPU registers below that if used. When a new task is created, pxPortInitialiseStack builds exactly this frame by hand, with PC set to the task function and xPSR set to the Thumb bit, so the very first switch into it looks like a return from an earlier switch out.
high addresses
xPSR 0x01000000
PC task entry
LR prvTaskExitError
R12, R3, R2, R1
R0 pvParameters
EXC_RETURN 0xFFFFFFFD
R11 ... R4
low addresses <- saved pxTopOfStackThe values shown follow the pattern the port writes for a task that has not used the FPU, with 0xFFFFFFFD meaning "return to thread mode using PSP with a basic frame." That is the layout you see in a debugger when you inspect a freshly created task, and the entry order is the one pxPortInitialiseStack produces.
When it goes wrong
Three failures trace back to this handler.
Installing the handlers wrongly. The vector table must point SVCall and PendSV at vPortSVCHandler and xPortPendSVHandler, usually with #define xPortPendSVHandler PendSV_Handler in FreeRTOSConfig.h. V11 asserts at scheduler start if the table is wrong and configCHECK_HANDLER_INSTALLATION is on.
Raising PendSV's priority above the syscall limit. The port sets the lowest priority for a reason; if a vendor library reprograms it, switches can occur inside other handlers.
Calling portYIELD() with interrupts blocked by PRIMASK. The exception stays pending until you re-enable them, which delays the switch.
The boundary: this post covers the single-core Cortex-M4F port. Cortex-M0 has no BASEPRI, and ARMv8-M ports add TrustZone and a different save sequence, so check the portable directory for your core.


