I. Why Do Computers Need Memory Management?
When a program runs, its instructions and data must be loaded into memory so that the CPU can access and execute them quickly.
But physical memory is a limited resource. Suppose a computer has only 16 GB of RAM and is running a browser, a database, an IDE, and several background services at the same time—each program needs to request memory.
Without a unified memory management mechanism, many problems arise:
- Memory resource conflicts: Multiple programs may mistakenly access the same block of physical memory.
- Memory fragmentation: Free memory gets split into many non-contiguous small blocks.
- Unstable program addresses: Programs would need to know the exact location of their data in physical memory.
- Insufficient memory capacity: The total memory required by all programs may exceed the physical memory available.
- Lack of security isolation: One process may read or modify another process's data.
- Low memory allocation efficiency: Frequent allocation and release of memory incurs management overhead.
The core task of memory management is to provide a safe, efficient, and mutually isolated memory environment for multiple programs on limited physical memory.
1.1 Core Problems That Memory Management Must Solve
| Problem | Meaning | Mechanism |
|---|---|---|
| Address space | How a program obtains its own address space | Virtual memory |
| Address translation | How virtual addresses find physical locations | MMU, page tables |
| Memory allocation | How memory is allocated to programs | Paging, allocators |
| Memory protection | How to prevent processes from accessing beyond their privileges | Page table permissions, privilege levels |
| Memory expansion | What to do when physical memory is insufficient | Swap, demand paging |
| Memory reclamation | How to release memory that is no longer used | Page reclaim, garbage collection |
| Performance optimization | How to reduce memory access overhead | TLB, cache, prefetching |
1.2 Overall Architecture of Memory Management
Modern operating systems generally adopt a virtual memory mechanism. A program accesses a virtual address; the hardware memory management unit (MMU) performs address translation according to the page tables, and ultimately accesses physical memory.
flowchart TD
A["Application"] --> B["Virtual address space"]
B --> C["MMU address translation"]
C --> D["Page table lookup"]
D --> E["Physical address"]
E --> F["Physical memory RAM"]
D --> G["Page fault"]
G --> H["Operating system memory management"]
H --> I["Allocate a physical page or read from storage"]
I --> D
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#FFF1CC,stroke:#E5C77A,color:#755719
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#FCE8E8,stroke:#D9A1A1,color:#824444
style H fill:#F1F3F5,stroke:#B9C1CA,color:#475569
style I fill:#FFF1CC,stroke:#E5C77A,color:#755719
II. Physical Memory: The Real Storage Space
Physical memory usually refers to the RAM in a computer, that is, random-access memory.
It consists of memory chips and is the primary working storage area that the CPU can access directly.
Compared with hard disks and SSDs, RAM has lower access latency, but its capacity is usually smaller, and its data is lost when power is removed.
2.1 Basic Characteristics of Physical Memory
| Characteristic | Description |
|---|---|
| Fast access | Suitable for storing running programs and data |
| Limited capacity | Constrained by the number and specifications of memory modules and by motherboard support |
| Volatile | Data in ordinary RAM is lost when power is removed |
| Accessed by address | The CPU locates memory positions through physical addresses |
| Shared by multiple processes | The memory of multiple processes is ultimately carried by the same physical memory resource |
2.2 What Is a Physical Address?
A physical address is the address actually used to locate a position in physical memory.
For example, a piece of data is located at the physical address:
0x0000000010002000
This address indicates the position of the data in the physical address space.
Note that the physical address space does not necessarily all correspond to RAM.
In modern computers, the physical address space may also map:
- RAM memory regions.
- MMIO registers of PCIe devices.
- Memory regions of graphics cards and other devices.
- Firmware-reserved regions.
- Platform device regions such as ACPI.
Therefore, a physical address is not simply an offset into a particular chip on a memory module.
2.3 Organization of Physical Memory
Operating systems usually do not manage all physical memory directly in arbitrary byte units; instead, they divide physical memory into fixed-size page frames (Page Frame).
For example, when the system uses 4 KB pages:
Physical Memory
|
+-- Page Frame 0 4 KB
+-- Page Frame 1 4 KB
+-- Page Frame 2 4 KB
+-- Page Frame 3 4 KB
+-- Page Frame 4 4 KB
+-- ...
Each Page Frame has a corresponding physical page frame number.
Suppose the physical address is:
0x0000000012345678
In a 4 KB page system:
- Page size: 4096 bytes.
- Page offset: the low 12 bits.
- Physical page frame number: the high-order part.
The operating system can manage physical memory through page frame numbers without having to track every storage location byte by byte.
III. Virtual Memory: The Memory Space Programs See
Virtual Memory is a memory abstraction mechanism provided by the operating system.
It provides each process with an independent virtual address space, allowing programs to access data using virtual addresses without needing to know directly which physical memory the data actually resides in.
For example, both processes can use:
0x0000000000401000
this virtual address.
But they may map to completely different physical memory locations.
flowchart TD
A["Process A"] --> B["Virtual address 0x401000"]
C["Process B"] --> D["Virtual address 0x401000"]
B --> E["Process A's page table"]
D --> F["Process B's page table"]
E --> G["Physical page frame 100"]
F --> H["Physical page frame 500"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style G fill:#FFF1CC,stroke:#E5C77A,color:#755719
style H fill:#FFF1CC,stroke:#E5C77A,color:#755719
The two processes use the same virtual address, but they actually access different physical page frames.
This is an important foundation of process memory isolation.
3.1 What Problems Does Virtual Memory Solve?
First, it provides independent address spaces.
Each process has its own virtual address space and does not need to coordinate the use of virtual addresses with other processes.
Second, it simplifies program development.
Programs do not need to know which physical memory they are loaded into, nor do they need to manually calculate the physical memory layout.
Third, it enables memory protection.
The operating system can set read, write, and execute permissions for different memory regions to prevent processes from accessing beyond their privileges.
Fourth, it supports on-demand loading.
A program does not have to load all of its contents into RAM as soon as it starts. Only when a page is actually accessed may the system allocate a physical page or read data from a storage device.
Fifth, it supports memory sharing.
Multiple processes can map the same physical pages into their respective virtual address spaces, enabling features such as shared libraries and shared memory.
Sixth, it overcomes physical memory capacity limits.
The virtual address space can be larger than physical memory. The operating system manages the pages that are actually resident through mechanisms such as demand paging, file mapping, and swap space.
However, this does not mean virtual memory can expand indefinitely. The address space size, commit memory limits, and the capacities of physical memory and swap space all impose constraints.
3.2 Typical Layout of a Virtual Address Space
Taking a typical user process as an example, its virtual address space usually contains the following regions:
High address
+-----------------------------+
| Stack |
| Local vars, function calls |
+-----------------------------+
| |
| Memory-mapped region |
| mmap, shared libs, file maps|
| |
+-----------------------------+
| Heap |
| malloc/new dynamic alloc |
+-----------------------------+
| BSS |
| Uninitialized globals |
+-----------------------------+
| Data |
| Initialized globals |
+-----------------------------+
| Text |
| Program code |
+-----------------------------+
Low address
This is a conceptual layout and does not mean that all operating systems and architectures use exactly the same arrangement.
The actual layout may be affected by the following factors:
- Operating system and CPU architecture.
- Process bitness and address space configuration.
- ASLR, address space layout randomization.
- Dynamic linker and shared library loading methods.
- Specific policies for the stack and memory-mapped regions.
3.3 Composition of the Virtual Address Space
| Region | Contents | Typical Use |
|---|---|---|
| Text | Program machine instructions | Execute program code |
| Data | Initialized global and static variables | Store global data |
| BSS | Uninitialized or zero-initialized global and static variables | Store default-initialized data |
| Heap | Dynamically allocated memory | malloc, new |
| Memory Mapping | File mappings, shared libraries, anonymous mappings | mmap |
| Stack | Function call frames, local variables, etc. | Function execution |
Note the following:
- The heap and stack are logical regions in the virtual address space, not two separate types of physical memory.
- They both ultimately need address translation to access physical memory.
- The heap is not necessarily adjacent to the data segment, and the stack and heap do not necessarily grow in fixed directions.
- In modern systems, the layout of memory-mapped regions can be quite complex.
4. How Are Virtual Addresses and Physical Addresses Translated?
The key to virtual memory working is the address translation mechanism.
When the CPU executes load and store instructions, it typically uses virtual addresses. The MMU translates virtual addresses into physical addresses based on the address space mapping of the current process.
This process is completed jointly by hardware and the operating system.
4.1 What Is the MMU?
MMU stands for Memory Management Unit.
It is usually integrated into the CPU, is responsible for translating virtual addresses to physical addresses, and participates in memory access permission checks.
The MMU's main responsibilities include:
- Look up the address translation cache.
- Perform address translation based on the page table.
- Check page access permissions.
- Detect illegal memory accesses.
- Trigger a page fault exception when necessary.
The MMU is not responsible for deciding how much memory the entire system should allocate. Physical page allocation, page reclamation, page fault handling, and related work are mainly handled by the operating system.
4.2 Composition of a Virtual Address
In paged memory management, a virtual address can usually be split into two parts:
Virtual address
+---------------------------+----------------+
| Virtual page number (VPN) | Page offset |
+---------------------------+----------------+
- VPN: Virtual Page Number.
- Offset: the page offset, used to locate the specific byte within a page.
Assume the page size is 4 KB:
Therefore, the page offset requires 12 bits.
If the virtual address width is 48 bits, it can be conceptually divided as follows:
| Field | Bits | Purpose |
|---|---|---|
| Virtual page number | 36 bits | Locate the virtual page |
| Page offset | 12 bits | Locate the position within the page |
The actual usable virtual address range also depends on the CPU architecture, address conventions, and operating system configuration.
4.3 Example Address Translation Calculation
Assume:
- The page size is 4 KB.
- The virtual address is
0x12345ABC. - The page table maps the virtual page number to physical page frame
0x56789.
First, calculate the virtual page number and page offset.
The page size is 4 KB, so the low 12 bits are the page offset:
Virtual address: 0x12345ABC
Virtual page number: 0x12345
Page offset: 0xABC
Then look up the page table:
VPN 0x12345
|
v
PFN 0x56789
Finally, combine the physical page frame number with the page offset:
Physical address = PFN × Page size + Offset
That is:
Physical address = 0x56789000 + 0xABC
= 0x56789ABC
Therefore:
Virtual address: 0x12345ABC
Physical address: 0x56789ABC
The translation relationship here is determined by the page table; it is not simply adding a fixed offset to the virtual address.
4.4 The Complete Address Translation Process
flowchart TD
A["CPU generates virtual address"] --> B["Extract virtual page number and page offset"]
B --> C["Look up TLB"]
C --> D{"TLB hit?"}
D -->|Yes| E["Obtain physical page frame number"]
D -->|No| F["Look up multi-level page table"]
F --> G{"Page table entry valid?"}
G -->|Yes| H["Update TLB"]
H --> E
G -->|No| I["Trigger page fault exception"]
I --> J["Operating system handles page fault"]
J --> K["Create or update page table mapping"]
K --> L["Re-execute memory access"]
L --> C
E --> M["Combine physical page frame number and page offset"]
M --> N["Access physical memory"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style D fill:#FFF1CC,stroke:#E5C77A,color:#755719
style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#FFF1CC,stroke:#E5C77A,color:#755719
style H fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style I fill:#FCE8E8,stroke:#D9A1A1,color:#824444
style J fill:#F1F3F5,stroke:#B9C1CA,color:#475569
style K fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style M fill:#FFF1CC,stroke:#E5C77A,color:#755719
style N fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
5. Page Tables: The Core Data Structure of Virtual Memory Mapping
The page table is one of the core data structures maintained by the operating system.
It records the mapping between virtual pages and physical page frames, and stores information such as access permissions and validity status.
A page table can be understood as an address mapping table:
| Virtual Page Number VPN | Physical Page Frame PFN | Status | Permissions |
|---|---|---|---|
| 0x001 | 0x105 | Valid | Read, execute |
| 0x002 | 0x108 | Valid | Read/write |
| 0x003 | None | Unmapped | None |
| 0x004 | 0x210 | Valid | Read-only |
When the CPU accesses a virtual address, the MMU needs to find the corresponding physical page frame according to the page table.
5.1 What Does a Page Table Entry PTE Contain?
A page table entry typically contains the following information:
| Field | Function |
|---|---|
| Physical page frame number | Points to the corresponding physical page |
| Present / Valid | Indicates whether the mapping is valid or whether the page is resident |
| Read / Write | Controls read/write permissions |
| User / Supervisor | Controls user-mode and kernel-mode access |
| Execute Disable | Controls whether execution is allowed |
| Accessed | Records whether the page has been accessed |
| Dirty | Records whether the page has been written |
| Cache attributes | Controls cache-related behavior |
The exact field names, meanings, and encoding depend on the CPU architecture.
In particular, note that a page not existing, a page not being in memory, permissions not allowing access, and an address being unmapped are not exactly the same situation.
5.2 Why Are Multi-Level Page Tables Needed?
If a single-level page table is used, a process may require an extremely large page table.
Suppose:
- The virtual address space is 48 bits.
- The page size is 4 KB.
- The page table entry size is 8 bytes.
The number of virtual pages is:
A single-level page table would require:
That is, 512 GB.
Obviously, allocating such a huge page table for every process is unrealistic.
Therefore, modern operating systems usually use multi-level page tables.
Multi-level page tables create lower-level page tables only for address regions that are actually used, thereby reducing page table memory overhead.
5.3 How Multi-Level Page Tables Work
Take a typical four-level page table structure as an example:
flowchart TD
A["Virtual address"] --> B["PML4 index"]
B --> C["PML4 entry"]
C --> D["PDPT index"]
D --> E["PDPT entry"]
E --> F["PD index"]
F --> G["PD entry"]
G --> H["PT index"]
H --> I["Page table entry PTE"]
I --> J["Physical frame number"]
J --> K["Combine with page offset"]
K --> L["Physical address"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style D fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style E fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#FFF1CC,stroke:#E5C77A,color:#755719
style I fill:#FFF1CC,stroke:#E5C77A,color:#755719
style J fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style K fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style L fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
The four-level page table is a common traditional paging hierarchy example on x86-64. Actual systems may use a different number of page-table levels and may also enable larger pages.
5.4 What Are the Advantages of Multi-Level Page Tables?
- Saves space: lower-level page tables are created only for the virtual address regions that need them.
- Supports sparse address spaces: large amounts of unmapped addresses can remain between different regions.
- Easier to manage: mappings for different address ranges can be maintained hierarchically.
- Supports permission control: page-table entries at different levels can participate in permission restrictions.
The disadvantage is that page-table walking may require multiple memory accesses, which is also why the TLB is so important.
6. TLB: Why Doesn't Address Translation Need to Look Up the Page Table Every Time?
TLB, short for Translation Lookaside Buffer, is the address-translation cache.
It is a high-speed cache inside the CPU used to cache mappings from virtual addresses to physical addresses.
If every memory access had to walk the multi-level page table, it would incur extra access overhead.
The role of the TLB is to cache recently used address mappings and reduce the number of repeated page-table lookups.
6.1 TLB Hits and Misses
Suppose the CPU accesses a virtual address:
- TLB hit: the physical frame number is obtained directly.
- TLB miss: a page-table walk is required.
- Valid page-table mapping: the mapping result is placed in the TLB.
- Invalid page-table mapping or insufficient access permissions: an exception may be triggered.
flowchart TD
A["CPU initiates memory access"] --> B["Query TLB"]
B --> C{"Hit?"}
C -->|Hit| D["Obtain physical address mapping directly"]
C -->|Miss| E["Walk page table"]
E --> F{"Is mapping valid?"}
F -->|Valid| G["Update TLB"]
G --> D
F -->|Invalid or permission error| H["Trigger exception"]
D --> I["Access physical memory"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style C fill:#FFF1CC,stroke:#E5C77A,color:#755719
style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#FFF1CC,stroke:#E5C77A,color:#755719
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#FCE8E8,stroke:#D9A1A1,color:#824444
style I fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
6.2 Why Can the TLB Improve Performance?
Assume:
- The TLB hit rate is 99%.
- A TLB hit takes 1 time unit.
- A page-table walk after a TLB miss takes 10 time units.
- Other overheads are ignored for now.
The average address-translation time can be approximated as:
If an extra page-table walk is required every time, the translation overhead increases significantly.
Actual TLB access time, page-table walk time, and cache hit behavior depend on the processor microarchitecture; the above is only a simplified model for understanding.
6.3 Context Switching and the TLB
Different processes have different address spaces.
When the CPU switches from one process to another, the address-space mappings may change, so the cached mappings in the TLB also need to be managed.
Common mechanisms include:
- Flush part or all of the TLB when switching address spaces.
- Use address-space identifiers such as ASID or PCID to distinguish mappings belonging to different processes.
- After modifying page tables, use TLB invalidation mechanisms to ensure that stale mappings no longer take effect.
- Multicore systems coordinate other CPU cores through TLB shootdown.
TLB management is an important part of operating-system memory-management performance.
VII. Paging: How Do Modern Operating Systems Allocate Memory?
Paging is a memory-management approach widely adopted by modern operating systems.
It divides:
- The virtual address space into fixed-size pages.
- Physical memory into fixed-size page frames.
The two are usually the same size, and mappings are established through page tables.
7.1 Basic Principles of Paging
Assume the page size is 4 KB:
Virtual address space
Virtual page 0 ──────────┐
Virtual page 1 ──────────┤
Virtual page 2 ──────────┤
Virtual page 3 ──────────┤
Virtual page 4 ──────────┘
|
v
Page table
|
v
Physical memory
Physical page frame 0
Physical page frame 1
Physical page frame 2
Physical page frame 3
Physical page frame 4
Physical page frame 5
Physical page frame 6
Virtual pages do not need to be mapped to contiguous physical page frames.
For example:
| Virtual page | Physical page frame |
|---|---|
| Page 0 | Frame 5 |
| Page 1 | Frame 2 |
| Page 2 | Frame 8 |
| Page 3 | Frame 1 |
Therefore, the contiguous virtual address space seen by a program can consist of scattered physical pages.
7.2 What Problems Does Paging Solve?
Reduces external fragmentation.
Paging uses fixed-size physical page frames and does not require finding a single large, contiguous region of physical memory.
Simplifies memory allocation.
The operating system can choose pages from free page frames for allocation.
Supports memory protection.
Each page can have its own access permissions.
Supports page sharing.
Multiple processes can map the same physical page.
However, paging can still cause internal fragmentation.
For example, if a program needs only 1 KB of memory but the allocation unit is a 4 KB page, the remaining space may not be directly usable by other mappings.
7.3 Large-Page Mechanisms
In addition to the common 4 KB page, many processors also support larger pages.
Taking x86-64 as an example, common page sizes include:
- 4 KB.
- 2 MB.
- 1 GB.
Large pages can reduce the number of page-table entries and TLB pressure, and are especially suitable for large memory regions and for some databases, virtual machines, and memory-intensive applications.
But large pages also come at a cost:
- Memory allocation must satisfy the requirement for a larger contiguous physical region, depending on the implementation.
- They may increase internal fragmentation.
- Memory reclamation and migration become more complex.
- Benefits vary greatly across applications.
Therefore, large pages do not mean better performance in all scenarios.
VIII. Page Faults: What Happens When the Page Being Accessed Is Not in Memory?
Page faults are an important part of the virtual-memory mechanism.
When the CPU accesses a virtual address, a page fault may be triggered if the current mapping does not exist, the page is not resident, or the access permissions are not satisfied.
A page fault does not necessarily mean the program has an error.
The operating system can use a page-fault handler to perform page allocation, file reads, or permission checks.
8.1 Common Types of Page Faults
| Type | Meaning | Typical handling |
|---|---|---|
| First access to an anonymous page | Physical memory has not actually been allocated for the page | Allocate and initialize the page |
| File-mapped page fault | The corresponding file page has not yet been loaded | Read the page from the file |
| Swap page fault | The page has been swapped out to swap space | Read the swapped page |
| Copy-on-write page fault | The page has a read-only shared mapping, and the process attempts to write | Allocate a new page and copy |
| Permission error | The page does not permit the current access operation | Trigger an access exception |
| Invalid address | The address has no valid mapping | Usually terminate the process or hand it over to the exception-handling mechanism |
Exception classifications and handling details are not exactly the same across operating systems.
8.2 The Complete Page-Fault Handling Process
flowchart TD
A["Process accesses virtual address"] --> B["MMU looks up address mapping"]
B --> C{"Does a page fault occur?"}
C -->|No| D["Complete memory access"]
C -->|Yes| E["CPU triggers page fault exception"]
E --> F["Enter OS exception handler"]
F --> G["Check address and access permissions"]
G --> H{"Is access legal?"}
H -->|No| I["Report illegal access"]
H -->|Yes| J{"Source of page data"}
J -->|Anonymous memory| K["Allocate and initialize physical page"]
J -->|File mapping| L["Read page from file"]
J -->|Swap space| M["Read page from Swap"]
J -->|Copy-on-write| N["Allocate new page and copy data"]
K --> O["Update page table"]
L --> O
M --> O
N --> O
O --> P["Flush necessary TLB mappings"]
P --> Q["Re-execute original instruction"]
Q --> D
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style C fill:#FFF1CC,stroke:#E5C77A,color:#755719
style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style E fill:#FCE8E8,stroke:#D9A1A1,color:#824444
style F fill:#F1F3F5,stroke:#B9C1CA,color:#475569
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#FFF1CC,stroke:#E5C77A,color:#755719
style I fill:#FCE8E8,stroke:#D9A1A1,color:#824444
style J fill:#FFF1CC,stroke:#E5C77A,color:#755719
style K fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style M fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style N fill:#FFF1CC,stroke:#E5C77A,color:#755719
style O fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style P fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style Q fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
8.3 Major Fault and Minor Fault
Page faults can be divided into different types based on how they are handled.
Minor Page Fault:
It can be handled without reading a page from disk.
For example:
- On first access to anonymous memory, a physical page needs to be allocated and initialized.
- Accessing a file page that is already in the page cache.
- Handling certain shared mapping or copy-on-write scenarios.
Major Page Fault:
It requires waiting for a storage device to read data, and is usually much slower than a minor page fault.
For example:
- A file-mapped page has not yet entered the page cache.
- A swapped-out page needs to be read from Swap.
Different systems may count Minor and Major Faults differently.
8.4 Why do page faults affect performance?
CPU and RAM access speeds are relatively fast, while SSD or HDD access latency is usually much higher.
If an application frequently experiences major page faults that require disk I/O, the following may occur:
- The program responds more slowly.
- CPU time spent waiting for I/O increases.
- Disk read/write pressure increases.
- Memory contention arises among multiple processes.
- Overall system throughput decreases.
Therefore, when troubleshooting memory performance issues, you should not focus only on memory usage; you also need to pay attention to page fault rate, page reclamation, and swapping activity.
9. Virtual Memory and Swap: What If Physical Memory Is Insufficient?
Swap is a type of swap space used by the operating system.
It can be a dedicated partition or a swap file, used to temporarily hold some anonymous memory pages.
When physical memory is under pressure, the operating system can swap out some temporarily inactive pages to free physical page frames for workloads that need memory more urgently.
9.1 How Swap Works
flowchart TD
A["System memory pressure increases"] --> B["Memory reclaim mechanism starts"]
B --> C["Select reclaimable pages"]
C --> D{"Page type"}
D -->|File cache| E["Reclaim clean file pages"]
D -->|Anonymous pages| F["Write to Swap if necessary"]
E --> G["Release physical page frames"]
F --> G
G --> H["Physical memory available for other tasks"]
H --> I["Original process accesses the swapped-out page again"]
I --> J["Page fault triggered"]
J --> K["Read the page from Swap"]
K --> L["Re-establish the memory mapping"]
style A fill:#FFF1CC,stroke:#E5C77A,color:#755719
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style D fill:#FFF1CC,stroke:#E5C77A,color:#755719
style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style F fill:#FCE8E8,stroke:#D9A1A1,color:#824444
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#FFF1CC,stroke:#E5C77A,color:#755719
style J fill:#FCE8E8,stroke:#D9A1A1,color:#824444
style K fill:#E9E1F8,stroke:#B7A4D8,color:#514078
style L fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
9.2 The difference between Swap and virtual memory
They are not the same concept.
| Comparison item | Virtual memory | Swap |
|---|---|---|
| Essence | Address space and memory abstraction mechanism | Swap storage space |
| Role | Provides an independent address space and mapping mechanism | Temporarily holds some anonymous pages that have been swapped out |
| Must it depend on a disk? | No | Usually requires a storage device |
| Is it part of the address translation mechanism? | Yes | No |
| Does it solve memory isolation? | Yes | No |
| Does it support memory expansion? | Indirectly | To a certain extent |
Virtual memory is not equivalent to Swap.
Even if the system has no Swap configured, virtual memory can still be used normally.
9.3 Why can memory still run out even with Swap?
Swap cannot replace RAM.
The reasons include:
- Storage devices have access speeds far lower than RAM.
- Frequent page swapping in and out generates a large amount of I/O.
- Some memory allocations and kernel memory cannot be handled by ordinary Swap.
- The system may be subject to committed memory limits.
- Containers may also be subject to cgroup memory limits.
If the system keeps swapping pages out while continuously accessing those pages, it may enter a severe state of thrashing.
10. Thrashing: why does the program get slower the busier memory becomes?
Memory thrashing refers to the system spending a large amount of time handling page swapping in and out instead of executing actual business tasks.
Typical symptoms include:
- Swap I/O keeps rising.
- Page faults occur frequently.
- Disk reads and writes are busy.
- CPU utilization may drop.
- Application response time increases significantly.
10.1 Causes of memory thrashing
- Too many processes running at the same time.
- The working sets of the processes exceed the available physical memory.
- Memory leaks cause resident memory to keep growing.
- The application performs random access to large-scale data.
- The page reclaim policy cannot meet the needs of the workload.