OSCtxSw

Description

OSCtxSw() is called from the macro OS_TASK_SW(), which in turn is called from OSSched() to perform a task-level context switch. Interrupts are disabled when OSCtxSw() is called.

Prior to calling OSCtxSw()OSTCBCurPtr to point at the OS_TCB of the task that is being switched out, and OSSched() sets OSTCBHighRdyPtr to point at the OS_TCB of the task being switched in.

Files

os.h/os_cpu_a.asm

Prototype

void  OSCtxSw (void)

Arguments

None

Returned Values

None

Required Configuration

None

Callers

OSSched().

Notes/Warnings

None

Example Usage

The pseudocode for OSCtxSw() follows:

OSCtxSw() example usage
          void  OSCtxSw (void)
          {
              Save all CPU registers;                         (1)
              OSTCBCurPtr->StkPtr = SP;                       (2)
              OSTaskSwHook();                                 (3)
              OSPrioCur           = OSPrioHighRdy;            (4)
              OSTCBCurPtr         = OSTCBHighRdyPtr;          (5)
              SP                  = OSTCBHighRdyPtr->StkPtr;  (6)
              Restore all CPU registers;                      (7)
              Return from interrupt;                          (8)
          }

(1) OSCtxSw() must save all of the CPU registers onto the current task’s stack. OSCtxSw() is called from the context of the task being switched out. Therefore, the CPU stack pointer is pointing to the proper stack. The user must save all of the registers in the same order as if an ISR started and all the CPU registers were saved on the stack. The stacking order should therefore match that of OSTaskStkInit().

(2) The current task’s stack pointer is then saved into the current task’s OS_TCB.

(3) Next, OSCtxSw() must call OSTaskSwHook().

(4) OSPrioHighRdy is copied to OSPrioCur.

(5) OSTCBHighRdyPtr is copied to OSTCBCurPtr since the current task is now the task being switched in.

(6) The stack pointer of the new task is restored from the OS_TCB of the new task.

(7) All the CPU registers from the new task’s stack are restored.

(8) Finally, OSCtxSw() must execute a return from interrupt instruction.