[Operating System] An article will help you quickly understand user mode and kernel mode

Table of contents

1. Division of instructions

2. Privilege level

3. The operating system requires two CPU states

4. Conversion between CPU states

4.1 Ways of CPU state transition

4.2 CPU state conversion process

4.3 What situations will lead to switching from user mode to kernel mode?

Generally speaking, the following three situations will lead to switching from user mode to kernel mode:

1. System call

2. Abnormal

3. Interruption of peripheral devices

5. Why do we need user mode and kernel mode?

6. The difference between kernel mode and user mode


1. Division of instructions

Before talking about user mode and kernel mode, it is necessary to talk about CPU instruction set. The instruction set is the CPU implementation software to direct the hardware execution. Media, specifically, each assembly statement corresponds to a CPU instruction, and very, very many CPU instructions together can form one or even multiple sets. The set of instructions is calledCPU instruction Set.

At the same time, the CPU instruction set has permission levels. Just imagine, the CPU instruction set can directly operate the hardware. If the instruction operation is not standardized, the errors caused will affect the entire computer system. Just like when you write a program, because you are not familiar with hardware operations, the operating system kernel and all other running programs may suffer irreparable errors due to operational errors. In the end, you can only restart the computer.

The operation of hardware is very complicated, with many parameters, and the probability of problems is quite high. It must be operated carefully. It is an arduous task for developers and will increase the burden. At the same time, developers are not affected in this regard. Trust, so the operating system kernel directly shields developers from the possibility of operating the hardware, and does not let you encounter these CPU instruction sets.

Therefore, CPU instructions can be divided into the following two categories:

  • Privileged instructions:Instructions that can only be used by the operating system and cannot be used by user programs. Example: Start I/O, clear memory, modify program status word, set clock, allow/disable terminal, shutdown
  • Unprivileged instructions:Instructions that can be used by user programs. Examples: control transfer, arithmetic operation, fetch instruction Access instruction (making the user program fall from user mode into kernel mode)

The above figure vividly shows the permission restrictions of CPU instructions. Developers can only complete some instruction set calls through the operating system.

We can use a short story to vividly describe the relationship between them:

Zhang San is a junior Java development engineer (low permissions) of a technology company. He is currently working in the office code on the 15th floor. The company provides The resource is only a set of computers (user mode). Thinking about the housing prices in this area, Zhang San felt very stressed, so he set a goal for himself. You must be a technical director and take root on the front line.

Struggle forced Zhang San. After 5 years of hard work, he finally became the technical director (High authority). After that, Zhang San moved to the 30th floor. You can apply to the resources department (system call) at any time for various company resources and obtain the company's confidential information (kernel state ), the so-called reaching the pinnacle of life.

Through this story, we found that the scope of resources with low permissions is smaller, and the scope of resources with high permissions is larger. The so-called"User mode and kernel mode are just resources with different permissions. Scope".

2. Privilege level

In response to the actual needs mentioned in the previous section, hardware equipment vendors directly provide hardware-level support by setting permissions on the CPU instruction set. The CPU instruction sets that can be used by different levels of permissions are limited. Inter CPU For example, Inter classifies the permissions for CPU instruction set operations into 4 levels from high to low:

  • ring 0
  • ring 1
  • ring 2
  • ring 3

Among them, ring 0 has the highest authority and can use all CPU instruction sets, which is equivalent to the kernel state; ring 3 has the lowest authority and can only use the regular CPU instruction set and cannot use the CPU instruction set that operates hardware resources, such as IO reading and writing, network card access, and application. Even memory is not enough, R3 is equivalent to user mode; the Linux system only uses two permissions, ring 0 and ring 3.

The code executing in the kernel space has ring 0 protection level, has all operating permissions on the hardware, can execute all CPU instruction sets, and access memory at any address. Any exception in kernel mode is catastrophic and will cause the entire The machine is shut down.

In user mode, with ring 3 protection level, the code does not have direct control over the hardware, nor can it directly access the memory of the address. The program accesses the hardware and memory by calling system interfaces (System Call APIs). In this protection In this mode, even if the program crashes, it can be recovered. Most programs on the computer run in user mode.

To put it simply:

  • Ring 0 is called kernel state and runs entirely within the operating system kernel.
  • Ring 3 is called user mode and runs in the application

3. The operating system requires two types ofCPUstates

User mode and kernel mode are the two operating states of the operating system:

  • Kernel Mode: The CPU in the kernel mode can access any data, including peripheral devices, such as network cards, hard disks, etc. The CPU in the kernel mode can access data from a The program switches to another program, and the CPU occupied in this state will not be preempted. Generally, the state of privilege level 0 is called kernel state. This state is used to run operating system programs and operate hardware.
  • User Mode: The CPU in user mode can only have limited access to memory and is not allowed to access peripheral devices. The CPU in user mode is not allowed to be exclusive. In other words, the CPU can be obtained by other programs. This state is used to run user programs.

The kernel mode and user mode of the operating system not only limit the calling authority of the CPU instruction set, but also restrict the use of memory resources in the user mode and kernel mode. Each process creation will allocate "Virtual space address", taking the Linux 32-bit operating system as an example, its addressing space range is 4G (2 to the 32nd power), and the operating system will divide the virtual control address into two parts, one part is < a i=1>Kernel space, the other part is User space, high bits The upper 1G (from virtual address 0xC0000000 to 0xFFFFFFFF) is used by the kernel, while the lower 3G (from virtual address 0x00000000 to 0xBFFFFFFF) is used by individual processes.

  • User mode: can only operate low-order virtual space addresses in the 0-3G range
  • Kernel mode: Virtual space addresses in the 0-4G range can be operated, especially the high-order virtual space addresses in the 3-4G range must be operated in the kernel mode
  • Supplement: The 3G-4G part is shared by everyone (meaning that the kernel state logical addresses of all processes share the same memory address). It is the kernel state address space, where the entire kernel code and all kernel modules are stored, as well as the kernel maintained data

The 4G virtual space address of each process, the upper 1G are the same, that is, the kernel space. Only the remaining 3G is used by the process itself. In other words, the upper 1G of kernel space is shared by all processes!

Finally, to summarize, we distinguish user mode and kernel mode through instruction set permissions, and also limit the use of memory resources. The operating system divides two memory spaces for user mode and kernel mode, and uses their corresponding instruction sets.

4.CPUTransition between states

The concept of user mode and kernel mode is the difference between CPU instruction set permissions. To read and write IO in the process, the ring 0 level CPU instruction set will inevitably be used. At this time, the CPU instruction set operation permissions are only ring 3. In order to be able to operate Ring 0 level CPU instruction set, CPU switching instruction set operation permission level is ring 0, CPU then executes the corresponding ring 0 level CPU instruction set (kernel code), and the executed kernel code will use the kernel stack of the current process.

PS : Each process has two stacks, namely the user stack and the kernel stack, corresponding to the use of user mode and kernel mode

4.1 CPUState transition path

User mode--->Kernel mode:The only way is through interrupts, exceptions, and trap mechanisms (access management instructions)

Kernel mode--->User mode:Set program status word PSW

4.2 CPUcondition change process

I believe everyone has heard the saying "Switching between user mode and kernel mode is expensive", but where is the cost? To put it simply, the state transformation has the following steps:

  1. Preserve user state scene (context, registers, user stack, etc.)
  2. Copy the user mode parameters, switch the user stack to the kernel stack, and enter the kernel mode.
  3. Extra checks (because the kernel code doesn't trust the user)
  4. Execute kernel mode code
  5. Copy the kernel mode code execution results and return to user mode
  6. Restore user mode scene (context, registers, user stack, etc.)

In fact, the operating system will be more complicated than the above. This is just a rough idea. We can find that a switch goes through "user mode -> kernel mode -> user mode".

If the user state actively switches to the kernel state, there must be an entrance. In fact, the kernel state provides a unified entrance. The following is the overall architecture diagram of Linux.

From the above figure we can see that the entire Linux system is divided into user mode and kernel mode through system calls. In order for applications to access kernel resources, such as CPU, memory, and I/O, the kernel must provide a A set of common access interfaces, these interfaces are called system calls.

Library function is to shield these complex underlying implementation details, reduce the burden on programmers, and thus pay more attention to the upper-layer logic implementation. It encapsulates system calls and provides simple basic interface to programmers.

ShellAs the name suggests, it means shell, just like a shell that wraps the kernel. It is a special application, commonly known as the command line. Shell is also programmable. It has standard Shell syntax. Text that conforms to its syntax is called Shell script. Many people use Shell scripts to implement some common functions, which can improve work efficiency.

4.3 What situations will lead to switching from user mode to kernel mode

Generally speaking, the following three situations will lead to switching from user mode to kernel mode:

1, for system tuning

This is a way for the user mode process to actively request to switch to the kernel mode,The user mode process applies to use the operating system provided by the system call The service program completes the work. For example, fork() actually executes a system call that creates a new process.

The core of the system call mechanism is implemented using an interrupt specially opened by the operating system for users, such as the int 80h interrupt of Linux.

User programs usually call library functions, which then call system calls. Therefore, some library functions will cause the user program to enter the kernel state (as long as a system call is called somewhere in the library function), and some will not.

2、异常

When the CPU is executing a program running in user mode, some unknown exception occurs, which will trigger a switch from the current running process to the kernel-related program that handles the exception, and then transfer to the kernel mode, such as Page fault exception.

3, peripheral device interrupt

When the CPU is executing a user-mode process, after the peripheral device completes the operation requested by the user, it will send a corresponding interrupt signal to the CPU , at this time the CPU will suspend execution of the next instruction to be executed and instead execute the processing program corresponding to the interrupt signal,

If the previously executed instruction was a program in user mode, then the conversion process will naturally involve switching from user mode to kernel mode. For example, after the hard disk read and write operation is completed, the system will switch to the hard disk read and write interrupt handler to perform subsequent operations, etc.

These three methods are the most important ways for the system to transfer from user mode to kernel mode at runtime. System calls can be considered to be actively initiated by the user process, while exceptions and peripheral device interrupts are passive.

5. Why do we need user mode and kernel mode?

This is mainly due to the limitation of access capabilities. There are some relatively dangerous operations in the computer, such as setting the clock and cleaning up the memory. These need to be completed in the kernel state. If dangerous operations are performed at will, it is very easy to cause the system to crash.

6. The difference between kernel mode and user mode

  • Kernel mode and user mode are two operating levels of the operating system. When a program runs at the 3rd privilege level, it can be said to be running in user mode. Because this is the lowest privilege level, it is the privilege level for ordinary user processes to run. Most of the programs that users directly face run in user mode;
  • When a program runs at privilege level 0, it can be said to be running in kernel mode.
  • Programs running in user mode cannot directly access operating system kernel data structures and programs. When we execute a program in the system, it runs in the user mode most of the time. When it needs the help of the operating system to complete some work that it does not have the power and ability to complete, it will switch to the kernel mode (such as operating hardware). .

Summary: The main difference between these two states is

  • When executing in user mode, the memory space and objects that the process can access are restricted, and the processor it occupies can be preempted.
  • When executing in kernel mode, all memory spaces and objects can be accessed, and the occupied processor is not allowed to be preempted.

Reference article: https://blog.csdn.net/m0_37199770/article/details/113482312

Guess you like

Origin blog.csdn.net/cy973071263/article/details/129250644