Real-time operating systems (RTOS) are designed to execute application tasks in a timely and predictable manner. One key mechanism that enables real-time responsiveness in RTOS is context switching. Context switching allows the CPU to pause execution of one task and resume execution of another task in a seamless and efficient manner. The ability to rapidly switch between tasks is essential for meeting real-time constraints in embedded systems.
What is Context Switching?
Context switching refers to the procedure of storing and restoring the state or context of a CPU so that it can resume execution of a different process or thread. The context includes important data like register values, program counter, and stack pointer that are needed to pause and resume execution across several processes or threads.
Without context switching, the CPU would have to run each process until completion before switching to another process. Context switching enables the interleaving of multiple tasks by suspending the active task and resuming another waiting task. This allows the CPU to serve numerous tasks in a pseudo-parallel fashion.
Context Switching in RTOS
In RTOS, context switching occurs when a running task is interrupted by a higher priority task that becomes ready to execute. The state of the current task is stored to memory, and the context of the new higher priority task is loaded so that its execution can begin immediately.
Context switching in RTOS involves:
- Saving CPU registers, program counter, and other context data of the current task
- Updating scheduler and task control data structures
- Retrieving the context of the next task to run from memory
- Loading the new task’s context into CPU registers and program counter
- Resuming execution of the next task
The RTOS scheduler triggers a context switch when an interrupt occurs or the current task has to wait, yielding control to a higher priority task. Fast context switching minimizes the latency incurred during this transition and allows the new task to start running quickly.
Context Switching Methods
There are several techniques used to implement context switching in RTOS:
Cooperative Context Switching
In cooperative context switching, the control of the CPU is voluntarily relinquished by a task when it invokes a yield or block function. This allows the scheduler to switch context from the current task to the next ready task in the queue.
It does not use preemptive interrupts or timers to force a switch. A context switch only occurs when the running task is blocked or explicitly yields the CPU. The task must be well-behaved and designed to give up the CPU periodically.
Preemptive Context Switching
Preemptive context switching relies on timer interrupts and other hardware interrupts to halt execution of the currently running task and performs a context switch. The scheduler forcibly switches context from the current task to another task based on priority.
This ensures that higher priority tasks can preempt lower priority tasks without having to wait for the lower priority tasks to voluntarily yield control. The preemptive approach provides more reliable real-time responsiveness.
Hybrid Context Switching
Some RTOS use a hybrid model incorporating both cooperative and preemptive context switching. Tasks within a priority class cooperate with each other using cooperative switching. But a higher priority task can still preempt a currently running lower priority task.
This approach combines the benefits of predictable voluntary context switching with the responsiveness of urgent preemptive context switching across different priority levels.
Context Switching Time
The time taken to save and restore task context during a context switch is called context switch time. It is the latency incurred during the switchover between tasks.
Context switch time depends on:
- The RTOS design and optimization
- Number of registers that need to be saved and restored
- Memory speed where context is stored
- Task priority and scheduling logic
- Predictability of cache and memory access
A typical context switch may take a few microseconds on most modern RTOS platforms. The goal is to minimize context switch time so that real-time tasks are not delayed during transitions.
Context Switching Overhead
Frequent context switching can impose significant overhead on the system. Storing and retrieving context, updating scheduling data structures, and cache misses during transitions can degrade overall performance.
The overhead is directly proportional to the context switch frequency. Unnecessary context switches should be avoided by using proper task design, correct prioritization, and turning off unneeded peripherals.
Some techniques to reduce context switching overhead include:
- Keeping only essential data in saved task context
- Optimizing scheduler logic to avoid unnecessary switches
- Using fast caches and memory for context storage
- Assigning priorities appropriately to limit switches
- Deferring switches during critical sections of code
Benefits of Context Switching
Some key benefits provided by context switching in RTOS:
- concurrency – allows multiple tasks to run concurrently and make progress
- responsiveness – higher priority tasks can interrupt lower priority tasks
- scheduling – tasks can be scheduled based on their priority and state
- virtualization – gives each task the impression of exclusive CPU access
- isolation – faulty tasks cannot impair correctness of other tasks
Overall, context switching enables efficient interleaved execution of multiple tasks on a single CPU core in real-time embedded systems.
Context Switching in Popular RTOSes
Most modern RTOSes employ advanced context switching techniques:
FreeRTOS uses a hybrid preemptive + cooperative switching model. It uses preemption across priorities and cooperative switching among tasks of equal priority. The context size is user configurable.
ARM CMSIS RTOS
ARM CMSIS RTOS API allows both preemptive and cooperative context switching. The ARM Cortex-M core registers are automatically saved by hardware during interrupts.
Amazon FreeRTOS supports fully preemptive context switching for most tasks. Critical sections or resource sharing may use cooperative switching as needed. Hardware acceleration is used to boost performance.
RIOT OS is designed for low-power IoT devices. It uses tickless preemptive scheduling with idle sleep optimization. The context size is minimal with lazily saved registers.
The Zephyr RTOS uses nanokernel architecture with a minimal context switch footprint. It supports both cooperative and preemptive threads with flexible configuration options.
Context switching enables real-time multitasking by allowing the CPU to interleave execution of multiple tasks efficiently. RTOS leverage context switching techniques like preemptive scheduling and tailored context sizes to meet real-time constraints on embedded devices. Understanding context switching helps developers optimize system performance and utilization.