Mechanism: Limited Direct Execution
Crux
Attaining performance while maintaining control.
Basic Technique: Limited Direct Execution
Problem #1: Restricted Operations
Crux
If the process wishes to perform some kind of restricted operation like issuing an I/O request to a disk, or gaining access to more system resources such as CPU or memory, how to implement this function?
Solution: User mode and kernel mode
User mode: Code is restricted in what it can do. For example, when running in user mode, a process can’t issue I/O requests; doing so would result in the processor raising an exception; the OS would then likely kill the process.
Kernel Mode: Operating system (or kernel) runs in this mode. Code that runs can do what it likes, including privileged operations such as issuing I/O requests and executing all types of restricted instructions.
When a user process wishes to perform privileged operation: perform a system call.
Switching between user mode and kernel mode: trap and return-from-trap instruction
When the machine boots up, the OS informs the hardware of what to do when exceptional events occur, namely, the locations of the trap handlers.
Each process has a kernel stack where registers are saved to and restored from when transitioning into and out of the kernel.
Problem #2: Switching Between Processes
Crux
How can the operating system regain control of the CPU so that it can switch between processes?
A Cooperative Approach: Wait For System Calls
The OS trusts the processes of the system to behave reasonably, processes that run for too long are assumed to periodically give up the CPU so that the OS can decide to run some other task. The OS regains control of the CPU by waiting for a system call or an illegal operation of some kind to take place.
A Non-Cooperative Approach: The OS Takes Control
A timer interrupt is raised every so many milliseconds and then the currently running process is halted, and a pre-configured interrupt handler in the OS runs. At this point, the OS has regained control of the CPU, and thus can do what it pleases: stop the current process, and start a different one.
Which code to run when the timer interrupt occurs is informed by the OS at boot time, and the timer is started at the same time.
Saving and Restoring Context
The OS executes a low-level piece of code called context switch to switch from a process to another. Whether to switch is decided by scheduler.
What a context switch does: save a few register values for the currently-executing process onto its kernel stack and restore a few for the soon-to-be-executing process from its kernel stack
Notice that there are two types of register saves/restores that happen during this protocol. See P53 of the book for more details.