Context Switching

Context switching is a hardware-dependent component of the operating system kernel. It enables multitasking by allowing the CPU to rapidly switch between tasks, creating the appearance of simultaneous execution. Implementation of this logic is mandatory only when the operating system is active (i.e., the OS_USED constant is set to 1).

To switch execution from one task to another, the state of the currently running task must be saved immediately upon suspension and restored before the task resumes. This state, known as the task context, includes the CPU register set and other data required to continue execution from the point of interruption. The standard context switching workflow is as follows:

  • Interrupting the execution of the current task.
  • Saving the current task context.
  • Determining the next task to run (performed by the operating system scheduler).
  • Restoring the context of the new task.
  • Resuming execution of the new task.

The task context is defined by the TTaskContext structure. While all context data could theoretically be stored within this structure, it is highly recommended to store only the stack pointer here. The actual register state should be pushed onto the task's stack. This approach significantly accelerates context saving/restoring and reduces the overhead of manipulating the TTaskContext descriptor.

Before a task is executed for the first time, its stack must be initialized with a default startup context. The Program Counter (PC) or Instruction Pointer (IP) must be set to the task startup procedure. When the first context switch to the task occurs, execution will begin at this procedure using the default context values.

Preemption control is typically achieved by disabling and enabling global interrupts. Each task maintains its own interrupt state within its context. If preemption is disabled for the running task, context switching can only occur via a voluntary yield (by calling the arYield function). If preemption is enabled, context switching occurs automatically upon preemption events (e.g., timer ticks).

The following components must be implemented to support the Sirius RTOS:

  • arLock / arRestore: Functions for disabling and re-enabling preemption (interrupts).
  • TTaskContext: A structure definition containing the data required to save and restore a task context.
  • arCreateTaskContext / arReleaseTaskContext: Functions to initialize and release task contexts.
  • Preemption Handler: An ISR or procedure that realizes preemption, along with the arYield function for manual context switching.
  • arSetPreemptiveHandler: A function to register the operating system scheduler callback.
  • arSavePower: A function to enter low-power CPU modes when no tasks are executing (idle state).

Detailed descriptions of these items are provided in the following sections.

SpaceShadow documentation