type
status
date
slug
summary
tags
category
icon
password
How the CPU Translates Virtual Addresses to Physical Addresses?
CPU如何将虚拟地址转换为物理地址
CPU如何知道哪个物理地址映射到哪个虚拟地址?
引言
在现代操作系统中,进程运行在独立的虚拟内存空间中,无需了解底层的物理内存。这一抽象由CPU的**内存管理单元(MMU)**管理,实现了高效且安全的内存分配。但CPU如何知道哪个物理地址对应给定的虚拟地址呢?本文将探讨虚拟地址到物理地址转换的机制,包括页表、上下文切换等内容,并附上代码示例和图表。
1. 虚拟内存概述
虚拟内存使每个进程都认为它独占系统的内存。内存管理单元(MMU)将虚拟地址(软件使用的)转换为物理地址(硬件使用的)。其主要优点包括:
- 隔离:进程不能访问彼此的内存。
- 效率:物理内存根据需要动态分配。
- 安全性:内存权限(读/写/执行)得到严格执行。
2. MMU和页表(Page Tables)的作用
内存管理单元(MMU)使用页表——由操作系统维护的层次化数据结构——将虚拟地址映射到物理地址。每个进程都有自己的页表,并在上下文切换时进行更新。
Page Table Basics
- Page: 固定大小的内存块(通常为 4 KB)。
- Page Table Entry (PTE): 包含页面的物理地址和标志 (e.g., present, writable).

3. 多级页表 Multi-Level Page Tables
现代 CPU 使用多级页表来减少内存开销。例如,x86-64 使用 4 级结构:
Table Level | Index Bits | Description |
PML4 | 39–47 | Page Map Level 4 |
PDP | 30–38 | Page Directory Pointer |
PD | 21–29 | Page Directory |
PT | 12–20 | Page Table |
Translation Process:
- CR3 寄存器保存 PML4 表的物理地址。
- 虚拟地址的 39-47 位索引到 PML4 表。
- 每个条目指向一个 PDP 表,由 30-38 位索引。
- 重复此过程,直到 PT 条目提供物理页面地址。
- 其余 12 位是页面内的偏移量。The remaining 12 bits are the offset within the page.
4. 上下文切换和 CR3 寄存器
当操作系统切换进程时,它会更新 CR3 寄存器以指向新进程的 PML4 表。这可确保 MMU 使用正确的页表进行转换。
Process Control Block (PCB)
操作系统将进程特定的数据(包括 CR3)存储在 PCB 中。在上下文切换期间:
- 保存当前进程的状态(寄存器、CR3)。
- 将新进程的 CR3 加载到 MMU。
- 使 TLB 无效(除非使用进程上下文标识符)。
5. Translation Lookaside Buffer (TLB)
The TLB caches recent translations to avoid costly page table walks. On a context switch, the OS invalidates TLB entries unless they’re tagged with a Process Context Identifier (PCID).
TLB 会缓存最近的转换,以避免代价高昂的页表遍历。在上下文切换时,操作系统会使 TLB 条目无效,除非它们被标记为进程上下文标识符 (PCID)。

6. Code Examples
Example 1: 父进程和子进程中的虚拟地址
Virtual Addresses in Parent and Child Processes
Code (virtual_address.c
):
Compile and Run:
Expected Output:
Explanation:
- Parent and child share the same virtual address for
var
.(父进程和子进程为“var”共享相同的虚拟地址。)
- Due to copy-on-write, they point to different physical addresses.(由于写时复制,它们指向不同的物理地址)
Example 2: Translating Virtual to Physical Addresses
将虚拟地址转换为物理地址
Using /proc/[pid]/pagemap
:
The Linux kernel exposes physical page mappings via
/proc/[pid]/pagemap
.Linux 内核通过 /proc/[pid]/pagemap 公开物理页面映射。
Code (pagemap.c
):
Compile and Run (as root):
Expected Output:
Explanation:
- The program reads its own pagemap to resolve the physical address of
var
.
- Requires root privileges due to security restrictions.
Example 3: Inspecting Process Memory Maps
检查进程内存映射
Use pmap
to view a process’s memory regions:
Output:
Explanation:
- Shows virtual memory regions mapped to physical pages or files.
7. Conclusion
CPU 使用操作系统管理的页表将虚拟地址转换为物理地址。每个进程都有自己的页表,MMU 的 CR3 寄存器在上下文切换期间会更新。
TLB 缓存转换以提高速度,而操作系统则通过仔细管理页表和进程状态来确保隔离和正确性。通过了解这些机制,开发人员可以编写更高效、更安全的系统软件。