Skip to content

Commit 13c6457

Browse files
committed
virtual memory
1 parent 07b897c commit 13c6457

File tree

1 file changed

+237
-0
lines changed

1 file changed

+237
-0
lines changed

linux/virtual-memory.md

Lines changed: 237 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,237 @@
1+
# Virtual memory
2+
3+
Source:
4+
5+
- <https://tldp.org/LDP/tlk/mm/memory.html>
6+
- <https://docs.kernel.org/admin-guide/mm/concepts.html>
7+
8+
## What is virtual memory, anyway?
9+
10+
Virtual memory makes the system appear to have more memory than it actually has by sharing it between competing processes as they need it.
11+
12+
Virtual memory is used by all current operating systems. It simply means that the memory address a program requests is virtualized – not necessarily related to a physical memory address.
13+
14+
- The program may request the content of memory address 1000.
15+
- The computer looks at where the current map for address 1000 is pointing, and returns the contents of that address. (Virtual address 1000 may be mapped to physical address 20).
16+
- Of course, if the memory is virtualized, that means that there is no need to actually have physical memory on the server for every address the programs think they can address – so the programs can believe the server to have more memory than it physically does.
17+
- Virtual memory addresses do not need to be mapped to anything until they are allocated by a program. And a virtual memory address can be mapped not to a physical block of memory for storage, but to a block on a hard drive.
18+
19+
## 2. How virtual memory works: Key mechanisms
20+
21+
![](https://tldp.org/LDP/tlk/mm/vm.gif)
22+
23+
- Each process gets its **own virtual address space**. When the process accesses memory, it uses virtual addresses. Under the hood, the system (OS + hardware) translates those virtual access addresses to real physical addresses.
24+
- The mapping from virtual addresses -> physical addresses is maintained via **page tables**. Physical memory is split into "page frames", and virtual memory is split into "pages". Virtual pages get mapped to physical frames as needed.
25+
- Because of this mechanism, the OS doesn’t have to allocate contiguous physical memory for a program’s entire virtual memory space. This simplifies memory allocation and avoids fragmentation issues.
26+
27+
## 3. Demand paging, Backing storage and swapping
28+
29+
Because it's rarely efficient or necessary to load a program’s entire memory footprint into RAM at once, modern systems use demand-based and dynamic memory management:
30+
31+
- **Demand paging** - only the pages that a process actually needs (i.e. accesses) are loaded into physical memory; other pages remain on disk until they are needed. If a process accesses a page that is not resident, a **page fault** is raised, and the OS loads the required page from disk.
32+
- If physical RAM is scarce (or many processes are running), the OS may move seldom-used (inactive) pages from RAM to a special disk area (called **swap space**), freeing up RAM for active pages. Later, if those pages are needed again, they are read back into RAM.
33+
- This swapping (or paging) to disk allows the system to support workloads that, in total, need more memory than the physical RAM alone — at the cost of performance, since disk I/O is much slower than RAM access.
34+
- Swapping vs. Paging:
35+
- Paging moves individual pages between RAM and disk.
36+
- Swapping (much rarer today) refers to moving the entire process image out of RAM.
37+
38+
## 4. Benefits of virtual memory
39+
40+
Virtual memory does more than just make your computer's memory go further. The memory management subsystem provides:
41+
42+
- Large Address Spaces: The operating system makes the system appear as if it has a larger amount of memory than it actually has. The virtual memory can be many times larger than the physical memory in the system,
43+
- Protection: Each process in the system has its own virtual address space. These virtual address spaces are completely separate from each other and so a process running one application cannot affect another. Also, the hardware virtual memory mechanisms allow areas of memory to be protected against writing. This protects code and data from being overwritten by rogue applications.
44+
- Memory Mapping: Memory mapping is used to map image and data files into a processes address space. In memory mapping, the contents of a file are linked directly into the virtual address space of a process.
45+
- Fair Physical Memory Allocation: The memory management subsystem allows each running process in the system a fair share of the physical memory of the system,
46+
- Shared Virtual Memory:
47+
- Although virtual memory allows processes to have separate (virtual) address spaces, there are times when you need processes to share memory. For example there could be several processes in the system running the bash command shell. Rather than have several copies of bash, one in each processes virtual address space, it is better to have only one copy in physical memory and all of the processes running bash share it. Dynamic libraries are another common example of executing code shared between several processes.
48+
- Shared memory can also be used as an Inter Process Communication (IPC) mechanism, with two or more processes exchanging information via memory common to all of them. Linux supports the Unix TM System V shared memory IPC.
49+
50+
## 5. Costs and constraints
51+
52+
- Performance overhead: accessing pages from disk is orders of magnitude slower than accessing RAM. When the system relies heavily on disk-backed pages (known as thrashing), performance degrades significantly.
53+
- Management Complexity: Maintaining mappings, handling page faults, and updating page tables introduce overhead.
54+
- Physical Limits Still Matter: Virtual memory does not eliminate the need for sufficient physical RAM; it only allows more flexible and efficient usage of it.
55+
56+
## 6. Configuration
57+
58+
### 6.1. Swapping and Page-Reclaim Behavior
59+
60+
#### 6.1.1. **vm.swappiness**
61+
62+
Controls the kernel’s tendency to swap out anonymous memory (e.g., process heap/stack) versus evicting pagecache.
63+
64+
- **Range:** 0–100
65+
- **Lower values:** Avoid swapping; keep anonymous pages in RAM.
66+
- **Higher values:** Swap more aggressively.
67+
- **Defaults:** Often 60.
68+
69+
**Guidance:**
70+
71+
- Database servers: 1–10
72+
- General desktops: 30–60
73+
- Memory-constrained systems: higher values may help avoid OOM
74+
75+
#### 6.1.2. **vm.vfs_cache_pressure**
76+
77+
Controls how aggressively the kernel reclaims memory used for directory and inode caches.
78+
79+
- **Lower values (<100):** Keep inode/dentry cache longer.
80+
- **Higher values (>100):** Reclaim file metadata more aggressively.
81+
82+
**Usage:** Tune based on file system workload. Lower values can help workloads with heavy metadata access (build servers, file servers).
83+
84+
#### 6.1.3. **vm.page-cluster**
85+
86+
Determines how many pages the kernel reads/writes at once during swap I/O.
87+
88+
- Default typically 3 → 2³ = 8 pages per swap I/O.
89+
- Lower values reduce I/O burst size (may help SSDs).
90+
- Higher values increase batch I/O.
91+
92+
### 6.2. Out-of-Memory (OOM) Handling and Stability
93+
94+
#### 6.2.1. **vm.overcommit_memory**
95+
96+
Controls how the kernel accounts for process memory allocation.
97+
98+
- **0:** Heuristic overcommit (default).
99+
- **1:** Allow all allocations (don’t check).
100+
- **2:** Don’t overcommit beyond allowed memory (strict).
101+
102+
**Guidance:**
103+
104+
- For predictable environments like databases: set to **2**.
105+
- For HPC workloads needing large mmap regions: sometimes set to **1**.
106+
107+
#### 6.2.2. **vm.overcommit_ratio**
108+
109+
Used when `overcommit_memory = 2`.
110+
Defines how much memory can be committed as a percentage of RAM.
111+
112+
- Default: **50**
113+
- Commit limit = Swap + (RAM \* ratio/100)
114+
115+
---
116+
117+
#### 6.2.3. **vm.oom_kill_allocating_task**
118+
119+
If set to 1, the kernel kills the task that triggered the OOM, not the largest memory consumer.
120+
121+
Useful in debugging or in controlled environments but risky in production.
122+
123+
##### 6.2.4. **vm.panic_on_oom**
124+
125+
Controls whether the kernel panics instead of killing a task on OOM.
126+
127+
- **0:** Try to kill processes.
128+
- **1:** Panic on OOM.
129+
- **2:** Always panic.
130+
131+
Used in clusters where memory exhaustion indicates catastrophic failure requiring failover.
132+
133+
### 6.3. Dirty Page and Writeback Controls
134+
135+
These parameters strongly influence write-heavy workloads.
136+
137+
#### 6.3.1. **vm.dirty_ratio**
138+
139+
Maximum percentage of dirty pages allowed before processes must write them out.
140+
141+
- High = more dirty pages = potential latency spikes.
142+
143+
#### 6.3.2. **vm.dirty_background_ratio**
144+
145+
Percentage at which background writeback starts.
146+
147+
- Lower = cleaner system = more regular I/O.
148+
149+
#### 6.3.3. **vm.dirty_bytes / vm.dirty_background_bytes**
150+
151+
Byte-based equivalents.
152+
Preferred over ratios for servers with large RAM capacities.
153+
154+
#### 6.3.4. **vm.dirty_expire_centisecs**
155+
156+
Age after which dirty data is eligible for writeback.
157+
158+
#### 6.3.5. **vm.dirty_writeback_centisecs**
159+
160+
Frequency of writeback daemon wakeups.
161+
162+
### 6.4. Page Cache and Reclaim-Specific Controls
163+
164+
#### 6.4.1. **vm.min_free_kbytes**
165+
166+
Minimum amount of free memory the kernel keeps in reserve to avoid emergency slow-path allocations.
167+
168+
Increasing helps high-throughput networking and I/O.
169+
170+
#### 6.4.2. **vm.watermark_scale_factor**
171+
172+
Controls reclaim aggressiveness relative to memory pressures.
173+
174+
Useful for fine-tuning reclaim behavior in NUMA or high-memory systems.
175+
176+
#### 6.4.3. **vm.zone_reclaim_mode**
177+
178+
Enables reclaim before using remote memory on NUMA systems.
179+
180+
- Common values: 0 (off), 1 (reclaim local pages)
181+
182+
Not recommended for many workloads unless NUMA locality is critical.
183+
184+
### 6.5. Transparent Huge Pages (THP) Controls
185+
186+
#### 6.5.1. **vm.nr_hugepages**
187+
188+
Number of preallocated HugeTLB pages.
189+
190+
#### 6.5.2. **vm.nr_overcommit_hugepages**
191+
192+
Controls overcommit of hugepages.
193+
194+
#### 6.5.3. **vm.hugetlb_shm_group**
195+
196+
GID that can create hugepage-backed shared memory.
197+
198+
**Note:** THP is controlled via `/sys/kernel/mm/transparent_hugepage/` rather than sysctl, but affects virtual memory behavior.
199+
200+
### 6.6. Memory Control for Cgroups (indirect VM management)
201+
202+
While not purely sysctl, cgroup controllers largely replace many coarse tunings:
203+
204+
- `memory.high`
205+
- `memory.max`
206+
- `memory.swap.max`
207+
- `memory.min`
208+
209+
These provide **granular per-service virtual memory constraints**, often more effective than global sysctl tuning.
210+
211+
### 6.7. Common Tuning Profiles by Workload
212+
213+
#### 6.7.1. Database Servers (PostgreSQL, MySQL)
214+
215+
- `vm.swappiness = 1–10`
216+
- `vm.overcommit_memory = 2`
217+
- `vm.overcommit_ratio = 100–150`
218+
- Prefer `dirty_bytes` settings over ratios.
219+
220+
#### 6.7.2. File Servers / Build Servers
221+
222+
- `vm.vfs_cache_pressure = 10–50`
223+
- `vm.swappiness = 30–60`
224+
- Tune dirty_writeback settings for smoother I/O.
225+
226+
#### 6.7.3. High-throughput Application Servers
227+
228+
- `vm.min_free_kbytes` increased
229+
- Moderate `swappiness`
230+
- Consider adjusting watermark_scale_factor.
231+
232+
#### 6.7.4. Low-Latency / Real-Time Systems
233+
234+
- Minimal swapping → `swappiness = 0`
235+
- Reduced dirty ratios
236+
- Increased min_free_kbytes
237+
- Disable THP if causing latency spikes

0 commit comments

Comments
 (0)