A102 Context Switch

The hardware-dependent part of context switching takes place once the scheduler has decided to instruct the current process to relinquish the CPU so that another process can run. For this purpose, all architectures must provide the switch_to function or a corresponding macro with the following prototype in


void switch_to(struct task_struct *prev, struct task_struct *next, struct task_struct *last)

The function performs a context switch by saving the state of the process specified by prev and activating the process designated by next.

Although the last parameter may initially appear to be superfluous, it is used to find the process that was running immediately prior to the function return. Note that switch_to is not a function in the usual sense because the system state can change in any number of ways between the start and end of the function.

This can be best understood via an example in which the kernel switches from process A to process B. prev points to A and next to B. Both are local variables in context A.

After process B has executed, the kernel switches to other processes and finally arrives at process X; when this process ends, the kernel reverts to process A. Because process A was exited in the middle of switch_to, execution resumes in the second half of the process. The local variables are retained (the process is not allowed to notice that the scheduler has reclaimed the CPU in the meantime), so prev points to A and next to B. However, this information is not sufficient to enable the kernel to establish which process was running immediately prior to activation of A — although it is important to know this at various points in the kernel. This is where the last variable comes in. The low-level assembler code to implement context switching must ensure that last points to the task structure of the process that ran last so that this information is still available to the kernel after a switch has been made to process A.

Continue reading here: A103 Finding the Current Process

Was this article helpful?

0 0