what is the difference between user mode and kernel mode? why it need a context switch when switch between the 2?
migrated from stackoverflow.com Mar 26 '11 at 9:55
This question came from our site for professional and enthusiast programmers.
My answer relates to Linux because that's what I know, but it should be equally correct for most, if not all, versions of Unix.
User mode is where all processes that aren't part of the kernel (aka "non-kernel processes") run. In user mode, a process can only directly access its own memory, by default. This is to protect processes from each other and to try to prevent a bug in one process causing another process to crash. It also helps to enforce security, since a low-privilege process cannot directly access the memory of a process running as another user, which might contain confidential data such as credit card details.
However, there are some operations in the kernel that have to access the whole system memory - for example, creating new processes. For this, kernel mode is needed, because that can access any virtual or physical address that is physically accessible. (For the purposes of this answer I am ignoring hypervisors, which complicate this picture slightly.)
Switching between user mode and kernel mode may require a context switch, but only because of long-standing convention, not because it's absolutely necessary. Source: http://en.wikipedia.org/wiki/Context_switch#User_and_kernel_mode_switching
Assuming x86 architecture:
Yes, it's totally possible for a process in kernel mode to overwrite other processes or code in memory, such as critical kernel structures or device drivers.
A "context switch" is needed because whenever the x86 CPU is running a program, a lot of the current state of that program at a given moment exists in its registers, in addition to RAM locations it might be using for variables and temporary storage.
So, if we want the CPU to suddenly jump elsewhere, and then return to what it was doing before, it's necessary to save all the CPU registeres so they can be restored before the jump back.
The kernel is responsible for managing the system's resources (scheduling, memory management, networking etc). The kernel runs in a protected context called ring 0 to prevent it from modification by unprivileged users.
Applications run in user mode (ring 3), and switch context when it executes a system call to requests a service from the kernel.