title: Switching context inside an ISR on Cortex-M
body: <p>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. </p>
  
  <p>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. </p>
  
  <p>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? </p>
  
  <p>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 <code>BX</code> after I'm done to switch tasks?</p>
  
  <p>Here is what it says on the TRM:</p>
  
  <blockquote>
    <p>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.</p>
  </blockquote>
  
  <p>How do I go about loading the EXC_RETURN value? Should I just push it on to the stack (as it supposedly does <a href="http://coactionos.com/embedded%20design%20tips/2013/10/09/Tips-Context-Switching-on-the-Cortex-M3/" rel="noreferrer">here</a>)? 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?</p>
  
  <p>I've tried reading the TRM and other ARM references but they seem unclear.</p>