1. Why Does an Operating System Need a Layered Architecture?
When a computer runs applications, it needs to use the CPU, memory, disks, networks, and various external devices.
For example, opening a browser involves the following behind the scenes:
- The CPU executes the browser's instructions.
- Memory stores web page data and program state.
- The disk reads the browser program and cache files.
- The network card receives and sends network data.
- The graphics card renders the page.
- The operating system manages processes, threads, and device access.
If applications operated all the hardware directly, many problems would arise:
- Severe hardware coupling: different hardware requires different ways of operating, making programs hard to make compatible.
- Resource contention is hard to manage: multiple programs may request CPU, memory, and device resources at the same time.
- Higher security risk: an ordinary program may accidentally modify another program's data.
- Insufficient system stability: an error in an application may affect the entire computer.
- Software development is complex: every application would need to repeatedly implement a large amount of low-level functionality.
Through a layered architecture, the operating system separates hardware management, system services, and the application execution environment.
Its core ideas are:
- The kernel is responsible for core resource management.
- User mode provides a restricted runtime environment for ordinary applications.
- System calls provide a controlled entry point for accessing services.
- System libraries and runtimes provide applications with friendlier programming interfaces.
1.1 The Overall Layering of an Operating System
The logical structure of an operating system can be summarized in the following layers:
flowchart TD
A["Users and Applications"] --> B["User-Mode Runtime Environment"]
B --> C["System Libraries and Runtimes"]
C --> D["System Call Interface"]
D --> E["Kernel Space"]
E --> F["Process and Thread Management"]
E --> G["Memory Management"]
E --> H["File System"]
E --> I["Network Protocol Stack"]
E --> J["Device Drivers and I/O"]
F --> K["Computer Hardware"]
G --> K
H --> K
I --> K
J --> K
style A fill:#FFF1D6,stroke:#E7C77D,color:#72551E
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style D fill:#EAE4F8,stroke:#B6A4D9,color:#514276
style E fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#EAE4F8,stroke:#B6A4D9,color:#514276
style I fill:#F1F5F4,stroke:#C7D4CF,color:#475569
style J fill:#FFF1D6,stroke:#E7C77D,color:#72551E
style K fill:#F6FAF7,stroke:#DCE9E0,color:#334155
Note that this is a logical layering used to understand system responsibilities; it does not mean that all operating systems strictly adopt the same internal structure.
For example:
- Linux uses an architecture based on a monolithic kernel that supports modular extension.
- Windows uses a hybrid kernel architecture.
- macOS uses a hybrid kernel architecture based on XNU.
- Microkernel systems run more services outside the kernel.
Although the implementations differ, the basic relationship among the kernel, applications, and controlled service interfaces is common to all.
2. What Is a Kernel?
2.1 Definition of a Kernel
The kernel is the most central component of an operating system; it is responsible for managing computer hardware resources and providing basic system services to applications.
The kernel typically runs at a high privilege level of the CPU and can perform privileged operations that ordinary applications cannot perform directly.
The kernel's main responsibilities include:
| Core Module | Main Responsibilities |
|---|---|
| Process management | Create, schedule, and terminate processes |
| Thread management | Manage thread state and execution context |
| CPU scheduling | Decide which thread gets the processor |
| Memory management | Allocate memory and manage virtual addresses and pages |
| File system | Manage files, directories, and storage space |
| Device management | Manage hardware devices and drivers |
| Network protocol stack | Handle network protocols and data transmission |
| Interrupt handling | Respond to hardware and software interrupts |
| Security management | Check permissions and enforce resource access control |
You can think of the kernel as the core resource manager of the entire computer system.
2.2 Why Does the Kernel Need High Privileges?
The CPU does not have to run at only one privilege level.
Modern processors typically provide multiple privilege levels to distinguish the execution permissions of different code.
Taking a common processor architecture as an example:
- x86-64 uses privilege levels such as Ring 0 through Ring 3.
- ARM architectures use exception levels such as Exception Level.
In a typical operating system:
- Kernel code runs at a higher privilege level.
- Ordinary applications run at a lower privilege level.
High privilege allows the kernel to perform critical operations, for example:
- Configuring memory mappings.
- Controlling devices.
- Managing interrupts.
- Executing privileged instructions.
- Modifying the processor execution environment.
- Managing the address space of processes.
Ordinary applications should not have these permissions.
Otherwise, an ordinary program could modify critical system data, damage other processes, or even crash the entire system.
2.3 What resources does the kernel manage?
CPU management
The CPU is one of the most important computing resources in a computer.
When multiple programs run at the same time, the kernel must decide:
- Which thread executes first.
- Which thread gets the CPU.
- How long a thread runs.
- When a thread switch occurs.
- How to handle tasks of different priorities.
This process is handled by the CPU scheduler.
flowchart TD
A["Multiple ready threads"] --> B["CPU scheduler"]
B --> C["Select the thread to run"]
C --> D["Switch execution context"]
D --> E["CPU executes the thread"]
E --> F{"Is rescheduling needed?"}
F -->|No| E
F -->|Yes| G["Save the current thread state"]
G --> B
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#EAE4F8,stroke:#B6A4D9,color:#514276
style D fill:#FFF1D6,stroke:#E7C77D,color:#72551E
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#EAE4F8,stroke:#B6A4D9,color:#514276
style G fill:#F1F5F4,stroke:#C7D4CF,color:#475569
Memory management
The kernel is responsible for managing physical memory and providing each process with a virtual address space.
The main tasks include:
- Allocating and reclaiming physical memory.
- Managing page tables.
- Establishing mappings between virtual addresses and physical addresses.
- Managing page swapping in and out.
- Controlling memory access permissions.
- Handling page faults.
For example, browsers and editors usually have independent virtual address spaces.
They can use similar virtual addresses, but those addresses ultimately map to different physical memory regions.
Device management
The kernel manages hardware through device drivers.
For example:
- The graphics card driver manages the graphics device.
- The network card driver manages the network device.
- The storage driver manages the disk device.
- The USB driver manages USB controllers and devices.
Applications usually do not need to know about the registers and control commands inside a device; instead, they use the device through interfaces provided by the operating system.
File system management
The kernel manages how data is organized through the file system.
For example:
- Creating files.
- Deleting files.
- Opening files.
- Reading files.
- Writing files.
- Managing directories.
- Checking file permissions.
Applications only need to use file operation interfaces to access data on different storage devices.
2.4 The kernel is not the complete operating system
The kernel is the core of the operating system, but a complete operating system usually also includes a large number of user-space components.
For example, a Linux distribution typically includes:
- The Linux kernel.
- The GNU toolchain.
- The C standard library.
- A shell.
- System services.
- A package manager.
- Network management tools.
- A graphical desktop environment.
Therefore:
The Linux kernel is not the same as Ubuntu; Ubuntu is a complete operating system distribution built on top of the Linux kernel.
III. What is user mode?
3.1 Definition of user mode
User mode is the restricted execution environment in which ordinary applications run.
Browsers, text editors, games, database clients, and Python programs typically all run in user mode.
User-mode programs can execute ordinary computational instructions and can access the memory and system resources the operating system allows them to use.
However, they cannot execute all privileged instructions at will, nor can they directly access memory regions protected by the kernel.
For example, ordinary applications cannot arbitrarily:
- Modify kernel page tables.
- Directly disable critical system interrupts.
- Operate arbitrary hardware control registers.
- Read the protected memory of other processes.
- Modify the kernel's own data structures.
These restrictions can reduce the impact of application errors on the entire system.
3.2 What programs run in user mode?
User mode runs not only applications, but also many components that come with the operating system.
Common examples include:
| Type | Example | Main role |
|---|---|---|
| Ordinary applications | Chrome, VS Code | Provide user-facing functionality |
| Command interpreters | Bash, PowerShell | Parse and execute commands |
| System services | systemd services, Windows services | Provide background functionality |
| System libraries | glibc, system API libraries | Encapsulate system functionality |
| Runtime environments | JVM, Python Runtime | Execute high-level language programs |
| Desktop environments | GNOME, KDE | Provide graphical interaction |
For example, running in Linux:
ps aux
The command-line tool ps is itself a user-space program.
It displays the current process status by reading information provided by the kernel.
Another example:
systemctl status
systemctl is a user-space tool; it interacts with the systemd service manager through the corresponding interface.
3.3 Why does user mode need privilege restrictions?
Suppose an ordinary application had the same privileges as the kernel.
Then it might:
- Modify physical memory at will.
- Corrupt other programs' data.
- Directly control hardware devices.
- Modify critical operating system state.
- Cause the entire system to crash.
User-mode privilege restrictions can confine errors in ordinary programs to a smaller scope.
For example:
int *ptr = (int *)0x12345678;
*ptr = 100;
This code attempts to access a specified memory address.
But whether this address is valid and whether writing to it is allowed cannot be decided by the program itself.
The processor checks the operation according to the current address-space mapping and access permissions.
If the access is illegal, an exception may be triggered, and the operating system then handles the exception.
This is the basic mechanism of user-mode memory protection.
3.4 Core differences between user mode and kernel mode
| Comparison dimension | User Mode | Kernel Mode |
|---|---|---|
| English name | User Mode | Kernel Mode |
| Main running content | Applications, system tools, and services | Operating system kernel code |
| Execution privileges | Restricted | Higher |
| Memory access | Constrained by the process address space and permissions | Can access memory managed by the kernel |
| Privileged instructions | Usually cannot execute directly | Can execute |
| Hardware access | Usually requested through system interfaces | Can be managed through drivers and kernel mechanisms |
| Stability impact | Ordinary errors are usually confined to the process | Kernel errors may cause system crashes |
Note that user mode and kernel mode describe the processor's execution privilege environment; they are not two different computers, nor two independently running operating systems.
4. How do user mode and kernel mode switch?
Applications run in user mode, but many tasks need to be completed by the operating system.
For example:
- Read files.
- Create processes.
- Request memory mappings.
- Establish network connections.
- Access devices.
- Wait for an event.
This requires a controlled switching mechanism between user mode and kernel mode.
4.1 What is privilege-level switching?
Privilege-level switching is the process by which the processor transitions from one execution privilege level to another.
For example, a typical system call process:
- The application executes in user mode.
- The application initiates a system call.
- The processor enters kernel mode through a dedicated mechanism.
- The kernel executes the corresponding service logic.
- The kernel prepares the result to return.
- The processor restores the user-mode execution environment.
- The application continues execution.
Note that privilege-level switching does not necessarily mean a process switch.
For example, when a process executes a system call, it is usually still the same process, just temporarily entering kernel mode from user mode for execution.
4.2 User mode and kernel mode switching process
flowchart TD
A["Application Running"] --> B["Executing in User Mode"]
B --> C["Requires Operating System Service"]
C --> D["Issues a System Call"]
D --> E["Processor Enters Kernel Mode"]
E --> F["Kernel Validates Arguments and Permissions"]
F --> G["Executes Kernel Service"]
G --> H["Prepares the Return Result"]
H --> I["Restores User-Mode Execution Context"]
I --> J["Application Continues Running"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#FFF1D6,stroke:#E7C77D,color:#72551E
style D fill:#EAE4F8,stroke:#B6A4D9,color:#514276
style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style F fill:#F1F5F4,stroke:#C7D4CF,color:#475569
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#EAE4F8,stroke:#B6A4D9,color:#514276
style I fill:#FFF1D6,stroke:#E7C77D,color:#72551E
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
The actual switching process is implemented jointly by the processor architecture, the operating system kernel, and the system call entry point.
Taking x86-64 as an example, Linux commonly uses the syscall instruction to enter the system call entry point and returns to user mode through a dedicated return mechanism.
4.3 What does the processor need to save during the switch?
When entering kernel mode from user mode, the processor and the kernel must ensure that the execution context can be restored correctly.
The information involved may include:
- The location of the instruction being executed in user mode.
- The user-mode stack pointer.
- The state of the flags register.
- The contents of the necessary registers.
- The system call number.
- The system call arguments.
Some of this state is saved automatically by the processor hardware, while the rest is saved and handled by the kernel entry code.
When returning to user mode, the kernel restores the necessary state so that the program can continue executing from the correct location.
The specific implementation varies across CPU architectures and operating systems.
V. What Is a System Call?
5.1 Definition of a system call
A system call is a controlled interface through which an application requests services from the operating system kernel.
It is an important boundary between user mode and kernel mode.
Ordinary applications cannot freely manipulate the kernel's internal data structures; they must request that the kernel perform the corresponding operations through system calls.
For example:
| System service | Common Linux system calls |
|---|---|
| Create a process | fork(), clone() |
| Execute a program | execve() |
| Exit a process | exit() |
| Read a file | read() |
| Write to a file | write() |
| Open a file | openat() |
| Close a file | close() |
| Create a memory mapping | mmap() |
| Network communication | socket(), connect() |
| Wait for events | poll(), epoll_wait() |
These system calls constitute the important service interfaces that the Linux kernel provides to the outside world.
5.2 What is the difference between a system call and an ordinary function?
An ordinary function call usually takes place within the same execution privilege environment.
For example:
int add(int a, int b) {
return a + b;
}
int main(void) {
int result = add(10, 20);
return 0;
}
When add() is called, the program simply jumps to the function code within the current execution environment.
It usually does not trigger a switch from user mode to kernel mode.
System calls are different.
For example:
read(fd, buffer, sizeof(buffer));
If the call ultimately needs to execute the Linux kernel's read system call, it must enter the kernel through the system call entry point, and the kernel performs the corresponding service.
The differences between the two:
| Comparison dimension | Ordinary function call | System call |
|---|---|---|
| Call target | Ordinary function | System services provided by the kernel |
| Execution privilege | Usually remains at the current privilege level | Usually enters the kernel privilege level |
| Whether privilege-level switching is required | Usually not required | Required |
| Argument handling | Passed according to the function calling convention | Passed according to the system call ABI |
| Main overhead | Function call and return | Overhead of system call entry, checks, return, etc. |
| Example | add() |
read(), write() |
Note that the name of a function called by an application is not necessarily the system call itself.
For example, printf() in the C standard library is a library function. It usually goes through buffering and formatting, and may ultimately hand data to the operating system through interfaces such as write().
5.3 Basic Composition of a System Call
A system call usually involves the following parts:
- System call number.
- System call arguments.
- System call entry.
- Kernel service implementation.
- Return value or error information.
Taking Linux x86-64 as an example, system calls usually pass arguments through registers:
| Register | Purpose |
|---|---|
rax |
System call number; stores the result on return |
rdi |
First argument |
rsi |
Second argument |
rdx |
Third argument |
r10 |
Fourth argument |
r8 |
Fifth argument |
r9 |
Sixth argument |
System call numbers and argument-passing methods are ABI conventions specific to a platform and cannot be directly applied to other CPU architectures.
5.4 Complete Execution Process of a System Call
Taking file reading as an example:
flowchart TD
A["Application calls read"] --> B["Prepare file descriptor and buffer arguments"]
B --> C["Enter system call entry"]
C --> D["Switch to kernel mode"]
D --> E["Check arguments and file access permissions"]
E --> F["Look up file object"]
F --> G["File system handles read request"]
G --> H["Initiate storage I/O if necessary"]
H --> I["Copy data to user buffer"]
I --> J["Return number of bytes read or error"]
J --> K["Restore user mode"]
K --> L["Application continues processing data"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F1F5F4,stroke:#C7D4CF,color:#475569
style C fill:#EAE4F8,stroke:#B6A4D9,color:#514276
style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style E fill:#FFF1D6,stroke:#E7C77D,color:#72551E
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#EAE4F8,stroke:#B6A4D9,color:#514276
style I fill:#F1F5F4,stroke:#C7D4CF,color:#475569
style J fill:#FFF1D6,stroke:#E7C77D,color:#72551E
style K fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
There are several key points here:
- The system call entry is responsible for receiving the call request.
- The kernel needs to check arguments and access permissions.
- The file system is responsible for organizing file access logic.
- The storage subsystem may need to issue I/O to devices.
- The data is ultimately returned to user space through an appropriate mechanism.
Not every read() needs to access a physical disk.
If the data already exists in the page cache, the kernel may provide the data directly from the cache.
VI. What Are the Differences Between System Calls, System Libraries, and APIs?
These three concepts are often confused.
6.1 API: The Interface Seen by Applications
API stands for Application Programming Interface.
It describes which capabilities a program can call, and how arguments are passed and results obtained.
For example:
with open("hello.txt", "r", encoding="utf-8") as f:
content = f.read()
Here, open() and read() are file operation interfaces provided by Python.
Developers do not need to understand the details of kernel system calls directly.
6.2 System Libraries: Encapsulating Low-Level System Capabilities
System libraries usually provide commonly used functions for applications and encapsulate low-level system calls.
For example, the GNU C Library commonly found in Linux, also known as glibc.
It provides:
- File operation functions.
- Memory allocation functions.
- String processing functions.
- Process management functions.
- Thread-related functions.
- Network-related functions.
For example:
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}
printf() is a C standard library function.
It is responsible for formatting the output and may write the data out through low-level I/O interfaces.
6.3 System Calls: Controlled Entry into the Kernel
System calls provide kernel services.
For example, in Linux:
write(1, "Hello\n", 6);
Here, write() is a system call interface that operates on file descriptors.
Applications can use it through system library wrappers.
6.4 Relationship Among the Three
flowchart TD
A["Application"] --> B["Application API"]
B --> C["Language Runtime or System Library"]
C --> D["System Call Wrapper"]
D --> E["Processor System Call Instruction"]
E --> F["Kernel System Call Entry"]
F --> G["Kernel Service Implementation"]
G --> H["Hardware Resources or Kernel Data"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF1D6,stroke:#E7C77D,color:#72551E
style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style D fill:#EAE4F8,stroke:#B6A4D9,color:#514276
style E fill:#F1F5F4,stroke:#C7D4CF,color:#475569
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#F6FAF7,stroke:#DCE9E0,color:#334155
Note:
Not all APIs correspond to system calls.
For example:
strlen()usually only calculates the string length in user mode.printf()may first perform formatting and buffering in user mode.malloc()usually first manages allocator memory in user mode and requests more memory from the operating system only when necessary.- In Linux,
read()usually requests the kernel to read data through a system call.
Therefore, APIs, system libraries, and system calls are not simply equivalent.
7. Case Study: What Happens Inside the Operating System When Reading a File?
A simple C program can connect user mode, system libraries, system calls, and the kernel.
7.1 Example Program
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp = fopen("hello.txt", "r");
if (fp == NULL) {
perror("fopen");
return 1;
}
char buffer[128];
if (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("读取内容:%s", buffer);
}
fclose(fp);
return 0;
}
The program involves:
fopen(): open a file.fgets(): read a line of text.printf(): formatted output.fclose(): close a file.
These functions are interfaces provided by the C standard library.
7.2 Underlying Execution Process
From a system architecture perspective, the execution process of this program can be summarized as follows:
flowchart TD
A["Program runs in user mode"] --> B["Call fopen"]
B --> C["C standard library handles file opening"]
C --> D["Request kernel through interfaces such as openat"]
D --> E["Kernel checks path and permissions"]
E --> F["File system looks up the file"]
F --> G["Return file descriptor"]
G --> H["Call fgets to read data"]
H --> I["Standard library reads through interfaces such as read"]
I --> J["Kernel fetches data from page cache or storage device"]
J --> K["Data is returned to user space"]
K --> L["printf outputs content"]
L --> M["Call fclose to close the file"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF1D6,stroke:#E7C77D,color:#72551E
style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style D fill:#EAE4F8,stroke:#B6A4D9,color:#514276
style E fill:#F1F5F4,stroke:#C7D4CF,color:#475569
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#FFF1D6,stroke:#E7C77D,color:#72551E
style I fill:#EAE4F8,stroke:#B6A4D9,color:#514276
style J fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style K fill:#F1F5F4,stroke:#C7D4CF,color:#475569
style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style M fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
This is only a typical execution path. The standard library may use buffering, and the actual number of system calls depends on how data is read and the buffer state.
For example, fgets() may read a larger amount of data into a user-space buffer at once; subsequent reads can use the already buffered data directly and do not necessarily trigger a system call every time.
7.3 How to observe system calls?
On Linux, you can use strace to trace a program's system calls.
For example:
strace ./hello
If the program uses a dynamically linked C standard library, you can observe something like: