Cortex M0+ MSP/PSP Context Switching

I am using a NXP S32K118 Cortex M0+ processor

I have a "scheduler" function used to call different tasks and i need to do the following:

I have 3 stacks defined in ram ( main stack, secondary stack 1, secondary stack 2 ). The idea is that the scheduler function uses the main stack, and the scheduled tasks that are called from here use the secondary stack 1 or secondary stack 2, so i need to switch from MSP to PSP when i´m in the scheduer, before calling the corresponding task, and switch back from PSP to MSP once the corresponding task is completed and im back on the scheduler.

I know how to do the switch of these pointers writing to PSP/MSP/CONTROL registers, but the problem I have is i dont know how to do this context switch / what i need to do in addition of simply changing stack pointers in order to keep all the stacks working properly, so im here just finding for any help/tips if anyone knows how to implement this properly.

Upvotes: 1

Views: 1607

Answers (1)

cooperised
cooperised

Reputation: 2599

The arrangement you describe is a little odd. In general a "scheduler function" (context switch) does not call anything, but instead arranges to return into the appropriate task. Unless you're writing a run-to-completion kernel, but if you are there is no need for separate stacks because everything nests.

Assuming you're aiming for preemption, by far the easiest way of switching stack pointers is to allow the hardware to do it for you. Remember, either MSP or PSP is always mirrored through r13 (sp). Handler mode always uses MSP, so if you configure thread mode to use PSP using the CONTROL register (remember to do this from thread mode, before you remove thread mode privilege, and to only do it once you've got PSP pointing to a stack, and use a data barrier). Now all you have to do is to ensure that your context switch runs in handler mode. Your context switch will use MSP, and can swap out the active task stack in PSP before returning. When it returns, it will branch to the stacked program counter value (see the Cortex-M reference manual) so by manipulating this value you can force return to the appropriate task.

Upvotes: 1

Related Questions