PSP and MSP in ARM Cortex-M: What They Are and How They Work
MSP (Main Stack Pointer) and PSP (Process Stack Pointer) are two separate stack pointers used to manage different stack areas. MSP is typically used for system-level tasks like interrupts, while PSP is used for application-level code or threads.How It Works
Think of the ARM Cortex-M processor as having two backpacks to carry important data: one backpack is the Main Stack Pointer (MSP) and the other is the Process Stack Pointer (PSP). Each backpack holds temporary data like function calls and local variables, but they are used in different situations.
The MSP is the default backpack used by the system, especially when handling interrupts or exceptions. It ensures that critical system tasks have a safe and separate place to store their data without interfering with the main program.
The PSP is like a personal backpack for the application code or user threads. When the processor runs normal program code, it can switch to using the PSP so that the system stack remains untouched. This separation helps keep system and user data organized and secure.
Example
This example shows how to switch from using the MSP to the PSP in ARM Cortex-M assembly code. It sets up the PSP and then switches the processor to use it for normal code execution.
LDR R0, =0x20001000 ; Load address for PSP stack top MSR PSP, R0 ; Set PSP to this address MRS R0, CONTROL ; Read CONTROL register ORR R0, R0, #2 ; Set bit 1 to select PSP MSR CONTROL, R0 ; Write back to CONTROL ISB ; Instruction Synchronization Barrier
When to Use
Use MSP for system-level tasks such as interrupt handlers and exception processing because it keeps system operations safe and isolated.
Use PSP for application code or threads in an operating system environment. This allows each thread to have its own stack space, improving stability and security.
For example, in a real-time operating system (RTOS), the kernel uses MSP while each task runs with its own PSP. This separation helps prevent tasks from corrupting system data.
Key Points
- MSP is the default stack pointer used mainly for system and interrupt handling.
- PSP is used for application or thread stacks in user mode.
- Switching between MSP and PSP is controlled by the
CONTROLregister. - Using separate stacks improves system reliability and security.