OSCtxSw()

OSCtxSw() (see os_cpu_a.asm) is called when the task level scheduler (OSSched()) determines that a new high priority task needs to execute. The figure below shows the state of several µC/OS-III variables and data structures just prior to calling OSCtxSw().

Figure - Variables and data structures prior to calling OSCtxSw()

(1) OSTCBCurPtr points to the OS_TCB of the task that is currently running and that called OSSched().

(2) OSSched() finds the new task to run by having OSTCBHighRdyPtr point to its OS_TCB.

(3) OSTCBHighRdyPtr->StkPtr points to the top of stack of the new task to run.

(4) When µC/OS-III creates or suspends a task, it always leaves the stack frame to look as if an interrupt just occurred and all the registers saved onto it. This represents the expected state of the task so it can be resumed.

(5) The CPU’s stack pointer points within the stack area (i.e., RAM) of the task that called OSSched(). Depending on how OSCtxSw() is invoked, the stack pointer may be pointing at the return address of OSCtxSw().


The figure below shows the steps involved in performing the context switch as implemented by OSCtxSw().

Figure - Operations performed by OSCtxSw()

(1) OSCtxSw() begins by saving the status register and program counter of the current task onto the current task’s stack. The saving order of register depends on how the CPU expects the registers on the stack frame when an interrupt occurs. In this case, it is assumed that the SR is stacked first. The remaining registers are then saved onto the stack.

(2) OSCtxSw() saves the contents of the CPU’s stack pointer into the OS_TCB of the task being context switched out. In other words, OSTCBCurPtr->StkPtr = R14.

(3) OSCtxSw() then loads the CPU stack pointer with the saved top-of-stack from the new task’s OS_TCB. In other words, R14 = OSTCBHighRdyPtr->StkPtr.

(4) Finally, OSCtxSw() retrieves the CPU register contents from the new stack. The program counter and status registers are generally retrieved at the same time by executing a return from interrupt instruction.