125 / 163 · C11 · 约 8 分钟
超越物理内存:机制
先记住这句话
操作系统借助较慢的辅助存储作为交换区,并在页表项中增加存在位,从而在物理内存不足时仍为多个大地址空间进程提供透明的虚拟内存假象。缺页由软件处理程序完成调入。
为何引入交换区
当所有进程的虚拟地址空间总和超过DRAM容量时,操作系统必须把暂时不用的页面暂时放到容量更大但更慢的设备上。这块预留区域称为交换空间。程序员因此不必再手工安排覆盖,系统也能同时运行更多程序。
存在位如何指示页面位置
页表项增加一位存在标志。该位为1表示页面正占用某个物理帧,为0则表示页面位于磁盘。硬件在TLB未命中后检查此位;若清零就立即陷入操作系统,而不是生成非法物理地址。
缺页处理程序的工作步骤
陷入后操作系统从PTE里读出磁盘块号,必要时先把牺牲页写回交换区,再发起读请求把目标页装入空闲或腾出的帧,更新存在位和帧号,最后重新执行那条访存指令。
可执行文件页面与多道程序
程序代码不必占用交换区,因为它们可以随时从文件系统中的原始二进制再次装入。交换机制同时让早期内存很小的机器也能实现真正的多道程序设计。
常见误区
- 以为处理器自己会去磁盘取页
- 忘记代码页可以直接从可执行文件按需装入
- 把合法但被换出的访问误判为保护违例
运行一个例子
最低标准 C11 · 完整程序 · 下载 .c
#include <stdio.h>
#include <stdbool.h>
#define N 8
typedef struct {
bool present;
unsigned loc;
} PTE;
static void dump(const PTE pt[]) {
puts("VPN Present Location");
for (int i = 0; i < N; i++)
printf("%3d %7s %8u\n", i, pt[i].present ? "yes" : "no", pt[i].loc);
}
int main(void) {
PTE pt[N] = {
{true, 0}, {true, 1}, {false, 4}, {true, 2},
{false, 6}, {false, 2}, {true, 3}, {false, 7}
};
puts("=== Tiny VM with Swap Simulator ===");
puts("Initial page table:");
dump(pt);
puts("\nCPU references VPN 2 -> present bit clear -> PAGE FAULT");
puts("Handler reads disk block 4, evicts VPN 0 to swap 0, places page in PFN 0");
pt[0].present = false;
pt[0].loc = 0;
pt[2].present = true;
pt[2].loc = 0;
puts("Page table after fault handling:");
dump(pt);
puts("\nCPU references VPN 6 -> present, PFN 3, no fault");
puts("Large virtual memory illusion maintained.");
return 0;
}
在本地编译
gcc -std=c11 -Wall -Wextra -Wpedantic -Werror ostep-21-swapping-mechanisms.c -o example && ./example预期结果
=== Tiny VM with Swap Simulator ===
Initial page table:
VPN Present Location
0 yes 0
1 yes 1
2 no 4
3 yes 2
4 no 6
5 no 2
6 yes 3
7 no 7
CPU references VPN 2 -> present bit clear -> PAGE FAULT
Handler reads disk block 4, evicts VPN 0 to swap 0, places page in PFN 0
Page table after fault handling:
VPN Present Location
0 no 0
1 yes 1
2 yes 0
3 yes 2
4 no 6
5 no 2
6 yes 3
7 no 7
CPU references VPN 6 -> present, PFN 3, no fault
Large virtual memory illusion maintained.
CHECK YOUR UNDERSTANDING
合上答案,试着解释。
某PTE当前 present=0、磁盘块=17。缺页成功处理后这两个字段分别变成什么?
查看参考答案
present 变为 1,位置字段被改写成一个物理帧号(例如 5)。
继续查证
标准草案与官方章节会更新;版本标记只说明示例最低要求。