Switching context inside an ISR on Cortex-M

Shrikant Giridhar picture Shrikant Giridhar · Aug 8, 2014 · Viewed 8.3k times · Source

I'm trying to write a barebones round-robin scheduler for the Cortex-M using the CodeSourcery GCC toolchain. My scheduler uses the SysTick to fire an interrupt after the expiry of a time slice and the context switching takes place inside the ISR. To keep things simple, I am using only the main stack pointer (MSP) for everything.

I am stuck in determining how to handle loading the new context on the Cortex-M3. According to the Cortex-M3 Technical Reference Manual (TRM) the process pushes the PC, LR and status registers onto the current stack on the entry to the ISR.

If I push the rest of the registers to save the context of the present task and load a new SP value from the next task's control block how would I go about restoring the rest of its context?

According to what I understand, I need to pop out the registers I push (say {r4-r11}) and the processor will push out the rest (including the return address of the new task (LR) and status registers) automatically when the ISR returns. So I'm assuming I just need to execute a BX after I'm done to switch tasks?

Here is what it says on the TRM:

Exception returns occur when one of the following instructions loads a value of 0xFFFFFFFX into the PC when 1) POP/LDM which includes loading the PC 2) LDR with PC as a destination 3) BX with any register.

How do I go about loading the EXC_RETURN value? Should I just push it on to the stack (as it supposedly does here)? Assuming I've popped out the registers I've pushed via software, how does the Cortex go about popping the registers it has saved? In general, how do I restore a task's context?

I've tried reading the TRM and other ARM references but they seem unclear.

Answer

K.Mulier picture K.Mulier · Apr 9, 2016

It is indeed quite complicated. I am writing a book about the FreeRTOS operating system running on Cortex-M cores. I have written a chapter about this. From reading your question I believe this chapter will help you:

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here