Context Switch – Software vs Hardware Approach
A context switch(also known as task switch or process switch) is a mechanism of storing and restoring the state of a CPU which is assigned to a particular process(or task). A context is the contents of CPU’s registers and program counter at any point in time. During a context switch, kernel performs the following steps:
1. It suspends the process which is currently executed and stores the CPU’s state for that process somewhere in the memory.
2. Retrieve the context of the next process from memory and restores the CPU’s registers with the new register values.
3. It then returns to the location indicated by the program counter in order to resume the process.
Multitasking is successfully achieved using the very basic concept of context switching. In a multitasking operating system, multiple process execute in a single CPU seemingly simultaneously. These process does not interfere with each other. The illusion of concurrency is achieved by the means of context switches that occurs in a fraction of second.
The next task to be loaded into the memory is decided by the scheduler based on an algorithm. There are several scheduling algorithms available like, Round Robin, Priority based, Priority based Round Robin etc.
Context Switch can be performed either by using Software mechanism or Hardware mechanism.
Hardware approach uses a special hardware feature of x86 processors. This special feature is called Task State Segment(TSS). TSS is a data segment that contains the state of a processor which is associated with a particular task or a process. Each task has its own execution space like general purpose register, segments, flags, task registers etc. TSS maintain this execution state for each task. A task switch in this case can explicitly be invoked using instructions like CALL or JUMP. Thus, CPU automatically loads the new state of the process from the TSS.
Software approach is used to save and reload only the state that needs to be changed. The basic principle of software approach is to provide a function that saves the current stack pointer and reloads the new stack pointer. When this function is called, the current instruction pointer pointing to current stack pointer is stored in the old stack and the new instruction pointer pointing to the new stack pointer is popped off the new stack when the function returns. General purpose registers, flags, data segment and all other relevant registers must also be pushed on to the old stack and popped off the new stack.
As hardware approach saves almost all the register state it is slow when compared to the software approach. Performance being the main target of any operating system, software context switch is widely used in most modern operating system. Moreover, 64bit architecture does not support hardware context switches and are reliable only on software context switching.
Hope it helps.!!
Recent Comments