Saturday, 28 April 2012

Linux Kernel Mode


There are 2 modes in Linux: Kernel mode and User mode. Kernel mode is at a higher privilege level than user mode. All user programs and the applications running on the machine run in user mode. Only the kernel executes in kernel mode. A program executing in user mode can’t access kernel code, so can’t directly call system calls. This is done for security purposes because if a user program can access the kernel code, he can change it or access the memory which he should not access. So, the kernel assigns itself the highest privilege level: kernel mode. User processes are at the least privilege level: user mode. The kernel is protected by hardware, because programs executed in user mode can’t access the memory that belongs to programs executed in kernel mode.

This protection by hardware has a problem. User processes can’t access any feature provided by the kernel. In other words, user processes can’t make use of the system calls provided by the kernel. Again to cope up with this problem we go take help from the hardware. The only possible way to use system calls is to escalate the privilege level of the user process. So, we make use of interrupts, in this case software interrupt. A software interrupt can be seen as a special jump instruction whose target address is restricted by the kernel. The kernel sets the target address of the software instruction to the special routine that handles the system calls. Now suppose the user wants to use a system call. First of all what is done is that the code corresponding to the system call is put in a register for the kernel to understand which system call the user wants to call. The task of setting the system call code is done by the library procedure and is hidden from the user. After setting the code for the specific system call, a trap to the kernel takes place. Then the dispatcher in the kernel calls the specific system call using the code set in the register. Then a context switch takes place in which it saves the content of the registers of the user program. Then finally the control passes to the kernel procedure which performs its task.

But there is another side of the story. The system call by this hardware approach can become very slow because the software interrupt and the context switch, which takes place in the kernel require heavy and complex operations. This can be gauged by seeing that a system call is on an average about 30 times slower than a simple function call.

So the next question which comes to mind is how to accelerate system call? The obvious way to do this is to execute the user process in kernel mode. Then no software interrupt and context switch is needed. System calls would be just like normal function calls because the user process can access the kernel directly. But this is not as easy as it sounds. There are a lot of issues with this approach, foremost of which is security.

No comments:

Post a Comment