What are MSP and PSP and why are there two stack pointers?
Short answer: Cortex-M has two banked stack pointers. The Main Stack Pointer (MSP) is used after reset, by all exception handlers, and by bare-metal code. The Process Stack Pointer (PSP) can be used by code in Thread mode (when CONTROL.SPSEL = 1). An RTOS gives each task its own stack through PSP, while all interrupts run on the single main stack.
Why two stacks help
- Smaller task stacks: interrupts never use a task's stack, so each task stack does not need extra space for the worst-case nesting of interrupts (which could be several hundred bytes). With 20 tasks this saves a lot of RAM.
- Robustness: a task that overflows or corrupts its own stack does not break the stack that interrupts and the kernel rely on.
- Fast context switches: the RTOS only saves/restores PSP and the task's registers; handler mode keeps using MSP.
- Privilege separation: combined with unprivileged thread mode and the MPU, tasks cannot touch the kernel's stack.
How the hardware uses them
- On exception entry, the core pushes the exception frame onto whichever stack the interrupted code was using (MSP or PSP), then switches to MSP for the handler.
LRgets anEXC_RETURNvalue:0xFFFFFFF9return to Thread mode using MSP,0xFFFFFFFDreturn to Thread mode using PSP,0xFFFFFFF1return to Handler mode (nested). (Values with FP context differ in bit 4:0xFFFFFFE9/0xFFFFFFED.)
How an RTOS starts: the scheduler sets PSP to the first task's prepared stack and then either sets CONTROL.SPSEL and branches, or triggers an SVC whose return uses EXC_RETURN = 0xFFFFFFFD to "return" into the first task on PSP.
Bare-metal code usually never touches PSP; everything runs on MSP. The initial MSP value comes from the first entry of the vector table.
Debugging tip: in a HardFault handler, test bit 2 of LR to know which stack holds the faulting frame:
__attribute__((naked)) void HardFault_Handler(void)
{
__asm volatile(
"tst lr, #4 \n"
"ite eq \n"
"mrseq r0, msp \n"
"mrsne r0, psp \n"
"b hard_fault_c \n"); /* hard_fault_c(uint32_t *frame) reads frame[6] = PC */
}